Code cleanup, fixed HLSL shaders

This commit is contained in:
Sascha Willems 2024-01-14 10:24:55 +01:00
parent 6444281e34
commit 7ad9ee1dc3
16 changed files with 274 additions and 408 deletions

View file

@ -1,6 +1,9 @@
/* /*
* Vulkan Example - Dynamic terrain tessellation * Vulkan Example - Dynamic terrain tessellation
* *
* This samples draw a terrain from a heightmap texture and uses tessellation to add in details based on camera distance
* The height level is generated in the vertex shader by reading from the heightmap image
*
* Copyright (C) 2016-2023 by Sascha Willems - www.saschawillems.de * Copyright (C) 2016-2023 by Sascha Willems - www.saschawillems.de
* *
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
@ -21,13 +24,13 @@ public:
// Holds the buffers for rendering the tessellated terrain // Holds the buffers for rendering the tessellated terrain
struct { struct {
struct Vertices { struct Vertices {
VkBuffer buffer; VkBuffer buffer{ VK_NULL_HANDLE };
VkDeviceMemory memory; VkDeviceMemory memory{ VK_NULL_HANDLE };
} vertices; } vertices;
struct Indices { struct Indices {
int count; int count;
VkBuffer buffer; VkBuffer buffer{ VK_NULL_HANDLE };
VkDeviceMemory memory; VkDeviceMemory memory{ VK_NULL_HANDLE };
} indices; } indices;
} terrain; } terrain;
@ -47,7 +50,7 @@ public:
} uniformBuffers; } uniformBuffers;
// Shared values for tessellation control and evaluation stages // Shared values for tessellation control and evaluation stages
struct { struct UniformDataTessellation {
glm::mat4 projection; glm::mat4 projection;
glm::mat4 modelview; glm::mat4 modelview;
glm::vec4 lightPos = glm::vec4(-48.0f, -40.0f, 46.0f, 0.0f); glm::vec4 lightPos = glm::vec4(-48.0f, -40.0f, 46.0f, 0.0f);
@ -57,40 +60,40 @@ public:
glm::vec2 viewportDim; glm::vec2 viewportDim;
// Desired size of tessellated quad patch edge // Desired size of tessellated quad patch edge
float tessellatedEdgeSize = 20.0f; float tessellatedEdgeSize = 20.0f;
} uboTess; } uniformDataTessellation;
// Skysphere vertex shader stage // Skysphere vertex shader stage
struct { struct UniformDataVertex {
glm::mat4 mvp; glm::mat4 mvp;
} uboVS; } uniformDataVertex;
struct Pipelines { struct Pipelines {
VkPipeline terrain; VkPipeline terrain{ VK_NULL_HANDLE };
VkPipeline wireframe = VK_NULL_HANDLE; VkPipeline wireframe{ VK_NULL_HANDLE };
VkPipeline skysphere; VkPipeline skysphere{ VK_NULL_HANDLE };
} pipelines; } pipelines;
struct { struct {
VkDescriptorSetLayout terrain; VkDescriptorSetLayout terrain{ VK_NULL_HANDLE };
VkDescriptorSetLayout skysphere; VkDescriptorSetLayout skysphere{ VK_NULL_HANDLE };
} descriptorSetLayouts; } descriptorSetLayouts;
struct { struct {
VkPipelineLayout terrain; VkPipelineLayout terrain{ VK_NULL_HANDLE };
VkPipelineLayout skysphere; VkPipelineLayout skysphere{ VK_NULL_HANDLE };
} pipelineLayouts; } pipelineLayouts;
struct { struct {
VkDescriptorSet terrain; VkDescriptorSet terrain{ VK_NULL_HANDLE };
VkDescriptorSet skysphere; VkDescriptorSet skysphere{ VK_NULL_HANDLE };
} descriptorSets; } descriptorSets;
// Pipeline statistics // If supported, this sample will gather pipeline statistics to show e.g. tessellation related information
struct { struct {
VkBuffer buffer; VkBuffer buffer{ VK_NULL_HANDLE };
VkDeviceMemory memory; VkDeviceMemory memory{ VK_NULL_HANDLE };
} queryResult; } queryResult;
VkQueryPool queryPool = VK_NULL_HANDLE; VkQueryPool queryPool{ VK_NULL_HANDLE };
uint64_t pipelineStats[2] = { 0 }; uint64_t pipelineStats[2] = { 0 };
// View frustum passed to tessellation control shader for culling // View frustum passed to tessellation control shader for culling
@ -108,36 +111,36 @@ public:
~VulkanExample() ~VulkanExample()
{ {
// Clean up used Vulkan resources if (device) {
// Note : Inherited destructor cleans up resources stored in base class vkDestroyPipeline(device, pipelines.terrain, nullptr);
vkDestroyPipeline(device, pipelines.terrain, nullptr); if (pipelines.wireframe != VK_NULL_HANDLE) {
if (pipelines.wireframe != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipelines.wireframe, nullptr);
vkDestroyPipeline(device, pipelines.wireframe, nullptr); }
} vkDestroyPipeline(device, pipelines.skysphere, nullptr);
vkDestroyPipeline(device, pipelines.skysphere, nullptr);
vkDestroyPipelineLayout(device, pipelineLayouts.skysphere, nullptr); vkDestroyPipelineLayout(device, pipelineLayouts.skysphere, nullptr);
vkDestroyPipelineLayout(device, pipelineLayouts.terrain, nullptr); vkDestroyPipelineLayout(device, pipelineLayouts.terrain, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayouts.terrain, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayouts.terrain, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayouts.skysphere, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayouts.skysphere, nullptr);
uniformBuffers.skysphereVertex.destroy(); uniformBuffers.skysphereVertex.destroy();
uniformBuffers.terrainTessellation.destroy(); uniformBuffers.terrainTessellation.destroy();
textures.heightMap.destroy(); textures.heightMap.destroy();
textures.skySphere.destroy(); textures.skySphere.destroy();
textures.terrainArray.destroy(); textures.terrainArray.destroy();
vkDestroyBuffer(device, terrain.vertices.buffer, nullptr); vkDestroyBuffer(device, terrain.vertices.buffer, nullptr);
vkFreeMemory(device, terrain.vertices.memory, nullptr); vkFreeMemory(device, terrain.vertices.memory, nullptr);
vkDestroyBuffer(device, terrain.indices.buffer, nullptr); vkDestroyBuffer(device, terrain.indices.buffer, nullptr);
vkFreeMemory(device, terrain.indices.memory, nullptr); vkFreeMemory(device, terrain.indices.memory, nullptr);
if (queryPool != VK_NULL_HANDLE) { if (queryPool != VK_NULL_HANDLE) {
vkDestroyQueryPool(device, queryPool, nullptr); vkDestroyQueryPool(device, queryPool, nullptr);
vkDestroyBuffer(device, queryResult.buffer, nullptr); vkDestroyBuffer(device, queryResult.buffer, nullptr);
vkFreeMemory(device, queryResult.memory, nullptr); vkFreeMemory(device, queryResult.memory, nullptr);
}
} }
} }
@ -147,15 +150,14 @@ public:
// Tessellation shader support is required for this example // Tessellation shader support is required for this example
if (deviceFeatures.tessellationShader) { if (deviceFeatures.tessellationShader) {
enabledFeatures.tessellationShader = VK_TRUE; enabledFeatures.tessellationShader = VK_TRUE;
} } else {
else {
vks::tools::exitFatal("Selected GPU does not support tessellation shaders!", VK_ERROR_FEATURE_NOT_PRESENT); vks::tools::exitFatal("Selected GPU does not support tessellation shaders!", VK_ERROR_FEATURE_NOT_PRESENT);
} }
// Fill mode non solid is required for wireframe display // Fill mode non solid is required for wireframe display
if (deviceFeatures.fillModeNonSolid) { if (deviceFeatures.fillModeNonSolid) {
enabledFeatures.fillModeNonSolid = VK_TRUE; enabledFeatures.fillModeNonSolid = VK_TRUE;
}; };
// Pipeline statistics // Enable pipeline statistics if supported (to display them in the UI)
if (deviceFeatures.pipelineStatisticsQuery) { if (deviceFeatures.pipelineStatisticsQuery) {
enabledFeatures.pipelineStatisticsQuery = VK_TRUE; enabledFeatures.pipelineStatisticsQuery = VK_TRUE;
}; };
@ -163,19 +165,9 @@ public:
if (deviceFeatures.samplerAnisotropy) { if (deviceFeatures.samplerAnisotropy) {
enabledFeatures.samplerAnisotropy = VK_TRUE; enabledFeatures.samplerAnisotropy = VK_TRUE;
} }
// Enable texture compression
if (deviceFeatures.textureCompressionBC) {
enabledFeatures.textureCompressionBC = VK_TRUE;
}
else if (deviceFeatures.textureCompressionASTC_LDR) {
enabledFeatures.textureCompressionASTC_LDR = VK_TRUE;
}
else if (deviceFeatures.textureCompressionETC2) {
enabledFeatures.textureCompressionETC2 = VK_TRUE;
}
} }
// Setup pool and buffer for storing pipeline statistics results // Setup a pool and a buffer for storing pipeline statistics results
void setupQueryResultBuffer() void setupQueryResultBuffer()
{ {
uint32_t bufSize = 2 * sizeof(uint64_t); uint32_t bufSize = 2 * sizeof(uint64_t);
@ -265,8 +257,7 @@ public:
samplerInfo.minLod = 0.0f; samplerInfo.minLod = 0.0f;
samplerInfo.maxLod = (float)textures.terrainArray.mipLevels; samplerInfo.maxLod = (float)textures.terrainArray.mipLevels;
samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
if (deviceFeatures.samplerAnisotropy) if (deviceFeatures.samplerAnisotropy) {
{
samplerInfo.maxAnisotropy = 4.0f; samplerInfo.maxAnisotropy = 4.0f;
samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.anisotropyEnable = VK_TRUE;
} }
@ -342,107 +333,78 @@ public:
} }
} }
// Encapsulate height map data for easy sampling // Generate a terrain quad patch with normals based on heightmap data
struct HeightMap
{
private:
uint16_t *heightdata;
uint32_t dim;
uint32_t scale;
public:
#if defined(__ANDROID__)
HeightMap(std::string filename, uint32_t patchsize, AAssetManager* assetManager)
#else
HeightMap(std::string filename, uint32_t patchsize)
#endif
{
ktxResult result;
ktxTexture* ktxTexture;
#if defined(__ANDROID__)
AAsset* asset = AAssetManager_open(androidApp->activity->assetManager, filename.c_str(), AASSET_MODE_STREAMING);
assert(asset);
size_t size = AAsset_getLength(asset);
assert(size > 0);
ktx_uint8_t* textureData = new ktx_uint8_t[size];
AAsset_read(asset, textureData, size);
AAsset_close(asset);
result = ktxTexture_CreateFromMemory(textureData, size, KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &ktxTexture);
delete[] textureData;
#else
result = ktxTexture_CreateFromNamedFile(filename.c_str(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &ktxTexture);
#endif
assert(result == KTX_SUCCESS);
ktx_size_t ktxSize = ktxTexture_GetImageSize(ktxTexture, 0);
ktx_uint8_t* ktxImage = ktxTexture_GetData(ktxTexture);
dim = ktxTexture->baseWidth;
heightdata = new uint16_t[dim * dim];
memcpy(heightdata, ktxImage, ktxSize);
this->scale = dim / patchsize;
ktxTexture_Destroy(ktxTexture);
};
~HeightMap()
{
delete[] heightdata;
}
float getHeight(uint32_t x, uint32_t y)
{
glm::ivec2 rpos = glm::ivec2(x, y) * glm::ivec2(scale);
rpos.x = std::max(0, std::min(rpos.x, (int)dim-1));
rpos.y = std::max(0, std::min(rpos.y, (int)dim-1));
rpos /= glm::ivec2(scale);
return *(heightdata + (rpos.x + rpos.y * dim) * scale) / 65535.0f;
}
};
// Generate a terrain quad patch for feeding to the tessellation control shader
void generateTerrain() void generateTerrain()
{ {
#define PATCH_SIZE 64 const uint32_t patchSize{ 64 };
#define UV_SCALE 1.0f const float uvScale{ 1.0f };
const uint32_t vertexCount = PATCH_SIZE * PATCH_SIZE; uint16_t* heightdata;
uint32_t dim;
uint32_t scale;
ktxResult result;
ktxTexture* ktxTexture;
// We load the heightmap from an un-compressed ktx image with one channel that contains heights
std::string filename = getAssetPath() + "textures/terrain_heightmap_r16.ktx";
#if defined(__ANDROID__)
// On Android we need to load the file using the asset manager
AAsset* asset = AAssetManager_open(androidApp->activity->assetManager, filename.c_str(), AASSET_MODE_STREAMING);
assert(asset);
size_t size = AAsset_getLength(asset);
assert(size > 0);
ktx_uint8_t* textureData = new ktx_uint8_t[size];
AAsset_read(asset, textureData, size);
AAsset_close(asset);
result = ktxTexture_CreateFromMemory(textureData, size, KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &ktxTexture);
delete[] textureData;
#else
result = ktxTexture_CreateFromNamedFile(filename.c_str(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &ktxTexture);
#endif
assert(result == KTX_SUCCESS);
ktx_size_t ktxSize = ktxTexture_GetImageSize(ktxTexture, 0);
ktx_uint8_t* ktxImage = ktxTexture_GetData(ktxTexture);
dim = ktxTexture->baseWidth;
heightdata = new uint16_t[dim * dim];
memcpy(heightdata, ktxImage, ktxSize);
scale = dim / patchSize;
ktxTexture_Destroy(ktxTexture);
const uint32_t vertexCount = patchSize * patchSize;
// We use the Vertex definition from the glTF model loader, so we can re-use the vertex input state // We use the Vertex definition from the glTF model loader, so we can re-use the vertex input state
vkglTF::Vertex *vertices = new vkglTF::Vertex[vertexCount]; vkglTF::Vertex *vertices = new vkglTF::Vertex[vertexCount];
const float wx = 2.0f; const float wx = 2.0f;
const float wy = 2.0f; const float wy = 2.0f;
for (auto x = 0; x < PATCH_SIZE; x++) // Generate a two-dimensional vertex patch
{ for (auto x = 0; x < patchSize; x++) {
for (auto y = 0; y < PATCH_SIZE; y++) for (auto y = 0; y < patchSize; y++) {
{ uint32_t index = (x + y * patchSize);
uint32_t index = (x + y * PATCH_SIZE); vertices[index].pos[0] = x * wx + wx / 2.0f - (float)patchSize * wx / 2.0f;
vertices[index].pos[0] = x * wx + wx / 2.0f - (float)PATCH_SIZE * wx / 2.0f;
vertices[index].pos[1] = 0.0f; vertices[index].pos[1] = 0.0f;
vertices[index].pos[2] = y * wy + wy / 2.0f - (float)PATCH_SIZE * wy / 2.0f; vertices[index].pos[2] = y * wy + wy / 2.0f - (float)patchSize * wy / 2.0f;
vertices[index].uv = glm::vec2((float)x / (PATCH_SIZE - 1), (float)y / (PATCH_SIZE - 1)) * UV_SCALE; vertices[index].uv = glm::vec2((float)x / (patchSize - 1), (float)y / (patchSize - 1)) * uvScale;
} }
} }
// Calculate normals from height map using a sobel filter // Calculate normals from the height map using a sobel filter
#if defined(__ANDROID__) for (auto x = 0; x < patchSize; x++) {
HeightMap heightMap(getAssetPath() + "textures/terrain_heightmap_r16.ktx", PATCH_SIZE, androidApp->activity->assetManager); for (auto y = 0; y < patchSize; y++) {
#else // We get
HeightMap heightMap(getAssetPath() + "textures/terrain_heightmap_r16.ktx", PATCH_SIZE);
#endif
for (auto x = 0; x < PATCH_SIZE; x++)
{
for (auto y = 0; y < PATCH_SIZE; y++)
{
// Get height samples centered around current position
float heights[3][3]; float heights[3][3];
for (auto hx = -1; hx <= 1; hx++) for (auto sx = -1; sx <= 1; sx++) {
{ for (auto sy = -1; sy <= 1; sy++) {
for (auto hy = -1; hy <= 1; hy++) // Get height at sampled position from heightmap
{ glm::ivec2 rpos = glm::ivec2(x + sx, y + sy) * glm::ivec2(scale);
heights[hx+1][hy+1] = heightMap.getHeight(x + hx, y + hy); rpos.x = std::max(0, std::min(rpos.x, (int)dim - 1));
rpos.y = std::max(0, std::min(rpos.y, (int)dim - 1));
rpos /= glm::ivec2(scale);
heights[sx + 1][sy + 1] = *(heightdata + (rpos.x + rpos.y * dim) * scale) / 65535.0f;
} }
} }
// Calculate the normal
glm::vec3 normal; glm::vec3 normal;
// Gx sobel filter // Gx sobel filter
normal.x = heights[0][0] - heights[2][0] + 2.0f * heights[0][1] - 2.0f * heights[2][1] + heights[0][2] - heights[2][2]; normal.x = heights[0][0] - heights[2][0] + 2.0f * heights[0][1] - 2.0f * heights[2][1] + heights[0][2] - heights[2][2];
@ -452,12 +414,14 @@ public:
// The first value controls the bump strength // The first value controls the bump strength
normal.y = 0.25f * sqrt( 1.0f - normal.x * normal.x - normal.z * normal.z); normal.y = 0.25f * sqrt( 1.0f - normal.x * normal.x - normal.z * normal.z);
vertices[x + y * PATCH_SIZE].normal = glm::normalize(normal * glm::vec3(2.0f, 1.0f, 2.0f)); vertices[x + y * patchSize].normal = glm::normalize(normal * glm::vec3(2.0f, 1.0f, 2.0f));
} }
} }
// Indices delete[] heightdata;
const uint32_t w = (PATCH_SIZE - 1);
// Generate indices
const uint32_t w = (patchSize - 1);
const uint32_t indexCount = w * w * 4; const uint32_t indexCount = w * w * 4;
uint32_t *indices = new uint32_t[indexCount]; uint32_t *indices = new uint32_t[indexCount];
for (auto x = 0; x < w; x++) for (auto x = 0; x < w; x++)
@ -465,14 +429,16 @@ public:
for (auto y = 0; y < w; y++) for (auto y = 0; y < w; y++)
{ {
uint32_t index = (x + y * w) * 4; uint32_t index = (x + y * w) * 4;
indices[index] = (x + y * PATCH_SIZE); indices[index] = (x + y * patchSize);
indices[index + 1] = indices[index] + PATCH_SIZE; indices[index + 1] = indices[index] + patchSize;
indices[index + 2] = indices[index + 1] + 1; indices[index + 2] = indices[index + 1] + 1;
indices[index + 3] = indices[index] + 1; indices[index + 3] = indices[index] + 1;
} }
} }
terrain.indices.count = indexCount; terrain.indices.count = indexCount;
// Upload vertices and indices to device
uint32_t vertexBufferSize = vertexCount * sizeof(vkglTF::Vertex); uint32_t vertexBufferSize = vertexCount * sizeof(vkglTF::Vertex);
uint32_t indexBufferSize = indexCount * sizeof(uint32_t); uint32_t indexBufferSize = indexCount * sizeof(uint32_t);
@ -481,7 +447,7 @@ public:
VkDeviceMemory memory; VkDeviceMemory memory;
} vertexStaging, indexStaging; } vertexStaging, indexStaging;
// Create staging buffers // Stage the terrain vertex data to the device
VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
@ -545,77 +511,43 @@ public:
delete[] indices; delete[] indices;
} }
void setupDescriptorPool() void setupDescriptors()
{ {
std::vector<VkDescriptorPoolSize> poolSizes = // Pool
{ std::vector<VkDescriptorPoolSize> poolSizes = {
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3), vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 3),
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3) vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 3)
}; };
VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, 2);
VkDescriptorPoolCreateInfo descriptorPoolInfo =
vks::initializers::descriptorPoolCreateInfo(
static_cast<uint32_t>(poolSizes.size()),
poolSizes.data(),
2);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool));
}
void setupDescriptorSetLayouts() // Layouts
{
VkDescriptorSetLayoutCreateInfo descriptorLayout; VkDescriptorSetLayoutCreateInfo descriptorLayout;
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo;
std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings; std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings;
// Terrain // Terrain
setLayoutBindings = setLayoutBindings = {
{
// Binding 0 : Shared Tessellation shader ubo // Binding 0 : Shared Tessellation shader ubo
vks::initializers::descriptorSetLayoutBinding( vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, 0),
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT,
0),
// Binding 1 : Height map // Binding 1 : Height map
vks::initializers::descriptorSetLayoutBinding( vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 1),
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, // Binding 2 : Terrain texture array layers
VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 2),
1),
// Binding 3 : Terrain texture array layers
vks::initializers::descriptorSetLayoutBinding(
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT,
2),
}; };
descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings.data(), static_cast<uint32_t>(setLayoutBindings.size())); descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings.data(), static_cast<uint32_t>(setLayoutBindings.size()));
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayouts.terrain)); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayouts.terrain));
pipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayouts.terrain, 1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayouts.terrain));
// Skysphere // Skysphere
setLayoutBindings = setLayoutBindings = {
{
// Binding 0 : Vertex shader ubo // Binding 0 : Vertex shader ubo
vks::initializers::descriptorSetLayoutBinding( vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_VERTEX_BIT, 0),
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
VK_SHADER_STAGE_VERTEX_BIT,
0),
// Binding 1 : Color map // Binding 1 : Color map
vks::initializers::descriptorSetLayoutBinding( vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, 1),
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
VK_SHADER_STAGE_FRAGMENT_BIT,
1),
}; };
descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings.data(), static_cast<uint32_t>(setLayoutBindings.size())); descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings.data(), static_cast<uint32_t>(setLayoutBindings.size()));
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayouts.skysphere));
pipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayouts.skysphere, 1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayouts.skysphere));
}
void setupDescriptorSets() VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayouts.skysphere));
{ // Sets
VkDescriptorSetAllocateInfo allocInfo; VkDescriptorSetAllocateInfo allocInfo;
std::vector<VkWriteDescriptorSet> writeDescriptorSets; std::vector<VkWriteDescriptorSet> writeDescriptorSets;
@ -623,53 +555,40 @@ public:
allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.terrain, 1); allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.terrain, 1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.terrain)); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.terrain));
writeDescriptorSets = writeDescriptorSets = {
{
// Binding 0 : Shared tessellation shader ubo // Binding 0 : Shared tessellation shader ubo
vks::initializers::writeDescriptorSet( vks::initializers::writeDescriptorSet(descriptorSets.terrain, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffers.terrainTessellation.descriptor),
descriptorSets.terrain, // Binding 1 : Height map
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, vks::initializers::writeDescriptorSet(descriptorSets.terrain, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &textures.heightMap.descriptor),
0, // Binding 2 : Terrain texture array layers
&uniformBuffers.terrainTessellation.descriptor), vks::initializers::writeDescriptorSet(descriptorSets.terrain, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, &textures.terrainArray.descriptor),
// Binding 1 : Displacement map
vks::initializers::writeDescriptorSet(
descriptorSets.terrain,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1,
&textures.heightMap.descriptor),
// Binding 2 : Color map (alpha channel)
vks::initializers::writeDescriptorSet(
descriptorSets.terrain,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
2,
&textures.terrainArray.descriptor),
}; };
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL); vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr);
// Skysphere // Skysphere
allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.skysphere, 1); allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayouts.skysphere, 1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.skysphere)); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSets.skysphere));
writeDescriptorSets = {
writeDescriptorSets =
{
// Binding 0 : Vertex shader ubo // Binding 0 : Vertex shader ubo
vks::initializers::writeDescriptorSet( vks::initializers::writeDescriptorSet(descriptorSets.skysphere, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffers.skysphereVertex.descriptor),
descriptorSets.skysphere,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,
0,
&uniformBuffers.skysphereVertex.descriptor),
// Binding 1 : Fragment shader color map // Binding 1 : Fragment shader color map
vks::initializers::writeDescriptorSet( vks::initializers::writeDescriptorSet(descriptorSets.skysphere, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, &textures.skySphere.descriptor),
descriptorSets.skysphere,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
1,
&textures.skySphere.descriptor),
}; };
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL); vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr);
} }
void preparePipelines() void preparePipelines()
{ {
// Layouts
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo;
pipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayouts.terrain, 1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayouts.terrain));
pipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayouts.skysphere, 1);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayouts.skysphere));
// Pipelines
VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0);
VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo(1, &blendAttachmentState);
@ -703,7 +622,7 @@ public:
pipelineCI.pVertexInputState = vkglTF::Vertex::getPipelineVertexInputState({ vkglTF::VertexComponent::Position, vkglTF::VertexComponent::Normal, vkglTF::VertexComponent::UV }); pipelineCI.pVertexInputState = vkglTF::Vertex::getPipelineVertexInputState({ vkglTF::VertexComponent::Position, vkglTF::VertexComponent::Normal, vkglTF::VertexComponent::UV });
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.terrain)); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.terrain));
// Terrain wireframe pipeline // Terrain wireframe pipeline (if devie supports it)
if (deviceFeatures.fillModeNonSolid) { if (deviceFeatures.fillModeNonSolid) {
rasterizationState.polygonMode = VK_POLYGON_MODE_LINE; rasterizationState.polygonMode = VK_POLYGON_MODE_LINE;
VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.wireframe)); VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCI, nullptr, &pipelines.wireframe));
@ -729,74 +648,44 @@ public:
void prepareUniformBuffers() void prepareUniformBuffers()
{ {
// Shared tessellation shader stages uniform buffer // Shared tessellation shader stages uniform buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffers.terrainTessellation, sizeof(UniformDataTessellation)));
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBuffers.terrainTessellation,
sizeof(uboTess)));
// Skysphere vertex shader uniform buffer // Skysphere vertex shader uniform buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffers.skysphereVertex, sizeof(UniformDataVertex)));
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBuffers.skysphereVertex,
sizeof(uboVS)));
// Map persistent // Map persistent
VK_CHECK_RESULT(uniformBuffers.terrainTessellation.map()); VK_CHECK_RESULT(uniformBuffers.terrainTessellation.map());
VK_CHECK_RESULT(uniformBuffers.skysphereVertex.map()); VK_CHECK_RESULT(uniformBuffers.skysphereVertex.map());
updateUniformBuffers();
} }
void updateUniformBuffers() void updateUniformBuffers()
{ {
// Tessellation // Tessellation
uniformDataTessellation.projection = camera.matrices.perspective;
uniformDataTessellation.modelview = camera.matrices.view * glm::mat4(1.0f);
uniformDataTessellation.lightPos.y = -0.5f - uniformDataTessellation.displacementFactor; // todo: Not uesed yet
uniformDataTessellation.viewportDim = glm::vec2((float)width, (float)height);
uboTess.projection = camera.matrices.perspective; frustum.update(uniformDataTessellation.projection * uniformDataTessellation.modelview);
uboTess.modelview = camera.matrices.view * glm::mat4(1.0f); memcpy(uniformDataTessellation.frustumPlanes, frustum.planes.data(), sizeof(glm::vec4) * 6);
uboTess.lightPos.y = -0.5f - uboTess.displacementFactor; // todo: Not uesed yet
uboTess.viewportDim = glm::vec2((float)width, (float)height);
frustum.update(uboTess.projection * uboTess.modelview); float savedFactor = uniformDataTessellation.tessellationFactor;
memcpy(uboTess.frustumPlanes, frustum.planes.data(), sizeof(glm::vec4) * 6);
float savedFactor = uboTess.tessellationFactor;
if (!tessellation) if (!tessellation)
{ {
// Setting this to zero sets all tessellation factors to 1.0 in the shader // Setting this to zero sets all tessellation factors to 1.0 in the shader
uboTess.tessellationFactor = 0.0f; uniformDataTessellation.tessellationFactor = 0.0f;
} }
memcpy(uniformBuffers.terrainTessellation.mapped, &uboTess, sizeof(uboTess)); memcpy(uniformBuffers.terrainTessellation.mapped, &uniformDataTessellation, sizeof(UniformDataTessellation));
if (!tessellation) if (!tessellation)
{ {
uboTess.tessellationFactor = savedFactor; uniformDataTessellation.tessellationFactor = savedFactor;
} }
// Skysphere vertex shader // Vertex shader
uboVS.mvp = camera.matrices.perspective * glm::mat4(glm::mat3(camera.matrices.view)); uniformDataVertex.mvp = camera.matrices.perspective * glm::mat4(glm::mat3(camera.matrices.view));
memcpy(uniformBuffers.skysphereVertex.mapped, &uboVS, sizeof(uboVS)); memcpy(uniformBuffers.skysphereVertex.mapped, &uniformDataVertex, sizeof(UniformDataVertex));
}
void draw()
{
VulkanExampleBase::prepareFrame();
// Command buffer to be submitted to the queue
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
// Submit to queue
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
if (deviceFeatures.pipelineStatisticsQuery) {
// Read query results for displaying in next frame
getQueryResults();
}
VulkanExampleBase::submitFrame();
} }
void prepare() void prepare()
@ -808,27 +697,31 @@ public:
setupQueryResultBuffer(); setupQueryResultBuffer();
} }
prepareUniformBuffers(); prepareUniformBuffers();
setupDescriptorSetLayouts(); setupDescriptors();
preparePipelines(); preparePipelines();
setupDescriptorPool();
setupDescriptorSets();
buildCommandBuffers(); buildCommandBuffers();
prepared = true; prepared = true;
} }
void draw()
{
VulkanExampleBase::prepareFrame();
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
// Read query results for displaying in next frame (if the device supports pipeline statistics)
if (deviceFeatures.pipelineStatisticsQuery) {
getQueryResults();
}
VulkanExampleBase::submitFrame();
}
virtual void render() virtual void render()
{ {
if (!prepared) if (!prepared)
return; return;
draw();
if (camera.updated) {
updateUniformBuffers();
}
}
virtual void viewChanged()
{
updateUniformBuffers(); updateUniformBuffers();
draw();
} }
virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay) virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay)
@ -838,7 +731,7 @@ public:
if (overlay->checkBox("Tessellation", &tessellation)) { if (overlay->checkBox("Tessellation", &tessellation)) {
updateUniformBuffers(); updateUniformBuffers();
} }
if (overlay->inputFloat("Factor", &uboTess.tessellationFactor, 0.05f, 2)) { if (overlay->inputFloat("Factor", &uniformDataTessellation.tessellationFactor, 0.05f, 2)) {
updateUniformBuffers(); updateUniformBuffers();
} }
if (deviceFeatures.fillModeNonSolid) { if (deviceFeatures.fillModeNonSolid) {

View file

@ -20,30 +20,25 @@ public:
vkglTF::Model model; vkglTF::Model model;
struct { // One uniform data block is used by both tessellation shader stages
vks::Buffer tessControl, tessEval; struct UniformData {
} uniformBuffers;
struct UBOTessControl {
float tessLevel = 3.0f;
} uboTessControl;
struct UBOTessEval {
glm::mat4 projection; glm::mat4 projection;
glm::mat4 modelView; glm::mat4 modelView;
float tessAlpha = 1.0f; float tessAlpha = 1.0f;
} uboTessEval; float tessLevel = 3.0f;
} uniformData;
vks::Buffer uniformBuffer;
struct Pipelines { struct Pipelines {
VkPipeline solid; VkPipeline solid{ VK_NULL_HANDLE };
VkPipeline wire = VK_NULL_HANDLE; VkPipeline wire{ VK_NULL_HANDLE };
VkPipeline solidPassThrough; VkPipeline solidPassThrough{ VK_NULL_HANDLE };
VkPipeline wirePassThrough = VK_NULL_HANDLE; VkPipeline wirePassThrough{ VK_NULL_HANDLE };
} pipelines; } pipelines;
VkPipelineLayout pipelineLayout; VkPipelineLayout pipelineLayout{ VK_NULL_HANDLE };
VkDescriptorSet descriptorSet; VkDescriptorSet descriptorSet{ VK_NULL_HANDLE };
VkDescriptorSetLayout descriptorSetLayout; VkDescriptorSetLayout descriptorSetLayout{ VK_NULL_HANDLE };
VulkanExample() : VulkanExampleBase() VulkanExample() : VulkanExampleBase()
{ {
@ -56,28 +51,29 @@ public:
~VulkanExample() ~VulkanExample()
{ {
// Clean up used Vulkan resources if (device) {
// Note : Inherited destructor cleans up resources stored in base class // Clean up used Vulkan resources
vkDestroyPipeline(device, pipelines.solid, nullptr); // Note : Inherited destructor cleans up resources stored in base class
if (pipelines.wire != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipelines.solid, nullptr);
vkDestroyPipeline(device, pipelines.wire, nullptr); if (pipelines.wire != VK_NULL_HANDLE) {
}; vkDestroyPipeline(device, pipelines.wire, nullptr);
vkDestroyPipeline(device, pipelines.solidPassThrough, nullptr); };
if (pipelines.wirePassThrough != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipelines.solidPassThrough, nullptr);
vkDestroyPipeline(device, pipelines.wirePassThrough, nullptr); if (pipelines.wirePassThrough != VK_NULL_HANDLE) {
}; vkDestroyPipeline(device, pipelines.wirePassThrough, nullptr);
};
vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
uniformBuffers.tessControl.destroy(); uniformBuffer.destroy();
uniformBuffers.tessEval.destroy(); }
} }
// Enable physical device features required for this example // Enable physical device features required for this example
virtual void getEnabledFeatures() virtual void getEnabledFeatures()
{ {
// Example uses tessellation shaders // Example requires tessellation shaders
if (deviceFeatures.tessellationShader) { if (deviceFeatures.tessellationShader) {
enabledFeatures.tessellationShader = VK_TRUE; enabledFeatures.tessellationShader = VK_TRUE;
} }
@ -156,26 +152,35 @@ public:
model.loadFromFile(getAssetPath() + "models/deer.gltf", vulkanDevice, queue, vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::FlipY); model.loadFromFile(getAssetPath() + "models/deer.gltf", vulkanDevice, queue, vkglTF::FileLoadingFlags::PreTransformVertices | vkglTF::FileLoadingFlags::FlipY);
} }
void setupDescriptorPool() void setupDescriptors()
{ {
// Pool
const std::vector<VkDescriptorPoolSize> poolSizes = { const std::vector<VkDescriptorPoolSize> poolSizes = {
vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2),
}; };
VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, 1); VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo(poolSizes, 1);
VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool));
}
void setupDescriptorSetLayout() // Layout
{
const std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { const std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = {
// Binding 0 : Tessellation control shader ubo // Binding 0 : Tessellation shader ubo
vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, 0), vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, 0),
// Binding 1 : Tessellation evaluation shader ubo
vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, 1),
}; };
VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings);
VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout));
// Sets
VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet));
std::vector<VkWriteDescriptorSet> writeDescriptorSets = {
// Binding 0 : Tessellation shader ubo
vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffer.descriptor),
};
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr);
}
void preparePipelines()
{
// Layout uses set 0 for passing tessellation shader ubos and set 1 for fragment shader images (taken from glTF model) // Layout uses set 0 for passing tessellation shader ubos and set 1 for fragment shader images (taken from glTF model)
const std::vector<VkDescriptorSetLayout> setLayouts = { const std::vector<VkDescriptorSetLayout> setLayouts = {
descriptorSetLayout, descriptorSetLayout,
@ -183,23 +188,8 @@ public:
}; };
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(setLayouts.data(), 2); VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(setLayouts.data(), 2);
VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout)); VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, nullptr, &pipelineLayout));
}
void setupDescriptorSet() // Pipelines
{
VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1);
VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet));
std::vector<VkWriteDescriptorSet> writeDescriptorSets = {
// Binding 0 : Tessellation control shader ubo
vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffers.tessControl.descriptor),
// Binding 1 : Tessellation evaluation shader ubo
vks::initializers::writeDescriptorSet(descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &uniformBuffers.tessEval.descriptor),
};
vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, nullptr);
}
void preparePipelines()
{
VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, 0, VK_FALSE); VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo(VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, 0, VK_FALSE);
VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo(VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0);
VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE);
@ -260,45 +250,19 @@ public:
void prepareUniformBuffers() void prepareUniformBuffers()
{ {
// Tessellation evaluation shader uniform buffer // Tessellation evaluation shader uniform buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_CHECK_RESULT(vulkanDevice->createBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffer, sizeof(UniformData)));
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBuffers.tessEval,
sizeof(uboTessEval)));
// Tessellation control shader uniform buffer
VK_CHECK_RESULT(vulkanDevice->createBuffer(
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
&uniformBuffers.tessControl,
sizeof(uboTessControl)));
// Map persistent // Map persistent
VK_CHECK_RESULT(uniformBuffers.tessControl.map()); VK_CHECK_RESULT(uniformBuffer.map());
VK_CHECK_RESULT(uniformBuffers.tessEval.map());
updateUniformBuffers();
} }
void updateUniformBuffers() void updateUniformBuffers()
{ {
uboTessEval.projection = camera.matrices.perspective; // Adjust camera perspective if split screen is enabled
uboTessEval.modelView = camera.matrices.view; camera.setPerspective(45.0f, (float)(width * ((splitScreen) ? 0.5f : 1.0f)) / (float)height, 0.1f, 256.0f);
uniformData.projection = camera.matrices.perspective;
uniformData.modelView = camera.matrices.view;
// Tessellation evaluation uniform block // Tessellation evaluation uniform block
memcpy(uniformBuffers.tessEval.mapped, &uboTessEval, sizeof(uboTessEval)); memcpy(uniformBuffer.mapped, &uniformData, sizeof(UniformData));
// Tessellation control uniform block
memcpy(uniformBuffers.tessControl.mapped, &uboTessControl, sizeof(uboTessControl));
}
void draw()
{
VulkanExampleBase::prepareFrame();
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
} }
void prepare() void prepare()
@ -306,34 +270,33 @@ public:
VulkanExampleBase::prepare(); VulkanExampleBase::prepare();
loadAssets(); loadAssets();
prepareUniformBuffers(); prepareUniformBuffers();
setupDescriptorSetLayout(); setupDescriptors();
preparePipelines(); preparePipelines();
setupDescriptorPool();
setupDescriptorSet();
buildCommandBuffers(); buildCommandBuffers();
prepared = true; prepared = true;
} }
void draw()
{
VulkanExampleBase::prepareFrame();
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer];
VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE));
VulkanExampleBase::submitFrame();
}
virtual void render() virtual void render()
{ {
if (!prepared) if (!prepared)
return; return;
draw();
if (camera.updated) {
updateUniformBuffers();
}
}
virtual void viewChanged()
{
camera.setPerspective(45.0f, (float)(width * ((splitScreen) ? 0.5f : 1.0f)) / (float)height, 0.1f, 256.0f);
updateUniformBuffers(); updateUniformBuffers();
draw();
} }
virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay) virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay)
{ {
if (overlay->header("Settings")) { if (overlay->header("Settings")) {
if (overlay->inputFloat("Tessellation level", &uboTessControl.tessLevel, 0.25f, 2)) { if (overlay->inputFloat("Tessellation level", &uniformData.tessLevel, 0.25f, 2)) {
updateUniformBuffers(); updateUniformBuffers();
} }
if (deviceFeatures.fillModeNonSolid) { if (deviceFeatures.fillModeNonSolid) {

View file

@ -2,11 +2,12 @@
layout (triangles, fractional_odd_spacing, cw) in; layout (triangles, fractional_odd_spacing, cw) in;
layout (binding = 1) uniform UBO layout (binding = 0) uniform UBO
{ {
mat4 projection; mat4 projection;
mat4 model; mat4 model;
float tessAlpha; float tessAlpha;
float tessLevel;
} ubo; } ubo;
layout (location = 0) in vec3 inNormal[]; layout (location = 0) in vec3 inNormal[];

View file

@ -18,7 +18,10 @@ struct PnPatch
// tessellation levels // tessellation levels
layout (binding = 0) uniform UBO layout (binding = 0) uniform UBO
{ {
float tessLevel; mat4 projection;
mat4 model;
float tessAlpha;
float tessLevel;
} ubo; } ubo;
layout(vertices=3) out; layout(vertices=3) out;

View file

@ -15,11 +15,12 @@ struct PnPatch
float n101; float n101;
}; };
layout (binding = 1) uniform UBO layout (binding = 0) uniform UBO
{ {
mat4 projection; mat4 projection;
mat4 model; mat4 model;
float tessAlpha; float tessAlpha;
float tessLevel;
} ubo; } ubo;
layout(triangles, fractional_odd_spacing, cw) in; layout(triangles, fractional_odd_spacing, cw) in;

View file

@ -1,7 +1,7 @@
// Copyright 2020 Google LLC // Copyright 2020 Google LLC
Texture2D textureColorMap : register(t2); Texture2D textureColorMap : register(t0, space1);
SamplerState samplerColorMap : register(s2); SamplerState samplerColorMap : register(s0, space1);
struct DSOutput struct DSOutput
{ {

View file

@ -2,12 +2,13 @@
struct UBO struct UBO
{ {
float4x4 projection; float4x4 projection;
float4x4 model; float4x4 model;
float tessAlpha; float tessAlpha;
float tessLevel;
}; };
cbuffer ubo : register(b1) { UBO ubo; } cbuffer ubo : register(b0) { UBO ubo; }
struct HSOutput struct HSOutput
{ {

View file

@ -18,7 +18,10 @@ struct PnPatch
// tessellation levels // tessellation levels
struct UBO struct UBO
{ {
float tessLevel; float4x4 projection;
float4x4 model;
float tessAlpha;
float tessLevel;
}; };
cbuffer ubo : register(b0) { UBO ubo; } cbuffer ubo : register(b0) { UBO ubo; }
@ -83,7 +86,7 @@ ConstantsHSOutput ConstantsHS(InputPatch<VSOutput, 3> patch, uint InvocationID :
[domain("tri")] [domain("tri")]
[partitioning("fractional_odd")] [partitioning("fractional_odd")]
[outputtopology("triangle_ccw")] [outputtopology("triangle_cw")]
[outputcontrolpoints(3)] [outputcontrolpoints(3)]
[patchconstantfunc("ConstantsHS")] [patchconstantfunc("ConstantsHS")]
[maxtessfactor(20.0f)] [maxtessfactor(20.0f)]

View file

@ -20,9 +20,10 @@ struct UBO
float4x4 projection; float4x4 projection;
float4x4 model; float4x4 model;
float tessAlpha; float tessAlpha;
float tessLevel;
}; };
cbuffer ubo : register(b1) { UBO ubo; } cbuffer ubo : register(b0) { UBO ubo; }
struct HSOutput struct HSOutput
{ {