Skip to content

Instantly share code, notes, and snippets.

@mihakrajnc
Last active September 19, 2017 00:21
Show Gist options
  • Save mihakrajnc/06c5c6e6fae19acd5af13d63856c16b2 to your computer and use it in GitHub Desktop.
Save mihakrajnc/06c5c6e6fae19acd5af13d63856c16b2 to your computer and use it in GitHub Desktop.
A Mapbox factory that loads map images into Unity UI.
using System;
using Mapbox.Map;
using Mapbox.Unity.MeshGeneration.Data;
using Mapbox.Unity.MeshGeneration.Enums;
using Mapbox.Unity.MeshGeneration.Factories;
using UnityEngine;
using UnityEngine.UI;
[CreateAssetMenu(menuName = "Mapbox/Factories/Custom/UI Map Tile Factory")]
public class UiMapTileFactory : AbstractTileFactory
{
[SerializeField] private string mapId = "";
[SerializeField] private bool useCompression = true;
[SerializeField] private bool useRetina;
[SerializeField] private int unityTileSize = 100; // TODO: This should be automatic
[SerializeField] private float mapScale = 1.0f;
internal override void OnInitialized()
{
}
internal override void OnRegistered(UnityTile tile)
{
// Need to set / reset the scale or the map will be tiny with small zoom levels
tile.Map.Root.localScale = Vector3.one * mapScale;
tile.transform.SetParent(tile.Map.Root, false);
tile.transform.localScale = Vector3.one;
// Assuming that the image is always 512x512 and tile size is 100
tile.transform.localPosition = new Vector3(
Mathf.RoundToInt((float) (tile.Rect.Center.x - tile.Map.CenterMercator.x) *
tile.Map.WorldRelativeScale / unityTileSize * 512),
Mathf.RoundToInt((float) (tile.Rect.Center.y - tile.Map.CenterMercator.y) *
tile.Map.WorldRelativeScale / unityTileSize * 512),
0);
RasterTile rasterTile;
if (mapId.StartsWith("mapbox://", StringComparison.Ordinal))
{
rasterTile = useRetina ? new RetinaRasterTile() : new RasterTile();
}
else
{
rasterTile = useRetina ? new ClassicRetinaRasterTile() : new ClassicRasterTile();
}
tile.RasterDataState = TilePropertyState.Loading;
tile.AddTile(rasterTile);
Progress++;
rasterTile.Initialize(_fileSource, tile.CanonicalTileId, mapId, () =>
{
if (!tile) return;
if (rasterTile.HasError)
{
tile.RasterDataState = TilePropertyState.Error;
Progress--;
return;
}
Texture2D tex = new Texture2D(0, 0, TextureFormat.RGB24, false) {wrapMode = TextureWrapMode.Clamp};
tex.LoadImage(rasterTile.Data);
if (useCompression)
{
tex.Compress(false);
}
// Create an Image component with a sprite.
Image image = tile.gameObject.GetComponent<Image>() ?? tile.gameObject.AddComponent<Image>();
image.sprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f),
100.0f);
image.SetNativeSize();
tile.RasterDataState = TilePropertyState.Loaded;
Progress--;
});
}
internal override void OnUnregistered(UnityTile tile)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment