Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
308 changes: 308 additions & 0 deletions src/OrthoStreamXP/Configuration/CustomMapSources.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,308 @@
using System.Globalization;
using System.Text;
using OrthoGlobalXP.Geo;
using OrthoGlobalXP.Regions;
using OrthoStreamXP.Textures;

namespace OrthoStreamXP;

/// <summary>A user-defined XYZ or Quadkey tile source stored in orthostreamxp.ini.</summary>
internal sealed record CustomMapSource(string Name, string UrlTemplate);

/// <summary>A regional override mapping a Natural Earth region's 1x1 degree tiles to specific providers.</summary>
internal sealed record RegionalOverride(Region Region, string Providers, IReadOnlySet<TileCoordinate> Tiles);

/// <summary>
/// A prioritised hybrid map layer: a named set of 1x1 degree tiles (from Natural Earth, manual painting, or both)
/// routed to specific imagery providers, with a display colour and visibility toggle for the Hybrid Map Editor.
/// </summary>
internal sealed record HybridLayer(
string Name,
string ColorHex,
bool IsVisible,
string Providers,
IReadOnlySet<TileCoordinate> Tiles,
Region? SourceRegion = null);

/// <summary>Parses, validates and formats custom-sources and regional-providers in orthostreamxp.ini.</summary>
internal static class CustomMapSources
{
public const string SourcesKey = "custom-sources";
public const string OverridesKey = "regional-providers";

public static readonly string[] DefaultPalette =
[
"#F58231", // Orange
"#00B4D8", // Cyan
"#2FA36B", // Green
"#9D4EDD", // Purple
"#E6399B", // Pink
"#E9C46A", // Gold
"#3D8BFD", // Blue
"#E05252", // Coral Red
];

private static readonly char[] ForbiddenNameChars = ['|', ';', ','];
private static readonly char[] ForbiddenUrlChars = ['|', ';'];

/// <summary>Returns an error message if the custom source name or URL template is invalid; null when valid.</summary>
public static string? ValidateSource(string name, string urlTemplate)
{
string trimmedName = name.Trim();
if (trimmedName.Length == 0) return "Enter a name for this map source.";
if (trimmedName.Length > 40) return "The source name must be 40 characters or fewer.";
if (trimmedName.IndexOfAny(ForbiddenNameChars) >= 0) return "The source name cannot contain commas, pipes (|) or semicolons (;).";
if (ImageryProvider.BuiltIn.ContainsKey(trimmedName) || trimmedName.Equals(ImageryProvider.Synthetic, StringComparison.OrdinalIgnoreCase))
return $"'{trimmedName}' is already a built-in provider name.";

string trimmedUrl = urlTemplate.Trim();
if (trimmedUrl.Length == 0) return "Enter a tile URL template.";
if (trimmedUrl.IndexOfAny(ForbiddenUrlChars) >= 0) return "The URL template cannot contain pipes (|) or semicolons (;).";
if (!trimmedUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !trimmedUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
return "The URL template must start with http:// or https://.";

bool hasQuadkey = trimmedUrl.Contains("{q}", StringComparison.OrdinalIgnoreCase);
bool hasXyz = trimmedUrl.Contains("{z}", StringComparison.OrdinalIgnoreCase)
&& trimmedUrl.Contains("{x}", StringComparison.OrdinalIgnoreCase)
&& trimmedUrl.Contains("{y}", StringComparison.OrdinalIgnoreCase);
if (!hasQuadkey && !hasXyz)
return "The URL template must include {z}, {x} and {y} placeholders (or {q} for quadkey).";

return null;
}

public static string SanitizeLayerName(string name)
{
string clean = name.Replace('|', ' ').Replace(';', ' ').Trim();
return clean.Length == 0 ? "Custom Layer" : clean;
}

public static IReadOnlyList<CustomMapSource> ParseSources(string? raw)
{
if (string.IsNullOrWhiteSpace(raw)) return [];
var list = new List<CustomMapSource>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

foreach (string entry in raw.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
int sep = entry.IndexOf('|', StringComparison.Ordinal);
if (sep <= 0 || sep == entry.Length - 1)
throw new SettingsException($"Invalid entry in {SourcesKey}: '{entry}'. Expected 'Name|UrlTemplate'.");

string name = entry[..sep].Trim();
string url = entry[(sep + 1)..].Trim();
if (ValidateSource(name, url) is { } error)
throw new SettingsException($"Invalid {SourcesKey} entry '{name}': {error}");
if (!seen.Add(name))
throw new SettingsException($"Duplicate custom map source name '{name}' in {SourcesKey}.");

list.Add(new CustomMapSource(name, url));
}
return list;
}

public static string FormatSources(IEnumerable<CustomMapSource> sources) =>
string.Join(";", sources.Select(s => $"{s.Name.Trim()}|{s.UrlTemplate.Trim()}"));

public static IReadOnlyDictionary<string, string> ToLookup(IEnumerable<CustomMapSource> sources)
{
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (CustomMapSource source in sources)
map[source.Name.Trim()] = source.UrlTemplate.Trim();
return map;
}

public static IReadOnlyList<RegionalOverride> ParseOverrides(string? raw, IReadOnlyList<Region>? catalog = null)
{
if (string.IsNullOrWhiteSpace(raw)) return [];
IReadOnlyList<Region> regions = catalog ?? RegionCatalog.All;
var list = new List<RegionalOverride>();

foreach (string entry in raw.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
string[] parts = entry.Split('|');
if (parts.Length != 4)
throw new SettingsException($"Invalid entry in {OverridesKey}: '{entry}'. Expected 'Kind|Name|Parent|Providers'.");

if (!Enum.TryParse(parts[0].Trim(), ignoreCase: true, out RegionKind kind))
throw new SettingsException($"Unknown region kind '{parts[0]}' in {OverridesKey}.");

string name = parts[1].Trim();
string parent = parts[2].Trim();
string providers = parts[3].Trim();
if (providers.Length == 0)
throw new SettingsException($"No provider specified for '{name}' in {OverridesKey}.");

Region? region = regions.FirstOrDefault(r =>
r.Kind == kind
&& string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(r.Parent, parent, StringComparison.OrdinalIgnoreCase));

if (region is null)
throw new SettingsException($"Region '{name}' ({kind}) was not found in the Natural Earth catalog.");

list.Add(new RegionalOverride(region, providers, new HashSet<TileCoordinate>(region.Tiles)));
}
return list;
}

public static string FormatOverrides(IEnumerable<RegionalOverride> overrides) =>
string.Join(";", overrides.Select(o =>
string.Create(CultureInfo.InvariantCulture, $"{o.Region.Kind}|{o.Region.Name}|{o.Region.Parent}|{o.Providers.Trim()}")));

/// <summary>
/// Parses both legacy Natural Earth override entries (Kind|Name|Parent|Providers) and full hybrid layers
/// (Layer|Name|ColorHex|Visible|Providers|CompactTiles).
/// </summary>
public static IReadOnlyList<HybridLayer> ParseLayers(string? raw, IReadOnlyList<Region>? catalog = null)
{
if (string.IsNullOrWhiteSpace(raw)) return [];
IReadOnlyList<Region> regions = catalog ?? RegionCatalog.All;
var list = new List<HybridLayer>();
int index = 0;

foreach (string entry in raw.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
string[] parts = entry.Split('|');
if (parts.Length == 6 && parts[0].Trim().Equals("Layer", StringComparison.OrdinalIgnoreCase))
{
string name = SanitizeLayerName(parts[1]);
string color = NormalizeHexColor(parts[2], DefaultPalette[index % DefaultPalette.Length]);
bool visible = parts[3].Trim() != "0";
string providers = parts[4].Trim();
if (providers.Length == 0)
throw new SettingsException($"No provider specified for layer '{name}' in {OverridesKey}.");

HashSet<TileCoordinate> tiles = ParseCompactTiles(parts[5]);
list.Add(new HybridLayer(name, color, visible, providers, tiles));
index++;
continue;
}

if (parts.Length == 4)
{
if (!Enum.TryParse(parts[0].Trim(), ignoreCase: true, out RegionKind kind))
throw new SettingsException($"Unknown region kind '{parts[0]}' in {OverridesKey}.");

string name = parts[1].Trim();
string parent = parts[2].Trim();
string providers = parts[3].Trim();
if (providers.Length == 0)
throw new SettingsException($"No provider specified for '{name}' in {OverridesKey}.");

Region? region = regions.FirstOrDefault(r =>
r.Kind == kind
&& string.Equals(r.Name, name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(r.Parent, parent, StringComparison.OrdinalIgnoreCase));

if (region is null)
throw new SettingsException($"Region '{name}' ({kind}) was not found in the Natural Earth catalog.");

string color = DefaultPalette[index % DefaultPalette.Length];
list.Add(new HybridLayer(region.Name, color, true, providers, new HashSet<TileCoordinate>(region.Tiles), region));
index++;
continue;
}

throw new SettingsException($"Invalid entry in {OverridesKey}: '{entry}'.");
}
return list;
}

public static string FormatLayers(IEnumerable<HybridLayer> layers)
{
var entries = new List<string>();
foreach (HybridLayer layer in layers)
{
string name = SanitizeLayerName(layer.Name);
string color = NormalizeHexColor(layer.ColorHex, DefaultPalette[0]);
string visible = layer.IsVisible ? "1" : "0";
string providers = layer.Providers.Trim();
string tiles = FormatCompactTiles(layer.Tiles);
entries.Add($"Layer|{name}|{color}|{visible}|{providers}|{tiles}");
}
return string.Join(";", entries);
}

public static string FormatCompactTiles(IReadOnlySet<TileCoordinate> tiles)
{
if (tiles.Count == 0) return "";
var byLat = new SortedDictionary<int, List<int>>();
foreach (TileCoordinate t in tiles)
{
if (!byLat.TryGetValue(t.Lat, out List<int>? lons))
{
lons = [];
byLat[t.Lat] = lons;
}
lons.Add(t.Lon);
}

var sb = new StringBuilder();
foreach (var (lat, lons) in byLat)
{
lons.Sort();
int i = 0;
while (i < lons.Count)
{
int start = lons[i];
int end = start;
while (i + 1 < lons.Count && lons[i + 1] == end + 1)
{
i++;
end = lons[i];
}
if (sb.Length > 0) sb.Append(',');
if (start == end)
sb.Append(new TileCoordinate(lat, start).Name);
else
sb.Append(string.Create(CultureInfo.InvariantCulture, $"{lat:+00;-00;+00}{start:+000;-000;+000}..{end:+000;-000;+000}"));
i++;
}
}
return sb.ToString();
}

public static HashSet<TileCoordinate> ParseCompactTiles(string raw)
{
var result = new HashSet<TileCoordinate>();
if (string.IsNullOrWhiteSpace(raw)) return result;

foreach (string token in raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
int dots = token.IndexOf("..", StringComparison.Ordinal);
if (dots < 0)
{
if (!TileCoordinate.TryParse(token, out TileCoordinate single))
throw new SettingsException($"Invalid tile coordinate '{token}' in {OverridesKey}.");
result.Add(single);
continue;
}

if (dots != 7 || token.Length != 13
|| !int.TryParse(token.AsSpan(0, 3), NumberStyles.Integer, CultureInfo.InvariantCulture, out int lat)
|| !int.TryParse(token.AsSpan(3, 4), NumberStyles.Integer, CultureInfo.InvariantCulture, out int lonStart)
|| !int.TryParse(token.AsSpan(9, 4), NumberStyles.Integer, CultureInfo.InvariantCulture, out int lonEnd)
|| lat is < -90 or > 89
|| lonStart is < -180 or > 179
|| lonEnd is < -180 or > 179
|| lonEnd < lonStart)
{
throw new SettingsException($"Invalid tile range '{token}' in {OverridesKey}.");
}

for (int lon = lonStart; lon <= lonEnd; lon++)
result.Add(new TileCoordinate(lat, lon));
}
return result;
}

private static string NormalizeHexColor(string? raw, string fallback)
{
if (string.IsNullOrWhiteSpace(raw)) return fallback;
string trimmed = raw.Trim();
if (trimmed.Length == 7 && trimmed[0] == '#' && int.TryParse(trimmed.AsSpan(1), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _))
return trimmed.ToUpperInvariant();
return fallback;
}
}
37 changes: 32 additions & 5 deletions src/OrthoStreamXP/Configuration/MountSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,12 @@ public static MountSettings FromValues(SettingValues values, bool console = true
if (downloadWorkers < 1) throw new SettingsException("download-workers must be at least 1");
if (downloadTimeout is < 1 or > 120) throw new SettingsException("download-timeout must be between 1 and 120 seconds");
if (downloadAttempts is < 1 or > 10) throw new SettingsException("download-attempts must be between 1 and 10");
IReadOnlyList<ImageryProvider>? providers = provider is null ? null : ParseProviders(provider, values.String("texture-url"));
IReadOnlyList<CustomMapSource> customSources = CustomMapSources.ParseSources(values.String(CustomMapSources.SourcesKey));
IReadOnlyDictionary<string, string> customLookup = CustomMapSources.ToLookup(customSources);
IReadOnlyList<HybridLayer> regionalOverrides = CustomMapSources.ParseLayers(values.String(CustomMapSources.OverridesKey));
IReadOnlyList<ImageryProvider>? providers = provider is null
? null
: BuildProviders(provider, values.String("texture-url"), customLookup, regionalOverrides);
if (encoderWorkers is < 1 or > 16) throw new SettingsException("encoder-workers must be between 1 and 16");
if (ddsBuildWorkers < 1) throw new SettingsException("dds-build-workers must be at least 1");
if (fileSystemThreads is < 2 or > 512) throw new SettingsException("filesystem-threads must be between 2 and 512");
Expand Down Expand Up @@ -292,18 +297,41 @@ internal static IReadOnlyList<PackagePlan> PlanPackages(SettingValues values, st
}

/// <summary>The provider list of texture-provider, with its errors as usage errors.</summary>
public static IReadOnlyList<ImageryProvider> ParseProviders(string list, string? customTemplate)
public static IReadOnlyList<ImageryProvider> ParseProviders(
string list, string? customTemplate, IReadOnlyDictionary<string, string>? customSources = null)
{
try
{
return ImageryProvider.ParseList(list, customTemplate);
return ImageryProvider.ParseList(list, customTemplate, customSources);
}
catch (ArgumentException ex)
{
throw new SettingsException(ex.Message);
}
}

private static IReadOnlyList<ImageryProvider> BuildProviders(
string globalList,
string? customTemplate,
IReadOnlyDictionary<string, string> customLookup,
IReadOnlyList<HybridLayer> overrides)
{
IReadOnlyList<ImageryProvider> globalProviders = ParseProviders(globalList, customTemplate, customLookup);
if (overrides.Count == 0 || globalProviders[0].Name == ImageryProvider.Synthetic)
return globalProviders;

var combined = new List<ImageryProvider>();
foreach (HybridLayer rule in overrides)
{
if (!rule.IsVisible || rule.Tiles.Count == 0) continue;
IReadOnlyList<ImageryProvider> ruleProviders = ParseProviders(rule.Providers, null, customLookup);
foreach (ImageryProvider rp in ruleProviders)
combined.Add(rp with { AllowedTiles = rule.Tiles });
}
combined.AddRange(globalProviders);
return combined;
}

internal static SeasonOptions ParseSeasons(SettingValues values)
{
string onValue = values.String("seasons") ?? "off";
Expand All @@ -316,7 +344,6 @@ internal static SeasonOptions ParseSeasons(SettingValues values)
return new SeasonOptions(on, strength / 100, choice);
}

/// <summary>Dynamic quality's steps, or null when it is off.</summary>
/// <summary>The resolution of the preset the settings are at (resolution-&lt;preset&gt;); Full for a level no preset has.</summary>
private static TextureResolution ParseResolution(SettingValues values, Setup.QualityPreset? preset)
{
Expand Down Expand Up @@ -352,4 +379,4 @@ private static TextureResolution ParseResolution(SettingValues values, Setup.Qua

private static bool SamePath(string a, string b) =>
string.Equals(Path.TrimEndingDirectorySeparator(a), Path.TrimEndingDirectorySeparator(b), StringComparison.OrdinalIgnoreCase);
}
}
4 changes: 3 additions & 1 deletion src/OrthoStreamXP/Configuration/SettingsOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ internal static class SettingsOptions
.Add("lazy-texture-store", "Optional folder of ready-made DDS files (a textures folder's contents), served when no downloaded version is available")
.Add("texture-provider", "Generate missing DDS textures from bing, esri, geoportal (Poland's national orthophoto, asked only for tiles in Poland) or synthetic (or any name with texture-url). Several, comma-separated, are tried in order for each tile: esri,bing")
.Add("texture-url", "XYZ URL template for the provider that is not built in; supports {x}, {y}, {z}, {q}, {s}")
.Add(CustomMapSources.SourcesKey, "User-defined custom map sources as 'Name|UrlTemplate' separated by semicolons (;); each URL supports {x}, {y}, {z}, {q}, {s}")
.Add(CustomMapSources.OverridesKey, "Regional provider overrides (hybrid map) as 'Kind|Name|Parent|Providers' separated by semicolons (;); tried before the global texture-provider")
.Add("download-workers", "Parallel source-image downloads, shared by all DDS builds (default: 8)")
.Add("download-timeout", $"Seconds one tile download attempt may take before it is retried on another server (default: {TileSource.DefaultTimeoutSeconds})")
.Add("download-attempts", $"Tries per tile before its texture fails, 1-10 (default: {TileSource.DefaultAttempts})")
Expand Down Expand Up @@ -76,4 +78,4 @@ private static string ResolutionHelp(string preset) =>
"the wide ZL16 areas (8192 px: 4096) and keeps the airports' ZL18 ones; low halves them all. From the same downloads, for less graphics memory, RAM and disk " +
"(only halving: X-Plane takes no texture whose size is not a power of two). Used while the settings are at that preset; " +
"each resolution keeps its textures in its own cache subfolder (default: full)";
}
}
Loading