context.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { createProgramCache, ProgramCache } from './program'
  7. import { createShaderCache, ShaderCache } from './shader'
  8. // const extensions = [
  9. // 'OES_element_index_uint',
  10. // 'ANGLE_instanced_arrays'
  11. // ]
  12. // const optionalExtensions = [
  13. // 'EXT_disjoint_timer_query'
  14. // ]
  15. function unbindResources (gl: WebGLRenderingContext) {
  16. // bind null to all texture units
  17. const maxTextureImageUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS)
  18. for (let i = 0; i < maxTextureImageUnits; ++i) {
  19. gl.activeTexture(gl.TEXTURE0 + i)
  20. gl.bindTexture(gl.TEXTURE_2D, null)
  21. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null)
  22. }
  23. // assign the smallest possible buffer to all attributes
  24. const buf = gl.createBuffer();
  25. gl.bindBuffer(gl.ARRAY_BUFFER, buf);
  26. const maxVertexAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  27. for (let i = 0; i < maxVertexAttribs; ++i) {
  28. gl.vertexAttribPointer(i, 1, gl.FLOAT, false, 0, 0);
  29. }
  30. // bind null to all buffers
  31. gl.bindBuffer(gl.ARRAY_BUFFER, null)
  32. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)
  33. gl.bindRenderbuffer(gl.RENDERBUFFER, null)
  34. gl.bindFramebuffer(gl.FRAMEBUFFER, null)
  35. }
  36. type RequiredExtensions = {
  37. angleInstancedArrays: ANGLE_instanced_arrays
  38. oesElementIndexUint: OES_element_index_uint
  39. }
  40. export interface Context {
  41. gl: WebGLRenderingContext
  42. extensions: RequiredExtensions
  43. shaderCache: ShaderCache
  44. programCache: ProgramCache
  45. destroy: () => void
  46. }
  47. export function createContext(gl: WebGLRenderingContext): Context {
  48. const angleInstancedArrays = gl.getExtension('ANGLE_instanced_arrays')
  49. if (angleInstancedArrays === null) {
  50. throw new Error('Could not get "ANGLE_instanced_arrays" extension')
  51. }
  52. const oesElementIndexUint = gl.getExtension('OES_element_index_uint')
  53. if (oesElementIndexUint === null) {
  54. throw new Error('Could not get "OES_element_index_uint" extension')
  55. }
  56. return {
  57. gl,
  58. extensions: { angleInstancedArrays, oesElementIndexUint },
  59. shaderCache: createShaderCache(),
  60. programCache: createProgramCache(),
  61. destroy: () => {
  62. unbindResources(gl)
  63. // TODO destroy buffers and textures
  64. }
  65. }
  66. }