三.js/GLSL : WebGL shader to color fragments based on world space position

标签 three.js glsl webgl glsles

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

它们使用屏幕坐标,并且当相机移动或旋转时会发生变化;或仅适用于局部对象空间。

我想要完成的是根据片段在世界空间中的位置(如在 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 移动,您会发现颜色没有保持在原位。不过,我希望他们这么做。

最佳答案

您的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

关于三.js/GLSL : WebGL shader to color fragments based on world space position,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45906327/

相关文章:

c++ - GLSL - 统一缓冲对象奇怪的行为

javascript - THREE.js 从 GPUComputationRenderer 纹理读取像素

javascript - Webgl bindBufer 和 vertexAttribPointer 是否取决于缓冲区大小?

javascript - Three.js - TypeError : THREE. 场景不是构造函数

javascript - 从 OBJ 文件中选取选定的网格

javascript - 如何在物体上手动应用重力(cannon.js)?

ios - 在带有 Ludei/Cocoon JS 的 IOS 设备上使用 WebGL 不接触 ThreeJS OrbitControls

opengl - 在 GLSL 中对矩阵使用预乘顺序有什么缺点吗?

c++ - in vec 和 out vec 是什么意思?

javascript - webgl 应用程序中的 gl-matrix "cannot read property 0 of undefined"