【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);
kenkofox@qq.com
https://github.com/kenkozheng
欢迎投简历给我,一线大厂工作机会
分类:
HTML/JS/CSS
, WebGL/Canvas
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架