【WebGL】一次drawcall中繪制多個不同紋理的圖形


Demo: http://kenkozheng.github.io/WebGL/multi-texture-in-one-drawcall/index.html

關鍵點:
1、fragment shader接受參數(從vertex shader傳遞vary),動態指定sampler
2、設置sampler index buffer,連同vertex buffer一同綁定到當次渲染

Vertex Shader

attribute vec2 a_position;
attribute vec2 a_texCoord;
attribute lowp float textureIndex;

uniform vec2 u_resolution;
varying vec2 v_texCoord;
varying lowp float indexPicker;

void main() {
   // convert the rectangle from pixels to 0.0 to 1.0
   vec2 zeroToOne = a_position / u_resolution;

   // convert from 0->1 to 0->2
   vec2 zeroToTwo = zeroToOne * 2.0;

   // convert from 0->2 to -1->+1 (clipspace)
   vec2 clipSpace = zeroToTwo - 1.0;

   gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);

   // pass the texCoord to the fragment shader
   // The GPU will interpolate this value between points.
   v_texCoord = a_texCoord;
   indexPicker = textureIndex; // 控制fragment shader選哪一個紋理
}

Fragment shader

precision mediump float;

// our texture
uniform sampler2D u_image[2];

// the texCoords passed in from the vertex shader.
varying vec2 v_texCoord;
varying lowp float indexPicker;

void main() {
   if (indexPicker < 0.5) {
       gl_FragColor = texture2D(u_image[0], v_texCoord);
   } else {
       gl_FragColor = texture2D(u_image[1], v_texCoord);
   }
}

index buffer

  // provide texture index buffer. 前6次調用用0號紋理,后6次調用用1號紋理
  var textureIndexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, textureIndexBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]), gl.STATIC_DRAW);


  // Turn on the textureIndex attribute
  gl.enableVertexAttribArray(textureIndexLocation);
  gl.bindBuffer(gl.ARRAY_BUFFER, textureIndexBuffer);
  // Tell the textureIndex attribute how to get data out of textureIndexBuffer (ARRAY_BUFFER)
  var size = 1;          // 1 components per iteration
  var type = gl.FLOAT;   // the data is 32bit floats
  var normalize = false; // don't normalize the data
  var stride = 0;        // 0 = move forward size * sizeof(type) each iteration to get the next position
  var offset = 0;        // start at the beginning of the buffer
  gl.vertexAttribPointer(textureIndexLocation, size, type, normalize, stride, offset);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM