move stuff in common, clang-format, update copyright

This commit is contained in:
Guillaume Meunier
2022-11-13 11:00:04 +01:00
parent 294c4f81ba
commit 4baf2b17eb
62 changed files with 2291 additions and 2846 deletions
-112
View File
@@ -1,112 +0,0 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -8
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
#AlignConsecutiveMacros: true
AlignEscapedNewlines: Right
AlignOperands: true
AlignTrailingComments: true
#AllowAllArgumentsOnNextLine: false
#AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: false
#AllowShortLambdasOnASingleLine: Inline
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: true
BeforeCatch: true
BeforeElse: true
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: AfterColon
BreakInheritanceList: AfterColon
BreakStringLiterals: true
ColumnLimit: 0
#CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 8
ContinuationIndentWidth: 8
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
#ForEachMacros:
# - foreach
# - Q_FOREACH
# - BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
# openxr/openxr_platform.h depends on vulkan/vulkan.h
- Regex: '^<vulkan/.*>$'
Priority: 2
- Regex: '^<openxr/.*>$'
Priority: 3
- Regex: '^<.*>$'
Priority: 1
- Regex: '^".*"$'
Priority: 1
IncludeIsMainRegex: '$'
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth: 8
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: false
Language: Cpp
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Middle
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
#SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 8
UseTab: ForIndentation
+204 -197
View File
@@ -1,21 +1,3 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "scene_renderer.h"
#include "application.h"
#include "spdlog/spdlog.h"
@@ -34,6 +16,7 @@ VkFormat gltf_to_vkformat(int component, int bits, int pixel_type, bool srgb)
case TINYGLTF_COMPONENT_TYPE_SHORT:
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
assert(bits == 32);
break;
@@ -326,7 +309,8 @@ void scene_renderer::reserve(size_t size)
buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
staging_buffer = vk::buffer(device, buffer_info);
staging_memory = vk::device_memory(device, physical_device, staging_buffer, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
staging_memory =
vk::device_memory(device, physical_device, staging_buffer, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
staging_buffer_size = size;
staging_memory.map_memory();
}
@@ -346,10 +330,7 @@ void scene_renderer::load_buffer(VkBuffer b, const void * data, size_t size)
begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
CHECK_VK(vkBeginCommandBuffer(staging_command_buffer, &begin_info));
VkBufferCopy copy_info{
.srcOffset = 0,
.dstOffset = 0,
.size = size};
VkBufferCopy copy_info{.srcOffset = 0, .dstOffset = 0, .size = size};
vkCmdCopyBuffer(staging_command_buffer, staging_buffer, b, 1, &copy_info);
CHECK_VK(vkEndCommandBuffer(staging_command_buffer));
@@ -394,28 +375,29 @@ void scene_renderer::load_image(VkImage i, void * data, VkExtent2D size, VkForma
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = i,
.subresourceRange = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = mipmap_count,
.baseArrayLayer = 0,
.layerCount = 1,
},
.subresourceRange =
{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = mipmap_count,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
vkCmdPipelineBarrier(staging_command_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier);
VkBufferImageCopy copy_info{
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = VkImageSubresourceLayers{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = {0, 0, 0},
.imageExtent = {size.width, size.height, 1}};
VkBufferImageCopy copy_info{.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource =
VkImageSubresourceLayers{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1,
},
.imageOffset = {0, 0, 0},
.imageExtent = {size.width, size.height, 1}};
vkCmdCopyBufferToImage(staging_command_buffer, staging_buffer, i, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &copy_info);
VkOffset3D size_src = {(int32_t)size.width, (int32_t)size.height, 1};
@@ -431,19 +413,21 @@ void scene_renderer::load_image(VkImage i, void * data, VkExtent2D size, VkForma
VkOffset3D size_dst = {std::max(1, size_src.x / 2), std::max(1, size_src.y / 2), 1};
VkImageBlit blit_info{
.srcSubresource = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = mipmap - 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
.srcSubresource =
{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = mipmap - 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
.srcOffsets = {{0, 0, 0}, size_src},
.dstSubresource = {
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = mipmap,
.baseArrayLayer = 0,
.layerCount = 1,
},
.dstSubresource =
{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.mipLevel = mipmap,
.baseArrayLayer = 0,
.layerCount = 1,
},
.dstOffsets = {{0, 0, 0}, size_dst},
};
vkCmdBlitImage(staging_command_buffer, i, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, i, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit_info, VK_FILTER_LINEAR);
@@ -487,16 +471,8 @@ void scene_renderer::load_image(VkImage i, void * data, VkExtent2D size, VkForma
void scene_renderer::cleanup()
{
for (auto & i: shaders)
cleanup_shader(*i);
shaders.clear();
for (auto & i: images)
cleanup_image(*i);
images.clear();
for (auto & i: buffers)
cleanup_buffer(*i);
buffers.clear();
cleanup_output_images();
@@ -578,175 +554,204 @@ void scene_renderer::set_output_images(std::vector<VkImage> output_images_, VkEx
}
}
void scene_renderer::cleanup_shader(shader & s)
void scene_renderer::cleanup_shader(shader * s)
{
for (auto & i: s.descriptor_pools)
for (auto & i: s->descriptor_set_layouts)
vkDestroyDescriptorSetLayout(device, i, nullptr);
for (auto & i: s->descriptor_pools)
vkDestroyDescriptorPool(device, i, nullptr);
for (auto & i: s->pipelines)
vkDestroyPipeline(device, i.second, nullptr);
if (s.pipeline)
vkDestroyPipeline(device, s.pipeline, nullptr);
if (s.pipeline_layout)
vkDestroyPipelineLayout(device, s.pipeline_layout, nullptr);
if (s.descriptor_set_layout)
vkDestroyDescriptorSetLayout(device, s.descriptor_set_layout, nullptr);
s.descriptor_pools.clear();
s.pipeline = VK_NULL_HANDLE;
s.pipeline_layout = VK_NULL_HANDLE;
s.descriptor_set_layout = VK_NULL_HANDLE;
if (s->pipeline_layout)
vkDestroyPipelineLayout(device, s->pipeline_layout, nullptr);
if (s->fragment_shader)
vkDestroyShaderModule(device, s->fragment_shader, nullptr);
if (s->vertex_shader)
vkDestroyShaderModule(device, s->vertex_shader, nullptr);
}
scene_renderer::shader * scene_renderer::create_shader(std::string name, VkPrimitiveTopology topology, std::vector<VkDescriptorSetLayoutBinding> uniform_bindings, std::vector<VkVertexInputBindingDescription> vertex_bindings, std::vector<VkVertexInputAttributeDescription> vertex_attributes)
std::weak_ptr<scene_renderer::shader>
scene_renderer::create_shader(std::string name, std::vector<std::vector<VkDescriptorSetLayoutBinding>> uniform_bindings)
{
auto s = std::make_unique<shader>();
auto s = std::shared_ptr<shader>(new shader, [&](shader * s) { cleanup_shader(s); });
try
// Create graphics pipeline
s->vertex_shader = vk::shader(device, name + ".vert").release();
s->fragment_shader = vk::shader(device, name + ".frag").release();
s->descriptor_set_layouts.reserve(uniform_bindings.size());
for (std::vector<VkDescriptorSetLayoutBinding> & bindings: uniform_bindings)
{
// Create graphics pipeline
s->vertex_shader = vk::shader(device, name + ".vert").release();
s->fragment_shader = vk::shader(device, name + ".frag").release();
VkDescriptorSetLayoutCreateInfo layout_info{
.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
.bindingCount = (uint32_t)uniform_bindings.size(),
.pBindings = uniform_bindings.data(),
.pBindings = bindings.data(),
};
CHECK_VK(vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &s->descriptor_set_layout));
VkPipelineLayoutCreateInfo pipeline_layout_create_info{
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.setLayoutCount = 1,
.pSetLayouts = &s->descriptor_set_layout,
};
CHECK_VK(vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &s->pipeline_layout));
VkPipelineColorBlendAttachmentState pcbas{.colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT};
vk::pipeline::graphics_info pipeline_info{
.shader_stages =
{{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = s->vertex_shader, .pName = "main"},
{.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = s->fragment_shader, .pName = "main"}},
.vertex_input_bindings = vertex_bindings,
.vertex_input_attributes = vertex_attributes,
.InputAssemblyState = {.topology = topology},
.viewports = {VkViewport{.x = 0,
.y = 0,
.width = (float)output_size.width,
.height = (float)output_size.height,
.minDepth = 0,
.maxDepth = 1}},
.scissors = {VkRect2D{
.offset = {0, 0},
.extent = output_size,
}},
.RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1},
.MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT},
.ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas},
.dynamic_states = {},
.renderPass = renderpass,
.subpass = 0,
};
s->pipeline = vk::pipeline(device, pipeline_info, s->pipeline_layout).release();
}
catch (...)
{
cleanup_shader(*s);
throw;
VkDescriptorSetLayout descriptor_set_layout;
CHECK_VK(vkCreateDescriptorSetLayout(device, &layout_info, nullptr, &descriptor_set_layout));
s->descriptor_set_layouts.push_back(descriptor_set_layout);
}
return shaders.emplace_back(std::move(s)).get();
VkPipelineLayoutCreateInfo pipeline_layout_create_info{
.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
.setLayoutCount = (uint32_t)s->descriptor_set_layouts.size(),
.pSetLayouts = s->descriptor_set_layouts.data(),
};
CHECK_VK(vkCreatePipelineLayout(device, &pipeline_layout_create_info, nullptr, &s->pipeline_layout));
return shaders.emplace_back(s);
}
void scene_renderer::cleanup_image(scene_renderer::image & i)
VkPipeline scene_renderer::get_shader_pipeline(std::weak_ptr<shader> weak_shader, VkPrimitiveTopology topology, std::span<VkVertexInputBindingDescription> vertex_bindings, std::span<VkVertexInputAttributeDescription> vertex_attributes)
{
if (i.image)
vkDestroyImage(device, i.image, nullptr);
auto shader = weak_shader.lock();
if (!shader)
return VK_NULL_HANDLE;
if (i.memory)
vkFreeMemory(device, i.memory, nullptr);
for (auto & i: shader->pipelines)
{
if (topology != i.first.topology)
continue;
i.image = VK_NULL_HANDLE;
i.memory = VK_NULL_HANDLE;
if (vertex_bindings.size() != i.first.vertex_bindings.size())
continue;
if (memcmp(vertex_bindings.data(), i.first.vertex_bindings.data(), vertex_bindings.size() * sizeof(VkVertexInputBindingDescription)))
continue;
if (vertex_attributes.size() != i.first.vertex_attributes.size())
continue;
if (memcmp(vertex_attributes.data(), i.first.vertex_attributes.data(), vertex_attributes.size() * sizeof(VkVertexInputAttributeDescription)))
continue;
return i.second;
}
shader::pipeline_info info{
.topology = topology,
.vertex_bindings = {vertex_bindings.begin(), vertex_bindings.end()},
.vertex_attributes = {vertex_attributes.begin(), vertex_attributes.end()},
};
VkPipelineColorBlendAttachmentState pcbas{
.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT};
vk::pipeline::graphics_info pipeline_info{
.shader_stages =
{{.stage = VK_SHADER_STAGE_VERTEX_BIT, .module = shader->vertex_shader, .pName = "main"},
{.stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = shader->fragment_shader, .pName = "main"}},
.vertex_input_bindings = info.vertex_bindings,
.vertex_input_attributes = info.vertex_attributes,
.InputAssemblyState = {.topology = topology},
.viewports = {VkViewport{.x = 0,
.y = 0,
.width = (float)output_size.width,
.height = (float)output_size.height,
.minDepth = 0,
.maxDepth = 1}},
.scissors = {VkRect2D{
.offset = {0, 0},
.extent = output_size,
}},
.RasterizationState = {.polygonMode = VK_POLYGON_MODE_FILL, .lineWidth = 1},
.MultisampleState = {.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT},
.ColorBlendState = {.attachmentCount = 1, .pAttachments = &pcbas},
.dynamic_states = {},
.renderPass = renderpass,
.subpass = 0,
};
vk::pipeline pipeline(device, pipeline_info, shader->pipeline_layout);
return shader->pipelines.emplace_back(info, pipeline.release()).second;
}
scene_renderer::image * scene_renderer::create_image(void * data, VkExtent2D size, VkFormat format)
void scene_renderer::cleanup_image(scene_renderer::image * i)
{
auto i = std::make_unique<image>();
if (i->image_view)
vkDestroyImageView(device, i->image_view, nullptr);
try
{
uint32_t mipmaps = std::log2(std::max(size.width, size.height)) + 1;
if (i->vk_image)
vkDestroyImage(device, i->vk_image, nullptr);
VkImageCreateInfo image_info{
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.flags = 0,
.imageType = VK_IMAGE_TYPE_2D,
.format = format,
.extent = {size.width, size.height, 1},
.mipLevels = mipmaps,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
};
i->image = vk::image(device, image_info).release();
i->memory = vk::device_memory(device, physical_device, i->image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release();
load_image(i->image, data, size, format, mipmaps);
}
catch (...)
{
cleanup_image(*i);
throw;
}
return images.emplace_back(std::move(i)).get();
if (i->memory)
vkFreeMemory(device, i->memory, nullptr);
}
void scene_renderer::cleanup_buffer(scene_renderer::buffer & b)
std::weak_ptr<scene_renderer::image> scene_renderer::create_image(void * data, VkExtent2D size, VkFormat format)
{
if (b.buffer)
vkDestroyBuffer(device, b.buffer, nullptr);
if (b.memory)
vkFreeMemory(device, b.memory, nullptr);
auto i = std::shared_ptr<image>(new image, [&](image * i) { cleanup_image(i); });
b.buffer = VK_NULL_HANDLE;
b.memory = VK_NULL_HANDLE;
uint32_t mipmaps = std::log2(std::max(size.width, size.height)) + 1;
VkImageCreateInfo image_info{
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
.flags = 0,
.imageType = VK_IMAGE_TYPE_2D,
.format = format,
.extent = {size.width, size.height, 1},
.mipLevels = mipmaps,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
.tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
};
i->vk_image = vk::image(device, image_info).release();
i->memory =
vk::device_memory(device, physical_device, i->vk_image, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release();
load_image(i->vk_image, data, size, format, mipmaps);
VkImageViewCreateInfo image_view_info{
.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,
.flags = 0,
.image = i->vk_image,
.viewType = VK_IMAGE_VIEW_TYPE_2D,
.format = format,
.components = {VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY},
.subresourceRange = {.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = mipmaps,
.baseArrayLayer = 0,
.layerCount = 1}};
CHECK_VK(vkCreateImageView(device, &image_view_info, nullptr, &i->image_view));
return images.emplace_back(i);
}
scene_renderer::buffer * scene_renderer::create_buffer(const void * data, size_t size, VkBufferUsageFlags usage)
void scene_renderer::cleanup_buffer(scene_renderer::buffer * b)
{
auto b = std::make_unique<buffer>();
if (b->vk_buffer)
vkDestroyBuffer(device, b->vk_buffer, nullptr);
if (b->memory)
vkFreeMemory(device, b->memory, nullptr);
}
try
{
VkBufferCreateInfo buffer_info{
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.size = size,
.usage = usage | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
};
std::weak_ptr<scene_renderer::buffer> scene_renderer::create_buffer(const void * data, size_t size, VkBufferUsageFlags usage)
{
auto b = std::shared_ptr<buffer>(new buffer, [&](buffer * b) { cleanup_buffer(b); });
b->buffer = vk::buffer(device, buffer_info).release();
b->memory = vk::device_memory(device, physical_device, b->buffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release();
VkBufferCreateInfo buffer_info{
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.size = size,
.usage = usage | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
};
load_buffer(b->buffer, data, size);
}
catch (...)
{
cleanup_buffer(*b);
throw;
}
b->vk_buffer = vk::buffer(device, buffer_info).release();
b->memory =
vk::device_memory(device, physical_device, b->vk_buffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT).release();
return buffers.emplace_back(std::move(b)).get();
load_buffer(b->vk_buffer, data, size);
return buffers.emplace_back(b);
}
scene_renderer::model * scene_renderer::load_gltf(const std::string & filename)
@@ -775,7 +780,8 @@ scene_renderer::model * scene_renderer::load_gltf(const std::string & filename)
for (tinygltf::Buffer & i: m->gltf_model.buffers)
{
m->buffers.push_back(create_buffer(i.data, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT));
m->buffers.push_back(
create_buffer(i.data, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT));
}
std::vector<bool> srgb(m->gltf_model.images.size(), false);
@@ -784,7 +790,8 @@ scene_renderer::model * scene_renderer::load_gltf(const std::string & filename)
if (i.emissiveTexture.index >= 0 && i.emissiveTexture.index < (int)srgb.size())
srgb[i.emissiveTexture.index] = true;
if (i.pbrMetallicRoughness.baseColorTexture.index >= 0 && i.pbrMetallicRoughness.baseColorTexture.index < (int)srgb.size())
if (i.pbrMetallicRoughness.baseColorTexture.index >= 0 &&
i.pbrMetallicRoughness.baseColorTexture.index < (int)srgb.size())
srgb[i.pbrMetallicRoughness.baseColorTexture.index] = true;
}
+63 -40
View File
@@ -1,21 +1,3 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <memory>
@@ -23,6 +5,8 @@
#include <vector>
#include <vulkan/vulkan.h>
#include "glm/vec2.hpp"
#include "glm/vec3.hpp"
#include "tiny_gltf.h"
#include "vk/buffer.h"
#include "vk/command_pool.h"
@@ -32,18 +16,31 @@
#include "vk/renderpass.h"
class scene_renderer
{
public:
class shader
{
friend class scene_renderer;
VkDescriptorSetLayout descriptor_set_layout{};
std::vector<VkDescriptorSetLayout> descriptor_set_layouts;
std::vector<VkDescriptorPool> descriptor_pools;
VkShaderModule vertex_shader{};
VkShaderModule fragment_shader{};
VkPipelineLayout pipeline_layout{};
VkPipeline pipeline{};
VkShaderModule vertex_shader;
VkShaderModule fragment_shader;
struct pipeline_info
{
VkPrimitiveTopology topology;
std::vector<VkVertexInputBindingDescription> vertex_bindings;
std::vector<VkVertexInputAttributeDescription> vertex_attributes;
};
std::vector<std::pair<pipeline_info, VkPipeline>> pipelines;
shader() = default;
shader(const shader &) = delete;
shader(shader &&) = delete;
};
class image
@@ -52,9 +49,13 @@ public:
VkDeviceMemory memory{};
VkSampler sampler{};
VkImage image{};
VkImage vk_image{};
VkImageView image_view{};
VkDescriptorSet descriptor_set{};
image() = default;
image(const image &) = delete;
image(image &&) = delete;
};
class buffer
@@ -62,12 +63,32 @@ public:
friend class scene_renderer;
VkDeviceMemory memory{};
VkBuffer buffer{};
VkBuffer vk_buffer{};
buffer() = default;
buffer(const buffer &) = delete;
buffer(buffer &&) = delete;
};
struct mesh_primitive
{
shader * s;
struct vertex
{
glm::vec3 position;
glm::vec3 normal;
glm::vec2 texcoord;
};
VkPrimitiveTopology topology;
VkPipeline pipeline;
std::weak_ptr<buffer> indices;
size_t indices_offset;
size_t indices_count;
std::weak_ptr<buffer> vertices;
size_t vertices_offset;
};
class model
@@ -75,8 +96,8 @@ public:
friend class scene_renderer;
tinygltf::Model gltf_model;
std::vector<image *> images;
std::vector<buffer *> buffers;
std::vector<std::weak_ptr<image>> images;
std::vector<std::weak_ptr<buffer>> buffers;
};
class model_instance
@@ -115,11 +136,11 @@ private:
void load_image(VkImage i, void * data, VkExtent2D size, VkFormat format, uint32_t mipmap_count, VkImageLayout final_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
// Scene data
std::vector<std::unique_ptr<shader>> shaders;
std::vector<std::unique_ptr<image>> images;
std::vector<std::unique_ptr<buffer>> buffers;
std::vector<std::unique_ptr<mesh_primitive>> primitives;
std::vector<std::unique_ptr<model>> models;
std::vector<std::shared_ptr<shader>> shaders;
std::vector<std::shared_ptr<image>> images;
std::vector<std::shared_ptr<buffer>> buffers;
std::vector<std::shared_ptr<mesh_primitive>> primitives;
std::vector<std::shared_ptr<model>> models;
std::vector<model_instance> instances;
// Destination images
@@ -134,9 +155,9 @@ private:
void cleanup();
void cleanup_output_images();
void cleanup_shader(shader &);
void cleanup_buffer(buffer &);
void cleanup_image(image &);
void cleanup_shader(shader *);
void cleanup_buffer(buffer *);
void cleanup_image(image *);
public:
scene_renderer(VkDevice device, VkPhysicalDevice physical_device, VkQueue queue);
@@ -146,16 +167,18 @@ public:
void set_output_images(std::vector<VkImage> output_images, VkExtent2D output_size, VkFormat output_format);
shader * create_shader(std::string name, VkPrimitiveTopology topology, std::vector<VkDescriptorSetLayoutBinding> uniform_bindings, std::vector<VkVertexInputBindingDescription> vertex_bindings, std::vector<VkVertexInputAttributeDescription> vertex_attributes);
std::weak_ptr<shader> create_shader(std::string name,
std::vector<std::vector<VkDescriptorSetLayoutBinding>> uniform_bindings);
image * create_image(void * data, VkExtent2D size, VkFormat format);
VkPipeline get_shader_pipeline(std::weak_ptr<shader> shader, VkPrimitiveTopology topology, std::span<VkVertexInputBindingDescription> vertex_bindings, std::span<VkVertexInputAttributeDescription> vertex_attributes);
buffer * create_buffer(const void * data, size_t size, VkBufferUsageFlags usage);
std::weak_ptr<image> create_image(void * data, VkExtent2D size, VkFormat format);
std::weak_ptr<buffer> create_buffer(const void * data, size_t size, VkBufferUsageFlags usage);
template <typename T>
// requires(std::contiguous_iterator<typename T::iterator>)
buffer * create_buffer(const T & data,
VkBufferUsageFlags usage)
std::weak_ptr<buffer> create_buffer(const T & data, VkBufferUsageFlags usage)
{
return create_buffer(data.data(), data.size() * sizeof(T), usage);
}
-1
View File
@@ -357,7 +357,6 @@ void scenes::lobby::render()
void scenes::lobby::render_view(XrViewStateFlags flags, XrTime display_time, XrView & view, int swapchain_index, int image_index)
{
xr::swapchain & swapchain = swapchains[swapchain_index];
xr::swapchain::image & swapchain_image = swapchain.images()[image_index];
image_data & data = images_data[swapchain_index][image_index];
VkClearValue clearColor = {{{0.0f, 0.0f, 0.0f, 1.0f}}};
+5 -5
View File
@@ -211,7 +211,7 @@ void scenes::stream::render()
application::pop_scene();
XrFrameState framestate = session.wait_frame();
auto t0 = application::now();
// auto t0 = application::now();
if (decoders.empty())
framestate.shouldRender = false;
@@ -233,7 +233,7 @@ void scenes::stream::render()
}
session.begin_frame();
auto dt2 = application::now() - t0;
// auto dt2 = application::now() - t0;
auto [flags, views] = session.locate_views(viewconfig, framestate.predictedDisplayTime, world_space);
assert(views.size() == swapchains.size());
@@ -354,7 +354,7 @@ void scenes::stream::render()
.pCommandBuffers = &command_buffer,
};
CHECK_VK(vkQueueSubmit(queue, 1, &submit_info, fence));
auto dt4 = application::now() - t0;
// auto dt4 = application::now() - t0;
std::vector<XrCompositionLayerBaseHeader *> layers_base;
std::vector<XrCompositionLayerProjectionView> layer_view;
@@ -396,14 +396,14 @@ void scenes::stream::render()
layers_base.push_back(reinterpret_cast<XrCompositionLayerBaseHeader *>(&layer));
session.end_frame(/*timestamp*/ framestate.predictedDisplayTime, layers_base);
auto dt5 = application::now() - t0;
// auto dt5 = application::now() - t0;
CHECK_VK(vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX));
CHECK_VK(vkResetFences(device, 1, &fence));
// We don't need those after vkWaitForFences
current_blit_handles.clear();
auto dt6 = application::now() - t0;
// auto dt6 = application::now() - t0;
read_actions();
// spdlog::info("Render timing: begin frame {:.3f}ms, submit commands {:.3f}ms, end frame {:.3f}ms, wait fence {:.3f}ms, predicted display time {:.3f}ms", dt2/1.e6, dt4/1.e6, dt5/1.e6, dt6/1.e6, (framestate.predictedDisplayTime - t0) / 1.e6);
+15 -15
View File
@@ -81,21 +81,21 @@ static int iterate_phdr_callback(dl_phdr_info * info, size_t size, void * arg)
return 0;
}
static std::string unmangle(const char * function)
{
if (!function)
return "(null)";
int status;
char * demangled = abi::__cxa_demangle(function, nullptr, nullptr, &status);
if (status != 0)
return function;
std::string s = demangled;
free(demangled);
return s;
}
// static std::string unmangle(const char * function)
// {
// if (!function)
// return "(null)";
//
// int status;
// char * demangled = abi::__cxa_demangle(function, nullptr, nullptr, &status);
//
// if (status != 0)
// return function;
//
// std::string s = demangled;
// free(demangled);
// return s;
// }
std::vector<utils::backtrace_entry> utils::backtrace(size_t max)
{
-251
View File
@@ -1,251 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <array>
#include <chrono>
#include <cstdint>
#include <netinet/in.h>
#include <optional>
#include <string>
#include <variant>
#include <vector>
#include <openxr/openxr.h>
namespace xrt::drivers::wivrn
{
static const int control_port = 9757;
static const int stream_port = 9757;
enum class device_id : uint8_t
{
HEAD, // /user/head
LEFT_CONTROLLER_HAPTIC, // /user/hand/left/output/haptic
RIGHT_CONTROLLER_HAPTIC, // /user/hand/right/output/haptic
LEFT_GRIP, // /user/hand/left/input/grip/pose
LEFT_AIM, // /user/hand/left/input/aim/pose
RIGHT_GRIP, // /user/hand/right/input/grip/pose
RIGHT_AIM, // /user/hand/right/input/aim/pose
X_CLICK, // /user/hand/left/input/x/click
X_TOUCH, // /user/hand/left/input/x/touch
Y_CLICK, // /user/hand/left/input/y/click
Y_TOUCH, // /user/hand/left/input/y/touch
MENU_CLICK, // /user/hand/left/input/menu/click
LEFT_SQUEEZE_VALUE, // /user/hand/left/input/squeeze/value
LEFT_TRIGGER_VALUE, // /user/hand/left/input/trigger/value
LEFT_TRIGGER_TOUCH, // /user/hand/left/input/trigger/touch
LEFT_THUMBSTICK_X, // /user/hand/left/input/thumbstick/x
LEFT_THUMBSTICK_Y, // /user/hand/left/input/thumbstick/y
LEFT_THUMBSTICK_CLICK, // /user/hand/left/input/thumbstick/click
LEFT_THUMBSTICK_TOUCH, // /user/hand/left/input/thumbstick/touch
LEFT_THUMBREST_TOUCH, // /user/hand/left/input/thumbrest/touch
A_CLICK, // /user/hand/right/input/a/click
A_TOUCH, // /user/hand/right/input/a/touch
B_CLICK, // /user/hand/right/input/b/click
B_TOUCH, // /user/hand/right/input/b/touch
SYSTEM_CLICK, // /user/hand/right/input/system/click
RIGHT_SQUEEZE_VALUE, // /user/hand/right/input/squeeze/value
RIGHT_TRIGGER_VALUE, // /user/hand/right/input/trigger/value
RIGHT_TRIGGER_TOUCH, // /user/hand/right/input/trigger/touch
RIGHT_THUMBSTICK_X, // /user/hand/right/input/thumbstick/x
RIGHT_THUMBSTICK_Y, // /user/hand/right/input/thumbstick/y
RIGHT_THUMBSTICK_CLICK, // /user/hand/right/input/thumbstick/click
RIGHT_THUMBSTICK_TOUCH, // /user/hand/right/input/thumbstick/touch
RIGHT_THUMBREST_TOUCH, // /user/hand/right/input/thumbrest/touch
};
enum video_codec
{
h264,
hevc,
h265 = hevc,
};
namespace from_headset
{
struct headset_info_packet
{
uint32_t recommended_eye_width;
uint32_t recommended_eye_height;
std::vector<float> available_refresh_rates;
float preferred_refresh_rate;
uint32_t microphone_sample_rate;
};
struct tracking
{
enum flags : uint8_t
{
orientation_valid = 1 << 0,
position_valid = 1 << 1,
linear_velocity_valid = 1 << 2,
angular_velocity_valid = 1 << 3,
orientation_tracked = 1 << 4,
position_tracked = 1 << 5
};
struct pose
{
device_id device;
XrPosef pose;
XrVector3f linear_velocity;
XrVector3f angular_velocity;
uint8_t flags;
};
struct view
{
// Relative to XR_REFERENCE_SPACE_TYPE_VIEW
XrPosef pose;
XrFovf fov;
};
uint64_t timestamp;
XrViewStateFlags flags;
std::array<view, 2> views;
std::vector<pose> device_poses;
};
struct inputs
{
struct input_value
{
device_id id;
float value;
};
std::vector<input_value> values;
};
struct timesync_response
{
std::chrono::nanoseconds query;
uint64_t response;
};
struct feedback
{
uint64_t frame_index;
uint8_t stream_index;
// Timestamps
uint64_t received_first_packet;
uint64_t received_last_packet;
uint64_t reconstructed;
uint64_t sent_to_decoder;
uint64_t received_from_decoder;
uint64_t blitted;
uint64_t displayed;
std::array<XrPosef, 2> received_pose;
std::array<XrPosef, 2> real_pose;
uint8_t data_packets;
uint8_t parity_packets;
uint8_t received_data_packets;
uint8_t received_parity_packets;
};
using control_packets = std::variant<headset_info_packet, feedback>;
using stream_packets = std::variant<tracking, inputs, timesync_response>;
} // namespace from_headset
namespace to_headset
{
struct video_stream_description
{
struct item
{
uint16_t width;
uint16_t height;
uint16_t offset_x;
uint16_t offset_y;
video_codec codec;
};
uint16_t width;
uint16_t height;
float fps;
std::vector<item> items;
};
struct video_stream_data_shard
{
inline static const size_t max_payload_size = 1400;
enum flags : uint8_t
{
start_of_slice = 1,
end_of_slice = 1 << 1,
end_of_frame = 1 << 2,
};
// Identifier of stream in video_stream_description
uint8_t stream_item_idx;
// Counter increased for each frame
uint64_t frame_idx;
// Identifier of the shard within the frame
uint16_t shard_idx;
uint8_t flags;
// Actual video data, may contain multiple NAL units
std::vector<uint8_t> payload;
// Position information, must be present on last video shard
struct view_info_t
{
// ns in headset time referential
uint64_t display_time;
std::array<XrPosef, 2> pose;
std::array<XrFovf, 2> fov;
};
std::optional<view_info_t> view_info;
};
struct video_stream_parity_shard
{
uint8_t stream_item_idx;
uint64_t frame_idx;
uint16_t data_shard_count;
uint8_t num_parity_elements;
uint8_t parity_element;
// Parity data
std::vector<uint8_t> payload;
};
struct haptics
{
device_id id;
std::chrono::nanoseconds duration;
float frequency;
float amplitude;
};
struct timesync_query
{
std::chrono::nanoseconds query;
};
using stream_packets = std::variant<video_stream_data_shard, video_stream_parity_shard, haptics, timesync_query>;
using control_packets = std::variant<video_stream_description>;
} // namespace to_headset
} // namespace xrt::drivers::wivrn
-519
View File
@@ -1,519 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "boost/pfr/core.hpp"
#include "boost/pfr/tuple_size.hpp"
#include <array>
#include <boost/pfr.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <optional>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <variant>
#include <vector>
namespace xrt::drivers::wivrn
{
namespace details
{
struct hash_context
{
// FNV1a hash
static const uint64_t fnv_prime = 0x100000001b3;
static const uint64_t fnv_offset_basis = 0xcbf29ce484222325;
uint64_t hash = fnv_offset_basis;
constexpr uint64_t feed(std::string_view s)
{
for (const char c: s)
hash = (hash ^ c) * fnv_prime;
return hash;
}
constexpr uint64_t feed_unsigned(uint64_t n)
{
if (n >= 10)
feed(n / 10);
char digit[] = "0";
digit[0] += n % 10;
feed(digit);
return hash;
}
constexpr uint64_t feed(int64_t n)
{
if (n < 0)
{
feed("-");
feed_unsigned(static_cast<uint64_t>(-n));
}
else
{
feed_unsigned(static_cast<uint64_t>(n));
}
return hash;
}
};
} // namespace details
template <typename T, typename Enable = void>
struct serialization_traits;
class deserialization_error : public std::runtime_error
{
public:
deserialization_error() :
std::runtime_error("Deserialization error") {}
};
class serialization_packet
{
std::vector<uint8_t> buffer;
public:
serialization_packet() = default;
void write(const void * data, size_t size)
{
size_t index = buffer.size();
buffer.resize(index + size);
memcpy(&buffer[index], data, size);
}
const uint8_t * data() const
{
return buffer.data();
}
size_t size() const
{
return buffer.size();
}
template <typename T>
void serialize(const T & value)
{
serialization_traits<T>::serialize(value, *this);
}
operator std::vector<uint8_t> &&() &&
{
return std::move(buffer);
}
};
class deserialization_packet
{
std::vector<uint8_t> buffer;
size_t read_index;
public:
deserialization_packet() :
read_index(0) {}
explicit deserialization_packet(std::vector<uint8_t> buffer, size_t skip = 0) :
buffer(std::move(buffer)), read_index(skip)
{}
void read(void * data, size_t size)
{
check_remaining_size(size);
memcpy(data, &buffer[read_index], size);
read_index += size;
}
size_t remaining() const
{
return buffer.size() - read_index;
}
bool empty() const
{
return buffer.size() <= read_index;
}
void check_remaining_size(size_t min_size) const
{
if (min_size > remaining())
throw deserialization_error();
}
template <typename T>
T deserialize()
{
return serialization_traits<T>::deserialize(*this);
}
};
template <typename T>
struct serialization_traits<T, std::enable_if_t<std::is_arithmetic_v<T>>>
{
static constexpr void type_hash(details::hash_context & h)
{
if constexpr (std::is_floating_point_v<T>)
h.feed("float");
else if constexpr (std::is_integral_v<T>)
{
if constexpr (std::is_unsigned_v<T>)
h.feed("uint");
else
h.feed("int");
}
h.feed(sizeof(T) * 8);
}
static void serialize(T value, serialization_packet & packet)
{
packet.write(&value, sizeof(value));
}
static T deserialize(deserialization_packet & packet)
{
T value;
packet.read((char *)&value, sizeof(value));
return value;
}
};
template <typename T>
struct serialization_traits<T, std::enable_if_t<std::is_enum_v<T>>>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("enum");
h.feed(sizeof(T) * 8);
}
static void serialize(T value, serialization_packet & packet)
{
packet.write(&value, sizeof(value));
}
static T deserialize(deserialization_packet & packet)
{
T value;
packet.read((char *)&value, sizeof(value));
return value;
}
};
template <class>
struct is_stdarray : public std::false_type
{};
template <class T, size_t N>
struct is_stdarray<std::array<T, N>> : public std::true_type
{};
template <typename T>
inline constexpr bool is_stdarray_v = is_stdarray<T>::value;
template <typename T>
struct serialization_traits<T, std::enable_if_t<std::is_aggregate_v<T> && !is_stdarray_v<T>>>
{
template <size_t I>
static constexpr void aux2(details::hash_context & h)
{
if constexpr (I > 0)
h.feed(",");
serialization_traits<boost::pfr::tuple_element_t<I, T>>::type_hash(h);
}
template <size_t... I>
static constexpr void aux1(details::hash_context & h, std::index_sequence<I...>)
{
(aux2<I>(h), ...);
}
static constexpr void type_hash(details::hash_context & h)
{
h.feed("structure{");
aux1(h, std::make_index_sequence<boost::pfr::tuple_size_v<T>>());
h.feed("}");
}
static void serialize(const T & value, serialization_packet & packet)
{
boost::pfr::for_each_field(value, [&](const auto & x) { packet.serialize(x); });
}
static T deserialize(deserialization_packet & packet)
{
T value;
boost::pfr::for_each_field(
value, [&](auto & x) { x = packet.deserialize<std::remove_reference_t<decltype(x)>>(); });
return value;
}
};
template <>
struct serialization_traits<std::string>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("string");
}
static void serialize(const std::string & value, serialization_packet & packet)
{
packet.serialize<uint64_t>(value.size());
packet.write(value.data(), value.size());
}
static std::string deserialize(deserialization_packet & packet)
{
std::string value;
size_t size = packet.deserialize<uint64_t>();
packet.check_remaining_size(size);
value.resize(size);
packet.read(value.data(), size);
return value;
}
};
template <typename T>
struct serialization_traits<std::vector<T>>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("vector<");
serialization_traits<T>::type_hash(h);
h.feed(">");
}
static void serialize(const std::vector<T> & value, serialization_packet & packet)
{
packet.serialize<uint64_t>(value.size());
for (const T & i: value)
packet.serialize<T>(i);
}
static std::vector<T> deserialize(deserialization_packet & packet)
{
std::vector<T> value;
size_t size = packet.deserialize<uint64_t>();
packet.check_remaining_size(size);
value.reserve(size);
for (size_t i = 0; i < size; i++)
{
value.emplace_back(packet.deserialize<T>());
}
return value;
}
};
template <typename T>
struct serialization_traits<std::optional<T>>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("optional<");
serialization_traits<T>::type_hash(h);
h.feed(">");
}
static void serialize(const std::optional<T> & value, serialization_packet & packet)
{
if (value)
{
packet.serialize<bool>(true);
packet.serialize<T>(*value);
}
else
{
packet.serialize<bool>(false);
}
}
static std::optional<T> deserialize(deserialization_packet & packet)
{
if (packet.deserialize<bool>())
return packet.deserialize<T>();
else
return std::nullopt;
}
};
template <typename T, size_t N>
struct serialization_traits<std::array<T, N>>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("array<");
serialization_traits<T>::type_hash(h);
h.feed(",");
h.feed(N);
h.feed(">");
}
static void serialize(const std::array<T, N> & value, serialization_packet & packet)
{
for (const T & i: value)
packet.serialize<T>(i);
}
static std::array<T, N> deserialize(deserialization_packet & packet)
{
std::array<T, N> value;
for (size_t i = 0; i < N; i++)
{
value[i] = packet.deserialize<T>();
}
return value;
}
};
template <typename... T>
struct serialization_traits<std::variant<T...>>
{
template <typename U, typename... V>
static constexpr void type_list_hash(details::hash_context & h)
{
serialization_traits<U>::type_hash(h);
if constexpr (sizeof...(V) > 0)
{
h.feed(",");
type_list_hash<V...>(h);
}
}
static constexpr void type_hash(details::hash_context & h)
{
h.feed("variant<");
type_list_hash<T...>(h);
h.feed(">");
}
static void serialize(const std::variant<T...> & value, serialization_packet & packet)
{
packet.serialize<uint32_t>(value.index());
std::visit([&](const auto & x) { packet.serialize(x); }, value);
}
template <size_t I>
using i_th_type = std::tuple_element_t<I, std::tuple<T...>>;
template <size_t... I>
static std::variant<T...> deserialize_aux(deserialization_packet & packet, size_t type_index, std::index_sequence<I...>)
{
std::variant<T...> value;
((I == type_index ? (void)(value = packet.deserialize<i_th_type<I>>()) : (void)0), ...);
return value;
}
static std::variant<T...> deserialize(deserialization_packet & packet)
{
uint32_t type_index = packet.deserialize<uint32_t>();
if (type_index >= sizeof...(T))
throw deserialization_error();
return deserialize_aux(packet, type_index, std::make_index_sequence<sizeof...(T)>());
}
};
template <typename Rep, typename Period>
struct serialization_traits<std::chrono::duration<Rep, Period>>
{
static constexpr void type_hash(details::hash_context & h)
{
h.feed("duration<");
serialization_traits<Rep>::type_hash(h);
h.feed(",");
h.feed(Period::num);
h.feed("/");
h.feed(Period::den);
h.feed(">");
}
static void serialize(const std::chrono::duration<Rep, Period> & value, serialization_packet & packet)
{
packet.serialize<Rep>(value.count());
}
static std::chrono::duration<Rep, Period> deserialize(deserialization_packet & packet)
{
Rep nsec = packet.deserialize<Rep>();
return std::chrono::duration<Rep, Period>{nsec};
}
};
namespace unit_tests
{
template <typename T>
constexpr uint64_t hash(T s)
{
return details::hash_context{}.feed(s);
}
static_assert(hash("test") == 0xf9e6e6ef197c2b25);
static_assert(hash(1234) == 0x1fabbdf10314a21d);
static_assert(hash(-1234) == 0x77fa1c9653db5a84);
static_assert(hash(0) == 0xaf63ad4c86019caf);
template <typename T>
constexpr uint64_t serialization_type_hash()
{
details::hash_context h;
serialization_traits<T>::type_hash(h);
return h.hash;
}
static_assert(serialization_type_hash<bool>() == hash("uint8"));
static_assert(serialization_type_hash<int>() == hash("int32"));
static_assert(serialization_type_hash<float>() == hash("float32"));
static_assert(serialization_type_hash<double>() == hash("float64"));
static_assert(serialization_type_hash<std::chrono::nanoseconds>() == hash("duration<int64,1/1000000000>"));
static_assert(serialization_type_hash<std::optional<int>>() == hash("optional<int32>"));
static_assert(serialization_type_hash<std::vector<int>>() == hash("vector<int32>"));
static_assert(serialization_type_hash<std::array<int, 42>>() == hash("array<int32,42>"));
static_assert(serialization_type_hash<std::string>() == hash("string"));
static_assert(serialization_type_hash<std::variant<int, float>>() == hash("variant<int32,float32>"));
struct test
{
int x;
float y;
};
static_assert(serialization_type_hash<test>() == hash("structure{int32,float32}"));
} // namespace unit_tests
} // namespace xrt::drivers::wivrn
-343
View File
@@ -1,343 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "wivrn_sockets.h"
#include <arpa/inet.h>
#include <cassert>
#include <memory>
#include <netdb.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <system_error>
#include <unistd.h>
const char * xrt::drivers::wivrn::invalid_packet::what() const noexcept
{
return "Invalid packet";
}
const char * xrt::drivers::wivrn::socket_shutdown::what() const noexcept
{
return "Socket shutdown";
}
xrt::drivers::wivrn::socket_base::socket_base(xrt::drivers::wivrn::socket_base && other) :
fd(other.fd)
{
other.fd = -1;
}
xrt::drivers::wivrn::socket_base::~socket_base()
{
if (fd >= 0)
::close(fd);
}
xrt::drivers::wivrn::UDP::UDP()
{
fd = socket(AF_INET6, SOCK_DGRAM, 0);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
}
void xrt::drivers::wivrn::UDP::bind(int port)
{
sockaddr_in6 bind_addr{};
bind_addr.sin6_family = AF_INET6;
bind_addr.sin6_addr = IN6ADDR_ANY_INIT;
bind_addr.sin6_port = htons(port);
if (::bind(fd, (sockaddr *)&bind_addr, sizeof(bind_addr)) < 0)
throw std::system_error{errno, std::generic_category()};
}
void xrt::drivers::wivrn::UDP::connect(in6_addr address, int port)
{
sockaddr_in6 sa;
sa.sin6_family = AF_INET6;
sa.sin6_addr = address;
sa.sin6_port = htons(port);
if (::connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
throw std::system_error{errno, std::generic_category()};
}
void xrt::drivers::wivrn::UDP::connect(in_addr address, int port)
{
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr = address;
sa.sin_port = htons(port);
if (::connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
throw std::system_error{errno, std::generic_category()};
}
void xrt::drivers::wivrn::UDP::subscribe_multicast(in6_addr address)
{
assert(IN6_IS_ADDR_MULTICAST(&address));
ipv6_mreq subscribe{};
subscribe.ipv6mr_multiaddr = address;
if (setsockopt(fd, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &subscribe, sizeof(subscribe)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
}
void xrt::drivers::wivrn::UDP::unsubscribe_multicast(in6_addr address)
{
assert(IN6_IS_ADDR_MULTICAST(&address));
ipv6_mreq subscribe{};
subscribe.ipv6mr_multiaddr = address;
if (setsockopt(fd, IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, &subscribe, sizeof(subscribe)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
}
void xrt::drivers::wivrn::UDP::set_receive_buffer_size(int size)
{
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
}
void xrt::drivers::wivrn::TCP::init()
{
int nodelay = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
mutex = std::make_unique<std::mutex>();
}
xrt::drivers::wivrn::TCP::TCP(int fd)
{
this->fd = fd;
init();
}
xrt::drivers::wivrn::TCP::TCP(in6_addr address, int port)
{
fd = socket(AF_INET6, SOCK_STREAM, 0);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
sockaddr_in6 sa;
sa.sin6_family = AF_INET6;
sa.sin6_addr = address;
sa.sin6_port = htons(port);
if (connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
init();
}
xrt::drivers::wivrn::TCP::TCP(in_addr address, int port)
{
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr = address;
sa.sin_port = htons(port);
if (connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
init();
}
xrt::drivers::wivrn::TCPListener::TCPListener(int port)
{
fd = socket(AF_INET6, SOCK_STREAM, 0);
if (fd < 0)
{
throw std::system_error{errno, std::generic_category()};
}
int reuse_addr = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
sockaddr_in6 addr{};
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(port);
addr.sin6_addr = in6addr_any;
if (bind(fd, (sockaddr *)&addr, sizeof(addr)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
int backlog = 1;
if (listen(fd, backlog) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
}
std::pair<xrt::drivers::wivrn::TCP, sockaddr_in6>
xrt::drivers::wivrn::TCPListener::accept()
{
sockaddr_in6 addr{};
socklen_t addrlen = sizeof(addr);
int fd2 = ::accept(fd, (sockaddr *)&addr, &addrlen);
if (fd2 < 0)
throw std::system_error{errno, std::generic_category()};
return {TCP{fd2}, addr};
}
// std::pair<xrt::drivers::wivrn::deserialization_packet, sockaddr_in6> xrt::drivers::wivrn::UDP::receive_from_raw()
// {
// std::vector<uint8_t> buffer(2000);
//
// sockaddr_in6 addr;
// socklen_t addrlen = sizeof(addr);
//
// ssize_t received = recvfrom(fd, buffer.data(), buffer.size(), 0, (sockaddr *)&addr, &addrlen);
// if (received < 0)
// throw std::system_error{errno, std::generic_category()};
//
// buffer.resize(received);
//
// return {deserialization_packet{buffer}, addr};
// }
xrt::drivers::wivrn::deserialization_packet xrt::drivers::wivrn::UDP::receive_raw()
{
std::vector<uint8_t> buffer(2000);
ssize_t received = recv(fd, buffer.data(), buffer.size(), 0);
if (received < 0)
throw std::system_error{errno, std::generic_category()};
buffer.resize(received);
return deserialization_packet{buffer};
}
void xrt::drivers::wivrn::UDP::send_raw(const std::vector<uint8_t> & data)
{
if (::send(fd, data.data(), data.size(), 0) < 0)
throw std::system_error{errno, std::generic_category()};
}
xrt::drivers::wivrn::deserialization_packet xrt::drivers::wivrn::TCP::receive_raw()
{
size_t expected_size;
size_t already_received = buffer.size();
if (already_received < 4)
{
expected_size = 4 - buffer.size();
}
else
{
uint32_t payload_size = *reinterpret_cast<uint32_t *>(buffer.data());
expected_size = payload_size + 4 - buffer.size();
}
buffer.resize(already_received + expected_size);
ssize_t received = recv(fd, buffer.data() + already_received, expected_size, MSG_DONTWAIT);
if (received < 0)
throw std::system_error{errno, std::generic_category()};
if (received == 0)
throw socket_shutdown{};
buffer.resize(already_received + received);
if (buffer.size() < 4)
return {};
uint32_t payload_size = *reinterpret_cast<uint32_t *>(buffer.data());
if (buffer.size() < 4 + payload_size)
return {};
assert(buffer.size() == 4 + payload_size);
std::vector<uint8_t> new_buffer;
std::swap(buffer, new_buffer);
return deserialization_packet{std::move(new_buffer), 4};
}
void xrt::drivers::wivrn::TCP::send_raw(const std::vector<uint8_t> & data)
{
std::lock_guard lock(*mutex);
uint32_t size = data.size();
ssize_t sent = ::send(fd, &size, sizeof(size), MSG_NOSIGNAL);
if (sent == 0)
throw socket_shutdown{};
if (sent < 0)
throw std::system_error{errno, std::generic_category()};
assert(sent == sizeof(size));
size_t index = 0;
while (index < data.size())
{
sent = ::send(fd, data.data() + index, data.size() - index, MSG_NOSIGNAL);
if (sent == 0)
throw socket_shutdown{};
if (sent < 0)
throw std::system_error{errno, std::generic_category()};
index += sent;
}
}
-150
View File
@@ -1,150 +0,0 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "wivrn_serialization.h"
#include <memory>
#include <mutex>
#include <netinet/ip.h>
#include <stdexcept>
#include <utility>
#include <vector>
namespace xrt::drivers::wivrn
{
class socket_shutdown : public std::exception
{
public:
const char * what() const noexcept override;
};
class invalid_packet : public std::exception
{
public:
const char * what() const noexcept override;
};
template <typename T, typename... Ts>
struct index_of_type
{};
template <typename T, typename... Ts>
struct index_of_type<T, T, Ts...> : std::integral_constant<size_t, 0>
{};
template <typename T, typename T2, typename... Ts>
struct index_of_type<T, T2, Ts...> : std::integral_constant<size_t, 1 + index_of_type<T, Ts...>::value>
{};
static_assert(index_of_type<int, int, float>::value == 0);
static_assert(index_of_type<float, int, float>::value == 1);
class socket_base
{
protected:
int fd = -1;
socket_base() = default;
socket_base(const socket_base &) = delete;
socket_base(socket_base &&);
~socket_base();
public:
int get_fd() const
{
return fd;
}
};
class UDP : public socket_base
{
public:
UDP();
UDP(const UDP &) = delete;
UDP(UDP &&) = default;
deserialization_packet receive_raw();
void send_raw(const std::vector<uint8_t> & data);
void connect(in6_addr address, int port);
void connect(in_addr address, int port);
void bind(int port);
void subscribe_multicast(in6_addr address);
void unsubscribe_multicast(in6_addr address);
void set_receive_buffer_size(int size);
};
class TCP : public socket_base
{
std::vector<uint8_t> buffer;
std::unique_ptr<std::mutex> mutex;
void init();
public:
TCP(in6_addr address, int port);
TCP(in_addr address, int port);
explicit TCP(int fd);
TCP(const TCP &) = delete;
TCP(TCP &&) = default;
deserialization_packet receive_raw();
void send_raw(const std::vector<uint8_t> & data);
};
class TCPListener : public socket_base
{
public:
TCPListener(int port);
TCPListener(const TCPListener &) = delete;
TCPListener(TCPListener &&) = default;
std::pair<TCP, sockaddr_in6> accept();
};
template <typename Socket, typename ReceivedType, typename SentType>
class typed_socket : public Socket
{
public:
template <typename... Args>
typed_socket(Args &&... args) :
Socket(std::forward<Args>(args)...)
{}
std::optional<ReceivedType> receive()
{
deserialization_packet packet = this->receive_raw();
if (packet.empty())
return {};
return packet.deserialize<ReceivedType>();
}
template <typename T = SentType, typename = std::enable_if_t<std::is_same_v<T, SentType>>>
void send(const T & data)
{
serialization_packet p;
p.serialize(data);
this->send_raw(std::move(p));
}
};
} // namespace xrt::drivers::wivrn