使用CMake编译
配置文件
// CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(Rasterizer)
find_package(OpenCV REQUIRED)
set(CMAKE_CXX_STANDARD 17)
include_directories(/usr/local/include)
add_executable(Rasterizer main.cpp rasterizer.hpp rasterizer.cpp Triangle.hpp Triangle.cpp)
target_link_libraries(Rasterizer ${OpenCV_LIBRARIES})
编译步骤
$ mkdir build && cd build
$ cmake ..
$ make -j4
$ ./Rasterizer
$ ./Rasterizer -r 30 image.png
完成作业
描述
实现
constexpr double MY_PI = 3.1415926;
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 = translate * view;
return view;
}
Eigen::Matrix4f get_model_matrix(float rotation_angle)
{
Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
float angle = rotation_angle / 180.0 * MY_PI;
double sina = sin(angle),
cosa = cos(angle);
model << cosa, -sina, 0,
sina, cosa, 0,
0, 0, 1;
return model;
}
Eigen::Matrix4f get_projection_matrix(float eye_fov, float aspect_ratio,
float zNear, float zFar)
{
Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
Eigen::Matrix4f persp2ortho = Eigen::Matrix4f::Identity();
Eigen::Matrix4f orthoScale = Eigen::Matrix4f::Identity();
Eigen::Matrix4f orthoTrans = Eigen::Matrix4f::Identity();
Eigen::Matrix4f ortho = Eigen::Matrix4f::Identity();
float halfFov = eye_fov / (2 * 180.0) * MY_PI;
float t = zNear * tan(halfFov),
b = -t,
r = t * aspect_ratio,
l = -r;
persp2ortho << zNear, 0, 0, 0,
0, zNear, 0, 0,
0, 0, zNear + zFar, -zNear * zFar,
0, 0, 1, 0;
orthoScale << 2 / (r - l), 0, 0, 0,
0, 2 / (t - b), 0, 0,
0, 0, 2 / (zNear - zFar), 0,
0, 0, 0, 1;
orthoTrans << 1, 0, 0, -(r + l) / 2,
0, 1, 0, -(t + b) / 2,
0, 0, 1, -(zNear + zFar) / 2,
0, 0, 0, 0;
ortho = orthoScale * orthoTrans;
projection = ortho * persp2ortho;
return projection;
}
提高
Eigen::Matrix4f get_rotation(Vector3f axis, float angle)
{
Eigen::Matrix4f model = Eigen::Matrix4f::Identity();
angle = angle / 180.0 * MY_PI;
double sin_angle = sin(angle),
cos_angle = cos(angle);
double axis_x = axis.x(),
axis_y = axis.y(),
axis_z = axis.z();
model << axis_x * axis_x * (1 - cos_angle) + cos_angle, axis_y * axis_x * (1 - cos_angle) - axis_z * sin_angle, axis_z * axis_x * (1 - cos_angle) + axis_y * sin_angle, 0,
axis_x * axis_y * (1 - cos_angle) + axis_z * sin_angle, axis_y * axis_y * (1 - cos_angle) + cos_angle, axis_z * axis_y * (1 - cos_angle) - axis_x * sin_angle, 0,
axis_x * axis_z * (1 - cos_angle) - axis_y * sin_angle, axis_y * axis_z * (1 - cos_angle) + axis_x * sin_angle, axis_z * axis_z * (1 - cos_angle) + cos_angle, 0,
0, 0, 0, 1;
return model;
}
参考链接