babylon.engine.ts 182 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: string, shaderVersion: string): WebGLShader => {
  3. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  4. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  5. gl.compileShader(shader);
  6. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7. throw new Error(gl.getShaderInfoLog(shader));
  8. }
  9. return shader;
  10. };
  11. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  12. var magFilter = gl.NEAREST;
  13. var minFilter = gl.NEAREST;
  14. switch (samplingMode) {
  15. case Texture.BILINEAR_SAMPLINGMODE:
  16. magFilter = gl.LINEAR;
  17. if (generateMipMaps) {
  18. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  19. } else {
  20. minFilter = gl.LINEAR;
  21. }
  22. break;
  23. case Texture.TRILINEAR_SAMPLINGMODE:
  24. magFilter = gl.LINEAR;
  25. if (generateMipMaps) {
  26. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  27. } else {
  28. minFilter = gl.LINEAR;
  29. }
  30. break;
  31. case Texture.NEAREST_SAMPLINGMODE:
  32. magFilter = gl.NEAREST;
  33. if (generateMipMaps) {
  34. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  35. } else {
  36. minFilter = gl.NEAREST;
  37. }
  38. break;
  39. case Texture.NEAREST_NEAREST_MIPNEAREST:
  40. magFilter = gl.NEAREST;
  41. if (generateMipMaps) {
  42. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  43. } else {
  44. minFilter = gl.NEAREST;
  45. }
  46. break;
  47. case Texture.NEAREST_LINEAR_MIPNEAREST:
  48. magFilter = gl.NEAREST;
  49. if (generateMipMaps) {
  50. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  51. } else {
  52. minFilter = gl.LINEAR;
  53. }
  54. break;
  55. case Texture.NEAREST_LINEAR_MIPLINEAR:
  56. magFilter = gl.NEAREST;
  57. if (generateMipMaps) {
  58. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  59. } else {
  60. minFilter = gl.LINEAR;
  61. }
  62. break;
  63. case Texture.NEAREST_LINEAR:
  64. magFilter = gl.NEAREST;
  65. minFilter = gl.LINEAR;
  66. break;
  67. case Texture.NEAREST_NEAREST:
  68. magFilter = gl.NEAREST;
  69. minFilter = gl.NEAREST;
  70. break;
  71. case Texture.LINEAR_NEAREST_MIPNEAREST:
  72. magFilter = gl.LINEAR;
  73. if (generateMipMaps) {
  74. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  75. } else {
  76. minFilter = gl.NEAREST;
  77. }
  78. break;
  79. case Texture.LINEAR_NEAREST_MIPLINEAR:
  80. magFilter = gl.LINEAR;
  81. if (generateMipMaps) {
  82. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  83. } else {
  84. minFilter = gl.NEAREST;
  85. }
  86. break;
  87. case Texture.LINEAR_LINEAR:
  88. magFilter = gl.LINEAR;
  89. minFilter = gl.LINEAR;
  90. break;
  91. case Texture.LINEAR_NEAREST:
  92. magFilter = gl.LINEAR;
  93. minFilter = gl.NEAREST;
  94. break;
  95. }
  96. return {
  97. min: minFilter,
  98. mag: magFilter
  99. }
  100. }
  101. var partialLoad = (url: string, index: number, loadedImages: any, scene,
  102. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: () => void = null) => {
  103. var img: HTMLImageElement;
  104. var onload = () => {
  105. loadedImages[index] = img;
  106. loadedImages._internalCount++;
  107. scene._removePendingData(img);
  108. if (loadedImages._internalCount === 6) {
  109. onfinish(loadedImages);
  110. }
  111. };
  112. var onerror = () => {
  113. scene._removePendingData(img);
  114. if (onErrorCallBack) {
  115. onErrorCallBack();
  116. }
  117. };
  118. img = Tools.LoadImage(url, onload, onerror, scene.database);
  119. scene._addPendingData(img);
  120. }
  121. var cascadeLoad = (rootUrl: string, scene,
  122. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: () => void = null) => {
  123. var loadedImages: any = [];
  124. loadedImages._internalCount = 0;
  125. for (var index = 0; index < 6; index++) {
  126. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  127. }
  128. };
  129. class BufferPointer {
  130. public active: boolean;
  131. public index: number;
  132. public size: number;
  133. public type: number;
  134. public normalized: boolean;
  135. public stride: number;
  136. public offset: number;
  137. public buffer: WebGLBuffer;
  138. }
  139. export class InstancingAttributeInfo {
  140. /**
  141. * Index/offset of the attribute in the vertex shader
  142. */
  143. index: number;
  144. /**
  145. * size of the attribute, 1, 2, 3 or 4
  146. */
  147. attributeSize: number;
  148. /**
  149. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  150. * default is FLOAT
  151. */
  152. attribyteType: number;
  153. /**
  154. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  155. */
  156. normalized: boolean;
  157. /**
  158. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  159. */
  160. offset: number;
  161. /**
  162. * Name of the GLSL attribute, for debugging purpose only
  163. */
  164. attributeName: string;
  165. }
  166. /**
  167. * Regroup several parameters relative to the browser in use
  168. */
  169. export class EngineCapabilities {
  170. /** The maximum textures image */
  171. public maxTexturesImageUnits: number;
  172. public maxVertexTextureImageUnits: number;
  173. /** The maximum texture size */
  174. public maxTextureSize: number;
  175. public maxCubemapTextureSize: number;
  176. public maxRenderTextureSize: number;
  177. public maxVertexAttribs: number;
  178. public maxVaryingVectors: number;
  179. public maxVertexUniformVectors: number;
  180. public maxFragmentUniformVectors: number;
  181. public standardDerivatives: boolean;
  182. public s3tc: WEBGL_compressed_texture_s3tc;
  183. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  184. public etc1: any; //WEBGL_compressed_texture_etc1;
  185. public etc2: any; //WEBGL_compressed_texture_etc;
  186. public astc: any; //WEBGL_compressed_texture_astc;
  187. public textureFloat: boolean;
  188. public vertexArrayObject: boolean;
  189. public textureAnisotropicFilterExtension: EXT_texture_filter_anisotropic;
  190. public maxAnisotropy: number;
  191. public instancedArrays: boolean;
  192. public uintIndices: boolean;
  193. public highPrecisionShaderSupported: boolean;
  194. public fragmentDepthSupported: boolean;
  195. public textureFloatLinearFiltering: boolean;
  196. public textureFloatRender: boolean;
  197. public textureHalfFloat: boolean;
  198. public textureHalfFloatLinearFiltering: boolean;
  199. public textureHalfFloatRender: boolean;
  200. public textureLOD: boolean;
  201. public drawBuffersExtension;
  202. public colorBufferFloat: boolean;
  203. }
  204. export interface EngineOptions extends WebGLContextAttributes {
  205. limitDeviceRatio?: number;
  206. autoEnableWebVR?: boolean;
  207. disableWebGL2Support?: boolean;
  208. audioEngine?: boolean;
  209. deterministicLockstep?: boolean;
  210. lockstepMaxSteps?: number;
  211. }
  212. /**
  213. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  214. */
  215. export class Engine {
  216. public static Instances = new Array<Engine>();
  217. public static get LastCreatedEngine(): Engine {
  218. if (Engine.Instances.length === 0) {
  219. return null;
  220. }
  221. return Engine.Instances[Engine.Instances.length - 1];
  222. }
  223. public static get LastCreatedScene(): Scene {
  224. var lastCreatedEngine = Engine.LastCreatedEngine;
  225. if (!lastCreatedEngine) {
  226. return null;
  227. }
  228. if (lastCreatedEngine.scenes.length === 0) {
  229. return null;
  230. }
  231. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  232. }
  233. /**
  234. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  235. */
  236. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  237. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  238. var engine = Engine.Instances[engineIndex];
  239. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  240. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  241. }
  242. }
  243. }
  244. // Const statics
  245. private static _ALPHA_DISABLE = 0;
  246. private static _ALPHA_ADD = 1;
  247. private static _ALPHA_COMBINE = 2;
  248. private static _ALPHA_SUBTRACT = 3;
  249. private static _ALPHA_MULTIPLY = 4;
  250. private static _ALPHA_MAXIMIZED = 5;
  251. private static _ALPHA_ONEONE = 6;
  252. private static _ALPHA_PREMULTIPLIED = 7;
  253. private static _ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  254. private static _ALPHA_INTERPOLATE = 9;
  255. private static _ALPHA_SCREENMODE = 10;
  256. private static _DELAYLOADSTATE_NONE = 0;
  257. private static _DELAYLOADSTATE_LOADED = 1;
  258. private static _DELAYLOADSTATE_LOADING = 2;
  259. private static _DELAYLOADSTATE_NOTLOADED = 4;
  260. private static _TEXTUREFORMAT_ALPHA = 0;
  261. private static _TEXTUREFORMAT_LUMINANCE = 1;
  262. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  263. private static _TEXTUREFORMAT_RGB = 4;
  264. private static _TEXTUREFORMAT_RGBA = 5;
  265. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  266. private static _TEXTURETYPE_FLOAT = 1;
  267. private static _TEXTURETYPE_HALF_FLOAT = 2;
  268. // Depht or Stencil test Constants.
  269. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  270. 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.
  271. 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.
  272. 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.
  273. 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.
  274. 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.
  275. 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.
  276. 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.
  277. public static get NEVER(): number {
  278. return Engine._NEVER;
  279. }
  280. public static get ALWAYS(): number {
  281. return Engine._ALWAYS;
  282. }
  283. public static get LESS(): number {
  284. return Engine._LESS;
  285. }
  286. public static get EQUAL(): number {
  287. return Engine._EQUAL;
  288. }
  289. public static get LEQUAL(): number {
  290. return Engine._LEQUAL;
  291. }
  292. public static get GREATER(): number {
  293. return Engine._GREATER;
  294. }
  295. public static get GEQUAL(): number {
  296. return Engine._GEQUAL;
  297. }
  298. public static get NOTEQUAL(): number {
  299. return Engine._NOTEQUAL;
  300. }
  301. // Stencil Actions Constants.
  302. private static _KEEP = 0x1E00;
  303. private static _REPLACE = 0x1E01;
  304. private static _INCR = 0x1E02;
  305. private static _DECR = 0x1E03;
  306. private static _INVERT = 0x150A;
  307. private static _INCR_WRAP = 0x8507;
  308. private static _DECR_WRAP = 0x8508;
  309. public static get KEEP(): number {
  310. return Engine._KEEP;
  311. }
  312. public static get REPLACE(): number {
  313. return Engine._REPLACE;
  314. }
  315. public static get INCR(): number {
  316. return Engine._INCR;
  317. }
  318. public static get DECR(): number {
  319. return Engine._DECR;
  320. }
  321. public static get INVERT(): number {
  322. return Engine._INVERT;
  323. }
  324. public static get INCR_WRAP(): number {
  325. return Engine._INCR_WRAP;
  326. }
  327. public static get DECR_WRAP(): number {
  328. return Engine._DECR_WRAP;
  329. }
  330. public static get ALPHA_DISABLE(): number {
  331. return Engine._ALPHA_DISABLE;
  332. }
  333. public static get ALPHA_ONEONE(): number {
  334. return Engine._ALPHA_ONEONE;
  335. }
  336. public static get ALPHA_ADD(): number {
  337. return Engine._ALPHA_ADD;
  338. }
  339. public static get ALPHA_COMBINE(): number {
  340. return Engine._ALPHA_COMBINE;
  341. }
  342. public static get ALPHA_SUBTRACT(): number {
  343. return Engine._ALPHA_SUBTRACT;
  344. }
  345. public static get ALPHA_MULTIPLY(): number {
  346. return Engine._ALPHA_MULTIPLY;
  347. }
  348. public static get ALPHA_MAXIMIZED(): number {
  349. return Engine._ALPHA_MAXIMIZED;
  350. }
  351. public static get ALPHA_PREMULTIPLIED(): number {
  352. return Engine._ALPHA_PREMULTIPLIED;
  353. }
  354. public static get ALPHA_PREMULTIPLIED_PORTERDUFF(): number {
  355. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  356. }
  357. public static get ALPHA_INTERPOLATE(): number {
  358. return Engine._ALPHA_INTERPOLATE;
  359. }
  360. public static get ALPHA_SCREENMODE(): number {
  361. return Engine._ALPHA_SCREENMODE;
  362. }
  363. public static get DELAYLOADSTATE_NONE(): number {
  364. return Engine._DELAYLOADSTATE_NONE;
  365. }
  366. public static get DELAYLOADSTATE_LOADED(): number {
  367. return Engine._DELAYLOADSTATE_LOADED;
  368. }
  369. public static get DELAYLOADSTATE_LOADING(): number {
  370. return Engine._DELAYLOADSTATE_LOADING;
  371. }
  372. public static get DELAYLOADSTATE_NOTLOADED(): number {
  373. return Engine._DELAYLOADSTATE_NOTLOADED;
  374. }
  375. public static get TEXTUREFORMAT_ALPHA(): number {
  376. return Engine._TEXTUREFORMAT_ALPHA;
  377. }
  378. public static get TEXTUREFORMAT_LUMINANCE(): number {
  379. return Engine._TEXTUREFORMAT_LUMINANCE;
  380. }
  381. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  382. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  383. }
  384. public static get TEXTUREFORMAT_RGB(): number {
  385. return Engine._TEXTUREFORMAT_RGB;
  386. }
  387. public static get TEXTUREFORMAT_RGBA(): number {
  388. return Engine._TEXTUREFORMAT_RGBA;
  389. }
  390. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  391. return Engine._TEXTURETYPE_UNSIGNED_INT;
  392. }
  393. public static get TEXTURETYPE_FLOAT(): number {
  394. return Engine._TEXTURETYPE_FLOAT;
  395. }
  396. public static get TEXTURETYPE_HALF_FLOAT(): number {
  397. return Engine._TEXTURETYPE_HALF_FLOAT;
  398. }
  399. // Texture rescaling mode
  400. private static _SCALEMODE_FLOOR = 1;
  401. private static _SCALEMODE_NEAREST = 2;
  402. private static _SCALEMODE_CEILING = 3;
  403. public static get SCALEMODE_FLOOR(): number {
  404. return Engine._SCALEMODE_FLOOR;
  405. }
  406. public static get SCALEMODE_NEAREST(): number {
  407. return Engine._SCALEMODE_NEAREST;
  408. }
  409. public static get SCALEMODE_CEILING(): number {
  410. return Engine._SCALEMODE_CEILING;
  411. }
  412. public static get Version(): string {
  413. return "3.1-alpha";
  414. }
  415. // Updatable statics so stick with vars here
  416. public static CollisionsEpsilon = 0.001;
  417. public static CodeRepository = "src/";
  418. public static ShadersRepository = "src/Shaders/";
  419. // Public members
  420. public forcePOTTextures = false;
  421. public isFullscreen = false;
  422. public isPointerLock = false;
  423. public cullBackFaces = true;
  424. public renderEvenInBackground = true;
  425. public preventCacheWipeBetweenFrames = false;
  426. // To enable/disable IDB support and avoid XHR on .manifest
  427. public enableOfflineSupport = false;
  428. public scenes = new Array<Scene>();
  429. // Observables
  430. /**
  431. * Observable event triggered each time the rendering canvas is resized
  432. */
  433. public onResizeObservable = new Observable<Engine>();
  434. /**
  435. * Observable event triggered each time the canvas lost focus
  436. */
  437. public onCanvasBlurObservable = new Observable<Engine>();
  438. //WebVR
  439. //The new WebVR uses promises.
  440. //this promise resolves with the current devices available.
  441. public vrDisplaysPromise;
  442. private _vrDisplays;
  443. private _vrDisplayEnabled;
  444. private _oldSize: BABYLON.Size;
  445. private _oldHardwareScaleFactor: number;
  446. private _vrAnimationFrameHandler: number;
  447. // Private Members
  448. public _gl: WebGLRenderingContext;
  449. private _renderingCanvas: HTMLCanvasElement;
  450. private _windowIsBackground = false;
  451. private _webGLVersion = 1.0;
  452. public get needPOTTextures(): boolean {
  453. return this._webGLVersion < 2 || this.forcePOTTextures;
  454. }
  455. private _badOS = false;
  456. public get badOS(): boolean {
  457. return this._badOS;
  458. }
  459. private _badDesktopOS = false;
  460. public get badDesktopOS(): boolean {
  461. return this._badDesktopOS;
  462. }
  463. public static audioEngine: AudioEngine;
  464. private _onCanvasBlur: () => void;
  465. private _onBlur: () => void;
  466. private _onFocus: () => void;
  467. private _onFullscreenChange: () => void;
  468. private _onPointerLockChange: () => void;
  469. private _hardwareScalingLevel: number;
  470. private _caps: EngineCapabilities;
  471. private _pointerLockRequested: boolean;
  472. private _alphaTest: boolean;
  473. private _isStencilEnable: boolean;
  474. private _loadingScreen: ILoadingScreen;
  475. public _drawCalls = new PerfCounter();
  476. private _glVersion: string;
  477. private _glRenderer: string;
  478. private _glVendor: string;
  479. private _videoTextureSupported: boolean;
  480. private _renderingQueueLaunched = false;
  481. private _activeRenderLoops = [];
  482. // Deterministic lockstepMaxSteps
  483. private _deterministicLockstep: boolean = false;
  484. private _lockstepMaxSteps: number = 4;
  485. // FPS
  486. private _performanceMonitor = new PerformanceMonitor();
  487. private _fps = 60;
  488. private _deltaTime = 0;
  489. public get performanceMonitor(): PerformanceMonitor {
  490. return this._performanceMonitor;
  491. }
  492. // States
  493. private _depthCullingState = new Internals._DepthCullingState();
  494. private _stencilState = new Internals._StencilState();
  495. private _alphaState = new Internals._AlphaState();
  496. private _alphaMode = Engine.ALPHA_DISABLE;
  497. // Cache
  498. private _loadedTexturesCache = new Array<WebGLTexture>();
  499. private _maxTextureChannels = 16;
  500. private _activeTexture: number;
  501. private _activeTexturesCache = new Array<WebGLTexture>(this._maxTextureChannels);
  502. private _currentEffect: Effect;
  503. private _currentProgram: WebGLProgram;
  504. private _compiledEffects = {};
  505. private _vertexAttribArraysEnabled: boolean[] = [];
  506. private _cachedViewport: Viewport;
  507. private _cachedVertexArrayObject: WebGLVertexArrayObject;
  508. private _cachedVertexBuffers: any;
  509. private _cachedIndexBuffer: WebGLBuffer;
  510. private _cachedEffectForVertexBuffers: Effect;
  511. private _currentRenderTarget: WebGLTexture;
  512. private _uintIndicesCurrentlySet = false;
  513. private _currentBoundBuffer = new Array<WebGLBuffer>();
  514. private _currentFramebuffer: WebGLFramebuffer;
  515. private _currentBufferPointers = new Array<BufferPointer>();
  516. private _currentInstanceLocations = new Array<number>();
  517. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  518. private _textureUnits: Int32Array;
  519. private _workingCanvas: HTMLCanvasElement;
  520. private _workingContext: CanvasRenderingContext2D;
  521. private _rescalePostProcess: PassPostProcess;
  522. private _dummyFramebuffer: WebGLFramebuffer;
  523. private _externalData: StringDictionary<Object>;
  524. private _bindedRenderFunction: any;
  525. private _vaoRecordInProgress = false;
  526. private _mustWipeVertexAttributes = false;
  527. private _emptyTexture: WebGLTexture;
  528. private _emptyCubeTexture: WebGLTexture;
  529. // Hardware supported Compressed Textures
  530. private _texturesSupported = new Array<string>();
  531. private _textureFormatInUse: string;
  532. public get texturesSupported(): Array<string> {
  533. return this._texturesSupported;
  534. }
  535. public get textureFormatInUse(): string {
  536. return this._textureFormatInUse;
  537. }
  538. // Empty texture
  539. public get emptyTexture(): WebGLTexture {
  540. if (!this._emptyTexture) {
  541. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  542. }
  543. return this._emptyTexture;
  544. }
  545. public get emptyCubeTexture(): WebGLTexture {
  546. if (!this._emptyCubeTexture) {
  547. var faceData = new Uint8Array(4);
  548. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  549. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  550. }
  551. return this._emptyCubeTexture;
  552. }
  553. /**
  554. * @constructor
  555. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  556. * @param {boolean} [antialias] - enable antialias
  557. * @param options - further options to be sent to the getContext function
  558. */
  559. constructor(canvasOrContext: HTMLCanvasElement | WebGLRenderingContext, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio = false) {
  560. var canvas: HTMLCanvasElement;
  561. Engine.Instances.push(this);
  562. options = options || {};
  563. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  564. canvas = <HTMLCanvasElement>canvasOrContext;
  565. this._renderingCanvas = canvas;
  566. if (antialias != null) {
  567. options.antialias = antialias;
  568. }
  569. if (options.deterministicLockstep === undefined) {
  570. options.deterministicLockstep = false;
  571. }
  572. if (options.lockstepMaxSteps === undefined) {
  573. options.lockstepMaxSteps = 4;
  574. }
  575. if (options.preserveDrawingBuffer === undefined) {
  576. options.preserveDrawingBuffer = false;
  577. }
  578. if (options.audioEngine === undefined) {
  579. options.audioEngine = true;
  580. }
  581. if (options.stencil === undefined) {
  582. options.stencil = true;
  583. }
  584. this._deterministicLockstep = options.deterministicLockstep;
  585. this._lockstepMaxSteps = options.lockstepMaxSteps;
  586. // GL
  587. if (!options.disableWebGL2Support) {
  588. try {
  589. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  590. if (this._gl) {
  591. this._webGLVersion = 2.0;
  592. }
  593. } catch (e) {
  594. // Do nothing
  595. }
  596. }
  597. if (!this._gl) {
  598. if (!canvas) {
  599. throw new Error("The provided canvas is null or undefined.");
  600. }
  601. try {
  602. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  603. } catch (e) {
  604. throw new Error("WebGL not supported");
  605. }
  606. }
  607. if (!this._gl) {
  608. throw new Error("WebGL not supported");
  609. }
  610. this._onBlur = () => {
  611. this._performanceMonitor.disable();
  612. this._windowIsBackground = true;
  613. };
  614. this._onFocus = () => {
  615. this._performanceMonitor.enable();
  616. this._windowIsBackground = false;
  617. };
  618. this._onCanvasBlur = () => {
  619. this.onCanvasBlurObservable.notifyObservers(this);
  620. };
  621. window.addEventListener("blur", this._onBlur);
  622. window.addEventListener("focus", this._onFocus);
  623. canvas.addEventListener("pointerout", this._onCanvasBlur);
  624. } else {
  625. this._gl = <WebGLRenderingContext>canvasOrContext;
  626. this._renderingCanvas = this._gl.canvas
  627. if (this._gl.renderbufferStorageMultisample) {
  628. this._webGLVersion = 2.0;
  629. }
  630. options.stencil = this._gl.getContextAttributes().stencil;
  631. }
  632. // Viewport
  633. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  634. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  635. this.resize();
  636. // Caps
  637. this._isStencilEnable = options.stencil;
  638. this._caps = new EngineCapabilities();
  639. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  640. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  641. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  642. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  643. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  644. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  645. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  646. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  647. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  648. // Infos
  649. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  650. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  651. if (rendererInfo != null) {
  652. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  653. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  654. }
  655. if (!this._glVendor) {
  656. this._glVendor = "Unknown vendor";
  657. }
  658. if (!this._glRenderer) {
  659. this._glRenderer = "Unknown renderer";
  660. }
  661. // Constants
  662. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  663. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  664. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  665. this._gl.DEPTH24_STENCIL8 = 35056;
  666. // Extensions
  667. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  668. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  669. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  670. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  671. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  672. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  673. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  674. 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');
  675. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  676. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  677. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  678. this._caps.highPrecisionShaderSupported = true;
  679. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  680. // Checks if some of the format renders first to allow the use of webgl inspector.
  681. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  682. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  683. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  684. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  685. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  686. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  687. if (this._webGLVersion > 1) {
  688. this._gl.HALF_FLOAT_OES = 0x140B;
  689. }
  690. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  691. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  692. // Vertex array object
  693. if (this._webGLVersion > 1) {
  694. this._caps.vertexArrayObject = true;
  695. } else {
  696. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  697. if (vertexArrayObjectExtension != null) {
  698. this._caps.vertexArrayObject = true;
  699. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  700. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  701. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  702. } else {
  703. this._caps.vertexArrayObject = false;
  704. }
  705. }
  706. // Instances count
  707. if (this._webGLVersion > 1) {
  708. this._caps.instancedArrays = true;
  709. } else {
  710. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  711. if (instanceExtension != null) {
  712. this._caps.instancedArrays = true;
  713. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  714. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  715. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  716. } else {
  717. this._caps.instancedArrays = false;
  718. }
  719. }
  720. // Intelligently add supported compressed formats in order to check for.
  721. // Check for ASTC support first as it is most powerful and to be very cross platform.
  722. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  723. // Likely no hardware which supports both PVR & DXT, so order matters little.
  724. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  725. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  726. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  727. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  728. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  729. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  730. if (this._gl.getShaderPrecisionFormat) {
  731. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  732. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  733. }
  734. // Depth buffer
  735. this.setDepthBuffer(true);
  736. this.setDepthFunctionToLessOrEqual();
  737. this.setDepthWrite(true);
  738. if (canvas) {
  739. // Fullscreen
  740. this._onFullscreenChange = () => {
  741. if (document.fullscreen !== undefined) {
  742. this.isFullscreen = document.fullscreen;
  743. } else if (document.mozFullScreen !== undefined) {
  744. this.isFullscreen = document.mozFullScreen;
  745. } else if (document.webkitIsFullScreen !== undefined) {
  746. this.isFullscreen = document.webkitIsFullScreen;
  747. } else if (document.msIsFullScreen !== undefined) {
  748. this.isFullscreen = document.msIsFullScreen;
  749. }
  750. // Pointer lock
  751. if (this.isFullscreen && this._pointerLockRequested) {
  752. canvas.requestPointerLock = canvas.requestPointerLock ||
  753. canvas.msRequestPointerLock ||
  754. canvas.mozRequestPointerLock ||
  755. canvas.webkitRequestPointerLock;
  756. if (canvas.requestPointerLock) {
  757. canvas.requestPointerLock();
  758. }
  759. }
  760. };
  761. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  762. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  763. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  764. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  765. // Pointer lock
  766. this._onPointerLockChange = () => {
  767. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  768. document.webkitPointerLockElement === canvas ||
  769. document.msPointerLockElement === canvas ||
  770. document.pointerLockElement === canvas
  771. );
  772. };
  773. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  774. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  775. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  776. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  777. }
  778. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  779. Engine.audioEngine = new AudioEngine();
  780. }
  781. // Prepare buffer pointers
  782. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  783. this._currentBufferPointers[i] = new BufferPointer();
  784. }
  785. // Load WebVR Devices
  786. if (options.autoEnableWebVR) {
  787. this.initWebVR();
  788. }
  789. // Detect if we are running on a faulty buggy OS.
  790. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  791. // Detect if we are running on a faulty buggy desktop OS.
  792. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  793. Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  794. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  795. }
  796. public get webGLVersion(): number {
  797. return this._webGLVersion;
  798. }
  799. /**
  800. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  801. */
  802. public get isStencilEnable(): boolean {
  803. return this._isStencilEnable;
  804. }
  805. private _prepareWorkingCanvas(): void {
  806. if (this._workingCanvas) {
  807. return;
  808. }
  809. this._workingCanvas = document.createElement("canvas");
  810. this._workingContext = this._workingCanvas.getContext("2d");
  811. }
  812. public resetTextureCache() {
  813. for (var index = 0; index < this._maxTextureChannels; index++) {
  814. this._activeTexturesCache[index] = null;
  815. }
  816. }
  817. public isDeterministicLockStep(): boolean {
  818. return this._deterministicLockstep;
  819. }
  820. public getLockstepMaxSteps(): number {
  821. return this._lockstepMaxSteps;
  822. }
  823. public getGlInfo() {
  824. return {
  825. vendor: this._glVendor,
  826. renderer: this._glRenderer,
  827. version: this._glVersion
  828. }
  829. }
  830. public getAspectRatio(camera: Camera, useScreen = false): number {
  831. var viewport = camera.viewport;
  832. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  833. }
  834. public getRenderWidth(useScreen = false): number {
  835. if (!useScreen && this._currentRenderTarget) {
  836. return this._currentRenderTarget._width;
  837. }
  838. return this._gl.drawingBufferWidth;
  839. }
  840. public getRenderHeight(useScreen = false): number {
  841. if (!useScreen && this._currentRenderTarget) {
  842. return this._currentRenderTarget._height;
  843. }
  844. return this._gl.drawingBufferHeight;
  845. }
  846. public getRenderingCanvas(): HTMLCanvasElement {
  847. return this._renderingCanvas;
  848. }
  849. public getRenderingCanvasClientRect(): ClientRect {
  850. return this._renderingCanvas.getBoundingClientRect();
  851. }
  852. public setHardwareScalingLevel(level: number): void {
  853. this._hardwareScalingLevel = level;
  854. this.resize();
  855. }
  856. public getHardwareScalingLevel(): number {
  857. return this._hardwareScalingLevel;
  858. }
  859. public getLoadedTexturesCache(): WebGLTexture[] {
  860. return this._loadedTexturesCache;
  861. }
  862. public getCaps(): EngineCapabilities {
  863. return this._caps;
  864. }
  865. /** The number of draw calls submitted last frame */
  866. public get drawCalls(): number {
  867. return this._drawCalls.current;
  868. }
  869. public get drawCallsPerfCounter(): PerfCounter {
  870. return this._drawCalls;
  871. }
  872. public getDepthFunction(): number {
  873. return this._depthCullingState.depthFunc;
  874. }
  875. public setDepthFunction(depthFunc: number) {
  876. this._depthCullingState.depthFunc = depthFunc;
  877. }
  878. public setDepthFunctionToGreater(): void {
  879. this._depthCullingState.depthFunc = this._gl.GREATER;
  880. }
  881. public setDepthFunctionToGreaterOrEqual(): void {
  882. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  883. }
  884. public setDepthFunctionToLess(): void {
  885. this._depthCullingState.depthFunc = this._gl.LESS;
  886. }
  887. public setDepthFunctionToLessOrEqual(): void {
  888. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  889. }
  890. public getStencilBuffer(): boolean {
  891. return this._stencilState.stencilTest;
  892. }
  893. public setStencilBuffer(enable: boolean): void {
  894. this._stencilState.stencilTest = enable;
  895. }
  896. public getStencilMask(): number {
  897. return this._stencilState.stencilMask;
  898. }
  899. public setStencilMask(mask: number): void {
  900. this._stencilState.stencilMask = mask;
  901. }
  902. public getStencilFunction(): number {
  903. return this._stencilState.stencilFunc;
  904. }
  905. public getStencilFunctionReference(): number {
  906. return this._stencilState.stencilFuncRef;
  907. }
  908. public getStencilFunctionMask(): number {
  909. return this._stencilState.stencilFuncMask;
  910. }
  911. public setStencilFunction(stencilFunc: number) {
  912. this._stencilState.stencilFunc = stencilFunc;
  913. }
  914. public setStencilFunctionReference(reference: number) {
  915. this._stencilState.stencilFuncRef = reference;
  916. }
  917. public setStencilFunctionMask(mask: number) {
  918. this._stencilState.stencilFuncMask = mask;
  919. }
  920. public getStencilOperationFail(): number {
  921. return this._stencilState.stencilOpStencilFail;
  922. }
  923. public getStencilOperationDepthFail(): number {
  924. return this._stencilState.stencilOpDepthFail;
  925. }
  926. public getStencilOperationPass(): number {
  927. return this._stencilState.stencilOpStencilDepthPass;
  928. }
  929. public setStencilOperationFail(operation: number): void {
  930. this._stencilState.stencilOpStencilFail = operation;
  931. }
  932. public setStencilOperationDepthFail(operation: number): void {
  933. this._stencilState.stencilOpDepthFail = operation;
  934. }
  935. public setStencilOperationPass(operation: number): void {
  936. this._stencilState.stencilOpStencilDepthPass = operation;
  937. }
  938. public setDitheringState(value: boolean): void {
  939. if (value) {
  940. this._gl.enable(this._gl.DITHER);
  941. } else {
  942. this._gl.disable(this._gl.DITHER);
  943. }
  944. }
  945. /**
  946. * stop executing a render loop function and remove it from the execution array
  947. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  948. */
  949. public stopRenderLoop(renderFunction?: () => void): void {
  950. if (!renderFunction) {
  951. this._activeRenderLoops = [];
  952. return;
  953. }
  954. var index = this._activeRenderLoops.indexOf(renderFunction);
  955. if (index >= 0) {
  956. this._activeRenderLoops.splice(index, 1);
  957. }
  958. }
  959. public _renderLoop(): void {
  960. var shouldRender = true;
  961. if (!this.renderEvenInBackground && this._windowIsBackground) {
  962. shouldRender = false;
  963. }
  964. if (shouldRender) {
  965. // Start new frame
  966. this.beginFrame();
  967. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  968. var renderFunction = this._activeRenderLoops[index];
  969. renderFunction();
  970. }
  971. // Present
  972. this.endFrame();
  973. }
  974. if (this._activeRenderLoops.length > 0) {
  975. // Register new frame
  976. Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  977. } else {
  978. this._renderingQueueLaunched = false;
  979. }
  980. }
  981. /**
  982. * Register and execute a render loop. The engine can have more than one render function.
  983. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  984. * @example
  985. * engine.runRenderLoop(function () {
  986. * scene.render()
  987. * })
  988. */
  989. public runRenderLoop(renderFunction: () => void): void {
  990. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  991. return;
  992. }
  993. this._activeRenderLoops.push(renderFunction);
  994. if (!this._renderingQueueLaunched) {
  995. this._renderingQueueLaunched = true;
  996. this._bindedRenderFunction = this._renderLoop.bind(this);
  997. Tools.QueueNewFrame(this._bindedRenderFunction);
  998. }
  999. }
  1000. /**
  1001. * Toggle full screen mode.
  1002. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  1003. * @param {any} options - an options object to be sent to the requestFullscreen function
  1004. */
  1005. public switchFullscreen(requestPointerLock: boolean): void {
  1006. if (this.isFullscreen) {
  1007. Tools.ExitFullscreen();
  1008. } else {
  1009. this._pointerLockRequested = requestPointerLock;
  1010. Tools.RequestFullscreen(this._renderingCanvas);
  1011. }
  1012. }
  1013. public clear(color: Color4, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1014. this.applyStates();
  1015. var mode = 0;
  1016. if (backBuffer && color) {
  1017. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1018. mode |= this._gl.COLOR_BUFFER_BIT;
  1019. }
  1020. if (depth) {
  1021. this._gl.clearDepth(1.0);
  1022. mode |= this._gl.DEPTH_BUFFER_BIT;
  1023. }
  1024. if (stencil) {
  1025. this._gl.clearStencil(0);
  1026. mode |= this._gl.STENCIL_BUFFER_BIT;
  1027. }
  1028. this._gl.clear(mode);
  1029. }
  1030. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1031. let gl = this._gl;
  1032. // Save state
  1033. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1034. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1035. // Change state
  1036. gl.enable(gl.SCISSOR_TEST);
  1037. gl.scissor(x, y, width, height);
  1038. // Clear
  1039. this.clear(clearColor, true, true, true);
  1040. // Restore state
  1041. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1042. if (curScissor === true) {
  1043. gl.enable(gl.SCISSOR_TEST);
  1044. } else {
  1045. gl.disable(gl.SCISSOR_TEST);
  1046. }
  1047. }
  1048. /**
  1049. * Set the WebGL's viewport
  1050. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  1051. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  1052. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  1053. */
  1054. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1055. var width = requiredWidth || this.getRenderWidth();
  1056. var height = requiredHeight || this.getRenderHeight();
  1057. var x = viewport.x || 0;
  1058. var y = viewport.y || 0;
  1059. this._cachedViewport = viewport;
  1060. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1061. }
  1062. /**
  1063. * Directly set the WebGL Viewport
  1064. * The x, y, width & height are directly passed to the WebGL call
  1065. * @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.
  1066. */
  1067. public setDirectViewport(x: number, y: number, width: number, height: number): Viewport {
  1068. let currentViewport = this._cachedViewport;
  1069. this._cachedViewport = null;
  1070. this._gl.viewport(x, y, width, height);
  1071. return currentViewport;
  1072. }
  1073. public beginFrame(): void {
  1074. this._measureFps();
  1075. }
  1076. public endFrame(): void {
  1077. //force a flush in case we are using a bad OS.
  1078. if (this._badOS) {
  1079. this.flushFramebuffer();
  1080. }
  1081. //submit frame to the vr device, if enabled
  1082. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  1083. this._vrDisplayEnabled.submitFrame()
  1084. }
  1085. }
  1086. /**
  1087. * resize the view according to the canvas' size.
  1088. * @example
  1089. * window.addEventListener("resize", function () {
  1090. * engine.resize();
  1091. * });
  1092. */
  1093. public resize(): void {
  1094. // We're not resizing the size of the canvas while in VR mode & presenting
  1095. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  1096. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  1097. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  1098. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1099. }
  1100. }
  1101. /**
  1102. * force a specific size of the canvas
  1103. * @param {number} width - the new canvas' width
  1104. * @param {number} height - the new canvas' height
  1105. */
  1106. public setSize(width: number, height: number): void {
  1107. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1108. return;
  1109. }
  1110. this._renderingCanvas.width = width;
  1111. this._renderingCanvas.height = height;
  1112. for (var index = 0; index < this.scenes.length; index++) {
  1113. var scene = this.scenes[index];
  1114. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1115. var cam = scene.cameras[camIndex];
  1116. cam._currentRenderId = 0;
  1117. }
  1118. }
  1119. if (this.onResizeObservable.hasObservers) {
  1120. this.onResizeObservable.notifyObservers(this);
  1121. }
  1122. }
  1123. //WebVR functions
  1124. public isVRDevicePresent(callback: (result: boolean) => void) {
  1125. this.getVRDevice(null, (device) => {
  1126. callback(device !== null);
  1127. });
  1128. }
  1129. public getVRDevice(name: string, callback: (device: any) => void) {
  1130. if (!this.vrDisplaysPromise) {
  1131. callback(null);
  1132. return;
  1133. }
  1134. this.vrDisplaysPromise.then((devices) => {
  1135. if (devices.length > 0) {
  1136. if (name) {
  1137. var found = devices.some(device => {
  1138. if (device.displayName === name) {
  1139. callback(device);
  1140. return true;
  1141. } else {
  1142. return false;
  1143. }
  1144. });
  1145. if (!found) {
  1146. Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  1147. callback(devices[0]);
  1148. }
  1149. } else {
  1150. //choose the first one
  1151. callback(devices[0]);
  1152. }
  1153. } else {
  1154. Tools.Error("No WebVR devices found!");
  1155. callback(null);
  1156. }
  1157. });
  1158. }
  1159. public initWebVR(): void {
  1160. if (!this.vrDisplaysPromise) {
  1161. this._getVRDisplays();
  1162. }
  1163. }
  1164. public enableVR(vrDevice) {
  1165. this._vrDisplayEnabled = vrDevice;
  1166. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  1167. }
  1168. public disableVR() {
  1169. if (this._vrDisplayEnabled) {
  1170. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  1171. }
  1172. }
  1173. private _onVRFullScreenTriggered = () => {
  1174. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  1175. //get the old size before we change
  1176. this._oldSize = new BABYLON.Size(this.getRenderWidth(), this.getRenderHeight());
  1177. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  1178. //get the width and height, change the render size
  1179. var leftEye = this._vrDisplayEnabled.getEyeParameters('left');
  1180. var width, height;
  1181. this.setHardwareScalingLevel(1);
  1182. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  1183. } else {
  1184. //When the specs are implemented, need to uncomment this.
  1185. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  1186. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  1187. this.setSize(this._oldSize.width, this._oldSize.height);
  1188. this._vrDisplayEnabled = undefined;
  1189. }
  1190. }
  1191. private _getVRDisplays() {
  1192. var getWebVRDevices = (devices: Array<any>) => {
  1193. var size = devices.length;
  1194. var i = 0;
  1195. this._vrDisplays = devices.filter(function (device) {
  1196. return devices[i] instanceof VRDisplay;
  1197. });
  1198. return this._vrDisplays;
  1199. }
  1200. //using a key due to typescript
  1201. if (navigator.getVRDisplays) {
  1202. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  1203. }
  1204. }
  1205. public bindFramebuffer(texture: WebGLTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean): void {
  1206. if (this._currentRenderTarget) {
  1207. this.unBindFramebuffer(this._currentRenderTarget);
  1208. }
  1209. this._currentRenderTarget = texture;
  1210. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1211. var gl = this._gl;
  1212. if (texture.isCube) {
  1213. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  1214. }
  1215. if (this._cachedViewport && !forceFullscreenViewport) {
  1216. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1217. } else {
  1218. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  1219. }
  1220. this.wipeCaches();
  1221. }
  1222. private bindUnboundFramebuffer(framebuffer: WebGLFramebuffer) {
  1223. if (this._currentFramebuffer !== framebuffer) {
  1224. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1225. this._currentFramebuffer = framebuffer;
  1226. }
  1227. }
  1228. public unBindFramebuffer(texture: WebGLTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1229. this._currentRenderTarget = null;
  1230. // If MSAA, we need to bitblt back to main texture
  1231. var gl = this._gl;
  1232. if (texture._MSAAFramebuffer) {
  1233. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1234. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1235. gl.blitFramebuffer(0, 0, texture._width, texture._height,
  1236. 0, 0, texture._width, texture._height,
  1237. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1238. }
  1239. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1240. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  1241. gl.generateMipmap(gl.TEXTURE_2D);
  1242. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1243. }
  1244. if (onBeforeUnbind) {
  1245. if (texture._MSAAFramebuffer) {
  1246. // Bind the correct framebuffer
  1247. this.bindUnboundFramebuffer(texture._framebuffer);
  1248. }
  1249. onBeforeUnbind();
  1250. }
  1251. this.bindUnboundFramebuffer(null);
  1252. }
  1253. public generateMipMapsForCubemap(texture: WebGLTexture) {
  1254. if (texture.generateMipMaps) {
  1255. var gl = this._gl;
  1256. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  1257. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  1258. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  1259. }
  1260. }
  1261. public flushFramebuffer(): void {
  1262. this._gl.flush();
  1263. }
  1264. public restoreDefaultFramebuffer(): void {
  1265. if (this._currentRenderTarget) {
  1266. this.unBindFramebuffer(this._currentRenderTarget);
  1267. } else {
  1268. this.bindUnboundFramebuffer(null);
  1269. }
  1270. if (this._cachedViewport) {
  1271. this.setViewport(this._cachedViewport);
  1272. }
  1273. this.wipeCaches();
  1274. }
  1275. // UBOs
  1276. public createUniformBuffer(elements: number[] | Float32Array): WebGLBuffer {
  1277. var ubo = this._gl.createBuffer();
  1278. this.bindUniformBuffer(ubo);
  1279. if (elements instanceof Float32Array) {
  1280. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  1281. } else {
  1282. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  1283. }
  1284. this.bindUniformBuffer(null);
  1285. ubo.references = 1;
  1286. return ubo;
  1287. }
  1288. public createDynamicUniformBuffer(elements: number[] | Float32Array): WebGLBuffer {
  1289. var ubo = this._gl.createBuffer();
  1290. this.bindUniformBuffer(ubo);
  1291. if (elements instanceof Float32Array) {
  1292. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  1293. } else {
  1294. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  1295. }
  1296. this.bindUniformBuffer(null);
  1297. ubo.references = 1;
  1298. return ubo;
  1299. }
  1300. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: number[] | Float32Array, offset?: number, count?: number): void {
  1301. this.bindUniformBuffer(uniformBuffer);
  1302. if (offset === undefined) {
  1303. offset = 0;
  1304. }
  1305. if (count === undefined) {
  1306. if (elements instanceof Float32Array) {
  1307. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  1308. } else {
  1309. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  1310. }
  1311. } else {
  1312. if (elements instanceof Float32Array) {
  1313. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  1314. } else {
  1315. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  1316. }
  1317. }
  1318. this.bindUniformBuffer(null);
  1319. }
  1320. // VBOs
  1321. private _resetVertexBufferBinding(): void {
  1322. this.bindArrayBuffer(null);
  1323. this._cachedVertexBuffers = null;
  1324. }
  1325. public createVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1326. var vbo = this._gl.createBuffer();
  1327. this.bindArrayBuffer(vbo);
  1328. if (vertices instanceof Float32Array) {
  1329. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.STATIC_DRAW);
  1330. } else {
  1331. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.STATIC_DRAW);
  1332. }
  1333. this._resetVertexBufferBinding();
  1334. vbo.references = 1;
  1335. return vbo;
  1336. }
  1337. public createDynamicVertexBuffer(vertices: number[] | Float32Array): WebGLBuffer {
  1338. var vbo = this._gl.createBuffer();
  1339. this.bindArrayBuffer(vbo);
  1340. if (vertices instanceof Float32Array) {
  1341. this._gl.bufferData(this._gl.ARRAY_BUFFER, <Float32Array>vertices, this._gl.DYNAMIC_DRAW);
  1342. } else {
  1343. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(<number[]>vertices), this._gl.DYNAMIC_DRAW);
  1344. }
  1345. this._resetVertexBufferBinding();
  1346. vbo.references = 1;
  1347. return vbo;
  1348. }
  1349. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: number[] | Float32Array, offset?: number, count?: number): void {
  1350. this.bindArrayBuffer(vertexBuffer);
  1351. if (offset === undefined) {
  1352. offset = 0;
  1353. }
  1354. if (count === undefined) {
  1355. if (vertices instanceof Float32Array) {
  1356. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, <Float32Array>vertices);
  1357. } else {
  1358. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(<number[]>vertices));
  1359. }
  1360. } else {
  1361. if (vertices instanceof Float32Array) {
  1362. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <Float32Array>vertices.subarray(offset, offset + count));
  1363. } else {
  1364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(<number[]>vertices).subarray(offset, offset + count));
  1365. }
  1366. }
  1367. this._resetVertexBufferBinding();
  1368. }
  1369. private _resetIndexBufferBinding(): void {
  1370. this.bindIndexBuffer(null);
  1371. this._cachedIndexBuffer = null;
  1372. }
  1373. public createIndexBuffer(indices: IndicesArray): WebGLBuffer {
  1374. var vbo = this._gl.createBuffer();
  1375. this.bindIndexBuffer(vbo);
  1376. // Check for 32 bits indices
  1377. var arrayBuffer;
  1378. var need32Bits = false;
  1379. if (indices instanceof Uint16Array) {
  1380. arrayBuffer = indices;
  1381. } else {
  1382. //check 32 bit support
  1383. if (this._caps.uintIndices) {
  1384. if (indices instanceof Uint32Array) {
  1385. arrayBuffer = indices;
  1386. need32Bits = true;
  1387. } else {
  1388. //number[] or Int32Array, check if 32 bit is necessary
  1389. for (var index = 0; index < indices.length; index++) {
  1390. if (indices[index] > 65535) {
  1391. need32Bits = true;
  1392. break;
  1393. }
  1394. }
  1395. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  1396. }
  1397. } else {
  1398. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1399. arrayBuffer = new Uint16Array(indices);
  1400. }
  1401. }
  1402. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  1403. this._resetIndexBufferBinding();
  1404. vbo.references = 1;
  1405. vbo.is32Bits = need32Bits;
  1406. return vbo;
  1407. }
  1408. public bindArrayBuffer(buffer: WebGLBuffer): void {
  1409. if (!this._vaoRecordInProgress) {
  1410. this._unbindVertexArrayObject();
  1411. }
  1412. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1413. }
  1414. public bindUniformBuffer(buffer?: WebGLBuffer): void {
  1415. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  1416. }
  1417. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  1418. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  1419. }
  1420. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  1421. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  1422. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  1423. };
  1424. private bindIndexBuffer(buffer: WebGLBuffer): void {
  1425. if (!this._vaoRecordInProgress) {
  1426. this._unbindVertexArrayObject();
  1427. }
  1428. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1429. }
  1430. private bindBuffer(buffer: WebGLBuffer, target: number): void {
  1431. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1432. this._gl.bindBuffer(target, buffer);
  1433. this._currentBoundBuffer[target] = buffer;
  1434. }
  1435. }
  1436. public updateArrayBuffer(data: Float32Array): void {
  1437. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1438. }
  1439. private vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1440. var pointer = this._currentBufferPointers[indx];
  1441. var changed = false;
  1442. if (!pointer.active) {
  1443. changed = true;
  1444. pointer.active = true;
  1445. pointer.index = indx;
  1446. pointer.size = size;
  1447. pointer.type = type;
  1448. pointer.normalized = normalized;
  1449. pointer.stride = stride;
  1450. pointer.offset = offset;
  1451. pointer.buffer = buffer;
  1452. } else {
  1453. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1454. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1455. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1456. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1457. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1458. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1459. }
  1460. if (changed || this._vaoRecordInProgress) {
  1461. this.bindArrayBuffer(buffer);
  1462. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1463. }
  1464. }
  1465. private _bindIndexBufferWithCache(indexBuffer: WebGLBuffer): void {
  1466. if (indexBuffer == null) {
  1467. return;
  1468. }
  1469. if (this._cachedIndexBuffer !== indexBuffer) {
  1470. this._cachedIndexBuffer = indexBuffer;
  1471. this.bindIndexBuffer(indexBuffer);
  1472. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1473. }
  1474. }
  1475. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: VertexBuffer; }, effect: Effect) {
  1476. var attributes = effect.getAttributesNames();
  1477. if (!this._vaoRecordInProgress) {
  1478. this._unbindVertexArrayObject();
  1479. }
  1480. this.unbindAllAttributes();
  1481. for (var index = 0; index < attributes.length; index++) {
  1482. var order = effect.getAttributeLocation(index);
  1483. if (order >= 0) {
  1484. var vertexBuffer = vertexBuffers[attributes[index]];
  1485. if (!vertexBuffer) {
  1486. continue;
  1487. }
  1488. this._gl.enableVertexAttribArray(order);
  1489. if (!this._vaoRecordInProgress) {
  1490. this._vertexAttribArraysEnabled[order] = true;
  1491. }
  1492. var buffer = vertexBuffer.getBuffer();
  1493. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  1494. if (vertexBuffer.getIsInstanced()) {
  1495. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1496. if (!this._vaoRecordInProgress) {
  1497. this._currentInstanceLocations.push(order);
  1498. this._currentInstanceBuffers.push(buffer);
  1499. }
  1500. }
  1501. }
  1502. }
  1503. }
  1504. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): WebGLVertexArrayObject {
  1505. var vao = this._gl.createVertexArray();
  1506. this._vaoRecordInProgress = true;
  1507. this._gl.bindVertexArray(vao);
  1508. this._mustWipeVertexAttributes = true;
  1509. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1510. this.bindIndexBuffer(indexBuffer);
  1511. this._vaoRecordInProgress = false;
  1512. this._gl.bindVertexArray(null);
  1513. return vao;
  1514. }
  1515. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: WebGLBuffer): void {
  1516. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1517. this._cachedVertexArrayObject = vertexArrayObject;
  1518. this._gl.bindVertexArray(vertexArrayObject);
  1519. this._cachedVertexBuffers = null;
  1520. this._cachedIndexBuffer = null;
  1521. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1522. this._mustWipeVertexAttributes = true;
  1523. }
  1524. }
  1525. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1526. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1527. this._cachedVertexBuffers = vertexBuffer;
  1528. this._cachedEffectForVertexBuffers = effect;
  1529. let attributesCount = effect.getAttributesCount();
  1530. this._unbindVertexArrayObject();
  1531. this.unbindAllAttributes();
  1532. var offset = 0;
  1533. for (var index = 0; index < attributesCount; index++) {
  1534. if (index < vertexDeclaration.length) {
  1535. var order = effect.getAttributeLocation(index);
  1536. if (order >= 0) {
  1537. this._gl.enableVertexAttribArray(order);
  1538. this._vertexAttribArraysEnabled[order] = true;
  1539. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1540. }
  1541. offset += vertexDeclaration[index] * 4;
  1542. }
  1543. }
  1544. }
  1545. this._bindIndexBufferWithCache(indexBuffer);
  1546. }
  1547. private _unbindVertexArrayObject(): void {
  1548. if (!this._cachedVertexArrayObject) {
  1549. return;
  1550. }
  1551. this._cachedVertexArrayObject = null;
  1552. this._gl.bindVertexArray(null);
  1553. }
  1554. public bindBuffers(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: WebGLBuffer, effect: Effect): void {
  1555. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1556. this._cachedVertexBuffers = vertexBuffers;
  1557. this._cachedEffectForVertexBuffers = effect;
  1558. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1559. }
  1560. this._bindIndexBufferWithCache(indexBuffer);
  1561. }
  1562. public unbindInstanceAttributes() {
  1563. var boundBuffer;
  1564. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1565. var instancesBuffer = this._currentInstanceBuffers[i];
  1566. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  1567. boundBuffer = instancesBuffer;
  1568. this.bindArrayBuffer(instancesBuffer);
  1569. }
  1570. var offsetLocation = this._currentInstanceLocations[i];
  1571. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1572. }
  1573. this._currentInstanceBuffers.length = 0;
  1574. this._currentInstanceLocations.length = 0;
  1575. }
  1576. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1577. this._gl.deleteVertexArray(vao);
  1578. }
  1579. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  1580. buffer.references--;
  1581. if (buffer.references === 0) {
  1582. this._gl.deleteBuffer(buffer);
  1583. return true;
  1584. }
  1585. return false;
  1586. }
  1587. public createInstancesBuffer(capacity: number): WebGLBuffer {
  1588. var buffer = this._gl.createBuffer();
  1589. buffer.capacity = capacity;
  1590. this.bindArrayBuffer(buffer);
  1591. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  1592. return buffer;
  1593. }
  1594. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  1595. this._gl.deleteBuffer(buffer);
  1596. }
  1597. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1598. this.bindArrayBuffer(instancesBuffer);
  1599. if (data) {
  1600. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1601. }
  1602. if ((<any>offsetLocations[0]).index !== undefined) {
  1603. let stride = 0;
  1604. for (let i = 0; i < offsetLocations.length; i++) {
  1605. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1606. stride += ai.attributeSize * 4;
  1607. }
  1608. for (let i = 0; i < offsetLocations.length; i++) {
  1609. let ai = <InstancingAttributeInfo>offsetLocations[i];
  1610. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1611. this._gl.enableVertexAttribArray(ai.index);
  1612. this._vertexAttribArraysEnabled[ai.index] = true;
  1613. }
  1614. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1615. this._gl.vertexAttribDivisor(ai.index, 1);
  1616. this._currentInstanceLocations.push(ai.index);
  1617. this._currentInstanceBuffers.push(instancesBuffer);
  1618. }
  1619. } else {
  1620. for (let index = 0; index < 4; index++) {
  1621. let offsetLocation = <number>offsetLocations[index];
  1622. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1623. this._gl.enableVertexAttribArray(offsetLocation);
  1624. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1625. }
  1626. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1627. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1628. this._currentInstanceLocations.push(offsetLocation);
  1629. this._currentInstanceBuffers.push(instancesBuffer);
  1630. }
  1631. }
  1632. }
  1633. public applyStates() {
  1634. this._depthCullingState.apply(this._gl);
  1635. this._stencilState.apply(this._gl);
  1636. this._alphaState.apply(this._gl);
  1637. }
  1638. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1639. // Apply states
  1640. this.applyStates();
  1641. this._drawCalls.addCount(1, false);
  1642. // Render
  1643. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1644. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1645. if (instancesCount) {
  1646. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  1647. return;
  1648. }
  1649. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  1650. }
  1651. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1652. // Apply states
  1653. this.applyStates();
  1654. this._drawCalls.addCount(1, false);
  1655. if (instancesCount) {
  1656. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  1657. return;
  1658. }
  1659. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  1660. }
  1661. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1662. // Apply states
  1663. this.applyStates();
  1664. this._drawCalls.addCount(1, false);
  1665. if (instancesCount) {
  1666. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  1667. return;
  1668. }
  1669. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  1670. }
  1671. // Shaders
  1672. public _releaseEffect(effect: Effect): void {
  1673. if (this._compiledEffects[effect._key]) {
  1674. delete this._compiledEffects[effect._key];
  1675. if (effect.getProgram()) {
  1676. this._gl.deleteProgram(effect.getProgram());
  1677. }
  1678. }
  1679. }
  1680. /**
  1681. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  1682. * @param samplers An array of string used to represent textures
  1683. */
  1684. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  1685. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  1686. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1687. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1688. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  1689. if (this._compiledEffects[name]) {
  1690. var compiledEffect = <Effect>this._compiledEffects[name];
  1691. if (onCompiled && compiledEffect.isReady()) {
  1692. onCompiled(compiledEffect);
  1693. }
  1694. return compiledEffect;
  1695. }
  1696. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1697. effect._key = name;
  1698. this._compiledEffects[name] = effect;
  1699. return effect;
  1700. }
  1701. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  1702. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  1703. return this.createEffect(
  1704. {
  1705. vertex: "particles",
  1706. fragmentElement: fragmentName
  1707. },
  1708. ["position", "color", "options"],
  1709. ["view", "projection"].concat(uniformsNames),
  1710. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  1711. }
  1712. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: string, context?: WebGLRenderingContext): WebGLProgram {
  1713. context = context || this._gl;
  1714. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  1715. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  1716. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  1717. var shaderProgram = context.createProgram();
  1718. context.attachShader(shaderProgram, vertexShader);
  1719. context.attachShader(shaderProgram, fragmentShader);
  1720. context.linkProgram(shaderProgram);
  1721. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  1722. if (!linked) {
  1723. context.validateProgram(shaderProgram);
  1724. var error = context.getProgramInfoLog(shaderProgram);
  1725. if (error) {
  1726. throw new Error(error);
  1727. }
  1728. }
  1729. context.deleteShader(vertexShader);
  1730. context.deleteShader(fragmentShader);
  1731. return shaderProgram;
  1732. }
  1733. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[] {
  1734. var results = [];
  1735. for (var index = 0; index < uniformsNames.length; index++) {
  1736. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  1737. }
  1738. return results;
  1739. }
  1740. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  1741. var results = [];
  1742. for (var index = 0; index < attributesNames.length; index++) {
  1743. try {
  1744. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  1745. } catch (e) {
  1746. results.push(-1);
  1747. }
  1748. }
  1749. return results;
  1750. }
  1751. public enableEffect(effect: Effect): void {
  1752. // Use program
  1753. this.setProgram(effect.getProgram());
  1754. this._currentEffect = effect;
  1755. if (effect.onBind) {
  1756. effect.onBind(effect);
  1757. }
  1758. effect.onBindObservable.notifyObservers(effect);
  1759. }
  1760. public setIntArray(uniform: WebGLUniformLocation, array: Int32Array): void {
  1761. if (!uniform)
  1762. return;
  1763. this._gl.uniform1iv(uniform, array);
  1764. }
  1765. public setIntArray2(uniform: WebGLUniformLocation, array: Int32Array): void {
  1766. if (!uniform || array.length % 2 !== 0)
  1767. return;
  1768. this._gl.uniform2iv(uniform, array);
  1769. }
  1770. public setIntArray3(uniform: WebGLUniformLocation, array: Int32Array): void {
  1771. if (!uniform || array.length % 3 !== 0)
  1772. return;
  1773. this._gl.uniform3iv(uniform, array);
  1774. }
  1775. public setIntArray4(uniform: WebGLUniformLocation, array: Int32Array): void {
  1776. if (!uniform || array.length % 4 !== 0)
  1777. return;
  1778. this._gl.uniform4iv(uniform, array);
  1779. }
  1780. public setFloatArray(uniform: WebGLUniformLocation, array: Float32Array): void {
  1781. if (!uniform)
  1782. return;
  1783. this._gl.uniform1fv(uniform, array);
  1784. }
  1785. public setFloatArray2(uniform: WebGLUniformLocation, array: Float32Array): void {
  1786. if (!uniform || array.length % 2 !== 0)
  1787. return;
  1788. this._gl.uniform2fv(uniform, array);
  1789. }
  1790. public setFloatArray3(uniform: WebGLUniformLocation, array: Float32Array): void {
  1791. if (!uniform || array.length % 3 !== 0)
  1792. return;
  1793. this._gl.uniform3fv(uniform, array);
  1794. }
  1795. public setFloatArray4(uniform: WebGLUniformLocation, array: Float32Array): void {
  1796. if (!uniform || array.length % 4 !== 0)
  1797. return;
  1798. this._gl.uniform4fv(uniform, array);
  1799. }
  1800. public setArray(uniform: WebGLUniformLocation, array: number[]): void {
  1801. if (!uniform)
  1802. return;
  1803. this._gl.uniform1fv(uniform, <any>array);
  1804. }
  1805. public setArray2(uniform: WebGLUniformLocation, array: number[]): void {
  1806. if (!uniform || array.length % 2 !== 0)
  1807. return;
  1808. this._gl.uniform2fv(uniform, <any>array);
  1809. }
  1810. public setArray3(uniform: WebGLUniformLocation, array: number[]): void {
  1811. if (!uniform || array.length % 3 !== 0)
  1812. return;
  1813. this._gl.uniform3fv(uniform, <any>array);
  1814. }
  1815. public setArray4(uniform: WebGLUniformLocation, array: number[]): void {
  1816. if (!uniform || array.length % 4 !== 0)
  1817. return;
  1818. this._gl.uniform4fv(uniform, <any>array);
  1819. }
  1820. public setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void {
  1821. if (!uniform)
  1822. return;
  1823. this._gl.uniformMatrix4fv(uniform, false, matrices);
  1824. }
  1825. public setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void {
  1826. if (!uniform)
  1827. return;
  1828. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  1829. }
  1830. public setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1831. if (!uniform)
  1832. return;
  1833. this._gl.uniformMatrix3fv(uniform, false, matrix);
  1834. }
  1835. public setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void {
  1836. if (!uniform)
  1837. return;
  1838. this._gl.uniformMatrix2fv(uniform, false, matrix);
  1839. }
  1840. public setFloat(uniform: WebGLUniformLocation, value: number): void {
  1841. if (!uniform)
  1842. return;
  1843. this._gl.uniform1f(uniform, value);
  1844. }
  1845. public setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void {
  1846. if (!uniform)
  1847. return;
  1848. this._gl.uniform2f(uniform, x, y);
  1849. }
  1850. public setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void {
  1851. if (!uniform)
  1852. return;
  1853. this._gl.uniform3f(uniform, x, y, z);
  1854. }
  1855. public setBool(uniform: WebGLUniformLocation, bool: number): void {
  1856. if (!uniform)
  1857. return;
  1858. this._gl.uniform1i(uniform, bool);
  1859. }
  1860. public setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void {
  1861. if (!uniform)
  1862. return;
  1863. this._gl.uniform4f(uniform, x, y, z, w);
  1864. }
  1865. public setColor3(uniform: WebGLUniformLocation, color3: Color3): void {
  1866. if (!uniform)
  1867. return;
  1868. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  1869. }
  1870. public setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void {
  1871. if (!uniform)
  1872. return;
  1873. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  1874. }
  1875. // States
  1876. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  1877. // Culling
  1878. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  1879. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  1880. var cullFace = this.cullBackFaces ? showSide : hideSide;
  1881. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  1882. if (culling) {
  1883. this._depthCullingState.cullFace = cullFace;
  1884. this._depthCullingState.cull = true;
  1885. } else {
  1886. this._depthCullingState.cull = false;
  1887. }
  1888. }
  1889. // Z offset
  1890. this.setZOffset(zOffset);
  1891. }
  1892. public setZOffset(value: number): void {
  1893. this._depthCullingState.zOffset = value;
  1894. }
  1895. public getZOffset(): number {
  1896. return this._depthCullingState.zOffset;
  1897. }
  1898. public setDepthBuffer(enable: boolean): void {
  1899. this._depthCullingState.depthTest = enable;
  1900. }
  1901. public getDepthWrite(): boolean {
  1902. return this._depthCullingState.depthMask;
  1903. }
  1904. public setDepthWrite(enable: boolean): void {
  1905. this._depthCullingState.depthMask = enable;
  1906. }
  1907. public setColorWrite(enable: boolean): void {
  1908. this._gl.colorMask(enable, enable, enable, enable);
  1909. }
  1910. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  1911. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  1912. }
  1913. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  1914. if (this._alphaMode === mode) {
  1915. return;
  1916. }
  1917. switch (mode) {
  1918. case Engine.ALPHA_DISABLE:
  1919. this._alphaState.alphaBlend = false;
  1920. break;
  1921. case Engine.ALPHA_PREMULTIPLIED:
  1922. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1923. this._alphaState.alphaBlend = true;
  1924. break;
  1925. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  1926. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  1927. this._alphaState.alphaBlend = true;
  1928. break;
  1929. case Engine.ALPHA_COMBINE:
  1930. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  1931. this._alphaState.alphaBlend = true;
  1932. break;
  1933. case Engine.ALPHA_ONEONE:
  1934. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1935. this._alphaState.alphaBlend = true;
  1936. break;
  1937. case Engine.ALPHA_ADD:
  1938. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  1939. this._alphaState.alphaBlend = true;
  1940. break;
  1941. case Engine.ALPHA_SUBTRACT:
  1942. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1943. this._alphaState.alphaBlend = true;
  1944. break;
  1945. case Engine.ALPHA_MULTIPLY:
  1946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  1947. this._alphaState.alphaBlend = true;
  1948. break;
  1949. case Engine.ALPHA_MAXIMIZED:
  1950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  1951. this._alphaState.alphaBlend = true;
  1952. break;
  1953. case Engine.ALPHA_INTERPOLATE:
  1954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  1955. this._alphaState.alphaBlend = true;
  1956. break;
  1957. case Engine.ALPHA_SCREENMODE:
  1958. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  1959. this._alphaState.alphaBlend = true;
  1960. break;
  1961. }
  1962. if (!noDepthWriteChange) {
  1963. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  1964. }
  1965. this._alphaMode = mode;
  1966. }
  1967. public getAlphaMode(): number {
  1968. return this._alphaMode;
  1969. }
  1970. public setAlphaTesting(enable: boolean): void {
  1971. this._alphaTest = enable;
  1972. }
  1973. public getAlphaTesting(): boolean {
  1974. return !!this._alphaTest;
  1975. }
  1976. // Textures
  1977. public wipeCaches(bruteForce?: boolean): void {
  1978. if (this.preventCacheWipeBetweenFrames) {
  1979. return;
  1980. }
  1981. this.resetTextureCache();
  1982. this._currentEffect = null;
  1983. // 6/8/2017: deltakosh: Should not be required anymore.
  1984. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  1985. if (bruteForce) {
  1986. this._currentProgram = null;
  1987. this._stencilState.reset();
  1988. this._depthCullingState.reset();
  1989. this.setDepthFunctionToLessOrEqual();
  1990. this._alphaState.reset();
  1991. }
  1992. this._cachedVertexBuffers = null;
  1993. this._cachedIndexBuffer = null;
  1994. this._cachedEffectForVertexBuffers = null;
  1995. this._unbindVertexArrayObject();
  1996. this.bindIndexBuffer(null);
  1997. this.bindArrayBuffer(null);
  1998. }
  1999. /**
  2000. * Set the compressed texture format to use, based on the formats you have, and the formats
  2001. * supported by the hardware / browser.
  2002. *
  2003. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  2004. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  2005. * to API arguments needed to compressed textures. This puts the burden on the container
  2006. * generator to house the arcane code for determining these for current & future formats.
  2007. *
  2008. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  2009. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  2010. *
  2011. * Note: The result of this call is not taken into account when a texture is base64.
  2012. *
  2013. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  2014. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  2015. *
  2016. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  2017. * @returns The extension selected.
  2018. */
  2019. public setTextureFormatToUse(formatsAvailable: Array<string>): string {
  2020. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  2021. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  2022. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  2023. return this._textureFormatInUse = this._texturesSupported[i];
  2024. }
  2025. }
  2026. }
  2027. // actively set format to nothing, to allow this to be called more than once
  2028. // and possibly fail the 2nd time
  2029. return this._textureFormatInUse = null;
  2030. }
  2031. /**
  2032. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  2033. * @param {string} urlArg- This contains one of the following:
  2034. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  2035. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2036. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2037. *
  2038. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  2039. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  2040. * @param {Scene} scene- Needed for loading to the correct scene.
  2041. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  2042. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  2043. * @param {callback} onError- Optional callback to be called upon failure.
  2044. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  2045. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  2046. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  2047. *
  2048. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  2049. */
  2050. public createTexture(urlArg: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE, onLoad: () => void = null, onError: () => void = null, buffer: ArrayBuffer | HTMLImageElement = null, fallBack?: WebGLTexture, format?: number): WebGLTexture {
  2051. var texture = fallBack ? fallBack : this._gl.createTexture();
  2052. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  2053. var fromData = url.substr(0, 5) === "data:";
  2054. var isBase64 = fromData && url.indexOf("base64") !== -1;
  2055. // establish the file extension, if possible
  2056. var lastDot = url.lastIndexOf('.');
  2057. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  2058. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  2059. var isTGA = (extension === ".tga");
  2060. // determine if a ktx file should be substituted
  2061. var isKTX = false;
  2062. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  2063. url = url.substring(0, lastDot) + this._textureFormatInUse;
  2064. isKTX = true;
  2065. }
  2066. scene._addPendingData(texture);
  2067. texture.url = url;
  2068. texture.generateMipMaps = !noMipmap;
  2069. texture.references = 1;
  2070. texture.samplingMode = samplingMode;
  2071. texture.onLoadedCallbacks = [];
  2072. if (onLoad) {
  2073. texture.onLoadedCallbacks.push(onLoad);
  2074. }
  2075. if (!fallBack) this._loadedTexturesCache.push(texture);
  2076. var onerror = () => {
  2077. scene._removePendingData(texture);
  2078. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  2079. if (isKTX) {
  2080. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  2081. } else if (onError) {
  2082. onError();
  2083. }
  2084. };
  2085. var callback: (arrayBuffer: any) => void;
  2086. // processing for non-image formats
  2087. if (isKTX || isTGA || isDDS) {
  2088. if (isKTX) {
  2089. callback = (data) => {
  2090. var ktx = new Internals.KhronosTextureContainer(data, 1);
  2091. this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  2092. ktx.uploadLevels(this._gl, !noMipmap);
  2093. return false;
  2094. }, samplingMode);
  2095. };
  2096. } else if (isTGA) {
  2097. callback = (arrayBuffer) => {
  2098. var data = new Uint8Array(arrayBuffer);
  2099. var header = Internals.TGATools.GetTGAHeader(data);
  2100. this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, () => {
  2101. Internals.TGATools.UploadContent(this._gl, data);
  2102. return false;
  2103. }, samplingMode);
  2104. };
  2105. } else if (isDDS) {
  2106. callback = (data) => {
  2107. var info = Internals.DDSTools.GetDDSInfo(data);
  2108. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  2109. this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  2110. Internals.DDSTools.UploadDDSLevels(this, data, info, loadMipmap, 1);
  2111. return false;
  2112. }, samplingMode);
  2113. };
  2114. }
  2115. if (!buffer) {
  2116. Tools.LoadFile(url, data => {
  2117. callback(data);
  2118. }, null, scene.database, true, onerror);
  2119. } else {
  2120. callback(buffer);
  2121. }
  2122. // image format processing
  2123. } else {
  2124. var onload = (img) => {
  2125. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2126. let gl = this._gl;
  2127. var isPot = (img.width === potWidth && img.height === potHeight);
  2128. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2129. if (isPot) {
  2130. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2131. return false;
  2132. }
  2133. // Using shaders to rescale because canvas.drawImage is lossy
  2134. let source = gl.createTexture();
  2135. this._bindTextureDirectly(gl.TEXTURE_2D, source);
  2136. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2138. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2139. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2140. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2141. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2142. this._releaseTexture(source);
  2143. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2144. continuationCallback();
  2145. });
  2146. return true;
  2147. }, samplingMode);
  2148. };
  2149. if (!fromData || isBase64)
  2150. Tools.LoadImage(url, onload, onerror, scene.database);
  2151. else if (buffer instanceof Array || typeof buffer === "string")
  2152. Tools.LoadImage(buffer, onload, onerror, scene.database);
  2153. else
  2154. onload(buffer);
  2155. }
  2156. return texture;
  2157. }
  2158. private _rescaleTexture(source: WebGLTexture, destination: WebGLTexture, scene: Scene, internalFormat: number, onComplete: () => void): void {
  2159. let rtt = this.createRenderTargetTexture({
  2160. width: destination._width,
  2161. height: destination._height,
  2162. }, {
  2163. generateMipMaps: false,
  2164. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  2165. samplingMode: Texture.BILINEAR_SAMPLINGMODE,
  2166. generateDepthBuffer: false,
  2167. generateStencilBuffer: false
  2168. }
  2169. );
  2170. if (!this._rescalePostProcess) {
  2171. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  2172. }
  2173. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  2174. this._rescalePostProcess.onApply = function (effect) {
  2175. effect._bindTexture("textureSampler", source);
  2176. }
  2177. scene.postProcessManager.directRender([this._rescalePostProcess], rtt);
  2178. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination);
  2179. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination._width, destination._height, 0);
  2180. this.unBindFramebuffer(rtt);
  2181. this._releaseTexture(rtt);
  2182. if (onComplete) {
  2183. onComplete();
  2184. }
  2185. });
  2186. }
  2187. private _getInternalFormat(format: number): number {
  2188. var internalFormat = this._gl.RGBA;
  2189. switch (format) {
  2190. case Engine.TEXTUREFORMAT_ALPHA:
  2191. internalFormat = this._gl.ALPHA;
  2192. break;
  2193. case Engine.TEXTUREFORMAT_LUMINANCE:
  2194. internalFormat = this._gl.LUMINANCE;
  2195. break;
  2196. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  2197. internalFormat = this._gl.LUMINANCE_ALPHA;
  2198. break;
  2199. case Engine.TEXTUREFORMAT_RGB:
  2200. internalFormat = this._gl.RGB;
  2201. break;
  2202. case Engine.TEXTUREFORMAT_RGBA:
  2203. internalFormat = this._gl.RGBA;
  2204. break;
  2205. }
  2206. return internalFormat;
  2207. }
  2208. public updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression: string = null): void {
  2209. var internalFormat = this._getInternalFormat(format);
  2210. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2211. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2212. if (texture._width % 4 !== 0) {
  2213. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  2214. }
  2215. if (compression) {
  2216. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  2217. } else {
  2218. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  2219. }
  2220. if (texture.generateMipMaps) {
  2221. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2222. }
  2223. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2224. this.resetTextureCache();
  2225. texture.isReady = true;
  2226. }
  2227. public createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): WebGLTexture {
  2228. var texture = this._gl.createTexture();
  2229. texture._baseWidth = width;
  2230. texture._baseHeight = height;
  2231. texture._width = width;
  2232. texture._height = height;
  2233. texture.references = 1;
  2234. this.updateRawTexture(texture, data, format, invertY, compression);
  2235. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2236. // Filters
  2237. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  2238. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2239. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2240. if (generateMipMaps) {
  2241. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2242. }
  2243. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2244. texture.samplingMode = samplingMode;
  2245. this._loadedTexturesCache.push(texture);
  2246. return texture;
  2247. }
  2248. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): WebGLTexture {
  2249. var texture = this._gl.createTexture();
  2250. texture._baseWidth = width;
  2251. texture._baseHeight = height;
  2252. if (generateMipMaps) {
  2253. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  2254. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  2255. }
  2256. this.resetTextureCache();
  2257. texture._width = width;
  2258. texture._height = height;
  2259. texture.isReady = false;
  2260. texture.generateMipMaps = generateMipMaps;
  2261. texture.references = 1;
  2262. texture.samplingMode = samplingMode;
  2263. this.updateTextureSamplingMode(samplingMode, texture);
  2264. this._loadedTexturesCache.push(texture);
  2265. return texture;
  2266. }
  2267. public updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void {
  2268. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  2269. if (texture.isCube) {
  2270. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  2271. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2272. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2273. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2274. } else {
  2275. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2276. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  2277. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2278. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2279. }
  2280. texture.samplingMode = samplingMode;
  2281. }
  2282. public updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  2283. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2284. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  2285. if (premulAlpha) {
  2286. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  2287. }
  2288. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2289. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  2290. if (texture.generateMipMaps) {
  2291. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2292. }
  2293. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2294. if (premulAlpha) {
  2295. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2296. }
  2297. this.resetTextureCache();
  2298. texture.isReady = true;
  2299. }
  2300. public updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void {
  2301. if (texture._isDisabled) {
  2302. return;
  2303. }
  2304. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2305. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  2306. try {
  2307. // Testing video texture support
  2308. if (this._videoTextureSupported === undefined) {
  2309. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2310. if (this._gl.getError() !== 0) {
  2311. this._videoTextureSupported = false;
  2312. } else {
  2313. this._videoTextureSupported = true;
  2314. }
  2315. }
  2316. // Copy video through the current working canvas if video texture is not supported
  2317. if (!this._videoTextureSupported) {
  2318. if (!texture._workingCanvas) {
  2319. texture._workingCanvas = document.createElement("canvas");
  2320. texture._workingContext = texture._workingCanvas.getContext("2d");
  2321. texture._workingCanvas.width = texture._width;
  2322. texture._workingCanvas.height = texture._height;
  2323. }
  2324. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  2325. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  2326. } else {
  2327. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  2328. }
  2329. if (texture.generateMipMaps) {
  2330. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2331. }
  2332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2333. this.resetTextureCache();
  2334. texture.isReady = true;
  2335. } catch (ex) {
  2336. // Something unexpected
  2337. // Let's disable the texture
  2338. texture._isDisabled = true;
  2339. }
  2340. }
  2341. public createRenderTargetTexture(size: any, options): WebGLTexture {
  2342. // old version had a "generateMipMaps" arg instead of options.
  2343. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  2344. // in the same way, generateDepthBuffer is defaulted to true
  2345. var generateMipMaps = false;
  2346. var generateDepthBuffer = true;
  2347. var generateStencilBuffer = false;
  2348. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2349. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2350. if (options !== undefined) {
  2351. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  2352. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2353. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  2354. type = options.type === undefined ? type : options.type;
  2355. if (options.samplingMode !== undefined) {
  2356. samplingMode = options.samplingMode;
  2357. }
  2358. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2359. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2360. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2361. }
  2362. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2363. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2364. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2365. }
  2366. }
  2367. var gl = this._gl;
  2368. var texture = gl.createTexture();
  2369. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2370. var width = size.width || size;
  2371. var height = size.height || size;
  2372. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2373. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2374. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2375. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2376. }
  2377. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2381. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  2382. // Create the framebuffer
  2383. var framebuffer = gl.createFramebuffer();
  2384. this.bindUnboundFramebuffer(framebuffer);
  2385. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  2386. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  2387. if (generateMipMaps) {
  2388. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2389. }
  2390. // Unbind
  2391. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2392. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2393. this.bindUnboundFramebuffer(null);
  2394. texture._framebuffer = framebuffer;
  2395. texture._baseWidth = width;
  2396. texture._baseHeight = height;
  2397. texture._width = width;
  2398. texture._height = height;
  2399. texture.isReady = true;
  2400. texture.samples = 1;
  2401. texture.generateMipMaps = generateMipMaps;
  2402. texture.references = 1;
  2403. texture.samplingMode = samplingMode;
  2404. texture.type = type;
  2405. texture._generateDepthBuffer = generateDepthBuffer;
  2406. texture._generateStencilBuffer = generateStencilBuffer;
  2407. this.resetTextureCache();
  2408. this._loadedTexturesCache.push(texture);
  2409. return texture;
  2410. }
  2411. public createMultipleRenderTarget(size: any, options): WebGLTexture[] {
  2412. var generateMipMaps = false;
  2413. var generateDepthBuffer = true;
  2414. var generateStencilBuffer = false;
  2415. var generateDepthTexture = false;
  2416. var textureCount = 1;
  2417. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  2418. var defaultSamplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2419. var types = [], samplingModes = [];
  2420. if (options !== undefined) {
  2421. generateMipMaps = options.generateMipMaps;
  2422. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2423. generateStencilBuffer = options.generateStencilBuffer;
  2424. generateDepthTexture = options.generateDepthTexture;
  2425. textureCount = options.textureCount || 1;
  2426. if (options.types) {
  2427. types = options.types;
  2428. }
  2429. if (options.samplingModes) {
  2430. samplingModes = options.samplingModes;
  2431. }
  2432. }
  2433. var gl = this._gl;
  2434. // Create the framebuffer
  2435. var framebuffer = gl.createFramebuffer();
  2436. this.bindUnboundFramebuffer(framebuffer);
  2437. var width = size.width || size;
  2438. var height = size.height || size;
  2439. var textures = [];
  2440. var attachments = []
  2441. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  2442. for (var i = 0; i < textureCount; i++) {
  2443. var samplingMode = samplingModes[i] || defaultSamplingMode;
  2444. var type = types[i] || defaultType;
  2445. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  2446. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  2447. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2448. }
  2449. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  2450. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  2451. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  2452. }
  2453. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2454. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  2455. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  2456. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  2457. }
  2458. var texture = gl.createTexture();
  2459. var attachment = gl["COLOR_ATTACHMENT" + i];
  2460. textures.push(texture);
  2461. attachments.push(attachment);
  2462. gl.activeTexture(gl["TEXTURE" + i]);
  2463. gl.bindTexture(gl.TEXTURE_2D, texture);
  2464. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2465. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2466. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2467. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2468. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  2469. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  2470. if (generateMipMaps) {
  2471. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  2472. }
  2473. // Unbind
  2474. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2475. texture._framebuffer = framebuffer;
  2476. texture._depthStencilBuffer = depthStencilBuffer;
  2477. texture._baseWidth = width;
  2478. texture._baseHeight = height;
  2479. texture._width = width;
  2480. texture._height = height;
  2481. texture.isReady = true;
  2482. texture.samples = 1;
  2483. texture.generateMipMaps = generateMipMaps;
  2484. texture.references = 1;
  2485. texture.samplingMode = samplingMode;
  2486. texture.type = type;
  2487. texture._generateDepthBuffer = generateDepthBuffer;
  2488. texture._generateStencilBuffer = generateStencilBuffer;
  2489. this._loadedTexturesCache.push(texture);
  2490. }
  2491. if (generateDepthTexture) {
  2492. // Depth texture
  2493. var depthTexture = gl.createTexture();
  2494. gl.activeTexture(gl.TEXTURE0);
  2495. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  2496. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2497. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2500. gl.texImage2D(
  2501. gl.TEXTURE_2D,
  2502. 0,
  2503. gl.DEPTH_COMPONENT16,
  2504. width,
  2505. height,
  2506. 0,
  2507. gl.DEPTH_COMPONENT,
  2508. gl.UNSIGNED_SHORT,
  2509. null
  2510. );
  2511. gl.framebufferTexture2D(
  2512. gl.FRAMEBUFFER,
  2513. gl.DEPTH_ATTACHMENT,
  2514. gl.TEXTURE_2D,
  2515. depthTexture,
  2516. 0
  2517. );
  2518. depthTexture._framebuffer = framebuffer;
  2519. depthTexture._baseWidth = width;
  2520. depthTexture._baseHeight = height;
  2521. depthTexture._width = width;
  2522. depthTexture._height = height;
  2523. depthTexture.isReady = true;
  2524. depthTexture.samples = 1;
  2525. depthTexture.generateMipMaps = generateMipMaps;
  2526. depthTexture.references = 1;
  2527. depthTexture.samplingMode = gl.NEAREST;
  2528. depthTexture._generateDepthBuffer = generateDepthBuffer;
  2529. depthTexture._generateStencilBuffer = generateStencilBuffer;
  2530. textures.push(depthTexture)
  2531. this._loadedTexturesCache.push(depthTexture);
  2532. }
  2533. gl.drawBuffers(attachments);
  2534. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2535. this.bindUnboundFramebuffer(null);
  2536. this.resetTextureCache();
  2537. return textures;
  2538. }
  2539. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): WebGLRenderbuffer {
  2540. var depthStencilBuffer: WebGLRenderbuffer = null;
  2541. var gl = this._gl;
  2542. // Create the depth/stencil buffer
  2543. if (generateStencilBuffer) {
  2544. depthStencilBuffer = gl.createRenderbuffer();
  2545. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2546. if (samples > 1) {
  2547. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  2548. } else {
  2549. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  2550. }
  2551. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2552. }
  2553. else if (generateDepthBuffer) {
  2554. depthStencilBuffer = gl.createRenderbuffer();
  2555. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2556. if (samples > 1) {
  2557. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  2558. } else {
  2559. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  2560. }
  2561. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  2562. }
  2563. return depthStencilBuffer;
  2564. }
  2565. public updateRenderTargetTextureSampleCount(texture: WebGLTexture, samples: number): number {
  2566. if (this.webGLVersion < 2) {
  2567. return 1;
  2568. }
  2569. if (texture.samples === samples) {
  2570. return samples;
  2571. }
  2572. var gl = this._gl;
  2573. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  2574. // Dispose previous render buffers
  2575. if (texture._depthStencilBuffer) {
  2576. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2577. }
  2578. if (texture._MSAAFramebuffer) {
  2579. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2580. }
  2581. if (texture._MSAARenderBuffer) {
  2582. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2583. }
  2584. if (samples > 1) {
  2585. texture._MSAAFramebuffer = gl.createFramebuffer();
  2586. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  2587. var colorRenderbuffer = gl.createRenderbuffer();
  2588. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  2589. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  2590. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  2591. texture._MSAARenderBuffer = colorRenderbuffer;
  2592. } else {
  2593. this.bindUnboundFramebuffer(texture._framebuffer);
  2594. }
  2595. texture.samples = samples;
  2596. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  2597. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2598. this.bindUnboundFramebuffer(null);
  2599. return samples;
  2600. }
  2601. public _uploadDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, format: number, type: number, data: ArrayBufferView) {
  2602. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  2603. }
  2604. public _uploadCompressedDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, data: ArrayBufferView) {
  2605. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  2606. }
  2607. public createRenderTargetCubeTexture(size: number, options?: any): WebGLTexture {
  2608. var gl = this._gl;
  2609. var texture = gl.createTexture();
  2610. var generateMipMaps = true;
  2611. var generateDepthBuffer = true;
  2612. var generateStencilBuffer = false;
  2613. var samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  2614. if (options !== undefined) {
  2615. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  2616. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  2617. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  2618. if (options.samplingMode !== undefined) {
  2619. samplingMode = options.samplingMode;
  2620. }
  2621. }
  2622. texture.isCube = true;
  2623. texture.references = 1;
  2624. texture.generateMipMaps = generateMipMaps;
  2625. texture.references = 1;
  2626. texture.samples = 1;
  2627. texture.samplingMode = samplingMode;
  2628. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2629. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2630. for (var face = 0; face < 6; face++) {
  2631. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  2632. }
  2633. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  2634. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  2635. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2636. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2637. // Create the framebuffer
  2638. var framebuffer = gl.createFramebuffer();
  2639. this.bindUnboundFramebuffer(framebuffer);
  2640. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  2641. // Mipmaps
  2642. if (texture.generateMipMaps) {
  2643. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2644. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2645. }
  2646. // Unbind
  2647. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2648. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  2649. this.bindUnboundFramebuffer(null);
  2650. texture._framebuffer = framebuffer;
  2651. texture._width = size;
  2652. texture._height = size;
  2653. texture.isReady = true;
  2654. this.resetTextureCache();
  2655. this._loadedTexturesCache.push(texture);
  2656. return texture;
  2657. }
  2658. public createPrefilteredCubeTexture(rootUrl: string, scene: Scene, scale: number, offset: number, onLoad: () => void, onError: () => void = null, format?: number, forcedExtension = null): WebGLTexture {
  2659. var callback = (loadData) => {
  2660. if (this._caps.textureLOD || !loadData) {
  2661. // Do not add extra process if texture lod is supported.
  2662. if (onLoad) {
  2663. onLoad();
  2664. }
  2665. return;
  2666. }
  2667. const mipSlices = 3;
  2668. var gl = this._gl;
  2669. const width = loadData.width;
  2670. if (!width) {
  2671. return;
  2672. }
  2673. const textures: BaseTexture[] = [];
  2674. for (let i = 0; i < mipSlices; i++) {
  2675. //compute LOD from even spacing in smoothness (matching shader calculation)
  2676. let smoothness = i / (mipSlices - 1);
  2677. let roughness = 1 - smoothness;
  2678. let minLODIndex = offset; // roughness = 0
  2679. let maxLODIndex = Scalar.Log2(width) * scale + offset; // roughness = 1
  2680. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  2681. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  2682. var glTextureFromLod = gl.createTexture();
  2683. glTextureFromLod.isCube = true;
  2684. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  2685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  2687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2689. if (loadData.isDDS) {
  2690. var info: Internals.DDSInfo = loadData.info;
  2691. var data: any = loadData.data;
  2692. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  2693. Internals.DDSTools.UploadDDSLevels(this, data, info, true, 6, mipmapIndex);
  2694. }
  2695. else {
  2696. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  2697. }
  2698. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2699. // Wrap in a base texture for easy binding.
  2700. const lodTexture = new BaseTexture(scene);
  2701. lodTexture.isCube = true;
  2702. lodTexture._texture = glTextureFromLod;
  2703. glTextureFromLod.isReady = true;
  2704. textures.push(lodTexture);
  2705. }
  2706. (loadData.texture as WebGLTexture)._lodTextureHigh = textures[2];
  2707. (loadData.texture as WebGLTexture)._lodTextureMid = textures[1];
  2708. (loadData.texture as WebGLTexture)._lodTextureLow = textures[0];
  2709. if (onLoad) {
  2710. onLoad();
  2711. }
  2712. };
  2713. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  2714. }
  2715. public createCubeTexture(rootUrl: string, scene: Scene, files: string[], noMipmap?: boolean, onLoad: (data?: any) => void = null, onError: () => void = null, format?: number, forcedExtension = null): WebGLTexture {
  2716. var gl = this._gl;
  2717. var texture = gl.createTexture();
  2718. texture.isCube = true;
  2719. texture.url = rootUrl;
  2720. texture.references = 1;
  2721. texture.onLoadedCallbacks = [];
  2722. texture.generateMipMaps = !noMipmap;
  2723. var isKTX = false;
  2724. var isDDS = false;
  2725. var lastDot = rootUrl.lastIndexOf('.');
  2726. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  2727. if (this._textureFormatInUse) {
  2728. extension = this._textureFormatInUse;
  2729. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  2730. isKTX = true;
  2731. } else {
  2732. isDDS = (extension === ".dds");
  2733. }
  2734. if (isKTX) {
  2735. Tools.LoadFile(rootUrl, data => {
  2736. var ktx = new Internals.KhronosTextureContainer(data, 6);
  2737. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  2738. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2739. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  2740. ktx.uploadLevels(this._gl, !noMipmap);
  2741. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2742. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2743. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2744. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2745. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2746. this.resetTextureCache();
  2747. texture._width = ktx.pixelWidth;
  2748. texture._height = ktx.pixelHeight;
  2749. texture.isReady = true;
  2750. }, null, null, true, onError);
  2751. } else if (isDDS) {
  2752. Tools.LoadFile(rootUrl, data => {
  2753. var info = Internals.DDSTools.GetDDSInfo(data);
  2754. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  2755. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2756. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  2757. Internals.DDSTools.UploadDDSLevels(this, data, info, loadMipmap, 6);
  2758. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  2759. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2760. }
  2761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  2763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2764. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2765. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2766. this.resetTextureCache();
  2767. texture._width = info.width;
  2768. texture._height = info.height;
  2769. texture.isReady = true;
  2770. texture.type = info.textureType;
  2771. if (onLoad) {
  2772. onLoad({ isDDS: true, width: info.width, info, data, texture });
  2773. }
  2774. }, null, null, true, onError);
  2775. } else {
  2776. cascadeLoad(rootUrl, scene, imgs => {
  2777. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  2778. var height = width;
  2779. this._prepareWorkingCanvas();
  2780. this._workingCanvas.width = width;
  2781. this._workingCanvas.height = height;
  2782. var faces = [
  2783. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  2784. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  2785. ];
  2786. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2787. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2788. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  2789. for (var index = 0; index < faces.length; index++) {
  2790. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  2791. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  2792. }
  2793. if (!noMipmap) {
  2794. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2795. }
  2796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  2797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  2798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2800. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2801. this.resetTextureCache();
  2802. texture._width = width;
  2803. texture._height = height;
  2804. texture.isReady = true;
  2805. texture.onLoadedCallbacks.forEach(callback => {
  2806. callback();
  2807. });
  2808. if (onLoad) {
  2809. onLoad();
  2810. }
  2811. }, files, onError);
  2812. }
  2813. this._loadedTexturesCache.push(texture);
  2814. return texture;
  2815. }
  2816. public updateTextureSize(texture: WebGLTexture, width: number, height: number) {
  2817. texture._width = width;
  2818. texture._height = height;
  2819. texture._size = width * height;
  2820. texture._baseWidth = width;
  2821. texture._baseHeight = height;
  2822. }
  2823. public updateRawCubeTexture(texture: WebGLTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: string = null, level = 0): void {
  2824. var gl = this._gl;
  2825. var textureType = this._getWebGLTextureType(type);
  2826. var internalFormat = this._getInternalFormat(format);
  2827. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  2828. var needConversion = false;
  2829. if (internalFormat === gl.RGB) {
  2830. internalFormat = gl.RGBA;
  2831. needConversion = true;
  2832. }
  2833. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2834. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2835. if (texture._width % 4 !== 0) {
  2836. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  2837. }
  2838. // Data are known to be in +X +Y +Z -X -Y -Z
  2839. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  2840. let faceData = data[faceIndex];
  2841. if (compression) {
  2842. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  2843. } else {
  2844. if (needConversion) {
  2845. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  2846. }
  2847. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  2848. }
  2849. }
  2850. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture._width) && Tools.IsExponentOfTwo(texture._height));
  2851. if (isPot && texture.generateMipMaps && level === 0) {
  2852. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  2853. }
  2854. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2855. this.resetTextureCache();
  2856. texture.isReady = true;
  2857. }
  2858. public createRawCubeTexture(data: ArrayBufferView[], size: number, format: number, type: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: string = null): WebGLTexture {
  2859. var gl = this._gl;
  2860. var texture = gl.createTexture();
  2861. texture.isCube = true;
  2862. texture.references = 1;
  2863. texture.generateMipMaps = generateMipMaps;
  2864. texture.format = format;
  2865. texture.type = type;
  2866. var textureType = this._getWebGLTextureType(type);
  2867. var internalFormat = this._getInternalFormat(format);
  2868. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  2869. var needConversion = false;
  2870. if (internalFormat === gl.RGB) {
  2871. internalFormat = gl.RGBA;
  2872. needConversion = true;
  2873. }
  2874. var width = size;
  2875. var height = width;
  2876. texture._width = width;
  2877. texture._height = height;
  2878. // Double check on POT to generate Mips.
  2879. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture._width) && Tools.IsExponentOfTwo(texture._height));
  2880. if (!isPot) {
  2881. generateMipMaps = false;
  2882. }
  2883. // Upload data if needed. The texture won t be ready until then.
  2884. if (data) {
  2885. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  2886. }
  2887. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  2888. // Filters
  2889. if (data && generateMipMaps) {
  2890. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  2891. }
  2892. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  2893. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2894. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2895. }
  2896. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  2897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  2898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  2899. }
  2900. else {
  2901. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  2902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  2903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  2904. }
  2905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2907. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2908. return texture;
  2909. }
  2910. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  2911. callback: (ArrayBuffer: ArrayBuffer) => ArrayBufferView[],
  2912. mipmmapGenerator: ((faces: ArrayBufferView[]) => ArrayBufferView[][]),
  2913. onLoad: () => void = null,
  2914. onError: () => void = null,
  2915. samplingMode = Texture.TRILINEAR_SAMPLINGMODE,
  2916. invertY = false): WebGLTexture {
  2917. var gl = this._gl;
  2918. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  2919. scene._addPendingData(texture);
  2920. texture.url = url;
  2921. this._loadedTexturesCache.push(texture);
  2922. var onerror = () => {
  2923. scene._removePendingData(texture);
  2924. if (onError) {
  2925. onError();
  2926. }
  2927. };
  2928. var internalCallback = (data) => {
  2929. var width = texture._width;
  2930. var height = texture._height;
  2931. var faceDataArrays = callback(data);
  2932. if (mipmmapGenerator) {
  2933. var textureType = this._getWebGLTextureType(type);
  2934. var internalFormat = this._getInternalFormat(format);
  2935. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  2936. var needConversion = false;
  2937. if (internalFormat === gl.RGB) {
  2938. internalFormat = gl.RGBA;
  2939. needConversion = true;
  2940. }
  2941. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  2942. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  2943. var mipData = mipmmapGenerator(faceDataArrays);
  2944. for (var level = 0; level < mipData.length; level++) {
  2945. var mipSize = width >> level;
  2946. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  2947. let mipFaceData = mipData[level][faceIndex];
  2948. if (needConversion) {
  2949. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  2950. }
  2951. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  2952. }
  2953. }
  2954. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2955. }
  2956. else {
  2957. texture.generateMipMaps = !noMipmap;
  2958. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  2959. }
  2960. texture.isReady = true;
  2961. this.resetTextureCache();
  2962. scene._removePendingData(texture);
  2963. if (onLoad) {
  2964. onLoad();
  2965. }
  2966. };
  2967. Tools.LoadFile(url, data => {
  2968. internalCallback(data);
  2969. }, onerror, scene.database, true);
  2970. return texture;
  2971. };
  2972. private _prepareWebGLTextureContinuation(texture: WebGLTexture, scene: Scene, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  2973. var gl = this._gl;
  2974. if (!gl) {
  2975. return;
  2976. }
  2977. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2980. if (!noMipmap && !isCompressed) {
  2981. gl.generateMipmap(gl.TEXTURE_2D);
  2982. }
  2983. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2984. this.resetTextureCache();
  2985. scene._removePendingData(texture);
  2986. texture.onLoadedCallbacks.forEach(callback => {
  2987. callback();
  2988. });
  2989. texture.onLoadedCallbacks = [];
  2990. }
  2991. private _prepareWebGLTexture(texture: WebGLTexture, scene: Scene, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  2992. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): void {
  2993. var potWidth = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  2994. var potHeight = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  2995. var gl = this._gl;
  2996. if (!gl) {
  2997. return;
  2998. }
  2999. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  3000. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3001. texture._baseWidth = width;
  3002. texture._baseHeight = height;
  3003. texture._width = potWidth;
  3004. texture._height = potHeight;
  3005. texture.isReady = true;
  3006. if (processFunction(potWidth, potHeight, () => {
  3007. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3008. })) {
  3009. // Returning as texture needs extra async steps
  3010. return;
  3011. }
  3012. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3013. }
  3014. private _convertRGBtoRGBATextureData(rgbData: ArrayBufferView, width: number, height: number, textureType: number): ArrayBufferView {
  3015. // Create new RGBA data container.
  3016. var rgbaData: ArrayBufferView;
  3017. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  3018. rgbaData = new Float32Array(width * height * 4);
  3019. }
  3020. else {
  3021. rgbaData = new Uint32Array(width * height * 4);
  3022. }
  3023. // Convert each pixel.
  3024. for (let x = 0; x < width; x++) {
  3025. for (let y = 0; y < height; y++) {
  3026. let index = (y * width + x) * 3;
  3027. let newIndex = (y * width + x) * 4;
  3028. // Map Old Value to new value.
  3029. rgbaData[newIndex + 0] = rgbData[index + 0];
  3030. rgbaData[newIndex + 1] = rgbData[index + 1];
  3031. rgbaData[newIndex + 2] = rgbData[index + 2];
  3032. // Add fully opaque alpha channel.
  3033. rgbaData[newIndex + 3] = 1;
  3034. }
  3035. }
  3036. return rgbaData;
  3037. }
  3038. public _releaseFramebufferObjects(texture: WebGLTexture): void {
  3039. var gl = this._gl;
  3040. if (texture._framebuffer) {
  3041. gl.deleteFramebuffer(texture._framebuffer);
  3042. texture._framebuffer = null;
  3043. }
  3044. if (texture._depthStencilBuffer) {
  3045. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3046. texture._depthStencilBuffer = null;
  3047. }
  3048. if (texture._MSAAFramebuffer) {
  3049. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3050. texture._MSAAFramebuffer = null;
  3051. }
  3052. if (texture._MSAARenderBuffer) {
  3053. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3054. texture._MSAARenderBuffer = null;
  3055. }
  3056. }
  3057. public _releaseTexture(texture: WebGLTexture): void {
  3058. var gl = this._gl;
  3059. this._releaseFramebufferObjects(texture);
  3060. gl.deleteTexture(texture);
  3061. // Unbind channels
  3062. this.unbindAllTextures();
  3063. var index = this._loadedTexturesCache.indexOf(texture);
  3064. if (index !== -1) {
  3065. this._loadedTexturesCache.splice(index, 1);
  3066. }
  3067. // Integrated fixed lod samplers.
  3068. if (texture._lodTextureHigh) {
  3069. texture._lodTextureHigh.dispose();
  3070. }
  3071. if (texture._lodTextureMid) {
  3072. texture._lodTextureMid.dispose();
  3073. }
  3074. if (texture._lodTextureLow) {
  3075. texture._lodTextureLow.dispose();
  3076. }
  3077. }
  3078. private setProgram(program: WebGLProgram): void {
  3079. if (this._currentProgram !== program) {
  3080. this._gl.useProgram(program);
  3081. this._currentProgram = program;
  3082. }
  3083. }
  3084. public bindSamplers(effect: Effect): void {
  3085. this.setProgram(effect.getProgram());
  3086. var samplers = effect.getSamplers();
  3087. for (var index = 0; index < samplers.length; index++) {
  3088. var uniform = effect.getUniform(samplers[index]);
  3089. this._gl.uniform1i(uniform, index);
  3090. }
  3091. this._currentEffect = null;
  3092. }
  3093. private activateTexture(texture: number): void {
  3094. if (this._activeTexture !== texture) {
  3095. this._gl.activeTexture(texture);
  3096. this._activeTexture = texture;
  3097. }
  3098. }
  3099. public _bindTextureDirectly(target: number, texture: WebGLTexture): void {
  3100. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  3101. this._gl.bindTexture(target, texture);
  3102. this._activeTexturesCache[this._activeTexture] = texture;
  3103. }
  3104. }
  3105. public _bindTexture(channel: number, texture: WebGLTexture): void {
  3106. if (channel < 0) {
  3107. return;
  3108. }
  3109. this.activateTexture(this._gl.TEXTURE0 + channel);
  3110. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  3111. }
  3112. public setTextureFromPostProcess(channel: number, postProcess: PostProcess): void {
  3113. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  3114. }
  3115. public unbindAllTextures(): void {
  3116. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  3117. this.activateTexture(this._gl["TEXTURE" + channel]);
  3118. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3119. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3120. }
  3121. }
  3122. public setTexture(channel: number, uniform: WebGLUniformLocation, texture: BaseTexture): void {
  3123. if (channel < 0) {
  3124. return;
  3125. }
  3126. this._gl.uniform1i(uniform, channel);
  3127. this._setTexture(channel, texture);
  3128. }
  3129. private _setTexture(channel: number, texture: BaseTexture): void {
  3130. // Not ready?
  3131. if (!texture) {
  3132. if (this._activeTexturesCache[channel] != null) {
  3133. this.activateTexture(this._gl["TEXTURE" + channel]);
  3134. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3135. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3136. }
  3137. return;
  3138. }
  3139. // Video
  3140. var alreadyActivated = false;
  3141. if ((<VideoTexture>texture).video) {
  3142. this.activateTexture(this._gl["TEXTURE" + channel]);
  3143. alreadyActivated = true;
  3144. (<VideoTexture>texture).update();
  3145. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  3146. texture.delayLoad();
  3147. return;
  3148. }
  3149. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  3150. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  3151. if (this._activeTexturesCache[channel] === internalTexture) {
  3152. return;
  3153. }
  3154. if (!alreadyActivated) {
  3155. this.activateTexture(this._gl["TEXTURE" + channel]);
  3156. }
  3157. if (internalTexture.isCube) {
  3158. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  3159. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3160. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3161. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  3162. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3163. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  3164. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3165. }
  3166. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3167. } else {
  3168. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  3169. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3170. internalTexture._cachedWrapU = texture.wrapU;
  3171. switch (texture.wrapU) {
  3172. case Texture.WRAP_ADDRESSMODE:
  3173. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  3174. break;
  3175. case Texture.CLAMP_ADDRESSMODE:
  3176. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  3177. break;
  3178. case Texture.MIRROR_ADDRESSMODE:
  3179. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  3180. break;
  3181. }
  3182. }
  3183. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3184. internalTexture._cachedWrapV = texture.wrapV;
  3185. switch (texture.wrapV) {
  3186. case Texture.WRAP_ADDRESSMODE:
  3187. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  3188. break;
  3189. case Texture.CLAMP_ADDRESSMODE:
  3190. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  3191. break;
  3192. case Texture.MIRROR_ADDRESSMODE:
  3193. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  3194. break;
  3195. }
  3196. }
  3197. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3198. }
  3199. }
  3200. public setTextureArray(channel: number, uniform: WebGLUniformLocation, textures: BaseTexture[]): void {
  3201. if (channel < 0) {
  3202. return;
  3203. }
  3204. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  3205. this._textureUnits = new Int32Array(textures.length);
  3206. }
  3207. for (let i = 0; i < textures.length; i++) {
  3208. this._textureUnits[i] = channel + i;
  3209. }
  3210. this._gl.uniform1iv(uniform, this._textureUnits);
  3211. for (var index = 0; index < textures.length; index++) {
  3212. this._setTexture(channel + index, textures[index]);
  3213. }
  3214. }
  3215. public _setAnisotropicLevel(key: number, texture: BaseTexture) {
  3216. var internalTexture = texture.getInternalTexture();
  3217. if (!internalTexture) {
  3218. return;
  3219. }
  3220. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3221. var value = texture.anisotropicFilteringLevel;
  3222. if (internalTexture.samplingMode === Texture.NEAREST_SAMPLINGMODE) {
  3223. value = 1;
  3224. }
  3225. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  3226. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  3227. texture._cachedAnisotropicFilteringLevel = value;
  3228. }
  3229. }
  3230. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  3231. var data = new Uint8Array(height * width * 4);
  3232. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  3233. return data;
  3234. }
  3235. /**
  3236. * Add an externaly attached data from its key.
  3237. * This method call will fail and return false, if such key already exists.
  3238. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3239. * @param key the unique key that identifies the data
  3240. * @param data the data object to associate to the key for this Engine instance
  3241. * @return true if no such key were already present and the data was added successfully, false otherwise
  3242. */
  3243. public addExternalData<T>(key: string, data: T): boolean {
  3244. if (!this._externalData) {
  3245. this._externalData = new StringDictionary<Object>();
  3246. }
  3247. return this._externalData.add(key, data);
  3248. }
  3249. /**
  3250. * Get an externaly attached data from its key
  3251. * @param key the unique key that identifies the data
  3252. * @return the associated data, if present (can be null), or undefined if not present
  3253. */
  3254. public getExternalData<T>(key: string): T {
  3255. if (!this._externalData) {
  3256. this._externalData = new StringDictionary<Object>();
  3257. }
  3258. return <T>this._externalData.get(key);
  3259. }
  3260. /**
  3261. * Get an externaly attached data from its key, create it using a factory if it's not already present
  3262. * @param key the unique key that identifies the data
  3263. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3264. * @return the associated data, can be null if the factory returned null.
  3265. */
  3266. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  3267. if (!this._externalData) {
  3268. this._externalData = new StringDictionary<Object>();
  3269. }
  3270. return <T>this._externalData.getOrAddWithFactory(key, factory);
  3271. }
  3272. /**
  3273. * Remove an externaly attached data from the Engine instance
  3274. * @param key the unique key that identifies the data
  3275. * @return true if the data was successfully removed, false if it doesn't exist
  3276. */
  3277. public removeExternalData(key): boolean {
  3278. if (!this._externalData) {
  3279. this._externalData = new StringDictionary<Object>();
  3280. }
  3281. return this._externalData.remove(key);
  3282. }
  3283. public releaseInternalTexture(texture: WebGLTexture): void {
  3284. if (!texture) {
  3285. return;
  3286. }
  3287. texture.references--;
  3288. // Final reference ?
  3289. if (texture.references === 0) {
  3290. var texturesCache = this.getLoadedTexturesCache();
  3291. var index = texturesCache.indexOf(texture);
  3292. if (index > -1) {
  3293. texturesCache.splice(index, 1);
  3294. }
  3295. this._releaseTexture(texture);
  3296. }
  3297. }
  3298. public unbindAllAttributes() {
  3299. if (this._mustWipeVertexAttributes) {
  3300. this._mustWipeVertexAttributes = false;
  3301. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  3302. this._gl.disableVertexAttribArray(i);
  3303. this._vertexAttribArraysEnabled[i] = false;
  3304. this._currentBufferPointers[i].active = false;
  3305. }
  3306. return;
  3307. }
  3308. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  3309. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  3310. continue;
  3311. }
  3312. this._gl.disableVertexAttribArray(i);
  3313. this._vertexAttribArraysEnabled[i] = false;
  3314. this._currentBufferPointers[i].active = false;
  3315. }
  3316. }
  3317. public releaseEffects() {
  3318. for (var name in this._compiledEffects) {
  3319. this._gl.deleteProgram(this._compiledEffects[name]._program);
  3320. }
  3321. this._compiledEffects = {};
  3322. }
  3323. // Dispose
  3324. public dispose(): void {
  3325. this.hideLoadingUI();
  3326. this.stopRenderLoop();
  3327. // Empty texture
  3328. if (this._emptyTexture) {
  3329. this._releaseTexture(this._emptyTexture);
  3330. this._emptyTexture = null;
  3331. }
  3332. if (this._emptyCubeTexture) {
  3333. this._releaseTexture(this._emptyCubeTexture);
  3334. this._emptyCubeTexture = null;
  3335. }
  3336. // Rescale PP
  3337. if (this._rescalePostProcess) {
  3338. this._rescalePostProcess.dispose();
  3339. }
  3340. // Release scenes
  3341. while (this.scenes.length) {
  3342. this.scenes[0].dispose();
  3343. }
  3344. // Release audio engine
  3345. if (Engine.audioEngine) {
  3346. Engine.audioEngine.dispose();
  3347. }
  3348. // Release effects
  3349. this.releaseEffects();
  3350. // Unbind
  3351. this.unbindAllAttributes();
  3352. if (this._dummyFramebuffer) {
  3353. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  3354. }
  3355. this._gl = null;
  3356. //WebVR
  3357. this.disableVR();
  3358. // Events
  3359. window.removeEventListener("blur", this._onBlur);
  3360. window.removeEventListener("focus", this._onFocus);
  3361. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  3362. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  3363. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  3364. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  3365. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  3366. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  3367. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  3368. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  3369. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  3370. // Remove from Instances
  3371. var index = Engine.Instances.indexOf(this);
  3372. if (index >= 0) {
  3373. Engine.Instances.splice(index, 1);
  3374. }
  3375. this._workingCanvas = null;
  3376. this._workingContext = null;
  3377. this._currentBufferPointers = null;
  3378. this._renderingCanvas = null;
  3379. this._currentProgram = null;
  3380. this.onResizeObservable.clear();
  3381. this.onCanvasBlurObservable.clear();
  3382. BABYLON.Effect.ResetCache();
  3383. }
  3384. // Loading screen
  3385. public displayLoadingUI(): void {
  3386. const loadingScreen = this.loadingScreen;
  3387. if (loadingScreen) {
  3388. loadingScreen.displayLoadingUI();
  3389. }
  3390. }
  3391. public hideLoadingUI(): void {
  3392. const loadingScreen = this.loadingScreen;
  3393. if (loadingScreen) {
  3394. loadingScreen.hideLoadingUI();
  3395. }
  3396. }
  3397. public get loadingScreen(): ILoadingScreen {
  3398. if (!this._loadingScreen && DefaultLoadingScreen)
  3399. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  3400. return this._loadingScreen;
  3401. }
  3402. public set loadingScreen(loadingScreen: ILoadingScreen) {
  3403. this._loadingScreen = loadingScreen;
  3404. }
  3405. public set loadingUIText(text: string) {
  3406. this.loadingScreen.loadingUIText = text;
  3407. }
  3408. public set loadingUIBackgroundColor(color: string) {
  3409. this.loadingScreen.loadingUIBackgroundColor = color;
  3410. }
  3411. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3412. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  3413. }
  3414. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3415. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  3416. }
  3417. public getVertexShaderSource(program: WebGLProgram): string {
  3418. var shaders = this._gl.getAttachedShaders(program);
  3419. return this._gl.getShaderSource(shaders[0]);
  3420. }
  3421. public getFragmentShaderSource(program: WebGLProgram): string {
  3422. var shaders = this._gl.getAttachedShaders(program);
  3423. return this._gl.getShaderSource(shaders[1]);
  3424. }
  3425. public getError(): number {
  3426. return this._gl.getError();
  3427. }
  3428. // FPS
  3429. public getFps(): number {
  3430. return this._fps;
  3431. }
  3432. public getDeltaTime(): number {
  3433. return this._deltaTime;
  3434. }
  3435. private _measureFps(): void {
  3436. this._performanceMonitor.sampleFrame();
  3437. this._fps = this._performanceMonitor.averageFPS;
  3438. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  3439. }
  3440. public _readTexturePixels(texture: WebGLTexture, width: number, height: number, faceIndex = -1): ArrayBufferView {
  3441. let gl = this._gl;
  3442. if (!this._dummyFramebuffer) {
  3443. this._dummyFramebuffer = gl.createFramebuffer();
  3444. }
  3445. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  3446. if (faceIndex > -1) {
  3447. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  3448. } else {
  3449. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3450. }
  3451. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  3452. let buffer: ArrayBufferView;
  3453. switch (readType) {
  3454. case gl.UNSIGNED_BYTE:
  3455. buffer = new Uint8Array(4 * width * height);
  3456. readType = gl.UNSIGNED_BYTE;
  3457. break;
  3458. default:
  3459. buffer = new Float32Array(4 * width * height);
  3460. readType = gl.FLOAT;
  3461. break;
  3462. }
  3463. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  3464. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  3465. return buffer;
  3466. }
  3467. private _canRenderToFloatFramebuffer(): boolean {
  3468. if (this._webGLVersion > 1) {
  3469. return this._caps.colorBufferFloat;
  3470. }
  3471. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  3472. }
  3473. private _canRenderToHalfFloatFramebuffer(): boolean {
  3474. if (this._webGLVersion > 1) {
  3475. return this._caps.colorBufferFloat;
  3476. }
  3477. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  3478. }
  3479. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  3480. private _canRenderToFramebuffer(type: number): boolean {
  3481. let gl = this._gl;
  3482. //clear existing errors
  3483. while (gl.getError() !== gl.NO_ERROR) { }
  3484. let successful = true;
  3485. let texture = gl.createTexture();
  3486. gl.bindTexture(gl.TEXTURE_2D, texture);
  3487. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3488. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3489. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3490. let fb = gl.createFramebuffer();
  3491. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  3492. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3493. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  3494. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  3495. successful = successful && (gl.getError() === gl.NO_ERROR);
  3496. //try render by clearing frame buffer's color buffer
  3497. if (successful) {
  3498. gl.clear(gl.COLOR_BUFFER_BIT);
  3499. successful = successful && (gl.getError() === gl.NO_ERROR);
  3500. }
  3501. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  3502. if (successful) {
  3503. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  3504. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3505. let readFormat = gl.RGBA;
  3506. let readType = gl.UNSIGNED_BYTE;
  3507. let buffer = new Uint8Array(4);
  3508. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  3509. successful = successful && (gl.getError() === gl.NO_ERROR);
  3510. }
  3511. //clean up
  3512. gl.deleteTexture(texture);
  3513. gl.deleteFramebuffer(fb);
  3514. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3515. //clear accumulated errors
  3516. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  3517. return successful;
  3518. }
  3519. public _getWebGLTextureType(type: number): number {
  3520. if (type === Engine.TEXTURETYPE_FLOAT) {
  3521. return this._gl.FLOAT;
  3522. }
  3523. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  3524. // Add Half Float Constant.
  3525. return this._gl.HALF_FLOAT_OES;
  3526. }
  3527. return this._gl.UNSIGNED_BYTE;
  3528. };
  3529. public _getRGBABufferInternalSizedFormat(type: number): number {
  3530. if (this._webGLVersion === 1) {
  3531. return this._gl.RGBA;
  3532. }
  3533. if (type === Engine.TEXTURETYPE_FLOAT) {
  3534. return this._gl.RGBA32F;
  3535. }
  3536. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  3537. return this._gl.RGBA16F;
  3538. }
  3539. return this._gl.RGBA;
  3540. };
  3541. // Statics
  3542. public static isSupported(): boolean {
  3543. try {
  3544. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  3545. if (navigator.isCocoonJS) {
  3546. return true;
  3547. }
  3548. var tempcanvas = document.createElement("canvas");
  3549. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  3550. return gl != null && !!window.WebGLRenderingContext;
  3551. } catch (e) {
  3552. return false;
  3553. }
  3554. }
  3555. }
  3556. }