gl-util.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Tencent is pleased to support the open source community by making vap available.
  3. *
  4. * Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the MIT License (the "License"); you may not use this file except in
  7. * compliance with the License. You may obtain a copy of the License at
  8. *
  9. * http://opensource.org/licenses/MIT
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed under the License is
  12. * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  13. * either express or implied. See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. export function createShader(gl, type, source) {
  17. const shader = gl.createShader(type);
  18. gl.shaderSource(shader, source);
  19. gl.compileShader(shader);
  20. // if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  21. // console.error(gl.getShaderInfoLog(shader))
  22. // }
  23. return shader;
  24. }
  25. export function createProgram(gl, vertexShader, fragmentShader) {
  26. const program = gl.createProgram();
  27. gl.attachShader(program, vertexShader);
  28. gl.attachShader(program, fragmentShader);
  29. gl.linkProgram(program);
  30. // if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  31. // console.error(gl.getProgramInfoLog(program))
  32. // }
  33. gl.useProgram(program);
  34. return program;
  35. }
  36. export function createTexture(gl, index:number, imgData?:TexImageSource) {
  37. const texture = gl.createTexture();
  38. const textrueIndex = gl.TEXTURE0 + index;
  39. gl.activeTexture(textrueIndex);
  40. gl.bindTexture(gl.TEXTURE_2D, texture);
  41. // gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  42. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  43. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  44. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  45. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  46. if (imgData) {
  47. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, imgData);
  48. }
  49. return texture;
  50. }
  51. export function cleanWebGL(gl, shaders, program, textures, buffers) {
  52. try {
  53. gl.clear(gl.COLOR_BUFFER_BIT);
  54. textures.forEach(t => {
  55. gl.deleteTexture(t);
  56. });
  57. buffers.forEach(b => {
  58. gl.deleteBuffer(b);
  59. });
  60. shaders.forEach(shader => {
  61. gl.detachShader(program, shader);
  62. gl.deleteShader(shader);
  63. });
  64. gl.clear(gl.COLOR_BUFFER_BIT);
  65. gl.deleteProgram(program)
  66. } catch (e) {}
  67. }