c - 如何在 OpenGL 中创建便宜的阴影?

标签 c opengl 3d shadow

<分区>

我有两个模型,A 和 B,还有一个灯,L。我希望模型 A 在模型 B 上转换阴影。我暂时不想打扰阴影体积或适当的阴影,只是一个简单的圆形阴影就足够了。效果是模型 A 被视为用于阴影转换目的的球体。

这是我设想的算法:

对于模型 B 中的每个三角形,绘制三角形。沿着从 L 到 A 的线将一个圆投影到三角形上,根据三角形的距离增加圆的大小。确保圆被剪裁到三角形的边界(我想以某种方式使用模板缓冲区)。

我正在使用 OpenGL 和纯 C。

关于我可以阅读的一些引用文档的任何指示?还是实现思路?

最佳答案

我认为实现正确的阴影实际上更容易,因为 OpenGL 可以为您完成这项工作。

我在这里找到了一个包含大量文档的有效影子代码:http://www.opengl.org/resources/code/samples/mjktips/TexShadowReflectLight.html

上面的代码对对象进行了两次渲染:第一次是正常渲染,然后是一个特殊的矩阵渲染。它做了很多不相关的事情,比如用鼠标控制和反射。所以这里是有趣的部分。

计算阴影矩阵:

/* Create a matrix that will project the desired shadow. */
void
shadowMatrix(GLfloat shadowMat[4][4],
  GLfloat groundplane[4],
  GLfloat lightpos[4])
{
  GLfloat dot;

  /* Find dot product between light position vector and ground plane normal. */
  dot = groundplane[X] * lightpos[X] +
    groundplane[Y] * lightpos[Y] +
    groundplane[Z] * lightpos[Z] +
    groundplane[W] * lightpos[W];

  shadowMat[0][0] = dot - lightpos[X] * groundplane[X];
  shadowMat[1][0] = 0.f - lightpos[X] * groundplane[Y];
  shadowMat[2][0] = 0.f - lightpos[X] * groundplane[Z];
  shadowMat[3][0] = 0.f - lightpos[X] * groundplane[W];

  shadowMat[X][1] = 0.f - lightpos[Y] * groundplane[X];
  shadowMat[1][1] = dot - lightpos[Y] * groundplane[Y];
  shadowMat[2][1] = 0.f - lightpos[Y] * groundplane[Z];
  shadowMat[3][1] = 0.f - lightpos[Y] * groundplane[W];

  shadowMat[X][2] = 0.f - lightpos[Z] * groundplane[X];
  shadowMat[1][2] = 0.f - lightpos[Z] * groundplane[Y];
  shadowMat[2][2] = dot - lightpos[Z] * groundplane[Z];
  shadowMat[3][2] = 0.f - lightpos[Z] * groundplane[W];

  shadowMat[X][3] = 0.f - lightpos[W] * groundplane[X];
  shadowMat[1][3] = 0.f - lightpos[W] * groundplane[Y];
  shadowMat[2][3] = 0.f - lightpos[W] * groundplane[Z];
  shadowMat[3][3] = dot - lightpos[W] * groundplane[W];

}

我不会假装完全理解这一点。 lightpos 是光源的位置。 groundplane 的前 3 个坐标是地表的法 vector 。第四个是偏移量(距离 0,0,0 有多远)。

而这部分实际上渲染了阴影:

glPushMatrix();
/* Project the shadow. */
glMultMatrixf((GLfloat *) floorShadow);
drawDinosaur();
glPopMatrix();

您需要首先对 glEnable/glDisable 进行一些设置才能使其正常工作,因此请查看链接。

关于c - 如何在 OpenGL 中创建便宜的阴影?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114742/

相关文章:

c - C 中的 SegFault 错误

c++ - 协助调试 OpenGL glsl 着色器或使用它的代码

OpenGL - VBO 内部的顶点数组和外部的索引和纹理数组?

browser - Blender 与 Unity

c - 当 `char` 类型以 64 位表示时,它如何保持其范围不受 limits.h 影响

c++ - 取消引用指针 -vs- &-operator

c++ - 纹理和渲染缓冲区是否在帧缓冲区对象上共享相同的空间?

python - matplotlib 3d 轴刻度、标签和 LaTeX

c++ - glDrawArrays(GL_TRIANGLES, 0, model.indicesCount) 上的 openGL 未处理异常;称呼

c - 乘除法 : weird output in c