diff --git a/README.md b/README.md index ae0896a..7254eb8 100644 --- a/README.md +++ b/README.md @@ -2,50 +2,8 @@ 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: +Graphics pipeline and features implemented: * Vertex Shading * Primitive Assembly with support for triangle VBOs/IBOs @@ -56,129 +14,56 @@ You will need to implement the following stages of the graphics pipeline and fea * 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: +Extra 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. + * 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 + * Points ------------------------------------------------------------------------------- -BASE CODE TOUR: +CONTROL ------------------------------------------------------------------------------- -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. +Press 'left' and 'right' to rotate the camera -* 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. +Press 'A' to enable and disable line drawing -You will also want to familiarize yourself with: +Press 'S' to enable and disable points drawing -* 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 +Press 'D' to enable and disable back face culling ------------------------------------------------------------------------------- -SOME RESOURCES: +RESULTS ------------------------------------------------------------------------------- -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 +![](https://github.com/DiracSea3921/Project4-Rasterizer/blob/master/cow.png) -------------------------------------------------------------------------------- -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: +Texture mapping with diffuse lighting shading -* 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. +![](https://github.com/DiracSea3921/Project4-Rasterizer/blob/master/cow2.png) -------------------------------------------------------------------------------- -README -------------------------------------------------------------------------------- -All students must replace or augment the contents of this Readme.md in a clear -manner with the following: +Lines Rasterization -* 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). +![](https://github.com/DiracSea3921/Project4-Rasterizer/blob/master/cow3.png) -------------------------------------------------------------------------------- -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. +Points Rasterization -We encourage you to get creative with your tweaks. Consider places in your code -that could be considered bottlenecks and try to improve them. +![](https://github.com/DiracSea3921/Project4-Rasterizer/blob/master/texture.bmp) +![](https://github.com/DiracSea3921/Project4-Rasterizer/blob/master/cow4.png) -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. +Texture mapping with texture filtering, bilinear interpolation ------------------------------------------------------------------------------- -THIRD PARTY CODE POLICY +PERFORMANCE ANALYSIS ------------------------------------------------------------------------------- -* 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. +![](https://github.com/DiracSea3921/Project4-Rasterizer/blob/master/chart.png) + +With back face culling enabled the fps can be improved from 30 to 40. The expected performance impact is reduce half of the rasterization stage. The test result has proven this assumption. + +![](https://github.com/DiracSea3921/Project4-Rasterizer/blob/master/chart2.png) + +With different camera distances the fps will change dramatically. This is because in the rasterization stage each thread needs to rasterize one triangle. If the distance is too short, the triangle will be very large in the screen space. So each thread will need more time to resterize that triangle. + + diff --git a/chart.png b/chart.png new file mode 100644 index 0000000..c3551f8 Binary files /dev/null and b/chart.png differ diff --git a/chart2.png b/chart2.png new file mode 100644 index 0000000..0cdcb70 Binary files /dev/null and b/chart2.png differ diff --git a/cow.png b/cow.png new file mode 100644 index 0000000..d348147 Binary files /dev/null and b/cow.png differ diff --git a/cow2.png b/cow2.png new file mode 100644 index 0000000..82687bc Binary files /dev/null and b/cow2.png differ diff --git a/cow3.png b/cow3.png new file mode 100644 index 0000000..99fd40b Binary files /dev/null and b/cow3.png differ diff --git a/cow4.png b/cow4.png new file mode 100644 index 0000000..e767230 Binary files /dev/null and b/cow4.png differ diff --git a/external/include/objUtil/obj.h b/external/include/objUtil/obj.h index a8ae205..53ac563 100644 --- a/external/include/objUtil/obj.h +++ b/external/include/objUtil/obj.h @@ -26,6 +26,8 @@ class obj{ float* vbo; float* nbo; float* cbo; + float* tbo; + int tbosize; int* ibo; float* boundingbox; float top; diff --git a/src/main.cpp b/src/main.cpp index 13d8e67..e79f60c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -6,7 +6,7 @@ //------------------------------- //-------------MAIN-------------- //------------------------------- - +bmp_texture tex; int main(int argc, char** argv){ bool loadedScene = false; @@ -72,6 +72,11 @@ void mainLoop() { glfwTerminate(); } +float theTa =0; +float alpha =1; +bool line = false; +bool vertex = false; +bool back = true; //------------------------------- //---------RUNTIME STUFF--------- //------------------------------- @@ -93,8 +98,13 @@ void runCuda(){ ibo = mesh->getIBO(); ibosize = mesh->getIBOsize(); + nbo = mesh->getNBO(); + nbosize = mesh->getNBOsize(); + + texcoord = mesh->getTextureCoords(); + 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,&tex,texcoord,theTa,alpha,line,vertex,back); cudaGLUnmapBufferObject(pbo); vbo = NULL; @@ -105,11 +115,39 @@ void runCuda(){ fpstracker++; } - + +void readBMP(char* filename,bmp_texture &tex) +{ + int i; + FILE* f = fopen(filename, "rb"); + unsigned char info[54]; + fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header + + // extract image height and width from header + int width = *(int*)&info[18]; + int height = *(int*)&info[22]; + + int size = 3 * width * height; + unsigned char* data = new unsigned char[size]; // allocate 3 bytes per pixel + fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once + fclose(f); + glm::vec3 *color_data = new glm::vec3[size/3]; + for(i = 0; i < size; i += 3) + { + color_data[i/3].r = (int)data[i+2]/255.0f; + color_data[i/3].g = (int)data[i+1]/255.0f; + color_data[i/3].b = (int)data[i]/255.0f; + } + delete []data; + tex.data = color_data; + tex.height = height; + tex.width = width; +} //------------------------------- //----------SETUP STUFF---------- //------------------------------- + bool init(int argc, char* argv[]) { glfwSetErrorCallback(errorCallback); @@ -117,6 +155,7 @@ bool init(int argc, char* argv[]) { return false; } + readBMP("texture.bmp",tex); width = 800; height = 800; window = glfwCreateWindow(width, height, "CIS 565 Pathtracer", NULL, NULL); @@ -281,4 +320,27 @@ void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){ glfwSetWindowShouldClose(window, GL_TRUE); } + if(key == GLFW_KEY_RIGHT){ + theTa+=0.1f; + } + + if(key == GLFW_KEY_LEFT){ + theTa-=0.1f; + } + if(key == GLFW_KEY_UP && action == GLFW_PRESS){ + alpha+=0.1f; + } + + if(key == GLFW_KEY_DOWN && action == GLFW_PRESS){ + alpha-=0.1f; + } + if(key == GLFW_KEY_A && action == GLFW_PRESS){ + line = !line; + } + if(key == GLFW_KEY_S && action == GLFW_PRESS){ + vertex = !vertex; + } + if(key == GLFW_KEY_D && action == GLFW_PRESS){ + back = !back; + } } \ No newline at end of file diff --git a/src/main.h b/src/main.h index 8999110..a87567f 100644 --- a/src/main.h +++ b/src/main.h @@ -49,6 +49,10 @@ float* cbo; int cbosize; int* ibo; int ibosize; +float* nbo; +int nbosize; +vector* texcoord; + //------------------------------- //----------CUDA STUFF----------- diff --git a/src/rasterizeKernels.cu b/src/rasterizeKernels.cu index 10b0000..305ba8f 100644 --- a/src/rasterizeKernels.cu +++ b/src/rasterizeKernels.cu @@ -7,13 +7,16 @@ #include #include "rasterizeKernels.h" #include "rasterizeTools.h" +#include glm::vec3* framebuffer; fragment* depthbuffer; float* device_vbo; float* device_cbo; +float* device_nbo; int* device_ibo; triangle* primitives; +float* device_tbo; void checkCUDAError(const char *msg) { cudaError_t err = cudaGetLastError(); @@ -90,6 +93,7 @@ __global__ void clearDepthBuffer(glm::vec2 resolution, fragment* buffer, fragmen fragment f = frag; f.position.x = x; f.position.y = y; + f.type = 0; buffer[index] = f; } } @@ -129,33 +133,258 @@ __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* nbo,float* tbo, int vbosize,glm::mat4 *mvp){ int index = (blockIdx.x * blockDim.x) + threadIdx.x; if(index0) + return; + + int x = (primitives[index].p0.x/2+0.5f)*(int)resolution.x; + int y = (primitives[index].p0.y/2+0.5f)*(int)resolution.y; + int buffer_index = y*(int)resolution.y+x; + if(depthbuffer[buffer_index].position.z < getZAtCoordinate(glm::vec3(1,0,0),primitives[index])+0.0001f){ + depthbuffer[buffer_index].color = glm::vec3(1.0f,0,0); + depthbuffer[buffer_index].type = 2; + + x = (primitives[index].p0.x/2+0.5f)*(int)resolution.x+1; + y = (primitives[index].p0.y/2+0.5f)*(int)resolution.y; + depthbuffer[y*(int)resolution.y+x].color = glm::vec3(1.0f,0,0); + depthbuffer[y*(int)resolution.y+x].type = 2; + x = (primitives[index].p0.x/2+0.5f)*(int)resolution.x; + y = (primitives[index].p0.y/2+0.5f)*(int)resolution.y+1; + depthbuffer[y*(int)resolution.y+x].color = glm::vec3(1.0f,0,0); + depthbuffer[y*(int)resolution.y+x].type = 2; + x = (primitives[index].p0.x/2+0.5f)*(int)resolution.x+1; + y = (primitives[index].p0.y/2+0.5f)*(int)resolution.y+1; + depthbuffer[y*(int)resolution.y+x].color = glm::vec3(1.0f,0,0); + depthbuffer[y*(int)resolution.y+x].type = 2; + } + + x = (primitives[index].p1.x/2+0.5f)*(int)resolution.x; + y = (primitives[index].p1.y/2+0.5f)*(int)resolution.y; + buffer_index = y*(int)resolution.y+x; + if(depthbuffer[buffer_index].position.z < getZAtCoordinate(glm::vec3(0,1,0),primitives[index])+0.0001f){ + depthbuffer[buffer_index].color = glm::vec3(1.0f,0,0); + depthbuffer[buffer_index].type = 2; + + x = (primitives[index].p1.x/2+0.5f)*(int)resolution.x+1; + y = (primitives[index].p1.y/2+0.5f)*(int)resolution.y; + depthbuffer[y*(int)resolution.y+x].color = glm::vec3(1.0f,0,0); + depthbuffer[y*(int)resolution.y+x].type = 2; + x = (primitives[index].p1.x/2+0.5f)*(int)resolution.x; + y = (primitives[index].p1.y/2+0.5f)*(int)resolution.y+1; + depthbuffer[y*(int)resolution.y+x].color = glm::vec3(1.0f,0,0); + depthbuffer[y*(int)resolution.y+x].type = 2; + x = (primitives[index].p1.x/2+0.5f)*(int)resolution.x+1; + y = (primitives[index].p1.y/2+0.5f)*(int)resolution.y+1; + depthbuffer[y*(int)resolution.y+x].color = glm::vec3(1.0f,0,0); + depthbuffer[y*(int)resolution.y+x].type = 2; + } + } +} + +//Draw Lines +__global__ void rasterizationKernelLines(triangle* primitives, int primitivesCount, fragment* depthbuffer, glm::vec2 resolution){ + int index = (blockIdx.x * blockDim.x) + threadIdx.x; + if(index0) + return; + + glm::vec3 p1,p2,p; + float len; + p1 = primitives[index].p0; + p2 = primitives[index].p1; + len = glm::length(p1-p2); + for(float t=0;t<1;t+=2/(len*resolution.x)){ + p = (p2-p1)*t + p1; + int x = (p.x/2+0.5f)*(int)resolution.x; + int y = (p.y/2+0.5f)*(int)resolution.y; + int buffer_index = y*(int)resolution.y+x; + glm::vec3 coord = calculateBarycentricCoordinate (primitives[index], glm::vec2(p.x,p.y)); + float depth = getZAtCoordinate(coord,primitives[index]); + if(depthbuffer[buffer_index].position.z < depth+0.0001f){ + depthbuffer[buffer_index].color = glm::vec3(1.0f,1.0f,0); + depthbuffer[buffer_index].type = 3; + } + } + p1 = primitives[index].p1; + p2 = primitives[index].p2; + len = glm::length(p1-p2); + for(float t=0;t<1;t+=2/(len*resolution.x)){ + p = (p2-p1)*t + p1; + int x = (p.x/2+0.5f)*(int)resolution.x; + int y = (p.y/2+0.5f)*(int)resolution.y; + int buffer_index = y*(int)resolution.y+x; + glm::vec3 coord = calculateBarycentricCoordinate (primitives[index], glm::vec2(p.x,p.y)); + float depth = getZAtCoordinate(coord,primitives[index]); + if(depthbuffer[buffer_index].position.z < depth+0.0001f){ + depthbuffer[buffer_index].color = glm::vec3(1.0f,1.0f,0); + depthbuffer[buffer_index].type = 3; + } + } + p1 = primitives[index].p2; + p2 = primitives[index].p0; + len = glm::length(p1-p2); + for(float t=0;t<1;t+=2/(len*resolution.x)){ + p = (p2-p1)*t + p1; + int x = (p.x/2+0.5f)*(int)resolution.x; + int y = (p.y/2+0.5f)*(int)resolution.y; + int buffer_index = y*(int)resolution.y+x; + glm::vec3 coord = calculateBarycentricCoordinate (primitives[index], glm::vec2(p.x,p.y)); + float depth = getZAtCoordinate(coord,primitives[index]); + if(depthbuffer[buffer_index].position.z < depth+0.0001f){ + depthbuffer[buffer_index].color = glm::vec3(1.0f,1.0f,0); + depthbuffer[buffer_index].type = 3; + } + } } } //TODO: Implement a rasterization method, such as scanline. -__global__ void rasterizationKernel(triangle* primitives, int primitivesCount, fragment* depthbuffer, glm::vec2 resolution){ +__global__ void rasterizationKernel(triangle* primitives, int primitivesCount, fragment* depthbuffer, glm::vec2 resolution,bool back){ int index = (blockIdx.x * blockDim.x) + threadIdx.x; if(index0) + return; + } + + float maxX,maxY,minX,minY; + if(primitives[index].p0.x>primitives[index].p1.x){ + maxX = primitives[index].p0.x; + minX = primitives[index].p1.x; + }else{ + maxX = primitives[index].p1.x; + minX = primitives[index].p0.x; + } + maxX = primitives[index].p2.x > maxX ? primitives[index].p2.x : maxX; + minX = primitives[index].p2.x < minX ? primitives[index].p2.x : minX; + + if(primitives[index].p0.y>primitives[index].p1.y){ + maxY = primitives[index].p0.y; + minY = primitives[index].p1.y; + }else{ + maxY = primitives[index].p1.y; + minY = primitives[index].p0.y; + } + maxY = primitives[index].p2.y > maxY ? primitives[index].p2.y : maxY; + minY = primitives[index].p2.y < minY ? primitives[index].p2.y : minY; + + maxX = maxX>1.0f? 1.0f:maxX; + maxY = maxY>1.0f? 1.0f:maxY; + minX = minX<-1.0f? -1.0f:minX; + minY = minY<-1.0f? -1.0f:minY; + int leftX = (minX/2+0.5f) * resolution.x; + int rightX = (maxX/2+0.5f) * resolution.x; + int topY = (maxY/2+0.5f) * resolution.y; + int bottomY = (minY/2+0.5f) * resolution.y; + + for(int i = bottomY; i<= topY; i++) + for(int j = leftX;j <=rightX;j++){ + glm::vec3 coord = calculateBarycentricCoordinate (primitives[index], glm::vec2(j/resolution.x*2-1.0f,i/resolution.y*2-1.0f)); + int buffer_index= i*(int)resolution.y+j; + if (isBarycentricCoordInBounds (coord)) + { + float depth = getZAtCoordinate(coord,primitives[index]); + if(depthbuffer[buffer_index].position.z < depth){ + depthbuffer[buffer_index].position.z = depth; + depthbuffer[buffer_index].color = coord.x * primitives[index].c0 + coord.y * primitives[index].c1 + coord.z * primitives[index].c2; + depthbuffer[buffer_index].normal = coord.x * primitives[index].n0 + coord.y * primitives[index].n1 + coord.z * primitives[index].n2; + depthbuffer[buffer_index].texcoord = coord.x * primitives[index].t0 + coord.y * primitives[index].t1 + coord.z * primitives[index].t2; + depthbuffer[buffer_index].type = 1; + } + } + + } } } + + //TODO: Implement a fragment shader -__global__ void fragmentShadeKernel(fragment* depthbuffer, glm::vec2 resolution){ +__global__ void fragmentShadeKernel(fragment* depthbuffer, glm::vec2 resolution, glm::vec3 *lightDir, bmp_texture *tex,glm::vec3 *device_data){ int x = (blockIdx.x * blockDim.x) + threadIdx.x; int y = (blockIdx.y * blockDim.y) + threadIdx.y; int index = x + (y * resolution.x); if(x<=resolution.x && y<=resolution.y){ + if(depthbuffer[index].type !=1) + return; + float diffuse = glm::dot(-*lightDir,depthbuffer[index].normal); + diffuse = diffuse>0?diffuse:0; + int x = depthbuffer[index].texcoord.x * tex->width; + int y = depthbuffer[index].texcoord.y * tex->height; + glm::vec3 tex_color0 = device_data[y * tex->height + x]; + glm::vec3 tex_color1 = device_data[y * tex->height + x+1]; + glm::vec3 tex_color2 = device_data[(y+1) * tex->height + x]; + glm::vec3 tex_color3 = device_data[(y+1) * tex->height + x+1]; + + float xx = depthbuffer[index].texcoord.x * tex->width - x; + float yy = depthbuffer[index].texcoord.y * tex->height - y; + glm::vec3 tex_color = (tex_color0 * (1-xx) + tex_color1 * xx) * (1-yy) + (tex_color2 * (1-xx) + tex_color3 * xx) * yy; + depthbuffer[index].color = tex_color*diffuse*0.9f+tex_color*0.1f; } } @@ -171,8 +400,9 @@ __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,bmp_texture *tex,vector *texcoord,float theTa, float alpha,bool line, bool vertex,bool back){ // set up crucial magic int tileSize = 8; @@ -214,32 +444,67 @@ void cudaRasterizeCore(uchar4* PBOpos, glm::vec2 resolution, float frame, float* cudaMalloc((void**)&device_cbo, cbosize*sizeof(float)); cudaMemcpy( device_cbo, cbo, cbosize*sizeof(float), cudaMemcpyHostToDevice); + device_nbo = NULL; + cudaMalloc((void**)&device_nbo, nbosize*sizeof(float)); + cudaMemcpy( device_nbo, nbo, nbosize*sizeof(float), cudaMemcpyHostToDevice); + + device_tbo = NULL; + cudaMalloc((void**)&device_tbo, vbosize/3*2*sizeof(float)); + tileSize = 32; int primitiveBlocks = ceil(((float)vbosize/3)/((float)tileSize)); + glm::mat4 projection = glm::perspective(60.0f, resolution.y/resolution.x, 0.001f, 300.0f); + glm::mat4 camera = glm::lookAt(glm::vec3(cos(theTa)*alpha,alpha,sin(theTa)*alpha), glm::vec3(0,0,0), glm::vec3(0, 1, 0)); + projection = projection * camera; + glm::mat4 *device_mvp = NULL; + cudaMalloc((void**)&device_mvp, cbosize*sizeof(glm::mat4)); + cudaMemcpy( device_mvp, &projection, cbosize*sizeof(glm::mat4), cudaMemcpyHostToDevice); + + glm::vec3 lightDir = glm::vec3(1,-1,1); + lightDir = glm::normalize(lightDir); + glm::vec3 *device_lightDir = NULL; + cudaMalloc((void**)&device_lightDir, cbosize*sizeof(glm::vec3)); + cudaMemcpy( device_lightDir, &lightDir, cbosize*sizeof(glm::vec3), cudaMemcpyHostToDevice); + + bmp_texture *device_tex = NULL; + cudaMalloc((void**)&device_tex, sizeof(bmp_texture)); + cudaMemcpy( device_tex, tex, sizeof(bmp_texture), cudaMemcpyHostToDevice); + glm::vec3 *device_data = NULL; + cudaMalloc((void**)&device_data, tex->width * tex->height *sizeof(glm::vec3)); + cudaMemcpy( device_data, tex->data, tex->width * tex->height *sizeof(glm::vec3), cudaMemcpyHostToDevice); + + //------------------------------ //vertex shader //------------------------------ - vertexShadeKernel<<>>(device_vbo, vbosize); + vertexShadeKernel<<>>(device_vbo, device_nbo, device_tbo,vbosize, device_mvp); cudaDeviceSynchronize(); //------------------------------ //primitive assembly //------------------------------ primitiveBlocks = ceil(((float)ibosize/3)/((float)tileSize)); - primitiveAssemblyKernel<<>>(device_vbo, vbosize, device_cbo, cbosize, device_ibo, ibosize, primitives); + primitiveAssemblyKernel<<>>(device_vbo, vbosize, device_cbo, cbosize, device_ibo, ibosize, device_nbo, nbosize,device_tbo, primitives); cudaDeviceSynchronize(); //------------------------------ //rasterization //------------------------------ - rasterizationKernel<<>>(primitives, ibosize/3, depthbuffer, resolution); - + rasterizationKernel<<>>(primitives, ibosize/3, depthbuffer, resolution,back); cudaDeviceSynchronize(); + if(line){ + rasterizationKernelLines<<>>(primitives, ibosize/3, depthbuffer, resolution); + cudaDeviceSynchronize(); + } + if(vertex){ + rasterizationKernelVertices<<>>(primitives, ibosize/3, depthbuffer, resolution); + cudaDeviceSynchronize(); + } //------------------------------ //fragment shader //------------------------------ - fragmentShadeKernel<<>>(depthbuffer, resolution); + fragmentShadeKernel<<>>(depthbuffer, resolution, device_lightDir,device_tex,device_data); cudaDeviceSynchronize(); //------------------------------ @@ -260,6 +525,7 @@ void kernelCleanup(){ cudaFree( device_vbo ); cudaFree( device_cbo ); cudaFree( device_ibo ); + cudaFree( device_nbo ); cudaFree( framebuffer ); cudaFree( depthbuffer ); } diff --git a/src/rasterizeKernels.h b/src/rasterizeKernels.h index 784be17..a6e2d10 100644 --- a/src/rasterizeKernels.h +++ b/src/rasterizeKernels.h @@ -9,8 +9,13 @@ #include #include #include "glm/glm.hpp" +#include "glm/gtc/matrix_transform.hpp" +#include "utilities.h" +#include + +using namespace std; 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,bmp_texture *tex,vector *texcoord,float theTa, float alpha, bool line, bool vertex,bool back); #endif //RASTERIZEKERNEL_H diff --git a/src/rasterizeTools.h b/src/rasterizeTools.h index e9b5dcc..57771b7 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::vec2 t0; + glm::vec2 t1; + glm::vec2 t2; }; struct fragment{ + int type; glm::vec3 color; glm::vec3 normal; glm::vec3 position; + glm::vec2 texcoord; }; //Multiplies a cudaMat4 matrix and a vec4 diff --git a/src/utilities.cpp b/src/utilities.cpp index 4f8f4d3..9e71441 100644 --- a/src/utilities.cpp +++ b/src/utilities.cpp @@ -6,6 +6,7 @@ #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/matrix_inverse.hpp" + float utilityCore::clamp(float f, float min, float max){ if(f - + @@ -87,6 +87,6 @@ - + \ No newline at end of file diff --git a/windows/PROJ4_Rasterizer/PROJ4_Rasterizer/texture.bmp b/windows/PROJ4_Rasterizer/PROJ4_Rasterizer/texture.bmp new file mode 100644 index 0000000..7217358 Binary files /dev/null and b/windows/PROJ4_Rasterizer/PROJ4_Rasterizer/texture.bmp differ