You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebGL着色器遍历数组报错求助:字段选择需左侧为结构或向量

解决WebGL着色器中遍历数组的错误

Ah, I see the issue here—you're running into a common gotcha with how WebGL handles uniform arrays in shaders! Let's break down what's going wrong and how to fix it.

核心问题:Uniform声明不匹配

The error message "field selection requires structure or vector on left hand side" is telling you exactly what's off: in your fragment shader, you declared uniform vec2 particles—this defines a single 2D vector, not an array of vectors. When you try to access it like particles[i], the shader compiler gets confused because it expects you to use .x or .y (field selection) on a vec2, not bracket notation for array indexing.

修复步骤

1. 修正着色器中的Uniform声明

You need to declare particles as an array of vec2s. In WebGL 1.0, you have to specify a fixed size for the array (match the 100 elements you're passing from JavaScript):

// 片段着色器中正确的声明
uniform vec2 particles[100];

If you're using WebGL 2.0, you can use a dynamically sized array with a const qualifier (though fixed size still works fine):

const int PARTICLE_COUNT = 100;
uniform vec2 particles[PARTICLE_COUNT];

2. 正确遍历数组

Once the uniform is declared as an array, you can loop through it like you intended. For example:

void main() {
    vec3 color = vec3(0.0);
    for (int i = 0; i < 100; i++) {
        vec2 particlePos = particles[i];
        // 在这里处理每个粒子的坐标,比如计算距离、颜色贡献等
        float distance = length(gl_FragCoord.xy - particlePos);
        if (distance < 5.0) {
            color += vec3(1.0, 0.0, 0.0);
        }
    }
    gl_FragColor = vec4(color, 1.0);
}

3. 确认JavaScript部分的正确性

Your JavaScript code using gl.uniform2fv is already correct for passing an array of vec2s—just make sure you're getting the correct uniform location for the array (note: in WebGL, you don't need to append [0] to the uniform name when getting the location; just use "particles" directly):

// JavaScript示例代码
const particles = new Float32Array(200); // 100个xy坐标,共200个元素
// 填充particles数组...

const particlesUniformLoc = gl.getUniformLocation(shaderProgram, "particles");
gl.uniform2fv(particlesUniformLoc, particles);

额外注意事项

  • If you're working with a variable number of particles (not fixed at 100), you can pass an additional uniform to track the actual count, then loop up to that value instead of the full array size:
uniform int particleCount;
uniform vec2 particles[100];

void main() {
    vec3 color = vec3(0.0);
    for (int i = 0; i < particleCount; i++) {
        // 处理逻辑
    }
    gl_FragColor = vec4(color, 1.0);
}
  • WebGL 1.0 has limits on the size of uniform arrays—check gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS) to make sure your array size is within the allowed limit.

内容的提问来源于stack exchange,提问作者TheCat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:59:34