THREE.js / GLSL:WebGL着色器,根据世界空间位置对片段进行着色

时间:2017-08-27 15:01:24

标签: three.js glsl webgl glsles

我已经看到了基于颜色片段在屏幕空间或像Three.js/GLSL - Convert Pixel Coordinate to World Coordinate这样的本地对象空间中的位置的解决方案。

那些正在使用屏幕坐标,并在相机移动或旋转时进行更改;或仅适用于本地对象空间。

我想要完成的是根据世界空间中的position对片段进行着色(如在three.js场景图的世界空间中)。

即使相机移动,颜色也应保持不变。

希望行为的示例:位于(x:0,y:0,z:2)世界空间中的1x1x1立方体将使其第三个成分(蓝色== z)始终在1.5 - 2.5之间。即使相机移动也应如此。

到目前为止我得到了什么:

顶点着色器

varying vec4 worldPosition;

void main() {


  // The following changes on camera movement:
  worldPosition = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

  // This is closer to what I want (colors dont change when camera moves)
  // but it is in local not world space:
  worldPosition = vec4(position, 1.0);

  // This works fine as long as the camera doesnt move:
  worldPosition = modelViewMatrix * vec4(position, 1.0);
  // Instead I'd like the above behaviour but without color changes on camera movement


  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);

}

片段着色器

uniform vec2 u_resolution;
varying vec4 worldPosition;

void main(void)
{
    // I'd like to use worldPosition something like this:
    gl_FragColor = vec4(worldPosition.xyz * someScaling, 1.0);
    // Here this would mean that fragments xyz > 1.0 in world position would be white and black for <= 0.0; that would be fine because I can still divide it to compensate

}

这是我得到的: https://glitch.com/edit/#!/worldpositiontest?path=index.html:163:15

如果您使用 wasd 移动,您可以看到颜色不会停留在原位。不过,我还是喜欢他们。

1 个答案:

答案 0 :(得分:7)

您的worldPosition错了。您不应该在计算中涉及相机。这意味着,不是projectionMatrix也不是viewMatrix

// The world poisition of your vertex: NO CAMERA
vec4 worldPosition = modelMatrix * vec4(position, 1.0);

// Position in normalized screen coords: ADD CAMERA
gl_Position = projectionMatrix * viewMatrix * worldPosition;

// Here you can compute the color based on worldPosition, for example:
vColor = normalize(abs(worldPosition.xyz));

检查this fiddle

注意

请注意,此处使用的abs()颜色可能会为不同的位置提供相同的颜色,这可能不是您想要的颜色。

Position coords to color coords