diff --git a/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClient.cs b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClient.cs new file mode 100644 index 000000000..c3a07405d --- /dev/null +++ b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClient.cs @@ -0,0 +1,93 @@ + + +namespace Mapbox.Experimental.Platform +{ + + using System; + using System.Net; + using System.Net.Http; + using System.Threading; + + + public interface IMapboxHttpClient : IDisposable + { + HttpClient HttpClient { get; } + string BaseUrl { get; set; } + IMapboxHttpRequest Request(string url); + + bool IsDisposed { get; } + } + + + public class MapboxHttpClient : IMapboxHttpClient, IDisposable + { + + private readonly Lazy _client; + + public MapboxHttpClient(string baseUrl = null) + { + + UnityEngine.Debug.LogWarning("MAPBOX_EXPERIMENTAL TODO: add proxy - settings??"); + + BaseUrl = baseUrl; + + // DIRTY HACK! to get around missing Mono certificates: + // System.Net.WebException: Error: SecureChannelFailure (The authentication or decryption has failed.) ---> System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed. + // with newer Mono versions (+3.12.0) that *shouldn't* be necessary anymore: + // http://www.mono-project.com/docs/about-mono/releases/3.12.0/#cert-sync + ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true; + + //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; + var cookies = new CookieContainer(); + + _client = new Lazy(() => + new HttpClient(new HttpClientHandler + { + AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip, + //AutomaticRedirection = true, // not available + CookieContainer = cookies, + + //not implemented?? + //MaxConnectionsPerServer = 2, + + //UseProxy = true, + //Proxy = new WebProxy("192.168.1.125", 8888) + } + ) + { + Timeout = Timeout.InfiniteTimeSpan + }); + + //_client.DefaultRequestHeaders.Add("Accept", "text/html, application/json"); + //_client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"); + //_client.DefaultRequestHeaders.Add("Accept", "text/html, application/json"); + //_client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate"); + + } + + public string BaseUrl { get; set; } + + + public HttpClient HttpClient => _client.Value; + + public IMapboxHttpRequest Request(string url) + { + return new MapboxHttpRequest(url); + } + + + public bool IsDisposed { get; private set; } + + + public virtual void Dispose() + { + if (IsDisposed) { return; } + + //todo for httpmessagehandler + if (_client.IsValueCreated) { _client.Value.Dispose(); } + + IsDisposed = true; + } + + } +} diff --git a/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClient.cs.meta b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClient.cs.meta new file mode 100644 index 000000000..77cab0f88 --- /dev/null +++ b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClient.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 171f2e4a27f0acc44a07b021a6c193d6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClientFactory.cs b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClientFactory.cs new file mode 100644 index 000000000..67af8960b --- /dev/null +++ b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClientFactory.cs @@ -0,0 +1,58 @@ + + +namespace Mapbox.Experimental.Platform +{ + + using System; + using System.Collections.Concurrent; + using System.Net; + using System.Net.Http; + using System.Threading; + + public interface IMapboxHttpClientFactory : IDisposable + { + IMapboxHttpClient Get(string url); + } + + + public class MapboxHttpClientFactory : IMapboxHttpClientFactory + { + + private readonly ConcurrentDictionary _clients = new ConcurrentDictionary(); + + + public IMapboxHttpClient Get(string url) + { + if (string.IsNullOrWhiteSpace(url)) + { + throw new ArgumentNullException("url"); + } + + return + _clients.AddOrUpdate( + getCacheKey(url) + , u => create(u) + , (u, client) => client.IsDisposed ? create(u) : client + ); + } + + + private string getCacheKey(string url) => new Uri(url).Host; + + private IMapboxHttpClient create(string url) => new MapboxHttpClient(); + + + public void Dispose() + { + foreach (var kv in _clients) + { + if (!kv.Value.IsDisposed) + { + kv.Value.Dispose(); + } + } + _clients.Clear(); + } + + } +} diff --git a/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClientFactory.cs.meta b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClientFactory.cs.meta new file mode 100644 index 000000000..b267f748d --- /dev/null +++ b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpClientFactory.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 11cc772e47639784baef14d7dfe26f90 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpRequest.cs b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpRequest.cs new file mode 100644 index 000000000..0ac4efcba --- /dev/null +++ b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpRequest.cs @@ -0,0 +1,133 @@ + + +namespace Mapbox.Experimental.Platform +{ + + using Mapbox.Unity; + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + public interface IMapboxHttpRequest + { + IMapboxHttpClient Client { get; set; } + string Url { get; set; } + HttpMethod Verb { get; } + Task SendAsync( + object id + , HttpMethod verb + , HttpContent content = null + , Dictionary headers = null + , CancellationToken? cancellationToken = null + , HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead + ); + } + + public class MapboxHttpRequest : IMapboxHttpRequest + { + + + private static IMapboxHttpClient _client = null; + private HttpMethod _verb; + + public MapboxHttpRequest(string url) + { + Url = url; + } + + + //_client.DefaultRequestHeaders.Add("Accept", "text/html, application/json"); + //_client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36"); + //_client.DefaultRequestHeaders.Add("Accept", "text/html, application/json"); + //_client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate"); + + + public IMapboxHttpClient Client + { + get + { + return (null != _client) ? Client : + (!string.IsNullOrWhiteSpace(Url)) ? MapboxAccess.Instance.HttpClientFactory.Get(Url) : + null; + } + set { _client = value; } + } + + + public string Url { get; set; } + + + public HttpMethod Verb { get { return _verb; } } + public async Task SendAsync( + object id + , HttpMethod verb + , HttpContent content = null + , Dictionary headers = null + , CancellationToken? cancellationToken = null + , HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead + ) + { + + _verb = verb; + + string accessTokenQuery = $"&access_token={MapboxAccess.Instance.Configuration.AccessToken}"; + UriBuilder uriBuilder = new UriBuilder(Url); + if (!string.IsNullOrWhiteSpace(uriBuilder.Query) && uriBuilder.Query.Length > 1) + { + uriBuilder.Query = $"{uriBuilder.Query.Substring(1)}&{accessTokenQuery}"; + } + else + { + uriBuilder.Query = accessTokenQuery; + } + HttpRequestMessage request = new HttpRequestMessage + { + Method = verb, + Content = content, + RequestUri = uriBuilder.Uri + }; + + if (null != headers) + { + foreach (var hdr in headers) + { + request.Headers.Add(hdr.Key, hdr.Value); + } + } + + + var userToken = cancellationToken ?? CancellationToken.None; + + var cts = CancellationTokenSource.CreateLinkedTokenSource(userToken); + cts.CancelAfter(MapboxAccess.Instance.Configuration.DefaultTimeout * 1000); + var token = cts.Token; + + try + { + using (HttpResponseMessage resp = await Client.HttpClient.SendAsync(request, completionOption, token).ConfigureAwait(false)) + { + return await MapboxHttpResponse.FromWebResponse(this, resp, null); + } + } + catch (Exception ex) + { + UnityEngine.Debug.LogError(ex); + if (ex is OperationCanceledException && !token.IsCancellationRequested) + { + return await MapboxHttpResponse.FromWebResponse(this, null, new TimeoutException()); + } + return await MapboxHttpResponse.FromWebResponse(this, null, ex); + } + + } + + + + + + + + } +} diff --git a/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpRequest.cs.meta b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpRequest.cs.meta new file mode 100644 index 000000000..c04e8cb5a --- /dev/null +++ b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpRequest.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c9297f99faaf1c74081dc271a42f2a09 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpResponse.cs b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpResponse.cs new file mode 100644 index 000000000..5760c5bb4 --- /dev/null +++ b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpResponse.cs @@ -0,0 +1,192 @@ +//----------------------------------------------------------------------- +// +// Copyright (c) 2016 Mapbox. All rights reserved. +// +//----------------------------------------------------------------------- + + +namespace Mapbox.Experimental.Platform +{ + + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Threading.Tasks; + using Utils; + + + + + + /// A response from a request. + public class MapboxHttpResponse + { + + + private MapboxHttpResponse() { } + + + public IMapboxHttpRequest Request { get; private set; } + + + public bool RateLimitHit + { + get { return StatusCode.HasValue ? 429 == StatusCode.Value : false; } + } + + + /// Flag to indicate if the request was successful + public bool HasError + { + get { return _exceptions == null ? false : _exceptions.Count > 0; } + } + + /// Flag to indicate if the request was fullfilled from a local cache + public bool LoadedFromCache; + + /// Flag to indicate if the request was issued before but was issued again and updated + public bool IsUpdate = false; + + public string RequestUrl; + + + public int? StatusCode; + + + public string ContentType; + + + /// Length of rate-limiting interval in seconds. https://www.mapbox.com/api-documentation/#rate-limits + public int? XRateLimitInterval; + + + /// Maximum number of requests you may make in the current interval before reaching the limit. https://www.mapbox.com/api-documentation/#rate-limits + public long? XRateLimitLimit; + + + /// Timestamp of when the current interval will end and the ratelimit counter is reset. https://www.mapbox.com/api-documentation/#rate-limits + public DateTime? XRateLimitReset; + + + private List _exceptions; + /// Exceptions that might have occured during the request. + public ReadOnlyCollection Exceptions + { + get { return null == _exceptions ? null : _exceptions.AsReadOnly(); } + } + + + /// Messages of exceptions otherwise empty string. + public string ExceptionsAsString + { + get + { + if (null == _exceptions || _exceptions.Count == 0) { return string.Empty; } + return string.Join(Environment.NewLine, _exceptions.Select(e => e.Message).ToArray()); + } + } + + + /// Headers of the response. + public Dictionary Headers; + + + /// Raw data fetched from the request. + public byte[] Data; + + public void AddException(Exception ex) + { + if (null == _exceptions) { _exceptions = new List(); } + _exceptions.Add(ex); + } + + // TODO: we should store timestamp of the cache! + public static MapboxHttpResponse FromCache(byte[] data) + { + MapboxHttpResponse response = new MapboxHttpResponse(); + response.Data = data; + response.LoadedFromCache = true; + return response; + } + + + public static async Task FromWebResponse(IMapboxHttpRequest request, HttpResponseMessage apiResponse, Exception apiEx) + { + + MapboxHttpResponse response = new MapboxHttpResponse(); + response.Request = request; + + if (null != apiEx) + { + response.AddException(apiEx); + } + + // timeout: API response is null + if (null == apiResponse) + { + response.AddException(new Exception("No Reponse.")); + } + else + { + // https://www.mapbox.com/api-documentation/#rate-limits + if (null != apiResponse.Headers) + { + response.Headers = new Dictionary(); + foreach (var hdr in apiResponse.Headers) + { + string key = hdr.Key; + string val = hdr.Value.FirstOrDefault(); + response.Headers.Add(key, val); + if (key.Equals("X-Rate-Limit-Interval", StringComparison.OrdinalIgnoreCase)) + { + int limitInterval; + if (int.TryParse(val, out limitInterval)) { response.XRateLimitInterval = limitInterval; } + } + else if (key.Equals("X-Rate-Limit-Limit", StringComparison.OrdinalIgnoreCase)) + { + long limitLimit; + if (long.TryParse(val, out limitLimit)) { response.XRateLimitLimit = limitLimit; } + } + else if (key.Equals("X-Rate-Limit-Reset", StringComparison.OrdinalIgnoreCase)) + { + double unixTimestamp; + if (double.TryParse(val, out unixTimestamp)) + { + DateTime beginningOfTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); + response.XRateLimitReset = beginningOfTime.AddSeconds(unixTimestamp).ToLocalTime(); + } + } + else if (key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase)) + { + response.ContentType = val; + } + } + } + + if (apiResponse.StatusCode != HttpStatusCode.OK) + { + response.AddException(new Exception(string.Format("{0}: {1}", apiResponse.StatusCode, apiResponse.ReasonPhrase))); + } + int statusCode = (int)apiResponse.StatusCode; + response.StatusCode = statusCode; + if (429 == statusCode) + { + response.AddException(new Exception("Rate limit hit")); + } + + if (null != apiResponse) + { + response.Data = await apiResponse.Content.ReadAsByteArrayAsync(); + } + } + + return response; + } + + + } +} diff --git a/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpResponse.cs.meta b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpResponse.cs.meta new file mode 100644 index 000000000..a304c33a2 --- /dev/null +++ b/sdkproject/Assets/Mapbox/Core/mapbox-sdk-cs/Platform/MapboxHttpResponse.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f1667732b5c4c0468ee40a4acbe655c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/sdkproject/Assets/Mapbox/Unity/Location/LocationProviderFactory.cs b/sdkproject/Assets/Mapbox/Unity/Location/LocationProviderFactory.cs index 3809ea3b1..10bcb1f8c 100644 --- a/sdkproject/Assets/Mapbox/Unity/Location/LocationProviderFactory.cs +++ b/sdkproject/Assets/Mapbox/Unity/Location/LocationProviderFactory.cs @@ -4,9 +4,9 @@ namespace Mapbox.Unity.Location { - using UnityEngine; using Mapbox.Unity.Map; using System.Text.RegularExpressions; + using UnityEngine; /// /// Singleton factory to allow easy access to various LocationProviders. @@ -19,20 +19,20 @@ public class LocationProviderFactory : MonoBehaviour [SerializeField] [Tooltip("Provider using Unity's builtin 'Input.Location' service")] - AbstractLocationProvider _deviceLocationProviderUnity; + private AbstractLocationProvider _deviceLocationProviderUnity; [SerializeField] [Tooltip("Custom native Android location provider. If this is not set above provider is used")] - DeviceLocationProviderAndroidNative _deviceLocationProviderAndroid; + private DeviceLocationProviderAndroidNative _deviceLocationProviderAndroid; [SerializeField] - AbstractLocationProvider _editorLocationProvider; + private AbstractLocationProvider _editorLocationProvider; [SerializeField] - AbstractLocationProvider _transformLocationProvider; + private AbstractLocationProvider _transformLocationProvider; [SerializeField] - bool _dontDestroyOnLoad; + private bool _dontDestroyOnLoad; /// @@ -52,7 +52,7 @@ private set } } - ILocationProvider _defaultLocationProvider; + private ILocationProvider _defaultLocationProvider; /// /// The default location provider. @@ -142,8 +142,12 @@ protected virtual void Awake() /// Depending on the platform, this method and calls to it will be stripped during compile. /// [System.Diagnostics.Conditional("UNITY_EDITOR")] - void InjectEditorLocationProvider() + private void InjectEditorLocationProvider() { + if (null == _editorLocationProvider) + { + throw new System.Exception("Editor Location Provider not set"); + } Debug.LogFormat("LocationProviderFactory: Injected EDITOR Location Provider - {0}", _editorLocationProvider.GetType()); DefaultLocationProvider = _editorLocationProvider; } @@ -153,7 +157,7 @@ void InjectEditorLocationProvider() /// Depending on the platform, this method and calls to it will be stripped during compile. /// [System.Diagnostics.Conditional("NOT_UNITY_EDITOR")] - void InjectDeviceLocationProvider() + private void InjectDeviceLocationProvider() { int AndroidApiVersion = 0; var regex = new Regex(@"(?<=API-)-?\d+"); diff --git a/sdkproject/Assets/Mapbox/Unity/MapboxAccess.cs b/sdkproject/Assets/Mapbox/Unity/MapboxAccess.cs index 34dfb44dc..c2c33e719 100644 --- a/sdkproject/Assets/Mapbox/Unity/MapboxAccess.cs +++ b/sdkproject/Assets/Mapbox/Unity/MapboxAccess.cs @@ -1,3 +1,4 @@ +#if !MAPBOX_EXPERIMENTAL namespace Mapbox.Unity { using UnityEngine; @@ -333,3 +334,4 @@ public class MapboxConfiguration public bool AutoRefreshCache = false; } } +#endif diff --git a/sdkproject/Assets/Mapbox/Unity/MapboxAccessExperimental.cs b/sdkproject/Assets/Mapbox/Unity/MapboxAccessExperimental.cs new file mode 100644 index 000000000..22294cec1 --- /dev/null +++ b/sdkproject/Assets/Mapbox/Unity/MapboxAccessExperimental.cs @@ -0,0 +1,348 @@ +#if MAPBOX_EXPERIMENTAL +namespace Mapbox.Unity +{ + using UnityEngine; + using System; + using System.IO; + using Mapbox.Geocoding; + using Mapbox.Directions; + using Mapbox.Platform; + using Mapbox.Platform.Cache; + using Mapbox.Unity.Telemetry; + using Mapbox.Map; + using Mapbox.MapMatching; + using Mapbox.Tokens; + using Mapbox.Platform.TilesetTileJSON; + using Mapbox.Experimental.Platform; + using System.Threading.Tasks; + + /// + /// Object for retrieving an API token and making http requests. + /// Contains a lazy Geocoder and a lazy Directions for convenience. + /// + public class MapboxAccess : IFileSource + { + ITelemetryLibrary _telemetryLibrary; + CachingWebFileSource _fileSource; + + public delegate void TokenValidationEvent(MapboxTokenStatus response); + public event TokenValidationEvent OnTokenValidation; + + private static MapboxAccess _instance; + + /// + /// The singleton instance. + /// + public static MapboxAccess Instance + { + get + { + if (_instance == null) + { + _instance = new MapboxAccess(); + } + return _instance; + } + } + + + public MapboxHttpClientFactory HttpClientFactory = new MapboxHttpClientFactory(); + public static bool Configured; + public static string ConfigurationJSON; + private MapboxConfiguration _configuration; + private string _tokenNotSetErrorMessage = "No configuration file found! Configure your access token from the Mapbox > Setup menu."; + + /// + /// The Mapbox API access token. + /// + public MapboxConfiguration Configuration + { + get + { + return _configuration; + } + } + + MapboxAccess() + { +#if MAPBOX_EXPERIMENTAL && !NET_STANDARD_2_0 + throw new NotSupportedException("Api Compatibility Level has to be set to: '.NET Standard 2.0'"); +#endif + LoadAccessToken(); + if (null == _configuration || string.IsNullOrEmpty(_configuration.AccessToken)) + { + Debug.LogError(_tokenNotSetErrorMessage); + } + } + + public void SetConfiguration(MapboxConfiguration configuration, bool throwExecptions = true) + { + if (configuration == null) + { + if (throwExecptions) + { + throw new InvalidTokenException(_tokenNotSetErrorMessage); + } + + } + + if (null == configuration || string.IsNullOrEmpty(configuration.AccessToken)) + { + Debug.LogError(_tokenNotSetErrorMessage); + } + else + { + TokenValidator.Retrieve(configuration.AccessToken, (response) => + { + if (OnTokenValidation != null) + { + OnTokenValidation(response.Status); + } + + if (response.Status != MapboxTokenStatus.TokenValid + && throwExecptions) + { + configuration.AccessToken = string.Empty; + Debug.LogError(new InvalidTokenException(response.Status.ToString().ToString())); + } + }); + + _configuration = configuration; + + ConfigureFileSource(); + ConfigureTelemetry(); + + Configured = true; + } + } + + + public void ClearAllCacheFiles() + { + // explicity call Clear() to close any connections that might be referenced by the current scene + CachingWebFileSource cwfs = _fileSource as CachingWebFileSource; + if (null != cwfs) { cwfs.Clear(); } + + // remove all left over files (eg orphaned .journal) from the cache directory + string cacheDirectory = Path.Combine(Application.persistentDataPath, "cache"); + if (!Directory.Exists(cacheDirectory)) { return; } + + foreach (var file in Directory.GetFiles(cacheDirectory)) + { + try + { + File.Delete(file); + } + catch (Exception deleteEx) + { + Debug.LogErrorFormat("Could not delete [{0}]: {1}", file, deleteEx); + } + } + + //reinit caches after clear + if (null != cwfs) { cwfs.ReInit(); } + + Debug.Log("done clearing caches"); + } + + /// + /// Loads the access token from Resources folder. + /// + private void LoadAccessToken() + { + + if (string.IsNullOrEmpty(ConfigurationJSON)) + { + TextAsset configurationTextAsset = Resources.Load(Mapbox.Unity.Constants.Path.MAPBOX_RESOURCES_RELATIVE); + if (null == configurationTextAsset) + { + throw new InvalidTokenException(_tokenNotSetErrorMessage); + } + ConfigurationJSON = configurationTextAsset.text; + } + +#if !WINDOWS_UWP + SetConfiguration(ConfigurationJSON == null ? null : JsonUtility.FromJson(ConfigurationJSON)); +#else + SetConfiguration(ConfigurationJSON == null ? null : Mapbox.Json.JsonConvert.DeserializeObject(ConfigurationJSON)); +#endif + } + + + void ConfigureFileSource() + { + _fileSource = new CachingWebFileSource(_configuration.AccessToken, _configuration.AutoRefreshCache) + .AddCache(new MemoryCache(_configuration.MemoryCacheSize)) +#if !UNITY_WEBGL + .AddCache(new SQLiteCache(_configuration.FileCacheSize)) +#endif + ; + } + + + void ConfigureTelemetry() + { + // TODO: enable after token validation has been made async + //if ( + // null == _configuration + // || string.IsNullOrEmpty(_configuration.AccessToken) + // || !_tokenValid + //) + //{ + // Debug.LogError(_tokenNotSetErrorMessage); + // return; + //} + try + { + _telemetryLibrary = TelemetryFactory.GetTelemetryInstance(); + _telemetryLibrary.Initialize(_configuration.AccessToken); + _telemetryLibrary.SetLocationCollectionState(GetTelemetryCollectionState()); + _telemetryLibrary.SendTurnstile(); + } + catch (Exception ex) + { + Debug.LogErrorFormat("Error initializing telemetry: {0}", ex); + } + } + + public void SetLocationCollectionState(bool enable) + { + PlayerPrefs.SetInt(Mapbox.Unity.Constants.Path.SHOULD_COLLECT_LOCATION_KEY, (enable ? 1 : 0)); + PlayerPrefs.Save(); + _telemetryLibrary.SetLocationCollectionState(enable); + } + + bool GetTelemetryCollectionState() + { + if (!PlayerPrefs.HasKey(Mapbox.Unity.Constants.Path.SHOULD_COLLECT_LOCATION_KEY)) + { + PlayerPrefs.SetInt(Mapbox.Unity.Constants.Path.SHOULD_COLLECT_LOCATION_KEY, 1); + } + return PlayerPrefs.GetInt(Mapbox.Unity.Constants.Path.SHOULD_COLLECT_LOCATION_KEY) != 0; + } + + /// + /// Makes an asynchronous url query. + /// + /// The request. + /// URL. + /// Callback. + public IAsyncRequest Request( + string url + , Action callback + , int timeout = 10 + , CanonicalTileId tileId = new CanonicalTileId() + , string mapId = null + ) + { + return _fileSource.Request(url, callback, _configuration.DefaultTimeout, tileId, mapId); + } + + + public IMapboxHttpRequest RequestNew(string url) + { + return new MapboxHttpRequest(url); + } + + Geocoder _geocoder; + /// + /// Lazy geocoder. + /// + public Geocoder Geocoder + { + get + { + if (_geocoder == null) + { + _geocoder = new Geocoder(new FileSource(_configuration.AccessToken)); + } + return _geocoder; + } + } + + + Directions _directions; + /// + /// Lazy Directions. + /// + public Directions Directions + { + get + { + if (_directions == null) + { + _directions = new Directions(new FileSource(_configuration.AccessToken)); + } + return _directions; + } + } + + MapMatcher _mapMatcher; + /// + /// Lazy Map Matcher. + /// + public MapMatcher MapMatcher + { + get + { + if (_mapMatcher == null) + { + _mapMatcher = new MapMatcher(new FileSource(_configuration.AccessToken), _configuration.DefaultTimeout); + } + return _mapMatcher; + } + } + + + MapboxTokenApi _tokenValidator; + /// + /// Lazy token validator. + /// + public MapboxTokenApi TokenValidator + { + get + { + if (_tokenValidator == null) + { + _tokenValidator = new MapboxTokenApi(); + } + return _tokenValidator; + } + } + + + TileJSON _tileJson; + /// + /// Lazy TileJSON wrapper: https://www.mapbox.com/api-documentation/#retrieve-tilejson-metadata + /// + public TileJSON TileJSON + { + get + { + if (_tileJson == null) + { + _tileJson = new TileJSON(new FileSource(_configuration.AccessToken), _configuration.DefaultTimeout); + } + return _tileJson; + } + } + + + class InvalidTokenException : Exception + { + public InvalidTokenException(string message) : base(message) + { + } + } + } + + public class MapboxConfiguration + { + public string AccessToken; + public uint MemoryCacheSize = 500; + public uint FileCacheSize = 2500; + public int DefaultTimeout = 30; + public bool AutoRefreshCache = false; + } +} +#endif diff --git a/sdkproject/Assets/Mapbox/Unity/MapboxAccessExperimental.cs.meta b/sdkproject/Assets/Mapbox/Unity/MapboxAccessExperimental.cs.meta new file mode 100644 index 000000000..b815c4809 --- /dev/null +++ b/sdkproject/Assets/Mapbox/Unity/MapboxAccessExperimental.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a1c6add7831b00641b0088a18a36513b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/sdkproject/Assets/Resources.meta b/sdkproject/Assets/Resources.meta index 3543acb15..141b42bc4 100644 --- a/sdkproject/Assets/Resources.meta +++ b/sdkproject/Assets/Resources.meta @@ -1,8 +1,6 @@ fileFormatVersion: 2 -guid: 6c7f7345a2ce049d9b39d8ee2f388854 +guid: 9050eda1e5d529649b61b7be59cbbde8 folderAsset: yes -timeCreated: 1522933685 -licenseType: Pro DefaultImporter: externalObjects: {} userData: diff --git a/sdkproject/ProjectSettings/PresetManager.asset b/sdkproject/ProjectSettings/PresetManager.asset new file mode 100644 index 000000000..636a595b3 --- /dev/null +++ b/sdkproject/ProjectSettings/PresetManager.asset @@ -0,0 +1,6 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!1386491679 &1 +PresetManager: + m_ObjectHideFlags: 0 + m_DefaultList: [] diff --git a/sdkproject/ProjectSettings/ProjectSettings.asset b/sdkproject/ProjectSettings/ProjectSettings.asset index efdc8531c..8789f0b18 100644 --- a/sdkproject/ProjectSettings/ProjectSettings.asset +++ b/sdkproject/ProjectSettings/ProjectSettings.asset @@ -3,10 +3,11 @@ --- !u!129 &1 PlayerSettings: m_ObjectHideFlags: 0 - serializedVersion: 14 + serializedVersion: 15 productGUID: ca1e7757fee7043e7acc315135f2969e AndroidProfiler: 0 AndroidFilterTouchesWhenObscured: 0 + AndroidEnableSustainedPerformanceMode: 0 defaultScreenOrientation: 4 targetDevice: 0 useOnDemandResources: 0 @@ -64,7 +65,6 @@ PlayerSettings: preserveFramebufferAlpha: 0 disableDepthAndStencilBuffers: 0 androidBlitType: 0 - defaultIsFullScreen: 1 defaultIsNativeResolution: 1 macRetinaSupport: 1 runInBackground: 1 @@ -91,8 +91,7 @@ PlayerSettings: visibleInBackground: 0 allowFullscreenSwitch: 1 graphicsJobMode: 0 - macFullscreenMode: 2 - d3d11FullscreenMode: 1 + fullscreenMode: 1 xboxSpeechDB: 0 xboxEnableHeadOrientation: 0 xboxEnableGuest: 0 @@ -108,18 +107,10 @@ PlayerSettings: xboxOneLoggingLevel: 1 xboxOneDisableEsram: 0 xboxOnePresentImmediateThreshold: 0 + switchQueueCommandMemory: 0 videoMemoryForVertexBuffers: 0 psp2PowerMode: 0 psp2AcquireBGM: 1 - wiiUTVResolution: 0 - wiiUGamePadMSAA: 1 - wiiUSupportsNunchuk: 0 - wiiUSupportsClassicController: 0 - wiiUSupportsBalanceBoard: 0 - wiiUSupportsMotionPlus: 0 - wiiUSupportsProController: 0 - wiiUAllowScreenCapture: 1 - wiiUControllerCount: 0 m_SupportedAspectRatios: 4:3: 1 5:4: 1 @@ -147,6 +138,7 @@ PlayerSettings: hololens: depthFormat: 1 depthBufferSharingEnabled: 0 + enable360StereoCapture: 0 oculus: sharedDepthBuffer: 0 dashSupport: 0 @@ -179,9 +171,7 @@ PlayerSettings: APKExpansionFiles: 0 keepLoadedShadersAlive: 0 StripUnusedMeshComponents: 0 - VertexChannelCompressionMask: - serializedVersion: 2 - m_Bits: 238 + VertexChannelCompressionMask: 214 iPhoneSdkVersion: 988 iOSTargetOSVersionString: 11.2 tvOSSdkVersion: 0 @@ -244,9 +234,15 @@ PlayerSettings: appleDeveloperTeamID: iOSManualSigningProvisioningProfileID: tvOSManualSigningProvisioningProfileID: + iOSManualSigningProvisioningProfileType: 0 + tvOSManualSigningProvisioningProfileType: 0 appleEnableAutomaticSigning: 0 + iOSRequireARKit: 0 + appleEnableProMotion: 0 clonedFromGUID: 00000000000000000000000000000000 - AndroidTargetDevice: 0 + templatePackageId: + templateDefaultScene: + AndroidTargetArchitectures: 5 AndroidSplashScreenScale: 0 androidSplashScreen: {fileID: 0} AndroidKeystoreName: @@ -270,6 +266,7 @@ PlayerSettings: m_Width: 128 m_Height: 128 m_Kind: 45287 + m_BuildTargetPlatformIcons: [] m_BuildTargetBatching: - m_BuildTarget: iPhone m_StaticBatching: 0 @@ -348,25 +345,8 @@ PlayerSettings: m_EncodingQuality: 1 - m_BuildTarget: PS4 m_EncodingQuality: 1 - wiiUTitleID: 0005000011000000 - wiiUGroupID: 00010000 - wiiUCommonSaveSize: 4096 - wiiUAccountSaveSize: 2048 - wiiUOlvAccessKey: 0 - wiiUTinCode: 0 - wiiUJoinGameId: 0 - wiiUJoinGameModeMask: 0000000000000000 - wiiUCommonBossSize: 0 - wiiUAccountBossSize: 0 - wiiUAddOnUniqueIDs: [] - wiiUMainThreadStackSize: 3072 - wiiULoaderThreadStackSize: 1024 - wiiUSystemHeapSize: 128 - wiiUTVStartupScreen: {fileID: 0} - wiiUGamePadStartupScreen: {fileID: 0} - wiiUDrcBufferDisabled: 0 - wiiUProfilerLibPath: playModeTestRunnerEnabled: 1 + runPlayModeTestAsEditModeTest: 0 actionOnDotNetUnhandledException: 1 enableInternalProfiler: 0 logObjCUncaughtExceptions: 1 @@ -487,6 +467,7 @@ PlayerSettings: switchAllowsRuntimeAddOnContentInstall: 0 switchDataLossConfirmation: 0 switchSupportedNpadStyles: 3 + switchNativeFsCacheSize: 32 switchSocketConfigEnabled: 0 switchTcpInitialSendBufferSize: 32 switchTcpInitialReceiveBufferSize: 64 @@ -542,6 +523,7 @@ PlayerSettings: ps4pnFriends: 1 ps4pnGameCustomData: 1 playerPrefsSupport: 0 + enableApplicationExit: 0 restrictedAudioUsageRights: 0 ps4UseResolutionFallback: 0 ps4ReprojectionSupport: 0 @@ -612,7 +594,6 @@ PlayerSettings: psp2InfoBarOnStartup: 0 psp2InfoBarColor: 0 psp2ScriptOptimizationLevel: 0 - psmSplashimage: {fileID: 0} splashScreenBackgroundSourceLandscape: {fileID: 0} splashScreenBackgroundSourcePortrait: {fileID: 0} spritePackerPolicy: DefaultPackerPolicy @@ -626,10 +607,10 @@ PlayerSettings: webGLTemplate: APPLICATION:Default webGLAnalyzeBuildSize: 0 webGLUseEmbeddedResources: 0 - webGLUseWasm: 0 webGLCompressionFormat: 1 + webGLLinkerTarget: 0 scriptingDefineSymbols: - 1: CROSS_PLATFORM_INPUT + 1: CROSS_PLATFORM_INPUT;MAPBOX_EXPERIMENTAL 4: CROSS_PLATFORM_INPUT;MOBILE_INPUT 7: CROSS_PLATFORM_INPUT;MOBILE_INPUT 14: MOBILE_INPUT @@ -641,10 +622,13 @@ PlayerSettings: Standalone: 0 WebGL: 1 iOS: 1 + il2cppCompilerConfiguration: {} incrementalIl2cppBuild: {} + allowUnsafeCode: 0 additionalIl2CppArgs: - scriptingRuntimeVersion: 0 - apiCompatibilityLevelPerPlatform: {} + scriptingRuntimeVersion: 1 + apiCompatibilityLevelPerPlatform: + Standalone: 6 m_RenderingPath: 1 m_MobileRenderingPath: 1 metroPackageName: sdkproject @@ -714,6 +698,7 @@ PlayerSettings: XboxOneSplashScreen: {fileID: 0} XboxOneAllowedProductIds: [] XboxOnePersistentLocalStorageSize: 0 + XboxOneXTitleMemory: 8 xboxOneScriptCompiler: 0 vrEditorSettings: daydream: @@ -730,7 +715,7 @@ PlayerSettings: UNet: 0 Unity_Ads: 0 facebookSdkVersion: 7.9.4 - apiCompatibilityLevel: 2 + apiCompatibilityLevel: 3 cloudProjectId: f183eef4-72bf-420c-80e0-aaadeab22f30 projectName: Mapbox Unity SDK organizationId: mapbox-inc diff --git a/sdkproject/ProjectSettings/ProjectVersion.txt b/sdkproject/ProjectSettings/ProjectVersion.txt index 3c3649262..29eae9e06 100644 --- a/sdkproject/ProjectSettings/ProjectVersion.txt +++ b/sdkproject/ProjectSettings/ProjectVersion.txt @@ -1 +1 @@ -m_EditorVersion: 2017.4.2f2 +m_EditorVersion: 2018.1.6f1 diff --git a/sdkproject/UnityPackageManager/manifest.json b/sdkproject/UnityPackageManager/manifest.json deleted file mode 100644 index 526aca605..000000000 --- a/sdkproject/UnityPackageManager/manifest.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "dependencies": { - } -}