一、质心坐标
在几何结构中,质心坐标是指图形中的点相对各顶点的位置。以图1的线段 AB 为例,点 P 位于线段 AB 之间,
同理,在三角形 ABC 中,三角形内点 P 的计算公式为
最终就是计算三个参数:m、n、(1-m-n);如果m<0、n<0、m+n>1 则说明P点不在三角形内;
实现代码大体如下:
Vec3f barycentric(Vec2f A, Vec2f B, Vec2f C, Vec2f P) {
Vec3f s[2];
for (int i=2; i--; ) {
s[i][0] = C[i]-A[i];
s[i][1] = B[i]-A[i];
s[i][2] = A[i]-P[i];
}
Vec3f u = cross(s[0], s[1]);
if (std::abs(u[2])>1e-2) // dont forget that u[2] is integer. If it is zero then triangle ABC is degenerate
return Vec3f(1.f-(u.x+u.y)/u.z, u.y/u.z, u.x/u.z);
return Vec3f(-1,1,1); // in this case generate negative coordinates, it will be thrown away by the rasterizator
}
二、用opengl进行实现
1、开发环境介绍
- 操作系统:windows
- 开发软件:Visual Studio 2017
- 编程语言:基于控制台下的opengl
- 用到的库: glut
opengl环境配置可参照上一篇博客:控制台+OPENGL配置说明[GLUT篇]