diff --git a/2017-11-07 00-48-58.mp4 b/2017-11-07 00-48-58.mp4 new file mode 100644 index 0000000..3e2feec Binary files /dev/null and b/2017-11-07 00-48-58.mp4 differ diff --git a/README.md b/README.md index a744a2e..7c7f229 100644 --- a/README.md +++ b/README.md @@ -1,297 +1,64 @@ -Instructions - Vulkan Grass Rendering -======================== - -This is due **Sunday 11/5, evening at midnight**. - -**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. - -![](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. - -### 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) - -### 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. +**University of Pennsylvania, CIS 565: GPU Programming and Architecture, +Project 6 - Vulkan Grass Rendering** + +* Josh Lawrence +* Tested on: Windows 10, i7-6700HQ @ 2.6GHz 8GB, GTX 960M 2GB Personal + +**Overview**
+For implementation details see:
+https://www.cg.tuwien.ac.at/research/publications/2017/JAHRMANN-2017-RRTG/JAHRMANN-2017-RRTG-draft.pdfs +
+For tesselation details see:
+http://in2gpu.com/2014/07/12/tessellation-tutorial-opengl-4-3/ +http://prideout.net/blog/?p=48#levels + + +**Highlights**
+Several culling optimizations were used to reduce computation cost: orientation culling, frustum culling and distance culling. To reduce triangle count, tesselation level is reduced the further the blade is away from the camera. Performance comparisons between culling techniques are sensitive to the setup of the scene but provide insight into how much work is being removed by these culling techniques. For the scene provided frustum culling was the most effective at improving performance, followed orientation, then distance. This makes sense as frustum culling excludes most of the scene from the computation. Orientation and distance are still doing work for grass blades that don't show up on the screen and are more scene dependent. Distance could be more effective than orientation for very large scenes but for the scene that was rendered this was not the case. Tessaltion falloff based on distance from camera has noticable performance improvements when there are large numbers of grass blades to render but for realstic amounts of grass, it's not that useful. +
+
+ +**Vulkan Grass Rendering**
+![](img/thegrass.gif) + +**Screenshot**
+![](img/grass.png) + +# Data
+**Performance improvement due to all culling techniques**
+![](img/graphcullvsnocull.png) + +**Performance comparison between culling techniques**
+![](img/graphcullcompare.png) + +**Performance comparison between tesselation falloff vs no falloff**
+![](img/graphfalloffvsnofalloff.png) + +**Table of data used for graph**
+![](img/data.png) + + +**GPU Device Properties**
+https://devblogs.nvidia.com/parallelforall/5-things-you-should-know-about-new-maxwell-gpu-architecture/
+cuda cores 640
+mem bandwidth 86.4 GB/s
+L2 cache size 2MB
+num banks in shared memory 32
+number of multiprocessor 5
+max blocks per multiprocessor 32
+total shared mem per block 49152 bytes
+total shared mem per MP 65536 bytes
+total regs per block and MP 65536
+max threads per block 1024
+max threads per mp 2048
+total const memory 65536
+max reg per thread 255
+max concurrent warps 64
+total global mem 2G
+
+max dims for block 1024 1024 64
+max dims for a grid 2,147,483,647 65536 65536
+clock rate 1,097,5000
+texture alignment 512
+concurrent copy and execution yes
+major.minor 5.0
diff --git a/data.xlsx b/data.xlsx new file mode 100644 index 0000000..8149e1f Binary files /dev/null and b/data.xlsx differ diff --git a/img/data.png b/img/data.png new file mode 100644 index 0000000..0c955a2 Binary files /dev/null and b/img/data.png differ diff --git a/img/graphcullcompare.png b/img/graphcullcompare.png new file mode 100644 index 0000000..8d34bff Binary files /dev/null and b/img/graphcullcompare.png differ diff --git a/img/graphcullvsnocull.png b/img/graphcullvsnocull.png new file mode 100644 index 0000000..1d5f6da Binary files /dev/null and b/img/graphcullvsnocull.png differ diff --git a/img/graphfalloffvsnofalloff.png b/img/graphfalloffvsnofalloff.png new file mode 100644 index 0000000..d5f3a7f Binary files /dev/null and b/img/graphfalloffvsnofalloff.png differ diff --git a/img/grass.png b/img/grass.png new file mode 100644 index 0000000..6f372ef Binary files /dev/null and b/img/grass.png differ diff --git a/img/grassvid.mp4 b/img/grassvid.mp4 new file mode 100644 index 0000000..a791eb8 Binary files /dev/null and b/img/grassvid.mp4 differ diff --git a/settingUp.txt b/settingUp.txt new file mode 100644 index 0000000..957222e --- /dev/null +++ b/settingUp.txt @@ -0,0 +1,6 @@ +when you clone make sure its a recursive clone +have git bash installed. +rclick in window and bring up a git bash +do (without quotes): +"mkdir build; cd build; cmake-gui .." +click configure (might have to copy ), then generate, then open project diff --git a/src/Renderer.cpp b/src/Renderer.cpp index b445d04..317f22b 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(); + CreateGrassModelDescriptorSetLayout(); CreateTimeDescriptorSetLayout(); CreateComputeDescriptorSetLayout(); CreateDescriptorPool(); @@ -172,6 +173,27 @@ void Renderer::CreateModelDescriptorSetLayout() { } } +void Renderer::CreateGrassModelDescriptorSetLayout() { + 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, &grassModelDescriptorSetLayout) != VK_SUCCESS) { + throw std::runtime_error("Failed to create descriptor set layout"); + } +} + void Renderer::CreateTimeDescriptorSetLayout() { // Describe the binding of the descriptor set layout VkDescriptorSetLayoutBinding uboLayoutBinding = {}; @@ -198,24 +220,59 @@ 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 allGrassLayoutBinding = {}; + allGrassLayoutBinding.binding = 0; + allGrassLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;//no need for us to access once on the gpu + allGrassLayoutBinding.descriptorCount = 1; + allGrassLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + allGrassLayoutBinding.pImmutableSamplers = nullptr; + + VkDescriptorSetLayoutBinding culledGrassLayoutBinding = {}; + culledGrassLayoutBinding.binding = 1; + culledGrassLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + culledGrassLayoutBinding.descriptorCount = 1; + culledGrassLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + culledGrassLayoutBinding.pImmutableSamplers = nullptr; + + VkDescriptorSetLayoutBinding numGrassLayoutBinding = {}; + numGrassLayoutBinding.binding = 2; + numGrassLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + numGrassLayoutBinding.descriptorCount = 1; + numGrassLayoutBinding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; + numGrassLayoutBinding.pImmutableSamplers = nullptr; + std::vector bindings = { allGrassLayoutBinding, culledGrassLayoutBinding, numGrassLayoutBinding }; + + // 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() { // Describe which descriptor types that the descriptor sets will contain + const uint32_t numModels = scene->GetModels().size(); + const uint32_t numBlades = scene->GetBlades().size(); + const uint32_t numModelsAndBlades = numModels + numBlades; std::vector poolSizes = { // Camera { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER , 1}, // Models + Blades - { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER , static_cast(scene->GetModels().size() + scene->GetBlades().size()) }, + { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER , numModelsAndBlades }, // Models + Blades - { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER , static_cast(scene->GetModels().size() + scene->GetBlades().size()) }, + { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER , numModelsAndBlades }, // Time (compute) { 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, static_cast(3 * numBlades)} }; VkDescriptorPoolCreateInfo poolInfo = {}; @@ -320,6 +377,45 @@ 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[] = { grassModelDescriptorSetLayout};//same as model without the sampler + //VkDescriptorSetLayout layouts[] = { modelDescriptorSetLayout }; + 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"); + } + + const uint32_t numWrites = 1; + std::vector descriptorWrites(numWrites * 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[numWrites * i + 0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[numWrites * i + 0].dstSet = grassDescriptorSets[i]; + descriptorWrites[numWrites * i + 0].dstBinding = 0; + descriptorWrites[numWrites * i + 0].dstArrayElement = 0; + descriptorWrites[numWrites * i + 0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + descriptorWrites[numWrites * i + 0].descriptorCount = 1; + descriptorWrites[numWrites * i + 0].pBufferInfo = &modelBufferInfo; + descriptorWrites[numWrites * i + 0].pImageInfo = nullptr; + descriptorWrites[numWrites * i + 0].pTexelBufferView = nullptr; + + } + + // Update descriptor sets + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } void Renderer::CreateTimeDescriptorSet() { @@ -360,6 +456,74 @@ 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 };//same as model without the sampler + 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"); + } + + const uint32_t numWrites = 3; + std::vector descriptorWrites(numWrites * computeDescriptorSets.size()); + + for (uint32_t i = 0; i < scene->GetBlades().size(); ++i) { + VkDescriptorBufferInfo bladesBufferInfo = {}; + bladesBufferInfo.buffer = scene->GetBlades()[i]->GetBladesBuffer(); + bladesBufferInfo.offset = 0; + bladesBufferInfo.range = NUM_BLADES*sizeof(Blade); + + VkDescriptorBufferInfo culledBladesBufferInfo = {}; + culledBladesBufferInfo.buffer = scene->GetBlades()[i]->GetCulledBladesBuffer(); + culledBladesBufferInfo.offset = 0; + culledBladesBufferInfo.range = NUM_BLADES*sizeof(Blade); + + VkDescriptorBufferInfo numBladesBufferInfo = {}; + numBladesBufferInfo.buffer = scene->GetBlades()[i]->GetNumBladesBuffer(); + numBladesBufferInfo.offset = 0; + numBladesBufferInfo.range = sizeof(BladeDrawIndirect); + + descriptorWrites[numWrites * i + 0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[numWrites * i + 0].dstSet = computeDescriptorSets[i]; + descriptorWrites[numWrites * i + 0].dstBinding = 0; + descriptorWrites[numWrites * i + 0].dstArrayElement = 0; + descriptorWrites[numWrites * i + 0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[numWrites * i + 0].descriptorCount = 1; + descriptorWrites[numWrites * i + 0].pBufferInfo = &bladesBufferInfo; + descriptorWrites[numWrites * i + 0].pImageInfo = nullptr; + descriptorWrites[numWrites * i + 0].pTexelBufferView = nullptr; + + descriptorWrites[numWrites * i + 1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[numWrites * i + 1].dstSet = computeDescriptorSets[i]; + descriptorWrites[numWrites * i + 1].dstBinding = 1; + descriptorWrites[numWrites * i + 1].dstArrayElement = 0; + descriptorWrites[numWrites * i + 1].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[numWrites * i + 1].descriptorCount = 1; + descriptorWrites[numWrites * i + 1].pBufferInfo = &culledBladesBufferInfo; + descriptorWrites[numWrites * i + 1].pImageInfo = nullptr; + descriptorWrites[numWrites * i + 1].pTexelBufferView = nullptr; + + descriptorWrites[numWrites * i + 2].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + descriptorWrites[numWrites * i + 2].dstSet = computeDescriptorSets[i]; + descriptorWrites[numWrites * i + 2].dstBinding = 2; + descriptorWrites[numWrites * i + 2].dstArrayElement = 0; + descriptorWrites[numWrites * i + 2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + descriptorWrites[numWrites * i + 2].descriptorCount = 1; + descriptorWrites[numWrites * i + 2].pBufferInfo = &numBladesBufferInfo; + descriptorWrites[numWrites * i + 2].pImageInfo = nullptr; + descriptorWrites[numWrites * i + 2].pTexelBufferView = nullptr; + + } + + // Update descriptor sets + vkUpdateDescriptorSets(logicalDevice, static_cast(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr); } void Renderer::CreateGraphicsPipeline() { @@ -654,7 +818,8 @@ void Renderer::CreateGrassPipeline() { colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; - std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, modelDescriptorSetLayout }; + std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, grassModelDescriptorSetLayout }; + //std::vector descriptorSetLayouts = { cameraDescriptorSetLayout, modelDescriptorSetLayout }; // Pipeline layout: used to specify uniform values VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; @@ -717,7 +882,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 +1049,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, NUM_BLADES / WORKGROUP_SIZE, 1, 1); // ~ End recording ~ if (vkEndCommandBuffer(computeCommandBuffer) != VK_SUCCESS) { @@ -976,13 +1145,14 @@ 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 + 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 @@ -1057,6 +1227,7 @@ Renderer::~Renderer() { vkDestroyDescriptorSetLayout(logicalDevice, cameraDescriptorSetLayout, nullptr); vkDestroyDescriptorSetLayout(logicalDevice, modelDescriptorSetLayout, nullptr); vkDestroyDescriptorSetLayout(logicalDevice, timeDescriptorSetLayout, nullptr); + vkDestroyDescriptorSetLayout(logicalDevice, computeDescriptorSetLayout, nullptr); vkDestroyDescriptorPool(logicalDevice, descriptorPool, nullptr); diff --git a/src/Renderer.h b/src/Renderer.h index 95e025f..d168ba2 100644 --- a/src/Renderer.h +++ b/src/Renderer.h @@ -17,6 +17,7 @@ class Renderer { void CreateCameraDescriptorSetLayout(); void CreateModelDescriptorSetLayout(); + void CreateGrassModelDescriptorSetLayout(); void CreateTimeDescriptorSetLayout(); void CreateComputeDescriptorSetLayout(); @@ -55,12 +56,16 @@ class Renderer { VkDescriptorSetLayout cameraDescriptorSetLayout; VkDescriptorSetLayout modelDescriptorSetLayout; + VkDescriptorSetLayout grassModelDescriptorSetLayout; VkDescriptorSetLayout timeDescriptorSetLayout; + VkDescriptorSetLayout computeDescriptorSetLayout; VkDescriptorPool descriptorPool; VkDescriptorSet cameraDescriptorSet; std::vector modelDescriptorSets; + std::vector grassDescriptorSets; + std::vector computeDescriptorSets; VkDescriptorSet timeDescriptorSet; VkPipelineLayout graphicsPipelineLayout; diff --git a/src/main.cpp b/src/main.cpp index 8bf822b..0c3b049 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,11 +5,32 @@ #include "Camera.h" #include "Scene.h" #include "Image.h" - +#include Device* device; SwapChain* swapChain; Renderer* renderer; Camera* camera; +const float planeDim = 15.f;//15 was original val +const float WIDTH = 1280; +const float HEIGHT = 960; +double old = 0.f; +double current = 0.f; +int fps = 0; +int fpstracker = 0; + +std::string convertIntToString(int number) +{ + std::stringstream ss; + ss << number; + return ss.str(); +} + +std::string convertFloatToString(double number) +{ + std::stringstream ss; + ss << number; + return ss.str(); +} namespace { void resizeCallback(GLFWwindow* window, int width, int height) { @@ -67,7 +88,7 @@ namespace { int main() { static constexpr char* applicationName = "Vulkan Grass Rendering"; - InitializeWindow(640, 480, applicationName); + InitializeWindow(WIDTH, HEIGHT, applicationName); unsigned int glfwExtensionCount = 0; const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); @@ -90,7 +111,7 @@ int main() { swapChain = device->CreateSwapChain(surface, 5); - camera = new Camera(device, 640.f / 480.f); + camera = new Camera(device, WIDTH / HEIGHT); VkCommandPoolCreateInfo transferPoolInfo = {}; transferPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; @@ -116,7 +137,6 @@ int main() { grassImageMemory ); - float planeDim = 15.f; float halfWidth = planeDim * 0.5f; Model* plane = new Model(device, transferCommandPool, { @@ -145,6 +165,18 @@ int main() { while (!ShouldQuit()) { glfwPollEvents(); + + //see rasterizer hw + current = (double)time(NULL); + fpstracker++; + const double elapsed = current - old; + if (elapsed >= 1) { + fps = (int)(fpstracker / elapsed); + fpstracker = 0; + old = current; + std::string title = "Vulkan Grass Rendering | " + convertIntToString(fps) + " FPS " + convertFloatToString(1000.f/(double)fps) + " ms"; + glfwSetWindowTitle(GetGLFWWindow(), title.c_str()); + } scene->UpdateTime(); renderer->Frame(); } diff --git a/src/shaders/compute.comp b/src/shaders/compute.comp index 0fd0224..b80dec9 100644 --- a/src/shaders/compute.comp +++ b/src/shaders/compute.comp @@ -36,6 +36,20 @@ struct Blade { // uint firstInstance; // = 0 // } numBlades; +layout(set = 2, binding = 0) buffer Blades { + Blade blades[]; +}; +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); } @@ -43,14 +57,110 @@ bool inBounds(float value, float bounds) { 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 // TODO: Apply forces on every blade and update the vertices in the buffer + //make const + Blade thisblade = blades[gl_GlobalInvocationID.x]; + + //https://www.cg.tuwien.ac.at/research/publications/2017/JAHRMANN-2017-RRTG/JAHRMANN-2017-RRTG-draft.pdfs + //pull out the paper's blade properties v0,v1,v2, up,angle,h,w,stiffness stored in thisblade's four vec4s + //make const + vec3 v0 = thisblade.v0.xyz; + vec3 v1 = thisblade.v1.xyz; + vec3 v2 = thisblade.v2.xyz; + vec3 up = thisblade.up.xyz; + float angle = thisblade.v0.w; + float h = thisblade.v1.w; + float w = thisblade.v2.w; + float s = thisblade.up.w;//stiffness + + vec3 dir = normalize(cross( up,vec3(sin(angle),0,cos(angle)) )); + + //recovery + vec3 Iv2 = v0 + (h*up);//initial v2 + vec3 recovery = (Iv2 - v2)*s; + + //gravity (environment + front), more complicated in paper for environment but this will do + vec3 gravity = vec3(0.f, -9.8f, 0.f) + 0.25*9.8*dir; + + //wind + float oneOverHeight = 1.f/h; + vec3 wind_influence = sin(totalTime)*vec3(1.f, 0.f, 0.f) + sin(totalTime*0.5)*vec3(0.5f, 0.f, 0.5f); + vec3 baseToV2 = v2-v0; + float fd = 1.f - abs( dot(normalize(wind_influence), normalize(baseToV2)) ); + float fr = dot(baseToV2, up) * oneOverHeight; + float alignment_value = fd*fr; + vec3 wind = wind_influence*alignment_value*5.f; + + //get the new tip location + vec3 newV2 = v2 + (recovery+gravity+wind)*deltaTime; + newV2 = newV2 - (up * min(dot(up, newV2-v0),0.f) ); + + //get the new control point location + float lproj = length(newV2 - v0 - up*dot(newV2-v0,up)); + vec3 newV1 = v0 + h*up*max(1.f - (lproj/h), 0.05f*max(lproj/h, 1.f)); + + //get the corrected tip and control point location (make sure length is constant) + float L0 = length(newV2 - v0); + float L1 = length(newV1-newV2) + length(newV1-v0); + float L = (2.f*L0 + L1) * 0.33f; + float r = h / L; + vec3 v1_corr = v0 + r*(newV1-v0); + vec3 v2_corr = v1_corr + r*(newV2 - newV1); + + //update the blade + thisblade.v1 = vec4(v1_corr, h); + thisblade.v2 = vec4(v2_corr, w); + blades[gl_GlobalInvocationID.x] = thisblade; // 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 + + //v0 In Frustum + mat4 viewproj = camera.proj * camera.view; + float bound = 1.07; + vec4 v0ndc = viewproj * vec4(v0,1.f); + v0ndc.xyz *= -(1.f/v0ndc.w); + bool v0InFrust = inBounds(v0ndc.x, bound) && inBounds(v0ndc.y, bound) && inBounds(v0ndc.z, bound); + + //middle in Frustum + vec4 m = vec4(0.25f*v0 + 0.5f*v1_corr + 0.25f*v2_corr, 1.f); + vec4 mndc = viewproj * m; + mndc.xyz *= -(1.f/mndc.w); + bool mInFrust = inBounds(mndc.x, bound) && inBounds(mndc.y, bound) && inBounds(mndc.z, bound); + + //v2_corr in Frustum + vec4 v2ndc = viewproj * vec4(v2_corr,1.f); + v2ndc.xyz *= -(1.f/v2ndc.w); + bool v2InFrust = inBounds(v2ndc.x, bound) && inBounds(v2ndc.y, bound) && inBounds(v2ndc.z, bound); + + //frust cull + bool frustcull = !(v0InFrust || mInFrust || v2InFrust); + + + //ori cull + mat4 camToWorld = inverse(camera.view); + bool oricull = abs(dot(dir, normalize(v0-camToWorld[3].xyz))) > 0.9f; + + //distance cull + float n = 50; + float dmax = 50; + vec3 c = mat3(camToWorld) * -camera.view[3].xyz; + float dproj = length(v0 - c - up*dot(v0-c, up)); + float maxcullforbucket = floor( n * (1.f-(dproj/dmax)) ); + bool distcull = mod(gl_GlobalInvocationID.x, n) > maxcullforbucket; + + //add if not culled + if(!(oricull || frustcull || distcull)) { +// if(!oricull) { +// if(!distcull) { +// if(!frustcull) { + culledblades[atomicAdd(numBlades.vertexCount, 1)] = thisblade; + } +// culledblades[atomicAdd(numBlades.vertexCount, 1)] = thisblade; } diff --git a/src/shaders/grass.frag b/src/shaders/grass.frag index c7df157..8e2e559 100644 --- a/src/shaders/grass.frag +++ b/src/shaders/grass.frag @@ -7,11 +7,22 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { } camera; // TODO: Declare fragment shader inputs +//ins +layout(location = 0) in vec3 nortese; +layout(location = 1) in float uvtese_v; + layout(location = 0) out vec4 outColor; void main() { // TODO: Compute fragment color + vec3 lightdir = vec3(0,1,0); + + vec3 basecolor = vec3(0.3, 0.9, 0.5); + vec3 tipcolor = vec3(0.93, 0.91, 0.67); - outColor = vec4(1.0); + float lambert = clamp(abs(dot(nortese,lightdir)), 0.35, 1.0);//min clamp not 0 for ambient + float t = uvtese_v*uvtese_v*uvtese_v;//cube it to push tip color closer to tip + outColor = vec4(lambert*mix(basecolor, tipcolor, t),1.0); +// outColor = vec4(uvtese_v, uvtese_v, uvtese_v,1.0);//uv test } diff --git a/src/shaders/grass.tesc b/src/shaders/grass.tesc index f9ffd07..8f20003 100644 --- a/src/shaders/grass.tesc +++ b/src/shaders/grass.tesc @@ -9,18 +9,55 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { } camera; // TODO: Declare tessellation control shader inputs and outputs +//ins +layout(location = 0) in vec4 v1tesc[]; +layout(location = 1) in vec4 v2tesc[]; +layout(location = 2) in vec3 uptesc[]; +layout(location = 3) in vec3 bitantesc[]; + +//if no patch designation need [] +//outs +layout(location = 0) patch out vec4 v1tese; +layout(location = 1) patch out vec4 v2tese; +layout(location = 2) patch out vec3 uptese; +layout(location = 3) patch out vec3 bitantese; void main() { // Don't move the origin location of the patch + mat4 viewproj = camera.proj*camera.view; gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position; // TODO: Write any shader outputs + v1tese = v1tesc[gl_InvocationID]; + v2tese = v2tesc[gl_InvocationID]; + uptese = uptesc[gl_InvocationID]; + bitantese = bitantesc[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] = ??? + //http://in2gpu.com/2014/07/12/tessellation-tutorial-opengl-4-3 + + //to set level dynamically, you can find persp z (0-1) and use that to interp (mix) between tess levels (say 5 for close 1 for far) +// vec4 ndc = viewproj*vec4(gl_in[0].gl_Position.xyz,1.0); +// float t = -ndc.z / ndc.w; + + vec4 viewpos = camera.view*vec4(gl_in[0].gl_Position.xyz,1.0); + float t = clamp(-viewpos.z/30.f, 0.f, 1.f); + int mintess = 1; + int maxtess = 10; + float level = mix(maxtess, mintess, t); +// float level = maxtess; + + //controls inner tesselation. 0 == horiz tess, 1 == vert tess + gl_TessLevelInner[0] = 1; + gl_TessLevelInner[1] = level; + + //proceeds clockwise around quad, while vert indices are going ccw + //edge 0 to 3 (left) + gl_TessLevelOuter[0] = level; + //edge 3 to 2 (top) + gl_TessLevelOuter[1] = 1; + //edge 2 to 1 (right) + gl_TessLevelOuter[2] = level; + //edge 1 to 0 (bot) + gl_TessLevelOuter[3] = 1; } diff --git a/src/shaders/grass.tese b/src/shaders/grass.tese index 751fff6..723acc8 100644 --- a/src/shaders/grass.tese +++ b/src/shaders/grass.tese @@ -9,10 +9,36 @@ layout(set = 0, binding = 0) uniform CameraBufferObject { } camera; // TODO: Declare tessellation evaluation shader inputs and outputs +//if no patch designation need [] +//ins +layout(location = 0) patch in vec4 v1tese; +layout(location = 1) patch in vec4 v2tese; +layout(location = 2) patch in vec3 uptese; +layout(location = 3) patch in vec3 bitantese; + +//outs +layout(location = 0) out vec3 nortese; +layout(location = 1) out float uvtese_v; void main() { float u = gl_TessCoord.x; float v = gl_TessCoord.y; + uvtese_v = v; // TODO: Use u and v to parameterize along the grass blade and output positions for each vertex of the grass blade + mat4 viewproj = camera.proj*camera.view; + vec3 v0 = gl_in[0].gl_Position.xyz; + float w = v2tese.w;//width + vec3 t1 = bitantese.xyz;//bitan + vec3 a = v0 + v*(v1tese.xyz - v0); + vec3 b = v1tese.xyz + v*(v2tese.xyz - v1tese.xyz); + vec3 c = a + v*(b - a); + vec3 c0 = c - 0.5f*w*t1; + vec3 c1 = c + 0.5f*w*t1; + vec3 t0 = normalize(b-a);//tan + nortese = normalize(cross(t0,t1)); + + float t = 0.5 + (u-0.5)*(1.0-max(v-0.5,0)/(1.0-0.5)); + vec4 interppos = vec4((1.0 - t)*c0 + t*c1, 1.0); + gl_Position = viewproj*interppos; } diff --git a/src/shaders/grass.vert b/src/shaders/grass.vert index db9dfe9..e9b6f98 100644 --- a/src/shaders/grass.vert +++ b/src/shaders/grass.vert @@ -7,6 +7,18 @@ layout(set = 1, binding = 0) uniform ModelBufferObject { }; // TODO: Declare vertex shader inputs and outputs +//ins +layout(location = 0) in vec4 v0; +layout(location = 1) in vec4 v1; +layout(location = 2) in vec4 v2; +layout(location = 3) in vec4 up; + +//outs +layout(location = 0) out vec4 v1tesc; +layout(location = 1) out vec4 v2tesc; +layout(location = 2) out vec3 uptesc; +layout(location = 3) out vec3 bitantesc; + out gl_PerVertex { vec4 gl_Position; @@ -14,4 +26,17 @@ out gl_PerVertex { void main() { // TODO: Write gl_Position and any other shader outputs + vec4 v0worldpos = model * vec4(v0.xyz, 1.0); + vec4 v1worldpos = model * vec4(v1.xyz, 1.0); + vec4 v2worldpos = model * vec4(v2.xyz, 1.0); + vec4 upworld = model * vec4(up.xyz, 0.0); + + v1tesc = vec4(v1worldpos.xyz, v1.w); + v2tesc = vec4(v2worldpos.xyz, v2.w); + uptesc = normalize(upworld.xyz); + float angle = v0.w; + vec3 tandir = normalize( vec3(sin(angle), 0, cos(angle)) ); + bitantesc = normalize(cross(uptesc.xyz,tandir)); + + gl_Position = v0worldpos; }