[core] Add support for data-driven styling

This commit is contained in:
John Firebaugh
2016-10-28 16:39:50 -07:00
parent 6a6bddb453
commit 141e995806
149 changed files with 3464 additions and 1288 deletions

View File

@@ -70,11 +70,13 @@ set(MBGL_CORE_FILES
src/mbgl/gl/framebuffer.hpp
src/mbgl/gl/gl.cpp
src/mbgl/gl/index_buffer.hpp
src/mbgl/gl/normalization.hpp
src/mbgl/gl/object.cpp
src/mbgl/gl/object.hpp
src/mbgl/gl/primitives.hpp
src/mbgl/gl/program.hpp
src/mbgl/gl/renderbuffer.hpp
src/mbgl/gl/segment.cpp
src/mbgl/gl/segment.hpp
src/mbgl/gl/state.hpp
src/mbgl/gl/stencil_mode.cpp
@@ -205,14 +207,15 @@ set(MBGL_CORE_FILES
# style
include/mbgl/style/conversion.hpp
include/mbgl/style/data_driven_property_value.hpp
include/mbgl/style/filter.hpp
include/mbgl/style/filter_evaluator.hpp
include/mbgl/style/function.hpp
include/mbgl/style/layer.hpp
include/mbgl/style/property_value.hpp
include/mbgl/style/source.hpp
include/mbgl/style/transition_options.hpp
include/mbgl/style/types.hpp
include/mbgl/style/undefined.hpp
src/mbgl/style/bucket_parameters.cpp
src/mbgl/style/bucket_parameters.hpp
src/mbgl/style/cascade_parameters.hpp
@@ -220,7 +223,7 @@ set(MBGL_CORE_FILES
src/mbgl/style/class_dictionary.hpp
src/mbgl/style/cross_faded_property_evaluator.cpp
src/mbgl/style/cross_faded_property_evaluator.hpp
src/mbgl/style/function.cpp
src/mbgl/style/data_driven_property_evaluator.hpp
src/mbgl/style/group_by_layout.cpp
src/mbgl/style/group_by_layout.hpp
src/mbgl/style/layer.cpp
@@ -230,8 +233,10 @@ set(MBGL_CORE_FILES
src/mbgl/style/layout_property.hpp
src/mbgl/style/observer.hpp
src/mbgl/style/paint_property.hpp
src/mbgl/style/paint_property_binder.hpp
src/mbgl/style/parser.cpp
src/mbgl/style/parser.hpp
src/mbgl/style/possibly_evaluated_property_value.hpp
src/mbgl/style/property_evaluation_parameters.hpp
src/mbgl/style/property_evaluator.hpp
src/mbgl/style/property_parsing.cpp
@@ -252,6 +257,7 @@ set(MBGL_CORE_FILES
# style/conversion
include/mbgl/style/conversion/constant.hpp
include/mbgl/style/conversion/data_driven_property_value.hpp
include/mbgl/style/conversion/filter.hpp
include/mbgl/style/conversion/function.hpp
include/mbgl/style/conversion/geojson.hpp
@@ -264,6 +270,17 @@ set(MBGL_CORE_FILES
include/mbgl/style/conversion/tileset.hpp
src/mbgl/style/conversion/stringify.hpp
# style/function
include/mbgl/style/function/camera_function.hpp
include/mbgl/style/function/categorical_stops.hpp
include/mbgl/style/function/composite_function.hpp
include/mbgl/style/function/exponential_stops.hpp
include/mbgl/style/function/identity_stops.hpp
include/mbgl/style/function/interval_stops.hpp
include/mbgl/style/function/source_function.hpp
src/mbgl/style/function/categorical_stops.cpp
src/mbgl/style/function/identity_stops.cpp
# style/layers
include/mbgl/style/layers/background_layer.hpp
include/mbgl/style/layers/circle_layer.hpp
@@ -437,6 +454,7 @@ set(MBGL_CORE_FILES
src/mbgl/util/i18n.hpp
src/mbgl/util/ignore.hpp
src/mbgl/util/indexed_tuple.hpp
src/mbgl/util/interpolate.cpp
src/mbgl/util/interpolate.hpp
src/mbgl/util/intersection_tests.cpp
src/mbgl/util/intersection_tests.hpp
@@ -469,6 +487,7 @@ set(MBGL_CORE_FILES
src/mbgl/util/tile_cover.cpp
src/mbgl/util/tile_cover.hpp
src/mbgl/util/token.hpp
src/mbgl/util/type_list.hpp
src/mbgl/util/url.cpp
src/mbgl/util/url.hpp
src/mbgl/util/utf.hpp

View File

@@ -77,7 +77,11 @@ set(MBGL_TEST_FILES
# style
test/style/filter.test.cpp
test/style/functions.test.cpp
# style/function
test/style/function/camera_function.test.cpp
# style
test/style/group_by_layout.test.cpp
test/style/paint_property.test.cpp
test/style/source.test.cpp

View File

@@ -4,6 +4,7 @@
#include <mbgl/util/variant.hpp>
#include <mbgl/util/color.hpp>
#include <mbgl/style/property_value.hpp>
#include <mbgl/style/data_driven_property_value.hpp>
#include <cstdint>
#include <vector>
@@ -29,17 +30,17 @@ using ShapeAnnotationGeometry = variant<
class LineAnnotation {
public:
ShapeAnnotationGeometry geometry;
style::PropertyValue<float> opacity { 1.0f };
style::DataDrivenPropertyValue<float> opacity { 1.0f };
style::PropertyValue<float> width { 1.0f };
style::PropertyValue<Color> color { Color::black() };
style::DataDrivenPropertyValue<Color> color { Color::black() };
};
class FillAnnotation {
public:
ShapeAnnotationGeometry geometry;
style::PropertyValue<float> opacity { 1.0f };
style::PropertyValue<Color> color { Color::black() };
style::PropertyValue<Color> outlineColor {};
style::DataDrivenPropertyValue<float> opacity { 1.0f };
style::DataDrivenPropertyValue<Color> color { Color::black() };
style::DataDrivenPropertyValue<Color> outlineColor {};
};
// An annotation whose type and properties are sourced from a style layer.

View File

@@ -0,0 +1,46 @@
#pragma once
#include <mbgl/style/data_driven_property_value.hpp>
#include <mbgl/style/conversion.hpp>
#include <mbgl/style/conversion/constant.hpp>
#include <mbgl/style/conversion/function.hpp>
namespace mbgl {
namespace style {
namespace conversion {
template <class T>
struct Converter<DataDrivenPropertyValue<T>> {
template <class V>
Result<DataDrivenPropertyValue<T>> operator()(const V& value) const {
if (isUndefined(value)) {
return {};
} else if (!isObject(value)) {
Result<T> constant = convert<T>(value);
if (!constant) {
return constant.error();
}
return DataDrivenPropertyValue<T>(*constant);
} else if (!objectMember(value, "property")) {
Result<CameraFunction<T>> function = convert<CameraFunction<T>>(value);
if (!function) {
return function.error();
}
return DataDrivenPropertyValue<T>(*function);
} else {
Result<CompositeFunction<T>> composite = convert<CompositeFunction<T>>(value);
if (composite) {
return DataDrivenPropertyValue<T>(*composite);
}
Result<SourceFunction<T>> source = convert<SourceFunction<T>>(value);
if (!source) {
return source.error();
}
return DataDrivenPropertyValue<T>(*source);
}
}
};
} // namespace conversion
} // namespace style
} // namespace mbgl

View File

@@ -1,62 +1,73 @@
#pragma once
#include <mbgl/style/function.hpp>
#include <mbgl/style/function/camera_function.hpp>
#include <mbgl/style/function/source_function.hpp>
#include <mbgl/style/function/composite_function.hpp>
#include <mbgl/style/conversion.hpp>
#include <mbgl/style/conversion/constant.hpp>
#include <mbgl/util/ignore.hpp>
namespace mbgl {
namespace style {
namespace conversion {
template <class D, class R, class V>
Result<std::map<D, R>> convertStops(const V& value) {
auto stopsValue = objectMember(value, "stops");
if (!stopsValue) {
return Error { "function value must specify stops" };
}
if (!isArray(*stopsValue)) {
return Error { "function stops must be an array" };
}
if (arrayLength(*stopsValue) == 0) {
return Error { "function must have at least one stop" };
}
std::map<D, R> stops;
for (std::size_t i = 0; i < arrayLength(*stopsValue); ++i) {
const auto& stopValue = arrayMember(*stopsValue, i);
if (!isArray(stopValue)) {
return Error { "function stop must be an array" };
}
if (arrayLength(stopValue) != 2) {
return Error { "function stop must have two elements" };
}
Result<D> d = convert<D>(arrayMember(stopValue, 0));
if (!d) {
return d.error();
}
Result<R> r = convert<R>(arrayMember(stopValue, 1));
if (!r) {
return r.error();
}
stops.emplace(*d, *r);
}
return stops;
}
template <class T>
struct Converter<Function<T>> {
struct Converter<ExponentialStops<T>> {
static constexpr const char * type = "exponential";
template <class V>
Result<Function<T>> operator()(const V& value) const {
if (!isObject(value)) {
return Error { "function must be an object" };
}
auto stopsValue = objectMember(value, "stops");
if (!stopsValue) {
return Error { "function value must specify stops" };
}
if (!isArray(*stopsValue)) {
return Error { "function stops must be an array" };
}
if (arrayLength(*stopsValue) == 0) {
return Error { "function must have at least one stop" };
}
std::vector<std::pair<float, T>> stops;
for (std::size_t i = 0; i < arrayLength(*stopsValue); ++i) {
const auto& stopValue = arrayMember(*stopsValue, i);
if (!isArray(stopValue)) {
return Error { "function stop must be an array" };
}
if (arrayLength(stopValue) != 2) {
return Error { "function stop must have two elements" };
}
optional<float> z = toNumber(arrayMember(stopValue, 0));
if (!z) {
return Error { "function stop zoom level must be a number" };
}
Result<T> v = convert<T>(arrayMember(stopValue, 1));
if (!v) {
return v.error();
}
stops.emplace_back(*z, *v);
Result<ExponentialStops<T>> operator()(const V& value) const {
auto stops = convertStops<float, T>(value);
if (!stops) {
return stops.error();
}
auto baseValue = objectMember(value, "base");
if (!baseValue) {
return Function<T>(stops, 1.0f);
return ExponentialStops<T>(*stops);
}
optional<float> base = toNumber(*baseValue);
@@ -64,7 +75,266 @@ struct Converter<Function<T>> {
return Error { "function base must be a number"};
}
return Function<T>(stops, *base);
return ExponentialStops<T>(*stops, *base);
}
};
template <class T>
struct Converter<IntervalStops<T>> {
static constexpr const char * type = "interval";
template <class V>
Result<IntervalStops<T>> operator()(const V& value) const {
auto stops = convertStops<float, T>(value);
if (!stops) {
return stops.error();
}
return IntervalStops<T>(*stops);
}
};
template <>
struct Converter<CategoricalValue> {
template <class V>
Result<CategoricalValue> operator()(const V& value) const {
auto b = toBool(value);
if (b) {
return *b;
}
auto n = toNumber(value);
if (n) {
return int64_t(*n);
}
auto s = toString(value);
if (s) {
return *s;
}
return Error { "stop domain value must be a number, string, or boolean" };
}
};
template <class T>
struct Converter<CategoricalStops<T>> {
static constexpr const char * type = "categorical";
template <class V>
Result<CategoricalStops<T>> operator()(const V& value) const {
auto stops = convertStops<CategoricalValue, T>(value);
if (!stops) {
return stops.error();
}
return CategoricalStops<T>(
std::map<CategoricalValue, T>((*stops).begin(), (*stops).end()));
}
};
template <class T>
struct Converter<IdentityStops<T>> {
static constexpr const char * type = "identity";
template <class V>
Result<IdentityStops<T>> operator()(const V&) const {
return IdentityStops<T>();
}
};
template <class, class>
struct StopsConverter;
template <class T, class... Ts>
struct StopsConverter<T, variant<Ts...>> {
public:
template <class V>
Result<variant<Ts...>> operator()(const V& value) const {
std::string type = util::Interpolatable<T> ? "exponential" : "interval";
auto typeValue = objectMember(value, "type");
if (typeValue && toString(*typeValue)) {
type = *toString(*typeValue);
}
optional<Result<variant<Ts...>>> result;
// Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47226
auto tryConvert = [&] (auto* tp) {
using Stops = std::decay_t<decltype(*tp)>;
if (type == Converter<Stops>::type) {
auto stops = convert<Stops>(value);
result = stops
? Result<variant<Ts...>>(*stops)
: Result<variant<Ts...>>(stops.error());
}
};
util::ignore({
(tryConvert((Ts*)nullptr), 0)...
});
if (!result) {
return Error { "unsupported function type" };
}
return *result;
}
};
template <class T>
struct Converter<CameraFunction<T>> {
template <class V>
Result<CameraFunction<T>> operator()(const V& value) const {
if (!isObject(value)) {
return Error { "function must be an object" };
}
auto stops = StopsConverter<T, typename CameraFunction<T>::Stops>()(value);
if (!stops) {
return stops.error();
}
return CameraFunction<T>(*stops);
}
};
template <class T>
struct Converter<SourceFunction<T>> {
template <class V>
Result<SourceFunction<T>> operator()(const V& value) const {
if (!isObject(value)) {
return Error { "function must be an object" };
}
auto propertyValue = objectMember(value, "property");
if (!propertyValue) {
return Error { "function must specify property" };
}
auto propertyString = toString(*propertyValue);
if (!propertyString) {
return Error { "function property must be a string" };
}
auto stops = StopsConverter<T, typename SourceFunction<T>::Stops>()(value);
if (!stops) {
return stops.error();
}
return SourceFunction<T>(*propertyString, *stops);
}
};
template <class S>
struct CompositeValue : std::pair<float, S> {
using std::pair<float, S>::pair;
};
template <class S>
struct Converter<CompositeValue<S>> {
template <class V>
Result<CompositeValue<S>> operator()(const V& value) const {
if (!isObject(value)) {
return Error { "stop must be an object" };
}
auto zoomValue = objectMember(value, "zoom");
if (!zoomValue) {
return Error { "stop must specify zoom" };
}
auto propertyValue = objectMember(value, "value");
if (!propertyValue) {
return Error { "stop must specify value" };
}
Result<float> z = convert<float>(*zoomValue);
if (!z) {
return z.error();
}
Result<S> s = convert<S>(*propertyValue);
if (!s) {
return s.error();
}
return CompositeValue<S> { *z, *s };
}
};
template <class T>
struct Converter<CompositeFunction<T>> {
template <class V>
Result<CompositeFunction<T>> operator()(const V& value) const {
if (!isObject(value)) {
return Error { "function must be an object" };
}
auto propertyValue = objectMember(value, "property");
if (!propertyValue) {
return Error { "function must specify property" };
}
auto propertyString = toString(*propertyValue);
if (!propertyString) {
return Error { "function property must be a string" };
}
std::string type = "exponential";
auto typeValue = objectMember(value, "type");
if (typeValue && toString(*typeValue)) {
type = *toString(*typeValue);
}
if (type == "exponential") {
auto stops = convertStops<CompositeValue<float>, T>(value);
if (!stops) {
return stops.error();
}
auto base = 1.0f;
auto baseValue = objectMember(value, "base");
if (baseValue && toNumber(*baseValue)) {
base = *toNumber(*baseValue);
}
std::map<float, ExponentialStops<T>> convertedStops;
for (const auto& stop : *stops) {
auto& inner = convertedStops[stop.first.first];
inner.base = base;
inner.stops.emplace(stop.first.second, stop.second);
}
return CompositeFunction<T>(*propertyString, convertedStops);
} else if (type == "interval") {
auto stops = convertStops<CompositeValue<float>, T>(value);
if (!stops) {
return stops.error();
}
std::map<float, IntervalStops<T>> convertedStops;
for (const auto& stop : *stops) {
auto& inner = convertedStops[stop.first.first];
inner.stops.emplace(stop.first.second, stop.second);
}
return CompositeFunction<T>(*propertyString, convertedStops);
} else if (type == "categorical") {
auto stops = convertStops<CompositeValue<CategoricalValue>, T>(value);
if (!stops) {
return stops.error();
}
std::map<float, CategoricalStops<T>> convertedStops;
for (const auto& stop : *stops) {
auto& inner = convertedStops[stop.first.first];
inner.stops.emplace(stop.first.second, stop.second);
}
return CompositeFunction<T>(*propertyString, convertedStops);
} else {
return Error { "unsupported function type" };
}
}
};

View File

@@ -4,6 +4,7 @@
#include <mbgl/style/conversion.hpp>
#include <mbgl/style/conversion/constant.hpp>
#include <mbgl/style/conversion/property_value.hpp>
#include <mbgl/style/conversion/data_driven_property_value.hpp>
#include <functional>
#include <string>
@@ -18,15 +19,15 @@ using LayoutPropertySetter = std::function<optional<Error> (Layer&, const V&)>;
template <class V>
using PaintPropertySetter = std::function<optional<Error> (Layer&, const V&, const optional<std::string>&)>;
template <class V, class L, class T, class...Args>
auto makePropertySetter(void (L::*setter)(PropertyValue<T>, const Args&...args)) {
template <class V, class L, class PropertyValue, class...Args>
auto makePropertySetter(void (L::*setter)(PropertyValue, const Args&...args)) {
return [setter] (Layer& layer, const V& value, const Args&...args) -> optional<Error> {
L* typedLayer = layer.as<L>();
if (!typedLayer) {
return Error { "layer doesn't support this property" };
}
Result<PropertyValue<T>> typedValue = convert<PropertyValue<T>>(value);
Result<PropertyValue> typedValue = convert<PropertyValue>(value);
if (!typedValue) {
return typedValue.error();
}

View File

@@ -16,7 +16,7 @@ struct Converter<PropertyValue<T>> {
if (isUndefined(value)) {
return {};
} else if (isObject(value)) {
Result<Function<T>> function = convert<Function<T>>(value);
Result<CameraFunction<T>> function = convert<CameraFunction<T>>(value);
if (!function) {
return function.error();
}

View File

@@ -0,0 +1,51 @@
#pragma once
#include <mbgl/util/variant.hpp>
#include <mbgl/style/undefined.hpp>
#include <mbgl/style/function/camera_function.hpp>
#include <mbgl/style/function/source_function.hpp>
#include <mbgl/style/function/composite_function.hpp>
namespace mbgl {
namespace style {
template <class T>
class DataDrivenPropertyValue {
private:
using Value = variant<
Undefined,
T,
CameraFunction<T>,
SourceFunction<T>,
CompositeFunction<T>>;
Value value;
friend bool operator==(const DataDrivenPropertyValue& lhs,
const DataDrivenPropertyValue& rhs) {
return lhs.value == rhs.value;
}
public:
DataDrivenPropertyValue() = default;
DataDrivenPropertyValue( T v) : value(std::move(v)) {}
DataDrivenPropertyValue( CameraFunction<T> v) : value(std::move(v)) {}
DataDrivenPropertyValue( SourceFunction<T> v) : value(std::move(v)) {}
DataDrivenPropertyValue(CompositeFunction<T> v) : value(std::move(v)) {}
bool isUndefined() const {
return value.template is<Undefined>();
}
bool isDataDriven() const {
return value.template is<SourceFunction<T>>() || value.template is<CompositeFunction<T>>();
}
template <typename Evaluator>
auto evaluate(const Evaluator& evaluator) const {
return Value::visit(value, evaluator);
}
};
} // namespace style
} // namespace mbgl

View File

@@ -1,40 +0,0 @@
#pragma once
#include <cassert>
#include <utility>
#include <vector>
namespace mbgl {
namespace style {
template <typename T>
class Function {
public:
using Stop = std::pair<float, T>;
using Stops = std::vector<Stop>;
Function(Stops stops_, float base_)
: base(base_), stops(std::move(stops_)) {
assert(stops.size() > 0);
}
float getBase() const { return base; }
const std::vector<std::pair<float, T>>& getStops() const { return stops; }
T evaluate(float z) const;
friend bool operator==(const Function& lhs, const Function& rhs) {
return lhs.base == rhs.base && lhs.stops == rhs.stops;
}
friend bool operator!=(const Function& lhs, const Function& rhs) {
return !(lhs == rhs);
}
private:
float base = 1;
std::vector<std::pair<float, T>> stops;
};
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,41 @@
#pragma once
#include <mbgl/style/function/exponential_stops.hpp>
#include <mbgl/style/function/interval_stops.hpp>
#include <mbgl/util/interpolate.hpp>
#include <mbgl/util/variant.hpp>
namespace mbgl {
namespace style {
template <class T>
class CameraFunction {
public:
using Stops = std::conditional_t<
util::Interpolatable<T>,
variant<
ExponentialStops<T>,
IntervalStops<T>>,
variant<
IntervalStops<T>>>;
CameraFunction(Stops stops_)
: stops(std::move(stops_)) {
}
T evaluate(float zoom) const {
return stops.match([&] (const auto& s) {
return s.evaluate(Value(double(zoom)));
});
}
friend bool operator==(const CameraFunction& lhs,
const CameraFunction& rhs) {
return lhs.stops == rhs.stops;
}
Stops stops;
};
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,42 @@
#pragma once
#include <mbgl/util/feature.hpp>
#include <mbgl/util/variant.hpp>
#include <cassert>
#include <utility>
#include <map>
namespace mbgl {
namespace style {
class CategoricalValue : public variant<bool, int64_t, std::string> {
public:
using variant<bool, int64_t, std::string>::variant;
};
template <class T>
class CategoricalStops {
public:
using Stops = std::map<CategoricalValue, T>;
Stops stops;
T defaultValue;
CategoricalStops() = default;
CategoricalStops(Stops stops_, T defaultValue_ = T())
: stops(std::move(stops_)),
defaultValue(std::move(defaultValue_)) {
assert(stops.size() > 0);
}
T evaluate(const Value&) const;
friend bool operator==(const CategoricalStops& lhs,
const CategoricalStops& rhs) {
return lhs.stops == rhs.stops && lhs.defaultValue == rhs.defaultValue;
}
};
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,109 @@
#pragma once
#include <mbgl/style/function/exponential_stops.hpp>
#include <mbgl/style/function/interval_stops.hpp>
#include <mbgl/style/function/categorical_stops.hpp>
#include <mbgl/util/interpolate.hpp>
#include <mbgl/util/range.hpp>
#include <mbgl/util/variant.hpp>
#include <string>
#include <tuple>
namespace mbgl {
class GeometryTileFeature;
namespace style {
// A CompositeFunction consists of an outer zoom function whose stop range values are
// "inner" source functions. It provides the GL Native implementation of
// "zoom-and-property" functions from the style spec.
template <class T>
class CompositeFunction {
public:
using InnerStops = std::conditional_t<
util::Interpolatable<T>,
variant<
ExponentialStops<T>,
IntervalStops<T>,
CategoricalStops<T>>,
variant<
IntervalStops<T>,
CategoricalStops<T>>>;
using Stops = std::conditional_t<
util::Interpolatable<T>,
variant<
std::map<float, ExponentialStops<T>>,
std::map<float, IntervalStops<T>>,
std::map<float, CategoricalStops<T>>>,
variant<
std::map<float, IntervalStops<T>>,
std::map<float, CategoricalStops<T>>>>;
CompositeFunction(std::string property_, Stops stops_)
: property(std::move(property_)),
stops(std::move(stops_)) {
}
std::tuple<Range<float>, Range<InnerStops>>
coveringRanges(float zoom) const {
return stops.match(
[&] (const auto& s) {
assert(!s.empty());
auto minIt = s.lower_bound(zoom);
auto maxIt = s.upper_bound(zoom);
if (minIt != s.begin()) {
minIt--;
}
return std::make_tuple(
Range<float> {
minIt == s.end() ? s.rbegin()->first : minIt->first,
maxIt == s.end() ? s.rbegin()->first : maxIt->first
},
Range<InnerStops> {
minIt == s.end() ? s.rbegin()->second : minIt->second,
maxIt == s.end() ? s.rbegin()->second : maxIt->second
}
);
}
);
}
Range<T> evaluate(Range<InnerStops> coveringStops,
const GeometryTileFeature& feature) const {
optional<Value> v = feature.getValue(property);
if (!v) {
return { T(), T() };
}
auto eval = [&] (const auto& s) {
return s.evaluate(*v);
};
return Range<T> {
coveringStops.min.match(eval),
coveringStops.max.match(eval)
};
}
T evaluate(float zoom, const GeometryTileFeature& feature) const {
std::tuple<Range<float>, Range<InnerStops>> ranges = coveringRanges(zoom);
Range<T> resultRange = evaluate(std::get<1>(ranges), feature);
return util::interpolate(
resultRange.min,
resultRange.max,
util::interpolationFactor(1.0f, std::get<0>(ranges), zoom));
}
friend bool operator==(const CompositeFunction& lhs,
const CompositeFunction& rhs) {
return lhs.property == rhs.property && lhs.stops == rhs.stops;
}
std::string property;
Stops stops;
};
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,54 @@
#pragma once
#include <mbgl/util/feature.hpp>
#include <mbgl/util/interpolate.hpp>
#include <map>
namespace mbgl {
namespace style {
template <class T>
class ExponentialStops {
public:
using Stops = std::map<float, T>;
Stops stops;
float base = 1.0f;
ExponentialStops() = default;
ExponentialStops(Stops stops_, float base_ = 1.0f)
: stops(std::move(stops_)),
base(base_) {
}
T evaluate(const Value& value) const {
if (stops.empty()) {
assert(false);
return T();
}
optional<float> z = numericValue<float>(value);
if (!z) {
return T();
}
auto it = stops.upper_bound(*z);
if (it == stops.end()) {
return stops.rbegin()->second;
} else if (it == stops.begin()) {
return stops.begin()->second;
} else {
return util::interpolate(std::prev(it)->second, it->second,
util::interpolationFactor(base, { std::prev(it)->first, it->first }, *z));
}
}
friend bool operator==(const ExponentialStops& lhs,
const ExponentialStops& rhs) {
return lhs.stops == rhs.stops && lhs.base == rhs.base;
}
};
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,20 @@
#pragma once
#include <mbgl/util/feature.hpp>
namespace mbgl {
namespace style {
template <class T>
class IdentityStops {
public:
T evaluate(const Value&) const;
friend bool operator==(const IdentityStops&,
const IdentityStops&) {
return true;
}
};
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,49 @@
#pragma once
#include <mbgl/util/feature.hpp>
#include <map>
namespace mbgl {
namespace style {
template <class T>
class IntervalStops {
public:
using Stops = std::map<float, T>;
Stops stops;
IntervalStops() = default;
IntervalStops(Stops stops_)
: stops(std::move(stops_)) {
}
T evaluate(const Value& value) const {
if (stops.empty()) {
assert(false);
return T();
}
optional<float> z = numericValue<float>(value);
if (!z) {
return T();
}
auto it = stops.upper_bound(*z);
if (it == stops.end()) {
return stops.rbegin()->second;
} else if (it == stops.begin()) {
return stops.begin()->second;
} else {
return std::prev(it)->second;
}
}
friend bool operator==(const IntervalStops& lhs,
const IntervalStops& rhs) {
return lhs.stops == rhs.stops;
}
};
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,56 @@
#pragma once
#include <mbgl/style/function/exponential_stops.hpp>
#include <mbgl/style/function/interval_stops.hpp>
#include <mbgl/style/function/categorical_stops.hpp>
#include <mbgl/style/function/identity_stops.hpp>
#include <mbgl/tile/geometry_tile_data.hpp>
#include <mbgl/util/interpolate.hpp>
#include <mbgl/util/variant.hpp>
#include <string>
namespace mbgl {
namespace style {
template <class T>
class SourceFunction {
public:
using Stops = std::conditional_t<
util::Interpolatable<T>,
variant<
ExponentialStops<T>,
IntervalStops<T>,
CategoricalStops<T>,
IdentityStops<T>>,
variant<
IntervalStops<T>,
CategoricalStops<T>,
IdentityStops<T>>>;
SourceFunction(std::string property_, Stops stops_)
: property(std::move(property_)),
stops(std::move(stops_)) {
}
T evaluate(const GeometryTileFeature& feature) const {
optional<Value> v = feature.getValue(property);
if (!v) {
return T();
}
return stops.match([&] (const auto& s) {
return s.evaluate(*v);
});
}
friend bool operator==(const SourceFunction& lhs,
const SourceFunction& rhs) {
return lhs.property == rhs.property && lhs.stops == rhs.stops;
}
std::string property;
Stops stops;
};
} // namespace style
} // namespace mbgl

View File

@@ -5,6 +5,7 @@
#include <mbgl/style/layer.hpp>
#include <mbgl/style/filter.hpp>
#include <mbgl/style/property_value.hpp>
#include <mbgl/style/data_driven_property_value.hpp>
#include <mbgl/util/color.hpp>

View File

@@ -5,6 +5,7 @@
#include <mbgl/style/layer.hpp>
#include <mbgl/style/filter.hpp>
#include <mbgl/style/property_value.hpp>
#include <mbgl/style/data_driven_property_value.hpp>
#include <mbgl/util/color.hpp>
@@ -26,21 +27,21 @@ public:
// Paint properties
static PropertyValue<float> getDefaultCircleRadius();
PropertyValue<float> getCircleRadius(const optional<std::string>& klass = {}) const;
void setCircleRadius(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultCircleRadius();
DataDrivenPropertyValue<float> getCircleRadius(const optional<std::string>& klass = {}) const;
void setCircleRadius(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<Color> getDefaultCircleColor();
PropertyValue<Color> getCircleColor(const optional<std::string>& klass = {}) const;
void setCircleColor(PropertyValue<Color>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<Color> getDefaultCircleColor();
DataDrivenPropertyValue<Color> getCircleColor(const optional<std::string>& klass = {}) const;
void setCircleColor(DataDrivenPropertyValue<Color>, const optional<std::string>& klass = {});
static PropertyValue<float> getDefaultCircleBlur();
PropertyValue<float> getCircleBlur(const optional<std::string>& klass = {}) const;
void setCircleBlur(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultCircleBlur();
DataDrivenPropertyValue<float> getCircleBlur(const optional<std::string>& klass = {}) const;
void setCircleBlur(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<float> getDefaultCircleOpacity();
PropertyValue<float> getCircleOpacity(const optional<std::string>& klass = {}) const;
void setCircleOpacity(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultCircleOpacity();
DataDrivenPropertyValue<float> getCircleOpacity(const optional<std::string>& klass = {}) const;
void setCircleOpacity(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<std::array<float, 2>> getDefaultCircleTranslate();
PropertyValue<std::array<float, 2>> getCircleTranslate(const optional<std::string>& klass = {}) const;
@@ -54,17 +55,17 @@ public:
PropertyValue<CirclePitchScaleType> getCirclePitchScale(const optional<std::string>& klass = {}) const;
void setCirclePitchScale(PropertyValue<CirclePitchScaleType>, const optional<std::string>& klass = {});
static PropertyValue<float> getDefaultCircleStrokeWidth();
PropertyValue<float> getCircleStrokeWidth(const optional<std::string>& klass = {}) const;
void setCircleStrokeWidth(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultCircleStrokeWidth();
DataDrivenPropertyValue<float> getCircleStrokeWidth(const optional<std::string>& klass = {}) const;
void setCircleStrokeWidth(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<Color> getDefaultCircleStrokeColor();
PropertyValue<Color> getCircleStrokeColor(const optional<std::string>& klass = {}) const;
void setCircleStrokeColor(PropertyValue<Color>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<Color> getDefaultCircleStrokeColor();
DataDrivenPropertyValue<Color> getCircleStrokeColor(const optional<std::string>& klass = {}) const;
void setCircleStrokeColor(DataDrivenPropertyValue<Color>, const optional<std::string>& klass = {});
static PropertyValue<float> getDefaultCircleStrokeOpacity();
PropertyValue<float> getCircleStrokeOpacity(const optional<std::string>& klass = {}) const;
void setCircleStrokeOpacity(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultCircleStrokeOpacity();
DataDrivenPropertyValue<float> getCircleStrokeOpacity(const optional<std::string>& klass = {}) const;
void setCircleStrokeOpacity(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
// Private implementation

View File

@@ -5,6 +5,7 @@
#include <mbgl/style/layer.hpp>
#include <mbgl/style/filter.hpp>
#include <mbgl/style/property_value.hpp>
#include <mbgl/style/data_driven_property_value.hpp>
#include <mbgl/util/color.hpp>
@@ -30,9 +31,9 @@ public:
PropertyValue<float> getFillExtrusionOpacity(const optional<std::string>& klass = {}) const;
void setFillExtrusionOpacity(PropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<Color> getDefaultFillExtrusionColor();
PropertyValue<Color> getFillExtrusionColor(const optional<std::string>& klass = {}) const;
void setFillExtrusionColor(PropertyValue<Color>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<Color> getDefaultFillExtrusionColor();
DataDrivenPropertyValue<Color> getFillExtrusionColor(const optional<std::string>& klass = {}) const;
void setFillExtrusionColor(DataDrivenPropertyValue<Color>, const optional<std::string>& klass = {});
static PropertyValue<std::array<float, 2>> getDefaultFillExtrusionTranslate();
PropertyValue<std::array<float, 2>> getFillExtrusionTranslate(const optional<std::string>& klass = {}) const;
@@ -46,13 +47,13 @@ public:
PropertyValue<std::string> getFillExtrusionPattern(const optional<std::string>& klass = {}) const;
void setFillExtrusionPattern(PropertyValue<std::string>, const optional<std::string>& klass = {});
static PropertyValue<float> getDefaultFillExtrusionHeight();
PropertyValue<float> getFillExtrusionHeight(const optional<std::string>& klass = {}) const;
void setFillExtrusionHeight(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultFillExtrusionHeight();
DataDrivenPropertyValue<float> getFillExtrusionHeight(const optional<std::string>& klass = {}) const;
void setFillExtrusionHeight(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<float> getDefaultFillExtrusionBase();
PropertyValue<float> getFillExtrusionBase(const optional<std::string>& klass = {}) const;
void setFillExtrusionBase(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultFillExtrusionBase();
DataDrivenPropertyValue<float> getFillExtrusionBase(const optional<std::string>& klass = {}) const;
void setFillExtrusionBase(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
// Private implementation

View File

@@ -5,6 +5,7 @@
#include <mbgl/style/layer.hpp>
#include <mbgl/style/filter.hpp>
#include <mbgl/style/property_value.hpp>
#include <mbgl/style/data_driven_property_value.hpp>
#include <mbgl/util/color.hpp>
@@ -30,17 +31,17 @@ public:
PropertyValue<bool> getFillAntialias(const optional<std::string>& klass = {}) const;
void setFillAntialias(PropertyValue<bool>, const optional<std::string>& klass = {});
static PropertyValue<float> getDefaultFillOpacity();
PropertyValue<float> getFillOpacity(const optional<std::string>& klass = {}) const;
void setFillOpacity(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultFillOpacity();
DataDrivenPropertyValue<float> getFillOpacity(const optional<std::string>& klass = {}) const;
void setFillOpacity(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<Color> getDefaultFillColor();
PropertyValue<Color> getFillColor(const optional<std::string>& klass = {}) const;
void setFillColor(PropertyValue<Color>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<Color> getDefaultFillColor();
DataDrivenPropertyValue<Color> getFillColor(const optional<std::string>& klass = {}) const;
void setFillColor(DataDrivenPropertyValue<Color>, const optional<std::string>& klass = {});
static PropertyValue<Color> getDefaultFillOutlineColor();
PropertyValue<Color> getFillOutlineColor(const optional<std::string>& klass = {}) const;
void setFillOutlineColor(PropertyValue<Color>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<Color> getDefaultFillOutlineColor();
DataDrivenPropertyValue<Color> getFillOutlineColor(const optional<std::string>& klass = {}) const;
void setFillOutlineColor(DataDrivenPropertyValue<Color>, const optional<std::string>& klass = {});
static PropertyValue<std::array<float, 2>> getDefaultFillTranslate();
PropertyValue<std::array<float, 2>> getFillTranslate(const optional<std::string>& klass = {}) const;

View File

@@ -10,6 +10,7 @@
#include <mbgl/style/layer.hpp>
#include <mbgl/style/filter.hpp>
#include <mbgl/style/property_value.hpp>
#include <mbgl/style/data_driven_property_value.hpp>
#include <mbgl/util/color.hpp>
@@ -45,18 +46,18 @@ public:
// Layout properties
<% for (const property of layoutProperties) { -%>
static PropertyValue<<%- propertyType(property) %>> getDefault<%- camelize(property.name) %>();
PropertyValue<<%- propertyType(property) %>> get<%- camelize(property.name) %>() const;
void set<%- camelize(property.name) %>(PropertyValue<<%- propertyType(property) %>>);
static <%- propertyValueType(property) %> getDefault<%- camelize(property.name) %>();
<%- propertyValueType(property) %> get<%- camelize(property.name) %>() const;
void set<%- camelize(property.name) %>(<%- propertyValueType(property) %>);
<% } -%>
<% } -%>
// Paint properties
<% for (const property of paintProperties) { -%>
static PropertyValue<<%- propertyType(property) %>> getDefault<%- camelize(property.name) %>();
PropertyValue<<%- propertyType(property) %>> get<%- camelize(property.name) %>(const optional<std::string>& klass = {}) const;
void set<%- camelize(property.name) %>(PropertyValue<<%- propertyType(property) %>>, const optional<std::string>& klass = {});
static <%- propertyValueType(property) %> getDefault<%- camelize(property.name) %>();
<%- propertyValueType(property) %> get<%- camelize(property.name) %>(const optional<std::string>& klass = {}) const;
void set<%- camelize(property.name) %>(<%- propertyValueType(property) %>, const optional<std::string>& klass = {});
<% } -%>
// Private implementation

View File

@@ -5,6 +5,7 @@
#include <mbgl/style/layer.hpp>
#include <mbgl/style/filter.hpp>
#include <mbgl/style/property_value.hpp>
#include <mbgl/style/data_driven_property_value.hpp>
#include <mbgl/util/color.hpp>
@@ -46,13 +47,13 @@ public:
// Paint properties
static PropertyValue<float> getDefaultLineOpacity();
PropertyValue<float> getLineOpacity(const optional<std::string>& klass = {}) const;
void setLineOpacity(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultLineOpacity();
DataDrivenPropertyValue<float> getLineOpacity(const optional<std::string>& klass = {}) const;
void setLineOpacity(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<Color> getDefaultLineColor();
PropertyValue<Color> getLineColor(const optional<std::string>& klass = {}) const;
void setLineColor(PropertyValue<Color>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<Color> getDefaultLineColor();
DataDrivenPropertyValue<Color> getLineColor(const optional<std::string>& klass = {}) const;
void setLineColor(DataDrivenPropertyValue<Color>, const optional<std::string>& klass = {});
static PropertyValue<std::array<float, 2>> getDefaultLineTranslate();
PropertyValue<std::array<float, 2>> getLineTranslate(const optional<std::string>& klass = {}) const;
@@ -66,17 +67,17 @@ public:
PropertyValue<float> getLineWidth(const optional<std::string>& klass = {}) const;
void setLineWidth(PropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<float> getDefaultLineGapWidth();
PropertyValue<float> getLineGapWidth(const optional<std::string>& klass = {}) const;
void setLineGapWidth(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultLineGapWidth();
DataDrivenPropertyValue<float> getLineGapWidth(const optional<std::string>& klass = {}) const;
void setLineGapWidth(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<float> getDefaultLineOffset();
PropertyValue<float> getLineOffset(const optional<std::string>& klass = {}) const;
void setLineOffset(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultLineOffset();
DataDrivenPropertyValue<float> getLineOffset(const optional<std::string>& klass = {}) const;
void setLineOffset(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<float> getDefaultLineBlur();
PropertyValue<float> getLineBlur(const optional<std::string>& klass = {}) const;
void setLineBlur(PropertyValue<float>, const optional<std::string>& klass = {});
static DataDrivenPropertyValue<float> getDefaultLineBlur();
DataDrivenPropertyValue<float> getLineBlur(const optional<std::string>& klass = {}) const;
void setLineBlur(DataDrivenPropertyValue<float>, const optional<std::string>& klass = {});
static PropertyValue<std::vector<float>> getDefaultLineDasharray();
PropertyValue<std::vector<float>> getLineDasharray(const optional<std::string>& klass = {}) const;

View File

@@ -5,6 +5,7 @@
#include <mbgl/style/layer.hpp>
#include <mbgl/style/filter.hpp>
#include <mbgl/style/property_value.hpp>
#include <mbgl/style/data_driven_property_value.hpp>
#include <mbgl/util/color.hpp>

View File

@@ -5,6 +5,7 @@
#include <mbgl/style/layer.hpp>
#include <mbgl/style/filter.hpp>
#include <mbgl/style/property_value.hpp>
#include <mbgl/style/data_driven_property_value.hpp>
#include <mbgl/util/color.hpp>
@@ -72,9 +73,9 @@ public:
PropertyValue<std::string> getIconImage() const;
void setIconImage(PropertyValue<std::string>);
static PropertyValue<float> getDefaultIconRotate();
PropertyValue<float> getIconRotate() const;
void setIconRotate(PropertyValue<float>);
static DataDrivenPropertyValue<float> getDefaultIconRotate();
DataDrivenPropertyValue<float> getIconRotate() const;
void setIconRotate(DataDrivenPropertyValue<float>);
static PropertyValue<float> getDefaultIconPadding();
PropertyValue<float> getIconPadding() const;
@@ -84,9 +85,9 @@ public:
PropertyValue<bool> getIconKeepUpright() const;
void setIconKeepUpright(PropertyValue<bool>);
static PropertyValue<std::array<float, 2>> getDefaultIconOffset();
PropertyValue<std::array<float, 2>> getIconOffset() const;
void setIconOffset(PropertyValue<std::array<float, 2>>);
static DataDrivenPropertyValue<std::array<float, 2>> getDefaultIconOffset();
DataDrivenPropertyValue<std::array<float, 2>> getIconOffset() const;
void setIconOffset(DataDrivenPropertyValue<std::array<float, 2>>);
static PropertyValue<AlignmentType> getDefaultTextPitchAlignment();
PropertyValue<AlignmentType> getTextPitchAlignment() const;

View File

@@ -1,20 +1,16 @@
#pragma once
#include <mbgl/util/variant.hpp>
#include <mbgl/style/function.hpp>
#include <mbgl/style/undefined.hpp>
#include <mbgl/style/function/camera_function.hpp>
namespace mbgl {
namespace style {
class Undefined {};
inline bool operator==(const Undefined&, const Undefined&) { return true; }
inline bool operator!=(const Undefined&, const Undefined&) { return false; }
template <class T>
class PropertyValue {
private:
using Value = variant<Undefined, T, Function<T>>;
using Value = variant<Undefined, T, CameraFunction<T>>;
Value value;
friend bool operator==(const PropertyValue& lhs, const PropertyValue& rhs) {
@@ -26,16 +22,16 @@ private:
}
public:
PropertyValue() : value() {}
PropertyValue( T constant) : value(constant) {}
PropertyValue(Function<T> function) : value(function) {}
PropertyValue() : value() {}
PropertyValue( T constant) : value(constant) {}
PropertyValue(CameraFunction<T> function) : value(function) {}
bool isUndefined() const { return value.which() == 0; }
bool isConstant() const { return value.which() == 1; }
bool isFunction() const { return value.which() == 2; }
bool isUndefined() const { return value.which() == 0; }
bool isConstant() const { return value.which() == 1; }
bool isCameraFunction() const { return value.which() == 2; }
const T & asConstant() const { return value.template get< T >(); }
const Function<T>& asFunction() const { return value.template get<Function<T>>(); }
const T & asConstant() const { return value.template get< T >(); }
const CameraFunction<T>& asCameraFunction() const { return value.template get<CameraFunction<T>>(); }
explicit operator bool() const { return !isUndefined(); };

View File

@@ -0,0 +1,12 @@
#pragma once
namespace mbgl {
namespace style {
class Undefined {};
inline bool operator==(const Undefined&, const Undefined&) { return true; }
inline bool operator!=(const Undefined&, const Undefined&) { return false; }
} // namespace style
} // namespace mbgl

View File

@@ -12,4 +12,21 @@ using PropertyMap = mapbox::geometry::property_map;
using FeatureIdentifier = mapbox::geometry::identifier;
using Feature = mapbox::geometry::feature<double>;
template <class T>
optional<T> numericValue(const Value& value) {
return value.match(
[] (uint64_t t) {
return optional<T>(t);
},
[] (int64_t t) {
return optional<T>(t);
},
[] (double t) {
return optional<T>(t);
},
[] (auto) {
return optional<T>();
});
}
} // namespace mbgl

View File

@@ -14,28 +14,43 @@ if (!shaderName || !inputPath || !outputPath) {
process.exit(1);
}
var pragmaMapboxRe = /(\s*)#pragma\s+mapbox\s*:\s+(define|initialize)\s+(low|medium|high)p\s+(float|vec(?:2|3|4))\s+(.*)/;
function applyPragmas(source) {
return '\n' + source.split('\n').map(function(line) {
var params = line.match(pragmaMapboxRe);
if (params) {
if (params[2] === 'define') {
return params[1] + 'uniform ' + params[3] + 'p ' + params[4] + ' u_' + params[5] + ';';
} else {
return params[1] + params[3] + 'p ' + params[4] + ' ' + params[5] + ' = u_' + params[5] + ';';
}
} else {
return line;
}
}).join('\n');
function applyPragmas(source, pragmas) {
return source.replace(/#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g, (match, operation, precision, type, name) => {
return pragmas[operation]
.join("\n")
.replace(/\{type\}/g, type)
.replace(/\{precision\}/g, precision)
.replace(/\{name\}/g, name);
});
}
var vertexPrelude = fs.readFileSync(path.join(inputPath, '_prelude.vertex.glsl'));
var fragmentPrelude = fs.readFileSync(path.join(inputPath, '_prelude.fragment.glsl'));
var vertexSource = vertexPrelude + fs.readFileSync(path.join(inputPath, shaderName + '.vertex.glsl'), 'utf8');
var fragmentSource = fragmentPrelude + fs.readFileSync(path.join(inputPath, shaderName + '.fragment.glsl'), 'utf8');
function vertexSource() {
var prelude = fs.readFileSync(path.join(inputPath, '_prelude.vertex.glsl'));
var source = fs.readFileSync(path.join(inputPath, shaderName + '.vertex.glsl'), 'utf8');
return prelude + applyPragmas(source, {
define: [
"uniform lowp float a_{name}_t;",
"attribute {precision} {type} a_{name}_min;",
"attribute {precision} {type} a_{name}_max;",
"varying {precision} {type} {name};"
],
initialize: [
"{name} = mix(a_{name}_min, a_{name}_max, a_{name}_t);"
]
});
}
function fragmentSource() {
var prelude = fs.readFileSync(path.join(inputPath, '_prelude.fragment.glsl'));
var source = fs.readFileSync(path.join(inputPath, shaderName + '.fragment.glsl'), 'utf8');
return prelude + applyPragmas(source, {
define: [
"varying {precision} {type} {name};"
],
initialize: [
]
});
}
var content = "#pragma once\n" +
"\n" +
@@ -49,8 +64,8 @@ var content = "#pragma once\n" +
"class " + shaderName + " {\n" +
"public:\n" +
" static constexpr const char* name = \"" + shaderName + "\";\n" +
" static constexpr const char* vertexSource = R\"MBGL_SHADER(" + applyPragmas(vertexSource) + ")MBGL_SHADER\";\n" +
" static constexpr const char* fragmentSource = R\"MBGL_SHADER(" + applyPragmas(fragmentSource) + ")MBGL_SHADER\";\n" +
" static constexpr const char* vertexSource = R\"MBGL_SHADER(\n" + vertexSource() + ")MBGL_SHADER\";\n" +
" static constexpr const char* fragmentSource = R\"MBGL_SHADER(\n" + fragmentSource() + ")MBGL_SHADER\";\n" +
"};\n" +
"\n" +
"} // namespace shaders\n" +

View File

@@ -14,7 +14,11 @@ function parseCSSColor(str) {
];
}
global.propertyType = function (property) {
global.isDataDriven = function (property) {
return property['property-function'] === true;
};
global.evaluatedType = function (property) {
if (/-translate-anchor$/.test(property.name)) {
return 'TranslateAnchorType';
}
@@ -34,14 +38,45 @@ global.propertyType = function (property) {
return `Color`;
case 'array':
if (property.length) {
return `std::array<${propertyType({type: property.value})}, ${property.length}>`;
return `std::array<${evaluatedType({type: property.value})}, ${property.length}>`;
} else {
return `std::vector<${propertyType({type: property.value})}>`;
return `std::vector<${evaluatedType({type: property.value})}>`;
}
default: throw new Error(`unknown type for ${property.name}`)
}
};
function attributeType(property, type) {
const name = property.name.replace(type + '-', '').replace('-', '_');
return `attributes::a_${name}${name === 'offset' ? '<1>' : ''}`;
}
global.layoutPropertyType = function (property) {
if (isDataDriven(property)) {
return `DataDrivenLayoutProperty<${evaluatedType(property)}>`;
} else {
return `LayoutProperty<${evaluatedType(property)}>`;
}
};
global.paintPropertyType = function (property, type) {
if (isDataDriven(property)) {
return `DataDrivenPaintProperty<${evaluatedType(property)}, ${attributeType(property, type)}>`;
} else if (/-pattern$/.test(property.name) || property.name === 'line-dasharray') {
return `CrossFadedPaintProperty<${evaluatedType(property)}>`;
} else {
return `PaintProperty<${evaluatedType(property)}>`;
}
};
global.propertyValueType = function (property) {
if (isDataDriven(property)) {
return `DataDrivenPropertyValue<${evaluatedType(property)}>`;
} else {
return `PropertyValue<${evaluatedType(property)}>`;
}
};
global.defaultValue = function (property) {
// https://github.com/mapbox/mapbox-gl-native/issues/5258
if (property.name === 'line-round-limit') {
@@ -59,9 +94,9 @@ global.defaultValue = function (property) {
return JSON.stringify(property.default || "");
case 'enum':
if (property.default === undefined) {
return `${propertyType(property)}::Undefined`;
return `${evaluatedType(property)}::Undefined`;
} else {
return `${propertyType(property)}::${camelize(property.default)}`;
return `${evaluatedType(property)}::${camelize(property.default)}`;
}
case 'color':
const color = parseCSSColor(property.default).join(', ');

View File

@@ -1,29 +1,238 @@
#include <mbgl/gl/attribute.hpp>
#include <mbgl/gl/context.hpp>
#include <mbgl/gl/gl.hpp>
#include <mbgl/gl/normalization.hpp>
namespace mbgl {
namespace gl {
static_assert(offsetof(Normalized<uint8_t>, value) == 0, "unexpected normalized offset");
AttributeLocation bindAttributeLocation(ProgramID id, AttributeLocation location, const char* name) {
MBGL_CHECK_ERROR(glBindAttribLocation(id, location, name));
return location;
}
void bindAttribute(AttributeLocation location,
std::size_t count,
DataType type,
std::size_t vertexSize,
std::size_t vertexOffset,
std::size_t attributeOffset) {
template <class T> DataType DataTypeOf = static_cast<DataType>(0);
template <> DataType DataTypeOf< int8_t> = DataType::Byte;
template <> DataType DataTypeOf<uint8_t> = DataType::UnsignedByte;
template <> DataType DataTypeOf< int16_t> = DataType::Short;
template <> DataType DataTypeOf<uint16_t> = DataType::UnsignedShort;
template <> DataType DataTypeOf< int32_t> = DataType::Integer;
template <> DataType DataTypeOf<uint32_t> = DataType::UnsignedInteger;
template <> DataType DataTypeOf<float> = DataType::Float;
template <class T> bool IsNormalized = false;
template <class T> bool IsNormalized<Normalized<T>> = true;
template <class T> DataType DataTypeOf<Normalized<T>> = DataTypeOf<T>;
template <class T, std::size_t N>
void VariableAttributeBinding<T, N>::bind(Context& context,
AttributeLocation location,
optional<VariableAttributeBinding<T, N>>& oldBinding,
std::size_t vertexOffset) const {
if (oldBinding == *this) {
return;
}
context.vertexBuffer = vertexBuffer;
MBGL_CHECK_ERROR(glEnableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttribPointer(
location,
static_cast<GLint>(count),
static_cast<GLenum>(type),
GL_FALSE,
static_cast<GLint>(N),
static_cast<GLenum>(DataTypeOf<T>),
static_cast<GLboolean>(IsNormalized<T>),
static_cast<GLsizei>(vertexSize),
reinterpret_cast<GLvoid*>(attributeOffset + (vertexSize * vertexOffset))));
}
template class VariableAttributeBinding<uint8_t, 1>;
template class VariableAttributeBinding<uint8_t, 2>;
template class VariableAttributeBinding<uint8_t, 3>;
template class VariableAttributeBinding<uint8_t, 4>;
template class VariableAttributeBinding<Normalized<uint8_t>, 1>;
template class VariableAttributeBinding<Normalized<uint8_t>, 2>;
template class VariableAttributeBinding<Normalized<uint8_t>, 3>;
template class VariableAttributeBinding<Normalized<uint8_t>, 4>;
template class VariableAttributeBinding<uint16_t, 1>;
template class VariableAttributeBinding<uint16_t, 2>;
template class VariableAttributeBinding<uint16_t, 3>;
template class VariableAttributeBinding<uint16_t, 4>;
template class VariableAttributeBinding<int16_t, 1>;
template class VariableAttributeBinding<int16_t, 2>;
template class VariableAttributeBinding<int16_t, 3>;
template class VariableAttributeBinding<int16_t, 4>;
template class VariableAttributeBinding<float, 1>;
template class VariableAttributeBinding<float, 2>;
template class VariableAttributeBinding<float, 3>;
template class VariableAttributeBinding<float, 4>;
template <>
void ConstantAttributeBinding<uint8_t, 1>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<uint8_t, 1>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib1f(location, value[0]));
}
template <>
void ConstantAttributeBinding<uint8_t, 2>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<uint8_t, 2>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib2f(location, value[0], value[1]));
}
template <>
void ConstantAttributeBinding<uint8_t, 3>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<uint8_t, 3>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib3f(location, value[0], value[1], value[2]));
}
template <>
void ConstantAttributeBinding<uint8_t, 4>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<uint8_t, 4>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib4f(location, value[0], value[1], value[2], value[3]));
}
template <>
void ConstantAttributeBinding<Normalized<uint8_t>, 1>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<Normalized<uint8_t>, 1>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib1f(location, value[0].denormalized()));
}
template <>
void ConstantAttributeBinding<Normalized<uint8_t>, 2>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<Normalized<uint8_t>, 2>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib2f(location, value[0].denormalized(), value[1].denormalized()));
}
template <>
void ConstantAttributeBinding<Normalized<uint8_t>, 3>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<Normalized<uint8_t>, 3>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib3f(location, value[0].denormalized(), value[1].denormalized(), value[2].denormalized()));
}
template <>
void ConstantAttributeBinding<Normalized<uint8_t>, 4>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<Normalized<uint8_t>, 4>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib4f(location, value[0].denormalized(), value[1].denormalized(), value[2].denormalized(), value[3].denormalized()));
}
template <>
void ConstantAttributeBinding<uint16_t, 1>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<uint16_t, 1>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib1f(location, value[0]));
}
template <>
void ConstantAttributeBinding<uint16_t, 2>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<uint16_t, 2>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib2f(location, value[0], value[1]));
}
template <>
void ConstantAttributeBinding<uint16_t, 3>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<uint16_t, 3>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib3f(location, value[0], value[1], value[2]));
}
template <>
void ConstantAttributeBinding<uint16_t, 4>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<uint16_t, 4>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib4f(location, value[0], value[1], value[2], value[3]));
}
template <>
void ConstantAttributeBinding<int16_t, 1>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<int16_t, 1>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib1f(location, value[0]));
}
template <>
void ConstantAttributeBinding<int16_t, 2>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<int16_t, 2>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib2f(location, value[0], value[1]));
}
template <>
void ConstantAttributeBinding<int16_t, 3>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<int16_t, 3>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib3f(location, value[0], value[1], value[2]));
}
template <>
void ConstantAttributeBinding<int16_t, 4>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<int16_t, 4>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib4f(location, value[0], value[1], value[2], value[3]));
}
template <>
void ConstantAttributeBinding<float, 1>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<float, 1>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib1f(location, value[0]));
}
template <>
void ConstantAttributeBinding<float, 2>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<float, 2>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib2f(location, value[0], value[1]));
}
template <>
void ConstantAttributeBinding<float, 3>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<float, 3>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib3f(location, value[0], value[1], value[2]));
}
template <>
void ConstantAttributeBinding<float, 4>::bind(Context&, AttributeLocation location, optional<VariableAttributeBinding<float, 4>>& oldBinding, std::size_t) const {
assert(location != 0);
oldBinding = {};
MBGL_CHECK_ERROR(glDisableVertexAttribArray(location));
MBGL_CHECK_ERROR(glVertexAttrib4f(location, value[0], value[1], value[2], value[3]));
}
} // namespace gl
} // namespace mbgl

View File

@@ -1,8 +1,10 @@
#pragma once
#include <mbgl/gl/types.hpp>
#include <mbgl/gl/segment.hpp>
#include <mbgl/util/ignore.hpp>
#include <mbgl/util/indexed_tuple.hpp>
#include <mbgl/util/variant.hpp>
#include <cstddef>
#include <functional>
@@ -10,24 +12,79 @@
namespace mbgl {
namespace gl {
template <class Tag, class T, std::size_t N>
template <class T, std::size_t N>
class VariableAttributeBinding {
public:
VariableAttributeBinding(BufferID vertexBuffer_,
std::size_t vertexSize_,
std::size_t attributeOffset_)
: vertexBuffer(vertexBuffer_),
vertexSize(vertexSize_),
attributeOffset(attributeOffset_)
{}
void bind(Context&, AttributeLocation, optional<VariableAttributeBinding<T, N>>&, std::size_t vertexOffset) const;
friend bool operator==(const VariableAttributeBinding& lhs,
const VariableAttributeBinding& rhs) {
return lhs.vertexBuffer == rhs.vertexBuffer
&& lhs.vertexSize == rhs.vertexSize
&& lhs.attributeOffset == rhs.attributeOffset;
}
private:
BufferID vertexBuffer;
std::size_t vertexSize;
std::size_t attributeOffset;
};
template <class T, std::size_t N>
class ConstantAttributeBinding {
public:
ConstantAttributeBinding() { value.fill(T()); }
explicit ConstantAttributeBinding(std::array<T, N> value_)
: value(std::move(value_))
{}
void bind(Context&, AttributeLocation, optional<VariableAttributeBinding<T, N>>&, std::size_t) const;
friend bool operator==(const ConstantAttributeBinding& lhs,
const ConstantAttributeBinding& rhs) {
return lhs.value == rhs.value;
}
private:
std::array<T, N> value;
};
template <class T, std::size_t N>
class Attribute {
public:
using Type = T[N];
using Value = std::array<T, N>;
class State {
public:
explicit State(AttributeLocation location_)
: location(location_) {}
using VariableBinding = VariableAttributeBinding<T, N>;
using ConstantBinding = ConstantAttributeBinding<T, N>;
AttributeLocation location;
static constexpr std::size_t count = N;
static constexpr DataType type = DataTypeOf<T>::value;
};
using Location = AttributeLocation;
using Binding = variant<
ConstantBinding,
VariableBinding>;
static void bind(Context& context,
const Location& location,
optional<VariableBinding>& oldBinding,
const Binding& newBinding,
std::size_t vertexOffset) {
Binding::visit(newBinding, [&] (const auto& binding) {
binding.bind(context, location, oldBinding, vertexOffset);
});
}
};
#define MBGL_DEFINE_ATTRIBUTE(type_, n_, name_) \
struct name_ : ::mbgl::gl::Attribute<name_, type_, n_> { static constexpr auto name = #name_; }
struct name_ : ::mbgl::gl::Attribute<type_, n_> { static auto name() { return #name_; } }
namespace detail {
@@ -41,10 +98,16 @@ namespace detail {
template <class... As>
class Vertex;
template <>
class Vertex<> {
public:
using VertexType = Vertex<>;
};
template <class A1>
class Vertex<A1> {
public:
typename A1::Type a1;
typename A1::Value a1;
using VertexType = Vertex<A1>;
static const std::size_t attributeOffsets[1];
@@ -53,8 +116,8 @@ public:
template <class A1, class A2>
class Vertex<A1, A2> {
public:
typename A1::Type a1;
typename A2::Type a2;
typename A1::Value a1;
typename A2::Value a2;
using VertexType = Vertex<A1, A2>;
static const std::size_t attributeOffsets[2];
@@ -63,9 +126,9 @@ public:
template <class A1, class A2, class A3>
class Vertex<A1, A2, A3> {
public:
typename A1::Type a1;
typename A2::Type a2;
typename A3::Type a3;
typename A1::Value a1;
typename A2::Value a2;
typename A3::Value a3;
using VertexType = Vertex<A1, A2, A3>;
static const std::size_t attributeOffsets[3];
@@ -74,10 +137,10 @@ public:
template <class A1, class A2, class A3, class A4>
class Vertex<A1, A2, A3, A4> {
public:
typename A1::Type a1;
typename A2::Type a2;
typename A3::Type a3;
typename A4::Type a4;
typename A1::Value a1;
typename A2::Value a2;
typename A3::Value a3;
typename A4::Value a4;
using VertexType = Vertex<A1, A2, A3, A4>;
static const std::size_t attributeOffsets[4];
@@ -86,11 +149,11 @@ public:
template <class A1, class A2, class A3, class A4, class A5>
class Vertex<A1, A2, A3, A4, A5> {
public:
typename A1::Type a1;
typename A2::Type a2;
typename A3::Type a3;
typename A4::Type a4;
typename A5::Type a5;
typename A1::Value a1;
typename A2::Value a2;
typename A3::Value a3;
typename A4::Value a4;
typename A5::Value a5;
using VertexType = Vertex<A1, A2, A3, A4, A5>;
static const std::size_t attributeOffsets[5];
@@ -135,37 +198,71 @@ const std::size_t Vertex<A1, A2, A3, A4, A5>::attributeOffsets[5] = {
AttributeLocation bindAttributeLocation(ProgramID, AttributeLocation, const char * name);
void bindAttribute(AttributeLocation location,
std::size_t count,
DataType type,
std::size_t vertexSize,
std::size_t vertexOffset,
std::size_t attributeOffset);
template <class... As>
class Attributes {
public:
using State = IndexedTuple<TypeList<As...>, TypeList<typename As::State...>>;
using Types = TypeList<As...>;
using Locations = IndexedTuple<
TypeList<As...>,
TypeList<typename As::Location...>>;
using Bindings = IndexedTuple<
TypeList<As...>,
TypeList<typename As::Binding...>>;
using VariableBindings = IndexedTuple<
TypeList<As...>,
TypeList<optional<typename As::VariableBinding>...>>;
using Vertex = detail::Vertex<As...>;
template <class A>
static constexpr std::size_t Index = TypeIndex<A, As...>::value;
static State state(const ProgramID& id) {
return State { typename As::State(bindAttributeLocation(id, Index<As>, As::name))... };
static Locations locations(const ProgramID& id) {
return Locations { bindAttributeLocation(id, Index<As>, As::name())... };
}
static std::function<void (std::size_t)> binder(const State& state) {
return [&state] (std::size_t vertexOffset) {
util::ignore({ (bindAttribute(state.template get<As>().location,
state.template get<As>().count,
state.template get<As>().type,
sizeof(Vertex),
vertexOffset,
Vertex::attributeOffsets[Index<As>]), 0)... });
template <class DrawMode>
static Bindings allVariableBindings(const VertexBuffer<Vertex, DrawMode>& buffer) {
static_assert(std::is_standard_layout<Vertex>::value, "vertex type must use standard layout");
return Bindings {
typename As::VariableBinding {
buffer.buffer,
sizeof(Vertex),
Vertex::attributeOffsets[Index<As>]
}...
};
}
static void bind(Context& context,
const Locations& locations,
VariableBindings& oldBindings,
const Bindings& newBindings,
std::size_t vertexOffset) {
util::ignore({ (As::bind(context,
locations.template get<As>(),
oldBindings.template get<As>(),
newBindings.template get<As>(),
vertexOffset), 0)... });
}
};
namespace detail {
template <class...>
struct ConcatenateAttributes;
template <class... As, class... Bs>
struct ConcatenateAttributes<TypeList<As...>, TypeList<Bs...>> {
using Type = Attributes<As..., Bs...>;
};
} // namespace detail
template <class A, class B>
using ConcatenateAttributes = typename detail::ConcatenateAttributes<
typename A::Types,
typename B::Types>::Type;
} // namespace gl
} // namespace mbgl

View File

@@ -122,6 +122,16 @@ UniqueTexture Context::createTexture() {
return UniqueTexture{ std::move(id), { this } };
}
UniqueVertexArray Context::createVertexArray() {
if (!gl::GenVertexArrays) {
throw std::runtime_error("GL_ARB_vertex_array_object extension is required");
}
VertexArrayID id = 0;
MBGL_CHECK_ERROR(gl::GenVertexArrays(1, &id));
return UniqueVertexArray(std::move(id), { this });
}
UniqueFramebuffer Context::createFramebuffer() {
FramebufferID id = 0;
MBGL_CHECK_ERROR(glGenFramebuffers(1, &id));
@@ -407,32 +417,26 @@ void Context::clear(optional<mbgl::Color> color,
}
#if not MBGL_USE_GLES2
PrimitiveType Context::operator()(const Points& points) {
void Context::setDrawMode(const Points& points) {
pointSize = points.pointSize;
return PrimitiveType::Points;
}
#else
PrimitiveType Context::operator()(const Points&) {
return PrimitiveType::Points;
void Context::setDrawMode(const Points&) {
}
#endif // MBGL_USE_GLES2
PrimitiveType Context::operator()(const Lines& lines) {
void Context::setDrawMode(const Lines& lines) {
lineWidth = lines.lineWidth;
return PrimitiveType::Lines;
}
PrimitiveType Context::operator()(const LineStrip& lineStrip) {
void Context::setDrawMode(const LineStrip& lineStrip) {
lineWidth = lineStrip.lineWidth;
return PrimitiveType::LineStrip;
}
PrimitiveType Context::operator()(const Triangles&) {
return PrimitiveType::Triangles;
void Context::setDrawMode(const Triangles&) {
}
PrimitiveType Context::operator()(const TriangleStrip&) {
return PrimitiveType::TriangleStrip;
void Context::setDrawMode(const TriangleStrip&) {
}
void Context::setDepthMode(const DepthMode& depth) {
@@ -474,57 +478,14 @@ void Context::setColorMode(const ColorMode& color) {
colorMask = color.mask;
}
void Context::draw(const Drawable& drawable) {
if (drawable.segments.empty()) {
return;
}
PrimitiveType primitiveType = apply_visitor([&] (auto m) { return (*this)(m); }, drawable.drawMode);
setDepthMode(drawable.depthMode);
setStencilMode(drawable.stencilMode);
setColorMode(drawable.colorMode);
program = drawable.program;
drawable.bindUniforms();
for (const auto& segment : drawable.segments) {
auto needAttributeBindings = [&] () {
if (!gl::GenVertexArrays || !gl::BindVertexArray) {
return true;
}
if (segment.vao) {
vertexArrayObject = *segment.vao;
return false;
}
VertexArrayID id = 0;
MBGL_CHECK_ERROR(gl::GenVertexArrays(1, &id));
vertexArrayObject = id;
segment.vao = UniqueVertexArray(std::move(id), { this });
// If we are initializing a new VAO, we need to force the buffers
// to be rebound. VAOs don't inherit the existing buffer bindings.
vertexBuffer.setDirty();
elementBuffer.setDirty();
return true;
};
if (needAttributeBindings()) {
vertexBuffer = drawable.vertexBuffer;
elementBuffer = drawable.indexBuffer;
drawable.bindAttributes(segment.vertexOffset);
}
MBGL_CHECK_ERROR(glDrawElements(
static_cast<GLenum>(primitiveType),
static_cast<GLsizei>(segment.indexLength),
GL_UNSIGNED_SHORT,
reinterpret_cast<GLvoid*>(sizeof(uint16_t) * segment.indexOffset)));
}
void Context::draw(PrimitiveType primitiveType,
std::size_t indexOffset,
std::size_t indexLength) {
MBGL_CHECK_ERROR(glDrawElements(
static_cast<GLenum>(primitiveType),
static_cast<GLsizei>(indexLength),
GL_UNSIGNED_SHORT,
reinterpret_cast<GLvoid*>(sizeof(uint16_t) * indexOffset)));
}
void Context::performCleanup() {

View File

@@ -13,7 +13,6 @@
#include <mbgl/gl/depth_mode.hpp>
#include <mbgl/gl/stencil_mode.hpp>
#include <mbgl/gl/color_mode.hpp>
#include <mbgl/gl/segment.hpp>
#include <mbgl/util/noncopyable.hpp>
@@ -40,6 +39,7 @@ public:
UniqueProgram createProgram(ShaderID vertexShader, ShaderID fragmentShader);
void linkProgram(ProgramID);
UniqueTexture createTexture();
UniqueVertexArray createVertexArray();
template <class Vertex, class DrawMode>
VertexBuffer<Vertex, DrawMode> createVertexBuffer(VertexVector<Vertex, DrawMode>&& v) {
@@ -119,25 +119,20 @@ public:
optional<float> depth,
optional<int32_t> stencil);
struct Drawable {
DrawMode drawMode;
DepthMode depthMode;
StencilMode stencilMode;
ColorMode colorMode;
gl::ProgramID program;
gl::BufferID vertexBuffer;
gl::BufferID indexBuffer;
const std::vector<Segment>& segments;
std::function<void ()> bindUniforms;
std::function<void (std::size_t)> bindAttributes;
};
void draw(const Drawable&);
void setDrawMode(const Points&);
void setDrawMode(const Lines&);
void setDrawMode(const LineStrip&);
void setDrawMode(const Triangles&);
void setDrawMode(const TriangleStrip&);
void setDepthMode(const DepthMode&);
void setStencilMode(const StencilMode&);
void setColorMode(const ColorMode&);
void draw(PrimitiveType,
std::size_t indexOffset,
std::size_t indexLength);
// Actually remove the objects we marked as abandoned with the above methods.
// Only call this while the OpenGL context is exclusive to this thread.
void performCleanup();
@@ -164,6 +159,8 @@ public:
std::array<State<value::BindTexture>, 2> texture;
State<value::BindVertexArray> vertexArrayObject;
State<value::Program> program;
State<value::BindVertexBuffer> vertexBuffer;
State<value::BindElementBuffer> elementBuffer;
#if not MBGL_USE_GLES2
State<value::PixelZoom> pixelZoom;
@@ -196,8 +193,6 @@ private:
#if not MBGL_USE_GLES2
State<value::PointSize> pointSize;
#endif // MBGL_USE_GLES2
State<value::BindVertexBuffer> vertexBuffer;
State<value::BindElementBuffer> elementBuffer;
UniqueBuffer createVertexBuffer(const void* data, std::size_t size);
UniqueBuffer createIndexBuffer(const void* data, std::size_t size);
@@ -210,12 +205,6 @@ private:
void drawPixels(Size size, const void* data, TextureFormat);
#endif // MBGL_USE_GLES2
PrimitiveType operator()(const Points&);
PrimitiveType operator()(const Lines&);
PrimitiveType operator()(const LineStrip&);
PrimitiveType operator()(const Triangles&);
PrimitiveType operator()(const TriangleStrip&);
friend detail::ProgramDeleter;
friend detail::ShaderDeleter;
friend detail::BufferDeleter;

View File

@@ -1,7 +1,7 @@
#pragma once
#include <mbgl/gl/types.hpp>
#include <mbgl/gl/primitives.hpp>
#include <mbgl/util/variant.hpp>
#include <cassert>
@@ -11,7 +11,9 @@ namespace gl {
class Points {
public:
using Primitive = Point;
static constexpr std::size_t bufferGroupSize = 1;
static constexpr PrimitiveType primitiveType = PrimitiveType::Points;
explicit Points(float pointSize_) : pointSize(pointSize_) {}
@@ -21,7 +23,9 @@ public:
class Lines {
public:
using Primitive = Line;
static constexpr std::size_t bufferGroupSize = 2;
static constexpr PrimitiveType primitiveType = PrimitiveType::Lines;
explicit Lines(float lineWidth_) : lineWidth(lineWidth_) {
assert(lineWidth > 0);
@@ -35,7 +39,9 @@ public:
// LineStrip is a form of "Line" rendering, but the element buffer
// cannot be grouped into logical elements beyond a single Point.
using Primitive = Line;
static constexpr std::size_t bufferGroupSize = 1;
static constexpr PrimitiveType primitiveType = PrimitiveType::LineStrip;
explicit LineStrip(float lineWidth_) : lineWidth(lineWidth_) {
assert(lineWidth > 0);
@@ -47,7 +53,9 @@ public:
class Triangles {
public:
using Primitive = Triangle;
static constexpr std::size_t bufferGroupSize = 3;
static constexpr PrimitiveType primitiveType = PrimitiveType::Triangles;
};
class TriangleStrip {
@@ -55,7 +63,9 @@ public:
// TriangleStrip is a form of "Triangle" rendering, but the element buffer
// cannot be grouped into logical elements beyond a single Point.
using Primitive = Triangle;
static constexpr std::size_t bufferGroupSize = 1;
static constexpr PrimitiveType primitiveType = PrimitiveType::TriangleStrip;
};
// Special draw mode for use with VertexVector<Indexed, Vertex>, in which
@@ -65,12 +75,5 @@ public:
static constexpr std::size_t bufferGroupSize = 1;
};
using DrawMode = variant<
Points,
Lines,
LineStrip,
Triangles,
TriangleStrip>;
} // namespace gl
} // namespace mbgl

View File

@@ -0,0 +1,35 @@
#pragma once
#include <mbgl/math/clamp.hpp>
#include <cassert>
#include <limits>
namespace mbgl {
namespace gl {
template <class T>
class Normalized {
public:
T value;
Normalized() : value(0) {}
explicit Normalized(float f)
: value(static_cast<T>(std::numeric_limits<T>::max() * util::clamp(f, 0.0f, 1.0f))) {
assert(f >= 0.0f);
assert(f <= 1.0f);
}
float denormalized() const {
return float(value) / std::numeric_limits<T>::max();
}
};
template <class T>
bool operator==(const Normalized<T>& lhs, const Normalized<T>& rhs) {
return lhs.value == rhs.value;
}
} // namespace gl
} // namespace mbgl

View File

@@ -20,16 +20,14 @@ public:
using Attributes = As;
using Uniforms = Us;
using Vertex = typename Attributes::Vertex;
using UniformValues = typename Uniforms::Values;
static_assert(std::is_standard_layout<Vertex>::value, "vertex type must use standard layout");
using AttributeBindings = typename Attributes::Bindings;
Program(Context& context, const std::string& vertexSource, const std::string& fragmentSource)
: vertexShader(context.createShader(ShaderType::Vertex, vertexSource)),
fragmentShader(context.createShader(ShaderType::Fragment, fragmentSource)),
program(context.createProgram(vertexShader, fragmentShader)),
attributesState(Attributes::state(program)),
attributeLocations(Attributes::locations(program)),
uniformsState((context.linkProgram(program), Uniforms::state(program))) {}
template <class DrawMode>
@@ -39,22 +37,30 @@ public:
StencilMode stencilMode,
ColorMode colorMode,
UniformValues&& uniformValues,
const VertexBuffer<Vertex>& vertexBuffer,
AttributeBindings&& attributeBindings,
const IndexBuffer<DrawMode>& indexBuffer,
const SegmentVector<Attributes>& segments) {
static_assert(std::is_same<Primitive, typename DrawMode::Primitive>::value, "incompatible draw mode");
context.draw({
std::move(drawMode),
std::move(depthMode),
std::move(stencilMode),
std::move(colorMode),
program,
vertexBuffer.buffer,
indexBuffer.buffer,
segments,
Uniforms::binder(uniformsState, std::move(uniformValues)),
Attributes::binder(attributesState)
});
context.setDrawMode(drawMode);
context.setDepthMode(depthMode);
context.setStencilMode(stencilMode);
context.setColorMode(colorMode);
context.program = program;
Uniforms::bind(uniformsState, std::move(uniformValues));
for (const auto& segment : segments) {
segment.bind(context,
indexBuffer.buffer,
attributeLocations,
attributeBindings);
context.draw(drawMode.primitiveType,
segment.indexOffset,
segment.indexLength);
}
}
private:
@@ -62,7 +68,7 @@ private:
UniqueShader fragmentShader;
UniqueProgram program;
typename Attributes::State attributesState;
typename Attributes::Locations attributeLocations;
typename Uniforms::State uniformsState;
};

7
src/mbgl/gl/segment.cpp Normal file
View File

@@ -0,0 +1,7 @@
#include <mbgl/gl/segment.hpp>
namespace mbgl {
namespace gl {
} // namespace gl
} // namespace mbgl

View File

@@ -1,12 +1,16 @@
#pragma once
#include <mbgl/gl/context.hpp>
#include <mbgl/gl/vertex_buffer.hpp>
#include <mbgl/util/optional.hpp>
#include <cstddef>
#include <vector>
namespace mbgl {
namespace gl {
template <class Attributes>
class Segment {
public:
Segment(std::size_t vertexOffset_,
@@ -24,13 +28,38 @@ public:
std::size_t vertexLength;
std::size_t indexLength;
void bind(Context& context,
BufferID indexBuffer_,
const typename Attributes::Locations& attributeLocations,
const typename Attributes::Bindings& attributeBindings_) const {
if (!vao) {
vao = context.createVertexArray();
context.vertexBuffer.setDirty();
}
context.vertexArrayObject = *vao;
if (indexBuffer != indexBuffer_) {
indexBuffer = indexBuffer_;
context.elementBuffer.setDirty();
context.elementBuffer = indexBuffer_;
}
Attributes::bind(context,
attributeLocations,
variableBindings,
attributeBindings_,
vertexOffset);
}
private:
friend class Context;
mutable optional<UniqueVertexArray> vao;
mutable optional<BufferID> indexBuffer;
mutable typename Attributes::VariableBindings variableBindings;
};
template <class Attributes>
class SegmentVector : public std::vector<Segment> {
class SegmentVector : public std::vector<Segment<Attributes>> {
public:
SegmentVector() = default;
};

View File

@@ -34,16 +34,6 @@ enum class DataType : uint32_t {
Float = 0x1406
};
template <typename T> struct DataTypeOf;
template <> struct DataTypeOf<int8_t> : std::integral_constant<DataType, DataType::Byte> {};
template <> struct DataTypeOf<uint8_t> : std::integral_constant<DataType, DataType::UnsignedByte> {};
template <> struct DataTypeOf<int16_t> : std::integral_constant<DataType, DataType::Short> {};
template <> struct DataTypeOf<uint16_t> : std::integral_constant<DataType, DataType::UnsignedShort> {};
template <> struct DataTypeOf<int32_t> : std::integral_constant<DataType, DataType::Integer> {};
template <> struct DataTypeOf<uint32_t> : std::integral_constant<DataType, DataType::UnsignedInteger> {};
template <> struct DataTypeOf<float> : std::integral_constant<DataType, DataType::Float> {};
enum class RenderbufferType : uint32_t {
RGBA = 0x8058,
DepthStencil = 0x88F0,

View File

@@ -50,32 +50,49 @@ template <class Tag, class T, size_t N>
using UniformMatrix = Uniform<Tag, std::array<T, N*N>>;
#define MBGL_DEFINE_UNIFORM_SCALAR(type_, name_) \
struct name_ : ::mbgl::gl::UniformScalar<name_, type_> { static constexpr auto name = #name_; }
struct name_ : ::mbgl::gl::UniformScalar<name_, type_> { static auto name() { return #name_; } }
#define MBGL_DEFINE_UNIFORM_VECTOR(type_, n_, name_) \
struct name_ : ::mbgl::gl::UniformVector<name_, type_, n_> { static constexpr auto name = #name_; }
struct name_ : ::mbgl::gl::UniformVector<name_, type_, n_> { static auto name() { return #name_; } }
#define MBGL_DEFINE_UNIFORM_MATRIX(type_, n_, name_) \
struct name_ : ::mbgl::gl::UniformMatrix<name_, type_, n_> { static constexpr auto name = #name_; }
struct name_ : ::mbgl::gl::UniformMatrix<name_, type_, n_> { static auto name() { return #name_; } }
UniformLocation uniformLocation(ProgramID, const char * name);
template <class... Us>
class Uniforms {
public:
using Types = TypeList<Us...>;
using State = IndexedTuple<TypeList<Us...>, TypeList<typename Us::State...>>;
using Values = IndexedTuple<TypeList<Us...>, TypeList<typename Us::Value...>>;
static State state(const ProgramID& id) {
return State { { uniformLocation(id, Us::name) }... };
return State { { uniformLocation(id, Us::name()) }... };
}
static std::function<void ()> binder(State& state, Values&& values_) {
return [&state, values = std::move(values_)] () mutable {
util::ignore({ (state.template get<Us>() = values.template get<Us>(), 0)... });
};
static void bind(State& state, Values&& values) {
util::ignore({ (state.template get<Us>() = values.template get<Us>(), 0)... });
}
};
namespace detail {
template <class...>
struct ConcatenateUniforms;
template <class... As, class... Bs>
struct ConcatenateUniforms<TypeList<As...>, TypeList<Bs...>> {
using Type = Uniforms<As..., Bs...>;
};
} // namespace detail
template <class A, class B>
using ConcatenateUniforms = typename detail::ConcatenateUniforms<
typename A::Types,
typename B::Types>::Type;
} // namespace gl
} // namespace mbgl

View File

@@ -3,6 +3,7 @@
#include <mbgl/tile/geometry_tile_data.hpp>
#include <mbgl/util/optional.hpp>
#include <array>
#include <string>
namespace mbgl {
@@ -13,6 +14,8 @@ public:
GeometryCollection geometry;
optional<std::u16string> text;
optional<std::string> icon;
std::array<float, 2> iconOffset;
float iconRotation;
std::size_t index;
};

View File

@@ -3,7 +3,9 @@
#include <mbgl/layout/clip_lines.hpp>
#include <mbgl/renderer/symbol_bucket.hpp>
#include <mbgl/style/filter_evaluator.hpp>
#include <mbgl/style/layer.hpp>
#include <mbgl/style/bucket_parameters.hpp>
#include <mbgl/style/layers/symbol_layer.hpp>
#include <mbgl/style/layers/symbol_layer_impl.hpp>
#include <mbgl/sprite/sprite_atlas.hpp>
#include <mbgl/text/glyph_atlas.hpp>
#include <mbgl/text/get_anchors.hpp>
@@ -27,27 +29,49 @@ namespace mbgl {
using namespace style;
SymbolLayout::SymbolLayout(std::vector<std::string> layerIDs_,
std::string sourceLayerName_,
uint32_t overscaling_,
float zoom_,
const MapMode mode_,
const GeometryTileLayer& layer,
const style::Filter& filter,
style::SymbolLayoutProperties::Evaluated layout_,
float textMaxSize_,
SymbolLayout::SymbolLayout(const BucketParameters& parameters,
const std::vector<const Layer*>& layers,
const GeometryTileLayer& sourceLayer,
SpriteAtlas& spriteAtlas_)
: layerIDs(std::move(layerIDs_)),
sourceLayerName(std::move(sourceLayerName_)),
overscaling(overscaling_),
zoom(zoom_),
mode(mode_),
layout(std::move(layout_)),
textMaxSize(textMaxSize_),
: sourceLayerName(sourceLayer.getName()),
bucketName(layers.at(0)->getID()),
overscaling(parameters.tileID.overscaleFactor()),
zoom(parameters.tileID.overscaledZ),
mode(parameters.mode),
spriteAtlas(spriteAtlas_),
tileSize(util::tileSize * overscaling_),
tileSize(util::tileSize * overscaling),
tilePixelRatio(float(util::EXTENT) / tileSize) {
const SymbolLayer::Impl& leader = *layers.at(0)->as<SymbolLayer>()->impl;
layout = leader.layout.evaluate(PropertyEvaluationParameters(zoom));
if (layout.get<IconRotationAlignment>() == AlignmentType::Auto) {
if (layout.get<SymbolPlacement>() == SymbolPlacementType::Line) {
layout.get<IconRotationAlignment>() = AlignmentType::Map;
} else {
layout.get<IconRotationAlignment>() = AlignmentType::Viewport;
}
}
if (layout.get<TextRotationAlignment>() == AlignmentType::Auto) {
if (layout.get<SymbolPlacement>() == SymbolPlacementType::Line) {
layout.get<TextRotationAlignment>() = AlignmentType::Map;
} else {
layout.get<TextRotationAlignment>() = AlignmentType::Viewport;
}
}
// If unspecified `text-pitch-alignment` inherits `text-rotation-alignment`
if (layout.get<TextPitchAlignment>() == AlignmentType::Auto) {
layout.get<TextPitchAlignment>() = layout.get<TextRotationAlignment>();
}
textMaxSize = leader.layout.evaluate<TextSize>(PropertyEvaluationParameters(18));
layout.get<IconSize>() = leader.layout.evaluate<IconSize>(PropertyEvaluationParameters(zoom + 1));
layout.get<TextSize>() = leader.layout.evaluate<TextSize>(PropertyEvaluationParameters(zoom + 1));
const bool hasText = !layout.get<TextField>().empty() && !layout.get<TextFont>().empty();
const bool hasIcon = !layout.get<IconImage>().empty();
@@ -55,13 +79,15 @@ SymbolLayout::SymbolLayout(std::vector<std::string> layerIDs_,
return;
}
auto layerName = layer.getName();
for (const auto& layer : layers) {
layerPaintProperties.emplace(layer->getID(), layer->as<SymbolLayer>()->impl->paint.evaluated);
}
// Determine and load glyph ranges
const size_t featureCount = layer.featureCount();
const size_t featureCount = sourceLayer.featureCount();
for (size_t i = 0; i < featureCount; ++i) {
auto feature = layer.getFeature(i);
if (!filter(feature->getType(), feature->getID(), [&] (const auto& key) { return feature->getValue(key); }))
auto feature = sourceLayer.getFeature(i);
if (!leader.filter(feature->getType(), feature->getID(), [&] (const auto& key) { return feature->getValue(key); }))
continue;
SymbolFeature ft;
@@ -103,6 +129,8 @@ SymbolLayout::SymbolLayout(std::vector<std::string> layerIDs_,
if (hasIcon) {
ft.icon = util::replaceTokens(layout.get<IconImage>(), getValue);
ft.iconOffset = layout.get<IconOffset>().evaluate(zoom, *feature);
ft.iconRotation = layout.get<IconRotate>().evaluate(zoom, *feature) * util::DEG2RAD;
}
if (ft.text || ft.icon) {
@@ -209,14 +237,14 @@ void SymbolLayout::prepare(uintptr_t tileUID,
if (feature.icon) {
auto image = spriteAtlas.getImage(*feature.icon, SpritePatternMode::Single);
if (image) {
shapedIcon = shapeIcon(*image, layout);
shapedIcon = shapeIcon(*image, feature);
assert((*image).spriteImage);
if ((*image).spriteImage->sdf) {
sdfIcons = true;
}
if ((*image).relativePixelRatio != 1.0f) {
iconsNeedLinear = true;
} else if (layout.get<IconRotate>() != 0) {
} else if (layout.get<IconRotate>().constantOr(1) != 0) {
iconsNeedLinear = true;
}
}
@@ -254,7 +282,7 @@ void SymbolLayout::addFeature(const SymbolFeature& feature,
? SymbolPlacementType::Point
: layout.get<SymbolPlacement>();
const float textRepeatDistance = symbolSpacing / 2;
IndexedSubfeature indexedFeature = {feature.index, sourceLayerName, layerIDs.at(0), symbolInstances.size()};
IndexedSubfeature indexedFeature = {feature.index, sourceLayerName, bucketName, symbolInstances.size()};
auto addSymbolInstance = [&] (const GeometryCoordinates& line, Anchor& anchor) {
// https://github.com/mapbox/vector-tile-spec/tree/master/2.1#41-layers
@@ -350,7 +378,7 @@ bool SymbolLayout::anchorIsTooClose(const std::u16string& text, const float repe
}
std::unique_ptr<SymbolBucket> SymbolLayout::place(CollisionTile& collisionTile) {
auto bucket = std::make_unique<SymbolBucket>(mode, layout, sdfIcons, iconsNeedLinear);
auto bucket = std::make_unique<SymbolBucket>(layout, layerPaintProperties, zoom, sdfIcons, iconsNeedLinear);
// Calculate which labels can be shown and when they can be shown and
// create the bufers used for rendering.
@@ -487,13 +515,13 @@ void SymbolLayout::addSymbols(Buffer &buffer, const SymbolQuads &symbols, float
uint8_t glyphAngle = std::round((symbol.glyphAngle / (M_PI * 2)) * 256);
// coordinates (2 triangles)
buffer.vertices.emplace_back(SymbolAttributes::vertex(anchorPoint, tl, tex.x, tex.y,
buffer.vertices.emplace_back(SymbolLayoutAttributes::vertex(anchorPoint, tl, tex.x, tex.y,
minZoom, maxZoom, placementZoom, glyphAngle));
buffer.vertices.emplace_back(SymbolAttributes::vertex(anchorPoint, tr, tex.x + tex.w, tex.y,
buffer.vertices.emplace_back(SymbolLayoutAttributes::vertex(anchorPoint, tr, tex.x + tex.w, tex.y,
minZoom, maxZoom, placementZoom, glyphAngle));
buffer.vertices.emplace_back(SymbolAttributes::vertex(anchorPoint, bl, tex.x, tex.y + tex.h,
buffer.vertices.emplace_back(SymbolLayoutAttributes::vertex(anchorPoint, bl, tex.x, tex.y + tex.h,
minZoom, maxZoom, placementZoom, glyphAngle));
buffer.vertices.emplace_back(SymbolAttributes::vertex(anchorPoint, br, tex.x + tex.w, tex.y + tex.h,
buffer.vertices.emplace_back(SymbolLayoutAttributes::vertex(anchorPoint, br, tex.x + tex.w, tex.y + tex.h,
minZoom, maxZoom, placementZoom, glyphAngle));
// add the two triangles, referencing the four coordinates we just inserted.

View File

@@ -20,6 +20,7 @@ class GlyphAtlas;
class SymbolBucket;
namespace style {
class BucketParameters;
class Filter;
class Layer;
} // namespace style
@@ -28,15 +29,9 @@ struct Anchor;
class SymbolLayout {
public:
SymbolLayout(std::vector<std::string> layerIDs_,
std::string sourceLayerName_,
uint32_t overscaling,
float zoom,
const MapMode,
SymbolLayout(const style::BucketParameters&,
const std::vector<const style::Layer*>&,
const GeometryTileLayer&,
const style::Filter&,
style::SymbolLayoutProperties::Evaluated,
float textMaxSize,
SpriteAtlas&);
bool canPrepare(GlyphAtlas&);
@@ -56,8 +51,7 @@ public:
State state = Pending;
const std::vector<std::string> layerIDs;
const std::string sourceLayerName;
std::unordered_map<std::string, style::SymbolPaintProperties::Evaluated> layerPaintProperties;
private:
void addFeature(const SymbolFeature&,
@@ -75,11 +69,14 @@ private:
void addSymbols(Buffer&, const SymbolQuads&, float scale,
const bool keepUpright, const style::SymbolPlacementType, const float placementAngle);
const std::string sourceLayerName;
const std::string bucketName;
const float overscaling;
const float zoom;
const MapMode mode;
const style::SymbolLayoutProperties::Evaluated layout;
const float textMaxSize;
style::SymbolLayoutProperties::Evaluated layout;
float textMaxSize;
SpriteAtlas& spriteAtlas;

View File

@@ -1,22 +1,174 @@
#pragma once
#include <mbgl/gl/attribute.hpp>
#include <mbgl/gl/uniform.hpp>
#include <mbgl/gl/normalization.hpp>
#include <cstdint>
namespace mbgl {
namespace attributes {
// Attributes common to several shaders.
// Layout attributes
MBGL_DEFINE_ATTRIBUTE(int16_t, 2, a_pos);
MBGL_DEFINE_ATTRIBUTE(int16_t, 2, a_offset);
MBGL_DEFINE_ATTRIBUTE(int16_t, 2, a_extrude);
MBGL_DEFINE_ATTRIBUTE(uint16_t, 2, a_texture_pos);
template <std::size_t N>
struct a_data : gl::Attribute<a_data<N>, uint8_t, N> {
static constexpr auto name = "a_data";
struct a_data : gl::Attribute<uint8_t, N> {
static auto name() { return "a_data"; }
};
template <std::size_t N>
struct a_offset : gl::Attribute<int16_t, N> {
static auto name() { return "a_offset"; }
};
// Paint attributes
template <class Attr>
struct Min : Attr {
static auto name() {
static const std::string name = Attr::name() + std::string("_min");
return name.c_str();
}
};
template <class Attr>
struct Max : Attr {
static auto name() {
static const std::string name = Attr::name() + std::string("_max");
return name.c_str();
}
};
template <class Attr>
struct InterpolationUniform : gl::UniformScalar<InterpolationUniform<Attr>, float> {
static auto name() {
static const std::string name = Attr::name() + std::string("_t");
return name.c_str();
}
};
struct a_color : gl::Attribute<gl::Normalized<uint8_t>, 4> {
static auto name() { return "a_color"; }
static Value value(const Color& color) {
return {{
gl::Normalized<uint8_t>(color.r),
gl::Normalized<uint8_t>(color.g),
gl::Normalized<uint8_t>(color.b),
gl::Normalized<uint8_t>(color.a)
}};
}
};
struct a_stroke_color : gl::Attribute<gl::Normalized<uint8_t>, 4> {
static auto name() { return "a_stroke_color"; }
static Value value(const Color& color) {
return {{
gl::Normalized<uint8_t>(color.r),
gl::Normalized<uint8_t>(color.g),
gl::Normalized<uint8_t>(color.b),
gl::Normalized<uint8_t>(color.a)
}};
}
};
struct a_outline_color : gl::Attribute<gl::Normalized<uint8_t>, 4> {
static auto name() { return "a_outline_color"; }
static Value value(const Color& color) {
return {{
gl::Normalized<uint8_t>(color.r),
gl::Normalized<uint8_t>(color.g),
gl::Normalized<uint8_t>(color.b),
gl::Normalized<uint8_t>(color.a)
}};
}
};
struct a_opacity : gl::Attribute<gl::Normalized<uint8_t>, 1> {
static auto name() { return "a_opacity"; }
static Value value(float opacity) {
return {{ gl::Normalized<uint8_t>(opacity) }};
}
};
struct a_stroke_opacity : gl::Attribute<gl::Normalized<uint8_t>, 1> {
static auto name() { return "a_stroke_opacity"; }
static Value value(float opacity) {
return {{ gl::Normalized<uint8_t>(opacity) }};
}
};
struct a_blur : gl::Attribute<float, 1> {
static auto name() { return "a_blur"; }
static Value value(float blur) {
return {{ blur }};
}
};
struct a_radius : gl::Attribute<float, 1> {
static auto name() { return "a_radius"; }
static Value value(float radius) {
return {{ radius }};
}
};
struct a_width : gl::Attribute<float, 1> {
static auto name() { return "a_width"; }
static Value value(float width) {
return {{ width }};
}
};
struct a_height : gl::Attribute<float, 1> {
static auto name() { return "a_height"; }
static Value value(float width) {
return {{ width }};
}
};
struct a_base : gl::Attribute<float, 1> {
static auto name() { return "a_base"; }
static Value value(float width) {
return {{ width }};
}
};
struct a_gap_width : gl::Attribute<float, 1> {
static auto name() { return "a_gapwidth"; }
static Value value(float width) {
return {{ width }};
}
};
struct a_stroke_width : gl::Attribute<float, 1> {
static auto name() { return "a_stroke_width"; }
static Value value(float width) {
return {{ width }};
}
};
template <>
struct a_offset<1> : gl::Attribute<float, 1> {
static auto name() { return "a_offset"; }
static Value value(float offset) {
return {{ offset }};
}
};
} // namespace attributes

View File

@@ -2,6 +2,6 @@
namespace mbgl {
static_assert(sizeof(CircleProgram::Vertex) == 4, "expected CircleVertex size");
static_assert(sizeof(CircleLayoutVertex) == 4, "expected CircleLayoutVertex size");
} // namespace mbgl

View File

@@ -5,35 +5,24 @@
#include <mbgl/programs/uniforms.hpp>
#include <mbgl/shader/circle.hpp>
#include <mbgl/util/geometry.hpp>
#include <mbgl/style/layers/circle_layer_properties.hpp>
namespace mbgl {
namespace uniforms {
MBGL_DEFINE_UNIFORM_SCALAR(float, u_radius);
MBGL_DEFINE_UNIFORM_SCALAR(Color, u_stroke_color);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_stroke_width);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_stroke_opacity);
MBGL_DEFINE_UNIFORM_SCALAR(bool, u_scale_with_map);
} // namespace uniforms
using CircleAttributes = gl::Attributes<
attributes::a_pos>;
class CircleProgram : public Program<
shaders::circle,
gl::Triangle,
CircleAttributes,
gl::Attributes<
attributes::a_pos>,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_opacity,
uniforms::u_color,
uniforms::u_radius,
uniforms::u_blur,
uniforms::u_stroke_color,
uniforms::u_stroke_width,
uniforms::u_stroke_opacity,
uniforms::u_scale_with_map,
uniforms::u_extrude_scale>>
uniforms::u_extrude_scale>,
style::CirclePaintProperties>
{
public:
using Program::Program;
@@ -44,16 +33,17 @@ public:
* @param {number} ex extrude normal
* @param {number} ey extrude normal
*/
static Vertex vertex(Point<int16_t> p, float ex, float ey) {
return Vertex {
{
static LayoutVertex vertex(Point<int16_t> p, float ex, float ey) {
return LayoutVertex {
{{
static_cast<int16_t>((p.x * 2) + ((ex + 1) / 2)),
static_cast<int16_t>((p.y * 2) + ((ey + 1) / 2))
}
}}
};
}
};
using CircleVertex = CircleProgram::Vertex;
using CircleLayoutVertex = CircleProgram::LayoutVertex;
using CircleAttributes = CircleProgram::Attributes;
} // namespace mbgl

View File

@@ -2,6 +2,6 @@
namespace mbgl {
static_assert(sizeof(CollisionBoxProgram::Vertex) == 10, "expected CollisionBoxVertex size");
static_assert(sizeof(CollisionBoxProgram::LayoutVertex) == 10, "expected CollisionBoxVertex size");
} // namespace mbgl

View File

@@ -28,29 +28,30 @@ class CollisionBoxProgram : public Program<
uniforms::u_matrix,
uniforms::u_scale,
uniforms::u_zoom,
uniforms::u_maxzoom>>
uniforms::u_maxzoom>,
style::PaintProperties<>>
{
public:
using Program::Program;
static Vertex vertex(Point<float> a, Point<float> o, float maxzoom, float placementZoom) {
return Vertex {
{
static LayoutVertex vertex(Point<float> a, Point<float> o, float maxzoom, float placementZoom) {
return LayoutVertex {
{{
static_cast<int16_t>(a.x),
static_cast<int16_t>(a.y)
},
{
}},
{{
static_cast<int16_t>(::round(o.x)),
static_cast<int16_t>(::round(o.y))
},
{
}},
{{
static_cast<uint8_t>(maxzoom * 10),
static_cast<uint8_t>(placementZoom * 10)
}
}}
};
}
};
using CollisionBoxVertex = CollisionBoxProgram::Vertex;
using CollisionBoxVertex = CollisionBoxProgram::LayoutVertex;
} // namespace mbgl

View File

@@ -7,21 +7,21 @@
namespace mbgl {
using DebugAttributes = gl::Attributes<
attributes::a_pos>;
class DebugProgram : public Program<
shaders::debug,
gl::Line,
DebugAttributes,
gl::Attributes<
attributes::a_pos>,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_color>>
uniforms::u_color>,
style::PaintProperties<>>
{
public:
using Program::Program;
};
using DebugVertex = DebugProgram::Vertex;
using DebugLayoutVertex = DebugProgram::LayoutVertex;
using DebugAttributes = DebugProgram::Attributes;
} // namespace mbgl

View File

@@ -8,11 +8,10 @@ namespace mbgl {
using namespace style;
static_assert(sizeof(FillAttributes::Vertex) == 4, "expected FillVertex size");
static_assert(sizeof(FillLayoutVertex) == 4, "expected FillLayoutVertex size");
FillPatternUniforms::Values
FillPatternUniforms::values(mat4 matrix,
float opacity,
Size framebufferSize,
const SpriteAtlasPosition& a,
const SpriteAtlasPosition& b,
@@ -26,7 +25,6 @@ FillPatternUniforms::values(mat4 matrix,
return FillPatternUniforms::Values {
uniforms::u_matrix::Value{ matrix },
uniforms::u_opacity::Value{ opacity },
uniforms::u_world::Value{ framebufferSize },
uniforms::u_pattern_tl_a::Value{ a.tl },
uniforms::u_pattern_br_a::Value{ a.br },

View File

@@ -10,6 +10,7 @@
#include <mbgl/util/geometry.hpp>
#include <mbgl/util/mat4.hpp>
#include <mbgl/util/size.hpp>
#include <mbgl/style/layers/fill_layer_properties.hpp>
#include <string>
@@ -25,7 +26,6 @@ template <class> class Faded;
namespace uniforms {
MBGL_DEFINE_UNIFORM_SCALAR(Size, u_world);
MBGL_DEFINE_UNIFORM_SCALAR(Color, u_outline_color);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_scale_a);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_scale_b);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_tile_units_to_pixels);
@@ -33,32 +33,17 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 2, u_pixel_coord_upper);
MBGL_DEFINE_UNIFORM_VECTOR(float, 2, u_pixel_coord_lower);
} // namespace uniforms
struct FillAttributes : gl::Attributes<
struct FillLayoutAttributes : gl::Attributes<
attributes::a_pos>
{
static Vertex vertex(Point<int16_t> p) {
return Vertex {
{
p.x,
p.y
}
};
}
};
using FillVertex = FillAttributes::Vertex;
{};
struct FillUniforms : gl::Uniforms<
uniforms::u_matrix,
uniforms::u_opacity,
uniforms::u_color,
uniforms::u_outline_color,
uniforms::u_world>
{};
struct FillPatternUniforms : gl::Uniforms<
uniforms::u_matrix,
uniforms::u_opacity,
uniforms::u_world,
uniforms::u_pattern_tl_a,
uniforms::u_pattern_br_a,
@@ -75,7 +60,6 @@ struct FillPatternUniforms : gl::Uniforms<
uniforms::u_tile_units_to_pixels>
{
static Values values(mat4 matrix,
float opacity,
Size framebufferSize,
const SpriteAtlasPosition&,
const SpriteAtlasPosition&,
@@ -87,37 +71,57 @@ struct FillPatternUniforms : gl::Uniforms<
class FillProgram : public Program<
shaders::fill,
gl::Triangle,
FillAttributes,
FillUniforms>
FillLayoutAttributes,
FillUniforms,
style::FillPaintProperties>
{
public:
using Program::Program;
static LayoutVertex layoutVertex(Point<int16_t> p) {
return LayoutVertex {
{{
p.x,
p.y
}}
};
}
};
class FillPatternProgram : public Program<
shaders::fill_pattern,
gl::Triangle,
FillAttributes,
FillPatternUniforms>
FillLayoutAttributes,
FillPatternUniforms,
style::FillPaintProperties>
{
public:
using Program::Program;
};
class FillOutlineProgram : public Program<
shaders::fill_outline,
gl::Line,
FillAttributes,
FillUniforms>
FillLayoutAttributes,
FillUniforms,
style::FillPaintProperties>
{
public:
using Program::Program;
};
class FillOutlinePatternProgram : public Program<
shaders::fill_outline_pattern,
gl::Line,
FillAttributes,
FillPatternUniforms>
FillLayoutAttributes,
FillPatternUniforms,
style::FillPaintProperties>
{
public:
using Program::Program;
};
using FillLayoutVertex = FillProgram::LayoutVertex;
using FillAttributes = FillProgram::Attributes;
} // namespace mbgl

View File

@@ -10,7 +10,7 @@ namespace mbgl {
using namespace style;
static_assert(sizeof(LineAttributes::Vertex) == 8, "expected LineVertex size");
static_assert(sizeof(LineLayoutVertex) == 8, "expected LineLayoutVertex size");
template <class Values, class...Args>
Values makeValues(const LinePaintProperties::Evaluated& properties,
@@ -25,11 +25,7 @@ Values makeValues(const LinePaintProperties::Evaluated& properties,
properties.get<LineTranslateAnchor>(),
state)
},
uniforms::u_opacity::Value{ properties.get<LineOpacity>() },
uniforms::u_width::Value{ properties.get<LineWidth>() },
uniforms::u_gapwidth::Value{ properties.get<LineGapWidth>() },
uniforms::u_blur::Value{ properties.get<LineBlur>() },
uniforms::u_offset::Value{ properties.get<LineOffset>() },
uniforms::u_ratio::Value{ 1.0f / tile.id.pixelsToTileUnits(1.0, state.getZoom()) },
uniforms::u_gl_units_to_pixels::Value{{{ 1.0f / pixelsToGLUnits[0], 1.0f / pixelsToGLUnits[1] }}},
std::forward<Args>(args)...
@@ -45,8 +41,7 @@ LineProgram::uniformValues(const LinePaintProperties::Evaluated& properties,
properties,
tile,
state,
pixelsToGLUnits,
uniforms::u_color::Value{ properties.get<LineColor>() }
pixelsToGLUnits
);
}
@@ -78,7 +73,6 @@ LineSDFProgram::uniformValues(const LinePaintProperties::Evaluated& properties,
tile,
state,
pixelsToGLUnits,
uniforms::u_color::Value{ properties.get<LineColor>() },
uniforms::u_patternscale_a::Value{ scaleA },
uniforms::u_patternscale_b::Value{ scaleB },
uniforms::u_tex_y_a::Value{ posA.y },

View File

@@ -6,8 +6,8 @@
#include <mbgl/shader/line.hpp>
#include <mbgl/shader/line_pattern.hpp>
#include <mbgl/shader/line_sdf.hpp>
#include <mbgl/style/layers/line_layer_properties.hpp>
#include <mbgl/util/geometry.hpp>
#include <mbgl/style/layers/line_layer_properties.hpp>
#include <cmath>
@@ -21,8 +21,6 @@ class SpriteAtlasPosition;
namespace uniforms {
MBGL_DEFINE_UNIFORM_SCALAR(float, u_ratio);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_width);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_gapwidth);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_offset);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_tex_y_a);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_tex_y_b);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_sdfgamma);
@@ -32,23 +30,38 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 2, u_patternscale_b);
MBGL_DEFINE_UNIFORM_VECTOR(float, 2, u_gl_units_to_pixels);
} // namespace uniforms
struct LineAttributes : gl::Attributes<
struct LineLayoutAttributes : gl::Attributes<
attributes::a_pos,
attributes::a_data<4>>
{};
class LineProgram : public Program<
shaders::line,
gl::Triangle,
LineLayoutAttributes,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_width,
uniforms::u_ratio,
uniforms::u_gl_units_to_pixels>,
style::LinePaintProperties>
{
public:
using Program::Program;
/*
* @param p vertex position
* @param e extrude normal
* @param t texture normal
* @param dir direction of the line cap (-1/0/1)
*/
static Vertex vertex(Point<int16_t> p, Point<double> e, Point<bool> t, int8_t dir, int32_t linesofar = 0) {
return Vertex {
{
static LayoutVertex layoutVertex(Point<int16_t> p, Point<double> e, Point<bool> t, int8_t dir, int32_t linesofar = 0) {
return LayoutVertex {
{{
static_cast<int16_t>((p.x * 2) | t.x),
static_cast<int16_t>((p.y * 2) | t.y)
},
{
}},
{{
// add 128 to store a byte in an unsigned byte
static_cast<uint8_t>(::round(extrudeScale * e.x) + 128),
static_cast<uint8_t>(::round(extrudeScale * e.y) + 128),
@@ -65,7 +78,7 @@ struct LineAttributes : gl::Attributes<
// so we need to shift the linesofar.
static_cast<uint8_t>(((dir == 0 ? 0 : (dir < 0 ? -1 : 1 )) + 1) | ((linesofar & 0x3F) << 2)),
static_cast<uint8_t>(linesofar >> 6)
}
}}
};
}
@@ -77,27 +90,6 @@ struct LineAttributes : gl::Attributes<
* the acute/bevelled line join.
*/
static const int8_t extrudeScale = 63;
};
using LineVertex = LineAttributes::Vertex;
class LineProgram : public Program<
shaders::line,
gl::Triangle,
LineAttributes,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_opacity,
uniforms::u_width,
uniforms::u_gapwidth,
uniforms::u_blur,
uniforms::u_offset,
uniforms::u_ratio,
uniforms::u_gl_units_to_pixels,
uniforms::u_color>>
{
public:
using Program::Program;
static UniformValues uniformValues(const style::LinePaintProperties::Evaluated&,
const RenderTile&,
@@ -108,14 +100,10 @@ public:
class LinePatternProgram : public Program<
shaders::line_pattern,
gl::Triangle,
LineAttributes,
LineLayoutAttributes,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_opacity,
uniforms::u_width,
uniforms::u_gapwidth,
uniforms::u_blur,
uniforms::u_offset,
uniforms::u_ratio,
uniforms::u_gl_units_to_pixels,
uniforms::u_pattern_tl_a,
@@ -125,7 +113,8 @@ class LinePatternProgram : public Program<
uniforms::u_pattern_size_a,
uniforms::u_pattern_size_b,
uniforms::u_fade,
uniforms::u_image>>
uniforms::u_image>,
style::LinePaintProperties>
{
public:
using Program::Program;
@@ -141,24 +130,20 @@ public:
class LineSDFProgram : public Program<
shaders::line_sdf,
gl::Triangle,
LineAttributes,
LineLayoutAttributes,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_opacity,
uniforms::u_width,
uniforms::u_gapwidth,
uniforms::u_blur,
uniforms::u_offset,
uniforms::u_ratio,
uniforms::u_gl_units_to_pixels,
uniforms::u_color,
uniforms::u_patternscale_a,
uniforms::u_patternscale_b,
uniforms::u_tex_y_a,
uniforms::u_tex_y_b,
uniforms::u_mix,
uniforms::u_sdfgamma,
uniforms::u_image>>
uniforms::u_image>,
style::LinePaintProperties>
{
public:
using Program::Program;
@@ -174,4 +159,7 @@ public:
float atlasWidth);
};
using LineLayoutVertex = LineProgram::LayoutVertex;
using LineAttributes = LineProgram::Attributes;
} // namespace mbgl

View File

@@ -2,19 +2,38 @@
#include <mbgl/gl/program.hpp>
#include <mbgl/programs/program_parameters.hpp>
#include <mbgl/programs/attributes.hpp>
#include <mbgl/style/paint_property.hpp>
#include <sstream>
#include <cassert>
namespace mbgl {
template <class Shaders, class Primitive, class Attributes, class Uniforms>
class Program : public gl::Program<Primitive, Attributes, Uniforms> {
template <class Shaders,
class Primitive,
class LayoutAttrs,
class Uniforms,
class PaintProperties>
class Program {
public:
using ParentType = gl::Program<Primitive, Attributes, Uniforms>;
using LayoutAttributes = LayoutAttrs;
using LayoutVertex = typename LayoutAttributes::Vertex;
using PaintPropertyBinders = typename PaintProperties::Binders;
using PaintAttributes = typename PaintPropertyBinders::Attributes;
using Attributes = gl::ConcatenateAttributes<LayoutAttributes, PaintAttributes>;
using UniformValues = typename Uniforms::Values;
using PaintUniforms = typename PaintPropertyBinders::Uniforms;
using AllUniforms = gl::ConcatenateUniforms<Uniforms, PaintUniforms>;
using ProgramType = gl::Program<Primitive, Attributes, AllUniforms>;
ProgramType program;
Program(gl::Context& context, const ProgramParameters& programParameters)
: ParentType(context, vertexSource(programParameters), fragmentSource(programParameters))
: program(context, vertexSource(programParameters), fragmentSource(programParameters))
{}
static std::string pixelRatioDefine(const ProgramParameters& parameters) {
@@ -38,6 +57,33 @@ public:
return pixelRatioDefine(parameters) + Shaders::vertexSource;
}
template <class DrawMode>
void draw(gl::Context& context,
DrawMode drawMode,
gl::DepthMode depthMode,
gl::StencilMode stencilMode,
gl::ColorMode colorMode,
UniformValues&& uniformValues,
const gl::VertexBuffer<LayoutVertex>& layoutVertexBuffer,
const gl::IndexBuffer<DrawMode>& indexBuffer,
const gl::SegmentVector<Attributes>& segments,
const PaintPropertyBinders& paintPropertyBinders,
const typename PaintProperties::Evaluated& currentProperties,
float currentZoom) {
program.draw(
context,
std::move(drawMode),
std::move(depthMode),
std::move(stencilMode),
std::move(colorMode),
uniformValues
.concat(paintPropertyBinders.uniformValues(currentZoom)),
LayoutAttributes::allVariableBindings(layoutVertexBuffer)
.concat(paintPropertyBinders.attributeBindings(currentProperties)),
indexBuffer,
segments
);
}
};
} // namespace mbgl

View File

@@ -2,6 +2,6 @@
namespace mbgl {
static_assert(sizeof(RasterProgram::Vertex) == 8, "expected RasterVertex size");
static_assert(sizeof(RasterLayoutVertex) == 8, "expected RasterLayoutVertex size");
} // namespace mbgl

View File

@@ -5,6 +5,7 @@
#include <mbgl/programs/uniforms.hpp>
#include <mbgl/shader/raster.hpp>
#include <mbgl/util/geometry.hpp>
#include <mbgl/style/layers/raster_layer_properties.hpp>
namespace mbgl {
@@ -22,14 +23,12 @@ MBGL_DEFINE_UNIFORM_VECTOR(float, 3, u_spin_weights);
MBGL_DEFINE_UNIFORM_VECTOR(float, 2, u_tl_parent);
} // namespace uniforms
using RasterAttributes = gl::Attributes<
attributes::a_pos,
attributes::a_texture_pos>;
class RasterProgram : public Program<
shaders::raster,
gl::Triangle,
RasterAttributes,
gl::Attributes<
attributes::a_pos,
attributes::a_texture_pos>,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_image0,
@@ -43,25 +42,27 @@ class RasterProgram : public Program<
uniforms::u_spin_weights,
uniforms::u_buffer_scale,
uniforms::u_scale_parent,
uniforms::u_tl_parent>>
uniforms::u_tl_parent>,
style::RasterPaintProperties>
{
public:
using Program::Program;
static Vertex vertex(Point<int16_t> p, Point<uint16_t> t) {
return Vertex {
{
static LayoutVertex layoutVertex(Point<int16_t> p, Point<uint16_t> t) {
return LayoutVertex {
{{
p.x,
p.y
},
{
}},
{{
t.x,
t.y
}
}}
};
}
};
using RasterVertex = RasterProgram::Vertex;
using RasterLayoutVertex = RasterProgram::LayoutVertex;
using RasterAttributes = RasterProgram::Attributes;
} // namespace mbgl

View File

@@ -7,7 +7,7 @@ namespace mbgl {
using namespace style;
static_assert(sizeof(SymbolAttributes::Vertex) == 16, "expected SymbolVertex size");
static_assert(sizeof(SymbolLayoutVertex) == 16, "expected SymbolLayoutVertex size");
template <class Values, class...Args>
Values makeValues(const style::SymbolPropertyValues& values,

View File

@@ -7,6 +7,7 @@
#include <mbgl/shader/symbol_sdf.hpp>
#include <mbgl/util/geometry.hpp>
#include <mbgl/util/size.hpp>
#include <mbgl/style/layers/symbol_layer_properties.hpp>
#include <cmath>
#include <array>
@@ -31,9 +32,9 @@ MBGL_DEFINE_UNIFORM_SCALAR(float, u_gamma);
MBGL_DEFINE_UNIFORM_SCALAR(float, u_aspect_ratio);
} // namespace uniforms
struct SymbolAttributes : gl::Attributes<
struct SymbolLayoutAttributes : gl::Attributes<
attributes::a_pos,
attributes::a_offset,
attributes::a_offset<2>,
attributes::a_texture_pos,
attributes::a_data<4>>
{
@@ -46,34 +47,32 @@ struct SymbolAttributes : gl::Attributes<
float labelminzoom,
uint8_t labelangle) {
return Vertex {
{
{{
static_cast<int16_t>(a.x),
static_cast<int16_t>(a.y)
},
{
}},
{{
static_cast<int16_t>(::round(o.x * 64)), // use 1/64 pixels for placement
static_cast<int16_t>(::round(o.y * 64))
},
{
}},
{{
static_cast<uint16_t>(tx / 4),
static_cast<uint16_t>(ty / 4)
},
{
}},
{{
static_cast<uint8_t>(labelminzoom * 10), // 1/10 zoom levels: z16 == 160
static_cast<uint8_t>(labelangle),
static_cast<uint8_t>(minzoom * 10),
static_cast<uint8_t>(::fmin(maxzoom, 25) * 10)
}
}}
};
}
};
using SymbolVertex = SymbolAttributes::Vertex;
class SymbolIconProgram : public Program<
shaders::symbol_icon,
gl::Triangle,
SymbolAttributes,
SymbolLayoutAttributes,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_opacity,
@@ -82,7 +81,8 @@ class SymbolIconProgram : public Program<
uniforms::u_zoom,
uniforms::u_rotate_with_map,
uniforms::u_texture,
uniforms::u_fadetexture>>
uniforms::u_fadetexture>,
style::SymbolPaintProperties>
{
public:
using Program::Program;
@@ -97,7 +97,7 @@ public:
class SymbolSDFProgram : public Program<
shaders::symbol_sdf,
gl::Triangle,
SymbolAttributes,
SymbolLayoutAttributes,
gl::Uniforms<
uniforms::u_matrix,
uniforms::u_opacity,
@@ -113,7 +113,8 @@ class SymbolSDFProgram : public Program<
uniforms::u_pitch,
uniforms::u_bearing,
uniforms::u_aspect_ratio,
uniforms::u_pitch_with_map>>
uniforms::u_pitch_with_map>,
style::SymbolPaintProperties>
{
public:
using Program::Program;
@@ -133,4 +134,7 @@ public:
float pixelRatio);
};
using SymbolLayoutVertex = SymbolLayoutAttributes::Vertex;
using SymbolAttributes = SymbolIconProgram::Attributes;
} // namespace mbgl

View File

@@ -2,6 +2,7 @@
#include <mbgl/renderer/render_pass.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <mbgl/tile/geometry_tile_data.hpp>
#include <atomic>
@@ -22,6 +23,10 @@ class Layer;
class Bucket : private util::noncopyable {
public:
Bucket() = default;
virtual ~Bucket() = default;
virtual void addFeature(const GeometryTileFeature&,
const GeometryCollection&) {};
// As long as this bucket has a Prepare render pass, this function is getting called. Typically,
// this only happens once when the bucket is being rendered for the first time.
@@ -31,8 +36,6 @@ public:
// once or twice (for Opaque and Transparent render passes).
virtual void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) = 0;
virtual ~Bucket() = default;
virtual bool hasData() const = 0;
bool needsUpload() const {

View File

@@ -1,21 +1,33 @@
#include <mbgl/renderer/circle_bucket.hpp>
#include <mbgl/renderer/painter.hpp>
#include <mbgl/gl/context.hpp>
#include <mbgl/programs/circle_program.hpp>
#include <mbgl/style/bucket_parameters.hpp>
#include <mbgl/style/layers/circle_layer.hpp>
#include <mbgl/style/layers/circle_layer_impl.hpp>
#include <mbgl/util/constants.hpp>
namespace mbgl {
using namespace style;
CircleBucket::CircleBucket(MapMode mode_) : mode(mode_) {
CircleBucket::CircleBucket(const BucketParameters& parameters, const std::vector<const Layer*>& layers)
: mode(parameters.mode) {
for (const auto& layer : layers) {
paintPropertyBinders.emplace(layer->getID(),
CircleProgram::PaintPropertyBinders(
layer->as<CircleLayer>()->impl->paint.evaluated,
parameters.tileID.overscaledZ));
}
}
void CircleBucket::upload(gl::Context& context) {
vertexBuffer = context.createVertexBuffer(std::move(vertices));
indexBuffer = context.createIndexBuffer(std::move(triangles));
for (auto& pair : paintPropertyBinders) {
pair.second.upload(context);
}
uploaded = true;
}
@@ -30,10 +42,11 @@ bool CircleBucket::hasData() const {
return !segments.empty();
}
void CircleBucket::addGeometry(const GeometryCollection& geometryCollection) {
void CircleBucket::addFeature(const GeometryTileFeature& feature,
const GeometryCollection& geometry) {
constexpr const uint16_t vertexLength = 4;
for (auto& circle : geometryCollection) {
for (auto& circle : geometry) {
for(auto& point : circle) {
auto x = point.x;
auto y = point.y;
@@ -76,6 +89,10 @@ void CircleBucket::addGeometry(const GeometryCollection& geometryCollection) {
segment.indexLength += 6;
}
}
for (auto& pair : paintPropertyBinders) {
pair.second.populateVertexVectors(feature, vertices.vertexSize());
}
}
} // namespace mbgl

View File

@@ -7,26 +7,34 @@
#include <mbgl/gl/index_buffer.hpp>
#include <mbgl/gl/segment.hpp>
#include <mbgl/programs/circle_program.hpp>
#include <mbgl/style/layers/circle_layer_properties.hpp>
namespace mbgl {
namespace style {
class BucketParameters;
} // namespace style
class CircleBucket : public Bucket {
public:
CircleBucket(const MapMode);
CircleBucket(const style::BucketParameters&, const std::vector<const style::Layer*>&);
void addFeature(const GeometryTileFeature&,
const GeometryCollection&) override;
bool hasData() const override;
void upload(gl::Context&) override;
void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) override;
bool hasData() const override;
void addGeometry(const GeometryCollection&);
gl::VertexVector<CircleVertex> vertices;
gl::VertexVector<CircleLayoutVertex> vertices;
gl::IndexVector<gl::Triangles> triangles;
gl::SegmentVector<CircleAttributes> segments;
optional<gl::VertexBuffer<CircleVertex>> vertexBuffer;
optional<gl::VertexBuffer<CircleLayoutVertex>> vertexBuffer;
optional<gl::IndexBuffer<gl::Triangles>> indexBuffer;
std::unordered_map<std::string, CircleProgram::PaintPropertyBinders> paintPropertyBinders;
const MapMode mode;
};

View File

@@ -23,7 +23,7 @@ DebugBucket::DebugBucket(const OverscaledTileID& id,
expires(std::move(expires_)),
debugMode(debugMode_) {
gl::VertexVector<FillVertex> vertices;
gl::VertexVector<FillLayoutVertex> vertices;
gl::IndexVector<gl::Lines> indices;
auto addText = [&] (const std::string& text, double left, double baseline, double scale) {
@@ -43,7 +43,7 @@ DebugBucket::DebugBucket(const OverscaledTileID& id,
int16_t(::round(baseline - glyph.data[j + 1] * scale))
};
vertices.emplace_back(FillAttributes::vertex(p));
vertices.emplace_back(FillProgram::layoutVertex(p));
if (prev) {
indices.emplace_back(vertices.vertexSize() - 2,

View File

@@ -34,7 +34,7 @@ public:
const MapDebugOptions debugMode;
gl::SegmentVector<DebugAttributes> segments;
optional<gl::VertexBuffer<DebugVertex>> vertexBuffer;
optional<gl::VertexBuffer<DebugLayoutVertex>> vertexBuffer;
optional<gl::IndexBuffer<gl::Lines>> indexBuffer;
};

View File

@@ -1,8 +1,9 @@
#include <mbgl/renderer/fill_bucket.hpp>
#include <mbgl/style/layers/fill_layer.hpp>
#include <mbgl/renderer/painter.hpp>
#include <mbgl/programs/fill_program.hpp>
#include <mbgl/util/logging.hpp>
#include <mbgl/style/bucket_parameters.hpp>
#include <mbgl/style/layers/fill_layer.hpp>
#include <mbgl/style/layers/fill_layer_impl.hpp>
#include <mapbox/earcut.hpp>
@@ -26,7 +27,17 @@ using namespace style;
struct GeometryTooLongException : std::exception {};
void FillBucket::addGeometry(const GeometryCollection& geometry) {
FillBucket::FillBucket(const BucketParameters& parameters, const std::vector<const Layer*>& layers) {
for (const auto& layer : layers) {
paintPropertyBinders.emplace(layer->getID(),
FillProgram::PaintPropertyBinders(
layer->as<FillLayer>()->impl->paint.evaluated,
parameters.tileID.overscaledZ));
}
}
void FillBucket::addFeature(const GeometryTileFeature& feature,
const GeometryCollection& geometry) {
for (auto& polygon : classifyRings(geometry)) {
// Optimize polygons with many interior rings for earcut tesselation.
limitHoles(polygon, 500);
@@ -55,11 +66,11 @@ void FillBucket::addGeometry(const GeometryCollection& geometry) {
assert(lineSegment.vertexLength <= std::numeric_limits<uint16_t>::max());
uint16_t lineIndex = lineSegment.vertexLength;
vertices.emplace_back(FillAttributes::vertex(ring[0]));
vertices.emplace_back(FillProgram::layoutVertex(ring[0]));
lines.emplace_back(lineIndex + nVertices - 1, lineIndex);
for (uint32_t i = 1; i < nVertices; i++) {
vertices.emplace_back(FillAttributes::vertex(ring[i]));
vertices.emplace_back(FillProgram::layoutVertex(ring[i]));
lines.emplace_back(lineIndex + i - 1, lineIndex + i);
}
@@ -89,6 +100,10 @@ void FillBucket::addGeometry(const GeometryCollection& geometry) {
triangleSegment.vertexLength += totalVertices;
triangleSegment.indexLength += nIndicies;
}
for (auto& pair : paintPropertyBinders) {
pair.second.populateVertexVectors(feature, vertices.vertexSize());
}
}
void FillBucket::upload(gl::Context& context) {
@@ -96,7 +111,10 @@ void FillBucket::upload(gl::Context& context) {
lineIndexBuffer = context.createIndexBuffer(std::move(lines));
triangleIndexBuffer = context.createIndexBuffer(std::move(triangles));
// From now on, we're going to render during the opaque and translucent pass.
for (auto& pair : paintPropertyBinders) {
pair.second.upload(context);
}
uploaded = true;
}

View File

@@ -6,28 +6,38 @@
#include <mbgl/gl/index_buffer.hpp>
#include <mbgl/gl/segment.hpp>
#include <mbgl/programs/fill_program.hpp>
#include <mbgl/style/layers/fill_layer_properties.hpp>
#include <vector>
namespace mbgl {
namespace style {
class BucketParameters;
} // namespace style
class FillBucket : public Bucket {
public:
void upload(gl::Context&) override;
void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) override;
FillBucket(const style::BucketParameters&, const std::vector<const style::Layer*>&);
void addFeature(const GeometryTileFeature&,
const GeometryCollection&) override;
bool hasData() const override;
void addGeometry(const GeometryCollection&);
void upload(gl::Context&) override;
void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) override;
gl::VertexVector<FillVertex> vertices;
gl::VertexVector<FillLayoutVertex> vertices;
gl::IndexVector<gl::Lines> lines;
gl::IndexVector<gl::Triangles> triangles;
gl::SegmentVector<FillAttributes> lineSegments;
gl::SegmentVector<FillAttributes> triangleSegments;
optional<gl::VertexBuffer<FillVertex>> vertexBuffer;
optional<gl::VertexBuffer<FillLayoutVertex>> vertexBuffer;
optional<gl::IndexBuffer<gl::Lines>> lineIndexBuffer;
optional<gl::IndexBuffer<gl::Triangles>> triangleIndexBuffer;
std::unordered_map<std::string, FillProgram::PaintPropertyBinders> paintPropertyBinders;
};
} // namespace mbgl

View File

@@ -1,6 +1,8 @@
#include <mbgl/renderer/line_bucket.hpp>
#include <mbgl/style/layers/line_layer.hpp>
#include <mbgl/renderer/painter.hpp>
#include <mbgl/style/layers/line_layer.hpp>
#include <mbgl/style/bucket_parameters.hpp>
#include <mbgl/style/layers/line_layer_impl.hpp>
#include <mbgl/util/math.hpp>
#include <mbgl/util/constants.hpp>
@@ -10,19 +12,29 @@ namespace mbgl {
using namespace style;
LineBucket::LineBucket(uint32_t overscaling_) : overscaling(overscaling_) {
}
LineBucket::~LineBucket() {
// Do not remove. header file only contains forward definitions to unique pointers.
}
void LineBucket::addGeometry(const GeometryCollection& geometryCollection) {
for (auto& line : geometryCollection) {
addGeometry(line);
LineBucket::LineBucket(const BucketParameters& parameters,
const std::vector<const Layer*>& layers,
const style::LineLayoutProperties& layout_)
: layout(layout_.evaluate(PropertyEvaluationParameters(parameters.tileID.overscaledZ))),
overscaling(parameters.tileID.overscaleFactor()) {
for (const auto& layer : layers) {
paintPropertyBinders.emplace(layer->getID(),
LineProgram::PaintPropertyBinders(
layer->as<LineLayer>()->impl->paint.evaluated,
parameters.tileID.overscaledZ));
}
}
void LineBucket::addFeature(const GeometryTileFeature& feature,
const GeometryCollection& geometryCollection) {
for (auto& line : geometryCollection) {
addGeometry(line);
}
for (auto& pair : paintPropertyBinders) {
pair.second.populateVertexVectors(feature, vertices.vertexSize());
}
}
/*
* Sharp corners cause dashed lines to tilt because the distance along the line
@@ -383,7 +395,7 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate,
Point<double> extrude = normal;
if (endLeft)
extrude = extrude - (util::perp(normal) * endLeft);
vertices.emplace_back(LineAttributes::vertex(currentCoordinate, extrude, { round, false }, endLeft, distance * LINE_DISTANCE_SCALE));
vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, { round, false }, endLeft, distance * LINE_DISTANCE_SCALE));
e3 = vertices.vertexSize() - 1 - startVertex;
if (e1 >= 0 && e2 >= 0) {
triangleStore.emplace_back(e1, e2, e3);
@@ -394,7 +406,7 @@ void LineBucket::addCurrentVertex(const GeometryCoordinate& currentCoordinate,
extrude = normal * -1.0;
if (endRight)
extrude = extrude - (util::perp(normal) * endRight);
vertices.emplace_back(LineAttributes::vertex(currentCoordinate, extrude, { round, true }, -endRight, distance * LINE_DISTANCE_SCALE));
vertices.emplace_back(LineProgram::layoutVertex(currentCoordinate, extrude, { round, true }, -endRight, distance * LINE_DISTANCE_SCALE));
e3 = vertices.vertexSize() - 1 - startVertex;
if (e1 >= 0 && e2 >= 0) {
triangleStore.emplace_back(e1, e2, e3);
@@ -419,7 +431,7 @@ void LineBucket::addPieSliceVertex(const GeometryCoordinate& currentVertex,
std::size_t startVertex,
std::vector<TriangleElement>& triangleStore) {
Point<double> flippedExtrude = extrude * (lineTurnsLeft ? -1.0 : 1.0);
vertices.emplace_back(LineAttributes::vertex(currentVertex, flippedExtrude, { false, lineTurnsLeft }, 0, distance * LINE_DISTANCE_SCALE));
vertices.emplace_back(LineProgram::layoutVertex(currentVertex, flippedExtrude, { false, lineTurnsLeft }, 0, distance * LINE_DISTANCE_SCALE));
e3 = vertices.vertexSize() - 1 - startVertex;
if (e1 >= 0 && e2 >= 0) {
triangleStore.emplace_back(e1, e2, e3);
@@ -436,7 +448,10 @@ void LineBucket::upload(gl::Context& context) {
vertexBuffer = context.createVertexBuffer(std::move(vertices));
indexBuffer = context.createIndexBuffer(std::move(triangles));
// From now on, we're only going to render during the translucent pass.
for (auto& pair : paintPropertyBinders) {
pair.second.upload(context);
}
uploaded = true;
}

View File

@@ -12,28 +12,37 @@
namespace mbgl {
namespace style {
class BucketParameters;
} // namespace style
class LineBucket : public Bucket {
public:
LineBucket(uint32_t overscaling);
~LineBucket() override;
LineBucket(const style::BucketParameters&,
const std::vector<const style::Layer*>&,
const style::LineLayoutProperties&);
void addFeature(const GeometryTileFeature&,
const GeometryCollection&) override;
bool hasData() const override;
void upload(gl::Context&) override;
void render(Painter&, PaintParameters&, const style::Layer&, const RenderTile&) override;
bool hasData() const override;
void addGeometry(const GeometryCollection&);
void addGeometry(const GeometryCoordinates& line);
style::LineLayoutProperties::Evaluated layout;
gl::VertexVector<LineVertex> vertices;
gl::VertexVector<LineLayoutVertex> vertices;
gl::IndexVector<gl::Triangles> triangles;
gl::SegmentVector<LineAttributes> segments;
optional<gl::VertexBuffer<LineVertex>> vertexBuffer;
optional<gl::VertexBuffer<LineLayoutVertex>> vertexBuffer;
optional<gl::IndexBuffer<gl::Triangles>> indexBuffer;
std::unordered_map<std::string, LineProgram::PaintPropertyBinders> paintPropertyBinders;
private:
void addGeometry(const GeometryCoordinates& line);
struct TriangleElement {
TriangleElement(uint16_t a_, uint16_t b_, uint16_t c_) : a(a_), b(b_), c(c_) {}
uint16_t a, b, c;

View File

@@ -42,12 +42,12 @@ namespace mbgl {
using namespace style;
static gl::VertexVector<FillVertex> tileVertices() {
gl::VertexVector<FillVertex> result;
result.emplace_back(FillAttributes::vertex({ 0, 0 }));
result.emplace_back(FillAttributes::vertex({ util::EXTENT, 0 }));
result.emplace_back(FillAttributes::vertex({ 0, util::EXTENT }));
result.emplace_back(FillAttributes::vertex({ util::EXTENT, util::EXTENT }));
static gl::VertexVector<FillLayoutVertex> tileVertices() {
gl::VertexVector<FillLayoutVertex> result;
result.emplace_back(FillProgram::layoutVertex({ 0, 0 }));
result.emplace_back(FillProgram::layoutVertex({ util::EXTENT, 0 }));
result.emplace_back(FillProgram::layoutVertex({ 0, util::EXTENT }));
result.emplace_back(FillProgram::layoutVertex({ util::EXTENT, util::EXTENT }));
return result;
}
@@ -68,12 +68,12 @@ static gl::IndexVector<gl::LineStrip> tileLineStripIndices() {
return result;
}
static gl::VertexVector<RasterVertex> rasterVertices() {
gl::VertexVector<RasterVertex> result;
result.emplace_back(RasterProgram::vertex({ 0, 0 }, { 0, 0 }));
result.emplace_back(RasterProgram::vertex({ util::EXTENT, 0 }, { 32767, 0 }));
result.emplace_back(RasterProgram::vertex({ 0, util::EXTENT }, { 0, 32767 }));
result.emplace_back(RasterProgram::vertex({ util::EXTENT, util::EXTENT }, { 32767, 32767 }));
static gl::VertexVector<RasterLayoutVertex> rasterVertices() {
gl::VertexVector<RasterLayoutVertex> result;
result.emplace_back(RasterProgram::layoutVertex({ 0, 0 }, { 0, 0 }));
result.emplace_back(RasterProgram::layoutVertex({ util::EXTENT, 0 }, { 32767, 0 }));
result.emplace_back(RasterProgram::layoutVertex({ 0, util::EXTENT }, { 0, 32767 }));
result.emplace_back(RasterProgram::layoutVertex({ util::EXTENT, util::EXTENT }, { 32767, 32767 }));
return result;
}

View File

@@ -158,8 +158,8 @@ private:
std::unique_ptr<Programs> overdrawPrograms;
#endif
gl::VertexBuffer<FillVertex> tileVertexBuffer;
gl::VertexBuffer<RasterVertex> rasterVertexBuffer;
gl::VertexBuffer<FillLayoutVertex> tileVertexBuffer;
gl::VertexBuffer<RasterLayoutVertex> rasterVertexBuffer;
gl::IndexBuffer<gl::Triangles> tileTriangleIndexBuffer;
gl::IndexBuffer<gl::LineStrip> tileBorderIndexBuffer;

View File

@@ -14,13 +14,20 @@ using namespace style;
void Painter::renderBackground(PaintParameters& parameters, const BackgroundLayer& layer) {
// Note that for bottommost layers without a pattern, the background color is drawn with
// glClear rather than this method.
const BackgroundPaintProperties::Evaluated& properties = layer.impl->paint.evaluated;
const BackgroundPaintProperties::Evaluated& background = layer.impl->paint.evaluated;
if (!properties.get<BackgroundPattern>().to.empty()) {
style::FillPaintProperties::Evaluated properties;
properties.get<FillPattern>() = background.get<BackgroundPattern>();
properties.get<FillOpacity>() = { background.get<BackgroundOpacity>() };
properties.get<FillColor>() = { background.get<BackgroundColor>() };
const FillProgram::PaintPropertyBinders paintAttibuteData(properties, 0);
if (!background.get<BackgroundPattern>().to.empty()) {
optional<SpriteAtlasPosition> imagePosA = spriteAtlas->getPosition(
properties.get<BackgroundPattern>().from, SpritePatternMode::Repeating);
background.get<BackgroundPattern>().from, SpritePatternMode::Repeating);
optional<SpriteAtlasPosition> imagePosB = spriteAtlas->getPosition(
properties.get<BackgroundPattern>().to, SpritePatternMode::Repeating);
background.get<BackgroundPattern>().to, SpritePatternMode::Repeating);
if (!imagePosA || !imagePosB)
return;
@@ -36,17 +43,19 @@ void Painter::renderBackground(PaintParameters& parameters, const BackgroundLaye
colorModeForRenderPass(),
FillPatternUniforms::values(
matrixForTile(tileID),
properties.get<BackgroundOpacity>(),
context.viewport.getCurrentValue().size,
*imagePosA,
*imagePosB,
properties.get<BackgroundPattern>(),
background.get<BackgroundPattern>(),
tileID,
state
),
tileVertexBuffer,
tileTriangleIndexBuffer,
tileTriangleSegments
tileTriangleSegments,
paintAttibuteData,
properties,
state.getZoom()
);
}
} else {
@@ -59,14 +68,14 @@ void Painter::renderBackground(PaintParameters& parameters, const BackgroundLaye
colorModeForRenderPass(),
FillProgram::UniformValues {
uniforms::u_matrix::Value{ matrixForTile(tileID) },
uniforms::u_opacity::Value{ properties.get<BackgroundOpacity>() },
uniforms::u_color::Value{ properties.get<BackgroundColor>() },
uniforms::u_outline_color::Value{ properties.get<BackgroundColor>() },
uniforms::u_world::Value{ context.viewport.getCurrentValue().size },
},
tileVertexBuffer,
tileTriangleIndexBuffer,
tileTriangleSegments
tileTriangleSegments,
paintAttibuteData,
properties,
state.getZoom()
);
}
}

View File

@@ -37,13 +37,6 @@ void Painter::renderCircle(PaintParameters& parameters,
properties.get<CircleTranslateAnchor>(),
state)
},
uniforms::u_opacity::Value{ properties.get<CircleOpacity>() },
uniforms::u_color::Value{ properties.get<CircleColor>() },
uniforms::u_radius::Value{ properties.get<CircleRadius>() },
uniforms::u_blur::Value{ properties.get<CircleBlur>() },
uniforms::u_stroke_color::Value{ properties.get<CircleStrokeColor>() },
uniforms::u_stroke_width::Value{ properties.get<CircleStrokeWidth>() },
uniforms::u_stroke_opacity::Value{ properties.get<CircleStrokeOpacity>() },
uniforms::u_scale_with_map::Value{ scaleWithMap },
uniforms::u_extrude_scale::Value{ scaleWithMap
? std::array<float, 2> {{
@@ -54,7 +47,10 @@ void Painter::renderCircle(PaintParameters& parameters,
},
*bucket.vertexBuffer,
*bucket.indexBuffer,
bucket.segments
bucket.segments,
bucket.paintPropertyBinders.at(layer.getID()),
properties,
state.getZoom()
);
}

View File

@@ -6,6 +6,8 @@
namespace mbgl {
void Painter::renderClippingMask(const UnwrappedTileID& tileID, const ClipID& clip) {
static const style::FillPaintProperties::Evaluated properties {};
static const FillProgram::PaintPropertyBinders paintAttibuteData(properties, 0);
programs->fill.draw(
context,
gl::Triangles(),
@@ -21,14 +23,14 @@ void Painter::renderClippingMask(const UnwrappedTileID& tileID, const ClipID& cl
gl::ColorMode::disabled(),
FillProgram::UniformValues {
uniforms::u_matrix::Value{ matrixForTile(tileID) },
uniforms::u_opacity::Value{ 0.0f },
uniforms::u_color::Value{ Color {} },
uniforms::u_outline_color::Value{ Color {} },
uniforms::u_world::Value{ context.viewport.getCurrentValue().size },
},
tileVertexBuffer,
tileTriangleIndexBuffer,
tileTriangleSegments
tileTriangleSegments,
paintAttibuteData,
properties,
state.getZoom()
);
}

View File

@@ -12,12 +12,17 @@
namespace mbgl {
using namespace style;
void Painter::renderTileDebug(const RenderTile& renderTile) {
if (frame.debugOptions == MapDebugOptions::NoDebug)
return;
MBGL_DEBUG_GROUP(std::string { "debug " } + util::toString(renderTile.id));
static const style::PaintProperties<>::Evaluated properties {};
static const DebugProgram::PaintPropertyBinders paintAttibuteData(properties, 0);
auto draw = [&] (Color color, const auto& vertexBuffer, const auto& indexBuffer, const auto& segments, auto drawMode) {
programs->debug.draw(
context,
@@ -31,7 +36,10 @@ void Painter::renderTileDebug(const RenderTile& renderTile) {
},
vertexBuffer,
indexBuffer,
segments
segments,
paintAttibuteData,
properties,
state.getZoom()
);
};

View File

@@ -38,7 +38,6 @@ void Painter::renderFill(PaintParameters& parameters,
auto draw = [&] (uint8_t sublayer,
auto& program,
const auto& drawMode,
const auto& vertexBuffer,
const auto& indexBuffer,
const auto& segments) {
program.draw(
@@ -51,7 +50,6 @@ void Painter::renderFill(PaintParameters& parameters,
tile.translatedMatrix(properties.get<FillTranslate>(),
properties.get<FillTranslateAnchor>(),
state),
properties.get<FillOpacity>(),
context.viewport.getCurrentValue().size,
*imagePosA,
*imagePosB,
@@ -59,16 +57,18 @@ void Painter::renderFill(PaintParameters& parameters,
tile.id,
state
),
vertexBuffer,
*bucket.vertexBuffer,
indexBuffer,
segments
segments,
bucket.paintPropertyBinders.at(layer.getID()),
properties,
state.getZoom()
);
};
draw(0,
parameters.programs.fillPattern,
gl::Triangles(),
*bucket.vertexBuffer,
*bucket.triangleIndexBuffer,
bucket.triangleSegments);
@@ -79,14 +79,12 @@ void Painter::renderFill(PaintParameters& parameters,
draw(2,
parameters.programs.fillOutlinePattern,
gl::Lines { 2.0f },
*bucket.vertexBuffer,
*bucket.lineIndexBuffer,
bucket.lineSegments);
} else {
auto draw = [&] (uint8_t sublayer,
auto& program,
const auto& drawMode,
const auto& vertexBuffer,
const auto& indexBuffer,
const auto& segments) {
program.draw(
@@ -96,17 +94,19 @@ void Painter::renderFill(PaintParameters& parameters,
stencilModeForClipping(tile.clip),
colorModeForRenderPass(),
FillProgram::UniformValues {
uniforms::u_matrix::Value{ tile.translatedMatrix(properties.get<FillTranslate>(),
properties.get<FillTranslateAnchor>(),
state) },
uniforms::u_opacity::Value{ properties.get<FillOpacity>() },
uniforms::u_color::Value{ properties.get<FillColor>() },
uniforms::u_outline_color::Value{ properties.get<FillOutlineColor>() },
uniforms::u_matrix::Value{
tile.translatedMatrix(properties.get<FillTranslate>(),
properties.get<FillTranslateAnchor>(),
state)
},
uniforms::u_world::Value{ context.viewport.getCurrentValue().size },
},
vertexBuffer,
*bucket.vertexBuffer,
indexBuffer,
segments
segments,
bucket.paintPropertyBinders.at(layer.getID()),
properties,
state.getZoom()
);
};
@@ -114,18 +114,17 @@ void Painter::renderFill(PaintParameters& parameters,
draw(2,
parameters.programs.fillOutline,
gl::Lines { 2.0f },
*bucket.vertexBuffer,
*bucket.lineIndexBuffer,
bucket.lineSegments);
}
// Only draw the fill when it's opaque and we're drawing opaque fragments,
// or when it's translucent and we're drawing translucent fragments.
if ((properties.get<FillColor>().a >= 1.0f && properties.get<FillOpacity>() >= 1.0f) == (pass == RenderPass::Opaque)) {
if ((properties.get<FillColor>().constantOr(Color()).a >= 1.0f
&& properties.get<FillOpacity>().constantOr(0) >= 1.0f) == (pass == RenderPass::Opaque)) {
draw(1,
parameters.programs.fill,
gl::Triangles(),
*bucket.vertexBuffer,
*bucket.triangleIndexBuffer,
bucket.triangleSegments);
}
@@ -134,7 +133,6 @@ void Painter::renderFill(PaintParameters& parameters,
draw(2,
parameters.programs.fillOutline,
gl::Lines { 2.0f },
*bucket.vertexBuffer,
*bucket.lineIndexBuffer,
bucket.lineSegments);
}

View File

@@ -33,7 +33,10 @@ void Painter::renderLine(PaintParameters& parameters,
std::move(uniformValues),
*bucket.vertexBuffer,
*bucket.indexBuffer,
bucket.segments
bucket.segments,
bucket.paintPropertyBinders.at(layer.getID()),
properties,
state.getZoom()
);
};

View File

@@ -49,6 +49,7 @@ void Painter::renderRaster(PaintParameters& parameters,
return;
const RasterPaintProperties::Evaluated& properties = layer.impl->paint.evaluated;
const RasterProgram::PaintPropertyBinders paintAttributeData(properties, 0);
assert(bucket.texture);
context.bindTexture(*bucket.texture, 0, gl::TextureFilter::Linear);
@@ -77,7 +78,10 @@ void Painter::renderRaster(PaintParameters& parameters,
},
rasterVertexBuffer,
tileTriangleIndexBuffer,
rasterSegments
rasterSegments,
paintAttributeData,
properties,
state.getZoom()
);
}

View File

@@ -51,7 +51,10 @@ void Painter::renderSymbol(PaintParameters& parameters,
std::move(uniformValues),
*buffers.vertexBuffer,
*buffers.indexBuffer,
buffers.segments
buffers.segments,
bucket.paintPropertyBinders.at(layer.getID()),
layer.impl->paint.evaluated,
state.getZoom()
);
};
@@ -110,6 +113,9 @@ void Painter::renderSymbol(PaintParameters& parameters,
}
if (bucket.hasCollisionBoxData()) {
static const style::PaintProperties<>::Evaluated properties {};
static const CollisionBoxProgram::PaintPropertyBinders paintAttributeData(properties, 0);
programs->collisionBox.draw(
context,
gl::Lines { 1.0f },
@@ -124,7 +130,10 @@ void Painter::renderSymbol(PaintParameters& parameters,
},
*bucket.collisionBox.vertexBuffer,
*bucket.collisionBox.indexBuffer,
bucket.collisionBox.segments
bucket.collisionBox.segments,
paintAttributeData,
properties,
state.getZoom()
);
}
}

View File

@@ -1,19 +1,25 @@
#include <mbgl/renderer/symbol_bucket.hpp>
#include <mbgl/renderer/painter.hpp>
#include <mbgl/style/bucket_parameters.hpp>
#include <mbgl/style/layers/symbol_layer.hpp>
#include <mbgl/style/layers/symbol_layer_impl.hpp>
namespace mbgl {
using namespace style;
SymbolBucket::SymbolBucket(const MapMode mode_,
style::SymbolLayoutProperties::Evaluated layout_,
SymbolBucket::SymbolBucket(style::SymbolLayoutProperties::Evaluated layout_,
const std::unordered_map<std::string, style::SymbolPaintProperties::Evaluated>& layerPaintProperties,
float zoom,
bool sdfIcons_,
bool iconsNeedLinear_)
: mode(mode_),
layout(std::move(layout_)),
: layout(std::move(layout_)),
sdfIcons(sdfIcons_),
iconsNeedLinear(iconsNeedLinear_) {
for (const auto& pair : layerPaintProperties) {
paintPropertyBinders.emplace(pair.first,
SymbolIconProgram::PaintPropertyBinders(pair.second, zoom));
}
}
void SymbolBucket::upload(gl::Context& context) {
@@ -32,6 +38,10 @@ void SymbolBucket::upload(gl::Context& context) {
collisionBox.indexBuffer = context.createIndexBuffer(std::move(collisionBox.lines));
}
for (auto& pair : paintPropertyBinders) {
pair.second.upload(context);
}
uploaded = true;
}

View File

@@ -16,8 +16,9 @@ namespace mbgl {
class SymbolBucket : public Bucket {
public:
SymbolBucket(const MapMode,
style::SymbolLayoutProperties::Evaluated,
SymbolBucket(style::SymbolLayoutProperties::Evaluated,
const std::unordered_map<std::string, style::SymbolPaintProperties::Evaluated>&,
float zoom,
bool sdfIcons,
bool iconsNeedLinear);
@@ -28,26 +29,27 @@ public:
bool hasIconData() const;
bool hasCollisionBoxData() const;
const MapMode mode;
const style::SymbolLayoutProperties::Evaluated layout;
const bool sdfIcons;
const bool iconsNeedLinear;
std::unordered_map<std::string, SymbolIconProgram::PaintPropertyBinders> paintPropertyBinders;
struct TextBuffer {
gl::VertexVector<SymbolVertex> vertices;
gl::VertexVector<SymbolLayoutVertex> vertices;
gl::IndexVector<gl::Triangles> triangles;
gl::SegmentVector<SymbolAttributes> segments;
optional<gl::VertexBuffer<SymbolVertex>> vertexBuffer;
optional<gl::VertexBuffer<SymbolLayoutVertex>> vertexBuffer;
optional<gl::IndexBuffer<gl::Triangles>> indexBuffer;
} text;
struct IconBuffer {
gl::VertexVector<SymbolVertex> vertices;
gl::VertexVector<SymbolLayoutVertex> vertices;
gl::IndexVector<gl::Triangles> triangles;
gl::SegmentVector<SymbolAttributes> segments;
optional<gl::VertexBuffer<SymbolVertex>> vertexBuffer;
optional<gl::VertexBuffer<SymbolLayoutVertex>> vertexBuffer;
optional<gl::IndexBuffer<gl::Triangles>> indexBuffer;
} icon;

View File

@@ -1,21 +1,7 @@
#include <mbgl/style/bucket_parameters.hpp>
#include <mbgl/style/filter_evaluator.hpp>
#include <mbgl/tile/geometry_tile_data.hpp>
namespace mbgl {
namespace style {
void BucketParameters::eachFilteredFeature(const Filter& filter,
const GeometryTileLayer& layer,
std::function<void (const GeometryTileFeature&, std::size_t index, const std::string& layerName)> function) {
auto name = layer.getName();
for (std::size_t i = 0; !cancelled() && i < layer.featureCount(); i++) {
auto feature = layer.getFeature(i);
if (!filter(feature->getType(), feature->getID(), [&] (const auto& key) { return feature->getValue(key); }))
continue;
function(*feature, i, name);
}
}
} // namespace style
} // namespace mbgl

View File

@@ -2,33 +2,14 @@
#include <mbgl/map/mode.hpp>
#include <mbgl/tile/tile_id.hpp>
#include <mbgl/style/filter.hpp>
#include <atomic>
#include <functional>
namespace mbgl {
class GeometryTileLayer;
class GeometryTileFeature;
class FeatureIndex;
namespace style {
class BucketParameters {
public:
const OverscaledTileID& tileID;
const std::atomic<bool>& obsolete;
FeatureIndex& featureIndex;
const OverscaledTileID tileID;
const MapMode mode;
bool cancelled() const {
return obsolete;
}
void eachFilteredFeature(const Filter&,
const GeometryTileLayer&,
std::function<void (const GeometryTileFeature&, std::size_t index, const std::string& layerName)>);
};
} // namespace style

View File

@@ -214,20 +214,131 @@ void stringify(Writer& writer, const Undefined&) {
writer.Null();
}
template <class Writer, class T>
void stringify(Writer& writer, const Function<T>& f) {
writer.StartObject();
writer.Key("base");
writer.Double(f.getBase());
writer.Key("stops");
writer.StartArray();
for (const auto& stop : f.getStops()) {
template <class Writer>
void stringify(Writer& writer, const CategoricalValue& v) {
CategoricalValue::visit(v, [&] (const auto& v_) { stringify(writer, v_); });
}
template <class Writer>
class StringifyStops {
public:
Writer& writer;
template <class T>
void operator()(const ExponentialStops<T>& f) {
writer.Key("type");
writer.String("exponential");
writer.Key("base");
writer.Double(f.base);
writer.Key("stops");
stringifyStops(f.stops);
}
template <class T>
void operator()(const IntervalStops<T>& f) {
writer.Key("type");
writer.String("interval");
writer.Key("stops");
stringifyStops(f.stops);
}
template <class T>
void operator()(const CategoricalStops<T>& f) {
writer.Key("type");
writer.String("categorical");
writer.Key("stops");
stringifyStops(f.stops);
}
template <class T>
void operator()(const IdentityStops<T>&) {
writer.Key("type");
writer.String("identity");
}
template <class T>
void operator()(const std::map<float, ExponentialStops<T>>& f) {
writer.Key("type");
writer.String("exponential");
if (!f.empty()) {
writer.Key("base");
writer.Double(f.begin()->second.base);
}
writer.Key("stops");
stringifyCompositeStops(f);
}
template <class T>
void operator()(const std::map<float, IntervalStops<T>>& f) {
writer.Key("type");
writer.String("interval");
writer.Key("stops");
stringifyCompositeStops(f);
}
template <class T>
void operator()(const std::map<float, CategoricalStops<T>>& f) {
writer.Key("type");
writer.String("categorical");
writer.Key("stops");
stringifyCompositeStops(f);
}
private:
template <class K, class V>
void stringifyStops(const std::map<K, V>& stops) {
writer.StartArray();
writer.Double(stop.first);
stringify(writer, stop.second);
for (const auto& stop : stops) {
writer.StartArray();
stringify(writer, stop.first);
stringify(writer, stop.second);
writer.EndArray();
}
writer.EndArray();
}
writer.EndArray();
template <class InnerStops>
void stringifyCompositeStops(const std::map<float, InnerStops>& stops) {
writer.StartArray();
for (const auto& outer : stops) {
for (const auto& inner : outer.second.stops) {
writer.StartArray();
writer.StartObject();
writer.Key("zoom");
writer.Double(outer.first);
writer.Key("value");
stringify(writer, inner.first);
writer.EndObject();
stringify(writer, inner.second);
writer.EndArray();
}
}
writer.EndArray();
}
};
template <class Writer, class T>
void stringify(Writer& writer, const CameraFunction<T>& f) {
writer.StartObject();
CameraFunction<T>::Stops::visit(f.stops, StringifyStops<Writer> { writer });
writer.EndObject();
}
template <class Writer, class T>
void stringify(Writer& writer, const SourceFunction<T>& f) {
writer.StartObject();
writer.Key("property");
writer.String(f.property);
SourceFunction<T>::Stops::visit(f.stops, StringifyStops<Writer> { writer });
writer.EndObject();
}
template <class Writer, class T>
void stringify(Writer& writer, const CompositeFunction<T>& f) {
writer.StartObject();
writer.Key("property");
writer.String(f.property);
CompositeFunction<T>::Stops::visit(f.stops, StringifyStops<Writer> { writer });
writer.EndObject();
}
@@ -238,7 +349,20 @@ void stringify(Writer& writer, const PropertyValue<T>& v) {
template <class Property, class Writer, class T>
void stringify(Writer& writer, const PropertyValue<T>& value) {
if (value) {
if (!value.isUndefined()) {
writer.Key(Property::key);
stringify(writer, value);
}
}
template <class Writer, class T>
void stringify(Writer& writer, const DataDrivenPropertyValue<T>& v) {
v.evaluate([&] (const auto& v_) { stringify(writer, v_); });
}
template <class Property, class Writer, class T>
void stringify(Writer& writer, const DataDrivenPropertyValue<T>& value) {
if (!value.isUndefined()) {
writer.Key(Property::key);
stringify(writer, value);
}

View File

@@ -17,21 +17,10 @@ Faded<T> CrossFadedPropertyEvaluator<T>::operator()(const T& constant) const {
}
template <typename T>
T getBiggestStopLessThan(const Function<T>& function, float z) {
const auto& stops = function.getStops();
for (uint32_t i = 0; i < stops.size(); i++) {
if (stops[i].first > z) {
return stops[i == 0 ? i : i - 1].second;
}
}
return stops.at(stops.size() - 1).second;
}
template <typename T>
Faded<T> CrossFadedPropertyEvaluator<T>::operator()(const Function<T>& function) const {
return calculate(getBiggestStopLessThan(function, parameters.z - 1.0f),
getBiggestStopLessThan(function, parameters.z),
getBiggestStopLessThan(function, parameters.z + 1.0f));
Faded<T> CrossFadedPropertyEvaluator<T>::operator()(const CameraFunction<T>& function) const {
return calculate(function.evaluate(parameters.z - 1.0f),
function.evaluate(parameters.z),
function.evaluate(parameters.z + 1.0f));
}
template <typename T>

View File

@@ -28,7 +28,7 @@ public:
Faded<T> operator()(const Undefined&) const;
Faded<T> operator()(const T& constant) const;
Faded<T> operator()(const Function<T>&) const;
Faded<T> operator()(const CameraFunction<T>&) const;
private:
Faded<T> calculate(const T& min, const T& mid, const T& max) const;

View File

@@ -0,0 +1,42 @@
#pragma once
#include <mbgl/style/property_value.hpp>
#include <mbgl/style/property_evaluation_parameters.hpp>
#include <mbgl/style/possibly_evaluated_property_value.hpp>
namespace mbgl {
namespace style {
template <typename T>
class DataDrivenPropertyEvaluator {
public:
using ResultType = PossiblyEvaluatedPropertyValue<T>;
DataDrivenPropertyEvaluator(const PropertyEvaluationParameters& parameters_, T defaultValue_)
: parameters(parameters_),
defaultValue(std::move(defaultValue_)) {}
ResultType operator()(const Undefined&) const {
return ResultType(defaultValue);
}
ResultType operator()(const T& constant) const {
return ResultType(constant);
}
ResultType operator()(const CameraFunction<T>& function) const {
return ResultType(function.evaluate(parameters.z));
}
template <class Function>
ResultType operator()(const Function& function) const {
return ResultType(function);
}
private:
const PropertyEvaluationParameters& parameters;
T defaultValue;
};
} // namespace style
} // namespace mbgl

View File

@@ -1,81 +0,0 @@
#include <mbgl/style/function.hpp>
#include <mbgl/style/types.hpp>
#include <mbgl/util/color.hpp>
#include <mbgl/util/interpolate.hpp>
#include <cmath>
namespace mbgl {
namespace style {
template <typename T>
T Function<T>::evaluate(float z) const {
bool smaller = false;
float smaller_z = 0.0f;
T smaller_val = T();
bool larger = false;
float larger_z = 0.0f;
T larger_val = T();
for (uint32_t i = 0; i < stops.size(); i++) {
float stop_z = stops[i].first;
T stop_val = stops[i].second;
if (stop_z <= z && (!smaller || smaller_z < stop_z)) {
smaller = true;
smaller_z = stop_z;
smaller_val = stop_val;
}
if (stop_z >= z && (!larger || larger_z > stop_z)) {
larger = true;
larger_z = stop_z;
larger_val = stop_val;
}
}
if (smaller && larger) {
if (larger_z == smaller_z || larger_val == smaller_val) {
return smaller_val;
}
const float zoomDiff = larger_z - smaller_z;
const float zoomProgress = z - smaller_z;
if (base == 1.0f) {
const float t = zoomProgress / zoomDiff;
return util::interpolate(smaller_val, larger_val, t);
} else {
const float t = (std::pow(base, zoomProgress) - 1) / (std::pow(base, zoomDiff) - 1);
return util::interpolate(smaller_val, larger_val, t);
}
} else if (larger) {
return larger_val;
} else if (smaller) {
return smaller_val;
} else {
// No stop defined.
assert(false);
return T();
}
}
template class Function<bool>;
template class Function<float>;
template class Function<Color>;
template class Function<std::vector<float>>;
template class Function<std::vector<std::string>>;
template class Function<std::array<float, 2>>;
template class Function<std::array<float, 4>>;
template class Function<std::string>;
template class Function<TranslateAnchorType>;
template class Function<RotateAnchorType>;
template class Function<CirclePitchScaleType>;
template class Function<LineCapType>;
template class Function<LineJoinType>;
template class Function<SymbolPlacementType>;
template class Function<TextAnchorType>;
template class Function<TextJustifyType>;
template class Function<TextTransformType>;
template class Function<AlignmentType>;
template class Function<IconTextFitType>;
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,35 @@
#include <mbgl/style/function/categorical_stops.hpp>
#include <mbgl/util/color.hpp>
#include <array>
namespace mbgl {
namespace style {
optional<CategoricalValue> categoricalValue(const Value& value) {
return value.match(
[] (bool t) { return optional<CategoricalValue>(t); },
[] (uint64_t t) { return optional<CategoricalValue>(int64_t(t)); },
[] (int64_t t) { return optional<CategoricalValue>(t); },
[] (double t) { return optional<CategoricalValue>(int64_t(t)); },
[] (const std::string& t) { return optional<CategoricalValue>(t); },
[] (const auto&) { return optional<CategoricalValue>(); }
);
}
template <class T>
T CategoricalStops<T>::evaluate(const Value& value) const {
auto v = categoricalValue(value);
if (!v) {
return defaultValue;
}
auto it = stops.find(*v);
return it == stops.end() ? defaultValue : it->second;
}
template class CategoricalStops<float>;
template class CategoricalStops<Color>;
template class CategoricalStops<std::array<float, 2>>;
} // namespace style
} // namespace mbgl

View File

@@ -0,0 +1,43 @@
#include <mbgl/style/function/identity_stops.hpp>
#include <mbgl/util/color.hpp>
#include <array>
namespace mbgl {
namespace style {
template <>
float IdentityStops<float>::evaluate(const Value& value) const {
return numericValue<float>(value)
.value_or(0.0f);
}
template <>
Color IdentityStops<Color>::evaluate(const Value& value) const {
if (!value.is<std::string>()) {
return Color::black();
}
return Color::parse(value.get<std::string>())
.value_or(Color::black());
}
template <>
std::array<float, 2> IdentityStops<std::array<float, 2>>::evaluate(const Value& value) const {
if (!value.is<std::vector<Value>>()) {
return {{ 0, 0 }};
}
const std::vector<Value>& vector = value.get<std::vector<Value>>();
if (vector.size() != 2 || !numericValue<float>(vector[0]) || !numericValue<float>(vector[1])) {
return {{ 0, 0 }};
}
return {{
*numericValue<float>(vector[0]),
*numericValue<float>(vector[1])
}};
}
} // namespace style
} // namespace mbgl

View File

@@ -61,7 +61,7 @@ public:
// Returns true if any paint properties have active transitions.
virtual bool evaluate(const PropertyEvaluationParameters&) = 0;
virtual std::unique_ptr<Bucket> createBucket(BucketParameters&, const GeometryTileLayer&) const = 0;
virtual std::unique_ptr<Bucket> createBucket(const BucketParameters&, const std::vector<const Layer*>&) const = 0;
// Checks whether this layer needs to be rendered in the given render pass.
bool hasRenderPass(RenderPass) const;

View File

@@ -12,6 +12,7 @@ public:
virtual void onLayerFilterChanged(Layer&) {}
virtual void onLayerVisibilityChanged(Layer&) {}
virtual void onLayerPaintPropertyChanged(Layer&) {}
virtual void onLayerDataDrivenPaintPropertyChanged(Layer&) {}
virtual void onLayerLayoutPropertyChanged(Layer&, const char *) {}
};

View File

@@ -16,7 +16,8 @@ bool BackgroundLayer::Impl::evaluate(const PropertyEvaluationParameters& paramet
return paint.hasTransition();
}
std::unique_ptr<Bucket> BackgroundLayer::Impl::createBucket(BucketParameters&, const GeometryTileLayer&) const {
std::unique_ptr<Bucket> BackgroundLayer::Impl::createBucket(const BucketParameters&, const std::vector<const Layer*>&) const {
assert(false);
return nullptr;
}

View File

@@ -16,7 +16,7 @@ public:
void cascade(const CascadeParameters&) override;
bool evaluate(const PropertyEvaluationParameters&) override;
std::unique_ptr<Bucket> createBucket(BucketParameters&, const GeometryTileLayer&) const override;
std::unique_ptr<Bucket> createBucket(const BucketParameters&, const std::vector<const Layer*>&) const override;
BackgroundPaintProperties paint;
};

View File

@@ -5,6 +5,7 @@
#include <mbgl/style/types.hpp>
#include <mbgl/style/layout_property.hpp>
#include <mbgl/style/paint_property.hpp>
#include <mbgl/programs/attributes.hpp>
namespace mbgl {
namespace style {

View File

@@ -65,64 +65,80 @@ const Filter& CircleLayer::getFilter() const {
// Paint properties
PropertyValue<float> CircleLayer::getDefaultCircleRadius() {
DataDrivenPropertyValue<float> CircleLayer::getDefaultCircleRadius() {
return { 5 };
}
PropertyValue<float> CircleLayer::getCircleRadius(const optional<std::string>& klass) const {
DataDrivenPropertyValue<float> CircleLayer::getCircleRadius(const optional<std::string>& klass) const {
return impl->paint.get<CircleRadius>(klass);
}
void CircleLayer::setCircleRadius(PropertyValue<float> value, const optional<std::string>& klass) {
void CircleLayer::setCircleRadius(DataDrivenPropertyValue<float> value, const optional<std::string>& klass) {
if (value == getCircleRadius(klass))
return;
impl->paint.set<CircleRadius>(value, klass);
impl->observer->onLayerPaintPropertyChanged(*this);
if (value.isDataDriven()) {
impl->observer->onLayerDataDrivenPaintPropertyChanged(*this);
} else {
impl->observer->onLayerPaintPropertyChanged(*this);
}
}
PropertyValue<Color> CircleLayer::getDefaultCircleColor() {
DataDrivenPropertyValue<Color> CircleLayer::getDefaultCircleColor() {
return { Color::black() };
}
PropertyValue<Color> CircleLayer::getCircleColor(const optional<std::string>& klass) const {
DataDrivenPropertyValue<Color> CircleLayer::getCircleColor(const optional<std::string>& klass) const {
return impl->paint.get<CircleColor>(klass);
}
void CircleLayer::setCircleColor(PropertyValue<Color> value, const optional<std::string>& klass) {
void CircleLayer::setCircleColor(DataDrivenPropertyValue<Color> value, const optional<std::string>& klass) {
if (value == getCircleColor(klass))
return;
impl->paint.set<CircleColor>(value, klass);
impl->observer->onLayerPaintPropertyChanged(*this);
if (value.isDataDriven()) {
impl->observer->onLayerDataDrivenPaintPropertyChanged(*this);
} else {
impl->observer->onLayerPaintPropertyChanged(*this);
}
}
PropertyValue<float> CircleLayer::getDefaultCircleBlur() {
DataDrivenPropertyValue<float> CircleLayer::getDefaultCircleBlur() {
return { 0 };
}
PropertyValue<float> CircleLayer::getCircleBlur(const optional<std::string>& klass) const {
DataDrivenPropertyValue<float> CircleLayer::getCircleBlur(const optional<std::string>& klass) const {
return impl->paint.get<CircleBlur>(klass);
}
void CircleLayer::setCircleBlur(PropertyValue<float> value, const optional<std::string>& klass) {
void CircleLayer::setCircleBlur(DataDrivenPropertyValue<float> value, const optional<std::string>& klass) {
if (value == getCircleBlur(klass))
return;
impl->paint.set<CircleBlur>(value, klass);
impl->observer->onLayerPaintPropertyChanged(*this);
if (value.isDataDriven()) {
impl->observer->onLayerDataDrivenPaintPropertyChanged(*this);
} else {
impl->observer->onLayerPaintPropertyChanged(*this);
}
}
PropertyValue<float> CircleLayer::getDefaultCircleOpacity() {
DataDrivenPropertyValue<float> CircleLayer::getDefaultCircleOpacity() {
return { 1 };
}
PropertyValue<float> CircleLayer::getCircleOpacity(const optional<std::string>& klass) const {
DataDrivenPropertyValue<float> CircleLayer::getCircleOpacity(const optional<std::string>& klass) const {
return impl->paint.get<CircleOpacity>(klass);
}
void CircleLayer::setCircleOpacity(PropertyValue<float> value, const optional<std::string>& klass) {
void CircleLayer::setCircleOpacity(DataDrivenPropertyValue<float> value, const optional<std::string>& klass) {
if (value == getCircleOpacity(klass))
return;
impl->paint.set<CircleOpacity>(value, klass);
impl->observer->onLayerPaintPropertyChanged(*this);
if (value.isDataDriven()) {
impl->observer->onLayerDataDrivenPaintPropertyChanged(*this);
} else {
impl->observer->onLayerPaintPropertyChanged(*this);
}
}
PropertyValue<std::array<float, 2>> CircleLayer::getDefaultCircleTranslate() {
@@ -170,49 +186,61 @@ void CircleLayer::setCirclePitchScale(PropertyValue<CirclePitchScaleType> value,
impl->observer->onLayerPaintPropertyChanged(*this);
}
PropertyValue<float> CircleLayer::getDefaultCircleStrokeWidth() {
DataDrivenPropertyValue<float> CircleLayer::getDefaultCircleStrokeWidth() {
return { 0 };
}
PropertyValue<float> CircleLayer::getCircleStrokeWidth(const optional<std::string>& klass) const {
DataDrivenPropertyValue<float> CircleLayer::getCircleStrokeWidth(const optional<std::string>& klass) const {
return impl->paint.get<CircleStrokeWidth>(klass);
}
void CircleLayer::setCircleStrokeWidth(PropertyValue<float> value, const optional<std::string>& klass) {
void CircleLayer::setCircleStrokeWidth(DataDrivenPropertyValue<float> value, const optional<std::string>& klass) {
if (value == getCircleStrokeWidth(klass))
return;
impl->paint.set<CircleStrokeWidth>(value, klass);
impl->observer->onLayerPaintPropertyChanged(*this);
if (value.isDataDriven()) {
impl->observer->onLayerDataDrivenPaintPropertyChanged(*this);
} else {
impl->observer->onLayerPaintPropertyChanged(*this);
}
}
PropertyValue<Color> CircleLayer::getDefaultCircleStrokeColor() {
DataDrivenPropertyValue<Color> CircleLayer::getDefaultCircleStrokeColor() {
return { Color::black() };
}
PropertyValue<Color> CircleLayer::getCircleStrokeColor(const optional<std::string>& klass) const {
DataDrivenPropertyValue<Color> CircleLayer::getCircleStrokeColor(const optional<std::string>& klass) const {
return impl->paint.get<CircleStrokeColor>(klass);
}
void CircleLayer::setCircleStrokeColor(PropertyValue<Color> value, const optional<std::string>& klass) {
void CircleLayer::setCircleStrokeColor(DataDrivenPropertyValue<Color> value, const optional<std::string>& klass) {
if (value == getCircleStrokeColor(klass))
return;
impl->paint.set<CircleStrokeColor>(value, klass);
impl->observer->onLayerPaintPropertyChanged(*this);
if (value.isDataDriven()) {
impl->observer->onLayerDataDrivenPaintPropertyChanged(*this);
} else {
impl->observer->onLayerPaintPropertyChanged(*this);
}
}
PropertyValue<float> CircleLayer::getDefaultCircleStrokeOpacity() {
DataDrivenPropertyValue<float> CircleLayer::getDefaultCircleStrokeOpacity() {
return { 1 };
}
PropertyValue<float> CircleLayer::getCircleStrokeOpacity(const optional<std::string>& klass) const {
DataDrivenPropertyValue<float> CircleLayer::getCircleStrokeOpacity(const optional<std::string>& klass) const {
return impl->paint.get<CircleStrokeOpacity>(klass);
}
void CircleLayer::setCircleStrokeOpacity(PropertyValue<float> value, const optional<std::string>& klass) {
void CircleLayer::setCircleStrokeOpacity(DataDrivenPropertyValue<float> value, const optional<std::string>& klass) {
if (value == getCircleStrokeOpacity(klass))
return;
impl->paint.set<CircleStrokeOpacity>(value, klass);
impl->observer->onLayerPaintPropertyChanged(*this);
if (value.isDataDriven()) {
impl->observer->onLayerDataDrivenPaintPropertyChanged(*this);
} else {
impl->observer->onLayerPaintPropertyChanged(*this);
}
}
} // namespace style

View File

@@ -1,5 +1,4 @@
#include <mbgl/style/layers/circle_layer_impl.hpp>
#include <mbgl/style/bucket_parameters.hpp>
#include <mbgl/renderer/circle_bucket.hpp>
#include <mbgl/geometry/feature_index.hpp>
#include <mbgl/util/math.hpp>
@@ -15,27 +14,22 @@ void CircleLayer::Impl::cascade(const CascadeParameters& parameters) {
bool CircleLayer::Impl::evaluate(const PropertyEvaluationParameters& parameters) {
paint.evaluate(parameters);
passes = (paint.evaluated.get<CircleRadius>() > 0 && paint.evaluated.get<CircleColor>().a > 0 && paint.evaluated.get<CircleOpacity>() > 0)
passes = (paint.evaluated.get<CircleRadius>().constantOr(1) > 0
&& paint.evaluated.get<CircleColor>().constantOr(Color::black()).a > 0
&& paint.evaluated.get<CircleOpacity>().constantOr(1) > 0)
? RenderPass::Translucent : RenderPass::None;
return paint.hasTransition();
}
std::unique_ptr<Bucket> CircleLayer::Impl::createBucket(BucketParameters& parameters, const GeometryTileLayer& layer) const {
auto bucket = std::make_unique<CircleBucket>(parameters.mode);
parameters.eachFilteredFeature(filter, layer, [&] (const auto& feature, std::size_t index, const std::string& layerName) {
auto geometries = feature.getGeometries();
bucket->addGeometry(geometries);
parameters.featureIndex.insert(geometries, index, layerName, id);
});
return std::move(bucket);
std::unique_ptr<Bucket> CircleLayer::Impl::createBucket(const BucketParameters& parameters, const std::vector<const Layer*>& layers) const {
return std::make_unique<CircleBucket>(parameters, layers);
}
float CircleLayer::Impl::getQueryRadius() const {
const std::array<float, 2>& translate = paint.evaluated.get<CircleTranslate>();
return paint.evaluated.get<CircleRadius>() + util::length(translate[0], translate[1]);
return paint.evaluated.get<CircleRadius>().constantOr(CircleRadius::defaultValue())
+ util::length(translate[0], translate[1]);
}
bool CircleLayer::Impl::queryIntersectsGeometry(
@@ -47,7 +41,7 @@ bool CircleLayer::Impl::queryIntersectsGeometry(
auto translatedQueryGeometry = FeatureIndex::translateQueryGeometry(
queryGeometry, paint.evaluated.get<CircleTranslate>(), paint.evaluated.get<CircleTranslateAnchor>(), bearing, pixelsToTileUnits);
auto circleRadius = paint.evaluated.get<CircleRadius>() * pixelsToTileUnits;
auto circleRadius = paint.evaluated.get<CircleRadius>().constantOr(CircleRadius::defaultValue()) * pixelsToTileUnits;
return util::polygonIntersectsBufferedMultiPoint(
translatedQueryGeometry.value_or(queryGeometry), geometry, circleRadius);

View File

@@ -16,7 +16,7 @@ public:
void cascade(const CascadeParameters&) override;
bool evaluate(const PropertyEvaluationParameters&) override;
std::unique_ptr<Bucket> createBucket(BucketParameters&, const GeometryTileLayer&) const override;
std::unique_ptr<Bucket> createBucket(const BucketParameters&, const std::vector<const Layer*>&) const override;
float getQueryRadius() const override;
bool queryIntersectsGeometry(

View File

@@ -5,23 +5,24 @@
#include <mbgl/style/types.hpp>
#include <mbgl/style/layout_property.hpp>
#include <mbgl/style/paint_property.hpp>
#include <mbgl/programs/attributes.hpp>
namespace mbgl {
namespace style {
struct CircleRadius : PaintProperty<float> {
struct CircleRadius : DataDrivenPaintProperty<float, attributes::a_radius> {
static float defaultValue() { return 5; }
};
struct CircleColor : PaintProperty<Color> {
struct CircleColor : DataDrivenPaintProperty<Color, attributes::a_color> {
static Color defaultValue() { return Color::black(); }
};
struct CircleBlur : PaintProperty<float> {
struct CircleBlur : DataDrivenPaintProperty<float, attributes::a_blur> {
static float defaultValue() { return 0; }
};
struct CircleOpacity : PaintProperty<float> {
struct CircleOpacity : DataDrivenPaintProperty<float, attributes::a_opacity> {
static float defaultValue() { return 1; }
};
@@ -37,15 +38,15 @@ struct CirclePitchScale : PaintProperty<CirclePitchScaleType> {
static CirclePitchScaleType defaultValue() { return CirclePitchScaleType::Map; }
};
struct CircleStrokeWidth : PaintProperty<float> {
struct CircleStrokeWidth : DataDrivenPaintProperty<float, attributes::a_stroke_width> {
static float defaultValue() { return 0; }
};
struct CircleStrokeColor : PaintProperty<Color> {
struct CircleStrokeColor : DataDrivenPaintProperty<Color, attributes::a_stroke_color> {
static Color defaultValue() { return Color::black(); }
};
struct CircleStrokeOpacity : PaintProperty<float> {
struct CircleStrokeOpacity : DataDrivenPaintProperty<float, attributes::a_stroke_opacity> {
static float defaultValue() { return 1; }
};

View File

@@ -70,7 +70,8 @@ bool CustomLayer::Impl::evaluate(const PropertyEvaluationParameters&) {
return false;
}
std::unique_ptr<Bucket> CustomLayer::Impl::createBucket(BucketParameters&, const GeometryTileLayer&) const {
std::unique_ptr<Bucket> CustomLayer::Impl::createBucket(const BucketParameters&, const std::vector<const Layer*>&) const {
assert(false);
return nullptr;
}

View File

@@ -32,7 +32,7 @@ private:
void cascade(const CascadeParameters&) final {}
bool evaluate(const PropertyEvaluationParameters&) final;
std::unique_ptr<Bucket> createBucket(BucketParameters&, const GeometryTileLayer&) const final;
std::unique_ptr<Bucket> createBucket(const BucketParameters&, const std::vector<const Layer*>&) const final;
CustomLayerInitializeFunction initializeFn = nullptr;
CustomLayerRenderFunction renderFn = nullptr;

Some files were not shown because too many files have changed in this diff Show More