core: Update Hillshade Algorithms and add Color-Relief Layer support (#3965)

This commit is contained in:
Andrew Calcutt
2026-02-25 20:50:06 -05:00
committed by GitHub
parent 9682e09ae4
commit 369af13ead
187 changed files with 8804 additions and 2352 deletions

View File

@@ -0,0 +1,26 @@
#pragma once
#include <mbgl/gfx/drawable_data.hpp>
#include <mbgl/shaders/color_relief_layer_ubo.hpp>
namespace mbgl {
namespace gfx {
/**
* @brief Drawable data for color-relief layer
*
* Stores per-tile DEM properties that are set during drawable creation
* and read by the tweaker during rendering. This is necessary because
* the DEM unpack vector and stride are only available from the bucket
* during drawable creation.
*/
class ColorReliefDrawableData : public DrawableData {
public:
explicit ColorReliefDrawableData(const shaders::ColorReliefTilePropsUBO& props)
: tileProps(props) {}
shaders::ColorReliefTilePropsUBO tileProps;
};
} // namespace gfx
} // namespace mbgl

View File

@@ -137,6 +137,7 @@ void RendererBackend::initShaders(gfx::ShaderRegistry& shaders, const ProgramPar
shaders::BuiltIn::HeatmapTextureShader,
shaders::BuiltIn::HillshadePrepareShader,
shaders::BuiltIn::HillshadeShader,
shaders::BuiltIn::ColorReliefShader,
shaders::BuiltIn::LineShader,
shaders::BuiltIn::LineGradientShader,
shaders::BuiltIn::LinePatternShader,

View File

@@ -44,6 +44,8 @@ size_t Texture2DDesc::channelCount() const {
size_t Texture2DDesc::channelStorageSize() const {
switch (channelType) {
case gfx::TextureChannelDataType::Float:
return 4;
case gfx::TextureChannelDataType::HalfFloat:
return 2;
case gfx::TextureChannelDataType::UnsignedByte:

View File

@@ -52,6 +52,8 @@ size_t Texture2D::getPixelStride() const noexcept {
return 1 * numChannels();
case gfx::TextureChannelDataType::HalfFloat:
return 2 * numChannels();
case gfx::TextureChannelDataType::Float:
return 4 * numChannels();
default:
return 0;
}

View File

@@ -0,0 +1,27 @@
#include <mbgl/layermanager/color_relief_layer_factory.hpp>
#include <mbgl/renderer/layers/render_color_relief_layer.hpp>
#include <mbgl/style/layers/color_relief_layer.hpp>
#include <mbgl/style/layers/color_relief_layer_impl.hpp>
namespace mbgl {
const style::LayerTypeInfo* ColorReliefLayerFactory::getTypeInfo() const noexcept {
return style::ColorReliefLayer::Impl::staticTypeInfo();
}
std::unique_ptr<style::Layer> ColorReliefLayerFactory::createLayer(
const std::string& id, const style::conversion::Convertible& value) noexcept {
const auto source = getSource(value);
if (!source) {
return nullptr;
}
return std::unique_ptr<style::Layer>(new (std::nothrow) style::ColorReliefLayer(id, *source));
}
std::unique_ptr<RenderLayer> ColorReliefLayerFactory::createRenderLayer(Immutable<style::Layer::Impl> impl) noexcept {
assert(impl->getTypeInfo() == getTypeInfo());
return std::make_unique<RenderColorReliefLayer>(staticImmutableCast<style::ColorReliefLayer::Impl>(impl));
}
} // namespace mbgl

View File

@@ -15,6 +15,7 @@
#include <mbgl/shaders/mtl/circle.hpp>
#include <mbgl/shaders/mtl/clipping_mask.hpp>
#include <mbgl/shaders/mtl/collision.hpp>
#include <mbgl/shaders/mtl/color_relief.hpp>
#include <mbgl/shaders/mtl/custom_geometry.hpp>
#include <mbgl/shaders/mtl/custom_symbol_icon.hpp>
#include <mbgl/shaders/mtl/debug.hpp>
@@ -121,6 +122,7 @@ void RendererBackend::initShaders(gfx::ShaderRegistry& shaders, const ProgramPar
shaders::BuiltIn::HeatmapTextureShader,
shaders::BuiltIn::HillshadeShader,
shaders::BuiltIn::HillshadePrepareShader,
shaders::BuiltIn::ColorReliefShader,
shaders::BuiltIn::LineShader,
shaders::BuiltIn::LineGradientShader,
shaders::BuiltIn::LineSDFShader,

View File

@@ -3,6 +3,7 @@
#include <mbgl/programs/circle_program.hpp>
#include <mbgl/programs/heatmap_program.hpp>
#include <mbgl/programs/hillshade_program.hpp>
#include <mbgl/programs/color_relief_program.hpp>
#include <mbgl/programs/fill_extrusion_program.hpp>
#include <mbgl/programs/fill_program.hpp>
#include <mbgl/programs/line_program.hpp>
@@ -50,6 +51,7 @@ void Programs::registerWith(gfx::ShaderRegistry& registry) {
HeatmapTextureProgram,
HillshadeProgram,
HillshadePrepareProgram,
ColorReliefProgram,
FillProgram,
FillPatternProgram,
FillOutlineProgram,

View File

@@ -0,0 +1,93 @@
#include <mbgl/renderer/layers/color_relief_layer_tweaker.hpp>
#include <mbgl/gfx/context.hpp>
#include <mbgl/gfx/drawable.hpp>
#include <mbgl/gfx/color_relief_drawable_data.hpp>
#include <mbgl/renderer/layer_group.hpp>
#include <mbgl/renderer/paint_parameters.hpp>
#include <mbgl/shaders/color_relief_layer_ubo.hpp>
#include <mbgl/style/layers/color_relief_layer_properties.hpp>
#include <mbgl/util/convert.hpp>
namespace mbgl {
using namespace shaders;
void ColorReliefLayerTweaker::execute(LayerGroupBase& layerGroup, const PaintParameters& parameters) {
auto& context = parameters.context;
const auto& props = static_cast<const style::ColorReliefLayerProperties&>(*evaluatedProperties);
const auto& evaluated = props.evaluated;
if (layerGroup.empty()) {
return;
}
// Update evaluated properties UBO
ColorReliefEvaluatedPropsUBO evaluatedPropsUBO;
evaluatedPropsUBO.opacity = evaluated.get<style::ColorReliefOpacity>();
evaluatedPropsUBO.pad_eval0 = 0.0f;
evaluatedPropsUBO.pad_eval1 = 0.0f;
evaluatedPropsUBO.pad_eval2 = 0.0f;
context.emplaceOrUpdateUniformBuffer(evaluatedPropsUniformBuffer, &evaluatedPropsUBO);
auto& layerUniforms = layerGroup.mutableUniformBuffers();
layerUniforms.set(idColorReliefEvaluatedPropsUBO, evaluatedPropsUniformBuffer);
#if MLN_UBO_CONSOLIDATION
int i = 0;
std::vector<ColorReliefDrawableUBO> drawableUBOVector(layerGroup.getDrawableCount());
std::vector<ColorReliefTilePropsUBO> tilePropsUBOVector(layerGroup.getDrawableCount());
#endif
visitLayerGroupDrawables(layerGroup, [&](gfx::Drawable& drawable) {
if (!drawable.getTileID()) {
return;
}
const UnwrappedTileID tileID = drawable.getTileID()->toUnwrapped();
#if MLN_UBO_CONSOLIDATION
drawableUBOVector[i].matrix = util::cast<float>(parameters.matrixForTile(tileID));
// Get tile props from drawable data (set during creation)
if (const auto& drawableData = drawable.getData()) {
if (const auto* data = static_cast<const gfx::ColorReliefDrawableData*>(drawableData.get())) {
tilePropsUBOVector[i] = data->tileProps;
}
}
drawable.setUBOIndex(i++);
#else
ColorReliefDrawableUBO drawableUBO;
drawableUBO.matrix = util::cast<float>(parameters.matrixForTile(tileID));
auto& drawableUniforms = drawable.mutableUniformBuffers();
drawableUniforms.createOrUpdate(idColorReliefDrawableUBO, &drawableUBO, context);
// Tile props UBO is set during drawable creation, doesn't change per frame
#endif
});
#if MLN_UBO_CONSOLIDATION
const size_t drawableUBOVectorSize = sizeof(ColorReliefDrawableUBO) * drawableUBOVector.size();
if (!drawableUniformBuffer || drawableUniformBuffer->getSize() < drawableUBOVectorSize) {
drawableUniformBuffer = context.createUniformBuffer(
drawableUBOVector.data(), drawableUBOVectorSize, false, true);
} else {
drawableUniformBuffer->update(drawableUBOVector.data(), drawableUBOVectorSize);
}
const size_t tilePropsUBOVectorSize = sizeof(ColorReliefTilePropsUBO) * tilePropsUBOVector.size();
if (!tilePropsUniformBuffer || tilePropsUniformBuffer->getSize() < tilePropsUBOVectorSize) {
tilePropsUniformBuffer = context.createUniformBuffer(
tilePropsUBOVector.data(), tilePropsUBOVectorSize, false, true);
} else {
tilePropsUniformBuffer->update(tilePropsUBOVector.data(), tilePropsUBOVectorSize);
}
layerUniforms.set(idColorReliefDrawableUBO, drawableUniformBuffer);
layerUniforms.set(idColorReliefTilePropsUBO, tilePropsUniformBuffer);
#endif
}
} // namespace mbgl

View File

@@ -0,0 +1,28 @@
#pragma once
#include <mbgl/renderer/layer_tweaker.hpp>
namespace mbgl {
/**
Color relief layer specific tweaker
*/
class ColorReliefLayerTweaker : public LayerTweaker {
public:
ColorReliefLayerTweaker(std::string id_, Immutable<style::LayerProperties> properties)
: LayerTweaker(std::move(id_), properties) {}
~ColorReliefLayerTweaker() override = default;
void execute(LayerGroupBase&, const PaintParameters&) override;
protected:
gfx::UniformBufferPtr evaluatedPropsUniformBuffer;
#if MLN_UBO_CONSOLIDATION
gfx::UniformBufferPtr drawableUniformBuffer;
gfx::UniformBufferPtr tilePropsUniformBuffer;
#endif
};
} // namespace mbgl

View File

@@ -8,6 +8,8 @@
#include <mbgl/shaders/hillshade_layer_ubo.hpp>
#include <mbgl/style/layers/hillshade_layer_properties.hpp>
#include <mbgl/util/convert.hpp>
#include <mbgl/math/angles.hpp>
#include <mbgl/util/geo.hpp>
namespace mbgl {
@@ -15,20 +17,113 @@ using namespace style;
using namespace shaders;
namespace {
// Structure to hold processed illumination properties
struct IlluminationProperties {
std::vector<float> directionRadians;
std::vector<float> altitudeRadians;
std::vector<Color> shadowColors;
std::vector<Color> highlightColors;
size_t numSources() const { return directionRadians.size(); }
};
// Convert style properties to illumination properties
IlluminationProperties getIlluminationProperties(const HillshadePaintProperties::PossiblyEvaluated& evaluated) {
IlluminationProperties props;
// Get the values from evaluated properties (these are now vectors)
std::vector<float> directions = evaluated.get<HillshadeIlluminationDirection>();
std::vector<float> altitudes = evaluated.get<HillshadeIlluminationAltitude>();
std::vector<Color> highlights = evaluated.get<HillshadeHighlightColor>();
std::vector<Color> shadows = evaluated.get<HillshadeShadowColor>();
// Find the maximum length to ensure all arrays are the same size
size_t maxLength = std::max({directions.size(), altitudes.size(), highlights.size(), shadows.size()});
// Ensure we don't exceed the maximum supported
maxLength = std::min(maxLength, static_cast<size_t>(MAX_ILLUMINATION_SOURCES));
// Pad shorter arrays by repeating the last element
auto padArray = [maxLength](auto& arr) {
if (arr.empty()) arr.push_back(typename std::decay<decltype(arr)>::type::value_type{});
while (arr.size() < maxLength) {
arr.push_back(arr.back());
}
};
padArray(directions);
padArray(altitudes);
padArray(highlights);
padArray(shadows);
// Convert degrees to radians
props.directionRadians.reserve(directions.size());
for (float deg : directions) {
props.directionRadians.push_back(util::deg2radf(deg));
}
props.altitudeRadians.reserve(altitudes.size());
for (float deg : altitudes) {
props.altitudeRadians.push_back(util::deg2radf(deg));
}
props.shadowColors = std::move(shadows);
props.highlightColors = std::move(highlights);
return props;
}
// Pack illumination properties into the UBO format
HillshadeEvaluatedPropsUBO packEvaluatedProps(const IlluminationProperties& illumination, const Color& accentColor) {
HillshadeEvaluatedPropsUBO ubo{};
// Pack accent color
ubo.accent = {accentColor.r, accentColor.g, accentColor.b, accentColor.a};
// Pack altitudes (up to 4)
for (size_t i = 0; i < illumination.altitudeRadians.size() && i < 4; ++i) {
ubo.altitudes[i] = illumination.altitudeRadians[i];
}
// Pack azimuths (up to 4)
for (size_t i = 0; i < illumination.directionRadians.size() && i < 4; ++i) {
ubo.azimuths[i] = illumination.directionRadians[i];
}
// Pack shadow colors (4 colors * 4 components = 16 floats)
for (size_t i = 0; i < illumination.shadowColors.size() && i < 4; ++i) {
const auto& color = illumination.shadowColors[i];
ubo.shadows[i * 4 + 0] = color.r;
ubo.shadows[i * 4 + 1] = color.g;
ubo.shadows[i * 4 + 2] = color.b;
ubo.shadows[i * 4 + 3] = color.a;
}
// Pack highlight colors (4 colors * 4 components = 16 floats)
for (size_t i = 0; i < illumination.highlightColors.size() && i < 4; ++i) {
const auto& color = illumination.highlightColors[i];
ubo.highlights[i * 4 + 0] = color.r;
ubo.highlights[i * 4 + 1] = color.g;
ubo.highlights[i * 4 + 2] = color.b;
ubo.highlights[i * 4 + 3] = color.a;
}
return ubo;
}
// Convert HillshadeMethodType enum to int for shader
int32_t methodToInt(HillshadeMethodType method) {
return static_cast<int32_t>(method);
}
// Calculate latitude range for tile
std::array<float, 2> getLatRange(const UnwrappedTileID& id) {
const LatLng latlng0 = LatLng(id);
const LatLng latlng1 = LatLng(UnwrappedTileID(id.canonical.z, id.canonical.x, id.canonical.y + 1));
return {{static_cast<float>(latlng0.latitude()), static_cast<float>(latlng1.latitude())}};
}
std::array<float, 2> getLight(const PaintParameters& parameters,
const HillshadePaintProperties::PossiblyEvaluated& evaluated) {
float azimuthal = util::deg2radf(evaluated.get<HillshadeIlluminationDirection>());
if (evaluated.get<HillshadeIlluminationAnchor>() == HillshadeIlluminationAnchorType::Viewport) {
azimuthal = azimuthal - static_cast<float>(parameters.state.getBearing());
}
return {{evaluated.get<HillshadeExaggeration>(), azimuthal}};
}
} // namespace
void HillshadeLayerTweaker::execute(LayerGroupBase& layerGroup, const PaintParameters& parameters) {
@@ -43,10 +138,21 @@ void HillshadeLayerTweaker::execute(LayerGroupBase& layerGroup, const PaintParam
const auto debugGroup = parameters.encoder->createDebugGroup(label.c_str());
#endif
// Get illumination properties
auto illumination = getIlluminationProperties(evaluated);
// Adjust azimuths if anchor is viewport
if (evaluated.get<HillshadeIlluminationAnchor>() == HillshadeIlluminationAnchorType::Viewport) {
float bearing = static_cast<float>(parameters.state.getBearing());
for (auto& azimuth : illumination.directionRadians) {
azimuth -= bearing;
}
}
if (!evaluatedPropsUniformBuffer || propertiesUpdated) {
const HillshadeEvaluatedPropsUBO evaluatedPropsUBO = {.highlight = evaluated.get<HillshadeHighlightColor>(),
.shadow = evaluated.get<HillshadeShadowColor>(),
.accent = evaluated.get<HillshadeAccentColor>()};
const HillshadeEvaluatedPropsUBO evaluatedPropsUBO = packEvaluatedProps(illumination,
evaluated.get<HillshadeAccentColor>());
parameters.context.emplaceOrUpdateUniformBuffer(evaluatedPropsUniformBuffer, &evaluatedPropsUBO);
propertiesUpdated = false;
}
@@ -83,7 +189,12 @@ void HillshadeLayerTweaker::execute(LayerGroupBase& layerGroup, const PaintParam
const HillshadeTilePropsUBO tilePropsUBO = {
#endif
.latrange = getLatRange(tileID),
.light = getLight(parameters, evaluated)
.exaggeration = evaluated.get<HillshadeExaggeration>(),
.method = methodToInt(evaluated.get<style::HillshadeMethod>()),
.num_lights = static_cast<int32_t>(illumination.numSources()),
.pad0 = 0.0f,
.pad1 = 0.0f,
.pad2 = 0.0f
};
#if MLN_UBO_CONSOLIDATION

View File

@@ -0,0 +1,451 @@
#include <mbgl/renderer/layers/render_color_relief_layer.hpp>
#include <mbgl/renderer/layers/color_relief_layer_tweaker.hpp>
#include <mbgl/renderer/buckets/hillshade_bucket.hpp>
#include <mbgl/renderer/render_tile.hpp>
#include <mbgl/renderer/sources/render_raster_dem_source.hpp>
#include <mbgl/renderer/paint_parameters.hpp>
#include <mbgl/renderer/render_static_data.hpp>
#include <mbgl/style/layers/color_relief_layer.hpp>
#include <mbgl/style/layers/color_relief_layer_impl.hpp>
#include <mbgl/gfx/cull_face_mode.hpp>
#include <mbgl/gfx/color_relief_drawable_data.hpp>
#include <mbgl/renderer/layer_group.hpp>
#include <mbgl/renderer/update_parameters.hpp>
#include <mbgl/shaders/shader_program_base.hpp>
#include <mbgl/shaders/shader_defines.hpp>
#include <mbgl/shaders/color_relief_layer_ubo.hpp>
#include <mbgl/gfx/drawable_builder.hpp>
#include <mbgl/gfx/shader_registry.hpp>
#include <mbgl/style/expression/value.hpp>
#include <mbgl/style/expression/expression.hpp>
#include <mbgl/style/expression/interpolate.hpp>
#include <mbgl/style/conversion/color_ramp_property_value.hpp>
#include <mbgl/util/premultiply.hpp>
#include <vector>
#include <cstring>
namespace mbgl {
using namespace style;
using namespace shaders;
namespace {
inline const ColorReliefLayer::Impl& impl_cast(const Immutable<Layer::Impl>& impl) {
assert(impl->getTypeInfo() == ColorReliefLayer::Impl::staticTypeInfo());
return static_cast<const ColorReliefLayer::Impl&>(*impl);
}
} // namespace
RenderColorReliefLayer::RenderColorReliefLayer(Immutable<ColorReliefLayer::Impl> _impl)
: RenderLayer(makeMutable<ColorReliefLayerProperties>(std::move(_impl))),
unevaluated(impl_cast(baseImpl).paint.untransitioned()) {
styleDependencies = unevaluated.getDependencies();
// Initialize color ramp data with RGBA format (4 floats per stop)
colorRampSize = 256;
elevationStopsData = std::make_shared<std::vector<float>>(colorRampSize * 4);
colorStops = std::make_shared<PremultipliedImage>(Size{colorRampSize, 1});
// Initialize with default color ramp immediately to avoid uninitialized state
updateColorRamp();
}
RenderColorReliefLayer::~RenderColorReliefLayer() = default;
void RenderColorReliefLayer::transition(const TransitionParameters& parameters) {
unevaluated = impl_cast(baseImpl).paint.transitioned(parameters, std::move(unevaluated));
styleDependencies = unevaluated.getDependencies();
updateColorRamp();
}
void RenderColorReliefLayer::evaluate(const PropertyEvaluationParameters& parameters) {
const auto previousProperties = staticImmutableCast<ColorReliefLayerProperties>(evaluatedProperties);
auto properties = makeMutable<ColorReliefLayerProperties>(
staticImmutableCast<ColorReliefLayer::Impl>(baseImpl),
unevaluated.evaluate(parameters, previousProperties->evaluated));
passes = (properties->evaluated.get<style::ColorReliefOpacity>() > 0) ? RenderPass::Translucent : RenderPass::None;
properties->renderPasses = mbgl::underlying_type(passes);
evaluatedProperties = std::move(properties);
if (layerTweaker) {
layerTweaker->updateProperties(evaluatedProperties);
}
}
bool RenderColorReliefLayer::hasTransition() const {
return unevaluated.hasTransition();
}
bool RenderColorReliefLayer::hasCrossfade() const {
return false;
}
void RenderColorReliefLayer::prepare(const LayerPrepareParameters& params) {
renderTiles = params.source->getRenderTiles();
updateRenderTileIDs();
}
void RenderColorReliefLayer::updateColorRamp() {
// Ensure data structures are initialized
if (!elevationStopsData || !colorStops) {
return;
}
// Get the color property value, using default if undefined
auto colorValue = unevaluated.get<ColorReliefColor>().getValue();
if (colorValue.isUndefined()) {
colorValue = style::ColorReliefLayer::getDefaultColorReliefColor();
if (colorValue.isUndefined()) {
// If even the default is undefined, we can't proceed
return;
}
}
std::vector<float> elevationStopsVector;
std::vector<Color> colorStopsVector;
// Get the expression from ColorRampPropertyValue
// Note: getExpression() dereferences the internal pointer, so we must ensure isUndefined() is false first
const mbgl::style::expression::Expression* exprPtr = &colorValue.getExpression();
if (!exprPtr) {
return;
}
const mbgl::style::expression::Expression& expr = *exprPtr;
if (expr.getKind() == mbgl::style::expression::Kind::Interpolate) {
const auto* interpolate = static_cast<const mbgl::style::expression::Interpolate*>(&expr);
size_t stopCount = interpolate->getStopCount();
elevationStopsVector.reserve(stopCount);
colorStopsVector.reserve(stopCount);
// Extract elevation values from stops
interpolate->eachStop([&](double elevation, const mbgl::style::expression::Expression& /*outputExpr*/) {
elevationStopsVector.push_back(static_cast<float>(elevation));
});
// Evaluate expression at each elevation to get colors
for (float elevation : elevationStopsVector) {
Color color = {0.0f, 0.0f, 0.0f, 0.0f}; // Default to transparent black
// Create evaluation context with elevation as color ramp parameter
expression::EvaluationContext context(std::nullopt, nullptr, static_cast<double>(elevation));
expression::EvaluationResult result = expr.evaluate(context);
if (result && result->is<Color>()) {
color = result->get<Color>();
}
colorStopsVector.push_back(color);
}
} else {
// Fallback: Sample the color ramp uniformly
const uint32_t numSamples = 256;
const float minElevation = -500.0f;
const float maxElevation = 9000.0f;
elevationStopsVector.reserve(numSamples);
colorStopsVector.reserve(numSamples);
for (uint32_t i = 0; i < numSamples; ++i) {
float t = static_cast<float>(i) / static_cast<float>(numSamples - 1);
float elevation = minElevation + t * (maxElevation - minElevation);
elevationStopsVector.push_back(elevation);
Color color = colorValue.evaluate(static_cast<double>(elevation));
colorStopsVector.push_back(color);
}
}
const uint32_t rampSize = static_cast<uint32_t>(elevationStopsVector.size());
if (rampSize == 0) {
return;
}
// Resize and prepare structures
elevationStopsData->resize(rampSize * 4); // RGBA float for compatibility
colorStops->resize({rampSize, 1});
this->colorRampSize = rampSize;
for (uint32_t i = 0; i < rampSize; ++i) {
// Store elevation in the R channel of an RGBA float vector
(*elevationStopsData)[i * 4 + 0] = elevationStopsVector[i]; // R = elevation
(*elevationStopsData)[i * 4 + 1] = 0.0f; // G = unused
(*elevationStopsData)[i * 4 + 2] = 0.0f; // B = unused
(*elevationStopsData)[i * 4 + 3] = 1.0f; // A = unused
// Store colors without premultiplication for proper interpolation
Color color = colorStopsVector[i];
colorStops->data[i * 4 + 0] = static_cast<uint8_t>(color.r * 255.0f);
colorStops->data[i * 4 + 1] = static_cast<uint8_t>(color.g * 255.0f);
colorStops->data[i * 4 + 2] = static_cast<uint8_t>(color.b * 255.0f);
colorStops->data[i * 4 + 3] = static_cast<uint8_t>(color.a * 255.0f);
}
colorRampChanged = true;
}
static const std::string ColorReliefShaderGroupName = "ColorReliefShader";
void RenderColorReliefLayer::update(gfx::ShaderRegistry& shaders,
gfx::Context& context,
const TransformState&,
const std::shared_ptr<UpdateParameters>&,
const RenderTree&,
UniqueChangeRequestVec& changes) {
if (!renderTiles || renderTiles->empty()) {
removeAllDrawables();
return;
}
// Set up layer group
if (!layerGroup) {
if (auto layerGroup_ = context.createTileLayerGroup(layerIndex, /*initialCapacity=*/64, getID())) {
setLayerGroup(std::move(layerGroup_), changes);
} else {
return;
}
}
auto* tileLayerGroup = static_cast<TileLayerGroup*>(layerGroup.get());
if (!layerTweaker) {
layerTweaker = std::make_shared<ColorReliefLayerTweaker>(getID(), evaluatedProperties);
layerGroup->addLayerTweaker(layerTweaker);
}
if (!colorReliefShader) {
colorReliefShader = context.getGenericShader(shaders, ColorReliefShaderGroupName);
}
if (!colorReliefShader) {
mbgl::Log::Error(mbgl::Event::Render, "ColorRelief shader failed to load");
removeAllDrawables();
return;
}
auto renderPass = RenderPass::Translucent;
if (!(mbgl::underlying_type(renderPass) & evaluatedProperties->renderPasses)) {
return;
}
stats.drawablesRemoved += tileLayerGroup->removeDrawablesIf(
[&](gfx::Drawable& drawable) { return drawable.getTileID() && !hasRenderTile(*drawable.getTileID()); });
if (!staticDataSharedVertices) {
staticDataSharedVertices = std::make_shared<ColorReliefVertexVector>(RenderStaticData::rasterVertices());
}
const auto staticDataIndices = RenderStaticData::quadTriangleIndices();
const auto staticDataSegments = RenderStaticData::rasterSegments();
// Update color ramp textures if changed
if (colorRampChanged && elevationStopsData && colorStops) {
if (!elevationStopsTexture) {
elevationStopsTexture = context.createTexture2D();
}
// Use RGBA32F instead of R32F for llvmpipe compatibility
elevationStopsTexture->setFormat(gfx::TexturePixelType::RGBA, gfx::TextureChannelDataType::Float);
elevationStopsTexture->upload(elevationStopsData->data(), Size{colorRampSize, 1});
elevationStopsTexture->setSamplerConfiguration({.filter = gfx::TextureFilterType::Nearest,
.wrapU = gfx::TextureWrapType::Clamp,
.wrapV = gfx::TextureWrapType::Clamp});
if (!colorStopsTexture) {
colorStopsTexture = context.createTexture2D();
}
colorStopsTexture->setImage(colorStops);
colorStopsTexture->setSamplerConfiguration({.filter = gfx::TextureFilterType::Linear,
.wrapU = gfx::TextureWrapType::Clamp,
.wrapV = gfx::TextureWrapType::Clamp});
colorRampChanged = false;
}
// Skip rendering if color ramp textures aren't ready
if (!elevationStopsTexture || !colorStopsTexture) {
return;
}
std::unique_ptr<gfx::DrawableBuilder> builder;
for (const RenderTile& tile : *renderTiles) {
const auto& tileID = tile.getOverscaledTileID();
auto* bucket_ = tile.getBucket(*baseImpl);
if (!bucket_ || !bucket_->hasData()) {
removeTile(renderPass, tileID);
continue;
}
auto& bucket = static_cast<HillshadeBucket&>(*bucket_);
const auto prevBucketID = getRenderTileBucketID(tileID);
if (prevBucketID != util::SimpleIdentity::Empty && prevBucketID != bucket.getID()) {
removeTile(renderPass, tileID);
}
setRenderTileBucketID(tileID, bucket.getID());
// Set up tile drawable
std::shared_ptr<ColorReliefVertexVector> vertices;
std::shared_ptr<gfx::IndexVector<gfx::Triangles>> indices;
auto* segments = &staticDataSegments;
if (!bucket.vertices.empty() && !bucket.indices.empty() && !bucket.segments.empty()) {
vertices = bucket.sharedVertices;
indices = bucket.sharedIndices;
segments = &bucket.segments;
} else {
vertices = staticDataSharedVertices;
indices = std::make_shared<gfx::IndexVector<gfx::Triangles>>(staticDataIndices);
}
if (!builder) {
builder = context.createDrawableBuilder("colorRelief");
}
gfx::VertexAttributeArrayPtr vertexAttrs;
auto buildVertexAttributes = [&] {
if (!vertexAttrs) {
vertexAttrs = context.createVertexAttributeArray();
if (const auto& attr = vertexAttrs->set(idColorReliefPosVertexAttribute)) {
attr->setSharedRawData(vertices,
offsetof(HillshadeLayoutVertex, a1),
0,
sizeof(HillshadeLayoutVertex),
gfx::AttributeDataType::Short2);
}
if (const auto& attr = vertexAttrs->set(idColorReliefTexturePosVertexAttribute)) {
attr->setSharedRawData(vertices,
offsetof(HillshadeLayoutVertex, a2),
0,
sizeof(HillshadeLayoutVertex),
gfx::AttributeDataType::Short2);
}
}
return vertexAttrs;
};
const auto updateExisting = [&](gfx::Drawable& drawable) {
if (drawable.getLayerTweaker() != layerTweaker) {
return false;
}
drawable.updateVertexAttributes(buildVertexAttributes(),
vertices->elements(),
gfx::Triangles(),
std::move(indices),
segments->data(),
segments->size());
// Update textures
auto demImagePtr = bucket.getDEMData().getImagePtr();
if (!demImagePtr || !demImagePtr->valid()) {
return false;
}
std::shared_ptr<gfx::Texture2D> demTexture = context.createTexture2D();
demTexture->setImage(demImagePtr);
demTexture->setSamplerConfiguration({.filter = gfx::TextureFilterType::Linear,
.wrapU = gfx::TextureWrapType::Clamp,
.wrapV = gfx::TextureWrapType::Clamp});
drawable.setTexture(demTexture, idColorReliefImageTexture);
if (elevationStopsTexture) {
drawable.setTexture(elevationStopsTexture, idColorReliefElevationStopsTexture);
}
if (colorStopsTexture) {
drawable.setTexture(colorStopsTexture, idColorReliefColorStopsTexture);
}
return true;
};
if (updateTile(renderPass, tileID, std::move(updateExisting))) {
continue;
}
builder->setShader(colorReliefShader);
builder->setDepthType(gfx::DepthMaskType::ReadOnly);
builder->setColorMode(gfx::ColorMode::alphaBlended());
builder->setCullFaceMode(gfx::CullFaceMode::disabled());
builder->setRenderPass(renderPass);
builder->setVertexAttributes(buildVertexAttributes());
builder->setRawVertices({}, vertices->elements(), gfx::AttributeDataType::Short2);
builder->setSegments(gfx::Triangles(), indices->vector(), segments->data(), segments->size());
// Bind DEM texture
auto demImagePtr = bucket.getDEMData().getImagePtr();
if (!demImagePtr || !demImagePtr->valid()) {
mbgl::Log::Warning(mbgl::Event::Render, "ColorRelief: DEM image not valid for tile");
continue; // Skip this tile if DEM data is not ready
}
const auto& demData = bucket.getDEMData();
std::shared_ptr<gfx::Texture2D> demTexture = context.createTexture2D();
demTexture->setImage(demImagePtr);
demTexture->setSamplerConfiguration({.filter = gfx::TextureFilterType::Linear,
.wrapU = gfx::TextureWrapType::Clamp,
.wrapV = gfx::TextureWrapType::Clamp});
builder->setTexture(demTexture, idColorReliefImageTexture);
// Bind color ramp textures
if (elevationStopsTexture) {
builder->setTexture(elevationStopsTexture, idColorReliefElevationStopsTexture);
}
if (colorStopsTexture) {
builder->setTexture(colorStopsTexture, idColorReliefColorStopsTexture);
}
builder->flush(context);
for (auto& drawable : builder->clearDrawables()) {
drawable->setTileID(tileID);
drawable->setLayerTweaker(layerTweaker);
// Set up tile properties data on the drawable
shaders::ColorReliefTilePropsUBO tilePropsUBO;
const auto unpackVector = demData.getUnpackVector();
tilePropsUBO.unpack = {{unpackVector[0], unpackVector[1], unpackVector[2], unpackVector[3]}};
// Use stride (dim + 2) for dimension, as the texture includes a 1-pixel border
tilePropsUBO.dimension = {{static_cast<float>(demData.stride), static_cast<float>(demData.stride)}};
tilePropsUBO.color_ramp_size = static_cast<int32_t>(colorRampSize);
tilePropsUBO.pad_tile0 = 0.0f;
// Store tile props in drawable data for use by the tweaker (for consolidated backends)
drawable->setData(std::make_unique<gfx::ColorReliefDrawableData>(tilePropsUBO));
#if !MLN_UBO_CONSOLIDATION
// For non-consolidated UBOs (OpenGL), set the uniform buffer directly on the drawable
auto& drawableUniforms = drawable->mutableUniformBuffers();
drawableUniforms.createOrUpdate(idColorReliefTilePropsUBO, &tilePropsUBO, context);
#endif
tileLayerGroup->addDrawable(renderPass, tileID, std::move(drawable));
++stats.drawablesAdded;
}
}
}
bool RenderColorReliefLayer::queryIntersectsFeature(const GeometryCoordinates&,
const GeometryTileFeature&,
float,
const TransformState&,
float,
const mat4&,
const FeatureState&) const {
return false;
}
} // namespace mbgl

View File

@@ -0,0 +1,72 @@
#pragma once
#include <mbgl/renderer/render_layer.hpp>
#include <mbgl/renderer/buckets/hillshade_bucket.hpp>
#include <mbgl/style/layers/color_relief_layer_impl.hpp>
#include <mbgl/style/layers/color_relief_layer_properties.hpp>
#include <mbgl/util/image.hpp>
#include <memory>
#include <vector> // Added for std::vector<float>
namespace mbgl {
namespace gfx {
class Texture2D;
class ShaderProgramBase;
} // namespace gfx
} // namespace mbgl
namespace mbgl {
class RenderColorReliefLayer final : public RenderLayer {
public:
explicit RenderColorReliefLayer(Immutable<style::ColorReliefLayer::Impl>);
~RenderColorReliefLayer() override;
/// Generate any changes needed by the layer
void update(gfx::ShaderRegistry&,
gfx::Context&,
const TransformState&,
const std::shared_ptr<UpdateParameters>&,
const RenderTree&,
UniqueChangeRequestVec&) override;
private:
void transition(const TransitionParameters&) override;
void evaluate(const PropertyEvaluationParameters&) override;
bool hasTransition() const override;
bool hasCrossfade() const override;
void prepare(const LayerPrepareParameters&) override;
bool queryIntersectsFeature(const GeometryCoordinates&,
const GeometryTileFeature&,
float,
const TransformState&,
float,
const mat4&,
const FeatureState&) const override;
void updateColorRamp();
// Paint properties
style::ColorReliefPaintProperties::Unevaluated unevaluated;
// Color ramp data
uint32_t colorRampSize = 256;
bool colorRampChanged = true;
// FIX 1: Changed type and name to correctly hold float elevation data
std::shared_ptr<std::vector<float>> elevationStopsData; // Elevation values for each stop
std::shared_ptr<PremultipliedImage> colorStops; // RGB colors for each stop
// GPU textures
std::shared_ptr<gfx::Texture2D> elevationStopsTexture;
std::shared_ptr<gfx::Texture2D> colorStopsTexture;
// Shader
gfx::ShaderProgramBasePtr colorReliefShader;
// Vertex data
using ColorReliefVertexVector = gfx::VertexVector<HillshadeLayoutVertex>;
std::shared_ptr<ColorReliefVertexVector> staticDataSharedVertices;
};
} // namespace mbgl

View File

@@ -18,6 +18,7 @@
#include <mbgl/renderer/render_target.hpp>
#include <mbgl/renderer/update_parameters.hpp>
#include <mbgl/shaders/shader_program_base.hpp>
#include <mbgl/shaders/hillshade_layer_ubo.hpp>
#include <mbgl/gfx/drawable_builder.hpp>
#include <mbgl/gfx/drawable_impl.hpp>
#include <mbgl/gfx/hillshade_prepare_drawable_data.hpp>
@@ -52,9 +53,14 @@ std::array<float, 2> RenderHillshadeLayer::getLatRange(const UnwrappedTileID& id
return {{static_cast<float>(latlng0.latitude()), static_cast<float>(latlng1.latitude())}};
}
// Keep old function for backward compatibility during transition
std::array<float, 2> RenderHillshadeLayer::getLight(const PaintParameters& parameters) {
const auto& evaluated = static_cast<const HillshadeLayerProperties&>(*evaluatedProperties).evaluated;
float azimuthal = util::deg2radf(evaluated.get<HillshadeIlluminationDirection>());
// Get first element from vectors (for backward compatibility)
std::vector<float> directions = evaluated.get<HillshadeIlluminationDirection>();
float azimuthal = util::deg2radf(directions.empty() ? 335.0f : directions[0]);
if (evaluated.get<HillshadeIlluminationAnchor>() == HillshadeIlluminationAnchorType::Viewport)
azimuthal = azimuthal - static_cast<float>(parameters.state.getBearing());
return {{evaluated.get<HillshadeExaggeration>(), azimuthal}};
@@ -175,9 +181,11 @@ void RenderHillshadeLayer::update(gfx::ShaderRegistry& shaders,
if (!hillshadePrepareShader) {
hillshadePrepareShader = context.getGenericShader(shaders, HillshadePrepareShaderGroupName);
}
if (!hillshadeShader) {
hillshadeShader = context.getGenericShader(shaders, HillshadeShaderGroupName);
}
if (!hillshadePrepareShader || !hillshadeShader) {
removeAllDrawables();
return;
@@ -278,7 +286,8 @@ void RenderHillshadeLayer::update(gfx::ShaderRegistry& shaders,
std::shared_ptr<gfx::Texture2D> texture = context.createTexture2D();
texture->setImage(bucket.getDEMData().getImagePtr());
texture->setSamplerConfiguration({.filter = gfx::TextureFilterType::Linear,
// Use Nearest filtering to match GL JS behavior - the Sobel kernel samples exact pixel values
texture->setSamplerConfiguration({.filter = gfx::TextureFilterType::Nearest,
.wrapU = gfx::TextureWrapType::Clamp,
.wrapV = gfx::TextureWrapType::Clamp});
hillshadePrepareBuilder->setTexture(texture, idHillshadeImageTexture);

View File

@@ -316,6 +316,24 @@ const std::vector<TextureInfo> HillshadeShaderInfo::textures = {
TextureInfo{"u_image", idHillshadeImageTexture},
};
// Color Relief
using ColorReliefShaderInfo = ShaderInfo<BuiltIn::ColorReliefShader, gfx::Backend::Type::OpenGL>;
const std::vector<UniformBlockInfo> ColorReliefShaderInfo::uniformBlocks = {
UniformBlockInfo{"ColorReliefDrawableUBO", idColorReliefDrawableUBO},
UniformBlockInfo{"ColorReliefTilePropsUBO", idColorReliefTilePropsUBO},
UniformBlockInfo{"ColorReliefEvaluatedPropsUBO", idColorReliefEvaluatedPropsUBO},
};
const std::vector<AttributeInfo> ColorReliefShaderInfo::attributes = {
AttributeInfo{"a_pos", idColorReliefPosVertexAttribute},
AttributeInfo{"a_texture_pos", idColorReliefTexturePosVertexAttribute},
};
const std::vector<TextureInfo> ColorReliefShaderInfo::textures = {
TextureInfo{"u_image", idColorReliefImageTexture},
TextureInfo{"u_elevation_stops", idColorReliefElevationStopsTexture},
TextureInfo{"u_color_stops", idColorReliefColorStopsTexture},
};
// Line
using LineShaderInfo = ShaderInfo<BuiltIn::LineShader, gfx::Backend::Type::OpenGL>;

View File

@@ -0,0 +1,21 @@
#include <mbgl/shaders/mtl/color_relief.hpp>
#include <mbgl/shaders/shader_defines.hpp>
#include <mbgl/shaders/mtl/shader_program.hpp>
namespace mbgl {
namespace shaders {
using ColorReliefShaderSource = ShaderSource<BuiltIn::ColorReliefShader, gfx::Backend::Type::Metal>;
const std::array<AttributeInfo, 2> ColorReliefShaderSource::attributes = {
AttributeInfo{colorReliefUBOCount + 0, gfx::AttributeDataType::Short2, idColorReliefPosVertexAttribute},
AttributeInfo{colorReliefUBOCount + 1, gfx::AttributeDataType::Short2, idColorReliefTexturePosVertexAttribute},
};
const std::array<TextureInfo, 3> ColorReliefShaderSource::textures = {
TextureInfo{0, idColorReliefImageTexture},
TextureInfo{1, idColorReliefElevationStopsTexture},
TextureInfo{2, idColorReliefColorStopsTexture},
};
} // namespace shaders
} // namespace mbgl

View File

@@ -6,7 +6,6 @@ namespace mbgl {
using namespace shaders;
// NOLINTNEXTLINE(modernize-use-ranges)
MBGL_DEFINE_ENUM(BuiltIn,
{{BuiltIn::None, "None"},
{BuiltIn::Prelude, "Prelude"},
@@ -29,6 +28,7 @@ MBGL_DEFINE_ENUM(BuiltIn,
{BuiltIn::HeatmapShader, "HeatmapShader"},
{BuiltIn::HeatmapTextureShader, "HeatmapTextureShader"},
{BuiltIn::HillshadePrepareShader, "HillshadePrepareShader"},
{BuiltIn::ColorReliefShader, "ColorReliefShader"},
{BuiltIn::HillshadeShader, "HillshadeShader"},
{BuiltIn::LineShader, "LineShader"},
{BuiltIn::LineGradientShader, "LineGradientShader"},

View File

@@ -0,0 +1,22 @@
#include <mbgl/shaders/vulkan/color_relief.hpp>
#include <mbgl/shaders/shader_defines.hpp>
#include <mbgl/shaders/color_relief_layer_ubo.hpp>
namespace mbgl {
namespace shaders {
using ColorReliefShaderSource = ShaderSource<BuiltIn::ColorReliefShader, gfx::Backend::Type::Vulkan>;
const std::array<AttributeInfo, 2> ColorReliefShaderSource::attributes = {
AttributeInfo{0, gfx::AttributeDataType::Short2, idColorReliefPosVertexAttribute},
AttributeInfo{1, gfx::AttributeDataType::Short2, idColorReliefTexturePosVertexAttribute},
};
const std::array<TextureInfo, 3> ColorReliefShaderSource::textures = {
TextureInfo{0, idColorReliefImageTexture},
TextureInfo{1, idColorReliefElevationStopsTexture},
TextureInfo{2, idColorReliefColorStopsTexture},
};
} // namespace shaders
} // namespace mbgl

View File

@@ -0,0 +1,22 @@
#include <mbgl/shaders/webgpu/color_relief.hpp>
#include <mbgl/shaders/shader_defines.hpp>
#include <mbgl/shaders/color_relief_layer_ubo.hpp>
namespace mbgl {
namespace shaders {
using ColorReliefShaderSource = ShaderSource<BuiltIn::ColorReliefShader, gfx::Backend::Type::WebGPU>;
const std::array<AttributeInfo, 2> ColorReliefShaderSource::attributes = {
AttributeInfo{5, gfx::AttributeDataType::Short2, idColorReliefPosVertexAttribute},
AttributeInfo{6, gfx::AttributeDataType::Short2, idColorReliefTexturePosVertexAttribute},
};
const std::array<TextureInfo, 3> ColorReliefShaderSource::textures = {
TextureInfo{0, idColorReliefImageTexture},
TextureInfo{1, idColorReliefElevationStopsTexture},
TextureInfo{2, idColorReliefColorStopsTexture},
};
} // namespace shaders
} // namespace mbgl

View File

@@ -502,6 +502,10 @@ void ShaderProgram::analyzeShaderBindings(const std::string& source, WGPUShaderS
if (colonPos == std::string::npos) {
break;
}
// Extract the variable name
const auto varName = trimString(std::string_view(source.data() + afterVar, colonPos - afterVar));
size_t typeStart = colonPos + 1;
size_t typeEnd = typeStart;
while (typeEnd < source.size()) {
@@ -517,7 +521,19 @@ void ShaderProgram::analyzeShaderBindings(const std::string& source, WGPUShaderS
if (typeName.find("sampler") != std::string::npos) {
type = BindingType::Sampler;
} else if (typeName.find("texture") != std::string::npos) {
type = BindingType::Texture;
// Check if this texture is used with textureLoad (unfilterable) or textureSample (filterable)
// Look for textureLoad(varName, which indicates it's used without filtering
std::string textureLoadPattern = std::string("textureLoad(") + std::string(varName);
std::string textureSamplePattern = std::string("textureSample(") + std::string(varName);
bool usesTextureLoad = source.find(textureLoadPattern) != std::string::npos;
bool usesTextureSample = source.find(textureSamplePattern) != std::string::npos;
// If only textureLoad is used (not textureSample), mark as unfilterable
if (usesTextureLoad && !usesTextureSample) {
type = BindingType::UnfilterableTexture;
} else {
type = BindingType::Texture;
}
}
}
@@ -600,6 +616,11 @@ void ShaderProgram::rebuildBindGroupLayouts() {
layoutEntry.texture.viewDimension = WGPUTextureViewDimension_2D;
layoutEntry.texture.multisampled = false;
break;
case BindingType::UnfilterableTexture:
layoutEntry.texture.sampleType = WGPUTextureSampleType_UnfilterableFloat;
layoutEntry.texture.viewDimension = WGPUTextureViewDimension_2D;
layoutEntry.texture.multisampled = false;
break;
}
layoutEntries.push_back(layoutEntry);

View File

@@ -25,14 +25,17 @@ std::optional<ColorRampPropertyValue> Converter<ColorRampPropertyValue>::operato
return std::nullopt;
}
assert(*expression);
if (!isFeatureConstant(**expression)) {
auto deps = (*expression)->dependencies;
if ((deps & Dependency::Feature) && !(deps & Dependency::Elevation)) {
error.message = "data expressions not supported";
return std::nullopt;
}
if (!isZoomConstant(**expression)) {
if (deps & Dependency::Zoom) {
error.message = "zoom expressions not supported";
return std::nullopt;
}
return ColorRampPropertyValue(std::move(*expression));
} else {
error.message = "color ramp must be an expression";

View File

@@ -78,6 +78,8 @@ template std::optional<CirclePitchScaleType> Converter<CirclePitchScaleType>::op
Error&) const;
template std::optional<HillshadeIlluminationAnchorType> Converter<HillshadeIlluminationAnchorType>::operator()(
const Convertible&, Error&) const;
template std::optional<HillshadeMethodType> Converter<HillshadeMethodType>::operator()(const Convertible&,
Error&) const;
template std::optional<IconTextFitType> Converter<IconTextFitType>::operator()(const Convertible&, Error&) const;
template std::optional<LightAnchorType> Converter<LightAnchorType>::operator()(const Convertible&, Error&) const;
template std::optional<LineCapType> Converter<LineCapType>::operator()(const Convertible&, Error&) const;
@@ -114,6 +116,28 @@ std::optional<Color> Converter<Color>::operator()(const Convertible& value, Erro
return color;
}
std::optional<std::vector<Color>> Converter<std::vector<Color>>::operator()(const Convertible& value,
Error& error) const {
if (!isArray(value)) {
// Try single color
auto color = convert<Color>(value, error);
if (!color) return std::nullopt;
return std::vector<Color>{*color};
}
std::vector<Color> result;
auto length = arrayLength(value);
result.reserve(length);
for (std::size_t i = 0; i < length; ++i) {
auto color = convert<Color>(arrayMember(value, i), error);
if (!color) return std::nullopt;
result.push_back(*color);
}
return result;
}
std::optional<Padding> Converter<Padding>::operator()(const Convertible& value, Error& error) const {
std::optional<Padding> result;
if (isArray(value)) {
@@ -237,8 +261,13 @@ template std::optional<std::array<double, 3>> Converter<std::array<double, 3>>::
std::optional<std::vector<float>> Converter<std::vector<float>>::operator()(const Convertible& value,
Error& error) const {
// Allow single number to be converted to a single-element array
if (std::optional<float> number = toNumber(value)) {
return std::vector<float>{*number};
}
if (!isArray(value)) {
error.message = "value must be an array";
error.message = "value must be a number or an array of numbers";
return std::nullopt;
}

View File

@@ -167,6 +167,10 @@ template std::optional<PropertyExpression<TextTransformType>> convertFunctionToE
const Convertible&, Error&, bool);
template std::optional<PropertyExpression<TranslateAnchorType>> convertFunctionToExpression<TranslateAnchorType>(
const Convertible&, Error&, bool);
template std::optional<PropertyExpression<std::vector<Color>>> convertFunctionToExpression<std::vector<Color>>(
const Convertible&, Error&, bool);
template std::optional<PropertyExpression<HillshadeMethodType>> convertFunctionToExpression<HillshadeMethodType>(
const Convertible&, Error&, bool);
template std::optional<PropertyExpression<Formatted>> convertFunctionToExpression<Formatted>(const Convertible&,
Error&,
bool);
@@ -217,7 +221,19 @@ bool interpolatable(type::Type type) noexcept {
[&](const type::ColorType&) { return true; },
[&](const type::PaddingType&) { return true; },
[&](const type::VariableAnchorOffsetCollectionType&) { return true; },
[&](const type::Array& array) { return array.N && array.itemType == type::Number; },
[&](const type::Array& array) {
// Arrays are interpolatable if they have a fixed size and item type is Number,
// OR if the item type itself is interpolatable (e.g., Array<Color>)
if (array.N && array.itemType == type::Number) {
return true;
}
// Variable-length Number arrays (like line-dasharray) are not interpolatable
// because interpolating between different dasharray patterns doesn't make semantic sense
if (!array.N && array.itemType == type::Number) {
return false;
}
return interpolatable(array.itemType);
},
[&](const auto&) { return false; });
}
@@ -355,17 +371,32 @@ std::optional<std::map<double, std::unique_ptr<Expression>>> convertStops(const
error.message = "function value must specify stops";
return std::nullopt;
}
if (!isArray(*stopsValue)) {
error.message = "function stops must be an array";
return std::nullopt;
}
if (arrayLength(*stopsValue) == 0) {
error.message = "function must have at least one stop";
return std::nullopt;
}
// For std::vector<Color> (hillshade color arrays), parse stops as the item type
// This allows zoom function interpolation of individual colors
// Other array types (translate, dasharray, etc) use the full type
type::Type stopType = type;
bool isColorArray = false;
type.match(
[&](const type::Array& arr) {
// Check if this is an array of Color
arr.itemType.match(
[&](const type::ColorType&) {
stopType = arr.itemType;
isColorArray = true;
},
[](const auto&) {});
},
[](const auto&) {});
std::map<double, std::unique_ptr<Expression>> stops;
for (std::size_t i = 0; i < arrayLength(*stopsValue); ++i) {
const auto& stopValue = arrayMember(*stopsValue, i);
@@ -386,14 +417,12 @@ std::optional<std::map<double, std::unique_ptr<Expression>>> convertStops(const
}
std::optional<std::unique_ptr<Expression>> e = convertLiteral(
type, arrayMember(stopValue, 1), error, convertTokens);
stopType, arrayMember(stopValue, 1), error, convertTokens);
if (!e) {
return std::nullopt;
}
stops.emplace(*t, std::move(*e));
}
return {std::move(stops)};
}
@@ -555,7 +584,28 @@ std::optional<std::unique_ptr<Expression>> convertIntervalFunction(
}
omitFirstStop(*stops);
auto expr = step(type, makeInput(true), std::move(*stops));
// For std::vector<Color> arrays, create step with item type
type::Type exprType = type;
bool isColorArray = false;
type.match(
[&](const type::Array& arr) {
// Check if this is an array of Color
arr.itemType.match(
[&](const type::ColorType&) {
exprType = arr.itemType;
isColorArray = true;
},
[](const auto&) {});
},
[](const auto&) {});
auto expr = step(exprType, makeInput(true), std::move(*stops));
// For color arrays with camera functions, return the step directly
if (isColorArray && !def) {
return expr;
}
return numberOrDefault(std::move(type), makeInput(false), std::move(expr), std::move(def));
}
@@ -575,7 +625,28 @@ std::optional<std::unique_ptr<Expression>> convertExponentialFunction(
return std::nullopt;
}
auto expr = interpolate(type, exponential(*base), makeInput(true), std::move(*stops));
// For std::vector<Color> arrays, create interpolation with item type
type::Type exprType = type;
bool isColorArray = false;
type.match(
[&](const type::Array& arr) {
// Check if this is an array of Color
arr.itemType.match(
[&](const type::ColorType&) {
exprType = arr.itemType;
isColorArray = true;
},
[](const auto&) {});
},
[](const auto&) {});
auto expr = interpolate(exprType, exponential(*base), makeInput(true), std::move(*stops));
// For color arrays with camera functions, return the interpolation directly
if (isColorArray && !def) {
return expr;
}
return numberOrDefault(std::move(type), makeInput(false), std::move(expr), std::move(def));
}

View File

@@ -0,0 +1,90 @@
#include <mbgl/style/conversion/property_value.hpp>
#include <mbgl/style/expression/value.hpp>
#include <mbgl/style/expression/type.hpp>
#include <mbgl/style/types.hpp>
#include <mbgl/util/color.hpp>
#include <mbgl/util/enum.hpp>
namespace mbgl {
// Enum specializations
template <>
const char* Enum<style::HillshadeMethodType>::toString(style::HillshadeMethodType t) {
switch (t) {
case style::HillshadeMethodType::Standard:
return "standard";
case style::HillshadeMethodType::Basic:
return "basic";
case style::HillshadeMethodType::Combined:
return "combined";
case style::HillshadeMethodType::Igor:
return "igor";
case style::HillshadeMethodType::Multidirectional:
return "multidirectional";
}
return "standard";
}
template <>
std::optional<style::HillshadeMethodType> Enum<style::HillshadeMethodType>::toEnum(const std::string& s) {
if (s == "standard") return style::HillshadeMethodType::Standard;
if (s == "basic") return style::HillshadeMethodType::Basic;
if (s == "combined") return style::HillshadeMethodType::Combined;
if (s == "igor") return style::HillshadeMethodType::Igor;
if (s == "multidirectional") return style::HillshadeMethodType::Multidirectional;
return std::nullopt;
}
namespace style {
namespace expression {
// valueTypeToExpressionType specializations
template <>
type::Type valueTypeToExpressionType<std::vector<Color>>() {
return type::Array(type::Color);
}
template <>
type::Type valueTypeToExpressionType<HillshadeMethodType>() {
return type::String;
}
// ValueConverter specializations for runtime expression evaluation
template <>
std::optional<std::vector<Color>> ValueConverter<std::vector<Color>>::fromExpressionValue(const Value& value) {
if (value.is<std::vector<Value>>()) {
const auto& values = value.get<std::vector<Value>>();
std::vector<Color> result;
result.reserve(values.size());
for (const auto& v : values) {
auto color = ValueConverter<Color>::fromExpressionValue(v);
if (!color) return std::nullopt;
result.push_back(*color);
}
return result;
}
// Handle single color - wrap in array
auto color = ValueConverter<Color>::fromExpressionValue(value);
if (!color) return std::nullopt;
return std::vector<Color>{*color};
}
template <>
std::optional<HillshadeMethodType> ValueConverter<HillshadeMethodType>::fromExpressionValue(const Value& value) {
if (!value.is<std::string>()) return std::nullopt;
const auto& str = value.get<std::string>();
if (str == "standard") return HillshadeMethodType::Standard;
if (str == "basic") return HillshadeMethodType::Basic;
if (str == "combined") return HillshadeMethodType::Combined;
if (str == "igor") return HillshadeMethodType::Igor;
if (str == "multidirectional") return HillshadeMethodType::Multidirectional;
return std::nullopt;
}
} // namespace expression
} // namespace style
} // namespace mbgl

View File

@@ -2,6 +2,7 @@
#include <mbgl/style/conversion/property_value.hpp>
#include <mbgl/style/conversion/rotation.hpp>
#include <mbgl/style/conversion_impl.hpp>
#include <mbgl/style/conversion.hpp>
namespace mbgl {
namespace style {
@@ -168,6 +169,12 @@ mbgl::style::conversion::Converter<PropertyValue<std::array<double, 3>>, void>::
template std::optional<PropertyValue<Rotation>> Converter<PropertyValue<Rotation>>::operator()(
conversion::Convertible const&, conversion::Error&, bool, bool) const;
// Hillshade array and enum types
template std::optional<PropertyValue<std::vector<Color>>> Converter<PropertyValue<std::vector<Color>>>::operator()(
conversion::Convertible const&, conversion::Error&, bool, bool) const;
template std::optional<PropertyValue<HillshadeMethodType>> Converter<PropertyValue<HillshadeMethodType>>::operator()(
conversion::Convertible const&, conversion::Error&, bool, bool) const;
} // namespace conversion
} // namespace style
} // namespace mbgl

View File

@@ -369,6 +369,26 @@ const auto& heatmapDensityCompoundExpression() {
return signature;
}
const auto& elevationCompoundExpression() {
static auto signature = detail::makeSignature(
"elevation",
[](const EvaluationContext& params) -> Result<double> {
// For color-relief, elevation is passed via colorRampParameter
if (params.colorRampParameter) {
return *(params.colorRampParameter);
}
// For 3D terrain, elevation is passed directly
if (params.elevation) {
return static_cast<double>(*(params.elevation));
}
// During parsing/validation, return a valid value to allow parsing to succeed
// The Dependency::Elevation flag prevents this from being optimized to a constant
return 0.0;
},
Dependency::Elevation);
return signature;
}
const auto& lineProgressCompoundExpression() {
static auto signature = detail::makeSignature("line-progress",
[](const EvaluationContext& params) -> Result<double> {
@@ -1007,6 +1027,7 @@ constexpr const auto compoundExpressionRegistry =
{"rgb", rgbCompoundExpression},
{"zoom", zoomCompoundExpression},
{"heatmap-density", heatmapDensityCompoundExpression},
{"elevation", elevationCompoundExpression},
{"line-progress", lineProgressCompoundExpression},
{"accumulated", accumulatedCompoundExpression},
{"has", hasContextCompoundExpression},

View File

@@ -44,7 +44,8 @@ namespace style {
namespace expression {
namespace {
const auto requiredProps = std::array<std::string_view, 4>{"zoom", "heatmap-density", "line-progress", "accumulated"};
const auto requiredProps = std::array<std::string_view, 5>{
"zoom", "heatmap-density", "line-progress", "accumulated", "elevation"};
bool isConstant(const Expression& expression) {
const auto kind = expression.getKind();

View File

@@ -0,0 +1,239 @@
// clang-format off
// This file is generated. Edit scripts/generate-style-code.js, then run `make style-code`.
#include <mbgl/style/layers/color_relief_layer.hpp>
#include <mbgl/style/layers/color_relief_layer_impl.hpp>
#include <mbgl/style/layer_observer.hpp>
#include <mbgl/style/conversion/color_ramp_property_value.hpp>
#include <mbgl/style/conversion/constant.hpp>
#include <mbgl/style/conversion/property_value.hpp>
#include <mbgl/style/conversion/transition_options.hpp>
#include <mbgl/style/conversion/json.hpp>
#include <mbgl/style/conversion_impl.hpp>
#include <mbgl/util/traits.hpp>
#include <mapbox/eternal.hpp>
namespace mbgl {
namespace style {
// static
const LayerTypeInfo* ColorReliefLayer::Impl::staticTypeInfo() noexcept {
const static LayerTypeInfo typeInfo{.type="color-relief",
.source=LayerTypeInfo::Source::Required,
.pass3d=LayerTypeInfo::Pass3D::NotRequired,
.layout=LayerTypeInfo::Layout::NotRequired,
.fadingTiles=LayerTypeInfo::FadingTiles::NotRequired,
.crossTileIndex=LayerTypeInfo::CrossTileIndex::NotRequired,
.tileKind=LayerTypeInfo::TileKind::RasterDEM};
return &typeInfo;
}
ColorReliefLayer::ColorReliefLayer(const std::string& layerID, const std::string& sourceID)
: Layer(makeMutable<Impl>(layerID, sourceID)) {
}
ColorReliefLayer::ColorReliefLayer(Immutable<Impl> impl_)
: Layer(std::move(impl_)) {
}
ColorReliefLayer::~ColorReliefLayer() {
weakFactory.invalidateWeakPtrs();
}
const ColorReliefLayer::Impl& ColorReliefLayer::impl() const {
return static_cast<const Impl&>(*baseImpl);
}
Mutable<ColorReliefLayer::Impl> ColorReliefLayer::mutableImpl() const {
return makeMutable<Impl>(impl());
}
std::unique_ptr<Layer> ColorReliefLayer::cloneRef(const std::string& id_) const {
auto impl_ = mutableImpl();
impl_->id = id_;
impl_->paint = ColorReliefPaintProperties::Transitionable();
return std::make_unique<ColorReliefLayer>(std::move(impl_));
}
void ColorReliefLayer::Impl::stringifyLayout(rapidjson::Writer<rapidjson::StringBuffer>&) const {
}
// Layout properties
// Paint properties
ColorRampPropertyValue ColorReliefLayer::getDefaultColorReliefColor() {
return {{}};
}
const ColorRampPropertyValue& ColorReliefLayer::getColorReliefColor() const {
return impl().paint.template get<ColorReliefColor>().value;
}
void ColorReliefLayer::setColorReliefColor(const ColorRampPropertyValue& value) {
if (value == getColorReliefColor())
return;
auto impl_ = mutableImpl();
impl_->paint.template get<ColorReliefColor>().value = value;
baseImpl = std::move(impl_);
observer->onLayerChanged(*this);
}
void ColorReliefLayer::setColorReliefColorTransition(const TransitionOptions& options) {
auto impl_ = mutableImpl();
impl_->paint.template get<ColorReliefColor>().options = options;
baseImpl = std::move(impl_);
}
TransitionOptions ColorReliefLayer::getColorReliefColorTransition() const {
return impl().paint.template get<ColorReliefColor>().options;
}
PropertyValue<float> ColorReliefLayer::getDefaultColorReliefOpacity() {
return {1.f};
}
const PropertyValue<float>& ColorReliefLayer::getColorReliefOpacity() const {
return impl().paint.template get<ColorReliefOpacity>().value;
}
void ColorReliefLayer::setColorReliefOpacity(const PropertyValue<float>& value) {
if (value == getColorReliefOpacity())
return;
auto impl_ = mutableImpl();
impl_->paint.template get<ColorReliefOpacity>().value = value;
baseImpl = std::move(impl_);
observer->onLayerChanged(*this);
}
void ColorReliefLayer::setColorReliefOpacityTransition(const TransitionOptions& options) {
auto impl_ = mutableImpl();
impl_->paint.template get<ColorReliefOpacity>().options = options;
baseImpl = std::move(impl_);
}
TransitionOptions ColorReliefLayer::getColorReliefOpacityTransition() const {
return impl().paint.template get<ColorReliefOpacity>().options;
}
using namespace conversion;
namespace {
constexpr uint8_t kPaintPropertyCount = 4u;
enum class Property : uint8_t {
ColorReliefColor,
ColorReliefOpacity,
ColorReliefColorTransition,
ColorReliefOpacityTransition,
};
template <typename T>
constexpr uint8_t toUint8(T t) noexcept {
return uint8_t(mbgl::underlying_type(t));
}
constexpr const auto layerProperties = mapbox::eternal::hash_map<mapbox::eternal::string, uint8_t>(
{{"color-relief-color", toUint8(Property::ColorReliefColor)},
{"color-relief-opacity", toUint8(Property::ColorReliefOpacity)},
{"color-relief-color-transition", toUint8(Property::ColorReliefColorTransition)},
{"color-relief-opacity-transition", toUint8(Property::ColorReliefOpacityTransition)}});
StyleProperty getLayerProperty(const ColorReliefLayer& layer, Property property) {
switch (property) {
case Property::ColorReliefColor:
return makeStyleProperty(layer.getColorReliefColor());
case Property::ColorReliefOpacity:
return makeStyleProperty(layer.getColorReliefOpacity());
case Property::ColorReliefColorTransition:
return makeStyleProperty(layer.getColorReliefColorTransition());
case Property::ColorReliefOpacityTransition:
return makeStyleProperty(layer.getColorReliefOpacityTransition());
}
return {};
}
StyleProperty getLayerProperty(const ColorReliefLayer& layer, const std::string& name) {
const auto it = layerProperties.find(name.c_str());
if (it == layerProperties.end()) {
return {};
}
return getLayerProperty(layer, static_cast<Property>(it->second));
}
} // namespace
Value ColorReliefLayer::serialize() const {
auto result = Layer::serialize();
assert(result.getObject());
for (const auto& property : layerProperties) {
auto styleProperty = getLayerProperty(*this, static_cast<Property>(property.second));
if (styleProperty.getKind() == StyleProperty::Kind::Undefined) continue;
serializeProperty(result, styleProperty, property.first.c_str(), property.second < kPaintPropertyCount);
}
return result;
}
std::optional<Error> ColorReliefLayer::setPropertyInternal(const std::string& name, const Convertible& value) {
const auto it = layerProperties.find(name.c_str());
if (it == layerProperties.end()) return Error{"layer doesn't support this property"};
auto property = static_cast<Property>(it->second);
if (property == Property::ColorReliefColor) {
Error error;
const auto& typedValue = convert<ColorRampPropertyValue>(value, error, false, false);
if (!typedValue) {
return error;
}
setColorReliefColor(*typedValue);
return std::nullopt;
}
if (property == Property::ColorReliefOpacity) {
Error error;
const auto& typedValue = convert<PropertyValue<float>>(value, error, false, false);
if (!typedValue) {
return error;
}
setColorReliefOpacity(*typedValue);
return std::nullopt;
}
Error error;
std::optional<TransitionOptions> transition = convert<TransitionOptions>(value, error);
if (!transition) {
return error;
}
if (property == Property::ColorReliefColorTransition) {
setColorReliefColorTransition(*transition);
return std::nullopt;
}
if (property == Property::ColorReliefOpacityTransition) {
setColorReliefOpacityTransition(*transition);
return std::nullopt;
}
return Error{"layer doesn't support this property"};
}
StyleProperty ColorReliefLayer::getProperty(const std::string& name) const {
return getLayerProperty(*this, name);
}
Mutable<Layer::Impl> ColorReliefLayer::mutableBaseImpl() const {
return staticMutableCast<Layer::Impl>(mutableImpl());
}
} // namespace style
} // namespace mbgl
// clang-format on

View File

@@ -0,0 +1,11 @@
#include <mbgl/style/layers/color_relief_layer_impl.hpp>
namespace mbgl {
namespace style {
bool ColorReliefLayer::Impl::hasLayoutDifference(const Layer::Impl&) const {
return false;
}
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,23 @@
#pragma once
#include <mbgl/style/layer_impl.hpp>
#include <mbgl/style/layers/color_relief_layer.hpp>
#include <mbgl/style/layers/color_relief_layer_properties.hpp>
namespace mbgl {
namespace style {
class ColorReliefLayer::Impl : public Layer::Impl {
public:
using Layer::Impl::Impl;
bool hasLayoutDifference(const Layer::Impl&) const override;
void stringifyLayout(rapidjson::Writer<rapidjson::StringBuffer>&) const override;
ColorReliefPaintProperties::Transitionable paint;
DECLARE_LAYER_TYPE_INFO;
};
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,39 @@
// clang-format off
// This file is generated. Edit scripts/generate-style-code.js, then run `make style-code`.
#include <mbgl/style/layers/color_relief_layer_properties.hpp>
#include <mbgl/style/layers/color_relief_layer_impl.hpp>
namespace mbgl {
namespace style {
ColorReliefLayerProperties::ColorReliefLayerProperties(
Immutable<ColorReliefLayer::Impl> impl_)
: LayerProperties(std::move(impl_)) {}
ColorReliefLayerProperties::ColorReliefLayerProperties(
Immutable<ColorReliefLayer::Impl> impl_,
ColorReliefPaintProperties::PossiblyEvaluated evaluated_)
: LayerProperties(std::move(impl_)),
evaluated(std::move(evaluated_)) {}
ColorReliefLayerProperties::~ColorReliefLayerProperties() = default;
unsigned long ColorReliefLayerProperties::constantsMask() const {
return evaluated.constantsMask();
}
const ColorReliefLayer::Impl& ColorReliefLayerProperties::layerImpl() const noexcept {
return static_cast<const ColorReliefLayer::Impl&>(*baseImpl);
}
expression::Dependency ColorReliefLayerProperties::getDependencies() const noexcept {
return layerImpl().paint.getDependencies();
}
} // namespace style
} // namespace mbgl
// clang-format on

View File

@@ -0,0 +1,51 @@
// clang-format off
// This file is generated. Edit scripts/generate-style-code.js, then run `make style-code`.
#pragma once
#include <mbgl/style/types.hpp>
#include <mbgl/style/layer_properties.hpp>
#include <mbgl/style/layers/color_relief_layer.hpp>
#include <mbgl/style/layout_property.hpp>
#include <mbgl/style/paint_property.hpp>
#include <mbgl/style/properties.hpp>
#include <mbgl/shaders/attributes.hpp>
#include <mbgl/shaders/uniforms.hpp>
namespace mbgl {
namespace style {
struct ColorReliefColor : ColorRampProperty {
};
struct ColorReliefOpacity : PaintProperty<float> {
static float defaultValue() { return 1.f; }
};
class ColorReliefPaintProperties : public Properties<
ColorReliefColor,
ColorReliefOpacity
> {};
class ColorReliefLayerProperties final : public LayerProperties {
public:
explicit ColorReliefLayerProperties(Immutable<ColorReliefLayer::Impl>);
ColorReliefLayerProperties(
Immutable<ColorReliefLayer::Impl>,
ColorReliefPaintProperties::PossiblyEvaluated);
~ColorReliefLayerProperties() override;
unsigned long constantsMask() const override;
expression::Dependency getDependencies() const noexcept override;
const ColorReliefLayer::Impl& layerImpl() const noexcept;
// Data members.
ColorReliefPaintProperties::PossiblyEvaluated evaluated;
};
} // namespace style
} // namespace mbgl
// clang-format on

View File

@@ -120,15 +120,15 @@ TransitionOptions HillshadeLayer::getHillshadeExaggerationTransition() const {
return impl().paint.template get<HillshadeExaggeration>().options;
}
PropertyValue<Color> HillshadeLayer::getDefaultHillshadeHighlightColor() {
return {Color::white()};
PropertyValue<std::vector<Color>> HillshadeLayer::getDefaultHillshadeHighlightColor() {
return {{Color::white()}};
}
const PropertyValue<Color>& HillshadeLayer::getHillshadeHighlightColor() const {
const PropertyValue<std::vector<Color>>& HillshadeLayer::getHillshadeHighlightColor() const {
return impl().paint.template get<HillshadeHighlightColor>().value;
}
void HillshadeLayer::setHillshadeHighlightColor(const PropertyValue<Color>& value) {
void HillshadeLayer::setHillshadeHighlightColor(const PropertyValue<std::vector<Color>>& value) {
if (value == getHillshadeHighlightColor())
return;
auto impl_ = mutableImpl();
@@ -147,6 +147,33 @@ TransitionOptions HillshadeLayer::getHillshadeHighlightColorTransition() const {
return impl().paint.template get<HillshadeHighlightColor>().options;
}
PropertyValue<std::vector<float>> HillshadeLayer::getDefaultHillshadeIlluminationAltitude() {
return {{45.f}};
}
const PropertyValue<std::vector<float>>& HillshadeLayer::getHillshadeIlluminationAltitude() const {
return impl().paint.template get<HillshadeIlluminationAltitude>().value;
}
void HillshadeLayer::setHillshadeIlluminationAltitude(const PropertyValue<std::vector<float>>& value) {
if (value == getHillshadeIlluminationAltitude())
return;
auto impl_ = mutableImpl();
impl_->paint.template get<HillshadeIlluminationAltitude>().value = value;
baseImpl = std::move(impl_);
observer->onLayerChanged(*this);
}
void HillshadeLayer::setHillshadeIlluminationAltitudeTransition(const TransitionOptions& options) {
auto impl_ = mutableImpl();
impl_->paint.template get<HillshadeIlluminationAltitude>().options = options;
baseImpl = std::move(impl_);
}
TransitionOptions HillshadeLayer::getHillshadeIlluminationAltitudeTransition() const {
return impl().paint.template get<HillshadeIlluminationAltitude>().options;
}
PropertyValue<HillshadeIlluminationAnchorType> HillshadeLayer::getDefaultHillshadeIlluminationAnchor() {
return {HillshadeIlluminationAnchorType::Viewport};
}
@@ -174,15 +201,15 @@ TransitionOptions HillshadeLayer::getHillshadeIlluminationAnchorTransition() con
return impl().paint.template get<HillshadeIlluminationAnchor>().options;
}
PropertyValue<float> HillshadeLayer::getDefaultHillshadeIlluminationDirection() {
return {335.f};
PropertyValue<std::vector<float>> HillshadeLayer::getDefaultHillshadeIlluminationDirection() {
return {{335.f}};
}
const PropertyValue<float>& HillshadeLayer::getHillshadeIlluminationDirection() const {
const PropertyValue<std::vector<float>>& HillshadeLayer::getHillshadeIlluminationDirection() const {
return impl().paint.template get<HillshadeIlluminationDirection>().value;
}
void HillshadeLayer::setHillshadeIlluminationDirection(const PropertyValue<float>& value) {
void HillshadeLayer::setHillshadeIlluminationDirection(const PropertyValue<std::vector<float>>& value) {
if (value == getHillshadeIlluminationDirection())
return;
auto impl_ = mutableImpl();
@@ -201,15 +228,42 @@ TransitionOptions HillshadeLayer::getHillshadeIlluminationDirectionTransition()
return impl().paint.template get<HillshadeIlluminationDirection>().options;
}
PropertyValue<Color> HillshadeLayer::getDefaultHillshadeShadowColor() {
return {Color::black()};
PropertyValue<HillshadeMethodType> HillshadeLayer::getDefaultHillshadeMethod() {
return {HillshadeMethodType::Standard};
}
const PropertyValue<Color>& HillshadeLayer::getHillshadeShadowColor() const {
const PropertyValue<HillshadeMethodType>& HillshadeLayer::getHillshadeMethod() const {
return impl().paint.template get<HillshadeMethod>().value;
}
void HillshadeLayer::setHillshadeMethod(const PropertyValue<HillshadeMethodType>& value) {
if (value == getHillshadeMethod())
return;
auto impl_ = mutableImpl();
impl_->paint.template get<HillshadeMethod>().value = value;
baseImpl = std::move(impl_);
observer->onLayerChanged(*this);
}
void HillshadeLayer::setHillshadeMethodTransition(const TransitionOptions& options) {
auto impl_ = mutableImpl();
impl_->paint.template get<HillshadeMethod>().options = options;
baseImpl = std::move(impl_);
}
TransitionOptions HillshadeLayer::getHillshadeMethodTransition() const {
return impl().paint.template get<HillshadeMethod>().options;
}
PropertyValue<std::vector<Color>> HillshadeLayer::getDefaultHillshadeShadowColor() {
return {{Color::black()}};
}
const PropertyValue<std::vector<Color>>& HillshadeLayer::getHillshadeShadowColor() const {
return impl().paint.template get<HillshadeShadowColor>().value;
}
void HillshadeLayer::setHillshadeShadowColor(const PropertyValue<Color>& value) {
void HillshadeLayer::setHillshadeShadowColor(const PropertyValue<std::vector<Color>>& value) {
if (value == getHillshadeShadowColor())
return;
auto impl_ = mutableImpl();
@@ -232,20 +286,24 @@ using namespace conversion;
namespace {
constexpr uint8_t kPaintPropertyCount = 12u;
constexpr uint8_t kPaintPropertyCount = 16u;
enum class Property : uint8_t {
HillshadeAccentColor,
HillshadeExaggeration,
HillshadeHighlightColor,
HillshadeIlluminationAltitude,
HillshadeIlluminationAnchor,
HillshadeIlluminationDirection,
HillshadeMethod,
HillshadeShadowColor,
HillshadeAccentColorTransition,
HillshadeExaggerationTransition,
HillshadeHighlightColorTransition,
HillshadeIlluminationAltitudeTransition,
HillshadeIlluminationAnchorTransition,
HillshadeIlluminationDirectionTransition,
HillshadeMethodTransition,
HillshadeShadowColorTransition,
};
@@ -258,14 +316,18 @@ constexpr const auto layerProperties = mapbox::eternal::hash_map<mapbox::eternal
{{"hillshade-accent-color", toUint8(Property::HillshadeAccentColor)},
{"hillshade-exaggeration", toUint8(Property::HillshadeExaggeration)},
{"hillshade-highlight-color", toUint8(Property::HillshadeHighlightColor)},
{"hillshade-illumination-altitude", toUint8(Property::HillshadeIlluminationAltitude)},
{"hillshade-illumination-anchor", toUint8(Property::HillshadeIlluminationAnchor)},
{"hillshade-illumination-direction", toUint8(Property::HillshadeIlluminationDirection)},
{"hillshade-method", toUint8(Property::HillshadeMethod)},
{"hillshade-shadow-color", toUint8(Property::HillshadeShadowColor)},
{"hillshade-accent-color-transition", toUint8(Property::HillshadeAccentColorTransition)},
{"hillshade-exaggeration-transition", toUint8(Property::HillshadeExaggerationTransition)},
{"hillshade-highlight-color-transition", toUint8(Property::HillshadeHighlightColorTransition)},
{"hillshade-illumination-altitude-transition", toUint8(Property::HillshadeIlluminationAltitudeTransition)},
{"hillshade-illumination-anchor-transition", toUint8(Property::HillshadeIlluminationAnchorTransition)},
{"hillshade-illumination-direction-transition", toUint8(Property::HillshadeIlluminationDirectionTransition)},
{"hillshade-method-transition", toUint8(Property::HillshadeMethodTransition)},
{"hillshade-shadow-color-transition", toUint8(Property::HillshadeShadowColorTransition)}});
StyleProperty getLayerProperty(const HillshadeLayer& layer, Property property) {
@@ -276,10 +338,14 @@ StyleProperty getLayerProperty(const HillshadeLayer& layer, Property property) {
return makeStyleProperty(layer.getHillshadeExaggeration());
case Property::HillshadeHighlightColor:
return makeStyleProperty(layer.getHillshadeHighlightColor());
case Property::HillshadeIlluminationAltitude:
return makeStyleProperty(layer.getHillshadeIlluminationAltitude());
case Property::HillshadeIlluminationAnchor:
return makeStyleProperty(layer.getHillshadeIlluminationAnchor());
case Property::HillshadeIlluminationDirection:
return makeStyleProperty(layer.getHillshadeIlluminationDirection());
case Property::HillshadeMethod:
return makeStyleProperty(layer.getHillshadeMethod());
case Property::HillshadeShadowColor:
return makeStyleProperty(layer.getHillshadeShadowColor());
case Property::HillshadeAccentColorTransition:
@@ -288,10 +354,14 @@ StyleProperty getLayerProperty(const HillshadeLayer& layer, Property property) {
return makeStyleProperty(layer.getHillshadeExaggerationTransition());
case Property::HillshadeHighlightColorTransition:
return makeStyleProperty(layer.getHillshadeHighlightColorTransition());
case Property::HillshadeIlluminationAltitudeTransition:
return makeStyleProperty(layer.getHillshadeIlluminationAltitudeTransition());
case Property::HillshadeIlluminationAnchorTransition:
return makeStyleProperty(layer.getHillshadeIlluminationAnchorTransition());
case Property::HillshadeIlluminationDirectionTransition:
return makeStyleProperty(layer.getHillshadeIlluminationDirectionTransition());
case Property::HillshadeMethodTransition:
return makeStyleProperty(layer.getHillshadeMethodTransition());
case Property::HillshadeShadowColorTransition:
return makeStyleProperty(layer.getHillshadeShadowColorTransition());
}
@@ -325,17 +395,31 @@ std::optional<Error> HillshadeLayer::setPropertyInternal(const std::string& name
auto property = static_cast<Property>(it->second);
if (property == Property::HillshadeAccentColor || property == Property::HillshadeHighlightColor ||
property == Property::HillshadeShadowColor) {
if (property == Property::HillshadeAccentColor) {
Error error;
const auto& typedValue = convert<PropertyValue<Color>>(value, error, false, false);
if (!typedValue) {
return error;
}
if (property == Property::HillshadeAccentColor) {
setHillshadeAccentColor(*typedValue);
return std::nullopt;
setHillshadeAccentColor(*typedValue);
return std::nullopt;
}
if (property == Property::HillshadeExaggeration) {
Error error;
const auto& typedValue = convert<PropertyValue<float>>(value, error, false, false);
if (!typedValue) {
return error;
}
setHillshadeExaggeration(*typedValue);
return std::nullopt;
}
if (property == Property::HillshadeHighlightColor || property == Property::HillshadeShadowColor) {
Error error;
const auto& typedValue = convert<PropertyValue<std::vector<Color>>>(value, error, false, false);
if (!typedValue) {
return error;
}
if (property == Property::HillshadeHighlightColor) {
@@ -348,15 +432,15 @@ std::optional<Error> HillshadeLayer::setPropertyInternal(const std::string& name
return std::nullopt;
}
}
if (property == Property::HillshadeExaggeration || property == Property::HillshadeIlluminationDirection) {
if (property == Property::HillshadeIlluminationAltitude || property == Property::HillshadeIlluminationDirection) {
Error error;
const auto& typedValue = convert<PropertyValue<float>>(value, error, false, false);
const auto& typedValue = convert<PropertyValue<std::vector<float>>>(value, error, false, false);
if (!typedValue) {
return error;
}
if (property == Property::HillshadeExaggeration) {
setHillshadeExaggeration(*typedValue);
if (property == Property::HillshadeIlluminationAltitude) {
setHillshadeIlluminationAltitude(*typedValue);
return std::nullopt;
}
@@ -375,6 +459,16 @@ std::optional<Error> HillshadeLayer::setPropertyInternal(const std::string& name
setHillshadeIlluminationAnchor(*typedValue);
return std::nullopt;
}
if (property == Property::HillshadeMethod) {
Error error;
const auto& typedValue = convert<PropertyValue<HillshadeMethodType>>(value, error, false, false);
if (!typedValue) {
return error;
}
setHillshadeMethod(*typedValue);
return std::nullopt;
}
Error error;
std::optional<TransitionOptions> transition = convert<TransitionOptions>(value, error);
@@ -397,6 +491,11 @@ std::optional<Error> HillshadeLayer::setPropertyInternal(const std::string& name
return std::nullopt;
}
if (property == Property::HillshadeIlluminationAltitudeTransition) {
setHillshadeIlluminationAltitudeTransition(*transition);
return std::nullopt;
}
if (property == Property::HillshadeIlluminationAnchorTransition) {
setHillshadeIlluminationAnchorTransition(*transition);
return std::nullopt;
@@ -407,6 +506,11 @@ std::optional<Error> HillshadeLayer::setPropertyInternal(const std::string& name
return std::nullopt;
}
if (property == Property::HillshadeMethodTransition) {
setHillshadeMethodTransition(*transition);
return std::nullopt;
}
if (property == Property::HillshadeShadowColorTransition) {
setHillshadeShadowColorTransition(*transition);
return std::nullopt;

View File

@@ -24,28 +24,38 @@ struct HillshadeExaggeration : PaintProperty<float> {
static float defaultValue() { return 0.5f; }
};
struct HillshadeHighlightColor : PaintProperty<Color> {
static Color defaultValue() { return Color::white(); }
struct HillshadeHighlightColor : PaintProperty<std::vector<Color>> {
static std::vector<Color> defaultValue() { return {Color::white()}; }
};
struct HillshadeIlluminationAltitude : PaintProperty<std::vector<float>> {
static std::vector<float> defaultValue() { return {45.f}; }
};
struct HillshadeIlluminationAnchor : PaintProperty<HillshadeIlluminationAnchorType> {
static HillshadeIlluminationAnchorType defaultValue() { return HillshadeIlluminationAnchorType::Viewport; }
};
struct HillshadeIlluminationDirection : PaintProperty<float> {
static float defaultValue() { return 335.f; }
struct HillshadeIlluminationDirection : PaintProperty<std::vector<float>> {
static std::vector<float> defaultValue() { return {335.f}; }
};
struct HillshadeShadowColor : PaintProperty<Color> {
static Color defaultValue() { return Color::black(); }
struct HillshadeMethod : PaintProperty<HillshadeMethodType> {
static HillshadeMethodType defaultValue() { return HillshadeMethodType::Standard; }
};
struct HillshadeShadowColor : PaintProperty<std::vector<Color>> {
static std::vector<Color> defaultValue() { return {Color::black()}; }
};
class HillshadePaintProperties : public Properties<
HillshadeAccentColor,
HillshadeExaggeration,
HillshadeHighlightColor,
HillshadeIlluminationAltitude,
HillshadeIlluminationAnchor,
HillshadeIlluminationDirection,
HillshadeMethod,
HillshadeShadowColor
> {};

View File

@@ -77,6 +77,9 @@ layerCapabilities['hillshade'] = defaults.require('Source')
.require('Pass3D')
.set('TileKind', 'RasterDEM')
.finalize();
layerCapabilities['color-relief'] = defaults.require('Source')
.set('TileKind', 'RasterDEM')
.finalize();
layerCapabilities['symbol'] = defaults.require('Source')
.require('Layout')
.require('FadingTiles')

View File

@@ -194,7 +194,7 @@ TransitionOptions LocationIndicatorLayer::getAccuracyRadiusColorTransition() con
}
PropertyValue<Rotation> LocationIndicatorLayer::getDefaultBearing() {
return {0};
return {0.f};
}
const PropertyValue<Rotation>& LocationIndicatorLayer::getBearing() const {

View File

@@ -44,7 +44,7 @@ struct AccuracyRadiusColor : PaintProperty<Color> {
};
struct Bearing : PaintProperty<Rotation> {
static Rotation defaultValue() { return 0; }
static Rotation defaultValue() { return 0.f; }
};
struct BearingImageSize : PaintProperty<float> {

View File

@@ -19,7 +19,7 @@ namespace style {
namespace {
LightObserver nullObserver;
}
} // namespace
Light::Light(Immutable<Light::Impl> impl_)
: impl(std::move(impl_)),

View File

@@ -20,7 +20,9 @@
namespace mbgl {
namespace style {
static LightObserver nullObserver;
namespace {
LightObserver nullObserver;
} // namespace
Light::Light(Immutable<Light::Impl> impl_) : impl(std::move(impl_)), observer(&nullObserver) {}

View File

@@ -1,7 +1,7 @@
#include <mbgl/util/color.hpp>
#include <mbgl/util/string.hpp>
#include <csscolorparser/csscolorparser.hpp>
#include <vector>
namespace mbgl {
@@ -23,6 +23,19 @@ std::string Color::stringify() const {
util::toString(array[3]) + ")";
}
mbgl::Value Color::serialize() const {
// Emit as an rgba expression array for expression serialization to avoid
// "Bare objects invalid" parse errors in expression roundtrips.
const auto array = toArray();
return std::vector<mbgl::Value>{
std::string("rgba"),
array[0],
array[1],
array[2],
array[3],
};
}
std::array<double, 4> Color::toArray() const {
if (a == 0) {
return {{0, 0, 0, 0}};
@@ -37,21 +50,11 @@ std::array<double, 4> Color::toArray() const {
}
mbgl::Value Color::toObject() const {
// Return object format for evaluation output
return mapbox::base::ValueObject{{"r", static_cast<double>(r)},
{"g", static_cast<double>(g)},
{"b", static_cast<double>(b)},
{"a", static_cast<double>(a)}};
}
mbgl::Value Color::serialize() const {
std::array<double, 4> array = toArray();
return std::vector<mbgl::Value>{
std::string("rgba"),
array[0],
array[1],
array[2],
array[3],
};
}
} // namespace mbgl

View File

@@ -5,6 +5,8 @@
#include <mbgl/util/color.hpp>
#include <mbgl/util/string.hpp>
#include <vector>
#include <rustutils/color.hpp>
namespace mbgl {
@@ -38,6 +40,7 @@ std::array<double, 4> Color::toArray() const {
}
mbgl::Value Color::toObject() const {
// Return object format for evaluation output
return mapbox::base::ValueObject{{"r", static_cast<double>(r)},
{"g", static_cast<double>(g)},
{"b", static_cast<double>(b)},
@@ -45,7 +48,9 @@ mbgl::Value Color::toObject() const {
}
mbgl::Value Color::serialize() const {
std::array<double, 4> array = toArray();
// Emit as an rgba expression array for expression serialization to avoid
// "Bare objects invalid" parse errors in expression roundtrips.
const auto array = toArray();
return std::vector<mbgl::Value>{
std::string("rgba"),
array[0],

View File

@@ -12,6 +12,7 @@
#include <mbgl/shaders/vulkan/circle.hpp>
#include <mbgl/shaders/vulkan/clipping_mask.hpp>
#include <mbgl/shaders/vulkan/collision.hpp>
#include <mbgl/shaders/vulkan/color_relief.hpp>
#include <mbgl/shaders/vulkan/custom_geometry.hpp>
#include <mbgl/shaders/vulkan/custom_symbol_icon.hpp>
#include <mbgl/shaders/vulkan/debug.hpp>
@@ -679,6 +680,7 @@ void RendererBackend::initShaders(gfx::ShaderRegistry& shaders, const ProgramPar
shaders::BuiltIn::ClippingMaskProgram,
shaders::BuiltIn::CollisionBoxShader,
shaders::BuiltIn::CollisionCircleShader,
shaders::BuiltIn::ColorReliefShader,
shaders::BuiltIn::CustomGeometryShader,
shaders::BuiltIn::CustomSymbolIconShader,
shaders::BuiltIn::DebugShader,

View File

@@ -618,7 +618,8 @@ void Drawable::draw(PaintParameters& parameters) const {
entry.sampler = texture->getSampler();
break;
}
case ShaderProgram::BindingType::Texture: {
case ShaderProgram::BindingType::Texture:
case ShaderProgram::BindingType::UnfilterableTexture: {
Texture2D* texture = findTextureForBinding(bindingInfo.binding, false);
if (!texture) {
validBindings = false;

View File

@@ -110,6 +110,11 @@ RenderPass::RenderPass(CommandEncoder& commandEncoder_, const char* name, const
colorAttachment.clearValue = value;
} else {
colorAttachment.loadOp = WGPULoadOp_Load;
#if MLN_WEBGPU_IMPL_WGPU
// wgpu-native requires clearValue to be set even when using LoadOp_Load
const WGPUColor defaultClearValue{0.0, 0.0, 0.0, 0.0};
colorAttachment.clearValue = defaultClearValue;
#endif
}
WGPURenderPassDepthStencilAttachment depthAttachment = {};

View File

@@ -21,6 +21,7 @@
#include <mbgl/shaders/webgpu/heatmap_texture.hpp>
#include <mbgl/shaders/webgpu/hillshade.hpp>
#include <mbgl/shaders/webgpu/hillshade_prepare.hpp>
#include <mbgl/shaders/webgpu/color_relief.hpp>
#include <mbgl/shaders/webgpu/line.hpp>
#include <mbgl/shaders/webgpu/location_indicator.hpp>
#include <mbgl/shaders/webgpu/raster.hpp>
@@ -108,6 +109,7 @@ void RendererBackend::initShaders(gfx::ShaderRegistry& registry, const ProgramPa
shaders::BuiltIn::HeatmapTextureShader,
shaders::BuiltIn::HillshadeShader,
shaders::BuiltIn::HillshadePrepareShader,
shaders::BuiltIn::ColorReliefShader,
shaders::BuiltIn::LineShader,
shaders::BuiltIn::LineGradientShader,
shaders::BuiltIn::LinePatternShader,