From 6ff09dc375ad6cec157806a37d95318598919111 Mon Sep 17 00:00:00 2001 From: David Allemang Date: Tue, 13 Oct 2020 10:57:30 -0400 Subject: [PATCH] Introduce perspective projection matrix. Also correct a bug where the view matrix was not being used. --- vis/include/geometry.hpp | 26 ++++++++++++++++++++++++-- vis/include/rendering.hpp | 7 +++++-- vis/shaders/slice/slice.gm.glsl | 2 +- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/vis/include/geometry.hpp b/vis/include/geometry.hpp index a4ced1c..b164722 100644 --- a/vis/include/geometry.hpp +++ b/vis/include/geometry.hpp @@ -27,8 +27,8 @@ using mat3 = mat<3>; using mat4 = mat<4>; using mat5 = mat<5>; -mat4 ortho(float left, float right, float bottom, float top, float front, float back) { - mat<4> res = mat4(); +mat4 orthographic(float left, float right, float bottom, float top, float front, float back) { + mat4 res = mat4(); res << 2 / (right - left), 0, 0, -(right + left) / (right - left), 0, 2 / (top - bottom), 0, -(top + bottom) / (top - bottom), @@ -36,3 +36,25 @@ mat4 ortho(float left, float right, float bottom, float top, float front, float 0, 0, 0, 1; return res; } + +mat4 perspective(float fovy, float aspect, float zNear, float zFar) { + float tanHalfFovy(std::tan(fovy / 2)); + + mat4 res = mat4::Identity(); + res(0, 0) = 1 / (aspect * tanHalfFovy); + res(1, 1) = 1 / (tanHalfFovy); + res(2, 2) = -(zFar + zNear) / (zFar - zNear); + res(3, 2) = -1; + res(2, 3) = -(2 + zFar * zNear) / (zFar - zNear); + return res; +} + +mat4 translation(float x, float y, float z) { + mat4 res = mat4(); + res << + 1, 0, 0, x, + 0, 1, 0, y, + 0, 0, 1, z, + 0, 0, 0, 1; + return res; +} diff --git a/vis/include/rendering.hpp b/vis/include/rendering.hpp index 9fe87d4..9f40ccf 100644 --- a/vis/include/rendering.hpp +++ b/vis/include/rendering.hpp @@ -19,9 +19,12 @@ struct Matrices { auto aspect = (float) screen.width() / (float) screen.height(); auto pheight = 1.4f; auto pwidth = aspect * pheight; - mat4 proj = ortho(-pwidth, pwidth, -pheight, pheight, -10.0f, 10.0f); +// auto proj = orthographic(-pwidth, pwidth, -pheight, pheight, -10.0f, 10.0f); +// auto proj = perspective(-pwidth, pwidth, pheight, -pheight, 10.0f, 0.01f); + auto proj = perspective(0.4, aspect, 0.1, 10.0); + + auto view = translation(0, 0, -4); - auto view = mat4::Identity(); return Matrices(proj, view); } }; diff --git a/vis/shaders/slice/slice.gm.glsl b/vis/shaders/slice/slice.gm.glsl index 08f094d..2ffe579 100644 --- a/vis/shaders/slice/slice.gm.glsl +++ b/vis/shaders/slice/slice.gm.glsl @@ -30,7 +30,7 @@ float unmix(float u, float v) { void emit(vec4 v) { pos = v; col = vCol[0]; - gl_Position = proj * vec4(v.xyz, 1); + gl_Position = proj * view * vec4(v.xyz, 1); EmitVertex(); }