@@ -0,0 +1,122 @@
#include "CameraClass.h"

#include "WindowFrameClass.h"
#include "InputClass.h"
#include "TimeClass.h"

Camera::Camera(float _screen_aspect,float _fov) {
near_z = 10.0f;
far_z = 1500.0f;
fov = _fov;
move_speed = 150.0f;
rotate_speed = 70.0f;

screen_aspect = _screen_aspect;

position.x = position.y = position.z = 0.0f;
position.z = -250.0f;
rotation.x = rotation.y = rotation.z = 0.0f;
}

//暂时用不上
Camera::~Camera()
{
}

void Camera::Update(float _screen_aspect, float _fov) {
screen_aspect = _screen_aspect;
fov = _fov;
m_UpdateViewToHomoMatrix4();
}

void Camera::Update() {
m_UpdateViewToHomoMatrix4();
}

void Camera::CameraControl() {
float delta_time = Time::GetDeltaTime();
if (Input::is_rbutton_up) {
Input::is_center_snapped = !Input::is_center_snapped;
ShowCursor(!Input::is_center_snapped);
if (Input::is_center_snapped) {
//重置鼠标的位置
Input::point_cursor_current = Input::point_cursor_last_frame = Input::point_cursor_center_snapped;
SetCursorPos(Input::point_cursor_center_snapped.x, Input::point_cursor_center_snapped.y);
}
}

if (Input::is_center_snapped) {
POINT pointCursorModify = { Input::point_cursor_current.x - Input::point_cursor_last_frame.x ,
Input::point_cursor_current.y - Input::point_cursor_last_frame.y };
Input::point_cursor_last_frame = Input::point_cursor_current;

//超出范围才重置位置
//范围为窗口的一半
//左移右移hack
if ((ABS(Input::point_cursor_current.x - Input::point_cursor_center_snapped.x) > (WindowFrame::rect_client.right >> 2)) ||
(ABS(Input::point_cursor_current.y - Input::point_cursor_center_snapped.y) > (WindowFrame::rect_client.bottom >> 2))) {
Input::point_cursor_current = Input::point_cursor_last_frame = Input::point_cursor_center_snapped;
SetCursorPos((int)Input::point_cursor_center_snapped.x, (int)Input::point_cursor_center_snapped.y);
}

//摄像头上下视角移动
rotation.x += (float)pointCursorModify.y / 15.0f;
//摄像头左右视角移动
rotation.y += (float)pointCursorModify.x / 15.0f;
}

if (Input::KeyPressed(VK_UP)) { rotation.x -= rotate_speed * delta_time; }
if (Input::KeyPressed(VK_DOWN)) { rotation.x += rotate_speed * delta_time; }
if (Input::KeyPressed(VK_LEFT)) { rotation.y -= rotate_speed * delta_time; }
if (Input::KeyPressed(VK_RIGHT)) { rotation.y += rotate_speed * delta_time; }

if (rotation.x < -90.0f) { rotation.x = -90.0f; }
if (rotation.x > 90.0f) { rotation.x = 90.0f; }
if (rotation.y < -180.0f) { rotation.y += 360.0f; }
if (rotation.y > 180.0f) { rotation.y -= 360.0f; }

//摄像机空间移动

if (Input::KeyPressed('W') || Input::KeyPressed('A') || Input::KeyPressed('S') || Input::KeyPressed('D') ||
Input::KeyPressed('Q') || Input::KeyPressed('E'))
{
Vector4 MovingDirection;
if (Input::KeyPressed('A')) { MovingDirection.x = -1.0f; }
if (Input::KeyPressed('D')) { MovingDirection.x = 1.0f; }
if (Input::KeyPressed('W')) { MovingDirection.z = 1.0f; }
if (Input::KeyPressed('S')) { MovingDirection.z = -1.0f; }
if (Input::KeyPressed('Q')) { MovingDirection.y = 1.0f; }
if (Input::KeyPressed('E')) { MovingDirection.y = -1.0f; }

MovingDirection = MovingDirection * (Matrix4('x', rotation.x) * Matrix4('y', rotation.y));
MovingDirection.VectorUnify();

position.x += MovingDirection.x*move_speed * delta_time;
position.y += MovingDirection.y*move_speed * delta_time;
position.z += MovingDirection.z*move_speed * delta_time;
}
}

void Camera::m_UpdateViewToHomoMatrix4() {
float l, r, t, b;

t = near_z*tanf(DEGREE(fov) / 2.0f);
b = -t;
r = t * screen_aspect;
l = -r;

view_to_homo.var[0][0] = (2 * near_z) / (r - l);
view_to_homo.var[1][1] = (2 * near_z) / (t - b);
//view_to_homo.var[2][0] = (l + r) / (l - r);
//view_to_homo.var[2][1] = (b + t) / (b - t);
view_to_homo.var[2][2] = (far_z) / (far_z - near_z);
view_to_homo.var[2][3] = 1.0f;
view_to_homo.var[3][2] = (near_z*far_z) / (near_z - far_z);
}

Matrix4 Camera::GetWorldToViewMatrix4()
{
Matrix4 WTV;
WTV = Matrix4('A', rotation) * Matrix4(position);
return WTV.Invert();
}
@@ -0,0 +1,55 @@
#ifndef RASTERIZER_CAMERACLASS_H
#define RASTERIZER_CAMERACLASS_H

#include "ProjectHeader.h"

class Camera {
//公有数据成员
public:
//坐标
Vector3 position;

//绕各个轴旋转的角度
//x -> pitch
//y -> yaw
//z -> roll
Vector3 rotation;

//最近的距离,最远显示的距离
float near_z, far_z;
//Field of View
float fov;

//屏幕高宽比
//根据画布分辨率设置
float screen_aspect;

//摄像机移动速度
float move_speed;
float rotate_speed;

//可以提前算出来
//仅受高宽比 和 FOV 的影响
Matrix4 view_to_homo;
private:
//摄像机坐标转换到齐次剪彩空间坐标
//仅在摄像机属性变化时重新生成
//不包括位置和旋转的变化
void m_UpdateViewToHomoMatrix4();
public:
//必须给出高宽比
Camera(float aspect, float fov);
~Camera();

//更新数据
//0代表不变
void Update(float aspect, float fov);
void Update();

void CameraControl();
//世界坐标转换到摄像机坐标
//即视口坐标
Matrix4 GetWorldToViewMatrix4();
};

#endif
@@ -0,0 +1,99 @@
#include "InputClass.h"

//static ³õʼ»¯
KeyPressedList Input::m_key_pressed = KeyPressedList();
POINT Input::point_cursor_center_snapped = POINT();
POINT Input::point_cursor_current = POINT();
POINT Input::point_cursor_last_frame = POINT();
bool Input::is_center_snapped = false;
bool Input::is_rbutton_up = false;
bool Input::is_lbutton_up = false;

Input::Input() {
m_hwnd = 0;
}


Input::~Input() {
m_hwnd = 0;
}

void Input::Initialize(HWND hWnd) {
m_hwnd = hWnd;
}

void Input::Press(int input) {
m_key_pressed.key[input] = true;
}

void Input::Press(char mouseButton) {
switch (mouseButton) {
case 'r':
case 'R':
m_key_pressed.right_mouse_button = true;
break;
case 'l':
case 'L':
m_key_pressed.left_mouse_button = true;
break;
default:
break;
}
}

void Input::Release(int input) {
m_key_pressed.key[input] = false;
}

void Input::Release(char mouseButton)
{
switch (mouseButton) {
case 'r':
case 'R':
m_key_pressed.right_mouse_button = false;
case 'l':
case 'L':
m_key_pressed.left_mouse_button = false;
default:
Release((int)mouseButton);
}
}

void Input::UpdateCursorCenterPostion(const RECT &rectRender)
{
point_cursor_center_snapped.x = rectRender.right / 2;
point_cursor_center_snapped.y = rectRender.bottom / 2;
ClientToScreen(m_hwnd, &point_cursor_center_snapped);
}

int Input::ReactToKeyPressed() {
//Èç¹û°´ÏÂESC
if (KeyPressed(VK_ESCAPE)) {
SendMessage(m_hwnd, WM_CLOSE, 0, 0);
}
return OK;
}

void Input::ClearFlag()
{
is_rbutton_up = is_lbutton_up = false;
}

inline bool Input::KeyPressed(int input) {
return m_key_pressed.key[input];
}

bool Input::KeyPressed(char mouseButton)
{
switch (mouseButton) {
case 'r':
case 'R':
return m_key_pressed.right_mouse_button;
case 'l':
case 'L':
return m_key_pressed.left_mouse_button;
default:
return KeyPressed((int)mouseButton);
}
return false;
}
@@ -0,0 +1,57 @@
#ifndef RASTERIZER_INPUTCLASS_H
#define RASTERIZER_INPUTCLASS_H

#include "ProjectHeader.h"

struct KeyPressedList {
//数组,记录按下的按键
bool key[512];
//鼠标左右键
bool right_mouse_button, left_mouse_button;

KeyPressedList() {
memset(key, false, 512 * sizeof(char));
right_mouse_button = left_mouse_button = false;
}
};

class Input {
private:
//数组,记录按下的按键
static KeyPressedList m_key_pressed;

HWND m_hwnd;
public:
///////////
// static //
//////////
//记录鼠标应当处于的坐标
static POINT point_cursor_center_snapped;
//记录鼠标当前的位置
static POINT point_cursor_current;
static POINT point_cursor_last_frame;
static bool is_center_snapped;
static bool is_rbutton_up;
static bool is_lbutton_up;
public:
Input();
~Input();

void Initialize(HWND);
void Press(int);
void Press(char);
void Release(int);
void Release(char);

//画布大小改变或
//窗口移动后调用
void UpdateCursorCenterPostion(const RECT &rect_of_client);
//根据已按下的按键做出反应
int ReactToKeyPressed();
void ClearFlag();

static bool KeyPressed(int);
static bool KeyPressed(char);
};

#endif
@@ -0,0 +1,32 @@
/*
最基本的光栅化渲染器代码
项目开始时间
2016/1/3
--Jeff
*/

#include "WindowFrameClass.h"

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPreinstance, LPSTR lpCmd, int nShowCmd) {
WindowFrame *mainWindow = new WindowFrame(RENDER_MODE_FILL);

//初始化
mainWindow->Initialize(800, 600);
//注册窗口
if (ERROR == mainWindow->RegisterCreateWindow(hInstance, hPreinstance, lpCmd, nShowCmd)) {
return ERROR;
}

//进行主循环
mainWindow->Run();

//关闭
mainWindow->Shutdown();

//善后处理
delete mainWindow;
mainWindow = NULL;

return OK;
}
@@ -0,0 +1,78 @@
#include "ObjectClass.h"
#include "WindowFrameClass.h"

#include <fstream>
using std::ifstream;
#include <string>
using std::string;

Object::Object() {
position.x = position.y = position.z = 0.0f;
rotation.x = rotation.y = rotation.z = 0.0f;
}

int Object::Initial(char *fileName,LPCWSTR texturename)
{
HBITMAP bmp_texture = (HBITMAP)LoadImage(NULL, texturename, IMAGE_BITMAP, 512, 512, LR_CREATEDIBSECTION | LR_DEFAULTSIZE | LR_LOADFROMFILE);
if (bmp_texture == NULL) {
return ERROR;
}
hdc_texture = CreateCompatibleDC(NULL);
SelectObject(hdc_texture, bmp_texture);

ifstream file(fileName);
if (!file.is_open()) {
file.close();
return ERROR;
}
float texture_coord_x = -1, texture_coord_y = -1, texture_coord_z = -1;
float vertice_x = -1, vertice_y = -1, vertice_z = -1;
int indice_x = -1, indice_y = -1, indice_z = -1;
int u = -1, v = -1, w = -1;

while (!file.eof()) {
string head;
file >> head;
//vertices and indices
if (head.size() == 1) {
switch (*(head.begin())) {
case 'v':
file >> vertice_x >> vertice_y >> vertice_z;
vertices.push_back(Vector3(vertice_x, vertice_y, vertice_z));
break;
case 'f':
file >> indice_x;
file.ignore(1, '/');
file >> u >> indice_y;
file.ignore(1, '/');
file >> v >> indice_z;
file.ignore(1, '/');
file >> w;
indices.push_back(Vector2<int>(indice_x - 1, u - 1));
indices.push_back(Vector2<int>(indice_y - 1, v - 1));
indices.push_back(Vector2<int>(indice_z - 1, w - 1));
break;
default:
file.ignore(100, '\n');
break;
}
}
//texture coord
else if (head.size() == 2) {
file >> texture_coord_x >> texture_coord_y >> texture_coord_z;
uv.push_back(Vector2<float>(texture_coord_x, texture_coord_y));
}
}
file.close();
return OK;
}

Object::Object(Vector3 _position) {
position = _position;
rotation.x = rotation.y = rotation.z = 0.0f;
}

Object::Object(Vector3 _position, Vector3 _rotation) {
position = _position;
rotation = _rotation;
}
@@ -0,0 +1,33 @@
#ifndef RASTERIZER_OBJECTCLASS_H
#define RASTERIZER_OBJECTCLASS_H

#include "ProjectHeader.h"

//目前一个Object就是一个三角形
class Object {
public:
//顶点的 x y z
vector<Vector3> vertices;
//顶点的 UV
vector<Vector2<float>> uv;
//每对索引 x -> 顶点, y -> UV
vector<Vector2<int>> indices;

HDC hdc_texture;

Vector3 position;
Vector3 rotation;
Vector3 scale;
public:
///////////////
// 构造函数 //
///////////////
Object();
int Initial(char*, LPCWSTR);
//给出Position
Object(Vector3);
//给出Pos 和 Rotation
Object(Vector3, Vector3);
};

#endif
@@ -0,0 +1,100 @@
/*
Just Include this single file in every other header
and everything will be just fine !
*/

/************************
项目通用规则定义:
坐标系:左手坐标系
世界坐标定义:
x轴:向右
y轴:向上
z轴:向屏幕里
旋转坐标定义:向主轴相反方向望去的顺时针方向为 正
x : Pitch
y : Yaw
z : Roll
物体基本元素:
三角形顶点缠绕方向:顺时针 为正面朝向
齐次剪裁空间:
范围 X,Y,Z ~ [-1, 1]
**********************/


#ifndef RASTERIZER_PROJECTHEADER_H
#define RASTERIZER_PROJECTHEADER_H

//#define DEBUG

/////////////////////
// System Header //
/////////////////////
#include "resource.h"
#include <Windows.h>
#include <assert.h>

//////////////////////////////
// STL and other Libraries //
/////////////////////////////
#include <array>
using std::array;
#include <queue>
using std::queue;
#include <vector>
using std::vector;

#include <string>
using std::wstring;
#include <sstream>
using std::wstringstream;
using std::endl;

#include <ctime>
using std::clock;
#include <cmath>
#include <memory>
using std::memset;

///////////////////
// User Header //
//////////////////
#include "Utility.h"


/////////////
// Macros //
/////////////

//角度转换
#define DEGREE(x) (0.01745f*(x))

//求绝对值(Absolute)
#define ABS(x) (((x) >= 0)?(x):-(x))

//#define ERROR 0
#define OK 1

//Default Color
#define COLOR_BLACK (RGB(0, 0, 0))
#define COLOR_WHITE (RGB(255, 255, 255))


//////////
// Flag //
/////////
#define FRAGMENT_MASK 0x00000001
#define FRAGMENT_GOOD 0x00000000
#define FRAGMENT_DELETED 0x00000001

//32位 int
//八位16进制数表示
//x
#define RENDER_MODE_OUTLINE 0x00000000
#define RENDER_MODE_FILL 0x00000001
#define RENDER_MODE_MASK 0x00000001

#endif
Binary file not shown.

Large diffs are not rendered by default.

@@ -0,0 +1,74 @@
#ifndef RASTERIZER_RENDERCLASS_H
#define RASTERIZER_RENDERCLASS_H

#include "ProjectHeader.h"

class Camera;
class Object;

class Render
{
private:
//当前程序的句柄
HWND *m_ptr_hwnd;
//屏幕的设备上下文
HDC m_hdc_screen;

//渲染缓冲区
HDC m_hdc_buffer;
//储存背景图案的画刷
HBRUSH m_brush_background;

//摄像机类
Camera *m_ptr_camera;

//私有函数
private:
float *m_z_depth_buffer;
void m_DrawObjects();
public:
Render();
~Render();

void Initialize(HWND*);
void DeleteResources();
void Shutdown();

//渲染一帧
void RenderAFrame();

//当窗口大小变化时
//重新设置画布大小以及相应资源
void UpdateSettings();

//////////////////////////////
// Canvas Draw Functions //
/////////////////////////////

//前后台缓存交换
void SwapBufferToScreen();

//清空画布
void ClearCanvas();

//输出文字
void OutputText(const wstring&, int linenumber);

//填充三角形
void FillTriangles(const vector<Fragment> &);
void FillTriangleTopFlat(Vector4 a, Vector2<float> uv_a, Vector4 b, Vector2<float> uv_b, Vector4 c, Vector2<float> uv_c,HDC);
void FillTriangleBottomFlat(Vector4 a, Vector2<float> uv_a, Vector4 b, Vector2<float> uv_b, Vector4 c, Vector2<float> uv_c,HDC);
//画三角形边框
void DrawTriangles(const vector<Fragment> &);
void DrawTriangle(const Vector4 p0, const Vector4 p1, const Vector4 p2, COLORREF);
//画线
void DrawLine(Vector2<float>, Vector2<float>, COLORREF);
//设置单个像素的颜色
void DrawPixel(int, int, COLORREF);

//模型数据
public:
vector<Object> vector_objects;
};

#endif
@@ -19,9 +19,9 @@
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{05712D68-54EC-4A3A-89D4-F945AB74F23E}</ProjectGuid>
<ProjectGuid>{9CCF6C37-5F2F-4724-8EC7-601927CA166D}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>TestUnit</RootNamespace>
<RootNamespace>RenderListTest</RootNamespace>
<WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
@@ -87,11 +87,11 @@
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
@@ -101,11 +101,11 @@
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
@@ -117,11 +117,11 @@
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
@@ -135,21 +135,36 @@
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<SDLCheck>true</SDLCheck>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="MathComplement.cpp" />
<ClCompile Include="CameraClass.cpp" />
<ClCompile Include="InputClass.cpp" />
<ClCompile Include="Main.cpp" />
<ClCompile Include="Utility.cpp" />
<ClCompile Include="ObjectClass.cpp" />
<ClCompile Include="RenderClass.cpp" />
<ClCompile Include="TimeClass.cpp" />
<ClCompile Include="WindowFrameClass.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="MathComplement.h" />
<ClInclude Include="CameraClass.h" />
<ClInclude Include="InputClass.h" />
<ClInclude Include="Utility.h" />
<ClInclude Include="ObjectClass.h" />
<ClInclude Include="ProjectHeader.h" />
<ClInclude Include="RenderClass.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="TimeClass.h" />
<ClInclude Include="WindowFrameClass.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="源文件">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="头文件">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="资源文件">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="CameraClass.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="InputClass.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Main.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="ObjectClass.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="RenderClass.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="TimeClass.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="WindowFrameClass.cpp">
<Filter>源文件</Filter>
</ClCompile>
<ClCompile Include="Utility.cpp">
<Filter>源文件</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="CameraClass.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="InputClass.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ObjectClass.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="ProjectHeader.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="RenderClass.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="resource.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="TimeClass.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="WindowFrameClass.h">
<Filter>头文件</Filter>
</ClInclude>
<ClInclude Include="Utility.h">
<Filter>头文件</Filter>
</ClInclude>
</ItemGroup>
</Project>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,46 @@
#include "TimeClass.h"

float Time::m_delta_time = 1.0f / 60;
int Time::m_queue_size = 60;
float Time::m_sum_of_queue = m_queue_size * m_delta_time;
wstring Time::m_fps_info = wstring();

inline void Time::m_Push(float gap)
{
m_sum_of_queue -= m_queue_delta_time.front();
m_queue_delta_time.pop();
m_sum_of_queue += gap;
m_queue_delta_time.push(gap);
}

Time::Time()
{
m_previous_clock = m_current_clock = 0.0f;

for (int lop = 0; lop < m_queue_size; lop++) {
m_queue_delta_time.push(m_delta_time);
}
}

void Time::ComputeTime()
{
m_current_clock = (float)clock();
m_delta_time = (m_current_clock - m_previous_clock) / CLK_TCK;
m_Push(m_delta_time);
m_previous_clock = m_current_clock;
}

float Time::GetDeltaTime()
{
return m_delta_time;
}

wstring Time::GetFPSwstring()
{
m_fps_info.clear();

wstringstream ws;
ws << TEXT("FPS : ") << (float)m_queue_size / m_sum_of_queue;
m_fps_info = ws.str();
return m_fps_info;
}
@@ -0,0 +1,38 @@
#ifndef RASTERIZER_TIMECLASS_H
#define RASTERIZER_TIMECLASS_H

#include "ProjectHeader.h"

class Time {
private:
queue<float> m_queue_delta_time;

//用于计算帧数的东西
float m_previous_clock;
float m_current_clock;

///////////
// static //
//////////
static wstring m_fps_info;
//上次渲染一帧后过去的时间
static float m_delta_time;
static int m_queue_size;
static float m_sum_of_queue;


void m_Push(float gap);

public:
Time();

//计算每帧的耗时
void ComputeTime();

static float GetDeltaTime();

//获得帧数的字符串信息
static wstring GetFPSwstring();
};

#endif

Large diffs are not rendered by default.

@@ -0,0 +1,317 @@
#ifndef RASTERIZER_MATHCLASS_H
#define RASTERIZER_MATHCLASS_H

/*
包含各种数学计算所需的函数等等
具体包括
二维向量
三维向量
向量之间的点积,叉积
向量之间的加法,减法
向量的归一化
三阶矩阵
四阶矩阵
以及矩阵之间的乘法,加法
矩阵的单位化
矩阵与数字的乘法
*/

#include "ProjectHeader.h"

///////////////
// 提前声明 //
//////////////

template < class T = float >
class Vector2;
class Vector3;
class Vector4;
class Matrix3;
class Matrix4;
typedef struct Fragment_TYPE Fragment;

///////////
// 函数 //
//////////

//交换
template <typename T>
void swap(T &a, T &b) {
T tmp = a;
a = b;
b = tmp;
}

//Clipping
//只要有一点落在外面,就不要
//同时进行背面剔除
void ClippingAndBackCull(vector<Fragment> &render_list);

//back face cull
bool TriangleBackcull(Fragment &fragment);

//tranform vertices from Homo to Screen
void HomoToScreenCoord(Vector4& vertex);



//////////////////////
// 数学类、结构体 //
/////////////////////

//存放一个将要渲染的三角形
typedef struct Fragment_TYPE {
int state;
HDC *texture;

//变换后的顶点
array<Vector4, 3> trans_vList;
//顶点的贴图坐标索引
//每个顶点有 2 个坐标信息
array<Vector2<float>, 3> uvList;
//该面的法向量
Vector3 n;

Fragment_TYPE(int _state, HDC *_texture) : state(_state), texture(_texture) {}

}Fragment;

template <class T>
class Vector2 {
public:
T x, y;

Vector2() {
x = y = 0;
}

Vector2(T all) {
x = y = all;
}

Vector2(T _x, T _y) {
x = _x;
y = _y;
}

Vector2(const Vector2& old) {
x = old.x;
y = old.y;
}

//template<class T>
Vector2<float> operator * (Vector2<float> &a, float &b) {
return Vector2<float>(a.x * b, a.y * b);
}
};

/*******************************
Vector 3
用于表示三维空间的点、旋转参数
*******************************/
class Vector3 {
public:
//
float x, y, z;

//构造函数
Vector3() :x(0), y(0), z(0) {}
Vector3(float _both) {
x = y = z = _both;
}
Vector3(float _x, float _y, float _z) :x(_x), y(_y), z(_z) {}
Vector3(const Vector3 &copy) {
x = copy.x;
y = copy.y;
z = copy.z;
}
~Vector3(){}

//向量的归一化
void VectorUnify();

//向量叉乘
Vector3 CrossProduct(const Vector3&);

//向量点乘
float DotProduct(const Vector3&);

//返回根据当前向量生成的平移矩阵
Matrix4 GetTransitonMatrix();


/////////////////////
//运算符重载部分 //
////////////////////

//3阶向量乘以3阶矩阵
Vector3 operator * (const Matrix3&);
//3阶向量乘以4阶矩阵
Vector4 operator * (const Matrix4&);

//加的运算符重载
Vector3 operator + (const Vector3&);
//减的运算符重载
Vector3 operator - (const Vector3&);

//输出流重载
friend wstringstream& operator << (wstringstream&, const Vector3&);
};


/****************
Vector 4
用于齐次剪彩空间的相应运算
*******************/

class Vector4 {
public:
//
float x, y, z, w;

//构造函数
Vector4() {
x = y = z = w = 0.0f;
}
Vector4(float _both) {
x = y = z = w = _both;
}
Vector4(float _x, float _y, float _z, float _w) {
x = _x;
y = _y;
z = _z;
w = _w;
}
Vector4(const Vector4 &copy) {
x = copy.x;
y = copy.y;
z = copy.z;
w = copy.w;
}

//点 或 向量 转换至齐次坐标系
Vector4(const Vector3& old, bool isVertex) {
x = old.x;
y = old.y;
z = old.z;
w = isVertex ? 1.0f : 0.0f;
}

~Vector4() {}

//齐次坐标系的变换
Vector4 operator* (const Matrix4& b);

void VectorUnify();

//输出流重载
friend wstringstream &operator << (wstringstream&, const Vector4&);
};


/*
矩阵
3 x 3
由于3阶矩阵在使用过程中不是很常见
所以暂不添加求逆矩阵等的"高级"功能
*/
class Matrix3 {
public:
float var[3][3];

Matrix3();
Matrix3(const Matrix3&);
~Matrix3() {}

void SetZero();


/////////////////////
//运算符重载部分 //
////////////////////

//重载乘法
Matrix3 operator * (const Matrix3&);
Matrix3 operator * (const float&);
};


/***************************
矩阵
4 x 4
***************************/

class Matrix4 {
public:
float var[4][4];

//常见的构造矩阵
Matrix4();
Matrix4(const Matrix4&);
~Matrix4() {}
void SetZero() {
memset(var, 0, 4 * 4 * sizeof(float));
}


/////////////////////////
// 特殊用处的构造矩阵 //
/////////////////////////

//创建对角线元素为给定数值的矩阵
//用于缩放
Matrix4(float);

//创建平移矩阵
Matrix4(const Vector3&);
Matrix4(float x, float y, float z);

//创建旋转矩阵
//旋转单位为 度数
//比如 正90 度
//绕单一轴的旋转
Matrix4(char axis, float degree);
//给定所有三个轴的旋转参数
Matrix4(char ThisUseless, const Vector3&);
Matrix4(char ThisUseless, float degreeX, float degreeY, float degreeZ);

//根据 缩放、旋转、平移 生成矩阵
Matrix4(float scale, Vector3 Rotation, Vector3 Position);

//矩阵相乘
Matrix4(Matrix4&, const Matrix4&);

////////////////以上是构造函数////////////////

//根据向量生成平移矩阵
void TransitionMatrix(const Vector3 &);

//求余子式
float Determinant(const Matrix3&);
//求逆矩阵
Matrix4 Invert();

////////////////
// static 函数 //
///////////////

//todo

/////////////////////
//运算符重载部分 //
////////////////////

//重载乘法
//矩阵 x 矩阵
Matrix4 operator * (const Matrix4&);
//矩阵 x 数字
Matrix4 operator * (const float&);

};

#endif
@@ -0,0 +1,181 @@
#include "WindowFrameClass.h"

#include "InputClass.h"
#include "RenderClass.h"
#include "TimeClass.h"

RECT WindowFrame::rect_client = RECT();
DWORD WindowFrame::STYLE_CHECKER = 0;

WindowFrame::WindowFrame(DWORD checker) {
STYLE_CHECKER = checker;

m_quit_software = false;
m_app_name = TEXT("Reasterizer");

AppHandler = this;
m_ptr_input = NULL;
m_ptr_renderer = NULL;
}

WindowFrame::~WindowFrame() {
Shutdown();
}

void WindowFrame::Initialize(int RENDER_X, int RENDER_Y) {
//设定初始渲染区域的大小
rect_client.top = 0; rect_client.left = 0; rect_client.bottom = RENDER_Y; rect_client.right = RENDER_X;
m_quit_software = false;

m_ptr_input = new Input();
m_ptr_time = new Time();
m_ptr_renderer = new Render();
}

void WindowFrame::Shutdown() {
if (m_ptr_renderer != nullptr) {
m_ptr_renderer->Shutdown();
delete m_ptr_renderer;
m_ptr_renderer = nullptr;
}

if(m_ptr_time != nullptr) {
delete m_ptr_time;
m_ptr_time = nullptr;
}

if (m_ptr_input != nullptr) {
delete m_ptr_input;
m_ptr_input = nullptr;
}
}

int WindowFrame::RegisterCreateWindow(HINSTANCE hInstance, HINSTANCE hPreinstance, LPSTR lpCmd, int nShowCmd) {
//获取桌面分辨率
//用于居中显示窗口
int m_WINDOW_X = GetSystemMetrics(SM_CXSCREEN);
int m_WINDOW_Y = GetSystemMetrics(SM_CYSCREEN);

//窗口注册相关
//不必太在意
WNDCLASSEX wnd = { 0 };
wnd.cbClsExtra = 0;
wnd.cbSize = sizeof(WNDCLASSEX);
wnd.cbWndExtra = 0;
wnd.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wnd.hCursor = LoadCursor(NULL, IDC_ARROW);
wnd.hIcon = NULL;
wnd.hIconSm = NULL;
wnd.hInstance = hInstance;
wnd.lpfnWndProc = CustomWinProc;
wnd.lpszClassName = m_app_name;
wnd.lpszMenuName = NULL;
wnd.style = CS_VREDRAW | CS_HREDRAW;

//注册窗口
RegisterClassEx(&wnd);
//居中显示窗口
m_hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, m_app_name, m_app_name,
WS_OVERLAPPEDWINDOW, (m_WINDOW_X - rect_client.right + rect_client.left) / 2, (m_WINDOW_Y - rect_client.bottom + rect_client.top) / 2,
rect_client.right , rect_client.bottom, NULL, NULL, hInstance, NULL);

if (!m_hwnd) {
return ERROR;
}
//从系统申请到窗口句柄后
//用它初始化各个类
//初始化主渲染类
m_ptr_renderer->Initialize(&m_hwnd);
//初始化输入类
m_ptr_input->Initialize(m_hwnd);


//显示窗口
ShowWindow(m_hwnd, nShowCmd);
UpdateWindow(m_hwnd);

return OK;
}

int WindowFrame::Run() {
MSG msg = { 0 };
//主要程序循环
while(!m_quit_software) {
//无消息时退出以下循环
while (1) {
if (!PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) break;
if (!GetMessage(&msg, NULL, 0, 0)) break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
m_ptr_time->ComputeTime();
GetCursorPos(&m_ptr_input->point_cursor_current);

//进行一帧渲染
m_ptr_renderer->RenderAFrame();

m_ptr_input->ClearFlag();

}
return msg.message;
}

//消息处理函数
LRESULT CALLBACK WindowFrame::WinProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch (Msg) {
case WM_SIZE:
//取得新屏幕的大小
rect_client.right = LOWORD(lParam);
rect_client.bottom = HIWORD(lParam);
rect_client.left = rect_client.top = 0;

//并更改画布的大小
m_ptr_renderer->UpdateSettings();
//重新设置鼠标的中心
m_ptr_input->UpdateCursorCenterPostion(rect_client);
break;
case WM_MOVE:
m_ptr_input->UpdateCursorCenterPostion(rect_client);
break;

//以下消息响应按键
case WM_LBUTTONDOWN:
m_ptr_input->Press('l');
break;
case WM_LBUTTONUP:
m_ptr_input->Release('l');
m_ptr_input->is_lbutton_up = true;
break;
case WM_RBUTTONDOWN:
m_ptr_input->Press('r');
break;
case WM_RBUTTONUP:
m_ptr_input->Release('r');
m_ptr_input->is_rbutton_up = true;
break;
case WM_KEYDOWN:
m_ptr_input->Press((int)wParam);
m_ptr_input->ReactToKeyPressed();
break;
case WM_KEYUP:
m_ptr_input->Release((int)wParam);
break;

//关闭程序
case WM_CLOSE:
case WM_DESTROY:
m_quit_software = true;
PostQuitMessage(0);
break;

default:
break;
}
return DefWindowProc(hWnd, Msg, wParam, lParam);
}

//无视
LRESULT CALLBACK CustomWinProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
return AppHandler->WinProc(hWnd, Msg, wParam, lParam);
}
@@ -0,0 +1,70 @@
#ifndef RASTERIZER_WINDOWFRAMECLASS_H
#define RASTERIZER_WINDOWFRAMECLASS_H

#define WIN32_LEAN_AND_MEAN
/*
类的功能:
创建具有窗口界面的程序
*/

#include "ProjectHeader.h"

class Render;
class Input;
class Time;

class WindowFrame {
public:
//程序句柄
HWND m_hwnd;
//渲染区域(客户坐标系)
//Rendering area(in client coordinate)
static RECT rect_client;

///////////
// FLAG //
///////////
//32 bit
//16 ^ 8 == 2^32 == long
//8 number each
//0x00000000L
static DWORD STYLE_CHECKER;
private:


//退出程序
bool m_quit_software;
//窗口名称
wchar_t *m_app_name;

//包含的类
//渲染类
Render *m_ptr_renderer;
//时间类
Time *m_ptr_time;
//记录当前按下的按键
Input *m_ptr_input;

public:
WindowFrame(DWORD checker = RENDER_MODE_FILL);
~WindowFrame();

//真正的消息处理函数
LRESULT CALLBACK WinProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);

//Initialize parameters
void Initialize(int,int);
void Shutdown();

//在系统中注册窗口
int RegisterCreateWindow(HINSTANCE hInstance, HINSTANCE hPreinstance, LPSTR lpCmd, int nShowCmd);

//主要的程序循环
int Run();
};

//骗Win的消息处理函数
LRESULT CALLBACK CustomWinProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
static WindowFrame *AppHandler = NULL;

#endif
Binary file not shown.

This file was deleted.

This file was deleted.

This file was deleted.