DebugLayer.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { fillRectangle} from "./2d"
  2. import { LayerAB, Scene } from "./Scene"
  3. import { createProgram, createShader } from "./utils"
  4. export class DebugLayer extends LayerAB {
  5. private vertexShaderCode = /*glsl*/ `
  6. attribute vec2 a_position;
  7. uniform mat4 u_matrix;
  8. void main() {
  9. gl_PointSize = 20.0;
  10. gl_Position = u_matrix * vec4(a_position, 0, 1);
  11. }
  12. `;
  13. private fragmentShaderCode = /*glsl*/ `
  14. precision mediump float;
  15. varying vec2 v_texCoord;
  16. void main() {
  17. gl_FragColor = vec4(0, 0, 1, 1);
  18. }
  19. `
  20. program: WebGLProgram
  21. aPositionLoc: number
  22. uMatrixLoc: WebGLUniformLocation
  23. vertexBuffer: WebGLBuffer
  24. vertexArray = new Float32Array(12)
  25. constructor(
  26. public readonly scene: Scene,
  27. ) {
  28. super()
  29. const gl = scene.gl;
  30. this.program = createProgram(gl,
  31. createShader(gl, gl.VERTEX_SHADER, this.vertexShaderCode)!,
  32. createShader(gl, gl.FRAGMENT_SHADER, this.fragmentShaderCode)!)!
  33. this.aPositionLoc = gl.getAttribLocation(this.program, "a_position")
  34. this.uMatrixLoc = gl.getUniformLocation(this.program, "u_matrix")!
  35. this.vertexBuffer = gl.createBuffer()!;
  36. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  37. gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW);
  38. }
  39. override draw() {
  40. const gl = this.scene.gl;
  41. gl.useProgram(this.program);
  42. gl.enableVertexAttribArray(this.aPositionLoc);
  43. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  44. gl.vertexAttribPointer(this.aPositionLoc, 2, gl.FLOAT, false, 0, 0)
  45. gl.uniformMatrix4fv(this.uMatrixLoc, false, this.scene.drawMatrix)
  46. gl.drawArrays(gl.POINTS, 0, 1);
  47. }
  48. override tap(cx: number, cy: number, sx: number, sy: number): void {
  49. console.log(`tap @${cx},${cy}`)
  50. const gl = this.scene.gl
  51. this.vertexArray[0] = cx;
  52. this.vertexArray[1] = cy;
  53. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  54. gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW);
  55. this.scene.invalidate()
  56. }
  57. toString(): string {
  58. return `DebugLayer()`
  59. }
  60. }