This commit is contained in:
Peter Liu
2015-04-01 17:05:22 -07:00
89 changed files with 2369 additions and 2004 deletions

4
.gitmodules vendored
View File

@@ -13,3 +13,7 @@
[submodule "test/ios/KIF"]
path = test/ios/KIF
url = https://github.com/mapbox/KIF.git
[submodule "platform/ios/vendor/SMCalloutView"]
path = platform/ios/vendor/SMCalloutView
url = https://github.com/nfarina/calloutview.git

View File

@@ -22,3 +22,34 @@ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===========================================================================
Mapbox GL uses portions of the Mapbox iOS SDK, which was derived from the
Route-Me open source project, including the Alpstein fork of it.
The Route-Me license appears below.
Copyright (c) 2008-2013, Route-Me Contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

View File

@@ -25,10 +25,13 @@ config/%.gypi: configure
styles/styles:
git submodule update --init styles
SMCalloutView:
git submodule update --init platform/ios/vendor/SMCalloutView
#### Library builds ############################################################
.PRECIOUS: Makefile/mbgl
Makefile/mbgl: config/$(HOST).gypi styles/styles
Makefile/mbgl: config/$(HOST).gypi styles/styles SMCalloutView
deps/run_gyp mbgl.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make
mbgl: Makefile/mbgl
@@ -41,13 +44,13 @@ install: Makefile/mbgl
LINK=`pwd`/gyp/link.py $(MAKE) -C build/$(HOST) BUILDTYPE=$(BUILDTYPE) install
.PRECIOUS: Xcode/mbgl
Xcode/mbgl: config/$(HOST).gypi styles/styles
Xcode/mbgl: config/$(HOST).gypi styles/styles SMCalloutView
deps/run_gyp mbgl.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f xcode
##### Test builds ##############################################################
.PRECIOUS: Makefile/test
Makefile/test: test/test.gyp config/$(HOST).gypi styles/styles
Makefile/test: test/test.gyp config/$(HOST).gypi styles/styles SMCalloutView
deps/run_gyp test/test.gyp $(CONFIG_$(HOST)) $(LIBS_$(HOST)) --generator-output=./build/$(HOST) -f make
test: Makefile/test
@@ -58,7 +61,7 @@ test-%: test
.PRECIOUS: Xcode/test
Xcode/test: test/test.gyp config/osx.gypi styles/styles
Xcode/test: test/test.gyp config/osx.gypi styles/styles SMCalloutView
deps/run_gyp test/test.gyp $(CONFIG_osx) $(LIBS_osx) --generator-output=./build/osx -f xcode
.PHONY: lproj lbuild run-xlinux
@@ -108,7 +111,7 @@ xproj: xosx-proj
#### iOS application builds ####################################################
.PRECIOUS: Xcode/ios
Xcode/ios: ios/app/mapboxgl-app.gyp config/ios.gypi styles/styles
Xcode/ios: ios/app/mapboxgl-app.gyp config/ios.gypi styles/styles SMCalloutView
deps/run_gyp ios/app/mapboxgl-app.gyp $(CONFIG_ios) $(LIBS_ios) --generator-output=./build/ios -f xcode
.PHONY: ios-proj ios run-ios

View File

@@ -55,9 +55,11 @@ If you merely want to install the library for iOS and try it out as an Objective
- `MapboxGL.bundle` is in your target's *Copy Bundle Resources* build phase.
- `libMapboxGL.a` is in your target's *Link Binary With Libraries* build phase.
3. Add the following Cocoa framework dependencies to your target's *Link Binary With Libraries* build phase:
- `CoreTelephony.framework`
- `GLKit.framework`
- `ImageIO.framework`
- `MobileCoreServices.framework`
- `QuartzCore.framework`
- `SystemConfiguration.framework`
- `libc++.dylib`
- `libsqlite3.dylib`

View File

@@ -160,7 +160,7 @@ jobject std_vector_string_to_jobject(JNIEnv *env, std::vector<std::string> vecto
return nullptr;
}
for (std::string str : vector) {
for (const auto& str : vector) {
env->CallBooleanMethod(jlist, arrayListAddId, std_string_to_jstring(env, str));
if (env->ExceptionCheck()) {
env->ExceptionDescribe();

View File

@@ -22,18 +22,16 @@
'../include/mbgl/ios/MGLMapView.h',
'../platform/ios/MGLMapView.mm',
'../include/mbgl/ios/MGLAnnotation.h',
'../include/mbgl/ios/MGLUserLocation.h',
'../platform/ios/MGLUserLocation_Private.h',
'../platform/ios/MGLUserLocation.m',
'../platform/ios/MGLUserLocationAnnotationView.h',
'../platform/ios/MGLUserLocationAnnotationView.m',
'../include/mbgl/ios/MGLMetricsLocationManager.h',
'../platform/ios/MGLMetricsLocationManager.m',
'../include/mbgl/ios/MGLStyleFunctionValue.h',
'../platform/ios/MGLStyleFunctionValue.m',
'../include/mbgl/ios/MGLTypes.h',
'../platform/ios/MGLTypes.m',
'../include/mbgl/ios/NSArray+MGLAdditions.h',
'../platform/ios/NSArray+MGLAdditions.m',
'../include/mbgl/ios/NSDictionary+MGLAdditions.h',
'../platform/ios/NSDictionary+MGLAdditions.m',
'../include/mbgl/ios/UIColor+MGLAdditions.h',
'../platform/ios/UIColor+MGLAdditions.m',
'../platform/ios/vendor/SMCalloutView/SMCalloutView.h',
'../platform/ios/vendor/SMCalloutView/SMCalloutView.m',
],
'variables': {
@@ -45,15 +43,13 @@
'<@(uv_static_libs)',
],
'ldflags': [
'-framework CoreGraphics',
'-framework CoreLocation',
'-framework CoreTelephony',
'-framework ImageIO',
'-framework GLKit',
'-framework ImageIO',
'-framework MobileCoreServices',
'-framework OpenGLES',
'-framework QuartzCore',
'-framework SystemConfiguration',
'-framework UIKit',
],
},
@@ -64,6 +60,7 @@
'xcode_settings': {
'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ],
'CLANG_ENABLE_OBJC_ARC': 'YES',
'CLANG_ENABLE_MODULES': 'YES',
},
'link_settings': {

View File

@@ -26,7 +26,6 @@
'<@(uv_static_libs)',
],
'ldflags': [
'-framework Foundation',
'-framework ImageIO',
'-framework CoreServices',
'-framework OpenGL',
@@ -42,6 +41,7 @@
'xcode_settings': {
'OTHER_CPLUSPLUSFLAGS': [ '<@(cflags_cc)' ],
'CLANG_ENABLE_OBJC_ARC': 'YES',
'CLANG_ENABLE_MODULES': 'YES',
},
'link_settings': {

View File

@@ -1,6 +1,10 @@
#import "MGLTypes.h"
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@class MGLUserLocation;
@protocol MGLMapViewDelegate;
@protocol MGLAnnotation;
@@ -29,6 +33,13 @@
* @return An initialized map view, or `nil` if the map view was unable to be initialized. */
- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken bundledStyleNamed:(NSString *)styleName;
/** Initialize a map view with a given frame, style URL, and access token.
* @param frame The frame with which to initialize the map view.
* @param accessToken A Mapbox API access token.
* @param styleURL The map style URL to use. Can be either an HTTP/HTTPS URL or a Mapbox map ID style URL (`mapbox://<user.style>`).
* @return An initialized map view, or `nil` if the map view was unable to be initialized. */
- (instancetype)initWithFrame:(CGRect)frame accessToken:(NSString *)accessToken styleURL:(NSURL *)styleURL;
/** Initialize a map view with a given frame, the default style, and an access token.
* @param frame The frame with which to initialize the map view.
* @param accessToken A Mapbox API access token.
@@ -185,6 +196,10 @@
* @param styleName The map style name to use. */
- (void)useBundledStyleNamed:(NSString *)styleName;
/** Sets the map style URL to use.
* @param styleURL The map style URL to use. Can be either an HTTP/HTTPS URL or a Mapbox map ID style URL (`mapbox://<user.style>`). */
- (void)setStyleURL:(NSURL *)styleURL;
#pragma mark - Annotating the Map
/** @name Annotating the Map */
@@ -234,6 +249,30 @@
* @param animated If `YES`, the callout view is animated offscreen. */
- (void)deselectAnnotation:(id <MGLAnnotation>)annotation animated:(BOOL)animated;
#pragma mark - Displaying the User's Location
/** A Boolean value indicating whether the map may display the user location.
This property does not indicate whether the user’s position is actually visible on the map, only whether the map view is allowed to display it. To determine whether the user’s position is visible, use the userLocationVisible property. The default value of this property is `NO`.
Setting this property to `YES` causes the map view to use the Core Location framework to find the current location. As long as this property is `YES`, the map view continues to track the user’s location and update it periodically.
On iOS 8 and above, your app must specify a value for `NSLocationWhenInUseUsageDescription` in its `Info.plist` to satisfy the requirements of the underlying Core Location framework when enabling this property.
*/
@property (nonatomic, assign) BOOL showsUserLocation;
/// Returns a Boolean value indicating whether the user currently sees the user location annotation.
@property (nonatomic, assign, readonly, getter=isUserLocationVisible) BOOL userLocationVisible;
/// Returns the annotation object indicating the user’s current location.
@property (nonatomic, readonly) MGLUserLocation *userLocation;
/** The mode used to track the user location. */
@property (nonatomic, assign) MGLUserTrackingMode userTrackingMode;
/** Whether the map view should display a heading calibration alert when necessary. The default value is `YES`. */
@property (nonatomic, assign) BOOL displayHeadingCalibration;
#pragma mark - Debugging
/** @name Debugging */
@@ -251,11 +290,15 @@
@end
#pragma mark - MGLMapViewDelegate
/** The MGLMapViewDelegate protocol defines a set of optional methods that you can use to receive map-related update messages. Because many map operations require the MGLMapView class to load data asynchronously, the map view calls these methods to notify your application when specific operations complete. The map view also uses these methods to request annotation marker symbology and to manage interactions with those markers. */
@protocol MGLMapViewDelegate <NSObject>
@optional
#pragma mark - Managing the Display of Annotations
/** @name Managing the Display of Annotations */
/** Returns the style's symbol name to use for the marker for the specified point annotation object.
@@ -264,14 +307,54 @@
* @return The marker symbol to display for the specified annotation or `nil` if you want to display the default symbol. */
- (NSString *)mapView:(MGLMapView *)mapView symbolNameForAnnotation:(id <MGLAnnotation>)annotation;
/** Returns a Boolean value indicating whether the annotation is able to display extra information in a callout bubble.
*
* If the value returned is `YES`, a standard callout bubble is shown when the user taps a selected annotation. The callout uses the title and subtitle text from the associated annotation object. If there is no title text, though, the annotation will not show a callout. The callout also displays any custom callout views returned by the delegate for the left and right callout accessory views.
*
* If the value returned is `NO`, the value of the title and subtitle strings are ignored.
*
* @param mapView The map view that requested the annotation callout ability.
* @param annotation The object representing the annotation.
* @return A Boolean indicating whether the annotation should show a callout. */
- (BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id <MGLAnnotation>)annotation;
/** Return the view to display on the left side of the standard callout bubble.
*
* The default value is treated as if `nil`. The left callout view is typically used to display information about the annotation or to link to custom information provided by your application.
*
* If the view you specify is also a descendant of the `UIControl` class, you can use the map view’s delegate to receive notifications when your control is tapped. If it does not descend from `UIControl`, your view is responsible for handling any touch events within its bounds.
*
* @param mapView The map view presenting the annotation callout.
* @param annotation The object representing the annotation with the callout.
* @return The accessory view to display. */
- (UIView *)mapView:(MGLMapView *)mapView leftCalloutAccessoryViewForAnnotation:(id <MGLAnnotation>)annotation;
/** Return the view to display on the right side of the standard callout bubble.
*
* The default value is treated is if `nil`. The right callout view is typically used to link to more detailed information about the annotation. A common view to specify for this property is `UIButton` object whose type is set to `UIButtonTypeDetailDisclosure`.
*
* If the view you specify is also a descendant of the `UIControl` class, you can use the map view’s delegate to receive notifications when your control is tapped. If it does not descend from `UIControl`, your view is responsible for handling any touch events within its bounds.
*
* @param mapView The map view presenting the annotation callout.
* @param annotation The object representing the annotation with the callout.
* @return The accessory view to display. */
- (UIView *)mapView:(MGLMapView *)mapView rightCalloutAccessoryViewForAnnotation:(id <MGLAnnotation>)annotation;
#pragma mark - Responding to Map Position Changes
// Responding to Map Position Changes
// TODO
- (void)mapView:(MGLMapView *)mapView regionWillChangeAnimated:(BOOL)animated;
// TODO
- (void)mapViewRegionIsChanging:(MGLMapView *)mapView;
// TODO
- (void)mapView:(MGLMapView *)mapView regionDidChangeAnimated:(BOOL)animated;
#pragma mark - Loading the Map Data
// Loading the Map Data
// TODO
@@ -289,4 +372,60 @@
// TODO
- (void)mapViewDidFinishRenderingMap:(MGLMapView *)mapView fullyRendered:(BOOL)fullyRendered;
#pragma mark - Tracking the User Location
/// Tells the delegate that the map view will begin tracking the user’s location.
- (void)mapViewWillStartLocatingUser:(MGLMapView *)mapView;
/// Tells the delegate that the map view has stopped tracking the user’s location.
- (void)mapViewDidStopLocatingUser:(MGLMapView *)mapView;
/// Tells the delegate that the map view has updated the user’s location to the given location.
- (void)mapView:(MGLMapView *)mapView didUpdateUserLocation:(MGLUserLocation *)userLocation;
/// Tells the delegate that the map view has failed to locate the user.
- (void)mapView:(MGLMapView *)mapView didFailToLocateUserWithError:(NSError *)error;
/**
Tells the delegate that the map view’s user tracking mode has changed.
This method is called after the map view asynchronously changes to reflect the new user tracking mode, for example by beginning to zoom or rotate.
*/
- (void)mapView:(MGLMapView *)mapView didChangeUserTrackingMode:(MGLUserTrackingMode)mode animated:(BOOL)animated;
#pragma mark - Managing Annotations
/** @name Managing Annotations */
/* Tells the delegate that the user tapped one of the annotation's accessory buttons.
*
* Accessory views contain custom content and are positioned on either side of the annotation title text. If a view you specify is a descendant of the `UIControl` class, the map view calls this method as a convenience whenever the user taps your view. You can use this method to respond to taps and perform any actions associated with that control. For example, if your control displayed additional information about the annotation, you could use this method to present a modal panel with that information.
*
* If your custom accessory views are not descendants of the `UIControl` class, the map view does not call this method.
*
* @param mapView The map view containing the specified annotation.
* @param annotation The annotation whose button was tapped.
* @param control The control that was tapped. */
- (void)mapView:(MGLMapView *)mapView annotation:(id <MGLAnnotation>)annotation calloutAccessoryControlTapped:(UIControl *)control;
#pragma mark - Selecting Annotations
/** @name Selecting Annotations */
/* Tells the delegate that one of its annotations was selected.
*
* You can use this method to track changes in the selection state of annotations.
*
* @param mapView The map view containing the annotation.
* @param annotation The annotation that was selected. */
- (void)mapView:(MGLMapView *)mapView didSelectAnnotation:(id <MGLAnnotation>)annotation;
/* Tells the delegate that one of its annotations was deselected.
*
* You can use this method to track changes in the selection state of annotations.
*
* @param mapView The map view containing the annotation.
* @param annotation The annotation that was deselected. */
- (void)mapView:(MGLMapView *)mapView didDeselectAnnotation:(id <MGLAnnotation>)annotation;
@end

View File

@@ -1,26 +1,50 @@
//
// MapboxEvents.h
// MapboxEvents
//
// Created by Brad Leege on 3/5/15.
// Copyright (c) 2015 Mapbox. All rights reserved.
//
#import <Foundation/Foundation.h>
extern NSString *const MGLEventTypeMapLoad;
extern NSString *const MGLEventTypeMapTap;
extern NSString *const MGLEventTypeMapDragEnd;
extern NSString *const MGLEventTypeLocation;
extern NSString *const MGLEventKeyLatitude;
extern NSString *const MGLEventKeyLongitude;
extern NSString *const MGLEventKeyZoomLevel;
extern NSString *const MGLEventKeyPushEnabled;
extern NSString *const MGLEventKeyEmailEnabled;
extern NSString *const MGLEventKeyGestureID;
extern NSString *const MGLEventGestureSingleTap;
extern NSString *const MGLEventGestureDoubleTap;
extern NSString *const MGLEventGestureTwoFingerSingleTap;
extern NSString *const MGLEventGestureQuickZoom;
extern NSString *const MGLEventGesturePanStart;
extern NSString *const MGLEventGesturePinchStart;
extern NSString *const MGLEventGestureRotateStart;
@interface MGLMapboxEvents : NSObject
@property (atomic) NSInteger flushAt;
@property (atomic) NSInteger flushAfter;
@property (atomic) NSString *api;
@property (atomic) NSString *token;
@property (atomic) NSString *appName;
@property (atomic) NSString *appVersion;
// You must call these methods from the main thread.
//
+ (void) setToken:(NSString *)token;
+ (void) setAppName:(NSString *)appName;
+ (void) setAppVersion:(NSString *)appVersion;
+ (id)sharedManager;
// You can call this method from any thread. Significant work will
// be dispatched to a low-priority background queue and all
// resulting calls are guaranteed threadsafe.
//
// Events or attributes passed could be accessed on non-main threads,
// so you must not reference UI elements from within any arguments.
// Copy any values needed first or create dedicated methods in this
// class for threadsafe access to UIKit classes.
//
+ (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary;
- (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary;
// You can call these methods from any thread.
//
+ (BOOL) checkPushEnabled;
- (void) flush;
// You can call this method from any thread.
//
+ (void) flush;
@end
@end

View File

@@ -1,22 +1,9 @@
//
// MBLocationManager.h
// Hermes
//
// Created by Brad Leege on 3/8/15.
// Copyright (c) 2015 Mapbox. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "CoreLocation/CoreLocation.h"
@interface MGLMetricsLocationManager : NSObject <CLLocationManagerDelegate>
@interface MGLMetricsLocationManager : NSObject
+ (id)sharedManager;
- (BOOL) isAuthorizedStatusDetermined;
- (void) requestAlwaysAuthorization;
- (void) startUpdatingLocation;
- (void) stopUpdatingLocation;
// This method can be called from any thread.
//
+ (instancetype)sharedManager;
@end

View File

@@ -1,23 +0,0 @@
#import <UIKit/UIKit.h>
@interface MGLStyleFunctionValue : NSObject
+ (instancetype)linearFunctionWithBaseZoomLevel:(CGFloat)zBase
initialValue:(CGFloat)val
slope:(CGFloat)slope
minimumValue:(CGFloat)min
maximumValue:(CGFloat)max;
+ (instancetype)exponentialFunctionWithBaseZoomLevel:(CGFloat)zBase
initialValue:(CGFloat)val
slope:(CGFloat)slope
minimumValue:(CGFloat)min
maximumValue:(CGFloat)max;
+ (instancetype)minimumZoomLevelFunction:(CGFloat)minimumZoom;
+ (instancetype)maximumZoomLevelFunction:(CGFloat)maximumZoom;
+ (instancetype)stopsFunctionWithZoomLevelsAndValues:(NSNumber *)firstZoom, ... NS_REQUIRES_NIL_TERMINATION;
@end

View File

@@ -1,17 +1,9 @@
#import <Foundation/Foundation.h>
// style property value types
//
extern NSString *const MGLStyleValueTypeBoolean;
extern NSString *const MGLStyleValueTypeNumber;
extern NSString *const MGLStyleValueTypeNumberPair;
extern NSString *const MGLStyleValueTypeColor;
extern NSString *const MGLStyleValueTypeString;
// style property function types
//
extern NSString *const MGLStyleValueTypeFunctionMinimumZoom;
extern NSString *const MGLStyleValueTypeFunctionMaximumZoom;
extern NSString *const MGLStyleValueTypeFunctionLinear;
extern NSString *const MGLStyleValueTypeFunctionExponential;
extern NSString *const MGLStyleValueTypeFunctionStops;
/// The degree to which the map view tracks the user’s location.
typedef NS_ENUM(NSUInteger, MGLUserTrackingMode)
{
MGLUserTrackingModeNone = 0, ///< does not track the user’s location or heading
MGLUserTrackingModeFollow = 1, ///< tracks the user’s location
MGLUserTrackingModeFollowWithHeading = 2, ///< tracks the user’s location and heading
};

View File

@@ -0,0 +1,26 @@
#import "MGLAnnotation.h"
@interface MGLUserLocation : NSObject <MGLAnnotation>
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
/** @name Determining the User’s Position */
/** The current location of the device. (read-only)
*
* This property contains `nil` if the map view is not currently showing the user location or if the user’s location has not yet been determined. */
@property (nonatomic, readonly) CLLocation *location;
/** A Boolean value indicating whether the user’s location is currently being updated. (read-only) */
@property (nonatomic, readonly, getter=isUpdating) BOOL updating; // FIXME
/** The heading of the user location. (read-only)
*
* This property is `nil` if the user location tracking mode is not `RMUserTrackingModeFollowWithHeading`. */
@property (nonatomic, readonly) CLHeading *heading;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end

View File

@@ -1,7 +1,4 @@
#import "MGLAnnotation.h"
#import "MGLMapView.h"
#import "MGLStyleFunctionValue.h"
#import "MGLTypes.h"
#import "NSArray+MGLAdditions.h"
#import "NSDictionary+MGLAdditions.h"
#import "UIColor+MGLAdditions.h"
#import "MGLUserLocation.h"

View File

@@ -1,7 +0,0 @@
#import <Foundation/Foundation.h>
@interface NSArray (MGLAdditions)
- (NSMutableArray *)deepMutableCopy;
@end

View File

@@ -1,7 +0,0 @@
#import <Foundation/Foundation.h>
@interface NSDictionary (MGLAdditions)
- (NSMutableDictionary *)deepMutableCopy;
@end

View File

@@ -1,11 +0,0 @@
#import <UIKit/UIKit.h>
@interface UIColor (MGLAdditions)
+ (UIColor *)colorWithRGBAString:(NSString *)rgbaString;
- (NSString *)rgbaStringFromColor;
+ (UIColor *)colorWithHexString:(NSString *)hexString;
- (NSString *)hexStringFromColor;
@end

View File

@@ -15,6 +15,7 @@
#include <iosfwd>
#include <set>
#include <vector>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
@@ -28,7 +29,6 @@ class LayerDescription;
class Sprite;
class Style;
class StyleLayer;
class StyleLayerGroup;
class StyleSource;
class TexturePool;
class FileSource;
@@ -153,13 +153,14 @@ public:
// Annotations
void setDefaultPointAnnotationSymbol(const std::string&);
double getTopOffsetPixelsForAnnotationSymbol(const std::string&);
uint32_t addPointAnnotation(const LatLng&, const std::string& symbol);
std::vector<uint32_t> addPointAnnotations(const std::vector<LatLng>&,
const std::vector<std::string>& symbols);
void removeAnnotation(uint32_t);
void removeAnnotations(const std::vector<uint32_t>&);
std::vector<uint32_t> getAnnotationsInBounds(const LatLngBounds&) const;
LatLngBounds getBoundsForAnnotations(const std::vector<uint32_t>&) const;
std::vector<uint32_t> getAnnotationsInBounds(const LatLngBounds&);
LatLngBounds getBoundsForAnnotations(const std::vector<uint32_t>&);
// Debug
void setDebug(bool value);
@@ -186,7 +187,6 @@ private:
void updateTiles();
void updateSources();
void updateSources(const util::ptr<StyleLayerGroup> &group);
// Triggered by triggerUpdate();
void update();
@@ -199,6 +199,12 @@ private:
// the stylesheet.
void prepare();
// Runs the function in the map thread.
void invokeTask(std::function<void()>&&);
template <typename Fn> auto invokeSyncTask(const Fn& fn) -> decltype(fn());
void processTasks();
void updateAnnotationTiles(const std::vector<Tile::ID>&);
enum class Mode : uint8_t {
@@ -218,6 +224,7 @@ private:
std::thread thread;
std::unique_ptr<uv::async> asyncTerminate;
std::unique_ptr<uv::async> asyncUpdate;
std::unique_ptr<uv::async> asyncInvoke;
std::unique_ptr<uv::async> asyncRender;
bool terminating = false;
@@ -256,6 +263,9 @@ private:
std::set<util::ptr<StyleSource>> activeSources;
std::atomic<UpdateType> updated;
std::mutex mutexTask;
std::queue<std::function<void()>> tasks;
};
}

View File

@@ -10,14 +10,15 @@ class Map;
enum MapChange : uint8_t {
MapChangeRegionWillChange = 0,
MapChangeRegionWillChangeAnimated = 1,
MapChangeRegionDidChange = 2,
MapChangeRegionDidChangeAnimated = 3,
MapChangeWillStartLoadingMap = 4,
MapChangeDidFinishLoadingMap = 5,
MapChangeDidFailLoadingMap = 6,
MapChangeWillStartRenderingMap = 7,
MapChangeDidFinishRenderingMap = 8,
MapChangeDidFinishRenderingMapFullyRendered = 9
MapChangeRegionIsChanging = 2,
MapChangeRegionDidChange = 3,
MapChangeRegionDidChangeAnimated = 4,
MapChangeWillStartLoadingMap = 5,
MapChangeDidFinishLoadingMap = 6,
MapChangeDidFailLoadingMap = 7,
MapChangeWillStartRenderingMap = 8,
MapChangeDidFinishRenderingMap = 9,
MapChangeDidFinishRenderingMapFullyRendered = 10
};
class View {

View File

@@ -1,6 +1,8 @@
#ifndef MBGL_COMMON_SETTINGS_NSUSERDEFAULTS
#define MBGL_COMMON_SETTINGS_NSUSERDEFAULTS
#import <mbgl/ios/MGLTypes.h>
namespace mbgl {
class Settings_NSUserDefaults {
@@ -16,6 +18,9 @@ public:
double zoom = 0;
double bearing = 0;
MGLUserTrackingMode userTrackingMode = MGLUserTrackingModeNone;
bool showsUserLocation = false;
bool debug = false;
};

View File

@@ -22,7 +22,7 @@ Pod::Spec.new do |m|
m.resource_bundle = { 'MapboxGL' => 'MapboxGL.bundle/*' }
m.frameworks = 'CoreLocation', 'GLKit', 'ImageIO', 'MobileCoreServices', 'SystemConfiguration'
m.frameworks = 'CoreLocation', 'CoreTelephony', 'GLKit', 'ImageIO', 'MobileCoreServices', 'QuartzCore', 'SystemConfiguration'
m.libraries = 'c++', 'sqlite3', 'z'

View File

@@ -21,10 +21,9 @@ static NSArray *const kStyleNames = @[
static NSString *const kStyleVersion = @"v7";
@interface MBXViewController () <UIActionSheetDelegate, CLLocationManagerDelegate>
@interface MBXViewController () <UIActionSheetDelegate, MGLMapViewDelegate>
@property (nonatomic) MGLMapView *mapView;
@property (nonatomic) CLLocationManager *locationManager;
@end
@@ -66,9 +65,10 @@ mbgl::Settings_NSUserDefaults *settings = nullptr;
self.mapView = [[MGLMapView alloc] initWithFrame:self.view.bounds accessToken:accessToken];
self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.mapView];
self.mapView.viewControllerForLayoutGuides = self;
self.mapView.showsUserLocation = YES;
self.mapView.delegate = self;
[self.view addSubview:self.mapView];
self.view.tintColor = kTintColor;
self.navigationController.navigationBar.tintColor = kTintColor;
@@ -107,6 +107,8 @@ mbgl::Settings_NSUserDefaults *settings = nullptr;
settings->zoom = self.mapView.zoomLevel;
settings->bearing = self.mapView.direction;
settings->debug = self.mapView.isDebugActive;
settings->userTrackingMode = self.mapView.userTrackingMode;
settings->showsUserLocation = self.mapView.showsUserLocation;
settings->save();
}
}
@@ -117,6 +119,8 @@ mbgl::Settings_NSUserDefaults *settings = nullptr;
settings->load();
[self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(settings->latitude, settings->longitude) zoomLevel:settings->zoom animated:NO];
self.mapView.direction = settings->bearing;
self.mapView.userTrackingMode = settings->userTrackingMode;
self.mapView.showsUserLocation = settings->showsUserLocation;
[self.mapView setDebugActive:settings->debug];
}
}
@@ -252,40 +256,17 @@ mbgl::Settings_NSUserDefaults *settings = nullptr;
- (void)locateUser
{
if ( ! self.locationManager)
if (self.mapView.userTrackingMode == MGLUserTrackingModeNone)
{
self.locationManager = [CLLocationManager new];
self.locationManager.delegate = self;
self.mapView.userTrackingMode = MGLUserTrackingModeFollow;
}
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
else if (self.mapView.userTrackingMode == MGLUserTrackingModeFollow)
{
[[[UIAlertView alloc] initWithTitle:@"Authorization Denied"
message:@"Please enable location services for this app in Privacy settings."
delegate:nil
cancelButtonTitle:nil otherButtonTitles:@"OK", nil] show];
self.mapView.userTrackingMode = MGLUserTrackingModeFollowWithHeading;
}
else
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([CLLocationManager instancesRespondToSelector:@selector(requestWhenInUseAuthorization)])
{
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse)
{
[self.locationManager startUpdatingLocation];
}
else
{
[_locationManager requestWhenInUseAuthorization];
}
}
else
{
[self.locationManager startUpdatingLocation];
}
#else
[self.locationManager startUpdatingLocation];
#endif
self.mapView.userTrackingMode = MGLUserTrackingModeNone;
}
}
@@ -303,39 +284,14 @@ mbgl::Settings_NSUserDefaults *settings = nullptr;
}
}
#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
switch (status)
{
case kCLAuthorizationStatusAuthorizedAlways:
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
case kCLAuthorizationStatusAuthorizedWhenInUse:
#endif
{
[manager startUpdatingLocation];
break;
}
default:
{
}
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
#pragma mark - MGLMapViewDelegate
- (BOOL)mapView:(MGLMapView *)mapView annotationCanShowCallout:(id <MGLAnnotation>)annotation
{
CLLocation *latestLocation = locations.lastObject;
if ([latestLocation distanceFromLocation:[[CLLocation alloc] initWithLatitude:self.mapView.centerCoordinate.latitude longitude:self.mapView.centerCoordinate.longitude]] > 100)
{
[self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(latestLocation.coordinate.latitude, latestLocation.coordinate.longitude) zoomLevel:17 animated:YES];
}
[self.locationManager stopUpdatingLocation];
return YES;
}
#pragma clang diagnostic pop

View File

@@ -10,7 +10,8 @@
'mac_bundle': 1,
'mac_bundle_resources': [
'<!@(find ./img -type f)',
'./features.geojson'
'./features.geojson',
'./Settings.bundle/'
],
'dependencies': [
@@ -41,6 +42,7 @@
'TARGETED_DEVICE_FAMILY': '1,2',
'COMBINE_HIDPI_IMAGES': 'NO', # don't merge @2x.png images into .tiff files
'CLANG_ENABLE_OBJC_ARC': 'YES',
'CLANG_ENABLE_MODULES': 'YES',
},
'configurations': {

View File

@@ -6,11 +6,15 @@ using namespace mbgl;
Settings_NSUserDefaults::Settings_NSUserDefaults()
{
[[NSUserDefaults standardUserDefaults] registerDefaults:@{ @"longitude" : @(longitude),
@"latitude" : @(latitude),
@"zoom" : @(zoom),
@"bearing" : @(bearing),
@"debug" : @(debug) }];
[[NSUserDefaults standardUserDefaults] registerDefaults:@{
@"longitude" : @(longitude),
@"latitude" : @(latitude),
@"zoom" : @(zoom),
@"bearing" : @(bearing),
@"userTrackingMode" : @(userTrackingMode),
@"showsUserLocation" : @(showsUserLocation),
@"debug" : @(debug),
}];
load();
}
@@ -23,15 +27,27 @@ void Settings_NSUserDefaults::load()
zoom = [settings[@"zoom"] doubleValue];
bearing = [settings[@"bearing"] doubleValue];
debug = [settings[@"debug"] boolValue];
unsigned uncheckedTrackingMode = [settings[@"trackingMode"] unsignedIntValue];
if (uncheckedTrackingMode > MGLUserTrackingModeNone &&
uncheckedTrackingMode <= MGLUserTrackingModeFollowWithHeading)
{
userTrackingMode = (MGLUserTrackingMode)uncheckedTrackingMode;
}
showsUserLocation = [settings[@"showsUserLocation"] boolValue];
}
void Settings_NSUserDefaults::save()
{
[[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:@{ @"longitude" : @(longitude),
@"latitude" : @(latitude),
@"zoom" : @(zoom),
@"bearing" : @(bearing),
@"debug" : @(debug) }];
[[NSUserDefaults standardUserDefaults] setValuesForKeysWithDictionary:@{
@"longitude" : @(longitude),
@"latitude" : @(latitude),
@"zoom" : @(zoom),
@"bearing" : @(bearing),
@"userTrackingMode" : @(userTrackingMode),
@"showsUserLocation" : @(showsUserLocation),
@"debug" : @(debug),
}];
[[NSUserDefaults standardUserDefaults] synchronize];
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,42 +1,99 @@
//
// MapboxEvents.m
// MapboxEvents
//
// Dynamic detection of ASIdentifierManager from Mixpanel
// https://github.com/mixpanel/mixpanel-iphone/blob/master/LICENSE
//
// Created by Brad Leege on 3/5/15.
// Copyright (c) 2015 Mapbox. All rights reserved.
//
#import "MGLMapboxEvents.h"
#import <UIKit/UIKit.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "MGLMetricsLocationManager.h"
#include <sys/sysctl.h>
#import <SystemConfiguration/CaptiveNetwork.h>
static NSString *const MGLMapboxEventsUserAgent = @"MapboxEventsiOS/1.0";
static NSString *const MGLMapboxEventsAPIBase = @"https://api.tiles.mapbox.com";
NSString *const MGLEventTypeMapLoad = @"map.load";
NSString *const MGLEventTypeMapTap = @"map.click";
NSString *const MGLEventTypeMapDragEnd = @"map.dragend";
NSString *const MGLEventTypeLocation = @"Location";
NSString *const MGLEventKeyLatitude = @"lat";
NSString *const MGLEventKeyLongitude = @"lng";
NSString *const MGLEventKeyZoomLevel = @"zoom";
NSString *const MGLEventKeyPushEnabled = @"enabled.push";
NSString *const MGLEventKeyEmailEnabled = @"enabled.email";
NSString *const MGLEventKeyGestureID = @"gesture";
NSString *const MGLEventGestureSingleTap = @"SingleTap";
NSString *const MGLEventGestureDoubleTap = @"DoubleTap";
NSString *const MGLEventGestureTwoFingerSingleTap = @"TwoFingerTap";
NSString *const MGLEventGestureQuickZoom = @"QuickZoom";
NSString *const MGLEventGesturePanStart = @"Pan";
NSString *const MGLEventGesturePinchStart = @"Pinch";
NSString *const MGLEventGestureRotateStart = @"Rotation";
//
// Threadsafety conventions:
//
// All variables accessed from more than one thread are
// designated `atomic` and accessed through dot syntax. The
// main thread uses underscore syntax during the
// initialization of the variable.
//
// All variables accessed outside of initialization and
// from within a single thread use underscore syntax.
//
// All captures of `self` from within asynchronous
// dispatches will use a `weakSelf` to avoid cyclical
// strong references.
//
@interface MGLMapboxEvents()
@property (atomic) NSMutableArray *queue;
@property (atomic) NSString *instance;
@property (atomic) NSString *anonid;
@property (atomic) NSTimer *timer;
// All of the following properties are written to only from
// the main thread, but can be read on any thread.
//
@property (atomic) NSString *token;
@property (atomic) NSString *appName;
@property (atomic) NSString *appVersion;
@property (atomic) NSString *instanceID;
@property (atomic) NSString *advertiserId;
@property (atomic) NSString *vendorId;
@property (atomic) NSString *appBundleId;
@property (atomic) NSString *userAgent;
@property (atomic) NSString *model;
@property (atomic) NSString *iOSVersion;
@property (atomic) NSString *carrier;
@property (atomic) NSUInteger flushAt;
@property (atomic) NSDateFormatter *rfc3339DateFormatter;
@property (atomic) CGFloat scale;
// The timer is only ever accessed from the main thread.
//
@property (nonatomic) NSTimer *timer;
// The flush expiration time is only ever accessed from the main thread.
//
@property (nonatomic) NSTimeInterval flushAfter;
// This is an array of events to push. All access to it will be
// from our own serial queue.
//
@property (nonatomic) NSMutableArray *eventQueue;
// This is a custom serial queue for accessing the event queue.
//
@property (nonatomic) dispatch_queue_t serialQueue;
@end
@implementation MGLMapboxEvents
static MGLMapboxEvents *sharedManager = nil;
// Must be called from the main thread. Only called internally.
//
- (instancetype) init {
assert([[NSThread currentThread] isMainThread]);
NSDateFormatter *rfc3339DateFormatter = nil;
NSString *model;
NSString *iOSVersion;
NSString *carrier;
NSNumber *scale;
- (id) init {
self = [super init];
if (self) {
@@ -45,6 +102,8 @@ NSNumber *scale;
if(!settingsBundle) {
NSLog(@"Could not find Settings.bundle");
} else {
// Dynamic Settings.bundle loading based on:
// http://stackoverflow.com/questions/510216/can-you-make-the-settings-in-settings-bundle-default-even-if-you-dont-open-the
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
@@ -57,14 +116,19 @@ NSNumber *scale;
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
}
_appBundleId = [[NSBundle mainBundle] bundleIdentifier];
NSString *uniqueID = [[NSProcessInfo processInfo] globallyUniqueString];
_serialQueue = dispatch_queue_create([[NSString stringWithFormat:@"%@.%@.events.serial", _appBundleId, uniqueID] UTF8String], DISPATCH_QUEUE_SERIAL);
// Configure Events Infrastructure
_queue = [[NSMutableArray alloc] init];
_eventQueue = [[NSMutableArray alloc] init];
_flushAt = 20;
_flushAfter = 10000;
_api = @"https://api.tiles.mapbox.com";
_flushAfter = 60;
_token = nil;
_instance = [[NSUUID UUID] UUIDString];
_instanceID = [[NSUUID UUID] UUIDString];
// Dynamic detection of ASIdentifierManager from Mixpanel
// https://github.com/mixpanel/mixpanel-iphone/blob/master/LICENSE
_advertiserId = @"";
Class ASIdentifierManagerClass = NSClassFromString(@"ASIdentifierManager");
if (ASIdentifierManagerClass) {
SEL sharedManagerSelector = NSSelectorFromString(@"sharedManager");
@@ -75,232 +139,348 @@ NSNumber *scale;
if (trackingEnabled) {
SEL advertisingIdentifierSelector = NSSelectorFromString(@"advertisingIdentifier");
NSUUID *uuid = ((NSUUID* (*)(id, SEL))[sharedManager methodForSelector:advertisingIdentifierSelector])(sharedManager, advertisingIdentifierSelector);
_anonid = [uuid UUIDString];
} else {
_anonid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
_advertiserId = [uuid UUIDString];
}
} else {
_anonid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}
_vendorId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
model = [self getSysInfoByName:"hw.machine"];
iOSVersion = [NSString stringWithFormat:@"%@ %@", [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion];
_model = [self getSysInfoByName:"hw.machine"];
_iOSVersion = [NSString stringWithFormat:@"%@ %@", [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion];
if ([UIScreen instancesRespondToSelector:@selector(nativeScale)]) {
scale = [[NSNumber alloc] initWithFloat:[UIScreen mainScreen].nativeScale];
_scale = [UIScreen mainScreen].nativeScale;
} else {
scale = [[NSNumber alloc] initWithFloat:[UIScreen mainScreen].scale];
_scale = [UIScreen mainScreen].scale;
}
CTCarrier *carrierVendor = [[[CTTelephonyNetworkInfo alloc] init] subscriberCellularProvider];
carrier = [carrierVendor carrierName];
_carrier = [carrierVendor carrierName];
_userAgent = @"MapboxEventsiOS/1.0";
_userAgent = MGLMapboxEventsUserAgent;
// Setup Date Format
rfc3339DateFormatter = [[NSDateFormatter alloc] init];
_rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[_rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[_rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[_rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
}
return self;
}
+ (id)sharedManager {
// Can be called from any thread. Called implicitly from any
// public class convenience methods.
//
+ (instancetype)sharedManager {
static dispatch_once_t onceToken;
static MGLMapboxEvents *_sharedManager;
dispatch_once(&onceToken, ^{
sharedManager = [[self alloc] init];
void (^setupBlock)() = ^{
_sharedManager = [[self alloc] init];
// setup dedicated location manager on first use
[MGLMetricsLocationManager sharedManager];
};
if ( ! [[NSThread currentThread] isMainThread]) {
dispatch_sync(dispatch_get_main_queue(), ^{
setupBlock();
});
} else {
setupBlock();
}
});
return sharedManager;
return _sharedManager;
}
// Must be called from the main thread.
//
+ (void) setToken:(NSString *)token {
assert([[NSThread currentThread] isMainThread]);
[MGLMapboxEvents sharedManager].token = token;
}
// Must be called from the main thread.
//
+ (void) setAppName:(NSString *)appName {
assert([[NSThread currentThread] isMainThread]);
[MGLMapboxEvents sharedManager].appName = appName;
}
// Must be called from the main thread.
//
+ (void) setAppVersion:(NSString *)appVersion {
assert([[NSThread currentThread] isMainThread]);
[MGLMapboxEvents sharedManager].appVersion = appVersion;
}
// Can be called from any thread. Can be called rapidly from
// the UI thread, so performance is paramount.
//
+ (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
[[MGLMapboxEvents sharedManager] pushEvent:event withAttributes:attributeDictionary];
});
}
// Can be called from any thread. Called implicitly from public
// use of +pushEvent:withAttributes:.
//
- (void) pushEvent:(NSString *)event withAttributes:(NSDictionary *)attributeDictionary {
// Opt Out Checking When Built
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"mapbox_metrics_enabled_preference"]) {
NSLog(@"Mapbox Metrics are not enabled, so clear any currently stored events, and return without sending in data.");
[_queue removeAllObjects];
return;
}
__weak MGLMapboxEvents *weakSelf = self;
// Add Metrics Disabled App Wide Check
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"mapbox_metrics_disabled"] != nil) {
NSLog(@"Mapbox Metrics have been disabled for this app.");
[_queue removeAllObjects];
return;
}
if (!event) {
return;
}
NSMutableDictionary *evt = [[NSMutableDictionary alloc] init];
// mapbox-events stock attributes
[evt setObject:event forKey:@"event"];
[evt setObject:[NSNumber numberWithInt:1] forKey:@"version"];
[evt setObject:[self formatDate:[NSDate date]] forKey:@"created"];
[evt setObject:self.instance forKey:@"instance"];
[evt setObject:self.anonid forKey:@"anonid"];
// mapbox-events-ios stock attributes
[evt setValue:[rfc3339DateFormatter stringFromDate:[NSDate date]] forKey:@"deviceTimestamp"];
[evt setValue:model forKey:@"model"];
[evt setValue:iOSVersion forKey:@"operatingSystem"];
[evt setValue:[self getDeviceOrientation] forKey:@"orientation"];
[evt setValue:[[NSNumber alloc] initWithFloat:(100 * [UIDevice currentDevice].batteryLevel)] forKey:@"batteryLevel"];
[evt setValue:scale forKey:@"resolution"];
[evt setValue:carrier forKey:@"carrier"];
[evt setValue:[self getWifiNetworkName] forKey:@"wifi"];
[evt setValue:[NSNumber numberWithInt:[self getContentSizeScale]] forKey:@"accessibilityFontScale"];
for (NSString *key in [attributeDictionary allKeys]) {
[evt setObject:[attributeDictionary valueForKey:key] forKey:key];
}
// Make Immutable Version
NSDictionary *finalEvent = [NSDictionary dictionaryWithDictionary:evt];
// Put On The Queue
[self.queue addObject:finalEvent];
// Has Flush Limit Been Reached?
if ((int)_queue.count >= (int)_flushAt) {
[self flush];
}
// Reset Timer (Initial Starting of Timer after first event is pushed)
[self startTimer];
}
- (void) flush {
if (_token == nil) {
NSLog(@"token hasn't been set yet, so no events can be sent. return");
return;
}
int upper = (int)_flushAt;
if (_flushAt > [_queue count]) {
if ([_queue count] == 0) {
dispatch_async(_serialQueue, ^{
// Opt Out Checking When Built
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"mapbox_metrics_enabled_preference"]) {
[_eventQueue removeAllObjects];
return;
}
upper = (int)[_queue count];
}
// Create Array of Events to push to the Server
NSRange theRange = NSMakeRange(0, upper);
NSArray *events = [_queue subarrayWithRange:theRange];
// Update Queue to remove events sent to server
[_queue removeObjectsInRange:theRange];
// Send Array of Events to Server
[self postEvents:events];
}
- (void) postEvents:(NSArray *)events {
// Setup URL Request
NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", _api, _token];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setValue:[self getUserAgent] forHTTPHeaderField:@"User-Agent"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
// Convert Array of Dictionaries to JSON
if ([NSJSONSerialization isValidJSONObject:events]) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:events options:NSJSONWritingPrettyPrinted error:nil];
[request setHTTPBody:jsonData];
// Add Metrics Disabled App Wide Check
if ([[NSUserDefaults standardUserDefaults] objectForKey:@"mapbox_metrics_disabled"] != nil) {
[_eventQueue removeAllObjects];
return;
}
// Send non blocking HTTP Request to server
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:nil];
}
if (!event) return;
NSMutableDictionary *evt = [[NSMutableDictionary alloc] initWithDictionary:attributeDictionary];
// mapbox-events stock attributes
[evt setObject:event forKey:@"event"];
[evt setObject:@(1) forKey:@"version"];
[evt setObject:[weakSelf formatDate:[NSDate date]] forKey:@"created"];
[evt setObject:weakSelf.instanceID forKey:@"instance"];
[evt setObject:weakSelf.advertiserId forKey:@"advertiserId"];
[evt setObject:weakSelf.vendorId forKey:@"vendorId"];
[evt setObject:weakSelf.appBundleId forKeyedSubscript:@"appBundleId"];
// mapbox-events-ios stock attributes
[evt setValue:[weakSelf.rfc3339DateFormatter stringFromDate:[NSDate date]] forKey:@"created"];
[evt setValue:weakSelf.model forKey:@"model"];
[evt setValue:weakSelf.iOSVersion forKey:@"operatingSystem"];
[evt setValue:[weakSelf getDeviceOrientation] forKey:@"orientation"];
[evt setValue:@(100 * [UIDevice currentDevice].batteryLevel) forKey:@"batteryLevel"];
[evt setValue:@(weakSelf.scale) forKey:@"resolution"];
[evt setValue:weakSelf.carrier forKey:@"carrier"];
[evt setValue:[weakSelf getCurrentCellularNetworkConnectionType] forKey:@"cellularNetworkType"];
[evt setValue:[weakSelf getWifiNetworkName] forKey:@"wifi"];
[evt setValue:@([weakSelf getContentSizeScale]) forKey:@"accessibilityFontScale"];
// Make Immutable Version
NSDictionary *finalEvent = [NSDictionary dictionaryWithDictionary:evt];
// Put On The Queue
[_eventQueue addObject:finalEvent];
// Has Flush Limit Been Reached?
if (_eventQueue.count >= weakSelf.flushAt) {
[weakSelf flush];
}
// Reset Timer (Initial Starting of Timer after first event is pushed)
[weakSelf startTimer];
});
}
// Can be called from any thread.
//
+ (void) flush {
[[MGLMapboxEvents sharedManager] flush];
}
// Can be called from any thread.
//
- (void) flush {
if (self.token == nil) return;
__weak MGLMapboxEvents *weakSelf = self;
dispatch_async(_serialQueue, ^{
__block NSArray *events;
NSUInteger upper = weakSelf.flushAt;
if (weakSelf.flushAt > [_eventQueue count]) {
if ([_eventQueue count] == 0) {
return;
}
upper = [_eventQueue count];
}
// Create Array of Events to push to the Server
NSRange theRange = NSMakeRange(0, upper);
events = [_eventQueue subarrayWithRange:theRange];
// Update Queue to remove events sent to server
[_eventQueue removeObjectsInRange:theRange];
// Send Array of Events to Server
[weakSelf postEvents:events];
});
}
// Can be called from any thread. Called implicitly from public
// use of +flush. Posts an async network request to upload metrics.
//
- (void) postEvents:(NSArray *)events {
__weak MGLMapboxEvents *weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Setup URL Request
NSString *url = [NSString stringWithFormat:@"%@/events/v1?access_token=%@", MGLMapboxEventsAPIBase, weakSelf.token];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setValue:[weakSelf getUserAgent] forHTTPHeaderField:@"User-Agent"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPMethod:@"POST"];
// Convert Array of Dictionaries to JSON
if ([NSJSONSerialization isValidJSONObject:events]) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:events options:NSJSONWritingPrettyPrinted error:nil];
[request setHTTPBody:jsonData];
// Send non blocking HTTP Request to server
[NSURLConnection sendAsynchronousRequest:request
queue:nil
completionHandler:nil];
}
});
}
// Can be called from any thread.
//
- (void) startTimer {
// Stop Timer if it already exists
if (_timer) {
[_timer invalidate];
_timer = nil;
void (^timerBlock)() = ^{
// Stop Timer if it already exists
if (_timer) {
[_timer invalidate];
_timer = nil;
}
// Start New Timer
_timer = [NSTimer scheduledTimerWithTimeInterval:_flushAfter
target:[self class]
selector:@selector(flush)
userInfo:nil
repeats:YES];
};
if ( ! [[NSThread currentThread] isMainThread]) {
dispatch_sync(dispatch_get_main_queue(), ^{
timerBlock();
});
} else {
timerBlock();
}
// Start New Timer
NSTimeInterval interval = (double)((NSInteger)_flushAfter);
_timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(flush) userInfo:nil repeats:YES];
}
// Can be called from any thread.
//
- (NSString *) getUserAgent {
if (_appName != nil && _appVersion != nil && ([_userAgent rangeOfString:_appName].location == NSNotFound)) {
_userAgent = [NSString stringWithFormat:@"%@/%@ %@", _appName, _appVersion, _userAgent];
if (self.appName != nil && self.appVersion != nil && ([self.userAgent rangeOfString:self.appName].location == NSNotFound)) {
self.userAgent = [NSString stringWithFormat:@"%@/%@ %@", self.appName, self.appVersion, self.userAgent];
}
return _userAgent;
return self.userAgent;
}
// Can be called from any thread.
//
- (NSString *) formatDate:(NSDate *)date {
return [rfc3339DateFormatter stringFromDate:date];
return [self.rfc3339DateFormatter stringFromDate:date];
}
// Can be called from any thread.
//
- (NSString *) getDeviceOrientation {
switch ([UIDevice currentDevice].orientation) {
case UIDeviceOrientationUnknown:
return @"Unknown";
break;
case UIDeviceOrientationPortrait:
return @"Portrait";
break;
case UIDeviceOrientationPortraitUpsideDown:
return @"PortraitUpsideDown";
break;
case UIDeviceOrientationLandscapeLeft:
return @"LandscapeLeft";
break;
case UIDeviceOrientationLandscapeRight:
return @"LandscapeRight";
break;
case UIDeviceOrientationFaceUp:
return @"FaceUp";
break;
case UIDeviceOrientationFaceDown:
return @"FaceDown";
break;
default:
return @"Default - Unknown";
break;
__block NSString *result;
NSString *(^deviceOrientationBlock)(void) = ^{
switch ([UIDevice currentDevice].orientation) {
case UIDeviceOrientationUnknown:
result = @"Unknown";
break;
case UIDeviceOrientationPortrait:
result = @"Portrait";
break;
case UIDeviceOrientationPortraitUpsideDown:
result = @"PortraitUpsideDown";
break;
case UIDeviceOrientationLandscapeLeft:
result = @"LandscapeLeft";
break;
case UIDeviceOrientationLandscapeRight:
result = @"LandscapeRight";
break;
case UIDeviceOrientationFaceUp:
result = @"FaceUp";
break;
case UIDeviceOrientationFaceDown:
result = @"FaceDown";
break;
default:
result = @"Default - Unknown";
break;
}
return result;
};
if ( ! [[NSThread currentThread] isMainThread]) {
dispatch_sync(dispatch_get_main_queue(), ^{
result = deviceOrientationBlock();
});
} else {
result = deviceOrientationBlock();
}
return result;
}
- (int) getContentSizeScale {
NSString *sc = [UIApplication sharedApplication].preferredContentSizeCategory;
if ([sc isEqualToString:UIContentSizeCategoryExtraSmall]) {
return -3;
} else if ([sc isEqualToString:UIContentSizeCategorySmall]) {
return -2;
} else if ([sc isEqualToString:UIContentSizeCategoryMedium]) {
return -1;
} else if ([sc isEqualToString:UIContentSizeCategoryLarge]) {
return 0;
} else if ([sc isEqualToString:UIContentSizeCategoryExtraLarge]) {
return 1;
} else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
return 2;
} else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
return 3;
} else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityMedium]) {
return -11;
} else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityLarge]) {
return 10;
} else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) {
return 11;
} else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) {
return 12;
} else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) {
return 13;
// Can be called from any thread.
//
- (NSInteger) getContentSizeScale {
__block NSInteger result = -9999;
NSInteger (^contentSizeScaleBlock)(void) = ^{
NSString *sc = [UIApplication sharedApplication].preferredContentSizeCategory;
if ([sc isEqualToString:UIContentSizeCategoryExtraSmall]) {
result = -3;
} else if ([sc isEqualToString:UIContentSizeCategorySmall]) {
result = -2;
} else if ([sc isEqualToString:UIContentSizeCategoryMedium]) {
result = -1;
} else if ([sc isEqualToString:UIContentSizeCategoryLarge]) {
result = 0;
} else if ([sc isEqualToString:UIContentSizeCategoryExtraLarge]) {
result = 1;
} else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
result = 2;
} else if ([sc isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
result = 3;
} else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityMedium]) {
result = -11;
} else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityLarge]) {
result = 10;
} else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) {
result = 11;
} else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) {
result = 12;
} else if ([sc isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) {
result = 13;
}
return result;
};
if ( ! [[NSThread currentThread] isMainThread]) {
dispatch_sync(dispatch_get_main_queue(), ^{
result = contentSizeScaleBlock();
});
} else {
result = contentSizeScaleBlock();
}
return -9999;
return result;
}
// Can be called from any thread.
//
- (NSString *)getSysInfoByName:(char *)typeSpecifier
{
size_t size;
@@ -315,6 +495,8 @@ NSNumber *scale;
return results;
}
// Can be called from any thread.
//
- (NSString *) getWifiNetworkName {
NSString *ssid = @"";
@@ -324,14 +506,80 @@ NSNumber *scale;
if (info) {
ssid = info[@"SSID"];
} else {
ssid = @"<<NONE>>";
ssid = @"NONE";
}
} else {
ssid = @"<<NONE>>";
ssid = @"NONE";
}
return ssid;
}
// Can be called from any thread.
//
- (NSString *) getCurrentCellularNetworkConnectionType {
CTTelephonyNetworkInfo *telephonyInfo = [CTTelephonyNetworkInfo new];
NSString *radioTech = telephonyInfo.currentRadioAccessTechnology;
if (radioTech == nil) {
return @"NONE";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyGPRS]) {
return @"GPRS";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyEdge]) {
return @"EDGE";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyWCDMA]) {
return @"WCDMA";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyHSDPA]) {
return @"HSDPA";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyHSUPA]) {
return @"HSUPA";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
return @"CDMA1x";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]) {
return @"CDMAEVDORev0";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]) {
return @"CDMAEVDORevA";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]) {
return @"CDMAEVDORevB";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyeHRPD]) {
return @"HRPD";
} else if ([radioTech isEqualToString:CTRadioAccessTechnologyLTE]) {
return @"LTE";
} else {
return @"Unknown";
}
}
@end
// Can be called from any thread.
//
+ (BOOL) checkPushEnabled {
BOOL (^pushCheckBlock)(void) = ^{
BOOL blockResult;
if ([[UIApplication sharedApplication] respondsToSelector:@selector(isRegisteredForRemoteNotifications)]) {
// iOS 8+
blockResult = [[UIApplication sharedApplication] isRegisteredForRemoteNotifications];
} else {
// iOS 7
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UIRemoteNotificationType types = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
blockResult = (types == UIRemoteNotificationTypeNone) ? NO : YES;
#pragma clang diagnostic pop
}
return blockResult;
};
__block BOOL result;
if ( ! [[NSThread currentThread] isMainThread]) {
dispatch_sync(dispatch_get_main_queue(), ^{
result = pushCheckBlock();
});
} else {
result = pushCheckBlock();
}
return result;
}
@end

View File

@@ -1,48 +1,18 @@
//
// MBLocationManager.m
// Hermes
//
// Dynamic Settings.bundle loading based on:
// http://stackoverflow.com/questions/510216/can-you-make-the-settings-in-settings-bundle-default-even-if-you-dont-open-the
//
// Created by Brad Leege on 3/8/15.
// Copyright (c) 2015 Mapbox. All rights reserved.
//
#import "MGLMetricsLocationManager.h"
#import "CoreLocation/CoreLocation.h"
#import "MGLMapboxEvents.h"
#import "MGLMetricsLocationManager.h"
@interface MGLMetricsLocationManager()
#import <CoreLocation/CoreLocation.h>
@property (atomic) CLLocationManager *locationManager;
@interface MGLMetricsLocationManager() <CLLocationManagerDelegate>
@property (nonatomic) CLLocationManager *locationManager;
@end
@implementation MGLMetricsLocationManager
static MGLMetricsLocationManager *sharedManager = nil;
- (id) init {
- (instancetype) init {
if (self = [super init]) {
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"bundle"];
if(!settingsBundle) {
NSLog(@"Could not find Settings.bundle");
} else {
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];
NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];
for(NSDictionary *prefSpecification in preferences) {
NSString *key = [prefSpecification objectForKey:@"Key"];
if(key && [[prefSpecification allKeys] containsObject:@"DefaultValue"]) {
[defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
}
}
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
}
_locationManager = [[CLLocationManager alloc] init];
_locationManager.distanceFilter = 2;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
@@ -52,46 +22,31 @@ static MGLMetricsLocationManager *sharedManager = nil;
return self;
}
+ (id)sharedManager {
+ (instancetype)sharedManager {
static dispatch_once_t onceToken;
static MGLMetricsLocationManager *sharedManager;
dispatch_once(&onceToken, ^{
sharedManager = [[self alloc] init];
});
return sharedManager;
}
- (BOOL) isAuthorizedStatusDetermined {
return ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined);
+ (void) startUpdatingLocation {
[[MGLMetricsLocationManager sharedManager].locationManager startUpdatingLocation];
}
- (void) requestAlwaysAuthorization {
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
} else {
// This is iOS 7 or below so Starting Location Updates will trigger authorization request
[self startUpdatingLocation];
}
}
- (void) startUpdatingLocation {
[self.locationManager startUpdatingLocation];
}
- (void) stopUpdatingLocation {
[self.locationManager stopUpdatingLocation];
+ (void) stopUpdatingLocation {
[[MGLMetricsLocationManager sharedManager].locationManager stopUpdatingLocation];
}
#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *loc = (CLLocation *)[locations objectAtIndex:0];
NSLog(@"didUpdateLocations() called with %lu location in array. First Location = %f, %f", (unsigned long)locations.count, loc.coordinate.latitude, loc.coordinate.longitude);
// Iterate through locations to pass all data
for (CLLocation *loc in locations) {
NSMutableDictionary *evt = [[NSMutableDictionary alloc] init];
[evt setValue:[[NSNumber alloc] initWithDouble:loc.coordinate.latitude] forKey:@"lat"];
[evt setValue:[[NSNumber alloc] initWithDouble:loc.coordinate.longitude] forKey:@"lng"];
[[MGLMapboxEvents sharedManager] pushEvent:@"location" withAttributes:evt];
[MGLMapboxEvents pushEvent:MGLEventTypeLocation withAttributes:@{
MGLEventKeyLatitude: @(loc.coordinate.latitude),
MGLEventKeyLongitude: @(loc.coordinate.longitude)
}];
}
}
@@ -106,24 +61,23 @@ static MGLMetricsLocationManager *sharedManager = nil;
break;
case kCLAuthorizationStatusDenied:
newStatus = @"User Explcitly Denied";
[[MGLMetricsLocationManager sharedManager] stopUpdatingLocation];
[MGLMetricsLocationManager stopUpdatingLocation];
break;
case kCLAuthorizationStatusAuthorized:
newStatus = @"User Has Authorized / Authorized Always";
[[MGLMetricsLocationManager sharedManager] startUpdatingLocation];
[MGLMetricsLocationManager startUpdatingLocation];
break;
// case kCLAuthorizationStatusAuthorizedAlways:
// newStatus = @"Not Determined";
// break;
case kCLAuthorizationStatusAuthorizedWhenInUse:
newStatus = @"User Has Authorized When In Use Only";
[[MGLMetricsLocationManager sharedManager] startUpdatingLocation];
[MGLMetricsLocationManager startUpdatingLocation];
break;
default:
newStatus = @"Unknown";
break;
}
NSLog(@"MGLMetricsLocationManager didChangeAuthorizationStatus() called. New Status = %@", newStatus);
}
@end

View File

@@ -1,190 +0,0 @@
#import "MGLStyleFunctionValue.h"
#import "MGLTypes.h"
@interface MGLStyleFunctionValue ()
@property (nonatomic) NSString *functionType;
@property (nonatomic) NSDictionary *stops;
@property (nonatomic) CGFloat zBase;
@property (nonatomic) CGFloat val;
@property (nonatomic) CGFloat slope;
@property (nonatomic) CGFloat min;
@property (nonatomic) CGFloat max;
@property (nonatomic) CGFloat minimumZoom;
@property (nonatomic) CGFloat maximumZoom;
- (NSDictionary *)rawStyle;
@end
@implementation MGLStyleFunctionValue
- (id)initWithFunctionType:(NSString *)functionType
stops:(NSDictionary *)stops
zBase:(CGFloat)zBase
val:(CGFloat)val
slope:(CGFloat)slope
min:(CGFloat)min
max:(CGFloat)max
minimumZoom:(CGFloat)minimumZoom
maximumZoom:(CGFloat)maximumZoom
{
self = [super init];
if (self)
{
_functionType = functionType;
_stops = stops;
_zBase = zBase;
_val = val;
_slope = slope;
_min = min;
_max = max;
_minimumZoom = minimumZoom;
_maximumZoom = maximumZoom;
}
return self;
}
- (id)rawStyle
{
if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionMinimumZoom])
{
return @[ @"min", @(self.minimumZoom) ];
}
else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionMaximumZoom])
{
return @[ @"max", @(self.maximumZoom) ];
}
else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionLinear])
{
return @[ @"linear", @(self.zBase), @(self.val), @(self.slope), @(self.min), @(self.max) ];
}
else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionExponential])
{
return @[ @"exponential", @(self.zBase), @(self.val), @(self.slope), @(self.min), @(self.max) ];
}
else if ([self.functionType isEqualToString:MGLStyleValueTypeFunctionStops])
{
NSMutableArray *returnArray = [NSMutableArray array];
for (NSNumber *z in [self.stops allKeys])
{
[returnArray addObject:@{ @"z" : z, @"val" : self.stops[z] }];
}
[returnArray insertObject:@"stops" atIndex:0];
return returnArray;
}
return nil;
}
+ (instancetype)stopsFunctionWithZoomLevelsAndValues:(NSNumber *)firstZoom, ...
{
NSMutableArray *numbersArray = [NSMutableArray array];
va_list args;
va_start(args, firstZoom);
for (NSNumber *arg = firstZoom; arg != nil; arg = va_arg(args, NSNumber *))
{
[numbersArray addObject:arg];
}
va_end(args);
NSAssert([numbersArray count] % 2 == 0, @"invalid number of arguments");
NSMutableDictionary *stops = [NSMutableDictionary dictionary];
for (NSUInteger i = 0; i < [numbersArray count]; i = i + 2)
{
stops[numbersArray[i]] = stops[numbersArray[i + 1]];
}
return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionStops
stops:stops
zBase:0
val:0
slope:0
min:0
max:0
minimumZoom:0
maximumZoom:0];
}
+ (instancetype)linearFunctionWithBaseZoomLevel:(CGFloat)zBase
initialValue:(CGFloat)val
slope:(CGFloat)slope
minimumValue:(CGFloat)min
maximumValue:(CGFloat)max
{
NSAssert(zBase >= 0 && zBase <= 18, @"invalid base zoom level");
NSAssert(min < max, @"minimum value must be less than maximum value");
return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionLinear
stops:nil
zBase:zBase
val:val
slope:slope
min:min
max:max
minimumZoom:0
maximumZoom:0];
}
+ (instancetype)exponentialFunctionWithBaseZoomLevel:(CGFloat)zBase
initialValue:(CGFloat)val
slope:(CGFloat)slope
minimumValue:(CGFloat)min
maximumValue:(CGFloat)max
{
NSAssert(zBase >= 0 && zBase <= 18, @"invalid base zoom level");
NSAssert(min < max, @"minimum value must be less than maximum value");
return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionExponential
stops:nil
zBase:zBase
val:val
slope:slope
min:min
max:max
minimumZoom:0
maximumZoom:0];
}
+ (instancetype)minimumZoomLevelFunction:(CGFloat)minimumZoom
{
NSAssert(minimumZoom >= 0 && minimumZoom <= 18, @"invalid minimum zoom value");
return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionMinimumZoom
stops:nil
zBase:0
val:0
slope:0
min:0
max:0
minimumZoom:minimumZoom
maximumZoom:0];
}
+ (instancetype)maximumZoomLevelFunction:(CGFloat)maximumZoom
{
NSAssert(maximumZoom >= 0 && maximumZoom <= 18, @"invalid maximum zoom value");
return [[self alloc] initWithFunctionType:MGLStyleValueTypeFunctionMaximumZoom
stops:nil
zBase:0
val:0
slope:0
min:0
max:0
minimumZoom:0
maximumZoom:maximumZoom];
}
@end

View File

@@ -1,24 +0,0 @@
#import "MGLTypes.h"
NSString *const MGLStyleKeyGeneric = @"MGLStyleKeyGeneric";
NSString *const MGLStyleKeyFill = @"MGLStyleKeyFill";
NSString *const MGLStyleKeyLine = @"MGLStyleKeyLine";
NSString *const MGLStyleKeyIcon = @"MGLStyleKeyIcon";
NSString *const MGLStyleKeyText = @"MGLStyleKeyText";
NSString *const MGLStyleKeyRaster = @"MGLStyleKeyRaster";
NSString *const MGLStyleKeyComposite = @"MGLStyleKeyComposite";
NSString *const MGLStyleKeyBackground = @"MGLStyleKeyBackground";
NSString *const MGLStyleValueTypeBoolean = @"MGLStyleValueTypeBoolean";
NSString *const MGLStyleValueTypeNumber = @"MGLStyleValueTypeNumber";
NSString *const MGLStyleValueTypeNumberPair = @"MGLStyleValueTypeNumberPair";
NSString *const MGLStyleValueTypeColor = @"MGLStyleValueTypeColor";
NSString *const MGLStyleValueTypeString = @"MGLStyleValueTypeString";
NSString *const MGLStyleValueFunctionAllowed = @"MGLStyleValueFunctionAllowed";
NSString *const MGLStyleValueTypeFunctionMinimumZoom = @"MGLStyleValueTypeFunctionMinimumZoom";
NSString *const MGLStyleValueTypeFunctionMaximumZoom = @"MGLStyleValueTypeFunctionMaximumZoom";
NSString *const MGLStyleValueTypeFunctionLinear = @"MGLStyleValueTypeFunctionLinear";
NSString *const MGLStyleValueTypeFunctionExponential = @"MGLStyleValueTypeFunctionExponential";
NSString *const MGLStyleValueTypeFunctionStops = @"MGLStyleValueTypeFunctionStops";

View File

@@ -0,0 +1,57 @@
#import "MGLUserLocation_Private.h"
@implementation MGLUserLocation
{
CLLocationCoordinate2D _coordinate;
}
@synthesize coordinate = _coordinate;
- (instancetype)init
{
if (self = [super init])
{
_coordinate = CLLocationCoordinate2DMake(MAXFLOAT, MAXFLOAT);
}
return self;
}
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key
{
return ! [key isEqualToString:@"location"] && ! [key isEqualToString:@"heading"];
}
+ (NSSet *)keyPathsForValuesAffectingCoordinate
{
return [NSSet setWithObject:@"location"];
}
- (void)setLocation:(CLLocation *)newLocation
{
if ([newLocation distanceFromLocation:_location] && newLocation.coordinate.latitude != 0 &&
newLocation.coordinate.longitude != 0)
{
[self willChangeValueForKey:@"location"];
_location = newLocation;
_coordinate = _location.coordinate;
[self didChangeValueForKey:@"location"];
}
}
- (void)setHeading:(CLHeading *)newHeading
{
if (newHeading.trueHeading != _heading.trueHeading)
{
[self willChangeValueForKey:@"heading"];
_heading = newHeading;
[self didChangeValueForKey:@"heading"];
}
}
- (NSString *)title
{
if ( ! _title) return @"Current Location";
}
@end

View File

@@ -0,0 +1,18 @@
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "MGLUserLocation.h"
@class MGLMapView;
/** The MGLUserLocationAnnotationView class defines a specific type of annotation that identifies the user’s current location. You do not create instances of this class directly. Instead, you retrieve an existing MGLUserLocationAnnotationView object from the userLocation property of the map view displayed in your application. */
@interface MGLUserLocationAnnotationView : UIView
@property (nonatomic, weak) MGLMapView *mapView;
@property (nonatomic) MGLUserLocation *annotation;
@property (nonatomic, readonly) CALayer *haloLayer;
- (instancetype)initInMapView:(MGLMapView *)mapView;
- (void)setupLayers;
@end

View File

@@ -0,0 +1,197 @@
#import "MGLUserLocationAnnotationView.h"
#import "MGLUserLocation_Private.h"
#import "MGLAnnotation.h"
#import "MGLMapView.h"
const CGFloat MGLTrackingDotRingWidth = 24.0;
@interface MGLUserLocationAnnotationView ()
@property (nonatomic, readwrite) CALayer *haloLayer;
@end
#pragma mark -
@implementation MGLUserLocationAnnotationView
{
CALayer *_accuracyRingLayer;
CALayer *_dotBorderLayer;
CALayer *_dotLayer;
}
- (instancetype)initInMapView:(MGLMapView *)mapView
{
if (self = [super init])
{
self.annotation = [[MGLUserLocation alloc] init];
_mapView = mapView;
[self setupLayers];
}
return self;
}
- (void)setTintColor:(UIColor *)tintColor
{
UIImage *trackingDotHaloImage = [self trackingDotHaloImage];
_haloLayer.bounds = CGRectMake(0, 0, trackingDotHaloImage.size.width, trackingDotHaloImage.size.height);
_haloLayer.contents = (__bridge id)[trackingDotHaloImage CGImage];
UIImage *dotImage = [self dotImage];
_dotLayer.bounds = CGRectMake(0, 0, dotImage.size.width, dotImage.size.height);
_dotLayer.contents = (__bridge id)[dotImage CGImage];
}
- (void)setupLayers
{
if (CLLocationCoordinate2DIsValid(self.annotation.coordinate))
{
if ( ! _accuracyRingLayer && self.annotation.location.horizontalAccuracy)
{
UIImage *accuracyRingImage = [self accuracyRingImage];
_accuracyRingLayer = [CALayer layer];
_haloLayer.bounds = CGRectMake(0, 0, accuracyRingImage.size.width, accuracyRingImage.size.height);
_haloLayer.contents = (__bridge id)[accuracyRingImage CGImage];
_haloLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0);
[self.layer addSublayer:_accuracyRingLayer];
}
if ( ! _haloLayer)
{
UIImage *haloImage = [self trackingDotHaloImage];
_haloLayer = [CALayer layer];
_haloLayer.bounds = CGRectMake(0, 0, haloImage.size.width, haloImage.size.height);
_haloLayer.contents = (__bridge id)[haloImage CGImage];
_haloLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0);
[CATransaction begin];
[CATransaction setAnimationDuration:3.5];
[CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]];
// scale out radially
//
CABasicAnimation *boundsAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
boundsAnimation.repeatCount = MAXFLOAT;
boundsAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)];
boundsAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(2.0, 2.0, 1.0)];
boundsAnimation.removedOnCompletion = NO;
[_haloLayer addAnimation:boundsAnimation forKey:@"animateScale"];
// go transparent as scaled out
//
CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
opacityAnimation.repeatCount = MAXFLOAT;
opacityAnimation.fromValue = [NSNumber numberWithFloat:1.0];
opacityAnimation.toValue = [NSNumber numberWithFloat:-1.0];
opacityAnimation.removedOnCompletion = NO;
[_haloLayer addAnimation:opacityAnimation forKey:@"animateOpacity"];
[CATransaction commit];
[self.layer addSublayer:_haloLayer];
}
// white dot background with shadow
//
if ( ! _dotBorderLayer)
{
CGRect rect = CGRectMake(0, 0, MGLTrackingDotRingWidth * 1.25, MGLTrackingDotRingWidth * 1.25);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetShadow(context, CGSizeMake(0, 0), MGLTrackingDotRingWidth / 4.0);
CGContextSetFillColorWithColor(context, [[UIColor whiteColor] CGColor]);
CGContextFillEllipseInRect(context, CGRectMake((rect.size.width - MGLTrackingDotRingWidth) / 2.0, (rect.size.height - MGLTrackingDotRingWidth) / 2.0, MGLTrackingDotRingWidth, MGLTrackingDotRingWidth));
UIImage *whiteBackground = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
_dotBorderLayer = [CALayer layer];
_dotBorderLayer.bounds = CGRectMake(0, 0, whiteBackground.size.width, whiteBackground.size.height);
_dotBorderLayer.contents = (__bridge id)[whiteBackground CGImage];
_dotBorderLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0);
[self.layer addSublayer:_dotBorderLayer];
}
// pulsing, tinted dot sublayer
//
if ( ! _dotLayer)
{
UIImage *dotImage = [self dotImage];
_dotLayer = [CALayer layer];
_dotLayer.bounds = CGRectMake(0, 0, dotImage.size.width, dotImage.size.height);
_dotLayer.contents = (__bridge id)[dotImage CGImage];
_dotLayer.position = CGPointMake(super.layer.bounds.size.width / 2.0, super.layer.bounds.size.height / 2.0);
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
animation.repeatCount = MAXFLOAT;
animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)];
animation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.8, 0.8, 1.0)];
animation.removedOnCompletion = NO;
animation.autoreverses = YES;
animation.duration = 1.5;
animation.beginTime = CACurrentMediaTime() + 1.0;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[_dotLayer addAnimation:animation forKey:@"animateTransform"];
[self.layer addSublayer:_dotLayer];
}
}
}
- (UIImage *)accuracyRingImage
{
CGFloat latRadians = self.annotation.coordinate.latitude * M_PI / 180.0f;
CGFloat pixelRadius = self.annotation.location.horizontalAccuracy / cos(latRadians) / [self.mapView metersPerPixelAtLatitude:self.annotation.coordinate.latitude];
UIGraphicsBeginImageContextWithOptions(CGSizeMake(pixelRadius * 2, pixelRadius * 2), NO, [[UIScreen mainScreen] scale]);
CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor colorWithRed:0.378 green:0.552 blue:0.827 alpha:0.7] CGColor]);
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[UIColor colorWithRed:0.378 green:0.552 blue:0.827 alpha:0.15] CGColor]);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 2.0);
CGContextStrokeEllipseInRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, pixelRadius * 2, pixelRadius * 2));
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return finalImage;
}
- (UIImage *)trackingDotHaloImage
{
UIGraphicsBeginImageContextWithOptions(CGSizeMake(100, 100), NO, [[UIScreen mainScreen] scale]);
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [[_mapView.tintColor colorWithAlphaComponent:0.75] CGColor]);
CGContextFillEllipseInRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, 100, 100));
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return finalImage;
}
- (UIImage *)dotImage
{
CGFloat tintedWidth = MGLTrackingDotRingWidth * 0.7;
CGRect rect = CGRectMake(0, 0, tintedWidth, tintedWidth);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [_mapView.tintColor CGColor]);
CGContextFillEllipseInRect(context, CGRectMake((rect.size.width - tintedWidth) / 2.0, (rect.size.height - tintedWidth) / 2.0, tintedWidth, tintedWidth));
UIImage *tintedForeground = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tintedForeground;
}
@end

View File

@@ -0,0 +1,9 @@
#import "MGLUserLocation.h"
@interface MGLUserLocation (Private)
@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;
@property (nonatomic, readwrite) CLLocation *location;
@property (nonatomic, readwrite) CLHeading *heading;
@end

View File

@@ -1,10 +0,0 @@
#import "NSArray+MGLAdditions.h"
@implementation NSArray (MGLAdditions)
- (NSMutableArray *)deepMutableCopy
{
return (NSMutableArray *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFArrayRef)self, kCFPropertyListMutableContainersAndLeaves));
}
@end

View File

@@ -1,10 +0,0 @@
#import "NSDictionary+MGLAdditions.h"
@implementation NSDictionary (MGLAdditions)
- (NSMutableDictionary *)deepMutableCopy
{
return (NSMutableDictionary *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)self, kCFPropertyListMutableContainersAndLeaves));
}
@end

View File

@@ -1,167 +0,0 @@
#import "UIColor+MGLAdditions.h"
/* Portions based on Erica Sadun's uicolor-utilities
https://github.com/erica/uicolor-utilities */
@interface UIColor (MGLAdditionsPrivate)
+ (UIColor *)colorWithRGBHex:(UInt32)hex;
- (CGColorSpaceModel)colorSpaceModel;
- (BOOL)canProvideRGBComponents;
- (BOOL)red:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha;
- (UInt32)rgbHex;
@end
@implementation UIColor (MGLAdditions)
+ (UIColor *)colorWithRGBAString:(NSString *)rgbaString
{
UIColor *color;
NSString *numberString = [rgbaString stringByReplacingOccurrencesOfString:@"rgba("
withString:@""];
numberString = [numberString stringByReplacingOccurrencesOfString:@"rgb("
withString:@""];
numberString = [numberString stringByReplacingOccurrencesOfString:@")"
withString:@""];
NSArray *numbers = [numberString componentsSeparatedByString:@","];
if ([rgbaString hasPrefix:@"rgb("] && [numbers count] == 3)
{
color = [UIColor colorWithRed:[numbers[0] floatValue] / 255
green:[numbers[1] floatValue] / 255
blue:[numbers[2] floatValue] / 255
alpha:1.0];
}
else if ([rgbaString hasPrefix:@"rgba("] && [numbers count] == 4)
{
color = [UIColor colorWithRed:[numbers[0] floatValue] / 255
green:[numbers[1] floatValue] / 255
blue:[numbers[2] floatValue] / 255
alpha:[numbers[3] floatValue]];
}
return color;
}
- (NSString *)rgbaStringFromColor
{
CGFloat r,g,b,a;
[self getRed:&r green:&g blue:&b alpha:&a];
r *= 255;
g *= 255;
b *= 255;
a *= 255;
return [NSString stringWithFormat:@"rgba(%lu,%lu,%lu,%lu)", (unsigned long)r, (unsigned long)g, (unsigned long)b, (unsigned long)a];
}
+ (UIColor *)colorWithRGBHex:(UInt32)hex
{
int r = (hex >> 16) & 0xFF;
int g = (hex >> 8) & 0xFF;
int b = (hex) & 0xFF;
return [UIColor colorWithRed:r / 255.0f
green:g / 255.0f
blue:b / 255.0f
alpha:1.0f];
}
- (CGColorSpaceModel)colorSpaceModel
{
return CGColorSpaceGetModel(CGColorGetColorSpace(self.CGColor));
}
- (BOOL)canProvideRGBComponents
{
switch (self.colorSpaceModel)
{
case kCGColorSpaceModelRGB:
case kCGColorSpaceModelMonochrome:
{
return YES;
}
default:
{
return NO;
}
}
}
- (BOOL)red:(CGFloat *)red green:(CGFloat *)green blue:(CGFloat *)blue alpha:(CGFloat *)alpha
{
const CGFloat *components = CGColorGetComponents(self.CGColor);
CGFloat r,g,b,a;
switch (self.colorSpaceModel)
{
case kCGColorSpaceModelMonochrome:
{
r = g = b = components[0];
a = components[1];
break;
}
case kCGColorSpaceModelRGB:
{
r = components[0];
g = components[1];
b = components[2];
a = components[3];
break;
}
default:
{
return NO;
}
}
if (red) *red = r;
if (green) *green = g;
if (blue) *blue = b;
if (alpha) *alpha = a;
return YES;
}
- (UInt32)rgbHex
{
NSAssert(self.canProvideRGBComponents, @"Must be a RGB color to use rgbHex");
CGFloat r, g, b, a;
if ( ! [self red:&r green:&g blue:&b alpha:&a])
return 0;
r = fminf(fmaxf(r, 0.0f), 1.0f);
g = fminf(fmaxf(g, 0.0f), 1.0f);
b = fminf(fmaxf(b, 0.0f), 1.0f);
return (((int)roundf(r * 255)) << 16) | (((int)roundf(g * 255)) << 8) | (((int)roundf(b * 255)));
}
- (NSString *)hexStringFromColor
{
return [NSString stringWithFormat:@"%0.6X", (unsigned int)(self.rgbHex)];
}
+ (UIColor *)colorWithHexString:(NSString *)hexString
{
NSScanner *scanner = [NSScanner scannerWithString:[hexString stringByReplacingOccurrencesOfString:@"#" withString:@""]];
unsigned hexNum;
if ( ! [scanner scanHexInt:&hexNum])
return nil;
return [UIColor colorWithRGBHex:hexNum];
}
@end

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.8 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 6.9 KiB

View File

@@ -4,6 +4,8 @@
#include <mbgl/platform/log.hpp>
#include <mbgl/platform/platform.hpp>
#include <boost/functional/hash.hpp>
#include <sstream>
#include <cmath>
@@ -26,21 +28,22 @@ LineAtlas::~LineAtlas() {
}
LinePatternPos LineAtlas::getDashPosition(const std::vector<float> &dasharray, bool round) {
size_t key = round ? std::numeric_limits<size_t>::min() : std::numeric_limits<size_t>::max();
for (const float part : dasharray) {
boost::hash_combine<float>(key, part);
}
// Note: We're not handling hash collisions here.
std::lock_guard<std::recursive_mutex> lock(mtx);
std::ostringstream sskey;
for (const float &part : dasharray) {
sskey << part << "-";
const auto it = positions.find(key);
if (it == positions.end()) {
auto inserted = positions.emplace(key, addDash(dasharray, round));
assert(inserted.second);
return inserted.first->second;
} else {
return it->second;
}
sskey << round;
std::string key = sskey.str();
if (positions.find(key) == positions.end()) {
positions[key] = addDash(dasharray, round);
}
return positions[key];
}
LinePatternPos LineAtlas::addDash(const std::vector<float> &dasharray, bool round) {
@@ -55,7 +58,7 @@ LinePatternPos LineAtlas::addDash(const std::vector<float> &dasharray, bool roun
}
float length = 0;
for (const float &part : dasharray) {
for (const float part : dasharray) {
length += part;
}

View File

@@ -33,7 +33,7 @@ private:
std::atomic<bool> dirty;
uint32_t texture = 0;
int nextRow = 0;
std::map<std::string, LinePatternPos> positions;
std::map<size_t, LinePatternPos> positions;
};
};

View File

@@ -73,7 +73,7 @@ Rect<SpriteAtlas::dimension> SpriteAtlas::allocateImage(const size_t pixel_width
// This is so we can scale down the texture coordinates and pack them
// into 2 bytes rather than 4 bytes.
const uint16_t pack_width = (pixel_width + 1) + (4 - (pixel_width + 1) % 4);
const uint16_t pack_height = (pixel_height + 1) + (4 - (pixel_width + 1) % 4);
const uint16_t pack_height = (pixel_height + 1) + (4 - (pixel_height + 1) % 4);
// We have to allocate a new area in the bin, and store an empty image in it.
// Add a 1px border around every image.
@@ -165,37 +165,37 @@ void SpriteAtlas::copy(const Rect<dimension>& dst, const SpritePosition& src, co
static_cast<uint32_t>(dst.originalW * pixelRatio),
static_cast<uint32_t>(dst.originalH * pixelRatio) };
util::bilinearScale(srcData, srcSize, srcPos, dstData, dstSize, dstPos);
util::bilinearScale(srcData, srcSize, srcPos, dstData, dstSize, dstPos, wrap);
// Add borders around the copied image if required.
if (wrap) {
// We're copying from the same image so we don't have to scale again.
const uint32_t border = 1;
const uint32_t borderX = dstPos.x != 0 ? border : 0;
const uint32_t borderY = dstPos.y != 0 ? border : 0;
// Left border
if (dstPos.x >= border) {
util::nearestNeighborScale(
dstData, dstSize, { dstPos.x + dstPos.w - border - 1, dstPos.y, border, dstPos.h },
dstData, dstSize, { dstPos.x - border, dstPos.y, border, dstPos.h });
}
util::nearestNeighborScale(
dstData, dstSize, { dstPos.x + dstPos.w - borderX, dstPos.y, borderX, dstPos.h },
dstData, dstSize, { dstPos.x - borderX, dstPos.y, borderX, dstPos.h });
// Right border
util::nearestNeighborScale(dstData, dstSize, { dstPos.x, dstPos.y, border, dstPos.h },
dstData, dstSize,
{ dstPos.x + dstPos.w, dstPos.y, border, dstPos.h });
// Top border
if (dstPos.y >= border) {
util::nearestNeighborScale(
dstData, dstSize, { dstPos.x - border, dstPos.y + dstPos.h - border - 1,
dstPos.w + 2 * border, border },
dstData, dstSize,
{ dstPos.x - border, dstPos.y - border, dstPos.w + 2 * border, border });
}
util::nearestNeighborScale(
dstData, dstSize, { dstPos.x - borderX, dstPos.y + dstPos.h - borderY,
dstPos.w + border + borderX, borderY },
dstData, dstSize,
{ dstPos.x - borderX, dstPos.y - borderY, dstPos.w + 2 * borderX, borderY });
// Bottom border
util::nearestNeighborScale(
dstData, dstSize, { dstPos.x - border, dstPos.y, dstPos.w + 2 * border, border },
dstData, dstSize, { dstPos.x - borderX, dstPos.y, dstPos.w + 2 * borderX, border },
dstData, dstSize,
{ dstPos.x - border, dstPos.y + dstPos.h, dstPos.w + 2 * border, border });
{ dstPos.x - borderX, dstPos.y + dstPos.h, dstPos.w + border + borderX, border });
}
dirty = true;

View File

@@ -4,7 +4,7 @@
namespace mbgl {
StaticVertexBuffer::StaticVertexBuffer(std::initializer_list<std::pair<int16_t, int16_t>> init) {
for (const std::pair<int16_t, int16_t> &vertex : init) {
for (const auto& vertex : init) {
vertex_type *vertices = static_cast<vertex_type *>(addElement());
vertices[0] = vertex.first;
vertices[1] = vertex.second;

View File

@@ -18,7 +18,6 @@
#include <mbgl/text/glyph_store.hpp>
#include <mbgl/geometry/glyph_atlas.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/util/texture_pool.hpp>
#include <mbgl/geometry/sprite_atlas.hpp>
@@ -129,14 +128,22 @@ void Map::start(bool startPaused) {
// Remove all of these to make sure they are destructed in the correct thread.
style.reset();
// Since we don't have a stylesheet anymore, this will disable all Sources and cancel
// their associated requests.
updateSources();
assert(activeSources.empty());
// It's now safe to destroy/join the workers since there won't be any more callbacks that
// could dispatch to the worker pool.
workers.reset();
activeSources.clear();
terminating = true;
// Closes all open handles on the loop. This means that the loop will automatically terminate.
asyncRender.reset();
asyncUpdate.reset();
asyncInvoke.reset();
asyncTerminate.reset();
});
@@ -144,6 +151,10 @@ void Map::start(bool startPaused) {
update();
});
asyncInvoke = util::make_unique<uv::async>(env->loop, [this] {
processTasks();
});
asyncRender = util::make_unique<uv::async>(env->loop, [this] {
// Must be called in Map thread.
assert(Environment::currentlyOn(ThreadType::Map));
@@ -315,6 +326,42 @@ void Map::triggerRender() {
asyncRender->send();
}
// Runs the function in the map thread.
void Map::invokeTask(std::function<void()>&& fn) {
{
std::lock_guard<std::mutex> lock(mutexTask);
tasks.emplace(::std::forward<std::function<void()>>(fn));
}
// TODO: Once we have aligned static and continuous rendering, this should always dispatch
// to the async queue.
if (asyncInvoke) {
asyncInvoke->send();
} else {
processTasks();
}
}
template <typename Fn> auto Map::invokeSyncTask(const Fn& fn) -> decltype(fn()) {
std::promise<decltype(fn())> promise;
invokeTask([&fn, &promise] { promise.set_value(fn()); });
return promise.get_future().get();
}
// Processes the functions that should be run in the map thread.
void Map::processTasks() {
std::queue<std::function<void()>> queue;
{
std::lock_guard<std::mutex> lock(mutexTask);
queue.swap(tasks);
}
while (!queue.empty()) {
queue.front()();
queue.pop();
}
}
void Map::checkForPause() {
std::unique_lock<std::mutex> lockRun (mutexRun);
while (pausing) {
@@ -352,13 +399,15 @@ void Map::setup() {
void Map::setStyleURL(const std::string &url) {
assert(Environment::currentlyOn(ThreadType::Main));
const size_t pos = url.rfind('/');
const std::string styleURL = mbgl::util::mapbox::normalizeStyleURL(url, getAccessToken());
const size_t pos = styleURL.rfind('/');
std::string base = "";
if (pos != std::string::npos) {
base = url.substr(0, pos + 1);
base = styleURL.substr(0, pos + 1);
}
data->setStyleInfo({ url, base, "" });
data->setStyleInfo({ styleURL, base, "" });
triggerUpdate(Update::StyleInfo);
}
@@ -542,21 +591,31 @@ std::string Map::getAccessToken() const {
void Map::setDefaultPointAnnotationSymbol(const std::string& symbol) {
assert(Environment::currentlyOn(ThreadType::Main));
annotationManager->setDefaultPointAnnotationSymbol(symbol);
invokeTask([=] {
annotationManager->setDefaultPointAnnotationSymbol(symbol);
});
}
double Map::getTopOffsetPixelsForAnnotationSymbol(const std::string& symbol) {
assert(Environment::currentlyOn(ThreadType::Main));
return invokeSyncTask([&] {
assert(sprite);
const SpritePosition pos = sprite->getSpritePosition(symbol);
return -pos.height / pos.pixelRatio / 2;
});
}
uint32_t Map::addPointAnnotation(const LatLng& point, const std::string& symbol) {
assert(Environment::currentlyOn(ThreadType::Main));
std::vector<LatLng> points({ point });
std::vector<std::string> symbols({ symbol });
return addPointAnnotations(points, symbols)[0];
return addPointAnnotations({ point }, { symbol }).front();
}
std::vector<uint32_t> Map::addPointAnnotations(const std::vector<LatLng>& points, const std::vector<std::string>& symbols) {
assert(Environment::currentlyOn(ThreadType::Main));
auto result = annotationManager->addPointAnnotations(points, symbols, *this);
updateAnnotationTiles(result.first);
return result.second;
return invokeSyncTask([&] {
auto result = annotationManager->addPointAnnotations(points, symbols, *this);
updateAnnotationTiles(result.first);
return result.second;
});
}
void Map::removeAnnotation(uint32_t annotation) {
@@ -566,22 +625,28 @@ void Map::removeAnnotation(uint32_t annotation) {
void Map::removeAnnotations(const std::vector<uint32_t>& annotations) {
assert(Environment::currentlyOn(ThreadType::Main));
auto result = annotationManager->removeAnnotations(annotations, *this);
updateAnnotationTiles(result);
invokeTask([=] {
auto result = annotationManager->removeAnnotations(annotations, *this);
updateAnnotationTiles(result);
});
}
std::vector<uint32_t> Map::getAnnotationsInBounds(const LatLngBounds& bounds) const {
std::vector<uint32_t> Map::getAnnotationsInBounds(const LatLngBounds& bounds) {
assert(Environment::currentlyOn(ThreadType::Main));
return annotationManager->getAnnotationsInBounds(bounds, *this);
return invokeSyncTask([&] {
return annotationManager->getAnnotationsInBounds(bounds, *this);
});
}
LatLngBounds Map::getBoundsForAnnotations(const std::vector<uint32_t>& annotations) const {
LatLngBounds Map::getBoundsForAnnotations(const std::vector<uint32_t>& annotations) {
assert(Environment::currentlyOn(ThreadType::Main));
return annotationManager->getBoundsForAnnotations(annotations);
return invokeSyncTask([&] {
return annotationManager->getBoundsForAnnotations(annotations);
});
}
void Map::updateAnnotationTiles(const std::vector<Tile::ID>& ids) {
assert(Environment::currentlyOn(ThreadType::Main));
assert(Environment::currentlyOn(ThreadType::Map));
for (const auto &source : activeSources) {
if (source->info.type == SourceType::Annotations) {
source->source->invalidateTiles(*this, ids);
@@ -657,7 +722,11 @@ void Map::updateSources() {
// Then, reenable all of those that we actually use when drawing this layer.
if (style) {
updateSources(style->layers);
for (const auto& layer : style->layers) {
if (layer->bucket && layer->bucket->style_source) {
(*activeSources.emplace(layer->bucket->style_source).first)->enabled = true;
}
}
}
// Then, construct or destroy the actual source object, depending on enabled state.
@@ -678,23 +747,9 @@ void Map::updateSources() {
});
}
void Map::updateSources(const util::ptr<StyleLayerGroup> &group) {
assert(Environment::currentlyOn(ThreadType::Map));
if (!group) {
return;
}
for (const util::ptr<StyleLayer> &layer : group->layers) {
if (!layer) continue;
if (layer->bucket && layer->bucket->style_source) {
(*activeSources.emplace(layer->bucket->style_source).first)->enabled = true;
}
}
}
void Map::updateTiles() {
assert(Environment::currentlyOn(ThreadType::Map));
for (const auto &source : activeSources) {
for (const auto& source : activeSources) {
source->source->update(*this, getWorker(), style, *glyphAtlas, *glyphStore,
*spriteAtlas, getSprite(), *texturePool, [this]() {
assert(Environment::currentlyOn(ThreadType::Map));
@@ -741,7 +796,7 @@ void Map::loadStyleJSON(const std::string& json, const std::string& base) {
style = std::make_shared<Style>();
style->base = base;
style->loadJSON((const uint8_t *)json.c_str());
style->cascadeClasses(data->getClasses());
style->cascade(data->getClasses());
style->setDefaultTransitionDuration(data->getDefaultTransitionDuration());
const std::string glyphURL = util::mapbox::normalizeGlyphsURL(style->glyph_url, getAccessToken());
@@ -754,7 +809,7 @@ void Map::prepare() {
assert(Environment::currentlyOn(ThreadType::Map));
const auto u = updated.exchange(static_cast<UpdateType>(Update::Nothing));
if (u & static_cast<UpdateType>(Update::StyleInfo)) {
if ((u & static_cast<UpdateType>(Update::StyleInfo)) || !style) {
reloadStyle();
}
if (u & static_cast<UpdateType>(Update::Debug)) {
@@ -768,7 +823,7 @@ void Map::prepare() {
}
if (u & static_cast<UpdateType>(Update::Classes)) {
if (style) {
style->cascadeClasses(data->getClasses());
style->cascade(data->getClasses());
}
}
@@ -784,7 +839,7 @@ void Map::prepare() {
if (style) {
updateSources();
style->updateProperties(state.getNormalizedZoom(), animationTime);
style->recalculate(state.getNormalizedZoom(), animationTime);
// Allow the sprite atlas to potentially pull new sprite images if needed.
spriteAtlas->resize(state.getPixelRatio());
@@ -804,6 +859,7 @@ void Map::render() {
// Cleanup OpenGL objects that we abandoned since the last render call.
env->performCleanup();
assert(style);
assert(painter);
painter->render(*style, activeSources,
state, data->getAnimationTime());

View File

@@ -78,7 +78,7 @@ void Source::updateClipIDs(const std::map<Tile::ID, ClipID> &mapping) {
}
void Source::updateMatrices(const mat4 &projMatrix, const TransformState &transform) {
for (std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair : tiles) {
for (const auto& pair : tiles) {
Tile &tile = *pair.second;
transform.matrixFor(tile.matrix, tile.id);
matrix::multiply(tile.matrix, projMatrix, tile.matrix);
@@ -90,7 +90,7 @@ size_t Source::getTileCount() const {
}
void Source::drawClippingMasks(Painter &painter) {
for (std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair : tiles) {
for (const auto& pair : tiles) {
Tile &tile = *pair.second;
gl::group group(std::string { "mask: " } + std::string(tile.id));
painter.drawClippingMask(tile.matrix, tile.clip);
@@ -99,7 +99,7 @@ void Source::drawClippingMasks(Painter &painter) {
void Source::render(Painter &painter, const StyleLayer &layer_desc) {
gl::group group(std::string { "layer: " } + layer_desc.id);
for (const std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair : tiles) {
for (const auto& pair : tiles) {
Tile &tile = *pair.second;
if (tile.data && tile.data->state == TileData::State::parsed) {
painter.renderTileLayer(tile, layer_desc, tile.matrix);
@@ -115,7 +115,7 @@ void Source::render(Painter &painter, const StyleLayer &layer_desc, const Tile::
}
void Source::finishRender(Painter &painter) {
for (std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair : tiles) {
for (const auto& pair : tiles) {
Tile &tile = *pair.second;
painter.renderTileDebug(tile);
}
@@ -252,7 +252,7 @@ bool Source::findLoadedChildren(const Tile::ID& id, int32_t maxCoveringZoom, std
bool complete = true;
int32_t z = id.z;
auto ids = id.children(z + 1);
for (const Tile::ID& child_id : ids) {
for (const auto& child_id : ids) {
const TileData::State state = hasTile(child_id);
if (state == TileData::State::parsed) {
retain.emplace_front(child_id);
@@ -301,8 +301,6 @@ void Source::update(Map &map,
return;
}
bool changed = false;
int32_t zoom = std::floor(getZoom(map.getState()));
std::forward_list<Tile::ID> required = coveringTiles(map.getState());
@@ -316,7 +314,7 @@ void Source::update(Map &map,
std::forward_list<Tile::ID> retain(required);
// Add existing child/parent tiles if the actual tile is not yet loaded
for (const Tile::ID& id : required) {
for (const auto& id : required) {
const TileData::State state = addTile(map, worker, style, glyphAtlas, glyphStore,
spriteAtlas, sprite, texturePool, id, callback);
@@ -334,21 +332,15 @@ void Source::update(Map &map,
findLoadedParent(id, minCoveringZoom, retain);
}
}
if (state == TileData::State::initial) {
changed = true;
}
}
// Remove tiles that we definitely don't need, i.e. tiles that are not on
// the required list.
std::set<Tile::ID> retain_data;
util::erase_if(tiles, [&retain, &retain_data, &changed](std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair) {
util::erase_if(tiles, [&retain, &retain_data](std::pair<const Tile::ID, std::unique_ptr<Tile>> &pair) {
Tile &tile = *pair.second;
bool obsolete = std::find(retain.begin(), retain.end(), tile.id) == retain.end();
if (obsolete) {
changed = true;
} else {
if (!obsolete) {
retain_data.insert(tile.data->id);
}
return obsolete;

View File

@@ -9,8 +9,6 @@
#include <mbgl/util/ptr.hpp>
#include <atomic>
#include <exception>
#include <iosfwd>
#include <string>
#include <functional>
@@ -22,7 +20,6 @@ typedef struct uv_loop_s uv_loop_t;
namespace mbgl {
class Map;
class Environment;
class Painter;
class SourceInfo;
@@ -32,12 +29,6 @@ class Request;
class TileData : public std::enable_shared_from_this<TileData>,
private util::noncopyable {
public:
struct exception : std::exception {};
struct geometry_too_long_exception : exception {};
public:
typedef util::ptr<TileData> Ptr;
enum class State {
invalid,
initial,
@@ -47,7 +38,6 @@ public:
obsolete
};
public:
TileData(Tile::ID const &id, const SourceInfo &);
~TileData();
@@ -65,16 +55,14 @@ public:
virtual void render(Painter &painter, const StyleLayer &layer_desc, const mat4 &matrix) = 0;
virtual bool hasData(StyleLayer const &layer_desc) const = 0;
public:
const Tile::ID id;
const std::string name;
std::atomic<State> state;
public:
protected:
const SourceInfo& source;
Environment& env;
protected:
Request *req = nullptr;
std::string data;

View File

@@ -3,8 +3,7 @@
#include <mbgl/platform/log.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/style/style_layout.hpp>
#include <mbgl/style/style_source.hpp>
#include <mbgl/renderer/fill_bucket.hpp>
#include <mbgl/renderer/line_bucket.hpp>
#include <mbgl/renderer/symbol_bucket.hpp>
@@ -49,18 +48,10 @@ TileParser::TileParser(const GeometryTile& geometryTile_,
assert(collision);
}
void TileParser::parse() {
parseStyleLayers(style->layers);
}
bool TileParser::obsolete() const { return tile.state == TileData::State::obsolete; }
void TileParser::parseStyleLayers(util::ptr<const StyleLayerGroup> group) {
if (!group) {
return;
}
for (const util::ptr<const StyleLayer> &layer_desc : group->layers) {
void TileParser::parse() {
for (const auto& layer_desc : style->layers) {
// Cancel early when parsing.
if (obsolete()) {
return;
@@ -122,65 +113,6 @@ void applyLayoutProperty(PropertyKey key, const ClassProperties &classProperties
}
}
std::unique_ptr<StyleLayoutFill> parseStyleLayoutFill(const StyleBucket &/*bucket*/, const float /*z*/) {
// no-op; Fill buckets don't currently have any applicable layout properties
auto fillPtr = util::make_unique<StyleLayoutFill>();
return fillPtr;
}
std::unique_ptr<StyleLayoutLine> parseStyleLayoutLine(const StyleBucket &bucket_desc, const float z) {
auto linePtr = util::make_unique<StyleLayoutLine>();
auto &line = *linePtr;
applyLayoutProperty(PropertyKey::LineCap, bucket_desc.layout, line.cap, z);
applyLayoutProperty(PropertyKey::LineJoin, bucket_desc.layout, line.join, z);
applyLayoutProperty(PropertyKey::LineMiterLimit, bucket_desc.layout, line.miter_limit, z);
applyLayoutProperty(PropertyKey::LineRoundLimit, bucket_desc.layout, line.round_limit, z);
return linePtr;
}
std::unique_ptr<StyleLayoutSymbol> parseStyleLayoutSymbol(const StyleBucket &bucket_desc, const float z) {
auto symbolPtr = util::make_unique<StyleLayoutSymbol>();
auto &symbol = *symbolPtr;
applyLayoutProperty(PropertyKey::SymbolPlacement, bucket_desc.layout, symbol.placement, z);
if (symbol.placement == PlacementType::Line) {
symbol.icon.rotation_alignment = RotationAlignmentType::Map;
symbol.text.rotation_alignment = RotationAlignmentType::Map;
};
applyLayoutProperty(PropertyKey::SymbolMinDistance, bucket_desc.layout, symbol.min_distance, z);
applyLayoutProperty(PropertyKey::SymbolAvoidEdges, bucket_desc.layout, symbol.avoid_edges, z);
applyLayoutProperty(PropertyKey::IconAllowOverlap, bucket_desc.layout, symbol.icon.allow_overlap, z);
applyLayoutProperty(PropertyKey::IconIgnorePlacement, bucket_desc.layout, symbol.icon.ignore_placement, z);
applyLayoutProperty(PropertyKey::IconOptional, bucket_desc.layout, symbol.icon.optional, z);
applyLayoutProperty(PropertyKey::IconRotationAlignment, bucket_desc.layout, symbol.icon.rotation_alignment, z);
applyLayoutProperty(PropertyKey::IconMaxSize, bucket_desc.layout, symbol.icon.max_size, z);
applyLayoutProperty(PropertyKey::IconImage, bucket_desc.layout, symbol.icon.image, z);
applyLayoutProperty(PropertyKey::IconPadding, bucket_desc.layout, symbol.icon.padding, z);
applyLayoutProperty(PropertyKey::IconRotate, bucket_desc.layout, symbol.icon.rotate, z);
applyLayoutProperty(PropertyKey::IconKeepUpright, bucket_desc.layout, symbol.icon.keep_upright, z);
applyLayoutProperty(PropertyKey::IconOffset, bucket_desc.layout, symbol.icon.offset, z);
applyLayoutProperty(PropertyKey::TextRotationAlignment, bucket_desc.layout, symbol.text.rotation_alignment, z);
applyLayoutProperty(PropertyKey::TextField, bucket_desc.layout, symbol.text.field, z);
applyLayoutProperty(PropertyKey::TextFont, bucket_desc.layout, symbol.text.font, z);
applyLayoutProperty(PropertyKey::TextMaxSize, bucket_desc.layout, symbol.text.max_size, z);
applyLayoutProperty(PropertyKey::TextMaxWidth, bucket_desc.layout, symbol.text.max_width, z);
applyLayoutProperty(PropertyKey::TextLineHeight, bucket_desc.layout, symbol.text.line_height, z);
applyLayoutProperty(PropertyKey::TextLetterSpacing, bucket_desc.layout, symbol.text.letter_spacing, z);
applyLayoutProperty(PropertyKey::TextMaxAngle, bucket_desc.layout, symbol.text.max_angle, z);
applyLayoutProperty(PropertyKey::TextRotate, bucket_desc.layout, symbol.text.rotate, z);
applyLayoutProperty(PropertyKey::TextPadding, bucket_desc.layout, symbol.text.padding, z);
applyLayoutProperty(PropertyKey::TextIgnorePlacement, bucket_desc.layout, symbol.text.ignore_placement, z);
applyLayoutProperty(PropertyKey::TextOptional, bucket_desc.layout, symbol.text.optional, z);
applyLayoutProperty(PropertyKey::TextJustify, bucket_desc.layout, symbol.text.justify, z);
applyLayoutProperty(PropertyKey::TextAnchor, bucket_desc.layout, symbol.text.anchor, z);
applyLayoutProperty(PropertyKey::TextKeepUpright, bucket_desc.layout, symbol.text.keep_upright, z);
applyLayoutProperty(PropertyKey::TextTransform, bucket_desc.layout, symbol.text.transform, z);
applyLayoutProperty(PropertyKey::TextOffset, bucket_desc.layout, symbol.text.offset, z);
applyLayoutProperty(PropertyKey::TextAllowOverlap, bucket_desc.layout, symbol.text.allow_overlap, z);
return symbolPtr;
}
std::unique_ptr<Bucket> TileParser::createBucket(const StyleBucket &bucketDesc) {
// Skip this bucket if we are to not render this
if (tile.id.z < std::floor(bucketDesc.min_zoom) && std::floor(bucketDesc.min_zoom) < tile.source.max_zoom) return nullptr;
@@ -230,32 +162,78 @@ void TileParser::addBucketGeometries(Bucket& bucket, const GeometryTileLayer& la
std::unique_ptr<Bucket> TileParser::createFillBucket(const GeometryTileLayer& layer,
const StyleBucket& bucket_desc) {
auto fill = parseStyleLayoutFill(bucket_desc, tile.id.z);
auto bucket = util::make_unique<FillBucket>(std::move(fill),
tile.fillVertexBuffer,
auto bucket = util::make_unique<FillBucket>(tile.fillVertexBuffer,
tile.triangleElementsBuffer,
tile.lineElementsBuffer);
addBucketGeometries(bucket, layer, bucket_desc.filter);
return obsolete() ? nullptr : std::move(bucket);
return std::move(bucket);
}
std::unique_ptr<Bucket> TileParser::createLineBucket(const GeometryTileLayer& layer,
const StyleBucket& bucket_desc) {
auto line = parseStyleLayoutLine(bucket_desc, tile.id.z);
auto bucket = util::make_unique<LineBucket>(std::move(line),
tile.lineVertexBuffer,
auto bucket = util::make_unique<LineBucket>(tile.lineVertexBuffer,
tile.triangleElementsBuffer,
tile.pointElementsBuffer);
const float z = tile.id.z;
auto& layout = bucket->layout;
applyLayoutProperty(PropertyKey::LineCap, bucket_desc.layout, layout.cap, z);
applyLayoutProperty(PropertyKey::LineJoin, bucket_desc.layout, layout.join, z);
applyLayoutProperty(PropertyKey::LineMiterLimit, bucket_desc.layout, layout.miter_limit, z);
applyLayoutProperty(PropertyKey::LineRoundLimit, bucket_desc.layout, layout.round_limit, z);
addBucketGeometries(bucket, layer, bucket_desc.filter);
return obsolete() ? nullptr : std::move(bucket);
return std::move(bucket);
}
std::unique_ptr<Bucket> TileParser::createSymbolBucket(const GeometryTileLayer& layer,
const StyleBucket& bucket_desc) {
auto symbol = parseStyleLayoutSymbol(bucket_desc, tile.id.z);
auto bucket = util::make_unique<SymbolBucket>(std::move(symbol), *collision);
auto bucket = util::make_unique<SymbolBucket>(*collision);
const float z = tile.id.z;
auto& layout = bucket->layout;
applyLayoutProperty(PropertyKey::SymbolPlacement, bucket_desc.layout, layout.placement, z);
if (layout.placement == PlacementType::Line) {
layout.icon.rotation_alignment = RotationAlignmentType::Map;
layout.text.rotation_alignment = RotationAlignmentType::Map;
};
applyLayoutProperty(PropertyKey::SymbolMinDistance, bucket_desc.layout, layout.min_distance, z);
applyLayoutProperty(PropertyKey::SymbolAvoidEdges, bucket_desc.layout, layout.avoid_edges, z);
applyLayoutProperty(PropertyKey::IconAllowOverlap, bucket_desc.layout, layout.icon.allow_overlap, z);
applyLayoutProperty(PropertyKey::IconIgnorePlacement, bucket_desc.layout, layout.icon.ignore_placement, z);
applyLayoutProperty(PropertyKey::IconOptional, bucket_desc.layout, layout.icon.optional, z);
applyLayoutProperty(PropertyKey::IconRotationAlignment, bucket_desc.layout, layout.icon.rotation_alignment, z);
applyLayoutProperty(PropertyKey::IconMaxSize, bucket_desc.layout, layout.icon.max_size, z);
applyLayoutProperty(PropertyKey::IconImage, bucket_desc.layout, layout.icon.image, z);
applyLayoutProperty(PropertyKey::IconPadding, bucket_desc.layout, layout.icon.padding, z);
applyLayoutProperty(PropertyKey::IconRotate, bucket_desc.layout, layout.icon.rotate, z);
applyLayoutProperty(PropertyKey::IconKeepUpright, bucket_desc.layout, layout.icon.keep_upright, z);
applyLayoutProperty(PropertyKey::IconOffset, bucket_desc.layout, layout.icon.offset, z);
applyLayoutProperty(PropertyKey::TextRotationAlignment, bucket_desc.layout, layout.text.rotation_alignment, z);
applyLayoutProperty(PropertyKey::TextField, bucket_desc.layout, layout.text.field, z);
applyLayoutProperty(PropertyKey::TextFont, bucket_desc.layout, layout.text.font, z);
applyLayoutProperty(PropertyKey::TextMaxSize, bucket_desc.layout, layout.text.max_size, z);
applyLayoutProperty(PropertyKey::TextMaxWidth, bucket_desc.layout, layout.text.max_width, z);
applyLayoutProperty(PropertyKey::TextLineHeight, bucket_desc.layout, layout.text.line_height, z);
applyLayoutProperty(PropertyKey::TextLetterSpacing, bucket_desc.layout, layout.text.letter_spacing, z);
applyLayoutProperty(PropertyKey::TextMaxAngle, bucket_desc.layout, layout.text.max_angle, z);
applyLayoutProperty(PropertyKey::TextRotate, bucket_desc.layout, layout.text.rotate, z);
applyLayoutProperty(PropertyKey::TextPadding, bucket_desc.layout, layout.text.padding, z);
applyLayoutProperty(PropertyKey::TextIgnorePlacement, bucket_desc.layout, layout.text.ignore_placement, z);
applyLayoutProperty(PropertyKey::TextOptional, bucket_desc.layout, layout.text.optional, z);
applyLayoutProperty(PropertyKey::TextJustify, bucket_desc.layout, layout.text.justify, z);
applyLayoutProperty(PropertyKey::TextAnchor, bucket_desc.layout, layout.text.anchor, z);
applyLayoutProperty(PropertyKey::TextKeepUpright, bucket_desc.layout, layout.text.keep_upright, z);
applyLayoutProperty(PropertyKey::TextTransform, bucket_desc.layout, layout.text.transform, z);
applyLayoutProperty(PropertyKey::TextOffset, bucket_desc.layout, layout.text.offset, z);
applyLayoutProperty(PropertyKey::TextAllowOverlap, bucket_desc.layout, layout.text.allow_overlap, z);
bucket->addFeatures(
layer, bucket_desc.filter, reinterpret_cast<uintptr_t>(&tile), spriteAtlas, *sprite, glyphAtlas, glyphStore);
return obsolete() ? nullptr : std::move(bucket);
return std::move(bucket);
}
}

View File

@@ -28,7 +28,6 @@ class StyleLayoutFill;
class StyleLayoutRaster;
class StyleLayoutLine;
class StyleLayoutSymbol;
class StyleLayerGroup;
class VectorTileData;
class Collision;
@@ -48,7 +47,6 @@ public:
private:
bool obsolete() const;
void parseStyleLayers(util::ptr<const StyleLayerGroup> group);
std::unique_ptr<Bucket> createBucket(const StyleBucket&);
std::unique_ptr<Bucket> createFillBucket(const GeometryTileLayer&, const StyleBucket&);
@@ -58,7 +56,6 @@ private:
template <class Bucket>
void addBucketGeometries(Bucket&, const GeometryTileLayer&, const FilterExpression&);
private:
const GeometryTile& geometryTile;
VectorTileData& tile;

View File

@@ -35,26 +35,7 @@ VectorTileFeature::VectorTileFeature(pbf feature_pbf, const VectorTileLayer& lay
if (feature_pbf.tag == 1) { // id
id = feature_pbf.varint<uint64_t>();
} else if (feature_pbf.tag == 2) { // tags
// tags are packed varints. They should have an even length.
pbf tags = feature_pbf.message();
while (tags) {
uint32_t tag_key = tags.varint();
if (layer.keys.size() <= tag_key) {
throw std::runtime_error("feature referenced out of range key");
}
if (!tags) {
throw std::runtime_error("uneven number of feature tag ids");
}
uint32_t tag_val = tags.varint();
if (layer.values.size() <= tag_val) {
throw std::runtime_error("feature referenced out of range value");
}
properties.emplace(tag_key, tag_val);
}
tags_pbf = feature_pbf.message();
} else if (feature_pbf.tag == 3) { // type
type = (FeatureType)feature_pbf.varint();
} else if (feature_pbf.tag == 4) { // geometry
@@ -70,11 +51,30 @@ mapbox::util::optional<Value> VectorTileFeature::getValue(const std::string& key
if (keyIter == layer.keys.end()) {
return mapbox::util::optional<Value>();
}
auto propIter = properties.find(keyIter->second);
if (propIter == properties.end()) {
return mapbox::util::optional<Value>();
pbf tags = tags_pbf;
while (tags) {
uint32_t tag_key = tags.varint();
if (layer.keys.size() <= tag_key) {
throw std::runtime_error("feature referenced out of range key");
}
if (!tags) {
throw std::runtime_error("uneven number of feature tag ids");
}
uint32_t tag_val = tags.varint();
if (layer.values.size() <= tag_val) {
throw std::runtime_error("feature referenced out of range value");
}
if (tag_key == keyIter->second) {
return layer.values[tag_val];
}
}
return layer.values[propIter->second];
return mapbox::util::optional<Value>();
}
GeometryCollection VectorTileFeature::getGeometries() const {

View File

@@ -22,7 +22,7 @@ private:
const VectorTileLayer& layer;
uint64_t id = 0;
FeatureType type = FeatureType::Unknown;
std::unordered_map<uint32_t, uint32_t> properties;
pbf tags_pbf;
pbf geometry_pbf;
};

View File

@@ -5,8 +5,6 @@
#include <cassert>
struct geometry_too_long_exception : std::exception {};
using namespace mbgl;
DebugBucket::DebugBucket(DebugFontBuffer& fontBuffer_)

View File

@@ -28,12 +28,10 @@ void FillBucket::free(void *, void *ptr) {
::free(ptr);
}
FillBucket::FillBucket(std::unique_ptr<const StyleLayoutFill> styleLayout_,
FillVertexBuffer &vertexBuffer_,
FillBucket::FillBucket(FillVertexBuffer &vertexBuffer_,
TriangleElementsBuffer &triangleElementsBuffer_,
LineElementsBuffer &lineElementsBuffer_)
: styleLayout(std::move(styleLayout_)),
allocator(new TESSalloc{
: allocator(new TESSalloc{
&alloc,
&realloc,
&free,
@@ -53,7 +51,6 @@ FillBucket::FillBucket(std::unique_ptr<const StyleLayoutFill> styleLayout_,
triangle_elements_start(triangleElementsBuffer_.index()),
line_elements_start(lineElementsBuffer.index()) {
assert(tesselator);
assert(styleLayout);
}
FillBucket::~FillBucket() {
@@ -95,7 +92,7 @@ void FillBucket::tessellate() {
}
size_t total_vertex_count = 0;
for (const std::vector<ClipperLib::IntPoint>& polygon : polygons) {
for (const auto& polygon : polygons) {
total_vertex_count += polygon.size();
}
@@ -112,12 +109,12 @@ void FillBucket::tessellate() {
line_group_type& lineGroup = *lineGroups.back();
uint32_t lineIndex = lineGroup.vertex_length;
for (const std::vector<ClipperLib::IntPoint>& polygon : polygons) {
for (const auto& polygon : polygons) {
const size_t group_count = polygon.size();
assert(group_count >= 3);
std::vector<TESSreal> clipped_line;
for (const ClipperLib::IntPoint& pt : polygon) {
for (const auto& pt : polygon) {
clipped_line.push_back(pt.X);
clipped_line.push_back(pt.Y);
vertexBuffer.add(pt.X, pt.Y);

View File

@@ -6,6 +6,7 @@
#include <mbgl/geometry/elements_buffer.hpp>
#include <mbgl/geometry/fill_buffer.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/style/style_layout.hpp>
#include <clipper/clipper.hpp>
#include <libtess2/tesselator.h>
@@ -39,8 +40,7 @@ class FillBucket : public Bucket {
typedef ElementGroup<1> line_group_type;
public:
FillBucket(std::unique_ptr<const StyleLayoutFill> styleLayout,
FillVertexBuffer &vertexBuffer,
FillBucket(FillVertexBuffer &vertexBuffer,
TriangleElementsBuffer &triangleElementsBuffer,
LineElementsBuffer &lineElementsBuffer);
~FillBucket() override;
@@ -57,7 +57,7 @@ public:
void drawVertices(OutlineShader& shader);
public:
const std::unique_ptr<const StyleLayoutFill> styleLayout;
StyleLayoutFill layout;
private:
TESSalloc *allocator;

View File

@@ -12,22 +12,17 @@
#include <cassert>
struct geometry_too_long_exception : std::exception {};
using namespace mbgl;
LineBucket::LineBucket(std::unique_ptr<const StyleLayoutLine> styleLayout_,
LineVertexBuffer &vertexBuffer_,
LineBucket::LineBucket(LineVertexBuffer &vertexBuffer_,
TriangleElementsBuffer &triangleElementsBuffer_,
PointElementsBuffer &pointElementsBuffer_)
: styleLayout(std::move(styleLayout_)),
vertexBuffer(vertexBuffer_),
: vertexBuffer(vertexBuffer_),
triangleElementsBuffer(triangleElementsBuffer_),
pointElementsBuffer(pointElementsBuffer_),
vertex_start(vertexBuffer_.index()),
triangle_elements_start(triangleElementsBuffer_.index()),
point_elements_start(pointElementsBuffer_.index()) {
assert(styleLayout);
}
LineBucket::~LineBucket() {
@@ -48,7 +43,6 @@ void LineBucket::addGeometry(const GeometryCollection& geometryCollection) {
}
void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
auto &layout = *styleLayout;
// TODO: use roundLimit
// const float roundLimit = geometry.round_limit;
@@ -302,7 +296,7 @@ void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
assert(triangleGroups.back());
triangle_group_type& group = *triangleGroups.back();
for (const TriangleElement& triangle : triangle_store) {
for (const auto& triangle : triangle_store) {
triangleElementsBuffer.add(
group.vertex_length + triangle.a,
group.vertex_length + triangle.b,
@@ -323,7 +317,7 @@ void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
assert(pointGroups.back());
point_group_type& group = *pointGroups.back();
for (PointElement point : point_store) {
for (const auto point : point_store) {
pointElementsBuffer.add(group.vertex_length + point);
}

View File

@@ -7,6 +7,7 @@
#include <mbgl/geometry/elements_buffer.hpp>
#include <mbgl/geometry/line_buffer.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/style/style_layout.hpp>
#include <mbgl/util/vec.hpp>
#include <vector>
@@ -14,7 +15,6 @@
namespace mbgl {
class Style;
class StyleLayoutLine;
class LineVertexBuffer;
class TriangleElementsBuffer;
class LineShader;
@@ -27,8 +27,7 @@ class LineBucket : public Bucket {
typedef ElementGroup<1> point_group_type;
public:
LineBucket(std::unique_ptr<const StyleLayoutLine> styleLayout,
LineVertexBuffer &vertexBuffer,
LineBucket(LineVertexBuffer &vertexBuffer,
TriangleElementsBuffer &triangleElementsBuffer,
PointElementsBuffer &pointElementsBuffer);
~LineBucket() override;
@@ -48,7 +47,7 @@ public:
void drawPoints(LinejoinShader& shader);
public:
const std::unique_ptr<const StyleLayoutLine> styleLayout;
StyleLayoutLine layout;
private:
LineVertexBuffer& vertexBuffer;

View File

@@ -2,7 +2,6 @@
#include <mbgl/platform/log.hpp>
#include <mbgl/style/style.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/util/string.hpp>
@@ -226,7 +225,7 @@ void Painter::render(const Style& style, const std::set<util::ptr<StyleSource>>&
// Update all clipping IDs.
ClipIDGenerator generator;
for (const util::ptr<StyleSource> &source : sources) {
for (const auto& source : sources) {
generator.update(source->source->getLoadedTiles());
source->source->updateMatrices(projMatrix, state);
}
@@ -237,23 +236,9 @@ void Painter::render(const Style& style, const std::set<util::ptr<StyleSource>>&
// Actually render the layers
if (debug::renderTree) { Log::Info(Event::Render, "{"); indent++; }
if (style.layers) {
renderLayers(*style.layers);
}
if (debug::renderTree) { Log::Info(Event::Render, "}"); indent--; }
// Finalize the rendering, e.g. by calling debug render calls per tile.
// This guarantees that we have at least one function per tile called.
// When only rendering layers via the stylesheet, it's possible that we don't
// ever visit a tile during rendering.
for (const util::ptr<StyleSource> &source : sources) {
source->source->finishRender(*this);
}
}
void Painter::renderLayers(const StyleLayerGroup &group) {
// TODO: Correctly compute the number of layers recursively beforehand.
float strata_thickness = 1.0f / (group.layers.size() + 1);
float strata_thickness = 1.0f / (style.layers.size() + 1);
// - FIRST PASS ------------------------------------------------------------
// Render everything top-to-bottom by using reverse iterators. Render opaque
@@ -263,7 +248,7 @@ void Painter::renderLayers(const StyleLayerGroup &group) {
Log::Info(Event::Render, "%*s%s", indent++ * 4, "", "OPAQUE {");
}
int i = 0;
for (auto it = group.layers.rbegin(), end = group.layers.rend(); it != end; ++it, ++i) {
for (auto it = style.layers.rbegin(), end = style.layers.rend(); it != end; ++it, ++i) {
setOpaque();
setStrata(i * strata_thickness);
renderLayer(**it);
@@ -279,7 +264,7 @@ void Painter::renderLayers(const StyleLayerGroup &group) {
Log::Info(Event::Render, "%*s%s", indent++ * 4, "", "TRANSLUCENT {");
}
--i;
for (auto it = group.layers.begin(), end = group.layers.end(); it != end; ++it, --i) {
for (auto it = style.layers.begin(), end = style.layers.end(); it != end; ++it, --i) {
setTranslucent();
setStrata(i * strata_thickness);
renderLayer(**it);
@@ -287,6 +272,16 @@ void Painter::renderLayers(const StyleLayerGroup &group) {
if (debug::renderTree) {
Log::Info(Event::Render, "%*s%s", --indent * 4, "", "}");
}
if (debug::renderTree) { Log::Info(Event::Render, "}"); indent--; }
// Finalize the rendering, e.g. by calling debug render calls per tile.
// This guarantees that we have at least one function per tile called.
// When only rendering layers via the stylesheet, it's possible that we don't
// ever visit a tile during rendering.
for (const auto& source : sources) {
source->source->finishRender(*this);
}
}
void Painter::renderLayer(const StyleLayer &layer_desc, const Tile::ID* id, const mat4* matrix) {

View File

@@ -43,7 +43,6 @@ class GlyphAtlas;
class LineAtlas;
class Source;
class StyleSource;
class StyleLayerGroup;
class FillBucket;
class LineBucket;
@@ -81,7 +80,6 @@ public:
TransformState state,
std::chrono::steady_clock::time_point time);
void renderLayers(const StyleLayerGroup &group);
void renderLayer(const StyleLayer &layer_desc, const Tile::ID* id = nullptr, const mat4* matrix = nullptr);
// Renders a particular layer from a tile.

View File

@@ -17,7 +17,7 @@ void Painter::drawClippingMasks(const std::set<util::ptr<StyleSource>> &sources)
coveringPlainArray.bind(*plainShader, tileStencilBuffer, BUFFER_OFFSET(0));
for (const util::ptr<StyleSource> &source : sources) {
for (const auto& source : sources) {
source->source->drawClippingMasks(*this);
}

View File

@@ -77,7 +77,7 @@ void Painter::renderDebugText(const std::vector<std::string> &strings) {
DebugFontBuffer debugFontBuffer;
int line = 25;
for (const std::string &str : strings) {
for (const auto& str : strings) {
debugFontBuffer.addText(str.c_str(), 10, line, 0.75);
line += 20;
}

View File

@@ -18,7 +18,7 @@ void Painter::renderLine(LineBucket& bucket, const StyleLayer &layer_desc, const
depthMask(false);
const auto &properties = layer_desc.getProperties<LineProperties>();
const auto &layout = *bucket.styleLayout;
const auto &layout = bucket.layout;
// the distance over which the line edge fades out.
// Retina devices need a smaller distance to avoid aliasing.

View File

@@ -2,7 +2,6 @@
#include <mbgl/platform/gl.hpp>
#include <mbgl/renderer/raster_bucket.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/util/std.hpp>
#include <mbgl/map/map.hpp>

View File

@@ -119,7 +119,7 @@ void Painter::renderSymbol(SymbolBucket &bucket, const StyleLayer &layer_desc, c
}
const auto &properties = layer_desc.getProperties<SymbolProperties>();
const auto &layout = *bucket.styleLayout;
const auto &layout = bucket.layout;
MBGL_CHECK_ERROR(glDisable(GL_STENCIL_TEST));
depthMask(false);

View File

@@ -22,9 +22,8 @@
namespace mbgl {
SymbolBucket::SymbolBucket(std::unique_ptr<const StyleLayoutSymbol> styleLayout_, Collision &collision_)
: styleLayout(std::move(styleLayout_)), collision(collision_) {
assert(styleLayout);
SymbolBucket::SymbolBucket(Collision &collision_)
: collision(collision_) {
}
SymbolBucket::~SymbolBucket() {
@@ -46,7 +45,6 @@ std::vector<SymbolFeature> SymbolBucket::processFeatures(const GeometryTileLayer
const FilterExpression& filter,
GlyphStore &glyphStore,
const Sprite &sprite) {
auto &layout = *styleLayout;
const bool has_text = layout.text.field.size();
const bool has_icon = layout.icon.image.size();
@@ -129,7 +127,6 @@ void SymbolBucket::addFeatures(const GeometryTileLayer& layer,
Sprite& sprite,
GlyphAtlas& glyphAtlas,
GlyphStore& glyphStore) {
auto &layout = *styleLayout;
const std::vector<SymbolFeature> features = processFeatures(layer, filter, glyphStore, sprite);
float horizontalAlign = 0.5;
@@ -175,7 +172,7 @@ void SymbolBucket::addFeatures(const GeometryTileLayer& layer,
const auto &fontStack = glyphStore.getFontStack(layout.text.font);
for (const SymbolFeature &feature : features) {
for (const auto& feature : features) {
if (!feature.geometry.size()) continue;
Shaping shaping;
@@ -212,7 +209,7 @@ void SymbolBucket::addFeatures(const GeometryTileLayer& layer,
// if either shaping or icon position is present, add the feature
if (shaping.size() || image) {
for (const std::vector<Coordinate> &line : feature.geometry) {
for (const auto& line : feature.geometry) {
if (line.size()) {
addFeature(line, shaping, face, image);
}
@@ -228,7 +225,6 @@ const PlacementRange fullRange{{2 * M_PI, 0}};
void SymbolBucket::addFeature(const std::vector<Coordinate> &line, const Shaping &shaping,
const GlyphPositions &face, const Rect<uint16_t> &image) {
assert(line.size());
auto &layout = *styleLayout;
const float minScale = 0.5f;
const float glyphSize = 24.0f;
@@ -276,7 +272,7 @@ void SymbolBucket::addFeature(const std::vector<Coordinate> &line, const Shaping
// TODO: figure out correct ascender height.
const vec2<float> origin = {0, -17};
for (Anchor &anchor : anchors) {
for (auto& anchor : anchors) {
// Calculate the scales at which the text and icons can be first shown without overlap
Placement glyphPlacement;
@@ -363,7 +359,7 @@ void SymbolBucket::addSymbols(Buffer &buffer, const PlacedGlyphs &symbols, float
const float placementZoom = std::log(scale) / std::log(2) + zoom;
for (const PlacedGlyph &symbol : symbols) {
for (const auto& symbol : symbols) {
const auto &tl = symbol.tl;
const auto &tr = symbol.tr;
const auto &bl = symbol.bl;

View File

@@ -10,7 +10,7 @@
#include <mbgl/text/types.hpp>
#include <mbgl/text/glyph.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/util/ptr.hpp>
#include <mbgl/style/style_layout.hpp>
#include <memory>
#include <map>
@@ -56,7 +56,7 @@ class SymbolBucket : public Bucket {
typedef ElementGroup<2> IconElementGroup;
public:
SymbolBucket(std::unique_ptr<const StyleLayoutSymbol> styleLayout, Collision &collision);
SymbolBucket(Collision &collision);
~SymbolBucket() override;
void render(Painter &painter, const StyleLayer &layer_desc, const Tile::ID &id,
@@ -90,7 +90,7 @@ private:
void addSymbols(Buffer &buffer, const PlacedGlyphs &symbols, float scale, PlacementRange placementRange);
public:
const std::unique_ptr<const StyleLayoutSymbol> styleLayout;
StyleLayoutSymbol layout;
bool sdfIcons = false;
private:

View File

@@ -1,6 +1,6 @@
#include <mbgl/style/style.hpp>
#include <mbgl/map/sprite.hpp>
#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_parser.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/util/constants.hpp>
@@ -25,19 +25,21 @@ Style::Style()
// for deleting the std::unique_ptr<uv::rwlock>.
Style::~Style() {}
void Style::updateProperties(float z, std::chrono::steady_clock::time_point now) {
void Style::cascade(const std::vector<std::string>& classes) {
std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
for (const auto& layer : layers) {
layer->setClasses(classes, now, defaultTransition);
}
}
void Style::recalculate(float z, std::chrono::steady_clock::time_point now) {
uv::writelock lock(mtx);
zoomHistory.update(z, now);
if (layers) {
layers->updateProperties(z, now, zoomHistory);
}
// Apply transitions after the first time.
if (!initial_render_complete) {
initial_render_complete = true;
return;
for (const auto& layer : layers) {
layer->updateProperties(z, now, zoomHistory);
}
}
@@ -49,22 +51,15 @@ void Style::setDefaultTransitionDuration(std::chrono::steady_clock::duration dur
defaultTransition.duration = duration;
}
void Style::cascadeClasses(const std::vector<std::string>& classes) {
if (layers) {
layers->setClasses(classes, std::chrono::steady_clock::now(), defaultTransition);
}
}
bool Style::hasTransitions() const {
if (layers) {
if (layers->hasTransitions()) {
for (const auto& layer : layers) {
if (layer->hasTransitions()) {
return true;
}
}
return false;
}
void Style::loadJSON(const uint8_t *const data) {
uv::writelock lock(mtx);

View File

@@ -2,54 +2,43 @@
#define MBGL_STYLE_STYLE
#include <mbgl/style/property_transition.hpp>
#include <mbgl/style/style_source.hpp>
#include <mbgl/style/zoom_history.hpp>
#include <mbgl/util/uv.hpp>
#include <mbgl/util/ptr.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <cstdint>
#include <map>
#include <string>
#include <unordered_map>
#include <vector>
#include <set>
#include <chrono>
namespace mbgl {
class Sprite;
class StyleLayer;
class StyleLayerGroup;
class Style : public util::noncopyable {
public:
struct exception : std::runtime_error { exception(const char *msg) : std::runtime_error(msg) {} };
Style();
~Style();
void loadJSON(const uint8_t *const data);
size_t layerCount() const;
void updateProperties(float z, std::chrono::steady_clock::time_point now);
void setDefaultTransitionDuration(std::chrono::steady_clock::duration duration = std::chrono::steady_clock::duration::zero());
void cascadeClasses(const std::vector<std::string>&);
void cascade(const std::vector<std::string>&);
void recalculate(float z, std::chrono::steady_clock::time_point now);
void setDefaultTransitionDuration(std::chrono::steady_clock::duration);
bool hasTransitions() const;
const std::string &getSpriteURL() const;
util::ptr<StyleLayerGroup> layers;
std::vector<std::string> appliedClasses;
std::vector<util::ptr<StyleLayer>> layers;
std::string glyph_url;
std::string base;
private:
std::string sprite_url;
PropertyTransition defaultTransition;
bool initial_render_complete = false;
std::unique_ptr<uv::rwlock> mtx;
ZoomHistory zoomHistory;
};

View File

@@ -1,6 +1,5 @@
#include <mbgl/style/style_layer.hpp>
#include <mbgl/style/style_bucket.hpp>
#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/style/property_fallback.hpp>
#include <mbgl/util/interpolate.hpp>
@@ -32,7 +31,7 @@ void StyleLayer::setClasses(const std::vector<std::string> &class_names, const s
// Make sure that we also transition to the fallback value for keys that aren't changed by
// any applied classes.
for (std::pair<const PropertyKey, AppliedClassProperties> &property_pair : appliedStyle) {
for (auto& property_pair : appliedStyle) {
const PropertyKey key = property_pair.first;
if (already_applied.find(key) != already_applied.end()) {
// This property has already been set by a previous class, so we don't need to
@@ -66,7 +65,7 @@ void StyleLayer::applyClassProperties(const ClassID class_id,
// Loop through all the properties in this style, and add transitions to them, if they're
// not already the most recent transition.
const ClassProperties &class_properties = style_it->second;
for (const std::pair<PropertyKey, PropertyValue> &property_pair : class_properties) {
for (const auto& property_pair : class_properties) {
PropertyKey key = property_pair.first;
if (already_applied.find(key) != already_applied.end()) {
// This property has already been set by a previous class.
@@ -126,7 +125,7 @@ void StyleLayer::applyStyleProperty(PropertyKey key, T &target, const float z, c
AppliedClassProperties &applied = it->second;
// Iterate through all properties that we need to apply in order.
const PropertyEvaluator<T> evaluator(z, zoomHistory);
for (AppliedClassProperty &property : applied.properties) {
for (auto& property : applied.properties) {
if (now >= property.begin) {
// We overwrite the current property with the new value.
target = mapbox::util::apply_visitor(evaluator, property.value);
@@ -144,7 +143,7 @@ void StyleLayer::applyTransitionedStyleProperty(PropertyKey key, T &target, cons
AppliedClassProperties &applied = it->second;
// Iterate through all properties that we need to apply in order.
const PropertyEvaluator<T> evaluator(z, zoomHistory);
for (AppliedClassProperty &property : applied.properties) {
for (auto& property : applied.properties) {
if (now >= property.end) {
// We overwrite the current property with the new value.
target = mapbox::util::apply_visitor(evaluator, property.value);
@@ -250,7 +249,7 @@ void StyleLayer::updateProperties(float z, const std::chrono::steady_clock::time
}
bool StyleLayer::hasTransitions() const {
for (const std::pair<PropertyKey, AppliedClassProperties> &pair : appliedStyle) {
for (const auto& pair : appliedStyle) {
if (pair.second.hasTransitions()) {
return true;
}

View File

@@ -8,6 +8,7 @@
#include <mbgl/style/zoom_history.hpp>
#include <mbgl/util/ptr.hpp>
#include <mbgl/util/noncopyable.hpp>
#include <vector>
#include <string>
@@ -18,9 +19,8 @@
namespace mbgl {
class StyleBucket;
class StyleLayerGroup;
class StyleLayer {
class StyleLayer : public util::noncopyable {
public:
StyleLayer(const std::string &id, std::map<ClassID, ClassProperties> &&styles);

View File

@@ -1,34 +0,0 @@
#include <mbgl/style/style_layer_group.hpp>
namespace mbgl {
void StyleLayerGroup::setClasses(const std::vector<std::string> &class_names, std::chrono::steady_clock::time_point now,
const PropertyTransition &defaultTransition) {
for (const util::ptr<StyleLayer> &layer : layers) {
if (layer) {
layer->setClasses(class_names, now, defaultTransition);
}
}
}
void StyleLayerGroup::updateProperties(float z, std::chrono::steady_clock::time_point now, ZoomHistory &zoomHistory) {
for (const util::ptr<StyleLayer> &layer: layers) {
if (layer) {
layer->updateProperties(z, now, zoomHistory);
}
}
}
bool StyleLayerGroup::hasTransitions() const {
for (const util::ptr<const StyleLayer> &layer: layers) {
if (layer) {
if (layer->hasTransitions()) {
return true;
}
}
}
return false;
}
}

View File

@@ -1,24 +0,0 @@
#ifndef MBGL_STYLE_STYLE_LAYER_GROUP
#define MBGL_STYLE_STYLE_LAYER_GROUP
#include <mbgl/style/style_layer.hpp>
#include <vector>
#include <chrono>
namespace mbgl {
class StyleLayerGroup {
public:
void setClasses(const std::vector<std::string> &class_names, std::chrono::steady_clock::time_point now,
const PropertyTransition &defaultTransition);
void updateProperties(float z, std::chrono::steady_clock::time_point now, ZoomHistory &zoomHistory);
bool hasTransitions() const;
public:
std::vector<util::ptr<StyleLayer>> layers;
};
}
#endif

View File

@@ -1,6 +1,6 @@
#include <mbgl/style/style_source.hpp>
#include <mbgl/style/style_parser.hpp>
#include <mbgl/style/style_layer_group.hpp>
#include <mbgl/style/style_layer.hpp>
#include <mbgl/map/annotation.hpp>
#include <mbgl/util/constants.hpp>
#include <mbgl/util/std.hpp>
@@ -9,6 +9,13 @@
#include <mbgl/platform/log.hpp>
#include <csscolorparser/csscolorparser.hpp>
#pragma GCC diagnostic push
#ifndef __clang__
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#include <boost/algorithm/string.hpp>
#pragma GCC diagnostic pop
#include <algorithm>
namespace mbgl {
@@ -28,8 +35,7 @@ void StyleParser::parse(JSVal document) {
}
if (document.HasMember("layers")) {
root = createLayers(document["layers"]);
parseLayers();
parseLayers(document["layers"]);
// create point annotations layer
//
@@ -38,8 +44,8 @@ void StyleParser::parse(JSVal document) {
std::map<ClassID, ClassProperties> paints;
util::ptr<StyleLayer> annotations = std::make_shared<StyleLayer>(id, std::move(paints));
annotations->type = StyleLayerType::Symbol;
layers.emplace(id, std::pair<JSVal, util::ptr<StyleLayer>> { JSVal(id), annotations });
root->layers.emplace_back(annotations);
layersMap.emplace(id, std::pair<JSVal, util::ptr<StyleLayer>> { JSVal(id), annotations });
layers.emplace_back(annotations);
util::ptr<StyleBucket> pointBucket = std::make_shared<StyleBucket>(annotations->type);
pointBucket->name = annotations->id;
@@ -447,6 +453,13 @@ bool StyleParser::parseOptionalProperty(const char *property_name, PropertyKey k
}
}
std::string normalizeFontStack(const std::string &name) {
namespace algo = boost::algorithm;
std::vector<std::string> parts;
algo::split(parts, name, algo::is_any_of(","), algo::token_compress_on);
std::for_each(parts.begin(), parts.end(), [](std::string& str) { algo::trim(str); });
return algo::join(parts, ", ");
}
template<> std::tuple<bool, std::string> StyleParser::parseProperty(JSVal value, const char *property_name) {
if (!value.IsString()) {
@@ -454,7 +467,13 @@ template<> std::tuple<bool, std::string> StyleParser::parseProperty(JSVal value,
return std::tuple<bool, std::string> { false, std::string() };
}
return std::tuple<bool, std::string> { true, { value.GetString(), value.GetStringLength() } };
if (std::string { "text-font" } == property_name) {
return std::tuple<bool, std::string> {
true, normalizeFontStack({ value.GetString(), value.GetStringLength() })
};
} else {
return std::tuple<bool, std::string> { true, { value.GetString(), value.GetStringLength() } };
}
}
template<> std::tuple<bool, bool> StyleParser::parseProperty(JSVal value, const char *property_name) {
@@ -662,61 +681,48 @@ template<> std::tuple<bool, PiecewiseConstantFunction<Faded<std::string>>> Style
#pragma mark - Parse Layers
std::unique_ptr<StyleLayerGroup> StyleParser::createLayers(JSVal value) {
if (value.IsArray()) {
std::unique_ptr<StyleLayerGroup> group = util::make_unique<StyleLayerGroup>();
for (rapidjson::SizeType i = 0; i < value.Size(); ++i) {
util::ptr<StyleLayer> layer = createLayer(value[i]);
if (layer) {
group->layers.emplace_back(layer);
}
}
return group;
} else {
void StyleParser::parseLayers(JSVal value) {
if (!value.IsArray()) {
Log::Warning(Event::ParseStyle, "layers must be an array");
return nullptr;
return;
}
}
util::ptr<StyleLayer> StyleParser::createLayer(JSVal value) {
if (value.IsObject()) {
if (!value.HasMember("id")) {
Log::Warning(Event::ParseStyle, "layer must have an id");
return nullptr;
for (rapidjson::SizeType i = 0; i < value.Size(); ++i) {
JSVal layerValue = value[i];
if (!layerValue.IsObject()) {
Log::Warning(Event::ParseStyle, "layer must be an object");
continue;
}
JSVal id = value["id"];
if (!layerValue.HasMember("id")) {
Log::Warning(Event::ParseStyle, "layer must have an id");
continue;
}
JSVal id = layerValue["id"];
if (!id.IsString()) {
Log::Warning(Event::ParseStyle, "layer id must be a string");
return nullptr;
continue;
}
const std::string layer_id = { id.GetString(), id.GetStringLength() };
if (layers.find(layer_id) != layers.end()) {
Log::Warning(Event::ParseStyle, "duplicate layer id %s", layer_id.c_str());
return nullptr;
const std::string layerID = { id.GetString(), id.GetStringLength() };
if (layersMap.find(layerID) != layersMap.end()) {
Log::Warning(Event::ParseStyle, "duplicate layer id %s", layerID.c_str());
continue;
}
// Parse paints already, as they can't be inherited anyway.
std::map<ClassID, ClassProperties> paints;
parsePaints(value, paints);
parsePaints(layerValue, paints);
util::ptr<StyleLayer> layer = std::make_shared<StyleLayer>(
layer_id, std::move(paints));
util::ptr<StyleLayer> layer = std::make_shared<StyleLayer>(layerID, std::move(paints));
// Store the layer ID so we can reference it later.
layers.emplace(layer_id, std::pair<JSVal, util::ptr<StyleLayer>> { value, layer });
return layer;
} else {
Log::Warning(Event::ParseStyle, "layer must be an object");
return nullptr;
layers.emplace_back(layer);
layersMap.emplace(layerID, std::pair<JSVal, util::ptr<StyleLayer>> { layerValue, layer });
}
}
void StyleParser::parseLayers() {
for (std::pair<const std::string, std::pair<JSVal, util::ptr<StyleLayer>>> &pair : layers) {
for (auto& pair : layersMap) {
parseLayer(pair.second);
}
}
@@ -904,8 +910,8 @@ void StyleParser::parseReference(JSVal value, util::ptr<StyleLayer> &layer) {
return;
}
const std::string ref { value.GetString(), value.GetStringLength() };
auto it = layers.find(ref);
if (it == layers.end()) {
auto it = layersMap.find(ref);
if (it == layersMap.end()) {
Log::Warning(Event::ParseStyle, "layer '%s' references unknown layer %s", layer->id.c_str(), ref.c_str());
// We cannot parse this layer further.
return;

View File

@@ -17,7 +17,6 @@ namespace mbgl {
enum class ClassID : uint32_t;
class StyleLayer;
class StyleLayerGroup;
class StyleParser {
public:
@@ -27,8 +26,8 @@ public:
void parse(JSVal document);
util::ptr<StyleLayerGroup> getLayers() {
return root;
std::vector<util::ptr<StyleLayer>> getLayers() {
return layers;
}
std::string getSprite() const {
@@ -44,10 +43,7 @@ private:
JSVal replaceConstant(JSVal value);
void parseSources(JSVal value);
std::unique_ptr<StyleLayerGroup> createLayers(JSVal value);
util::ptr<StyleLayer> createLayer(JSVal value);
void parseLayers();
void parseLayers(JSVal value);
void parseLayer(std::pair<JSVal, util::ptr<StyleLayer>> &pair);
void parsePaints(JSVal value, std::map<ClassID, ClassProperties> &paints);
void parsePaint(JSVal, ClassProperties &properties);
@@ -97,10 +93,10 @@ private:
std::unordered_map<std::string, const util::ptr<StyleSource>> sources;
// This stores the root layer.
util::ptr<StyleLayerGroup> root;
std::vector<util::ptr<StyleLayer>> layers;
// This maps ids to Layer objects, with all items being at the root level.
std::unordered_map<std::string, std::pair<JSVal, util::ptr<StyleLayer>>> layers;
std::unordered_map<std::string, std::pair<JSVal, util::ptr<StyleLayer>>> layersMap;
// Store a stack of layers we're parsing right now. This is to prevent reference cycles.
std::forward_list<StyleLayer *> stack;

View File

@@ -91,7 +91,7 @@ GlyphBox getMergedGlyphs(const GlyphBoxes &boxes, const CollisionAnchor &anchor)
mergedGlyphs.anchor = anchor;
CollisionRect &box = mergedGlyphs.box;
for (const GlyphBox &glyph : boxes) {
for (const auto& glyph : boxes) {
const CollisionRect &gbox = glyph.box;
box.tl.x = util::min(box.tl.x, gbox.tl.x);
box.tl.y = util::min(box.tl.y, gbox.tl.y);
@@ -105,7 +105,7 @@ GlyphBox getMergedGlyphs(const GlyphBoxes &boxes, const CollisionAnchor &anchor)
float Collision::getPlacementScale(const GlyphBoxes &glyphs, float minPlacementScale, bool avoidEdges) {
for (const GlyphBox &glyph : glyphs) {
for (const auto& glyph : glyphs) {
const CollisionRect &box = glyph.box;
const CollisionRect &bbox = glyph.hBox ? glyph.hBox.get() : glyph.box;
const CollisionAnchor &anchor = glyph.anchor;
@@ -141,7 +141,7 @@ float Collision::getPlacementScale(const GlyphBoxes &glyphs, float minPlacementS
const CollisionAnchor &na = anchor; // new anchor
const CollisionRect &nb = box; // new box
for (const PlacementValue &value : blocking) {
for (const auto& value : blocking) {
const PlacementBox &placement = std::get<1>(value);
const CollisionAnchor &oa = placement.anchor; // old anchor
const CollisionRect &ob = placement.box; // old box
@@ -198,7 +198,7 @@ PlacementRange Collision::getPlacementRange(const GlyphBoxes &glyphs, float plac
bool horizontal) {
PlacementRange placementRange = {{2.0f * M_PI, 0}};
for (const GlyphBox &glyph : glyphs) {
for (const auto& glyph : glyphs) {
const CollisionRect &bbox = glyph.hBox ? glyph.hBox.get() : glyph.box;
const CollisionAnchor &anchor = glyph.anchor;
@@ -216,7 +216,7 @@ PlacementRange Collision::getPlacementRange(const GlyphBoxes &glyphs, float plac
cTree.query(bgi::intersects(query_box), std::back_inserter(blocking));
}
for (const PlacementValue &value : blocking) {
for (const auto& value : blocking) {
const Box &s = std::get<0>(value);
const PlacementBox &b = std::get<1>(value);
const CollisionRect &bbox2 = b.hBox ? b.hBox.get() : b.box;
@@ -265,7 +265,7 @@ void Collision::insert(const GlyphBoxes &glyphs, const CollisionAnchor &anchor,
std::vector<PlacementValue> allBounds;
allBounds.reserve(glyphs.size());
for (const GlyphBox &glyph : glyphs) {
for (const auto& glyph : glyphs) {
const CollisionRect &box = glyph.box;
const CollisionRect &bbox = glyph.hBox ? glyph.hBox.get() : glyph.box;

View File

@@ -4,6 +4,7 @@
#include <mbgl/text/types.hpp>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wshadow"

View File

@@ -68,7 +68,7 @@ void align(Shaping &shaping, const float justify, const float horizontalAlign,
const float shiftX = (justify - horizontalAlign) * maxLineLength;
const float shiftY = (-verticalAlign * (line + 1) + 0.5) * lineHeight;
for (PositionedGlyph &glyph : shaping) {
for (auto& glyph : shaping) {
glyph.x += shiftX;
glyph.y += shiftY;
}
@@ -251,7 +251,7 @@ void GlyphStore::waitForGlyphRanges(const std::string &fontStack, const std::set
// Attempt to load the glyph range. If the GlyphSet already exists, we are getting back
// the same shared_future.
for (GlyphRange range : glyphRanges) {
for (const auto range : glyphRanges) {
futures.emplace_back(loadGlyphRange(fontStack, rangeSets, range));
}
}
@@ -259,7 +259,7 @@ void GlyphStore::waitForGlyphRanges(const std::string &fontStack, const std::set
// Now that we potentially created all GlyphSets, we are waiting for the results, one by one.
// When we get a result (or the GlyphSet is aready loaded), we are attempting to parse the
// GlyphSet.
for (std::shared_future<GlyphPBF &> &future : futures) {
for (const auto& future : futures) {
future.get().parse(stack);
}
}

View File

@@ -110,7 +110,7 @@ GlyphBox getMergedBoxes(const GlyphBoxes &glyphs, const Anchor &anchor) {
CollisionRect &box = mergedglyphs.box;
for (const GlyphBox &glyph : glyphs) {
for (const auto& glyph : glyphs) {
const CollisionRect &gbox = glyph.box;
box.tl.x = util::min(box.tl.x, gbox.tl.x);
box.tl.y = util::min(box.tl.y, gbox.tl.y);
@@ -211,7 +211,7 @@ Placement Placement::getGlyphs(Anchor &anchor, const vec2<float> &origin, const
const uint32_t buffer = 3;
for (const PositionedGlyph &shape : shaping) {
for (const auto& shape : shaping) {
auto face_it = face.find(shape.glyph);
if (face_it == face.end())
continue;
@@ -250,7 +250,7 @@ Placement Placement::getGlyphs(Anchor &anchor, const vec2<float> &origin, const
const CollisionRect obox{boxScale * x1, boxScale * y1, boxScale * x2, boxScale * y2};
for (const GlyphInstance &instance : glyphInstances) {
for (const auto& instance : glyphInstances) {
vec2<float> tl = otl;
vec2<float> tr = otr;
vec2<float> bl = obl;
@@ -301,7 +301,7 @@ Placement Placement::getGlyphs(Anchor &anchor, const vec2<float> &origin, const
const float minPlacementScale = anchor.scale;
placement.minScale = std::numeric_limits<float>::infinity();
for (const GlyphBox &box : placement.boxes) {
for (const auto& box : placement.boxes) {
placement.minScale = util::min(placement.minScale, box.minScale);
}
placement.minScale = util::max(minPlacementScale, Placement::globalMinScale);

View File

@@ -17,7 +17,7 @@ CollisionRange mergeCollisions(const CollisionList &collisions,
float min = 2.0f * M_PI;
float max = 0.0f;
for (CollisionRange collision : collisions) {
for (const auto& collision : collisions) {
bool entryOutside =
ignoreRange[0] <= collision[0] && collision[0] <= ignoreRange[1];
bool exitOutside =

View File

@@ -18,7 +18,7 @@ ClipIDGenerator::Leaf::Leaf(Tile &tile_) : tile(tile_) {}
void ClipIDGenerator::Leaf::add(const Tile::ID &p) {
if (p.isChildOf(tile.id)) {
// Ensure that no already present child is a parent of the new p.
for (const Tile::ID &child : children) {
for (const auto& child : children) {
if (p.isChildOf(child))
return;
}
@@ -31,7 +31,7 @@ bool ClipIDGenerator::Leaf::operator==(const Leaf &other) const {
}
bool ClipIDGenerator::reuseExisting(Leaf &leaf) {
for (const std::vector<Leaf> &pool : pools) {
for (const auto& pool : pools) {
auto existing = std::find(pool.begin(), pool.end(), leaf);
if (existing != pool.end()) {
leaf.tile.clip = existing->tile.clip;
@@ -80,7 +80,7 @@ void ClipIDGenerator::update(std::forward_list<Tile *> tiles) {
// We are starting our count with 1 since we need at least 1 bit set to distinguish between
// areas without any tiles whatsoever and the current area.
uint8_t count = 1;
for (Leaf &leaf : pool) {
for (auto& leaf : pool) {
leaf.tile.clip.mask = mask;
leaf.tile.clip.reference = count++ << bit_offset;
}

View File

@@ -8,11 +8,12 @@ namespace mapbox {
const std::string mapbox = "mapbox://";
std::string normalizeURL(const std::string& url, const std::string& accessToken) {
std::string normalizeURL(const std::string& url, const std::string& pathPrefix, const std::string& accessToken) {
if (accessToken.empty())
throw std::runtime_error("You must provide a Mapbox API access token for Mapbox tile sources");
return std::string("https://api.tiles.mapbox.com/v4/")
return std::string("https://api.tiles.mapbox.com")
+ pathPrefix
+ url.substr(mapbox.length())
+ "?access_token="
+ accessToken;
@@ -22,7 +23,7 @@ std::string normalizeSourceURL(const std::string& url, const std::string& access
if (url.compare(0, mapbox.length(), mapbox) != 0)
return url;
std::string result = normalizeURL(url + ".json", accessToken);
std::string result = normalizeURL(url + ".json", "/v4/", accessToken);
// TileJSON requests need a secure flag appended to their URLs so
// that the server knows to send SSL-ified resource references.
@@ -31,11 +32,20 @@ std::string normalizeSourceURL(const std::string& url, const std::string& access
return result;
}
std::string normalizeStyleURL(const std::string& url, const std::string& accessToken) {
if (url.compare(0, mapbox.length(), mapbox) != 0)
return url;
const std::string user = url.substr(mapbox.length(), url.find('.') - mapbox.length());
return normalizeURL(url, "/styles/v1/" + user + "/", accessToken);
}
std::string normalizeGlyphsURL(const std::string& url, const std::string& accessToken) {
if (url.compare(0, mapbox.length(), mapbox) != 0)
return url;
return normalizeURL(url, accessToken);
return normalizeURL(url, "/v4/", accessToken);
}
std::string normalizeTileURL(const std::string& url, const std::string& sourceURL, SourceType sourceType) {

View File

@@ -9,6 +9,7 @@ namespace util {
namespace mapbox {
std::string normalizeSourceURL(const std::string& url, const std::string& accessToken);
std::string normalizeStyleURL(const std::string& url, const std::string& accessToken);
std::string normalizeGlyphsURL(const std::string& url, const std::string& accessToken);
std::string normalizeTileURL(const std::string& url, const std::string& sourceURL, SourceType sourceType);

View File

@@ -1,13 +1,16 @@
#include "merge_lines.hpp"
#include <sstream>
#include <boost/functional/hash.hpp>
namespace mbgl {
namespace util {
using Index = std::map<size_t, unsigned int>;
unsigned int mergeFromRight(std::vector<SymbolFeature> &features,
std::map<std::string, unsigned int> &rightIndex,
std::map<std::string, unsigned int>::iterator left,
std::string &rightKey,
Index &rightIndex,
Index::iterator left,
size_t rightKey,
std::vector<std::vector<Coordinate>> &geom) {
unsigned int index = left->second;
@@ -21,9 +24,9 @@ unsigned int mergeFromRight(std::vector<SymbolFeature> &features,
}
unsigned int mergeFromLeft(std::vector<SymbolFeature> &features,
std::map<std::string, unsigned int> &leftIndex,
std::string &leftKey,
std::map<std::string, unsigned int>::iterator right,
Index &leftIndex,
size_t leftKey,
Index::iterator right,
std::vector<std::vector<Coordinate>> &geom) {
unsigned int index = right->second;
@@ -37,21 +40,20 @@ unsigned int mergeFromLeft(std::vector<SymbolFeature> &features,
return index;
}
std::string
getKey(const std::u32string &text, const std::vector<std::vector<Coordinate>> &geom, bool onRight) {
const Coordinate &coord = onRight ? geom[0].back() : geom[0].front();
std::ostringstream key;
for (const char32_t &c : text) {
key << (char)c;
}
key << ":" << coord.x << ":" << coord.y;
return key.str();
size_t
getKey(const std::u32string& text, const std::vector<std::vector<Coordinate>>& geom, bool onRight) {
const Coordinate& coord = onRight ? geom[0].back() : geom[0].front();
auto hash = std::hash<std::u32string>()(text);
boost::hash_combine(hash, coord.x);
boost::hash_combine(hash, coord.y);
return hash;
}
void mergeLines(std::vector<SymbolFeature> &features) {
std::map<std::string, unsigned int> leftIndex;
std::map<std::string, unsigned int> rightIndex;
Index leftIndex;
Index rightIndex;
for (unsigned int k = 0; k < features.size(); k++) {
SymbolFeature &feature = features[k];
@@ -61,11 +63,11 @@ void mergeLines(std::vector<SymbolFeature> &features) {
continue;
}
std::string leftKey = getKey(feature.label, geometry, false);
std::string rightKey = getKey(feature.label, geometry, true);
const auto leftKey = getKey(feature.label, geometry, false);
const auto rightKey = getKey(feature.label, geometry, true);
auto left = rightIndex.find(leftKey);
auto right = leftIndex.find(rightKey);
const auto left = rightIndex.find(leftKey);
const auto right = leftIndex.find(rightKey);
if ((left != rightIndex.end()) && (right != leftIndex.end()) &&
(left->second != right->second)) {

View File

@@ -49,38 +49,39 @@ namespace util {
void bilinearScale(const uint32_t* srcData, const vec2<uint32_t>& srcSize,
const Rect<uint32_t>& srcPos, uint32_t* dstData, const vec2<uint32_t>& dstSize,
const Rect<uint32_t>& dstPos) {
const Rect<uint32_t>& dstPos, bool wrap) {
const auto factor = getFactor(srcPos, dstPos);
const auto bounds = getBounds(srcSize, srcPos, dstSize, dstPos, factor);
double fractSrcY = srcPos.y;
double fractSrcX;
uint32_t x, y;
size_t i = dstSize.x * dstPos.y + dstPos.x;
for (y = 0; y < bounds.y; y++) {
fractSrcX = srcPos.x;
const uint32_t srcY0 = fractSrcY;
const uint32_t srcY1 = std::min(srcY0 + 1, srcSize.y - 1);
const double fractY = y * factor.y;
const uint32_t Y0 = fractY;
const uint32_t Y1 = wrap ? (Y0 + 1) % srcPos.h : (Y0 + 1);
const uint32_t srcY0 = srcPos.y + Y0;
const uint32_t srcY1 = std::min(srcPos.y + Y1, srcSize.y - 1);
for (x = 0; x < bounds.x; x++) {
const uint32_t srcX0 = fractSrcX;
const uint32_t srcX1 = std::min(srcX0 + 1, srcSize.x - 1);
const double fractX = x * factor.x;
const uint32_t X0 = fractX;
const uint32_t X1 = wrap ? (X0 + 1) % srcPos.w : (X0 + 1);
const uint32_t srcX0 = srcPos.x + X0;
const uint32_t srcX1 = std::min(srcPos.x + X1, srcSize.x - 1);
const uint32_t tl = srcData[srcSize.x * srcY0 + srcX0];
const uint32_t tr = srcData[srcSize.x * srcY0 + srcX1];
const uint32_t bl = srcData[srcSize.x * srcY1 + srcX0];
const uint32_t br = srcData[srcSize.x * srcY1 + srcX1];
const double dx = fractSrcX - srcX0;
const double dy = fractSrcY - srcY0;
const double dx = fractX - X0;
const double dy = fractY - Y0;
uint32_t& dst = dstData[i + x];
b<0>(dst) = bilinearInterpolate(b<0>(tl), b<0>(tr), b<0>(bl), b<0>(br), dx, dy);
b<1>(dst) = bilinearInterpolate(b<1>(tl), b<1>(tr), b<1>(bl), b<1>(br), dx, dy);
b<2>(dst) = bilinearInterpolate(b<2>(tl), b<2>(tr), b<2>(bl), b<2>(br), dx, dy);
b<3>(dst) = bilinearInterpolate(b<3>(tl), b<3>(tr), b<3>(bl), b<3>(br), dx, dy);
fractSrcX += factor.x;
}
i += dstSize.x;
fractSrcY += factor.y;
}
}
@@ -108,4 +109,4 @@ void nearestNeighborScale(const uint32_t* srcData, const vec2<uint32_t>& srcSize
}
}
}
}

View File

@@ -12,7 +12,7 @@ namespace util {
void bilinearScale(const uint32_t* srcData, const vec2<uint32_t>& srcSize,
const Rect<uint32_t>& srcPos, uint32_t* dstData, const vec2<uint32_t>& dstSize,
const Rect<uint32_t>& dstPos);
const Rect<uint32_t>& dstPos, bool wrap);
void nearestNeighborScale(const uint32_t* srcData, const vec2<uint32_t>& srcSize,
const Rect<uint32_t>& srcPos, uint32_t* dstData,

View File

@@ -28,7 +28,7 @@ bool FixtureLogObserver::onRecord(EventSeverity severity, Event event, int64_t c
size_t FixtureLogObserver::count(const LogMessage &message) const {
size_t message_count = 0;
for (const LogMessage &msg : messages) {
for (const auto& msg : messages) {
if (msg == message) {
message_count++;
msg.checked = true;
@@ -39,7 +39,7 @@ size_t FixtureLogObserver::count(const LogMessage &message) const {
std::vector<FixtureLogObserver::LogMessage> FixtureLogObserver::unchecked() const {
std::vector<LogMessage> unchecked_messages;
for (const LogMessage &msg : messages) {
for (const auto& msg : messages) {
if (!msg.checked) {
unchecked_messages.push_back(msg);
msg.checked = true;
@@ -50,7 +50,7 @@ std::vector<FixtureLogObserver::LogMessage> FixtureLogObserver::unchecked() cons
::std::ostream &operator<<(::std::ostream &os,
const std::vector<FixtureLogObserver::LogMessage> &messages) {
for (const FixtureLogObserver::LogMessage &message : messages) {
for (const auto& message : messages) {
os << "- " << message;
}
return os;

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.9 KiB

After

Width:  |  Height:  |  Size: 8.9 KiB

View File

@@ -28,19 +28,19 @@ TEST(Bilinear, Scaling) {
uint32_t *dstData = dst.get();
std::fill(dstData, dstData + dstSize.x * dstSize.y, 0xFFFF00FF);
util::bilinearScale(srcData, srcSize, { 0, 0, 24, 24 }, dstData, dstSize, { 8, 8, 24, 24 });
util::bilinearScale(srcData, srcSize, { 26, 0, 24, 24 }, dstData, dstSize, { 0, 40, 48, 48 });
util::bilinearScale(srcData, srcSize, { 26, 26, 24, 24 }, dstData, dstSize, { 52, 40, 36, 36 });
util::bilinearScale(srcData, srcSize, { 26, 26, 24, 24 }, dstData, dstSize, { 52, 40, 36, 36 });
util::bilinearScale(srcData, srcSize, { 104, 0, 24, 24 }, dstData, dstSize, { 96, 0, 48, 48 });
util::bilinearScale(srcData, srcSize, { 52, 260, 24, 24 }, dstData, dstSize, { 108, 108, 38, 38 });
util::bilinearScale(srcData, srcSize, { 380, 0, 24, 24 }, dstData, dstSize, { 36, 0, 24, 24 });
util::bilinearScale(srcData, srcSize, { 396, 396, 24, 24 }, dstData, dstSize, { 0, 0, 50, 50 });
util::bilinearScale(srcData, srcSize, { 380, 182, 12, 12 }, dstData, dstSize, { 52, 80, 24, 24 });
util::bilinearScale(srcData, srcSize, { 0, 0, 24, 24 }, dstData, dstSize, { 8, 8, 24, 24 }, false);
util::bilinearScale(srcData, srcSize, { 26, 0, 24, 24 }, dstData, dstSize, { 0, 40, 48, 48 }, false);
util::bilinearScale(srcData, srcSize, { 26, 26, 24, 24 }, dstData, dstSize, { 52, 40, 36, 36 }, false);
util::bilinearScale(srcData, srcSize, { 26, 26, 24, 24 }, dstData, dstSize, { 52, 40, 36, 36 }, false);
util::bilinearScale(srcData, srcSize, { 104, 0, 24, 24 }, dstData, dstSize, { 96, 0, 48, 48 }, false);
util::bilinearScale(srcData, srcSize, { 52, 260, 24, 24 }, dstData, dstSize, { 108, 108, 38, 38 }, false);
util::bilinearScale(srcData, srcSize, { 380, 0, 24, 24 }, dstData, dstSize, { 36, 0, 24, 24 }, false);
util::bilinearScale(srcData, srcSize, { 396, 396, 24, 24 }, dstData, dstSize, { 0, 0, 50, 50 }, false);
util::bilinearScale(srcData, srcSize, { 380, 182, 12, 12 }, dstData, dstSize, { 52, 80, 24, 24 }, false);
// From the bottom
util::bilinearScale(srcData, srcSize, { 252, 380, 12, 12 }, dstData, dstSize, { 0, 90, 12, 12 });
util::bilinearScale(srcData, srcSize, { 252, 380, 12, 12 }, dstData, dstSize, { 18, 90, 24, 24 });
util::bilinearScale(srcData, srcSize, { 252, 380, 12, 12 }, dstData, dstSize, { 0, 90, 12, 12 }, false);
util::bilinearScale(srcData, srcSize, { 252, 380, 12, 12 }, dstData, dstSize, { 18, 90, 24, 24 }, false);
const std::string data { reinterpret_cast<char *>(dstData), dstSize.x * dstSize.y * sizeof(uint32_t) };
util::write_file("test/fixtures/sprites/atlas_actual.png", util::compress_png(dstSize.x, dstSize.y, dstData));

View File

@@ -18,6 +18,11 @@ TEST(Mapbox, GlyphsURL) {
EXPECT_EQ(mbgl::util::mapbox::normalizeGlyphsURL("http://path", "key"), "http://path");
}
TEST(Mapbox, StyleURL) {
EXPECT_EQ(mbgl::util::mapbox::normalizeStyleURL("mapbox://user.style", "key"), "https://api.tiles.mapbox.com/styles/v1/user/user.style?access_token=key");
EXPECT_EQ(mbgl::util::mapbox::normalizeStyleURL("http://path", "key"), "http://path");
}
TEST(Mapbox, TileURL) {
try {
EXPECT_EQ(mbgl::util::mapbox::normalizeTileURL("http://path.png/tile.png", "mapbox://user.map", SourceType::Raster), "http://path.png/tile{ratio}.png");