diff --git a/README.md b/README.md index ae0896a..848660c 100644 --- a/README.md +++ b/README.md @@ -1,184 +1,43 @@ -------------------------------------------------------------------------------- -CIS565: Project 4: CUDA Rasterizer -------------------------------------------------------------------------------- -Fall 2014 -------------------------------------------------------------------------------- -Due Monday 10/27/2014 @ 12 PM -------------------------------------------------------------------------------- - -------------------------------------------------------------------------------- -NOTE: -------------------------------------------------------------------------------- -This project requires an NVIDIA graphics card with CUDA capability! Any card with CUDA compute capability 1.1 or higher will work fine for this project. For a full list of CUDA capable cards and their compute capability, please consult: http://developer.nvidia.com/cuda/cuda-gpus. If you do not have an NVIDIA graphics card in the machine you are working on, feel free to use any machine in the SIG Lab or in Moore100 labs. All machines in the SIG Lab and Moore100 are equipped with CUDA capable NVIDIA graphics cards. If this too proves to be a problem, please contact Patrick or Karl as soon as possible. - -------------------------------------------------------------------------------- -INTRODUCTION: -------------------------------------------------------------------------------- -In this project, you will implement a simplified CUDA based implementation of a standard rasterized graphics pipeline, similar to the OpenGL pipeline. In this project, you will implement vertex shading, primitive assembly, perspective transformation, rasterization, fragment shading, and write the resulting fragments to a framebuffer. More information about the rasterized graphics pipeline can be found in the class slides and in your notes from CIS560. - -The basecode provided includes an OBJ loader and much of the mundane I/O and bookkeeping code. The basecode also includes some functions that you may find useful, described below. The core rasterization pipeline is left for you to implement. - -You MAY NOT use ANY raycasting/raytracing AT ALL in this project, EXCEPT in the fragment shader step. One of the purposes of this project is to see how a rasterization pipeline can generate graphics WITHOUT the need for raycasting! Raycasting may only be used in the fragment shader effect for interesting shading results, but is absolutely not allowed in any other stages of the pipeline. - -Also, you MAY NOT use OpenGL ANYWHERE in this project, aside from the given OpenGL code for drawing Pixel Buffer Objects to the screen. Use of OpenGL for any pipeline stage instead of your own custom implementation will result in an incomplete project. - -Finally, note that while this basecode is meant to serve as a strong starting point for a CUDA rasterizer, you are not required to use this basecode if you wish, and you may also change any part of the basecode specification as you please, so long as the final rendered result is correct. - -------------------------------------------------------------------------------- -CONTENTS: -------------------------------------------------------------------------------- -The Project4 root directory contains the following subdirectories: - -* src/ contains the source code for the project. Both the Windows Visual Studio solution and the OSX makefile reference this folder for all source; the base source code compiles on OSX and Windows without modification. -* objs/ contains example obj test files: cow.obj, cube.obj, tri.obj. -* renders/ contains an example render of the given example cow.obj file with a z-depth fragment shader. -* windows/ contains a Windows Visual Studio 2010 project and all dependencies needed for building and running on Windows 7. - -The Windows and OSX versions of the project build and run exactly the same way as in Project0, Project1, and Project2. - -------------------------------------------------------------------------------- -REQUIREMENTS: -------------------------------------------------------------------------------- -In this project, you are given code for: - -* A library for loading/reading standard Alias/Wavefront .obj format mesh files and converting them to OpenGL style VBOs/IBOs -* A suggested order of kernels with which to implement the graphics pipeline -* Working code for CUDA-GL interop - -You will need to implement the following stages of the graphics pipeline and features: - -* Vertex Shading -* Primitive Assembly with support for triangle VBOs/IBOs -* Perspective Transformation -* Rasterization through either a scanline or a tiled approach -* Fragment Shading -* A depth buffer for storing and depth testing fragments -* Fragment to framebuffer writing -* A simple lighting/shading scheme, such as Lambert or Blinn-Phong, implemented in the fragment shader - -You are also required to implement at least 3 of the following features: - -* Additional pipeline stages. Each one of these stages can count as 1 feature: - * Geometry shader - * Transformation feedback - * Back-face culling - * Scissor test - * Stencil test - * Blending - -IMPORTANT: For each of these stages implemented, you must also add a section to your README stating what the expected performance impact of that pipeline stage is, and real performance comparisons between your rasterizer with that stage and without. - -* Correct color interpolation between points on a primitive -* Texture mapping WITH texture filtering and perspective correct texture coordinates -* Support for additional primitices. Each one of these can count as HALF of a feature. - * Lines - * Line strips - * Triangle fans - * Triangle strips - * Points -* Anti-aliasing -* Order-independent translucency using a k-buffer -* MOUSE BASED interactive camera support. Interactive camera support based only on the keyboard is not acceptable for this feature. - -------------------------------------------------------------------------------- -BASE CODE TOUR: -------------------------------------------------------------------------------- -You will be working primarily in two files: rasterizeKernel.cu, and rasterizerTools.h. Within these files, areas that you need to complete are marked with a TODO comment. Areas that are useful to and serve as hints for optional features are marked with TODO (Optional). Functions that are useful for reference are marked with the comment LOOK. - -* rasterizeKernels.cu contains the core rasterization pipeline. - * A suggested sequence of kernels exists in this file, but you may choose to alter the order of this sequence or merge entire kernels if you see fit. For example, if you decide that doing has benefits, you can choose to merge the vertex shader and primitive assembly kernels, or merge the perspective transform into another kernel. There is not necessarily a right sequence of kernels (although there are wrong sequences, such as placing fragment shading before vertex shading), and you may choose any sequence you want. Please document in your README what sequence you choose and why. - * The provided kernels have had their input parameters removed beyond basic inputs such as the framebuffer. You will have to decide what inputs should go into each stage of the pipeline, and what outputs there should be. - -* rasterizeTools.h contains various useful tools, including a number of barycentric coordinate related functions that you may find useful in implementing scanline based rasterization... - * A few pre-made structs are included for you to use, such as fragment and triangle. A simple rasterizer can be implemented with these structs as is. However, as with any part of the basecode, you may choose to modify, add to, use as-is, or outright ignore them as you see fit. - * If you do choose to add to the fragment struct, be sure to include in your README a rationale for why. - -You will also want to familiarize yourself with: - -* main.cpp, which contains code that transfers VBOs/CBOs/IBOs to the rasterization pipeline. Interactive camera work will also have to be implemented in this file if you choose that feature. -* utilities.h, which serves as a kitchen-sink of useful functions - -------------------------------------------------------------------------------- -SOME RESOURCES: -------------------------------------------------------------------------------- -The following resources may be useful for this project: - -* High-Performance Software Rasterization on GPUs - * Paper (HPG 2011): http://www.tml.tkk.fi/~samuli/publications/laine2011hpg_paper.pdf - * Code: http://code.google.com/p/cudaraster/ Note that looking over this code for reference with regard to the paper is fine, but we most likely will not grant any requests to actually incorporate any of this code into your project. - * Slides: http://bps11.idav.ucdavis.edu/talks/08-gpuSoftwareRasterLaineAndPantaleoni-BPS2011.pdf -* The Direct3D 10 System (SIGGRAPH 2006) - for those interested in doing geometry shaders and transform feedback. - * http://133.11.9.3/~takeo/course/2006/media/papers/Direct3D10_siggraph2006.pdf -* Multi-Fragment Effects on the GPU using the k-Buffer - for those who want to do a k-buffer - * http://www.inf.ufrgs.br/~comba/papers/2007/kbuffer_preprint.pdf -* FreePipe: A Programmable, Parallel Rendering Architecture for Efficient Multi-Fragment Effects (I3D 2010) - * https://sites.google.com/site/hmcen0921/cudarasterizer -* Writing A Software Rasterizer In Javascript: - * Part 1: http://simonstechblog.blogspot.com/2012/04/software-rasterizer-part-1.html - * Part 2: http://simonstechblog.blogspot.com/2012/04/software-rasterizer-part-2.html - -------------------------------------------------------------------------------- -NOTES ON GLM: -------------------------------------------------------------------------------- -This project uses GLM, the GL Math library, for linear algebra. You need to know two important points on how GLM is used in this project: - -* In this project, indices in GLM vectors (such as vec3, vec4), are accessed via swizzling. So, instead of v[0], v.x is used, and instead of v[1], v.y is used, and so on and so forth. -* GLM Matrix operations work fine on NVIDIA Fermi cards and later, but pre-Fermi cards do not play nice with GLM matrices. As such, in this project, GLM matrices are replaced with a custom matrix struct, called a cudaMat4, found in cudaMat4.h. A custom function for multiplying glm::vec4s and cudaMat4s is provided as multiplyMV() in intersections.h. - -------------------------------------------------------------------------------- -README -------------------------------------------------------------------------------- -All students must replace or augment the contents of this Readme.md in a clear -manner with the following: - -* A brief description of the project and the specific features you implemented. -* At least one screenshot of your project running. -* A 30 second or longer video of your project running. To create the video you - can use http://www.microsoft.com/expression/products/Encoder4_Overview.aspx -* A performance evaluation (described in detail below). - -------------------------------------------------------------------------------- -PERFORMANCE EVALUATION -------------------------------------------------------------------------------- -The performance evaluation is where you will investigate how to make your CUDA -programs more efficient using the skills you've learned in class. You must have -performed at least one experiment on your code to investigate the positive or -negative effects on performance. - -We encourage you to get creative with your tweaks. Consider places in your code -that could be considered bottlenecks and try to improve them. - -Each student should provide no more than a one page summary of their -optimizations along with tables and or graphs to visually explain any -performance differences. - -------------------------------------------------------------------------------- -THIRD PARTY CODE POLICY -------------------------------------------------------------------------------- -* Use of any third-party code must be approved by asking on Piazza. If it is approved, all students are welcome to use it. Generally, we approve use of third-party code that is not a core part of the project. For example, for the ray tracer, we would approve using a third-party library for loading models, but would not approve copying and pasting a CUDA function for doing refraction. -* Third-party code must be credited in README.md. -* Using third-party code without its approval, including using another student's code, is an academic integrity violation, and will result in you receiving an F for the semester. - -------------------------------------------------------------------------------- -SELF-GRADING -------------------------------------------------------------------------------- -* On the submission date, email your grade, on a scale of 0 to 100, to Liam, harmoli+cis565@seas.upenn.edu, with a one paragraph explanation. Be concise and realistic. Recall that we reserve 30 points as a sanity check to adjust your grade. Your actual grade will be (0.7 * your grade) + (0.3 * our grade). We hope to only use this in extreme cases when your grade does not realistically reflect your work - it is either too high or too low. In most cases, we plan to give you the exact grade you suggest. -* Projects are not weighted evenly, e.g., Project 0 doesn't count as much as the path tracer. We will determine the weighting at the end of the semester based on the size of each project. - ---- -SUBMISSION ---- -As with the previous project, you should fork this project and work inside of -your fork. Upon completion, commit your finished project back to your fork, and -make a pull request to the master repository. You should include a README.md -file in the root directory detailing the following - -* A brief description of the project and specific features you implemented -* At least one screenshot of your project running. -* A link to a video of your raytracer running. -* Instructions for building and running your project if they differ from the - base code. -* A performance writeup as detailed above. -* A list of all third-party code used. -* This Readme file edited as described above in the README section. - +Software Rasterizer in CUDA +============ +Features +-------- + +Here's a quick down break down of the features: +- Vertex Shading +- Primitive Assembly with support for triangle VBOs/IBOs +- Perspective Transformation +- Rasterization through either a scanline or a tiled approach +- Fragment Shading +- A depth buffer for storing and depth testing fragments +- Fragment to framebuffer writing +- A simple lighting/shading scheme, such as Lambert or Blinn-Phong, implemented in the fragment shader +- Back face culling +- Mouse based interaction +- Color interpolation + +Here is a render! +![Base PT Image][base pt image] + +I'm going to talk about the performance of the system briefly. All times are measured with the dragon file, which is 100,000 triangles. + +- Base code (io really) 0.007 ms total per frame +- With vertex shader 0.008 ms total per frame +- With assembly 0.0095 ms total per frame (+18.75%) +- Rasterization step 0.012 ms total per frame (+26%) +- Rasterization step with back face culling 0.011 ms total per frame (-19%) +- Fragment shader 0.013 ms total per frame (+18%) +- Fragment shader w/color interpolation 0.013 ms total per frame (+18%) +- Render step 0.014 ms total per frame (+7%) + +So, culling unseen faces save you on render pretty substantially! And color interpolation didn't affect things in a noticeable way. + +![ee][e] +Blue is with back face culling, red is without. + +And mouse based scrolling obviously doesn't affect anything. in terms of performance. + +http://youtu.be/rjKDOhJbNLc + +[base pt image]:http://2.bp.blogspot.com/-5HfoVl3K_CE/VFQRZcV1bNI/AAAAAAAACd8/BAUZy5cwuqY/s1600/render.png +[e]:http://3.bp.blogspot.com/-Hl2XbNgf__w/VFQTiHrPO1I/AAAAAAAACeI/YlHoSi2JyZA/s1600/image.png \ No newline at end of file diff --git a/objs/dragon.mtl b/objs/dragon.mtl new file mode 100644 index 0000000..c89145d --- /dev/null +++ b/objs/dragon.mtl @@ -0,0 +1,6 @@ +newmtl initialShadingGroup +illum 4 +Kd 0.50 0.50 0.50 +Ka 0.00 0.00 0.00 +Tf 1.00 1.00 1.00 +Ni 1.00 diff --git a/objs/test.mtl b/objs/test.mtl new file mode 100644 index 0000000..c89145d --- /dev/null +++ b/objs/test.mtl @@ -0,0 +1,6 @@ +newmtl initialShadingGroup +illum 4 +Kd 0.50 0.50 0.50 +Ka 0.00 0.00 0.00 +Tf 1.00 1.00 1.00 +Ni 1.00 diff --git a/objs/tri.obj b/objs/tri.obj index fb38e35..5054b10 100644 --- a/objs/tri.obj +++ b/objs/tri.obj @@ -1,6 +1,6 @@ v 0 0 0 v 0.1 0 0 -v 0 0.1 0 +v 0 -0.1 0 vn 0 0 1 diff --git a/src/main.cpp b/src/main.cpp index 13d8e67..5f4aade 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -7,6 +7,11 @@ //-------------MAIN-------------- //------------------------------- +camera cam; +int mouse_old_x, mouse_old_y; +int pressed = -1; +float t = 0; + int main(int argc, char** argv){ bool loadedScene = false; @@ -29,6 +34,14 @@ int main(int argc, char** argv){ return 0; } + cam.aspectRatio = (float)width/(float)height; + cam.fovy = 60; + cam.zNear = 0.1; + cam.zFar = 1000; + cam.eye = glm::vec3(0,0.5,1); + cam.center = glm::vec3(0,0.5,0); + cam.up = glm::vec3(0,1,0); + frame = 0; seconds = time (NULL); fpstracker = 0; @@ -93,13 +106,17 @@ void runCuda(){ ibo = mesh->getIBO(); ibosize = mesh->getIBOsize(); + nbo = mesh->getNBO(); + nbosize = mesh->getNBOsize(); + cudaGLMapBufferObject((void**)&dptr, pbo); - cudaRasterizeCore(dptr, glm::vec2(width, height), frame, vbo, vbosize, cbo, cbosize, ibo, ibosize); + cudaRasterizeCore(dptr, glm::vec2(width, height), frame, vbo, vbosize, cbo, cbosize, ibo, ibosize, nbo, nbosize, cam); cudaGLUnmapBufferObject(pbo); vbo = NULL; cbo = NULL; ibo = NULL; + nbo = NULL; frame++; fpstracker++; @@ -126,6 +143,8 @@ bool init(int argc, char* argv[]) { } glfwMakeContextCurrent(window); glfwSetKeyCallback(window, keyCallback); + glfwSetMouseButtonCallback(window, mouseButtonCallback); + glfwSetCursorPosCallback(window, mouseMotionCallback); // Set up GL context glewExperimental = GL_TRUE; @@ -281,4 +300,49 @@ void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ glfwSetWindowShouldClose(window, GL_TRUE); } + else if (key == GLFW_KEY_S){ + glm::vec3 dir = cam.center - cam.eye; + cam.eye -= 0.05f*cam.up; + } + else if (key == GLFW_KEY_W){ + glm::vec3 dir = cam.center - cam.eye; + cam.eye += 0.05f*cam.up; + } + + std::cout<mouse_old_y) cam.eye += 0.1f*cam.up; + else cam.eye -= 0.1f*cam.up; + } + else if (pressed = 2){ + } + + mouse_old_x = x; + mouse_old_y = y; } \ No newline at end of file diff --git a/src/main.h b/src/main.h index 8999110..ebf376c 100644 --- a/src/main.h +++ b/src/main.h @@ -49,6 +49,8 @@ float* cbo; int cbosize; int* ibo; int ibosize; +float* nbo; +int nbosize; //------------------------------- //----------CUDA STUFF----------- @@ -99,5 +101,7 @@ void deleteTexture(GLuint* tex); void mainLoop(); void errorCallback(int error, const char *description); void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods); +void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods); +void mouseMotionCallback(GLFWwindow* window, double x, double y); #endif \ No newline at end of file diff --git a/src/rasterizeKernels.cu b/src/rasterizeKernels.cu index 10b0000..dd2a70e 100644 --- a/src/rasterizeKernels.cu +++ b/src/rasterizeKernels.cu @@ -10,7 +10,7 @@ glm::vec3* framebuffer; fragment* depthbuffer; -float* device_vbo; +float* device_vbo, *device_vbow, *device_nbo; float* device_cbo; int* device_ibo; triangle* primitives; @@ -129,17 +129,105 @@ __global__ void sendImageToPBO(uchar4* PBOpos, glm::vec2 resolution, glm::vec3* } //TODO: Implement a vertex shader -__global__ void vertexShadeKernel(float* vbo, int vbosize){ +__global__ void vertexShadeKernel(float* vbo, float* vbow, float* nbo, int vbosize, glm::mat4 MV, glm::mat4 P, glm::vec2 resolution, float zNear, float zFar){ int index = (blockIdx.x * blockDim.x) + threadIdx.x; if(index= 0) isFrontFacing = true; + else if (glm::dot(viewDir,tri.n1) >= 0) isFrontFacing = true; + else if (glm::dot(viewDir,tri.n2) >= 0) isFrontFacing = true; + + glm::vec4 normal(tri.n0, 0); + normal = MV*normal; + tri.n0.x = normal.x; + tri.n0.y = normal.y; + tri.n0.z = normal.z; + + normal = glm::vec4(tri.n1, 0); + normal = MV*normal; + tri.n1.x = normal.x; + tri.n1.y = normal.y; + tri.n1.z = normal.z; + + normal = glm::vec4(tri.n2, 0); + normal = MV*normal; + tri.n2.x = normal.x; + tri.n2.y = normal.y; + tri.n2.z = normal.z; + + tri.isFrontFacing = isFrontFacing; + + primitives[index] = tri; } } @@ -147,15 +235,70 @@ __global__ void primitiveAssemblyKernel(float* vbo, int vbosize, float* cbo, int __global__ void rasterizationKernel(triangle* primitives, int primitivesCount, fragment* depthbuffer, glm::vec2 resolution){ int index = (blockIdx.x * blockDim.x) + threadIdx.x; if(index1) diff=1; + + depthbuffer[index].color.x = abs(norm.x); + depthbuffer[index].color.y = abs(norm.y); + depthbuffer[index].color.z = abs(norm.z); + + depthbuffer[index].color = col*diff; } } @@ -172,7 +315,10 @@ __global__ void render(glm::vec2 resolution, fragment* depthbuffer, glm::vec3* f } // Wrapper for the __global__ call that sets up the kernel calls and does a ton of memory management -void cudaRasterizeCore(uchar4* PBOpos, glm::vec2 resolution, float frame, float* vbo, int vbosize, float* cbo, int cbosize, int* ibo, int ibosize){ +void cudaRasterizeCore(uchar4* PBOpos, glm::vec2 resolution, float frame, float* vbo, int vbosize, float* cbo, int cbosize, int* ibo, int ibosize, float* nbo, int nbosize, camera cam){ + + clock_t t; + t = clock(); // set up crucial magic int tileSize = 8; @@ -193,7 +339,7 @@ void cudaRasterizeCore(uchar4* PBOpos, glm::vec2 resolution, float frame, float* fragment frag; frag.color = glm::vec3(0,0,0); frag.normal = glm::vec3(0,0,0); - frag.position = glm::vec3(0,0,-10000); + frag.position = glm::vec3(0,0,10000); clearDepthBuffer<<>>(resolution, depthbuffer,frag); //------------------------------ @@ -210,6 +356,14 @@ void cudaRasterizeCore(uchar4* PBOpos, glm::vec2 resolution, float frame, float* cudaMalloc((void**)&device_vbo, vbosize*sizeof(float)); cudaMemcpy( device_vbo, vbo, vbosize*sizeof(float), cudaMemcpyHostToDevice); + device_vbow = NULL; + cudaMalloc((void**)&device_vbow, vbosize*sizeof(float)); + cudaMemcpy( device_vbow, vbo, vbosize*sizeof(float), cudaMemcpyHostToDevice); + + device_nbo = NULL; + cudaMalloc((void**)&device_nbo, nbosize*sizeof(float)); + cudaMemcpy( device_nbo, nbo, nbosize*sizeof(float), cudaMemcpyHostToDevice); + device_cbo = NULL; cudaMalloc((void**)&device_cbo, cbosize*sizeof(float)); cudaMemcpy( device_cbo, cbo, cbosize*sizeof(float), cudaMemcpyHostToDevice); @@ -217,31 +371,43 @@ void cudaRasterizeCore(uchar4* PBOpos, glm::vec2 resolution, float frame, float* tileSize = 32; int primitiveBlocks = ceil(((float)vbosize/3)/((float)tileSize)); + glm::mat4 persp = glm::perspective(cam.fovy, cam.aspectRatio, cam.zNear, cam.zFar); + glm::mat4 view = glm::lookAt(cam.eye, cam.center, cam.up); + glm::mat4 model(1.0f); + + glm::mat4 MVP = persp*view*model; + glm::mat4 MV = view*model; + glm::mat4 P = persp; //------------------------------ //vertex shader //------------------------------ - vertexShadeKernel<<>>(device_vbo, vbosize); + vertexShadeKernel<<>>(device_vbo, device_vbow, device_nbo, vbosize, MV, P, resolution, cam.zNear, cam.zFar); cudaDeviceSynchronize(); + checkCUDAError("Kernel failed1!"); + //------------------------------ //primitive assembly //------------------------------ primitiveBlocks = ceil(((float)ibosize/3)/((float)tileSize)); - primitiveAssemblyKernel<<>>(device_vbo, vbosize, device_cbo, cbosize, device_ibo, ibosize, primitives); + primitiveAssemblyKernel<<>>(device_vbo, device_vbow, vbosize, device_nbo, nbosize, device_cbo, cbosize, device_ibo, ibosize, primitives, glm::normalize(cam.center-cam.eye), MV); cudaDeviceSynchronize(); + checkCUDAError("Kernel failed2!"); //------------------------------ //rasterization //------------------------------ rasterizationKernel<<>>(primitives, ibosize/3, depthbuffer, resolution); cudaDeviceSynchronize(); + checkCUDAError("Kernel failed3!"); //------------------------------ //fragment shader //------------------------------ - fragmentShadeKernel<<>>(depthbuffer, resolution); + fragmentShadeKernel<<>>(depthbuffer, resolution, glm::vec3(0,2.5,0)); cudaDeviceSynchronize(); + checkCUDAError("Kernel failed4!"); //------------------------------ //write fragments to framebuffer //------------------------------ @@ -252,12 +418,16 @@ void cudaRasterizeCore(uchar4* PBOpos, glm::vec2 resolution, float frame, float* kernelCleanup(); - checkCUDAError("Kernel failed!"); + checkCUDAError("Kernel failed5!"); + t = clock() - t; + //std::cout<<(float)t/CLOCKS_PER_SEC< #include #include "glm/glm.hpp" +#include "glm/gtc/matrix_transform.hpp" +#include + +struct camera{ + float aspectRatio; + float fovy; + float zNear; + float zFar; + glm::vec3 eye; + glm::vec3 center; + glm::vec3 up; +}; void kernelCleanup(); -void cudaRasterizeCore(uchar4* pos, glm::vec2 resolution, float frame, float* vbo, int vbosize, float* cbo, int cbosize, int* ibo, int ibosize); +void cudaRasterizeCore(uchar4* pos, glm::vec2 resolution, float frame, float* vbo, int vbosize, float* cbo, int cbosize, int* ibo, int ibosize, float* nbo, int nbosize, camera cam); #endif //RASTERIZEKERNEL_H diff --git a/src/rasterizeTools.h b/src/rasterizeTools.h index e9b5dcc..4ef2a82 100644 --- a/src/rasterizeTools.h +++ b/src/rasterizeTools.h @@ -16,12 +16,20 @@ struct triangle { glm::vec3 c0; glm::vec3 c1; glm::vec3 c2; + glm::vec3 n0; + glm::vec3 n1; + glm::vec3 n2; + glm::vec3 p0w; + glm::vec3 p1w; + glm::vec3 p2w; + bool isFrontFacing; }; struct fragment{ glm::vec3 color; glm::vec3 normal; glm::vec3 position; + glm::vec3 positionw; }; //Multiplies a cudaMat4 matrix and a vec4 @@ -33,6 +41,16 @@ __host__ __device__ glm::vec3 multiplyMV(cudaMat4 m, glm::vec4 v){ return r; } +//Multiplies a cudaMat4 matrix and a vec4 +__host__ __device__ glm::vec4 multiplyMV4(cudaMat4 m, glm::vec4 v){ + glm::vec4 r(1,1,1,1); + r.x = (m.x.x*v.x)+(m.x.y*v.y)+(m.x.z*v.z)+(m.x.w*v.w); + r.y = (m.y.x*v.x)+(m.y.y*v.y)+(m.y.z*v.z)+(m.y.w*v.w); + r.z = (m.z.x*v.x)+(m.z.y*v.y)+(m.z.z*v.z)+(m.z.w*v.w); + r.w = (m.w.x*v.x)+(m.w.y*v.y)+(m.w.z*v.z)+(m.w.w*v.w); + return r; +} + //LOOK: finds the axis aligned bounding box for a given triangle __host__ __device__ void getAABBForTriangle(triangle tri, glm::vec3& minpoint, glm::vec3& maxpoint){ minpoint = glm::vec3(min(min(tri.p0.x, tri.p1.x),tri.p2.x), @@ -63,6 +81,14 @@ __host__ __device__ glm::vec3 calculateBarycentricCoordinate(triangle tri, glm:: return glm::vec3(alpha,beta,gamma); } +//LOOK: calculates barycentric coordinates +__host__ __device__ glm::vec3 calculateBarycentricCoordinateW(triangle tri, glm::vec2 point){ + float beta = calculateBarycentricCoordinateValue(glm::vec2(tri.p0w.x,tri.p0w.y), point, glm::vec2(tri.p2w.x,tri.p2w.y), tri); + float gamma = calculateBarycentricCoordinateValue(glm::vec2(tri.p0w.x,tri.p0w.y), glm::vec2(tri.p1w.x,tri.p1w.y), point, tri); + float alpha = 1.0-beta-gamma; + return glm::vec3(alpha,beta,gamma); +} + //LOOK: checks if a barycentric coordinate is within the boundaries of a triangle __host__ __device__ bool isBarycentricCoordInBounds(glm::vec3 barycentricCoord){ return barycentricCoord.x >= 0.0 && barycentricCoord.x <= 1.0 &&