1
0
Fork 0
2018-soft-3d-renderer/src/engine.cpp

160 lines
3.4 KiB
C++

#include "camera.h"
#include "color.h"
#include "engine.h"
#include "geometry.h"
#include "loader.h"
#include "matrix.h"
#include "transform.h"
#include "util.h"
#include <cstdio>
// GLOBALS
static Mesh mesh;
static Camera camera;
// PRIVATE PROTOTYPES
static void CheckInputs(uint32_t input);
// PUBLIC FUNCTIONS
int Engine_Init(Engine_Buffer &buffer, char *filename)
{
int result = LoadMesh(filename, mesh);
if (result < 0)
{
return -1;
}
mesh.position.z = 250;
camera.SetFOV(90.0f, buffer.width, buffer.height);
return 0;
}
void Engine_Render(Engine_Buffer &buffer, uint32_t input)
{
CheckInputs(input);
Matrix tTranslate = Transform_Translate(
mesh.position.x, mesh.position.y, mesh.position.z);
Matrix tRotate = Transform_Rotate(
mesh.rotation[0], mesh.rotation[1], mesh.rotation[2]);
Matrix tScale = Transform_Scale(
mesh.scale);
Matrix tView = Transform_View(
camera.position, camera.rotation);
Matrix tPersp = Transform_Perspective(
camera.xZoom, camera.yZoom, camera.nearClip, camera.farClip);
for (size_t v = 0; v < mesh.verts.size(); ++v)
{
mesh.vertsTransformed[v] =
mesh.verts[v] * tScale * tRotate * tTranslate * tView * tPersp;
mesh.vertsTransformed[v] =
mesh.vertsTransformed[v] / mesh.vertsTransformed[v].w;
}
Matrix tScreen = Transform_Screen(camera.xScale, camera.yScale);
for (size_t v = 0; v < mesh.verts.size(); ++v)
{
mesh.vertsTransformed[v] = mesh.vertsTransformed[v] * tScreen;
}
for(size_t f = 0; f < mesh.faces.size(); ++f)
{
unsigned int v0 = mesh.faces[f].vertIndex[0];
unsigned int v1 = mesh.faces[f].vertIndex[1];
unsigned int v2 = mesh.faces[f].vertIndex[2];
ColorU32 white = {0xff,0xff,0xff,0xff};
FillTriangle(
buffer.pixels, buffer.width, white.u32,
mesh.vertsTransformed[v0].x, mesh.vertsTransformed[v0].y,
mesh.vertsTransformed[v1].x, mesh.vertsTransformed[v1].y,
mesh.vertsTransformed[v2].x, mesh.vertsTransformed[v2].y);
}
}
void Engine_Shutdown(void)
{
}
// PRIVATE FUNCTIONS
static void CheckInputs(uint32_t input)
{
if (CHECK_BIT(input, TRANSLATE_X_POS))
{
mesh.position.x += 10;
}
else if (CHECK_BIT(input, TRANSLATE_X_NEG))
{
mesh.position.x -= 10;
}
if (CHECK_BIT(input, TRANSLATE_Z_POS))
{
mesh.position.z += 10;
}
else if (CHECK_BIT(input, TRANSLATE_Z_NEG))
{
mesh.position.z -= 10;
}
if (CHECK_BIT(input, TRANSLATE_Y_POS))
{
mesh.position.y += 10;
}
else if (CHECK_BIT(input, TRANSLATE_Y_NEG))
{
mesh.position.y -= 10;
}
if (CHECK_BIT(input, ROTATE_X_POS))
{
mesh.rotation[0] += .10;
}
else if (CHECK_BIT(input, ROTATE_X_NEG))
{
mesh.rotation[0] -= .10;
}
if (CHECK_BIT(input, ROTATE_Z_POS))
{
mesh.rotation[1] += .10;
}
else if (CHECK_BIT(input, ROTATE_Z_NEG))
{
mesh.rotation[1] -= .10;
}
if (CHECK_BIT(input, ROTATE_Y_POS))
{
mesh.rotation[2] += .10;
}
else if (CHECK_BIT(input, ROTATE_Y_NEG))
{
mesh.rotation[2] -= .10;
}
if (CHECK_BIT(input, SCALE_UP))
{
mesh.scale += 0.1f;
}
else if (CHECK_BIT(input, SCALE_DOWN))
{
mesh.scale -= 0.1f;
}
}