我用OpenGL创建了一个简单的2D区域,由平铺块组成。默认情况下,这些平铺块相对于屏幕的纵横比被拉伸。为了解决这个问题,我尝试使用一个正交投影矩阵。下面是我创建它的方法:
public void createProjectionMatrix() {
float left = 0;
float right = DisplayManager.getScreenWidth();
float top = 0;
float bottom = DisplayManager.getScreenHeight();
float near = 1;
float far = -1;
projectionMatrix.m00 = 2 / (r - l);
projectionMatrix.m11 = 2 / (t - b);
projectionMatrix.m22 = -2 / (f - n);
projectionMatrix.m30 = - (r + l) / (r - l);
projectionMatrix.m31 = - (t + b) / (t - b);
projectionMatrix.m32 = - (f + n) / (f - n);
projectionMatrix.m33 = 1;
}
问题可能就在这里,但我就是找不到。然后我在创建渲染器时调用这个方法,将其存储在一个统一变量中,并在顶点着色器中使用,如下所示:
vec4 worldPosition = transformationMatrix * vec4(position, 0, 1);
gl_Position = projectionMatrix * viewMatrix * worldPosition;
其中projectionMatrix是mat4,它对应于先前创建的正交投影矩阵。
现在除了清晰的颜色渲染外,什么都没有。
编辑:
在创建渲染器和着色器之后,将立即创建正交投影矩阵并将其加载到着色器中。
public Renderer() {
createOrthoMatrix();
terrainShader.start();
terrainShader.loadProjectionMatrix(projectionMatrix);
terrainShader.stop();
GL11.glEnable(GL13.GL_MULTISAMPLE);
GL11.glClearColor(0, 0, 0.5f, 1);
}
其余的矩阵在每次渲染时都使用loadUniforms()方法传入。
for(Terrain t : batch) {
loadUniforms(t, terrainManager, camera, lights);
GL11.glDrawElements(GL11.GL_TRIANGLES, model.getModel().getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
}
private void loadUniforms(Terrain t, TerrainManager tm, Camera camera, List<Light> lights) {
Matrix4f matrix = Maths.createTransformationMatrix(t.getPosition(), 0, 0, 0, 1);
terrainShader.loadTransformationMatrix(matrix);
terrainShader.loadViewMatrix(camera);
terrainShader.loadNumberOfRows(tm.getNumberOfRows());
terrainShader.loadOffset(t.getOffset());
terrainShader.loadLights(lights);
}
最后,顶点着色器如下所示:
# version 400 core
in vec2 position;
uniform mat4 transformationMatrix;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
void main(void) {
vec4 worldPosition = transformationMatrix * vec4(position, 0, 1);
gl_Position = projectionMatrix * viewMatrix * worldPosition;
}
2条答案
按热度按时间wyyhbhjk1#
这是一个漫长而艰巨的任务(如果我自己听起来不称职的话)。但我已经找到了解决我的问题的方法,可能有更好的方法来解决它,但这就是我如何做到的。
我将createProjectionMatrix()更改为
将m00和m11乘以一个大的数字是我能够看到除了清晰的颜色之外的任何东西的唯一方法。如果我没有记错的话,这是因为渲染器的渲染速度低于一个像素。这个想法是由@NicoSchertler提供给我的。所以非常感谢!着色器看起来是一样的,现在它运行得很好。如果有人有一个更少的盗版解决方案,请分享它。因为我会很高兴看到它是如何解决的。这里有一个对我很有帮助的链接,OpenGL 3+ with orthographic projection of directional light。
hsvhsicv2#
这将解决您的方面问题。试试看: