英文:
z and w components of position vector act like they are switched in WGSL
问题
以下是您要翻译的代码部分:
struct Vertex {
@builtin(position) position : vec4<f32>,
@location(0) color : vec4<f32>,
}
@vertex
fn vMain(@builtin(vertex_index) vertexIndex: u32) -> Vertex {
var positions = array<vec4<f32>, 3> (
vec4<f32>(0, 0.5, 0, 1),
vec4<f32>(-0.5, -0.5, 0, 1),
vec4<f32>(0.5, -0.5, 0, 1),
);
var output: Vertex;
output.position = positions[vertexIndex];
output.color = vec4<f32>(1, 1, 1, 1);
return output;
}
@fragment
fn fMain(@location(0) color: vec4<f32>) -> @location(0) vec4<f32> {
return color;
}
希望这对您有所帮助。如果您有其他问题,请随时提问。
英文:
I have the following WGSL shader that creates a triangle:
struct Vertex {
@builtin(position) position : vec4<f32>,
@location(0) color : vec4<f32>,
}
@vertex
fn vMain(@builtin(vertex_index) vertexIndex: u32) -> Vertex {
var positions = array<vec4<f32>, 3> (
vec4<f32>(0, 0.5, 0, 1),
vec4<f32>(-0.5, -0.5, 0, 1),
vec4<f32>(0.5, -0.5, 0, 1),
);
var output: Vertex;
output.position = positions[vertexIndex];
output.color = vec4<f32>(1, 1, 1, 1);
return output;
}
@fragment
fn fMain(@location(0) color: vec4<f32>) -> @location(0) vec4<f32> {
return color;
}
According to everything I've found the 4 component vectors should be treated as x, y, z, and w in that order. The problem is that when I change the w component, it acts as if I am changing the z; the vertices of the triangle look as if they are getting farther or nearer. And when I change the z, the triangle never changes shape but instead will be partially clipped sometimes.
Changing z of top vertex to 2:
Changing w of left vertex to 2:
I do not understand why this effect is happening.
答案1
得分: 0
W 在正常的 3D 变换流程中有特殊的含义。它用于将透视应用于模型。虽然你从顶点着色器返回了一个 4D 向量,但它经过了所谓的透视除法,因此你应该考虑返回的是 3D 向量 [x/w, y/w, z/w]。请注意,这个问题不仅适用于 WebGPU,而且在所有 3D 库中都是相同的。
你可以在不同的地方阅读更多关于这个主题的信息:
- https://stackoverflow.com/questions/17269686/why-do-we-need-perspective-division
- https://www.tomdalling.com/blog/modern-opengl/explaining-homogenous-coordinates-and-projective-geometry/
英文:
W has a special meaning in the normal 3d transform pipeline. It is used to apply perspective to a model. While you are returning a 4d vector from the vertex shader, that is put through what is called a perspective divide, so in stead you should think that you are returning the 3d vector [x/w, y/w, z/w]. Note that this question is not webgpu specific and is the same through all 3d libraries.
You can read more about this in various places:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论