Vulkan renderer backend (#2564)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Bart Louwers <bart.louwers@gmail.com>
This commit is contained in:
@@ -50,17 +50,11 @@ public:
|
||||
}
|
||||
|
||||
static std::unique_ptr<Instance> createInstance(gl::Context& context,
|
||||
const ProgramParameters& programParameters,
|
||||
const std::string& additionalDefines) {
|
||||
[[maybe_unused]] const ProgramParameters& programParameters,
|
||||
[[maybe_unused]] const std::string& additionalDefines) {
|
||||
#if MLN_RENDER_BACKEND_OPENGL
|
||||
constexpr auto backend = gfx::Backend::Type::OpenGL;
|
||||
#elif MLN_RENDER_BACKEND_METAL
|
||||
constexpr auto backend = gfx::Backend::Type::Metal;
|
||||
#endif
|
||||
|
||||
#if MLN_RENDER_BACKEND_METAL
|
||||
return std::make_unique<Instance>(context);
|
||||
#else
|
||||
// Compile the shader
|
||||
std::initializer_list<const char*> vertexSource = {
|
||||
"#version 300 es\n",
|
||||
@@ -77,6 +71,8 @@ public:
|
||||
programParameters.fragmentSource(gfx::Backend::Type::OpenGL).c_str()};
|
||||
|
||||
return std::make_unique<Instance>(context, vertexSource, fragmentSource);
|
||||
#else
|
||||
return std::make_unique<Instance>(context);
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
#include <unordered_map>
|
||||
|
||||
#include <mbgl/shaders/shader_manifest.hpp>
|
||||
#if !MLN_RENDER_BACKEND_METAL
|
||||
#if MLN_RENDER_BACKEND_OPENGL
|
||||
#include <mbgl/gl/program.hpp>
|
||||
#endif
|
||||
|
||||
@@ -52,12 +52,16 @@ public:
|
||||
|
||||
std::unique_ptr<gfx::Program<Name>> program;
|
||||
|
||||
Program(const ProgramParameters& programParameters) {
|
||||
Program([[maybe_unused]] const ProgramParameters& programParameters) {
|
||||
switch (gfx::Backend::GetType()) {
|
||||
#if MLN_RENDER_BACKEND_METAL
|
||||
case gfx::Backend::Type::Metal: {
|
||||
break;
|
||||
}
|
||||
#elif MLN_RENDER_BACKEND_VULKAN
|
||||
case gfx::Backend::Type::Vulkan: {
|
||||
break;
|
||||
}
|
||||
#else // MLN_RENDER_BACKEND_OPENGL
|
||||
case gfx::Backend::Type::OpenGL: {
|
||||
program = std::make_unique<gl::Program<Name>>(programParameters.withDefaultSource(
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
#include <array>
|
||||
|
||||
#include <mbgl/shaders/shader_manifest.hpp>
|
||||
#if !MLN_RENDER_BACKEND_METAL
|
||||
#if MLN_RENDER_BACKEND_OPENGL
|
||||
#include <mbgl/gl/program.hpp>
|
||||
#endif
|
||||
|
||||
@@ -261,9 +261,9 @@ public:
|
||||
|
||||
std::unique_ptr<gfx::Program<Name>> program;
|
||||
|
||||
SymbolProgram(const ProgramParameters& programParameters) {
|
||||
SymbolProgram([[maybe_unused]] const ProgramParameters& programParameters) {
|
||||
switch (gfx::Backend::GetType()) {
|
||||
#if !MLN_RENDER_BACKEND_METAL
|
||||
#if MLN_RENDER_BACKEND_OPENGL
|
||||
case gfx::Backend::Type::OpenGL: {
|
||||
program = std::make_unique<gl::Program<Name>>(programParameters.withDefaultSource(
|
||||
{gfx::Backend::Type::OpenGL,
|
||||
|
||||
@@ -87,6 +87,7 @@ void FillLayerTweaker::execute(LayerGroupBase& layerGroup, const PaintParameters
|
||||
}
|
||||
|
||||
auto& drawableUniforms = drawable.mutableUniformBuffers();
|
||||
|
||||
switch (static_cast<RenderFillLayer::FillVariant>(drawable.getType())) {
|
||||
case RenderFillLayer::FillVariant::Fill: {
|
||||
const FillDrawableUBO drawableUBO = {/*.matrix=*/util::cast<float>(matrix)};
|
||||
|
||||
@@ -16,6 +16,12 @@
|
||||
#include <mbgl/shaders/mtl/clipping_mask.hpp>
|
||||
#endif // MLN_RENDER_BACKEND_METAL
|
||||
|
||||
#if MLN_RENDER_BACKEND_VULKAN
|
||||
#include <mbgl/vulkan/render_pass.hpp>
|
||||
#include <mbgl/shaders/vulkan/clipping_mask.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#endif // MLN_RENDER_BACKEND_VULKAN
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
TransformParameters::TransformParameters(const TransformState& state_)
|
||||
@@ -139,6 +145,11 @@ void PaintParameters::clearStencil() {
|
||||
0,
|
||||
0}};
|
||||
mtlContext.renderTileClippingMasks(*renderPass, staticData, tileUBO);
|
||||
context.renderingStats().stencilClears++;
|
||||
#elif MLN_RENDER_BACKEND_VULKAN
|
||||
const auto& vulkanRenderPass = static_cast<vulkan::RenderPass&>(*renderPass);
|
||||
vulkanRenderPass.clearStencil();
|
||||
|
||||
context.renderingStats().stencilClears++;
|
||||
#else // !MLN_RENDER_BACKEND_METAL
|
||||
context.clearStencilBuffer(0b00000000);
|
||||
@@ -198,6 +209,39 @@ void PaintParameters::renderTileClippingMasks(const RenderTiles& renderTiles) {
|
||||
mtlContext.renderingStats().stencilUpdates++;
|
||||
}
|
||||
|
||||
#elif MLN_RENDER_BACKEND_VULKAN
|
||||
|
||||
std::vector<shaders::ClipUBO> tileUBOs;
|
||||
for (const auto& tileRef : *renderTiles) {
|
||||
const auto& tileID = tileRef.get().id;
|
||||
|
||||
const uint32_t stencilID = nextStencilID;
|
||||
const auto result = tileClippingMaskIDs.insert(std::make_pair(tileID, stencilID));
|
||||
if (result.second) {
|
||||
// inserted
|
||||
nextStencilID++;
|
||||
} else {
|
||||
// already present
|
||||
continue;
|
||||
}
|
||||
|
||||
if (tileUBOs.empty()) {
|
||||
tileUBOs.reserve(count);
|
||||
}
|
||||
|
||||
tileUBOs.emplace_back(shaders::ClipUBO{util::cast<float>(matrixForTile(tileID)), stencilID});
|
||||
}
|
||||
|
||||
if (!tileUBOs.empty()) {
|
||||
#if !defined(NDEBUG)
|
||||
const auto debugGroup = renderPass->createDebugGroup("tile-clip-masks");
|
||||
#endif
|
||||
|
||||
auto& vulkanContext = static_cast<vulkan::Context&>(context);
|
||||
vulkanContext.renderTileClippingMasks(*renderPass, staticData, tileUBOs);
|
||||
vulkanContext.renderingStats().stencilUpdates++;
|
||||
}
|
||||
|
||||
#else // !MLN_RENDER_BACKEND_METAL
|
||||
auto program = staticData.shaders->getLegacyGroup().get<ClippingMaskProgram>();
|
||||
|
||||
|
||||
@@ -278,13 +278,14 @@ void Renderer::Impl::render(const RenderTree& renderTree,
|
||||
const auto debugGroup(parameters.encoder->createDebugGroup("common-3d"));
|
||||
parameters.pass = RenderPass::Pass3D;
|
||||
|
||||
if (!parameters.staticData.depthRenderbuffer ||
|
||||
parameters.staticData.depthRenderbuffer->getSize() != parameters.staticData.backendSize) {
|
||||
parameters.staticData.depthRenderbuffer =
|
||||
parameters.context.createRenderbuffer<gfx::RenderbufferPixelType::Depth>(
|
||||
parameters.staticData.backendSize);
|
||||
}
|
||||
parameters.staticData.depthRenderbuffer->setShouldClear(true);
|
||||
// TODO is this needed?
|
||||
// if (!parameters.staticData.depthRenderbuffer ||
|
||||
// parameters.staticData.depthRenderbuffer->getSize() != parameters.staticData.backendSize) {
|
||||
// parameters.staticData.depthRenderbuffer =
|
||||
// parameters.context.createRenderbuffer<gfx::RenderbufferPixelType::Depth>(
|
||||
// parameters.staticData.backendSize);
|
||||
//}
|
||||
// parameters.staticData.depthRenderbuffer->setShouldClear(true);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
28
src/mbgl/shaders/vulkan/background.cpp
Normal file
28
src/mbgl/shaders/vulkan/background.cpp
Normal file
@@ -0,0 +1,28 @@
|
||||
#include <mbgl/shaders/vulkan/background.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<UniformBlockInfo, 2> ShaderSource<BuiltIn::BackgroundShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(BackgroundDrawableUBO), idBackgroundDrawableUBO},
|
||||
UniformBlockInfo{false, true, sizeof(BackgroundLayerUBO), idBackgroundLayerUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 1> ShaderSource<BuiltIn::BackgroundShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Float3, idBackgroundPosVertexAttribute},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 3>
|
||||
ShaderSource<BuiltIn::BackgroundPatternShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{false, true, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(BackgroundPatternDrawableUBO), idBackgroundDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(BackgroundPatternLayerUBO), idBackgroundLayerUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 1>
|
||||
ShaderSource<BuiltIn::BackgroundPatternShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Float3, idBackgroundPosVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::BackgroundPatternShader, gfx::Backend::Type::Vulkan>::textures =
|
||||
{TextureInfo{0, idBackgroundImageTexture}};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
24
src/mbgl/shaders/vulkan/circle.cpp
Normal file
24
src/mbgl/shaders/vulkan/circle.cpp
Normal file
@@ -0,0 +1,24 @@
|
||||
#include <mbgl/shaders/vulkan/circle.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<UniformBlockInfo, 4> ShaderSource<BuiltIn::CircleShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(CircleDrawableUBO), idCircleDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(CircleEvaluatedPropsUBO), idCircleEvaluatedPropsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(CircleInterpolateUBO), idCircleInterpolateUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 8> ShaderSource<BuiltIn::CircleShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idCirclePosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Float4, idCircleColorVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float2, idCircleRadiusVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float2, idCircleBlurVertexAttribute},
|
||||
AttributeInfo{4, gfx::AttributeDataType::Float2, idCircleOpacityVertexAttribute},
|
||||
AttributeInfo{5, gfx::AttributeDataType::Float4, idCircleStrokeColorVertexAttribute},
|
||||
AttributeInfo{6, gfx::AttributeDataType::Float2, idCircleStrokeWidthVertexAttribute},
|
||||
AttributeInfo{7, gfx::AttributeDataType::Float2, idCircleStrokeOpacityVertexAttribute},
|
||||
};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
10
src/mbgl/shaders/vulkan/clipping_mask.cpp
Normal file
10
src/mbgl/shaders/vulkan/clipping_mask.cpp
Normal file
@@ -0,0 +1,10 @@
|
||||
#include <mbgl/shaders/vulkan/clipping_mask.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<AttributeInfo, 1> ShaderSource<BuiltIn::ClippingMaskProgram, gfx::Backend::Type::Vulkan>::attributes =
|
||||
{AttributeInfo{0, gfx::AttributeDataType::Short2, idClippingMaskPosVertexAttribute}};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
31
src/mbgl/shaders/vulkan/collision.cpp
Normal file
31
src/mbgl/shaders/vulkan/collision.cpp
Normal file
@@ -0,0 +1,31 @@
|
||||
#include <mbgl/shaders/vulkan/collision.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<UniformBlockInfo, 1> ShaderSource<BuiltIn::CollisionBoxShader, gfx::Backend::Type::Vulkan>::uniforms =
|
||||
{
|
||||
UniformBlockInfo{true, true, sizeof(CollisionUBO), idCollisionUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 5> ShaderSource<BuiltIn::CollisionBoxShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idCollisionPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Short2, idCollisionAnchorPosVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Short2, idCollisionExtrudeVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::UShort2, idCollisionPlacedVertexAttribute},
|
||||
AttributeInfo{4, gfx::AttributeDataType::Float2, idCollisionShiftVertexAttribute},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 1>
|
||||
ShaderSource<BuiltIn::CollisionCircleShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, true, sizeof(CollisionUBO), idCollisionUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 4>
|
||||
ShaderSource<BuiltIn::CollisionCircleShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idCollisionPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Short2, idCollisionAnchorPosVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Short2, idCollisionExtrudeVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::UShort2, idCollisionPlacedVertexAttribute},
|
||||
};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
17
src/mbgl/shaders/vulkan/debug.cpp
Normal file
17
src/mbgl/shaders/vulkan/debug.cpp
Normal file
@@ -0,0 +1,17 @@
|
||||
#include <mbgl/shaders/vulkan/debug.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<UniformBlockInfo, 1> ShaderSource<BuiltIn::DebugShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, true, sizeof(DebugUBO), idDebugUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 1> ShaderSource<BuiltIn::DebugShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idDebugPosVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::DebugShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idDebugOverlayTexture},
|
||||
};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
116
src/mbgl/shaders/vulkan/fill.cpp
Normal file
116
src/mbgl/shaders/vulkan/fill.cpp
Normal file
@@ -0,0 +1,116 @@
|
||||
#include <mbgl/shaders/vulkan/fill.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<UniformBlockInfo, 3> ShaderSource<BuiltIn::FillShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(FillDrawableUBO), idFillDrawableUBO},
|
||||
UniformBlockInfo{true, false, sizeof(FillInterpolateUBO), idFillInterpolateUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillEvaluatedPropsUBO), idFillEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 3> ShaderSource<BuiltIn::FillShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idFillPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Float4, idFillColorVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float2, idFillOpacityVertexAttribute},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 4> ShaderSource<BuiltIn::FillOutlineShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(FillOutlineDrawableUBO), idFillDrawableUBO},
|
||||
UniformBlockInfo{true, false, sizeof(FillOutlineInterpolateUBO), idFillInterpolateUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillEvaluatedPropsUBO), idFillEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 3> ShaderSource<BuiltIn::FillOutlineShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idFillPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Float4, idFillOutlineColorVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float2, idFillOpacityVertexAttribute},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 5> ShaderSource<BuiltIn::FillPatternShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillPatternDrawableUBO), idFillDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillPatternTilePropsUBO), idFillTilePropsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(FillPatternInterpolateUBO), idFillInterpolateUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillEvaluatedPropsUBO), idFillEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 4> ShaderSource<BuiltIn::FillPatternShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idFillPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::UShort4, idFillPatternFromVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::UShort4, idFillPatternToVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float2, idFillOpacityVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::FillPatternShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idFillImageTexture},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 5>
|
||||
ShaderSource<BuiltIn::FillOutlinePatternShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillOutlinePatternDrawableUBO), idFillDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillOutlinePatternTilePropsUBO), idFillTilePropsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(FillOutlinePatternInterpolateUBO), idFillInterpolateUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillEvaluatedPropsUBO), idFillEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 4>
|
||||
ShaderSource<BuiltIn::FillOutlinePatternShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idFillPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::UShort4, idFillPatternFromVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::UShort4, idFillPatternToVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float2, idFillOpacityVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::FillOutlinePatternShader, gfx::Backend::Type::Vulkan>::textures =
|
||||
{
|
||||
TextureInfo{0, idFillImageTexture},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 3>
|
||||
ShaderSource<BuiltIn::FillOutlineTriangulatedShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(FillOutlineTriangulatedDrawableUBO), idFillDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillEvaluatedPropsUBO), idFillEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 2>
|
||||
ShaderSource<BuiltIn::FillOutlineTriangulatedShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idLinePosNormalVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::UByte4, idLineDataVertexAttribute},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 3> ShaderSource<BuiltIn::FillExtrusionShader, gfx::Backend::Type::Vulkan>::uniforms =
|
||||
{
|
||||
UniformBlockInfo{true, false, sizeof(FillExtrusionDrawableUBO), idFillExtrusionDrawableUBO},
|
||||
UniformBlockInfo{true, false, sizeof(FillExtrusionPropsUBO), idFillExtrusionPropsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(FillExtrusionInterpolateUBO), idFillExtrusionInterpolateUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 5> ShaderSource<BuiltIn::FillExtrusionShader, gfx::Backend::Type::Vulkan>::attributes =
|
||||
{
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idFillExtrusionPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Short4, idFillExtrusionNormalEdVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float4, idFillExtrusionColorVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float2, idFillExtrusionBaseVertexAttribute},
|
||||
AttributeInfo{4, gfx::AttributeDataType::Float2, idFillExtrusionHeightVertexAttribute},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 5>
|
||||
ShaderSource<BuiltIn::FillExtrusionPatternShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillExtrusionDrawableUBO), idFillExtrusionDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillExtrusionPropsUBO), idFillExtrusionPropsUBO},
|
||||
UniformBlockInfo{true, true, sizeof(FillExtrusionTilePropsUBO), idFillExtrusionTilePropsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(FillExtrusionInterpolateUBO), idFillExtrusionInterpolateUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 6>
|
||||
ShaderSource<BuiltIn::FillExtrusionPatternShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idFillExtrusionPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Short4, idFillExtrusionNormalEdVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float2, idFillExtrusionBaseVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float2, idFillExtrusionHeightVertexAttribute},
|
||||
AttributeInfo{4, gfx::AttributeDataType::UShort4, idFillExtrusionPatternFromVertexAttribute},
|
||||
AttributeInfo{5, gfx::AttributeDataType::UShort4, idFillExtrusionPatternToVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1>
|
||||
ShaderSource<BuiltIn::FillExtrusionPatternShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idFillExtrusionImageTexture},
|
||||
};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
32
src/mbgl/shaders/vulkan/heatmap.cpp
Normal file
32
src/mbgl/shaders/vulkan/heatmap.cpp
Normal file
@@ -0,0 +1,32 @@
|
||||
#include <mbgl/shaders/vulkan/heatmap.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<UniformBlockInfo, 3> ShaderSource<BuiltIn::HeatmapShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(HeatmapDrawableUBO), idHeatmapDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(HeatmapEvaluatedPropsUBO), idHeatmapEvaluatedPropsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(HeatmapInterpolateUBO), idHeatmapInterpolateUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 3> ShaderSource<BuiltIn::HeatmapShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idHeatmapPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Float2, idHeatmapWeightVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float2, idHeatmapRadiusVertexAttribute},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 2>
|
||||
ShaderSource<BuiltIn::HeatmapTextureShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, true, sizeof(HeatmapTexturePropsUBO), idHeatmapTexturePropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 1> ShaderSource<BuiltIn::HeatmapTextureShader, gfx::Backend::Type::Vulkan>::attributes =
|
||||
{
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idHeatmapPosVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 2> ShaderSource<BuiltIn::HeatmapTextureShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idHeatmapImageTexture},
|
||||
TextureInfo{1, idHeatmapColorRampTexture},
|
||||
};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
32
src/mbgl/shaders/vulkan/hillshade.cpp
Normal file
32
src/mbgl/shaders/vulkan/hillshade.cpp
Normal file
@@ -0,0 +1,32 @@
|
||||
#include <mbgl/shaders/vulkan/hillshade.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<UniformBlockInfo, 1>
|
||||
ShaderSource<BuiltIn::HillshadePrepareShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, true, sizeof(HillshadePrepareDrawableUBO), idHillshadePrepareDrawableUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 2>
|
||||
ShaderSource<BuiltIn::HillshadePrepareShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idHillshadePosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Short2, idHillshadeTexturePosVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::HillshadePrepareShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idHillshadeImageTexture},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 2> ShaderSource<BuiltIn::HillshadeShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, true, sizeof(HillshadeDrawableUBO), idHillshadeDrawableUBO},
|
||||
UniformBlockInfo{false, true, sizeof(HillshadeEvaluatedPropsUBO), idHillshadeEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 2> ShaderSource<BuiltIn::HillshadeShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idHillshadePosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Short2, idHillshadeTexturePosVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::HillshadeShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idHillshadeImageTexture},
|
||||
};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
90
src/mbgl/shaders/vulkan/line.cpp
Normal file
90
src/mbgl/shaders/vulkan/line.cpp
Normal file
@@ -0,0 +1,90 @@
|
||||
#include <mbgl/shaders/vulkan/line.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<UniformBlockInfo, 4> ShaderSource<BuiltIn::LineShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, true, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(LineDrawableUBO), idLineDrawableUBO},
|
||||
UniformBlockInfo{true, false, sizeof(LineInterpolationUBO), idLineInterpolationUBO},
|
||||
UniformBlockInfo{true, true, sizeof(LineEvaluatedPropsUBO), idLineEvaluatedPropsUBO},
|
||||
};
|
||||
|
||||
const std::array<AttributeInfo, 8> ShaderSource<BuiltIn::LineShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idLinePosNormalVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::UByte4, idLineDataVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float4, idLineColorVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float2, idLineBlurVertexAttribute},
|
||||
AttributeInfo{4, gfx::AttributeDataType::Float2, idLineOpacityVertexAttribute},
|
||||
AttributeInfo{5, gfx::AttributeDataType::Float2, idLineGapWidthVertexAttribute},
|
||||
AttributeInfo{6, gfx::AttributeDataType::Float2, idLineOffsetVertexAttribute},
|
||||
AttributeInfo{7, gfx::AttributeDataType::Float2, idLineWidthVertexAttribute},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 4> ShaderSource<BuiltIn::LineGradientShader, gfx::Backend::Type::Vulkan>::uniforms =
|
||||
{
|
||||
UniformBlockInfo{true, true, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(LineDrawableUBO), idLineDrawableUBO},
|
||||
UniformBlockInfo{true, false, sizeof(LineInterpolationUBO), idLineInterpolationUBO},
|
||||
UniformBlockInfo{true, true, sizeof(LineEvaluatedPropsUBO), idLineEvaluatedPropsUBO},
|
||||
};
|
||||
|
||||
const std::array<AttributeInfo, 7> ShaderSource<BuiltIn::LineGradientShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idLinePosNormalVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::UByte4, idLineDataVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float2, idLineBlurVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float2, idLineOpacityVertexAttribute},
|
||||
AttributeInfo{4, gfx::AttributeDataType::Float2, idLineGapWidthVertexAttribute},
|
||||
AttributeInfo{5, gfx::AttributeDataType::Float2, idLineOffsetVertexAttribute},
|
||||
AttributeInfo{6, gfx::AttributeDataType::Float2, idLineWidthVertexAttribute},
|
||||
};
|
||||
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::LineGradientShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idLineImageTexture},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 5> ShaderSource<BuiltIn::LinePatternShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, true, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, true, sizeof(LinePatternDrawableUBO), idLineDrawableUBO},
|
||||
UniformBlockInfo{true, false, sizeof(LinePatternInterpolationUBO), idLineInterpolationUBO},
|
||||
UniformBlockInfo{true, true, sizeof(LinePatternTilePropertiesUBO), idLineTilePropertiesUBO},
|
||||
UniformBlockInfo{true, true, sizeof(LineEvaluatedPropsUBO), idLineEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 9> ShaderSource<BuiltIn::LinePatternShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idLinePosNormalVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::UByte4, idLineDataVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float2, idLineBlurVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float2, idLineOpacityVertexAttribute},
|
||||
AttributeInfo{4, gfx::AttributeDataType::Float2, idLineGapWidthVertexAttribute},
|
||||
AttributeInfo{5, gfx::AttributeDataType::Float2, idLineOffsetVertexAttribute},
|
||||
AttributeInfo{6, gfx::AttributeDataType::Float2, idLineWidthVertexAttribute},
|
||||
AttributeInfo{7, gfx::AttributeDataType::UShort4, idLinePatternFromVertexAttribute},
|
||||
AttributeInfo{8, gfx::AttributeDataType::UShort4, idLinePatternToVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::LinePatternShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idLineImageTexture},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 4> ShaderSource<BuiltIn::LineSDFShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, true, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, true, sizeof(LineSDFDrawableUBO), idLineDrawableUBO},
|
||||
UniformBlockInfo{true, false, sizeof(LineSDFInterpolationUBO), idLineInterpolationUBO},
|
||||
UniformBlockInfo{true, true, sizeof(LineEvaluatedPropsUBO), idLineEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 9> ShaderSource<BuiltIn::LineSDFShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idLinePosNormalVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::UByte4, idLineDataVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float4, idLineColorVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float2, idLineBlurVertexAttribute},
|
||||
AttributeInfo{4, gfx::AttributeDataType::Float2, idLineOpacityVertexAttribute},
|
||||
AttributeInfo{5, gfx::AttributeDataType::Float2, idLineGapWidthVertexAttribute},
|
||||
AttributeInfo{6, gfx::AttributeDataType::Float2, idLineOffsetVertexAttribute},
|
||||
AttributeInfo{7, gfx::AttributeDataType::Float2, idLineWidthVertexAttribute},
|
||||
AttributeInfo{8, gfx::AttributeDataType::Float2, idLineFloorWidthVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::LineSDFShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idLineImageTexture},
|
||||
};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
20
src/mbgl/shaders/vulkan/raster.cpp
Normal file
20
src/mbgl/shaders/vulkan/raster.cpp
Normal file
@@ -0,0 +1,20 @@
|
||||
#include <mbgl/shaders/vulkan/raster.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<UniformBlockInfo, 2> ShaderSource<BuiltIn::RasterShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(RasterDrawableUBO), idRasterDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(RasterEvaluatedPropsUBO), idRasterEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 2> ShaderSource<BuiltIn::RasterShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short2, idRasterPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Short2, idRasterTexturePosVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 2> ShaderSource<BuiltIn::RasterShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idRasterImage0Texture},
|
||||
TextureInfo{1, idRasterImage1Texture},
|
||||
};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
269
src/mbgl/shaders/vulkan/shader_program.cpp
Normal file
269
src/mbgl/shaders/vulkan/shader_program.cpp
Normal file
@@ -0,0 +1,269 @@
|
||||
#include <mbgl/shaders/vulkan/shader_program.hpp>
|
||||
|
||||
#include <mbgl/gfx/render_pass.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/vulkan/renderer_backend.hpp>
|
||||
#include <mbgl/vulkan/renderable_resource.hpp>
|
||||
#include <mbgl/vulkan/uniform_block.hpp>
|
||||
#include <mbgl/vulkan/uniform_buffer.hpp>
|
||||
#include <mbgl/vulkan/vertex_attribute.hpp>
|
||||
#include <mbgl/programs/program_parameters.hpp>
|
||||
#include <mbgl/shaders/shader_manifest.hpp>
|
||||
#include <mbgl/shaders/vulkan/common.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
|
||||
#include <cstring>
|
||||
#include <utility>
|
||||
#include <algorithm>
|
||||
|
||||
#include <glslang/Public/ShaderLang.h>
|
||||
#include <glslang/Public/ResourceLimits.h>
|
||||
#include <SPIRV/GlslangToSpv.h>
|
||||
|
||||
using namespace std::string_literals;
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
namespace vulkan {
|
||||
|
||||
ShaderProgram::ShaderProgram(const std::string& name,
|
||||
const std::string_view& vertex,
|
||||
const std::string_view& fragment,
|
||||
const ProgramParameters& programParameters,
|
||||
const mbgl::unordered_map<std::string, std::string>& additionalDefines,
|
||||
RendererBackend& backend_)
|
||||
: ShaderProgramBase(),
|
||||
shaderName(name),
|
||||
backend(backend_) {
|
||||
constexpr auto targetClientVersion = glslang::EShTargetVulkan_1_0;
|
||||
constexpr auto targetLanguageVersion = glslang::EShTargetSpv_1_0;
|
||||
constexpr auto defaultVersion = 450;
|
||||
constexpr auto messages = EShMsgSpvRules | EShMsgVulkanRules;
|
||||
const auto defaultResources = GetDefaultResources();
|
||||
|
||||
std::string defineStr = programParameters.getDefinesString() + "\n\n";
|
||||
for (const auto& define : additionalDefines) {
|
||||
defineStr += "#define " + define.first + " " + define.second + "\n";
|
||||
}
|
||||
|
||||
const auto compileGlsl = [&](const EShLanguage& language, const std::string_view& data, const char* prelude) {
|
||||
glslang::TShader glslShader(language);
|
||||
|
||||
const auto preamble = defineStr + "\n" + prelude;
|
||||
const char* shaderData = data.data();
|
||||
const int shaderDataSize = data.size();
|
||||
|
||||
glslShader.setPreamble(preamble.c_str());
|
||||
glslShader.setStringsWithLengths(&shaderData, &shaderDataSize, 1);
|
||||
glslShader.setEnvClient(glslang::EShClientVulkan, targetClientVersion);
|
||||
glslShader.setEnvTarget(glslang::EShTargetSpv, targetLanguageVersion);
|
||||
glslShader.setEntryPoint("main");
|
||||
|
||||
if (!glslShader.parse(defaultResources, defaultVersion, ENoProfile, false, true, messages)) {
|
||||
mbgl::Log::Error(mbgl::Event::Shader, shaderName + " - " + glslShader.getInfoLog());
|
||||
return std::vector<uint32_t>();
|
||||
}
|
||||
|
||||
glslang::TProgram glslProgram;
|
||||
glslProgram.addShader(&glslShader);
|
||||
|
||||
if (!glslProgram.link(messages)) {
|
||||
mbgl::Log::Error(mbgl::Event::Shader, shaderName + " - " + glslProgram.getInfoLog());
|
||||
return std::vector<uint32_t>();
|
||||
}
|
||||
|
||||
const auto intermediate = glslProgram.getIntermediate(language);
|
||||
|
||||
std::vector<uint32_t> spirv;
|
||||
glslang::GlslangToSpv(*intermediate, spirv);
|
||||
|
||||
return spirv;
|
||||
};
|
||||
|
||||
const auto& vertexSpirv = compileGlsl(
|
||||
EShLanguage::EShLangVertex,
|
||||
vertex,
|
||||
shaders::ShaderSource<shaders::BuiltIn::Prelude, gfx::Backend::Type::Vulkan>::vertex);
|
||||
const auto& fragmentSpirv = compileGlsl(
|
||||
EShLanguage::EShLangFragment,
|
||||
fragment,
|
||||
shaders::ShaderSource<shaders::BuiltIn::Prelude, gfx::Backend::Type::Vulkan>::fragment);
|
||||
|
||||
if (vertexSpirv.empty() || fragmentSpirv.empty()) return;
|
||||
|
||||
const auto& device = backend.getDevice();
|
||||
|
||||
vertexShader = device->createShaderModuleUnique(
|
||||
vk::ShaderModuleCreateInfo(vk::ShaderModuleCreateFlags(), vertexSpirv));
|
||||
fragmentShader = device->createShaderModuleUnique(
|
||||
vk::ShaderModuleCreateInfo(vk::ShaderModuleCreateFlags(), fragmentSpirv));
|
||||
|
||||
backend.setDebugName(vertexShader.get(), shaderName + ".vert");
|
||||
backend.setDebugName(fragmentShader.get(), shaderName + ".frag");
|
||||
}
|
||||
|
||||
ShaderProgram::~ShaderProgram() noexcept = default;
|
||||
|
||||
const vk::UniquePipeline& ShaderProgram::getPipeline(const PipelineInfo& pipelineInfo) {
|
||||
auto& pipeline = pipelines[pipelineInfo.hash()];
|
||||
if (pipeline) return pipeline;
|
||||
|
||||
const auto vertexInputState = vk::PipelineVertexInputStateCreateInfo()
|
||||
.setVertexBindingDescriptions(pipelineInfo.inputBindings)
|
||||
.setVertexAttributeDescriptions(pipelineInfo.inputAttributes);
|
||||
|
||||
const auto inputAssemblyState = vk::PipelineInputAssemblyStateCreateInfo().setTopology(pipelineInfo.topology);
|
||||
|
||||
const auto renderableExtent = pipelineInfo.viewExtent;
|
||||
|
||||
const vk::Viewport viewportExtent(0.0f, 0.0f, renderableExtent.width, renderableExtent.height, 0.0f, 1.0f);
|
||||
const vk::Rect2D scissorRect({}, {renderableExtent.width, renderableExtent.height});
|
||||
|
||||
const auto viewportState = vk::PipelineViewportStateCreateInfo()
|
||||
.setViewportCount(1)
|
||||
.setPViewports(&viewportExtent)
|
||||
.setScissorCount(1)
|
||||
.setPScissors(&scissorRect);
|
||||
|
||||
const auto rasterState = vk::PipelineRasterizationStateCreateInfo()
|
||||
.setCullMode(pipelineInfo.cullMode)
|
||||
.setFrontFace(pipelineInfo.frontFace)
|
||||
.setPolygonMode(pipelineInfo.polygonMode)
|
||||
.setLineWidth(1.0f);
|
||||
|
||||
const auto multisampleState = vk::PipelineMultisampleStateCreateInfo().setRasterizationSamples(
|
||||
vk::SampleCountFlagBits::e1);
|
||||
|
||||
const auto stencilState = vk::StencilOpState()
|
||||
.setCompareOp(pipelineInfo.stencilFunction)
|
||||
.setPassOp(pipelineInfo.stencilPass)
|
||||
.setFailOp(pipelineInfo.stencilFail)
|
||||
.setDepthFailOp(pipelineInfo.stencilDepthFail);
|
||||
|
||||
const auto depthStencilState = vk::PipelineDepthStencilStateCreateInfo()
|
||||
.setDepthTestEnable(pipelineInfo.depthTest)
|
||||
.setDepthWriteEnable(pipelineInfo.depthWrite)
|
||||
.setDepthBoundsTestEnable(false)
|
||||
.setMinDepthBounds(0.0f)
|
||||
.setMaxDepthBounds(1.0f)
|
||||
.setDepthCompareOp(pipelineInfo.depthFunction)
|
||||
.setStencilTestEnable(pipelineInfo.stencilTest)
|
||||
.setFront(stencilState)
|
||||
.setBack(stencilState);
|
||||
|
||||
const auto colorBlendAttachments = vk::PipelineColorBlendAttachmentState()
|
||||
.setBlendEnable(pipelineInfo.colorBlend)
|
||||
.setColorBlendOp(pipelineInfo.colorBlendFunction)
|
||||
.setSrcColorBlendFactor(pipelineInfo.srcBlendFactor)
|
||||
.setDstColorBlendFactor(pipelineInfo.dstBlendFactor)
|
||||
.setAlphaBlendOp(pipelineInfo.colorBlendFunction)
|
||||
.setSrcAlphaBlendFactor(pipelineInfo.srcBlendFactor)
|
||||
.setDstAlphaBlendFactor(pipelineInfo.dstBlendFactor)
|
||||
.setColorWriteMask(pipelineInfo.colorMask);
|
||||
|
||||
const auto colorBlendState = vk::PipelineColorBlendStateCreateInfo()
|
||||
.setAttachmentCount(1)
|
||||
.setPAttachments(&colorBlendAttachments)
|
||||
.setLogicOpEnable(VK_FALSE)
|
||||
.setLogicOp(vk::LogicOp::eCopy);
|
||||
|
||||
// values available for core 1.0
|
||||
// vk::DynamicState::eViewport,
|
||||
// vk::DynamicState::eScissor,
|
||||
// vk::DynamicState::eLineWidth,
|
||||
// vk::DynamicState::eStencilCompareMask,
|
||||
// vk::DynamicState::eStencilWriteMask,
|
||||
// vk::DynamicState::eStencilReference,
|
||||
// vk::DynamicState::eBlendConstants,
|
||||
// vk::DynamicState::eDepthBias,
|
||||
// vk::DynamicState::eDepthBounds,
|
||||
|
||||
const auto& dynamicValues = pipelineInfo.getDynamicStates();
|
||||
const vk::PipelineDynamicStateCreateInfo dynamicState({}, dynamicValues);
|
||||
|
||||
const auto& device = backend.getDevice();
|
||||
auto& context = static_cast<Context&>(backend.getContext());
|
||||
const auto& pipelineLayout = pipelineInfo.usePushConstants ? context.getPushConstantPipelineLayout()
|
||||
: context.getGeneralPipelineLayout();
|
||||
|
||||
const std::array<vk::PipelineShaderStageCreateInfo, 2> shaderStages = {
|
||||
vk::PipelineShaderStageCreateInfo()
|
||||
.setStage(vk::ShaderStageFlagBits::eVertex)
|
||||
.setModule(vertexShader.get())
|
||||
.setPName("main"),
|
||||
|
||||
vk::PipelineShaderStageCreateInfo()
|
||||
.setStage(vk::ShaderStageFlagBits::eFragment)
|
||||
.setModule(fragmentShader.get())
|
||||
.setPName("main")};
|
||||
|
||||
const auto pipelineCreateInfo = vk::GraphicsPipelineCreateInfo()
|
||||
.setStages(shaderStages)
|
||||
.setPVertexInputState(&vertexInputState)
|
||||
.setPInputAssemblyState(&inputAssemblyState)
|
||||
.setPViewportState(&viewportState)
|
||||
.setPRasterizationState(&rasterState)
|
||||
.setPMultisampleState(&multisampleState)
|
||||
.setPDepthStencilState(&depthStencilState)
|
||||
.setPColorBlendState(&colorBlendState)
|
||||
.setPDynamicState(&dynamicState)
|
||||
.setLayout(pipelineLayout.get())
|
||||
.setRenderPass(pipelineInfo.renderPass);
|
||||
|
||||
pipeline = std::move(device->createGraphicsPipelineUnique(nullptr, pipelineCreateInfo).value);
|
||||
backend.setDebugName(pipeline.get(), shaderName + "_pipeline");
|
||||
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
bool ShaderProgram::hasTextures() const {
|
||||
return std::any_of(
|
||||
textureBindings.begin(), textureBindings.end(), [](const auto& texture) { return texture.has_value(); });
|
||||
}
|
||||
|
||||
void ShaderProgram::initAttribute(const shaders::AttributeInfo& info) {
|
||||
const auto index = static_cast<int>(info.index);
|
||||
#if !defined(NDEBUG)
|
||||
// Indexes must be unique, if there's a conflict check the `attributes` array in the shader
|
||||
vertexAttributes.visitAttributes([&](const gfx::VertexAttribute& attrib) { assert(attrib.getIndex() != index); });
|
||||
instanceAttributes.visitAttributes([&](const gfx::VertexAttribute& attrib) { assert(attrib.getIndex() != index); });
|
||||
uniformBlocks.visit([&](const gfx::UniformBlock& block) { assert(block.getIndex() != index); });
|
||||
#endif
|
||||
vertexAttributes.set(info.id, index, info.dataType, 1);
|
||||
}
|
||||
|
||||
void ShaderProgram::initInstanceAttribute(const shaders::AttributeInfo& info) {
|
||||
// Index is the block index of the instance attribute
|
||||
const auto index = static_cast<int>(info.index);
|
||||
#if !defined(NDEBUG)
|
||||
// Indexes must not be reused by regular attributes or uniform blocks
|
||||
// More than one instance attribute can have the same index, if they share the block
|
||||
vertexAttributes.visitAttributes([&](const gfx::VertexAttribute& attrib) { assert(attrib.getIndex() != index); });
|
||||
uniformBlocks.visit([&](const gfx::UniformBlock& block) { assert(block.getIndex() != index); });
|
||||
#endif
|
||||
instanceAttributes.set(info.id, index, info.dataType, 1);
|
||||
}
|
||||
|
||||
void ShaderProgram::initUniformBlock(const shaders::UniformBlockInfo& info) {
|
||||
const auto index = static_cast<int>(info.index);
|
||||
#if !defined(NDEBUG)
|
||||
// Indexes must be unique, if there's a conflict check the `attributes` array in the shader
|
||||
uniformBlocks.visit([&](const gfx::UniformBlock& block) { assert(block.getIndex() != index); });
|
||||
#endif
|
||||
if (const auto& block_ = uniformBlocks.set(info.id, index, info.size)) {
|
||||
auto& block = static_cast<UniformBlock&>(*block_);
|
||||
block.setBindVertex(info.vertex);
|
||||
block.setBindFragment(info.fragment);
|
||||
}
|
||||
}
|
||||
|
||||
void ShaderProgram::initTexture(const shaders::TextureInfo& info) {
|
||||
assert(info.id < textureBindings.size());
|
||||
if (info.id >= textureBindings.size()) {
|
||||
return;
|
||||
}
|
||||
textureBindings[info.id] = info.index;
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
98
src/mbgl/shaders/vulkan/symbol.cpp
Normal file
98
src/mbgl/shaders/vulkan/symbol.cpp
Normal file
@@ -0,0 +1,98 @@
|
||||
#include <mbgl/shaders/vulkan/symbol.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace shaders {
|
||||
|
||||
const std::array<UniformBlockInfo, 5> ShaderSource<BuiltIn::SymbolIconShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(SymbolDrawableUBO), idSymbolDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(SymbolTilePropsUBO), idSymbolTilePropsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(SymbolInterpolateUBO), idSymbolInterpolateUBO},
|
||||
UniformBlockInfo{false, true, sizeof(SymbolEvaluatedPropsUBO), idSymbolEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 6> ShaderSource<BuiltIn::SymbolIconShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short4, idSymbolPosOffsetVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::UShort4, idSymbolDataVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Short4, idSymbolPixelOffsetVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float3, idSymbolProjectedPosVertexAttribute},
|
||||
AttributeInfo{4, gfx::AttributeDataType::Float, idSymbolFadeOpacityVertexAttribute},
|
||||
AttributeInfo{5, gfx::AttributeDataType::Float, idSymbolOpacityVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::SymbolIconShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idSymbolImageTexture},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 5> ShaderSource<BuiltIn::SymbolSDFIconShader, gfx::Backend::Type::Vulkan>::uniforms =
|
||||
{
|
||||
UniformBlockInfo{true, false, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, true, sizeof(SymbolDrawableUBO), idSymbolDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(SymbolTilePropsUBO), idSymbolTilePropsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(SymbolInterpolateUBO), idSymbolInterpolateUBO},
|
||||
UniformBlockInfo{false, true, sizeof(SymbolEvaluatedPropsUBO), idSymbolEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 10> ShaderSource<BuiltIn::SymbolSDFIconShader, gfx::Backend::Type::Vulkan>::attributes =
|
||||
{
|
||||
// always attributes
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short4, idSymbolPosOffsetVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::UShort4, idSymbolDataVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Short4, idSymbolPixelOffsetVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float3, idSymbolProjectedPosVertexAttribute},
|
||||
AttributeInfo{4, gfx::AttributeDataType::Float2, idSymbolFadeOpacityVertexAttribute},
|
||||
|
||||
// sometimes uniforms
|
||||
AttributeInfo{5, gfx::AttributeDataType::Float4, idSymbolColorVertexAttribute},
|
||||
AttributeInfo{6, gfx::AttributeDataType::Float4, idSymbolHaloColorVertexAttribute},
|
||||
AttributeInfo{7, gfx::AttributeDataType::Float2, idSymbolOpacityVertexAttribute},
|
||||
AttributeInfo{8, gfx::AttributeDataType::Float2, idSymbolHaloWidthVertexAttribute},
|
||||
AttributeInfo{9, gfx::AttributeDataType::Float2, idSymbolHaloBlurVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::SymbolSDFIconShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idSymbolImageTexture},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 5>
|
||||
ShaderSource<BuiltIn::SymbolTextAndIconShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(GlobalPaintParamsUBO), idGlobalPaintParamsUBO},
|
||||
UniformBlockInfo{true, true, sizeof(SymbolDrawableUBO), idSymbolDrawableUBO},
|
||||
UniformBlockInfo{true, true, sizeof(SymbolTilePropsUBO), idSymbolTilePropsUBO},
|
||||
UniformBlockInfo{true, false, sizeof(SymbolInterpolateUBO), idSymbolInterpolateUBO},
|
||||
UniformBlockInfo{false, true, sizeof(SymbolEvaluatedPropsUBO), idSymbolEvaluatedPropsUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 9>
|
||||
ShaderSource<BuiltIn::SymbolTextAndIconShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
// always attributes
|
||||
AttributeInfo{0, gfx::AttributeDataType::Short4, idSymbolPosOffsetVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::UShort4, idSymbolDataVertexAttribute},
|
||||
AttributeInfo{2, gfx::AttributeDataType::Float3, idSymbolProjectedPosVertexAttribute},
|
||||
AttributeInfo{3, gfx::AttributeDataType::Float2, idSymbolFadeOpacityVertexAttribute},
|
||||
|
||||
// sometimes uniforms
|
||||
AttributeInfo{4, gfx::AttributeDataType::Float4, idSymbolColorVertexAttribute},
|
||||
AttributeInfo{5, gfx::AttributeDataType::Float4, idSymbolHaloColorVertexAttribute},
|
||||
AttributeInfo{6, gfx::AttributeDataType::Float2, idSymbolOpacityVertexAttribute},
|
||||
AttributeInfo{7, gfx::AttributeDataType::Float2, idSymbolHaloWidthVertexAttribute},
|
||||
AttributeInfo{8, gfx::AttributeDataType::Float2, idSymbolHaloBlurVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 2> ShaderSource<BuiltIn::SymbolTextAndIconShader, gfx::Backend::Type::Vulkan>::textures =
|
||||
{
|
||||
TextureInfo{0, idSymbolImageTexture},
|
||||
TextureInfo{1, idSymbolImageIconTexture},
|
||||
};
|
||||
|
||||
const std::array<UniformBlockInfo, 2>
|
||||
ShaderSource<BuiltIn::CustomSymbolIconShader, gfx::Backend::Type::Vulkan>::uniforms = {
|
||||
UniformBlockInfo{true, false, sizeof(CustomSymbolIconDrawableUBO), idCustomSymbolDrawableUBO},
|
||||
UniformBlockInfo{true, false, sizeof(CustomSymbolIconParametersUBO), idCustomSymbolParametersUBO},
|
||||
};
|
||||
const std::array<AttributeInfo, 2>
|
||||
ShaderSource<BuiltIn::CustomSymbolIconShader, gfx::Backend::Type::Vulkan>::attributes = {
|
||||
// always attributes
|
||||
AttributeInfo{0, gfx::AttributeDataType::Float2, idCustomSymbolPosVertexAttribute},
|
||||
AttributeInfo{1, gfx::AttributeDataType::Float2, idCustomSymbolTexVertexAttribute},
|
||||
};
|
||||
const std::array<TextureInfo, 1> ShaderSource<BuiltIn::CustomSymbolIconShader, gfx::Backend::Type::Vulkan>::textures = {
|
||||
TextureInfo{0, idCustomSymbolImageTexture},
|
||||
};
|
||||
|
||||
} // namespace shaders
|
||||
} // namespace mbgl
|
||||
164
src/mbgl/vulkan/buffer_resource.cpp
Normal file
164
src/mbgl/vulkan/buffer_resource.cpp
Normal file
@@ -0,0 +1,164 @@
|
||||
#include <mbgl/vulkan/buffer_resource.hpp>
|
||||
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/vulkan/renderer_backend.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
bool BufferAllocation::create(const VmaAllocationCreateInfo& allocInfo, const vk::BufferCreateInfo& bufferInfo) {
|
||||
VkResult result = vmaCreateBuffer(
|
||||
allocator, reinterpret_cast<const VkBufferCreateInfo*>(&bufferInfo), &allocInfo, &buffer, &allocation, nullptr);
|
||||
|
||||
if (result != VK_SUCCESS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void BufferAllocation::destroy() {
|
||||
if (mappedBuffer) vmaUnmapMemory(allocator, allocation);
|
||||
vmaDestroyBuffer(allocator, buffer, allocation);
|
||||
mappedBuffer = nullptr;
|
||||
}
|
||||
|
||||
void BufferAllocation::setName([[maybe_unused]] const std::string& name) const {
|
||||
#ifdef ENABLE_VMA_DEBUG
|
||||
if (allocation) {
|
||||
vmaSetAllocationName(allocator, allocation, name.data());
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
BufferResource::BufferResource(
|
||||
Context& context_, const void* data, std::size_t size_, std::uint32_t usage_, bool persistent_)
|
||||
: context(context_),
|
||||
size(size_),
|
||||
usage(usage_),
|
||||
persistent(persistent_) {
|
||||
const auto& allocator = context.getBackend().getAllocator();
|
||||
|
||||
std::size_t totalSize = size;
|
||||
|
||||
// TODO -> check avg minUniformBufferOffsetAlignment vs individual buffers
|
||||
if (usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) {
|
||||
const auto& backend = context.getBackend();
|
||||
const auto& deviceProps = backend.getDeviceProperties();
|
||||
const auto& align = deviceProps.limits.minUniformBufferOffsetAlignment;
|
||||
bufferWindowSize = (size + align - 1) & ~(align - 1);
|
||||
|
||||
assert(bufferWindowSize != 0);
|
||||
|
||||
totalSize = bufferWindowSize * backend.getMaxFrames();
|
||||
}
|
||||
|
||||
const auto bufferInfo = vk::BufferCreateInfo()
|
||||
.setSize(totalSize)
|
||||
.setUsage(vk::BufferUsageFlags(usage))
|
||||
.setSharingMode(vk::SharingMode::eExclusive);
|
||||
|
||||
VmaAllocationCreateInfo allocationInfo = {};
|
||||
|
||||
allocationInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST;
|
||||
allocationInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
|
||||
allocationInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
|
||||
|
||||
bufferAllocation = std::make_shared<BufferAllocation>(allocator);
|
||||
if (!bufferAllocation->create(allocationInfo, bufferInfo)) {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Vulkan buffer allocation failed");
|
||||
return;
|
||||
}
|
||||
|
||||
vmaMapMemory(allocator, bufferAllocation->allocation, &bufferAllocation->mappedBuffer);
|
||||
|
||||
if (data) {
|
||||
raw.resize(size);
|
||||
std::memcpy(raw.data(), data, size);
|
||||
std::memcpy(static_cast<uint8_t*>(bufferAllocation->mappedBuffer) + getVulkanBufferOffset(), data, size);
|
||||
}
|
||||
|
||||
if (isValid()) {
|
||||
auto& stats = context.renderingStats();
|
||||
stats.numBuffers++;
|
||||
stats.memBuffers += totalSize;
|
||||
stats.totalBuffers++;
|
||||
|
||||
stats.totalBufferObjs++;
|
||||
}
|
||||
}
|
||||
|
||||
BufferResource::BufferResource(BufferResource&& other) noexcept
|
||||
: context(other.context),
|
||||
raw(std::move(other.raw)),
|
||||
size(other.size),
|
||||
usage(other.usage),
|
||||
persistent(other.persistent),
|
||||
bufferAllocation(std::move(other.bufferAllocation)),
|
||||
bufferWindowSize(other.bufferWindowSize) {
|
||||
other.bufferAllocation = nullptr;
|
||||
}
|
||||
|
||||
BufferResource::~BufferResource() noexcept {
|
||||
if (isValid()) {
|
||||
context.renderingStats().numBuffers--;
|
||||
context.renderingStats().memBuffers -= size;
|
||||
}
|
||||
|
||||
if (!bufferAllocation) return;
|
||||
|
||||
context.enqueueDeletion([allocation = std::move(bufferAllocation)](const auto&) mutable { allocation.reset(); });
|
||||
}
|
||||
|
||||
BufferResource BufferResource::clone() const {
|
||||
return {context, contents(), size, usage, persistent};
|
||||
}
|
||||
|
||||
BufferResource& BufferResource::operator=(BufferResource&& other) noexcept {
|
||||
assert(&context == &other.context);
|
||||
if (isValid()) {
|
||||
context.renderingStats().numBuffers--;
|
||||
context.renderingStats().memBuffers -= size;
|
||||
};
|
||||
raw = std::move(other.raw);
|
||||
size = other.size;
|
||||
usage = other.usage;
|
||||
persistent = other.persistent;
|
||||
bufferAllocation = std::move(other.bufferAllocation);
|
||||
bufferWindowSize = other.bufferWindowSize;
|
||||
return *this;
|
||||
}
|
||||
|
||||
void BufferResource::update(const void* newData, std::size_t updateSize, std::size_t offset) noexcept {
|
||||
assert(size >= 0 && updateSize + offset <= size);
|
||||
updateSize = std::min(updateSize, size - offset);
|
||||
if (updateSize <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto& stats = context.renderingStats();
|
||||
|
||||
std::memcpy(raw.data() + offset, newData, updateSize);
|
||||
std::memcpy(
|
||||
static_cast<uint8_t*>(bufferAllocation->mappedBuffer) + getVulkanBufferOffset() + offset, newData, updateSize);
|
||||
stats.bufferUpdateBytes += updateSize;
|
||||
|
||||
stats.bufferUpdates++;
|
||||
version++;
|
||||
}
|
||||
|
||||
std::size_t BufferResource::getVulkanBufferOffset() const noexcept {
|
||||
if (bufferWindowSize > 0) return 0;
|
||||
|
||||
return context.getCurrentFrameResourceIndex() * bufferWindowSize;
|
||||
}
|
||||
|
||||
std::size_t BufferResource::getVulkanBufferSize() const noexcept {
|
||||
return bufferWindowSize > 0 ? bufferWindowSize : size;
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
42
src/mbgl/vulkan/command_encoder.cpp
Normal file
42
src/mbgl/vulkan/command_encoder.cpp
Normal file
@@ -0,0 +1,42 @@
|
||||
#include <mbgl/vulkan/command_encoder.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/vulkan/renderable_resource.hpp>
|
||||
#include <mbgl/vulkan/upload_pass.hpp>
|
||||
#include <mbgl/vulkan/render_pass.hpp>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
CommandEncoder::CommandEncoder(Context& context_, const vk::UniqueCommandBuffer& buffer_)
|
||||
: context(context_),
|
||||
commandBuffer(buffer_) {}
|
||||
|
||||
CommandEncoder::~CommandEncoder() {}
|
||||
|
||||
std::unique_ptr<gfx::UploadPass> CommandEncoder::createUploadPass(const char* name, gfx::Renderable& renderable) {
|
||||
return std::make_unique<UploadPass>(renderable, *this, name);
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::RenderPass> CommandEncoder::createRenderPass(const char* name,
|
||||
const gfx::RenderPassDescriptor& descriptor) {
|
||||
return std::make_unique<RenderPass>(*this, name, descriptor);
|
||||
}
|
||||
|
||||
void CommandEncoder::present(gfx::Renderable&) {}
|
||||
|
||||
void CommandEncoder::pushDebugGroup(const char* name) {
|
||||
pushDebugGroup(name, {});
|
||||
}
|
||||
|
||||
void CommandEncoder::pushDebugGroup(const char* name, const std::array<float, 4>& color) {
|
||||
context.getBackend().beginDebugLabel(commandBuffer.get(), name, color);
|
||||
}
|
||||
|
||||
void CommandEncoder::popDebugGroup() {
|
||||
context.getBackend().endDebugLabel(commandBuffer.get());
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
560
src/mbgl/vulkan/context.cpp
Normal file
560
src/mbgl/vulkan/context.cpp
Normal file
@@ -0,0 +1,560 @@
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
|
||||
#include <mbgl/gfx/shader_registry.hpp>
|
||||
#include <mbgl/programs/program_parameters.hpp>
|
||||
#include <mbgl/renderer/paint_parameters.hpp>
|
||||
#include <mbgl/renderer/render_static_data.hpp>
|
||||
#include <mbgl/renderer/render_target.hpp>
|
||||
#include <mbgl/vulkan/command_encoder.hpp>
|
||||
#include <mbgl/vulkan/drawable_builder.hpp>
|
||||
#include <mbgl/vulkan/offscreen_texture.hpp>
|
||||
#include <mbgl/vulkan/layer_group.hpp>
|
||||
#include <mbgl/vulkan/tile_layer_group.hpp>
|
||||
#include <mbgl/vulkan/renderable_resource.hpp>
|
||||
#include <mbgl/vulkan/render_pass.hpp>
|
||||
#include <mbgl/vulkan/texture2d.hpp>
|
||||
#include <mbgl/vulkan/vertex_attribute.hpp>
|
||||
#include <mbgl/shaders/vulkan/shader_program.hpp>
|
||||
#include <mbgl/shaders/vulkan/clipping_mask.hpp>
|
||||
#include <mbgl/util/traits.hpp>
|
||||
#include <mbgl/util/std.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
#include <mbgl/util/thread_pool.hpp>
|
||||
#include <mbgl/util/hash.hpp>
|
||||
|
||||
#include <glslang/Public/ShaderLang.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
#ifndef MLN_VULKAN_DESCRIPTOR_POOL_SIZE
|
||||
#define MLN_VULKAN_DESCRIPTOR_POOL_SIZE 10000
|
||||
#endif
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
// Maximum number of vertex attributes, per vertex descriptor
|
||||
// 32 on most devices (~30% Android use 16),
|
||||
// per https://vulkan.gpuinfo.org/displaydevicelimit.php?name=maxVertexInputBindings
|
||||
// this can be queried at runtime (VkPhysicalDeviceLimits.maxVertexInputBindings)
|
||||
constexpr uint32_t maximumVertexBindingCount = 16;
|
||||
static uint32_t glslangRefCount = 0;
|
||||
|
||||
class RenderbufferResource : public gfx::RenderbufferResource {
|
||||
public:
|
||||
RenderbufferResource() = default;
|
||||
};
|
||||
|
||||
Context::Context(RendererBackend& backend_)
|
||||
: gfx::Context(vulkan::maximumVertexBindingCount),
|
||||
backend(backend_) {
|
||||
if (glslangRefCount++ == 0) {
|
||||
glslang::InitializeProcess();
|
||||
}
|
||||
|
||||
initFrameResources();
|
||||
}
|
||||
|
||||
Context::~Context() noexcept {
|
||||
backend.getThreadPool().runRenderJobs(true /* closeQueue */);
|
||||
|
||||
destroyResources();
|
||||
|
||||
if (--glslangRefCount == 0) {
|
||||
glslang::FinalizeProcess();
|
||||
}
|
||||
}
|
||||
|
||||
void Context::initFrameResources() {
|
||||
const auto& device = backend.getDevice();
|
||||
const auto frameCount = backend.getMaxFrames();
|
||||
|
||||
// command buffers
|
||||
const vk::CommandBufferAllocateInfo allocateInfo(
|
||||
backend.getCommandPool().get(), vk::CommandBufferLevel::ePrimary, frameCount);
|
||||
|
||||
auto commandBuffers = backend.getDevice()->allocateCommandBuffersUnique(allocateInfo);
|
||||
|
||||
// descriptor pool info
|
||||
const std::vector<vk::DescriptorPoolSize> poolSizes = {
|
||||
{vk::DescriptorType::eUniformBuffer, MLN_VULKAN_DESCRIPTOR_POOL_SIZE},
|
||||
{vk::DescriptorType::eCombinedImageSampler, MLN_VULKAN_DESCRIPTOR_POOL_SIZE},
|
||||
};
|
||||
|
||||
const auto descriptorPoolInfo = vk::DescriptorPoolCreateInfo().setPoolSizes(poolSizes).setMaxSets(
|
||||
MLN_VULKAN_DESCRIPTOR_POOL_SIZE);
|
||||
|
||||
frameResources.reserve(frameCount);
|
||||
|
||||
for (uint32_t index = 0; index < frameCount; ++index) {
|
||||
frameResources.emplace_back(commandBuffers[index],
|
||||
device->createDescriptorPoolUnique(descriptorPoolInfo),
|
||||
device->createSemaphoreUnique({}),
|
||||
device->createSemaphoreUnique({}),
|
||||
device->createFenceUnique(vk::FenceCreateInfo(vk::FenceCreateFlagBits::eSignaled)));
|
||||
|
||||
const auto& frame = frameResources.back();
|
||||
|
||||
backend.setDebugName(frame.commandBuffer.get(), "FrameCommandBuffer_" + std::to_string(index));
|
||||
backend.setDebugName(frame.descriptorPool.get(), "DescriptorPool_" + std::to_string(index));
|
||||
backend.setDebugName(frame.frameSemaphore.get(), "FrameSemaphore_" + std::to_string(index));
|
||||
backend.setDebugName(frame.surfaceSemaphore.get(), "SurfaceSemaphore_" + std::to_string(index));
|
||||
backend.setDebugName(frame.flightFrameFence.get(), "FrameFence_" + std::to_string(index));
|
||||
}
|
||||
|
||||
// force placeholder texture upload before any descriptor sets
|
||||
(void)getDummyTexture();
|
||||
}
|
||||
|
||||
void Context::destroyResources() {
|
||||
backend.getDevice()->waitIdle();
|
||||
|
||||
for (auto& frame : frameResources) {
|
||||
frame.runDeletionQueue(*this);
|
||||
}
|
||||
|
||||
// all resources have unique handles
|
||||
frameResources.clear();
|
||||
}
|
||||
|
||||
const vk::UniqueDescriptorPool& Context::getCurrentDescriptorPool() const {
|
||||
return frameResources[frameResourceIndex].descriptorPool;
|
||||
}
|
||||
|
||||
void Context::enqueueDeletion(std::function<void(const Context&)>&& function) {
|
||||
if (frameResources.empty()) {
|
||||
function(*this);
|
||||
return;
|
||||
}
|
||||
|
||||
frameResources[frameResourceIndex].deletionQueue.push_back(std::move(function));
|
||||
}
|
||||
|
||||
void Context::submitOneTimeCommand(const std::function<void(const vk::UniqueCommandBuffer&)>& function) {
|
||||
const vk::CommandBufferAllocateInfo allocateInfo(
|
||||
backend.getCommandPool().get(), vk::CommandBufferLevel::ePrimary, 1);
|
||||
|
||||
const auto& commandBuffers = backend.getDevice()->allocateCommandBuffersUnique(allocateInfo);
|
||||
auto& commandBuffer = commandBuffers.front();
|
||||
|
||||
backend.setDebugName(commandBuffer.get(), "OneTimeSubmitCommandBuffer");
|
||||
|
||||
commandBuffer->begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit));
|
||||
function(commandBuffer);
|
||||
commandBuffer->end();
|
||||
|
||||
const auto submitInfo = vk::SubmitInfo().setCommandBuffers(commandBuffer.get());
|
||||
|
||||
backend.getGraphicsQueue().submit(submitInfo);
|
||||
backend.getDevice()->waitIdle();
|
||||
}
|
||||
|
||||
void Context::waitFrame() const {
|
||||
const auto& device = backend.getDevice();
|
||||
auto& frame = frameResources[frameResourceIndex];
|
||||
constexpr uint64_t timeout = std::numeric_limits<uint64_t>::max();
|
||||
|
||||
const vk::Result waitFenceResult = device->waitForFences(1, &frame.flightFrameFence.get(), VK_TRUE, timeout);
|
||||
if (waitFenceResult != vk::Result::eSuccess) {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Wait fence failed");
|
||||
}
|
||||
}
|
||||
void Context::beginFrame() {
|
||||
backend.startFrameCapture();
|
||||
|
||||
const auto& device = backend.getDevice();
|
||||
auto& renderableResource = backend.getDefaultRenderable().getResource<SurfaceRenderableResource>();
|
||||
auto& frame = frameResources[frameResourceIndex];
|
||||
constexpr uint64_t timeout = std::numeric_limits<uint64_t>::max();
|
||||
|
||||
waitFrame();
|
||||
|
||||
device->resetDescriptorPool(getCurrentDescriptorPool().get());
|
||||
frame.runDeletionQueue(*this);
|
||||
|
||||
if (renderableResource.getPlatformSurface()) {
|
||||
try {
|
||||
const vk::ResultValue acquireImageResult = device->acquireNextImageKHR(
|
||||
renderableResource.getSwapchain().get(), timeout, frame.surfaceSemaphore.get(), nullptr);
|
||||
|
||||
if (acquireImageResult.result == vk::Result::eSuccess)
|
||||
renderableResource.setAcquiredImageIndex(acquireImageResult.value);
|
||||
else if (acquireImageResult.result == vk::Result::eSuboptimalKHR)
|
||||
renderableResource.recreateSwapchain();
|
||||
|
||||
} catch (const vk::OutOfDateKHRError& e) {
|
||||
renderableResource.recreateSwapchain();
|
||||
}
|
||||
} else {
|
||||
renderableResource.setAcquiredImageIndex(frameResourceIndex);
|
||||
}
|
||||
|
||||
frame.commandBuffer->reset(vk::CommandBufferResetFlagBits::eReleaseResources);
|
||||
frame.commandBuffer->begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit));
|
||||
|
||||
backend.getThreadPool().runRenderJobs();
|
||||
}
|
||||
|
||||
void Context::endFrame() {
|
||||
const auto& frame = frameResources[frameResourceIndex];
|
||||
frame.commandBuffer->end();
|
||||
|
||||
const auto& device = backend.getDevice();
|
||||
const auto& graphicsQueue = backend.getGraphicsQueue();
|
||||
auto& renderableResource = backend.getDefaultRenderable().getResource<SurfaceRenderableResource>();
|
||||
|
||||
// submit frame commands
|
||||
const vk::PipelineStageFlags waitStageMask[] = {vk::PipelineStageFlagBits::eColorAttachmentOutput};
|
||||
auto submitInfo = vk::SubmitInfo().setCommandBuffers(frame.commandBuffer.get());
|
||||
|
||||
if (renderableResource.getPlatformSurface()) {
|
||||
submitInfo.setSignalSemaphores(frame.frameSemaphore.get())
|
||||
.setWaitSemaphores(frame.surfaceSemaphore.get())
|
||||
.setWaitDstStageMask(waitStageMask);
|
||||
}
|
||||
|
||||
const vk::Result resetFenceResult = device->resetFences(1, &frame.flightFrameFence.get());
|
||||
if (resetFenceResult != vk::Result::eSuccess) {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Reset fence failed");
|
||||
}
|
||||
|
||||
graphicsQueue.submit(submitInfo, frame.flightFrameFence.get());
|
||||
|
||||
// present rendered frame
|
||||
if (renderableResource.getPlatformSurface()) {
|
||||
const auto acquiredImage = renderableResource.getAcquiredImageIndex();
|
||||
const auto presentInfo = vk::PresentInfoKHR()
|
||||
.setSwapchains(renderableResource.getSwapchain().get())
|
||||
.setWaitSemaphores(frame.frameSemaphore.get())
|
||||
.setImageIndices(acquiredImage);
|
||||
|
||||
try {
|
||||
const auto& presentQueue = backend.getPresentQueue();
|
||||
const vk::Result presentResult = presentQueue.presentKHR(presentInfo);
|
||||
if (presentResult == vk::Result::eSuboptimalKHR) renderableResource.recreateSwapchain();
|
||||
} catch (const vk::OutOfDateKHRError& e) {
|
||||
renderableResource.recreateSwapchain();
|
||||
}
|
||||
}
|
||||
|
||||
frameResourceIndex = (frameResourceIndex + 1) % frameResources.size();
|
||||
|
||||
backend.endFrameCapture();
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::CommandEncoder> Context::createCommandEncoder() {
|
||||
const auto& frame = frameResources[frameResourceIndex];
|
||||
return std::make_unique<CommandEncoder>(*this, frame.commandBuffer);
|
||||
}
|
||||
|
||||
BufferResource Context::createBuffer(const void* data, std::size_t size, std::uint32_t usage, bool persistent) const {
|
||||
return BufferResource(const_cast<Context&>(*this), data, size, usage, persistent);
|
||||
}
|
||||
|
||||
UniqueShaderProgram Context::createProgram(std::string name,
|
||||
const std::string_view vertex,
|
||||
const std::string_view fragment,
|
||||
const ProgramParameters& programParameters,
|
||||
const mbgl::unordered_map<std::string, std::string>& additionalDefines) {
|
||||
return std::make_unique<ShaderProgram>(name, vertex, fragment, programParameters, additionalDefines, backend);
|
||||
}
|
||||
|
||||
gfx::UniqueDrawableBuilder Context::createDrawableBuilder(std::string name) {
|
||||
return std::make_unique<DrawableBuilder>(std::move(name));
|
||||
}
|
||||
|
||||
gfx::UniformBufferPtr Context::createUniformBuffer(const void* data, std::size_t size, bool persistent) {
|
||||
return std::make_shared<UniformBuffer>(createBuffer(data, size, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, persistent));
|
||||
}
|
||||
|
||||
gfx::ShaderProgramBasePtr Context::getGenericShader(gfx::ShaderRegistry& shaders, const std::string& name) {
|
||||
const auto shaderGroup = shaders.getShaderGroup(name);
|
||||
auto shader = shaderGroup ? shaderGroup->getOrCreateShader(*this, {}) : gfx::ShaderProgramBasePtr{};
|
||||
return std::static_pointer_cast<gfx::ShaderProgramBase>(std::move(shader));
|
||||
}
|
||||
|
||||
TileLayerGroupPtr Context::createTileLayerGroup(int32_t layerIndex, std::size_t initialCapacity, std::string name) {
|
||||
return std::make_shared<TileLayerGroup>(layerIndex, initialCapacity, std::move(name));
|
||||
}
|
||||
|
||||
LayerGroupPtr Context::createLayerGroup(int32_t layerIndex, std::size_t initialCapacity, std::string name) {
|
||||
return std::make_shared<LayerGroup>(layerIndex, initialCapacity, name);
|
||||
}
|
||||
|
||||
bool Context::emplaceOrUpdateUniformBuffer(gfx::UniformBufferPtr& buffer,
|
||||
const void* data,
|
||||
std::size_t size,
|
||||
bool persistent) {
|
||||
if (buffer) {
|
||||
buffer->update(data, size);
|
||||
return false;
|
||||
} else {
|
||||
buffer = createUniformBuffer(data, size, persistent);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
gfx::Texture2DPtr Context::createTexture2D() {
|
||||
return std::make_shared<Texture2D>(*this);
|
||||
}
|
||||
|
||||
RenderTargetPtr Context::createRenderTarget(const Size size, const gfx::TextureChannelDataType type) {
|
||||
return std::make_shared<RenderTarget>(*this, size, type);
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::OffscreenTexture> Context::createOffscreenTexture(Size size,
|
||||
gfx::TextureChannelDataType type,
|
||||
bool depth,
|
||||
bool stencil) {
|
||||
return std::make_unique<OffscreenTexture>(*this, size, type, depth, stencil);
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::OffscreenTexture> Context::createOffscreenTexture(Size size, gfx::TextureChannelDataType type) {
|
||||
return createOffscreenTexture(size, type, false, false);
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::TextureResource> Context::createTextureResource(Size,
|
||||
gfx::TexturePixelType,
|
||||
gfx::TextureChannelDataType) {
|
||||
throw std::runtime_error("Vulkan TextureResource not implemented");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::RenderbufferResource> Context::createRenderbufferResource(gfx::RenderbufferPixelType, Size) {
|
||||
return std::make_unique<RenderbufferResource>();
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::DrawScopeResource> Context::createDrawScopeResource() {
|
||||
throw std::runtime_error("Vulkan DrawScopeResource not implemented");
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
gfx::VertexAttributeArrayPtr Context::createVertexAttributeArray() const {
|
||||
return std::make_shared<VertexAttributeArray>();
|
||||
}
|
||||
|
||||
#if !defined(NDEBUG)
|
||||
void Context::visualizeStencilBuffer() {}
|
||||
|
||||
void Context::visualizeDepthBuffer(float) {}
|
||||
#endif // !defined(NDEBUG)
|
||||
|
||||
void Context::clearStencilBuffer(int32_t) {
|
||||
// See `PaintParameters::clearStencil`
|
||||
assert(false);
|
||||
}
|
||||
|
||||
void Context::bindGlobalUniformBuffers(gfx::RenderPass&) const noexcept {}
|
||||
|
||||
bool Context::renderTileClippingMasks(gfx::RenderPass& renderPass,
|
||||
RenderStaticData& staticData,
|
||||
const std::vector<shaders::ClipUBO>& tileUBOs) {
|
||||
using ShaderClass = shaders::ShaderSource<shaders::BuiltIn::ClippingMaskProgram, gfx::Backend::Type::Vulkan>;
|
||||
|
||||
if (!clipping.shader) {
|
||||
const auto group = staticData.shaders->getShaderGroup("ClippingMaskProgram");
|
||||
if (group) {
|
||||
clipping.shader = std::static_pointer_cast<gfx::ShaderProgramBase>(group->getOrCreateShader(*this, {}));
|
||||
}
|
||||
}
|
||||
if (!clipping.shader) {
|
||||
assert(!"Failed to create shader for clip masking");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Create a vertex buffer from the fixed tile coordinates
|
||||
if (!clipping.vertexBuffer) {
|
||||
const auto vertices = RenderStaticData::tileVertices();
|
||||
clipping.vertexBuffer.emplace(
|
||||
createBuffer(vertices.data(), vertices.bytes(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, false));
|
||||
}
|
||||
|
||||
// Create a buffer from the fixed tile indexes
|
||||
if (!clipping.indexBuffer) {
|
||||
const auto indices = RenderStaticData::quadTriangleIndices();
|
||||
clipping.indexBuffer.emplace(
|
||||
createBuffer(indices.data(), indices.bytes(), VK_BUFFER_USAGE_INDEX_BUFFER_BIT, false));
|
||||
clipping.indexCount = 6;
|
||||
}
|
||||
|
||||
// build pipeline
|
||||
if (clipping.pipelineInfo.inputAttributes.empty()) {
|
||||
clipping.pipelineInfo.usePushConstants = true;
|
||||
|
||||
clipping.pipelineInfo.colorBlend = false;
|
||||
clipping.pipelineInfo.colorMask = vk::ColorComponentFlags();
|
||||
|
||||
clipping.pipelineInfo.depthTest = false;
|
||||
clipping.pipelineInfo.depthWrite = false;
|
||||
|
||||
clipping.pipelineInfo.stencilTest = true;
|
||||
clipping.pipelineInfo.stencilFunction = vk::CompareOp::eAlways;
|
||||
clipping.pipelineInfo.stencilPass = vk::StencilOp::eReplace;
|
||||
clipping.pipelineInfo.dynamicValues.stencilWriteMask = 0b11111111;
|
||||
clipping.pipelineInfo.dynamicValues.stencilRef = 0b11111111;
|
||||
|
||||
clipping.pipelineInfo.inputBindings.push_back(
|
||||
vk::VertexInputBindingDescription()
|
||||
.setBinding(0)
|
||||
.setStride(VertexAttribute::getStrideOf(ShaderClass::attributes[0].dataType))
|
||||
.setInputRate(vk::VertexInputRate::eVertex));
|
||||
|
||||
clipping.pipelineInfo.inputAttributes.push_back(
|
||||
vk::VertexInputAttributeDescription()
|
||||
.setBinding(0)
|
||||
.setLocation(ShaderClass::attributes[0].index)
|
||||
.setFormat(PipelineInfo::vulkanFormat(ShaderClass::attributes[0].dataType)));
|
||||
}
|
||||
|
||||
auto& shaderImpl = static_cast<ShaderProgram&>(*clipping.shader);
|
||||
auto& renderPassImpl = static_cast<RenderPass&>(renderPass);
|
||||
auto& commandBuffer = renderPassImpl.getEncoder().getCommandBuffer();
|
||||
|
||||
clipping.pipelineInfo.setRenderable(renderPassImpl.getDescriptor().renderable);
|
||||
|
||||
const auto& pipeline = shaderImpl.getPipeline(clipping.pipelineInfo);
|
||||
|
||||
commandBuffer->bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.get());
|
||||
clipping.pipelineInfo.setDynamicValues(commandBuffer);
|
||||
|
||||
const std::array<vk::Buffer, 1> vertexBuffers = {clipping.vertexBuffer->getVulkanBuffer()};
|
||||
const std::array<vk::DeviceSize, 1> offset = {0};
|
||||
|
||||
commandBuffer->bindVertexBuffers(0, vertexBuffers, offset);
|
||||
commandBuffer->bindIndexBuffer(clipping.indexBuffer->getVulkanBuffer(), 0, vk::IndexType::eUint16);
|
||||
|
||||
for (const auto& tileInfo : tileUBOs) {
|
||||
commandBuffer->setStencilReference(vk::StencilFaceFlagBits::eFrontAndBack, tileInfo.stencil_ref);
|
||||
|
||||
commandBuffer->pushConstants(
|
||||
getPushConstantPipelineLayout().get(),
|
||||
vk::ShaderStageFlags() | vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
|
||||
0,
|
||||
sizeof(tileInfo.matrix),
|
||||
&tileInfo.matrix);
|
||||
commandBuffer->drawIndexed(clipping.indexCount, 1, 0, 0, 0);
|
||||
}
|
||||
|
||||
stats.numDrawCalls++;
|
||||
stats.totalDrawCalls++;
|
||||
return true;
|
||||
}
|
||||
|
||||
const std::unique_ptr<BufferResource>& Context::getDummyVertexBuffer() {
|
||||
if (!dummyVertexBuffer)
|
||||
dummyVertexBuffer = std::make_unique<BufferResource>(
|
||||
*this, nullptr, 16, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, false);
|
||||
return dummyVertexBuffer;
|
||||
}
|
||||
|
||||
const std::unique_ptr<BufferResource>& Context::getDummyUniformBuffer() {
|
||||
if (!dummyUniformBuffer)
|
||||
dummyUniformBuffer = std::make_unique<BufferResource>(
|
||||
*this, nullptr, 16, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, false);
|
||||
return dummyUniformBuffer;
|
||||
}
|
||||
|
||||
const std::unique_ptr<Texture2D>& Context::getDummyTexture() {
|
||||
if (!dummyTexture2D) {
|
||||
const Size size(2, 2);
|
||||
const std::vector<Color> data(4ull * size.width * size.height, Color::white());
|
||||
|
||||
dummyTexture2D = std::make_unique<Texture2D>(*this);
|
||||
dummyTexture2D->setFormat(gfx::TexturePixelType::RGBA, gfx::TextureChannelDataType::UnsignedByte);
|
||||
dummyTexture2D->setSize(size);
|
||||
|
||||
submitOneTimeCommand([&](const vk::UniqueCommandBuffer& commandBuffer) {
|
||||
dummyTexture2D->uploadSubRegion(data.data(), size, 0, 0, commandBuffer);
|
||||
});
|
||||
}
|
||||
|
||||
return dummyTexture2D;
|
||||
}
|
||||
|
||||
const vk::UniqueDescriptorSetLayout& Context::getUniformDescriptorSetLayout() {
|
||||
if (!uniformDescriptorSetLayout) {
|
||||
std::vector<vk::DescriptorSetLayoutBinding> bindings;
|
||||
const auto stageFlags = vk::ShaderStageFlags() | vk::ShaderStageFlagBits::eVertex |
|
||||
vk::ShaderStageFlagBits::eFragment;
|
||||
|
||||
for (size_t i = 0; i < shaders::maxUBOCountPerShader; ++i) {
|
||||
bindings.push_back(vk::DescriptorSetLayoutBinding()
|
||||
.setBinding(i)
|
||||
.setStageFlags(stageFlags)
|
||||
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
|
||||
.setDescriptorCount(1));
|
||||
}
|
||||
|
||||
const auto descriptorSetLayoutCreateInfo = vk::DescriptorSetLayoutCreateInfo().setBindings(bindings);
|
||||
uniformDescriptorSetLayout = backend.getDevice()->createDescriptorSetLayoutUnique(
|
||||
descriptorSetLayoutCreateInfo);
|
||||
backend.setDebugName(uniformDescriptorSetLayout.get(), "UniformDescriptorSetLayout");
|
||||
}
|
||||
|
||||
return uniformDescriptorSetLayout;
|
||||
}
|
||||
|
||||
const vk::UniqueDescriptorSetLayout& Context::getImageDescriptorSetLayout() {
|
||||
if (!imageDescriptorSetLayout) {
|
||||
std::vector<vk::DescriptorSetLayoutBinding> bindings;
|
||||
|
||||
for (size_t i = 0; i < shaders::maxTextureCountPerShader; ++i) {
|
||||
bindings.push_back(vk::DescriptorSetLayoutBinding()
|
||||
.setBinding(i)
|
||||
.setStageFlags(vk::ShaderStageFlagBits::eFragment)
|
||||
.setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
|
||||
.setDescriptorCount(1));
|
||||
}
|
||||
|
||||
const auto descriptorSetLayoutCreateInfo = vk::DescriptorSetLayoutCreateInfo().setBindings(bindings);
|
||||
imageDescriptorSetLayout = backend.getDevice()->createDescriptorSetLayoutUnique(descriptorSetLayoutCreateInfo);
|
||||
backend.setDebugName(imageDescriptorSetLayout.get(), "ImageDescriptorSetLayout");
|
||||
}
|
||||
|
||||
return imageDescriptorSetLayout;
|
||||
}
|
||||
|
||||
const std::vector<vk::DescriptorSetLayout>& Context::getDescriptorSetLayouts() {
|
||||
if (descriptorSetLayouts.empty()) {
|
||||
descriptorSetLayouts = {getUniformDescriptorSetLayout().get(), getImageDescriptorSetLayout().get()};
|
||||
}
|
||||
|
||||
return descriptorSetLayouts;
|
||||
}
|
||||
|
||||
const vk::UniquePipelineLayout& Context::getGeneralPipelineLayout() {
|
||||
if (generalPipelineLayout) return generalPipelineLayout;
|
||||
|
||||
const auto& descriptorLayouts = getDescriptorSetLayouts();
|
||||
|
||||
generalPipelineLayout = backend.getDevice()->createPipelineLayoutUnique(
|
||||
vk::PipelineLayoutCreateInfo().setSetLayouts(descriptorLayouts));
|
||||
|
||||
backend.setDebugName(generalPipelineLayout.get(), "PipelineLayout_general");
|
||||
|
||||
return generalPipelineLayout;
|
||||
}
|
||||
|
||||
const vk::UniquePipelineLayout& Context::getPushConstantPipelineLayout() {
|
||||
if (pushConstantPipelineLayout) return pushConstantPipelineLayout;
|
||||
|
||||
const auto stages = vk::ShaderStageFlags() | vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment;
|
||||
const auto pushConstant = vk::PushConstantRange().setSize(sizeof(matf4)).setStageFlags(stages);
|
||||
|
||||
pushConstantPipelineLayout = backend.getDevice()->createPipelineLayoutUnique(
|
||||
vk::PipelineLayoutCreateInfo().setPushConstantRanges(pushConstant));
|
||||
|
||||
backend.setDebugName(pushConstantPipelineLayout.get(), "PipelineLayout_pushConstants");
|
||||
|
||||
return pushConstantPipelineLayout;
|
||||
}
|
||||
|
||||
void Context::FrameResources::runDeletionQueue(const Context& context) {
|
||||
for (const auto& function : deletionQueue) function(context);
|
||||
|
||||
deletionQueue.clear();
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
453
src/mbgl/vulkan/drawable.cpp
Normal file
453
src/mbgl/vulkan/drawable.cpp
Normal file
@@ -0,0 +1,453 @@
|
||||
#include <mbgl/vulkan/drawable.hpp>
|
||||
|
||||
#include <mbgl/gfx/color_mode.hpp>
|
||||
#include <mbgl/gfx/depth_mode.hpp>
|
||||
#include <mbgl/renderer/paint_parameters.hpp>
|
||||
#include <mbgl/vulkan/command_encoder.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/vulkan/drawable_impl.hpp>
|
||||
#include <mbgl/vulkan/render_pass.hpp>
|
||||
#include <mbgl/vulkan/renderable_resource.hpp>
|
||||
#include <mbgl/vulkan/renderer_backend.hpp>
|
||||
#include <mbgl/vulkan/upload_pass.hpp>
|
||||
#include <mbgl/vulkan/index_buffer_resource.hpp>
|
||||
#include <mbgl/vulkan/vertex_buffer_resource.hpp>
|
||||
#include <mbgl/vulkan/texture2d.hpp>
|
||||
#include <mbgl/shaders/vulkan/shader_program.hpp>
|
||||
#include <mbgl/programs/segment.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
#include <mbgl/util/variant.hpp>
|
||||
#include <mbgl/util/hash.hpp>
|
||||
|
||||
#include <cassert>
|
||||
#if !defined(NDEBUG)
|
||||
#include <sstream>
|
||||
#endif
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
struct IndexBuffer : public gfx::IndexBufferBase {
|
||||
IndexBuffer(std::unique_ptr<gfx::IndexBuffer>&& buffer_)
|
||||
: buffer(std::move(buffer_)) {}
|
||||
~IndexBuffer() override = default;
|
||||
|
||||
std::unique_ptr<mbgl::gfx::IndexBuffer> buffer;
|
||||
};
|
||||
|
||||
#if !defined(NDEBUG)
|
||||
static std::string debugLabel(const gfx::Drawable& drawable) {
|
||||
std::ostringstream oss;
|
||||
oss << drawable.getID().id() << "/" << drawable.getName() << "/tile=";
|
||||
|
||||
if (const auto& tileID = drawable.getTileID()) {
|
||||
oss << util::toString(*tileID);
|
||||
} else {
|
||||
oss << "(none)";
|
||||
}
|
||||
|
||||
return oss.str();
|
||||
}
|
||||
#endif // !defined(NDEBUG)
|
||||
|
||||
Drawable::Drawable(std::string name_)
|
||||
: gfx::Drawable(std::move(name_)),
|
||||
impl(std::make_unique<Impl>()) {}
|
||||
|
||||
Drawable::~Drawable() {}
|
||||
|
||||
void Drawable::setEnableColor(bool value) {
|
||||
gfx::Drawable::setEnableColor(value);
|
||||
|
||||
if (value) {
|
||||
impl->pipelineInfo.colorMask = vk::FlagTraits<vk::ColorComponentFlagBits>::allFlags;
|
||||
} else {
|
||||
impl->pipelineInfo.colorMask = vk::ColorComponentFlags();
|
||||
}
|
||||
}
|
||||
|
||||
void Drawable::setColorMode(const gfx::ColorMode& value) {
|
||||
gfx::Drawable::setColorMode(value);
|
||||
impl->pipelineInfo.setColorBlend(value);
|
||||
}
|
||||
|
||||
void Drawable::setEnableDepth(bool value) {
|
||||
gfx::Drawable::setEnableDepth(value);
|
||||
impl->pipelineInfo.depthTest = value;
|
||||
}
|
||||
|
||||
void Drawable::setDepthType(gfx::DepthMaskType value) {
|
||||
gfx::Drawable::setDepthType(value);
|
||||
impl->pipelineInfo.setDepthWrite(value);
|
||||
}
|
||||
|
||||
void Drawable::setDepthModeFor3D(const gfx::DepthMode& value) {
|
||||
impl->depthFor3D = value;
|
||||
}
|
||||
|
||||
void Drawable::setStencilModeFor3D(const gfx::StencilMode& value) {
|
||||
impl->stencilFor3D = value;
|
||||
}
|
||||
|
||||
void Drawable::setLineWidth(int32_t value) {
|
||||
gfx::Drawable::setLineWidth(value);
|
||||
impl->pipelineInfo.wideLines = value != 1;
|
||||
impl->pipelineInfo.dynamicValues.lineWidth = static_cast<float>(value);
|
||||
}
|
||||
|
||||
void Drawable::setCullFaceMode(const gfx::CullFaceMode& mode) {
|
||||
gfx::Drawable::setCullFaceMode(mode);
|
||||
impl->pipelineInfo.setCullMode(mode);
|
||||
}
|
||||
|
||||
void Drawable::upload(gfx::UploadPass& uploadPass_) {
|
||||
if (isCustom) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!shader) {
|
||||
Log::Warning(Event::General, "Missing shader for drawable " + util::toString(getID()) + "/" + getName());
|
||||
assert(false);
|
||||
return;
|
||||
}
|
||||
|
||||
auto& uploadPass = static_cast<UploadPass&>(uploadPass_);
|
||||
constexpr auto usage = gfx::BufferUsageType::StaticDraw;
|
||||
|
||||
// We need either raw index data or a buffer already created from them.
|
||||
// We can have a buffer and no indexes, but only if it's not marked dirty.
|
||||
if (!impl->indexes || (impl->indexes->empty() && (!impl->indexes->getBuffer() || impl->indexes->getDirty()))) {
|
||||
assert(!"Missing index data");
|
||||
return;
|
||||
}
|
||||
|
||||
if (impl->indexes->getDirty()) {
|
||||
// Create or update a buffer for the index data. We don't update any
|
||||
// existing buffer because it may still be in use by the previous frame.
|
||||
auto indexBufferResource{uploadPass.createIndexBufferResource(
|
||||
impl->indexes->data(), impl->indexes->bytes(), usage, /*persistent=*/false)};
|
||||
auto indexBuffer = std::make_unique<gfx::IndexBuffer>(impl->indexes->elements(),
|
||||
std::move(indexBufferResource));
|
||||
auto buffer = std::make_unique<IndexBuffer>(std::move(indexBuffer));
|
||||
|
||||
impl->indexes->setBuffer(std::move(buffer));
|
||||
impl->indexes->setDirty(false);
|
||||
}
|
||||
|
||||
const bool buildAttribs = !vertexAttributes || vertexAttributes->isDirty() ||
|
||||
impl->pipelineInfo.inputAttributes.empty();
|
||||
|
||||
if (buildAttribs) {
|
||||
#if !defined(NDEBUG)
|
||||
const auto debugGroup = uploadPass.createDebugGroup(debugLabel(*this));
|
||||
#endif
|
||||
|
||||
if (!vertexAttributes) {
|
||||
vertexAttributes = std::make_shared<VertexAttributeArray>();
|
||||
}
|
||||
|
||||
// Apply drawable values to shader defaults
|
||||
std::vector<std::unique_ptr<gfx::VertexBufferResource>> vertexBuffers;
|
||||
auto attributeBindings_ = uploadPass.buildAttributeBindings(impl->vertexCount,
|
||||
impl->vertexType,
|
||||
/*vertexAttributeIndex=*/-1,
|
||||
/*vertexData=*/{},
|
||||
shader->getVertexAttributes(),
|
||||
*vertexAttributes,
|
||||
usage,
|
||||
vertexBuffers);
|
||||
|
||||
vertexAttributes->visitAttributes([](gfx::VertexAttribute& attrib) { attrib.setDirty(false); });
|
||||
|
||||
if (impl->attributeBindings != attributeBindings_) {
|
||||
impl->attributeBindings = std::move(attributeBindings_);
|
||||
}
|
||||
}
|
||||
|
||||
// build instance buffer
|
||||
const bool buildInstanceBuffer = (instanceAttributes && instanceAttributes->isDirty());
|
||||
|
||||
if (buildInstanceBuffer) {
|
||||
// Build instance attribute buffers
|
||||
std::vector<std::unique_ptr<gfx::VertexBufferResource>> instanceBuffers;
|
||||
auto instanceBindings_ = uploadPass.buildAttributeBindings(instanceAttributes->getMaxCount(),
|
||||
/*vertexType*/ gfx::AttributeDataType::Byte,
|
||||
/*vertexAttributeIndex=*/-1,
|
||||
/*vertexData=*/{},
|
||||
shader->getInstanceAttributes(),
|
||||
*instanceAttributes,
|
||||
usage,
|
||||
instanceBuffers);
|
||||
|
||||
// clear dirty flag
|
||||
instanceAttributes->visitAttributes([](gfx::VertexAttribute& attrib) { attrib.setDirty(false); });
|
||||
|
||||
if (impl->instanceBindings != instanceBindings_) {
|
||||
impl->instanceBindings = std::move(instanceBindings_);
|
||||
}
|
||||
}
|
||||
|
||||
if (buildAttribs || buildInstanceBuffer) {
|
||||
buildVulkanInputBindings();
|
||||
}
|
||||
|
||||
const bool texturesNeedUpload = std::any_of(
|
||||
textures.begin(), textures.end(), [](const auto& texture) { return texture && texture->needsUpload(); });
|
||||
|
||||
if (texturesNeedUpload) {
|
||||
uploadTextures(uploadPass);
|
||||
}
|
||||
}
|
||||
|
||||
void Drawable::draw(PaintParameters& parameters) const {
|
||||
if (isCustom) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto& context = static_cast<Context&>(parameters.context);
|
||||
auto& renderPass = static_cast<RenderPass&>(*parameters.renderPass);
|
||||
auto& encoder = renderPass.getEncoder();
|
||||
auto& commandBuffer = encoder.getCommandBuffer();
|
||||
|
||||
auto& shaderImpl = static_cast<mbgl::vulkan::ShaderProgram&>(*shader);
|
||||
|
||||
if (!bindAttributes(encoder)) return;
|
||||
if (!bindDescriptors(encoder)) return;
|
||||
|
||||
if (is3D) {
|
||||
impl->pipelineInfo.setDepthMode(impl->depthFor3D);
|
||||
impl->pipelineInfo.setStencilMode(impl->stencilFor3D);
|
||||
} else {
|
||||
if (enableDepth) {
|
||||
const auto& depthMode = parameters.depthModeForSublayer(getSubLayerIndex(), getDepthType());
|
||||
impl->pipelineInfo.setDepthMode(depthMode);
|
||||
} else {
|
||||
impl->pipelineInfo.setDepthMode(gfx::DepthMode::disabled());
|
||||
}
|
||||
|
||||
if (enableStencil) {
|
||||
const auto& stencilMode = parameters.stencilModeForClipping(tileID->toUnwrapped());
|
||||
impl->pipelineInfo.setStencilMode(stencilMode);
|
||||
} else {
|
||||
impl->pipelineInfo.setStencilMode(gfx::StencilMode::disabled());
|
||||
}
|
||||
}
|
||||
|
||||
impl->pipelineInfo.setRenderable(renderPass.getDescriptor().renderable);
|
||||
|
||||
const uint32_t instances = instanceAttributes ? instanceAttributes->getMaxCount() : 1;
|
||||
|
||||
for (const auto& seg : impl->segments) {
|
||||
const auto& segment = seg->getSegment();
|
||||
|
||||
// update pipeline info with per segment modifiers
|
||||
impl->pipelineInfo.setDrawMode(seg->getMode());
|
||||
|
||||
impl->pipelineInfo.setDynamicValues(commandBuffer);
|
||||
|
||||
const auto& pipeline = shaderImpl.getPipeline(impl->pipelineInfo);
|
||||
commandBuffer->bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline.get());
|
||||
|
||||
if (segment.indexLength) {
|
||||
commandBuffer->drawIndexed(segment.indexLength, instances, segment.indexOffset, segment.vertexOffset, 0);
|
||||
} else {
|
||||
commandBuffer->draw(segment.vertexLength, instances, segment.vertexOffset, 0);
|
||||
}
|
||||
|
||||
context.renderingStats().numDrawCalls++;
|
||||
}
|
||||
}
|
||||
|
||||
void Drawable::setIndexData(gfx::IndexVectorBasePtr indexes, std::vector<UniqueDrawSegment> segments) {
|
||||
assert(indexes && indexes->elements());
|
||||
impl->indexes = std::move(indexes);
|
||||
impl->segments = std::move(segments);
|
||||
}
|
||||
|
||||
void Drawable::setVertices(std::vector<uint8_t>&& data, std::size_t count, gfx::AttributeDataType type) {
|
||||
impl->vertexCount = count;
|
||||
impl->vertexType = type;
|
||||
|
||||
if (count && type != gfx::AttributeDataType::Invalid && !data.empty()) {
|
||||
if (!vertexAttributes) {
|
||||
vertexAttributes = std::make_shared<VertexAttributeArray>();
|
||||
}
|
||||
if (auto& attrib = vertexAttributes->set(impl->vertexAttrId, /*index=*/-1, type)) {
|
||||
attrib->setRawData(std::move(data));
|
||||
attrib->setStride(VertexAttribute::getStrideOf(type));
|
||||
} else {
|
||||
using namespace std::string_literals;
|
||||
Log::Warning(Event::General,
|
||||
"Vertex attribute type mismatch: "s + name + " / " + util::toString(impl->vertexAttrId));
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const gfx::UniformBufferArray& Drawable::getUniformBuffers() const {
|
||||
return impl->uniformBuffers;
|
||||
}
|
||||
|
||||
gfx::UniformBufferArray& Drawable::mutableUniformBuffers() {
|
||||
return impl->uniformBuffers;
|
||||
}
|
||||
|
||||
void Drawable::buildVulkanInputBindings() noexcept {
|
||||
impl->vulkanVertexBuffers.clear();
|
||||
impl->vulkanVertexOffsets.clear();
|
||||
|
||||
impl->pipelineInfo.inputAttributes.clear();
|
||||
impl->pipelineInfo.inputBindings.clear();
|
||||
|
||||
std::vector<const gfx::VertexBufferResource*> uniqueBuffers;
|
||||
|
||||
const auto buildBindings = [&](const gfx::AttributeBindingArray& bindings, vk::VertexInputRate inputRate) {
|
||||
for (size_t i = 0; i < bindings.size(); ++i) {
|
||||
const auto& binding = bindings[i];
|
||||
if (!binding.has_value() || !binding->vertexBufferResource) continue;
|
||||
|
||||
const auto& vertexBuffer = static_cast<const VertexBufferResource*>(binding->vertexBufferResource);
|
||||
const auto& buffer = vertexBuffer->get();
|
||||
|
||||
const auto& buffIt = std::find(uniqueBuffers.begin(), uniqueBuffers.end(), binding->vertexBufferResource);
|
||||
uint32_t bindingIndex = 0;
|
||||
|
||||
if (buffIt == uniqueBuffers.end()) {
|
||||
bindingIndex = impl->pipelineInfo.inputBindings.size();
|
||||
|
||||
uniqueBuffers.push_back(binding->vertexBufferResource);
|
||||
|
||||
// add new buffer binding
|
||||
impl->pipelineInfo.inputBindings.push_back(vk::VertexInputBindingDescription()
|
||||
.setBinding(bindingIndex)
|
||||
.setStride(binding->vertexStride)
|
||||
.setInputRate(inputRate));
|
||||
|
||||
impl->vulkanVertexBuffers.push_back(buffer.getVulkanBuffer());
|
||||
impl->vulkanVertexOffsets.push_back(0u);
|
||||
} else {
|
||||
bindingIndex = std::distance(uniqueBuffers.begin(), buffIt);
|
||||
}
|
||||
|
||||
impl->pipelineInfo.inputAttributes.push_back(
|
||||
vk::VertexInputAttributeDescription()
|
||||
.setBinding(bindingIndex)
|
||||
.setLocation(i)
|
||||
.setFormat(PipelineInfo::vulkanFormat(binding->attribute.dataType))
|
||||
.setOffset(binding->attribute.offset));
|
||||
}
|
||||
};
|
||||
|
||||
buildBindings(impl->attributeBindings, vk::VertexInputRate::eVertex);
|
||||
buildBindings(impl->instanceBindings, vk::VertexInputRate::eInstance);
|
||||
|
||||
impl->pipelineInfo.updateVertexInputHash();
|
||||
}
|
||||
|
||||
bool Drawable::bindAttributes(CommandEncoder& encoder) const noexcept {
|
||||
if (impl->vulkanVertexBuffers.empty()) return false;
|
||||
|
||||
const auto& commandBuffer = encoder.getCommandBuffer();
|
||||
|
||||
commandBuffer->bindVertexBuffers(0, impl->vulkanVertexBuffers, impl->vulkanVertexOffsets);
|
||||
|
||||
if (impl->indexes) {
|
||||
const auto* indexBuffer = static_cast<const IndexBuffer*>(impl->indexes->getBuffer());
|
||||
const auto& indexBufferResource = indexBuffer->buffer->getResource<IndexBufferResource>().get();
|
||||
commandBuffer->bindIndexBuffer(indexBufferResource.getVulkanBuffer(), 0, vk::IndexType::eUint16);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Drawable::bindDescriptors(CommandEncoder& encoder) const noexcept {
|
||||
if (!shader) return false;
|
||||
|
||||
auto& context = encoder.getContext();
|
||||
const auto& device = context.getBackend().getDevice();
|
||||
const auto& descriptorPool = context.getCurrentDescriptorPool();
|
||||
const auto& descriptorSetLayouts = context.getDescriptorSetLayouts();
|
||||
|
||||
const auto descriptorAllocInfo =
|
||||
vk::DescriptorSetAllocateInfo().setDescriptorPool(*descriptorPool).setSetLayouts(descriptorSetLayouts);
|
||||
|
||||
const auto& drawableDescriptorSets = device->allocateDescriptorSets(descriptorAllocInfo);
|
||||
const auto& uniformDescriptorSet = drawableDescriptorSets[0];
|
||||
|
||||
const auto updateUniformDescriptors = [&](const auto& buffer, bool fillGaps) {
|
||||
for (size_t id = 0; id < buffer.allocatedSize(); ++id) {
|
||||
vk::DescriptorBufferInfo descriptorBufferInfo;
|
||||
|
||||
if (const auto& uniformBuffer = buffer.get(id)) {
|
||||
const auto& uniformBufferImpl = static_cast<const UniformBuffer&>(*uniformBuffer);
|
||||
const auto& bufferResource = uniformBufferImpl.getBufferResource();
|
||||
descriptorBufferInfo.setBuffer(bufferResource.getVulkanBuffer())
|
||||
.setOffset(bufferResource.getVulkanBufferOffset())
|
||||
.setRange(bufferResource.getVulkanBufferSize());
|
||||
} else if (fillGaps) {
|
||||
descriptorBufferInfo.setBuffer(context.getDummyUniformBuffer()->getVulkanBuffer())
|
||||
.setOffset(0)
|
||||
.setRange(VK_WHOLE_SIZE);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
const auto writeDescriptorSet = vk::WriteDescriptorSet()
|
||||
.setBufferInfo(descriptorBufferInfo)
|
||||
.setDescriptorCount(1)
|
||||
.setDescriptorType(vk::DescriptorType::eUniformBuffer)
|
||||
.setDstBinding(id)
|
||||
.setDstSet(uniformDescriptorSet);
|
||||
|
||||
device->updateDescriptorSets(writeDescriptorSet, nullptr);
|
||||
}
|
||||
};
|
||||
const auto& globalUniforms = context.getGlobalUniformBuffers();
|
||||
for (size_t i = 0; i < globalUniforms.allocatedSize(); ++i) {
|
||||
if (globalUniforms.get(i)) impl->uniformBuffers.set(i, globalUniforms.get(i));
|
||||
}
|
||||
|
||||
updateUniformDescriptors(getUniformBuffers(), true);
|
||||
|
||||
if (drawableDescriptorSets.size() >= 2) {
|
||||
const auto& imageDescriptorSet = drawableDescriptorSets[1];
|
||||
|
||||
for (size_t id = 0; id < shaders::maxTextureCountPerShader; ++id) {
|
||||
const auto& texture = id < textures.size() ? textures[id] : nullptr;
|
||||
auto& textureImpl = texture ? static_cast<Texture2D&>(*texture) : *context.getDummyTexture();
|
||||
|
||||
const auto descriptorImageInfo = vk::DescriptorImageInfo()
|
||||
.setImageLayout(textureImpl.getVulkanImageLayout())
|
||||
.setImageView(textureImpl.getVulkanImageView().get())
|
||||
.setSampler(textureImpl.getVulkanSampler());
|
||||
|
||||
const auto writeDescriptorSet = vk::WriteDescriptorSet()
|
||||
.setImageInfo(descriptorImageInfo)
|
||||
.setDescriptorCount(1)
|
||||
.setDescriptorType(vk::DescriptorType::eCombinedImageSampler)
|
||||
.setDstBinding(id)
|
||||
.setDstSet(imageDescriptorSet);
|
||||
|
||||
device->updateDescriptorSets(writeDescriptorSet, nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
if (drawableDescriptorSets.empty()) return true;
|
||||
|
||||
const auto& commandBuffer = encoder.getCommandBuffer();
|
||||
commandBuffer->bindDescriptorSets(
|
||||
vk::PipelineBindPoint::eGraphics, context.getGeneralPipelineLayout().get(), 0, drawableDescriptorSets, nullptr);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void Drawable::uploadTextures(UploadPass&) const noexcept {
|
||||
for (const auto& texture : textures) {
|
||||
if (texture) {
|
||||
texture->upload();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
47
src/mbgl/vulkan/drawable_builder.cpp
Normal file
47
src/mbgl/vulkan/drawable_builder.cpp
Normal file
@@ -0,0 +1,47 @@
|
||||
#include <mbgl/vulkan/drawable_builder.hpp>
|
||||
|
||||
#include <mbgl/gfx/drawable_builder_impl.hpp>
|
||||
#include <mbgl/gfx/drawable_impl.hpp>
|
||||
#include <mbgl/vulkan/drawable.hpp>
|
||||
#include <mbgl/vulkan/drawable_impl.hpp>
|
||||
#include <mbgl/util/convert.hpp>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
gfx::UniqueDrawable DrawableBuilder::createDrawable() const {
|
||||
return std::make_unique<Drawable>(drawableName.empty() ? name : drawableName);
|
||||
};
|
||||
|
||||
std::unique_ptr<gfx::Drawable::DrawSegment> DrawableBuilder::createSegment(gfx::DrawMode mode, SegmentBase&& seg) {
|
||||
return std::make_unique<Drawable::DrawSegment>(mode, std::move(seg));
|
||||
}
|
||||
|
||||
void DrawableBuilder::init() {
|
||||
auto& drawable = static_cast<Drawable&>(*currentDrawable);
|
||||
|
||||
if (impl->rawVerticesCount) {
|
||||
auto raw = impl->rawVertices;
|
||||
drawable.setVertices(std::move(raw), impl->rawVerticesCount, impl->rawVerticesType);
|
||||
} else {
|
||||
const auto& verts = impl->vertices.vector();
|
||||
constexpr auto vertSize = sizeof(std::remove_reference<decltype(verts)>::type::value_type);
|
||||
std::vector<uint8_t> raw(verts.size() * vertSize);
|
||||
std::memcpy(raw.data(), verts.data(), raw.size());
|
||||
drawable.setVertices(std::move(raw), verts.size(), gfx::AttributeDataType::Short2);
|
||||
}
|
||||
|
||||
if (!impl->sharedIndexes && !impl->buildIndexes.empty()) {
|
||||
impl->sharedIndexes = std::make_shared<gfx::IndexVectorBase>(std::move(impl->buildIndexes));
|
||||
}
|
||||
assert(impl->sharedIndexes && impl->sharedIndexes->elements());
|
||||
drawable.setIndexData(std::move(impl->sharedIndexes), std::move(impl->segments));
|
||||
|
||||
impl->clear();
|
||||
textures.fill(nullptr);
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
53
src/mbgl/vulkan/drawable_impl.hpp
Normal file
53
src/mbgl/vulkan/drawable_impl.hpp
Normal file
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include <mbgl/gfx/cull_face_mode.hpp>
|
||||
#include <mbgl/gfx/drawable_impl.hpp>
|
||||
#include <mbgl/gfx/index_buffer.hpp>
|
||||
#include <mbgl/gfx/uniform.hpp>
|
||||
#include <mbgl/vulkan/uniform_buffer.hpp>
|
||||
#include <mbgl/vulkan/render_pass.hpp>
|
||||
#include <mbgl/vulkan/upload_pass.hpp>
|
||||
#include <mbgl/vulkan/pipeline.hpp>
|
||||
#include <mbgl/programs/segment.hpp>
|
||||
#include <mbgl/util/mat4.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
using namespace platform;
|
||||
|
||||
class Drawable::Impl final {
|
||||
public:
|
||||
Impl() = default;
|
||||
~Impl() = default;
|
||||
|
||||
std::vector<UniqueDrawSegment> segments;
|
||||
|
||||
gfx::IndexVectorBasePtr indexes;
|
||||
std::size_t vertexCount = 0;
|
||||
gfx::AttributeDataType vertexType = gfx::AttributeDataType::Invalid;
|
||||
|
||||
gfx::AttributeBindingArray attributeBindings;
|
||||
gfx::AttributeBindingArray instanceBindings;
|
||||
|
||||
vulkan::UniformBufferArray uniformBuffers;
|
||||
|
||||
std::size_t vertexAttrId = 0;
|
||||
|
||||
std::optional<gfx::RenderPassDescriptor> renderPassDescriptor;
|
||||
|
||||
gfx::DepthMode depthFor3D = gfx::DepthMode::disabled();
|
||||
gfx::StencilMode stencilFor3D = gfx::StencilMode::disabled();
|
||||
|
||||
PipelineInfo pipelineInfo;
|
||||
|
||||
std::vector<vk::Buffer> vulkanVertexBuffers;
|
||||
std::vector<vk::DeviceSize> vulkanVertexOffsets;
|
||||
};
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
26
src/mbgl/vulkan/index_buffer_resource.cpp
Normal file
26
src/mbgl/vulkan/index_buffer_resource.cpp
Normal file
@@ -0,0 +1,26 @@
|
||||
#include <mbgl/vulkan/index_buffer_resource.hpp>
|
||||
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
IndexBufferResource::IndexBufferResource(BufferResource&& ptr) noexcept
|
||||
: buffer(std::move(ptr)) {
|
||||
if (buffer) {
|
||||
auto& stats = buffer.getContext().renderingStats();
|
||||
stats.numIndexBuffers++;
|
||||
stats.memIndexBuffers += buffer.getSizeInBytes();
|
||||
}
|
||||
}
|
||||
|
||||
IndexBufferResource::~IndexBufferResource() noexcept {
|
||||
if (buffer) {
|
||||
auto& stats = buffer.getContext().renderingStats();
|
||||
stats.numIndexBuffers--;
|
||||
stats.memIndexBuffers -= buffer.getSizeInBytes();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
89
src/mbgl/vulkan/layer_group.cpp
Normal file
89
src/mbgl/vulkan/layer_group.cpp
Normal file
@@ -0,0 +1,89 @@
|
||||
#include <mbgl/vulkan/layer_group.hpp>
|
||||
|
||||
#include <mbgl/gfx/drawable_tweaker.hpp>
|
||||
#include <mbgl/gfx/renderable.hpp>
|
||||
#include <mbgl/gfx/renderer_backend.hpp>
|
||||
#include <mbgl/gfx/upload_pass.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/vulkan/drawable.hpp>
|
||||
#include <mbgl/vulkan/render_pass.hpp>
|
||||
#include <mbgl/renderer/paint_parameters.hpp>
|
||||
#include <mbgl/util/convert.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
LayerGroup::LayerGroup(int32_t layerIndex_, std::size_t initialCapacity, std::string name_)
|
||||
: mbgl::LayerGroup(layerIndex_, initialCapacity, std::move(name_)) {}
|
||||
|
||||
void LayerGroup::upload(gfx::UploadPass& uploadPass) {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
#if !defined(NDEBUG)
|
||||
const auto debugGroup = uploadPass.createDebugGroup(getName() + "-upload");
|
||||
#endif
|
||||
|
||||
visitDrawables([&](gfx::Drawable& drawable_) {
|
||||
if (drawable_.getEnabled()) {
|
||||
auto& drawable = static_cast<Drawable&>(drawable_);
|
||||
drawable.upload(uploadPass);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void LayerGroup::render(RenderOrchestrator&, PaintParameters& parameters) {
|
||||
if (!enabled || !getDrawableCount() || !parameters.renderPass) {
|
||||
return;
|
||||
}
|
||||
|
||||
#if !defined(NDEBUG)
|
||||
const auto debugGroup = parameters.encoder->createDebugGroup(getName() + "-render");
|
||||
#endif
|
||||
|
||||
auto& renderPass = static_cast<RenderPass&>(*parameters.renderPass);
|
||||
|
||||
bool bindUBOs = false;
|
||||
visitDrawables([&](gfx::Drawable& drawable) {
|
||||
if (!drawable.getEnabled() || !drawable.hasRenderPass(parameters.pass)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const auto& tweaker : drawable.getTweakers()) {
|
||||
tweaker->execute(drawable, parameters);
|
||||
}
|
||||
|
||||
if (!bindUBOs) {
|
||||
bindUniformBuffers(renderPass);
|
||||
bindUBOs = true;
|
||||
}
|
||||
|
||||
auto& drawableUniforms = drawable.mutableUniformBuffers();
|
||||
for (size_t i = 0; i < uniformBuffers.allocatedSize(); ++i) {
|
||||
if (uniformBuffers.get(i)) {
|
||||
drawableUniforms.set(i, uniformBuffers.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
drawable.draw(parameters);
|
||||
});
|
||||
|
||||
if (bindUBOs) {
|
||||
unbindUniformBuffers(renderPass);
|
||||
}
|
||||
}
|
||||
|
||||
void LayerGroup::bindUniformBuffers(RenderPass& renderPass) const noexcept {
|
||||
for (size_t id = 0; id < uniformBuffers.allocatedSize(); id++) {
|
||||
const auto& uniformBuffer = uniformBuffers.get(id);
|
||||
if (!uniformBuffer) continue;
|
||||
const auto& buffer = static_cast<UniformBuffer&>(*uniformBuffer);
|
||||
const auto& resource = buffer.getBufferResource();
|
||||
renderPass.bindVertex(resource, 0, id);
|
||||
renderPass.bindFragment(resource, 0, id);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
148
src/mbgl/vulkan/offscreen_texture.cpp
Normal file
148
src/mbgl/vulkan/offscreen_texture.cpp
Normal file
@@ -0,0 +1,148 @@
|
||||
#include <mbgl/vulkan/offscreen_texture.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/vulkan/renderable_resource.hpp>
|
||||
#include <mbgl/vulkan/renderer_backend.hpp>
|
||||
#include <mbgl/vulkan/texture2d.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
class OffscreenTextureResource final : public RenderableResource {
|
||||
public:
|
||||
OffscreenTextureResource(RendererBackend& backend_, const Size size_, const gfx::TextureChannelDataType type_)
|
||||
: RenderableResource(backend_),
|
||||
size(size_),
|
||||
type(type_) {
|
||||
assert(!size.isEmpty());
|
||||
|
||||
extent.width = size.width;
|
||||
extent.height = size.height;
|
||||
|
||||
colorTexture = backend.getContext().createTexture2D();
|
||||
auto& texture = static_cast<Texture2D&>(*colorTexture);
|
||||
|
||||
texture.setSize(size);
|
||||
texture.setFormat(gfx::TexturePixelType::RGBA, type);
|
||||
texture.setSamplerConfiguration(
|
||||
{gfx::TextureFilterType::Linear, gfx::TextureWrapType::Clamp, gfx::TextureWrapType::Clamp});
|
||||
texture.setUsage(Texture2DUsage::Attachment);
|
||||
|
||||
backend.getContext().renderingStats().numFrameBuffers++;
|
||||
}
|
||||
|
||||
~OffscreenTextureResource() noexcept override {
|
||||
framebuffer.reset();
|
||||
renderPass.reset();
|
||||
colorTexture.reset();
|
||||
|
||||
backend.getContext().renderingStats().numFrameBuffers--;
|
||||
}
|
||||
|
||||
void bind() override {
|
||||
colorTexture->create();
|
||||
createRenderPass();
|
||||
}
|
||||
|
||||
const vk::UniqueFramebuffer& getFramebuffer() const override { return framebuffer; };
|
||||
|
||||
PremultipliedImage readStillImage() {
|
||||
assert(false);
|
||||
return {};
|
||||
}
|
||||
|
||||
gfx::Texture2DPtr& getTexture() {
|
||||
assert(colorTexture);
|
||||
return colorTexture;
|
||||
}
|
||||
|
||||
void createRenderPass() {
|
||||
if (renderPass) return;
|
||||
|
||||
assert(colorTexture);
|
||||
auto& texture = static_cast<Texture2D&>(*colorTexture);
|
||||
|
||||
const auto colorAttachment = vk::AttachmentDescription(vk::AttachmentDescriptionFlags())
|
||||
.setFormat(texture.getVulkanFormat())
|
||||
.setSamples(vk::SampleCountFlagBits::e1)
|
||||
.setLoadOp(vk::AttachmentLoadOp::eClear)
|
||||
.setStoreOp(vk::AttachmentStoreOp::eStore)
|
||||
.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
|
||||
.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
|
||||
.setInitialLayout(vk::ImageLayout::eUndefined)
|
||||
.setFinalLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
|
||||
|
||||
const vk::AttachmentReference colorAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal);
|
||||
|
||||
const auto subpass = vk::SubpassDescription(vk::SubpassDescriptionFlags())
|
||||
.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
|
||||
.setColorAttachments(colorAttachmentRef);
|
||||
|
||||
const auto subpassSrcStageMask = vk::PipelineStageFlags() | vk::PipelineStageFlagBits::eColorAttachmentOutput |
|
||||
vk::PipelineStageFlagBits::eLateFragmentTests;
|
||||
|
||||
const auto subpassDstStageMask = vk::PipelineStageFlags() | vk::PipelineStageFlagBits::eColorAttachmentOutput |
|
||||
vk::PipelineStageFlagBits::eEarlyFragmentTests;
|
||||
|
||||
const auto subpassSrcAccessMask = vk::AccessFlags() | vk::AccessFlagBits::eDepthStencilAttachmentWrite;
|
||||
|
||||
const auto subpassDstAccessMask = vk::AccessFlags() | vk::AccessFlagBits::eColorAttachmentWrite |
|
||||
vk::AccessFlagBits::eDepthStencilAttachmentWrite;
|
||||
|
||||
const auto subpassDependency = vk::SubpassDependency()
|
||||
.setSrcSubpass(VK_SUBPASS_EXTERNAL)
|
||||
.setDstSubpass(0)
|
||||
.setSrcStageMask(subpassSrcStageMask)
|
||||
.setDstStageMask(subpassDstStageMask)
|
||||
.setSrcAccessMask(subpassSrcAccessMask)
|
||||
.setDstAccessMask(subpassDstAccessMask);
|
||||
|
||||
const auto renderPassCreateInfo = vk::RenderPassCreateInfo()
|
||||
.setAttachments(colorAttachment)
|
||||
.setSubpasses(subpass)
|
||||
.setDependencies(subpassDependency);
|
||||
|
||||
renderPass = backend.getDevice()->createRenderPassUnique(renderPassCreateInfo);
|
||||
|
||||
const auto framebufferCreateInfo = vk::FramebufferCreateInfo()
|
||||
.setRenderPass(renderPass.get())
|
||||
.setAttachments(texture.getVulkanImageView().get())
|
||||
.setAttachmentCount(1)
|
||||
.setWidth(extent.width)
|
||||
.setHeight(extent.height)
|
||||
.setLayers(1);
|
||||
|
||||
framebuffer = backend.getDevice()->createFramebufferUnique(framebufferCreateInfo);
|
||||
}
|
||||
|
||||
private:
|
||||
const Size size;
|
||||
const gfx::TextureChannelDataType type;
|
||||
|
||||
gfx::Texture2DPtr colorTexture;
|
||||
vk::UniqueFramebuffer framebuffer;
|
||||
};
|
||||
|
||||
OffscreenTexture::OffscreenTexture(Context& context,
|
||||
const Size size_,
|
||||
const gfx::TextureChannelDataType type,
|
||||
[[maybe_unused]] bool depth,
|
||||
[[maybe_unused]] bool stencil)
|
||||
: gfx::OffscreenTexture(size, std::make_unique<OffscreenTextureResource>(context.getBackend(), size_, type)) {
|
||||
assert(!depth);
|
||||
assert(!stencil);
|
||||
}
|
||||
|
||||
bool OffscreenTexture::isRenderable() {
|
||||
return true;
|
||||
}
|
||||
|
||||
PremultipliedImage OffscreenTexture::readStillImage() {
|
||||
return getResource<OffscreenTextureResource>().readStillImage();
|
||||
}
|
||||
|
||||
const gfx::Texture2DPtr& OffscreenTexture::getTexture() {
|
||||
return getResource<OffscreenTextureResource>().getTexture();
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
441
src/mbgl/vulkan/pipeline.cpp
Normal file
441
src/mbgl/vulkan/pipeline.cpp
Normal file
@@ -0,0 +1,441 @@
|
||||
#include <mbgl/vulkan/pipeline.hpp>
|
||||
#include <mbgl/gfx/cull_face_mode.hpp>
|
||||
#include <mbgl/util/hash.hpp>
|
||||
#include <mbgl/vulkan/renderable_resource.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
vk::Format PipelineInfo::vulkanFormat(const gfx::AttributeDataType& value) {
|
||||
switch (value) {
|
||||
case gfx::AttributeDataType::Byte:
|
||||
return vk::Format::eR8Sscaled;
|
||||
case gfx::AttributeDataType::Byte2:
|
||||
return vk::Format::eR8G8Sscaled;
|
||||
case gfx::AttributeDataType::Byte3:
|
||||
return vk::Format::eR8G8B8Sscaled;
|
||||
case gfx::AttributeDataType::Byte4:
|
||||
return vk::Format::eR8G8B8A8Sscaled;
|
||||
case gfx::AttributeDataType::UByte:
|
||||
return vk::Format::eR8Uscaled;
|
||||
case gfx::AttributeDataType::UByte2:
|
||||
return vk::Format::eR8G8Uscaled;
|
||||
case gfx::AttributeDataType::UByte3:
|
||||
return vk::Format::eR8G8B8Uscaled;
|
||||
case gfx::AttributeDataType::UByte4:
|
||||
return vk::Format::eR8G8B8A8Uscaled;
|
||||
case gfx::AttributeDataType::Short:
|
||||
return vk::Format::eR16Sscaled;
|
||||
case gfx::AttributeDataType::Short2:
|
||||
return vk::Format::eR16G16Sscaled;
|
||||
case gfx::AttributeDataType::Short3:
|
||||
return vk::Format::eR16G16B16Sscaled;
|
||||
case gfx::AttributeDataType::Short4:
|
||||
return vk::Format::eR16G16B16A16Sscaled;
|
||||
case gfx::AttributeDataType::UShort:
|
||||
return vk::Format::eR16Uscaled;
|
||||
case gfx::AttributeDataType::UShort2:
|
||||
return vk::Format::eR16G16Uscaled;
|
||||
case gfx::AttributeDataType::UShort3:
|
||||
return vk::Format::eR16G16B16Uscaled;
|
||||
case gfx::AttributeDataType::UShort4:
|
||||
return vk::Format::eR16G16B16A16Uscaled;
|
||||
case gfx::AttributeDataType::Int:
|
||||
return vk::Format::eR32Sint;
|
||||
case gfx::AttributeDataType::Int2:
|
||||
return vk::Format::eR32G32Sint;
|
||||
case gfx::AttributeDataType::Int3:
|
||||
return vk::Format::eR32G32B32Sint;
|
||||
case gfx::AttributeDataType::Int4:
|
||||
return vk::Format::eR32G32B32A32Sint;
|
||||
case gfx::AttributeDataType::UInt:
|
||||
return vk::Format::eR32Uint;
|
||||
case gfx::AttributeDataType::UInt2:
|
||||
return vk::Format::eR32G32Uint;
|
||||
case gfx::AttributeDataType::UInt3:
|
||||
return vk::Format::eR32G32B32Uint;
|
||||
case gfx::AttributeDataType::UInt4:
|
||||
return vk::Format::eR32G32B32A32Uint;
|
||||
case gfx::AttributeDataType::Float:
|
||||
return vk::Format::eR32Sfloat;
|
||||
case gfx::AttributeDataType::Float2:
|
||||
return vk::Format::eR32G32Sfloat;
|
||||
case gfx::AttributeDataType::Float3:
|
||||
return vk::Format::eR32G32B32Sfloat;
|
||||
case gfx::AttributeDataType::Float4:
|
||||
return vk::Format::eR32G32B32A32Sfloat;
|
||||
|
||||
default:
|
||||
[[fallthrough]];
|
||||
case gfx::AttributeDataType::UShort8:
|
||||
[[fallthrough]];
|
||||
case gfx::AttributeDataType::Invalid:
|
||||
return vk ::Format::eUndefined;
|
||||
}
|
||||
}
|
||||
|
||||
vk::PrimitiveTopology PipelineInfo::vulkanPrimitiveTopology(const gfx::DrawModeType& value) {
|
||||
switch (value) {
|
||||
case gfx::DrawModeType::Points:
|
||||
return vk::PrimitiveTopology::ePointList;
|
||||
case gfx::DrawModeType::Lines:
|
||||
return vk::PrimitiveTopology::eLineList;
|
||||
case gfx::DrawModeType::LineLoop:
|
||||
return vk::PrimitiveTopology::eLineStrip;
|
||||
case gfx::DrawModeType::LineStrip:
|
||||
return vk::PrimitiveTopology::eLineStrip;
|
||||
case gfx::DrawModeType::Triangles:
|
||||
return vk::PrimitiveTopology::eTriangleList;
|
||||
case gfx::DrawModeType::TriangleStrip:
|
||||
return vk::PrimitiveTopology::eTriangleStrip;
|
||||
case gfx::DrawModeType::TriangleFan:
|
||||
return vk::PrimitiveTopology::eTriangleFan;
|
||||
default:
|
||||
return vk::PrimitiveTopology::eTriangleList;
|
||||
}
|
||||
}
|
||||
|
||||
vk::CullModeFlagBits PipelineInfo::vulkanCullMode(const gfx::CullFaceSideType& value) {
|
||||
switch (value) {
|
||||
case gfx::CullFaceSideType::Back:
|
||||
return vk::CullModeFlagBits::eBack;
|
||||
case gfx::CullFaceSideType::Front:
|
||||
return vk::CullModeFlagBits::eFront;
|
||||
case gfx::CullFaceSideType::FrontAndBack:
|
||||
return vk::CullModeFlagBits::eFrontAndBack;
|
||||
default:
|
||||
return vk::CullModeFlagBits::eNone;
|
||||
}
|
||||
}
|
||||
|
||||
vk::FrontFace PipelineInfo::vulkanFrontFace(const gfx::CullFaceWindingType& value) {
|
||||
switch (value) {
|
||||
default:
|
||||
[[fallthrough]];
|
||||
case gfx::CullFaceWindingType::Clockwise:
|
||||
return vk::FrontFace::eClockwise;
|
||||
case gfx::CullFaceWindingType::CounterClockwise:
|
||||
return vk::FrontFace::eCounterClockwise;
|
||||
}
|
||||
}
|
||||
|
||||
vk::BlendOp PipelineInfo::vulkanBlendOp(const gfx::ColorBlendEquationType& value) {
|
||||
switch (value) {
|
||||
default:
|
||||
[[fallthrough]];
|
||||
case gfx::ColorBlendEquationType::Add:
|
||||
return vk::BlendOp::eAdd;
|
||||
case gfx::ColorBlendEquationType::Subtract:
|
||||
return vk::BlendOp::eSubtract;
|
||||
case gfx::ColorBlendEquationType::ReverseSubtract:
|
||||
return vk::BlendOp::eReverseSubtract;
|
||||
}
|
||||
}
|
||||
|
||||
vk::BlendFactor PipelineInfo::vulkanBlendFactor(const gfx::ColorBlendFactorType& value) {
|
||||
switch (value) {
|
||||
default:
|
||||
[[fallthrough]];
|
||||
case gfx::ColorBlendFactorType::Zero:
|
||||
return vk::BlendFactor::eZero;
|
||||
case gfx::ColorBlendFactorType::One:
|
||||
return vk::BlendFactor::eOne;
|
||||
case gfx::ColorBlendFactorType::SrcColor:
|
||||
return vk::BlendFactor::eSrcColor;
|
||||
case gfx::ColorBlendFactorType::OneMinusSrcColor:
|
||||
return vk::BlendFactor::eOneMinusSrcColor;
|
||||
case gfx::ColorBlendFactorType::SrcAlpha:
|
||||
return vk::BlendFactor::eSrcAlpha;
|
||||
case gfx::ColorBlendFactorType::OneMinusSrcAlpha:
|
||||
return vk::BlendFactor::eOneMinusSrcAlpha;
|
||||
case gfx::ColorBlendFactorType::DstAlpha:
|
||||
return vk::BlendFactor::eDstAlpha;
|
||||
case gfx::ColorBlendFactorType::OneMinusDstAlpha:
|
||||
return vk::BlendFactor::eOneMinusDstAlpha;
|
||||
case gfx::ColorBlendFactorType::DstColor:
|
||||
return vk::BlendFactor::eDstColor;
|
||||
case gfx::ColorBlendFactorType::OneMinusDstColor:
|
||||
return vk::BlendFactor::eOneMinusDstColor;
|
||||
case gfx::ColorBlendFactorType::SrcAlphaSaturate:
|
||||
return vk::BlendFactor::eSrcAlphaSaturate;
|
||||
case gfx::ColorBlendFactorType::ConstantColor:
|
||||
return vk::BlendFactor::eConstantColor;
|
||||
case gfx::ColorBlendFactorType::OneMinusConstantColor:
|
||||
return vk::BlendFactor::eOneMinusConstantColor;
|
||||
case gfx::ColorBlendFactorType::ConstantAlpha:
|
||||
return vk::BlendFactor::eConstantAlpha;
|
||||
case gfx::ColorBlendFactorType::OneMinusConstantAlpha:
|
||||
return vk::BlendFactor::eOneMinusConstantAlpha;
|
||||
}
|
||||
}
|
||||
|
||||
vk::CompareOp PipelineInfo::vulkanCompareOp(const gfx::DepthFunctionType& value) {
|
||||
switch (value) {
|
||||
default:
|
||||
[[fallthrough]];
|
||||
case gfx::DepthFunctionType::Never:
|
||||
return vk::CompareOp::eNever;
|
||||
case gfx::DepthFunctionType::Less:
|
||||
return vk::CompareOp::eLess;
|
||||
case gfx::DepthFunctionType::Equal:
|
||||
return vk::CompareOp::eEqual;
|
||||
case gfx::DepthFunctionType::LessEqual:
|
||||
return vk::CompareOp::eLessOrEqual;
|
||||
case gfx::DepthFunctionType::Greater:
|
||||
return vk::CompareOp::eGreater;
|
||||
case gfx::DepthFunctionType::NotEqual:
|
||||
return vk::CompareOp::eNotEqual;
|
||||
case gfx::DepthFunctionType::GreaterEqual:
|
||||
return vk::CompareOp::eGreaterOrEqual;
|
||||
case gfx::DepthFunctionType::Always:
|
||||
return vk::CompareOp::eAlways;
|
||||
}
|
||||
}
|
||||
|
||||
vk::CompareOp PipelineInfo::vulkanCompareOp(const gfx::StencilFunctionType& value) {
|
||||
switch (value) {
|
||||
default:
|
||||
[[fallthrough]];
|
||||
case gfx::StencilFunctionType::Never:
|
||||
return vk::CompareOp::eNever;
|
||||
case gfx::StencilFunctionType::Less:
|
||||
return vk::CompareOp::eLess;
|
||||
case gfx::StencilFunctionType::Equal:
|
||||
return vk::CompareOp::eEqual;
|
||||
case gfx::StencilFunctionType::LessEqual:
|
||||
return vk::CompareOp::eLessOrEqual;
|
||||
case gfx::StencilFunctionType::Greater:
|
||||
return vk::CompareOp::eGreater;
|
||||
case gfx::StencilFunctionType::NotEqual:
|
||||
return vk::CompareOp::eNotEqual;
|
||||
case gfx::StencilFunctionType::GreaterEqual:
|
||||
return vk::CompareOp::eGreaterOrEqual;
|
||||
case gfx::StencilFunctionType::Always:
|
||||
return vk::CompareOp::eAlways;
|
||||
}
|
||||
}
|
||||
|
||||
vk::StencilOp PipelineInfo::vulkanStencilOp(const gfx::StencilOpType& value) {
|
||||
switch (value) {
|
||||
default:
|
||||
[[fallthrough]];
|
||||
case gfx::StencilOpType::Zero:
|
||||
return vk::StencilOp::eZero;
|
||||
case gfx::StencilOpType::Keep:
|
||||
return vk::StencilOp::eKeep;
|
||||
case gfx::StencilOpType::Replace:
|
||||
return vk::StencilOp::eReplace;
|
||||
case gfx::StencilOpType::Increment:
|
||||
return vk::StencilOp::eIncrementAndClamp;
|
||||
case gfx::StencilOpType::Decrement:
|
||||
return vk::StencilOp::eDecrementAndClamp;
|
||||
case gfx::StencilOpType::Invert:
|
||||
return vk::StencilOp::eInvert;
|
||||
case gfx::StencilOpType::IncrementWrap:
|
||||
return vk::StencilOp::eIncrementAndWrap;
|
||||
case gfx::StencilOpType::DecrementWrap:
|
||||
return vk::StencilOp::eDecrementAndWrap;
|
||||
}
|
||||
}
|
||||
|
||||
void PipelineInfo::setCullMode(const gfx::CullFaceMode& value) {
|
||||
cullMode = value.enabled ? vulkanCullMode(value.side) : vk::CullModeFlagBits::eNone;
|
||||
frontFace = vulkanFrontFace(value.winding);
|
||||
}
|
||||
|
||||
void PipelineInfo::setDrawMode(const gfx::DrawModeType& value) {
|
||||
topology = vulkanPrimitiveTopology(value);
|
||||
}
|
||||
|
||||
void PipelineInfo::setDrawMode(const gfx::DrawMode& value) {
|
||||
topology = vulkanPrimitiveTopology(value.type);
|
||||
|
||||
if (value.type == gfx::DrawModeType::Lines || value.type == gfx::DrawModeType::LineStrip ||
|
||||
value.type == gfx::DrawModeType::LineLoop) {
|
||||
setLineWidth(value.size);
|
||||
} else {
|
||||
setLineWidth(1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
void PipelineInfo::setColorBlend(const gfx::ColorMode& value) {
|
||||
setColorBlendFunction(value.blendFunction);
|
||||
|
||||
if (usesBlendConstants()) {
|
||||
dynamicValues.blendConstants = value.blendColor;
|
||||
} else {
|
||||
dynamicValues.blendConstants.reset();
|
||||
}
|
||||
|
||||
colorMask = vk::ColorComponentFlags();
|
||||
|
||||
if (value.mask.r) colorMask |= vk::ColorComponentFlagBits::eR;
|
||||
if (value.mask.g) colorMask |= vk::ColorComponentFlagBits::eG;
|
||||
if (value.mask.b) colorMask |= vk::ColorComponentFlagBits::eB;
|
||||
if (value.mask.a) colorMask |= vk::ColorComponentFlagBits::eA;
|
||||
}
|
||||
|
||||
void PipelineInfo::setColorBlendFunction(const gfx::ColorMode::BlendFunction& value) {
|
||||
colorBlend = !value.is<gfx::ColorMode::Replace>();
|
||||
|
||||
apply_visitor(
|
||||
[&](const auto& blendFunction) {
|
||||
colorBlendFunction = vulkanBlendOp(blendFunction.equation);
|
||||
srcBlendFactor = vulkanBlendFactor(blendFunction.srcFactor);
|
||||
dstBlendFactor = vulkanBlendFactor(blendFunction.dstFactor);
|
||||
},
|
||||
value);
|
||||
}
|
||||
|
||||
void PipelineInfo::setDepthWrite(const gfx::DepthMaskType& value) {
|
||||
switch (value) {
|
||||
default:
|
||||
[[fallthrough]];
|
||||
case gfx::DepthMaskType::ReadOnly:
|
||||
depthWrite = false;
|
||||
break;
|
||||
case gfx::DepthMaskType::ReadWrite:
|
||||
depthWrite = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void PipelineInfo::setDepthMode(const gfx::DepthMode& value) {
|
||||
depthFunction = vulkanCompareOp(value.func);
|
||||
setDepthWrite(value.mask);
|
||||
}
|
||||
|
||||
void PipelineInfo::setStencilMode(const gfx::StencilMode& value) {
|
||||
if (value.test.is<gfx::StencilMode::Always>()) {
|
||||
stencilTest = false;
|
||||
stencilFunction = vk::CompareOp::eNever;
|
||||
return;
|
||||
}
|
||||
|
||||
stencilTest = true;
|
||||
|
||||
if (value.test.is<gfx::StencilMode::Never>()) {
|
||||
stencilFunction = vk::CompareOp::eNever;
|
||||
return;
|
||||
}
|
||||
|
||||
apply_visitor(
|
||||
[&](const auto& test) {
|
||||
stencilFunction = vulkanCompareOp(test.func);
|
||||
dynamicValues.stencilCompareMask = test.mask;
|
||||
},
|
||||
value.test);
|
||||
|
||||
dynamicValues.stencilWriteMask = value.mask;
|
||||
dynamicValues.stencilRef = value.ref;
|
||||
|
||||
stencilPass = vulkanStencilOp(value.pass);
|
||||
stencilFail = vulkanStencilOp(value.fail);
|
||||
stencilDepthFail = vulkanStencilOp(value.depthFail);
|
||||
}
|
||||
|
||||
void PipelineInfo::setRenderable(const gfx::Renderable& value) {
|
||||
const auto& renderableResource = value.getResource<RenderableResource>();
|
||||
|
||||
renderPass = renderableResource.getRenderPass().get();
|
||||
viewExtent = renderableResource.getExtent();
|
||||
}
|
||||
|
||||
void PipelineInfo::setLineWidth(float value) {
|
||||
wideLines = value != 1.0f;
|
||||
dynamicValues.lineWidth = value;
|
||||
}
|
||||
|
||||
bool PipelineInfo::usesBlendConstants() const {
|
||||
if (srcBlendFactor == vk::BlendFactor::eConstantAlpha || srcBlendFactor == vk::BlendFactor::eConstantColor ||
|
||||
srcBlendFactor == vk::BlendFactor::eOneMinusConstantAlpha ||
|
||||
srcBlendFactor == vk::BlendFactor::eOneMinusConstantColor) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (dstBlendFactor == vk::BlendFactor::eConstantAlpha || dstBlendFactor == vk::BlendFactor::eConstantColor ||
|
||||
dstBlendFactor == vk::BlendFactor::eOneMinusConstantAlpha ||
|
||||
dstBlendFactor == vk::BlendFactor::eOneMinusConstantColor) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void PipelineInfo::updateVertexInputHash() {
|
||||
vertexInputHash = 0;
|
||||
|
||||
for (const auto& value : inputAttributes) {
|
||||
util::hash_combine(vertexInputHash, value.binding);
|
||||
util::hash_combine(vertexInputHash, value.format);
|
||||
util::hash_combine(vertexInputHash, value.location);
|
||||
util::hash_combine(vertexInputHash, value.offset);
|
||||
}
|
||||
|
||||
for (const auto& value : inputBindings) {
|
||||
util::hash_combine(vertexInputHash, value.binding);
|
||||
util::hash_combine(vertexInputHash, value.inputRate);
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t PipelineInfo::hash() const {
|
||||
return util::hash(topology,
|
||||
cullMode,
|
||||
frontFace,
|
||||
polygonMode,
|
||||
colorBlend,
|
||||
colorBlendFunction,
|
||||
srcBlendFactor,
|
||||
dstBlendFactor,
|
||||
VkColorComponentFlags(colorMask),
|
||||
depthTest,
|
||||
depthWrite,
|
||||
depthFunction,
|
||||
stencilTest,
|
||||
stencilFunction,
|
||||
stencilPass,
|
||||
stencilFail,
|
||||
stencilDepthFail,
|
||||
wideLines,
|
||||
VkRenderPass(renderPass),
|
||||
vertexInputHash);
|
||||
}
|
||||
|
||||
void PipelineInfo::setDynamicValues(const vk::UniqueCommandBuffer& buffer) const {
|
||||
if (dynamicValues.blendConstants.has_value()) {
|
||||
buffer->setBlendConstants(dynamicValues.blendConstants.value().data());
|
||||
}
|
||||
|
||||
if (stencilTest) {
|
||||
buffer->setStencilWriteMask(vk::StencilFaceFlagBits::eFrontAndBack, dynamicValues.stencilWriteMask);
|
||||
buffer->setStencilCompareMask(vk::StencilFaceFlagBits::eFrontAndBack, dynamicValues.stencilCompareMask);
|
||||
buffer->setStencilReference(vk::StencilFaceFlagBits::eFrontAndBack, dynamicValues.stencilRef);
|
||||
}
|
||||
|
||||
if (wideLines) {
|
||||
buffer->setLineWidth(dynamicValues.lineWidth);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<vk::DynamicState> PipelineInfo::getDynamicStates() const {
|
||||
std::vector<vk::DynamicState> dynamicStates;
|
||||
|
||||
if (usesBlendConstants()) {
|
||||
dynamicStates.push_back(vk::DynamicState::eBlendConstants);
|
||||
}
|
||||
|
||||
if (stencilTest) {
|
||||
dynamicStates.push_back(vk::DynamicState::eStencilCompareMask);
|
||||
dynamicStates.push_back(vk::DynamicState::eStencilWriteMask);
|
||||
dynamicStates.push_back(vk::DynamicState::eStencilReference);
|
||||
}
|
||||
|
||||
if (wideLines) {
|
||||
dynamicStates.push_back(vk::DynamicState::eLineWidth);
|
||||
}
|
||||
|
||||
return dynamicStates;
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
85
src/mbgl/vulkan/render_pass.cpp
Normal file
85
src/mbgl/vulkan/render_pass.cpp
Normal file
@@ -0,0 +1,85 @@
|
||||
#include <mbgl/vulkan/render_pass.hpp>
|
||||
|
||||
#include <mbgl/vulkan/command_encoder.hpp>
|
||||
#include <mbgl/vulkan/renderable_resource.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
RenderPass::RenderPass(CommandEncoder& commandEncoder_, const char* name, const gfx::RenderPassDescriptor& descriptor)
|
||||
: descriptor(descriptor),
|
||||
commandEncoder(commandEncoder_) {
|
||||
auto& resource = descriptor.renderable.getResource<RenderableResource>();
|
||||
|
||||
resource.bind();
|
||||
|
||||
std::array<vk::ClearValue, 2> clearValues;
|
||||
|
||||
if (descriptor.clearColor.has_value())
|
||||
clearValues[0].setColor(descriptor.clearColor.value().operator std::array<float, 4>());
|
||||
clearValues[1].depthStencil.setDepth(descriptor.clearDepth.value_or(1.0f));
|
||||
clearValues[1].depthStencil.setStencil(descriptor.clearStencil.value_or(0));
|
||||
|
||||
const auto renderPassBeginInfo = vk::RenderPassBeginInfo()
|
||||
.setRenderPass(resource.getRenderPass().get())
|
||||
.setFramebuffer(resource.getFramebuffer().get())
|
||||
.setRenderArea({{0, 0}, resource.getExtent()})
|
||||
.setClearValues(clearValues);
|
||||
|
||||
pushDebugGroup(name);
|
||||
|
||||
commandEncoder.getCommandBuffer()->beginRenderPass(renderPassBeginInfo, vk::SubpassContents::eInline);
|
||||
|
||||
commandEncoder.context.performCleanup();
|
||||
}
|
||||
|
||||
RenderPass::~RenderPass() {
|
||||
endEncoding();
|
||||
|
||||
popDebugGroup();
|
||||
}
|
||||
|
||||
void RenderPass::endEncoding() {
|
||||
commandEncoder.getCommandBuffer()->endRenderPass();
|
||||
}
|
||||
|
||||
void RenderPass::clearStencil(uint32_t value) const {
|
||||
const auto& resource = descriptor.renderable.getResource<RenderableResource>();
|
||||
const auto& extent = resource.getExtent();
|
||||
|
||||
const auto attach = vk::ClearAttachment()
|
||||
.setAspectMask(vk::ImageAspectFlagBits::eStencil)
|
||||
.setClearValue(vk::ClearDepthStencilValue(0.0f, value));
|
||||
|
||||
const auto& rect = vk::ClearRect().setBaseArrayLayer(0).setLayerCount(1).setRect(
|
||||
{{0, 0}, {extent.width, extent.height}});
|
||||
|
||||
commandEncoder.getCommandBuffer()->clearAttachments(attach, rect);
|
||||
}
|
||||
|
||||
void RenderPass::pushDebugGroup(const char* name) {
|
||||
commandEncoder.pushDebugGroup(name);
|
||||
}
|
||||
|
||||
void RenderPass::popDebugGroup() {
|
||||
commandEncoder.popDebugGroup();
|
||||
}
|
||||
|
||||
void RenderPass::addDebugSignpost(const char* name) {
|
||||
commandEncoder.getContext().getBackend().insertDebugLabel(commandEncoder.getCommandBuffer().get(), name);
|
||||
}
|
||||
|
||||
void RenderPass::bindVertex(const BufferResource& buf, std::size_t offset, std::size_t, std::size_t size) {
|
||||
[[maybe_unused]] const auto actualSize = size ? size : buf.getSizeInBytes() - offset;
|
||||
assert(actualSize <= buf.getSizeInBytes());
|
||||
}
|
||||
|
||||
void RenderPass::bindFragment(const BufferResource& buf, std::size_t offset, std::size_t, std::size_t size) {
|
||||
[[maybe_unused]] const auto actualSize = size ? size : buf.getSizeInBytes() - offset;
|
||||
assert(actualSize <= buf.getSizeInBytes());
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
344
src/mbgl/vulkan/renderable_resource.cpp
Normal file
344
src/mbgl/vulkan/renderable_resource.cpp
Normal file
@@ -0,0 +1,344 @@
|
||||
#include <mbgl/vulkan/renderable_resource.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
static bool hasMemoryType(const vk::PhysicalDevice& physicalDevice, const vk::MemoryPropertyFlagBits& type) {
|
||||
const auto& memoryProps = physicalDevice.getMemoryProperties();
|
||||
for (uint32_t i = 0; i < memoryProps.memoryTypeCount; ++i) {
|
||||
if (memoryProps.memoryTypes[i].propertyFlags & type) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
SurfaceRenderableResource::~SurfaceRenderableResource() {
|
||||
// specific order
|
||||
swapchainFramebuffers.clear();
|
||||
renderPass.reset();
|
||||
swapchainImageViews.clear();
|
||||
swapchainImages.clear();
|
||||
swapchain.reset();
|
||||
surface.reset();
|
||||
|
||||
depthAllocation.reset();
|
||||
colorAllocations.clear();
|
||||
}
|
||||
|
||||
void SurfaceRenderableResource::initColor(uint32_t w, uint32_t h) {
|
||||
const uint32_t imageCount = backend.getMaxFrames();
|
||||
|
||||
colorAllocations.reserve(imageCount);
|
||||
swapchainImages.reserve(imageCount);
|
||||
|
||||
colorFormat = vk::Format::eR8G8B8A8Unorm;
|
||||
extent = vk::Extent2D(w, h);
|
||||
|
||||
const auto imageUsage = vk::ImageUsageFlags() | vk::ImageUsageFlagBits::eColorAttachment |
|
||||
vk::ImageUsageFlagBits::eTransferSrc;
|
||||
|
||||
const auto imageCreateInfo = vk::ImageCreateInfo()
|
||||
.setImageType(vk::ImageType::e2D)
|
||||
.setFormat(colorFormat)
|
||||
.setExtent({w, h, 1})
|
||||
.setMipLevels(1)
|
||||
.setArrayLayers(1)
|
||||
.setSamples(vk::SampleCountFlagBits::e1)
|
||||
.setTiling(vk::ImageTiling::eOptimal)
|
||||
.setUsage(imageUsage)
|
||||
.setSharingMode(vk::SharingMode::eExclusive)
|
||||
.setInitialLayout(vk::ImageLayout::eUndefined);
|
||||
|
||||
VmaAllocationCreateInfo allocCreateInfo = {};
|
||||
|
||||
allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
|
||||
allocCreateInfo.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
|
||||
|
||||
for (uint32_t i = 0; i < imageCount; ++i) {
|
||||
colorAllocations.push_back(std::make_unique<ImageAllocation>(backend.getAllocator()));
|
||||
auto& colorAllocation = colorAllocations.back();
|
||||
|
||||
if (!colorAllocation->create(allocCreateInfo, imageCreateInfo)) {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Vulkan color texture allocation failed");
|
||||
}
|
||||
|
||||
swapchainImages.push_back(colorAllocation->image);
|
||||
}
|
||||
}
|
||||
|
||||
void SurfaceRenderableResource::initSwapchain(uint32_t w, uint32_t h) {
|
||||
const auto& physicalDevice = backend.getPhysicalDevice();
|
||||
const auto& device = backend.getDevice();
|
||||
|
||||
const std::vector<vk::SurfaceFormatKHR>& formats = physicalDevice.getSurfaceFormatsKHR(surface.get());
|
||||
const auto& formatIt = std::find_if(formats.begin(), formats.end(), [](const vk::SurfaceFormatKHR& format) {
|
||||
return (format.format == vk::Format::eB8G8R8A8Unorm || format.format == vk::Format::eR8G8B8A8Unorm) &&
|
||||
format.colorSpace == vk::ColorSpaceKHR::eSrgbNonlinear;
|
||||
});
|
||||
|
||||
if (formatIt == formats.end()) throw std::runtime_error("No suitable swapchain format found");
|
||||
|
||||
// only vk::PresentModeKHR::eFifo (vsync on) is guaranteed
|
||||
// TODO check for vk::PresentModeKHR::eImmediate when uncapped
|
||||
|
||||
// pick surface size
|
||||
const vk::SurfaceCapabilitiesKHR& capabilities = physicalDevice.getSurfaceCapabilitiesKHR(surface.get());
|
||||
|
||||
if (capabilities.currentExtent.width != std::numeric_limits<uint32_t>::max()) {
|
||||
extent = capabilities.currentExtent;
|
||||
} else {
|
||||
// update values based on surface limits
|
||||
extent.width = std::min(std::max(w, capabilities.minImageExtent.width), capabilities.maxImageExtent.width);
|
||||
extent.height = std::min(std::max(h, capabilities.minImageExtent.height), capabilities.maxImageExtent.height);
|
||||
}
|
||||
|
||||
uint32_t swapchainImageCount = capabilities.minImageCount + 1;
|
||||
// check surface limits (0 is unlimited)
|
||||
if (capabilities.maxImageCount > 0) swapchainImageCount = std::min(swapchainImageCount, capabilities.maxImageCount);
|
||||
|
||||
auto swapchainCreateInfo = vk::SwapchainCreateInfoKHR()
|
||||
.setSurface(surface.get())
|
||||
.setMinImageCount(swapchainImageCount)
|
||||
.setImageFormat(formatIt->format)
|
||||
.setImageColorSpace(formatIt->colorSpace)
|
||||
.setPresentMode(vk::PresentModeKHR::eFifo)
|
||||
.setImageExtent(extent)
|
||||
.setImageArrayLayers(1)
|
||||
.setImageUsage(vk::ImageUsageFlagBits::eColorAttachment);
|
||||
|
||||
int32_t graphicsQueueIndex = backend.getGraphicsQueueIndex();
|
||||
int32_t presentQueueIndex = backend.getPresentQueueIndex();
|
||||
|
||||
if (graphicsQueueIndex != presentQueueIndex) {
|
||||
// TODO if this scenario is widespred and performance is a problem (shouldn't be the case on most hardware)
|
||||
// rework to vk::SharingMode::eExclusive + queue ownership
|
||||
swapchainCreateInfo.setImageSharingMode(vk::SharingMode::eConcurrent);
|
||||
const std::array<uint32_t, 2> queueIndices = {static_cast<uint32_t>(graphicsQueueIndex),
|
||||
static_cast<uint32_t>(presentQueueIndex)};
|
||||
swapchainCreateInfo.setQueueFamilyIndices(queueIndices);
|
||||
} else {
|
||||
swapchainCreateInfo.setImageSharingMode(vk::SharingMode::eExclusive);
|
||||
}
|
||||
|
||||
swapchainCreateInfo.setPreTransform(capabilities.currentTransform);
|
||||
swapchainCreateInfo.setClipped(VK_TRUE);
|
||||
|
||||
if (capabilities.supportedCompositeAlpha & vk::CompositeAlphaFlagBitsKHR::eInherit) {
|
||||
swapchainCreateInfo.setCompositeAlpha(vk::CompositeAlphaFlagBitsKHR::eInherit);
|
||||
} else {
|
||||
swapchainCreateInfo.setCompositeAlpha(vk::CompositeAlphaFlagBitsKHR::eOpaque);
|
||||
}
|
||||
|
||||
// update this when recreating
|
||||
swapchainCreateInfo.setOldSwapchain(vk::SwapchainKHR(swapchain.get()));
|
||||
|
||||
swapchain = device->createSwapchainKHRUnique(swapchainCreateInfo);
|
||||
swapchainImages = device->getSwapchainImagesKHR(swapchain.get());
|
||||
|
||||
colorFormat = swapchainCreateInfo.imageFormat;
|
||||
extent = swapchainCreateInfo.imageExtent;
|
||||
}
|
||||
|
||||
void SurfaceRenderableResource::initDepthStencil() {
|
||||
const auto& physicalDevice = backend.getPhysicalDevice();
|
||||
const auto& device = backend.getDevice();
|
||||
|
||||
// check for depth format support
|
||||
const std::vector<vk::Format> formats = {
|
||||
vk::Format::eD24UnormS8Uint,
|
||||
vk::Format::eD32SfloatS8Uint,
|
||||
vk::Format::eD16UnormS8Uint,
|
||||
};
|
||||
|
||||
const auto& formatIt = std::find_if(formats.begin(), formats.end(), [&](const auto& format) {
|
||||
const auto& formatProps = physicalDevice.getFormatProperties(format);
|
||||
return formatProps.optimalTilingFeatures & vk::FormatFeatureFlagBits::eDepthStencilAttachment;
|
||||
});
|
||||
|
||||
if (formatIt == formats.end()) {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Depth/Stencil format not available");
|
||||
return;
|
||||
}
|
||||
|
||||
depthFormat = *formatIt;
|
||||
|
||||
const bool hasLazyMemory = hasMemoryType(physicalDevice, vk::MemoryPropertyFlagBits::eLazilyAllocated);
|
||||
const auto memoryUsage = hasLazyMemory ? VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED
|
||||
: VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
|
||||
|
||||
const auto imageUsage = vk::ImageUsageFlags() | vk::ImageUsageFlagBits::eDepthStencilAttachment |
|
||||
vk::ImageUsageFlagBits::eTransientAttachment;
|
||||
|
||||
const auto imageCreateInfo = vk::ImageCreateInfo()
|
||||
.setImageType(vk::ImageType::e2D)
|
||||
.setFormat(depthFormat)
|
||||
.setExtent({extent.width, extent.height, 1})
|
||||
.setMipLevels(1)
|
||||
.setArrayLayers(1)
|
||||
.setSamples(vk::SampleCountFlagBits::e1)
|
||||
.setTiling(vk::ImageTiling::eOptimal)
|
||||
.setUsage(imageUsage)
|
||||
.setSharingMode(vk::SharingMode::eExclusive)
|
||||
.setInitialLayout(vk::ImageLayout::eUndefined);
|
||||
|
||||
VmaAllocationCreateInfo allocCreateInfo = {};
|
||||
allocCreateInfo.usage = memoryUsage;
|
||||
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
|
||||
|
||||
depthAllocation = std::make_unique<ImageAllocation>(backend.getAllocator());
|
||||
if (!depthAllocation->create(allocCreateInfo, imageCreateInfo)) {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Vulkan depth texture allocation failed");
|
||||
return;
|
||||
}
|
||||
|
||||
const auto imageViewCreateInfo =
|
||||
vk::ImageViewCreateInfo()
|
||||
.setImage(depthAllocation->image)
|
||||
.setViewType(vk::ImageViewType::e2D)
|
||||
.setFormat(depthFormat)
|
||||
.setComponents(vk::ComponentMapping()) // defaults to vk::ComponentSwizzle::eIdentity
|
||||
.setSubresourceRange(vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1));
|
||||
|
||||
depthAllocation->imageView = device->createImageViewUnique(imageViewCreateInfo);
|
||||
|
||||
backend.setDebugName(vk::Image(depthAllocation->image), "SwapchainDepthImage");
|
||||
backend.setDebugName(depthAllocation->imageView.get(), "SwapchainDepthImageView");
|
||||
}
|
||||
|
||||
const vk::Image SurfaceRenderableResource::getAcquiredImage() const {
|
||||
if (surface) {
|
||||
return swapchainImages[acquiredImageIndex];
|
||||
}
|
||||
|
||||
return colorAllocations[acquiredImageIndex]->image;
|
||||
}
|
||||
|
||||
void SurfaceRenderableResource::init(uint32_t w, uint32_t h) {
|
||||
if (surface) {
|
||||
initSwapchain(w, h);
|
||||
} else {
|
||||
initColor(w, h);
|
||||
}
|
||||
|
||||
const auto& device = backend.getDevice();
|
||||
|
||||
// create swapchain image views
|
||||
swapchainImageViews.reserve(swapchainImages.size());
|
||||
|
||||
auto imageViewCreateInfo = vk::ImageViewCreateInfo()
|
||||
.setViewType(vk::ImageViewType::e2D)
|
||||
.setFormat(colorFormat)
|
||||
.setComponents(vk::ComponentMapping()) // defaults to vk::ComponentSwizzle::eIdentity
|
||||
.setSubresourceRange(
|
||||
vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
|
||||
|
||||
for (const auto& image : swapchainImages) {
|
||||
imageViewCreateInfo.setImage(image);
|
||||
swapchainImageViews.push_back(device->createImageViewUnique(imageViewCreateInfo));
|
||||
|
||||
const size_t index = swapchainImageViews.size() - 1;
|
||||
backend.setDebugName(vk::Image(image), "SwapchainImage_" + std::to_string(index));
|
||||
backend.setDebugName(vk::Image(image), "SwapchainImageView_" + std::to_string(index));
|
||||
}
|
||||
|
||||
// depth resources
|
||||
initDepthStencil();
|
||||
|
||||
// create render pass
|
||||
const auto colorLayout = surface ? vk::ImageLayout::ePresentSrcKHR : vk::ImageLayout::eTransferSrcOptimal;
|
||||
const auto colorAttachment = vk::AttachmentDescription(vk::AttachmentDescriptionFlags())
|
||||
.setFormat(colorFormat)
|
||||
.setSamples(vk::SampleCountFlagBits::e1)
|
||||
.setLoadOp(vk::AttachmentLoadOp::eClear)
|
||||
.setStoreOp(vk::AttachmentStoreOp::eStore)
|
||||
.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
|
||||
.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
|
||||
.setInitialLayout(vk::ImageLayout::eUndefined)
|
||||
.setFinalLayout(colorLayout);
|
||||
|
||||
const vk::AttachmentReference colorAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal);
|
||||
|
||||
const auto depthAttachment = vk::AttachmentDescription()
|
||||
.setFormat(depthFormat)
|
||||
.setSamples(vk::SampleCountFlagBits::e1)
|
||||
.setLoadOp(vk::AttachmentLoadOp::eClear)
|
||||
.setStoreOp(vk::AttachmentStoreOp::eDontCare)
|
||||
.setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
|
||||
.setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
|
||||
.setInitialLayout(vk::ImageLayout::eUndefined)
|
||||
.setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
|
||||
|
||||
const vk::AttachmentReference depthAttachmentRef(1, vk::ImageLayout::eDepthStencilAttachmentOptimal);
|
||||
|
||||
const auto subpass = vk::SubpassDescription()
|
||||
.setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
|
||||
.setColorAttachmentCount(1)
|
||||
.setColorAttachments(colorAttachmentRef)
|
||||
.setPDepthStencilAttachment(&depthAttachmentRef);
|
||||
|
||||
const auto subpassSrcStageMask = vk::PipelineStageFlags() | vk::PipelineStageFlagBits::eColorAttachmentOutput |
|
||||
vk::PipelineStageFlagBits::eLateFragmentTests;
|
||||
|
||||
const auto subpassDstStageMask = vk::PipelineStageFlags() | vk::PipelineStageFlagBits::eColorAttachmentOutput |
|
||||
vk::PipelineStageFlagBits::eEarlyFragmentTests;
|
||||
|
||||
const auto subpassSrcAccessMask = vk::AccessFlags() | vk::AccessFlagBits::eDepthStencilAttachmentWrite;
|
||||
|
||||
const auto subpassDstAccessMask = vk::AccessFlags() | vk::AccessFlagBits::eColorAttachmentWrite |
|
||||
vk::AccessFlagBits::eDepthStencilAttachmentWrite;
|
||||
|
||||
const auto subpassDependency = vk::SubpassDependency()
|
||||
.setSrcSubpass(VK_SUBPASS_EXTERNAL)
|
||||
.setDstSubpass(0)
|
||||
.setSrcStageMask(subpassSrcStageMask)
|
||||
.setDstStageMask(subpassDstStageMask)
|
||||
.setSrcAccessMask(subpassSrcAccessMask)
|
||||
.setDstAccessMask(subpassDstAccessMask);
|
||||
|
||||
const std::array<vk::AttachmentDescription, 2> attachments = {colorAttachment, depthAttachment};
|
||||
const auto renderPassCreateInfo =
|
||||
vk::RenderPassCreateInfo().setAttachments(attachments).setSubpasses(subpass).setDependencies(subpassDependency);
|
||||
|
||||
renderPass = device->createRenderPassUnique(renderPassCreateInfo);
|
||||
|
||||
// create swapchain framebuffers
|
||||
swapchainFramebuffers.reserve(swapchainImageViews.size());
|
||||
|
||||
auto framebufferCreateInfo = vk::FramebufferCreateInfo()
|
||||
.setRenderPass(renderPass.get())
|
||||
.setAttachmentCount(2)
|
||||
.setWidth(extent.width)
|
||||
.setHeight(extent.height)
|
||||
.setLayers(1);
|
||||
|
||||
for (const auto& imageView : swapchainImageViews) {
|
||||
const std::array<vk::ImageView, 2> imageViews = {imageView.get(), depthAllocation->imageView.get()};
|
||||
|
||||
framebufferCreateInfo.setAttachments(imageViews);
|
||||
swapchainFramebuffers.push_back(device->createFramebufferUnique(framebufferCreateInfo));
|
||||
}
|
||||
}
|
||||
|
||||
void SurfaceRenderableResource::recreateSwapchain() {
|
||||
if (!surface) return;
|
||||
|
||||
backend.getDevice()->waitIdle();
|
||||
|
||||
swapchainFramebuffers.clear();
|
||||
renderPass.reset();
|
||||
swapchainImageViews.clear();
|
||||
swapchainImages.clear();
|
||||
|
||||
init(extent.width, extent.height);
|
||||
}
|
||||
|
||||
const vk::UniqueFramebuffer& SurfaceRenderableResource::getFramebuffer() const {
|
||||
return swapchainFramebuffers[backend.getContext<Context&>().getCurrentFrameResourceIndex()];
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
616
src/mbgl/vulkan/renderer_backend.cpp
Normal file
616
src/mbgl/vulkan/renderer_backend.cpp
Normal file
@@ -0,0 +1,616 @@
|
||||
#include <mbgl/vulkan/renderer_backend.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/vulkan/renderable_resource.hpp>
|
||||
|
||||
#include <mbgl/gfx/backend_scope.hpp>
|
||||
#include <mbgl/gfx/shader_registry.hpp>
|
||||
#include <mbgl/shaders/shader_source.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
|
||||
#include <mbgl/shaders/vulkan/shader_group.hpp>
|
||||
#include <mbgl/shaders/vulkan/background.hpp>
|
||||
#include <mbgl/shaders/vulkan/circle.hpp>
|
||||
#include <mbgl/shaders/vulkan/clipping_mask.hpp>
|
||||
#include <mbgl/shaders/vulkan/collision.hpp>
|
||||
#include <mbgl/shaders/vulkan/debug.hpp>
|
||||
#include <mbgl/shaders/vulkan/fill.hpp>
|
||||
#include <mbgl/shaders/vulkan/heatmap.hpp>
|
||||
#include <mbgl/shaders/vulkan/hillshade.hpp>
|
||||
#include <mbgl/shaders/vulkan/line.hpp>
|
||||
#include <mbgl/shaders/vulkan/raster.hpp>
|
||||
#include <mbgl/shaders/vulkan/symbol.hpp>
|
||||
|
||||
#include <cassert>
|
||||
#include <string>
|
||||
|
||||
#ifdef ENABLE_VULKAN_VALIDATION
|
||||
#include <vulkan/vulkan_to_string.hpp>
|
||||
#endif
|
||||
|
||||
VULKAN_HPP_DEFAULT_DISPATCH_LOADER_DYNAMIC_STORAGE
|
||||
|
||||
#ifdef ENABLE_VMA_DEBUG
|
||||
|
||||
#define VMA_DEBUG_MARGIN 16
|
||||
#define VMA_DEBUG_DETECT_CORRUPTION 1
|
||||
#define VMA_DEBUG_INITIALIZE_ALLOCATIONS 1
|
||||
|
||||
#define VMA_LEAK_LOG_FORMAT(format, ...) \
|
||||
{ \
|
||||
char buffer[4096]; \
|
||||
sprintf(buffer, format, __VA_ARGS__); \
|
||||
mbgl::Log::Info(mbgl::Event::Render, buffer); \
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#define VMA_IMPLEMENTATION
|
||||
#include "vk_mem_alloc.h"
|
||||
|
||||
#ifdef ENABLE_RENDERDOC_FRAME_CAPTURE
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
#include "renderdoc_app.h"
|
||||
static RENDERDOC_API_1_1_2* g_rdoc_api = nullptr;
|
||||
|
||||
#endif
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
template <typename T, typename F>
|
||||
static bool checkAvailability(const std::vector<T>& availableValues,
|
||||
const std::vector<const char*>& requiredValues,
|
||||
const F& getter) {
|
||||
for (const auto& requiredValue : requiredValues) {
|
||||
bool found = false;
|
||||
for (const auto& availableValue : availableValues) {
|
||||
if (strcmp(requiredValue, getter(availableValue)) == 0) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
RendererBackend::RendererBackend(const gfx::ContextMode contextMode_)
|
||||
: gfx::RendererBackend(contextMode_),
|
||||
allocator(nullptr) {}
|
||||
|
||||
RendererBackend::~RendererBackend() {
|
||||
destroyResources();
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::Context> RendererBackend::createContext() {
|
||||
return std::make_unique<vulkan::Context>(*this);
|
||||
}
|
||||
|
||||
std::vector<const char*> RendererBackend::getLayers() {
|
||||
return {
|
||||
#ifdef ENABLE_VULKAN_VALIDATION
|
||||
"VK_LAYER_KHRONOS_validation"
|
||||
#endif
|
||||
};
|
||||
}
|
||||
|
||||
std::vector<const char*> RendererBackend::getInstanceExtensions() {
|
||||
return {};
|
||||
}
|
||||
|
||||
std::vector<const char*> RendererBackend::getDeviceExtensions() {
|
||||
return getDefaultRenderable().getResource<SurfaceRenderableResource>().getDeviceExtensions();
|
||||
}
|
||||
|
||||
std::vector<const char*> RendererBackend::getDebugExtensions() {
|
||||
std::vector<const char*> extensions;
|
||||
|
||||
const auto& availableExtensions = vk::enumerateInstanceExtensionProperties();
|
||||
|
||||
debugUtilsEnabled = checkAvailability(
|
||||
availableExtensions, {VK_EXT_DEBUG_UTILS_EXTENSION_NAME}, [](const vk::ExtensionProperties& value) {
|
||||
return value.extensionName.data();
|
||||
});
|
||||
|
||||
if (debugUtilsEnabled) {
|
||||
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
|
||||
} else {
|
||||
// check for VK_EXT_debug_report (deprecated)
|
||||
bool debugReportAvailable = checkAvailability(
|
||||
availableExtensions, {VK_EXT_DEBUG_REPORT_EXTENSION_NAME}, [](const vk::ExtensionProperties& value) {
|
||||
return value.extensionName.data();
|
||||
});
|
||||
|
||||
if (debugReportAvailable) {
|
||||
extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
|
||||
} else {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "No debugging extension available");
|
||||
}
|
||||
}
|
||||
|
||||
return extensions;
|
||||
}
|
||||
|
||||
void RendererBackend::beginDebugLabel([[maybe_unused]] const vk::CommandBuffer& buffer,
|
||||
[[maybe_unused]] const char* name,
|
||||
[[maybe_unused]] const std::array<float, 4>& color) const {
|
||||
#ifdef ENABLE_VULKAN_VALIDATION
|
||||
if (!debugUtilsEnabled) return;
|
||||
buffer.beginDebugUtilsLabelEXT(vk::DebugUtilsLabelEXT().setPLabelName(name).setColor(color));
|
||||
#endif
|
||||
}
|
||||
|
||||
void RendererBackend::endDebugLabel([[maybe_unused]] const vk::CommandBuffer& buffer) const {
|
||||
#ifdef ENABLE_VULKAN_VALIDATION
|
||||
if (!debugUtilsEnabled) return;
|
||||
buffer.endDebugUtilsLabelEXT();
|
||||
#endif
|
||||
}
|
||||
|
||||
void RendererBackend::insertDebugLabel([[maybe_unused]] const vk::CommandBuffer& buffer,
|
||||
[[maybe_unused]] const char* name) const {
|
||||
#ifdef ENABLE_VULKAN_VALIDATION
|
||||
if (!debugUtilsEnabled) return;
|
||||
buffer.insertDebugUtilsLabelEXT(vk::DebugUtilsLabelEXT().setPLabelName(name));
|
||||
#endif
|
||||
}
|
||||
|
||||
void RendererBackend::initFrameCapture() {
|
||||
#ifdef ENABLE_RENDERDOC_FRAME_CAPTURE
|
||||
|
||||
#ifdef _WIN32
|
||||
if (HMODULE mod = GetModuleHandleA("renderdoc.dll")) {
|
||||
pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)GetProcAddress(mod, "RENDERDOC_GetAPI");
|
||||
int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_1_2, (void**)&g_rdoc_api);
|
||||
assert(ret == 1);
|
||||
}
|
||||
#elif __unix__
|
||||
if (void* mod = dlopen("librenderdoc.so", RTLD_NOW | RTLD_NOLOAD)) {
|
||||
pRENDERDOC_GetAPI RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dlsym(mod, "RENDERDOC_GetAPI");
|
||||
int ret = RENDERDOC_GetAPI(eRENDERDOC_API_Version_1_1_2, (void**)&g_rdoc_api);
|
||||
assert(ret == 1);
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
void RendererBackend::startFrameCapture() {
|
||||
#ifdef ENABLE_RENDERDOC_FRAME_CAPTURE
|
||||
if (g_rdoc_api) {
|
||||
g_rdoc_api->StartFrameCapture(nullptr, nullptr);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void RendererBackend::endFrameCapture() {
|
||||
#ifdef ENABLE_RENDERDOC_FRAME_CAPTURE
|
||||
if (g_rdoc_api) {
|
||||
g_rdoc_api->EndFrameCapture(nullptr, nullptr);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef ENABLE_VULKAN_VALIDATION
|
||||
|
||||
static VKAPI_ATTR VkBool32 VKAPI_CALL vkDebugUtilsCallback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
|
||||
VkDebugUtilsMessageTypeFlagsEXT,
|
||||
const VkDebugUtilsMessengerCallbackDataEXT* callbackData,
|
||||
void*) {
|
||||
EventSeverity mbglSeverity = EventSeverity::Debug;
|
||||
|
||||
switch (messageSeverity) {
|
||||
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT:
|
||||
mbglSeverity = EventSeverity::Debug;
|
||||
break;
|
||||
|
||||
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT:
|
||||
mbglSeverity = EventSeverity::Info;
|
||||
break;
|
||||
|
||||
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT:
|
||||
mbglSeverity = EventSeverity::Warning;
|
||||
break;
|
||||
|
||||
case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT:
|
||||
mbglSeverity = EventSeverity::Error;
|
||||
break;
|
||||
|
||||
default:
|
||||
return VK_FALSE;
|
||||
}
|
||||
|
||||
mbgl::Log::Record(mbglSeverity, mbgl::Event::Render, callbackData->pMessage);
|
||||
|
||||
return VK_FALSE;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkBool32 vkDebugReportCallback(VkDebugReportFlagsEXT flags,
|
||||
VkDebugReportObjectTypeEXT objectType,
|
||||
[[maybe_unused]] uint64_t object,
|
||||
[[maybe_unused]] size_t location,
|
||||
int32_t messageCode,
|
||||
const char* pLayerPrefix,
|
||||
const char* pMessage,
|
||||
[[maybe_unused]] void* pUserData) {
|
||||
EventSeverity mbglSeverity = EventSeverity::Debug;
|
||||
|
||||
if (flags & VK_DEBUG_REPORT_INFORMATION_BIT_EXT) {
|
||||
mbglSeverity = EventSeverity::Info;
|
||||
} else if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT) {
|
||||
mbglSeverity = EventSeverity::Warning;
|
||||
} else if (flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) {
|
||||
mbglSeverity = EventSeverity::Warning;
|
||||
} else if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
|
||||
mbglSeverity = EventSeverity::Error;
|
||||
} else if (flags & VK_DEBUG_REPORT_DEBUG_BIT_EXT) {
|
||||
mbglSeverity = EventSeverity::Debug;
|
||||
}
|
||||
|
||||
const std::string message = "[" + vk::to_string(vk::DebugReportObjectTypeEXT(objectType)) + "]" + "[code - " +
|
||||
std::to_string(messageCode) + "]" + "[layer - " + pLayerPrefix + "]" + pMessage;
|
||||
|
||||
mbgl::Log::Record(mbglSeverity, mbgl::Event::Render, message);
|
||||
|
||||
return VK_FALSE;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
void RendererBackend::initDebug() {
|
||||
#ifdef ENABLE_VULKAN_VALIDATION
|
||||
if (debugUtilsEnabled) {
|
||||
const vk::DebugUtilsMessageSeverityFlagsEXT severity = vk::DebugUtilsMessageSeverityFlagsEXT() |
|
||||
vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose |
|
||||
vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo |
|
||||
vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
|
||||
vk::DebugUtilsMessageSeverityFlagBitsEXT::eError;
|
||||
|
||||
const vk::DebugUtilsMessageTypeFlagsEXT type = vk::DebugUtilsMessageTypeFlagsEXT() |
|
||||
vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral |
|
||||
vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation |
|
||||
vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance |
|
||||
vk::DebugUtilsMessageTypeFlagBitsEXT::eDeviceAddressBinding;
|
||||
|
||||
const auto createInfo =
|
||||
vk::DebugUtilsMessengerCreateInfoEXT().setMessageSeverity(severity).setMessageType(type).setPfnUserCallback(
|
||||
vkDebugUtilsCallback);
|
||||
|
||||
debugUtilsCallback = instance->createDebugUtilsMessengerEXTUnique(createInfo);
|
||||
|
||||
if (!debugUtilsCallback) {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Failed to register Vulkan debug utils callback");
|
||||
}
|
||||
} else {
|
||||
const vk::DebugReportFlagsEXT flags = vk::DebugReportFlagsEXT() | vk::DebugReportFlagBitsEXT::eDebug |
|
||||
vk::DebugReportFlagBitsEXT::eError |
|
||||
vk::DebugReportFlagBitsEXT::eInformation |
|
||||
vk::DebugReportFlagBitsEXT::ePerformanceWarning |
|
||||
vk::DebugReportFlagBitsEXT::eWarning;
|
||||
|
||||
const auto createInfo = vk::DebugReportCallbackCreateInfoEXT().setFlags(flags).setPfnCallback(
|
||||
vkDebugReportCallback);
|
||||
|
||||
debugReportCallback = instance->createDebugReportCallbackEXTUnique(createInfo);
|
||||
|
||||
if (!debugReportCallback) {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Failed to register Vulkan debug report callback");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void RendererBackend::init() {
|
||||
initFrameCapture();
|
||||
initInstance();
|
||||
initSurface();
|
||||
initDevice();
|
||||
initAllocator();
|
||||
initSwapchain();
|
||||
initCommandPool();
|
||||
}
|
||||
|
||||
void RendererBackend::initInstance() {
|
||||
// initialize minimal set of function pointers
|
||||
VULKAN_HPP_DEFAULT_DISPATCHER.init(dynamicLoader);
|
||||
|
||||
// Vulkan 1.1 on Android is supported on 71% of devices (compared to 1.3 with 6%) as of April 23 2024
|
||||
// https://vulkan.gpuinfo.org/
|
||||
vk::ApplicationInfo appInfo("maplibre-native", 1, "maplibre-native", 1, VK_API_VERSION_1_0);
|
||||
vk::InstanceCreateInfo createInfo(vk::InstanceCreateFlags(), &appInfo);
|
||||
|
||||
const auto& layers = getLayers();
|
||||
|
||||
bool layersAvailable = checkAvailability(vk::enumerateInstanceLayerProperties(),
|
||||
layers,
|
||||
[](const vk::LayerProperties& value) { return value.layerName.data(); });
|
||||
|
||||
if (layersAvailable) {
|
||||
createInfo.setPEnabledLayerNames(layers);
|
||||
} else {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Vulkan layers not found");
|
||||
}
|
||||
|
||||
auto extensions = getInstanceExtensions();
|
||||
|
||||
bool extensionsAvailable = checkAvailability(
|
||||
vk::enumerateInstanceExtensionProperties(), extensions, [](const vk::ExtensionProperties& value) {
|
||||
return value.extensionName.data();
|
||||
});
|
||||
|
||||
#ifdef ENABLE_VULKAN_VALIDATION
|
||||
const auto& debugExtensions = getDebugExtensions();
|
||||
extensions.insert(extensions.end(), debugExtensions.begin(), debugExtensions.end());
|
||||
|
||||
#ifdef ENABLE_VULKAN_GPU_ASSISTED_VALIDATION
|
||||
appInfo.setApiVersion(VK_API_VERSION_1_1);
|
||||
|
||||
const std::array<vk::ValidationFeatureEnableEXT, 2> validationFeatures = {
|
||||
vk::ValidationFeatureEnableEXT::eGpuAssisted, vk::ValidationFeatureEnableEXT::eGpuAssistedReserveBindingSlot};
|
||||
const vk::ValidationFeaturesEXT validationFeatureInfo(validationFeatures);
|
||||
|
||||
createInfo.setPNext(&validationFeatureInfo);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
if (extensionsAvailable) {
|
||||
createInfo.setPEnabledExtensionNames(extensions);
|
||||
} else {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Vulkan extensions not found");
|
||||
}
|
||||
|
||||
instance = vk::createInstanceUnique(createInfo);
|
||||
|
||||
// initialize function pointers for instance
|
||||
VULKAN_HPP_DEFAULT_DISPATCHER.init(instance.get());
|
||||
|
||||
#ifdef ENABLE_VULKAN_VALIDATION
|
||||
// enable validation layer callback
|
||||
initDebug();
|
||||
#endif
|
||||
}
|
||||
|
||||
void RendererBackend::initSurface() {
|
||||
getDefaultRenderable().getResource<SurfaceRenderableResource>().createPlatformSurface();
|
||||
}
|
||||
|
||||
void RendererBackend::initAllocator() {
|
||||
VmaVulkanFunctions functions = {};
|
||||
|
||||
functions.vkGetInstanceProcAddr = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetInstanceProcAddr;
|
||||
functions.vkGetDeviceProcAddr = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetDeviceProcAddr;
|
||||
|
||||
functions.vkGetPhysicalDeviceProperties = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetPhysicalDeviceProperties;
|
||||
functions.vkGetPhysicalDeviceMemoryProperties = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetPhysicalDeviceMemoryProperties;
|
||||
functions.vkAllocateMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkAllocateMemory;
|
||||
functions.vkFreeMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkFreeMemory;
|
||||
functions.vkMapMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkMapMemory;
|
||||
functions.vkUnmapMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkUnmapMemory;
|
||||
functions.vkFlushMappedMemoryRanges = VULKAN_HPP_DEFAULT_DISPATCHER.vkFlushMappedMemoryRanges;
|
||||
functions.vkInvalidateMappedMemoryRanges = VULKAN_HPP_DEFAULT_DISPATCHER.vkInvalidateMappedMemoryRanges;
|
||||
functions.vkBindBufferMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkBindBufferMemory;
|
||||
functions.vkBindImageMemory = VULKAN_HPP_DEFAULT_DISPATCHER.vkBindImageMemory;
|
||||
functions.vkGetBufferMemoryRequirements = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetBufferMemoryRequirements;
|
||||
functions.vkGetImageMemoryRequirements = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetImageMemoryRequirements;
|
||||
functions.vkCreateBuffer = VULKAN_HPP_DEFAULT_DISPATCHER.vkCreateBuffer;
|
||||
functions.vkDestroyBuffer = VULKAN_HPP_DEFAULT_DISPATCHER.vkDestroyBuffer;
|
||||
functions.vkCreateImage = VULKAN_HPP_DEFAULT_DISPATCHER.vkCreateImage;
|
||||
functions.vkDestroyImage = VULKAN_HPP_DEFAULT_DISPATCHER.vkDestroyImage;
|
||||
functions.vkCmdCopyBuffer = VULKAN_HPP_DEFAULT_DISPATCHER.vkCmdCopyBuffer;
|
||||
functions.vkGetBufferMemoryRequirements2KHR = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetBufferMemoryRequirements2KHR;
|
||||
functions.vkGetImageMemoryRequirements2KHR = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetImageMemoryRequirements2KHR;
|
||||
functions.vkBindBufferMemory2KHR = VULKAN_HPP_DEFAULT_DISPATCHER.vkBindBufferMemory2KHR;
|
||||
functions.vkBindImageMemory2KHR = VULKAN_HPP_DEFAULT_DISPATCHER.vkBindImageMemory2KHR;
|
||||
functions.vkGetPhysicalDeviceMemoryProperties2KHR =
|
||||
VULKAN_HPP_DEFAULT_DISPATCHER.vkGetPhysicalDeviceMemoryProperties2KHR;
|
||||
|
||||
VmaAllocatorCreateInfo allocatorCreateInfo = {};
|
||||
|
||||
allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_0;
|
||||
allocatorCreateInfo.physicalDevice = physicalDevice;
|
||||
allocatorCreateInfo.device = device.get();
|
||||
allocatorCreateInfo.instance = instance.get();
|
||||
allocatorCreateInfo.pVulkanFunctions = &functions;
|
||||
|
||||
VkResult result = vmaCreateAllocator(&allocatorCreateInfo, &allocator);
|
||||
if (result != VK_SUCCESS) {
|
||||
throw std::runtime_error("Vulkan allocator init failed");
|
||||
}
|
||||
}
|
||||
|
||||
void RendererBackend::initDevice() {
|
||||
const auto& extensions = getDeviceExtensions();
|
||||
const auto& layers = getLayers();
|
||||
const auto& surface = getDefaultRenderable().getResource<SurfaceRenderableResource>().getPlatformSurface().get();
|
||||
|
||||
const auto& isPhysicalDeviceCompatible = [&](const vk::PhysicalDevice& candidate) -> bool {
|
||||
bool extensionsAvailable = checkAvailability(
|
||||
candidate.enumerateDeviceExtensionProperties(), extensions, [](const vk::ExtensionProperties& value) {
|
||||
return value.extensionName.data();
|
||||
});
|
||||
|
||||
if (!extensionsAvailable) return false;
|
||||
|
||||
graphicsQueueIndex = -1;
|
||||
presentQueueIndex = -1;
|
||||
|
||||
const auto& queues = candidate.getQueueFamilyProperties();
|
||||
|
||||
for (auto i = 0u; i < queues.size(); ++i) {
|
||||
const auto& queue = queues[i];
|
||||
|
||||
if (queue.queueCount == 0) continue;
|
||||
|
||||
if (queue.queueFlags & vk::QueueFlagBits::eGraphics) graphicsQueueIndex = i;
|
||||
|
||||
if (surface && candidate.getSurfaceSupportKHR(i, surface)) presentQueueIndex = i;
|
||||
|
||||
if (graphicsQueueIndex != -1 && (!surface || presentQueueIndex != -1)) break;
|
||||
}
|
||||
|
||||
if (graphicsQueueIndex == -1 || (surface && presentQueueIndex == -1)) return false;
|
||||
|
||||
if (surface) {
|
||||
if (candidate.getSurfaceFormatsKHR(surface).empty()) return false;
|
||||
if (candidate.getSurfacePresentModesKHR(surface).empty()) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
const auto& pickPhysicalDevice = [&]() {
|
||||
const auto& physicalDevices = instance->enumeratePhysicalDevices();
|
||||
if (physicalDevices.empty()) throw std::runtime_error("No Vulkan compatible GPU found");
|
||||
|
||||
for (const auto& candidate : physicalDevices) {
|
||||
if (isPhysicalDeviceCompatible(candidate)) {
|
||||
physicalDevice = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
physicalDeviceProperties = physicalDevice.getProperties();
|
||||
|
||||
if (!physicalDevice) throw std::runtime_error("No suitable GPU found");
|
||||
};
|
||||
|
||||
pickPhysicalDevice();
|
||||
|
||||
std::vector<vk::DeviceQueueCreateInfo> queueCreateInfos;
|
||||
|
||||
float queuePriority = 1.0f;
|
||||
|
||||
queueCreateInfos.emplace_back(vk::DeviceQueueCreateFlags(), graphicsQueueIndex, 1, &queuePriority);
|
||||
|
||||
if (surface && graphicsQueueIndex != presentQueueIndex)
|
||||
queueCreateInfos.emplace_back(vk::DeviceQueueCreateFlags(), presentQueueIndex, 1, &queuePriority);
|
||||
|
||||
const auto& supportedDeviceFeatures = physicalDevice.getFeatures();
|
||||
|
||||
vk::PhysicalDeviceFeatures enabledDeviceFeatures;
|
||||
|
||||
if (supportedDeviceFeatures.wideLines) {
|
||||
enabledDeviceFeatures.setWideLines(true);
|
||||
|
||||
// more wideLines info
|
||||
// physicalDeviceProperties.limits.lineWidthRange;
|
||||
// physicalDeviceProperties.limits.lineWidthGranularity;
|
||||
} else {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Wide line support not available");
|
||||
}
|
||||
|
||||
auto createInfo = vk::DeviceCreateInfo()
|
||||
.setQueueCreateInfos(queueCreateInfos)
|
||||
.setEnabledExtensionCount(static_cast<uint32_t>(extensions.size()))
|
||||
.setPpEnabledExtensionNames(extensions.data())
|
||||
.setPEnabledFeatures(&enabledDeviceFeatures);
|
||||
|
||||
// this is not needed for newer implementations
|
||||
createInfo.setPEnabledLayerNames(layers);
|
||||
|
||||
device = physicalDevice.createDeviceUnique(createInfo);
|
||||
|
||||
// optional function pointer specialization for device
|
||||
VULKAN_HPP_DEFAULT_DISPATCHER.init(device.get());
|
||||
|
||||
graphicsQueue = device->getQueue(graphicsQueueIndex, 0);
|
||||
if (presentQueueIndex != -1) presentQueue = device->getQueue(presentQueueIndex, 0);
|
||||
}
|
||||
|
||||
void RendererBackend::initSwapchain() {
|
||||
const auto& renderable = getDefaultRenderable();
|
||||
auto& renderableResource = renderable.getResource<SurfaceRenderableResource>();
|
||||
const auto& size = renderable.getSize();
|
||||
renderableResource.init(size.width, size.height);
|
||||
|
||||
if (renderableResource.getPlatformSurface()) {
|
||||
maxFrames = renderableResource.getImageCount();
|
||||
}
|
||||
}
|
||||
|
||||
void RendererBackend::initCommandPool() {
|
||||
const vk::CommandPoolCreateInfo createInfo(vk::CommandPoolCreateFlagBits::eResetCommandBuffer, graphicsQueueIndex);
|
||||
commandPool = device->createCommandPoolUnique(createInfo);
|
||||
}
|
||||
|
||||
void RendererBackend::destroyResources() {
|
||||
if (device) device->waitIdle();
|
||||
|
||||
context.reset();
|
||||
commandPool.reset();
|
||||
|
||||
vmaDestroyAllocator(allocator);
|
||||
|
||||
device.reset();
|
||||
|
||||
// destroy this last so we have cleanup validation
|
||||
debugUtilsCallback.reset();
|
||||
debugReportCallback.reset();
|
||||
instance.reset();
|
||||
}
|
||||
|
||||
/// @brief Register a list of types with a shader registry instance
|
||||
/// @tparam ...ShaderID Pack of BuiltIn:: shader IDs
|
||||
/// @param registry A shader registry instance
|
||||
/// @param programParameters ProgramParameters used to initialize each instance
|
||||
template <shaders::BuiltIn... ShaderID>
|
||||
void registerTypes(gfx::ShaderRegistry& registry, const ProgramParameters& programParameters) {
|
||||
/// The following fold expression will create a shader for every type
|
||||
/// in the parameter pack and register it with the shader registry.
|
||||
|
||||
// Registration calls are wrapped in a lambda that throws on registration
|
||||
// failure, we shouldn't expect registration to faill unless the shader
|
||||
// registry instance provided already has conflicting programs present.
|
||||
(
|
||||
[&]() {
|
||||
using namespace std::string_literals;
|
||||
using ShaderClass = shaders::ShaderSource<ShaderID, gfx::Backend::Type::Vulkan>;
|
||||
auto group = std::make_shared<ShaderGroup<ShaderID>>(programParameters);
|
||||
if (!registry.registerShaderGroup(std::move(group), ShaderClass::name)) {
|
||||
assert(!"duplicate shader group");
|
||||
throw std::runtime_error("Failed to register "s + ShaderClass::name + " with shader registry!");
|
||||
}
|
||||
}(),
|
||||
...);
|
||||
}
|
||||
|
||||
void RendererBackend::initShaders(gfx::ShaderRegistry& shaders, const ProgramParameters& programParameters) {
|
||||
registerTypes<shaders::BuiltIn::BackgroundShader,
|
||||
shaders::BuiltIn::BackgroundPatternShader,
|
||||
shaders::BuiltIn::CircleShader,
|
||||
shaders::BuiltIn::ClippingMaskProgram,
|
||||
shaders::BuiltIn::CollisionBoxShader,
|
||||
shaders::BuiltIn::CollisionCircleShader,
|
||||
shaders::BuiltIn::CustomSymbolIconShader,
|
||||
shaders::BuiltIn::DebugShader,
|
||||
shaders::BuiltIn::FillShader,
|
||||
shaders::BuiltIn::FillOutlineShader,
|
||||
shaders::BuiltIn::FillPatternShader,
|
||||
shaders::BuiltIn::FillOutlinePatternShader,
|
||||
shaders::BuiltIn::FillOutlineTriangulatedShader,
|
||||
shaders::BuiltIn::FillExtrusionShader,
|
||||
shaders::BuiltIn::FillExtrusionPatternShader,
|
||||
shaders::BuiltIn::HeatmapShader,
|
||||
shaders::BuiltIn::HeatmapTextureShader,
|
||||
shaders::BuiltIn::HillshadeShader,
|
||||
shaders::BuiltIn::HillshadePrepareShader,
|
||||
shaders::BuiltIn::LineShader,
|
||||
shaders::BuiltIn::LineGradientShader,
|
||||
shaders::BuiltIn::LineSDFShader,
|
||||
shaders::BuiltIn::LinePatternShader,
|
||||
shaders::BuiltIn::RasterShader,
|
||||
shaders::BuiltIn::SymbolIconShader,
|
||||
shaders::BuiltIn::SymbolSDFIconShader,
|
||||
shaders::BuiltIn::SymbolTextAndIconShader,
|
||||
shaders::BuiltIn::WideVectorShader>(shaders, programParameters);
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
508
src/mbgl/vulkan/texture2d.cpp
Normal file
508
src/mbgl/vulkan/texture2d.cpp
Normal file
@@ -0,0 +1,508 @@
|
||||
#include <mbgl/vulkan/texture2d.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/vulkan/render_pass.hpp>
|
||||
#include <mbgl/vulkan/upload_pass.hpp>
|
||||
#include <mbgl/vulkan/buffer_resource.hpp>
|
||||
#include <mbgl/vulkan/command_encoder.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
bool ImageAllocation::create(const VmaAllocationCreateInfo& allocInfo, const vk::ImageCreateInfo& imageInfo) {
|
||||
VkResult result = vmaCreateImage(
|
||||
allocator, reinterpret_cast<const VkImageCreateInfo*>(&imageInfo), &allocInfo, &image, &allocation, nullptr);
|
||||
|
||||
if (result != VK_SUCCESS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImageAllocation::destroy() {
|
||||
imageView.reset();
|
||||
vmaDestroyImage(allocator, image, allocation);
|
||||
}
|
||||
|
||||
void ImageAllocation::setName([[maybe_unused]] const std::string& name) const {
|
||||
#ifdef ENABLE_VMA_DEBUG
|
||||
if (allocation) {
|
||||
vmaSetAllocationName(allocator, allocation, name.data());
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
Texture2D::Texture2D(Context& context_)
|
||||
: context(context_) {}
|
||||
|
||||
Texture2D::~Texture2D() {
|
||||
destroyTexture();
|
||||
destroySampler();
|
||||
|
||||
context.renderingStats().numActiveTextures--;
|
||||
context.renderingStats().memTextures -= Texture2D::getDataSize();
|
||||
}
|
||||
|
||||
gfx::Texture2D& Texture2D::setSamplerConfiguration(const SamplerState& samplerState_) noexcept {
|
||||
samplerState = samplerState_;
|
||||
samplerStateDirty = true;
|
||||
return *this;
|
||||
}
|
||||
|
||||
gfx::Texture2D& Texture2D::setFormat(gfx::TexturePixelType pixelFormat_,
|
||||
gfx::TextureChannelDataType channelType_) noexcept {
|
||||
if (pixelFormat_ == pixelFormat && channelType_ == channelType) {
|
||||
return *this;
|
||||
}
|
||||
pixelFormat = pixelFormat_;
|
||||
channelType = channelType_;
|
||||
textureDirty = true;
|
||||
return *this;
|
||||
}
|
||||
|
||||
gfx::Texture2D& Texture2D::setSize(mbgl::Size size_) noexcept {
|
||||
if (size_ == size) {
|
||||
return *this;
|
||||
}
|
||||
size = size_;
|
||||
textureDirty = true;
|
||||
return *this;
|
||||
}
|
||||
|
||||
gfx::Texture2D& Texture2D::setImage(std::shared_ptr<PremultipliedImage> image_) noexcept {
|
||||
imageData = std::move(image_);
|
||||
return *this;
|
||||
}
|
||||
|
||||
gfx::Texture2D& Texture2D::setUsage(Texture2DUsage value) noexcept {
|
||||
textureUsage = value;
|
||||
textureDirty = true;
|
||||
return *this;
|
||||
}
|
||||
|
||||
size_t Texture2D::getDataSize() const noexcept {
|
||||
return Texture2D::getPixelStride() * size.width * size.height;
|
||||
}
|
||||
|
||||
size_t Texture2D::getPixelStride() const noexcept {
|
||||
switch (channelType) {
|
||||
case gfx::TextureChannelDataType::UnsignedByte:
|
||||
return 1 * Texture2D::numChannels();
|
||||
case gfx::TextureChannelDataType::HalfFloat:
|
||||
return 2 * Texture2D::numChannels();
|
||||
case gfx::TextureChannelDataType::Float:
|
||||
return 4 * Texture2D::numChannels();
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
size_t Texture2D::numChannels() const noexcept {
|
||||
switch (pixelFormat) {
|
||||
case gfx::TexturePixelType::RGBA:
|
||||
return 4;
|
||||
case gfx::TexturePixelType::Alpha:
|
||||
return 1;
|
||||
case gfx::TexturePixelType::Stencil:
|
||||
return 1;
|
||||
case gfx::TexturePixelType::Depth:
|
||||
return 1;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void Texture2D::create() noexcept {
|
||||
if (textureDirty) {
|
||||
createTexture();
|
||||
}
|
||||
}
|
||||
|
||||
void Texture2D::upload() noexcept {
|
||||
if (!imageData) return;
|
||||
|
||||
upload(imageData->data.get(), imageData->size);
|
||||
|
||||
imageData.reset();
|
||||
}
|
||||
|
||||
void Texture2D::upload(const void* pixelData, const Size& size_) noexcept {
|
||||
setSize(size_);
|
||||
uploadSubRegion(pixelData, size_, 0, 0);
|
||||
}
|
||||
|
||||
void Texture2D::uploadSubRegion(const void* pixelData, const Size& size_, uint16_t xOffset, uint16_t yOffset) noexcept {
|
||||
if (!pixelData || size_.width == 0 || size_.height == 0) return;
|
||||
|
||||
const auto& encoder = context.createCommandEncoder();
|
||||
const auto& encoderImpl = static_cast<const CommandEncoder&>(*encoder);
|
||||
|
||||
uploadSubRegion(pixelData, size_, xOffset, yOffset, encoderImpl.getCommandBuffer());
|
||||
}
|
||||
|
||||
void Texture2D::uploadSubRegion(const void* pixelData,
|
||||
const Size& size_,
|
||||
uint16_t xOffset,
|
||||
uint16_t yOffset,
|
||||
const vk::UniqueCommandBuffer& commandBuffer) noexcept {
|
||||
if (!pixelData || size_.width == 0 || size_.height == 0) return;
|
||||
|
||||
create();
|
||||
|
||||
if (!imageAllocation) return;
|
||||
|
||||
const auto& allocator = context.getBackend().getAllocator();
|
||||
|
||||
const auto bufferInfo = vk::BufferCreateInfo()
|
||||
.setSize(static_cast<vk::DeviceSize>(size_.width) * size_.height * getPixelStride())
|
||||
.setUsage(vk::BufferUsageFlagBits::eTransferSrc)
|
||||
.setSharingMode(vk::SharingMode::eExclusive);
|
||||
|
||||
VmaAllocationCreateInfo allocationInfo = {};
|
||||
|
||||
allocationInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST;
|
||||
allocationInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
|
||||
allocationInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
|
||||
|
||||
SharedBufferAllocation bufferAllocation = std::make_shared<BufferAllocation>(allocator);
|
||||
if (!bufferAllocation->create(allocationInfo, bufferInfo)) {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Vulkan texture buffer allocation failed");
|
||||
return;
|
||||
}
|
||||
|
||||
vmaMapMemory(allocator, bufferAllocation->allocation, &bufferAllocation->mappedBuffer);
|
||||
memcpy(bufferAllocation->mappedBuffer, pixelData, bufferInfo.size);
|
||||
|
||||
const auto enqueueCommands = [&](const auto& buffer) {
|
||||
transitionToTransferLayout(buffer);
|
||||
|
||||
const auto region = vk::BufferImageCopy()
|
||||
.setBufferOffset(0)
|
||||
.setBufferRowLength(size_.width)
|
||||
.setImageSubresource(
|
||||
vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor, 0, 0, 1))
|
||||
.setImageOffset(vk::Offset3D(xOffset, yOffset))
|
||||
.setImageExtent(vk::Extent3D(size_.width, size_.height, 1));
|
||||
|
||||
buffer->copyBufferToImage(bufferAllocation->buffer, imageAllocation->image, imageLayout, region);
|
||||
|
||||
transitionToShaderReadLayout(buffer);
|
||||
};
|
||||
|
||||
enqueueCommands(commandBuffer);
|
||||
|
||||
context.enqueueDeletion([buffAlloc = std::move(bufferAllocation)](const auto&) mutable { buffAlloc.reset(); });
|
||||
|
||||
context.renderingStats().numTextureUpdates++;
|
||||
}
|
||||
|
||||
vk::Format Texture2D::vulkanFormat(const gfx::TexturePixelType pixel, gfx::TextureChannelDataType channel) {
|
||||
// depth/stencil are packed formats
|
||||
if (pixel == gfx::TexturePixelType::Stencil) return vk::Format::eS8Uint;
|
||||
|
||||
if (pixel == gfx::TexturePixelType::Depth) return vk::Format::eUndefined;
|
||||
|
||||
if (pixel == gfx::TexturePixelType::Alpha) {
|
||||
switch (channel) {
|
||||
case gfx::TextureChannelDataType::UnsignedByte:
|
||||
return vk::Format::eR8Unorm;
|
||||
case gfx::TextureChannelDataType::HalfFloat:
|
||||
return vk::Format::eR16Sfloat;
|
||||
case gfx::TextureChannelDataType::Float:
|
||||
return vk::Format::eR32Sfloat;
|
||||
}
|
||||
}
|
||||
|
||||
if (pixel == gfx::TexturePixelType::RGBA) {
|
||||
switch (channel) {
|
||||
case gfx::TextureChannelDataType::UnsignedByte:
|
||||
return vk::Format::eR8G8B8A8Unorm;
|
||||
case gfx::TextureChannelDataType::HalfFloat:
|
||||
return vk::Format::eR16G16B16A16Sfloat;
|
||||
case gfx::TextureChannelDataType::Float:
|
||||
return vk::Format::eR32G32B32A32Sfloat;
|
||||
}
|
||||
}
|
||||
|
||||
return vk::Format::eUndefined;
|
||||
}
|
||||
|
||||
vk::Filter Texture2D::vulkanFilter(const gfx::TextureFilterType type) {
|
||||
switch (type) {
|
||||
default:
|
||||
[[fallthrough]];
|
||||
case gfx::TextureFilterType::Nearest:
|
||||
return vk::Filter::eNearest;
|
||||
case gfx::TextureFilterType::Linear:
|
||||
return vk::Filter::eLinear;
|
||||
}
|
||||
}
|
||||
|
||||
vk::SamplerAddressMode Texture2D::vulkanAddressMode(const gfx::TextureWrapType type) {
|
||||
switch (type) {
|
||||
default:
|
||||
[[fallthrough]];
|
||||
case gfx::TextureWrapType::Clamp:
|
||||
return vk::SamplerAddressMode::eClampToEdge;
|
||||
case gfx::TextureWrapType::Repeat:
|
||||
return vk::SamplerAddressMode::eRepeat;
|
||||
}
|
||||
}
|
||||
|
||||
void Texture2D::createTexture() {
|
||||
if (size.width == 0 || size.height == 0) return;
|
||||
|
||||
const auto& backend = context.getBackend();
|
||||
|
||||
const auto format = vulkanFormat(pixelFormat, channelType);
|
||||
|
||||
vk::ImageUsageFlags imageUsage;
|
||||
vk::ImageTiling imageTiling;
|
||||
|
||||
switch (textureUsage) {
|
||||
default:
|
||||
case Texture2DUsage::ShaderInput:
|
||||
imageUsage = vk::ImageUsageFlags() | vk::ImageUsageFlagBits::eTransferDst |
|
||||
vk::ImageUsageFlagBits::eSampled;
|
||||
imageTiling = vk::ImageTiling::eOptimal;
|
||||
break;
|
||||
|
||||
case Texture2DUsage::Attachment:
|
||||
imageUsage = vk::ImageUsageFlags() | vk::ImageUsageFlagBits::eColorAttachment |
|
||||
vk::ImageUsageFlagBits::eSampled;
|
||||
imageTiling = vk::ImageTiling::eOptimal;
|
||||
break;
|
||||
|
||||
case Texture2DUsage::Read:
|
||||
imageUsage = vk::ImageUsageFlags() | vk::ImageUsageFlagBits::eTransferDst;
|
||||
imageTiling = vk::ImageTiling::eLinear;
|
||||
break;
|
||||
}
|
||||
|
||||
const auto imageCreateInfo = vk::ImageCreateInfo()
|
||||
.setImageType(vk::ImageType::e2D)
|
||||
.setFormat(format)
|
||||
.setExtent({size.width, size.height, 1})
|
||||
.setMipLevels(1)
|
||||
.setArrayLayers(1)
|
||||
.setSamples(vk::SampleCountFlagBits::e1)
|
||||
.setTiling(imageTiling)
|
||||
.setUsage(imageUsage)
|
||||
.setSharingMode(vk::SharingMode::eExclusive)
|
||||
.setInitialLayout(vk::ImageLayout::eUndefined);
|
||||
|
||||
VmaAllocationCreateInfo allocCreateInfo = {};
|
||||
|
||||
if (textureUsage != Texture2DUsage::Read) {
|
||||
allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_DEVICE;
|
||||
allocCreateInfo.requiredFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
|
||||
} else {
|
||||
allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO_PREFER_HOST;
|
||||
allocCreateInfo.requiredFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
|
||||
allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_SEQUENTIAL_WRITE_BIT;
|
||||
}
|
||||
|
||||
imageAllocation = std::make_shared<ImageAllocation>(backend.getAllocator());
|
||||
if (!imageAllocation->create(allocCreateInfo, imageCreateInfo)) {
|
||||
mbgl::Log::Error(mbgl::Event::Render, "Vulkan texture allocation failed");
|
||||
return;
|
||||
}
|
||||
|
||||
// defaults to eIdentity
|
||||
vk::ComponentMapping imageSwizzle;
|
||||
|
||||
// alpha only format (eA8UnormKHR) is not part of core
|
||||
// use a R8 texture and map red channel to alpha
|
||||
if (pixelFormat == gfx::TexturePixelType::Alpha) {
|
||||
imageSwizzle = vk::ComponentMapping(vk::ComponentSwizzle::eZero,
|
||||
vk::ComponentSwizzle::eZero,
|
||||
vk::ComponentSwizzle::eZero,
|
||||
vk::ComponentSwizzle::eR);
|
||||
}
|
||||
|
||||
if (textureUsage != Texture2DUsage::Read) {
|
||||
auto imageViewCreateInfo = vk::ImageViewCreateInfo()
|
||||
.setImage(imageAllocation->image)
|
||||
.setViewType(vk::ImageViewType::e2D)
|
||||
.setFormat(format)
|
||||
.setComponents(imageSwizzle)
|
||||
.setSubresourceRange(
|
||||
vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
|
||||
|
||||
imageAllocation->imageView = backend.getDevice()->createImageViewUnique(imageViewCreateInfo);
|
||||
}
|
||||
|
||||
// if the image is used as an attachment
|
||||
// it's layout is managed by the render pass
|
||||
if (textureUsage == Texture2DUsage::Attachment) {
|
||||
imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
|
||||
} else {
|
||||
imageLayout = imageCreateInfo.initialLayout;
|
||||
}
|
||||
|
||||
context.renderingStats().numCreatedTextures++;
|
||||
context.renderingStats().numActiveTextures++;
|
||||
context.renderingStats().memTextures += getDataSize();
|
||||
textureDirty = false;
|
||||
}
|
||||
|
||||
void Texture2D::createSampler() {
|
||||
destroySampler();
|
||||
|
||||
const auto filter = vulkanFilter(samplerState.filter);
|
||||
const auto addressModeU = vulkanAddressMode(samplerState.wrapU);
|
||||
const auto addressModeV = vulkanAddressMode(samplerState.wrapV);
|
||||
|
||||
const auto samplerCreateInfo = vk::SamplerCreateInfo()
|
||||
.setMinFilter(filter)
|
||||
.setMagFilter(filter)
|
||||
.setMipmapMode(vk::SamplerMipmapMode::eNearest)
|
||||
.setMinLod(-VK_LOD_CLAMP_NONE)
|
||||
.setMaxLod(VK_LOD_CLAMP_NONE)
|
||||
.setAddressModeU(addressModeU)
|
||||
.setAddressModeV(addressModeV)
|
||||
.setAddressModeW(vk::SamplerAddressMode::eRepeat)
|
||||
.setAnisotropyEnable(false);
|
||||
|
||||
sampler = context.getBackend().getDevice()->createSampler(samplerCreateInfo);
|
||||
|
||||
samplerStateDirty = false;
|
||||
}
|
||||
|
||||
void Texture2D::destroyTexture() {
|
||||
if (imageAllocation) {
|
||||
context.enqueueDeletion([allocation = std::move(imageAllocation)](const auto&) mutable { allocation.reset(); });
|
||||
|
||||
imageLayout = vk::ImageLayout::eUndefined;
|
||||
}
|
||||
}
|
||||
|
||||
void Texture2D::destroySampler() {
|
||||
if (sampler) {
|
||||
context.enqueueDeletion([sampler_ = std::move(sampler)](const auto& context_) mutable {
|
||||
context_.getBackend().getDevice()->destroySampler(sampler_);
|
||||
});
|
||||
|
||||
sampler = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void Texture2D::transitionToTransferLayout(const vk::UniqueCommandBuffer& buffer) {
|
||||
const auto barrier = vk::ImageMemoryBarrier()
|
||||
.setImage(imageAllocation->image)
|
||||
.setOldLayout(imageLayout)
|
||||
.setNewLayout(vk::ImageLayout::eTransferDstOptimal)
|
||||
.setSrcAccessMask({})
|
||||
.setDstAccessMask(vk::AccessFlagBits::eTransferWrite)
|
||||
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
|
||||
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
|
||||
.setSubresourceRange(
|
||||
vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
|
||||
|
||||
buffer->pipelineBarrier(
|
||||
vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer, {}, nullptr, nullptr, barrier);
|
||||
|
||||
imageLayout = barrier.newLayout;
|
||||
}
|
||||
|
||||
void Texture2D::transitionToShaderReadLayout(const vk::UniqueCommandBuffer& buffer) {
|
||||
const auto barrier = vk::ImageMemoryBarrier()
|
||||
.setImage(imageAllocation->image)
|
||||
.setOldLayout(imageLayout)
|
||||
.setNewLayout(vk::ImageLayout::eShaderReadOnlyOptimal)
|
||||
.setSrcAccessMask(vk::AccessFlagBits::eTransferWrite)
|
||||
.setDstAccessMask(vk::AccessFlagBits::eShaderRead)
|
||||
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
|
||||
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
|
||||
.setSubresourceRange(
|
||||
vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
|
||||
|
||||
buffer->pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
|
||||
vk::PipelineStageFlagBits::eFragmentShader,
|
||||
{},
|
||||
nullptr,
|
||||
nullptr,
|
||||
barrier);
|
||||
|
||||
imageLayout = barrier.newLayout;
|
||||
}
|
||||
|
||||
void Texture2D::transitionToGeneralLayout(const vk::UniqueCommandBuffer& buffer) {
|
||||
const auto barrier = vk::ImageMemoryBarrier()
|
||||
.setImage(imageAllocation->image)
|
||||
.setOldLayout(imageLayout)
|
||||
.setNewLayout(vk::ImageLayout::eGeneral)
|
||||
.setSrcAccessMask(vk::AccessFlagBits::eTransferWrite)
|
||||
.setDstAccessMask(vk::AccessFlagBits::eMemoryRead)
|
||||
.setSrcQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
|
||||
.setDstQueueFamilyIndex(VK_QUEUE_FAMILY_IGNORED)
|
||||
.setSubresourceRange(
|
||||
vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1));
|
||||
|
||||
buffer->pipelineBarrier(
|
||||
vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eTransfer, {}, nullptr, nullptr, barrier);
|
||||
|
||||
imageLayout = barrier.newLayout;
|
||||
}
|
||||
|
||||
const vk::Sampler& Texture2D::getVulkanSampler() {
|
||||
if (samplerStateDirty) {
|
||||
createSampler();
|
||||
}
|
||||
|
||||
return sampler;
|
||||
}
|
||||
|
||||
void Texture2D::copyImage(vk::Image image) {
|
||||
if (!image) return;
|
||||
|
||||
create();
|
||||
|
||||
context.submitOneTimeCommand([&](const vk::UniqueCommandBuffer& commandBuffer) {
|
||||
const auto copyInfo = vk::ImageCopy()
|
||||
.setSrcSubresource({vk::ImageAspectFlagBits::eColor, 0, 0, 1})
|
||||
.setDstSubresource({vk::ImageAspectFlagBits::eColor, 0, 0, 1})
|
||||
.setExtent({size.width, size.height, 1});
|
||||
|
||||
transitionToTransferLayout(commandBuffer);
|
||||
commandBuffer->copyImage(
|
||||
image, vk::ImageLayout::eTransferSrcOptimal, imageAllocation->image, imageLayout, copyInfo);
|
||||
transitionToGeneralLayout(commandBuffer);
|
||||
});
|
||||
}
|
||||
|
||||
std::shared_ptr<PremultipliedImage> Texture2D::readImage() {
|
||||
if (!imageData) {
|
||||
imageData = std::make_shared<PremultipliedImage>();
|
||||
}
|
||||
|
||||
// check for offset/padding
|
||||
const auto& device = context.getBackend().getDevice();
|
||||
const auto& layout = device->getImageSubresourceLayout(imageAllocation->image,
|
||||
vk::ImageSubresource(vk::ImageAspectFlagBits::eColor, 0, 0));
|
||||
|
||||
imageData->resize(size);
|
||||
const auto& imageSize = getDataSize();
|
||||
|
||||
void* mappedData_ = nullptr;
|
||||
vmaMapMemory(context.getBackend().getAllocator(), imageAllocation->allocation, &mappedData_);
|
||||
|
||||
uint8_t* mappedData = reinterpret_cast<uint8_t*>(mappedData_) + layout.offset;
|
||||
|
||||
if (imageSize == layout.arrayPitch) {
|
||||
memcpy(imageData->data.get(), mappedData, imageSize);
|
||||
} else {
|
||||
uint32_t rowSize = size.width * getPixelStride();
|
||||
for (uint32_t i = 0; i < size.height; ++i) {
|
||||
memcpy(imageData->data.get() + rowSize * i, mappedData + layout.rowPitch * i, rowSize);
|
||||
}
|
||||
}
|
||||
|
||||
vmaUnmapMemory(context.getBackend().getAllocator(), imageAllocation->allocation);
|
||||
|
||||
return imageData;
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
135
src/mbgl/vulkan/tile_layer_group.cpp
Normal file
135
src/mbgl/vulkan/tile_layer_group.cpp
Normal file
@@ -0,0 +1,135 @@
|
||||
#include <mbgl/vulkan/tile_layer_group.hpp>
|
||||
|
||||
#include <mbgl/gfx/drawable_tweaker.hpp>
|
||||
#include <mbgl/gfx/renderable.hpp>
|
||||
#include <mbgl/gfx/renderer_backend.hpp>
|
||||
#include <mbgl/gfx/upload_pass.hpp>
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/vulkan/drawable.hpp>
|
||||
#include <mbgl/vulkan/render_pass.hpp>
|
||||
#include <mbgl/renderer/paint_parameters.hpp>
|
||||
#include <mbgl/util/convert.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
TileLayerGroup::TileLayerGroup(int32_t layerIndex_, std::size_t initialCapacity, std::string name_)
|
||||
: mbgl::TileLayerGroup(layerIndex_, initialCapacity, std::move(name_)) {}
|
||||
|
||||
void TileLayerGroup::upload(gfx::UploadPass& uploadPass) {
|
||||
if (!enabled || !getDrawableCount()) {
|
||||
return;
|
||||
}
|
||||
|
||||
#if !defined(NDEBUG)
|
||||
const auto debugGroup = uploadPass.createDebugGroup(getName() + "-upload");
|
||||
#endif
|
||||
|
||||
visitDrawables([&](gfx::Drawable& drawable_) {
|
||||
if (drawable_.getEnabled()) {
|
||||
auto& drawable = static_cast<Drawable&>(drawable_);
|
||||
drawable.upload(uploadPass);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void TileLayerGroup::render(RenderOrchestrator&, PaintParameters& parameters) {
|
||||
if (!enabled || !getDrawableCount() || !parameters.renderPass) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto& renderPass = static_cast<RenderPass&>(*parameters.renderPass);
|
||||
|
||||
// `stencilModeFor3D` uses a different stencil mask value each time its called, so if the
|
||||
// drawables in this layer use 3D stencil mode, we need to set it up here so that all the
|
||||
// drawables end up using the same mode value.
|
||||
// 2D and 3D features in the same layer group is not supported.
|
||||
bool features3d = false;
|
||||
bool stencil3d = false;
|
||||
std::optional<gfx::DepthMode> depthMode3d;
|
||||
std::optional<gfx::StencilMode> stencilMode3d;
|
||||
|
||||
// If we're using stencil clipping, we need to handle 3D features separately
|
||||
if (stencilTiles && !stencilTiles->empty()) {
|
||||
// 2D and 3D features in the same layer group is not supported.
|
||||
visitDrawables([&](const gfx::Drawable& drawable) {
|
||||
if (drawable.getEnabled() && drawable.getIs3D() && drawable.hasRenderPass(parameters.pass)) {
|
||||
features3d = true;
|
||||
if (drawable.getEnableStencil()) {
|
||||
stencil3d = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#if !defined(NDEBUG)
|
||||
const auto debugGroupRender = parameters.encoder->createDebugGroup(getName() + "-render");
|
||||
#endif
|
||||
|
||||
// If we're doing 3D stenciling and have any features to draw, set up the single-value stencil mask.
|
||||
// If we're doing 2D stenciling and have any drawables with tile IDs, render each tile into the stencil buffer with
|
||||
// a different value.
|
||||
if (features3d) {
|
||||
depthMode3d = parameters.depthModeFor3D();
|
||||
|
||||
if (stencil3d) {
|
||||
stencilMode3d = parameters.stencilModeFor3D();
|
||||
}
|
||||
} else if (stencilTiles && !stencilTiles->empty()) {
|
||||
parameters.renderTileClippingMasks(stencilTiles);
|
||||
}
|
||||
|
||||
bool bindUBOs = false;
|
||||
visitDrawables([&](gfx::Drawable& drawable) {
|
||||
if (!drawable.getEnabled() || !drawable.hasRenderPass(parameters.pass)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const auto& tweaker : drawable.getTweakers()) {
|
||||
tweaker->execute(drawable, parameters);
|
||||
}
|
||||
|
||||
if (!bindUBOs) {
|
||||
bindUniformBuffers(renderPass);
|
||||
bindUBOs = true;
|
||||
}
|
||||
|
||||
auto& drawableImpl = static_cast<Drawable&>(drawable);
|
||||
auto& drawableUniforms = drawable.mutableUniformBuffers();
|
||||
for (size_t id = 0; id < uniformBuffers.allocatedSize(); id++) {
|
||||
const auto& uniformBuffer = uniformBuffers.get(id);
|
||||
if (!uniformBuffer) continue;
|
||||
|
||||
if (features3d) {
|
||||
drawableImpl.setDepthModeFor3D(drawableImpl.getEnableDepth() ? depthMode3d.value()
|
||||
: gfx::DepthMode::disabled());
|
||||
|
||||
drawableImpl.setStencilModeFor3D(drawableImpl.getEnableStencil() ? stencilMode3d.value()
|
||||
: gfx::StencilMode::disabled());
|
||||
}
|
||||
|
||||
drawableUniforms.set(id, uniformBuffer);
|
||||
}
|
||||
|
||||
drawable.draw(parameters);
|
||||
});
|
||||
|
||||
if (bindUBOs) {
|
||||
unbindUniformBuffers(renderPass);
|
||||
}
|
||||
}
|
||||
|
||||
void TileLayerGroup::bindUniformBuffers(RenderPass& renderPass) const noexcept {
|
||||
for (size_t id = 0; id < uniformBuffers.allocatedSize(); id++) {
|
||||
const auto& uniformBuffer = uniformBuffers.get(id);
|
||||
if (!uniformBuffer) continue;
|
||||
const auto& buffer = static_cast<UniformBuffer&>(*uniformBuffer);
|
||||
const auto& resource = buffer.getBufferResource();
|
||||
renderPass.bindVertex(resource, 0, id);
|
||||
renderPass.bindFragment(resource, 0, id);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
42
src/mbgl/vulkan/uniform_buffer.cpp
Normal file
42
src/mbgl/vulkan/uniform_buffer.cpp
Normal file
@@ -0,0 +1,42 @@
|
||||
#include <mbgl/vulkan/uniform_buffer.hpp>
|
||||
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
|
||||
#include <cassert>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
UniformBuffer::UniformBuffer(BufferResource&& buffer_)
|
||||
: gfx::UniformBuffer(buffer_.getSizeInBytes()),
|
||||
buffer(std::move(buffer_)) {
|
||||
buffer.getContext().renderingStats().numUniformBuffers++;
|
||||
buffer.getContext().renderingStats().memUniformBuffers += size;
|
||||
}
|
||||
|
||||
UniformBuffer::UniformBuffer(UniformBuffer&& other)
|
||||
: gfx::UniformBuffer(std::move(other)),
|
||||
buffer(std::move(other.buffer)) {}
|
||||
|
||||
UniformBuffer::~UniformBuffer() {
|
||||
buffer.getContext().renderingStats().numUniformBuffers--;
|
||||
buffer.getContext().renderingStats().memUniformBuffers -= size;
|
||||
}
|
||||
|
||||
void UniformBuffer::update(const void* data, std::size_t size_) {
|
||||
assert(size == size_);
|
||||
if (size != size_ || size != buffer.getSizeInBytes()) {
|
||||
Log::Error(
|
||||
Event::General,
|
||||
"Mismatched size given to UBO update, expected " + std::to_string(size) + ", got " + std::to_string(size_));
|
||||
return;
|
||||
}
|
||||
|
||||
buffer.getContext().renderingStats().numUniformUpdates++;
|
||||
buffer.getContext().renderingStats().uniformUpdateBytes += size_;
|
||||
buffer.update(data, size, /*offset=*/0);
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
201
src/mbgl/vulkan/upload_pass.cpp
Normal file
201
src/mbgl/vulkan/upload_pass.cpp
Normal file
@@ -0,0 +1,201 @@
|
||||
#include <mbgl/vulkan/upload_pass.hpp>
|
||||
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
#include <mbgl/vulkan/command_encoder.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
#include <mbgl/vulkan/vertex_attribute.hpp>
|
||||
#include <mbgl/vulkan/vertex_buffer_resource.hpp>
|
||||
#include <mbgl/vulkan/index_buffer_resource.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
UploadPass::UploadPass(gfx::Renderable&, CommandEncoder& commandEncoder_, const char* name)
|
||||
: commandEncoder(commandEncoder_) {
|
||||
// Push the group for the name provided
|
||||
debugGroups.emplace_back(gfx::DebugGroup<gfx::UploadPass>{*this, name});
|
||||
}
|
||||
|
||||
UploadPass::~UploadPass() {
|
||||
endEncoding();
|
||||
}
|
||||
|
||||
void UploadPass::endEncoding() {
|
||||
debugGroups.clear();
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::VertexBufferResource> UploadPass::createVertexBufferResource(const void* data,
|
||||
const std::size_t size,
|
||||
const gfx::BufferUsageType,
|
||||
bool persistent) {
|
||||
return std::make_unique<VertexBufferResource>(
|
||||
commandEncoder.context.createBuffer(data, size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, persistent));
|
||||
}
|
||||
|
||||
void UploadPass::updateVertexBufferResource(gfx::VertexBufferResource& resource, const void* data, std::size_t size) {
|
||||
static_cast<VertexBufferResource&>(resource).get().update(data, size, /*offset=*/0);
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::IndexBufferResource> UploadPass::createIndexBufferResource(const void* data,
|
||||
const std::size_t size,
|
||||
const gfx::BufferUsageType,
|
||||
bool persistent) {
|
||||
return std::make_unique<IndexBufferResource>(
|
||||
commandEncoder.context.createBuffer(data, size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, persistent));
|
||||
}
|
||||
|
||||
void UploadPass::updateIndexBufferResource(gfx::IndexBufferResource& resource, const void* data, std::size_t size) {
|
||||
static_cast<IndexBufferResource&>(resource).get().update(data, size, /*offset=*/0);
|
||||
}
|
||||
|
||||
std::unique_ptr<gfx::TextureResource> UploadPass::createTextureResource(const Size,
|
||||
const void*,
|
||||
gfx::TexturePixelType,
|
||||
gfx::TextureChannelDataType) {
|
||||
assert(false);
|
||||
throw std::runtime_error("UploadPass::createTextureResource not implemented on Vulkan!");
|
||||
}
|
||||
|
||||
void UploadPass::updateTextureResource(
|
||||
gfx::TextureResource&, const Size, const void*, gfx::TexturePixelType, gfx::TextureChannelDataType) {
|
||||
assert(false);
|
||||
throw std::runtime_error("UploadPass::updateTextureResource not implemented on Vulkan!");
|
||||
}
|
||||
|
||||
void UploadPass::updateTextureResourceSub(gfx::TextureResource&,
|
||||
const uint16_t,
|
||||
const uint16_t,
|
||||
const Size,
|
||||
const void*,
|
||||
gfx::TexturePixelType,
|
||||
gfx::TextureChannelDataType) {
|
||||
assert(false);
|
||||
throw std::runtime_error("UploadPass::updateTextureResourceSub not implemented on Vulkan!");
|
||||
}
|
||||
|
||||
struct VertexBuffer : public gfx::VertexBufferBase {
|
||||
~VertexBuffer() override = default;
|
||||
|
||||
std::unique_ptr<gfx::VertexBufferResource> resource;
|
||||
};
|
||||
|
||||
static const std::unique_ptr<gfx::VertexBufferResource> noBuffer;
|
||||
|
||||
const gfx::UniqueVertexBufferResource& UploadPass::getBuffer(const gfx::VertexVectorBasePtr& vec,
|
||||
const gfx::BufferUsageType usage) {
|
||||
if (vec) {
|
||||
const auto* rawBufPtr = vec->getRawData();
|
||||
const auto rawBufSize = vec->getRawCount() * vec->getRawSize();
|
||||
|
||||
// If we already have a buffer...
|
||||
if (auto* rawData = static_cast<VertexBuffer*>(vec->getBuffer()); rawData && rawData->resource) {
|
||||
auto& resource = static_cast<VertexBufferResource&>(*rawData->resource);
|
||||
|
||||
// If it's changed, update it
|
||||
if (rawBufSize <= resource.getSizeInBytes()) {
|
||||
if (vec->getDirty()) {
|
||||
updateVertexBufferResource(resource, rawBufPtr, rawBufSize);
|
||||
vec->setDirty(false);
|
||||
}
|
||||
return rawData->resource;
|
||||
}
|
||||
}
|
||||
// Otherwise, create a new one
|
||||
if (rawBufSize > 0) {
|
||||
auto buffer = std::make_unique<VertexBuffer>();
|
||||
buffer->resource = createVertexBufferResource(rawBufPtr, rawBufSize, usage, /*persistent=*/false);
|
||||
vec->setBuffer(std::move(buffer));
|
||||
vec->setDirty(false);
|
||||
return static_cast<VertexBuffer*>(vec->getBuffer())->resource;
|
||||
}
|
||||
}
|
||||
return noBuffer;
|
||||
}
|
||||
|
||||
gfx::AttributeBindingArray UploadPass::buildAttributeBindings(
|
||||
const std::size_t,
|
||||
const gfx::AttributeDataType,
|
||||
const std::size_t,
|
||||
const std::vector<std::uint8_t>&,
|
||||
const gfx::VertexAttributeArray& defaults,
|
||||
const gfx::VertexAttributeArray& overrides,
|
||||
const gfx::BufferUsageType usage,
|
||||
/*out*/ std::vector<std::unique_ptr<gfx::VertexBufferResource>>&) {
|
||||
gfx::AttributeBindingArray bindings;
|
||||
|
||||
// For each attribute in the program, with the corresponding default and optional override...
|
||||
const auto resolveAttr = [&](const size_t, auto& default_, auto& override_) -> void {
|
||||
auto& effectiveAttr = override_ ? *override_ : default_;
|
||||
const auto& defaultAttr = static_cast<const VertexAttribute&>(default_);
|
||||
const auto index = static_cast<std::size_t>(defaultAttr.getIndex());
|
||||
|
||||
bindings.resize(std::max(bindings.size(), index + 1));
|
||||
|
||||
if (!override_) {
|
||||
// No attribute was provided, this value will be used from a uniform, but we have to set
|
||||
// up a valid binding or the validation will complain when the shader code references the
|
||||
// attribute at compile time, regardless of whether it's ever used at runtime.
|
||||
bindings[index] = {
|
||||
/*.attribute = */ {defaultAttr.getDataType(), /*offset=*/0},
|
||||
/*.vertexStride = */ static_cast<uint32_t>(VertexAttribute::getStrideOf(defaultAttr.getDataType())),
|
||||
/*.vertexBufferResource = */ nullptr,
|
||||
/*.vertexOffset = */ 0,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// If the attribute references data shared with a bucket, get the corresponding buffer.
|
||||
if (const auto& buffer = getBuffer(effectiveAttr.getSharedRawData(), usage)) {
|
||||
assert(effectiveAttr.getSharedStride() * effectiveAttr.getSharedVertexOffset() <
|
||||
effectiveAttr.getSharedRawData()->getRawSize() * effectiveAttr.getSharedRawData()->getRawCount());
|
||||
|
||||
bindings[index] = {
|
||||
/*.attribute = */ {effectiveAttr.getSharedType(), effectiveAttr.getSharedOffset()},
|
||||
/*.vertexStride = */ effectiveAttr.getSharedStride(),
|
||||
/*.vertexBufferResource = */ buffer.get(),
|
||||
/*.vertexOffset = */ effectiveAttr.getSharedVertexOffset(),
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
assert(effectiveAttr.getStride() > 0);
|
||||
|
||||
// Otherwise, turn the data managed by the attribute into a buffer.
|
||||
if (const auto& buffer = VertexAttribute::getBuffer(effectiveAttr, *this, gfx::BufferUsageType::StaticDraw)) {
|
||||
bindings[index] = {
|
||||
/*.attribute = */ {effectiveAttr.getDataType(), /*offset=*/0},
|
||||
/*.vertexStride = */ static_cast<uint32_t>(effectiveAttr.getStride()),
|
||||
/*.vertexBufferResource = */ buffer.get(),
|
||||
/*.vertexOffset = */ 0,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
assert(false);
|
||||
};
|
||||
|
||||
defaults.resolve(overrides, resolveAttr);
|
||||
|
||||
return bindings;
|
||||
}
|
||||
|
||||
void UploadPass::pushDebugGroup(const char* name) {
|
||||
commandEncoder.pushDebugGroup(name);
|
||||
}
|
||||
|
||||
void UploadPass::popDebugGroup() {
|
||||
commandEncoder.popDebugGroup();
|
||||
}
|
||||
|
||||
gfx::Context& UploadPass::getContext() {
|
||||
return commandEncoder.context;
|
||||
}
|
||||
|
||||
const gfx::Context& UploadPass::getContext() const {
|
||||
return commandEncoder.context;
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
50
src/mbgl/vulkan/vertex_attribute.cpp
Normal file
50
src/mbgl/vulkan/vertex_attribute.cpp
Normal file
@@ -0,0 +1,50 @@
|
||||
#include <mbgl/vulkan/vertex_attribute.hpp>
|
||||
|
||||
#include <mbgl/gfx/vertex_vector.hpp>
|
||||
#include <mbgl/vulkan/buffer_resource.hpp>
|
||||
#include <mbgl/vulkan/upload_pass.hpp>
|
||||
#include <mbgl/util/logging.hpp>
|
||||
#include <mbgl/util/convert.hpp>
|
||||
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
const gfx::UniqueVertexBufferResource& VertexAttribute::getBuffer(gfx::VertexAttribute& attrib_,
|
||||
UploadPass& uploadPass,
|
||||
const gfx::BufferUsageType usage) {
|
||||
if (!attrib_.getBuffer()) {
|
||||
auto& attrib = static_cast<VertexAttribute&>(attrib_);
|
||||
if (attrib.sharedRawData) {
|
||||
return uploadPass.getBuffer(attrib.sharedRawData, usage);
|
||||
} else {
|
||||
if (!attrib.rawData.empty()) {
|
||||
auto buffer = uploadPass.createVertexBufferResource(
|
||||
attrib.rawData.data(), attrib.rawData.size(), usage, false);
|
||||
attrib.setBuffer(std::move(buffer));
|
||||
attrib.setRawData({});
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
return attrib_.getBuffer();
|
||||
}
|
||||
|
||||
bool VertexAttributeArray::isDirty() const {
|
||||
return std::any_of(attrs.begin(), attrs.end(), [](const auto& attr) {
|
||||
if (attr) {
|
||||
// If we have shared data, the dirty flag from that overrides ours
|
||||
const auto& attrib = static_cast<const VertexAttribute&>(*attr);
|
||||
if (const auto& shared = attrib.getSharedRawData()) {
|
||||
return shared->getDirty();
|
||||
}
|
||||
}
|
||||
return attr && attr->isDirty();
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
26
src/mbgl/vulkan/vertex_buffer_resource.cpp
Normal file
26
src/mbgl/vulkan/vertex_buffer_resource.cpp
Normal file
@@ -0,0 +1,26 @@
|
||||
#include <mbgl/vulkan/vertex_buffer_resource.hpp>
|
||||
|
||||
#include <mbgl/vulkan/context.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace vulkan {
|
||||
|
||||
VertexBufferResource::VertexBufferResource(BufferResource&& ptr) noexcept
|
||||
: buffer(std::move(ptr)) {
|
||||
if (buffer) {
|
||||
auto& stats = buffer.getContext().renderingStats();
|
||||
stats.numVertexBuffers++;
|
||||
stats.memVertexBuffers += buffer.getSizeInBytes();
|
||||
}
|
||||
}
|
||||
|
||||
VertexBufferResource::~VertexBufferResource() noexcept {
|
||||
if (buffer) {
|
||||
auto& stats = buffer.getContext().renderingStats();
|
||||
stats.numVertexBuffers--;
|
||||
stats.memVertexBuffers -= buffer.getSizeInBytes();
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace vulkan
|
||||
} // namespace mbgl
|
||||
Reference in New Issue
Block a user