问题描述
我有顶点和三角形数据,其中包含每个 triangle (面)的颜色,而不是每个顶点的颜色.即单个顶点由多个面共享,每个面可能具有不同的颜色.
I have vertex and triangle data which contains a color for each triangle (face), not for each vertex. i.e. A single vertex is shared by multiple faces, each face potentially a different color.
我应该如何在GLSL中解决此问题,以获取要渲染的每个 face 的纯色分配?通过平均顶点相邻多边形的颜色来计算和分配顶点颜色"缓冲区很容易,但这当然会产生模糊的结果,在这些颜色中将颜色插值到片段着色器中.
How should I approach this problem in GLSL to obtain a solid color assignment for each face being rendered? Calculating and assigning a "vertex color" buffer by averaging the colors of a vertex's neighboring polys is easy enough, but this of course produces a blurry result where the colors are interpolated in the fragment shader.
我真正需要的根本不应该是插值颜色值,一旦按预期工作,我将有大约40k三角形,并带有约15种可能的纯色.
What I really need shouldn't be interpolated color values at all, I'll have about 40k triangles shaded with approx 15 possible solid colors once this is working as intended.
推荐答案
虽然您可以在高端GLSL中做到这一点,但进行实心着色的正确方法是为每个三角形制作唯一的顶点.这是一个微不足道的循环.对于每个顶点,计算有多少个三角形共享它.这就是您必须复制它的频率.确保执行此操作的循环为O(n).然后,只需将每个顶点颜色或法线设置为三角形的颜色即可.再次是一个直线循环.不要为共享颜色而优化,这是不值得的.
While you maybe could do this in high end GLSL, the right way to do solid shading is to make unique vertices for every triangle. This is a trivial loop. For every vertex, count how many triangles share it. That's how often you have to replicate it. Make sure your loop to do this is O(n). Then just set each vertex color or normal to that of the triangle. Again one straight loop. Do not bother to optimize for shared colors, it is not worth it.
稍后进行编辑,因为这是一个受欢迎的答案:
Edit much later, because this is a popular answer:
要对每个面进行平面处理着色,您可以插值世界或视图空间中的顶点位置.然后在片段着色器中计算此变量的ddx(dFdx)和ddy(dFdy).取这两个向量的叉积并将其归一化-您得到了平坦的法线!完全不需要网格更改或每个顶点数据.
To do flat per face shading you can interpolate the vertex position in world or view space. Then in the fragment shader compute ddx(dFdx) and ddy(dFdy) of this variable. Take the cross product of those two vectors and normalize it - you got a flat normal! No mesh changes or per vertex data needed at all.
这篇关于编写每个三角形/面均具有纯色的GLSL片段着色器的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!