c++ - 如何为 2D 和 3D 调整顶点着色器?

标签 c++ opengl 3d 2d glsl

我正在 2D 中进行粒子模拟,我需要将其扩展到 3D。为了支持 2D 和 3D,只需更改标志即可很好地适应 C++ 代码,但是,我刚刚开始学习 OpenGL 和着色器,想知道是否有一种好的方法可以使我的顶点着色器通用。

到目前为止我的着色器看起来像

in vec3 vertexPosition;
uniform mat4 MVP;

void main()
{
   gl_Position = MVP * vec4(vertexPosition.xyz,1.0);
}

在 3D 中工作正常,但如果我转为 2D,我需要修改它。我想解决它的一种方法是只使用 2 个不同的着色器,一个用于 2D,一个用于 3D,并使用我在 C++ 中的标志选择合适的着色器,但我想知道是否有更好的方法来实现这一点而无需两个单独的着色器文件。

有什么建议吗?

最佳答案

您只需将 Z 坐标设置为 0,当您只为该属性传递 2 个组件时,这会自动发生。

参见 Vertex format openGL wiki 上的顶点规范页面部分:

Each attribute index represents a vector of some type, from 1 to 4 components in length. The size​ parameter of the glVertexAttribPointer​ functions defines the number of components in the vector provided by the attribute array. It can be any number 1-4. Note that size​ does not have to exactly match the size used by the vertex shader. If the vertex shader has fewer components than the attribute provides, then the extras are ignored. If the vertex shader has more components than the array provides, the extras are given values from the vector (0, 0, 0, 1) for the XYZW components. Note that for double-precision inputs (GL 4.1 or ARB_vertex_attrib_64bit), having more components than provided leaves the extra components with undefined values.

关于c++ - 如何为 2D 和 3D 调整顶点着色器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27012092/

相关文章:

c++ - 堆栈上的 Const C 字符串?

c++ - 在 constexpr GLenum 数组中存储 OpenGL 颜色附件

python - 归一化倾斜的地球磁场

ios - Scenekit - SCNNode 的多次旋转和轴的方向

c++ - 使用 C++ 从 MAT 文件导入 3D 数组

c++ - 使用 c++/win32 的正常外观按钮

c++ - 在实际创建文件之前检查文件名是否有效

c++ - 为什么这个顶点缓冲对象更新失败?

java - 为什么所有 opengl 枚举都是十六进制的?

javascript - 在 Three.js CSSRenderer 中补偿浏览器缩放