Browse Source

Cleaned up every file and added comments.

angel 7 years ago
parent
commit
ca37a66b68

+ 0 - 18
include/bound3.h

@@ -1,18 +0,0 @@
-#ifndef BOUND3_H
-#define BOUND3_H
-
-#include "vector3.h"
-
-//Struct containing vertex data for a tight bounding box around a model.
-//Primarily for use in frustum culling
-struct Bound3{
-    float mMinX = 0.0;
-    float mMinY = 0.0;
-    float mMinZ = 0.0;
-
-    float mMaxX = 0.0;
-    float mMaxY = 0.0;
-    float mMaxZ = 0.0;
-};
-
-#endif

+ 7 - 1
include/buffer.h

@@ -4,6 +4,9 @@
 #include "SDL.h"
 #include <type_traits>
 
+//Templated struct to emulate GPU buffers such as 
+//the frame buffer and the ZBuffer along with others
+//Also keeps track of a bunch of useful data about itself
 template<class T>
 struct Buffer{
         int mWidth;
@@ -20,10 +23,14 @@ struct Buffer{
         : mWidth(w), mHeight(h), mPixelCount(w*h),
                 mPitch(w*sizeof(T)), buffer(array) 
         {}
+
         ~Buffer(){
                 delete [] buffer;
         };
         
+        //Cannot use memset to clear a float since the binary
+        //Representation is more complex. We just iterate through the whole
+        //thing and explicitely set it to zero instead
         void clear(){
                 if(std::is_same<T,float>::value){
                         for(int i = 0; i < mPixelCount;++i){
@@ -34,7 +41,6 @@ struct Buffer{
                         memset(buffer,0, mPitch*mHeight);       
                 }
         }
-        
 };
 
 #endif

+ 7 - 5
include/camera.h

@@ -8,18 +8,20 @@
 struct Camera{
     Camera();
 
+    //In the future user input should control this. For now just simple movement
     void update();
 
-    //Position and direction of camera
+    Matrix4 viewMatrix;
+    Matrix4 projectionMatrix;
+
+    //Position and direction of camera, used to build view matrix
     Vector3 position{0,0,8};
     Vector3 target{0,0,0};
     Vector3 up{0,1,0};
 
-    //Matrices and frustrum stuff
-    Matrix4 viewMatrix;
-    Matrix4 projectionMatrix;
+    //Variables that determine frustrum (Future class?)
+    //Used to build projection matrix
     float fov{90};
-    //Given in positive values but changed to negative in the matrix
     float near{0.1};
     float far{100};
     float aspectRatio{1.0};

+ 5 - 3
include/displayManager.h

@@ -13,9 +13,10 @@
 class DisplayManager{
 
     public:
-        const static int SCREEN_WIDTH  = 1280; //640
-        const static int SCREEN_HEIGHT = 960; //480
+        const static int SCREEN_WIDTH  = 640; //640 1280
+        const static int SCREEN_HEIGHT = 480; //480 720
         const static int SCREEN_PITCH  = SCREEN_HEIGHT*sizeof(Uint32);
+        constexpr static float SCREEN_ASPECT_RATIO = SCREEN_WIDTH /(float)SCREEN_HEIGHT;
 
         //Dummy Constructor / Destructor
         DisplayManager();
@@ -25,13 +26,14 @@ class DisplayManager{
         bool startUp();
         void shutDown();
 
-        //Clear screens to black
+        //Clear screens to draw color (Normally black)
         void clear();
 
         //Swaps the pixel buffer with the texture buffer and draws to screen
         void swapBuffers(Buffer<Uint32> *pixelBuffer);
 
     private:
+        //Wrappers for SDL init functions
         bool startSDL();
         bool createWindow();
         bool createSDLRenderer();

+ 6 - 4
include/inputManager.h

@@ -7,16 +7,18 @@
 class InputManager{
 
     public:
+        //Dummy constructors / Destructors
+        //Not necessary here, but follow the same format for consistency
         InputManager();
-
         ~InputManager();
 
         bool startUp();
-
-        bool processInput();
-
         void shutDown();
 
+        //Processes all the SDL events that have ocurred in the given frame
+        //For now only listens to the SDL_QUIT event that signifies the window was 
+        //closed.
+        bool processInput();
     private:
         bool handleEvent(SDL_Event * event);
 };

+ 21 - 16
include/matrix.h

@@ -4,6 +4,7 @@
 #include <array>
 #include <vector3.h>
 
+//Data struct holding all of the data you need to make a transform matrix
 struct TransformParameters{
     TransformParameters() :scaling(Vector3(1,1,1)) {};
     Vector3 translation;
@@ -11,36 +12,40 @@ struct TransformParameters{
     Vector3 scaling;
 };
 
+//Matrices are stored in memory in row major order, but operations are done as if it was
+//Column major. 
 class Matrix4{
     public:
+        //Operators
         float& operator()(size_t y, size_t x){
             return mMatrix[y*4 + x];
         }
         Matrix4 operator* (Matrix4 &rhs);
-
-        Vector3 matMultVec(Vector3 &vec);
+        Vector3 matMultVec(Vector3 &vec); 
         
-        void printMat();
-
-        //Probably should be their own classes or constructors in the future
+        //Named constructor idiom to build the basic matrices we need for 
+        //transformation.
         Matrix4 static makeTestMat();
-        Matrix4 static makeFullRotMat(float alpha, float beta, float gamma);
-        Matrix4 static makeScaleMat(float scaleX, float scaleY, float scaleZ);
-        Matrix4 static makeTranslateMat(float dx, float dy, float dz);
+        Matrix4 static unitMatrix(); 
+        
+        //Uses ZYX convention for rotation
+        Matrix4 static fullRotMat(float alpha, float beta, float gamma);
+        Matrix4 static scaleMat(float scaleX, float scaleY, float scaleZ);
+        Matrix4 static translateMat(float dx, float dy, float dz);
+        Matrix4(){};
 
-        //Builds a matrix that rotates, scales and translates all in one
+        //Builds a matrix that scales, rotates and translates all at once
         Matrix4 static transformMatrix(TransformParameters transform);
 
-        //Camera transformation matrix (the world from the camera's eyes)
+        //Inverse Camera transformation matrix (the world from the camera's eyes)
         Matrix4 static lookAt(Vector3& position, Vector3& target, Vector3& temp);
 
-        //2D to 3D projection matrix
-        Matrix4 static makeProjectionMatrix(float fov, float AR, float near, float far);
-
-        Matrix4 static unitMatrix();
-
-        Matrix4(){};
+        //3D projection matrix. When applied results in the camera frustrum area being 
+        //defined as X[-1,1] Y[-1,1] Z[1,0] 
+        Matrix4 static projectionMatrix(float fov, float AR, float near, float far);
 
+        //Debug stuff
+        void print();
     private:
         std::array<float, 16> mMatrix{};
 };

+ 15 - 1
include/mesh.h

@@ -4,10 +4,11 @@
 #include "vector3.h"
 #include <vector>
 
+//Struct containing information relevant to the renderer about the vertices, normals and
+//texture coordinates of a model. Also keeps track of useful stuff for iterations.
 struct Mesh{
     int numVertices = 0;
     std::vector<Vector3> vertices;
-
     std::vector<Vector3> normals;
 
     int numFaces = 0;
@@ -15,7 +16,20 @@ struct Mesh{
     std::vector<Vector3> textureIndices;
     std::vector<Vector3> normalsIndices;
 
+    //Simple mesh description for debugging.
     void describeMesh();
 };
 
+//Struct containing vertex data for a tight bounding box around a model.
+//Primarily for use in frustum culling
+struct Bound3{
+    float mMinX = 0.0;
+    float mMinY = 0.0;
+    float mMinZ = 0.0;
+
+    float mMaxX = 0.0;
+    float mMaxY = 0.0;
+    float mMaxZ = 0.0;
+};
+
 #endif

+ 9 - 6
include/model.h

@@ -1,23 +1,26 @@
 #ifndef MODEL_H
 #define MODEL_H
 
+#include <string>
 #include "mesh.h"
-#include "string"
-#include "bound3.h"
 #include "matrix.h"
 #include "objParser.h"
 
 class Model{
     public:
-        Model(std::string path); 
-        void describeMesh();
+        Model(std::string path, TransformParameters &initParameters); 
 
         Mesh *getMesh();
-        
-        void initPosition(TransformParameters initPos);
+
         void update();
 
+        //Prints the mesh vertices for debugging
+        void describeMesh();
     private:
+        //Transform matrix from object space to worldSpace
+        void initPosition(TransformParameters initPos);
+
+        //Calculates the boundary box of the mesh in object space
         void buildBoundaryBox();
         Mesh mMesh;
         Bound3 mBounds;

+ 6 - 3
include/objParser.h

@@ -5,16 +5,19 @@
 #include <sstream>
 #include "mesh.h"
 
+//Just a namespace for functions related to loading data from wavefront OBJ files
 namespace OBJ{
+    //Assumes that the path given is valid
     Mesh& buildMeshFromFile(Mesh &mesh, std::string &path);
 
+    //Checks if the path actually contains a valid file
     bool fileExists(std::string &path);
 
-    //Get vertices and Normal data
+    //Get vertices, normals and all index data into the mesh object
     void loadFileData(Mesh &mesh, std::ifstream &file);
 
-    std::vector<std::string> split(std::string &str, char delim);
-
+    //Simple string splitting method using a single char delimeter
+    std::vector<std::string> splitStr(std::string &str, char delim);
 }
 
 #endif

+ 20 - 12
include/rasterizer.h

@@ -6,29 +6,37 @@
 #include "vector3.h"
 #include "shader.h"
 
+//Takes in vertex data, rasterizes the surface and applies the fragment shader at
+//each fragment. If it passes the depth test the fragment is written to the pixel buffer.
 class Rasterizer{
-
     public:
-        static void drawTriangles(Vector3 *vertices, IShader &shader, Buffer<Uint32> *pixelBuffer, Buffer<float> *zBuffer);
-
-        static void drawWireFrame(Vector3 *vertices, IShader &shader, Buffer<Uint32> *pixelBuffer);
-
-        static void testPattern(Buffer<Uint32> *pixelBuffer);
-
+        //Simple full screen effects that don't need any vertex data
         static void makeCoolPattern(Buffer<Uint32> *pixelBuffer);
+        static void testPattern(Buffer<Uint32> *pixelBuffer);
 
+        //Bresenham's line drawing algorithm using only int arithmetic
         static void drawLine(Vector3 &vertex1, Vector3 &vertex2, const Uint32 &color, Buffer<Uint32> *pixelBuffer);
 
-        static void screenSpaceTransform(Buffer<Uint32> *pixelBuffer, Vector3 *vertices,std::array<int, 3>   &xV,std::array<int, 3>   &yV, Vector3  &zV);
+        //Draws wireframe rendering of triangle by calling the line drawer for each
+        //Line in a triangle.(AB, BC, AC)
+        static void drawWireFrame(Vector3 *vertices, IShader &shader, Buffer<Uint32> *pixelBuffer);
+
+        //Proper triangle rasterization with vertex interpolation.
+        static void drawTriangles(Vector3 *vertices, IShader &shader, Buffer<Uint32> *pixelBuffer, Buffer<float> *zBuffer);
+
+        //Transforms coordinates from NDC to pixel values(Integers)
+        static void viewportTransform(Buffer<Uint32> *pixelBuffer, Vector3 *vertices,std::array<int, 3>   &xV,std::array<int, 3>   &yV, Vector3  &zV);
 
-        //Don't look at my ugly code!
-        static void baricentric(Vector3 &lambdas, float InvArea, int x, int y,
+        //Given a set of vertex values, the triangle area in screen space
+        //and a target point returns the barycentric coordinates calculated using
+        //Edge functions
+        static void barycentric(Vector3 &lambdas, float InvArea, int x, int y,
                          std::array<int, 3>   &xV, std::array<int, 3>   &yV);
 
     private:
-        Rasterizer(){};
+        Rasterizer(){}; //Ensuring an object can never be instanced accidentally
 
-        //Setting this equal to the same pixel format our textures are in
+        //Setting this equal to the same pixel format our screen texture is in
         static const Uint32 PIXEL_FORMAT = SDL_PIXELFORMAT_RGBA8888;
         static const SDL_PixelFormat* mappingFormat;
 

+ 3 - 2
include/renderManager.h

@@ -16,12 +16,12 @@ class RenderManager{
         RenderManager();
         ~RenderManager();
 
-        //Gets scene and display info to 
+        //Gets scene and display info. Will be used to build render Queue
         bool startUp(DisplayManager &displayManager,SceneManager &sceneManager );
         void shutDown();
 
         //Performs all high level prep operations that the graphics library
-        //Needs to do before acting
+        //Needs to do before drawin each model in the scene.
         void render();
 
     private:
@@ -31,6 +31,7 @@ class RenderManager{
         //This is a pointer to a pointer to allow for scene switching 
         SceneManager   * sceneLocator;
         DisplayManager * screen;
+
         SoftwareRenderer renderInstance;
         std::queue<Mesh*> renderQueue;        
 };

+ 11 - 4
include/scene.h

@@ -2,23 +2,31 @@
 #define SCENE_H
 
 #include <string>
+#include <vector>
 #include "model.h"
 #include "camera.h"
-#include <vector>
 
+//Keeps track of all the lights, models and cameras contained in a current
+//scene. Also performs frustrumc ulling to determine what objects to send to
+//the render queue visibility.
 class Scene{
     public:
-        //Builds a scene based on a path containing the scene's content
+        //Builds a scene based on a path to the folder containing the scene's
+        //content
         Scene(std::string path);
         ~Scene();
 
-        //Updates all objects and cameras in scene
+        //Updates all models, lights and cameras in scene
         void update();
 
+        //Returns the list of models not culled by the frustrum
         std::vector<Model*>* getVisiblemodels();
 
         Camera * getCurrentCamera();
 
+        //Used in the scene loading check to determine if models were loaded 
+        //correctly. It sends this info upstream to the scene manager to abort
+        //the load procedure.
         bool checkIfEmpty();
     private:
         Camera mainCamera;
@@ -30,7 +38,6 @@ class Scene{
         //Contains the models that remain after frustrum culling
         std::vector<Model*> visibleModels;
         
-        //Initializes all modelsin the scene
         bool loadSceneModels(std::string &path);
 
         //Cull objects that should not be visible and add the visible to the 

+ 1 - 1
include/sceneManager.h

@@ -21,8 +21,8 @@ class SceneManager{
         // Update current scene
         void update();
 
+        //Called by the rendermanager to prep the render queue 
         Scene* getCurrentScene();
-
     private:
         bool loadScene();
         bool closeScene();

+ 7 - 6
include/shader.h

@@ -6,42 +6,43 @@
 #include "rasterizer.h"
 #include <array>
 
+//Shader Interface for a class that emulates modern GPU fragment and vertex shaders
 struct IShader {
     virtual ~IShader() {};
     virtual Vector3 vertex(Vector3 &vertex, Matrix4 &MVP, Vector3 &normals, Vector3 &light, int i) = 0;
     virtual bool fragment(Vector3 &bari, Vector3 &color, float &depth, Vector3 &zVerts) = 0;
 };
 
+//Simplest shader. Calculates light intensity per triangle.
 struct FlatShader : public IShader {
     float varIntensity;
     Vector3 rgb{255,255,255};
 
-     Vector3 vertex(Vector3 &vertex, Matrix4 &MVP, Vector3 &normals, Vector3 &light, int index) override{
+    Vector3 vertex(Vector3 &vertex, Matrix4 &MVP, Vector3 &normals, Vector3 &light, int index) override{
         varIntensity = std::max(0.0f,normals.dotProduct(light));
-        return MVP.matMultVec(vertex);
+        return MVP.matMultVec(vertex); //Transforms verts into projected space
     }
 
-     bool fragment(Vector3 &bari, Vector3 &color, float &depth, Vector3 &zVerts) override{
+    bool fragment(Vector3 &bari, Vector3 &color, float &depth, Vector3 &zVerts) override{
         depth = bari.dotProduct(zVerts);
         color = rgb*varIntensity;
-        //color.print();
         return false;
     }
 
 };
 
+//More Complex shader that calculates a per-vertex intensity and interpolates 
+//through the fragments of the triangle
 struct GouraudShader : public IShader {
     Vector3 varying_intensity;
     Vector3 rgb{255,255,255};
 
     Vector3 vertex(Vector3 &vertex, Matrix4 &MVP, Vector3 &normals, Vector3 &light, int index) override{
-        //normals.print();
         varying_intensity.data[index] = std::max(0.0f, normals.dotProduct(light));
         return MVP.matMultVec(vertex);
     }
 
     bool fragment(Vector3 &bari, Vector3 &color, float &depth, Vector3 &zVerts) override{
-        //varying_intensity.print();
         float intensity = bari.y*varying_intensity.x + bari.z*varying_intensity.y + bari.x*varying_intensity.z;
         color = rgb * intensity;
         depth = bari.dotProduct(zVerts);

+ 4 - 4
include/softwareRenderer.h

@@ -17,16 +17,17 @@ class SoftwareRenderer {
         bool startUp(int w, int h);  
         void shutDown();      
 
-        //This could be expanded with more methods
-        // to draw different types of meshes or models
+        //Draws mesh assuming it is made of triangular primites
+        //1.-Gets pointers to render data form mesh
+        //2.-Builds MVP 
         void drawTriangularMesh(Mesh * triMesh);
 
         void clearBuffers();
 
+        //Returns pixel buffer
         Buffer<Uint32>* getRenderTarget();
 
         void setCameraToRenderFrom(Camera * camera);
-        
     private:
         //Buffer methods
         bool createBuffers(int w, int h);
@@ -37,7 +38,6 @@ class SoftwareRenderer {
         //Culling methods
         bool backFaceCulling(Vector3 *trianglePrim);
 
-        
         //Pointer to the scene's target camera
         Camera * mCamera;
         bool startUpComplete = false;

+ 15 - 24
include/vector3.h

@@ -3,8 +3,13 @@
 
 #include <string>
 
+//Basic 3D vector class for general calculations
+//Should probably be made a template at some point 
 struct Vector3{
+    //I know this is undefined behaviour and really not recommended but
+    //Using an operator overload for looping was slowing down my program 20%
     union {
+            //Anonymous struct and array union hack
             float data[3];
             struct {
                 float x;
@@ -13,37 +18,23 @@ struct Vector3{
             };
         };
     
-    Vector3(float x1, float y1, float z1) : x(x1), y(y1), z(z1)
-    {}
+    Vector3(float x1, float y1, float z1) : x(x1), y(y1), z(z1) {};
+    Vector3(): x(0.0f), y(0.0f), z(0.0f) {};
 
-    Vector3(): x(0.0f), y(0.0f), z(0.0f)
-    {};
-
-
-    //Negate components of vector
-    Vector3 &operator-();
+    //Scalar operations
+    Vector3 &operator-(); //Negate components of vector
+    Vector3 operator*(float rhs); //Scalar vector multiplication
 
+    //Vector operations
     Vector3 operator-(Vector3 &rhs);
-
     Vector3 operator+(Vector3 &rhs);
-
-    Vector3 operator*(float rhs);
-
-    //Accessing components using array notation for looping
-    //float &operator[](int i);
-
-    Vector3 &normalized();
-
-    float length();
-
     Vector3 crossProduct(Vector3 &rhs);
-
+    Vector3 &normalized();
     float   dotProduct(Vector3 &rhs);
-
-
-
+    float length();
+    
+    //Print for debugging purposes
     void print();
-
 };
 
 #endif

BIN
models/.elephant.obj.swp


+ 2 - 2
src/camera.cpp

@@ -4,8 +4,8 @@
 
 Camera::Camera(){
     viewMatrix = Matrix4::lookAt(position,target,up);
-    aspectRatio =  DisplayManager::SCREEN_WIDTH/(float)DisplayManager::SCREEN_HEIGHT;
-    projectionMatrix = Matrix4::makeProjectionMatrix(fov, aspectRatio, near,far);
+    aspectRatio =  DisplayManager::SCREEN_ASPECT_RATIO;
+    projectionMatrix = Matrix4::projectionMatrix(fov, aspectRatio, near,far);
 }
 
 void Camera::update(){

+ 3 - 7
src/displayManager.cpp

@@ -1,12 +1,8 @@
 #include "displayManager.h"
 
-DisplayManager::DisplayManager(){
-    
-}
-
-DisplayManager::~DisplayManager(){
-    
-}
+//Dummy constructurs/destructors
+DisplayManager::DisplayManager(){}
+DisplayManager::~DisplayManager(){}
 
 bool DisplayManager::startUp(){
     bool success = true;

+ 6 - 8
src/engine.cpp

@@ -1,10 +1,8 @@
 #include "engine.h"
 
-Engine::Engine(){
-}
-
-Engine::~Engine(){
-}
+//Dummy constructors and destructors
+Engine::Engine(){}
+Engine::~Engine(){}
 
 //Starts up subsystems in an order that satifies their dependencies
 bool Engine::startUp(){
@@ -61,7 +59,7 @@ void Engine::run(){
     bool done = false;
     bool switchScene = false;
 
-    //Counters
+    //Iteration and time keeping counters
     int count = 0;
     unsigned int end = 0;
     unsigned int start = 0;
@@ -85,15 +83,15 @@ void Engine::run(){
         //Handle all user input
         done = gInputManager.processInput();
 
-        //Update all models and camera in the current scene
+        //Update all models, camera and lighting in the current scene
         gSceneManager.update();
 
         //Update Rendering Queue and draw each item 
         gRenderManager.render();
 
+        //Stats about frame
         end = SDL_GetTicks();
         printf("%2.1d: Loop elapsed time (ms):%d\n",count,end - start);
-        //break;
     }
     printf("Closing engine\n");
 }

+ 3 - 7
src/inputManager.cpp

@@ -1,12 +1,7 @@
 #include "inputManager.h"
 
-InputManager::InputManager(){
-
-}
-
-InputManager::~InputManager(){
-
-}
+InputManager::InputManager(){}
+InputManager::~InputManager(){}
 
 bool InputManager::startUp(){
     //Nothing to do yet
@@ -26,6 +21,7 @@ bool InputManager::processInput(){
     return done;
 }
 
+//TODO all input handling will go here
 bool InputManager::handleEvent(SDL_Event * event){
     if(event->type == SDL_QUIT){
         return true;

+ 92 - 110
src/matrix.cpp

@@ -1,9 +1,7 @@
 #include "matrix.h"
 #include <math.h>
 
-
 Vector3 Matrix4::matMultVec(Vector3 &vec){
-
     Vector3 newVec(0,0,0);
     float w2 = 0;
     newVec.x = vec.x*(*this)(0,0)+
@@ -28,8 +26,6 @@ Vector3 Matrix4::matMultVec(Vector3 &vec){
     
     //Division is expensive, only do it if you need it
     //Also here is where perspective divide happens!
-    //vec.print();
-    //printf("%f\n",w2);
     if(w2 != 1){
         newVec.x /= w2;
         newVec.y /= w2;
@@ -39,7 +35,57 @@ Vector3 Matrix4::matMultVec(Vector3 &vec){
     return newVec;
 }
 
-Matrix4 Matrix4::makeFullRotMat(float alpha, float beta, float gamma){
+//Way too general, should probably change in the future since I think
+//I'll only need 4x4 stuff and this technically allows for any n matrix.
+//Traverse the matrix cell by cell and find the final value through a step of 
+//sub multiplications that are then added together
+Matrix4 Matrix4::operator*(Matrix4 &rhs){
+    //Matrix dimensions
+    Matrix4 results;
+    int n = 4;
+    for(int rows = 0; rows < n; ++rows){
+        for(int cols = 0; cols < n; ++cols){
+            float total = 0;
+            //total value of multiplication with all submultiplications added together
+            //sub represents submultiplications in the actual matrix multiplication
+            //For a nxn matrix you have n submultiplications
+            for(int sub = 1; sub < n+1; ++sub ){
+                int rowLhs = rows; //row ind left matrix
+                int colLhs = sub - 1; //col ind left matrix
+                int rowRhs = sub - 1; //row ind right matrix
+                int colRhs = cols; //col ind right matrix
+
+                total += (*this)(rowLhs,colLhs) * rhs(rowRhs,colRhs);
+            }
+            results(rows,cols) = total;
+        }
+    }
+    return results;
+}
+
+Matrix4 Matrix4::makeTestMat(){
+    Matrix4 testMat;
+    int n = 4;
+    int val = 1;
+    for(int rows = 0; rows < n; ++rows){
+        for(int cols = 0; cols < n; ++cols){
+            testMat(rows,cols) = val;
+            ++val;
+        }
+    }
+    return testMat;
+}
+
+Matrix4 Matrix4::unitMatrix(){
+    Matrix4 testMat;
+    testMat(0,0) = 1;
+    testMat(1,1) = 1;
+    testMat(2,2) = 1;
+    testMat(3,3) = 1;
+    return testMat;
+}
+//Uses ZYX convention for rotation
+Matrix4 Matrix4::fullRotMat(float alpha, float beta, float gamma){
     Matrix4 rotMat;
     float cosA = std::cos(alpha);
     float sinA = std::sin(alpha);
@@ -71,7 +117,7 @@ Matrix4 Matrix4::makeFullRotMat(float alpha, float beta, float gamma){
     return rotMat;
 }
 
-Matrix4 Matrix4::makeScaleMat(float scaleX, float scaleY, float scaleZ){
+Matrix4 Matrix4::scaleMat(float scaleX, float scaleY, float scaleZ){
     Matrix4 scaleMat;
     scaleMat(0,0) = scaleX;
     scaleMat(1,1) = scaleY;
@@ -80,7 +126,7 @@ Matrix4 Matrix4::makeScaleMat(float scaleX, float scaleY, float scaleZ){
     return scaleMat;
 }
 
-Matrix4 Matrix4::makeTranslateMat(float dx, float dy, float dz){
+Matrix4 Matrix4::translateMat(float dx, float dy, float dz){
     Matrix4 transMat;
     transMat(0,0) = 1;
     transMat(1,1) = 1;
@@ -89,117 +135,23 @@ Matrix4 Matrix4::makeTranslateMat(float dx, float dy, float dz){
     transMat(1,3) = dy;
     transMat(2,3) = dz;
     transMat(3,3) = 1;
-
     return transMat;
 }
 
-Matrix4 Matrix4::makeTestMat(){
-    Matrix4 testMat;
-    int n = 4;
-    int val = 1;
-    for(int rows = 0; rows < n; ++rows){
-        for(int cols = 0; cols < n; ++cols){
-            testMat(rows,cols) = val;
-            ++val;
-        }
-    }
-    return testMat;
-}
-
-Matrix4 Matrix4::unitMatrix(){
-    Matrix4 testMat;
-    testMat(0,0) = 1;
-    testMat(1,1) = 1;
-    testMat(2,2) = 1;
-    testMat(3,3) = 1;
-    return testMat;
-}
-
-void Matrix4::printMat(){
-    int n = 4;
-    for(int rows = 0; rows < n; ++rows){
-        for(int cols = 0; cols < n; ++cols){
-            float val = (*this)(rows,cols) ;
-            printf("%f\t",val);
-        }
-        printf("\n");
-    }
-    printf("\n");
-}
-
-//Way too general, should probably change in the future since I think
-//I'll only need 4x4 stuff and this technically allows for any n matrix.
-//Traverse the matrix cell by cell and find the final value through a step of 
-//sub multiplications that are then added together
-Matrix4 Matrix4::operator*(Matrix4 &rhs){
-    //Matrix dimensions
-    Matrix4 results;
-    int n = 4;
-
-    for(int rows = 0; rows < n; ++rows){
-        for(int cols = 0; cols < n; ++cols){
-            float total = 0;
-            //total value of multiplication with all submultiplications added together
-
-            //sub represents submultiplications in the actual matrix multiplication
-            //For a nxn matrix you have n submultiplications
-
-            for(int sub = 1; sub < n+1; ++sub ){
-                int rowLhs = rows; //row ind left matrix
-                int colLhs = sub - 1; //col ind left matrix
-
-                int rowRhs = sub -1; //row ind right matrix
-                int colRhs = cols; //col ind right matrix
-
-                total += (*this)(rowLhs,colLhs) * rhs(rowRhs,colRhs);
-                
-            }
-
-            //Setting the specific row and column to the total value of the subm-
-            //multiplications for that specifc cell of the matrix
-            results(rows,cols) = total;
-        }
-    }
-    return results;
-}
-
 Matrix4 Matrix4::transformMatrix(TransformParameters transform){
-    Matrix4 rotMatrix = Matrix4::makeFullRotMat(transform.rotation.x,
+    Matrix4 rotMatrix = Matrix4::fullRotMat(transform.rotation.x,
                          transform.rotation.y, transform.rotation.z);
-    Matrix4 scaleMatrix = Matrix4::makeScaleMat(transform.scaling.x,
+    Matrix4 scaleMatrix = Matrix4::scaleMat(transform.scaling.x,
                          transform.scaling.y, transform.scaling.z);
-    Matrix4 translationMatrix = Matrix4::makeTranslateMat(transform.translation.x,
+    Matrix4 translationMatrix = Matrix4::translateMat(transform.translation.x,
                          transform.translation.y, transform.translation.z);
+
     Matrix4 temp = (rotMatrix*scaleMatrix);
     return  translationMatrix*(temp);
 }
 
-Matrix4 Matrix4::makeProjectionMatrix(float fov, float AR, float near, float far){
-    float tanHalfFOVYInverse   =  1/tan( (fov/2) * (M_PI / 180) );
-    //float bot   =  -top;
-    //float right =  top * AR;
-    //float left  =  bot * AR;
-    Matrix4 projectionMat;
-
-
-    //First Row
-    projectionMat(0,0) = 1.0f* tanHalfFOVYInverse;
-
-    //Second row
-    projectionMat(1,1) = AR * tanHalfFOVYInverse;
-
-    //Third row (Mine calculated for 1- 0)
-    projectionMat(2,2) =  (near) / (far - near);
-    projectionMat(2,3) =  (far * near) / (far - near);
-    
-    //Fourth row
-    projectionMat(3,2) = -1;
-    
-    return projectionMat;
-}
-
 Matrix4 Matrix4::lookAt(Vector3& position, Vector3& target, Vector3& temp){
-
+    //Gram–Schmidt_process
     Vector3 forward = (position - target).normalized();
     Vector3 side    = (temp.crossProduct(forward)).normalized();
     Vector3 up      = forward.crossProduct(side);
@@ -211,21 +163,19 @@ Matrix4 Matrix4::lookAt(Vector3& position, Vector3& target, Vector3& temp){
     //I bet you this will be really confusing in a couple of weeks
     Matrix4 worldToCam;
     
-    
     //First row
     worldToCam(0,0) = side.x;
     worldToCam(0,1) = side.y;
     worldToCam(0,2) = side.z;
     worldToCam(0,3) = -side.dotProduct(position);
 
-
-    //First row
+    //Second row
     worldToCam(1,0) = up.x;
     worldToCam(1,1) = up.y;
     worldToCam(1,2) = up.z;
     worldToCam(1,3) = -up.dotProduct(position);
 
-    //First row
+    //Third row
     worldToCam(2,0) = forward.x;
     worldToCam(2,1) = forward.y;
     worldToCam(2,2) = forward.z;
@@ -235,4 +185,36 @@ Matrix4 Matrix4::lookAt(Vector3& position, Vector3& target, Vector3& temp){
     worldToCam(3,3) = 1;
 
     return worldToCam;
+}
+
+Matrix4 Matrix4::projectionMatrix(float fov, float AR, float near, float far){
+    Matrix4 projectionMat;
+    float tanHalfFOVInverse   =  1/tan( (fov/2) * (M_PI / 180) );
+    
+    //First Row
+    projectionMat(0,0) = tanHalfFOVInverse; // near/right
+
+    //Second row
+    projectionMat(1,1) = AR * tanHalfFOVInverse; //near / top (top = right /AR)
+
+    //Third row (Calculated for 1- 0)
+    projectionMat(2,2) =  (near) / (far - near);
+    projectionMat(2,3) =  (far * near) / (far - near);
+    
+    //Fourth row
+    projectionMat(3,2) = -1;
+    
+    return projectionMat;
+}
+
+void Matrix4::print(){
+    int n = 4;
+    for(int rows = 0; rows < n; ++rows){
+        for(int cols = 0; cols < n; ++cols){
+            float val = (*this)(rows,cols) ;
+            printf("%f\t",val);
+        }
+        printf("\n");
+    }
+    printf("\n");
 }

+ 2 - 3
src/mesh.cpp

@@ -1,10 +1,9 @@
 #include "mesh.h"
 
 void Mesh::describeMesh(){
-    int meshSize = numVertices;
-    for(int i = 0; i < meshSize; ++i){
+    for(int i = 0; i < numVertices; ++i){
         Vector3 vertex = vertices[i];
         printf("Vertex  %2.1d: %f, %f, %f \n",i,vertex.x, vertex.y, vertex.z);
     }
-    printf("Meshsize is: %d \n", meshSize);
+    printf("Meshsize is: %d \n", numVertices);
 }

+ 3 - 2
src/model.cpp

@@ -2,10 +2,10 @@
 #include "vector3.h"
 #include <limits>
 
-Model::Model(std::string path){
+Model::Model(std::string path, TransformParameters &initParameters){
     OBJ::buildMeshFromFile(mMesh, path);
+    initPosition(initParameters);
     buildBoundaryBox();
-    
 }
 
 Mesh * Model::getMesh(){
@@ -79,6 +79,7 @@ void Model::buildBoundaryBox(){
 
 }
 
+//TO DO 
 void Model::update(){
     
 }

+ 11 - 8
src/objParser.cpp

@@ -39,11 +39,11 @@ void OBJ::loadFileData(Mesh &mesh, std::ifstream &file){
         }
         else if(key == "f"){ //index data
             iss >> x >> y >> z;
-            std::vector<std::string> splitX = split(x,delimeter); 
-            std::vector<std::string> splitY = split(y,delimeter);
-            std::vector<std::string> splitZ = split(z,delimeter);
+            std::vector<std::string> splitX = splitStr(x,delimeter); 
+            std::vector<std::string> splitY = splitStr(y,delimeter);
+            std::vector<std::string> splitZ = splitStr(z,delimeter);
             for(int i = 0; i < splitX.size(); ++i){
-                //printf("%s\n",splitX[i].c_str());
+                //Subtracted by 1 because OBJ files count indices starting by 1
                 indices[i] = Vector3(std::stof(splitX[i])-1,std::stof(splitY[i])-1,std::stof(splitZ[i])-1);
             }
             printf("\n");
@@ -54,19 +54,22 @@ void OBJ::loadFileData(Mesh &mesh, std::ifstream &file){
     }
     mesh.numVertices = mesh.vertices.size();
     mesh.numFaces = mesh.vertexIndices.size();
+    //Reset file in case you want to re-read it
     file.clear();
     file.seekg(0, file.beg);
 }
 
-std::vector<std::string> OBJ::split(std::string &str, char delim){
+//Creates stringstream of string and subdivides it by the delimeter and returns
+//a vector of the individual components of the string
+std::vector<std::string> OBJ::splitStr(std::string &str, char delim){
     std::stringstream ss(str);
     std::string token;
     std::vector<std::string> splitString;
     while(std::getline(ss,token,delim)){
         if(token == ""){
-            //If token is empty just write -1
-            //Since you cannot have an idnex of that size anyway
-            splitString.push_back("-1"); 
+            //If token is empty just write 0 it will result in a -1 index
+            //Since that index number is nonsensical you can catch it pretty easily later
+            splitString.push_back("0"); 
         }
         else{
             splitString.push_back(token);

+ 22 - 18
src/rasterizer.cpp

@@ -3,6 +3,7 @@
 #include "array"
 #include <algorithm>
 
+//Initializing all the basic colors 
 const SDL_PixelFormat* Rasterizer::mappingFormat( SDL_AllocFormat(PIXEL_FORMAT));
 const Uint32 Rasterizer::white(SDL_MapRGBA(mappingFormat, 0xFF,0xFF,0xFF,0xFF));
 const Uint32 Rasterizer::red(SDL_MapRGBA(mappingFormat, 0xFF,0x00,0x00,0xFF));
@@ -29,6 +30,7 @@ void Rasterizer::testPattern(Buffer<Uint32> *pixelBuffer){
 }
 
 void Rasterizer::drawLine(Vector3 &vertex1, Vector3 &vertex2,const Uint32 &color, Buffer<Uint32> *pixelBuffer ){
+    //NDC to viewport transform
     int x1 = (vertex1.x + 1 ) * pixelBuffer->mWidth * 0.5;
     int y1 = (-vertex1.y + 1 ) * pixelBuffer->mHeight * 0.5;
     int x2 = (vertex2.x +1 ) * pixelBuffer->mWidth  * 0.5;
@@ -47,6 +49,8 @@ void Rasterizer::drawLine(Vector3 &vertex1, Vector3 &vertex2,const Uint32 &color
         std::swap(x1,x2);
         std::swap(y1,y2);
     }
+
+    //Redefined to use only int arithmetic
     int dx = x2 - x1;
     int dy = y2 - y1;
     int derror2 = std::abs(dy)*2;
@@ -55,19 +59,17 @@ void Rasterizer::drawLine(Vector3 &vertex1, Vector3 &vertex2,const Uint32 &color
 
     for(int x=x1; x <= x2 ; x++){
         if(steep){
-                (*pixelBuffer)(y, x) = color;
-            }
-            else{
-                (*pixelBuffer)(x,y) = color;
-            }
+            (*pixelBuffer)(y, x) = color; //Swap back because of steep transpose
+        }
+        else{
+            (*pixelBuffer)(x,y) = color;
+        }
         error2 += derror2;
         if (error2 > dx){
             y += (y2 > y1  ? 1 : -1);
             error2 -= dx*2;
         }
-
-    }
-        
+    } 
 }
 
 void Rasterizer::drawWireFrame(Vector3 *vertices, IShader &shader, Buffer<Uint32> *pixelBuffer){
@@ -79,11 +81,11 @@ void Rasterizer::drawWireFrame(Vector3 *vertices, IShader &shader, Buffer<Uint32
 //Draws triangles using baricentric coordinates,
 void Rasterizer::drawTriangles(Vector3 *vertices, IShader &shader, Buffer<Uint32> *pixelBuffer, Buffer<float> *zBuffer){
 
-    //Converting to screen space
+    //Converting to viewport space 
     std::array<int, 3>   xVerts;
     std::array<int, 3>   yVerts;
     Vector3 zVerts;
-    Rasterizer::screenSpaceTransform(pixelBuffer, vertices, xVerts, yVerts, zVerts);
+    Rasterizer::viewportTransform(pixelBuffer, vertices, xVerts, yVerts, zVerts);
 
     //Finding triangle bounding box limits clips it to the screen dimension
     //Whenever I get to clipping this will probably prove to be unnecessary 
@@ -101,35 +103,37 @@ void Rasterizer::drawTriangles(Vector3 *vertices, IShader &shader, Buffer<Uint32
 
     //Find triangle area
     float invArea = 1/(float)((xVerts[2]-xVerts[0])*(yVerts[1]-yVerts[0]) 
-                            - (xVerts[1]-xVerts[0])*(yVerts[2]-yVerts[0]));                 
+                            - (xVerts[1]-xVerts[0])*(yVerts[2]-yVerts[0]));     
+    //Per fragment variables            
     float depth = 0;
     Vector3 lambdas;
     Vector3 rgbVals;
+
+    //Iterating through triangle bounding box
     for(int y = yMin; y <= yMax; ++y){
         for(int x = xMin; x <= xMax; ++x){
             
-            Rasterizer::baricentric(lambdas, invArea, x, y, xVerts, yVerts);
+            Rasterizer::barycentric(lambdas, invArea, x, y, xVerts, yVerts);
 
             //Throw pixel away if not in triangle
             if(lambdas.data[0] < 0 || lambdas.data[1] < 0 || lambdas.data[2] < 0) continue;
-   
+
+            //Run fragment shader
             shader.fragment(lambdas, rgbVals, depth, zVerts);
 
-            //Zbuffer to paint
+            //Zbuffer check
             if((*zBuffer)(x,y) < depth){
                 if(depth <= 1.0){
                     (*zBuffer)(x,y) = depth;
                     (*pixelBuffer)(x,y) = SDL_MapRGBA(mappingFormat,
                 rgbVals.data[0],rgbVals.data[1],rgbVals.data[2],0xFF);
-                    //rgbVals.print();
                 }   
             } 
         }
     }
-
 }  
 
-void Rasterizer::screenSpaceTransform(Buffer<Uint32> *pixelBuffer, Vector3 *vertices,std::array<int, 3>   &xV,std::array<int, 3>   &yV, Vector3   &zV){
+void Rasterizer::viewportTransform(Buffer<Uint32> *pixelBuffer, Vector3 *vertices,std::array<int, 3>   &xV,std::array<int, 3>   &yV, Vector3   &zV){
     for(int i = 0; i < 3; ++i){
         xV[i] = (int)((vertices[i].x + 1 ) * pixelBuffer->mWidth * 0.5);
         yV[i] = (int)((-vertices[i].y + 1 ) * pixelBuffer->mHeight * 0.5);
@@ -138,7 +142,7 @@ void Rasterizer::screenSpaceTransform(Buffer<Uint32> *pixelBuffer, Vector3 *vert
 }
 
 //Calculates baricentric coordinates of triangles using the cross
-void Rasterizer::baricentric(Vector3 &lambdas, float invArea, int x, int y,  
+void Rasterizer::barycentric(Vector3 &lambdas, float invArea, int x, int y,  
                         std::array<int, 3>   &xVerts, std::array<int, 3>   &yVerts){
     for(int i = 0; i < 3; ++i){
         int i2 = (i+1)%3;

+ 17 - 17
src/renderManager.cpp

@@ -2,13 +2,9 @@
 #include <vector>
 #include "model.h"
 
-RenderManager::RenderManager(){
-
-}
-
-RenderManager::~RenderManager(){
-
-}
+//Dummy constructors / Destructors
+RenderManager::RenderManager(){}
+RenderManager::~RenderManager(){}
 
 bool RenderManager::startUp(DisplayManager &displayManager,SceneManager &sceneManager ){
     screen = &displayManager;
@@ -27,13 +23,14 @@ void RenderManager::shutDown(){
 }
 
 void RenderManager::render(){
-
     //Clear screen and reset current buffers
     screen->clear();
     renderInstance.clearBuffers();
 
-    //Build a render Queue for drawing multiple models and assign camera
+    //Build a render Queue for drawing multiple models
+    //Also assigns the current camera to the software renderer
     buildRenderQueue();
+
     //Draw all meshes in the render queue so far we assume they are
     //normal triangular meshes.
     while( !renderQueue.empty() ){
@@ -49,21 +46,16 @@ void RenderManager::render(){
     renderInstance.setCameraToRenderFrom(nullptr);
 }
 
-bool RenderManager::initSoftwareRenderer(){
-    int w = DisplayManager::SCREEN_WIDTH;
-    int h = DisplayManager::SCREEN_HEIGHT;
-    return renderInstance.startUp(w,h);
-}
-
-
 //Gets the list of visible models from the current scene and 
-//extracts a list of pointers to their meshes. Also
+//extracts a list of pointers to their meshes. 
+//Done every frame in case scene changes
 void RenderManager::buildRenderQueue(){
     
     //Set renderer camera
     Scene* currentScene = sceneLocator->getCurrentScene();
     renderInstance.setCameraToRenderFrom(currentScene->getCurrentCamera());
 
+    //Get pointers to the visible models
     std::vector<Model*>* visibleModels = currentScene->getVisiblemodels();
     
     //Builds render queue from visibleModels list
@@ -72,6 +64,14 @@ void RenderManager::buildRenderQueue(){
     }
 }
 
+bool RenderManager::initSoftwareRenderer(){
+    int w = DisplayManager::SCREEN_WIDTH;
+    int h = DisplayManager::SCREEN_HEIGHT;
+    return renderInstance.startUp(w,h);
+}
+
+
+
 
 
 

+ 2 - 11
src/scene.cpp

@@ -3,7 +3,6 @@
 
 Scene::Scene(std::string path){
     emptyScene = loadSceneModels(path);
-
 }
 
 Scene::~Scene(){
@@ -26,7 +25,7 @@ void Scene::update(){
 
 bool Scene::loadSceneModels(std::string &path){
     //In the future I want to read all o the models in the model folder
-    //And build them here.  For now only one
+    //And build them here. For now only one is loaded.
     std::string fullPath = "../models/";
     fullPath = fullPath + path;
 
@@ -35,19 +34,11 @@ bool Scene::loadSceneModels(std::string &path){
         return true;
     }
     else{
-        modelsInScene.push_back(new Model(fullPath));
-        
-        //We also initialize the model position here position here
         TransformParameters initParameters;
-        //initParameters.scaling = Vector3(1, 60, 60);
-        //initParameters.rotation = Vector3(0,0,0);
         initParameters.translation = Vector3(0, -1.5, 0);
-        modelsInScene[0]->initPosition(initParameters);
-
-        //sceneModel->describeMesh();
+        modelsInScene.push_back(new Model(fullPath, initParameters));
         return false;
     }
-    
 }
 
 void Scene::frustrumCulling(){

+ 6 - 10
src/sceneManager.cpp

@@ -1,16 +1,12 @@
 #include "sceneManager.h"
 
-SceneManager::SceneManager(){
-    
-}
-
-SceneManager::~SceneManager(){
-    
-}
+//Dummy constructors / destructors
+SceneManager::SceneManager(){}
+SceneManager::~SceneManager(){}
 
 bool SceneManager::startUp(){
     if (!loadScene()){
-        printf("Could not load scene.\n");
+        printf("Could not load scene. No models succesfully loaded!\n");
         return false;
     }
     return true;
@@ -25,10 +21,10 @@ bool SceneManager::switchScene(){
     return true;
 }
 
-//for now just loads the teapot.obj
+//for now just loads a single .obj based on the  given string
 bool SceneManager::loadScene(){
     currentScene = new Scene("elephant.obj");
-    return  !currentScene->checkIfEmpty();
+    return  !currentScene->checkIfEmpty(); //True if empty, so it's negated for startup
 }
 
 void SceneManager::update(){

+ 0 - 0
src/shader.cpp


+ 39 - 57
src/softwareRenderer.cpp

@@ -1,13 +1,8 @@
 #include "softwareRenderer.h"
 #include "shader.h"
 
-SoftwareRenderer::SoftwareRenderer(){
-
-}
-
-SoftwareRenderer::~SoftwareRenderer(){
-
-}
+SoftwareRenderer::SoftwareRenderer(){}
+SoftwareRenderer::~SoftwareRenderer(){}
 
 bool SoftwareRenderer::startUp(int w, int h){
     if( !createBuffers(w, h) ){
@@ -18,37 +13,11 @@ bool SoftwareRenderer::startUp(int w, int h){
 }
 
 void SoftwareRenderer::shutDown(){
-
     mCamera = nullptr;
     if (startUpComplete){
         delete zBuffer;
         delete pixelBuffer;
     }
-
-}
-
-void SoftwareRenderer::clearBuffers(){
-    zBuffer->clear();
-    pixelBuffer->clear();
-}
-
-bool SoftwareRenderer::createBuffers(int w, int h){
-    int pixelCount = w*h;
-    bool success = true;
-
-    zBuffer = new Buffer<float>(w, h, new float[pixelCount]);
-    if( zBuffer == nullptr){
-        printf("Could not build z-Buffer.\n");
-        success = false;
-    }
-    else{
-        pixelBuffer = new Buffer<Uint32>(w, h, new Uint32[pixelCount]);
-        if( pixelBuffer == nullptr){
-            printf("Could not build pixel Buffer.\n");
-            success = false;
-        }
-    }
-    return success;
 }
 
 void SoftwareRenderer::drawTriangularMesh(Mesh* triMesh){
@@ -59,8 +28,7 @@ void SoftwareRenderer::drawTriangularMesh(Mesh* triMesh){
     std::vector<Vector3> * vertices = &triMesh->vertices;
     std::vector<Vector3> * normals = &triMesh->normals;
     int numFaces = triMesh->numFaces;
-    //printf("nFaces: %d nNormals: %lu \n", numFaces, (*normals).size());
-    //(*normals)[numFaces-1].print();
+
     //Array grouping vertices together into triangle
     Vector3 trianglePrimitive[3];
     Vector3 normalPrim[3];
@@ -69,60 +37,74 @@ void SoftwareRenderer::drawTriangularMesh(Mesh* triMesh){
     GouraudShader shader;
 
     //Basic light direction
-
     Vector3 lightDir{1,0,0};
+
     //Building ModelViewProjection matrix
     Matrix4 MVP = (mCamera->projectionMatrix)*(mCamera->viewMatrix);
 
-    float intensity = 0;
+    //Iterate through every triangle
     for (int j = 0; j < numFaces; ++j){
-        //printf("\nCurrent Face: %d\n",j);
+        //Current vertex and normal indices
         Vector3 f = (*vIndices)[j];
         Vector3 n = (*nIndices)[j];
 
-        //Pack vertices together into an array
+        //Pack vertex and normal data together into an array
         buildTri(f,trianglePrimitive, *vertices);
         buildTri(n,normalPrim, *normals);
 
         //Skip faces that are pointing away from us
         if (backFaceCulling(trianglePrimitive)) continue;
 
-        // Vector3 N1 = trianglePrimitive[1] - trianglePrimitive[0];
-        // Vector3 N2 = trianglePrimitive[2] - trianglePrimitive[0];
-        // Vector3 N  = (N1.crossProduct(N2)).normalized();
-
         //Apply vertex shader
         for(int i = 0; i < 3; ++i){
-            //trianglePrimitive[i].print();
-            //normalPrim[i].print();
-            //printf("\n");
-            //Vector3 normal = (mCamera->viewMatrix).matMultVec(N);
-            trianglePrimitive[i] = shader.vertex(trianglePrimitive[i], MVP, normalPrim[i].normalized(), lightDir.normalized(), i);
+            //Vector3 normal = (mCamera->viewMatrix).matMultVec(normalPrim[i]);
+            trianglePrimitive[i] = shader.vertex(trianglePrimitive[i], MVP, normalPrim[i], lightDir.normalized(), i);
         }
 
         //Clipping should occur here
 
         //Send to rasterizer which will also call the fragment shader and write to the 
-        //zbuffer and pixel buffer
+        //zbuffer and pixel buffer.
         Rasterizer::drawTriangles(trianglePrimitive, shader, pixelBuffer, zBuffer);
     }
 }
 
+void SoftwareRenderer::clearBuffers(){
+    zBuffer->clear();
+    pixelBuffer->clear();
+}
+
 Buffer<Uint32>* SoftwareRenderer::getRenderTarget(){
     return pixelBuffer;
 }
 
+void SoftwareRenderer::setCameraToRenderFrom(Camera * camera){
+    mCamera = camera;
+}
+
+bool SoftwareRenderer::createBuffers(int w, int h){
+    int pixelCount = w*h;
+    bool success = true;
+
+    zBuffer = new Buffer<float>(w, h, new float[pixelCount]);
+    if( zBuffer == nullptr){
+        printf("Could not build z-Buffer.\n");
+        success = false;
+    }
+    else{
+        pixelBuffer = new Buffer<Uint32>(w, h, new Uint32[pixelCount]);
+        if( pixelBuffer == nullptr){
+            printf("Could not build pixel Buffer.\n");
+            success = false;
+        }
+    }
+    return success;
+}
+
 void SoftwareRenderer::buildTri(Vector3 &index, Vector3 *primitive, std::vector<Vector3> &vals){
     for(int i = 0; i < 3; ++i){
-        //printf("%d\t",(int)index.data[i]);
         primitive[i] = vals[(int)index.data[i]];
-        
     }
-    //printf("\n");
-}
-
-void SoftwareRenderer::setCameraToRenderFrom(Camera * camera){
-    mCamera = camera;
 }
 
 bool SoftwareRenderer::backFaceCulling(Vector3 *trianglePrim){
@@ -132,10 +114,10 @@ bool SoftwareRenderer::backFaceCulling(Vector3 *trianglePrim){
         Vector3 N2 = trianglePrim[2] - trianglePrim[0];
         Vector3 N  = (N2.crossProduct(N1)).normalized();
 
-        //View direction
         Vector3 view_dir =  trianglePrim[0] - mCamera->position;
         view_dir = view_dir.normalized();
 
+        //Returns false if the triangle cannot see the camera
         float intensity =  N.dotProduct(view_dir);
         return intensity <= 0.0;
 }

+ 16 - 16
src/vector.cpp → src/vector3.cpp

@@ -1,6 +1,7 @@
 #include "vector3.h"
 #include "math.h"
 
+//Scalar-vector stuff
 Vector3 &Vector3::operator-(){
     x = -x;
     y = -y;
@@ -8,6 +9,13 @@ Vector3 &Vector3::operator-(){
     return *this;
 }
 
+Vector3 Vector3::operator*(float rhs){
+    return Vector3(this->x * rhs,
+                   this->y * rhs,
+                   this->z * rhs);
+}
+
+//Vector-vector operations
 Vector3 Vector3::operator-(Vector3 &rhs){
     return Vector3(this->x - rhs.x,
                    this->y - rhs.y,
@@ -22,14 +30,14 @@ Vector3 Vector3::operator+(Vector3 &rhs){
     );
 }
 
-Vector3 Vector3::operator*(float rhs){
-    return Vector3(this->x * rhs,
-                   this->y * rhs,
-                   this->z * rhs);
+Vector3 Vector3::crossProduct(Vector3 &rhs){
+    Vector3 temp;
+    temp.x = ((this->y)*rhs.z) - (this->z)*rhs.y;
+    temp.y = ((this->z)*rhs.x) - (this->x)*rhs.z;
+    temp.z = ((this->x)*rhs.y) - (this->y)*rhs.x;
+    return temp;
 }
 
-
-
 Vector3& Vector3::normalized(){
     float len = this->length();
     if(len > 0){
@@ -39,20 +47,12 @@ Vector3& Vector3::normalized(){
         this->z*= factor;
     }
     else{
-        //Deal with this at some point!
-        //printf("Your vector is all zeros!!\n");
+        //Deal with this more nicely at some point!
+        printf("Your vector is all zeros!!\n");
     }
     return *this;
 }     
 
-Vector3 Vector3::crossProduct(Vector3 &rhs){
-    Vector3 temp;
-    temp.x = (this->y)*rhs.z - (this->z)*rhs.y;
-    temp.y = (this->z)*rhs.x - (this->x)*rhs.z;
-    temp.z = (this->x)*rhs.y - (this->y)*rhs.x;
-    return temp;
-}
-
 float Vector3::dotProduct(Vector3 &rhs){
     return (this->x)*rhs.x + (this->y)*rhs.y + (this->z)*rhs.z;
 }