Computer graphics in Game development
Ivan Belyavtsev
23.10.2020
It’s possible to construct any image using the next operation:
\[y = ax+b\]
\[a = \frac{y_1 - y_2}{x_1 - x_2}\] \[b = y_1 - x_1\frac{y_1 - y_2}{x_1 - x_2}\]
\[y= y_1 + \frac{y_1 - y_2}{x_1 - x_2}(x - x_1)\]
slope = (y_begin - y_end)/(x_begin - x_end)
for x in range(x_begin, x_end):
    y = y_begin + slope*(x - x_begin)
    draw_point(x, round(y))[1]
Let’s implement it together
Let’s fix it
[2]
[3]
[4]
[3]
# - commentv - vertexvn - normalsvt - texture coordinatesf - face (polygon) - list of verteces, normals, and tex coordinates [5]## Object floor
v  -1.01  0.00   0.99
v   1.00  0.00   0.99
v   1.00  0.00  -1.04
v  -0.99  0.00  -1.04
g floor
usemtl floor
f -4 -3 -2 -1
## Object ceiling
v  -1.02  1.99   0.99  
v  -1.02  1.99  -1.04
v   1.00  1.99  -1.04
v   1.00  1.99   0.99
g ceiling
usemtl ceiling
f -4 -3 -2 -1Let’s skip reinventing the wheel
There are a lot of libraries to parse OBJ files
We will use tinyobjloader [6]
#define TINYOBJLOADER_IMPLEMENTATION // define this in only *one* .cc
#include "tiny_obj_loader.h"
std::string inputfile = "cornell_box.obj";
tinyobj::attrib_t attrib;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string warn;
std::string err;
bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, inputfile.c_str());
if (!warn.empty()) {
  std::cout << warn << std::endl;
}
if (!err.empty()) {
  std::cerr << err << std::endl;
}
if (!ret) {
  exit(1);
}
// Loop over shapes
for (size_t s = 0; s < shapes.size(); s++) {
  // Loop over faces(polygon)
  size_t index_offset = 0;
  for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
    int fv = shapes[s].mesh.num_face_vertices[f];
    // Loop over vertices in the face.
    for (size_t v = 0; v < fv; v++) {
      // access to vertex
      tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
      tinyobj::real_t vx = attrib.vertices[3*idx.vertex_index+0];
      tinyobj::real_t vy = attrib.vertices[3*idx.vertex_index+1];
      tinyobj::real_t vz = attrib.vertices[3*idx.vertex_index+2];
      tinyobj::real_t nx = attrib.normals[3*idx.normal_index+0];
      tinyobj::real_t ny = attrib.normals[3*idx.normal_index+1];
      tinyobj::real_t nz = attrib.normals[3*idx.normal_index+2];
      tinyobj::real_t tx = attrib.texcoords[2*idx.texcoord_index+0];
      tinyobj::real_t ty = attrib.texcoords[2*idx.texcoord_index+1];
      // Optional: vertex colors
      // tinyobj::real_t red = attrib.colors[3*idx.vertex_index+0];
      // tinyobj::real_t green = attrib.colors[3*idx.vertex_index+1];
      // tinyobj::real_t blue = attrib.colors[3*idx.vertex_index+2];
    }
    index_offset += fv;
    // per-face material
    shapes[s].mesh.material_ids[f];
  }
}[6]