diff --git a/README.md b/README.md index a744a2e..0f5acaf 100644 --- a/README.md +++ b/README.md @@ -1,249 +1,68 @@ -Instructions - Vulkan Grass Rendering -======================== +# Vulkan Grass Rendering +================ -This is due **Sunday 11/5, evening at midnight**. +**University of Pennsylvania, CIS 565: GPU Programming and Architecture, Project 6** -**Summary:** -In this project, you will use Vulkan to implement a grass simulator and renderer. You will -use compute shaders to perform physics calculations on Bezier curves that represent individual -grass blades in your application. Since rendering every grass blade on every frame will is fairly -inefficient, you will also use compute shaders to cull grass blades that don't contribute to a given frame. -The remaining blades will be passed to a graphics pipeline, in which you will write several shaders. -You will write a vertex shader to transform Bezier control points, tessellation shaders to dynamically create -the grass geometry from the Bezier curves, and a fragment shader to shade the grass blades. +* Name: William Ho +* Email: willho@seas.upenn.edu +* Tested on: Windows 10 Home, Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz, 20.4GB, GeForce GT 730 -The base code provided includes all of the basic Vulkan setup, including a compute pipeline that will run your compute -shaders and two graphics pipelines, one for rendering the geometry that grass will be placed on and the other for -rendering the grass itself. Your job will be to write the shaders for the grass graphics pipeline and the compute pipeline, -as well as binding any resources (descriptors) you may need to accomplish the tasks described in this assignment. +# Overview -![](img/grass.gif) +![](img/grassDemoGif.gif) +![](img/ScreenCaptureProject3.gif) -You are not required to use this base code if you don't want -to. You may also change any part of the base code as you please. -**This is YOUR project.** The above .gif is just a simple example that you -can use as a reference to compare to. - -**Important:** -- If you are not in CGGT/DMD, you may replace this project with a GPU compute -project. You MUST get this pre-approved by Austin Eng before continuing! - -### Contents - -* `src/` C++/Vulkan source files. - * `shaders/` glsl shader source files - * `images/` images used as textures within graphics pipelines -* `external/` Includes and static libraries for 3rd party libraries. -* `img/` Screenshots and images to use in your READMEs - -### Installing Vulkan - -In order to run a Vulkan project, you first need to download and install the [Vulkan SDK](https://vulkan.lunarg.com/). -Make sure to run the downloaded installed as administrator so that the installer can set the appropriate environment -variables for you. - -Once you have done this, you need to make sure your GPU driver supports Vulkan. Download and install a -[Vulkan driver](https://developer.nvidia.com/vulkan-driver) from NVIDIA's website. - -Finally, to check that Vulkan is ready for use, go to your Vulkan SDK directory (`C:/VulkanSDK/` unless otherwise specified) -and run the `cube.exe` example within the `Bin` directory. IF you see a rotating gray cube with the LunarG logo, then you -are all set! - -### Running the code - -While developing your grass renderer, you will want to keep validation layers enabled so that error checking is turned on. -The project is set up such that when you are in `debug` mode, validation layers are enabled, and when you are in `release` mode, -validation layers are disabled. After building the code, you should be able to run the project without any errors. You will see -a plane with a grass texture on it to begin with. - -![](img/cube_demo.png) - -## Requirements - -**Ask on the mailing list for any clarifications.** - -In this project, you are given the following code: - -* The basic setup for a Vulkan project, including the swapchain, physical device, logical device, and the pipelines described above. -* Structs for some of the uniform buffers you will be using. -* Some buffer creation utility functions. -* A simple interactive camera using the mouse. - -You need to implement the following features/pipeline stages: - -* Compute shader (`shaders/compute.comp`) -* Grass pipeline stages - * Vertex shader (`shaders/grass.vert') - * Tessellation control shader (`shaders/grass.tesc`) - * Tessellation evaluation shader (`shaders/grass.tese`) - * Fragment shader (`shaders/grass.frag`) -* Binding of any extra descriptors you may need - -See below for more guidance. - -## Base Code Tour - -Areas that you need to complete are -marked with a `TODO` comment. Functions that are useful -for reference are marked with the comment `CHECKITOUT`. - -* `src/main.cpp` is the entry point of our application. -* `src/Instance.cpp` sets up the application state, initializes the Vulkan library, and contains functions that will create our -physical and logical device handles. -* `src/Device.cpp` manages the logical device and sets up the queues that our command buffers will be submitted to. -* `src/Renderer.cpp` contains most of the rendering implementation, including Vulkan setup and resource creation. You will -likely have to make changes to this file in order to support changes to your pipelines. -* `src/Camera.cpp` manages the camera state. -* `src/Model.cpp` manages the state of the model that grass will be created on. Currently a plane is hardcoded, but feel free to -update this with arbitrary model loading! -* `src/Blades.cpp` creates the control points corresponding to the grass blades. There are many parameters that you can play with -here that will change the behavior of your rendered grass blades. -* `src/Scene.cpp` manages the scene state, including the model, blades, and simualtion time. -* `src/BufferUtils.cpp` provides helper functions for creating buffers to be used as descriptors. - -We left out descriptions for a couple files that you likely won't have to modify. Feel free to investigate them to understand their -importance within the scope of the project. - -## Grass Rendering - -This project is an implementation of the paper, [Responsive Real-Time Grass Rendering for General 3D Scenes](https://www.cg.tuwien.ac.at/research/publications/2017/JAHRMANN-2017-RRTG/JAHRMANN-2017-RRTG-draft.pdf). -Please make sure to use this paper as a primary resource while implementing your grass renderers. It does a great job of explaining -the key algorithms and math you will be using. Below is a brief description of the different components in chronological order of how your renderer will -execute, but feel free to develop the components in whatever order you prefer. - -### Representing Grass as Bezier Curves - -In this project, grass blades will be represented as Bezier curves while performing physics calculations and culling operations. -Each Bezier curve has three control points. -* `v0`: the position of the grass blade on the geomtry -* `v1`: a Bezier curve guide that is always "above" `v0` with respect to the grass blade's up vector (explained soon) -* `v2`: a physical guide for which we simulate forces on - -We also need to store per-blade characteristics that will help us simulate and tessellate our grass blades correctly. -* `up`: the blade's up vector, which corresponds to the normal of the geometry that the grass blade resides on at `v0` -* Orientation: the orientation of the grass blade's face -* Height: the height of the grass blade -* Width: the width of the grass blade's face -* Stiffness coefficient: the stiffness of our grass blade, which will affect the force computations on our blade - -We can pack all this data into four `vec4`s, such that `v0.w` holds orientation, `v1.w` holds height, `v2.w` holds width, and -`up.w` holds the stiffness coefficient. - -![](img/blade_model.jpg) +This project is an implementation of the paper [Responsive Real-Time Grass Grass Rendering for General 3D Scenes](https://www.cg.tuwien.ac.at/research/publications/2017/JAHRMANN-2017-RRTG/JAHRMANN-2017-RRTG-draft.pdf). I use compute shaders in a Vulkan compute pipeline to simulate physical forces on blades of grass, which are modeled as bezier curves composed of 3 control points. A separate graphics pipeline is used to tesselate the grass blades and rasterize them. ### Simulating Forces -In this project, you will be simulating forces on grass blades while they are still Bezier curves. This will be done in a compute -shader using the compute pipeline that has been created for you. Remember that `v2` is our physical guide, so we will be -applying transformations to `v2` initially, then correcting for potential errors. We will finally update `v1` to maintain the appropriate -length of our grass blade. - -#### Binding Resources +I simulate the effects of three forces on every blade of grass. Each blade of grass is given its own width, height, orientation, and stiffness coefficient within a probability distribution. These values determine how a single blade of grass will behave in relation to the following forces: -In order to update the state of your grass blades on every frame, you will need to create a storage buffer to maintain the grass data. -You will also need to pass information about how much time has passed in the simulation and the time since the last frame. To do this, -you can extend or create descriptor sets that will be bound to the compute pipeline. +- Gravity: The force of gravity is applied to show the realistic bending of the grass blades as their weight pulls them down. It is composed of two components, an environmental gravity force, and a "front" gravity force that depends on the blades orientation. -#### Gravity +- Recovery: The force which a blade of grass exerts on itself to try and return to its initial position. -Given a gravity direction, `D.xyz`, and the magnitude of acceleration, `D.w`, we can compute the environmental gravity in -our scene as `gE = normalize(D.xyz) * D.w`. +- Wind: The directional force of wind at the location of the blade. -We then determine the contribution of the gravity with respect to the front facing direction of the blade, `f`, -as a term called the "front gravity". Front gravity is computed as `gF = (1/4) * ||gE|| * f`. +The total force acting on a blade of grass is simply the sum of these 3 forces multiplied by the time change between frames. I simulate these forces for every blade in the simulation, however, there are several culling operations that can be performed that eliminate the need to render all of the blades. -We can then determine the total gravity on the grass blade as `g = gE + gF`. +### Culling -#### Recovery +#### Orientation Culling -Recovery corresponds to the counter-force that brings our grass blade back into equilibrium. This is derived in the paper using Hooke's law. -In order to determine the recovery force, we need to compare the current position of `v2` to its original position before -simulation started, `iv2`. At the beginning of our simulation, `v1` and `v2` are initialized to be a distance of the blade height along the `up` vector. +Since the blades of grass are modeled as flat 2D tessellated geometry, blades viewed at an angle perpendicular to their face normal can result in visual artifacts that lower image quality. Furthermore, as they contribute very little to the scene, these blades can be culled using a simple dot product test. From any given view, the number of such blades is relatively small, but it does grant a modest speed improvement. -Once we have `iv2`, we can compute the recovery forces as `r = (iv2 - v2) * stiffness`. +![](img/data/normals.PNG) -#### Wind +#### View-frustum Culling -In order to simulate wind, you are at liberty to create any wind function you want! In order to have something interesting, -you can make the function depend on the position of `v0` and a function that changes with time. Consider using some combination -of sine or cosine functions. +Of course, blades outside the camera's view frustrum need not be rendered, and those can be culled as well. My implementation is to cull based on the first control point of a given blade, which is located at the point it connects to the ground. This seems to result in the cleanest culling, as using other control points can lead to flickering at the edges. However, having some margin on each dimension of the frustrum is advisable since it is possible to accidentally cull a blade whose top should be visible. -Your wind function will determine a wind direction that is affecting the blade, but it is also worth noting that wind has a larger impact on -grass blades whose forward directions are parallel to the wind direction. The paper describes this as a "wind alignment" term. We won't go -over the exact math here, but use the paper as a reference when implementing this. It does a great job of explaining this! +#### Distance Based Culling +|No Distance Culling (2^14 blades) | Distance Culling (2^15 blades) | +|:----:|:----:| +|![](img/NoDistanceCulling2pow14.PNG)|![](img/DistanceCulling2pow15.PNG)| -Once you have a wind direction and a wind alignment term, your total wind force (`w`) will be `windDirection * windAlignment`. +Distance based culling is used to leverage the fact that we can achieve similar visual results by having a greater concentration of blades closer to the camera and fewer blades as we move away. In my implementation, blades are placed into buckets based on how far from the camera they are. At each successive bucket further from the camera, the probability of a blade being culled increases based on a pseudo random probability distribution function. The debug screenshot below illustrates this using the center of the scene in place of the camera eye. -#### Total force +![](img/DistanceCullingDebug.PNG) -We can then determine a translation for `v2` based on the forces as `tv2 = (gravity + recovery + wind) * deltaTime`. However, we can't simply -apply this translation and expect the simulation to be robust. Our forces might push `v2` under the ground! Similarly, moving `v2` but leaving -`v1` in the same position will cause our grass blade to change length, which doesn't make sense. +Some tweaking is required with this culling method. My implementation increases the "culling probability" exponentially away from the camera, but it would be worth it to explore what might be optimal. It is also important to note that we want to balance between gaining time wins and culling too many blades. In the examples above, we achieve comparable images from rendering 2^14 blades without culling and rendering 2^15 blades with my current distance based culling method. However, note that as shown by the chart below, the right side image still had a significant time win. -Read section 5.2 of the paper in order to learn how to determine the corrected final positions for `v1` and `v2`. +![](img/data/distanceCulling.PNG) -### Culling tests -Although we need to simulate forces on every grass blade at every frame, there are many blades that we won't need to render -due to a variety of reasons. Here are some heuristics we can use to cull blades that won't contribute positively to a given frame. +### Distance Based Tessellation -#### Orientation culling +|No Distance Based Tessellation (2^16 blades) | Distance Based Tesselation (2^16 blades) | +|:----:|:----:| +|![](img/NoDistanceBasedTesselation2pow16.PNG)|![](img/DistanceBasedTesselation2pow16.PNG)| -Consider the scenario in which the front face direction of the grass blade is perpendicular to the view vector. Since our grass blades -won't have width, we will end up trying to render parts of the grass that are actually smaller than the size of a pixel. This could -lead to aliasing artifacts. +Similarly to culling based on distance form the camera, we can leverage the fact that at farther distances from the camera, blades do not need to be modelled in as high definition. By reducing tessellation parameters based on distance, we can gain a very significant time optimization (~50%) where the visual differences are almost imperceptible. -In order to remedy this, we can cull these blades! Simply do a dot product test to see if the view vector and front face direction of -the blade are perpendicular. The paper uses a threshold value of `0.9` to cull, but feel free to use what you think looks best. +![](img/data/distanceTessellation.PNG) -#### View-frustum culling - -We also want to cull blades that are outside of the view-frustum, considering they won't show up in the frame anyway. To determine if -a grass blade is in the view-frustum, we want to compare the visibility of three points: `v0, v2, and m`, where `m = (1/4)v0 * (1/2)v1 * (1/4)v2`. -Notice that we aren't using `v1` for the visibility test. This is because the `v1` is a Bezier guide that doesn't represent a position on the grass blade. -We instead use `m` to approximate the midpoint of our Bezier curve. - -If all three points are outside of the view-frustum, we will cull the grass blade. The paper uses a tolerance value for this test so that we are culling -blades a little more conservatively. This can help with cases in which the Bezier curve is technically not visible, but we might be able to see the blade -if we consider its width. - -#### Distance culling - -Similarly to orientation culling, we can end up with grass blades that at large distances are smaller than the size of a pixel. This could lead to additional -artifacts in our renders. In this case, we can cull grass blades as a function of their distance from the camera. - -You are free to define two parameters here. -* A max distance afterwhich all grass blades will be culled. -* A number of buckets to place grass blades between the camera and max distance into. - -Define a function such that the grass blades in the bucket closest to the camera are kept while an increasing number of grass blades -are culled with each farther bucket. - -#### Occlusion culling (extra credit) - -This type of culling only makes sense if our scene has additional objects aside from the plane and the grass blades. We want to cull grass blades that -are occluded by other geometry. Think about how you can use a depth map to accomplish this! - -### Tessellating Bezier curves into grass blades - -In this project, you should pass in each Bezier curve as a single patch to be processed by your grass graphics pipeline. You will tessellate this patch into -a quad with a shape of your choosing (as long as it looks sufficiently like grass of course). The paper has some examples of grass shapes you can use as inspiration. - -In the tessellation control shader, specify the amount of tessellation you want to occur. Remember that you need to provide enough detail to create the curvature of a grass blade. - -The generated vertices will be passed to the tessellation evaluation shader, where you will place the vertices in world space, respecting the width, height, and orientation information -of each blade. Once you have determined the world space position of each vector, make sure to set the output `gl_Position` in clip space! - -** Extra Credit**: Tessellate to varying levels of detail as a function of how far the grass blade is from the camera. For example, if the blade is very far, only generate four vertices in the tessellation control shader. - -To build more intuition on how tessellation works, I highly recommend playing with the [helloTessellation sample](https://github.com/CIS565-Fall-2017/Vulkan-Samples/tree/master/samples/5_helloTessellation) -and reading this [tutorial on tessellation](http://in2gpu.com/2014/07/12/tessellation-tutorial-opengl-4-3/). - -## Resources - -### Links - -The following resources may be useful for this project. +### References * [Responsive Real-Time Grass Grass Rendering for General 3D Scenes](https://www.cg.tuwien.ac.at/research/publications/2017/JAHRMANN-2017-RRTG/JAHRMANN-2017-RRTG-draft.pdf) * [CIS565 Vulkan samples](https://github.com/CIS565-Fall-2017/Vulkan-Samples) @@ -252,46 +71,3 @@ The following resources may be useful for this project. * [RenderDoc blog on Vulkan](https://renderdoc.org/vulkan-in-30-minutes.html) * [Tessellation tutorial](http://in2gpu.com/2014/07/12/tessellation-tutorial-opengl-4-3/) - -## Third-Party Code Policy - -* Use of any third-party code must be approved by asking on our Google Group. -* 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 path 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, at minimum, - result in you receiving an F for the semester. - - -## README - -* A brief description of the project and the specific features you implemented. -* At least one screenshot of your project running. -* A performance analysis (described below). - -### Performance Analysis - -The performance analysis is where you will investigate how... -* Your renderer handles varying numbers of grass blades -* The improvement you get by culling using each of the three culling tests - -## Submit - -If you have modified any of the `CMakeLists.txt` files at all (aside from the -list of `SOURCE_FILES`), mentions it explicity. -Beware of any build issues discussed on the Google Group. - -Open a GitHub pull request so that we can see that you have finished. -The title should be "Project 6: YOUR NAME". -The template of the comment section of your pull request is attached below, you can do some copy and paste: - -* [Repo Link](https://link-to-your-repo) -* (Briefly) Mentions features that you've completed. Especially those bells and whistles you want to highlight - * Feature 0 - * Feature 1 - * ... -* Feedback on the project itself, if any. diff --git a/img/DistanceBasedTesselation2pow16.PNG b/img/DistanceBasedTesselation2pow16.PNG new file mode 100644 index 0000000..eeb03ab Binary files /dev/null and b/img/DistanceBasedTesselation2pow16.PNG differ diff --git a/img/DistanceBasedTesselation2pow18.PNG b/img/DistanceBasedTesselation2pow18.PNG new file mode 100644 index 0000000..692645a Binary files /dev/null and b/img/DistanceBasedTesselation2pow18.PNG differ diff --git a/img/DistanceCulling2pow15.PNG b/img/DistanceCulling2pow15.PNG new file mode 100644 index 0000000..8b334c3 Binary files /dev/null and b/img/DistanceCulling2pow15.PNG differ diff --git a/img/DistanceCullingDebug.PNG b/img/DistanceCullingDebug.PNG new file mode 100644 index 0000000..28e371b Binary files /dev/null and b/img/DistanceCullingDebug.PNG differ diff --git a/img/NoDistanceBasedTesselation2pow16.PNG b/img/NoDistanceBasedTesselation2pow16.PNG new file mode 100644 index 0000000..7ae3a43 Binary files /dev/null and b/img/NoDistanceBasedTesselation2pow16.PNG differ diff --git a/img/NoDistanceBasedTesselation2pow18.PNG b/img/NoDistanceBasedTesselation2pow18.PNG new file mode 100644 index 0000000..a94ad6b Binary files /dev/null and b/img/NoDistanceBasedTesselation2pow18.PNG differ diff --git a/img/NoDistanceCulling2pow14.PNG b/img/NoDistanceCulling2pow14.PNG new file mode 100644 index 0000000..ed7ab91 Binary files /dev/null and b/img/NoDistanceCulling2pow14.PNG differ diff --git a/img/data/baseline.PNG b/img/data/baseline.PNG new file mode 100644 index 0000000..20c91c2 Binary files /dev/null and b/img/data/baseline.PNG differ diff --git a/img/data/distanceCulling.PNG b/img/data/distanceCulling.PNG new file mode 100644 index 0000000..d056ed3 Binary files /dev/null and b/img/data/distanceCulling.PNG differ diff --git a/img/data/distanceTessellation.PNG b/img/data/distanceTessellation.PNG new file mode 100644 index 0000000..283b35e Binary files /dev/null and b/img/data/distanceTessellation.PNG differ diff --git a/img/data/normals.PNG b/img/data/normals.PNG new file mode 100644 index 0000000..942546c Binary files /dev/null and b/img/data/normals.PNG differ diff --git a/img/grassDemoGif.gif b/img/grassDemoGif.gif new file mode 100644 index 0000000..9293194 Binary files /dev/null and b/img/grassDemoGif.gif differ diff --git a/src/Blades.h b/src/Blades.h index 9bd1eed..8c61ddd 100644 --- a/src/Blades.h +++ b/src/Blades.h @@ -4,7 +4,7 @@ #include #include "Model.h" -constexpr static unsigned int NUM_BLADES = 1 << 13; +constexpr static unsigned int NUM_BLADES = 1 << 16; constexpr static float MIN_HEIGHT = 1.3f; constexpr static float MAX_HEIGHT = 2.5f; constexpr static float MIN_WIDTH = 0.1f; diff --git a/src/Renderer.cpp b/src/Renderer.cpp index b445d04..490440f 100644 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -198,6 +198,41 @@ void Renderer::CreateComputeDescriptorSetLayout() { // TODO: Create the descriptor set layout for the compute pipeline // Remember this is like a class definition stating why types of information // will be stored at each binding + + //input blades + VkDescriptorSetLayoutBinding sboLayoutBinding1 = {}; + sboLayoutBinding1.binding = 0; + sboLayoutBinding1.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + sboLayoutBinding1.descriptorCount = 1; //ME-TODO: This will probably need to be at least 2 + sboLayoutBinding1.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + sboLayoutBinding1.pImmutableSamplers = nullptr; + + //culled blades + VkDescriptorSetLayoutBinding sboLayoutBinding2 = {}; + sboLayoutBinding2.binding = 1; + sboLayoutBinding2.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + sboLayoutBinding2.descriptorCount = 1; + sboLayoutBinding2.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + sboLayoutBinding2.pImmutableSamplers = nullptr; + + //number of blades + VkDescriptorSetLayoutBinding sboLayoutBinding3 = {}; + sboLayoutBinding3.binding = 2; + sboLayoutBinding3.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + sboLayoutBinding3.descriptorCount = 1; + sboLayoutBinding3.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + sboLayoutBinding3.pImmutableSamplers = nullptr; + + std::vector bindings = { sboLayoutBinding1, sboLayoutBinding2, sboLayoutBinding3 }; + + VkDescriptorSetLayoutCreateInfo layoutInfo = {}; + layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + layoutInfo.bindingCount = static_cast(bindings.size()); + layoutInfo.pBindings = bindings.data(); + + if (vkCreateDescriptorSetLayout(logicalDevice, &layoutInfo, nullptr, &computeDescriptorSetLayout) != VK_SUCCESS) { + throw std::runtime_error("Failed to create descriptor set layout"); + } } void Renderer::CreateDescriptorPool() { @@ -216,13 +251,20 @@ void Renderer::CreateDescriptorPool() { { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER , 1 }, // TODO: Add any additional types and counts of descriptors you will need to allocate + + //input blades and culled blades + { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER , 2 }, + + //struct with culled blades data + {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER , 1} + }; VkDescriptorPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = static_cast(poolSizes.size()); poolInfo.pPoolSizes = poolSizes.data(); - poolInfo.maxSets = 5; + poolInfo.maxSets = 6; if (vkCreateDescriptorPool(logicalDevice, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor pool"); @@ -360,6 +402,66 @@ void Renderer::CreateTimeDescriptorSet() { void Renderer::CreateComputeDescriptorSets() { // TODO: Create Descriptor sets for the compute pipeline // The descriptors should point to Storage buffers which will hold the grass blades, the culled grass blades, and the output number of grass blades + VkDescriptorSetLayout layouts[] = { computeDescriptorSetLayout }; + VkDescriptorSetAllocateInfo allocInfo = {}; + allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocInfo.descriptorPool = descriptorPool; + allocInfo.descriptorSetCount = 1; + allocInfo.pSetLayouts = layouts; + + //Allocate descriptor sets + if (vkAllocateDescriptorSets(logicalDevice, &allocInfo, &computeDescriptorSet) != VK_SUCCESS) { + throw std::runtime_error("Failed to allocate descriptor set"); + } + + VkDescriptorBufferInfo computeBufferInfo = {}; + Blades* blades = scene->GetBlades().at(0); + computeBufferInfo.buffer = blades->GetBladesBuffer(); + computeBufferInfo.offset = 0; + computeBufferInfo.range = NUM_BLADES * sizeof(Blade); + + VkDescriptorBufferInfo computeBufferCulledBladesInfo = {}; + computeBufferCulledBladesInfo.buffer = blades->GetCulledBladesBuffer(); + computeBufferCulledBladesInfo.offset = 0; + computeBufferCulledBladesInfo.range = NUM_BLADES * sizeof(Blade); + + VkDescriptorBufferInfo computeBufferNumBladesInfo = {}; + computeBufferNumBladesInfo.buffer = blades->GetNumBladesBuffer(); + computeBufferNumBladesInfo.offset = 0; + computeBufferNumBladesInfo.range = sizeof(BladeDrawIndirect); + + std::array descriptorWrites = {}; + descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[0].dstSet = computeDescriptorSet; + descriptorWrites[0].dstBinding = 0; + descriptorWrites[0].dstArrayElement = 0; + descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[0].descriptorCount = 1; + descriptorWrites[0].pBufferInfo = &computeBufferInfo; + descriptorWrites[0].pImageInfo = nullptr; + descriptorWrites[0].pTexelBufferView = nullptr; + + descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[1].dstSet = computeDescriptorSet; + descriptorWrites[1].dstBinding = 1; + descriptorWrites[1].dstArrayElement = 0; + descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[1].descriptorCount = 1; + descriptorWrites[1].pBufferInfo = &computeBufferCulledBladesInfo; + descriptorWrites[1].pImageInfo = nullptr; + descriptorWrites[1].pTexelBufferView = nullptr; + + descriptorWrites[2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[2].dstSet = computeDescriptorSet; + descriptorWrites[2].dstBinding = 2; + descriptorWrites[2].dstArrayElement = 0; + descriptorWrites[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[2].descriptorCount = 1; + descriptorWrites[2].pBufferInfo = &computeBufferNumBladesInfo; + descriptorWrites[2].pImageInfo = nullptr; + descriptorWrites[2].pTexelBufferView = nullptr; + + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } void Renderer::CreateGraphicsPipeline() { @@ -717,7 +819,7 @@ void Renderer::CreateComputePipeline() { computeShaderStageInfo.pName = "main"; // TODO: Add the compute dsecriptor set layout you create to this list - std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, timeDescriptorSetLayout }; + std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, timeDescriptorSetLayout, computeDescriptorSetLayout}; // Create pipeline layout VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; @@ -884,6 +986,11 @@ void Renderer::RecordComputeCommandBuffer() { vkCmdBindDescriptorSets(computeCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 1, 1, &timeDescriptorSet, 0, nullptr); // TODO: For each group of blades bind its descriptor set and dispatch + vkCmdBindDescriptorSets(computeCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 2, 1, &computeDescriptorSet, 0, nullptr); + + vkCmdDispatch(computeCommandBuffer, static_cast(NUM_BLADES / WORKGROUP_SIZE), 1, 1); + + //vkCmdDispatch(computeCommandBuffer, 10, 1, 1); // ~ End recording ~ if (vkEndCommandBuffer(computeCommandBuffer) != VK_SUCCESS) { @@ -976,13 +1083,13 @@ void Renderer::RecordCommandBuffers() { VkBuffer vertexBuffers[] = { scene->GetBlades()[j]->GetCulledBladesBuffer() }; VkDeviceSize offsets[] = { 0 }; // TODO: Uncomment this when the buffers are populated - // vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, vertexBuffers, offsets); + vkCmdBindVertexBuffers(commandBuffers[i], 0, 1, vertexBuffers, offsets); // TODO: Bind the descriptor set for each grass blades model // Draw // TODO: Uncomment this when the buffers are populated - // vkCmdDrawIndirect(commandBuffers[i], scene->GetBlades()[j]->GetNumBladesBuffer(), 0, 1, sizeof(BladeDrawIndirect)); + vkCmdDrawIndirect(commandBuffers[i], scene->GetBlades()[j]->GetNumBladesBuffer(), 0, 1, sizeof(BladeDrawIndirect)); } // End render pass @@ -1050,7 +1157,7 @@ Renderer::~Renderer() { vkDestroyPipeline(logicalDevice, grassPipeline, nullptr); vkDestroyPipeline(logicalDevice, computePipeline, nullptr); - vkDestroyPipelineLayout(logicalDevice, graphicsPipelineLayout, nullptr); + vkDestroyPipelineLayout(logicalDevice, graphicsPipelineLayout, nullptr); vkDestroyPipelineLayout(logicalDevice, grassPipelineLayout, nullptr); vkDestroyPipelineLayout(logicalDevice, computePipelineLayout, nullptr); @@ -1058,10 +1165,15 @@ Renderer::~Renderer() { vkDestroyDescriptorSetLayout(logicalDevice, modelDescriptorSetLayout, nullptr); vkDestroyDescriptorSetLayout(logicalDevice, timeDescriptorSetLayout, nullptr); + //destroy new descriptorSets + vkDestroyDescriptorSetLayout(logicalDevice, computeDescriptorSetLayout, nullptr); + vkDestroyDescriptorPool(logicalDevice, descriptorPool, nullptr); vkDestroyRenderPass(logicalDevice, renderPass, nullptr); DestroyFrameResources(); vkDestroyCommandPool(logicalDevice, computeCommandPool, nullptr); vkDestroyCommandPool(logicalDevice, graphicsCommandPool, nullptr); + + } diff --git a/src/Renderer.h b/src/Renderer.h index 95e025f..7340c8b 100644 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -79,4 +79,8 @@ class Renderer { std::vector commandBuffers; VkCommandBuffer computeCommandBuffer; + + //Additional members + VkDescriptorSetLayout computeDescriptorSetLayout; + VkDescriptorSet computeDescriptorSet; }; diff --git a/src/shaders/compute.comp b/src/shaders/compute.comp index 0fd0224..078a7d7 100644 --- a/src/shaders/compute.comp +++ b/src/shaders/compute.comp @@ -21,36 +21,117 @@ struct Blade { vec4 up; }; -// TODO: Add bindings to: -// 1. Store the input blades -// 2. Write out the culled blades -// 3. Write the total number of blades remaining - -// The project is using vkCmdDrawIndirect to use a buffer as the arguments for a draw call -// This is sort of an advanced feature so we've showed you what this buffer should look like -// -// layout(set = ???, binding = ???) buffer NumBlades { -// uint vertexCount; // Write the number of blades remaining here -// uint instanceCount; // = 1 -// uint firstVertex; // = 0 -// uint firstInstance; // = 0 -// } numBlades; +layout(set = 2, binding = 0) buffer InputBlades { + Blade inputBlades[]; +}; + +layout(set = 2, binding = 1) buffer CulledBlades { + Blade culledBlades[]; +}; + + layout(set = 2, binding = 2) buffer NumBlades { + uint vertexCount; // Write the number of blades remaining here + uint instanceCount; // = 1 + uint firstVertex; // = 0 + uint firstInstance; // = 0 + } numBlades; bool inBounds(float value, float bounds) { return (value >= -bounds) && (value <= bounds); } +bool distanceCulled(float distance, uint index, vec3 pos) { + + float closestBucket = 0.0; + float maxDistance = 40.0; + float totalBuckets = 10.0; + float bucket = max(0.0, floor((maxDistance - distance) / (maxDistance / totalBuckets))); + float pdf = abs(sin(dot(pos, vec3(12.9898, 54.3289, 78.233))) * 43758.5453); + pdf = pdf - floor(pdf); + float threshold = bucket / totalBuckets; + threshold = pow(threshold, 2.0); + return pdf > threshold || bucket == 0; +} + void main() { // Reset the number of blades to 0 if (gl_GlobalInvocationID.x == 0) { - // numBlades.vertexCount = 0; + numBlades.vertexCount = 0; } barrier(); // Wait till all threads reach this point + float time = deltaTime + totalTime; + uint index = gl_GlobalInvocationID.x; + + Blade blade = inputBlades[index]; + + vec4 v0 = blade.v0; + vec4 v1 = blade.v1; + vec4 v2 = blade.v2; + vec4 up = blade.up; + + vec3 bladeNormal = vec3(sin(v0.w), 0.0, cos(v0.w)); + + //recovery force + vec3 recovery = (v0.xyz + v1.w * up.xyz) - v2.xyz; + recovery *= up.w; // multiply by stiffness coefficient + + //gravity + vec3 envGravity = 1.0 * (-up.xyz * 9.8); + vec3 frontGravity = .25 * length(envGravity) * bladeNormal; + vec3 gravity = envGravity + frontGravity; + + //wind + vec3 windForce = sin(totalTime * 4.0 + abs(cos(v0.x) - cos(v0.z))) * vec3(3.0, 0.0, -3.0); + //vec3 windCenter = 0.5 * vec3(sin(totalTime), 0.0, cos(totalTime)); + //vec3 windForce = (-sin(totalTime * 20.0 - length(v0.xyz - windCenter)) + 0.8) * normalize(v0.xyz - windCenter) * 100.0; + float directionAlignment = abs(dot(normalize(windForce), normalize(bladeNormal))); + float heightRatio = dot(v2.xyz - v0.xyz, up.xyz) / v1.w; + float alignmentValue = directionAlignment * heightRatio; + vec3 wind = alignmentValue * windForce; - // TODO: Apply forces on every blade and update the vertices in the buffer + //total the forces + vec3 translation = (recovery + gravity + wind) * deltaTime; + + //do initial translation on control point + v2 += vec4(translation, 0.0); + + //state validation + v2.xyz = v2.xyz - up.xyz * min(dot(up.xyz, v2.xyz - v0.xyz), 0); + + float lProj = length(v2.xyz - v0.xyz - up.xyz * dot(v2.xyz - v0.xyz, up.xyz)); + v1.xyz = v0.xyz + v1.w * up.xyz * max(1.0 - lProj / v1.w, 0.05 * max(lProj / v1.w, 1.0)); + + float L0 = distance(v0.xyz, v2.xyz); + float L1 = distance(v0.xyz, v1.xyz) + distance(v1.xyz, v2.xyz); + float L = (2.0 * L0 + 2.0 * L1) / 4.0; + float r = v1.w / L; + vec3 v1Tmp = v1.xyz; + v1.xyz = v0.xyz + r * (v1.xyz - v0.xyz); + v2.xyz = v1.xyz + r * (v2.xyz - v1Tmp); + + //update Blades + inputBlades[index].v1 = v1; + inputBlades[index].v2 = v2; + + culledBlades[index] = inputBlades[index]; // TODO: Cull blades that are too far away or not in the camera frustum and write them // to the culled blades buffer + + vec4 clipTest = camera.proj * camera.view * vec4(v0.xyz, 1.0); + bool cullByDistance = distanceCulled(length(vec3(camera.view * vec4(v0.xyz, 1.0))), index, v0.xyz); + clipTest /= clipTest.w; + + float normalTest = dot(normalize(vec3(camera.view * vec4(v0.xyz, 1.0))), normalize(vec3(camera.view * vec4(bladeNormal, 0.0)))); + + if (inBounds(clipTest.x, 1.05) && inBounds(clipTest.y, 1.3) && abs(normalTest) > 0.05 && !cullByDistance) { + culledBlades[atomicAdd(numBlades.vertexCount, 1)] = inputBlades[index]; + } + // Note: to do this, you will need to use an atomic operation to read and update numBlades.vertexCount // You want to write the visible blades to the buffer without write conflicts between threads + + //culledBlades.data[index] = inBlades.data[index]; + + } diff --git a/src/shaders/grass.frag b/src/shaders/grass.frag index c7df157..fdfb218 100644 --- a/src/shaders/grass.frag +++ b/src/shaders/grass.frag @@ -8,10 +8,12 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { // TODO: Declare fragment shader inputs +layout(location = 0) in float colorHeight; + layout(location = 0) out vec4 outColor; void main() { // TODO: Compute fragment color - outColor = vec4(1.0); + outColor = colorHeight * vec4(0.0, 1.0, 0.0, 1.0); } diff --git a/src/shaders/grass.tesc b/src/shaders/grass.tesc index f9ffd07..6f9f85a 100644 --- a/src/shaders/grass.tesc +++ b/src/shaders/grass.tesc @@ -10,17 +10,39 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { // TODO: Declare tessellation control shader inputs and outputs +layout(location = 0) in vec2 dimensions[]; +layout(location = 1) in vec3 orientation[]; +layout(location = 2) in vec4 tescV0[]; +layout(location = 3) in vec4 tescV1[]; +layout(location = 4) in vec4 tescV2[]; +layout(location = 5) in vec4 tescUp[]; + + +layout(location = 0) out vec2 teseDimensions[]; +layout(location = 1) out vec3 teseOrientation[]; +layout(location = 2) out vec4 teseV0[]; +layout(location = 3) out vec4 teseV1[]; +layout(location = 4) out vec4 teseV2[]; +layout(location = 5) out vec4 teseUp[]; + + void main() { // Don't move the origin location of the patch gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; - // TODO: Write any shader outputs + teseDimensions[gl_InvocationID] = dimensions[gl_InvocationID]; + teseOrientation[gl_InvocationID] = orientation[gl_InvocationID]; + teseV0[gl_InvocationID] = tescV0[gl_InvocationID]; + teseV1[gl_InvocationID] = tescV1[gl_InvocationID]; + teseV2[gl_InvocationID] = tescV2[gl_InvocationID]; + teseUp[gl_InvocationID] = tescUp[gl_InvocationID]; + - // TODO: Set level of tesselation - // gl_TessLevelInner[0] = ??? - // gl_TessLevelInner[1] = ??? - // gl_TessLevelOuter[0] = ??? - // gl_TessLevelOuter[1] = ??? - // gl_TessLevelOuter[2] = ??? - // gl_TessLevelOuter[3] = ??? + //TODO: Set level of tesselation + gl_TessLevelInner[0] = 16.0; + gl_TessLevelInner[1] = 4.0; + gl_TessLevelOuter[0] = 16.0; + gl_TessLevelOuter[1] = 4.0; + gl_TessLevelOuter[2] = 16.0; + gl_TessLevelOuter[3] = 4.0; } diff --git a/src/shaders/grass.tese b/src/shaders/grass.tese index 751fff6..c201671 100644 --- a/src/shaders/grass.tese +++ b/src/shaders/grass.tese @@ -10,9 +10,43 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { // TODO: Declare tessellation evaluation shader inputs and outputs +layout(location = 0) in vec2 teseDimensions[]; +layout(location = 1) in vec3 teseOrientation[]; +layout(location = 2) in vec4 teseV0[]; +layout(location = 3) in vec4 teseV1[]; +layout(location = 4) in vec4 teseV2[]; +layout(location = 5) in vec4 teseUp[]; + +layout(location = 0) out float colorHeight[]; + void main() { float u = gl_TessCoord.x; float v = gl_TessCoord.y; - // TODO: Use u and v to parameterize along the grass blade and output positions for each vertex of the grass blade + vec3 orientation = teseOrientation[0]; + vec4 v0 = teseV0[0]; + vec4 v1 = teseV1[0]; + vec4 v2 = teseV2[0]; + vec4 Up = teseUp[0]; + + vec3 a = v0.xyz + v * (v1.xyz - v0.xyz); + vec3 b = v1.xyz + v * (v2.xyz - v1.xyz); + vec3 c = a + v * (b - a); + vec3 c0 = c - teseDimensions[0].x * 0.5 * orientation; + vec3 c1 = c + teseDimensions[0].x * 0.5 * orientation; + vec3 t0 = normalize(b - a); + vec3 n = normalize(cross(t0, orientation)); + float t = u + 0.5 * v - u * v; + vec3 finalPosition = (1.0 - t) * c0 + t * c1; + + //vec3 B0 = vec3(0.0, 0.0, 0.0); + //vec3 B1 = v1.xyz - v0.xyz; + //vec3 B2 = v2.xyz - v0.xyz; + //vec3 curveTranslation = B0 * (1.0 - v) * (1.0 - v) + B1 * 2 * v * (1.0 - v) + B2 * v * v; + + //vec3 vAxis = teseV2[0].xyz - vec3(gl_in[0].gl_Position); + //vec3 uAxis = normalize(cross(vAxis, orientation)) * teseDimensions[0].x; + + gl_Position = camera.proj * camera.view * vec4(finalPosition, 1.0); + colorHeight[0] = v * 0.5 + 0.25; } diff --git a/src/shaders/grass.vert b/src/shaders/grass.vert index db9dfe9..0fd1382 100644 --- a/src/shaders/grass.vert +++ b/src/shaders/grass.vert @@ -6,12 +6,34 @@ layout(set = 1, binding = 0) uniform ModelBufferObject { mat4 model; }; +layout(location = 0) in vec4 v0; +layout(location = 1) in vec4 v1; +layout(location = 2) in vec4 v2; +layout(location = 3) in vec4 up; + // TODO: Declare vertex shader inputs and outputs out gl_PerVertex { vec4 gl_Position; }; +layout (location = 0) out vec2 dimensions; +layout (location = 1) out vec3 orientation; + +layout (location = 2) out vec4 tescV0; +layout (location = 3) out vec4 tescV1; +layout (location = 4) out vec4 tescV2; +layout (location = 5) out vec4 tescUp; + void main() { // TODO: Write gl_Position and any other shader outputs + gl_Position = vec4(v0.xyz, 1.0); + dimensions.x = v2.w; + dimensions.y = v1.w; + tescV0 = v0; + tescV1 = v1; + tescV2 = v2; + tescUp = up; + + orientation = vec3(sin(v0.w), 0.0, cos(v0.w)); }