WebGL 高效粒子系统实战:把粒子计算搬进 Shader(webgl-fundamentals 指南)
WebGL 高效粒子系统实战:把粒子计算搬进 Shader(webgl-fundamentals 指南)
本篇指南围绕 webgl-fundamentals 仓库中《Efficient particle system in javascript? (WebGL)》问答展开,剖析一个经典性能困境:同样的 10000 个粒子,用 Canvas 2D 能跑 25 fps,改用 WebGL 后反而降到 15 fps。文章将给出根因分析、把粒子运动全部搬到 GPU shader 中的完整方案(含数据结构、关键公式与 GLSL 代码),并结合仓库中 webgl/lessons/webgl-gpgpu.md 的 GPGPU 粒子教程与 webgl/webgl-gpgpu-particles.html 的可运行示例,补充用纹理存储粒子状态、双缓冲交换、顶点拉取等进阶技术。读完你将掌握一套让 JavaScript 每帧几乎零计算的高效粒子系统实现思路。
一、问题场景:为什么 WebGL 反而更慢?
原问答中提问者的做法很有代表性:用 Canvas 2D 绘制 10000 个粒子,约 25 fps;重写为 WebGL 后反而只有约 15 fps。他同时使用 glMatrix 做向量运算,代码结构如下。
1. 初始化代码
gl = null;
try {
// Try to grab the standard context. If it fails, fallback to experimental.
gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
gl.viewportWidth = canvas.width;
gl.viewportHeight = canvas.height;
}
catch(e) {}
if(gl){
gl.clearColor(0.0,0.0,0.0,1.0);
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Initialize the shaders; this is where all the lighting for the
// vertices and so forth is established.
initShaders();
// Here's where we call the routine that builds all the objects
// we'll be drawing.
initBuffers();
}else{
alert("WebGL unable to initialize");
}
/* Initialize actors */
for(var i=0;i<NUM_SQS;i++){
sqs.push(new Square(canvas.width*Math.random(),canvas.height*Math.random(),1,1));
}
/* Begin animation loop by referencing the drawFrame() method */
gl.bindBuffer(gl.ARRAY_BUFFER, squareVerticesBuffer);
gl.vertexAttribPointer(vertexPositionAttribute, 2, gl.FLOAT, false, 0, 0);
requestAnimationFrame(drawFrame,canvas);
2. 每帧绘制循环
function drawFrame(){
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT);
//mvTranslate([-0.0,0.0,-6.0]);
for(var i=0;i<NUM_SQS;i++){
sqs[i].accelerate();
/* Translate current buffer (?) */
gl.uniform2fv(translationLocation,sqs[i].posVec);
/* Draw current buffer (?) */;
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
window.requestAnimationFrame(drawFrame, canvas);
}
3. 物理对象类(以 Square 为子类)
function PhysicsObject(startX,startY,size,mass){
/* Class instances */
this.posVec = vec2.fromValues(startX,startY);
this.velVec = vec2.fromValues(0.0,0.0);
this.accelVec = vec2.fromValues(0.0,0.0);
this.mass = mass;
this.size = size;
this.accelerate = function(){
var r2 = vec2.sqrDist(GRAV_VEC,this.posVec)+EARTH_RADIUS;
var dirVec = vec2.create();
vec2.set(this.accelVec,
G_CONST_X/r2,
G_CONST_Y/r2
);
/* Make dirVec unit vector in direction of gravitational acceleration */
vec2.sub(dirVec,GRAV_VEC,this.posVec)
vec2.normalize(dirVec,dirVec)
/* Point acceleration vector in direction of dirVec */
vec2.multiply(this.accelVec,this.accelVec,dirVec);
vec2.add(this.velVec,this.velVec,this.accelVec);
vec2.add(this.posVec,this.posVec,this.velVec);
};
}
4. 使用的 Shader
<script id="shader-fs" type="x-shader/x-fragment">
void main(void) {
gl_FragColor = vec4(0.7, 0.8, 1.0, 1.0);
}
</script>
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec2 a_position;
uniform vec2 u_resolution;
uniform vec2 u_translation;
void main() {
// Add in the translation.
vec2 position = a_position + u_translation;
// convert the rectangle from pixels to 0.0 to 1.0
vec2 zeroToOne = 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);
}
</script>
5. 性能瓶颈分析
从源码结构可以清晰看出问题所在:
- 每帧 10000 次 draw call:
drawFrame()中每个粒子一次gl.drawArrays,这意味着每帧向 GPU 提交 10000 个绘制命令; - 每帧 10000 次 uniform 更新:
gl.uniform2fv把每个粒子的位置逐个上传,JavaScript 与 GPU 之间存在大量往返; - JavaScript 承担全部物理计算:
accelerate()中每个粒子都要做距离计算、归一化、向量加减乘,10000 个粒子意味着每帧 10000 次循环; - 渲染管线闲置:每次
drawArrays之间 GPU 都在等待,无法充分利用并行能力。
这正是"Delays between the GPU and Javascript"——即 JavaScript 与 GPU 之间的同步开销。WebGL 的威力在于一次调用处理海量顶点,而不是把 CPU 循环照搬到 GPU 调用上。
二、核心方案:把粒子运动全部放进 Shader
原回答给出了关键判断:如果你的"重力"只是 velocity += acceleration; position += velocity 这样的简单积分,而非带碰撞的物理模拟,那么所有数学都可以在 shader 中完成——粒子系统初始化之后,唯一的每帧输入只有 time。
1. 每个粒子的顶点数据结构
在这种方案中,每个"粒子"由 4 个顶点(一个单位 quad)构成,每个顶点包含:
local_position(单位 quad 的局部坐标)texture_coord(纹理坐标)lifetime(生命周期)starting_position(起始位置)starting_time(起始时刻)velocity(速度)acceleration(加速度)start_size(起始尺寸)end_size(结束尺寸)orientation(四元数方向)color multiplier(颜色倍率)
2. 关键公式
给定当前时间 time,可以算出粒子的本地时间(自出生起的经过时间):
local_time = time - starting_time;
进而用匀加速运动公式计算基准位置:
base_position = start_position +
velocity * local_time +
acceleration * local_time * local_time;
即 acceleration * time²。再将 local_position 加到 base_position 上,就得到渲染 quad 所需的顶点位置。
同时可以计算粒子生命周期内的 0~1 插值因子:
lerp = local_time / lifetime;
用这个 lerp 值可以插值所有其他属性:
size = mix(start_size, end_size, lerp);
如果粒子超出生命周期,把尺寸置零即可让 GPU 不绘制它:
if (lerp < 0.0 || lerp > 1.0) {
size = 0.0;
}
3. 用 ramp 纹理实现颜色随时间变化
利用 ramp 纹理(一张 1xN 像素的纹理),可以轻松让粒子随时间改变颜色:
color = texture2D(rampTexture, vec4(lerp, 0.5));
同样的思路还可以扩展到:粒子的旋转(这是点精灵 point sprites 难以做到的)、按帧在纹理上做动画、2D 与 3D 朝向粒子等。原回答中给出这些搭配建议:
- 2D 粒子:适合烟雾、尾气、火焰、爆炸;
- 3D 粒子:适合波纹、可能还有轮胎痕迹;
- 2D + 3D 组合:可以用地面 puff 掩盖纯 2D 粒子的 z-fighting 问题。
示例还支持一次性效果(爆炸、puff,按 P 键触发)和拖尾效果(按住 T 键查看)。
4. 效率的本质
原回答指出:"AFAIK these are pretty efficient particles in that JavaScript is doing almost nothing." 这种方案的效率核心在于:初始化后 JavaScript 每帧只需要更新 time uniform,粒子从出生、运动、变尺寸、变颜色到死亡的全部逻辑都由 GPU 并行完成。10000 个粒子对 GPU 来说是微不足道的并行负载,而 JavaScript 侧的每帧工作量趋近于零。
三、仓库源码佐证:GPGPU 粒子系统的完整实现
上述"shader 里做一切"的思路,在仓库教程 webgl/lessons/webgl-gpgpu.md 的 "First example: particles" 一节和可运行示例 webgl/webgl-gpgpu-particles.html 中有完整实现,可作为本问答的进阶深化。
1. 思路对比:从 JS 循环到 GPGPU
传统做法是在 JavaScript 里逐粒子更新并逐个绘制(性能瓶颈,正是本问答中的问题):
for (const particle of particles) {
particle.pos.x = (particle.pos.x + particle.velocity.x) % canvas.width;
particle.pos.y = (particle.pos.y + particle.velocity.y) % canvas.height;
}
或者一次性上传所有新位置再批量绘制:
bindBuffer(..., particlePositionBuffer)
bufferData(..., latestParticlePositions, ...)
useProgram (particleShader)
setup particle attributes
set uniforms
draw particles
而 GPGPU 方案把位置和速度都存进纹理,用 shader 更新粒子位置。这依赖两个前提认知(见 webgl/lessons/webgl-gpgpu.md 开头):
- 纹理不是"图像",本质是二维数值数组;
- 结合读取纹理(webgl-3d-textures)与写入纹理(webgl-render-to-texture),就得到了读写二维数组的通用手段——这就是 WebGL 中 GPGPU 的本质。
2. 能力检查与浮点纹理扩展
由于要在纹理中存浮点位置/速度,并让顶点 shader 读取纹理,示例 webgl/webgl-gpgpu-particles.html 在初始化时做了三项能力检查:
// check we can use floating point textures
const ext1 = gl.getExtension('OES_texture_float');
if (!ext1) {
alert('Need OES_texture_float');
return;
}
// check we can render to floating point textures
const ext2 = gl.getExtension('WEBGL_color_buffer_float');
if (!ext2) {
alert('Need WEBGL_color_buffer_float');
return;
}
// check we can use textures in a vertex shader
if (gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS) < 1) {
alert('Can not use textures in vertex shaders');
return;
}
依据 webgl/lessons/webgl-gpgpu.md:浮点纹理是 WebGL 的可选特性,多数设备可读,桌面设备通常可渲染到浮点纹理,但大部分智能手机不支持渲染到浮点纹理。顶点 shader 中使用纹理同样是可选特性。
3. 更新位置的 fragment shader
这是整个 GPGPU 粒子的核心:它把每个 texel 当作一个粒子,用 gl_FragCoord 算出纹理坐标,读取旧位置与速度,按 position + velocity * deltaTime 积分并回绕边界,把新位置写入 gl_FragColor:
precision highp float;
uniform sampler2D positionTex;
uniform sampler2D velocityTex;
uniform vec2 texDimensions;
uniform vec2 canvasDimensions;
uniform float deltaTime;
vec2 euclideanModulo(vec2 n, vec2 m) {
return mod(mod(n, m) + m, m);
}
void main() {
// compute texcoord from gl_FragCoord;
vec2 texcoord = gl_FragCoord.xy / texDimensions;
vec2 position = texture2D(positionTex, texcoord).xy;
vec2 velocity = texture2D(velocityTex, texcoord).xy;
vec2 newPosition = euclideanModulo(position + velocity * deltaTime, canvasDimensions);
gl_FragColor = vec4(newPosition, 0, 1);
}
位置纹理与速度纹理一一对应(一个位置配一个速度),尺寸相同;而新位置写入的纹理与源纹理尺寸也相同,因此三个纹理可以共用 texDimensions。
4. 用 vertex id 从纹理拉取位置
绘制粒子时,顶点 shader 使用一个 id attribute(vertex id 技巧详见 webgl-drawing-without-data),从纹理中按一维数组索引取出对应粒子的位置:
attribute float id;
uniform sampler2D positionTex;
uniform vec2 texDimensions;
uniform mat4 matrix;
vec4 getValueFrom2DTextureAs1DArray(sampler2D tex, vec2 dimensions, float index) {
float y = floor(index / dimensions.x);
float x = mod(index, dimensions.x);
vec2 texcoord = (vec2(x, y) + 0.5) / dimensions;
return texture2D(tex, texcoord);
}
void main() {
// pull the position from the texture
vec4 position = getValueFrom2DTextureAs1DArray(positionTex, texDimensions, id);
// do the common matrix math
gl_Position = matrix * vec4(position.xy, 0, 1);
gl_PointSize = 10.0;
}
这里用 gl_POINTS 以点精灵方式绘制粒子;webgl-drawing-without-data.md 展示了如何仅凭 vertex id 加上一点 shader 数学,就用单个 draw call 画出圆形点阵乃至雨滴效果。
5. 双缓冲交换:为什么需要两张位置纹理
因为 WebGL 不允许在读取纹理的同时写入同一纹理,所以示例准备了 3 张纹理:1 张速度纹理 + 2 张位置纹理,每帧执行:
newPositions = oldPositions + velocities
然后交换新旧:
// create a texture for the velocity and 2 textures for the positions.
const velocityTex = createTexture(gl, velocities, particleTexWidth, particleTexHeight);
const positionTex1 = createTexture(gl, positions, particleTexWidth, particleTexHeight);
const positionTex2 = createTexture(gl, null, particleTexWidth, particleTexHeight);
每帧渲染时,先绑定新位置纹理对应的 framebuffer 运行更新 shader(画一个覆盖全屏的 quad,即 gl.drawArrays(gl.TRIANGLES, 0, 6)),再把视口切回画布、绑定新位置纹理,用 gl.drawArrays(gl.POINTS, 0, numParticles) 绘制全部粒子,最后交换指针:
// swap which texture we will read from
// and which one we will write to
{
const temp = oldPositionsInfo;
oldPositionsInfo = newPositionsInfo;
newPositionsInfo = temp;
}
关于 framebuffer 与离屏渲染的细节可参考 webgl-render-to-texture。
6. 效果与限制
教程给出的结论是:得到 GPGPU 粒子后,"JavaScript is doing almost no work except calling gl.drawArrays twice. Once to update the positions, and once to draw the particles"——每帧仅两次 gl.drawArrays 调用:一次更新位置,一次绘制粒子,与本文第二部分的"shader 里做一切"理念一脉相承。
需要注意的纹理限制(依据 webgl/lessons/webgl-gpgpu.md):示例用 20x10 的纹理绘制 200 个粒子;纹理本质是二维数组,无法做出恰好 199 像素的二维数组,这类"不能整齐放进二维数组"的问题需要自行设计方案(例如分配 200 个只绘制 199 个)。
四、延伸阅读:粒子数据在纹理中的定位与状态管理
粒子系统还经常涉及"如何让每个粒子固定占据纹理中的同一坐标"这类问题,仓库中 webgl-qna-how-to-process-particle-positions.md 的问答对此有清晰解释,与本主题强相关:
- 更新粒子位置的 fragment shader 不能选择自己更新哪个像素,它只能写
gl.outColor; - shader 的输入只有
gl_FragCoord和 program 的 uniform,因此粒子数据必须通过纹理网格(texel 坐标)组织,而不是靠 CPU 端对象数组; - 教程给出了三个递进示例(example-1、example-2、example-3):纯 JavaScript 版本 → 模拟 WebGL 运行方式的 JavaScript 版本 → 真实 WebGL 版本,帮助理解"粒子位置存纹理、数据留在 GPU"的思维转变。
五、总结:高效 WebGL 粒子的四条准则
综合本问答与仓库教程,可归纳出高效 WebGL 粒子系统的关键原则:
- 消灭逐粒子 draw call:把 10000 次
gl.drawArrays合并为一次批量绘制,这是从 15 fps 回升到高效的最关键一步; - 把物理计算移进 shader:
velocity += acceleration; position += velocity这类运算交给 GPU 并行执行,JavaScript 每帧只更新time/deltaTime等少量 uniform; - 用数据驱动替代对象驱动:粒子属性打包进顶点 attribute(本问答方案)或纹理 texel(GPGPU 方案),避免每帧上传海量位置数据;
- 善用纹理即二维数组的认知:位置、速度、ramp 颜色曲线都可以用纹理表达,配合 framebuffer 离屏渲染与双缓冲交换,实现完整 GPU 内循环。
本问答的其他 Q&A 还收录在索引页 webgl-qna.md 中,如"如何批量绘制精灵并传每精灵 alpha"(Passing in per sprite alpha values when batching)、"绘制大量圆形的最快方式"(The fastest way to draw many circles)等,可与本文互相印证,共同构成 WebGL 高性能绘制的完整知识链。