Skip to content
Open
Show file tree
Hide file tree
Changes from 13 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
78 changes: 26 additions & 52 deletions Mapify/Locale.cs
Original file line number Diff line number Diff line change
@@ -1,74 +1,48 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using I2.Loc;
using Mapify.Utils;
using DVLangHelper.Data;
using DVLangHelper.Runtime;
using UnityModManagerNet;

namespace Mapify
{
public static class Locale
{
private const string DEFAULT_LANGUAGE = "English";
private const string MISSING_TRANSLATION = "[ MISSING TRANSLATION ]";
public const string PREFIX = "mapify/";
public const string STATION_PREFIX = PREFIX + "station/";
public const string SESSION__MAP_SELECTOR = PREFIX + "session/map_selector";
public const string LAUNCHER__SESSION_MAP = PREFIX + "launcher/session_map";
public const string LAUNCHER__SESSION_MAP_NOT_INSTALLED = PREFIX + "launcher/session_map_not_installed";
public const string LOADING__PLEASE_WAIT = PREFIX + "loading/please_wait";
public const string LOADING__LOADING_MAP = PREFIX + "loading/loading_map";
private static readonly char[] PREFIX_CHARS = PREFIX.ToCharArray();
private const string LOCALE_FILE = "locale.csv";
// copied from DV.Localization.LocalizationAPI.Sanitized
public const string MISSING_TRANSLATION = "[ MISSING TRANSLATION ]";

private static bool initializeAttempted;
private static ReadOnlyDictionary<string, Dictionary<string, string>> csv;
public const string SESSION__MAP_SELECTOR = "session/map_selector";
public const string LAUNCHER__SESSION_MAP = "launcher/session_map";
public const string LAUNCHER__SESSION_MAP_NOT_INSTALLED = "launcher/session_map_not_installed";
public const string LOADING__PLEASE_WAIT = "loading/please_wait";
public const string LOADING__LOADING_MAP = "loading/loading_map";

public static bool Load(string localeFilePath)
private static TranslationInjector translationsInjector;

public static bool Setup()
{
initializeAttempted = true;
if (!File.Exists(localeFilePath))
return false;
csv = CSV.Parse(File.ReadAllText(localeFilePath));
return true;
translationsInjector = new TranslationInjector(Mapify.ModEntry.Info.Id);
return Reset();
}

public static string Get(string key)
public static bool Reset()
{
if (!initializeAttempted)
throw new InvalidOperationException("Not initialized");
translationsInjector.ResetData();
var localeFilePath = Path.Combine(Mapify.ModEntry.Path, LOCALE_FILE);

string locale = LocalizationManager.CurrentLanguage;

if (!csv.ContainsKey(locale))
if (!File.Exists(localeFilePath))
{
if (locale == DEFAULT_LANGUAGE)
{
Mapify.LogError($"Failed to find locale language {locale}! Something is broken, this shouldn't happen. Dumping CSV data:");
Mapify.LogError($"\n{CSV.Dump(csv)}");
return MISSING_TRANSLATION;
}

locale = DEFAULT_LANGUAGE;
Mapify.LogWarning($"Failed to find locale language {locale}");
}

Dictionary<string, string> localeDict = csv[locale];

if (localeDict.TryGetValue(key.TrimStart(PREFIX_CHARS), out string value)) {
return value;
}

// If there is no translation for this station's name, don't translate it.
if (key.StartsWith(STATION_PREFIX)) {
return key.Replace(STATION_PREFIX, "");;
Mapify.LogError($"Failed to find locale file at {localeFilePath}! Please make sure it's there.");
return false;
}

return MISSING_TRANSLATION;
translationsInjector.AddTranslationsFromCsv(localeFilePath);
return true;
}

public static string Get(string key, params object[] placeholders)
public static void AddTranslation(string key, DVLanguage translationSetLanguage, string translationSetTranslation)
{
return string.Format(Get(key), placeholders);
translationsInjector.AddTranslation(key, translationSetLanguage, translationSetTranslation);
}
}
}
6 changes: 4 additions & 2 deletions Mapify/Map/MapLifeCycle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Linq;
using System.Text.RegularExpressions;
using DV.CashRegister;
using DV.Localization;
using DV.Utils;
using Mapify.Editor;
using Mapify.Editor.Utils;
Expand Down Expand Up @@ -44,15 +45,15 @@ public static IEnumerator LoadMap(BasicMapInfo basicMapInfo)
WorldStreamingInit wsi = SingletonBehaviour<WorldStreamingInit>.Instance;
DisplayLoadingInfo loadingInfo = Object.FindObjectOfType<DisplayLoadingInfo>();

string loadingMapLogMsg = Locale.Get(Locale.LOADING__LOADING_MAP, basicMapInfo.name);
string loadingMapLogMsg = LocalizationAPI.L(Locale.LOADING__LOADING_MAP, basicMapInfo.name);
loadingInfo.UpdateLoadingStatus(loadingMapLogMsg, 0);
yield return null;

// Load asset bundles
loadedAssetBundles = new List<AssetBundle>();
string mapDir = Maps.GetDirectory(basicMapInfo);

// Register mapinfo
string mapDir = Maps.GetDirectory(basicMapInfo);
Mapify.LogDebug(() => $"Loading AssetBundle '{Names.MAP_INFO_ASSET_BUNDLE}'");
AssetBundleCreateRequest mapInfoRequest = AssetBundle.LoadFromFileAsync(Maps.GetMapAsset(Names.MAP_INFO_ASSET_BUNDLE, mapDir));
do
Expand Down Expand Up @@ -336,6 +337,7 @@ private static void InitializeLists()

private static void Cleanup()
{
Locale.Reset();
WorldMapSetup.Cleanup();
StreamedObjectInitPatch.ResetStreamers();
Maps.UnregisterLoadedMap();
Expand Down
29 changes: 15 additions & 14 deletions Mapify/Mapify.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
using System;
using System.IO;
using DV.UI;
using HarmonyLib;
using Mapify.Map;
using Mapify.Patches;
using UnityModManagerNet;
using Object = UnityEngine.Object;

namespace Mapify
{
public static class Mapify
{
private static UnityModManager.ModEntry ModEntry { get; set; }
public static UnityModManager.ModEntry ModEntry { get; private set; }
private static Settings Settings;
private const string LOCALE_FILE = "locale.csv";

internal static Harmony Harmony { get; private set; }

Expand All @@ -27,7 +22,10 @@ private static bool Load(UnityModManager.ModEntry modEntry)

try
{
LoadLocale();
if (!Locale.Setup())
{
return false;
}
Maps.Init();
Patch();
}
Expand All @@ -40,13 +38,6 @@ private static bool Load(UnityModManager.ModEntry modEntry)
return true;
}

private static void LoadLocale()
{
string localePath = Path.Combine(ModEntry.Path, LOCALE_FILE);
if (!Locale.Load(localePath))
LogError($"Failed to find locale file at {localePath}! Please make sure it's there.");
}

private static void Patch()
{
Log("Patching...");
Expand All @@ -63,12 +54,22 @@ public static void LogDebugExtreme(Func<object> resolver)
LogDebug(resolver);
}

public static void LogDebugExtreme(object msg)
{
LogDebugExtreme(() => msg);
}

public static void LogDebug(Func<object> resolver)
{
if (Settings.VerboseLogging)
ModEntry.Logger.Log($"[Debug] {resolver.Invoke()}");
}

public static void LogDebug(object msg)
{
LogDebug(() => msg);
}

public static void Log(object msg)
{
ModEntry.Logger.Log($"[Info] {msg}");
Expand Down
7 changes: 7 additions & 0 deletions Mapify/Mapify.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<Publicize Include="DV.UI" IncludeCompilerGeneratedMembers="false" />
<Publicize Include="DV.TerrainSystem" IncludeCompilerGeneratedMembers="false" />
<Publicize Include="DV.RailTrack" IncludeCompilerGeneratedMembers="false" />
<Publicize Include="DVLangHelper.Data" />
</ItemGroup>

<!-- Derail Valley -->
Expand Down Expand Up @@ -49,6 +50,12 @@
<PackageReference Include="UnityModManager" Version="0.27.2" />
</ItemGroup>

<!-- DV mods -->
<ItemGroup>
<Reference Include="DVLangHelper.Data" />
<Reference Include="DVLangHelper.Runtime" />
</ItemGroup>

<!-- Third-party -->
<ItemGroup>
<Reference Include="AwesomeTechnologies.VegetationStudioPro.Runtime" />
Expand Down
3 changes: 2 additions & 1 deletion Mapify/Patches/DisplayLoadingInfoPatch.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using DV.Localization;
using HarmonyLib;

namespace Mapify.Patches
Expand Down Expand Up @@ -44,7 +45,7 @@ private static bool Prefix(DisplayLoadingInfo __instance, string message, bool i
}

string formattedWhat = string.IsNullOrWhiteSpace(what) ? "" : $" {what}";
__instance.percentageLoadedTMP.text = Locale.Get(Locale.LOADING__PLEASE_WAIT, formattedWhat, percentageLoaded.ToString("F0"));
__instance.percentageLoadedTMP.text = LocalizationAPI.L(Locale.LOADING__PLEASE_WAIT, formattedWhat, percentageLoaded.ToString("F0"));

if (!Bootstrap.bootstrapped)
return false;
Expand Down
3 changes: 2 additions & 1 deletion Mapify/Patches/LauncherControllerPatch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using DV.Common;
using DV.Localization;
using DV.UI;
using DV.UI.PresetEditors;
using DV.UIFramework;
Expand Down Expand Up @@ -71,7 +72,7 @@ private static bool Prefix(LauncherController __instance, ISaveGame ___saveGame)
Popup okPopupPrefab = __instance.GetComponentInParent<InitialScreenController>().continueLoadNewController.career.okPopupPrefab;

Popup popup = popupManager.ShowPopup(okPopupPrefab);
popup.labelTMPro.text = Locale.Get(Locale.LAUNCHER__SESSION_MAP_NOT_INSTALLED, basicMapInfo.name);
popup.labelTMPro.text = LocalizationAPI.L(Locale.LAUNCHER__SESSION_MAP_NOT_INSTALLED, basicMapInfo.name);
return false;
}
}
Expand Down
18 changes: 0 additions & 18 deletions Mapify/Patches/LocalizationManagerPatch.cs

This file was deleted.

17 changes: 15 additions & 2 deletions Mapify/SceneInitializers/GameContent/StationSetup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ public override void Run()
GameObject stationObject = station.gameObject;
StationController stationController = stationObject.GetComponent<StationController>();

// Station info
stationController.stationInfo = new StationInfo(station.stationName, " ", station.stationID, station.color, Locale.STATION_PREFIX+station.stationName);
SetupStationInfo(station, stationController);

// Station tracks
stationController.storageRailtracksGONames = station.storageTrackNames;
Expand All @@ -51,6 +50,20 @@ public override void Run()
SingletonBehaviour<LogicController>.Instance.gameObject.SetActive(true);
}

private void SetupStationInfo(Station station, StationController stationController)
{
var locaKey = station.GetStationLocalizationKey();
stationController.stationInfo = new StationInfo(station.stationName, " ", station.stationID, station.color, locaKey);

var mbs = station.GetComponents<TranslationSetBehaviour>();
station.stationNameTranslations = mbs.Take(station.stationNameTranslationsCount).Select(mb => mb.ToOriginal()).ToList();

foreach (var translationSet in station.stationNameTranslations)
{
Locale.AddTranslation(locaKey, translationSet.language, translationSet.translation);
}
}

private static void SetupJobBookletSpawnSurface(Station station, StationController stationController)
{
PointOnPlane jobBookletSpawnSurface = station.transform.parent.GetComponentInChildren<PointOnPlane>();
Expand Down
11 changes: 6 additions & 5 deletions Mapify/SceneInitializers/GameContent/WorldMapSetup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,12 @@ private static void UpdateMapOverview(Transform transform)
name.FindChildByName("Color").GetComponent<Image>().color = station.color;
name.FindChildByName("IndustryCode").GetComponent<TMP_Text>().text = station.stationID;
name.FindChildByName("OriginalName").GetComponent<TMP_Text>().text = station.stationName;
GameObject localizedName = name.FindChildByName("LocalizedName");
localizedName.GetComponent<TMP_Text>().text = station.stationName;
foreach (Localize i2Localize in localizedName.GetComponents<Localize>())
GameObject localizedNameObject = name.FindChildByName("LocalizedName");
localizedNameObject.GetComponent<TMP_Text>().text = station.GetLocalizedStationName();

foreach (Localize i2Localize in localizedNameObject.GetComponents<Localize>())
Object.DestroyImmediate(i2Localize);
Object.DestroyImmediate(localizedName.GetComponent<DV.Localization.Localize>());
Object.DestroyImmediate(localizedNameObject.GetComponent<DV.Localization.Localize>());
}

Object.Destroy(listItemPrefab.gameObject);
Expand Down Expand Up @@ -128,7 +129,7 @@ private static void ShowNamesOnMap(Transform mapTransform)
TMP_Text tmp = name.GetComponent<TMP_Text>();
tmp.rectTransform.localPosition = station.YardCenter.position.ToXZ().Scale(0, Maps.LoadedMap.worldSize, -0.175f, 0.175f);

tmp.text = ShowStationNamesOnMap ? station.stationName : station.stationID;
tmp.text = ShowStationNamesOnMap ? station.GetLocalizedStationName() : station.stationID;
}

Object.Destroy(namePrefab);
Expand Down
5 changes: 4 additions & 1 deletion Mapify/Utils/CSVParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,16 @@ public static ReadOnlyDictionary<string, Dictionary<string, string>> Parse(strin

List<string> keys = ParseLine(lines[0]);
foreach (string key in keys)
{
if(key == "") continue;
columns.Add(key, new Dictionary<string, string>());
}

for (int i = 1; i < lines.Length; i++)
{
string line = lines[i];
List<string> values = ParseLine(line);
if (values.Count == 0)
if (values.Count == 0 || values[0] == "")
continue;
string key = values[0];
for (int j = 0; j < values.Count; j++)
Expand Down
13 changes: 13 additions & 0 deletions Mapify/Utils/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using CommandTerminal;
using DV;
using DV.JObjectExtstensions;
using DV.Localization;
using DV.PointSet;
using DV.ThingTypes;
using HarmonyLib;
Expand Down Expand Up @@ -291,6 +292,18 @@ public static GameObject Replace(this VanillaObject vanillaObject, bool active =
return vanillaObject.gameObject.Replace(AssetCopier.Instantiate(vanillaObject.asset, active, originShift), preserveTypes, vanillaObject.keepChildren, vanillaObject.rotationOffset);
}

public static string GetLocalizedStationName(this Station station)
{
var localized = LocalizationAPI.L(station.GetStationLocalizationKey());
//if there is no translation, don't translate
return localized == Locale.MISSING_TRANSLATION ? station.stationName : localized;
}

public static string GetStationLocalizationKey(this Station station)
{
return "station/" + station.stationID;
}

#endregion
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,13 @@ protected override void Update(Scenes scenes)
station.outputCargoGroups.ForEach(set => set.ToMonoBehaviour(station.gameObject));

#endregion

#region Translations

station.stationNameTranslationsCount = station.stationNameTranslations.Count;
station.stationNameTranslations.ForEach(set => set.ToMonoBehaviour(station.gameObject));

#endregion
}
}

Expand Down
Loading