为什么在片段着色器中插入一个简单的 vec3 颜色属性?

问题描述 投票:0回答:1

我正在使用 Three.js,我发现了非常奇怪的结果。

我只是在调整,以试验属性,如下所示

const colors = [
      new THREE.Color(0xFF0000),
      new THREE.Color(0x00FF00),
      new THREE.Color(0x0000FF),
      new THREE.Color(0x00FFFF),
    ]
const colorFloats = colors.map(c => c.toArray()).flat();


    const material = new THREE.ShaderMaterial({
      uniforms: {
        color1: {
          value : new THREE.Vector4(1,1,0,1)
        },
        color2: {
          value : new THREE.Vector4(0,1,1,1)
        }
      },
      vertexShader: await vsh.text(),
      fragmentShader: await fsh.text()
    });

    const geometry = new THREE.PlaneGeometry(1, 1);
    geometry.setAttribute('myColor',
    new THREE.Float32BufferAttribute(colorFloats, 3))

顶点着色器


attribute vec3 myColor;
varying vec2 vUvs;
varying vec3 vColor;

void main(){
  vec4 localPosition=vec4(position,1.);
  vColor=myColor;
  gl_Position=projectionMatrix*modelViewMatrix*localPosition;
}

对于片段。着色器

varying vec3 vColor;

void main(){
  
  gl_FragColor=vec4(
    vColor,
    1.
  );
}

我得到如下所示的结果:

真不明白为什么会这样显示

我刚刚传递了 4 个 Three.js 颜色实例作为 bufferArray(它有 12 个项目 [1,0,0,0,1,0,0,0,1,0,1,1]

据我所知,着色器应该将这些值作为 vec3。结果不应该是 Vec3(1,0,0),因为我正在将“myColor”属性转换为 3D 向量吗?

three.js webgl
1个回答
1
投票

几何体的每个角都有 1 个顶点。顶点着色器为4个顶点中的每一个运行,读取顶点的唯一颜色,然后将其写入“varying”。当片段着色器运行时,它使用来自该三角形顶点的变量的加权混合。这就是 GLSL 变量的目的——您可以在 https://jameshfisher.com/2017/10/19/glsl-varying/.

中阅读更长的解释

为了在平面中间的颜色之间进行硬截断,您需要 (a) 沿着分界线的顶点,或者 (b) 更复杂的片段着色器逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.