[core] Add line-gradient property

Porting of https://github.com/mapbox/mapbox-gl-js/pull/6303
See the link above for the description of the feature and
its limitations).

Based on patch from @lbud (Lauren Budorick).
This commit is contained in:
Mikhail Pozdnyakov
2018-08-08 15:09:27 +03:00
parent 52275f835a
commit fb5afd34b9
36 changed files with 1897 additions and 1500 deletions

View File

@@ -316,6 +316,8 @@ src/mbgl/shaders/hillshade_prepare.cpp
src/mbgl/shaders/hillshade_prepare.hpp
src/mbgl/shaders/line.cpp
src/mbgl/shaders/line.hpp
src/mbgl/shaders/line_gradient.cpp
src/mbgl/shaders/line_gradient.hpp
src/mbgl/shaders/line_pattern.cpp
src/mbgl/shaders/line_pattern.hpp
src/mbgl/shaders/line_sdf.cpp

View File

@@ -7,7 +7,7 @@
#pragma once
<% if (type === 'heatmap') { -%>
<% if (type === 'heatmap' || type === 'line') { -%>
#include <mbgl/style/color_ramp_property_value.hpp>
<% } -%>
#include <mbgl/style/layer.hpp>

View File

@@ -2,6 +2,7 @@
#pragma once
#include <mbgl/style/color_ramp_property_value.hpp>
#include <mbgl/style/layer.hpp>
#include <mbgl/style/filter.hpp>
#include <mbgl/style/property_value.hpp>
@@ -119,6 +120,12 @@ public:
void setLinePatternTransition(const TransitionOptions&);
TransitionOptions getLinePatternTransition() const;
static ColorRampPropertyValue getDefaultLineGradient();
ColorRampPropertyValue getLineGradient() const;
void setLineGradient(ColorRampPropertyValue);
void setLineGradientTransition(const TransitionOptions&);
TransitionOptions getLineGradientTransition() const;
// Private implementation
class Impl;

View File

@@ -478,6 +478,34 @@ public class LineLayer extends Layer {
nativeSetLinePatternTransition(options.getDuration(), options.getDelay());
}
/**
* Get the LineGradient property
*
* @return property wrapper value around String
*/
@SuppressWarnings("unchecked")
public PropertyValue<String> getLineGradient() {
checkThread();
return (PropertyValue<String>) new PropertyValue("line-gradient", nativeGetLineGradient());
}
/**
* Defines a gradient with which to color a line feature. Can only be used with GeoJSON sources that specify `"lineMetrics": true`.
*
* @return int representation of a rgba string color
* @throws RuntimeException thrown if property isn't a value
*/
@ColorInt
public int getLineGradientAsInt() {
checkThread();
PropertyValue<String> value = getLineGradient();
if (value.isValue()) {
return rgbaToColor(value.getValue());
} else {
throw new RuntimeException("line-gradient was set as a Function");
}
}
@Keep
private native Object nativeGetLineCap();
@@ -574,6 +602,9 @@ public class LineLayer extends Layer {
@Keep
private native void nativeSetLinePatternTransition(long duration, long delay);
@Keep
private native Object nativeGetLineGradient();
@Override
@Keep
protected native void finalize() throws Throwable;

View File

@@ -394,6 +394,36 @@ public class PropertyFactory {
return new PaintPropertyValue<>("line-pattern", expression);
}
/**
* Defines a gradient with which to color a line feature. Can only be used with GeoJSON sources that specify `"lineMetrics": true`.
*
* @param value a int color value
* @return property wrapper around String color
*/
public static PropertyValue<String> lineGradient(@ColorInt int value) {
return new PaintPropertyValue<>("line-gradient", colorToRgbaString(value));
}
/**
* Defines a gradient with which to color a line feature. Can only be used with GeoJSON sources that specify `"lineMetrics": true`.
*
* @param value a String value
* @return property wrapper around String
*/
public static PropertyValue<String> lineGradient(String value) {
return new PaintPropertyValue<>("line-gradient", value);
}
/**
* Defines a gradient with which to color a line feature. Can only be used with GeoJSON sources that specify `"lineMetrics": true`.
*
* @param expression an expression statement
* @return property wrapper around an expression statement
*/
public static PropertyValue<Expression> lineGradient(Expression expression) {
return new PaintPropertyValue<>("line-gradient", expression);
}
/**
* The opacity at which the icon will be drawn.
*

View File

@@ -118,7 +118,7 @@ public class <%- camelize(type) %>LayerTest extends BaseActivityTest {
<% } -%>
<% for (const property of properties) { -%>
<% if (property.name != 'heatmap-color') { -%>
<% if (property['property-type'] !== 'color-ramp') { -%>
<% if (property.transition) { -%>
@Test

View File

@@ -236,6 +236,12 @@ namespace android {
layer.as<mbgl::style::LineLayer>()->LineLayer::setLinePatternTransition(options);
}
jni::Object<jni::ObjectTag> LineLayer::getLineGradient(jni::JNIEnv& env) {
using namespace mbgl::android::conversion;
Result<jni::jobject*> converted = convert<jni::jobject*>(env, layer.as<mbgl::style::LineLayer>()->LineLayer::getLineGradient());
return jni::Object<jni::ObjectTag>(*converted);
}
jni::Class<LineLayer> LineLayer::javaClass;
@@ -287,7 +293,8 @@ namespace android {
METHOD(&LineLayer::getLineDasharray, "nativeGetLineDasharray"),
METHOD(&LineLayer::getLinePatternTransition, "nativeGetLinePatternTransition"),
METHOD(&LineLayer::setLinePatternTransition, "nativeSetLinePatternTransition"),
METHOD(&LineLayer::getLinePattern, "nativeGetLinePattern"));
METHOD(&LineLayer::getLinePattern, "nativeGetLinePattern"),
METHOD(&LineLayer::getLineGradient, "nativeGetLineGradient"));
}
} // namespace android

View File

@@ -74,6 +74,8 @@ public:
jni::Object<jni::ObjectTag> getLinePattern(jni::JNIEnv&);
void setLinePatternTransition(jni::JNIEnv&, jlong duration, jlong delay);
jni::Object<TransitionOptions> getLinePatternTransition(jni::JNIEnv&);
jni::Object<jni::ObjectTag> getLineGradient(jni::JNIEnv&);
jni::jobject* createJavaPeer(jni::JNIEnv&);
}; // class LineLayer

View File

@@ -367,6 +367,8 @@ global.propertyReqs = function (property, propertiesByName, type) {
return '`' + camelizeWithLeadingLowercase(req['!']) + '` is set to `nil`';
} else {
let name = Object.keys(req)[0];
if (name === 'source')
return 'the data source requirements are met';
return '`' + camelizeWithLeadingLowercase(name) + '` is set to an expression that evaluates to ' + describeValue(req[name], propertiesByName[name], type);
}
}).join(', and ') + '. Otherwise, it is ignored.';

View File

@@ -366,6 +366,50 @@ MGL_EXPORT
*/
@property (nonatomic) MGLTransition lineGapWidthTransition;
#if TARGET_OS_IPHONE
/**
Defines a gradient with which to color a line feature. Can only be used with
GeoJSON sources that specify `"lineMetrics": true`.
This property is only applied to the style if `lineDasharray` is set to `nil`,
and `linePattern` is set to `nil`, and the data source requirements are met.
Otherwise, it is ignored.
You can set this property to an expression containing any of the following:
* Constant `UIColor` values
* Predefined functions, including mathematical and string operators
* Conditional expressions
* Variable assignments and references to assigned variables
* Interpolation and step functions applied to the `$lineProgress` variable
This property does not support applying interpolation or step functions to
feature attributes.
*/
@property (nonatomic, null_resettable) NSExpression *lineGradient;
#else
/**
Defines a gradient with which to color a line feature. Can only be used with
GeoJSON sources that specify `"lineMetrics": true`.
This property is only applied to the style if `lineDasharray` is set to `nil`,
and `linePattern` is set to `nil`, and the data source requirements are met.
Otherwise, it is ignored.
You can set this property to an expression containing any of the following:
* Constant `NSColor` values
* Predefined functions, including mathematical and string operators
* Conditional expressions
* Variable assignments and references to assigned variables
* Interpolation and step functions applied to the `$lineProgress` variable
This property does not support applying interpolation or step functions to
feature attributes.
*/
@property (nonatomic, null_resettable) NSExpression *lineGradient;
#endif
/**
The line's offset. For linear features, a positive value offsets the line to
the right, relative to the direction of the line, and a negative value to the

View File

@@ -306,6 +306,23 @@ namespace mbgl {
return transition;
}
- (void)setLineGradient:(NSExpression *)lineGradient {
MGLAssertStyleLayerIsValid();
auto mbglValue = MGLStyleValueTransformer<mbgl::Color, MGLColor *>().toPropertyValue<mbgl::style::ColorRampPropertyValue>(lineGradient);
self.rawLayer->setLineGradient(mbglValue);
}
- (NSExpression *)lineGradient {
MGLAssertStyleLayerIsValid();
auto propertyValue = self.rawLayer->getLineGradient();
if (propertyValue.isUndefined()) {
propertyValue = self.rawLayer->getDefaultLineGradient();
}
return MGLStyleValueTransformer<mbgl::Color, MGLColor *>().toExpression(propertyValue);
}
- (void)setLineOffset:(NSExpression *)lineOffset {
MGLAssertStyleLayerIsValid();

View File

@@ -169,7 +169,7 @@ namespace mbgl {
<% switch (property['property-type']) {
case 'color-ramp': -%>
auto mbglValue = MGLStyleValueTransformer<mbgl::Color, MGLColor *>().toPropertyValue<mbgl::style::ColorRampPropertyValue>(heatmapColor);
auto mbglValue = MGLStyleValueTransformer<mbgl::Color, MGLColor *>().toPropertyValue<mbgl::style::ColorRampPropertyValue>(<%- objCName(property) %>);
<% break
case 'data-driven':
case 'cross-faded-data-driven': -%>

View File

@@ -43,8 +43,6 @@
"render-tests/geojson/inline-polygon-symbol": "behavior needs reconciliation with gl-js",
"render-tests/icon-rotate/with-offset": "https://github.com/mapbox/mapbox-gl-native/issues/11872",
"render-tests/icon-no-cross-source-collision/default": "skip - gl-js only",
"render-tests/line-gradient/gradient": "https://github.com/mapbox/mapbox-gl-native/issues/11718",
"render-tests/line-gradient/translucent": "https://github.com/mapbox/mapbox-gl-native/issues/11718",
"render-tests/mixed-zoom/z10-z11": "https://github.com/mapbox/mapbox-gl-native/issues/10397",
"render-tests/raster-masking/overlapping-zoom": "https://github.com/mapbox/mapbox-gl-native/issues/10195",
"render-tests/real-world/bangkok": "https://github.com/mapbox/mapbox-gl-native/issues/10412",

View File

@@ -8,8 +8,6 @@ const zlib = require('zlib');
var shaders = require('../mapbox-gl-js/src/shaders');
delete shaders.lineGradient;
require('./style-code');
let concatenated = '';

View File

@@ -114,7 +114,7 @@ global.defaultValue = function (property) {
return '{}';
}
if (property.name === 'heatmap-color') {
if (property['property-type'] === 'color-ramp') {
return '{}';
}

View File

@@ -1,4 +1,3 @@
var spec = module.exports = require('../mapbox-gl-js/src/style-spec/reference/v8');
// Make temporary modifications here when Native doesn't have all features that JS has.
delete spec.paint_line['line-gradient'];

View File

@@ -116,4 +116,18 @@ LinePatternProgram::uniformValues(const RenderLinePaintProperties::PossiblyEvalu
);
}
LineGradientProgram::UniformValues
LineGradientProgram::uniformValues(const RenderLinePaintProperties::PossiblyEvaluated& properties,
const RenderTile& tile,
const TransformState& state,
const std::array<float, 2>& pixelsToGLUnits) {
return makeValues<LineGradientProgram::UniformValues>(
properties,
tile,
state,
pixelsToGLUnits,
uniforms::u_image::Value{ 0 }
);
}
} // namespace mbgl

View File

@@ -4,6 +4,7 @@
#include <mbgl/programs/attributes.hpp>
#include <mbgl/programs/uniforms.hpp>
#include <mbgl/shaders/line.hpp>
#include <mbgl/shaders/line_gradient.hpp>
#include <mbgl/shaders/line_pattern.hpp>
#include <mbgl/shaders/line_sdf.hpp>
#include <mbgl/util/geometry.hpp>
@@ -159,6 +160,26 @@ public:
float atlasWidth);
};
class LineGradientProgram : public Program<
shaders::line_gradient,
gl::Triangle,
LineLayoutAttributes,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_ratio,
uniforms::u_gl_units_to_pixels,
uniforms::u_image>,
RenderLinePaintProperties>
{
public:
using Program::Program;
static UniformValues uniformValues(const RenderLinePaintProperties::PossiblyEvaluated&,
const RenderTile&,
const TransformState&,
const std::array<float, 2>& pixelsToGLUnits);
};
using LineLayoutVertex = LineProgram::LayoutVertex;
using LineAttributes = LineProgram::Attributes;

View File

@@ -37,6 +37,7 @@ public:
hillshade(context, programParameters),
hillshadePrepare(context, programParameters),
line(context, programParameters),
lineGradient(context, programParameters),
lineSDF(context, programParameters),
linePattern(context, programParameters),
raster(context, programParameters),
@@ -64,6 +65,7 @@ public:
HillshadeProgram hillshade;
HillshadePrepareProgram hillshadePrepare;
ProgramMap<LineProgram> line;
ProgramMap<LineGradientProgram> lineGradient;
ProgramMap<LineSDFProgram> lineSDF;
ProgramMap<LinePatternProgram> linePattern;
RasterProgram raster;

View File

@@ -64,6 +64,27 @@ const float LINE_DISTANCE_SCALE = 1.0 / 2.0;
// The maximum line distance, in tile units, that fits in the buffer.
const float MAX_LINE_DISTANCE = std::pow(2, LINE_DISTANCE_BUFFER_BITS) / LINE_DISTANCE_SCALE;
class LineBucket::Distances {
public:
Distances(double clipStart_, double clipEnd_, double total_)
: clipStart(clipStart_), clipEnd(clipEnd_), total(total_) {}
// Scale line distance from tile units to [0, 2^15).
double scaleToMaxLineDistance(double tileDistance) const {
double relativeTileDistance = tileDistance / total;
if (std::isinf(relativeTileDistance) || std::isnan(relativeTileDistance)) {
assert(false);
relativeTileDistance = 0.0;
}
return (relativeTileDistance * (clipEnd - clipStart) + clipStart) * (MAX_LINE_DISTANCE - 1);
}
private:
double clipStart;
double clipEnd;
double total;
};
void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const GeometryTileFeature& feature) {
const FeatureType type = feature.getType();
const std::size_t len = [&coordinates] {
@@ -89,6 +110,22 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const Geome
return;
}
optional<Distances> lineDistances;
const auto &props = feature.getProperties();
auto clip_start_it = props.find("mapbox_clip_start");
auto clip_end_it = props.find("mapbox_clip_end");
if (clip_start_it != props.end() && clip_end_it != props.end()) {
double total_length = 0.0;
for (std::size_t i = first; i < len - 1; ++i) {
total_length += util::dist<double>(coordinates[i], coordinates[i + 1]);
}
lineDistances = Distances{*numericValue<double>(clip_start_it->second),
*numericValue<double>(clip_end_it->second),
total_length};
}
const LineJoinType joinType = layout.evaluate<LineJoin>(zoom, feature);
const float miterLimit = joinType == LineJoinType::Bevel ? 1.05f : float(layout.get<LineMiterLimit>());
@@ -99,7 +136,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const Geome
const LineCapType beginCap = layout.get<LineCap>();
const LineCapType endCap = type == FeatureType::Polygon ? LineCapType::Butt : LineCapType(layout.get<LineCap>());
double distance = 0;
double distance = 0.0;
bool startOfLine = true;
optional<GeometryCoordinate> currentCoordinate;
optional<GeometryCoordinate> prevCoordinate;
@@ -191,7 +228,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const Geome
if (prevSegmentLength > 2.0 * sharpCornerOffset) {
GeometryCoordinate newPrevVertex = *currentCoordinate - convertPoint<int16_t>(util::round(convertPoint<double>(*currentCoordinate - *prevCoordinate) * (sharpCornerOffset / prevSegmentLength)));
distance += util::dist<double>(newPrevVertex, *prevCoordinate);
addCurrentVertex(newPrevVertex, distance, *prevNormal, 0, 0, false, startVertex, triangleStore);
addCurrentVertex(newPrevVertex, distance, *prevNormal, 0, 0, false, startVertex, triangleStore, lineDistances);
prevCoordinate = newPrevVertex;
}
}
@@ -236,7 +273,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const Geome
if (middleVertex && currentJoin == LineJoinType::Miter) {
joinNormal = joinNormal * miterLength;
addCurrentVertex(*currentCoordinate, distance, joinNormal, 0, 0, false, startVertex,
triangleStore);
triangleStore, lineDistances);
} else if (middleVertex && currentJoin == LineJoinType::FlipBevel) {
// miter is too big, flip the direction to make a beveled join
@@ -252,10 +289,10 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const Geome
}
addCurrentVertex(*currentCoordinate, distance, joinNormal, 0, 0, false, startVertex,
triangleStore);
triangleStore, lineDistances);
addCurrentVertex(*currentCoordinate, distance, joinNormal * -1.0, 0, 0, false, startVertex,
triangleStore);
triangleStore, lineDistances);
} else if (middleVertex && (currentJoin == LineJoinType::Bevel || currentJoin == LineJoinType::FakeRound)) {
const bool lineTurnsLeft = (prevNormal->x * nextNormal->y - prevNormal->y * nextNormal->x) > 0;
const float offset = -std::sqrt(miterLength * miterLength - 1);
@@ -273,7 +310,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const Geome
// Close previous segement with bevel
if (!startOfLine) {
addCurrentVertex(*currentCoordinate, distance, *prevNormal, offsetA, offsetB, false,
startVertex, triangleStore);
startVertex, triangleStore, lineDistances);
}
if (currentJoin == LineJoinType::FakeRound) {
@@ -288,41 +325,41 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const Geome
for (int m = 0; m < n; m++) {
auto approxFractionalJoinNormal = util::unit(*nextNormal * ((m + 1.0) / (n + 1.0)) + *prevNormal);
addPieSliceVertex(*currentCoordinate, distance, approxFractionalJoinNormal, lineTurnsLeft, startVertex, triangleStore);
addPieSliceVertex(*currentCoordinate, distance, approxFractionalJoinNormal, lineTurnsLeft, startVertex, triangleStore, lineDistances);
}
addPieSliceVertex(*currentCoordinate, distance, joinNormal, lineTurnsLeft, startVertex, triangleStore);
addPieSliceVertex(*currentCoordinate, distance, joinNormal, lineTurnsLeft, startVertex, triangleStore, lineDistances);
for (int k = n - 1; k >= 0; k--) {
auto approxFractionalJoinNormal = util::unit(*prevNormal * ((k + 1.0) / (n + 1.0)) + *nextNormal);
addPieSliceVertex(*currentCoordinate, distance, approxFractionalJoinNormal, lineTurnsLeft, startVertex, triangleStore);
addPieSliceVertex(*currentCoordinate, distance, approxFractionalJoinNormal, lineTurnsLeft, startVertex, triangleStore, lineDistances);
}
}
// Start next segment
if (nextCoordinate) {
addCurrentVertex(*currentCoordinate, distance, *nextNormal, -offsetA, -offsetB,
false, startVertex, triangleStore);
false, startVertex, triangleStore, lineDistances);
}
} else if (!middleVertex && currentCap == LineCapType::Butt) {
if (!startOfLine) {
// Close previous segment with a butt
addCurrentVertex(*currentCoordinate, distance, *prevNormal, 0, 0, false,
startVertex, triangleStore);
startVertex, triangleStore, lineDistances);
}
// Start next segment with a butt
if (nextCoordinate) {
addCurrentVertex(*currentCoordinate, distance, *nextNormal, 0, 0, false,
startVertex, triangleStore);
startVertex, triangleStore, lineDistances);
}
} else if (!middleVertex && currentCap == LineCapType::Square) {
if (!startOfLine) {
// Close previous segment with a square cap
addCurrentVertex(*currentCoordinate, distance, *prevNormal, 1, 1, false,
startVertex, triangleStore);
startVertex, triangleStore, lineDistances);
// The segment is done. Unset vertices to disconnect segments.
e1 = e2 = -1;
@@ -331,18 +368,18 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const Geome
// Start next segment
if (nextCoordinate) {
addCurrentVertex(*currentCoordinate, distance, *nextNormal, -1, -1, false,
startVertex, triangleStore);
startVertex, triangleStore, lineDistances);
}
} else if (middleVertex ? currentJoin == LineJoinType::Round : currentCap == LineCapType::Round) {
if (!startOfLine) {
// Close previous segment with a butt
addCurrentVertex(*currentCoordinate, distance, *prevNormal, 0, 0, false,
startVertex, triangleStore);
startVertex, triangleStore, lineDistances);
// Add round cap or linejoin at end of segment
addCurrentVertex(*currentCoordinate, distance, *prevNormal, 1, 1, true, startVertex,
triangleStore);
triangleStore, lineDistances);
// The segment is done. Unset vertices to disconnect segments.
e1 = e2 = -1;
@@ -352,10 +389,10 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const Geome
if (nextCoordinate) {
// Add round cap before first segment
addCurrentVertex(*currentCoordinate, distance, *nextNormal, -1, -1, true,
startVertex, triangleStore);
startVertex, triangleStore, lineDistances);
addCurrentVertex(*currentCoordinate, distance, *nextNormal, 0, 0, false,
startVertex, triangleStore);
startVertex, triangleStore, lineDistances);
}
}
@@ -364,7 +401,7 @@ void LineBucket::addGeometry(const GeometryCoordinates& coordinates, const Geome
if (nextSegmentLength > 2 * sharpCornerOffset) {
GeometryCoordinate newCurrentVertex = *currentCoordinate + convertPoint<int16_t>(util::round(convertPoint<double>(*nextCoordinate - *currentCoordinate) * (sharpCornerOffset / nextSegmentLength)));
distance += util::dist<double>(newCurrentVertex, *currentCoordinate);
addCurrentVertex(newCurrentVertex, distance, *nextNormal, 0, 0, false, startVertex, triangleStore);
addCurrentVertex(newCurrentVertex, distance, *nextNormal, 0, 0, false, startVertex, triangleStore, lineDistances);
currentCoordinate = newCurrentVertex;
}
}
@@ -398,11 +435,14 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate,
double endRight,
bool round,
std::size_t startVertex,
std::vector<TriangleElement>& triangleStore) {
std::vector<TriangleElement>& triangleStore,
optional<Distances> lineDistances) {
Point<double> extrude = normal;
double scaledDistance = lineDistances ? lineDistances->scaleToMaxLineDistance(distance) : distance;
if (endLeft)
extrude = extrude - (util::perp(normal) * endLeft);
vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, round, false, endLeft, distance * LINE_DISTANCE_SCALE));
vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, round, false, endLeft, scaledDistance * LINE_DISTANCE_SCALE));
e3 = vertices.vertexSize() - 1 - startVertex;
if (e1 >= 0 && e2 >= 0) {
triangleStore.emplace_back(e1, e2, e3);
@@ -413,7 +453,7 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate,
extrude = normal * -1.0;
if (endRight)
extrude = extrude - (util::perp(normal) * endRight);
vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, round, true, -endRight, distance * LINE_DISTANCE_SCALE));
vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, round, true, -endRight, scaledDistance * LINE_DISTANCE_SCALE));
e3 = vertices.vertexSize() - 1 - startVertex;
if (e1 >= 0 && e2 >= 0) {
triangleStore.emplace_back(e1, e2, e3);
@@ -425,9 +465,9 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate,
// When we get close to the distance, reset it to zero and add the vertex again with
// a distance of zero. The max distance is determined by the number of bits we allocate
// to `linesofar`.
if (distance > MAX_LINE_DISTANCE / 2.0f) {
distance = 0;
addCurrentVertex(currentCoordinate, distance, normal, endLeft, endRight, round, startVertex, triangleStore);
if (distance > MAX_LINE_DISTANCE / 2.0f && !lineDistances) {
distance = 0.0;
addCurrentVertex(currentCoordinate, distance, normal, endLeft, endRight, round, startVertex, triangleStore, lineDistances);
}
}
@@ -436,8 +476,13 @@ void LineBucket::addPieSliceVertex(const GeometryCoordinate& currentVertex,
const Point<double>& extrude,
bool lineTurnsLeft,
std::size_t startVertex,
std::vector<TriangleElement>& triangleStore) {
std::vector<TriangleElement>& triangleStore,
optional<Distances> lineDistances) {
Point<double> flippedExtrude = extrude * (lineTurnsLeft ? -1.0 : 1.0);
if (lineDistances) {
distance = lineDistances->scaleToMaxLineDistance(distance);
}
vertices.emplace_back(LineProgram::layoutVertex(currentVertex, flippedExtrude, false, lineTurnsLeft, 0, distance * LINE_DISTANCE_SCALE));
e3 = vertices.vertexSize() - 1 - startVertex;
if (e1 >= 0 && e2 >= 0) {

View File

@@ -47,12 +47,17 @@ private:
TriangleElement(uint16_t a_, uint16_t b_, uint16_t c_) : a(a_), b(b_), c(c_) {}
uint16_t a, b, c;
};
class Distances;
void addCurrentVertex(const GeometryCoordinate& currentVertex, double& distance,
const Point<double>& normal, double endLeft, double endRight, bool round,
std::size_t startVertex, std::vector<LineBucket::TriangleElement>& triangleStore);
std::size_t startVertex, std::vector<LineBucket::TriangleElement>& triangleStore,
optional<Distances> distances);
void addPieSliceVertex(const GeometryCoordinate& currentVertex, double distance,
const Point<double>& extrude, bool lineTurnsLeft, std::size_t startVertex,
std::vector<TriangleElement>& triangleStore);
std::vector<TriangleElement>& triangleStore,
optional<Distances> distances);
std::ptrdiff_t e1;
std::ptrdiff_t e2;

View File

@@ -18,7 +18,8 @@ using namespace style;
RenderLineLayer::RenderLineLayer(Immutable<style::LineLayer::Impl> _impl)
: RenderLayer(style::LayerType::Line, _impl),
unevaluated(impl().paint.untransitioned()) {
unevaluated(impl().paint.untransitioned()),
colorRamp({256, 1}) {
}
const style::LineLayer::Impl& RenderLineLayer::impl() const {
@@ -134,7 +135,18 @@ void RenderLineLayer::render(PaintParameters& parameters, RenderSource*) {
parameters.imageManager.getPixelSize(),
*posA,
*posB));
} else if (!unevaluated.get<LineGradient>().getValue().isUndefined()) {
if (!colorRampTexture) {
colorRampTexture = parameters.context.createTexture(colorRamp);
}
parameters.context.bindTexture(*colorRampTexture, 0, gl::TextureFilter::Linear);
draw(parameters.programs.lineGradient,
LineGradientProgram::uniformValues(
evaluated,
tile,
parameters.state,
parameters.pixelsToGLUnits));
} else {
draw(parameters.programs.line,
LineProgram::uniformValues(
@@ -207,6 +219,27 @@ bool RenderLineLayer::queryIntersectsFeature(
halfWidth);
}
void RenderLineLayer::updateColorRamp() {
auto colorValue = unevaluated.get<LineGradient>().getValue();
if (colorValue.isUndefined()) {
return;
}
const auto length = colorRamp.bytes();
for (uint32_t i = 0; i < length; i += 4) {
const auto color = colorValue.evaluate(static_cast<double>(i) / length);
colorRamp.data[i] = std::floor(color.r * 255);
colorRamp.data[i + 1] = std::floor(color.g * 255);
colorRamp.data[i + 2] = std::floor(color.b * 255);
colorRamp.data[i + 3] = std::floor(color.a * 255);
}
if (colorRampTexture) {
colorRampTexture = nullopt;
}
}
float RenderLineLayer::getLineWidth(const GeometryTileFeature& feature, const float zoom) const {
float lineWidth = evaluated.get<style::LineWidth>()
.evaluate(feature, zoom, style::LineWidth::defaultValue());

View File

@@ -4,6 +4,7 @@
#include <mbgl/style/layers/line_layer_impl.hpp>
#include <mbgl/style/layers/line_layer_properties.hpp>
#include <mbgl/programs/uniforms.hpp>
#include <mbgl/util/image.hpp>
namespace mbgl {
@@ -33,6 +34,8 @@ public:
const float,
const mat4&) const override;
void updateColorRamp();
std::unique_ptr<Bucket> createBucket(const BucketParameters&, const std::vector<const RenderLayer*>&) const override;
// Paint properties
@@ -43,6 +46,8 @@ public:
private:
float getLineWidth(const GeometryTileFeature&, const float) const;
PremultipliedImage colorRamp;
optional<gl::Texture> colorRampTexture;
};
template <>

View File

@@ -189,6 +189,10 @@ void Renderer::Impl::render(const UpdateParameters& updateParameters) {
if (layer.is<RenderHeatmapLayer>()) {
layer.as<RenderHeatmapLayer>()->updateColorRamp();
}
if (layer.is<RenderLineLayer>()) {
layer.as<RenderLineLayer>()->updateColorRamp();
}
}
if (layerAdded || layerChanged || zoomChanged || layer.hasTransition()) {

View File

@@ -0,0 +1,14 @@
// NOTE: DO NOT CHANGE THIS FILE. IT IS AUTOMATICALLY GENERATED.
#include <mbgl/shaders/line_gradient.hpp>
#include <mbgl/shaders/source.hpp>
namespace mbgl {
namespace shaders {
const char* line_gradient::name = "line_gradient";
const char* line_gradient::vertexSource = source() + 43378;
const char* line_gradient::fragmentSource = source() + 47687;
} // namespace shaders
} // namespace mbgl

View File

@@ -0,0 +1,16 @@
// NOTE: DO NOT CHANGE THIS FILE. IT IS AUTOMATICALLY GENERATED.
#pragma once
namespace mbgl {
namespace shaders {
class line_gradient {
public:
static const char* name;
static const char* vertexSource;
static const char* fragmentSource;
};
} // namespace shaders
} // namespace mbgl

View File

@@ -7,8 +7,8 @@ namespace mbgl {
namespace shaders {
const char* line_pattern::name = "line_pattern";
const char* line_pattern::vertexSource = source() + 43378;
const char* line_pattern::fragmentSource = source() + 47787;
const char* line_pattern::vertexSource = source() + 48972;
const char* line_pattern::fragmentSource = source() + 53381;
} // namespace shaders
} // namespace mbgl

View File

@@ -7,8 +7,8 @@ namespace mbgl {
namespace shaders {
const char* line_sdf::name = "line_sdf";
const char* line_sdf::vertexSource = source() + 50098;
const char* line_sdf::fragmentSource = source() + 55464;
const char* line_sdf::vertexSource = source() + 55692;
const char* line_sdf::fragmentSource = source() + 61058;
} // namespace shaders
} // namespace mbgl

View File

@@ -7,8 +7,8 @@ namespace mbgl {
namespace shaders {
const char* raster::name = "raster";
const char* raster::vertexSource = source() + 57390;
const char* raster::fragmentSource = source() + 58203;
const char* raster::vertexSource = source() + 62984;
const char* raster::fragmentSource = source() + 63797;
} // namespace shaders
} // namespace mbgl

File diff suppressed because it is too large Load Diff

View File

@@ -7,8 +7,8 @@ namespace mbgl {
namespace shaders {
const char* symbol_icon::name = "symbol_icon";
const char* symbol_icon::vertexSource = source() + 59607;
const char* symbol_icon::fragmentSource = source() + 63013;
const char* symbol_icon::vertexSource = source() + 65201;
const char* symbol_icon::fragmentSource = source() + 68607;
} // namespace shaders
} // namespace mbgl

View File

@@ -7,8 +7,8 @@ namespace mbgl {
namespace shaders {
const char* symbol_sdf::name = "symbol_sdf";
const char* symbol_sdf::vertexSource = source() + 63463;
const char* symbol_sdf::fragmentSource = source() + 69386;
const char* symbol_sdf::vertexSource = source() + 69057;
const char* symbol_sdf::fragmentSource = source() + 74980;
} // namespace shaders
} // namespace mbgl

View File

@@ -352,6 +352,15 @@ std::unordered_map<std::string, CompoundExpressionRegistry::Definition> initiali
return *(params.colorRampParameter);
});
define("line-progress", [](const EvaluationContext& params) -> Result<double> {
if (!params.colorRampParameter) {
return EvaluationError {
"The 'line-progress' expression is unavailable in the current evaluation context."
};
}
return *(params.colorRampParameter);
});
define("has", [](const EvaluationContext& params, const std::string& key) -> Result<bool> {
if (!params.feature) {
return EvaluationError {

View File

@@ -69,7 +69,8 @@ bool isConstant(const Expression& expression) {
}
return isFeatureConstant(expression) &&
isGlobalPropertyConstant(expression, std::array<std::string, 2>{{"zoom", "heatmap-density"}});
isGlobalPropertyConstant(expression, std::array<std::string, 2>{{"zoom", "heatmap-density"}}) &&
isGlobalPropertyConstant(expression, std::array<std::string, 2>{{"zoom", "line-progress"}});
}
using namespace mbgl::style::conversion;

View File

@@ -438,6 +438,33 @@ TransitionOptions LineLayer::getLinePatternTransition() const {
return impl().paint.template get<LinePattern>().options;
}
ColorRampPropertyValue LineLayer::getDefaultLineGradient() {
return { {} };
}
ColorRampPropertyValue LineLayer::getLineGradient() const {
return impl().paint.template get<LineGradient>().value;
}
void LineLayer::setLineGradient(ColorRampPropertyValue value) {
if (value == getLineGradient())
return;
auto impl_ = mutableImpl();
impl_->paint.template get<LineGradient>().value = value;
baseImpl = std::move(impl_);
observer->onLayerChanged(*this);
}
void LineLayer::setLineGradientTransition(const TransitionOptions& options) {
auto impl_ = mutableImpl();
impl_->paint.template get<LineGradient>().options = options;
baseImpl = std::move(impl_);
}
TransitionOptions LineLayer::getLineGradientTransition() const {
return impl().paint.template get<LineGradient>().options;
}
using namespace conversion;
optional<Error> LineLayer::setPaintProperty(const std::string& name, const Convertible& value) {
@@ -453,6 +480,7 @@ optional<Error> LineLayer::setPaintProperty(const std::string& name, const Conve
LineBlur,
LineDasharray,
LinePattern,
LineGradient,
LineOpacityTransition,
LineColorTransition,
LineTranslateTransition,
@@ -463,6 +491,7 @@ optional<Error> LineLayer::setPaintProperty(const std::string& name, const Conve
LineBlurTransition,
LineDasharrayTransition,
LinePatternTransition,
LineGradientTransition,
};
Property property = Property::Unknown;
@@ -567,6 +596,16 @@ optional<Error> LineLayer::setPaintProperty(const std::string& name, const Conve
property = Property::LinePatternTransition;
}
break;
case util::hashFNV1a("line-gradient"):
if (name == "line-gradient") {
property = Property::LineGradient;
}
break;
case util::hashFNV1a("line-gradient-transition"):
if (name == "line-gradient-transition") {
property = Property::LineGradientTransition;
}
break;
}
@@ -669,6 +708,18 @@ optional<Error> LineLayer::setPaintProperty(const std::string& name, const Conve
}
if (property == Property::LineGradient) {
Error error;
optional<ColorRampPropertyValue> typedValue = convert<ColorRampPropertyValue>(value, error, false, false);
if (!typedValue) {
return error;
}
setLineGradient(*typedValue);
return nullopt;
}
Error error;
optional<TransitionOptions> transition = convert<TransitionOptions>(value, error);
@@ -726,6 +777,11 @@ optional<Error> LineLayer::setPaintProperty(const std::string& name, const Conve
return nullopt;
}
if (property == Property::LineGradientTransition) {
setLineGradientTransition(*transition);
return nullopt;
}
return Error { "layer doesn't support this property" };
}

View File

@@ -72,6 +72,9 @@ struct LinePattern : CrossFadedPaintProperty<std::string> {
static std::string defaultValue() { return ""; }
};
struct LineGradient : ColorRampProperty {
};
class LineLayoutProperties : public Properties<
LineCap,
LineJoin,
@@ -89,7 +92,8 @@ class LinePaintProperties : public Properties<
LineOffset,
LineBlur,
LineDasharray,
LinePattern
LinePattern,
LineGradient
> {};
} // namespace style