diff --git a/README.md b/README.md index a744a2e..5ad64d8 100644 --- a/README.md +++ b/README.md @@ -1,116 +1,23 @@ -Instructions - Vulkan Grass Rendering +Vulkan Grass Rendering ======================== -This is due **Sunday 11/5, evening at midnight**. +* Jiawei Wang +* Tested on: **Google Chrome 62.0.3202.75 (Official Build) (64-bit)** on + Windows 10, i7-6700 @ 2.60GHz 16.0GB, GTX 970M 3072MB (Personal) -**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. -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 +Implemented a grass simulator and renderer using Vulkan, based on 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) +* Used compute shaders to perform physics calculations on Bezier curves that represent individual grass blades in application. +* Also used compute shaders to cull grass blades that don't contribute to a given frame. +* Wrote 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. -![](img/grass.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. +| **Final Result** | +|---| +|| +___ +## Features ### Representing Grass as Bezier Curves In this project, grass blades will be represented as Bezier curves while performing physics calculations and culling operations. @@ -131,167 +38,101 @@ We can pack all this data into four `vec4`s, such that `v0.w` holds orientation, ![](img/blade_model.jpg) -### 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 - -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 - -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`. - -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`. - -We can then determine the total gravity on the grass blade as `g = gE + gF`. - -#### Recovery - -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. - -Once we have `iv2`, we can compute the recovery forces as `r = (iv2 - v2) * stiffness`. - -#### Wind - -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. - -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! - -Once you have a wind direction and a wind alignment term, your total wind force (`w`) will be `windDirection * windAlignment`. - -#### Total force - -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. - -Read section 5.2 of the paper in order to learn how to determine the corrected final positions for `v1` and `v2`. - -### 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. - -#### Orientation culling - -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. - -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. - -#### 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. - -* [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) -* [Official Vulkan documentation](https://www.khronos.org/registry/vulkan/) -* [Vulkan tutorial](https://vulkan-tutorial.com/) -* [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. +### Compute Shader +Compute Shader in Vulkan is the same as in OpenGL, it's similar to CUDA parrellel programming. It is a **Shader Stage** that is used entirely for computing arbitrary information. While it can do rendering, it is generally used for tasks not directly related to drawing triangles and pixels.
+Here I used it to do 2 things as following: +* **Force Calculation**: + * ***Gravity***: 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`. 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`. We can then determine the total gravity on the grass blade as `g = gE + gF`. + * ***Recovery Force***: 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. Once we have `iv2`, we can compute the recovery forces as `r = (iv2 - v2) * stiffness`. + * ***Wind***: 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. + * According to the paper, I used following method to simulate the wind force + ```glsl + //Wind + vec3 wind_dir = normalize(vec3(0.5, 0, 1)); + float wind_speed = 8.0; + float wave_division_width = 5.0; + + float wave_info = (cos((dot(vec3(this_v0.x, 0, this_v0.z), wind_dir) - wind_speed * totalTime) / wave_division_width) + 0.7); + + //5.1 Wind + //directional alignment + float fd = 1 - abs(dot(wind_dir, normalize(this_v2 - this_v0))); + + //height ratio + float fr = dot((this_v2 - this_v0), this_up) / this_h; + + // + float wind_power = 15.0f; + vec3 w = wind_dir * wind_power * wave_info * fd * fr; + + ``` +* **Blades Culling**: I implemented three culling conditions as following: + * ***Orientation Culling***: 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. 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. + * ***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. Not as the paper provides, I transformed the point into **NDC coorditnates** and then check if they are inside of the frustum. + * ***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. Here I used the same method the paper presents as following: (Divide the blades into different buckets according to the horizontal distance, and then cull different number of the bladess according to the division) + ```glsl + //Distance Culling + bool distance_culled = false; + float min_distance = 0.1; + float far_distance = 100; + + //seperate into 10 buckets + //the distance between each bucket is 10 + vec4 view_v0 = camera.view * vec4(this_v0, 1.0f); + float horizontal_distance = abs(dot(view_v0.xyz, vec3(0,0,1))); + + if(horizontal_distance > far_distance){ + distance_culled = true; + } + else{ + int bucket_level = int(horizontal_distance) / 10; + if(bucket_level > 0){ + if(index % bucket_level < int(bucket_level * (1.0 - horizontal_distance/far_distance))){ + distance_culled = true; + } + } + } + ``` + +| **Distance Culling(`far_clip = 100`, 10 buckets)** | +|---| +|| + + +### Tessellation Shader +I won't explain too much about how the tessellation shader works, but I will present how tessellation works on some different shapes mentioned in the paper. Here are the code in *tessellation evaluation shader*: +```glsl + // quad + //float t = u; + + // triangle + //float t = u + 0.5 * v - u * v; + + // quadratic + //float t = u - u * v * v; + + // triangle-tip + // border threshold between quad and triangle + float threshold = 0.35; + float t = 0.5 + (u - 0.5) * (1 - max(v - threshold, 0)/(1 - threshold)); +``` +There is also a method mentioned in the paper that can generate **Dandelion** shape, which is calculated by a complex equation that uses trigonometric functions. + +___ +## Performance Analysis +Most of the realization is very routine, although Vulkan is extremely hard to use. So, I only did the comparison of the different culling methods. + +| **Before Culling** | **After Culling** | +|---|---| +||| + +| **Comparison Between different Culling** | +|---| +|| + +| **Comparison Between different Culling(FPS)** | +|---| +|| + +* According to the results, we can find that in this example, the one before culling will have more artifacts than the one after culling, this is because without ***orientation culling***, some pixels on grass will smaller than the size of a pixel and it will lead to some unexpected artifacts. +* Besides, the results show that all of the culling will enhance the performance of the simulator, and the ***distance culling*** is the most remarkable method here. And one reason that the ***view frustum culling*** doesn't affect too much is that only a few blades in this example are outside of the frustum. diff --git a/bin/Debug/vulkan_grass_rendering.exe b/bin/Debug/vulkan_grass_rendering.exe new file mode 100644 index 0000000..5fe5d9e Binary files /dev/null and b/bin/Debug/vulkan_grass_rendering.exe differ diff --git a/bin/Debug/vulkan_grass_rendering.ilk b/bin/Debug/vulkan_grass_rendering.ilk new file mode 100644 index 0000000..500ad4d Binary files /dev/null and b/bin/Debug/vulkan_grass_rendering.ilk differ diff --git a/bin/Debug/vulkan_grass_rendering.pdb b/bin/Debug/vulkan_grass_rendering.pdb new file mode 100644 index 0000000..492aaf0 Binary files /dev/null and b/bin/Debug/vulkan_grass_rendering.pdb differ diff --git a/bin/Release/vulkan_grass_rendering.exe b/bin/Release/vulkan_grass_rendering.exe new file mode 100644 index 0000000..28e1184 Binary files /dev/null and b/bin/Release/vulkan_grass_rendering.exe differ diff --git a/results/after.gif b/results/after.gif new file mode 100644 index 0000000..04fbec4 Binary files /dev/null and b/results/after.gif differ diff --git a/results/before.gif b/results/before.gif new file mode 100644 index 0000000..97a0685 Binary files /dev/null and b/results/before.gif differ diff --git a/results/directional_wind.gif b/results/directional_wind.gif new file mode 100644 index 0000000..5c89f7a Binary files /dev/null and b/results/directional_wind.gif differ diff --git a/results/distance_culled.gif b/results/distance_culled.gif new file mode 100644 index 0000000..c7cf215 Binary files /dev/null and b/results/distance_culled.gif differ diff --git a/results/form.JPG b/results/form.JPG new file mode 100644 index 0000000..0374a16 Binary files /dev/null and b/results/form.JPG differ diff --git a/results/plot.JPG b/results/plot.JPG new file mode 100644 index 0000000..d138603 Binary files /dev/null and b/results/plot.JPG differ diff --git a/src/Blades.h b/src/Blades.h index 9bd1eed..9a57427 100644 --- a/src/Blades.h +++ b/src/Blades.h @@ -4,13 +4,13 @@ #include #include "Model.h" -constexpr static unsigned int NUM_BLADES = 1 << 13; +constexpr static unsigned int NUM_BLADES = 1 << 17; constexpr static float MIN_HEIGHT = 1.3f; constexpr static float MAX_HEIGHT = 2.5f; constexpr static float MIN_WIDTH = 0.1f; constexpr static float MAX_WIDTH = 0.14f; constexpr static float MIN_BEND = 7.0f; -constexpr static float MAX_BEND = 13.0f; +constexpr static float MAX_BEND = 14.0f; struct Blade { // Position and direction diff --git a/src/Camera.cpp b/src/Camera.cpp index 3afb5b8..18097a1 100644 --- a/src/Camera.cpp +++ b/src/Camera.cpp @@ -12,7 +12,7 @@ Camera::Camera(Device* device, float aspectRatio) : device(device) { r = 10.0f; theta = 0.0f; phi = 0.0f; - cameraBufferObject.viewMatrix = glm::lookAt(glm::vec3(0.0f, 1.0f, 10.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); + cameraBufferObject.viewMatrix = glm::lookAt(glm::vec3(0.0f, 8.0f, -30.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); cameraBufferObject.projectionMatrix = glm::perspective(glm::radians(45.0f), aspectRatio, 0.1f, 100.0f); cameraBufferObject.projectionMatrix[1][1] *= -1; // y-coordinate is flipped @@ -41,6 +41,12 @@ void Camera::UpdateOrbit(float deltaX, float deltaY, float deltaZ) { memcpy(mappedData, &cameraBufferObject, sizeof(CameraBufferObject)); } +void Camera::UpdateAspectRatio(float aspectRatio) { + cameraBufferObject.projectionMatrix = glm::perspective(glm::radians(45.0f), aspectRatio, 0.1f, 100.0f); + cameraBufferObject.projectionMatrix[1][1] *= -1; // y-coordinate is flipped + memcpy(mappedData, &cameraBufferObject, sizeof(CameraBufferObject)); +} + Camera::~Camera() { vkUnmapMemory(device->GetVkDevice(), bufferMemory); vkDestroyBuffer(device->GetVkDevice(), buffer, nullptr); diff --git a/src/Camera.h b/src/Camera.h index 6b10747..28a5770 100644 --- a/src/Camera.h +++ b/src/Camera.h @@ -29,4 +29,5 @@ class Camera { VkBuffer GetBuffer() const; void UpdateOrbit(float deltaX, float deltaY, float deltaZ); + void UpdateAspectRatio(float aspectRatio); }; diff --git a/src/Renderer.cpp b/src/Renderer.cpp index b445d04..f43bc8c 100644 --- a/src/Renderer.cpp +++ b/src/Renderer.cpp @@ -19,6 +19,7 @@ Renderer::Renderer(Device* device, SwapChain* swapChain, Scene* scene, Camera* c CreateRenderPass(); CreateCameraDescriptorSetLayout(); CreateModelDescriptorSetLayout(); + CreateGrassDescriptorSetLayout(); CreateTimeDescriptorSetLayout(); CreateComputeDescriptorSetLayout(); CreateDescriptorPool(); @@ -172,6 +173,8 @@ void Renderer::CreateModelDescriptorSetLayout() { } } + + void Renderer::CreateTimeDescriptorSetLayout() { // Describe the binding of the descriptor set layout VkDescriptorSetLayoutBinding uboLayoutBinding = {}; @@ -194,10 +197,63 @@ void Renderer::CreateTimeDescriptorSetLayout() { } } +void Renderer::CreateGrassDescriptorSetLayout(){ + VkDescriptorSetLayoutBinding uboLayoutBinding = {}; + uboLayoutBinding.binding = 0; + uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + uboLayoutBinding.descriptorCount = 1; + uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + uboLayoutBinding.pImmutableSamplers = nullptr; + + std::vector bindings = { uboLayoutBinding }; + + // Create the descriptor set layout + 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, &grassDescriptorSetLayout) != VK_SUCCESS) { + throw std::runtime_error("Failed to create descriptor set layout"); + } +} + 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 + VkDescriptorSetLayoutBinding bladesBinding = {}; + bladesBinding.binding = 0; + bladesBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + bladesBinding.descriptorCount = 1; + bladesBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + bladesBinding.pImmutableSamplers = nullptr; + + VkDescriptorSetLayoutBinding culledBladesBinding = {}; + culledBladesBinding.binding = 1; + culledBladesBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + culledBladesBinding.descriptorCount = 1; + culledBladesBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + culledBladesBinding.pImmutableSamplers = nullptr; + + VkDescriptorSetLayoutBinding numBladesBinding = {}; + numBladesBinding.binding = 2; + numBladesBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + numBladesBinding.descriptorCount = 1; + numBladesBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + numBladesBinding.pImmutableSamplers = nullptr; + + std::vector bindings = { bladesBinding, culledBladesBinding, numBladesBinding }; + + // Create the descriptor set layout + 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,6 +272,7 @@ void Renderer::CreateDescriptorPool() { { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER , 1 }, // TODO: Add any additional types and counts of descriptors you will need to allocate + { VK_DESCRIPTOR_TYPE_STORAGE_BUFFER , 3 * (uint32_t)scene->GetBlades().size() }, }; VkDescriptorPoolCreateInfo poolInfo = {}; @@ -320,6 +377,42 @@ void Renderer::CreateModelDescriptorSets() { void Renderer::CreateGrassDescriptorSets() { // TODO: Create Descriptor sets for the grass. // This should involve creating descriptor sets which point to the model matrix of each group of grass blades + grassDescriptorSets.resize(scene->GetBlades().size()); + + // Describe the desciptor set + VkDescriptorSetLayout layouts[] = { grassDescriptorSetLayout }; + VkDescriptorSetAllocateInfo allocInfo = {}; + allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocInfo.descriptorPool = descriptorPool; + allocInfo.descriptorSetCount = static_cast(grassDescriptorSets.size()); + allocInfo.pSetLayouts = layouts; + + // Allocate descriptor sets + if (vkAllocateDescriptorSets(logicalDevice, &allocInfo, grassDescriptorSets.data()) != VK_SUCCESS) { + throw std::runtime_error("Failed to allocate descriptor set"); + } + + std::vector descriptorWrites(grassDescriptorSets.size()); + + for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) { + VkDescriptorBufferInfo modelBufferInfo = {}; + modelBufferInfo.buffer = scene->GetBlades()[i]->GetModelBuffer(); + modelBufferInfo.offset = 0; + modelBufferInfo.range = sizeof(ModelBufferObject); + + descriptorWrites[i + 0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[i + 0].dstSet = grassDescriptorSets[i]; + descriptorWrites[i + 0].dstBinding = 0; + descriptorWrites[i + 0].dstArrayElement = 0; + descriptorWrites[i + 0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptorWrites[i + 0].descriptorCount = 1; + descriptorWrites[i + 0].pBufferInfo = &modelBufferInfo; + descriptorWrites[i + 0].pImageInfo = nullptr; + descriptorWrites[i + 0].pTexelBufferView = nullptr; + } + + // Update descriptor sets + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } void Renderer::CreateTimeDescriptorSet() { @@ -360,6 +453,76 @@ 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 + computeDescriptorSets.resize(scene->GetBlades().size()); + + // Describe the desciptor set + VkDescriptorSetLayout layouts[] = { computeDescriptorSetLayout }; + VkDescriptorSetAllocateInfo allocInfo = {}; + allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + allocInfo.descriptorPool = descriptorPool; + allocInfo.descriptorSetCount = static_cast(computeDescriptorSets.size()); + allocInfo.pSetLayouts = layouts; + + // Allocate descriptor sets + if (vkAllocateDescriptorSets(logicalDevice, &allocInfo, computeDescriptorSets.data()) != VK_SUCCESS) { + throw std::runtime_error("Failed to allocate descriptor set"); + } + + std::vector descriptorWrites(3 * computeDescriptorSets.size()); + + for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) { + //Blades + VkDescriptorBufferInfo bladesBufferInfo = {}; + bladesBufferInfo.buffer = scene->GetBlades()[i]->GetBladesBuffer(); + bladesBufferInfo.offset = 0; + bladesBufferInfo.range = NUM_BLADES * sizeof(Blade); + + //CulledBlades + VkDescriptorBufferInfo culledBaldesBufferInfo = {}; + culledBaldesBufferInfo.buffer = scene->GetBlades()[i]->GetCulledBladesBuffer(); + culledBaldesBufferInfo.offset = 0; + culledBaldesBufferInfo.range = NUM_BLADES * sizeof(Blade); + + //Num of Blades + VkDescriptorBufferInfo numBaldesBufferInfo = {}; + numBaldesBufferInfo.buffer = scene->GetBlades()[i]->GetNumBladesBuffer(); + numBaldesBufferInfo.offset = 0; + numBaldesBufferInfo.range = sizeof(BladeDrawIndirect); + + + descriptorWrites[3 * i + 0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[3 * i + 0].dstSet = computeDescriptorSets[i]; + descriptorWrites[3 * i + 0].dstBinding = 0; + descriptorWrites[3 * i + 0].dstArrayElement = 0; + descriptorWrites[3 * i + 0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[3 * i + 0].descriptorCount = 1; + descriptorWrites[3 * i + 0].pBufferInfo = &bladesBufferInfo; + descriptorWrites[3 * i + 0].pImageInfo = nullptr; + descriptorWrites[3 * i + 0].pTexelBufferView = nullptr; + + descriptorWrites[3 * i + 1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[3 * i + 1].dstSet = computeDescriptorSets[i]; + descriptorWrites[3 * i + 1].dstBinding = 1; + descriptorWrites[3 * i + 1].dstArrayElement = 0; + descriptorWrites[3 * i + 1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[3 * i + 1].descriptorCount = 1; + descriptorWrites[3 * i + 1].pBufferInfo = &culledBaldesBufferInfo; + descriptorWrites[3 * i + 1].pImageInfo = nullptr; + descriptorWrites[3 * i + 1].pTexelBufferView = nullptr; + + descriptorWrites[3 * i + 2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[3 * i + 2].dstSet = computeDescriptorSets[i]; + descriptorWrites[3 * i + 2].dstBinding = 2; + descriptorWrites[3 * i + 2].dstArrayElement = 0; + descriptorWrites[3 * i + 2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[3 * i + 2].descriptorCount = 1; + descriptorWrites[3 * i + 2].pBufferInfo = &numBaldesBufferInfo; + descriptorWrites[3 * i + 2].pImageInfo = nullptr; + descriptorWrites[3 * i + 2].pTexelBufferView = nullptr; + } + + // Update descriptor sets + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } void Renderer::CreateGraphicsPipeline() { @@ -654,7 +817,7 @@ void Renderer::CreateGrassPipeline() { colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; - std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, modelDescriptorSetLayout }; + std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, grassDescriptorSetLayout }; // Pipeline layout: used to specify uniform values VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; @@ -717,7 +880,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 +1047,10 @@ 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 + for (int i = 0; i < scene->GetBlades().size(); ++i) { + vkCmdBindDescriptorSets(computeCommandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, computePipelineLayout, 2, 1, &computeDescriptorSets[i], 0, nullptr); + vkCmdDispatch(computeCommandBuffer, (int)(NUM_BLADES / WORKGROUP_SIZE + 1), 1, 1); + } // ~ End recording ~ if (vkEndCommandBuffer(computeCommandBuffer) != VK_SUCCESS) { @@ -973,16 +1140,19 @@ void Renderer::RecordCommandBuffers() { vkCmdBindPipeline(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, grassPipeline); for (uint32_t j = 0; j < scene->GetBlades().size(); ++j) { - VkBuffer vertexBuffers[] = { scene->GetBlades()[j]->GetCulledBladesBuffer() }; - VkDeviceSize offsets[] = { 0 }; + VkBuffer vertexBuffers[] = { scene->GetBlades()[j]->GetCulledBladesBuffer() }; + //VkBuffer vertexBuffers[] = { scene->GetBlades()[j]->GetBladesBuffer() }; + + 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 + vkCmdBindDescriptorSets(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, grassPipelineLayout, 1, 1, &grassDescriptorSets[j], 0, nullptr); // 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 @@ -1056,7 +1226,10 @@ Renderer::~Renderer() { vkDestroyDescriptorSetLayout(logicalDevice, cameraDescriptorSetLayout, nullptr); vkDestroyDescriptorSetLayout(logicalDevice, modelDescriptorSetLayout, nullptr); - vkDestroyDescriptorSetLayout(logicalDevice, timeDescriptorSetLayout, nullptr); + vkDestroyDescriptorSetLayout(logicalDevice, timeDescriptorSetLayout, nullptr); + vkDestroyDescriptorSetLayout(logicalDevice, grassDescriptorSetLayout, nullptr); + vkDestroyDescriptorSetLayout(logicalDevice, computeDescriptorSetLayout, nullptr); + vkDestroyDescriptorPool(logicalDevice, descriptorPool, nullptr); diff --git a/src/Renderer.h b/src/Renderer.h index 95e025f..42a28fc 100644 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -17,8 +17,10 @@ class Renderer { void CreateCameraDescriptorSetLayout(); void CreateModelDescriptorSetLayout(); - void CreateTimeDescriptorSetLayout(); - void CreateComputeDescriptorSetLayout(); + void CreateGrassDescriptorSetLayout(); + void CreateTimeDescriptorSetLayout(); + + void CreateComputeDescriptorSetLayout(); void CreateDescriptorPool(); @@ -53,15 +55,21 @@ class Renderer { VkRenderPass renderPass; - VkDescriptorSetLayout cameraDescriptorSetLayout; - VkDescriptorSetLayout modelDescriptorSetLayout; - VkDescriptorSetLayout timeDescriptorSetLayout; - - VkDescriptorPool descriptorPool; + VkDescriptorSetLayout cameraDescriptorSetLayout; + VkDescriptorSetLayout modelDescriptorSetLayout; + VkDescriptorSetLayout grassDescriptorSetLayout; + VkDescriptorSetLayout timeDescriptorSetLayout; + + VkDescriptorSetLayout computeDescriptorSetLayout; + + VkDescriptorPool descriptorPool; + + VkDescriptorSet cameraDescriptorSet; + std::vector modelDescriptorSets; + VkDescriptorSet timeDescriptorSet; - VkDescriptorSet cameraDescriptorSet; - std::vector modelDescriptorSets; - VkDescriptorSet timeDescriptorSet; + std::vector grassDescriptorSets; + std::vector computeDescriptorSets; VkPipelineLayout graphicsPipelineLayout; VkPipelineLayout grassPipelineLayout; diff --git a/src/SwapChain.cpp b/src/SwapChain.cpp index 711fec0..532c358 100644 --- a/src/SwapChain.cpp +++ b/src/SwapChain.cpp @@ -188,8 +188,9 @@ VkSemaphore SwapChain::GetRenderFinishedVkSemaphore() const { return renderFinishedSemaphore; } -void SwapChain::Recreate() { +void SwapChain::Recreate(float width, float height) { Destroy(); + glfwSetWindowSize(GetGLFWWindow(), width, height); Create(); } @@ -204,7 +205,9 @@ bool SwapChain::Acquire() { } if (result == VK_ERROR_OUT_OF_DATE_KHR) { - Recreate(); + int width, height; + glfwGetWindowSize(GetGLFWWindow(), &width, &height); + Recreate(width, height); return false; } @@ -233,7 +236,9 @@ bool SwapChain::Present() { } if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) { - Recreate(); + int width, height; + glfwGetWindowSize(GetGLFWWindow(), &width, &height); + Recreate(width, height); return false; } diff --git a/src/SwapChain.h b/src/SwapChain.h index dbafcf0..0cbaf0f 100644 --- a/src/SwapChain.h +++ b/src/SwapChain.h @@ -17,7 +17,7 @@ class SwapChain { VkSemaphore GetImageAvailableVkSemaphore() const; VkSemaphore GetRenderFinishedVkSemaphore() const; - void Recreate(); + void Recreate(float width, float height); bool Acquire(); bool Present(); ~SwapChain(); diff --git a/src/main.cpp b/src/main.cpp index 8bf822b..6f54658 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -16,7 +16,8 @@ namespace { if (width == 0 || height == 0) return; vkDeviceWaitIdle(device->GetVkDevice()); - swapChain->Recreate(); + swapChain->Recreate(width, height); + camera->UpdateAspectRatio(float(width) / height); renderer->RecreateFrameResources(); } @@ -67,7 +68,7 @@ namespace { int main() { static constexpr char* applicationName = "Vulkan Grass Rendering"; - InitializeWindow(640, 480, applicationName); + InitializeWindow(1280, 960, applicationName); unsigned int glfwExtensionCount = 0; const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); @@ -90,7 +91,7 @@ int main() { swapChain = device->CreateSwapChain(surface, 5); - camera = new Camera(device, 640.f / 480.f); + camera = new Camera(device, 1280.f / 960.f); VkCommandPoolCreateInfo transferPoolInfo = {}; transferPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; @@ -116,7 +117,7 @@ int main() { grassImageMemory ); - float planeDim = 15.f; + float planeDim = 50.f; float halfWidth = planeDim * 0.5f; Model* plane = new Model(device, transferCommandPool, { @@ -128,7 +129,7 @@ int main() { { 0, 1, 2, 2, 3, 0 } ); plane->SetTexture(grassImage); - + Blades* blades = new Blades(device, transferCommandPool, planeDim); vkDestroyCommandPool(device->GetVkDevice(), transferCommandPool, nullptr); @@ -143,10 +144,20 @@ int main() { glfwSetMouseButtonCallback(GetGLFWWindow(), mouseDownCallback); glfwSetCursorPosCallback(GetGLFWWindow(), mouseMoveCallback); + int time_start = GetTickCount(); + int count = 0; + while (!ShouldQuit()) { glfwPollEvents(); scene->UpdateTime(); renderer->Frame(); + count++; + if (count == 1000) { + int total_time = GetTickCount() - time_start; + printf("Total Time for 500 frames: %d\n", total_time); + printf("Time per frame: %f\n", float(total_time) / 1000.0); + printf("fps: %f\n", 1000000.0 / float(total_time)); + } } vkDeviceWaitIdle(device->GetVkDevice()); diff --git a/src/shaders/compute.comp b/src/shaders/compute.comp index 0fd0224..010a389 100644 --- a/src/shaders/compute.comp +++ b/src/shaders/compute.comp @@ -15,9 +15,13 @@ layout(set = 1, binding = 0) uniform Time { }; struct Blade { + // Position and direction vec4 v0; + // Bezier point and height vec4 v1; + // Physical model guide and width vec4 v2; + // Up vector and stiffness coefficient vec4 up; }; @@ -26,31 +30,181 @@ struct Blade { // 2. Write out the culled blades // 3. Write the total number of blades remaining +layout(set = 2, binding = 0) buffer Blades{ + Blade blades[]; +}; + +layout(set = 2, binding = 1) buffer CulledBlades{ + Blade culledBlades[]; +}; + // 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 = 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); } void main() { - // Reset the number of blades to 0 - if (gl_GlobalInvocationID.x == 0) { - // numBlades.vertexCount = 0; - } - barrier(); // Wait till all threads reach this point + // Reset the number of blades to 0 + if (gl_GlobalInvocationID.x == 0) { + numBlades.vertexCount = 0; + } + barrier(); // Wait till all threads reach this point // TODO: Apply forces on every blade and update the vertices in the buffer + uint index = gl_GlobalInvocationID.x; + + Blade this_blade = blades[index]; + + vec3 this_v0 = this_blade.v0.xyz; + vec3 this_v1 = this_blade.v1.xyz; + vec3 this_v2 = this_blade.v2.xyz; + vec3 this_up = this_blade.up.xyz; + + float this_h = this_blade.v1.w; + float this_theta = this_blade.v0.w; + + + //Gravity + vec4 D = vec4(0, -1, 0, 9.8f); + vec3 gE = normalize(D.xyz) * D.w; + + //Front Gravity + vec3 width_dir = (vec3(sin(this_theta), 0, cos(this_theta))); + vec3 front_dir = normalize(cross(this_up, width_dir)); + + vec3 gF = 0.25 * length(gE) * front_dir; + + vec3 g = gE + gF; + + //Recovery + float stiffness = this_blade.up.w; + + vec3 iv2 = this_v0 + normalize(this_up) * this_h; + +//Thanks for byumjin + //min, max Height : 1.3, 2.5 + float maxCap = 1.8; + vec3 r = (iv2 - this_v2) * stiffness * maxCap/ min(this_h, maxCap); + + //Wind + vec3 wind_dir = normalize(vec3(0.5, 0, 1)); + float wind_speed = 8.0; + float wave_division_width = 5.0; + + float wave_info = (cos((dot(vec3(this_v0.x, 0, this_v0.z), wind_dir) - wind_speed * totalTime) / wave_division_width) + 0.7); + +//5.1 Wind + //directional alignment + float fd = 1 - abs(dot(wind_dir, normalize(this_v2 - this_v0))); + + //height ratio + float fr = dot((this_v2 - this_v0), this_up) / this_h; + + // + float wind_power = 15.0f; + vec3 w = wind_dir * wind_power * wave_info * fd * fr; + + //Total Force + vec3 tv2 = (g + r + w) * deltaTime; + vec3 fv2 = this_v2 + tv2; + +//5.2 State Validation + //1. v2 must not be pushed beneath the ground, + //2. the position of v1 has to be set according to the position of v2, + //3. and the length of the curve must be equal to the height of the blade of grass. + //Total force + + + //a position of v2 above the local plane can be ensured + fv2 = fv2 - this_up * min(dot(this_up, (fv2 - this_v0)), 0); + + + float l_proj = length(fv2 - this_v0 - this_up * dot((fv2 - this_v0),this_up)); + float lprohOverh = l_proj / this_h; + vec3 fv1 = this_v0 + this_h * this_up * max((1 - l_proj / this_h), 0.05*max(l_proj / this_h, 1)); + + + float L0 = distance(fv2, this_v0); + float L1 = distance(fv2, fv1) + distance(fv1, this_v0); + float L = (2.0*L0 + (3.0-1.0)*L1)/(3.0+1.0); + float r_len = this_h / L; + + this_blade.v1.xyz = this_v0 + r_len*(fv1 - this_v0); + this_blade.v2.xyz = this_blade.v1.xyz + r_len*(fv2 - fv1); + blades[index] = this_blade; + + // TODO: Cull blades that are too far away or not in the camera frustum and write them + // to the culled blades buffer + // 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 + + this_v1 = this_blade.v1.xyz; + this_v2 = this_blade.v2.xyz; + + //Orientation culling + bool orientation_culled = false; + mat4 inverse_view = inverse(camera.view); + vec3 world_view_dir = (inverse_view * vec4(0,0,1,0)).xyz; + float Epsilon = 0.05; + if(abs(dot(front_dir, world_view_dir)) < Epsilon) + orientation_culled = true; + + //View-Frustum Culling + bool view_frustum_culled = true; + vec3 this_mid = 0.25 * this_v0 + 0.5 * this_v1 + 0.25 * this_v2; + vec4 NDC_v0, NDC_v2, NDC_mid; + mat4 vp = camera.proj * camera.view; + NDC_v0 = vp * vec4(this_v0, 1.0f); + NDC_v2 = vp * vec4(this_v2, 1.0f); + NDC_mid = vp * vec4(this_mid, 1.0f); + + NDC_v0/=NDC_v0.w; + NDC_v2/=NDC_v2.w; + NDC_mid/=NDC_mid.w; + + float tolerance = 0.2; + + if(NDC_v0.x < 1+tolerance && NDC_v0.x > -1-tolerance && NDC_v0.y < 1+tolerance && NDC_v0.y > -1-tolerance && NDC_v0.z < 1+tolerance && NDC_v0.z > -tolerance + || NDC_v2.x < 1+tolerance && NDC_v2.x > -1-tolerance && NDC_v2.y < 1+tolerance && NDC_v2.y > -1-tolerance && NDC_v2.z < 1+tolerance && NDC_v2.z > -tolerance + || NDC_mid.x < 1+tolerance && NDC_mid.x > -1-tolerance && NDC_mid.y < 1+tolerance && NDC_mid.y > -1-tolerance && NDC_mid.z < 1+tolerance && NDC_mid.z > -tolerance){ + view_frustum_culled = false; + } + + //Distance Culling + bool distance_culled = false; + float min_distance = 0.1; + float far_distance = 100; + + //seperate into 10 buckets + //the distance between each bucket is 10 + vec4 view_v0 = camera.view * vec4(this_v0, 1.0f); + float horizontal_distance = abs(dot(view_v0.xyz, vec3(0,0,1))); + + if(horizontal_distance > far_distance){ + distance_culled = true; + } + else{ + int bucket_level = int(horizontal_distance) / 10; + if(bucket_level > 0){ + if(index % bucket_level < int(bucket_level * (1.0 - horizontal_distance/far_distance))){ + distance_culled = true; + } + } + } + + + if(!orientation_culled && !view_frustum_culled && !distance_culled){ + //Add to the culledBlades + culledBlades[atomicAdd(numBlades.vertexCount , 1)] = this_blade; + } - // TODO: Cull blades that are too far away or not in the camera frustum and write them - // to the culled blades buffer - // 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 } diff --git a/src/shaders/graphics.frag b/src/shaders/graphics.frag index 5f15861..864ec5b 100644 --- a/src/shaders/graphics.frag +++ b/src/shaders/graphics.frag @@ -9,5 +9,7 @@ layout(location = 1) in vec2 fragTexCoord; layout(location = 0) out vec4 outColor; void main() { - outColor = texture(texSampler, fragTexCoord); + //Yellow Tint + vec4 TintColor = vec4(0.7,0.7,0.3,1.0); + outColor = texture(texSampler, fragTexCoord) * TintColor; } diff --git a/src/shaders/grass.frag b/src/shaders/grass.frag index c7df157..f4f296b 100644 --- a/src/shaders/grass.frag +++ b/src/shaders/grass.frag @@ -7,11 +7,64 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { } camera; // TODO: Declare fragment shader inputs +layout(location = 0) in vec4 world_pos; +layout(location = 1) in vec3 world_normal; +layout(location = 2) in vec2 tex_coords; layout(location = 0) out vec4 outColor; void main() { // TODO: Compute fragment color + vec3 upper_color = vec3(0.3,0.9,0.1); + vec3 lower_color = vec3(0.0,0.4,0.1); - outColor = vec4(1.0); + vec3 yellow_upper_color = vec3(0.6,0.8,0.35); + vec3 yellow_lower_color = vec3(0.6,0.55,0.23); + + vec3 lightDir = normalize(vec3(-1.0, 5.0, -3.0)); + +//basic diffuse(lambert) + //float NoL = clamp(dot(world_normal, lightDir), 0.1, 1.0); + + //vec3 diffuse_color = mix(yellow_lower_color, yellow_upper_color, tex_coords.y); + //vec3 colorLinear = diffuse_color * NoL; + +//blinn-phong + vec3 normal = normalize(world_normal); + vec4 cameraPos = inverse(camera.view) * vec4(0,0,0,1); + cameraPos /= cameraPos.w; + float lambertian = max(dot(lightDir,normal), 0.0); + float specular = 0.0; + + if(lambertian > 0.0) { + vec3 viewDir = normalize((cameraPos - world_pos).xyz); + vec3 halfDir = normalize(lightDir + viewDir); + float specAngle = max(dot(halfDir, normal), 0.0); + specular = pow(specAngle, 128); + } + + vec3 specColor = vec3(0.9,0.9,0.9); + vec3 diffuseColor = mix(lower_color, upper_color, tex_coords.y); + float ambient = 0.15; + vec3 colorLinear = (ambient + + lambertian + specular) * diffuseColor; + + + ////Distance Culling + //float min_distance = 0.1; + //float far_distance = 100; + + ////seperate into 10 buckets + //the distance between each bucket is 10 + //vec4 view_v0 = camera.view * vec4(world_pos.xyz, 1.0f); + //float horizontal_distance = abs(dot(view_v0.xyz, vec3(0,0,1))); + + //int bucket_level = 11; + //if(horizontal_distance < far_distance){ + // bucket_level = int(horizontal_distance) / 10; + //} + //outColor = vec4(vec3(float(bucket_level)/10.0f), 1.0f); + outColor = vec4(colorLinear, 1.0); + + //outColor = vec4(1.0); } diff --git a/src/shaders/grass.tesc b/src/shaders/grass.tesc index f9ffd07..67461d7 100644 --- a/src/shaders/grass.tesc +++ b/src/shaders/grass.tesc @@ -1,6 +1,7 @@ #version 450 #extension GL_ARB_separate_shader_objects : enable +//only need one vertex position in the evaluation shader(v0) layout(vertices = 1) out; layout(set = 0, binding = 0) uniform CameraBufferObject { @@ -9,18 +10,38 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { } camera; // TODO: Declare tessellation control shader inputs and outputs +layout(location = 0) in vec4 tesc_v1[]; +layout(location = 1) in vec4 tesc_v2[]; +layout(location = 2) in vec4 tesc_up[]; +layout(location = 3) in vec4 tesc_width_dir[]; + +layout(location = 0) patch out vec4 tese_v1; +layout(location = 1) patch out vec4 tese_v2; +layout(location = 2) patch out vec4 tese_up; +layout(location = 3) patch out vec4 tese_width_dir; 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 + // TODO: Write any shader outputs + // only need one vertex data + tese_v1 = tesc_v1[0]; + tese_v2 = tesc_v2[0]; + tese_up = tesc_up[0]; + tese_width_dir = tesc_width_dir[0]; // TODO: Set level of tesselation - // gl_TessLevelInner[0] = ??? - // gl_TessLevelInner[1] = ??? - // gl_TessLevelOuter[0] = ??? - // gl_TessLevelOuter[1] = ??? - // gl_TessLevelOuter[2] = ??? - // gl_TessLevelOuter[3] = ??? + // horizontal tesellation + gl_TessLevelInner[0] = 1.0; + // vertical tesellation + gl_TessLevelInner[1] = 7.0; + // vertical + gl_TessLevelOuter[0] = 7.0; + // horizontal + gl_TessLevelOuter[1] = 1.0; + // vertical + gl_TessLevelOuter[2] = 7.0; + // horizontal + gl_TessLevelOuter[3] = 1.0; } diff --git a/src/shaders/grass.tese b/src/shaders/grass.tese index 751fff6..a4414ce 100644 --- a/src/shaders/grass.tese +++ b/src/shaders/grass.tese @@ -8,11 +8,56 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { mat4 proj; } camera; +layout(location = 0) patch in vec4 tese_v1; +layout(location = 1) patch in vec4 tese_v2; +layout(location = 2) patch in vec4 tese_up; +layout(location = 3) patch in vec4 tese_width_dir; + +layout(location = 0) out vec4 world_pos; +layout(location = 1) out vec3 world_normal; +layout(location = 2) out vec2 tex_coords; + // TODO: Declare tessellation evaluation shader inputs and outputs void main() { float u = gl_TessCoord.x; float v = gl_TessCoord.y; + //Camera Matrix + mat4 vp = camera.proj * camera.view; + + //"Responsive Real-Time Grass Rendering for General 3D Scenes" 6.3 Blade Geometry + vec3 v0 = gl_in[0].gl_Position.xyz; + vec3 a = v0 + v * (tese_v1.xyz - v0); + vec3 b = tese_v1.xyz + v * (tese_v2.xyz - tese_v1.xyz); + vec3 c = a + v * (b - a); + vec3 t1 = tese_width_dir.xyz; // bitangent + float w = tese_v2.w; + vec3 c0 = c - w * t1 * 0.5; + vec3 c1 = c + w * t1 * 0.5; + vec3 t0 = normalize(b-a); + vec3 n = normalize(cross(t0,t1)); + + // quad + //float t = u; + + // triangle + //float t = u + 0.5 * v - u * v; + + // quadratic + //float t = u - u * v * v; + + // triangle-tip + // border threshold between quad and triangle + float threshold = 0.35; + float t = 0.5 + (u - 0.5) * (1 - max(v - threshold, 0)/(1 - threshold)); + + vec3 p = (1 - t) * c0 + t * c1; + gl_Position = vp * vec4(p, 1.0); + + // out + world_pos = vec4(p, 1.0); + world_normal = n; + tex_coords = vec2(u,v); // TODO: Use u and v to parameterize along the grass blade and output positions for each vertex of the grass blade -} +} \ No newline at end of file diff --git a/src/shaders/grass.vert b/src/shaders/grass.vert index db9dfe9..ac4ba97 100644 --- a/src/shaders/grass.vert +++ b/src/shaders/grass.vert @@ -7,6 +7,15 @@ layout(set = 1, binding = 0) uniform ModelBufferObject { }; // TODO: Declare vertex shader inputs and outputs +layout(location = 0) in vec4 v0; +layout(location = 1) in vec4 v1; +layout(location = 2) in vec4 v2; +layout(location = 3) in vec4 up; + +layout(location = 0) out vec4 tesc_v1; +layout(location = 1) out vec4 tesc_v2; +layout(location = 2) out vec4 tesc_up; +layout(location = 3) out vec4 tesc_width_dir; out gl_PerVertex { vec4 gl_Position; @@ -14,4 +23,20 @@ out gl_PerVertex { void main() { // TODO: Write gl_Position and any other shader outputs + vec4 world_v0 = model * v0; + vec4 world_v1 = model * vec4(v1.xyz,1.0); + world_v1 /= world_v1.w; + vec4 world_v2 = model * vec4(v2.xyz,1.0); + world_v2 /= world_v2.w; + //v0.w is orientation, v1.w is height, v2.w is width, up.w is stiffness + + tesc_v1 = vec4(world_v1.xyz, v1.w); + tesc_v2 = vec4(world_v2.xyz, v2.w); + tesc_up.xyz = normalize(up.xyz); + + float sin_theta = sin(v0.w), cos_theta = cos(v0.w); + tesc_width_dir.xyz = normalize(vec3(sin_theta, 0, cos_theta)); + tesc_width_dir.w = up.w; + + gl_Position = world_v0; }