1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| #include <iostream> #include <Eigen/Core> #include <Eigen/Dense>
#define MY_PI 3.1415926 #define TWO_PI (2.0 * MY_PI) inline double DEG2RAD(double deg) { return deg * MY_PI / 180; }
Eigen:: Matrix4f get_view_matrix(Eigen:: Vector3f eye_pos) { Eigen:: Matrix4f view = Eigen:: Matrix4f:: Identity();
Eigen:: Matrix4f translate; translate << 1, 0, 0, -eye_pos[0],
0, 1, 0, -eye_pos[1], 0, 0, 1, -eye_pos[2], 0, 0, 0, 1;
view = view * translate;
return view; }
Eigen:: Matrix4f get_model_matrix(float angle) { Eigen:: Matrix4f rotation; angle = angle * MY_PI / 180.f; rotation << cos(angle), 0, sin(angle), 0,
0, 1, 0, 0, -sin(angle), 0, cos(angle), 0, 0, 0, 0, 1;
Eigen:: Matrix4f scale; scale << 1, 0, 0, 0,
0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;
Eigen:: Matrix4f translate; translate << 1, 0, 0, 0,
0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;
return translate * rotation * scale; }
Eigen:: Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio, float zNear, float zFar) { Eigen:: Matrix4f projection; float top = tan(DEG2RAD(eye_fov / 2.0f)) * abs(zNear); float right = top * aspect_ratio;
projection << zNear / right, 0, 0, 0,
0, zNear / top, 0, 0, 0, 0, (zNear + zFar) / (zNear - zFar), (2 * zNear * zFar) / (zNear - zFar), 0, 0, -1, 0;
return projection; }
Eigen:: Matrix4f get_viewport_matrix(float width, float height) { Eigen:: Matrix4f viewport; float half_width = width / 2.0; float half_height = height / 2.0;
viewport << half_width, 0, 0, half_width,
0, half_height, 0, half_height, 0, 0, 1, 0, 0, 0, 0, 1;
return viewport; }
int main() { Eigen:: Vector3f eye_pos = {0, 0, 10}; Eigen:: Vector4f p = {0, 0, 2, 1};
Eigen:: Matrix4f view = get_view_matrix(eye_pos); std::cout << "view: \n"
<< view << std::endl;
Eigen:: Matrix4f projection = get_projection_matrix(45.0, 1920.0 / 1080, 1, 50); std::cout << "projection: \n"
<< projection << std::endl;
Eigen:: Matrix4f viewport = get_viewport_matrix(1920.0, 1080); std::cout << "viewport: \n"
<< viewport << std::endl;
Eigen:: Vector4f ndc = projection * view * p; ndc = ndc / ndc[3]; std::cout << "ndc: \n"
<< ndc << std::endl;
Eigen:: Vector4f screen = viewport * ndc; std::cout << "screen: \n"
<< screen << std::endl;
return 0; }
|