I'm trying to set up a working camera in c++ with opengl - I want to implement it by myself, not using glm.
I was trying to find my error for long time now, tried much different approaches but it's not working like it should. vector&matrix are implemented in the framework I got at university (row-major).
I thought, setting the camera at +10 @z-axis and placing the object at the origin should at least show anything. But it's just a blue window. If i just load ViewMatrix*ModelMatrix to the vertex shader, I get a rectangle, which is fine.
I'm not sure if I understand near and far plane right - the values are regarding to the position of the camera, right ? So e.g. having the camera positioned at z=10, and having zn=2 & zf = 20, means that the planes are actually positioned on zn=8 and zf=-10, right ?
void Camera::calcProjMatrix() {
float s = 1.0f / (_alpha * tanf(_beta / 2.0f * M_PI / 180.0f ));
float frustum = _zf - _zn;
_projectionMatrix = matrix<float, 4, 4>(0);
_projectionMatrix._11 = s;
_projectionMatrix._22 = s * _alpha;
_projectionMatrix._33 = -(_zf + _zn) / frustum;
_projectionMatrix._34 = -(2 * _zf * _zn) / frustum;
_projectionMatrix._43 = -1;
}
void Camera::calcViewMatrix() {
vector<float, 3> zAxis = normalize(_pos - _target);
vector<float, 3> xAxis = normalize(cross(_up, zAxis));
vector<float, 3> yAxis = cross(zAxis, xAxis);
vector<float, 4> row1 = vector<float, 4>(xAxis.x, yAxis.x, zAxis.x, 0);
vector<float, 4> row2 = vector<float, 4>(xAxis.y, yAxis.y, zAxis.y, 0);
vector<float, 4> row3 = vector<float, 4>(xAxis.z, yAxis.z, zAxis.z, 0);
vector<float, 4> row4 = vector<float, 4>(-dot(xAxis, _pos), -dot(yAxis, _pos), -dot(zAxis, _pos), 1);
_viewMatrix = matrix<float, 4, 4>();
_viewMatrix = matrix<float, 4, 4>::from_rows(row1, row2, row3, row4);
}
I'm creating the camera with following parameters:
vector<float, 3> position = vector<float, 3>(0.1f, 0.1f, 10);
vector<float, 3> up = vector<float, 3>(0, 1, 0);
vector<float, 3> target = vector<float, 3>(0, 0, 0);
float beta = 45.0f;
float zn = 2.0f; float zf = 30.0f;
float alpha = 4.0f / 3.0f;
camera = Camera(position, up, target, alpha, beta, zn, zf);
render loop: (modelmatrix is Identity matrix)
matrix<float, 4, 4> mv = camera.getViewMatrix() * cube.getModelMatrix();
matrix<float, 4, 4> mvp = camera.getProjMatrix() * mv;
shader.loadMatrix4f("mvp", GL_TRUE, mvp._m);
vertex shader:
#version 410
layout(location=0) in vec3 position;
uniform mat4 mvp;
void main()
{
gl_Position = mvp * vec4(position, 1.0f);
}
Thanks for any help!