前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【WebGL】一次drawcall中绘制多个不同纹理的图形

【WebGL】一次drawcall中绘制多个不同纹理的图形

作者头像
用户1258909
发布2020-07-27 16:24:38
1.7K0
发布2020-07-27 16:24:38
举报
文章被收录于专栏:拂晓风起拂晓风起

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

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
  // 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);
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-07-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档