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:
Adrian Cojocaru
2024-08-01 22:49:49 +03:00
committed by GitHub
parent 88993b9420
commit 072aa32e8b
103 changed files with 11459 additions and 135 deletions

View File

@@ -13,12 +13,15 @@ public:
enum class Type : uint8_t {
OpenGL, ///< The OpenGL API backend
Metal, ///< The Metal API backend
Vulkan, ///< The Vulkan API backend
TYPE_MAX, ///< Not a valid backend type, used to determine the number
///< of available backends (ie for array allocation).
};
#if MLN_RENDER_BACKEND_METAL
static constexpr Type DefaultType = Type::Metal;
#elif MLN_RENDER_BACKEND_VULKAN
static constexpr Type DefaultType = Type::Vulkan;
#else // assume MLN_RENDER_BACKEND_OPENGL
static constexpr Type DefaultType = Type::OpenGL;
#endif
@@ -38,6 +41,8 @@ public:
static std::unique_ptr<T> Create(Args... args) {
#if MLN_RENDER_BACKEND_METAL
return Create<Type::Metal, T, Args...>(std::forward<Args>(args)...);
#elif MLN_RENDER_BACKEND_VULKAN
return Create<Type::Vulkan, T, Args...>(std::forward<Args>(args)...);
#else // assume MLN_RENDER_BACKEND_OPENGL
return Create<Type::OpenGL, T, Args...>(std::forward<Args>(args)...);
#endif

View File

@@ -97,7 +97,7 @@ public:
int32_t getLineWidth() const { return lineWidth; }
/// Set line width
void setLineWidth(int32_t value) { lineWidth = value; }
virtual void setLineWidth(int32_t value) { lineWidth = value; }
/// @brief Get the texture at the given internal ID.
const gfx::Texture2DPtr& getTexture(size_t id) const;
@@ -122,7 +122,7 @@ public:
bool getEnableColor() const { return enableColor; }
/// Set whether to render to the color target
void setEnableColor(bool value) { enableColor = value; }
virtual void setEnableColor(bool value) { enableColor = value; }
/// Whether to do stenciling (based on the Tile ID or 3D)
bool getEnableStencil() const { return enableStencil; }
@@ -175,7 +175,7 @@ public:
const gfx::CullFaceMode& getCullFaceMode() const;
/// Set cull face mode
void setCullFaceMode(const gfx::CullFaceMode&);
virtual void setCullFaceMode(const gfx::CullFaceMode&);
/// Get color mode
const gfx::ColorMode& getColorMode() const;

View File

@@ -12,8 +12,8 @@ using UniqueUniformBlock = std::unique_ptr<UniformBlock>;
/// @brief This class represents an uniform block
class UniformBlock {
protected:
/// @brief Constructor. Can only be created by UniformBlockArray implementations
public:
/// @brief Constructor
/// @param index_
/// @param size_
UniformBlock(int index_, std::size_t size_)
@@ -23,8 +23,6 @@ protected:
UniformBlock(UniformBlock&& other)
: index(other.index),
size(other.size) {}
public:
/// @brief Destructor
virtual ~UniformBlock() = default;

View File

@@ -6,21 +6,15 @@
namespace mbgl {
namespace gl {
class UniformBlockArrayGL;
class UniformBlockGL final : public gfx::UniformBlock {
// Can only be created by UniformBlockArrayGL
private:
friend UniformBlockArrayGL;
public:
UniformBlockGL(int index_, std::size_t size_)
: UniformBlock(index_, size_) {}
UniformBlockGL(const UniformBlockGL& other)
: UniformBlock(other) {}
UniformBlockGL(UniformBlockGL&& other)
: UniformBlock(std::move(other)) {}
public:
~UniformBlockGL() override = default;
void bindBuffer(const gfx::UniformBuffer& uniformBuffer) override;
void unbindBuffer() override;
};
@@ -44,11 +38,10 @@ public:
private:
std::unique_ptr<gfx::UniformBlock> create(int index, std::size_t size) override {
return std::unique_ptr<gfx::UniformBlock>(new UniformBlockGL(index, size));
return std::make_unique<UniformBlockGL>(index, size);
}
std::unique_ptr<gfx::UniformBlock> copy(const gfx::UniformBlock& uniformBlocks) override {
return std::unique_ptr<gfx::UniformBlock>(
new UniformBlockGL(static_cast<const UniformBlockGL&>(uniformBlocks)));
return std::make_unique<UniformBlockGL>(static_cast<const UniformBlockGL&>(uniformBlocks));
}
};

View File

@@ -11,13 +11,10 @@ class VertexBufferResource;
} // namespace gfx
namespace gl {
class VertexAttributeArrayGL;
class UploadPass;
class VertexAttributeGL final : public gfx::VertexAttribute {
// Can only be created by VertexAttributeArrayGL
private:
friend VertexAttributeArrayGL;
public:
VertexAttributeGL(int index_, gfx::AttributeDataType dataType_, std::size_t count_)
: VertexAttribute(index_, dataType_, count_) {}
VertexAttributeGL(const VertexAttributeGL& other)
@@ -26,8 +23,6 @@ private:
VertexAttributeGL(VertexAttributeGL&& other)
: VertexAttribute(std::move(other)),
glType(other.glType) {}
public:
~VertexAttributeGL() override = default;
platform::GLenum getGLType() const { return glType; }
@@ -70,12 +65,11 @@ private:
std::unique_ptr<gfx::VertexAttribute> create(int index,
gfx::AttributeDataType dataType,
std::size_t count) const override {
return std::unique_ptr<gfx::VertexAttribute>(new VertexAttributeGL(index, dataType, count));
return std::make_unique<VertexAttributeGL>(index, dataType, count);
}
using gfx::VertexAttributeArray::copy;
std::unique_ptr<gfx::VertexAttribute> copy(const gfx::VertexAttribute& attr) const override {
return std::unique_ptr<gfx::VertexAttribute>(
new VertexAttributeGL(static_cast<const VertexAttributeGL&>(attr)));
return std::make_unique<VertexAttributeGL>(static_cast<const VertexAttributeGL&>(attr));
}
};

View File

@@ -6,21 +6,15 @@
namespace mbgl {
namespace mtl {
class UniformBlockArray;
class UniformBlock final : public gfx::UniformBlock {
// Can only be created by UniformBlockArray
private:
friend UniformBlockArray;
public:
UniformBlock(int index_, std::size_t size_)
: gfx::UniformBlock(index_, size_) {}
UniformBlock(const UniformBlock& other)
: gfx::UniformBlock(other) {}
UniformBlock(UniformBlock&& other)
: gfx::UniformBlock(std::move(other)) {}
public:
~UniformBlock() override = default;
void bindBuffer(const gfx::UniformBuffer& uniformBuffer) override;
void unbindBuffer() override;
@@ -54,10 +48,10 @@ public:
private:
std::unique_ptr<gfx::UniformBlock> create(int index, std::size_t size) override {
return std::unique_ptr<gfx::UniformBlock>(new UniformBlock(index, size));
return std::make_unique<UniformBlock>(index, size);
}
std::unique_ptr<gfx::UniformBlock> copy(const gfx::UniformBlock& uniformBlocks) override {
return std::unique_ptr<gfx::UniformBlock>(new UniformBlock(static_cast<const UniformBlock&>(uniformBlocks)));
return std::make_unique<UniformBlock>(static_cast<const UniformBlock&>(uniformBlocks));
}
};

View File

@@ -9,20 +9,15 @@ class VertexBufferResource;
} // namespace gfx
namespace mtl {
class VertexAttributeArray;
class UploadPass;
class VertexAttribute final : public gfx::VertexAttribute {
// Can only be created by VertexAttributeArray
private:
friend VertexAttributeArray;
public:
VertexAttribute(int index_, gfx::AttributeDataType dataType_, std::size_t count_)
: gfx::VertexAttribute(index_, dataType_, count_) {}
VertexAttribute(const VertexAttribute& other) = delete;
VertexAttribute(VertexAttribute&& other)
: gfx::VertexAttribute(std::move(other)) {}
public:
~VertexAttribute() override = default;
static const gfx::UniqueVertexBufferResource& getBuffer(gfx::VertexAttribute&,
@@ -48,7 +43,7 @@ public:
private:
gfx::UniqueVertexAttribute create(int index, gfx::AttributeDataType dataType, std::size_t count) const override {
return gfx::UniqueVertexAttribute(new VertexAttribute(index, dataType, count));
return std::make_unique<VertexAttribute>(index, dataType, count);
}
};

View File

@@ -0,0 +1,152 @@
#pragma once
#include <mbgl/shaders/shader_source.hpp>
#include <mbgl/shaders/vulkan/shader_program.hpp>
namespace mbgl {
namespace shaders {
template <>
struct ShaderSource<BuiltIn::BackgroundShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "BackgroundShader";
static const std::array<UniformBlockInfo, 2> uniforms;
static const std::array<AttributeInfo, 1> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static constexpr std::array<TextureInfo, 0> textures{};
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
layout(set = 0, binding = 1) uniform BackgroundDrawableUBO {
mat4 matrix;
} drawable;
void main() {
gl_Position = drawable.matrix * vec4(in_position, 0.0, 1.0);
gl_Position.y *= -1.0;
}
)";
static constexpr auto fragment = R"(
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 2) uniform BackgroundLayerUBO {
vec4 color;
float opacity;
float pad1, pad2, pad3;
} layer;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
out_color = layer.color * layer.opacity;
}
)";
};
template <>
struct ShaderSource<BuiltIn::BackgroundPatternShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "BackgroundPatternShader";
static const std::array<UniformBlockInfo, 3> uniforms;
static const std::array<AttributeInfo, 1> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static const std::array<TextureInfo, 1> textures;
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
layout(set = 0, binding = 1) uniform BackgroundPatternDrawableUBO {
mat4 matrix;
vec2 pixel_coord_upper;
vec2 pixel_coord_lower;
float tile_units_to_pixels;
float pad1, pad2, pad3;
} drawable;
layout(set = 0, binding = 2) uniform BackgroundPatternLayerUBO {
vec2 pattern_tl_a;
vec2 pattern_br_a;
vec2 pattern_tl_b;
vec2 pattern_br_b;
vec2 pattern_size_a;
vec2 pattern_size_b;
float scale_a;
float scale_b;
float mix;
float opacity;
} layer;
layout(location = 0) out vec2 frag_pos_a;
layout(location = 1) out vec2 frag_pos_b;
void main() {
frag_pos_a = get_pattern_pos(drawable.pixel_coord_upper,
drawable.pixel_coord_lower,
layer.scale_a * layer.pattern_size_a,
drawable.tile_units_to_pixels,
in_position);
frag_pos_b = get_pattern_pos(drawable.pixel_coord_upper,
drawable.pixel_coord_lower,
layer.scale_b * layer.pattern_size_b,
drawable.tile_units_to_pixels,
in_position);
gl_Position = drawable.matrix * vec4(in_position, 0.0, 1.0);
gl_Position.y *= -1.0;
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in vec2 frag_pos_a;
layout(location = 1) in vec2 frag_pos_b;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 2) uniform BackgroundPatternLayerUBO {
vec2 pattern_tl_a;
vec2 pattern_br_a;
vec2 pattern_tl_b;
vec2 pattern_br_b;
vec2 pattern_size_a;
vec2 pattern_size_b;
float scale_a;
float scale_b;
float mix;
float opacity;
} layer;
layout(set = 1, binding = 0) uniform sampler2D image_sampler;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
const vec2 texsize = global.pattern_atlas_texsize;
const vec2 imagecoord = mod(frag_pos_a, 1.0);
const vec2 pos = mix(layer.pattern_tl_a / texsize, layer.pattern_br_a / texsize, imagecoord);
const vec4 color1 = texture(image_sampler, pos);
const vec2 imagecoord_b = mod(frag_pos_b, 1.0);
const vec2 pos2 = mix(layer.pattern_tl_b / texsize, layer.pattern_br_b / texsize, imagecoord_b);
const vec4 color2 = texture(image_sampler, pos2);
out_color = mix(color1, color2, layer.mix) * layer.opacity;
}
)";
};
} // namespace shaders
} // namespace mbgl

View File

@@ -0,0 +1,295 @@
#pragma once
#include <mbgl/shaders/shader_source.hpp>
#include <mbgl/shaders/vulkan/shader_program.hpp>
namespace mbgl {
namespace shaders {
template <>
struct ShaderSource<BuiltIn::CircleShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "CircleShader";
static const std::array<UniformBlockInfo, 4> uniforms;
static const std::array<AttributeInfo, 8> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static constexpr std::array<TextureInfo, 0> textures{};
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
#if !defined(HAS_UNIFORM_u_color)
layout(location = 1) in vec4 in_color;
#endif
#if !defined(HAS_UNIFORM_u_radius)
layout(location = 2) in vec2 in_radius;
#endif
#if !defined(HAS_UNIFORM_u_blur)
layout(location = 3) in vec2 in_blur;
#endif
#if !defined(HAS_UNIFORM_u_opacity)
layout(location = 4) in vec2 in_opacity;
#endif
#if !defined(HAS_UNIFORM_u_stroke_color)
layout(location = 5) in vec4 in_stroke_color;
#endif
#if !defined(HAS_UNIFORM_u_stroke_width)
layout(location = 6) in vec2 in_stroke_width;
#endif
#if !defined(HAS_UNIFORM_u_stroke_opacity)
layout(location = 7) in vec2 in_stroke_opacity;
#endif
layout(set = 0, binding = 1) uniform CircleDrawableUBO {
mat4 matrix;
vec2 extrude_scale;
vec2 padding;
} drawable;
layout(set = 0, binding = 2) uniform CircleEvaluatedPropsUBO {
vec4 color;
vec4 stroke_color;
float radius;
float blur;
float opacity;
float stroke_width;
float stroke_opacity;
bool scale_with_map;
bool pitch_with_map;
float padding;
} props;
layout(set = 0, binding = 3) uniform CircleInterpolateUBO {
float color_t;
float radius_t;
float blur_t;
float opacity_t;
float stroke_color_t;
float stroke_width_t;
float stroke_opacity_t;
float pad1_;
} interp;
layout(location = 0) out vec2 frag_extrude;
layout(location = 1) out float frag_antialiasblur;
#if !defined(HAS_UNIFORM_u_color)
layout(location = 2) out vec4 frag_color;
#endif
#if !defined(HAS_UNIFORM_u_radius)
layout(location = 3) out mediump float frag_radius;
#endif
#if !defined(HAS_UNIFORM_u_blur)
layout(location = 4) out lowp float frag_blur;
#endif
#if !defined(HAS_UNIFORM_u_opacity)
layout(location = 5) out lowp float frag_opacity;
#endif
#if !defined(HAS_UNIFORM_u_stroke_color)
layout(location = 6) out vec4 frag_stroke_color;
#endif
#if !defined(HAS_UNIFORM_u_stroke_width)
layout(location = 7) out mediump float frag_stroke_width;
#endif
#if !defined(HAS_UNIFORM_u_stroke_opacity)
layout(location = 8) out lowp float frag_stroke_opacity;
#endif
void main() {
#if defined(HAS_UNIFORM_u_radius)
const float radius = props.radius;
#else
const float radius = unpack_mix_float(in_radius, interp.radius_t);
#endif
#if defined(HAS_UNIFORM_u_stroke_width)
const float stroke_width = props.stroke_width;
#else
const float stroke_width = unpack_mix_float(in_stroke_width, interp.stroke_width_t);
#endif
// unencode the extrusion vector that we snuck into the a_pos vector
const vec2 extrude = mod(in_position, 2.0) * 2.0 - 1.0;
const vec2 scaled_extrude = extrude * drawable.extrude_scale;
// multiply a_pos by 0.5, since we had it * 2 in order to sneak in extrusion data
const vec2 circle_center = floor(in_position * 0.5);
if (props.pitch_with_map) {
vec2 corner_position = circle_center;
if (props.scale_with_map) {
corner_position += scaled_extrude * (radius + stroke_width);
} else {
// Pitching the circle with the map effectively scales it with the map
// To counteract the effect for pitch-scale: viewport, we rescale the
// whole circle based on the pitch scaling effect at its central point
const vec4 projected_center = drawable.matrix * vec4(circle_center, 0, 1);
corner_position += scaled_extrude * (radius + stroke_width) *
(projected_center.w / global.camera_to_center_distance);
}
gl_Position = drawable.matrix * vec4(corner_position, 0, 1);
} else {
gl_Position = drawable.matrix * vec4(circle_center, 0, 1);
const float factor = props.scale_with_map ? global.camera_to_center_distance : gl_Position.w;
gl_Position.xy += scaled_extrude * (radius + stroke_width) * factor;
}
gl_Position.y *= -1.0;
// This is a minimum blur distance that serves as a faux-antialiasing for
// the circle. since blur is a ratio of the circle's size and the intent is
// to keep the blur at roughly 1px, the two are inversely related.
frag_antialiasblur = 1.0 / DEVICE_PIXEL_RATIO / (radius + stroke_width);
frag_extrude = extrude;
#if !defined(HAS_UNIFORM_u_color)
frag_color = unpack_mix_color(in_color, interp.color_t);
#endif
#if !defined(HAS_UNIFORM_u_radius)
frag_radius = radius;
#endif
#if !defined(HAS_UNIFORM_u_blur)
frag_blur = unpack_mix_float(in_blur, interp.blur_t);
#endif
#if !defined(HAS_UNIFORM_u_opacity)
frag_opacity = unpack_mix_float(in_opacity, interp.opacity_t);
#endif
#if !defined(HAS_UNIFORM_u_stroke_color)
frag_stroke_color = unpack_mix_color(in_stroke_color, interp.stroke_color_t);
#endif
#if !defined(HAS_UNIFORM_u_stroke_width)
frag_stroke_width = stroke_width;
#endif
#if !defined(HAS_UNIFORM_u_stroke_opacity)
frag_stroke_opacity = unpack_mix_float(in_stroke_opacity, interp.stroke_opacity_t);
#endif
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in vec2 frag_extrude;
layout(location = 1) in float frag_antialiasblur;
#if !defined(HAS_UNIFORM_u_color)
layout(location = 2) in vec4 frag_color;
#endif
#if !defined(HAS_UNIFORM_u_radius)
layout(location = 3) in mediump float frag_radius;
#endif
#if !defined(HAS_UNIFORM_u_blur)
layout(location = 4) in lowp float frag_blur;
#endif
#if !defined(HAS_UNIFORM_u_opacity)
layout(location = 5) in lowp float frag_opacity;
#endif
#if !defined(HAS_UNIFORM_u_stroke_color)
layout(location = 6) in vec4 frag_stroke_color;
#endif
#if !defined(HAS_UNIFORM_u_stroke_width)
layout(location = 7) in mediump float frag_stroke_width;
#endif
#if !defined(HAS_UNIFORM_u_stroke_opacity)
layout(location = 8) in lowp float frag_stroke_opacity;
#endif
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 2) uniform CircleEvaluatedPropsUBO {
vec4 color;
vec4 stroke_color;
float radius;
float blur;
float opacity;
float stroke_width;
float stroke_opacity;
bool scale_with_map;
bool pitch_with_map;
float padding;
} props;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
#if defined(HAS_UNIFORM_u_color)
const vec4 color = props.color;
#else
const vec4 color = frag_color;
#endif
#if defined(HAS_UNIFORM_u_radius)
const float radius = props.radius;
#else
const float radius = frag_radius;
#endif
#if defined(HAS_UNIFORM_u_blur)
const float blur = props.blur;
#else
const float blur = frag_blur;
#endif
#if defined(HAS_UNIFORM_u_opacity)
const float opacity = props.opacity;
#else
const float opacity = frag_opacity;
#endif
#if defined(HAS_UNIFORM_u_stroke_color)
const vec4 stroke_color = props.stroke_color;
#else
const vec4 stroke_color = frag_stroke_color;
#endif
#if defined(HAS_UNIFORM_u_stroke_width)
const float stroke_width = props.stroke_width;
#else
const float stroke_width = frag_stroke_width;
#endif
#if defined(HAS_UNIFORM_u_stroke_opacity)
const float stroke_opacity = props.stroke_opacity;
#else
const float stroke_opacity = frag_stroke_opacity;
#endif
const float extrude_length = length(frag_extrude);
const float antialiased_blur = -max(blur, frag_antialiasblur);
const float opacity_t = smoothstep(0.0, antialiased_blur, extrude_length - 1.0);
const float color_t = (stroke_width < 0.01) ? 0.0 :
smoothstep(antialiased_blur, 0.0, extrude_length - radius / (radius + stroke_width));
out_color = opacity_t * mix(color * opacity, stroke_color * stroke_opacity, color_t);
}
)";
};
} // namespace shaders
} // namespace mbgl

View File

@@ -0,0 +1,47 @@
#pragma once
#include <mbgl/shaders/shader_source.hpp>
#include <mbgl/shaders/vulkan/shader_program.hpp>
#include <mbgl/util/mat4.hpp>
namespace mbgl {
namespace shaders {
struct ClipUBO {
matf4 matrix;
std::uint32_t stencil_ref;
};
template <>
struct ShaderSource<BuiltIn::ClippingMaskProgram, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "ClippingMaskProgram";
static constexpr std::array<UniformBlockInfo, 0> uniforms{};
static const std::array<AttributeInfo, 1> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static constexpr std::array<TextureInfo, 0> textures{};
static constexpr auto vertex = R"(
layout(location = 0) in vec2 position;
layout(push_constant) uniform constants {
mat4 matrix;
} constant;
void main() {
gl_Position = constant.matrix * vec4(position, 0.0, 1.0);
gl_Position.y *= -1.0;
}
)";
static constexpr auto fragment = R"(
layout(location = 0) out vec4 outColor;
void main() {
outColor = vec4(0.0f);
}
)";
};
} // namespace shaders
} // namespace mbgl

View File

@@ -0,0 +1,189 @@
#pragma once
#include <mbgl/shaders/shader_source.hpp>
#include <mbgl/shaders/vulkan/shader_program.hpp>
namespace mbgl {
namespace shaders {
template <>
struct ShaderSource<BuiltIn::CollisionBoxShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "CollisionBoxShader";
static const std::array<UniformBlockInfo, 1> uniforms;
static const std::array<AttributeInfo, 5> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static constexpr std::array<TextureInfo, 0> textures{};
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
layout(location = 1) in vec2 in_anchor_position;
layout(location = 2) in vec2 in_extrude;
layout(location = 3) in vec2 in_placed;
layout(location = 4) in vec2 in_shift;
layout(set = 0, binding = 1) uniform CollisionBoxUBO {
mat4 matrix;
vec2 extrude_scale;
float overscale_factor;
float pad1;
} drawable;
layout(location = 0) out float frag_placed;
layout(location = 1) out float frag_notUsed;
void main() {
vec4 projectedPoint = drawable.matrix * vec4(in_anchor_position, 0.0, 1.0);
float camera_to_anchor_distance = projectedPoint.w;
float collision_perspective_ratio = clamp(
0.5 + 0.5 * (global.camera_to_center_distance / camera_to_anchor_distance),
0.0, // Prevents oversized near-field boxes in pitched/overzoomed tiles
4.0);
gl_Position = drawable.matrix * vec4(in_position, 0.0, 1.0);
gl_Position.xy += (in_extrude + in_shift) * drawable.extrude_scale * gl_Position.w * collision_perspective_ratio;
gl_Position.y *= -1.0;
frag_placed = in_placed.x;
frag_notUsed = in_placed.y;
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in float frag_placed;
layout(location = 1) in float frag_notUsed;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 1) uniform CollisionBoxUBO {
mat4 matrix;
vec2 extrude_scale;
float overscale_factor;
float pad1;
} drawable;
void main() {
float alpha = 0.5;
// Red = collision, hide label
vec4 color = vec4(1.0, 0.0, 0.0, 1.0) * alpha;
// Blue = no collision, label is showing
if (frag_placed > 0.5) {
color = vec4(0.0, 0.0, 1.0, 0.5) * alpha;
}
if (frag_notUsed > 0.5) {
// This box not used, fade it out
color *= 0.1;
}
out_color = color;
}
)";
};
template <>
struct ShaderSource<BuiltIn::CollisionCircleShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "CollisionCircleShader";
static const std::array<UniformBlockInfo, 1> uniforms;
static const std::array<AttributeInfo, 4> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static constexpr std::array<TextureInfo, 0> textures{};
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
layout(location = 1) in vec2 in_anchor_position;
layout(location = 2) in vec2 in_extrude;
layout(location = 3) in vec2 in_placed;
layout(set = 0, binding = 1) uniform CollisionCircleUBO {
mat4 matrix;
vec2 extrude_scale;
float overscale_factor;
float pad1;
} drawable;
layout(location = 0) out float frag_placed;
layout(location = 1) out float frag_notUsed;
layout(location = 2) out float frag_radius;
layout(location = 3) out vec2 frag_extrude;
layout(location = 4) out vec2 frag_extrude_scale;
void main() {
vec4 projectedPoint = drawable.matrix * vec4(in_anchor_position, 0, 1);
float camera_to_anchor_distance = projectedPoint.w;
float collision_perspective_ratio = clamp(
0.5 + 0.5 * (global.camera_to_center_distance / camera_to_anchor_distance),
0.0, // Prevents oversized near-field circles in pitched/overzoomed tiles
4.0);
float padding_factor = 1.2; // Pad the vertices slightly to make room for anti-alias blur
gl_Position = drawable.matrix * vec4(in_position, 0.0, 1.0);
gl_Position.xy += in_extrude * drawable.extrude_scale * padding_factor * gl_Position.w * collision_perspective_ratio;
gl_Position.y *= -1.0;
frag_placed = in_placed.x;
frag_notUsed = in_placed.y;
frag_radius = abs(float(in_extrude.y)); // We don't pitch the circles, so both units of the extrusion vector are equal in magnitude to the radius
frag_extrude = in_extrude * padding_factor;
frag_extrude_scale = drawable.extrude_scale * global.camera_to_center_distance * collision_perspective_ratio;
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in float frag_placed;
layout(location = 1) in float frag_notUsed;
layout(location = 2) in float frag_radius;
layout(location = 3) in vec2 frag_extrude;
layout(location = 4) in vec2 frag_extrude_scale;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 1) uniform CollisionCircleUBO {
mat4 matrix;
vec2 extrude_scale;
float overscale_factor;
float pad1;
} drawable;
void main() {
float alpha = 0.5;
// Red = collision, hide label
vec4 color = vec4(1.0, 0.0, 0.0, 1.0) * alpha;
// Blue = no collision, label is showing
if (frag_placed > 0.5) {
color = vec4(0.0, 0.0, 1.0, 0.5) * alpha;
}
if (frag_notUsed > 0.5) {
// This box not used, fade it out
color *= 0.2;
}
float extrude_scale_length = length(frag_extrude_scale);
float extrude_length = length(frag_extrude) * extrude_scale_length;
float stroke_width = 15.0 * extrude_scale_length / drawable.overscale_factor;
float radius = frag_radius * extrude_scale_length;
float distance_to_edge = abs(extrude_length - radius);
float opacity_t = smoothstep(-stroke_width, 0.0, -distance_to_edge);
out_color = color * opacity_t;
}
)";
};
} // namespace shaders
} // namespace mbgl

View File

@@ -0,0 +1,104 @@
#pragma once
#include <mbgl/shaders/shader_source.hpp>
namespace mbgl {
namespace shaders {
template <>
struct ShaderSource<BuiltIn::Prelude, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "Prelude";
static constexpr auto vertex = R"(
#define M_PI 3.1415926535897932384626433832795
// The maximum allowed miter limit is 2.0 at the moment. the extrude normal is stored
// in a byte (-128..127). We scale regular normals up to length 63, but there are also
// "special" normals that have a bigger length (of up to 126 in this case).
#define LINE_NORMAL_SCALE (1.0 / (127 / 2))
// The attribute conveying progress along a line is scaled to [0, 2^15).
#define MAX_LINE_DISTANCE 32767.0
// Unpack a pair of values that have been packed into a single float.
// The packed values are assumed to be 8-bit unsigned integers, and are
// packed like so:
// packedValue = floor(input[0]) * 256 + input[1],
vec2 unpack_float(const float packedValue) {
int packedIntValue = int(packedValue);
int v0 = packedIntValue / 256;
return vec2(v0, packedIntValue - v0 * 256);
}
vec2 unpack_opacity(const float packedOpacity) {
int intOpacity = int(packedOpacity) / 2;
return vec2(float(intOpacity) / 127.0, mod(packedOpacity, 2.0));
}
// To minimize the number of attributes needed, we encode a 4-component
// color into a pair of floats (i.e. a vec2) as follows:
// [ floor(color.r * 255) * 256 + color.g * 255,
// floor(color.b * 255) * 256 + color.g * 255 ]
vec4 decode_color(const vec2 encodedColor) {
return vec4(
unpack_float(encodedColor[0]) / 255.0,
unpack_float(encodedColor[1]) / 255.0
);
}
// Unpack a pair of paint values and interpolate between them.
float unpack_mix_float(const vec2 packedValue, const float t) {
return mix(packedValue[0], packedValue[1], t);
}
// Unpack a pair of paint values and interpolate between them.
vec4 unpack_mix_color(const vec4 packedColors, const float t) {
vec4 minColor = decode_color(vec2(packedColors[0], packedColors[1]));
vec4 maxColor = decode_color(vec2(packedColors[2], packedColors[3]));
return mix(minColor, maxColor, t);
}
// unpack pattern position
vec2 get_pattern_pos(const vec2 pixel_coord_upper, const vec2 pixel_coord_lower,
const vec2 pattern_size, const float tile_units_to_pixels, const vec2 pos) {
const vec2 offset = mod(mod(mod(pixel_coord_upper, pattern_size) * 256.0, pattern_size) * 256.0 + pixel_coord_lower, pattern_size);
return (tile_units_to_pixels * pos + offset) / pattern_size;
}
layout(set = 0, binding = 0) uniform GlobalPaintParamsUBO {
vec2 pattern_atlas_texsize;
vec2 units_to_pixels;
vec2 world_size;
float camera_to_center_distance;
float symbol_fade_change;
float aspect_ratio;
float pixel_ratio;
float zoom;
float pad1;
} global;
)";
static constexpr auto fragment = R"(
#define M_PI 3.1415926535897932384626433832795
#define SDF_PX 8.0
layout(set = 0, binding = 0) uniform GlobalPaintParamsUBO {
vec2 pattern_atlas_texsize;
vec2 units_to_pixels;
vec2 world_size;
float camera_to_center_distance;
float symbol_fade_change;
float aspect_ratio;
float pixel_ratio;
float zoom;
float pad1;
} global;
)";
};
} // namespace shaders
} // namespace mbgl

View File

@@ -0,0 +1,76 @@
#pragma once
#include <mbgl/shaders/shader_source.hpp>
#include <mbgl/shaders/vulkan/shader_program.hpp>
namespace mbgl {
namespace shaders {
template <>
struct ShaderSource<BuiltIn::DebugShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "DebugShader";
static const std::array<UniformBlockInfo, 1> uniforms;
static const std::array<AttributeInfo, 1> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static const std::array<TextureInfo, 1> textures;
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
layout(set = 0, binding = 1) uniform DebugUBO {
mat4 matrix;
vec4 color;
float overlay_scale;
float pad1, pad2, pad3;
} debug;
layout(location = 0) out vec2 frag_uv;
void main() {
gl_Position = debug.matrix * vec4(in_position * debug.overlay_scale, 0, 1);
gl_Position.y *= -1.0;
// This vertex shader expects a EXTENT x EXTENT quad,
// The UV co-ordinates for the overlay texture can be calculated using that knowledge
frag_uv = in_position / 8192.0;
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in vec2 frag_uv;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 1) uniform DebugUBO {
mat4 matrix;
vec4 color;
float overlay_scale;
float pad1, pad2, pad3;
} debug;
layout(set = 1, binding = 0) uniform sampler2D image_sampler;
void main() {
vec4 overlay_color = texture(image_sampler, frag_uv);
out_color = mix(debug.color, overlay_color, overlay_color.a);
}
)";
};
template <>
struct ShaderSource<BuiltIn::WideVectorShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "WideVectorShader";
static constexpr std::array<UniformBlockInfo, 0> uniforms{};
static constexpr std::array<AttributeInfo, 0> attributes{};
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static constexpr std::array<TextureInfo, 0> textures{};
static constexpr auto vertex = R"()";
static constexpr auto fragment = R"()";
};
} // namespace shaders
} // namespace mbgl

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,200 @@
#pragma once
#include <mbgl/shaders/shader_source.hpp>
#include <mbgl/shaders/vulkan/shader_program.hpp>
namespace mbgl {
namespace shaders {
template <>
struct ShaderSource<BuiltIn::HeatmapShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "HeatmapShader";
static const std::array<UniformBlockInfo, 3> uniforms;
static const std::array<AttributeInfo, 3> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static constexpr std::array<TextureInfo, 0> textures{};
static constexpr auto vertex = R"(
// Effective "0" in the kernel density texture to adjust the kernel size to;
// this empirically chosen number minimizes artifacts on overlapping kernels
// for typical heatmap cases (assuming clustered source)
const float ZERO = 1.0 / 255.0 / 16.0;
// Gaussian kernel coefficient: 1 / sqrt(2 * PI)
#define GAUSS_COEF 0.3989422804014327
layout(location = 0) in vec2 in_position;
#if !defined(HAS_UNIFORM_u_weight)
layout(location = 1) in vec2 in_weight;
#endif
#if !defined(HAS_UNIFORM_u_radius)
layout(location = 2) in vec2 in_radius;
#endif
layout(set = 0, binding = 1) uniform HeatmapDrawableUBO {
mat4 matrix;
float extrude_scale;
float pad1;
vec2 pad2;
} drawable;
layout(set = 0, binding = 2) uniform HeatmapEvaluatedPropsUBO {
float weight;
float radius;
float intensity;
float pad1;
} props;
layout(set = 0, binding = 3) uniform HeatmapInterpolateUBO {
float weight_t;
float radius_t;
vec2 pad1;
} interp;
layout(location = 0) out float frag_weight;
layout(location = 1) out lowp vec2 frag_extrude;
void main() {
#if defined(HAS_UNIFORM_u_weight)
const float weight = props.weight;
#else
const float weight = unpack_mix_float(in_weight, interp.weight_t);
#endif
#if defined(HAS_UNIFORM_u_radius)
const float radius = props.radius;
#else
const float radius = unpack_mix_float(in_radius, interp.radius_t);
#endif
// unencode the extrusion vector that we snuck into the a_pos vector
const vec2 unscaled_extrude = mod(in_position, 2.0) * 2.0 - 1.0;
// This 'extrude' comes in ranging from [-1, -1], to [1, 1]. We'll use
// it to produce the vertices of a square mesh framing the point feature
// we're adding to the kernel density texture. We'll also pass it as
// a varying, so that the fragment shader can determine the distance of
// each fragment from the point feature.
// Before we do so, we need to scale it up sufficiently so that the
// kernel falls effectively to zero at the edge of the mesh.
// That is, we want to know S such that
// weight * u_intensity * GAUSS_COEF * exp(-0.5 * 3.0^2 * S^2) == ZERO
// Which solves to:
// S = sqrt(-2.0 * log(ZERO / (weight * u_intensity * GAUSS_COEF))) / 3.0
const float S = sqrt(-2.0 * log(ZERO / weight / props.intensity / GAUSS_COEF)) / 3.0;
// Pass the varying in units of radius
const vec2 extrude = S * unscaled_extrude;
// Scale by radius and the zoom-based scale factor to produce actual
// mesh position
const vec2 scaled_extrude = extrude * radius * drawable.extrude_scale;
// multiply a_pos by 0.5, since we had it * 2 in order to sneak
// in extrusion data
gl_Position = drawable.matrix * vec4(floor(in_position * 0.5) + scaled_extrude, 0, 1);
gl_Position.y *= -1.0;
frag_weight = weight;
frag_extrude = extrude;
}
)";
static constexpr auto fragment = R"(
// Gaussian kernel coefficient: 1 / sqrt(2 * PI)
#define GAUSS_COEF 0.3989422804014327
layout(location = 0) in float frag_weight;
layout(location = 1) in lowp vec2 frag_extrude;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 2) uniform HeatmapEvaluatedPropsUBO {
float weight;
float radius;
float intensity;
float pad1;
} props;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
// Kernel density estimation with a Gaussian kernel of size 5x5
const float d = -0.5 * 3.0 * 3.0 * dot(frag_extrude, frag_extrude);
const float val = frag_weight * props.intensity * GAUSS_COEF * exp(d);
out_color = vec4(val, 1.0, 1.0, 1.0);
}
)";
};
template <>
struct ShaderSource<BuiltIn::HeatmapTextureShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "HeatmapTextureShader";
static const std::array<UniformBlockInfo, 2> uniforms;
static const std::array<AttributeInfo, 1> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static const std::array<TextureInfo, 2> textures;
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
layout(set = 0, binding = 1) uniform HeatmapTexturePropsUBO {
mat4 matrix;
float opacity;
float pad1, pad2, pad3;
} props;
layout(location = 0) out vec2 frag_position;
void main() {
gl_Position = props.matrix * vec4(in_position * global.world_size, 0, 1);
gl_Position.y *= -1.0;
frag_position = in_position;
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in vec2 frag_position;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 1) uniform HeatmapTexturePropsUBO {
mat4 matrix;
float opacity;
float pad1, pad2, pad3;
} props;
layout(set = 1, binding = 0) uniform sampler2D image_sampler;
layout(set = 1, binding = 1) uniform sampler2D color_ramp_sampler;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
const float t = texture(image_sampler, frag_position).r;
const vec4 color = texture(color_ramp_sampler, vec2(t, 0.5));
out_color = color * props.opacity;
}
)";
};
} // namespace shaders
} // namespace mbgl

View File

@@ -0,0 +1,227 @@
#pragma once
#include <mbgl/shaders/shader_source.hpp>
#include <mbgl/shaders/vulkan/shader_program.hpp>
namespace mbgl {
namespace shaders {
template <>
struct ShaderSource<BuiltIn::HillshadePrepareShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "HillshadePrepareShader";
static const std::array<UniformBlockInfo, 1> uniforms;
static const std::array<AttributeInfo, 2> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static const std::array<TextureInfo, 1> textures;
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
layout(location = 1) in vec2 in_texture_position;
layout(set = 0, binding = 1) uniform HillshadePrepareDrawableUBO {
mat4 matrix;
vec4 unpack;
vec2 dimension;
float zoom;
float maxzoom;
} drawable;
layout(location = 0) out vec2 frag_position;
void main() {
gl_Position = drawable.matrix * vec4(in_position, 0.0, 1.0);
gl_Position.y *= -1.0;
const vec2 epsilon = vec2(1.0) / drawable.dimension;
const float scale = (drawable.dimension.x - 2.0) / drawable.dimension.x;
frag_position = in_texture_position / 8192.0 * scale + epsilon;
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in vec2 frag_position;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 1) uniform HillshadePrepareDrawableUBO {
mat4 matrix;
vec4 unpack;
vec2 dimension;
float zoom;
float maxzoom;
} drawable;
layout(set = 1, binding = 0) uniform sampler2D image_sampler;
float getElevation(vec2 coord, float bias, sampler2D image_sampler, vec4 unpack) {
// Convert encoded elevation value to meters
vec4 data = texture(image_sampler, coord) * 255.0;
data.a = -1.0;
return dot(data, unpack) / 4.0;
}
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
const vec2 epsilon = 1.0 / drawable.dimension;
// queried pixels:
// +-----------+
// | | | |
// | a | b | c |
// | | | |
// +-----------+
// | | | |
// | d | e | f |
// | | | |
// +-----------+
// | | | |
// | g | h | i |
// | | | |
// +-----------+
float a = getElevation(frag_position + vec2(-epsilon.x, -epsilon.y), 0.0, image_sampler, drawable.unpack);
float b = getElevation(frag_position + vec2(0, -epsilon.y), 0.0, image_sampler, drawable.unpack);
float c = getElevation(frag_position + vec2(epsilon.x, -epsilon.y), 0.0, image_sampler, drawable.unpack);
float d = getElevation(frag_position + vec2(-epsilon.x, 0), 0.0, image_sampler, drawable.unpack);
//float e = getElevation(frag_position, 0.0, image_sampler, drawable.unpack);
float f = getElevation(frag_position + vec2(epsilon.x, 0), 0.0, image_sampler, drawable.unpack);
float g = getElevation(frag_position + vec2(-epsilon.x, epsilon.y), 0.0, image_sampler, drawable.unpack);
float h = getElevation(frag_position + vec2(0, epsilon.y), 0.0, image_sampler, drawable.unpack);
float i = getElevation(frag_position + vec2(epsilon.x, epsilon.y), 0.0, image_sampler, drawable.unpack);
// here we divide the x and y slopes by 8 * pixel size
// where pixel size (aka meters/pixel) is:
// circumference of the world / (pixels per tile * number of tiles)
// which is equivalent to: 8 * 40075016.6855785 / (512 * pow(2, u_zoom))
// which can be reduced to: pow(2, 19.25619978527 - u_zoom)
// we want to vertically exaggerate the hillshading though, because otherwise
// it is barely noticeable at low zooms. to do this, we multiply this by some
// scale factor pow(2, (u_zoom - u_maxzoom) * a) where a is an arbitrary value
// Here we use a=0.3 which works out to the expression below. see
// nickidlugash's awesome breakdown for more info
// https://github.com/mapbox/mapbox-gl-js/pull/5286#discussion_r148419556
float exaggeration = drawable.zoom < 2.0 ? 0.4 : drawable.zoom < 4.5 ? 0.35 : 0.3;
vec2 deriv = vec2(
(c + f + f + i) - (a + d + d + g),
(g + h + h + i) - (a + b + b + c)
) / pow(2.0, (drawable.zoom - drawable.maxzoom) * exaggeration + 19.2562 - drawable.zoom);
out_color = clamp(vec4(
deriv.x / 2.0 + 0.5,
deriv.y / 2.0 + 0.5,
1.0,
1.0), 0.0, 1.0);
}
)";
};
template <>
struct ShaderSource<BuiltIn::HillshadeShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "HillshadeShader";
static const std::array<UniformBlockInfo, 2> uniforms;
static const std::array<AttributeInfo, 2> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static const std::array<TextureInfo, 1> textures;
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
layout(location = 1) in vec2 in_texture_position;
layout(set = 0, binding = 1) uniform HillshadeDrawableUBO {
mat4 matrix;
vec2 latrange;
vec2 light;
} drawable;
layout(location = 0) out vec2 frag_position;
void main() {
gl_Position = drawable.matrix * vec4(in_position, 0.0, 1.0);
gl_Position.y *= -1.0;
frag_position = vec2(in_texture_position) / 8192.0;
frag_position.y = 1.0 - frag_position.y; // TODO check this. prepare should ignore the flip
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in vec2 frag_position;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 1) uniform HillshadeDrawableUBO {
mat4 matrix;
vec2 latrange;
vec2 light;
} drawable;
layout(set = 0, binding = 2) uniform HillshadeEvaluatedPropsUBO {
vec4 highlight;
vec4 shadow;
vec4 accent;
} props;
layout(set = 1, binding = 0) uniform sampler2D image_sampler;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
vec4 pixel = texture(image_sampler, frag_position);
vec2 deriv = pixel.rg * 2.0 - 1.0;
// We divide the slope by a scale factor based on the cosin of the pixel's approximate latitude
// to account for mercator projection distortion. see #4807 for details
float scaleFactor = cos(radians((drawable.latrange[0] - drawable.latrange[1]) * frag_position.y + drawable.latrange[1]));
// We also multiply the slope by an arbitrary z-factor of 1.25
float slope = atan(1.25 * length(deriv) / scaleFactor);
float aspect = deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : M_PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);
float intensity = drawable.light.x;
// We add PI to make this property match the global light object, which adds PI/2 to the light's azimuthal
// position property to account for 0deg corresponding to north/the top of the viewport in the style spec
// and the original shader was written to accept (-illuminationDirection - 90) as the azimuthal.
float azimuth = drawable.light.y + M_PI;
// We scale the slope exponentially based on intensity, using a calculation similar to
// the exponential interpolation function in the style spec:
// https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/expression/definitions/interpolate.js#L217-L228
// so that higher intensity values create more opaque hillshading.
float base = 1.875 - intensity * 1.75;
float maxValue = 0.5 * M_PI;
float scaledSlope = intensity != 0.5 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;
// The accent color is calculated with the cosine of the slope while the shade color is calculated with the sine
// so that the accent color's rate of change eases in while the shade color's eases out.
float accent = cos(scaledSlope);
// We multiply both the accent and shade color by a clamped intensity value
// so that intensities >= 0.5 do not additionally affect the color values
// while intensity values < 0.5 make the overall color more transparent.
vec4 accent_color = (1.0 - accent) * props.accent * clamp(intensity * 2.0, 0.0, 1.0);
float shade = abs(mod((aspect + azimuth) / M_PI + 0.5, 2.0) - 1.0);
vec4 shade_color = mix(props.shadow, props.highlight, shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);
vec4 color = accent_color * (1.0 - shade_color.a) + shade_color;
out_color = color;
}
)";
};
} // namespace shaders
} // namespace mbgl

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,126 @@
#pragma once
#include <mbgl/shaders/shader_source.hpp>
#include <mbgl/shaders/vulkan/shader_program.hpp>
namespace mbgl {
namespace shaders {
template <>
struct ShaderSource<BuiltIn::RasterShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "RasterShader";
static const std::array<UniformBlockInfo, 2> uniforms;
static const std::array<AttributeInfo, 2> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static const std::array<TextureInfo, 2> textures;
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
layout(location = 1) in vec2 in_texture_position;
layout(set = 0, binding = 1) uniform RasterDrawableUBO {
mat4 matrix;
} drawable;
layout(set = 0, binding = 2) uniform RasterEvaluatedPropsUBO {
vec4 spin_weights;
vec2 tl_parent;
float scale_parent;
float buffer_scale;
float fade_t;
float opacity;
float brightness_low;
float brightness_high;
float saturation_factor;
float contrast_factor;
float pad1, pad2;
} props;
layout(location = 0) out vec2 frag_position0;
layout(location = 1) out vec2 frag_position1;
void main() {
gl_Position = drawable.matrix * vec4(in_position, 0, 1);
gl_Position.y *= -1.0;
// We are using Int16 for texture position coordinates to give us enough precision for
// fractional coordinates. We use 8192 to scale the texture coordinates in the buffer
// as an arbitrarily high number to preserve adequate precision when rendering.
// This is also the same value as the EXTENT we are using for our tile buffer pos coordinates,
// so math for modifying either is consistent.
frag_position0 = (((in_texture_position / 8192.0) - 0.5) / props.buffer_scale ) + 0.5;
frag_position1 = (frag_position0 * props.scale_parent) + props.tl_parent;
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in vec2 frag_position0;
layout(location = 1) in vec2 frag_position1;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 2) uniform RasterEvaluatedPropsUBO {
vec4 spin_weights;
vec2 tl_parent;
float scale_parent;
float buffer_scale;
float fade_t;
float opacity;
float brightness_low;
float brightness_high;
float saturation_factor;
float contrast_factor;
float pad1, pad2;
} props;
layout(set = 1, binding = 0) uniform sampler2D image0_sampler;
layout(set = 1, binding = 1) uniform sampler2D image1_sampler;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
// read and cross-fade colors from the main and parent tiles
vec4 color0 = texture(image0_sampler, frag_position0);
vec4 color1 = texture(image1_sampler, frag_position1);
if (color0.a > 0.0) {
color0.rgb = color0.rgb / color0.a;
}
if (color1.a > 0.0) {
color1.rgb = color1.rgb / color1.a;
}
vec4 color = mix(color0, color1, props.fade_t);
color.a *= props.opacity;
vec3 rgb = color.rgb;
// spin
rgb = vec3(
dot(rgb, props.spin_weights.xyz),
dot(rgb, props.spin_weights.zxy),
dot(rgb, props.spin_weights.yzx));
// saturation
float average = (color.r + color.g + color.b) / 3.0;
rgb += (average - rgb) * props.saturation_factor;
// contrast
rgb = (rgb - 0.5) * props.contrast_factor + 0.5;
// brightness
vec3 high_vec = vec3(props.brightness_low, props.brightness_low, props.brightness_low);
vec3 low_vec = vec3(props.brightness_high, props.brightness_high, props.brightness_high);
out_color = vec4(vec3(mix(high_vec, low_vec, rgb) * color.a), color.a);
}
)";
};
} // namespace shaders
} // namespace mbgl

View File

@@ -0,0 +1,92 @@
#pragma once
#include <mbgl/gfx/shader_group.hpp>
#include <mbgl/programs/program_parameters.hpp>
#include <mbgl/shaders/vulkan/shader_program.hpp>
#include <mbgl/shaders/shader_source.hpp>
#include <mbgl/util/hash.hpp>
#include <mbgl/util/containers.hpp>
#include <numeric>
#include <string>
#include <type_traits>
namespace mbgl {
namespace vulkan {
class ShaderGroupBase : public gfx::ShaderGroup {
protected:
ShaderGroupBase(const ProgramParameters& parameters_)
: programParameters(parameters_) {}
using DefinesMap = mbgl::unordered_map<std::string, std::string>;
void addAdditionalDefines(const StringIDSetsPair& propertiesAsUniforms, DefinesMap& additionalDefines) {
additionalDefines.reserve(propertiesAsUniforms.first.size());
for (const auto name : propertiesAsUniforms.first) {
// We expect the names to be prefixed by "a_", but we need just the base here.
const auto* base = (name[0] == 'a' && name[1] == '_') ? &name[2] : name.data();
additionalDefines.insert(std::make_pair(std::string(uniformPrefix) + base, std::string()));
}
}
ProgramParameters programParameters;
private:
static constexpr auto uniformPrefix = "HAS_UNIFORM_u_";
};
template <shaders::BuiltIn ShaderID>
class ShaderGroup final : public ShaderGroupBase {
public:
ShaderGroup(const ProgramParameters& programParameters_)
: ShaderGroupBase(programParameters_) {}
~ShaderGroup() noexcept override = default;
gfx::ShaderPtr getOrCreateShader(gfx::Context& gfxContext,
const StringIDSetsPair& propertiesAsUniforms,
std::string_view /*firstAttribName*/) override {
using ShaderSource = shaders::ShaderSource<ShaderID, gfx::Backend::Type::Vulkan>;
constexpr auto& name = ShaderSource::name;
constexpr auto& vert = ShaderSource::vertex;
constexpr auto& frag = ShaderSource::fragment;
std::size_t seed = 0;
mbgl::util::hash_combine(seed, propertyHash(propertiesAsUniforms));
mbgl::util::hash_combine(seed, programParameters.getDefinesHash());
const std::string shaderName = getShaderName(name, seed);
auto shader = get<vulkan::ShaderProgram>(shaderName);
if (!shader) {
DefinesMap additionalDefines;
addAdditionalDefines(propertiesAsUniforms, additionalDefines);
auto& context = static_cast<Context&>(gfxContext);
shader = context.createProgram(shaderName, vert, frag, programParameters, additionalDefines);
assert(shader);
if (!shader || !registerShader(shader, shaderName)) {
assert(false);
throw std::runtime_error("Failed to register " + shaderName + " with shader group!");
}
using ShaderClass = shaders::ShaderSource<ShaderID, gfx::Backend::Type::Vulkan>;
for (const auto& attrib : ShaderClass::attributes) {
if (!propertiesAsUniforms.second.count(attrib.id)) {
shader->initAttribute(attrib);
}
}
for (const auto& attrib : ShaderClass::instanceAttributes) {
shader->initInstanceAttribute(attrib);
}
for (const auto& uniform : ShaderClass::uniforms) {
shader->initUniformBlock(uniform);
}
for (const auto& texture : ShaderClass::textures) {
shader->initTexture(texture);
}
}
return shader;
}
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,95 @@
#pragma once
#include <mbgl/shaders/shader_program_base.hpp>
#include <mbgl/vulkan/uniform_block.hpp>
#include <mbgl/vulkan/vertex_attribute.hpp>
#include <mbgl/vulkan/renderer_backend.hpp>
#include <mbgl/vulkan/pipeline.hpp>
#include <optional>
#include <string>
#include <unordered_map>
namespace mbgl {
namespace shaders {
struct UniformBlockInfo {
constexpr UniformBlockInfo(bool vertex_, bool fragment_, std::size_t size_, std::size_t id_)
: index(id_),
vertex(vertex_),
fragment(fragment_),
size(size_),
id(id_) {}
std::size_t index;
bool vertex;
bool fragment;
std::size_t size;
std::size_t id;
};
struct AttributeInfo {
constexpr AttributeInfo(std::size_t index_, gfx::AttributeDataType dataType_, std::size_t id_)
: index(index_),
dataType(dataType_),
id(id_) {}
std::size_t index;
gfx::AttributeDataType dataType;
std::size_t id;
};
struct TextureInfo {
constexpr TextureInfo(std::size_t index_, std::size_t id_)
: index(index_),
id(id_) {}
std::size_t index;
std::size_t id;
};
} // namespace shaders
namespace vulkan {
class RenderableResource;
class RendererBackend;
class ShaderProgram;
using UniqueShaderProgram = std::unique_ptr<ShaderProgram>;
class ShaderProgram final : public gfx::ShaderProgramBase {
public:
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);
~ShaderProgram() noexcept override;
static constexpr std::string_view Name{"GenericVulkanShader"};
const std::string_view typeName() const noexcept override { return Name; }
const vk::UniquePipeline& getPipeline(const PipelineInfo& pipelineInfo);
std::optional<size_t> getSamplerLocation(const size_t id) const override { return textureBindings[id]; }
const gfx::VertexAttributeArray& getVertexAttributes() const override { return vertexAttributes; }
const gfx::VertexAttributeArray& getInstanceAttributes() const override { return instanceAttributes; }
const gfx::UniformBlockArray& getUniformBlocks() const override { return uniformBlocks; }
gfx::UniformBlockArray& mutableUniformBlocks() override { return uniformBlocks; }
bool hasTextures() const;
void initAttribute(const shaders::AttributeInfo&);
void initInstanceAttribute(const shaders::AttributeInfo&);
void initUniformBlock(const shaders::UniformBlockInfo&);
void initTexture(const shaders::TextureInfo&);
protected:
std::string shaderName;
RendererBackend& backend;
vk::UniqueShaderModule vertexShader;
vk::UniqueShaderModule fragmentShader;
std::unordered_map<std::size_t, vk::UniquePipeline> pipelines;
UniformBlockArray uniformBlocks;
VertexAttributeArray vertexAttributes;
VertexAttributeArray instanceAttributes;
std::array<std::optional<size_t>, shaders::maxTextureCountPerShader> textureBindings;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,890 @@
#pragma once
#include <mbgl/shaders/shader_source.hpp>
#include <mbgl/shaders/vulkan/shader_program.hpp>
namespace mbgl {
namespace shaders {
template <>
struct ShaderSource<BuiltIn::SymbolIconShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "SymbolIconShader";
static const std::array<UniformBlockInfo, 5> uniforms;
static const std::array<AttributeInfo, 6> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static const std::array<TextureInfo, 1> textures;
static constexpr auto vertex = R"(
layout(location = 0) in vec4 in_pos_offset;
layout(location = 1) in vec4 in_data;
layout(location = 2) in vec4 in_pixeloffset;
layout(location = 3) in vec3 in_projected_pos;
layout(location = 4) in float in_fade_opacity;
#if !defined(HAS_UNIFORM_u_opacity)
layout(location = 5) in vec2 in_opacity;
#endif
layout(set = 0, binding = 1) uniform SymbolDrawableUBO {
mat4 matrix;
mat4 label_plane_matrix;
mat4 coord_matrix;
vec2 texsize;
vec2 texsize_icon;
float gamma_scale;
bool rotate_symbol;
vec2 pad;
} drawable;
layout(set = 0, binding = 2) uniform SymbolTilePropsUBO {
bool is_text;
bool is_halo;
bool pitch_with_map;
bool is_size_zoom_constant;
bool is_size_feature_constant;
float size_t;
float size;
float padding;
} tile;
layout(set = 0, binding = 3) uniform SymbolInterpolateUBO {
float fill_color_t;
float halo_color_t;
float opacity_t;
float halo_width_t;
float halo_blur_t;
float pad1, pad2, pad3;
} interp;
layout(location = 0) out mediump vec2 frag_tex;
layout(location = 1) out mediump float frag_opacity;
void main() {
const vec2 a_pos = in_pos_offset.xy;
const vec2 a_offset = in_pos_offset.zw;
const vec2 a_tex = in_data.xy;
const vec2 a_size = in_data.zw;
const float a_size_min = floor(a_size[0] * 0.5);
const vec2 a_pxoffset = in_pixeloffset.xy;
const vec2 a_minFontScale = in_pixeloffset.zw / 256.0;
const float segment_angle = -in_projected_pos[2];
float size;
if (!tile.is_size_zoom_constant && !tile.is_size_feature_constant) {
size = mix(a_size_min, a_size[1], tile.size_t) / 128.0;
} else if (tile.is_size_zoom_constant && !tile.is_size_feature_constant) {
size = a_size_min / 128.0;
} else {
size = tile.size;
}
const vec4 projectedPoint = drawable.matrix * vec4(a_pos, 0, 1);
const float camera_to_anchor_distance = projectedPoint.w;
// See comments in symbol_sdf.vertex
const float distance_ratio = tile.pitch_with_map ?
camera_to_anchor_distance / global.camera_to_center_distance :
global.camera_to_center_distance / camera_to_anchor_distance;
const float perspective_ratio = clamp(
0.5 + 0.5 * distance_ratio,
0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles
4.0);
size *= perspective_ratio;
const float fontScale = tile.is_text ? size / 24.0 : size;
float symbol_rotation = 0.0;
if (drawable.rotate_symbol) {
// See comments in symbol_sdf.vertex
const vec4 offsetProjectedPoint = drawable.matrix * vec4(a_pos + vec2(1, 0), 0, 1);
const vec2 a = projectedPoint.xy / projectedPoint.w;
const vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;
symbol_rotation = atan((b.y - a.y) / global.aspect_ratio, b.x - a.x);
}
const float angle_sin = sin(segment_angle + symbol_rotation);
const float angle_cos = cos(segment_angle + symbol_rotation);
const mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);
const vec4 projected_pos = drawable.label_plane_matrix * vec4(in_projected_pos.xy, 0.0, 1.0);
const vec2 pos0 = projected_pos.xy / projected_pos.w;
const vec2 posOffset = a_offset * max(a_minFontScale, fontScale) / 32.0 + a_pxoffset / 16.0;
gl_Position = drawable.coord_matrix * vec4(pos0 + rotation_matrix * posOffset, 0.0, 1.0);
gl_Position.y *= -1.0;
const vec2 raw_fade_opacity = unpack_opacity(in_fade_opacity);
const float fade_change = raw_fade_opacity[1] > 0.5 ? global.symbol_fade_change : -global.symbol_fade_change;
const float fade_opacity = max(0.0, min(1.0, raw_fade_opacity[0] + fade_change));
frag_tex = a_tex / drawable.texsize;
#if defined(HAS_UNIFORM_u_opacity)
frag_opacity = fade_opacity;
#else
frag_opacity = unpack_mix_float(in_opacity, interp.opacity_t) * fade_opacity;
#endif
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in mediump vec2 frag_tex;
layout(location = 1) in mediump float frag_opacity;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 2) uniform SymbolTilePropsUBO {
bool is_text;
bool is_halo;
bool pitch_with_map;
bool is_size_zoom_constant;
bool is_size_feature_constant;
float size_t;
float size;
float padding;
} tile;
layout(set = 0, binding = 4) uniform SymbolEvaluatedPropsUBO {
vec4 text_fill_color;
vec4 text_halo_color;
float text_opacity;
float text_halo_width;
float text_halo_blur;
float pad1;
vec4 icon_fill_color;
vec4 icon_halo_color;
float icon_opacity;
float icon_halo_width;
float icon_halo_blur;
float pad2;
} props;
layout(set = 1, binding = 0) uniform sampler2D image0_sampler;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
#if defined(HAS_UNIFORM_u_opacity)
const float opacity = (tile.is_text ? props.text_opacity : props.icon_opacity) * frag_opacity;
#else
const float opacity = frag_opacity; // fade_opacity is baked in for this case
#endif
out_color = texture(image0_sampler, frag_tex) * opacity;
}
)";
};
template <>
struct ShaderSource<BuiltIn::SymbolSDFIconShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "SymbolSDFIconShader";
static const std::array<UniformBlockInfo, 5> uniforms;
static const std::array<AttributeInfo, 10> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static const std::array<TextureInfo, 1> textures;
static constexpr auto vertex = R"(
layout(location = 0) in vec4 in_pos_offset;
layout(location = 1) in vec4 in_data;
layout(location = 2) in vec4 in_pixeloffset;
layout(location = 3) in vec3 in_projected_pos;
layout(location = 4) in float in_fade_opacity;
#if !defined(HAS_UNIFORM_u_fill_color)
layout(location = 5) in vec4 in_fill_color;
#endif
#if !defined(HAS_UNIFORM_u_halo_color)
layout(location = 6) in vec4 in_halo_color;
#endif
#if !defined(HAS_UNIFORM_u_opacity)
layout(location = 7) in vec2 in_opacity;
#endif
#if !defined(HAS_UNIFORM_u_halo_width)
layout(location = 8) in vec2 in_halo_width;
#endif
#if !defined(HAS_UNIFORM_u_halo_blur)
layout(location = 9) in vec2 in_halo_blur;
#endif
layout(set = 0, binding = 1) uniform SymbolDrawableUBO {
mat4 matrix;
mat4 label_plane_matrix;
mat4 coord_matrix;
vec2 texsize;
vec2 texsize_icon;
float gamma_scale;
bool rotate_symbol;
vec2 pad;
} drawable;
layout(set = 0, binding = 2) uniform SymbolTilePropsUBO {
bool is_text;
bool is_halo;
bool pitch_with_map;
bool is_size_zoom_constant;
bool is_size_feature_constant;
float size_t;
float size;
float padding;
} tile;
layout(set = 0, binding = 3) uniform SymbolInterpolateUBO {
float fill_color_t;
float halo_color_t;
float opacity_t;
float halo_width_t;
float halo_blur_t;
float pad1, pad2, pad3;
} interp;
layout(location = 0) out mediump vec2 frag_tex;
layout(location = 1) out mediump float frag_fade_opacity;
layout(location = 2) out mediump float frag_font_scale;
layout(location = 3) out mediump float frag_gamma_scale;
#if !defined(HAS_UNIFORM_u_fill_color)
layout(location = 4) out mediump vec4 frag_fill_color;
#endif
#if !defined(HAS_UNIFORM_u_halo_color)
layout(location = 5) out mediump vec4 frag_halo_color;
#endif
#if !defined(HAS_UNIFORM_u_opacity)
layout(location = 6) out mediump float frag_opacity;
#endif
#if !defined(HAS_UNIFORM_u_halo_width)
layout(location = 7) out mediump float frag_halo_width;
#endif
#if !defined(HAS_UNIFORM_u_halo_blur)
layout(location = 8) out mediump float frag_halo_blur;
#endif
void main() {
const vec2 a_pos = in_pos_offset.xy;
const vec2 a_offset = in_pos_offset.zw;
const vec2 a_tex = in_data.xy;
const vec2 a_size = in_data.zw;
const float a_size_min = floor(a_size[0] * 0.5);
const vec2 a_pxoffset = in_pixeloffset.xy;
const float segment_angle = -in_projected_pos[2];
float size;
if (!tile.is_size_zoom_constant && !tile.is_size_feature_constant) {
size = mix(a_size_min, a_size[1], tile.size_t) / 128.0;
} else if (tile.is_size_zoom_constant && !tile.is_size_feature_constant) {
size = a_size_min / 128.0;
} else {
size = tile.size;
}
const vec4 projectedPoint = drawable.matrix * vec4(a_pos, 0, 1);
const float camera_to_anchor_distance = projectedPoint.w;
// If the label is pitched with the map, layout is done in pitched space,
// which makes labels in the distance smaller relative to viewport space.
// We counteract part of that effect by multiplying by the perspective ratio.
// If the label isn't pitched with the map, we do layout in viewport space,
// which makes labels in the distance larger relative to the features around
// them. We counteract part of that effect by dividing by the perspective ratio.
const float distance_ratio = tile.pitch_with_map ?
camera_to_anchor_distance / global.camera_to_center_distance :
global.camera_to_center_distance / camera_to_anchor_distance;
const float perspective_ratio = clamp(
0.5 + 0.5 * distance_ratio,
0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles
4.0);
size *= perspective_ratio;
const float fontScale = tile.is_text ? size / 24.0 : size;
float symbol_rotation = 0.0;
if (drawable.rotate_symbol) {
// Point labels with 'rotation-alignment: map' are horizontal with respect to tile units
// To figure out that angle in projected space, we draw a short horizontal line in tile
// space, project it, and measure its angle in projected space.
const vec4 offsetProjectedPoint = drawable.matrix * vec4(a_pos + vec2(1, 0), 0, 1);
const vec2 a = projectedPoint.xy / projectedPoint.w;
const vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;
symbol_rotation = atan((b.y - a.y) / global.aspect_ratio, b.x - a.x);
}
const float angle_sin = sin(segment_angle + symbol_rotation);
const float angle_cos = cos(segment_angle + symbol_rotation);
const mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);
const vec4 projected_pos = drawable.label_plane_matrix * vec4(in_projected_pos.xy, 0.0, 1.0);
const vec2 pos_rot = a_offset / 32.0 * fontScale + a_pxoffset;
const vec2 pos0 = projected_pos.xy / projected_pos.w + rotation_matrix * pos_rot;
gl_Position = drawable.coord_matrix * vec4(pos0, 0.0, 1.0);
gl_Position.y *= -1.0;
const vec2 raw_fade_opacity = unpack_opacity(in_fade_opacity);
const float fade_change = raw_fade_opacity[1] > 0.5 ? global.symbol_fade_change : -global.symbol_fade_change;
frag_tex = a_tex / drawable.texsize;
frag_fade_opacity = max(0.0, min(1.0, raw_fade_opacity[0] + fade_change));
frag_font_scale = fontScale;
frag_gamma_scale = gl_Position.w;
#if !defined(HAS_UNIFORM_u_fill_color)
frag_fill_color = unpack_mix_color(in_fill_color, interp.fill_color_t);
#endif
#if !defined(HAS_UNIFORM_u_halo_color)
frag_halo_color = unpack_mix_color(in_halo_color, interp.halo_color_t);
#endif
#if !defined(HAS_UNIFORM_u_halo_width)
frag_halo_width = unpack_mix_float(in_halo_width, interp.halo_width_t);
#endif
#if !defined(HAS_UNIFORM_u_halo_blur)
frag_halo_blur = unpack_mix_float(in_halo_blur, interp.halo_blur_t);
#endif
#if !defined(HAS_UNIFORM_u_opacity)
frag_opacity = unpack_mix_float(in_opacity, interp.opacity_t);
#endif
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in mediump vec2 frag_tex;
layout(location = 1) in mediump float frag_fade_opacity;
layout(location = 2) in mediump float frag_font_scale;
layout(location = 3) in mediump float frag_gamma_scale;
#if !defined(HAS_UNIFORM_u_fill_color)
layout(location = 4) in mediump vec4 frag_fill_color;
#endif
#if !defined(HAS_UNIFORM_u_halo_color)
layout(location = 5) in mediump vec4 frag_halo_color;
#endif
#if !defined(HAS_UNIFORM_u_opacity)
layout(location = 6) in mediump float frag_opacity;
#endif
#if !defined(HAS_UNIFORM_u_halo_width)
layout(location = 7) in mediump float frag_halo_width;
#endif
#if !defined(HAS_UNIFORM_u_halo_blur)
layout(location = 8) in mediump float frag_halo_blur;
#endif
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 1) uniform SymbolDrawableUBO {
mat4 matrix;
mat4 label_plane_matrix;
mat4 coord_matrix;
vec2 texsize;
vec2 texsize_icon;
float gamma_scale;
bool rotate_symbol;
vec2 pad;
} drawable;
layout(set = 0, binding = 2) uniform SymbolTilePropsUBO {
bool is_text;
bool is_halo;
bool pitch_with_map;
bool is_size_zoom_constant;
bool is_size_feature_constant;
float size_t;
float size;
float padding;
} tile;
layout(set = 0, binding = 4) uniform SymbolEvaluatedPropsUBO {
vec4 text_fill_color;
vec4 text_halo_color;
float text_opacity;
float text_halo_width;
float text_halo_blur;
float pad1;
vec4 icon_fill_color;
vec4 icon_halo_color;
float icon_opacity;
float icon_halo_width;
float icon_halo_blur;
float pad2;
} props;
layout(set = 1, binding = 0) uniform sampler2D image0_sampler;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
#if defined(HAS_UNIFORM_u_fill_color)
const vec4 fill_color = tile.is_text ? props.text_fill_color : props.icon_fill_color;
#else
const vec4 fill_color = frag_fill_color;
#endif
#if defined(HAS_UNIFORM_u_halo_color)
const vec4 halo_color = tile.is_text ? props.text_halo_color : props.icon_halo_color;
#else
const vec4 halo_color = frag_halo_color;
#endif
#if defined(HAS_UNIFORM_u_opacity)
const float opacity = tile.is_text ? props.text_opacity : props.icon_opacity;
#else
const float opacity = frag_opacity;
#endif
#if defined(HAS_UNIFORM_u_halo_width)
const float halo_width = tile.is_text ? props.text_halo_width : props.icon_halo_width;
#else
const float halo_width = frag_halo_width;
#endif
#if defined(HAS_UNIFORM_u_halo_blur)
const float halo_blur = tile.is_text ? props.text_halo_blur : props.icon_halo_blur;
#else
const float halo_blur = frag_halo_blur;
#endif
const float EDGE_GAMMA = 0.105 / DEVICE_PIXEL_RATIO;
const float fontGamma = frag_font_scale * drawable.gamma_scale;
const vec4 color = tile.is_halo ? halo_color : fill_color;
const float gamma = ((tile.is_halo ? (halo_blur * 1.19 / SDF_PX) : 0) + EDGE_GAMMA) / fontGamma;
const float buff = tile.is_halo ? (6.0 - halo_width / frag_font_scale) / SDF_PX : (256.0 - 64.0) / 256.0;
const float dist = texture(image0_sampler, frag_tex).a;
const float gamma_scaled = gamma * frag_gamma_scale;
const float alpha = smoothstep(buff - gamma_scaled, buff + gamma_scaled, dist);
out_color = color * (alpha * opacity * frag_fade_opacity);
}
)";
};
template <>
struct ShaderSource<BuiltIn::SymbolTextAndIconShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "SymbolTextAndIconShader";
static const std::array<UniformBlockInfo, 5> uniforms;
static const std::array<AttributeInfo, 9> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static const std::array<TextureInfo, 2> textures;
static constexpr auto vertex = R"(
#define SDF 1.0
#define ICON 0.0
layout(location = 0) in vec4 in_pos_offset;
layout(location = 1) in vec4 in_data;
layout(location = 2) in vec3 in_projected_pos;
layout(location = 3) in float in_fade_opacity;
#if !defined(HAS_UNIFORM_u_fill_color)
layout(location = 4) in vec4 in_fill_color;
#endif
#if !defined(HAS_UNIFORM_u_halo_color)
layout(location = 5) in vec4 in_halo_color;
#endif
#if !defined(HAS_UNIFORM_u_opacity)
layout(location = 6) in vec2 in_opacity;
#endif
#if !defined(HAS_UNIFORM_u_halo_width)
layout(location = 7) in vec2 in_halo_width;
#endif
#if !defined(HAS_UNIFORM_u_halo_blur)
layout(location = 8) in vec2 in_halo_blur;
#endif
layout(set = 0, binding = 1) uniform SymbolDrawableUBO {
mat4 matrix;
mat4 label_plane_matrix;
mat4 coord_matrix;
vec2 texsize;
vec2 texsize_icon;
float gamma_scale;
bool rotate_symbol;
vec2 pad;
} drawable;
layout(set = 0, binding = 2) uniform SymbolTilePropsUBO {
bool is_text;
bool is_halo;
bool pitch_with_map;
bool is_size_zoom_constant;
bool is_size_feature_constant;
float size_t;
float size;
float padding;
} tile;
layout(set = 0, binding = 3) uniform SymbolInterpolateUBO {
float fill_color_t;
float halo_color_t;
float opacity_t;
float halo_width_t;
float halo_blur_t;
float pad1, pad2, pad3;
} interp;
layout(location = 0) out mediump vec2 frag_tex;
layout(location = 1) out mediump float frag_fade_opacity;
layout(location = 2) out mediump float frag_font_scale;
layout(location = 3) out mediump float frag_gamma_scale;
#if !defined(HAS_UNIFORM_u_fill_color)
layout(location = 4) out mediump vec4 frag_fill_color;
#endif
#if !defined(HAS_UNIFORM_u_halo_color)
layout(location = 5) out mediump vec4 frag_halo_color;
#endif
#if !defined(HAS_UNIFORM_u_opacity)
layout(location = 6) out mediump float frag_opacity;
#endif
#if !defined(HAS_UNIFORM_u_halo_width)
layout(location = 7) out mediump float frag_halo_width;
#endif
#if !defined(HAS_UNIFORM_u_halo_blur)
layout(location = 8) out mediump float frag_halo_blur;
#endif
layout(location = 9) out int frag_is_icon;
void main() {
const vec2 a_pos = in_pos_offset.xy;
const vec2 a_offset = in_pos_offset.zw;
const vec2 a_tex = in_data.xy;
const vec2 a_size = in_data.zw;
const float a_size_min = floor(a_size[0] * 0.5);
const float is_sdf = a_size[0] - 2.0 * a_size_min;
const float segment_angle = -in_projected_pos[2];
float size;
if (!tile.is_size_zoom_constant && !tile.is_size_feature_constant) {
size = mix(a_size_min, a_size[1], tile.size_t) / 128.0;
} else if (tile.is_size_zoom_constant && !tile.is_size_feature_constant) {
size = a_size_min / 128.0;
} else {
size = tile.size;
}
const vec4 projectedPoint = drawable.matrix * vec4(a_pos, 0, 1);
const float camera_to_anchor_distance = projectedPoint.w;
// If the label is pitched with the map, layout is done in pitched space,
// which makes labels in the distance smaller relative to viewport space.
// We counteract part of that effect by multiplying by the perspective ratio.
// If the label isn't pitched with the map, we do layout in viewport space,
// which makes labels in the distance larger relative to the features around
// them. We counteract part of that effect by dividing by the perspective ratio.
const float distance_ratio = tile.pitch_with_map ?
camera_to_anchor_distance / global.camera_to_center_distance :
global.camera_to_center_distance / camera_to_anchor_distance;
const float perspective_ratio = clamp(
0.5 + 0.5 * distance_ratio,
0.0, // Prevents oversized near-field symbols in pitched/overzoomed tiles
4.0);
size *= perspective_ratio;
const float fontScale = size / 24.0;
float symbol_rotation = 0.0;
if (drawable.rotate_symbol) {
// Point labels with 'rotation-alignment: map' are horizontal with respect to tile units
// To figure out that angle in projected space, we draw a short horizontal line in tile
// space, project it, and measure its angle in projected space.
const vec4 offsetProjectedPoint = drawable.matrix * vec4(a_pos + vec2(1, 0), 0, 1);
const vec2 a = projectedPoint.xy / projectedPoint.w;
const vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;
symbol_rotation = atan((b.y - a.y) / global.aspect_ratio, b.x - a.x);
}
const float angle_sin = sin(segment_angle + symbol_rotation);
const float angle_cos = cos(segment_angle + symbol_rotation);
const mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);
const vec4 projected_pos = drawable.label_plane_matrix * vec4(in_projected_pos.xy, 0.0, 1.0);
const vec2 pos_rot = a_offset / 32.0 * fontScale;
const vec2 pos0 = projected_pos.xy / projected_pos.w + rotation_matrix * pos_rot;
gl_Position = drawable.coord_matrix * vec4(pos0, 0.0, 1.0);
gl_Position.y *= -1.0;
const vec2 raw_fade_opacity = unpack_opacity(in_fade_opacity);
const float fade_change = raw_fade_opacity[1] > 0.5 ? global.symbol_fade_change : -global.symbol_fade_change;
const bool is_icon = (is_sdf == ICON);
frag_is_icon = int(is_icon);
frag_tex = a_tex / (is_icon ? drawable.texsize_icon : drawable.texsize);
frag_fade_opacity = max(0.0, min(1.0, raw_fade_opacity[0] + fade_change));
frag_font_scale = fontScale;
frag_gamma_scale = gl_Position.w;
#if !defined(HAS_UNIFORM_u_fill_color)
frag_fill_color = unpack_mix_color(in_fill_color, interp.fill_color_t);
#endif
#if !defined(HAS_UNIFORM_u_halo_color)
frag_halo_color = unpack_mix_color(in_halo_color, interp.halo_color_t);
#endif
#if !defined(HAS_UNIFORM_u_halo_width)
frag_halo_width = unpack_mix_float(in_halo_width, interp.halo_width_t);
#endif
#if !defined(HAS_UNIFORM_u_halo_blur)
frag_halo_blur = unpack_mix_float(in_halo_blur, interp.halo_blur_t);
#endif
#if !defined(HAS_UNIFORM_u_opacity)
frag_opacity = unpack_mix_float(in_opacity, interp.opacity_t);
#endif
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in mediump vec2 frag_tex;
layout(location = 1) in mediump float frag_fade_opacity;
layout(location = 2) in mediump float frag_font_scale;
layout(location = 3) in mediump float frag_gamma_scale;
#if !defined(HAS_UNIFORM_u_fill_color)
layout(location = 4) in mediump vec4 frag_fill_color;
#endif
#if !defined(HAS_UNIFORM_u_halo_color)
layout(location = 5) in mediump vec4 frag_halo_color;
#endif
#if !defined(HAS_UNIFORM_u_opacity)
layout(location = 6) in mediump float frag_opacity;
#endif
#if !defined(HAS_UNIFORM_u_halo_width)
layout(location = 7) in mediump float frag_halo_width;
#endif
#if !defined(HAS_UNIFORM_u_halo_blur)
layout(location = 8) in mediump float frag_halo_blur;
#endif
layout(location = 9) flat in int frag_is_icon;
layout(location = 0) out vec4 out_color;
layout(set = 0, binding = 1) uniform SymbolDrawableUBO {
mat4 matrix;
mat4 label_plane_matrix;
mat4 coord_matrix;
vec2 texsize;
vec2 texsize_icon;
float gamma_scale;
bool rotate_symbol;
vec2 pad;
} drawable;
layout(set = 0, binding = 2) uniform SymbolTilePropsUBO {
bool is_text;
bool is_halo;
bool pitch_with_map;
bool is_size_zoom_constant;
bool is_size_feature_constant;
float size_t;
float size;
float padding;
} tile;
layout(set = 0, binding = 4) uniform SymbolEvaluatedPropsUBO {
vec4 text_fill_color;
vec4 text_halo_color;
float text_opacity;
float text_halo_width;
float text_halo_blur;
float pad1;
vec4 icon_fill_color;
vec4 icon_halo_color;
float icon_opacity;
float icon_halo_width;
float icon_halo_blur;
float pad2;
} props;
layout(set = 1, binding = 0) uniform sampler2D glyph_image;
layout(set = 1, binding = 1) uniform sampler2D icon_image;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
#if defined(HAS_UNIFORM_u_fill_color)
const vec4 fill_color = tile.is_text ? props.text_fill_color : props.icon_fill_color;
#else
const vec4 fill_color = frag_fill_color;
#endif
#if defined(HAS_UNIFORM_u_halo_color)
const vec4 halo_color = tile.is_text ? props.text_halo_color : props.icon_halo_color;
#else
const vec4 halo_color = frag_halo_color;
#endif
#if defined(HAS_UNIFORM_u_opacity)
const float opacity = tile.is_text ? props.text_opacity : props.icon_opacity;
#else
const float opacity = frag_opacity;
#endif
#if defined(HAS_UNIFORM_u_halo_width)
const float halo_width = tile.is_text ? props.text_halo_width : props.icon_halo_width;
#else
const float halo_width = frag_halo_width;
#endif
#if defined(HAS_UNIFORM_u_halo_blur)
const float halo_blur = tile.is_text ? props.text_halo_blur : props.icon_halo_blur;
#else
const float halo_blur = frag_halo_blur;
#endif
if (bool(frag_is_icon)) {
const float alpha = opacity * frag_fade_opacity;
out_color = texture(icon_image, frag_tex) * alpha;
return;
}
const float EDGE_GAMMA = 0.105 / DEVICE_PIXEL_RATIO;
const float fontGamma = frag_font_scale * drawable.gamma_scale;
const vec4 color = tile.is_halo ? halo_color : fill_color;
const float gamma = ((tile.is_halo ? (halo_blur * 1.19 / SDF_PX) : 0) + EDGE_GAMMA) / fontGamma;
const float buff = tile.is_halo ? (6.0 - halo_width / frag_font_scale) / SDF_PX : (256.0 - 64.0) / 256.0;
const float dist = texture(glyph_image, frag_tex).a;
const float gamma_scaled = gamma * frag_gamma_scale;
const float alpha = smoothstep(buff - gamma_scaled, buff + gamma_scaled, dist);
out_color = color * (alpha * opacity * frag_fade_opacity);
}
)";
};
template <>
struct ShaderSource<BuiltIn::CustomSymbolIconShader, gfx::Backend::Type::Vulkan> {
static constexpr const char* name = "CustomSymbolIconShader";
static const std::array<UniformBlockInfo, 2> uniforms;
static const std::array<AttributeInfo, 2> attributes;
static constexpr std::array<AttributeInfo, 0> instanceAttributes{};
static const std::array<TextureInfo, 1> textures;
static constexpr auto vertex = R"(
layout(location = 0) in vec2 in_position;
layout(location = 1) in vec2 in_tex;
layout(set = 0, binding = 1) uniform CustomSymbolIconDrawableUBO {
mat4 matrix;
} drawable;
layout(set = 0, binding = 2) uniform CustomSymbolIconParametersUBO {
vec2 extrude_scale;
vec2 anchor;
float angle_degrees;
bool scale_with_map;
bool pitch_with_map;
float camera_to_center_distance;
float aspect_ratio;
float pad0, pad1, pad3;
} parameters;
layout(location = 0) out vec2 frag_tex;
vec2 rotateVec2(vec2 v, float angle) {
float cosA = cos(angle);
float sinA = sin(angle);
return vec2(v.x * cosA - v.y * sinA, v.x * sinA + v.y * cosA);
}
vec2 ellipseRotateVec2(vec2 v, float angle, float radiusRatio /* A/B */) {
float cosA = cos(angle);
float sinA = sin(angle);
float invRatio = 1.0 / radiusRatio;
return vec2(v.x * cosA - radiusRatio * v.y * sinA, invRatio * v.x * sinA + v.y * cosA);
}
void main() {
const vec2 extrude = mod(in_position, 2.0) * 2.0 - 1.0;
const vec2 anchor = (parameters.anchor - vec2(0.5, 0.5)) * 2.0;
const vec2 center = floor(in_position * 0.5);
const float angle = radians(-parameters.angle_degrees);
vec2 corner = extrude - anchor;
vec4 position;
if (parameters.pitch_with_map) {
if (parameters.scale_with_map) {
corner *= parameters.extrude_scale;
} else {
vec4 projected_center = drawable.matrix * vec4(center, 0, 1);
corner *= parameters.extrude_scale * (projected_center.w / parameters.camera_to_center_distance);
}
corner = center + rotateVec2(corner, angle);
position = drawable.matrix * vec4(corner, 0, 1);
} else {
position = drawable.matrix * vec4(center, 0, 1);
const float factor = parameters.scale_with_map ? parameters.camera_to_center_distance : position.w;
position.xy += ellipseRotateVec2(corner * parameters.extrude_scale * factor, angle, parameters.aspect_ratio);
}
gl_Position = position;
gl_Position.y *= -1.0;
frag_tex = in_tex;
}
)";
static constexpr auto fragment = R"(
layout(location = 0) in vec2 frag_tex;
layout(location = 0) out vec4 out_color;
layout(set = 1, binding = 0) uniform sampler2D image_sampler;
void main() {
#if defined(OVERDRAW_INSPECTOR)
out_color = vec4(1.0);
return;
#endif
out_color = texture(image_sampler, frag_tex);
}
)";
};
} // namespace shaders
} // namespace mbgl

View File

@@ -0,0 +1,92 @@
#pragma once
#include <mbgl/vulkan/renderer_backend.hpp>
#include <cstddef>
#include <cstdint>
#include <vector>
namespace mbgl {
namespace vulkan {
class Context;
struct BufferAllocation {
const VmaAllocator& allocator;
VmaAllocation allocation{};
VkBuffer buffer{};
void* mappedBuffer{};
BufferAllocation() = delete;
BufferAllocation(BufferAllocation&) = delete;
BufferAllocation& operator=(const BufferAllocation& other) = delete;
BufferAllocation(const VmaAllocator& allocator_)
: allocator(allocator_) {}
BufferAllocation(BufferAllocation&& other) noexcept
: allocator(other.allocator),
allocation(other.allocation),
buffer(other.buffer),
mappedBuffer(other.mappedBuffer) {
other.buffer = nullptr;
other.allocation = nullptr;
other.mappedBuffer = nullptr;
}
~BufferAllocation() { destroy(); }
bool create(const VmaAllocationCreateInfo& allocInfo, const vk::BufferCreateInfo& bufferInfo);
void destroy();
void setName(const std::string& name) const;
};
using UniqueBufferAllocation = std::unique_ptr<BufferAllocation>;
using SharedBufferAllocation = std::shared_ptr<BufferAllocation>;
class BufferResource {
public:
BufferResource() noexcept = delete;
BufferResource(Context& context_, const void* raw, std::size_t size, std::uint32_t usage, bool persistent);
BufferResource(BufferResource&&) noexcept;
virtual ~BufferResource() noexcept;
BufferResource& operator=(BufferResource&&) noexcept;
BufferResource clone() const;
void update(const void* data, std::size_t size, std::size_t offset) noexcept;
std::size_t getSizeInBytes() const noexcept { return size; }
const void* contents() const noexcept { return (raw.empty() ? nullptr : raw.data()); }
Context& getContext() const noexcept { return context; }
const VkBuffer& getVulkanBuffer() const noexcept { return bufferAllocation->buffer; }
std::size_t getVulkanBufferOffset() const noexcept;
std::size_t getVulkanBufferSize() const noexcept;
bool isValid() const noexcept { return !raw.empty(); }
operator bool() const noexcept { return isValid(); }
bool operator!() const noexcept { return !isValid(); }
using VersionType = std::uint16_t;
/// Used to detect whether buffer contents have changed
VersionType getVersion() const noexcept { return version; }
protected:
Context& context;
std::vector<std::uint8_t> raw;
std::size_t size;
std::uint32_t usage;
std::uint16_t version = 0;
bool persistent;
SharedBufferAllocation bufferAllocation;
size_t bufferWindowSize = 0;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,46 @@
#pragma once
#include <mbgl/gfx/command_encoder.hpp>
#include <mbgl/util/containers.hpp>
#include <mbgl/vulkan/renderer_backend.hpp>
namespace mbgl {
namespace gfx {
class Renderable;
} // namespace gfx
namespace vulkan {
class Context;
class RenderPass;
class UploadPass;
class CommandEncoder final : public gfx::CommandEncoder {
public:
explicit CommandEncoder(Context& context_, const vk::UniqueCommandBuffer& buffer_);
~CommandEncoder() override;
vulkan::Context& getContext() { return context; }
const vulkan::Context& getContext() const { return context; }
const vk::UniqueCommandBuffer& getCommandBuffer() const { return commandBuffer; }
std::unique_ptr<gfx::UploadPass> createUploadPass(const char* name, gfx::Renderable&) override;
std::unique_ptr<gfx::RenderPass> createRenderPass(const char* name, const gfx::RenderPassDescriptor&) override;
void present(gfx::Renderable&) override;
private:
void pushDebugGroup(const char* name) override;
void pushDebugGroup(const char* name, const std::array<float, 4>& color);
void popDebugGroup() override;
private:
friend class RenderPass;
friend class UploadPass;
vulkan::Context& context;
const vk::UniqueCommandBuffer& commandBuffer;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,203 @@
#pragma once
#include <mbgl/gfx/texture.hpp>
#include <mbgl/gfx/draw_mode.hpp>
#include <mbgl/gfx/depth_mode.hpp>
#include <mbgl/gfx/stencil_mode.hpp>
#include <mbgl/gfx/color_mode.hpp>
#include <mbgl/gfx/texture2d.hpp>
#include <mbgl/gfx/context.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/util/containers.hpp>
#include <mbgl/vulkan/uniform_buffer.hpp>
#include <mbgl/vulkan/renderer_backend.hpp>
#include <mbgl/vulkan/pipeline.hpp>
#include <memory>
#include <optional>
#include <unordered_map>
#include <vector>
namespace mbgl {
class ProgramParameters;
class RenderStaticData;
namespace gfx {
class VertexAttributeArray;
using VertexAttributeArrayPtr = std::shared_ptr<VertexAttributeArray>;
} // namespace gfx
namespace shaders {
struct ClipUBO;
} // namespace shaders
namespace vulkan {
class RenderPass;
class RendererBackend;
class ShaderProgram;
class VertexBufferResource;
class Texture2D;
using UniqueShaderProgram = std::unique_ptr<ShaderProgram>;
using UniqueVertexBufferResource = std::unique_ptr<VertexBufferResource>;
class Context final : public gfx::Context {
public:
Context(RendererBackend&);
~Context() noexcept override;
Context(const Context&) = delete;
Context& operator=(const Context& other) = delete;
RendererBackend& getBackend() const { return backend; }
void beginFrame() override;
void endFrame() override;
void waitFrame() const;
std::unique_ptr<gfx::CommandEncoder> createCommandEncoder() override;
BufferResource createBuffer(const void* data, std::size_t size, std::uint32_t usage, bool persistent) const;
UniqueShaderProgram 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);
/// Called at the end of a frame.
void performCleanup() override {}
void reduceMemoryUsage() override {}
gfx::UniqueDrawableBuilder createDrawableBuilder(std::string name) override;
gfx::UniformBufferPtr createUniformBuffer(const void* data, std::size_t size, bool persistent) override;
gfx::ShaderProgramBasePtr getGenericShader(gfx::ShaderRegistry&, const std::string& name) override;
TileLayerGroupPtr createTileLayerGroup(int32_t layerIndex, std::size_t initialCapacity, std::string name) override;
LayerGroupPtr createLayerGroup(int32_t layerIndex, std::size_t initialCapacity, std::string name) override;
gfx::Texture2DPtr createTexture2D() override;
RenderTargetPtr createRenderTarget(const Size size, const gfx::TextureChannelDataType type) override;
void resetState(gfx::DepthMode, gfx::ColorMode) override {}
bool emplaceOrUpdateUniformBuffer(gfx::UniformBufferPtr&,
const void* data,
std::size_t size,
bool persistent = false) override;
void setDirtyState() override {}
std::unique_ptr<gfx::OffscreenTexture> createOffscreenTexture(Size, gfx::TextureChannelDataType, bool, bool);
std::unique_ptr<gfx::OffscreenTexture> createOffscreenTexture(Size, gfx::TextureChannelDataType) override;
std::unique_ptr<gfx::TextureResource> createTextureResource(Size,
gfx::TexturePixelType,
gfx::TextureChannelDataType) override;
std::unique_ptr<gfx::RenderbufferResource> createRenderbufferResource(gfx::RenderbufferPixelType,
Size size) override;
std::unique_ptr<gfx::DrawScopeResource> createDrawScopeResource() override;
gfx::VertexAttributeArrayPtr createVertexAttributeArray() const override;
#if !defined(NDEBUG)
void visualizeStencilBuffer() override;
void visualizeDepthBuffer(float depthRangeSize) override;
#endif
void clearStencilBuffer(int32_t) override;
/// Get the global uniform buffers
const gfx::UniformBufferArray& getGlobalUniformBuffers() const override { return globalUniformBuffers; };
/// Get the mutable global uniform buffer array
gfx::UniformBufferArray& mutableGlobalUniformBuffers() override { return globalUniformBuffers; };
/// Bind the global uniform buffers
void bindGlobalUniformBuffers(gfx::RenderPass&) const noexcept override;
/// Unbind the global uniform buffers
void unbindGlobalUniformBuffers(gfx::RenderPass&) const noexcept override {}
bool renderTileClippingMasks(gfx::RenderPass& renderPass,
RenderStaticData& staticData,
const std::vector<shaders::ClipUBO>& tileUBOs);
const std::unique_ptr<BufferResource>& getDummyVertexBuffer();
const std::unique_ptr<BufferResource>& getDummyUniformBuffer();
const std::unique_ptr<Texture2D>& getDummyTexture();
const vk::UniqueDescriptorSetLayout& getUniformDescriptorSetLayout();
const vk::UniqueDescriptorSetLayout& getImageDescriptorSetLayout();
const std::vector<vk::DescriptorSetLayout>& getDescriptorSetLayouts();
const vk::UniquePipelineLayout& getGeneralPipelineLayout();
const vk::UniquePipelineLayout& getPushConstantPipelineLayout();
uint8_t getCurrentFrameResourceIndex() const { return frameResourceIndex; }
const vk::UniqueDescriptorPool& getCurrentDescriptorPool() const;
void enqueueDeletion(std::function<void(const Context&)>&& function);
void submitOneTimeCommand(const std::function<void(const vk::UniqueCommandBuffer&)>& function);
private:
struct FrameResources {
vk::UniqueCommandBuffer commandBuffer;
vk::UniqueDescriptorPool descriptorPool;
vk::UniqueSemaphore surfaceSemaphore;
vk::UniqueSemaphore frameSemaphore;
vk::UniqueFence flightFrameFence;
std::vector<std::function<void(const Context&)>> deletionQueue;
FrameResources(vk::UniqueCommandBuffer& cb,
vk::UniqueDescriptorPool&& dp,
vk::UniqueSemaphore&& surf,
vk::UniqueSemaphore&& frame,
vk::UniqueFence&& flight)
: commandBuffer(std::move(cb)),
descriptorPool(std::move(dp)),
surfaceSemaphore(std::move(surf)),
frameSemaphore(std::move(frame)),
flightFrameFence(std::move(flight)) {}
void runDeletionQueue(const Context&);
};
void initFrameResources();
void destroyResources();
private:
RendererBackend& backend;
vulkan::UniformBufferArray globalUniformBuffers;
std::unique_ptr<BufferResource> dummyVertexBuffer;
std::unique_ptr<BufferResource> dummyUniformBuffer;
std::unique_ptr<Texture2D> dummyTexture2D;
vk::UniqueDescriptorSetLayout uniformDescriptorSetLayout;
vk::UniqueDescriptorSetLayout imageDescriptorSetLayout;
std::vector<vk::DescriptorSetLayout> descriptorSetLayouts;
vk::UniquePipelineLayout generalPipelineLayout;
vk::UniquePipelineLayout pushConstantPipelineLayout;
uint8_t frameResourceIndex = 0;
std::vector<FrameResources> frameResources;
struct {
gfx::ShaderProgramBasePtr shader;
std::optional<BufferResource> vertexBuffer;
std::optional<BufferResource> indexBuffer;
uint32_t indexCount = 0;
PipelineInfo pipelineInfo;
} clipping;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,60 @@
#pragma once
#include <mbgl/gfx/drawable.hpp>
#include <mbgl/gfx/draw_mode.hpp>
#include <memory>
namespace mbgl {
namespace gfx {
class UploadPass;
class DepthMode;
class StencilMode;
} // namespace gfx
namespace vulkan {
class CommandEncoder;
class UploadPass;
class Drawable : public gfx::Drawable {
public:
Drawable(std::string name);
~Drawable() override;
void upload(gfx::UploadPass&);
void draw(PaintParameters&) const override;
void setIndexData(gfx::IndexVectorBasePtr, std::vector<UniqueDrawSegment> segments) override;
void setVertices(std::vector<uint8_t>&&, std::size_t, gfx::AttributeDataType) override;
const gfx::UniformBufferArray& getUniformBuffers() const override;
gfx::UniformBufferArray& mutableUniformBuffers() override;
void setEnableColor(bool value) override;
void setColorMode(const gfx::ColorMode& value) override;
void setEnableDepth(bool value) override;
void setDepthType(gfx::DepthMaskType value) override;
void setDepthModeFor3D(const gfx::DepthMode& value);
void setStencilModeFor3D(const gfx::StencilMode& value);
void setLineWidth(int32_t value) override;
void setCullFaceMode(const gfx::CullFaceMode&) override;
protected:
void buildVulkanInputBindings() noexcept;
bool bindAttributes(CommandEncoder&) const noexcept;
bool bindDescriptors(CommandEncoder&) const noexcept;
void uploadTextures(UploadPass&) const noexcept;
class Impl;
const std::unique_ptr<Impl> impl;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,28 @@
#pragma once
#include <mbgl/gfx/drawable_builder.hpp>
namespace mbgl {
namespace vulkan {
/**
Base class for Vulkan-specific drawable builders.
*/
class DrawableBuilder final : public gfx::DrawableBuilder {
public:
DrawableBuilder(std::string name_)
: gfx::DrawableBuilder(std::move(name_)) {}
~DrawableBuilder() override = default;
using DrawSegment = gfx::Drawable::DrawSegment;
std::unique_ptr<DrawSegment> createSegment(gfx::DrawMode, SegmentBase&&) override;
protected:
gfx::UniqueDrawable createDrawable() const override;
/// Setup the SDK-specific aspects after all the values are present
void init() override;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,28 @@
#pragma once
#include <mbgl/gfx/index_buffer.hpp>
#include <mbgl/vulkan/buffer_resource.hpp>
namespace mbgl {
namespace vulkan {
class IndexBufferResource : public gfx::IndexBufferResource {
public:
IndexBufferResource() noexcept = delete;
IndexBufferResource(BufferResource&&) noexcept;
IndexBufferResource(IndexBufferResource&& other) noexcept
: buffer(std::move(other.buffer)) {}
~IndexBufferResource() noexcept override;
std::size_t getSizeInBytes() const noexcept { return buffer.getSizeInBytes(); }
const void* contents() const noexcept { return buffer.contents(); }
BufferResource& get() noexcept { return buffer; }
const BufferResource& get() const noexcept { return buffer; }
protected:
BufferResource buffer;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,37 @@
#pragma once
#include <mbgl/renderer/layer_group.hpp>
#include <mbgl/vulkan/uniform_buffer.hpp>
namespace mbgl {
class PaintParameters;
namespace vulkan {
class RenderPass;
/**
A layer group for non-tile-based drawables
*/
class LayerGroup : public mbgl::LayerGroup {
public:
LayerGroup(int32_t layerIndex, std::size_t initialCapacity, std::string name);
~LayerGroup() override {}
void upload(gfx::UploadPass&) override;
void render(RenderOrchestrator&, PaintParameters&) override;
const gfx::UniformBufferArray& getUniformBuffers() const override { return uniformBuffers; };
gfx::UniformBufferArray& mutableUniformBuffers() override { return uniformBuffers; };
void bindUniformBuffers(RenderPass&) const noexcept;
void unbindUniformBuffers(RenderPass&) const noexcept {}
protected:
UniformBufferArray uniformBuffers;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,23 @@
#pragma once
#include <mbgl/gfx/offscreen_texture.hpp>
#include <mbgl/gfx/types.hpp>
namespace mbgl {
namespace vulkan {
class Context;
class Texture2D;
class OffscreenTexture final : public gfx::OffscreenTexture {
public:
OffscreenTexture(Context&, Size size, gfx::TextureChannelDataType type, bool depth, bool stencil);
bool isRenderable() override;
PremultipliedImage readStillImage() override;
const gfx::Texture2DPtr& getTexture() override;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,93 @@
#pragma once
#include <mbgl/vulkan/renderer_backend.hpp>
#include <mbgl/gfx/draw_mode.hpp>
#include <mbgl/gfx/color_mode.hpp>
#include <mbgl/gfx/depth_mode.hpp>
#include <mbgl/gfx/stencil_mode.hpp>
namespace mbgl {
namespace vulkan {
class PipelineInfo final {
public:
PipelineInfo() noexcept = default;
~PipelineInfo() noexcept = default;
// used to select the pipeline layout
bool usePushConstants = false;
vk::PrimitiveTopology topology = vk::PrimitiveTopology::eTriangleList;
vk::CullModeFlagBits cullMode = vk::CullModeFlagBits::eNone;
vk::FrontFace frontFace = vk::FrontFace::eClockwise;
vk::PolygonMode polygonMode = vk::PolygonMode::eFill;
bool colorBlend = true;
vk::BlendOp colorBlendFunction = vk::BlendOp::eAdd;
vk::BlendFactor srcBlendFactor = vk::BlendFactor::eOne;
vk::BlendFactor dstBlendFactor = vk::BlendFactor::eZero;
vk::ColorComponentFlags colorMask = vk::FlagTraits<vk::ColorComponentFlagBits>::allFlags;
bool depthTest = false;
bool depthWrite = true;
vk::CompareOp depthFunction = vk::CompareOp::eAlways;
bool stencilTest = false;
vk::CompareOp stencilFunction = vk::CompareOp::eNever;
vk::StencilOp stencilPass = vk::StencilOp::eKeep;
vk::StencilOp stencilFail = vk::StencilOp::eKeep;
vk::StencilOp stencilDepthFail = vk::StencilOp::eKeep;
bool wideLines = false;
// external values (used in hash)
vk::RenderPass renderPass{};
vk::Extent2D viewExtent{};
// dynamic values (not part of the pipeline/ignored in hash)
struct {
std::optional<std::array<float, 4>> blendConstants;
uint32_t stencilWriteMask = 0;
uint32_t stencilCompareMask = 0;
uint32_t stencilRef = 0;
float lineWidth = 1.0f;
} dynamicValues;
std::vector<vk::VertexInputBindingDescription> inputBindings;
std::vector<vk::VertexInputAttributeDescription> inputAttributes;
public:
static vk::Format vulkanFormat(const gfx::AttributeDataType& value);
static vk::PrimitiveTopology vulkanPrimitiveTopology(const gfx::DrawModeType& value);
static vk::CullModeFlagBits vulkanCullMode(const gfx::CullFaceSideType& value);
static vk::FrontFace vulkanFrontFace(const gfx::CullFaceWindingType& value);
static vk::BlendOp vulkanBlendOp(const gfx::ColorBlendEquationType& value);
static vk::BlendFactor vulkanBlendFactor(const gfx::ColorBlendFactorType& value);
static vk::CompareOp vulkanCompareOp(const gfx::DepthFunctionType& value);
static vk::CompareOp vulkanCompareOp(const gfx::StencilFunctionType& value);
static vk::StencilOp vulkanStencilOp(const gfx::StencilOpType& value);
void setCullMode(const gfx::CullFaceMode& value);
void setDrawMode(const gfx::DrawModeType& value);
void setDrawMode(const gfx::DrawMode& value);
void setColorBlend(const gfx::ColorMode& value);
void setColorBlendFunction(const gfx::ColorMode::BlendFunction& value);
void setDepthWrite(const gfx::DepthMaskType& value);
void setDepthMode(const gfx::DepthMode& value);
void setStencilMode(const gfx::StencilMode& value);
void setRenderable(const gfx::Renderable& value);
void setLineWidth(float value);
bool usesBlendConstants() const;
void updateVertexInputHash();
std::size_t hash() const;
void setDynamicValues(const vk::UniqueCommandBuffer& buffer) const;
std::vector<vk::DynamicState> getDynamicStates() const;
protected:
std::size_t vertexInputHash{0};
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,41 @@
#pragma once
#include <mbgl/gfx/render_pass.hpp>
#include <memory>
#include <optional>
namespace mbgl {
namespace vulkan {
class BufferResource;
class CommandEncoder;
class Context;
class RenderPass final : public gfx::RenderPass {
public:
RenderPass(CommandEncoder&, const char* name, const gfx::RenderPassDescriptor&);
~RenderPass() override;
vulkan::CommandEncoder& getEncoder() { return commandEncoder; }
const gfx::RenderPassDescriptor& getDescriptor() { return descriptor; }
void endEncoding();
void clearStencil(uint32_t value = 0) const;
void addDebugSignpost(const char* name) override;
void bindVertex(const BufferResource&, std::size_t offset, std::size_t index, std::size_t size = 0);
void bindFragment(const BufferResource&, std::size_t offset, std::size_t index, std::size_t size = 0);
private:
void pushDebugGroup(const char* name) override;
void popDebugGroup() override;
private:
gfx::RenderPassDescriptor descriptor;
vulkan::CommandEncoder& commandEncoder;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,76 @@
#pragma once
#include <mbgl/gfx/renderable.hpp>
#include <mbgl/vulkan/renderer_backend.hpp>
#include <mbgl/vulkan/texture2d.hpp>
namespace mbgl {
namespace vulkan {
class Context;
class RenderableResource : public gfx::RenderableResource {
protected:
explicit RenderableResource(RendererBackend& backend_)
: backend(backend_) {}
~RenderableResource() override = default;
public:
const vk::Extent2D& getExtent() const { return extent; }
const vk::UniqueRenderPass& getRenderPass() const { return renderPass; }
virtual const vk::UniqueFramebuffer& getFramebuffer() const = 0;
protected:
RendererBackend& backend;
vk::Extent2D extent;
vk::UniqueRenderPass renderPass;
};
class SurfaceRenderableResource : public RenderableResource {
protected:
explicit SurfaceRenderableResource(RendererBackend& backend_)
: RenderableResource(backend_) {}
~SurfaceRenderableResource() override;
void initColor(uint32_t w, uint32_t h);
void initSwapchain(uint32_t w, uint32_t h);
void initDepthStencil();
public:
virtual void createPlatformSurface() = 0;
virtual std::vector<const char*> getDeviceExtensions() { return {}; }
const vk::UniqueSurfaceKHR& getPlatformSurface() const { return surface; }
const vk::UniqueSwapchainKHR& getSwapchain() const { return swapchain; }
const vk::UniqueFramebuffer& getFramebuffer() const override;
uint32_t getImageCount() const { return static_cast<uint32_t>(swapchainFramebuffers.size()); };
uint32_t getAcquiredImageIndex() const { return acquiredImageIndex; };
void setAcquiredImageIndex(uint32_t index) { acquiredImageIndex = index; };
const vk::Image getAcquiredImage() const;
void init(uint32_t w, uint32_t h);
void recreateSwapchain();
protected:
vk::UniqueSurfaceKHR surface;
vk::UniqueSwapchainKHR swapchain;
uint32_t acquiredImageIndex{0};
// optional color textures when no surface is available
std::vector<UniqueImageAllocation> colorAllocations;
std::vector<vk::Image> swapchainImages;
std::vector<vk::UniqueImageView> swapchainImageViews;
std::vector<vk::UniqueFramebuffer> swapchainFramebuffers;
vk::Format colorFormat{vk::Format::eUndefined};
UniqueImageAllocation depthAllocation;
vk::Format depthFormat{vk::Format::eUndefined};
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,116 @@
#pragma once
#include <mbgl/gfx/renderer_backend.hpp>
#include <mbgl/gfx/context.hpp>
#ifdef _WIN32
#define VK_USE_PLATFORM_WIN32_KHR
#elif defined(__ANDROID__)
#define VK_USE_PLATFORM_ANDROID_KHR
#endif
#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
#include <vulkan/vulkan.hpp>
#define VMA_VULKAN_VERSION 1000000
#define VMA_STATIC_VULKAN_FUNCTIONS 0
#define VMA_DYNAMIC_VULKAN_FUNCTIONS 0
#include "vk_mem_alloc.h"
#ifndef NDEBUG
#define ENABLE_VULKAN_VALIDATION
// #define ENABLE_VULKAN_GPU_ASSISTED_VALIDATION
// #define ENABLE_VMA_DEBUG
#endif
namespace mbgl {
class ProgramParameters;
namespace vulkan {
class RendererBackend : public gfx::RendererBackend {
public:
RendererBackend(gfx::ContextMode);
~RendererBackend() override;
/// One-time shader initialization
void initShaders(gfx::ShaderRegistry&, const ProgramParameters& programParameters) override;
void init();
const vk::UniqueInstance& getInstance() const { return instance; }
const vk::PhysicalDevice& getPhysicalDevice() const { return physicalDevice; }
const vk::UniqueDevice& getDevice() const { return device; }
const vk::UniqueCommandPool& getCommandPool() const { return commandPool; }
const vk::Queue& getGraphicsQueue() const { return graphicsQueue; }
const vk::Queue& getPresentQueue() const { return presentQueue; }
uint32_t getMaxFrames() const { return maxFrames; }
const VmaAllocator& getAllocator() const { return allocator; }
const vk::PhysicalDeviceProperties& getDeviceProperties() const { return physicalDeviceProperties; }
int32_t getGraphicsQueueIndex() const { return graphicsQueueIndex; }
int32_t getPresentQueueIndex() const { return presentQueueIndex; }
template <typename T, typename = typename std::enable_if<vk::isVulkanHandleType<T>::value>>
void setDebugName([[maybe_unused]] const T& object, [[maybe_unused]] const std::string& name) const {
#ifdef ENABLE_VULKAN_VALIDATION
if (!debugUtilsEnabled) return;
const uint64_t handle = reinterpret_cast<uint64_t>(static_cast<typename T::CType>(object));
device->setDebugUtilsObjectNameEXT(vk::DebugUtilsObjectNameInfoEXT()
.setObjectType(object.objectType)
.setObjectHandle(handle)
.setPObjectName(name.c_str()));
#endif
}
void beginDebugLabel(const vk::CommandBuffer& buffer, const char* name, const std::array<float, 4>& color) const;
void endDebugLabel(const vk::CommandBuffer& buffer) const;
void insertDebugLabel(const vk::CommandBuffer& buffer, const char* name) const;
void startFrameCapture();
void endFrameCapture();
protected:
std::unique_ptr<gfx::Context> createContext() override;
virtual std::vector<const char*> getLayers();
virtual std::vector<const char*> getInstanceExtensions();
virtual std::vector<const char*> getDeviceExtensions();
std::vector<const char*> getDebugExtensions();
void initInstance();
void initDebug();
void initSurface();
void initDevice();
void initAllocator();
void initSwapchain();
void initCommandPool();
void initFrameCapture();
void destroyResources();
protected:
vk::DynamicLoader dynamicLoader;
vk::UniqueInstance instance;
vk::UniqueDebugUtilsMessengerEXT debugUtilsCallback;
vk::UniqueDebugReportCallbackEXT debugReportCallback;
vk::PhysicalDevice physicalDevice;
vk::UniqueDevice device;
vk::PhysicalDeviceProperties physicalDeviceProperties;
int32_t graphicsQueueIndex = -1;
int32_t presentQueueIndex = -1;
vk::Queue graphicsQueue;
vk::Queue presentQueue;
vk::UniqueCommandPool commandPool;
uint32_t maxFrames = 1;
VmaAllocator allocator;
bool debugUtilsEnabled{false};
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,128 @@
#pragma once
#include <mbgl/gfx/texture2d.hpp>
#include <mbgl/util/image.hpp>
#include <mbgl/vulkan/renderer_backend.hpp>
#include <memory>
namespace mbgl {
namespace vulkan {
class Context;
class RenderPass;
struct ImageAllocation {
const VmaAllocator& allocator;
VmaAllocation allocation{};
VkImage image{};
vk::UniqueImageView imageView{};
ImageAllocation() = delete;
ImageAllocation(ImageAllocation&) = delete;
ImageAllocation& operator=(const ImageAllocation& other) = delete;
ImageAllocation(const VmaAllocator& allocator_)
: allocator(allocator_) {}
ImageAllocation(ImageAllocation&& other) noexcept
: allocator(other.allocator),
allocation(other.allocation),
image(other.image),
imageView(std::move(other.imageView)) {
other.image = nullptr;
other.allocation = nullptr;
}
~ImageAllocation() { destroy(); }
bool create(const VmaAllocationCreateInfo& allocInfo, const vk::ImageCreateInfo& imageInfo);
void destroy();
void setName(const std::string& name) const;
};
using UniqueImageAllocation = std::unique_ptr<ImageAllocation>;
using SharedImageAllocation = std::shared_ptr<ImageAllocation>;
enum class Texture2DUsage {
ShaderInput,
Attachment,
Read,
};
class Texture2D : public gfx::Texture2D {
public:
Texture2D(Context& context_);
~Texture2D() override;
gfx::Texture2D& setSamplerConfiguration(const SamplerState&) noexcept override;
gfx::Texture2D& setFormat(gfx::TexturePixelType, gfx::TextureChannelDataType) noexcept override;
gfx::Texture2D& setSize(Size size_) noexcept override;
gfx::Texture2D& setImage(std::shared_ptr<PremultipliedImage>) noexcept override;
gfx::Texture2D& setUsage(Texture2DUsage) noexcept;
Size getSize() const noexcept override { return size; }
size_t getDataSize() const noexcept override;
size_t getPixelStride() const noexcept override;
size_t numChannels() const noexcept override;
void create() noexcept override;
void upload() noexcept override;
void upload(const void* pixelData, const Size& size_) noexcept override;
void uploadSubRegion(const void* pixelData, const Size& size, uint16_t xOffset, uint16_t yOffset) noexcept override;
void uploadSubRegion(const void* pixelData,
const Size& size,
uint16_t xOffset,
uint16_t yOffset,
const vk::UniqueCommandBuffer& buffer) noexcept;
bool needsUpload() const noexcept override { return !!imageData; };
vk::Format getVulkanFormat() const { return vulkanFormat(pixelFormat, channelType); }
const vk::ImageLayout& getVulkanImageLayout() const { return imageLayout; }
const vk::UniqueImageView& getVulkanImageView() const { return imageAllocation->imageView; }
const vk::Sampler& getVulkanSampler();
void copyImage(vk::Image image);
std::shared_ptr<PremultipliedImage> readImage();
private:
static vk::Format vulkanFormat(const gfx::TexturePixelType, const gfx::TextureChannelDataType);
static vk::Filter vulkanFilter(const gfx::TextureFilterType);
static vk::SamplerAddressMode vulkanAddressMode(const gfx::TextureWrapType);
void createTexture();
void createSampler();
void destroyTexture();
void destroySampler();
void transitionToTransferLayout(const vk::UniqueCommandBuffer&);
void transitionToShaderReadLayout(const vk::UniqueCommandBuffer&);
void transitionToGeneralLayout(const vk::UniqueCommandBuffer&);
private:
Context& context;
Size size{0, 0};
gfx::TexturePixelType pixelFormat{gfx::TexturePixelType::RGBA};
gfx::TextureChannelDataType channelType{gfx::TextureChannelDataType::UnsignedByte};
SamplerState samplerState{};
std::shared_ptr<PremultipliedImage> imageData{nullptr};
bool textureDirty{true};
bool samplerStateDirty{true};
SharedImageAllocation imageAllocation;
vk::ImageLayout imageLayout{vk::ImageLayout::eUndefined};
vk::Sampler sampler{};
Texture2DUsage textureUsage{Texture2DUsage::ShaderInput};
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,39 @@
#pragma once
#include <mbgl/vulkan/uniform_buffer.hpp>
#include <mbgl/renderer/layer_group.hpp>
#include <optional>
namespace mbgl {
class PaintParameters;
namespace vulkan {
class RenderPass;
/**
A layer group for tile-based drawables
*/
class TileLayerGroup : public mbgl::TileLayerGroup {
public:
TileLayerGroup(int32_t layerIndex, std::size_t initialCapacity, std::string name);
~TileLayerGroup() override {}
void upload(gfx::UploadPass&) override;
void render(RenderOrchestrator&, PaintParameters&) override;
const gfx::UniformBufferArray& getUniformBuffers() const override { return uniformBuffers; };
gfx::UniformBufferArray& mutableUniformBuffers() override { return uniformBuffers; };
void bindUniformBuffers(RenderPass&) const noexcept;
void unbindUniformBuffers(RenderPass&) const noexcept {}
protected:
UniformBufferArray uniformBuffers;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,59 @@
#pragma once
#include <mbgl/gfx/uniform_block.hpp>
namespace mbgl {
namespace vulkan {
class UniformBlock final : public gfx::UniformBlock {
public:
UniformBlock(int index_, std::size_t size_)
: gfx::UniformBlock(index_, size_) {}
UniformBlock(const UniformBlock& other)
: gfx::UniformBlock(other) {}
UniformBlock(UniformBlock&& other)
: gfx::UniformBlock(std::move(other)) {}
~UniformBlock() override = default;
void bindBuffer(const gfx::UniformBuffer&) override {}
void unbindBuffer() override {}
bool getBindVertex() const { return bindVertex; }
void setBindVertex(bool value) { bindVertex = value; }
bool getBindFragment() const { return bindFragment; }
void setBindFragment(bool value) { bindFragment = value; }
protected:
bool bindVertex = false;
bool bindFragment = false;
};
/// Stores a collection of uniform blocks by name
class UniformBlockArray final : public gfx::UniformBlockArray {
public:
UniformBlockArray() = default;
UniformBlockArray(UniformBlockArray&& other)
: gfx::UniformBlockArray(std::move(other)) {}
UniformBlockArray(const UniformBlockArray&) = delete;
UniformBlockArray& operator=(UniformBlockArray&& other) {
gfx::UniformBlockArray::operator=(std::move(other));
return *this;
}
UniformBlockArray& operator=(const UniformBlockArray& other) {
gfx::UniformBlockArray::operator=(other);
return *this;
}
private:
std::unique_ptr<gfx::UniformBlock> create(int index, std::size_t size) override {
return std::make_unique<UniformBlock>(index, size);
}
std::unique_ptr<gfx::UniformBlock> copy(const gfx::UniformBlock& uniformBlocks) override {
return std::make_unique<UniformBlock>(static_cast<const UniformBlock&>(uniformBlocks));
}
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,50 @@
#pragma once
#include <mbgl/gfx/uniform_buffer.hpp>
#include <mbgl/vulkan/buffer_resource.hpp>
namespace mbgl {
namespace vulkan {
class UniformBuffer final : public gfx::UniformBuffer {
public:
UniformBuffer(BufferResource&&);
UniformBuffer(const UniformBuffer&) = delete;
UniformBuffer(UniformBuffer&&);
~UniformBuffer() override;
const BufferResource& getBufferResource() const { return buffer; }
UniformBuffer clone() const { return {buffer.clone()}; }
void update(const void* data, std::size_t size_) override;
protected:
BufferResource buffer;
};
/// Stores a collection of uniform buffers by name
class UniformBufferArray final : public gfx::UniformBufferArray {
public:
UniformBufferArray() = default;
UniformBufferArray(UniformBufferArray&& other)
: gfx::UniformBufferArray(std::move(other)) {}
UniformBufferArray(const UniformBufferArray&) = delete;
UniformBufferArray& operator=(UniformBufferArray&& other) {
gfx::UniformBufferArray::operator=(std::move(other));
return *this;
}
UniformBufferArray& operator=(const UniformBufferArray& other) {
gfx::UniformBufferArray::operator=(other);
return *this;
}
private:
gfx::UniqueUniformBuffer copy(const gfx::UniformBuffer& buffer) override {
return std::make_unique<UniformBuffer>(static_cast<const UniformBuffer&>(buffer).clone());
}
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,93 @@
#pragma once
#include <mbgl/gfx/index_buffer.hpp>
#include <mbgl/gfx/renderbuffer.hpp>
#include <mbgl/gfx/texture.hpp>
#include <mbgl/gfx/upload_pass.hpp>
#include <mbgl/gfx/vertex_buffer.hpp>
#include <vector>
namespace mbgl {
namespace gfx {
class CommandEncoder;
class Renderable;
class VertexVectorBase;
using VertexVectorBasePtr = std::shared_ptr<VertexVectorBase>;
} // namespace gfx
namespace vulkan {
class BufferResource;
class CommandEncoder;
class Context;
class VertexArray;
class Texture2D;
class RenderbufferResource : public gfx::RenderbufferResource {
public:
RenderbufferResource() = default;
};
class UploadPass final : public gfx::UploadPass {
public:
UploadPass(gfx::Renderable&, CommandEncoder&, const char* name);
~UploadPass() override;
gfx::Context& getContext() override;
const gfx::Context& getContext() const override;
std::unique_ptr<gfx::VertexBufferResource> createVertexBufferResource(const void* data,
std::size_t size,
gfx::BufferUsageType,
bool persistent) override;
void updateVertexBufferResource(gfx::VertexBufferResource&, const void* data, std::size_t size) override;
std::unique_ptr<gfx::IndexBufferResource> createIndexBufferResource(const void* data,
std::size_t size,
gfx::BufferUsageType,
bool persistent) override;
void updateIndexBufferResource(gfx::IndexBufferResource&, const void* data, std::size_t size) override;
const gfx::UniqueVertexBufferResource& getBuffer(const gfx::VertexVectorBasePtr&, gfx::BufferUsageType);
gfx::AttributeBindingArray buildAttributeBindings(
const std::size_t vertexCount,
const gfx::AttributeDataType vertexType,
const std::size_t vertexAttributeIndex,
const std::vector<std::uint8_t>& vertexData,
const gfx::VertexAttributeArray& defaults,
const gfx::VertexAttributeArray& overrides,
gfx::BufferUsageType,
/*out*/ std::vector<std::unique_ptr<gfx::VertexBufferResource>>& outBuffers) override;
std::unique_ptr<gfx::TextureResource> createTextureResource(Size,
const void* data,
gfx::TexturePixelType,
gfx::TextureChannelDataType) override;
void updateTextureResource(
gfx::TextureResource&, Size, const void* data, gfx::TexturePixelType, gfx::TextureChannelDataType) override;
void updateTextureResourceSub(gfx::TextureResource&,
uint16_t xOffset,
uint16_t yOffset,
Size,
const void* data,
gfx::TexturePixelType,
gfx::TextureChannelDataType) override;
private:
void pushDebugGroup(const char* name) override;
void popDebugGroup() override;
void endEncoding();
private:
CommandEncoder& commandEncoder;
std::vector<gfx::DebugGroup<gfx::UploadPass>> debugGroups;
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,52 @@
#pragma once
#include <mbgl/gfx/types.hpp>
#include <mbgl/gfx/vertex_attribute.hpp>
namespace mbgl {
namespace gfx {
class VertexBufferResource;
} // namespace gfx
namespace vulkan {
class VertexAttributeArray;
class UploadPass;
class VertexAttribute final : public gfx::VertexAttribute {
public:
VertexAttribute(int index_, gfx::AttributeDataType dataType_, std::size_t count_)
: gfx::VertexAttribute(index_, dataType_, count_) {}
VertexAttribute(VertexAttribute&& other)
: gfx::VertexAttribute(std::move(other)) {}
VertexAttribute(const VertexAttribute& other) = delete;
~VertexAttribute() override = default;
static const gfx::UniqueVertexBufferResource& getBuffer(gfx::VertexAttribute&,
UploadPass&,
const gfx::BufferUsageType);
};
/// Stores a collection of vertex attributes by name
class VertexAttributeArray final : public gfx::VertexAttributeArray {
public:
VertexAttributeArray() = default;
VertexAttributeArray(VertexAttributeArray&& other)
: gfx::VertexAttributeArray(std::move(other)) {}
VertexAttributeArray& operator=(VertexAttributeArray&& other) {
gfx::VertexAttributeArray::operator=(std::move(other));
return *this;
}
VertexAttributeArray& operator=(const VertexAttributeArray& other) = delete;
/// Indicates whether any values have changed
bool isDirty() const override;
private:
gfx::UniqueVertexAttribute create(int index, gfx::AttributeDataType dataType, std::size_t count) const override {
return std::make_unique<VertexAttribute>(index, dataType, count);
}
};
} // namespace vulkan
} // namespace mbgl

View File

@@ -0,0 +1,32 @@
#pragma once
#include <mbgl/vulkan/buffer_resource.hpp>
#include <memory>
namespace mbgl {
namespace vulkan {
class VertexBufferResource : public gfx::VertexBufferResource {
public:
VertexBufferResource() noexcept = delete;
VertexBufferResource(BufferResource&& buffer_) noexcept
: buffer(std::move(buffer_)) {}
VertexBufferResource(VertexBufferResource&& other) noexcept
: buffer(std::move(other.buffer)) {}
~VertexBufferResource() noexcept override = default;
std::size_t getSizeInBytes() const noexcept { return buffer.getSizeInBytes(); }
const void* contents() const noexcept { return buffer.contents(); }
BufferResource& get() noexcept { return buffer; }
const BufferResource& get() const noexcept { return buffer; }
protected:
BufferResource buffer;
};
using UniqueVertexBufferResource = std::unique_ptr<VertexBufferResource>;
} // namespace vulkan
} // namespace mbgl