Context.js 50 KB

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