Context.js 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. import Check from "../Core/Check.js";
  2. import clone from "../Core/clone.js";
  3. import Color from "../Core/Color.js";
  4. import ComponentDatatype from "../Core/ComponentDatatype.js";
  5. import createGuid from "../Core/createGuid.js";
  6. import defaultValue from "../Core/defaultValue.js";
  7. import defined from "../Core/defined.js";
  8. import destroyObject from "../Core/destroyObject.js";
  9. import DeveloperError from "../Core/DeveloperError.js";
  10. import Geometry from "../Core/Geometry.js";
  11. import GeometryAttribute from "../Core/GeometryAttribute.js";
  12. import Matrix4 from "../Core/Matrix4.js";
  13. import PixelFormat from "../Core/PixelFormat.js";
  14. import PrimitiveType from "../Core/PrimitiveType.js";
  15. import RuntimeError from "../Core/RuntimeError.js";
  16. import WebGLConstants from "../Core/WebGLConstants.js";
  17. import ViewportQuadVS from "../Shaders/ViewportQuadVS.js";
  18. import BufferUsage from "./BufferUsage.js";
  19. import ClearCommand from "./ClearCommand.js";
  20. import ContextLimits from "./ContextLimits.js";
  21. import CubeMap from "./CubeMap.js";
  22. import DrawCommand from "./DrawCommand.js";
  23. import PassState from "./PassState.js";
  24. import PixelDatatype from "./PixelDatatype.js";
  25. import RenderState from "./RenderState.js";
  26. import ShaderCache from "./ShaderCache.js";
  27. import ShaderProgram from "./ShaderProgram.js";
  28. import Texture from "./Texture.js";
  29. import TextureCache from "./TextureCache.js";
  30. import UniformState from "./UniformState.js";
  31. import VertexArray from "./VertexArray.js";
  32. function errorToString(gl, error) {
  33. var message = "WebGL Error: ";
  34. switch (error) {
  35. case gl.INVALID_ENUM:
  36. message += "INVALID_ENUM";
  37. break;
  38. case gl.INVALID_VALUE:
  39. message += "INVALID_VALUE";
  40. break;
  41. case gl.INVALID_OPERATION:
  42. message += "INVALID_OPERATION";
  43. break;
  44. case gl.OUT_OF_MEMORY:
  45. message += "OUT_OF_MEMORY";
  46. break;
  47. case gl.CONTEXT_LOST_WEBGL:
  48. message += "CONTEXT_LOST_WEBGL lost";
  49. break;
  50. default:
  51. message += "Unknown (" + error + ")";
  52. }
  53. return message;
  54. }
  55. function createErrorMessage(gl, glFunc, glFuncArguments, error) {
  56. var message = errorToString(gl, error) + ": " + glFunc.name + "(";
  57. for (var i = 0; i < glFuncArguments.length; ++i) {
  58. if (i !== 0) {
  59. message += ", ";
  60. }
  61. message += glFuncArguments[i];
  62. }
  63. message += ");";
  64. return message;
  65. }
  66. function throwOnError(gl, glFunc, glFuncArguments) {
  67. var error = gl.getError();
  68. if (error !== gl.NO_ERROR) {
  69. throw new RuntimeError(
  70. createErrorMessage(gl, glFunc, glFuncArguments, error)
  71. );
  72. }
  73. }
  74. function makeGetterSetter(gl, propertyName, logFunction) {
  75. return {
  76. get: function () {
  77. var value = gl[propertyName];
  78. logFunction(gl, "get: " + propertyName, value);
  79. return gl[propertyName];
  80. },
  81. set: function (value) {
  82. gl[propertyName] = value;
  83. logFunction(gl, "set: " + propertyName, value);
  84. },
  85. };
  86. }
  87. function wrapGL(gl, logFunction) {
  88. if (!defined(logFunction)) {
  89. return gl;
  90. }
  91. function wrapFunction(property) {
  92. return function () {
  93. var result = property.apply(gl, arguments);
  94. logFunction(gl, property, arguments);
  95. return result;
  96. };
  97. }
  98. var glWrapper = {};
  99. // JavaScript linters normally demand that a for..in loop must directly contain an if,
  100. // but in our loop below, we actually intend to iterate all properties, including
  101. // those in the prototype.
  102. /*eslint-disable guard-for-in*/
  103. for (var propertyName in gl) {
  104. var property = gl[propertyName];
  105. // wrap any functions we encounter, otherwise just copy the property to the wrapper.
  106. if (property instanceof Function) {
  107. glWrapper[propertyName] = wrapFunction(property);
  108. } else {
  109. Object.defineProperty(
  110. glWrapper,
  111. propertyName,
  112. makeGetterSetter(gl, propertyName, logFunction)
  113. );
  114. }
  115. }
  116. /*eslint-enable guard-for-in*/
  117. return glWrapper;
  118. }
  119. function getExtension(gl, names) {
  120. var length = names.length;
  121. for (var i = 0; i < length; ++i) {
  122. var extension = gl.getExtension(names[i]);
  123. if (extension) {
  124. return extension;
  125. }
  126. }
  127. return undefined;
  128. }
  129. /**
  130. * @private
  131. * @constructor
  132. */
  133. function Context(canvas, options) {
  134. // this check must use typeof, not defined, because defined doesn't work with undeclared variables.
  135. if (typeof WebGLRenderingContext === "undefined") {
  136. throw new RuntimeError(
  137. "The browser does not support WebGL. Visit http://get.webgl.org."
  138. );
  139. }
  140. //>>includeStart('debug', pragmas.debug);
  141. Check.defined("canvas", canvas);
  142. //>>includeEnd('debug');
  143. this._canvas = canvas;
  144. options = clone(options, true);
  145. // Don't use defaultValue.EMPTY_OBJECT here because the options object gets modified in the next line.
  146. options = defaultValue(options, {});
  147. options.allowTextureFilterAnisotropic = defaultValue(
  148. options.allowTextureFilterAnisotropic,
  149. true
  150. );
  151. var webglOptions = defaultValue(options.webgl, {});
  152. // Override select WebGL defaults
  153. webglOptions.alpha = defaultValue(webglOptions.alpha, false); // WebGL default is true
  154. webglOptions.stencil = defaultValue(webglOptions.stencil, true); // WebGL default is false
  155. var requestWebgl2 =
  156. defaultValue(options.requestWebgl2, false) &&
  157. typeof WebGL2RenderingContext !== "undefined";
  158. var webgl2 = false;
  159. var glContext;
  160. var getWebGLStub = options.getWebGLStub;
  161. if (!defined(getWebGLStub)) {
  162. if (requestWebgl2) {
  163. glContext =
  164. canvas.getContext("webgl2", webglOptions) ||
  165. canvas.getContext("experimental-webgl2", webglOptions) ||
  166. undefined;
  167. if (defined(glContext)) {
  168. webgl2 = true;
  169. }
  170. }
  171. if (!defined(glContext)) {
  172. glContext =
  173. canvas.getContext("webgl", webglOptions) ||
  174. canvas.getContext("experimental-webgl", webglOptions) ||
  175. undefined;
  176. }
  177. if (!defined(glContext)) {
  178. throw new RuntimeError(
  179. "The browser supports WebGL, but initialization failed."
  180. );
  181. }
  182. } else {
  183. // Use WebGL stub when requested for unit tests
  184. glContext = getWebGLStub(canvas, webglOptions);
  185. }
  186. this._originalGLContext = glContext;
  187. this._gl = glContext;
  188. this._webgl2 = webgl2;
  189. this._id = createGuid();
  190. // Validation and logging disabled by default for speed.
  191. this.validateFramebuffer = false;
  192. this.validateShaderProgram = false;
  193. this.logShaderCompilation = false;
  194. this._throwOnWebGLError = false;
  195. this._shaderCache = new ShaderCache(this);
  196. this._textureCache = new TextureCache();
  197. var gl = glContext;
  198. this._stencilBits = gl.getParameter(gl.STENCIL_BITS);
  199. ContextLimits._maximumCombinedTextureImageUnits = gl.getParameter(
  200. gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS
  201. ); // min: 8
  202. ContextLimits._maximumCubeMapSize = gl.getParameter(
  203. gl.MAX_CUBE_MAP_TEXTURE_SIZE
  204. ); // min: 16
  205. ContextLimits._maximumFragmentUniformVectors = gl.getParameter(
  206. gl.MAX_FRAGMENT_UNIFORM_VECTORS
  207. ); // min: 16
  208. ContextLimits._maximumTextureImageUnits = gl.getParameter(
  209. gl.MAX_TEXTURE_IMAGE_UNITS
  210. ); // min: 8
  211. ContextLimits._maximumRenderbufferSize = gl.getParameter(
  212. gl.MAX_RENDERBUFFER_SIZE
  213. ); // min: 1
  214. ContextLimits._maximumTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); // min: 64
  215. ContextLimits._maximumVaryingVectors = gl.getParameter(
  216. gl.MAX_VARYING_VECTORS
  217. ); // min: 8
  218. ContextLimits._maximumVertexAttributes = gl.getParameter(
  219. gl.MAX_VERTEX_ATTRIBS
  220. ); // min: 8
  221. ContextLimits._maximumVertexTextureImageUnits = gl.getParameter(
  222. gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS
  223. ); // min: 0
  224. ContextLimits._maximumVertexUniformVectors = gl.getParameter(
  225. gl.MAX_VERTEX_UNIFORM_VECTORS
  226. ); // min: 128
  227. var aliasedLineWidthRange = gl.getParameter(gl.ALIASED_LINE_WIDTH_RANGE); // must include 1
  228. ContextLimits._minimumAliasedLineWidth = aliasedLineWidthRange[0];
  229. ContextLimits._maximumAliasedLineWidth = aliasedLineWidthRange[1];
  230. var aliasedPointSizeRange = gl.getParameter(gl.ALIASED_POINT_SIZE_RANGE); // must include 1
  231. ContextLimits._minimumAliasedPointSize = aliasedPointSizeRange[0];
  232. ContextLimits._maximumAliasedPointSize = aliasedPointSizeRange[1];
  233. var maximumViewportDimensions = gl.getParameter(gl.MAX_VIEWPORT_DIMS);
  234. ContextLimits._maximumViewportWidth = maximumViewportDimensions[0];
  235. ContextLimits._maximumViewportHeight = maximumViewportDimensions[1];
  236. var highpFloat = gl.getShaderPrecisionFormat(
  237. gl.FRAGMENT_SHADER,
  238. gl.HIGH_FLOAT
  239. );
  240. ContextLimits._highpFloatSupported = highpFloat.precision !== 0;
  241. var highpInt = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT);
  242. ContextLimits._highpIntSupported = highpInt.rangeMax !== 0;
  243. this._antialias = gl.getContextAttributes().antialias;
  244. // Query and initialize extensions
  245. this._standardDerivatives = !!getExtension(gl, ["OES_standard_derivatives"]);
  246. this._blendMinmax = !!getExtension(gl, ["EXT_blend_minmax"]);
  247. this._elementIndexUint = !!getExtension(gl, ["OES_element_index_uint"]);
  248. this._depthTexture = !!getExtension(gl, [
  249. "WEBGL_depth_texture",
  250. "WEBKIT_WEBGL_depth_texture",
  251. ]);
  252. this._fragDepth = !!getExtension(gl, ["EXT_frag_depth"]);
  253. this._debugShaders = getExtension(gl, ["WEBGL_debug_shaders"]);
  254. this._textureFloat = !!getExtension(gl, ["OES_texture_float"]);
  255. this._textureHalfFloat = !!getExtension(gl, ["OES_texture_half_float"]);
  256. this._textureFloatLinear = !!getExtension(gl, ["OES_texture_float_linear"]);
  257. this._textureHalfFloatLinear = !!getExtension(gl, [
  258. "OES_texture_half_float_linear",
  259. ]);
  260. this._colorBufferFloat = !!getExtension(gl, [
  261. "EXT_color_buffer_float",
  262. "WEBGL_color_buffer_float",
  263. ]);
  264. this._floatBlend = !!getExtension(gl, ["EXT_float_blend"]);
  265. this._colorBufferHalfFloat = !!getExtension(gl, [
  266. "EXT_color_buffer_half_float",
  267. ]);
  268. this._s3tc = !!getExtension(gl, [
  269. "WEBGL_compressed_texture_s3tc",
  270. "MOZ_WEBGL_compressed_texture_s3tc",
  271. "WEBKIT_WEBGL_compressed_texture_s3tc",
  272. ]);
  273. this._pvrtc = !!getExtension(gl, [
  274. "WEBGL_compressed_texture_pvrtc",
  275. "WEBKIT_WEBGL_compressed_texture_pvrtc",
  276. ]);
  277. this._etc1 = !!getExtension(gl, ["WEBGL_compressed_texture_etc1"]);
  278. var textureFilterAnisotropic = options.allowTextureFilterAnisotropic
  279. ? getExtension(gl, [
  280. "EXT_texture_filter_anisotropic",
  281. "WEBKIT_EXT_texture_filter_anisotropic",
  282. ])
  283. : undefined;
  284. this._textureFilterAnisotropic = textureFilterAnisotropic;
  285. ContextLimits._maximumTextureFilterAnisotropy = defined(
  286. textureFilterAnisotropic
  287. )
  288. ? gl.getParameter(textureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)
  289. : 1.0;
  290. var glCreateVertexArray;
  291. var glBindVertexArray;
  292. var glDeleteVertexArray;
  293. var glDrawElementsInstanced;
  294. var glDrawArraysInstanced;
  295. var glVertexAttribDivisor;
  296. var glDrawBuffers;
  297. var vertexArrayObject;
  298. var instancedArrays;
  299. var drawBuffers;
  300. if (webgl2) {
  301. var that = this;
  302. glCreateVertexArray = function () {
  303. return that._gl.createVertexArray();
  304. };
  305. glBindVertexArray = function (vao) {
  306. that._gl.bindVertexArray(vao);
  307. };
  308. glDeleteVertexArray = function (vao) {
  309. that._gl.deleteVertexArray(vao);
  310. };
  311. glDrawElementsInstanced = function (
  312. mode,
  313. count,
  314. type,
  315. offset,
  316. instanceCount
  317. ) {
  318. gl.drawElementsInstanced(mode, count, type, offset, instanceCount);
  319. };
  320. glDrawArraysInstanced = function (mode, first, count, instanceCount) {
  321. gl.drawArraysInstanced(mode, first, count, instanceCount);
  322. };
  323. glVertexAttribDivisor = function (index, divisor) {
  324. gl.vertexAttribDivisor(index, divisor);
  325. };
  326. glDrawBuffers = function (buffers) {
  327. gl.drawBuffers(buffers);
  328. };
  329. } else {
  330. vertexArrayObject = getExtension(gl, ["OES_vertex_array_object"]);
  331. if (defined(vertexArrayObject)) {
  332. glCreateVertexArray = function () {
  333. return vertexArrayObject.createVertexArrayOES();
  334. };
  335. glBindVertexArray = function (vertexArray) {
  336. vertexArrayObject.bindVertexArrayOES(vertexArray);
  337. };
  338. glDeleteVertexArray = function (vertexArray) {
  339. vertexArrayObject.deleteVertexArrayOES(vertexArray);
  340. };
  341. }
  342. instancedArrays = getExtension(gl, ["ANGLE_instanced_arrays"]);
  343. if (defined(instancedArrays)) {
  344. glDrawElementsInstanced = function (
  345. mode,
  346. count,
  347. type,
  348. offset,
  349. instanceCount
  350. ) {
  351. instancedArrays.drawElementsInstancedANGLE(
  352. mode,
  353. count,
  354. type,
  355. offset,
  356. instanceCount
  357. );
  358. };
  359. glDrawArraysInstanced = function (mode, first, count, instanceCount) {
  360. instancedArrays.drawArraysInstancedANGLE(
  361. mode,
  362. first,
  363. count,
  364. instanceCount
  365. );
  366. };
  367. glVertexAttribDivisor = function (index, divisor) {
  368. instancedArrays.vertexAttribDivisorANGLE(index, divisor);
  369. };
  370. }
  371. drawBuffers = getExtension(gl, ["WEBGL_draw_buffers"]);
  372. if (defined(drawBuffers)) {
  373. glDrawBuffers = function (buffers) {
  374. drawBuffers.drawBuffersWEBGL(buffers);
  375. };
  376. }
  377. }
  378. this.glCreateVertexArray = glCreateVertexArray;
  379. this.glBindVertexArray = glBindVertexArray;
  380. this.glDeleteVertexArray = glDeleteVertexArray;
  381. this.glDrawElementsInstanced = glDrawElementsInstanced;
  382. this.glDrawArraysInstanced = glDrawArraysInstanced;
  383. this.glVertexAttribDivisor = glVertexAttribDivisor;
  384. this.glDrawBuffers = glDrawBuffers;
  385. this._vertexArrayObject = !!vertexArrayObject;
  386. this._instancedArrays = !!instancedArrays;
  387. this._drawBuffers = !!drawBuffers;
  388. ContextLimits._maximumDrawBuffers = this.drawBuffers
  389. ? gl.getParameter(WebGLConstants.MAX_DRAW_BUFFERS)
  390. : 1;
  391. ContextLimits._maximumColorAttachments = this.drawBuffers
  392. ? gl.getParameter(WebGLConstants.MAX_COLOR_ATTACHMENTS)
  393. : 1;
  394. this._clearColor = new Color(0.0, 0.0, 0.0, 0.0);
  395. this._clearDepth = 1.0;
  396. this._clearStencil = 0;
  397. var us = new UniformState();
  398. var ps = new PassState(this);
  399. var rs = RenderState.fromCache();
  400. this._defaultPassState = ps;
  401. this._defaultRenderState = rs;
  402. this._defaultTexture = undefined;
  403. this._defaultCubeMap = undefined;
  404. this._us = us;
  405. this._currentRenderState = rs;
  406. this._currentPassState = ps;
  407. this._currentFramebuffer = undefined;
  408. this._maxFrameTextureUnitIndex = 0;
  409. // Vertex attribute divisor state cache. Workaround for ANGLE (also look at VertexArray.setVertexAttribDivisor)
  410. this._vertexAttribDivisors = [];
  411. this._previousDrawInstanced = false;
  412. for (var i = 0; i < ContextLimits._maximumVertexAttributes; i++) {
  413. this._vertexAttribDivisors.push(0);
  414. }
  415. this._pickObjects = {};
  416. this._nextPickColor = new Uint32Array(1);
  417. /**
  418. * @example
  419. * {
  420. * webgl : {
  421. * alpha : false,
  422. * depth : true,
  423. * stencil : false,
  424. * antialias : true,
  425. * premultipliedAlpha : true,
  426. * preserveDrawingBuffer : false,
  427. * failIfMajorPerformanceCaveat : true
  428. * },
  429. * allowTextureFilterAnisotropic : true
  430. * }
  431. */
  432. this.options = options;
  433. /**
  434. * A cache of objects tied to this context. Just before the Context is destroyed,
  435. * <code>destroy</code> will be invoked on each object in this object literal that has
  436. * such a method. This is useful for caching any objects that might otherwise
  437. * be stored globally, except they're tied to a particular context, and to manage
  438. * their lifetime.
  439. *
  440. * @type {Object}
  441. */
  442. this.cache = {};
  443. RenderState.apply(gl, rs, ps);
  444. }
  445. var defaultFramebufferMarker = {};
  446. Object.defineProperties(Context.prototype, {
  447. id: {
  448. get: function () {
  449. return this._id;
  450. },
  451. },
  452. webgl2: {
  453. get: function () {
  454. return this._webgl2;
  455. },
  456. },
  457. canvas: {
  458. get: function () {
  459. return this._canvas;
  460. },
  461. },
  462. shaderCache: {
  463. get: function () {
  464. return this._shaderCache;
  465. },
  466. },
  467. textureCache: {
  468. get: function () {
  469. return this._textureCache;
  470. },
  471. },
  472. uniformState: {
  473. get: function () {
  474. return this._us;
  475. },
  476. },
  477. /**
  478. * The number of stencil bits per pixel in the default bound framebuffer. The minimum is eight bits.
  479. * @memberof Context.prototype
  480. * @type {Number}
  481. * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>STENCIL_BITS</code>.
  482. */
  483. stencilBits: {
  484. get: function () {
  485. return this._stencilBits;
  486. },
  487. },
  488. /**
  489. * <code>true</code> if the WebGL context supports stencil buffers.
  490. * Stencil buffers are not supported by all systems.
  491. * @memberof Context.prototype
  492. * @type {Boolean}
  493. */
  494. stencilBuffer: {
  495. get: function () {
  496. return this._stencilBits >= 8;
  497. },
  498. },
  499. /**
  500. * <code>true</code> if the WebGL context supports antialiasing. By default
  501. * antialiasing is requested, but it is not supported by all systems.
  502. * @memberof Context.prototype
  503. * @type {Boolean}
  504. */
  505. antialias: {
  506. get: function () {
  507. return this._antialias;
  508. },
  509. },
  510. /**
  511. * <code>true</code> if the OES_standard_derivatives extension is supported. This
  512. * extension provides access to <code>dFdx</code>, <code>dFdy</code>, and <code>fwidth</code>
  513. * functions from GLSL. A shader using these functions still needs to explicitly enable the
  514. * extension with <code>#extension GL_OES_standard_derivatives : enable</code>.
  515. * @memberof Context.prototype
  516. * @type {Boolean}
  517. * @see {@link http://www.khronos.org/registry/gles/extensions/OES/OES_standard_derivatives.txt|OES_standard_derivatives}
  518. */
  519. standardDerivatives: {
  520. get: function () {
  521. return this._standardDerivatives || this._webgl2;
  522. },
  523. },
  524. /**
  525. * <code>true</code> if the EXT_float_blend extension is supported. This
  526. * extension enables blending with 32-bit float values.
  527. * @memberof Context.prototype
  528. * @type {Boolean}
  529. * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_float_blend/}
  530. */
  531. floatBlend: {
  532. get: function () {
  533. return this._floatBlend;
  534. },
  535. },
  536. /**
  537. * <code>true</code> if the EXT_blend_minmax extension is supported. This
  538. * extension extends blending capabilities by adding two new blend equations:
  539. * the minimum or maximum color components of the source and destination colors.
  540. * @memberof Context.prototype
  541. * @type {Boolean}
  542. * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_blend_minmax/}
  543. */
  544. blendMinmax: {
  545. get: function () {
  546. return this._blendMinmax || this._webgl2;
  547. },
  548. },
  549. /**
  550. * <code>true</code> if the OES_element_index_uint extension is supported. This
  551. * extension allows the use of unsigned int indices, which can improve performance by
  552. * eliminating batch breaking caused by unsigned short indices.
  553. * @memberof Context.prototype
  554. * @type {Boolean}
  555. * @see {@link http://www.khronos.org/registry/webgl/extensions/OES_element_index_uint/|OES_element_index_uint}
  556. */
  557. elementIndexUint: {
  558. get: function () {
  559. return this._elementIndexUint || this._webgl2;
  560. },
  561. },
  562. /**
  563. * <code>true</code> if WEBGL_depth_texture is supported. This extension provides
  564. * access to depth textures that, for example, can be attached to framebuffers for shadow mapping.
  565. * @memberof Context.prototype
  566. * @type {Boolean}
  567. * @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/|WEBGL_depth_texture}
  568. */
  569. depthTexture: {
  570. get: function () {
  571. return this._depthTexture || this._webgl2;
  572. },
  573. },
  574. /**
  575. * <code>true</code> if OES_texture_float is supported. This extension provides
  576. * access to floating point textures that, for example, can be attached to framebuffers for high dynamic range.
  577. * @memberof Context.prototype
  578. * @type {Boolean}
  579. * @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_float/}
  580. */
  581. floatingPointTexture: {
  582. get: function () {
  583. return this._webgl2 || this._textureFloat;
  584. },
  585. },
  586. /**
  587. * <code>true</code> if OES_texture_half_float is supported. This extension provides
  588. * access to floating point textures that, for example, can be attached to framebuffers for high dynamic range.
  589. * @memberof Context.prototype
  590. * @type {Boolean}
  591. * @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_float/}
  592. */
  593. halfFloatingPointTexture: {
  594. get: function () {
  595. return this._webgl2 || this._textureHalfFloat;
  596. },
  597. },
  598. /**
  599. * <code>true</code> if OES_texture_float_linear is supported. This extension provides
  600. * access to linear sampling methods for minification and magnification filters of floating-point textures.
  601. * @memberof Context.prototype
  602. * @type {Boolean}
  603. * @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_float_linear/}
  604. */
  605. textureFloatLinear: {
  606. get: function () {
  607. return this._textureFloatLinear;
  608. },
  609. },
  610. /**
  611. * <code>true</code> if OES_texture_half_float_linear is supported. This extension provides
  612. * access to linear sampling methods for minification and magnification filters of half floating-point textures.
  613. * @memberof Context.prototype
  614. * @type {Boolean}
  615. * @see {@link https://www.khronos.org/registry/webgl/extensions/OES_texture_half_float_linear/}
  616. */
  617. textureHalfFloatLinear: {
  618. get: function () {
  619. return (
  620. (this._webgl2 && this._textureFloatLinear) ||
  621. (!this._webgl2 && this._textureHalfFloatLinear)
  622. );
  623. },
  624. },
  625. /**
  626. * <code>true</code> if EXT_texture_filter_anisotropic is supported. This extension provides
  627. * access to anisotropic filtering for textured surfaces at an oblique angle from the viewer.
  628. * @memberof Context.prototype
  629. * @type {Boolean}
  630. * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_texture_filter_anisotropic/}
  631. */
  632. textureFilterAnisotropic: {
  633. get: function () {
  634. return !!this._textureFilterAnisotropic;
  635. },
  636. },
  637. /**
  638. * <code>true</code> if WEBGL_texture_compression_s3tc is supported. This extension provides
  639. * access to DXT compressed textures.
  640. * @memberof Context.prototype
  641. * @type {Boolean}
  642. * @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/}
  643. */
  644. s3tc: {
  645. get: function () {
  646. return this._s3tc;
  647. },
  648. },
  649. /**
  650. * <code>true</code> if WEBGL_texture_compression_pvrtc is supported. This extension provides
  651. * access to PVR compressed textures.
  652. * @memberof Context.prototype
  653. * @type {Boolean}
  654. * @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/}
  655. */
  656. pvrtc: {
  657. get: function () {
  658. return this._pvrtc;
  659. },
  660. },
  661. /**
  662. * <code>true</code> if WEBGL_texture_compression_etc1 is supported. This extension provides
  663. * access to ETC1 compressed textures.
  664. * @memberof Context.prototype
  665. * @type {Boolean}
  666. * @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc1/}
  667. */
  668. etc1: {
  669. get: function () {
  670. return this._etc1;
  671. },
  672. },
  673. /**
  674. * <code>true</code> if the OES_vertex_array_object extension is supported. This
  675. * extension can improve performance by reducing the overhead of switching vertex arrays.
  676. * When enabled, this extension is automatically used by {@link VertexArray}.
  677. * @memberof Context.prototype
  678. * @type {Boolean}
  679. * @see {@link http://www.khronos.org/registry/webgl/extensions/OES_vertex_array_object/|OES_vertex_array_object}
  680. */
  681. vertexArrayObject: {
  682. get: function () {
  683. return this._vertexArrayObject || this._webgl2;
  684. },
  685. },
  686. /**
  687. * <code>true</code> if the EXT_frag_depth extension is supported. This
  688. * extension provides access to the <code>gl_FragDepthEXT</code> built-in output variable
  689. * from GLSL fragment shaders. A shader using these functions still needs to explicitly enable the
  690. * extension with <code>#extension GL_EXT_frag_depth : enable</code>.
  691. * @memberof Context.prototype
  692. * @type {Boolean}
  693. * @see {@link http://www.khronos.org/registry/webgl/extensions/EXT_frag_depth/|EXT_frag_depth}
  694. */
  695. fragmentDepth: {
  696. get: function () {
  697. return this._fragDepth || this._webgl2;
  698. },
  699. },
  700. /**
  701. * <code>true</code> if the ANGLE_instanced_arrays extension is supported. This
  702. * extension provides access to instanced rendering.
  703. * @memberof Context.prototype
  704. * @type {Boolean}
  705. * @see {@link https://www.khronos.org/registry/webgl/extensions/ANGLE_instanced_arrays}
  706. */
  707. instancedArrays: {
  708. get: function () {
  709. return this._instancedArrays || this._webgl2;
  710. },
  711. },
  712. /**
  713. * <code>true</code> if the EXT_color_buffer_float extension is supported. This
  714. * extension makes the gl.RGBA32F format color renderable.
  715. * @memberof Context.prototype
  716. * @type {Boolean}
  717. * @see {@link https://www.khronos.org/registry/webgl/extensions/WEBGL_color_buffer_float/}
  718. * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_float/}
  719. */
  720. colorBufferFloat: {
  721. get: function () {
  722. return this._colorBufferFloat;
  723. },
  724. },
  725. /**
  726. * <code>true</code> if the EXT_color_buffer_half_float extension is supported. This
  727. * extension makes the format gl.RGBA16F format color renderable.
  728. * @memberof Context.prototype
  729. * @type {Boolean}
  730. * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_half_float/}
  731. * @see {@link https://www.khronos.org/registry/webgl/extensions/EXT_color_buffer_float/}
  732. */
  733. colorBufferHalfFloat: {
  734. get: function () {
  735. return (
  736. (this._webgl2 && this._colorBufferFloat) ||
  737. (!this._webgl2 && this._colorBufferHalfFloat)
  738. );
  739. },
  740. },
  741. /**
  742. * <code>true</code> if the WEBGL_draw_buffers extension is supported. This
  743. * extensions provides support for multiple render targets. The framebuffer object can have mutiple
  744. * color attachments and the GLSL fragment shader can write to the built-in output array <code>gl_FragData</code>.
  745. * A shader using this feature needs to explicitly enable the extension with
  746. * <code>#extension GL_EXT_draw_buffers : enable</code>.
  747. * @memberof Context.prototype
  748. * @type {Boolean}
  749. * @see {@link http://www.khronos.org/registry/webgl/extensions/WEBGL_draw_buffers/|WEBGL_draw_buffers}
  750. */
  751. drawBuffers: {
  752. get: function () {
  753. return this._drawBuffers || this._webgl2;
  754. },
  755. },
  756. debugShaders: {
  757. get: function () {
  758. return this._debugShaders;
  759. },
  760. },
  761. throwOnWebGLError: {
  762. get: function () {
  763. return this._throwOnWebGLError;
  764. },
  765. set: function (value) {
  766. this._throwOnWebGLError = value;
  767. this._gl = wrapGL(
  768. this._originalGLContext,
  769. value ? throwOnError : undefined
  770. );
  771. },
  772. },
  773. /**
  774. * A 1x1 RGBA texture initialized to [255, 255, 255, 255]. This can
  775. * be used as a placeholder texture while other textures are downloaded.
  776. * @memberof Context.prototype
  777. * @type {Texture}
  778. */
  779. defaultTexture: {
  780. get: function () {
  781. if (this._defaultTexture === undefined) {
  782. this._defaultTexture = new Texture({
  783. context: this,
  784. source: {
  785. width: 1,
  786. height: 1,
  787. arrayBufferView: new Uint8Array([255, 255, 255, 255]),
  788. },
  789. flipY: false,
  790. });
  791. }
  792. return this._defaultTexture;
  793. },
  794. },
  795. /**
  796. * A cube map, where each face is a 1x1 RGBA texture initialized to
  797. * [255, 255, 255, 255]. This can be used as a placeholder cube map while
  798. * other cube maps are downloaded.
  799. * @memberof Context.prototype
  800. * @type {CubeMap}
  801. */
  802. defaultCubeMap: {
  803. get: function () {
  804. if (this._defaultCubeMap === undefined) {
  805. var face = {
  806. width: 1,
  807. height: 1,
  808. arrayBufferView: new Uint8Array([255, 255, 255, 255]),
  809. };
  810. this._defaultCubeMap = new CubeMap({
  811. context: this,
  812. source: {
  813. positiveX: face,
  814. negativeX: face,
  815. positiveY: face,
  816. negativeY: face,
  817. positiveZ: face,
  818. negativeZ: face,
  819. },
  820. flipY: false,
  821. });
  822. }
  823. return this._defaultCubeMap;
  824. },
  825. },
  826. /**
  827. * The drawingBufferHeight of the underlying GL context.
  828. * @memberof Context.prototype
  829. * @type {Number}
  830. * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight}
  831. */
  832. drawingBufferHeight: {
  833. get: function () {
  834. return this._gl.drawingBufferHeight;
  835. },
  836. },
  837. /**
  838. * The drawingBufferWidth of the underlying GL context.
  839. * @memberof Context.prototype
  840. * @type {Number}
  841. * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferWidth|drawingBufferWidth}
  842. */
  843. drawingBufferWidth: {
  844. get: function () {
  845. return this._gl.drawingBufferWidth;
  846. },
  847. },
  848. /**
  849. * Gets an object representing the currently bound framebuffer. While this instance is not an actual
  850. * {@link Framebuffer}, it is used to represent the default framebuffer in calls to
  851. * {@link Texture.fromFramebuffer}.
  852. * @memberof Context.prototype
  853. * @type {Object}
  854. */
  855. defaultFramebuffer: {
  856. get: function () {
  857. return defaultFramebufferMarker;
  858. },
  859. },
  860. });
  861. /**
  862. * Validates a framebuffer.
  863. * Available in debug builds only.
  864. * @private
  865. */
  866. function validateFramebuffer(context) {
  867. //>>includeStart('debug', pragmas.debug);
  868. if (context.validateFramebuffer) {
  869. var gl = context._gl;
  870. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  871. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  872. var message;
  873. switch (status) {
  874. case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
  875. message =
  876. "Framebuffer is not complete. Incomplete attachment: at least one attachment point with a renderbuffer or texture attached has its attached object no longer in existence or has an attached image with a width or height of zero, or the color attachment point has a non-color-renderable image attached, or the depth attachment point has a non-depth-renderable image attached, or the stencil attachment point has a non-stencil-renderable image attached. Color-renderable formats include GL_RGBA4, GL_RGB5_A1, and GL_RGB565. GL_DEPTH_COMPONENT16 is the only depth-renderable format. GL_STENCIL_INDEX8 is the only stencil-renderable format.";
  877. break;
  878. case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
  879. message =
  880. "Framebuffer is not complete. Incomplete dimensions: not all attached images have the same width and height.";
  881. break;
  882. case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
  883. message =
  884. "Framebuffer is not complete. Missing attachment: no images are attached to the framebuffer.";
  885. break;
  886. case gl.FRAMEBUFFER_UNSUPPORTED:
  887. message =
  888. "Framebuffer is not complete. Unsupported: the combination of internal formats of the attached images violates an implementation-dependent set of restrictions.";
  889. break;
  890. }
  891. throw new DeveloperError(message);
  892. }
  893. }
  894. //>>includeEnd('debug');
  895. }
  896. function applyRenderState(context, renderState, passState, clear) {
  897. var previousRenderState = context._currentRenderState;
  898. var previousPassState = context._currentPassState;
  899. context._currentRenderState = renderState;
  900. context._currentPassState = passState;
  901. RenderState.partialApply(
  902. context._gl,
  903. previousRenderState,
  904. renderState,
  905. previousPassState,
  906. passState,
  907. clear
  908. );
  909. }
  910. var scratchBackBufferArray;
  911. // this check must use typeof, not defined, because defined doesn't work with undeclared variables.
  912. if (typeof WebGLRenderingContext !== "undefined") {
  913. scratchBackBufferArray = [WebGLConstants.BACK];
  914. }
  915. function bindFramebuffer(context, framebuffer) {
  916. if (framebuffer !== context._currentFramebuffer) {
  917. context._currentFramebuffer = framebuffer;
  918. var buffers = scratchBackBufferArray;
  919. if (defined(framebuffer)) {
  920. framebuffer._bind();
  921. validateFramebuffer(context);
  922. // TODO: Need a way for a command to give what draw buffers are active.
  923. buffers = framebuffer._getActiveColorAttachments();
  924. } else {
  925. var gl = context._gl;
  926. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  927. }
  928. if (context.drawBuffers) {
  929. context.glDrawBuffers(buffers);
  930. }
  931. }
  932. }
  933. var defaultClearCommand = new ClearCommand();
  934. Context.prototype.clear = function (clearCommand, passState) {
  935. clearCommand = defaultValue(clearCommand, defaultClearCommand);
  936. passState = defaultValue(passState, this._defaultPassState);
  937. var gl = this._gl;
  938. var bitmask = 0;
  939. var c = clearCommand.color;
  940. var d = clearCommand.depth;
  941. var s = clearCommand.stencil;
  942. if (defined(c)) {
  943. if (!Color.equals(this._clearColor, c)) {
  944. Color.clone(c, this._clearColor);
  945. gl.clearColor(c.red, c.green, c.blue, c.alpha);
  946. }
  947. bitmask |= gl.COLOR_BUFFER_BIT;
  948. }
  949. if (defined(d)) {
  950. if (d !== this._clearDepth) {
  951. this._clearDepth = d;
  952. gl.clearDepth(d);
  953. }
  954. bitmask |= gl.DEPTH_BUFFER_BIT;
  955. }
  956. if (defined(s)) {
  957. if (s !== this._clearStencil) {
  958. this._clearStencil = s;
  959. gl.clearStencil(s);
  960. }
  961. bitmask |= gl.STENCIL_BUFFER_BIT;
  962. }
  963. var rs = defaultValue(clearCommand.renderState, this._defaultRenderState);
  964. applyRenderState(this, rs, passState, true);
  965. // The command's framebuffer takes presidence over the pass' framebuffer, e.g., for off-screen rendering.
  966. var framebuffer = defaultValue(
  967. clearCommand.framebuffer,
  968. passState.framebuffer
  969. );
  970. bindFramebuffer(this, framebuffer);
  971. gl.clear(bitmask);
  972. };
  973. function beginDraw(
  974. context,
  975. framebuffer,
  976. passState,
  977. shaderProgram,
  978. renderState
  979. ) {
  980. //>>includeStart('debug', pragmas.debug);
  981. if (defined(framebuffer) && renderState.depthTest) {
  982. if (renderState.depthTest.enabled && !framebuffer.hasDepthAttachment) {
  983. throw new DeveloperError(
  984. "The depth test can not be enabled (drawCommand.renderState.depthTest.enabled) because the framebuffer (drawCommand.framebuffer) does not have a depth or depth-stencil renderbuffer."
  985. );
  986. }
  987. }
  988. //>>includeEnd('debug');
  989. bindFramebuffer(context, framebuffer);
  990. applyRenderState(context, renderState, passState, false);
  991. shaderProgram._bind();
  992. context._maxFrameTextureUnitIndex = Math.max(
  993. context._maxFrameTextureUnitIndex,
  994. shaderProgram.maximumTextureUnitIndex
  995. );
  996. }
  997. function continueDraw(context, drawCommand, shaderProgram, uniformMap) {
  998. var primitiveType = drawCommand._primitiveType;
  999. var va = drawCommand._vertexArray;
  1000. var offset = drawCommand._offset;
  1001. var count = drawCommand._count;
  1002. var instanceCount = drawCommand.instanceCount;
  1003. //>>includeStart('debug', pragmas.debug);
  1004. if (!PrimitiveType.validate(primitiveType)) {
  1005. throw new DeveloperError(
  1006. "drawCommand.primitiveType is required and must be valid."
  1007. );
  1008. }
  1009. Check.defined("drawCommand.vertexArray", va);
  1010. Check.typeOf.number.greaterThanOrEquals("drawCommand.offset", offset, 0);
  1011. if (defined(count)) {
  1012. Check.typeOf.number.greaterThanOrEquals("drawCommand.count", count, 0);
  1013. }
  1014. Check.typeOf.number.greaterThanOrEquals(
  1015. "drawCommand.instanceCount",
  1016. instanceCount,
  1017. 0
  1018. );
  1019. if (instanceCount > 0 && !context.instancedArrays) {
  1020. throw new DeveloperError("Instanced arrays extension is not supported");
  1021. }
  1022. //>>includeEnd('debug');
  1023. context._us.model = defaultValue(drawCommand._modelMatrix, Matrix4.IDENTITY);
  1024. shaderProgram._setUniforms(
  1025. uniformMap,
  1026. context._us,
  1027. context.validateShaderProgram
  1028. );
  1029. va._bind();
  1030. var indexBuffer = va.indexBuffer;
  1031. if (defined(indexBuffer)) {
  1032. offset = offset * indexBuffer.bytesPerIndex; // offset in vertices to offset in bytes
  1033. count = defaultValue(count, indexBuffer.numberOfIndices);
  1034. if (instanceCount === 0) {
  1035. context._gl.drawElements(
  1036. primitiveType,
  1037. count,
  1038. indexBuffer.indexDatatype,
  1039. offset
  1040. );
  1041. } else {
  1042. context.glDrawElementsInstanced(
  1043. primitiveType,
  1044. count,
  1045. indexBuffer.indexDatatype,
  1046. offset,
  1047. instanceCount
  1048. );
  1049. }
  1050. } else {
  1051. count = defaultValue(count, va.numberOfVertices);
  1052. if (instanceCount === 0) {
  1053. context._gl.drawArrays(primitiveType, offset, count);
  1054. } else {
  1055. context.glDrawArraysInstanced(
  1056. primitiveType,
  1057. offset,
  1058. count,
  1059. instanceCount
  1060. );
  1061. }
  1062. }
  1063. va._unBind();
  1064. }
  1065. Context.prototype.draw = function (
  1066. drawCommand,
  1067. passState,
  1068. shaderProgram,
  1069. uniformMap
  1070. ) {
  1071. //>>includeStart('debug', pragmas.debug);
  1072. Check.defined("drawCommand", drawCommand);
  1073. Check.defined("drawCommand.shaderProgram", drawCommand._shaderProgram);
  1074. //>>includeEnd('debug');
  1075. passState = defaultValue(passState, this._defaultPassState);
  1076. // The command's framebuffer takes presidence over the pass' framebuffer, e.g., for off-screen rendering.
  1077. var framebuffer = defaultValue(
  1078. drawCommand._framebuffer,
  1079. passState.framebuffer
  1080. );
  1081. var renderState = defaultValue(
  1082. drawCommand._renderState,
  1083. this._defaultRenderState
  1084. );
  1085. shaderProgram = defaultValue(shaderProgram, drawCommand._shaderProgram);
  1086. uniformMap = defaultValue(uniformMap, drawCommand._uniformMap);
  1087. beginDraw(this, framebuffer, passState, shaderProgram, renderState);
  1088. continueDraw(this, drawCommand, shaderProgram, uniformMap);
  1089. };
  1090. Context.prototype.endFrame = function () {
  1091. var gl = this._gl;
  1092. gl.useProgram(null);
  1093. this._currentFramebuffer = undefined;
  1094. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  1095. var buffers = scratchBackBufferArray;
  1096. if (this.drawBuffers) {
  1097. this.glDrawBuffers(buffers);
  1098. }
  1099. var length = this._maxFrameTextureUnitIndex;
  1100. this._maxFrameTextureUnitIndex = 0;
  1101. for (var i = 0; i < length; ++i) {
  1102. gl.activeTexture(gl.TEXTURE0 + i);
  1103. gl.bindTexture(gl.TEXTURE_2D, null);
  1104. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  1105. }
  1106. };
  1107. Context.prototype.readPixels = function (readState) {
  1108. var gl = this._gl;
  1109. readState = defaultValue(readState, defaultValue.EMPTY_OBJECT);
  1110. var x = Math.max(defaultValue(readState.x, 0), 0);
  1111. var y = Math.max(defaultValue(readState.y, 0), 0);
  1112. var width = defaultValue(readState.width, gl.drawingBufferWidth);
  1113. var height = defaultValue(readState.height, gl.drawingBufferHeight);
  1114. var framebuffer = readState.framebuffer;
  1115. //>>includeStart('debug', pragmas.debug);
  1116. Check.typeOf.number.greaterThan("readState.width", width, 0);
  1117. Check.typeOf.number.greaterThan("readState.height", height, 0);
  1118. //>>includeEnd('debug');
  1119. var pixelDatatype = PixelDatatype.UNSIGNED_BYTE;
  1120. if (defined(framebuffer) && framebuffer.numberOfColorAttachments > 0) {
  1121. pixelDatatype = framebuffer.getColorTexture(0).pixelDatatype;
  1122. }
  1123. var pixels = PixelFormat.createTypedArray(
  1124. PixelFormat.RGBA,
  1125. pixelDatatype,
  1126. width,
  1127. height
  1128. );
  1129. bindFramebuffer(this, framebuffer);
  1130. gl.readPixels(
  1131. x,
  1132. y,
  1133. width,
  1134. height,
  1135. PixelFormat.RGBA,
  1136. PixelDatatype.toWebGLConstant(pixelDatatype, this),
  1137. pixels
  1138. );
  1139. return pixels;
  1140. };
  1141. var viewportQuadAttributeLocations = {
  1142. position: 0,
  1143. textureCoordinates: 1,
  1144. };
  1145. Context.prototype.getViewportQuadVertexArray = function () {
  1146. // Per-context cache for viewport quads
  1147. var vertexArray = this.cache.viewportQuad_vertexArray;
  1148. if (!defined(vertexArray)) {
  1149. var geometry = new Geometry({
  1150. attributes: {
  1151. position: new GeometryAttribute({
  1152. componentDatatype: ComponentDatatype.FLOAT,
  1153. componentsPerAttribute: 2,
  1154. values: [-1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0],
  1155. }),
  1156. textureCoordinates: new GeometryAttribute({
  1157. componentDatatype: ComponentDatatype.FLOAT,
  1158. componentsPerAttribute: 2,
  1159. values: [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0],
  1160. }),
  1161. },
  1162. // Workaround Internet Explorer 11.0.8 lack of TRIANGLE_FAN
  1163. indices: new Uint16Array([0, 1, 2, 0, 2, 3]),
  1164. primitiveType: PrimitiveType.TRIANGLES,
  1165. });
  1166. vertexArray = VertexArray.fromGeometry({
  1167. context: this,
  1168. geometry: geometry,
  1169. attributeLocations: viewportQuadAttributeLocations,
  1170. bufferUsage: BufferUsage.STATIC_DRAW,
  1171. interleave: true,
  1172. });
  1173. this.cache.viewportQuad_vertexArray = vertexArray;
  1174. }
  1175. return vertexArray;
  1176. };
  1177. Context.prototype.createViewportQuadCommand = function (
  1178. fragmentShaderSource,
  1179. overrides
  1180. ) {
  1181. overrides = defaultValue(overrides, defaultValue.EMPTY_OBJECT);
  1182. return new DrawCommand({
  1183. vertexArray: this.getViewportQuadVertexArray(),
  1184. primitiveType: PrimitiveType.TRIANGLES,
  1185. renderState: overrides.renderState,
  1186. shaderProgram: ShaderProgram.fromCache({
  1187. context: this,
  1188. vertexShaderSource: ViewportQuadVS,
  1189. fragmentShaderSource: fragmentShaderSource,
  1190. attributeLocations: viewportQuadAttributeLocations,
  1191. }),
  1192. uniformMap: overrides.uniformMap,
  1193. owner: overrides.owner,
  1194. framebuffer: overrides.framebuffer,
  1195. pass: overrides.pass,
  1196. });
  1197. };
  1198. /**
  1199. * Gets the object associated with a pick color.
  1200. *
  1201. * @param {Color} pickColor The pick color.
  1202. * @returns {Object} The object associated with the pick color, or undefined if no object is associated with that color.
  1203. *
  1204. * @example
  1205. * var object = context.getObjectByPickColor(pickColor);
  1206. *
  1207. * @see Context#createPickId
  1208. */
  1209. Context.prototype.getObjectByPickColor = function (pickColor) {
  1210. //>>includeStart('debug', pragmas.debug);
  1211. Check.defined("pickColor", pickColor);
  1212. //>>includeEnd('debug');
  1213. return this._pickObjects[pickColor.toRgba()];
  1214. };
  1215. function PickId(pickObjects, key, color) {
  1216. this._pickObjects = pickObjects;
  1217. this.key = key;
  1218. this.color = color;
  1219. }
  1220. Object.defineProperties(PickId.prototype, {
  1221. object: {
  1222. get: function () {
  1223. return this._pickObjects[this.key];
  1224. },
  1225. set: function (value) {
  1226. this._pickObjects[this.key] = value;
  1227. },
  1228. },
  1229. });
  1230. PickId.prototype.destroy = function () {
  1231. delete this._pickObjects[this.key];
  1232. return undefined;
  1233. };
  1234. /**
  1235. * Creates a unique ID associated with the input object for use with color-buffer picking.
  1236. * The ID has an RGBA color value unique to this context. You must call destroy()
  1237. * on the pick ID when destroying the input object.
  1238. *
  1239. * @param {Object} object The object to associate with the pick ID.
  1240. * @returns {Object} A PickId object with a <code>color</code> property.
  1241. *
  1242. * @exception {RuntimeError} Out of unique Pick IDs.
  1243. *
  1244. *
  1245. * @example
  1246. * this._pickId = context.createPickId({
  1247. * primitive : this,
  1248. * id : this.id
  1249. * });
  1250. *
  1251. * @see Context#getObjectByPickColor
  1252. */
  1253. Context.prototype.createPickId = function (object) {
  1254. //>>includeStart('debug', pragmas.debug);
  1255. Check.defined("object", object);
  1256. //>>includeEnd('debug');
  1257. // the increment and assignment have to be separate statements to
  1258. // actually detect overflow in the Uint32 value
  1259. ++this._nextPickColor[0];
  1260. var key = this._nextPickColor[0];
  1261. if (key === 0) {
  1262. // In case of overflow
  1263. throw new RuntimeError("Out of unique Pick IDs.");
  1264. }
  1265. this._pickObjects[key] = object;
  1266. return new PickId(this._pickObjects, key, Color.fromRgba(key));
  1267. };
  1268. Context.prototype.isDestroyed = function () {
  1269. return false;
  1270. };
  1271. Context.prototype.destroy = function () {
  1272. // Destroy all objects in the cache that have a destroy method.
  1273. var cache = this.cache;
  1274. for (var property in cache) {
  1275. if (cache.hasOwnProperty(property)) {
  1276. var propertyValue = cache[property];
  1277. if (defined(propertyValue.destroy)) {
  1278. propertyValue.destroy();
  1279. }
  1280. }
  1281. }
  1282. this._shaderCache = this._shaderCache.destroy();
  1283. this._textureCache = this._textureCache.destroy();
  1284. this._defaultTexture = this._defaultTexture && this._defaultTexture.destroy();
  1285. this._defaultCubeMap = this._defaultCubeMap && this._defaultCubeMap.destroy();
  1286. return destroyObject(this);
  1287. };
  1288. export default Context;