gpt4 book ai didi

c++ - GLSL - 给定顶点法线计算表面法线

转载 作者:行者123 更新时间:2023-12-04 14:46:55 25 4
gpt4 key购买 nike

我想在 OpenGL 上实现平面着色。我用谷歌搜索并发现了这个问题:How to achieve flat shading with light calculated at centroids? .

我理解最佳答案的想法,并且正在尝试实现它。但是,我不知道如何在给定三角形每个顶点的法线的情况下找到表面法线。

顶点着色器中的相关代码:

#version 400 core

...

layout(location = 0) in vec4 position;
layout(location = 1) in vec3 normal;

uniform mat4 Mm;
uniform mat3 normalMatrix;

out vec3 vertexN;
out vec3 vertexP;

...

int main() {
...
vertexN = normalize(normalMatrix * normal);
vertexP = vec3(Mm * position);
...
}

几何着色器中的相关代码:

#version 400 core

...
layout (triangles) in;
layout (triangle_strip, max_vertices=3) out;

in vec3 vertexP[3];
in vec3 vertexN[3];

...

void main(){
...
vec3 centroidPosition(0.0);
for(int i = 0; i < 3; i++) centroidPosition += vertexP[i];
centroidPosition/=3.0;

// calculate surface normal

...
}

最佳答案

可以使用 Cross product 计算表面法线表面上的 2 个 vector 。以下代码用于逆时针三角形:

vec3 v1 = vertexP[1] - vertexP[0];
vec3 v2 = vertexP[2] - vertexP[0];
vec3 surfNormal = normalize(cross(v1, v2));

如果三角形的缠绕顺序是顺时针,则必须交换 v1v2:

vec3 surfNormal = normalize(cross(v2, v1));

使用 Dot product在混合三角形的缠绕顺序时确保表面法线的方向正确:

surfNormal *= sign(dot(surfNormal, vertexN[0]+vertexN[1]+vertexN[2]));

关于c++ - GLSL - 给定顶点法线计算表面法线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69854268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com