Context.js 47 KB

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