diff --git a/PROJ3_WIN/565Rasterizer.sdf b/PROJ3_WIN/565Rasterizer.sdf new file mode 100644 index 0000000..91749c4 Binary files /dev/null and b/PROJ3_WIN/565Rasterizer.sdf differ diff --git a/PROJ3_WIN/565Rasterizer/565Rasterizer.vcxproj b/PROJ3_WIN/565Rasterizer/565Rasterizer.vcxproj index 1077f39..3d86b5f 100755 --- a/PROJ3_WIN/565Rasterizer/565Rasterizer.vcxproj +++ b/PROJ3_WIN/565Rasterizer/565Rasterizer.vcxproj @@ -72,7 +72,7 @@ Level3 Disabled WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\include;C:\ProgramData\NVIDIA Corporation\NVIDIA GPU Computing SDK 4.0\C\common\inc;../shared/glew/include;../shared/freeglut/include;%(AdditionalIncludeDirectories) + C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\include;C:\ProgramData\NVIDIA Corporation\NVIDIA GPU Computing SDK 4.2\C\common\inc;../shared/glew/include;../shared/freeglut/include;%(AdditionalIncludeDirectories) Console @@ -85,7 +85,8 @@ $(ProjectDir)$(Platform)/$(Configuration)/%(Filename)%(Extension).obj - C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.0\include;C:/ProgramData/NVIDIA Corporation/NVIDIA GPU Computing SDK 4.0/C/common/inc;../shared/glew/includes;../shared/freeglut/includes + C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\include;C:/ProgramData/NVIDIA Corporation/NVIDIA GPU Computing SDK 4.2/C/common/inc;../shared/glew/includes;../shared/freeglut/includes + compute_20,sm_20 diff --git a/PROJ3_WIN/Build/CUDA 4.0.props b/PROJ3_WIN/Build/CUDA 4.0.props index d0c1013..5b2b2c7 100755 --- a/PROJ3_WIN/Build/CUDA 4.0.props +++ b/PROJ3_WIN/Build/CUDA 4.0.props @@ -7,13 +7,13 @@ $(CudaToolkitCustomDir) - v4.0 - 4.00.0000.0000 + v4.2 + 4.20.0000.0000 - $(CUDA_PATH_V4_0) + $(CUDA_PATH_V4_2) $([MSBuild]::GetRegistryValueFromView('HKEY_LOCAL_MACHINE\SOFTWARE\NVIDIA Corporation\GPU Computing Toolkit\Cuda\$(CudaToolkitVersion)', 'InstallDir', null, RegistryView.Registry64, RegistryView.Registry32)) diff --git a/PROJ3_WIN/Build/CUDA 4.0.targets b/PROJ3_WIN/Build/CUDA 4.0.targets index 27717b0..3f17113 100755 --- a/PROJ3_WIN/Build/CUDA 4.0.targets +++ b/PROJ3_WIN/Build/CUDA 4.0.targets @@ -10,7 +10,7 @@ $(MSBuildThisFileDirectory)CUDA 4.0.xml - $(MSBuildThisFileDirectory)Nvda.Build.CudaTasks.v4.0.dll + $(MSBuildThisFileDirectory)Nvda.Build.CudaTasks.v4.2.dll @@ -437,7 +437,7 @@ DependsOnTargets="$(CudaCleanDependsOn)" Outputs="%(CudaCompile.CompileOut)"> - + diff --git a/PROJ3_WIN/Build/Nvda.Build.CudaTasks.v4.2.dll b/PROJ3_WIN/Build/Nvda.Build.CudaTasks.v4.2.dll new file mode 100644 index 0000000..fa28c84 Binary files /dev/null and b/PROJ3_WIN/Build/Nvda.Build.CudaTasks.v4.2.dll differ diff --git a/README.md b/README.md index dd7d45a..acacea3 100644 --- a/README.md +++ b/README.md @@ -1,162 +1,196 @@ -------------------------------------------------------------------------------- -CIS565: Project 3: CUDA Rasterizer -------------------------------------------------------------------------------- -Fall 2012 -------------------------------------------------------------------------------- -Due Monday 11/05/2012 -------------------------------------------------------------------------------- - -------------------------------------------------------------------------------- -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 10/15 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 Project3 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 an example cow.obj test file: the standard "bovine test". -* renders/ contains an example render of the given example cow.obj file with a z-depth fragment shader. -* PROJ1_WIN/ contains a Windows Visual Studio 2010 project and all dependencies needed for building and running on Windows 7. -* PROJ1_OSX/ contains a OSX makefile, run script, and all dependencies needed for building and running on Mac OSX 10.8. - -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 interpretation 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. - -------------------------------------------------------------------------------- -BLOG -------------------------------------------------------------------------------- -As mentioned in class, all students should have student blogs detailing progress on projects. If you already have a blog, you can use it; otherwise, please create a blog using www.blogger.com or any other tool, such as www.wordpress.org. Blog posts on your project are due on the SAME DAY as the project, and should include: - -* A brief description of the project and the specific features you implemented. -* A link to your github repo if the code is open source. -* At least one screenshot of your project running. -* A 30 second or longer video of your project running. To create the video use http://www.microsoft.com/expression/products/Encoder4_Overview.aspx - -------------------------------------------------------------------------------- -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 Karl, yiningli@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, and at least one screenshot of the final rendered output of your raytracer -* Instructions for building and running your project if they differ from the base code -* A link to your blog post detailing the project +-------------------------------------------------------------------------------- +SUBMITTED ITEMS +-------------------------------------------------------------------------------- +I have implemented the following 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 as well as Blinn-Phong + + +Some additional features: + + Back-face culling - Performance did not improve after implementing this. Infact, the FPS count decreased after implementing this test. I implemented this at the primitive assembly stage. + Scissor test - Performance increased after implementing this test. + Correct color interpretation between points on a primitive + +---------------------------------------------------------------------------------- +How to run +---------------------------------------------------------------------------------- +The project is using CUDA 4.2. Hence, I have uploaded the project with the changes required for CUDA 4.2. +There is little functionality which I have added to enable or disable some tests: +1. Press B or b to enable/disable back face culling. +2. Press s or S to enable/disable scissor test. Right now I have hard coded the window size. +3. Press l or L to enable the second light. +4. Press t ot T to see the number of triangles being drawn on output window. + +Link to my blog: http://cudarasterizerproject.blogspot.com/ + + +------------------------------------------------------------------------------- +CIS565: Project 3: CUDA Rasterizer +------------------------------------------------------------------------------- +Fall 2012 +------------------------------------------------------------------------------- +Due Monday 11/05/2012 +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +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 10/15 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 Project3 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 an example cow.obj test file: the standard "bovine test". +* renders/ contains an example render of the given example cow.obj file with a z-depth fragment shader. +* PROJ1_WIN/ contains a Windows Visual Studio 2010 project and all dependencies needed for building and running on Windows 7. +* PROJ1_OSX/ contains a OSX makefile, run script, and all dependencies needed for building and running on Mac OSX 10.8. + +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 interpretation 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. + +------------------------------------------------------------------------------- +BLOG +------------------------------------------------------------------------------- +As mentioned in class, all students should have student blogs detailing progress on projects. If you already have a blog, you can use it; otherwise, please create a blog using www.blogger.com or any other tool, such as www.wordpress.org. Blog posts on your project are due on the SAME DAY as the project, and should include: + +* A brief description of the project and the specific features you implemented. +* A link to your github repo if the code is open source. +* At least one screenshot of your project running. +* A 30 second or longer video of your project running. To create the video use http://www.microsoft.com/expression/products/Encoder4_Overview.aspx + +------------------------------------------------------------------------------- +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 Karl, yiningli@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, and at least one screenshot of the final rendered output of your raytracer +* Instructions for building and running your project if they differ from the base code +* A link to your blog post detailing the project * A list of all third-party code used \ No newline at end of file diff --git a/objs/cube1.mtl b/objs/cube1.mtl new file mode 100644 index 0000000..c89145d --- /dev/null +++ b/objs/cube1.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/cube1.obj b/objs/cube1.obj new file mode 100644 index 0000000..1125a06 --- /dev/null +++ b/objs/cube1.obj @@ -0,0 +1,59 @@ +# This file uses centimeters as units for non-parametric coordinates. + +mtllib cube1.mtl +g default +v -0.500000 -0.500000 0.500000 +v 0.500000 -0.500000 0.500000 +v -0.500000 0.500000 0.500000 +v 0.500000 0.500000 0.500000 +v -0.500000 0.500000 -0.500000 +v 0.500000 0.500000 -0.500000 +v -0.500000 -0.500000 -0.500000 +v 0.500000 -0.500000 -0.500000 +vt 0.375000 0.000000 +vt 0.625000 0.000000 +vt 0.375000 0.250000 +vt 0.625000 0.250000 +vt 0.375000 0.500000 +vt 0.625000 0.500000 +vt 0.375000 0.750000 +vt 0.625000 0.750000 +vt 0.375000 1.000000 +vt 0.625000 1.000000 +vt 0.875000 0.000000 +vt 0.875000 0.250000 +vt 0.125000 0.000000 +vt 0.125000 0.250000 +vn 0.000000 0.000000 1.000000 +vn 0.000000 0.000000 1.000000 +vn 0.000000 0.000000 1.000000 +vn 0.000000 0.000000 1.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 1.000000 0.000000 +vn 0.000000 0.000000 -1.000000 +vn 0.000000 0.000000 -1.000000 +vn 0.000000 0.000000 -1.000000 +vn 0.000000 0.000000 -1.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 0.000000 -1.000000 0.000000 +vn 1.000000 0.000000 0.000000 +vn 1.000000 0.000000 0.000000 +vn 1.000000 0.000000 0.000000 +vn 1.000000 0.000000 0.000000 +vn -1.000000 0.000000 0.000000 +vn -1.000000 0.000000 0.000000 +vn -1.000000 0.000000 0.000000 +vn -1.000000 0.000000 0.000000 +s off +g pCube1 +usemtl initialShadingGroup +f 1/1/1 2/2/2 4/4/3 3/3/4 +f 3/3/5 4/4/6 6/6/7 5/5/8 +f 5/5/9 6/6/10 8/8/11 7/7/12 +f 7/7/13 8/8/14 2/10/15 1/9/16 +f 2/2/17 8/11/18 6/12/19 4/4/20 +f 7/13/21 1/1/22 3/3/23 5/14/24 diff --git a/src/main.cpp b/src/main.cpp index dfb689a..d999c7c 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,354 +1,407 @@ -// CIS565 CUDA Rasterizer: A simple rasterization pipeline for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania -// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania - -#include "main.h" - -//------------------------------- -//-------------MAIN-------------- -//------------------------------- - -int main(int argc, char** argv){ - - bool loadedScene = false; - for(int i=1; ibuildVBOs(); - delete loader; - loadedScene = true; - } - } - - if(!loadedScene){ - cout << "Usage: mesh=[obj file]" << endl; - return 0; - } - - frame = 0; - seconds = time (NULL); - fpstracker = 0; - - // Launch CUDA/GL - #ifdef __APPLE__ - // Needed in OSX to force use of OpenGL3.2 - glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); - glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); - glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); - glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); - init(); - #else - init(argc, argv); - #endif - - initCuda(); - - initVAO(); - initTextures(); - - GLuint passthroughProgram; - passthroughProgram = initShader("shaders/passthroughVS.glsl", "shaders/passthroughFS.glsl"); - - glUseProgram(passthroughProgram); - glActiveTexture(GL_TEXTURE0); - - #ifdef __APPLE__ - // send into GLFW main loop - while(1){ - display(); - if (glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS || !glfwGetWindowParam( GLFW_OPENED )){ - kernelCleanup(); - cudaDeviceReset(); - exit(0); - } - } - - glfwTerminate(); - #else - glutDisplayFunc(display); - glutKeyboardFunc(keyboard); - - glutMainLoop(); - #endif - kernelCleanup(); - return 0; -} - -//------------------------------- -//---------RUNTIME STUFF--------- -//------------------------------- - -void runCuda(){ - // Map OpenGL buffer object for writing from CUDA on a single GPU - // No data is moved (Win & Linux). When mapped to CUDA, OpenGL should not use this buffer - dptr=NULL; - - vbo = mesh->getVBO(); - vbosize = mesh->getVBOsize(); - - float newcbo[] = {0.0, 1.0, 0.0, - 0.0, 0.0, 1.0, - 1.0, 0.0, 0.0}; - cbo = newcbo; - cbosize = 9; - - ibo = mesh->getIBO(); - ibosize = mesh->getIBOsize(); - - cudaGLMapBufferObject((void**)&dptr, pbo); - cudaRasterizeCore(dptr, glm::vec2(width, height), frame, vbo, vbosize, cbo, cbosize, ibo, ibosize); - cudaGLUnmapBufferObject(pbo); - - vbo = NULL; - cbo = NULL; - ibo = NULL; - - frame++; - fpstracker++; - -} - -#ifdef __APPLE__ - - void display(){ - runCuda(); - time_t seconds2 = time (NULL); - - if(seconds2-seconds >= 1){ - - fps = fpstracker/(seconds2-seconds); - fpstracker = 0; - seconds = seconds2; - - } - - string title = "CIS565 Rasterizer | "+ utilityCore::convertIntToString((int)fps) + "FPS"; - - glfwSetWindowTitle(title.c_str()); - - - glBindBuffer( GL_PIXEL_UNPACK_BUFFER, pbo); - glBindTexture(GL_TEXTURE_2D, displayImage); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, - GL_RGBA, GL_UNSIGNED_BYTE, NULL); - - - glClear(GL_COLOR_BUFFER_BIT); - - // VAO, shader program, and texture already bound - glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); - - glfwSwapBuffers(); - } - -#else - - void display(){ - runCuda(); - time_t seconds2 = time (NULL); - - if(seconds2-seconds >= 1){ - - fps = fpstracker/(seconds2-seconds); - fpstracker = 0; - seconds = seconds2; - - } - - string title = "CIS565 Rasterizer | "+ utilityCore::convertIntToString((int)fps) + "FPS"; - glutSetWindowTitle(title.c_str()); - - glBindBuffer( GL_PIXEL_UNPACK_BUFFER, pbo); - glBindTexture(GL_TEXTURE_2D, displayImage); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, - GL_RGBA, GL_UNSIGNED_BYTE, NULL); - - glClear(GL_COLOR_BUFFER_BIT); - - // VAO, shader program, and texture already bound - glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); - - glutPostRedisplay(); - glutSwapBuffers(); - } - - void keyboard(unsigned char key, int x, int y) - { - switch (key) - { - case(27): - shut_down(1); - break; - } - } - -#endif - -//------------------------------- -//----------SETUP STUFF---------- -//------------------------------- - -#ifdef __APPLE__ - void init(){ - - if (glfwInit() != GL_TRUE){ - shut_down(1); - } - - // 16 bit color, no depth, alpha or stencil buffers, windowed - if (glfwOpenWindow(width, height, 5, 6, 5, 0, 0, 0, GLFW_WINDOW) != GL_TRUE){ - shut_down(1); - } - - // Set up vertex array object, texture stuff - initVAO(); - initTextures(); - } -#else - void init(int argc, char* argv[]){ - glutInit(&argc, argv); - glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); - glutInitWindowSize(width, height); - glutCreateWindow("CIS565 Rasterizer"); - - // Init GLEW - glewInit(); - GLenum err = glewInit(); - if (GLEW_OK != err) - { - /* Problem: glewInit failed, something is seriously wrong. */ - std::cout << "glewInit failed, aborting." << std::endl; - exit (1); - } - - initVAO(); - initTextures(); - } -#endif - -void initPBO(GLuint* pbo){ - if (pbo) { - // set up vertex data parameter - int num_texels = width*height; - int num_values = num_texels * 4; - int size_tex_data = sizeof(GLubyte) * num_values; - - // Generate a buffer ID called a PBO (Pixel Buffer Object) - glGenBuffers(1,pbo); - // Make this the current UNPACK buffer (OpenGL is state-based) - glBindBuffer(GL_PIXEL_UNPACK_BUFFER, *pbo); - // Allocate data for the buffer. 4-channel 8-bit image - glBufferData(GL_PIXEL_UNPACK_BUFFER, size_tex_data, NULL, GL_DYNAMIC_COPY); - cudaGLRegisterBufferObject( *pbo ); - } -} - -void initCuda(){ - // Use device with highest Gflops/s - cudaGLSetGLDevice( cutGetMaxGflopsDeviceId() ); - - initPBO(&pbo); - - // Clean up on program exit - atexit(cleanupCuda); - - runCuda(); -} - -void initTextures(){ - glGenTextures(1,&displayImage); - glBindTexture(GL_TEXTURE_2D, displayImage); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA, - GL_UNSIGNED_BYTE, NULL); -} - -void initVAO(void){ - GLfloat vertices[] = - { - -1.0f, -1.0f, - 1.0f, -1.0f, - 1.0f, 1.0f, - -1.0f, 1.0f, - }; - - GLfloat texcoords[] = - { - 1.0f, 1.0f, - 0.0f, 1.0f, - 0.0f, 0.0f, - 1.0f, 0.0f - }; - - GLushort indices[] = { 0, 1, 3, 3, 1, 2 }; - - GLuint vertexBufferObjID[3]; - glGenBuffers(3, vertexBufferObjID); - - glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjID[0]); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - glVertexAttribPointer((GLuint)positionLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); - glEnableVertexAttribArray(positionLocation); - - glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjID[1]); - glBufferData(GL_ARRAY_BUFFER, sizeof(texcoords), texcoords, GL_STATIC_DRAW); - glVertexAttribPointer((GLuint)texcoordsLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); - glEnableVertexAttribArray(texcoordsLocation); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexBufferObjID[2]); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); -} - -GLuint initShader(const char *vertexShaderPath, const char *fragmentShaderPath){ - GLuint program = glslUtility::createProgram(vertexShaderPath, fragmentShaderPath, attributeLocations, 2); - GLint location; - - glUseProgram(program); - - if ((location = glGetUniformLocation(program, "u_image")) != -1) - { - glUniform1i(location, 0); - } - - return program; -} - -//------------------------------- -//---------CLEANUP STUFF--------- -//------------------------------- - -void cleanupCuda(){ - if(pbo) deletePBO(&pbo); - if(displayImage) deleteTexture(&displayImage); -} - -void deletePBO(GLuint* pbo){ - if (pbo) { - // unregister this buffer object with CUDA - cudaGLUnregisterBufferObject(*pbo); - - glBindBuffer(GL_ARRAY_BUFFER, *pbo); - glDeleteBuffers(1, pbo); - - *pbo = (GLuint)NULL; - } -} - -void deleteTexture(GLuint* tex){ - glDeleteTextures(1, tex); - *tex = (GLuint)NULL; -} - -void shut_down(int return_code){ - kernelCleanup(); - cudaDeviceReset(); - #ifdef __APPLE__ - glfwTerminate(); - #endif - exit(return_code); -} +// CIS565 CUDA Rasterizer: A simple rasterization pipeline for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania +// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania + +#include "main.h" + + +//------------------------------- +//-------------MAIN-------------- +//------------------------------- + +int lastX = 0; +int lastY = 0; + +int main(int argc, char** argv){ + + + bool loadedScene = false; + for(int i=1; ibuildVBOs(); + delete loader; + loadedScene = true; + } + } + + if(!loadedScene){ + cout << "Usage: mesh=[obj file]" << endl; + return 0; + } + + + frame = 0; + seconds = time (NULL); + fpstracker = 0; + + // Launch CUDA/GL + #ifdef __APPLE__ + // Needed in OSX to force use of OpenGL3.2 + glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); + glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2); + glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); + glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + init(); + #else + init(argc, argv); + #endif + + initCuda(); + + initVAO(); + initTextures(); + + GLuint passthroughProgram; + passthroughProgram = initShader("shaders/passthroughVS.glsl", "shaders/passthroughFS.glsl"); + + glUseProgram(passthroughProgram); + glActiveTexture(GL_TEXTURE0); + + #ifdef __APPLE__ + // send into GLFW main loop + while(1){ + display(); + if (glfwGetKey(GLFW_KEY_ESC) == GLFW_PRESS || !glfwGetWindowParam( GLFW_OPENED )){ + kernelCleanup(); + cudaDeviceReset(); + exit(0); + } + } + + glfwTerminate(); + #else + glutDisplayFunc(display); + glutKeyboardFunc(keyboard); + glutMouseFunc(mouseMotion); + + glutMainLoop(); + #endif + kernelCleanup(); + return 0; +} + +//------------------------------- +//---------RUNTIME STUFF--------- +//------------------------------- + +void runCuda(){ + // Map OpenGL buffer object for writing from CUDA on a single GPU + // No data is moved (Win & Linux). When mapped to CUDA, OpenGL should not use this buffer + dptr=NULL; + + vbo = mesh->getVBO(); + vbosize = mesh->getVBOsize(); + + float newcbo[] = {0.49, 0.49, 0.49, + 0.49, 0.49, 0.49, + 0.49, 0.49, 0.49}; + cbo = newcbo; + cbosize = 9; + + ibo = mesh->getIBO(); + ibosize = mesh->getIBOsize(); + + nbo = mesh->getNBO(); + nbosize = mesh->getNBOsize(); + + //model = glm::rotate(model, (float)frame, glm::vec3(0.0f, 1.0f, 0.0f)); + // enableBACKFACECULL = false; +// enableSCISSORTEST = false; + + cudaGLMapBufferObject((void**)&dptr, pbo); + cudaRasterizeCore(dptr, glm::vec2(width, height), frame, vbo, vbosize, cbo, cbosize, ibo, ibosize, nbo, nbosize); + cudaGLUnmapBufferObject(pbo); + + vbo = NULL; + cbo = NULL; + ibo = NULL; + + frame++; + fpstracker++; + +} + +#ifdef __APPLE__ + + void display(){ + runCuda(); + time_t seconds2 = time (NULL); + + if(seconds2-seconds >= 1){ + + fps = fpstracker/(seconds2-seconds); + fpstracker = 0; + seconds = seconds2; + + } + + string title = "CIS565 Rasterizer | "+ utilityCore::convertIntToString((int)fps) + "FPS"; + + glfwSetWindowTitle(title.c_str()); + + + glBindBuffer( GL_PIXEL_UNPACK_BUFFER, pbo); + glBindTexture(GL_TEXTURE_2D, displayImage); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, + GL_RGBA, GL_UNSIGNED_BYTE, NULL); + + + glClear(GL_COLOR_BUFFER_BIT); + + // VAO, shader program, and texture already bound + glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); + + glfwSwapBuffers(); + } + +#else + + void display(){ + runCuda(); + time_t seconds2 = time (NULL); + + if(seconds2-seconds >= 1){ + + fps = fpstracker/(seconds2-seconds); + fpstracker = 0; + seconds = seconds2; + + } + + string title = "CIS565 Rasterizer | "+ utilityCore::convertIntToString((int)fps) + "FPS"; + glutSetWindowTitle(title.c_str()); + + glBindBuffer( GL_PIXEL_UNPACK_BUFFER, pbo); + glBindTexture(GL_TEXTURE_2D, displayImage); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, + GL_RGBA, GL_UNSIGNED_BYTE, NULL); + + glClear(GL_COLOR_BUFFER_BIT); + + // VAO, shader program, and texture already bound + glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); + + glutPostRedisplay(); + glutSwapBuffers(); + } + + void keyboard(unsigned char key, int x, int y) + { + if (key == 27) + shut_down(1); + else if (key == 'b' || key == 'B') + enableBackFaceCull(); + else if (key == 's' || key == 'S') + enableScissorTest(); + else if (key == 't' || key == 'T') + enableStencilBuffer(); + else if (key == 'l' || key == 'L') + enableLight2(); + /* switch (key) + { + case(27): + shut_down(1); + break; + case('b' || 'B'): + enableBackFaceCull(); + break; + }*/ + glutPostRedisplay(); + } + + void updateCam(int x, int y) + { + + return; + } + void mouseMotion(int button, int state, int x, int y) + { + + if (button == GLUT_LEFT_BUTTON) { + + if (state == GLUT_UP) { + lastX = 0; + lastY = 0; + } + else if (state == GLUT_DOWN) { + lastX = x; + lastY = y; + glutMotionFunc(updateCam); + } + glutPostRedisplay(); + } + + return; + } + +#endif + +//------------------------------- +//----------SETUP STUFF---------- +//------------------------------- + +#ifdef __APPLE__ + void init(){ + + if (glfwInit() != GL_TRUE){ + shut_down(1); + } + + // 16 bit color, no depth, alpha or stencil buffers, windowed + if (glfwOpenWindow(width, height, 5, 6, 5, 0, 0, 0, GLFW_WINDOW) != GL_TRUE){ + shut_down(1); + } + + // Set up vertex array object, texture stuff + initVAO(); + initTextures(); + } +#else + void init(int argc, char* argv[]){ + glutInit(&argc, argv); + glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); + glutInitWindowSize(width, height); + glutCreateWindow("CIS565 Rasterizer"); + + // Init GLEW + glewInit(); + GLenum err = glewInit(); + if (GLEW_OK != err) + { + /* Problem: glewInit failed, something is seriously wrong. */ + std::cout << "glewInit failed, aborting." << std::endl; + exit (1); + } + + initVAO(); + initTextures(); + } +#endif + +void initPBO(GLuint* pbo){ + if (pbo) { + // set up vertex data parameter + int num_texels = width*height; + int num_values = num_texels * 4; + int size_tex_data = sizeof(GLubyte) * num_values; + + // Generate a buffer ID called a PBO (Pixel Buffer Object) + glGenBuffers(1,pbo); + // Make this the current UNPACK buffer (OpenGL is state-based) + glBindBuffer(GL_PIXEL_UNPACK_BUFFER, *pbo); + // Allocate data for the buffer. 4-channel 8-bit image + glBufferData(GL_PIXEL_UNPACK_BUFFER, size_tex_data, NULL, GL_DYNAMIC_COPY); + cudaGLRegisterBufferObject( *pbo ); + } +} + +void initCuda(){ + // Use device with highest Gflops/s + cudaGLSetGLDevice( cutGetMaxGflopsDeviceId() ); + + initPBO(&pbo); + + // Clean up on program exit + atexit(cleanupCuda); + + runCuda(); +} + +void initTextures(){ + glGenTextures(1,&displayImage); + glBindTexture(GL_TEXTURE_2D, displayImage); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_BGRA, + GL_UNSIGNED_BYTE, NULL); +} + +void initVAO(void){ + GLfloat vertices[] = + { + -1.0f, -1.0f, + 1.0f, -1.0f, + 1.0f, 1.0f, + -1.0f, 1.0f, + }; + + GLfloat texcoords[] = + { + 1.0f, 1.0f, + 0.0f, 1.0f, + 0.0f, 0.0f, + 1.0f, 0.0f + }; + + GLushort indices[] = { 0, 1, 3, 3, 1, 2 }; + + GLuint vertexBufferObjID[3]; + glGenBuffers(3, vertexBufferObjID); + + glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjID[0]); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); + glVertexAttribPointer((GLuint)positionLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); + glEnableVertexAttribArray(positionLocation); + + glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjID[1]); + glBufferData(GL_ARRAY_BUFFER, sizeof(texcoords), texcoords, GL_STATIC_DRAW); + glVertexAttribPointer((GLuint)texcoordsLocation, 2, GL_FLOAT, GL_FALSE, 0, 0); + glEnableVertexAttribArray(texcoordsLocation); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexBufferObjID[2]); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); +} + +GLuint initShader(const char *vertexShaderPath, const char *fragmentShaderPath){ + GLuint program = glslUtility::createProgram(vertexShaderPath, fragmentShaderPath, attributeLocations, 2); + GLint location; + + glUseProgram(program); + + if ((location = glGetUniformLocation(program, "u_image")) != -1) + { + glUniform1i(location, 0); + } + + return program; +} + +//------------------------------- +//---------CLEANUP STUFF--------- +//------------------------------- + +void cleanupCuda(){ + if(pbo) deletePBO(&pbo); + if(displayImage) deleteTexture(&displayImage); +} + +void deletePBO(GLuint* pbo){ + if (pbo) { + // unregister this buffer object with CUDA + cudaGLUnregisterBufferObject(*pbo); + + glBindBuffer(GL_ARRAY_BUFFER, *pbo); + glDeleteBuffers(1, pbo); + + *pbo = (GLuint)NULL; + } +} + +void deleteTexture(GLuint* tex){ + glDeleteTextures(1, tex); + *tex = (GLuint)NULL; +} + +void shut_down(int return_code){ + kernelCleanup(); + cudaDeviceReset(); + #ifdef __APPLE__ + glfwTerminate(); + #endif + exit(return_code); +} diff --git a/src/main.h b/src/main.h index 63bf0fa..3841224 100755 --- a/src/main.h +++ b/src/main.h @@ -1,105 +1,111 @@ -// CIS565 CUDA Rasterizer: A simple rasterization pipeline for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania -// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania - -#ifndef MAIN_H -#define MAIN_H - -#ifdef __APPLE__ - #include -#else - #include - #include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "glslUtility.h" -#include "glm/glm.hpp" -#include "rasterizeKernels.h" -#include "utilities.h" -#include "ObjCore/objloader.h" - -using namespace std; - -//------------------------------- -//------------GL STUFF----------- -//------------------------------- -int frame; -int fpstracker; -double seconds; -int fps = 0; -GLuint positionLocation = 0; -GLuint texcoordsLocation = 1; -const char *attributeLocations[] = { "Position", "Tex" }; -GLuint pbo = (GLuint)NULL; -GLuint displayImage; -uchar4 *dptr; - -obj* mesh; - -float* vbo; -int vbosize; -float* cbo; -int cbosize; -int* ibo; -int ibosize; - -//------------------------------- -//----------CUDA STUFF----------- -//------------------------------- - -int width=800; int height=800; - -//------------------------------- -//-------------MAIN-------------- -//------------------------------- - -int main(int argc, char** argv); - -//------------------------------- -//---------RUNTIME STUFF--------- -//------------------------------- - -void runCuda(); - -#ifdef __APPLE__ - void display(); -#else - void display(); - void keyboard(unsigned char key, int x, int y); -#endif - -//------------------------------- -//----------SETUP STUFF---------- -//------------------------------- - -#ifdef __APPLE__ - void init(); -#else - void init(int argc, char* argv[]); -#endif - -void initPBO(GLuint* pbo); -void initCuda(); -void initTextures(); -void initVAO(); -GLuint initShader(const char *vertexShaderPath, const char *fragmentShaderPath); - -//------------------------------- -//---------CLEANUP STUFF--------- -//------------------------------- - -void cleanupCuda(); -void deletePBO(GLuint* pbo); -void deleteTexture(GLuint* tex); -void shut_down(int return_code); - +// CIS565 CUDA Rasterizer: A simple rasterization pipeline for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania +// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania + +#ifndef MAIN_H +#define MAIN_H + +#ifdef __APPLE__ + #include +#else + #include + #include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "glslUtility.h" +#include "glm/glm.hpp" +#include "rasterizeKernels.h" +#include "utilities.h" +#include "ObjCore/objloader.h" + +using namespace std; + +//------------------------------- +//------------GL STUFF----------- +//------------------------------- +int frame; +int fpstracker; +double seconds; +int fps = 0; +GLuint positionLocation = 0; +GLuint texcoordsLocation = 1; +const char *attributeLocations[] = { "Position", "Tex" }; +GLuint pbo = (GLuint)NULL; +GLuint displayImage; +uchar4 *dptr; + +obj* mesh; + +float* vbo; +int vbosize; +float* cbo; +int cbosize; +int* ibo; +int ibosize; +float *nbo; +int nbosize; + +//------------------------------- +//----------CUDA STUFF----------- +//------------------------------- + +int width=800; int height=600; + + +//------------------------------- +//-------------MAIN-------------- +//------------------------------- + +int main(int argc, char** argv); + +//------------------------------- +//---------RUNTIME STUFF--------- +//------------------------------- + +void runCuda(); + +#ifdef __APPLE__ + void display(); +#else + void display(); + void keyboard(unsigned char key, int x, int y); + void mouseMotion(int button, int state, int x, int y); + void updateCam(int x, int y); + +#endif + +//------------------------------- +//----------SETUP STUFF---------- +//------------------------------- + +#ifdef __APPLE__ + void init(); +#else + void init(int argc, char* argv[]); +#endif + +void initPBO(GLuint* pbo); +void initCuda(); +void initTextures(); +void initVAO(); +GLuint initShader(const char *vertexShaderPath, const char *fragmentShaderPath); + +//------------------------------- +//---------CLEANUP STUFF--------- +//------------------------------- + +void cleanupCuda(); +void deletePBO(GLuint* pbo); +void deleteTexture(GLuint* tex); +void shut_down(int return_code); + #endif \ No newline at end of file diff --git a/src/rasterizeKernels.cu b/src/rasterizeKernels.cu index 826ec80..b8271f5 100755 --- a/src/rasterizeKernels.cu +++ b/src/rasterizeKernels.cu @@ -1,267 +1,459 @@ -// CIS565 CUDA Rasterizer: A simple rasterization pipeline for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania -// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania - -#include -#include -#include -#include -#include -#include "rasterizeKernels.h" -#include "rasterizeTools.h" - -glm::vec3* framebuffer; -fragment* depthbuffer; -float* device_vbo; -float* device_cbo; -int* device_ibo; -triangle* primitives; - -void checkCUDAError(const char *msg) { - cudaError_t err = cudaGetLastError(); - if( cudaSuccess != err) { - fprintf(stderr, "Cuda error: %s: %s.\n", msg, cudaGetErrorString( err) ); - exit(EXIT_FAILURE); - } -} - -//Handy dandy little hashing function that provides seeds for random number generation -__host__ __device__ unsigned int hash(unsigned int a){ - a = (a+0x7ed55d16) + (a<<12); - a = (a^0xc761c23c) ^ (a>>19); - a = (a+0x165667b1) + (a<<5); - a = (a+0xd3a2646c) ^ (a<<9); - a = (a+0xfd7046c5) + (a<<3); - a = (a^0xb55a4f09) ^ (a>>16); - return a; -} - -//Writes a given fragment to a fragment buffer at a given location -__host__ __device__ void writeToDepthbuffer(int x, int y, fragment frag, fragment* depthbuffer, glm::vec2 resolution){ - if(x255){ - color.x = 255; - } - - if(color.y>255){ - color.y = 255; - } - - if(color.z>255){ - color.z = 255; - } - - // Each thread writes one pixel location in the texture (textel) - PBOpos[index].w = 0; - PBOpos[index].x = color.x; - PBOpos[index].y = color.y; - PBOpos[index].z = color.z; - } -} - -//TODO: Implement a vertex shader -__global__ void vertexShadeKernel(float* vbo, int vbosize){ - int index = (blockIdx.x * blockDim.x) + threadIdx.x; - if(index>>(resolution, framebuffer, glm::vec3(0,0,0)); - - fragment frag; - frag.color = glm::vec3(0,0,0); - frag.normal = glm::vec3(0,0,0); - frag.position = glm::vec3(0,0,-10000); - clearDepthBuffer<<>>(resolution, depthbuffer,frag); - - //------------------------------ - //memory stuff - //------------------------------ - primitives = NULL; - cudaMalloc((void**)&primitives, (ibosize/3)*sizeof(triangle)); - - device_ibo = NULL; - cudaMalloc((void**)&device_ibo, ibosize*sizeof(int)); - cudaMemcpy( device_ibo, ibo, ibosize*sizeof(int), cudaMemcpyHostToDevice); - - device_vbo = NULL; - cudaMalloc((void**)&device_vbo, vbosize*sizeof(float)); - cudaMemcpy( device_vbo, vbo, vbosize*sizeof(float), cudaMemcpyHostToDevice); - - device_cbo = NULL; - cudaMalloc((void**)&device_cbo, cbosize*sizeof(float)); - cudaMemcpy( device_cbo, cbo, cbosize*sizeof(float), cudaMemcpyHostToDevice); - - tileSize = 32; - int primitiveBlocks = ceil(((float)vbosize/3)/((float)tileSize)); - - //------------------------------ - //vertex shader - //------------------------------ - vertexShadeKernel<<>>(device_vbo, vbosize); - - cudaDeviceSynchronize(); - //------------------------------ - //primitive assembly - //------------------------------ - primitiveBlocks = ceil(((float)ibosize/3)/((float)tileSize)); - primitiveAssemblyKernel<<>>(device_vbo, vbosize, device_cbo, cbosize, device_ibo, ibosize, primitives); - - cudaDeviceSynchronize(); - //------------------------------ - //rasterization - //------------------------------ - rasterizationKernel<<>>(primitives, ibosize/3, depthbuffer, resolution); - - cudaDeviceSynchronize(); - //------------------------------ - //fragment shader - //------------------------------ - fragmentShadeKernel<<>>(depthbuffer, resolution); - - cudaDeviceSynchronize(); - //------------------------------ - //write fragments to framebuffer - //------------------------------ - render<<>>(resolution, depthbuffer, framebuffer); - sendImageToPBO<<>>(PBOpos, resolution, framebuffer); - - cudaDeviceSynchronize(); - - kernelCleanup(); - - checkCUDAError("Kernel failed!"); -} - -void kernelCleanup(){ - cudaFree( primitives ); - cudaFree( device_vbo ); - cudaFree( device_cbo ); - cudaFree( device_ibo ); - cudaFree( framebuffer ); - cudaFree( depthbuffer ); -} - +// CIS565 CUDA Rasterizer: A simple rasterization pipeline for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania +// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania + +#include +#include +#include +#include +#include +#include +#include "rasterizeKernels.h" +#include "rasterizeTools.h" + + +glm::vec3* framebuffer; +fragment* depthbuffer; +float* device_vbo; +float* device_cbo; +int* device_ibo; +triangle* primitives; + + +using namespace std; + +void checkCUDAError(const char *msg) { + cudaError_t err = cudaGetLastError(); + if( cudaSuccess != err) { + fprintf(stderr, "Cuda error: %s: %s.\n", msg, cudaGetErrorString( err) ); + exit(EXIT_FAILURE); + } +} + +//Handy dandy little hashing function that provides seeds for random number generation +__host__ __device__ unsigned int hash(unsigned int a){ + a = (a+0x7ed55d16) + (a<<12); + a = (a^0xc761c23c) ^ (a>>19); + a = (a+0x165667b1) + (a<<5); + a = (a+0xd3a2646c) ^ (a<<9); + a = (a+0xfd7046c5) + (a<<3); + a = (a^0xb55a4f09) ^ (a>>16); + return a; +} + +//Writes a given fragment to a fragment buffer at a given location +__host__ __device__ void writeToDepthbuffer(int x, int y, fragment frag, fragment* depthbuffer, glm::vec2 resolution){ + if(x255){ + color.x = 255; + } + + if(color.y>255){ + color.y = 255; + } + + if(color.z>255){ + color.z = 255; + } + + // Each thread writes one pixel location in the texture (textel) + PBOpos[index].w = 0; + PBOpos[index].x = color.x; + PBOpos[index].y = color.y; + PBOpos[index].z = color.z; + } +} + +//TODO: Implement a vertex shader +__global__ void vertexShadeKernel(float* vbo, int vbosize,glm::mat4 mvp){ + + + int index = (blockIdx.x * blockDim.x) + threadIdx.x; + if(index depthbuffer[ dBufIndex].position.z ) + { + depthbuffer[dBufIndex] = frag; + + } + syncLoop = false; + depthbuffer[ dBufIndex].syncLock = 0; + } + } + } + } // end x loop + }//end y loop + } + }//end (index 0) + { + float spec = powf( cosAngle, specularExponent) * glm::dot(specularColor,depthbuffer[index].color) ; + if(spec > 0){ + colors += depthbuffer[index].color*spec * diffuseLightColor;// * depthbuffer[index].color; + } + } + colors+=(depthbuffer[index].color*diffuse) * diffuseLightColor + 0.15f * ambientColor * depthbuffer[index].color; + if(enableLIGHT2){ + glm::vec3 lightPos2 = glm::vec3(2,2.5,1.0f); + glm::vec3 lightDir2 = glm::normalize(lightPos2 - depthbuffer[index].position); + float diffuse2 = glm::max(glm::dot(depthbuffer[index].normal, lightDir2), 0.0f); + float cosAngle2 = glm::max(glm::dot(camDir, lightDir2 - 2.0f * glm::dot( lightDir2, depthbuffer[index].normal ) * depthbuffer[index].normal ),0.0f); + if (cosAngle2 > 0) + { + float spec2 = powf( cosAngle2, 10.0f) * glm::dot(specularColor,depthbuffer[index].color) ; + if(spec2 > 0){ + colors += depthbuffer[index].color*spec2 * diffuseLightColor;// * depthbuffer[index].color; + } + } + colors+=(depthbuffer[index].color*diffuse) * diffuseLightColor; + + } + depthbuffer[index].color = colors; + } +} + +//Writes fragment colors to the framebuffer +__global__ void render(glm::vec2 resolution, fragment* depthbuffer, glm::vec3* framebuffer){ + + 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){ + framebuffer[index] = depthbuffer[index].color; + } +} + +// 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, float* nbo, int nbosize){ + + // set up crucial magic + int tileSize = 8; + dim3 threadsPerBlock(tileSize, tileSize); + dim3 fullBlocksPerGrid((int)ceil(float(resolution.x)/float(tileSize)), (int)ceil(float(resolution.y)/float(tileSize))); + + //set up framebuffer + framebuffer = NULL; + cudaMalloc((void**)&framebuffer, (int)resolution.x*(int)resolution.y*sizeof(glm::vec3)); + + //set up depthbuffer + depthbuffer = NULL; + cudaMalloc((void**)&depthbuffer, (int)resolution.x*(int)resolution.y*sizeof(fragment)); + + //kernel launches to black out accumulated/unaccumlated pixel buffers and clear our scattering states + clearImage<<>>(resolution, framebuffer, glm::vec3(0,0,0)); + + fragment frag; + frag.color = glm::vec3(0,0,0); + frag.normal = glm::vec3(0,0,0); + frag.position = glm::vec3(0,0,-10000); + frag.syncLock = 0; + frag.distance = -10000; + clearDepthBuffer<<>>(resolution, depthbuffer,frag); + + + //------------------------------ + //Seting up the Projection Matrix + //------------------------------ + glm::mat4 model = glm::mat4(1.0f); + //rotating position for the model + model = glm::rotate(model,frame, glm::vec3(0.0f, 1.0f, 0.0f)); + glm::mat4 modelViewProj = projection * view * model; + + //matrix used to transform the corrdinates into pixel coordinates + glm::mat3 sm = glm::mat3(resolution.x / 2, 0, 0, 0, resolution.y / 2, 0, 0, 0, 1); + + + //------------------------------ + //memory stuff + //------------------------------ + primitives = NULL; + cudaMalloc((void**)&primitives, (ibosize/3)*sizeof(triangle)); + + device_ibo = NULL; + cudaMalloc((void**)&device_ibo, ibosize*sizeof(int)); + cudaMemcpy( device_ibo, ibo, ibosize*sizeof(int), cudaMemcpyHostToDevice); + + device_vbo = NULL; + cudaMalloc((void**)&device_vbo, vbosize*sizeof(float)); + cudaMemcpy( device_vbo, vbo, vbosize*sizeof(float), cudaMemcpyHostToDevice); + + device_cbo = NULL; + cudaMalloc((void**)&device_cbo, cbosize*sizeof(float)); + cudaMemcpy( device_cbo, cbo, cbosize*sizeof(float), cudaMemcpyHostToDevice); + + float * device_nbo = NULL; + cudaMalloc((void**)&device_nbo, nbosize*sizeof(float)); + cudaMemcpy( device_nbo, nbo, nbosize*sizeof(float), cudaMemcpyHostToDevice); + + tileSize = 32; + int primitiveBlocks = ceil(((float)vbosize/3)/((float)tileSize)); + + //------------------------------ + //vertex shader + //------------------------------ + vertexShadeKernel<<>>(device_vbo, vbosize, modelViewProj); + + cudaDeviceSynchronize(); + //------------------------------ + //primitive assembly + //------------------------------ + glm::vec4 viewport = glm::vec4(0.0, 0.0, resolution.x, resolution.y); + primitiveBlocks = ceil(((float)ibosize/3)/((float)tileSize)); + primitiveAssemblyKernel<<>>(device_vbo, vbosize, device_cbo, cbosize, device_ibo, ibosize,device_nbo, nbosize, primitives, cameraPos, model, projection,view, viewport, enableBACKFACECULL); + + cudaDeviceSynchronize(); + + //display the number of primitives currently displayed after back face cull + if(enableSTENCILTEST){ + int count = 0; + for(int i =0;i>>(primitives, ibosize/3, depthbuffer, resolution, sm, enableSCISSORTEST, scissorTestWindow); + + cudaDeviceSynchronize(); + //------------------------------ + //fragment shader + //------------------------------ + fragmentShadeKernel<<>>(depthbuffer, resolution, cameraPos, lightPos, diffuseLightColor, specularColor, specularExponent, ambientColor, enableLIGHT2); + + cudaDeviceSynchronize(); + //------------------------------ + //write fragments to framebuffer + //------------------------------ + render<<>>(resolution, depthbuffer, framebuffer); + sendImageToPBO<<>>(PBOpos, resolution, framebuffer); + + cudaDeviceSynchronize(); + + kernelCleanup(); +// delete device_vbo1; + cudaFree( device_nbo ); + + checkCUDAError("Kernel failed!"); +} + +void kernelCleanup(){ + cudaFree( primitives ); + cudaFree( device_vbo ); + cudaFree( device_cbo ); + cudaFree( device_ibo ); + cudaFree( framebuffer ); + cudaFree( depthbuffer ); +} + +void enableBackFaceCull(){ + + enableBACKFACECULL = !enableBACKFACECULL; +} +void enableScissorTest(){ + enableSCISSORTEST = !enableSCISSORTEST; +} + +void enableStencilBuffer(){ + enableSTENCILTEST = !enableSTENCILTEST; +} +void resetTransformations(float x, float y){ + + /*cameraPos.x = x; + cameraPos.y = y; + view = glm::lookAt(cameraPos, + glm::vec3(0.0, 0.5, 0),//look at + glm::vec3(0, -1, 0));//Head*/ + + +} +void enableLight2(){ + enableLIGHT2 = !enableLIGHT2; +} \ No newline at end of file diff --git a/src/rasterizeKernels.h b/src/rasterizeKernels.h index bef3653..3d8c637 100755 --- a/src/rasterizeKernels.h +++ b/src/rasterizeKernels.h @@ -1,17 +1,24 @@ -// CIS565 CUDA Rasterizer: A simple rasterization pipeline for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania -// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania - -#ifndef RASTERIZEKERNEL_H -#define RASTERIZEKERNEL_H - -#include -#include -#include -#include -#include -#include "glm/glm.hpp" - -void kernelCleanup(); -void cudaRasterizeCore(uchar4* pos, glm::vec2 resolution, float frame, float* vbo, int vbosize, float* cbo, int cbosize, int* ibo, int ibosize); - -#endif //RASTERIZEKERNEL_H +// CIS565 CUDA Rasterizer: A simple rasterization pipeline for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania +// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania + +#ifndef RASTERIZEKERNEL_H +#define RASTERIZEKERNEL_H + +#include +#include +#include +#include +#include +#include "glm/glm.hpp" +#include "glm/gtc/matrix_transform.hpp" + + +void enableBackFaceCull(); +void enableScissorTest(); +void enableStencilBuffer(); +void enableLight2(); +void resetTransformations(float x, float y); +void kernelCleanup(); +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); + +#endif //RASTERIZEKERNEL_H diff --git a/src/rasterizeTools.h b/src/rasterizeTools.h index e9b5dcc..469b7f0 100755 --- a/src/rasterizeTools.h +++ b/src/rasterizeTools.h @@ -1,78 +1,110 @@ -// CIS565 CUDA Rasterizer: A simple rasterization pipeline for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania -// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania - -#ifndef RASTERIZETOOLS_H -#define RASTERIZETOOLS_H - -#include -#include "glm/glm.hpp" -#include "utilities.h" -#include "cudaMat4.h" - -struct triangle { - glm::vec3 p0; - glm::vec3 p1; - glm::vec3 p2; - glm::vec3 c0; - glm::vec3 c1; - glm::vec3 c2; -}; - -struct fragment{ - glm::vec3 color; - glm::vec3 normal; - glm::vec3 position; -}; - -//Multiplies a cudaMat4 matrix and a vec4 -__host__ __device__ glm::vec3 multiplyMV(cudaMat4 m, glm::vec4 v){ - glm::vec3 r(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); - 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), - min(min(tri.p0.y, tri.p1.y),tri.p2.y), - min(min(tri.p0.z, tri.p1.z),tri.p2.z)); - maxpoint = glm::vec3(max(max(tri.p0.x, tri.p1.x),tri.p2.x), - max(max(tri.p0.y, tri.p1.y),tri.p2.y), - max(max(tri.p0.z, tri.p1.z),tri.p2.z)); -} - -//LOOK: calculates the signed area of a given triangle -__host__ __device__ float calculateSignedArea(triangle tri){ - return 0.5*((tri.p2.x - tri.p0.x)*(tri.p1.y - tri.p0.y) - (tri.p1.x - tri.p0.x)*(tri.p2.y - tri.p0.y)); -} - -//LOOK: helper function for calculating barycentric coordinates -__host__ __device__ float calculateBarycentricCoordinateValue(glm::vec2 a, glm::vec2 b, glm::vec2 c, triangle tri){ - triangle baryTri; - baryTri.p0 = glm::vec3(a,0); baryTri.p1 = glm::vec3(b,0); baryTri.p2 = glm::vec3(c,0); - return calculateSignedArea(baryTri)/calculateSignedArea(tri); -} - -//LOOK: calculates barycentric coordinates -__host__ __device__ glm::vec3 calculateBarycentricCoordinate(triangle tri, glm::vec2 point){ - float beta = calculateBarycentricCoordinateValue(glm::vec2(tri.p0.x,tri.p0.y), point, glm::vec2(tri.p2.x,tri.p2.y), tri); - float gamma = calculateBarycentricCoordinateValue(glm::vec2(tri.p0.x,tri.p0.y), glm::vec2(tri.p1.x,tri.p1.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 && - barycentricCoord.y >= 0.0 && barycentricCoord.y <= 1.0 && - barycentricCoord.z >= 0.0 && barycentricCoord.z <= 1.0; -} - -//LOOK: for a given barycentric coordinate, return the corresponding z position on the triangle -__host__ __device__ float getZAtCoordinate(glm::vec3 barycentricCoord, triangle tri){ - return -(barycentricCoord.x*tri.p0.z + barycentricCoord.y*tri.p1.z + barycentricCoord.z*tri.p2.z); -} - +// CIS565 CUDA Rasterizer: A simple rasterization pipeline for Patrick Cozzi's CIS565: GPU Computing at the University of Pennsylvania +// Written by Yining Karl Li, Copyright (c) 2012 University of Pennsylvania + +#ifndef RASTERIZETOOLS_H +#define RASTERIZETOOLS_H + +#include +#include "glm/glm.hpp" +#include "utilities.h" +#include "cudaMat4.h" + +struct triangle { + glm::vec3 p0; + glm::vec3 p1; + glm::vec3 p2; + glm::vec3 c0; + glm::vec3 c1; + glm::vec3 c2; + float backFace; + +}; + +struct fragment{ + glm::vec3 color; + glm::vec3 normal; + glm::vec3 position; + int syncLock; + float distance; + +}; + +/************************************TRANSFORMATION SETTINGS**********************************************************/ +glm::vec3 cameraPos = glm::vec3(0.0f, 1.5f, 4.5f); +glm::mat4 projection = glm::perspective(30.0f, static_cast(200) / static_cast(200), 0.1f, 50.0f); +glm::mat4 view = glm::lookAt(cameraPos, + glm::vec3(0.0, 0.5, 0),//look at + glm::vec3(0, -1, 0));//Head +glm::mat4 model = glm::mat4(1.0f); + +/**********************************LIGHT SETTINGS******************************************************************/ +glm::vec3 lightPos = glm::vec3(0,4.5,0.0f); +glm::vec3 diffuseLightColor = glm::vec3(1.0); +glm::vec3 specularColor = glm::vec3(1.0, 1.0,1.0); +float specularExponent = 5.0f; +glm::vec3 ambientColor = glm::vec3(1.0,1.0,1.0); +bool enableLIGHT2; + + + +/*********************************TESTING*************************************************************************/ +bool enableBACKFACECULL; +bool enableSCISSORTEST; +bool enableSTENCILTEST; + +glm::vec4 scissorTestWindow = glm::vec4(300,100,400,300); + +glm::vec4 stencilWindow[2]; + +//Multiplies a cudaMat4 matrix and a vec4 +__host__ __device__ glm::vec3 multiplyMV(cudaMat4 m, glm::vec4 v){ + glm::vec3 r(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); + 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), + min(min(tri.p0.y, tri.p1.y),tri.p2.y), + min(min(tri.p0.z, tri.p1.z),tri.p2.z)); + maxpoint = glm::vec3(max(max(tri.p0.x, tri.p1.x),tri.p2.x), + max(max(tri.p0.y, tri.p1.y),tri.p2.y), + max(max(tri.p0.z, tri.p1.z),tri.p2.z)); +} + +//LOOK: calculates the signed area of a given triangle +__host__ __device__ float calculateSignedArea(triangle tri){ + return 0.5*((tri.p2.x - tri.p0.x)*(tri.p1.y - tri.p0.y) - (tri.p1.x - tri.p0.x)*(tri.p2.y - tri.p0.y)); +} + +//LOOK: helper function for calculating barycentric coordinates +__host__ __device__ float calculateBarycentricCoordinateValue(glm::vec2 a, glm::vec2 b, glm::vec2 c, triangle tri){ + triangle baryTri; + baryTri.p0 = glm::vec3(a,0); baryTri.p1 = glm::vec3(b,0); baryTri.p2 = glm::vec3(c,0); + return calculateSignedArea(baryTri)/calculateSignedArea(tri); +} + +//LOOK: calculates barycentric coordinates +__host__ __device__ glm::vec3 calculateBarycentricCoordinate(triangle tri, glm::vec2 point){ + float beta = calculateBarycentricCoordinateValue(glm::vec2(tri.p0.x,tri.p0.y), point, glm::vec2(tri.p2.x,tri.p2.y), tri); + float gamma = calculateBarycentricCoordinateValue(glm::vec2(tri.p0.x,tri.p0.y), glm::vec2(tri.p1.x,tri.p1.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 && barycentricCoord.y >= 0.0 && barycentricCoord.y <= 1.0 && barycentricCoord.z >= 0.0 && barycentricCoord.z <= 1.0; +// return barycentricCoord.x >= 0.0 && barycentricCoord.y >= 0.0 && (barycentricCoord.x+ barycentricCoord.y) <=1; +} + +//LOOK: for a given barycentric coordinate, return the corresponding z position on the triangle +__host__ __device__ float getZAtCoordinate(glm::vec3 barycentricCoord, triangle tri){ + return (barycentricCoord.x*tri.p0.z + barycentricCoord.y*tri.p1.z + barycentricCoord.z*tri.p2.z); +} + #endif \ No newline at end of file