diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..4d3e7c3 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,50 @@ +root = true + +[*] +charset = utf-8 +insert_final_newline = true +trim_trailing_whitespace = true + +[*.json] +indent_style = tab +tab_width = 4 +indent_size = 4 + +[*.{yml,yaml}] +indent_style = space +indent_size = 2 + +[*.cs] +indent_style = space +tab_width = 4 +indent_size = 4 +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_space_after_cast = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_indent_case_contents = true +csharp_indent_switch_labels = true +csharp_style_var_when_type_is_apparent = true:suggestion +dotnet_style_qualification_for_field = false:warning +dotnet_style_qualification_for_property = false:warning +dotnet_style_qualification_for_method = false:warning +csharp_prefer_braces = when_multiline:suggestion +dotnet_diagnostic.IDE0005.severity = warning +dotnet_diagnostic.CS4014.severity = warning +dotnet_diagnostic.IDE0051.severity = none +dotnet_diagnostic.IDE0060.severity = none +dotnet_diagnostic.CA1707.severity = none +dotnet_diagnostic.CA1051.severity = none +dotnet_diagnostic.CA2211.severity = none +dotnet_diagnostic.CA1805.severity = suggestion +dotnet_diagnostic.CA1716.severity = none +dotnet_diagnostic.CA1708.severity = none +dotnet_diagnostic.CS1591.severity = none +dotnet_diagnostic.CS1573.severity = none + +[tests/**.cs] +dotnet_diagnostic.CA1861.severity = none diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml deleted file mode 100644 index f75f773..0000000 --- a/.github/workflows/installer.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: Installer -on: - push: - paths: - - 'installer/**' - pull_request: - paths: - - 'installer/**' -jobs: - job: - defaults: - run: - working-directory: ./installer - strategy: - fail-fast: false - matrix: - os: [windows-latest, ubuntu-22.04, macos-13] - name: Build on ${{ matrix.os }} - runs-on: ${{ matrix.os }} - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 - with: - python-version: '3.11' - - name: Install requirements - run: pip install -r requirements.txt - - name: Build - run: python build.py - - uses: actions/upload-artifact@v4 - with: - name: ${{ matrix.os }} - path: installer/dist/ - merge: - name: Merge artifacts - runs-on: ubuntu-latest - needs: job - steps: - - uses: actions/upload-artifact/merge@v4 - with: - name: artifacts - delete-merged: true - separate-directories: true - diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..66f37af --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,14 @@ + + + + true + latest + Recommended + true + + + true + $(NoWarn);CS1591 + + + diff --git a/README.md b/README.md index 2772d50..13499c7 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,58 @@ ![](https://img.shields.io/codefactor/grade/github/PolyModdingTeam/PolyMod) ![](https://img.shields.io/github/actions/workflow/status/PolyModdingTeam/PolyMod/cicd.yml) +**The mod loader for The Battle of Polytopia.** + +PolyMod lets you play Polytopia with new tribes, units, buildings, skins and much more, made by the community. Mods are just folders or archives you drop into the game, and PolyMod takes care of the rest. Your vanilla game, saves and settings stay untouched. + | | x86 | ARM | |:-------:|:---:|:---:| | Windows | ✅ | ❌ | | Linux | ⏺️ | ❌ | -| MacOS | ⏺️ | ❌ | +| MacOS | ❌ | ❌ | | Android | ➖ | 🚧 | | IOS | ➖ | ❌ | + +## Features + +- **Play with mods in a few clicks.** Browse and download mods right in the launcher or on our website, then start the game. +- **Keep your vanilla game safe.** Modded games use their own save data. Start the game without the launcher, and you get plain Polytopia. +- **Everything in one place.** The PolyMod Hub shows your mods, their status and config, and opens with **Ctrl + Tab** from anywhere in the game. +- **Made for modders.** Change the game logic with JSON patches, add your own sprites, translations and prefabs, or write code mods in C#. + +## Installation + +1. Download the **PolyMod Launcher** from [polymod.dev/download](https://polymod.dev/download/). +2. Install PolyMod with the launcher. +3. Start Polytopia from the launcher. + +That's it. The PolyMod button on the start screen opens the hub. + +### Installing mods + +The easiest way is to download mods directly in the launcher or on [polymod.dev](https://polymod.dev). + +You can also install a mod by hand: put it into the `Mods` folder next to the game and restart. + +> [!NOTE] +> Modded multiplayer is not supported yet. Weekly challenges and achievements are only available in vanilla Polytopia, so they are turned off while PolyMod is active. + +## Making mods + +Want to make your own tribe, unit or skin? Everything you need is on the [wiki](https://github.com/PolyModdingTeam/PolyMod/wiki), and the community on [Discord](https://discord.gg/eWPdhWtfVy) is always happy to help. + +## Building from source + +You need the [.NET 8 SDK](https://dotnet.microsoft.com/download). + +```bash +git clone https://github.com/PolyModdingTeam/PolyMod.git +cd PolyMod +dotnet build +``` + +Copy `src/bin/IL2CPP/net6.0/PolyMod.dll` into the `BepInEx/plugins` folder of your game. Run `dotnet test` to run the tests. + +## License + +PolyMod is licensed under [CC BY-NC-ND 4.0](LICENSE). diff --git a/installer/build.py b/installer/build.py deleted file mode 100644 index 8b802ae..0000000 --- a/installer/build.py +++ /dev/null @@ -1,19 +0,0 @@ -import os -import PyInstaller.__main__ - -ROOT = os.path.abspath(os.getcwd()) - -PyInstaller.__main__.run( - [ - "--noconfirm", - "--onefile", - "--windowed", - "--icon", - ROOT + "/icon.ico", - "--name", - "PolyMod", - "--add-data", - ROOT + "/icon.ico:.", - ROOT + "/main.py", - ] -) diff --git a/installer/icon.ico b/installer/icon.ico deleted file mode 100644 index f52643a..0000000 Binary files a/installer/icon.ico and /dev/null differ diff --git a/installer/main.py b/installer/main.py deleted file mode 100644 index e1fad1b..0000000 --- a/installer/main.py +++ /dev/null @@ -1,154 +0,0 @@ -import os -import io -import sys -import shutil -import zipfile -import requests -import threading -import subprocess -import customtkinter -import CTkMessagebox as messagebox - -OS = { - "linux": "linux", - "linux2": "linux", - "win32": "win", - "darwin": "macos", -}[sys.platform] -BEPINEX = "https://polymod.dev/data/bepinex.txt" -POLYMOD = "https://api.github.com/repos/PolyModdingTeam/PolyMod/releases" - - -def resource_path(path): - try: - base_path = sys._MEIPASS - except Exception: - base_path = os.path.abspath(".") - return os.path.join(base_path, path) - - -def to_zip(request: requests.Response): - return zipfile.ZipFile(io.BytesIO(request.content)) - - -def browse(): - global path_entry - path_entry.delete(0, customtkinter.END) - path_entry.insert(0, customtkinter.filedialog.askdirectory()) - - -def prepare(target): - global progress_bar - path = path_entry.get() - try: - if "Polytopia_Data" not in os.listdir(path): - raise FileNotFoundError - except FileNotFoundError: - messagebox.CTkMessagebox( - title="Error", - message="The folder does not exist or is not valid!", - icon="cancel", - width=100, - height=50 - ) - return - path_entry.configure(state=customtkinter.DISABLED) - browse_button.configure(state=customtkinter.DISABLED) - prerelease_checkbox.destroy() - install_button.destroy() - uninstall_button.destroy() - progress_bar = customtkinter.CTkProgressBar(app, determinate_speed=50 / 2) - progress_bar.grid(column=0, row=1, columnspan=2, padx=5, pady=5) - progress_bar.set(0) - threading.Thread(target=target, daemon=True, args=(path, )).start() - - -def install(path): - to_zip( - requests.get( - requests.get(BEPINEX).text.strip().replace("{os}", OS) - ) - ).extractall(path) - progress_bar.step() - - for release in requests.get(POLYMOD).json(): - if release["prerelease"] and not prerelease_checkbox.get(): continue - latest = release - break - open(path + "/BepInEx/plugins/PolyMod.dll", "wb").write( - requests.get(latest["assets"][0]["browser_download_url"]).content - ) - progress_bar.step() - - customtkinter.CTkButton(app, text="Launch", command=lambda: launch(path)).grid( - column=0, row=2, columnspan=2, padx=5, pady=5 - ) - - -def uninstall(path): - dirs = [ - "BepInEx", - "dotnet", - ] - files = [ - ".doorstop_version", - "changelog.txt", - "doorstop_config.ini", - "winhttp.dll", # windows - "libdoorstop.so", # linux - "libdoorstop.dylib", # mac - "run_bepinex.sh", # linux + mac - ] - for dir in dirs: - shutil.rmtree(path + "/" + dir, True) - progress_bar.step() - for file in files: - try: - os.remove(path + "/" + file) - except FileNotFoundError: - ... - progress_bar.step() - customtkinter.CTkButton(app, text="Quit", command=quit).grid( - column=0, row=2, columnspan=2, padx=5, pady=5 - ) - - -def launch(path): - if sys.platform != "win32": - subprocess.check_call(f"chmod +x {path}/run_bepinex.sh", shell=True) - subprocess.check_call(f"{path}/run_bepinex.sh {path}/Polytopia.*", shell=True) - subprocess.check_call(f"xdg-open https://docs.bepinex.dev/articles/advanced/steam_interop.html", shell=True) - else: - subprocess.check_call(f"start steam://rungameid/874390", shell=True) - quit() - - -def quit(): - app.destroy() - sys.exit() - - -app = customtkinter.CTk() -app.title("PolyMod") -if OS != "linux": - app.iconbitmap(default=resource_path("icon.ico")) -app.resizable(False, False) - -path_entry = customtkinter.CTkEntry( - app, placeholder_text="Game path", width=228) -browse_button = customtkinter.CTkButton( - app, text="Browse", command=browse, width=1) -prerelease_checkbox = customtkinter.CTkCheckBox( - app, text="Prerelease", width=1) -install_button = customtkinter.CTkButton( - app, text="Install", command=lambda: prepare(install)) -uninstall_button = customtkinter.CTkButton( - app, text="Uninstall", command=lambda: prepare(uninstall)) - -path_entry.grid(column=0, row=0, padx=5, pady=5) -browse_button.grid(column=1, row=0, padx=(0, 5), pady=5) -prerelease_checkbox.grid(column=0, row=1, columnspan=2, padx=5, pady=5) -install_button.grid(column=0, row=2, columnspan=2, padx=5, pady=5) -uninstall_button.grid(column=0, row=3, columnspan=2, padx=5, pady=5) - -app.mainloop() diff --git a/installer/requirements.txt b/installer/requirements.txt deleted file mode 100644 index c396099..0000000 --- a/installer/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -requests -pyinstaller -customtkinter -CTkMessagebox \ No newline at end of file diff --git a/resources/localization.json b/resources/localization.json index 3b19f1e..1010202 100644 --- a/resources/localization.json +++ b/resources/localization.json @@ -43,34 +43,54 @@ "Elyrion": "{0}þr∑∑Ŧ!{1}\niii ŋ∑ƒ ƒ§§π mȱΔ#:", "German (Germany)": "{0} Willkommen! {1}\nDiese Mods sind gerade eben geladen:" }, - "polymod_hub_mod": { - "English": "Name: {0}\nStatus: {1}\nAuthors: {2}\nVersion: {3}\nDescription: {4}", - "Russian": "Имя: {0}\nСтатус: {1}\nАвторы: {2}\nВерсия: {3}\nОписание: {4}", - "Turkish": "İsim: {0}\nDurum: {1}\nYaratıcılar: {2}\nSürüm: {3}", - "Spanish (Mexico)": "Titulo: {0}\nEstado: {1}\nPublicador: {2}\nVersion: {3}", - "French (France)": "Titre: {0}\nEtat: {1}\nAuteurs: {2}\nVersion: {3}", - "Polish": "Nazwa: {0}\nStatus: {1}\nAutorzy: {2}\nWersja: {3}", - "Portuguese (Brazil)": "Nome: {0}\nStatus: {1}\nAutores: {2}\nVersão: {3}", - "Elyrion": "r₼: {0}\n^ŦaŦ₺^: {1}\na₺Ŧţȱr: {2}\nƒƒƒƒƒƒƒ: {3}", - "German (Germany)": "Name: {0}\nStatus: {1}\nAutoren: {2}\nVersion: {3}" - }, "polymod_hub_dump": { "English": "DUMP DATA", "Russian": "ЗАДАМПИТЬ ДАННЫЕ", + "Turkish": "VERİLERİ DIŞA AKTAR", + "Spanish (Mexico)": "VOLCAR DATOS", + "French (France)": "EXTRAIRE LES DONNÉES", + "Polish": "ZRZUĆ DANE", + "Portuguese (Brazil)": "EXTRAIR DADOS", "German (Germany)": "DATENDUMP" }, "polymod_hub_dumped": { - "English": "Dump completed successfully!", - "Russian": "Дамп завершен успешно!", - "German (Germany)": "Dump erfolgreich beendet!" + "English": "Dump completed successfully!\n\n{0}", + "Russian": "Дамп завершен успешно!\n\n{0}", + "Turkish": "Veriler başarıyla dışa aktarıldı!\n\n{0}", + "Spanish (Mexico)": "¡Volcado completado con éxito!\n\n{0}", + "French (France)": "Extraction terminée avec succès!\n\n{0}", + "Polish": "Zrzut zakończony pomyślnie!\n\n{0}", + "Portuguese (Brazil)": "Extração concluída com sucesso!\n\n{0}", + "German (Germany)": "Dump erfolgreich beendet!\n\n{0}" + }, + "polymod_hub_openfolder": { + "English": "OPEN FOLDER", + "Russian": "ОТКРЫТЬ ПАПКУ", + "Turkish": "KLASÖRÜ AÇ", + "Spanish (Mexico)": "ABRIR CARPETA", + "French (France)": "OUVRIR LE DOSSIER", + "Polish": "OTWÓRZ FOLDER", + "Portuguese (Brazil)": "ABRIR PASTA", + "German (Germany)": "ORDNER ÖFFNEN" }, "polymod_cycle": { "English": "Dependency cycle detected", - "Russian": "Обнаружен цикл зависимостей" + "Russian": "Обнаружен цикл зависимостей", + "Turkish": "Bağımlılık döngüsü algılandı", + "Spanish (Mexico)": "Se detectó un ciclo de dependencias", + "French (France)": "Cycle de dépendances détecté", + "Polish": "Wykryto cykl zależności", + "Portuguese (Brazil)": "Ciclo de dependências detectado", + "German (Germany)": "Abhängigkeitszyklus erkannt" }, "polymod_cycle_description": { "English": "Unable to determine mod loading order!", "Russian": "Невозможно определить порядок загрузки модов!", + "Turkish": "Mod yükleme sırası belirlenemedi!", + "Spanish (Mexico)": "¡No se pudo determinar el orden de carga de los mods!", + "French (France)": "Impossible de déterminer l'ordre de chargement des mods!", + "Polish": "Nie można określić kolejności ładowania modów!", + "Portuguese (Brazil)": "Não foi possível determinar a ordem de carregamento dos mods!", "German (Germany)": "Mod - ladereihenfolge konnte nicht bestimmt werden!" }, "polymod_hub_mod_status_error": { @@ -117,17 +137,6 @@ "Elyrion": "#₺rr∑ŋŦ mȱΔ# ₼π₺þþţ∫ ȱriþiŋa∫ mȱΔ#!", "German (Germany)": "Einige aktuelle mods sind nicht mit Älteren kompatibel!" }, - "polymod_signature_maybe_incompatible": { - "English": "Current mods may not be compatible with original mods!", - "Russian": "Текущие моды могут быть несовместимы с оригинальными модами!", - "Turkish": "Mevcut modlar orijinal modlarla uyumlu olmayabilir!", - "Spanish (Mexico)": "Es posible que este mod no sea compatibile con el original!", - "French (France)": "Les mods actuels peuvent ne pas être compatibles avec les mods originaux!", - "Polish": "Obecne mody mogą nie być kompatybilne z oryginalnymi modami!", - "Portuguese (Brazil)": "É possível que os mods carregados não sejam compatíveis com os mods originais", - "Elyrion": "#₺rr∑ŋŦ mȱΔ# maỹ ₼π₺þþţ∫ ȱriþiŋa∫ mȱΔ#!", - "German (Germany)": "Einige aktuelle mods könnten mit Älteren inkompatibel sein!" - }, "polymod_signature_mismatch": { "English": "Signature mismatch", "Russian": "Несоответствие подписи", @@ -172,75 +181,205 @@ "Elyrion": "Δ∑o₺þ", "German (Germany)": "Debuggen" }, - "polymod_autoupdate": { - "English": "Auto-update", - "Russian": "Автообновление", - "Turkish": "Otomatik güncelleme", - "Spanish (Mexico)": "Actualización automática", - "French (France)": "MAJ auto", - "Polish": "Auto aktualizacja", - "Portuguese (Brazil)": "Atualização automática", - "Elyrion": "a₺Ŧȱ₺πΔaŦ∑", - "German (Germany)": "Auto Aktualisierung" - }, - "polymod_autoupdate_alpha": { - "English": "Include alphas", - "Russian": "Включить альфы", - "Elyrion": "iŋ#∫₺Δ∑ a∫πţaȓ" - }, - "polymod_autoupdate_description": { - "English": "New update available!", - "Russian": "Доступно новое обновление!", - "Elyrion": "ŋ∑~ ₺πΔaŦ∑ a‡ai∫ao∫∑" - }, - "polymod_autoupdate_update": { - "English": "Update", - "Russian": "Обновить", - "Elyrion": "₺πΔaŦ∑" - }, "polymod_hub_config": { "English": "CONFIG", "Russian": "КОНФИГ", - "Elyrion": "#ȱŋ₼iþ" - }, - "polymod_hub_config_enable": { - "English": "ENABLE {0}", - "Russian": "ВКЛЮЧИТЬ {0}", - "Elyrion": "∑ŋao∫∑ {0}" - }, - "polymod_hub_config_disable": { - "English": "DISABLE {0}", - "Russian": "ВЫКЛЮЧИТЬ {0}", - "Elyrion": "Δiȓao∫∑ {0}" - }, - "polymod_config_setto": { - "English": "{0} is set to {1}!", - "Russian": "{0} задан на {1}!", - "Elyrion": "{0} iȓ ȓ∑Ŧ Ŧȱ {1}!" - }, - "polymod_hub_spriteinfo_update": { - "English": "UPDATE SPRITES", - "Russian": "ОБНОВИТЬ СПРАЙТЫ", - "Elyrion": "₺πΔaŦ∑ ȓπriŦ∑ȓ" - }, - "polymod_spriteinfo_updated": { - "English": "Sprite info for mod {0} updated!", - "Russian": "Данные спрайтов обновлены для мода {0}!", - "Elyrion": "ȓπriŦ∑ iŋ₼ȱ ₼ȱr mȱΔ {0} ₺πΔaŦ∑Δ!" - }, - "polymod_spriteinfo_notupdated": { - "English": "No sprite infos were found!", - "Russian": "Данные спрайтов не найдены!", - "Elyrion": "ŋȱ ȓπriŦ∑ iŋ₼ȱȓ ~∑r∑ ₼ȱ₺ŋΔ!" - }, - "polymod_wc_warning": { - "English": "{0} may not work correctly due to PolyMod. Do you wish to proceed?", - "Russian": "{0} может работать некорректно из-за PolyMod'а. Вы уверены что хотите продолжить?", - "Elyrion": "{0} maỹ ŋȱŦ ~ȱr§ #ȱrr∑#Ŧ∫ỹ Δ₺∑ Ŧȱ πȱ∫ỹmȱΔ. Δȱ ỹȱ₺ ~iȓţ Ŧȱ πrȱ#∑∑Δ?" - }, - "polymod_wc_proceed": { - "English": "PROCEED", - "Russian": "ПРОДОЛЖИТЬ", - "Elyrion": "πrȱ#∑∑Δ" + "Turkish": "AYARLAR", + "Spanish (Mexico)": "CONFIGURACIÓN", + "French (France)": "CONFIGURATION", + "Polish": "KONFIGURACJA", + "Portuguese (Brazil)": "CONFIGURAÇÕES", + "Elyrion": "#ȱŋ₼iþ", + "German (Germany)": "KONFIGURATION" + }, + "polymod_hub_hotreload": { + "English": "HOT RELOAD", + "Russian": "ГОРЯЧАЯ ПЕРЕЗАГРУЗКА", + "Turkish": "ANINDA YENİDEN YÜKLE", + "Spanish (Mexico)": "RECARGA EN CALIENTE", + "French (France)": "RECHARGEMENT À CHAUD", + "Polish": "PRZEŁADOWANIE NA GORĄCO", + "Portuguese (Brazil)": "RECARGA A QUENTE", + "German (Germany)": "SOFORT NEU LADEN" + }, + "polymod_wc_vanillaonly": { + "English": "{0} is only available in vanilla Polytopia. Disable PolyMod in the launcher, or start the game without the launcher.", + "Russian": "{0} доступен только в ванильной Polytopia. Отключите PolyMod в лаунчере или запустите игру без лаунчера.", + "Turkish": "{0} yalnızca orijinal Polytopia'da kullanılabilir. Başlatıcıda PolyMod'u devre dışı bırak veya oyunu başlatıcı olmadan başlat.", + "Spanish (Mexico)": "{0} solo está disponible en Polytopia sin mods. Desactiva PolyMod en el launcher o inicia el juego sin el launcher.", + "French (France)": "{0} n'est disponible que dans Polytopia sans mods. Désactivez PolyMod dans le launcher ou lancez le jeu sans le launcher.", + "Polish": "{0} jest dostępne tylko w niezmodowanej Polytopii. Wyłącz PolyMod w launcherze lub uruchom grę bez launchera.", + "Portuguese (Brazil)": "{0} só está disponível no Polytopia sem mods. Desative o PolyMod no launcher ou inicie o jogo sem o launcher.", + "German (Germany)": "{0} ist nur im unmodifizierten Polytopia verfügbar. Deaktiviere PolyMod im Launcher oder starte das Spiel ohne den Launcher." + }, + "polymod_achi_vanillaonly": { + "English": "{0} are only available in vanilla Polytopia. Disable PolyMod in the launcher, or start the game without the launcher.", + "Russian": "{0} доступны только в ванильной Polytopia. Отключите PolyMod в лаунчере или запустите игру без лаунчера.", + "Turkish": "{0} yalnızca orijinal Polytopia'da kullanılabilir. Başlatıcıda PolyMod'u devre dışı bırak veya oyunu başlatıcı olmadan başlat.", + "Spanish (Mexico)": "{0} solo están disponibles en Polytopia sin mods. Desactiva PolyMod en el launcher o inicia el juego sin el launcher.", + "French (France)": "{0} ne sont disponibles que dans Polytopia sans mods. Désactivez PolyMod dans le launcher ou lancez le jeu sans le launcher.", + "Polish": "{0} są dostępne tylko w niezmodowanej Polytopii. Wyłącz PolyMod w launcherze lub uruchom grę bez launchera.", + "Portuguese (Brazil)": "{0} só estão disponíveis no Polytopia sem mods. Desative o PolyMod no launcher ou inicie o jogo sem o launcher.", + "German (Germany)": "{0} sind nur im unmodifizierten Polytopia verfügbar. Deaktiviere PolyMod im Launcher oder starte das Spiel ohne den Launcher." + }, + "polymod_title_invalid": { + "English": "Invalid Launch", + "Russian": "Неверный Запуск", + "Turkish": "Geçersiz Başlatma", + "Spanish (Mexico)": "Inicio no válido", + "French (France)": "Lancement invalide", + "Polish": "Nieprawidłowe uruchomienie", + "Portuguese (Brazil)": "Inicialização inválida", + "German (Germany)": "Ungültiger Start" + }, + "polymod_description_invalid": { + "English": "PolyMod launch was invalid. Please, open the game via the PolyMod Launcher or proceed to our site to install it :)", + "Russian": "PolyMod запущен некорректно. Пожалуйста, откройте игру через PolyMod Launcher или перейдите на наш сайт и установите его :)", + "Turkish": "PolyMod geçersiz şekilde başlatıldı. Lütfen oyunu PolyMod Launcher ile aç veya yüklemek için sitemize git :)", + "Spanish (Mexico)": "PolyMod se inició de forma incorrecta. Abre el juego con el PolyMod Launcher o visita nuestro sitio para instalarlo :)", + "French (France)": "PolyMod a été lancé de manière incorrecte. Veuillez ouvrir le jeu via le PolyMod Launcher ou vous rendre sur notre site pour l'installer :)", + "Polish": "PolyMod został uruchomiony nieprawidłowo. Otwórz grę przez PolyMod Launcher lub przejdź na naszą stronę, aby go zainstalować :)", + "Portuguese (Brazil)": "O PolyMod foi iniciado de forma inválida. Abra o jogo pelo PolyMod Launcher ou acesse nosso site para instalá-lo :)", + "German (Germany)": "PolyMod wurde ungültig gestartet. Öffne das Spiel bitte über den PolyMod Launcher oder besuche unsere Website, um ihn zu installieren :)" + }, + "buttons_download_launcher": { + "English": "OUR SITE", + "Russian": "НАШ САЙТ", + "Turkish": "SİTEMİZ", + "Spanish (Mexico)": "NUESTRO SITIO", + "French (France)": "NOTRE SITE", + "Polish": "NASZA STRONA", + "Portuguese (Brazil)": "NOSSO SITE", + "German (Germany)": "UNSERE WEBSITE" + }, + "polymod_hub_summary": { + "English": "{0} of {1} mods loaded.", + "Russian": "Загружено модов: {0} из {1}.", + "Turkish": "{1} moddan {0} tanesi yüklendi.", + "Spanish (Mexico)": "{0} de {1} mods cargados.", + "French (France)": "{0} mods sur {1} chargés.", + "Polish": "Załadowano modów: {0} z {1}.", + "Portuguese (Brazil)": "{0} de {1} mods carregados.", + "German (Germany)": "{0} von {1} Mods geladen." + }, + "polymod_hub_mods_none": { + "English": "No mods are installed yet. Put mod archives into the Mods folder next to the game and restart it.", + "Russian": "Моды пока не установлены. Положите архивы модов в папку Mods рядом с игрой и перезапустите её.", + "Turkish": "Henüz yüklü mod yok. Mod arşivlerini oyunun yanındaki Mods klasörüne koy ve oyunu yeniden başlat.", + "Spanish (Mexico)": "Aún no hay mods instalados. Coloca los archivos de mods en la carpeta Mods junto al juego y reinícialo.", + "French (France)": "Aucun mod n'est encore installé. Placez les archives de mods dans le dossier Mods à côté du jeu, puis redémarrez-le.", + "Polish": "Nie zainstalowano jeszcze żadnych modów. Umieść archiwa modów w folderze Mods obok gry i uruchom ją ponownie.", + "Portuguese (Brazil)": "Nenhum mod instalado ainda. Coloque os arquivos dos mods na pasta Mods ao lado do jogo e reinicie-o.", + "German (Germany)": "Es sind noch keine Mods installiert. Lege Mod-Archive in den Ordner Mods neben dem Spiel und starte es neu." + }, + "polymod_hub_mod_authors": { + "English": "by {0}", + "Russian": "от {0}", + "Turkish": "{0} tarafından", + "Spanish (Mexico)": "por {0}", + "French (France)": "par {0}", + "Polish": "autor: {0}", + "Portuguese (Brazil)": "por {0}", + "German (Germany)": "von {0}" + }, + "polymod_hub_mod_checksum": { + "English": "checksum {0}", + "Russian": "контрольная сумма {0}", + "Turkish": "sağlama toplamı {0}", + "Spanish (Mexico)": "suma de verificación {0}", + "French (France)": "somme de contrôle {0}", + "Polish": "suma kontrolna {0}", + "Portuguese (Brazil)": "soma de verificação {0}", + "German (Germany)": "Prüfsumme {0}" + }, + "polymod_hub_checksum": { + "English": "Global checksum: {0}", + "Russian": "Общая контрольная сумма: {0}", + "Turkish": "Genel sağlama toplamı: {0}", + "Spanish (Mexico)": "Suma de verificación global: {0}", + "French (France)": "Somme de contrôle globale: {0}", + "Polish": "Globalna suma kontrolna: {0}", + "Portuguese (Brazil)": "Soma de verificação global: {0}", + "German (Germany)": "Globale Prüfsumme: {0}" + }, + "polymod_hub_config_debug": { + "English": "DEBUG", + "Russian": "ОТЛАДКА", + "Turkish": "HATA AYIKLAMA", + "Spanish (Mexico)": "DEPURACIÓN", + "French (France)": "DÉBOGAGE", + "Polish": "DEBUGOWANIE", + "Portuguese (Brazil)": "DEPURAÇÃO", + "German (Germany)": "DEBUGGEN" + }, + "polymod_hub_config_coordinates": { + "English": "COORDINATES", + "Russian": "КООРДИНАТЫ", + "Turkish": "KOORDİNATLAR", + "Spanish (Mexico)": "COORDENADAS", + "French (France)": "COORDONNÉES", + "Polish": "WSPÓŁRZĘDNE", + "Portuguese (Brazil)": "COORDENADAS", + "German (Germany)": "KOORDINATEN" + }, + "polymod_debug_description": { + "English": "Opens the developer console and writes verbose logs.", + "Russian": "Открывает консоль разработчика и включает подробные логи.", + "Turkish": "Geliştirici konsolunu açar ve ayrıntılı günlük kaydı tutar.", + "Spanish (Mexico)": "Abre la consola de desarrollador y escribe registros detallados.", + "French (France)": "Ouvre la console de développement et écrit des journaux détaillés.", + "Polish": "Otwiera konsolę deweloperską i zapisuje szczegółowe logi.", + "Portuguese (Brazil)": "Abre o console de desenvolvedor e grava logs detalhados.", + "German (Germany)": "Öffnet die Entwicklerkonsole und schreibt ausführliche Logs." + }, + "polymod_coordinates": { + "English": "Coordinates", + "Russian": "Координаты", + "Turkish": "Koordinatlar", + "Spanish (Mexico)": "Coordenadas", + "French (France)": "Coordonnées", + "Polish": "Współrzędne", + "Portuguese (Brazil)": "Coordenadas", + "German (Germany)": "Koordinaten" + }, + "polymod_coordinates_description": { + "English": "Shows the coordinates of every tile on the map.", + "Russian": "Показывает координаты каждой клетки на карте.", + "Turkish": "Haritadaki her karenin koordinatlarını gösterir.", + "Spanish (Mexico)": "Muestra las coordenadas de cada casilla del mapa.", + "French (France)": "Affiche les coordonnées de chaque case de la carte.", + "Polish": "Pokazuje współrzędne każdego pola na mapie.", + "Portuguese (Brazil)": "Mostra as coordenadas de cada casa do mapa.", + "German (Germany)": "Zeigt die Koordinaten jedes Feldes auf der Karte." + }, + "polymod_on": { + "English": "ON", + "Russian": "ВКЛ", + "Turkish": "AÇIK", + "Spanish (Mexico)": "ACTIVADO", + "French (France)": "ACTIVÉ", + "Polish": "WŁ.", + "Portuguese (Brazil)": "LIGADO", + "German (Germany)": "AN" + }, + "polymod_off": { + "English": "OFF", + "Russian": "ВЫКЛ", + "Turkish": "KAPALI", + "Spanish (Mexico)": "DESACTIVADO", + "French (France)": "DÉSACTIVÉ", + "Polish": "WYŁ.", + "Portuguese (Brazil)": "DESLIGADO", + "German (Germany)": "AUS" + }, + "polymod_hotreload_unavailable": { + "English": "Hot reload is not available yet.", + "Russian": "Горячая перезагрузка пока недоступна.", + "Turkish": "Anında yeniden yükleme henüz kullanılamıyor.", + "Spanish (Mexico)": "La recarga en caliente aún no está disponible.", + "French (France)": "Le rechargement à chaud n'est pas encore disponible.", + "Polish": "Przeładowanie na gorąco nie jest jeszcze dostępne.", + "Portuguese (Brazil)": "A recarga a quente ainda não está disponível.", + "German (Germany)": "Sofortiges Neuladen ist noch nicht verfügbar." } -} +} \ No newline at end of file diff --git a/src/Api/Config.cs b/src/Api/Config.cs index f253bf8..dc0ef25 100644 --- a/src/Api/Config.cs +++ b/src/Api/Config.cs @@ -1,120 +1,174 @@ -using System.Text.Json; -using System.Text.Json.Nodes; +// using System.Text.Json; +// using System.Text.Json.Nodes; -namespace PolyMod.Api; +// namespace PolyMod.Api; -/// -/// Allows mods to save config. -/// -public class Config where T : class -{ - private T? currentConfig; - private readonly string modName; - private readonly ConfigTypes configType; - private static readonly string ExposedConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); - private readonly string perModConfigPath; - private T? defaultConfig; - public Config(string modName, ConfigTypes configType) - { - this.modName = modName; - this.configType = configType; - perModConfigPath = Path.Combine(Plugin.MODS_PATH, $"{modName}.json"); - Load(); - } +// /// +// /// The config of a mod. It keeps the config object in memory and reads it from and writes it to a JSON file. +// /// +// /// +// /// +// /// To use a config, call first. Then use or . +// /// Call to write your changes to disk. +// /// +// /// +// /// The class uses System.Text.Json to read and write the config object. +// /// +// /// +// /// The type of the config object. +// // should be public when i get through it +// internal class Config where T : class +// { +// private static readonly JsonSerializerOptions indentedJsonOptions = new() { WriteIndented = true }; +// private T? currentConfig; +// private readonly string modName; +// private readonly ConfigTypes configType; +// private static readonly string ExposedConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); +// private readonly string perModConfigPath; +// private T? defaultConfig; +// /// +// /// Makes a config for a mod and reads the config from disk if the config file exists. +// /// +// /// The mod name, normally the mod id. The config uses it as the file name or as the key in mods.json. +// /// The place on disk for the config. +// // should be public when i get through it +// internal Config(string modName, ConfigTypes configType) +// { +// this.modName = modName; +// this.configType = configType; +// perModConfigPath = Path.Combine(Plugin.MODS_PATH, $"{modName}.json"); +// Load(); +// } - internal void Load() // can be called internally if config changes; gui config not implemented yet - { - switch (configType) - { - case ConfigTypes.PerMod: - { - if (!File.Exists(perModConfigPath)) - { - return; - } - var jsonText = File.ReadAllText(perModConfigPath); - currentConfig = JsonSerializer.Deserialize(jsonText); - break; - } - case ConfigTypes.Exposed: - { - if (!File.Exists(ExposedConfigPath)) - { - return; - } - var jsonText = File.ReadAllText(ExposedConfigPath); - currentConfig = JsonNode.Parse(jsonText)![modName]?.Deserialize(); - break; - } - default: - throw new ArgumentOutOfRangeException(); - } - } - /// - /// Sets the default if the config does not exist yet. Always call this before reading from the config. - /// - public void SetDefaultConfig(T defaultValue) - { - defaultConfig = defaultValue; - if (currentConfig is not null) return; - Write(defaultConfig); - SaveChanges(); - } +// /// +// /// Reads the config from disk into memory. +// /// For , the method reads the file Mods/{modName}.json. +// /// For , the method reads the value with the mod name as its key in mods.json. +// /// If the file does not exist, the method does not change the config in memory. +// /// +// /// The config type is not a known value. +// internal void Load() // can be called internally if config changes; gui config not implemented yet +// { +// switch (configType) +// { +// case ConfigTypes.PerMod: +// { +// if (!File.Exists(perModConfigPath)) +// { +// return; +// } +// var jsonText = File.ReadAllText(perModConfigPath); +// currentConfig = JsonSerializer.Deserialize(jsonText); +// break; +// } +// case ConfigTypes.Exposed: +// { +// if (!File.Exists(ExposedConfigPath)) +// { +// return; +// } +// var jsonText = File.ReadAllText(ExposedConfigPath); +// currentConfig = JsonNode.Parse(jsonText)![modName]?.Deserialize(); +// break; +// } +// default: +// throw new ArgumentOutOfRangeException(); +// } +// } +// /// +// /// Sets the default config. Call this method before you read or edit the config. +// /// If there is no config in memory, the method uses the default config and writes it to disk. +// /// If there is a config in memory, for example a config that the constructor read from disk, the method keeps that config. +// /// +// /// The config object to use when there is no config in memory. +// // should be public when i get through it +// internal void SetDefaultConfig(T defaultValue) +// { +// defaultConfig = defaultValue; +// if (currentConfig is not null) return; +// Write(defaultConfig); +// SaveChanges(); +// } - /// - /// Writes the **entire** config. Usage not recommended, use Edit() instead - /// - public void Write(T config) - { - currentConfig = config; - } - /// - /// Gets the config. Should only be called after setting a default. - /// - public T Get() - { - return currentConfig ?? throw new InvalidOperationException("Must set default before reading config."); - } - /// - /// Edits the config. Should only be called after setting a default. - /// - /// Call SaveChanges after editing - public void Edit(Action editor) - { - editor(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); - } - /// - /// Gets part of the config. Should only be called after setting a default - /// - public TResult Get(Func getter) - { - return getter(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); - } - /// - /// Writes the config to disk - /// - public void SaveChanges() - { - switch (configType) - { - case ConfigTypes.PerMod: - var perModJson = JsonSerializer.Serialize(currentConfig, new JsonSerializerOptions { WriteIndented = true }); - File.WriteAllText(perModConfigPath, perModJson); - break; - case ConfigTypes.Exposed: - var modsConfigText = File.ReadAllText(ExposedConfigPath); - var modsConfigJson = JsonNode.Parse(modsConfigText)!.AsObject(); - modsConfigJson[modName] = JsonSerializer.SerializeToNode(currentConfig!); - File.WriteAllText(ExposedConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); - break; - default: - throw new ArgumentOutOfRangeException(); - } - } +// /// +// /// Replaces the full config object in memory. To change only some values, use . +// /// This method does not write to disk. Call to write the config to disk. +// /// +// /// The new config object. +// // should be public when i get through it +// internal void Write(T config) +// { +// currentConfig = config; +// } +// /// +// /// Gets the config object that is in memory. +// /// +// /// The config object. Changes to it stay in memory until you call . +// /// There is no config in memory. This occurs when there is no config on disk and you did not call . +// // should be public when i get through it +// internal T Get() +// { +// return currentConfig ?? throw new InvalidOperationException("Must set default before reading config."); +// } +// /// +// /// Calls an action on the config object that is in memory, so that the action can change the config. +// /// +// /// This method does not write to disk. Call after you edit the config. +// /// The action that changes the config object. +// /// There is no config in memory. This occurs when there is no config on disk and you did not call . +// // should be public when i get through it +// internal void Edit(Action editor) +// { +// editor(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); +// } +// /// +// /// Gets one value from the config object that is in memory. +// /// +// /// The type of the value. +// /// The function that gets the value from the config object. +// /// The value that gives. +// /// There is no config in memory. This occurs when there is no config on disk and you did not call . +// // should be public when i get through it +// internal TResult Get(Func getter) +// { +// return getter(currentConfig ?? throw new InvalidOperationException("Must set default before reading config.")); +// } +// /// +// /// Writes the config object that is in memory to disk as indented JSON. +// /// For , the method replaces the file Mods/{modName}.json. +// /// For , the method replaces the value with the mod name as its key in mods.json. +// /// It keeps the values of other mods in mods.json. +// /// +// /// The config type is not a known value. +// // should be public when i get through it +// internal void SaveChanges() +// { +// switch (configType) +// { +// case ConfigTypes.PerMod: +// var perModJson = JsonSerializer.Serialize(currentConfig, indentedJsonOptions); +// File.WriteAllText(perModConfigPath, perModJson); +// break; +// case ConfigTypes.Exposed: +// var modsConfigText = File.ReadAllText(ExposedConfigPath); +// var modsConfigJson = JsonNode.Parse(modsConfigText)!.AsObject(); +// modsConfigJson[modName] = JsonSerializer.SerializeToNode(currentConfig!); +// File.WriteAllText(ExposedConfigPath, modsConfigJson.ToJsonString(indentedJsonOptions)); +// break; +// default: +// throw new ArgumentOutOfRangeException(); +// } +// } - public enum ConfigTypes - { - PerMod, - Exposed - } -} \ No newline at end of file +// /// +// /// The places on disk for a config. +// /// +// // should be public when i get through it +// internal enum ConfigTypes +// { +// /// The config is in its own file, Mods/{modName}.json. +// PerMod, +// /// The config is a value in the shared mods.json file in the game folder, with the mod name as its key. +// Exposed +// } +// } diff --git a/src/Api/GLDConfig.cs b/src/Api/GLDConfig.cs index ecda511..02bdb56 100644 --- a/src/Api/GLDConfig.cs +++ b/src/Api/GLDConfig.cs @@ -1,94 +1,132 @@ -using System.Text.Json; -using System.Text.Json.Nodes; -using Scriban; -using Scriban.Runtime; +// using System.Text.Json; +// using System.Text.Json.Nodes; +// using Scriban; +// using Scriban.Runtime; -namespace PolyMod.Api; +// namespace PolyMod.Api; -public class GldConfigTemplate -{ - private static readonly string ConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); +// /// +// /// A GLD patch template with config values. +// /// PolyMod uses it for each patch.json and patch_*.json file of a mod. +// /// +// /// +// /// +// /// A patch file can use the Scriban template syntax. In the template, write {{ config "key" "default" }} to get a config value. +// /// The function gets the value with that key from the section of the mod in mods.json, as text. +// /// If the key does not exist, the function adds the key with the default value and gives the default value. +// /// +// /// +// /// The users can change the values in mods.json. The changes apply the next time that PolyMod loads the patch. +// /// +// /// +// // should be public when i get through it +// internal class GldConfigTemplate +// { +// private static readonly string ConfigPath = Path.Combine(Plugin.BASE_PATH, "mods.json"); - private readonly string templateText; - private JsonObject currentConfig = new(); - private string modName; +// private readonly string templateText; +// private JsonObject currentConfig = new(); +// private string modName; - public GldConfigTemplate(string templateText, string modName) - { - this.templateText = templateText; - this.modName = modName; - Load(); - } - private void Load() - { - if (File.Exists(ConfigPath)) - { - var json = File.ReadAllText(ConfigPath); - if (JsonNode.Parse(json) is JsonObject modsConfig - && modsConfig.TryGetPropertyValue(modName, out var modConfigNode) - && modConfigNode is JsonObject modConfig) - { - currentConfig = modConfig; - return; - } - } - currentConfig = new JsonObject(); - } +// /// +// /// Makes a template from the text of a patch file and reads the config values of the mod from mods.json. +// /// +// /// The text of the patch file. +// /// The mod id. The template uses it as the key of the mod section in mods.json. +// // should be public when i get through it +// internal GldConfigTemplate(string templateText, string modName) +// { +// this.templateText = templateText; +// this.modName = modName; +// Load(); +// } +// /// +// /// Reads the config values of the mod from mods.json. +// /// If the file does not exist, or the mod does not have a JSON object in it, the method uses an empty config. +// /// +// private void Load() +// { +// if (File.Exists(ConfigPath)) +// { +// var json = File.ReadAllText(ConfigPath); +// if (JsonNode.Parse(json) is JsonObject modsConfig +// && modsConfig.TryGetPropertyValue(modName, out var modConfigNode) +// && modConfigNode is JsonObject modConfig) +// { +// currentConfig = modConfig; +// return; +// } +// } +// currentConfig = new JsonObject(); +// } - public string? Render() - { - if (!templateText.Contains("{{")) return templateText; - var template = Template.Parse(templateText); - var context = new TemplateContext(); - var scriptObject = new ScriptObject(); +// /// +// /// Renders the template with the config values of the mod. +// /// If the text does not contain {{, the method gives the text without changes. +// /// If the template uses a key that is not in the config, the method writes the default value to mods.json. +// /// +// /// The rendered text, or null if the template has an error. The method writes the error to the log. +// // should be public when i get through it +// internal string? Render() +// { +// if (!templateText.Contains("{{")) return templateText; +// var template = Template.Parse(templateText); +// var context = new TemplateContext(); +// var scriptObject = new ScriptObject(); - bool changedConfig = false; - scriptObject.Import("config", - new Func((key, defaultValue) => - { - if (currentConfig.TryGetPropertyValue(key, out var token) && token != null) - { - return token.ToString(); - } +// bool changedConfig = false; +// scriptObject.Import("config", +// new Func((key, defaultValue) => +// { +// if (currentConfig.TryGetPropertyValue(key, out var token) && token != null) +// { +// return token.ToString(); +// } - changedConfig = true; - currentConfig[key] = defaultValue; +// changedConfig = true; +// currentConfig[key] = defaultValue; - return defaultValue; - }) - ); - context.PushGlobal(scriptObject); - string? result; - try - { - result = template.Render(context); - } - catch (Exception e) - { - Plugin.logger.LogError("error during parse of gld patch template: " + e.ToString()); - result = null; - } - if (changedConfig) - { - SaveChanges(); - } - return result; - } +// return defaultValue; +// }) +// ); +// context.PushGlobal(scriptObject); +// string? result; +// try +// { +// result = template.Render(context); +// } +// catch (Exception e) +// { +// Plugin.logger.LogError("error during parse of gld patch template: " + e.ToString()); +// result = null; +// } +// if (changedConfig) +// { +// SaveChanges(); +// } +// return result; +// } - public void SaveChanges() - { - JsonObject modsConfigJson; - if (File.Exists(ConfigPath)) - { - var modsConfigText = File.ReadAllText(ConfigPath); - modsConfigJson = (JsonNode.Parse(modsConfigText) as JsonObject) ?? new JsonObject(); - } - else - { - modsConfigJson = new JsonObject(); - } +// /// +// /// Writes the config values of the mod to mods.json as indented JSON. +// /// The method replaces the section of the mod and keeps the sections of other mods. +// /// If the file does not exist or does not contain a JSON object, the method makes a new file. +// /// +// // should be public when i get through it +// internal void SaveChanges() +// { +// JsonObject modsConfigJson; +// if (File.Exists(ConfigPath)) +// { +// var modsConfigText = File.ReadAllText(ConfigPath); +// modsConfigJson = (JsonNode.Parse(modsConfigText) as JsonObject) ?? new JsonObject(); +// } +// else +// { +// modsConfigJson = new JsonObject(); +// } - modsConfigJson[modName] = currentConfig; - File.WriteAllText(ConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); - } -} \ No newline at end of file +// modsConfigJson[modName] = currentConfig; +// File.WriteAllText(ConfigPath, modsConfigJson.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); +// } +// } diff --git a/src/Api/PolyScript.cs b/src/Api/PolyScript.cs index 09fd36e..6d3c9d4 100644 --- a/src/Api/PolyScript.cs +++ b/src/Api/PolyScript.cs @@ -1,54 +1,112 @@ using BepInEx.Logging; -using Newtonsoft.Json.Linq; +// using Newtonsoft.Json.Linq; namespace PolyMod.Api; -public abstract class PolyScriptBase +/// +/// The base class of all mod scripts. Do not use this class directly. +/// To make a mod script, make a subclass of . +/// +/// +/// When PolyMod loads a mod assembly, it finds the first type in the assembly that is a subclass of this class. +/// It makes an instance of that type, calls , and then calls . +/// +// should be public when i get through it +internal abstract class PolyScriptBase { /// - /// Initializes the PolyScript with the given mod and logger. + /// Gives the mod and the logger to the script. PolyMod calls this method before . /// - /// The mod instance. - /// The logger instance. + /// The mod that the script belongs to. + /// The log source of the mod. internal abstract void Initialize(Mod mod, ManualLogSource logger); - /// > - /// Called when the mod is loaded. + /// + /// Starts the mod script. PolyMod calls this method one time, after it loads the mod assembly. + /// Put the code that starts your mod here, for example the code that applies your Harmony patches. /// - public abstract void Load(); + // should be public when i get through it + internal abstract void Load(); /// - /// Called when the mod is unloaded. + /// Stops the mod script. PolyMod does not call this method at this time. /// - public abstract void Unload(); + // should be public when i get through it + internal abstract void Unload(); + /// + /// Makes a script. The constructor is internal, so only classes in PolyMod can be direct subclasses. + /// internal PolyScriptBase() { } } -public abstract class PolyScript : PolyScriptBase where TConfig : class where TExposedConfig : class +/// +/// The base class for a mod script. +/// +/// +/// Make a subclass and override . +/// Before PolyMod calls , it sets the and properties. +/// +// should be public when i get through it +// internal abstract class PolyScript : PolyScriptBase where TConfig : class where TExposedConfig : class +internal abstract class PolyScript : PolyScriptBase { + /// + /// Sets the and properties. + /// + /// The mod that the script belongs to. + /// The log source of the mod. internal override void Initialize(Mod mod, ManualLogSource logger) { Mod = mod; - Config = new Config(mod.id, Config.ConfigTypes.PerMod); - ExposedConfig = new Config(mod.id, Config.ConfigTypes.Exposed); + // Config = new Config(mod.id, Config.ConfigTypes.PerMod); + // ExposedConfig = new Config(mod.id, Config.ConfigTypes.Exposed); Logger = logger; } + /// + /// Gets the contents of a file of the mod. + /// + /// The name of the file in the mod. The name must match exactly. + /// The bytes of the file, or null if the mod does not have a file with that name. internal byte[]? GetFile(string fileName) { return Registry.mods[Mod.id].files.FirstOrDefault(f => f.name == fileName)?.bytes; } - public override void Unload() { } + /// + /// Does nothing. Override this method to stop your mod. PolyMod does not call this method at this time. + /// + // should be public when i get through it + internal override void Unload() { } - public Mod Mod { get; private set; } = null!; - protected Config Config { get; private set; } = null!; - protected Config ExposedConfig { get; private set; } = null!; + /// + /// Gets the mod that the script belongs to. + /// + // should be public when i get through it + internal Mod Mod { get; private set; } = null!; + // /// + // /// Gets the per-mod config. PolyMod keeps it in the file Mods/{mod id}.json. + // /// Call before you read it. + // /// + // protected Config Config { get; private set; } = null!; + // /// + // /// Gets the exposed config. PolyMod keeps it in the shared mods.json file, with the mod id as its key. + // /// Call before you read it. + // /// + // protected Config ExposedConfig { get; private set; } = null!; + /// + /// Gets the log source of the mod. Use it to write messages to the BepInEx log. + /// protected ManualLogSource Logger { get; private set; } = null!; } -public abstract class PolyScript : PolyScript -{ -} \ No newline at end of file +// /// +// /// The base class for a mod script that uses for the per-mod config and the exposed config. +// /// Make a subclass and override . +// /// +// // should be public when i get through it +// internal abstract class PolyScript : PolyScript +// { +// } diff --git a/src/Dumper.cs b/src/Dumper.cs new file mode 100644 index 0000000..cd072c9 --- /dev/null +++ b/src/Dumper.cs @@ -0,0 +1,354 @@ +using System.Text.Encodings.Web; +using System.Text.Json; +using Il2CppSystem.Linq; +using PolyMod.Json; +using PolytopiaBackendBase.Common; +using UnityEngine; + +namespace PolyMod.Managers; + +/// +/// The manager that writes the data of the game to disk as a reference for mod authors. +/// It writes the game logic, the localization, the sprites, the tribe previews, and the prefabs. +/// +internal static class Dumper +{ + private static readonly JsonSerializerOptions INDENTED = new() + { + WriteIndented = true, + }; + + private static readonly JsonSerializerOptions INDENTED_WITH_VECTORS = new() + { + WriteIndented = true, + Converters = { new Vector2Json() }, + }; + + private static readonly JsonSerializerOptions LOCALIZATION = new() + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + /// + /// Gets the full path of the folder that contains the dump. + /// + internal static string RootPath => Path.GetFullPath(Plugin.DUMPED_DATA_PATH); + + /// + /// Makes the dump folder and writes all parts of the dump. + /// + /// + /// The method calls , , , , and . + /// Each of these methods writes an error to the log if it fails, and the next method runs. + /// + internal static void DumpAll() + { + Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); + DumpLogic(); + DumpLocalization(); + DumpSprites(); + DumpTribePreviews(); + DumpPrefabs(); + } + + /// + /// Writes each version of the game logic data and of the avatar data to . + /// + /// + /// The file names are GameLogicData{version}.json and AvatarData{version}.json. + /// If an error occurs, the method writes it to the log. + /// + internal static void DumpLogic() + { + try + { + Directory.CreateDirectory(Plugin.LOGIC_DUMP_PATH); + for (int version = 1; version <= VersionManager.GameLogicDataVersion; version++) + { + File.WriteAllText( + Path.Combine(Plugin.LOGIC_DUMP_PATH, $"GameLogicData{version}.json"), + PolytopiaDataManager.provider.LoadGameLogicData(version) + ); + } + for (int version = 1; version <= VersionManager.AvatarDataVersion; version++) + { + File.WriteAllText( + Path.Combine(Plugin.LOGIC_DUMP_PATH, $"AvatarData{version}.json"), + PolytopiaDataManager.provider.LoadAvatarData(version) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping logic failed: {exception}"); + } + } + + /// + /// Writes the localization of the game to . + /// + /// + /// The method uses the first localization source of the game. + /// For each language, it writes a language_{code}.json file with all terms that have a translation. + /// For each category, it writes a localization_{category}.csv file. + /// If an error occurs, the method writes it to the log. + /// + internal static void DumpLocalization() + { + try + { + Directory.CreateDirectory(Plugin.LOCALIZATION_DUMP_PATH); + var source = I2.Loc.LocalizationManager.Sources[0]; + + foreach (var language in source.GetLanguages()) + { + int languageIndex = source.GetLanguageIndex(language); + Dictionary translations = new(); + foreach (var term in source.mTerms) + { + string translation = term.GetTranslation(languageIndex); + if (!string.IsNullOrEmpty(translation)) + translations[term.Term] = translation; + } + File.WriteAllText( + Path.Combine( + Plugin.LOCALIZATION_DUMP_PATH, + $"language_{source.mLanguages[languageIndex].Code}.json" + ), + JsonSerializer.Serialize(translations, LOCALIZATION) + ); + } + + foreach (var category in source.GetCategories()) + { + File.WriteAllText( + Path.Combine(Plugin.LOCALIZATION_DUMP_PATH, $"localization_{category}.csv"), + source.Export_CSV(category) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping localization failed: {exception}"); + } + } + + /// + /// Writes the sprites of the loaded atlases to . + /// + /// + /// The method uses the atlas list in AtlasData.raw and skips each atlas that is not loaded. + /// For each atlas, it makes a folder with the atlas name. + /// It writes each sprite of the atlas as a PNG file in that folder. + /// It also writes the sprite information of the atlas to sprites_{atlas}.json. + /// If an error occurs, the method writes it to the log. + /// + internal static void DumpSprites() + { + try + { + Directory.CreateDirectory(Plugin.SPRITES_DUMP_PATH); + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + + for (int i = 0; i < AtlasData.raw.Count; i++) + { + if (spriteAtlasManager.loadedAtlases[i] == null) continue; + + string[] row = AtlasData.raw[i]; + string atlasName = row[0]; + string directory = Path.Combine(Plugin.SPRITES_DUMP_PATH, atlasName); + Directory.CreateDirectory(directory); + + Dictionary atlasSpriteInfo = new(); + for (int j = 1; j < row.Length; j++) + { + string spriteName = row[j]; + Sprite sprite = spriteAtlasManager.GetSprite(spriteName, atlasName); + if (sprite == null) continue; + + (byte[] bytes, Visual.SpriteInfo spriteInfo) = Visual.SpriteToPng(sprite); + File.WriteAllBytes(Path.Combine(directory, $"{spriteName}.png"), bytes); + atlasSpriteInfo[spriteName] = spriteInfo; + } + File.WriteAllText( + Path.Combine(directory, $"sprites_{atlasName}.json"), + JsonSerializer.Serialize(atlasSpriteInfo, INDENTED_WITH_VECTORS) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping sprites failed: {exception}"); + } + } + + /// + /// Writes the tribe preview map of each tribe to . + /// + /// + /// The method uses only the preview of the default skin. + /// For each tribe that has a preview, it reads the save state of the preview. + /// It writes the terrain, resource, unit, improvement, and tile effects of each tile to preview_{tribe}.json. + /// If the method cannot read a save state, it writes a warning and skips that tribe. + /// If an error occurs, the method writes it to the log. + /// + internal static void DumpTribePreviews() + { + try + { + foreach (TribeType type in Enum.GetValues()) + { + SaveStateData saveStateData = TribePreviewRegistry.GetTribePreviewData(type, SkinType.Default); // TODO: skins + if (saveStateData == null) continue; + + if (!DiskSerializationHelpers.FromLZ4CompressedByteArray( + saveStateData.byteArray, out ClientSerializationWrapper wrapper, out int _)) + { + Plugin.logger.LogWarning($"Dump skipped preview of {type}: save state could not be read"); + continue; + } + + List previewTiles = new(); + foreach (var tileData in wrapper.GetCurrentGameState().Map.Tiles) + { + previewTiles.Add(new TribePreviews.PreviewTile + { + x = tileData.coordinates.x, + y = tileData.coordinates.y, + terrainType = tileData.terrain, + resourceType = tileData.resource != null ? tileData.resource.type : null, + unitType = tileData.unit != null ? tileData.unit.type : null, + improvementType = tileData.improvement != null ? tileData.improvement.type : null, + tileEffects = tileData.effects.ToArray().ToList(), + }); + } + + File.WriteAllText( + Path.Combine(Plugin.DUMPED_DATA_PATH, $"preview_{type}.json"), + JsonSerializer.Serialize(previewTiles, INDENTED) + ); + } + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping tribe previews failed: {exception}"); + } + } + + /// + /// Writes the unit, improvement, and resource prefabs to prefabs.json in . + /// + /// + /// The method writes the file in the format. + /// The units come from , and the improvements and resources come from PrefabManager. + /// The method skips each prefab that has no SkinVisualsReference. + /// It does not write weapon prefabs. + /// If an error occurs, the method writes it to the log. + /// + internal static void DumpPrefabs() + { + try + { + Directory.CreateDirectory(Plugin.PREFABS_DUMP_PATH); + PrefabsInfo prefabsInfo = new(); + + foreach (var entry in Prefabs.unitsNew) + { + List? visualParts = CollectVisualParts(entry.Value, entry.Key.unitType); + if (visualParts == null) continue; + + prefabsInfo.units.Add(new UnitPrefabInfo + { + headPositionMarker = entry.Value.headPositionMarker.gameObject.name, + skinnedKey = entry.Key, + visualParts = visualParts, + }); + } + + foreach (var entry in PrefabManager.improvements) + { + List? visualParts = CollectVisualParts(entry.Value, entry.Key); + if (visualParts == null) continue; + + prefabsInfo.improvements.Add(new ImprovementPrefabInfo + { + improvementType = entry.Key, + visualParts = visualParts, + }); + } + + foreach (var entry in PrefabManager.resources) + { + List? visualParts = CollectVisualParts(entry.Value, entry.Key); + if (visualParts == null) continue; + + prefabsInfo.resources.Add(new ResourcePrefabInfo + { + resourceType = entry.Key, + visualParts = visualParts, + }); + } + + // TODO + // foreach (var entry in PrefabManager.weapons) + // { + // WeaponGFX weaponGFX = entry.Value; + // prefabsInfo.weapons.Add(new WeaponPrefabInfo + // { + // weaponEnum = entry.Key, + // spriteName = weaponGFX.defaultSprite.name, + // pathType = weaponGFX.pathType, + // pathMode = weaponGFX.pathMode, + // pathResolution = weaponGFX.pathResolution, + // pathEase = weaponGFX.pathEase, + // lookAheadOffset = weaponGFX.lookAheadOffset, + // handleAngleOffset = weaponGFX.handleAngleOffset, + // sfxType = SFXTypes.None, //TODO + // weaponPuffInfo = null, //TODO + // weaponRangedInfo = null //TODO + // }); + // } + + File.WriteAllText( + Path.Combine(Plugin.PREFABS_DUMP_PATH, "prefabs.json"), + JsonSerializer.Serialize(prefabsInfo, INDENTED_WITH_VECTORS) + ); + } + catch (Exception exception) + { + Plugin.logger.LogError($"Dumping prefabs failed: {exception}"); + } + } + + /// + /// Gets the descriptions of the visual parts of a prefab. + /// + /// + /// The method skips each visual part that is null or that has no visual part object. + /// If the prefab has no SkinVisualsReference or no visual parts, the method writes a warning. + /// + /// The prefab to read. + /// The key of the prefab. The method uses it only in the warning. + /// The descriptions of the visual parts, or null if the prefab has no SkinVisualsReference or no visual parts. + private static List? CollectVisualParts(Component prefab, object key) + { + SkinVisualsReference skinVisualsReference = prefab.GetComponent(); + if (skinVisualsReference == null || skinVisualsReference.visualParts == null) + { + Plugin.logger.LogWarning($"Dump skipped {key}: no SkinVisualsReference"); + return null; + } + + List visualParts = new(); + foreach (var visualPart in skinVisualsReference.visualParts) + { + if (visualPart == null || visualPart.visualPart == null) continue; + + VisualPartInfo visualPartInfo = new(); + visualPartInfo.CopyFromVisualPart(visualPart); + visualParts.Add(visualPartInfo); + } + return visualParts; + } +} diff --git a/src/Json/EnumCacheJson.cs b/src/Json/EnumCacheJson.cs index 5f561c6..964e0ff 100644 --- a/src/Json/EnumCacheJson.cs +++ b/src/Json/EnumCacheJson.cs @@ -4,33 +4,38 @@ namespace PolyMod.Json; /// -/// A custom JSON converter for enum types that integrates with EnumCache. -/// Supports serializing and deserializing enums by their cached string names, -/// and works with both single enum values and property names. +/// The JSON converter that reads and writes a game enum value as its name in EnumCache. +/// The JSON form is a string, for example "imperius". The converter also reads and writes the value as a property name. /// -/// The enum type being converted. +/// +/// Use this converter for enums that mods can extend, because EnumCache also has the names of the values that mods add. +/// +/// The enum type to convert. public class EnumCacheJson : JsonConverter where T : struct, Enum { /// - /// Determines whether the converter can handle the given type. - /// Supports both the enum type and . + /// Finds if the converter accepts a type. + /// The method gives true for and for of . /// - /// The type to check for compatibility. - /// True if the type can be converted; otherwise false. + /// + /// The method can read only . For lists, use . + /// + /// The type to check. + /// True if the type is or of , otherwise false. public override bool CanConvert(Type typeToConvert) { return typeToConvert == typeof(T) || typeToConvert == typeof(List); } /// - /// Reads a JSON string and converts it into the corresponding enum value - /// using the EnumCache lookup. + /// Reads a JSON string and gets the enum value with that name from EnumCache. + /// If EnumCache does not have the name, EnumCache throws an exception. /// - /// The JSON reader. - /// The type to convert into. - /// Serialization options. - /// The enum value represented by the JSON string. - /// Thrown if the type is not supported. + /// The JSON reader, at a string token or a property name token. + /// The type to read. It must be . + /// The serializer options. The method does not use them. + /// The enum value that has the name in the JSON string. + /// is not . public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (typeToConvert == typeof(T)) @@ -43,34 +48,35 @@ public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerial /// - /// Writes the enum value as its cached string representation. + /// Writes the enum value as a JSON string with its name from EnumCache. /// /// The JSON writer. /// The enum value to write. - /// Serialization options. + /// The serializer options. The method does not use them. public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { writer.WriteStringValue(EnumCache.GetName(value)); } /// - /// Reads a JSON property name and converts it into the corresponding enum value. + /// Reads a JSON property name and gets the enum value with that name from EnumCache. + /// The method calls . /// - /// The JSON reader. - /// The target type. - /// Serialization options. - /// The enum value represented by the property name. + /// The JSON reader, at a property name token. + /// The type to read. It must be . + /// The serializer options. The method does not use them. + /// The enum value that has the name in the property name. public override T ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return Read(ref reader, typeToConvert, options); } /// - /// Writes the enum value as a property name using its cached string representation. + /// Writes the enum value as a JSON property name with its name from EnumCache. /// /// The JSON writer. /// The enum value to write. - /// Serialization options. + /// The serializer options. The method does not use them. public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { writer.WritePropertyName(EnumCache.GetName(value)); @@ -78,25 +84,25 @@ public override void WriteAsPropertyName(Utf8JsonWriter writer, T value, JsonSer } /// -/// A custom JSON converter for lists of enum values that integrates with EnumCache. -/// Serializes enum values as strings and deserializes them back into a list of enums. +/// The JSON converter that reads and writes a list of game enum values as their names in EnumCache. +/// The JSON form is an array of strings, for example ["imperius", "bardur"]. /// -/// The enum type being converted. +/// The enum type of the list items. public class EnumCacheListJson : JsonConverter> where T : struct, Enum { /// - /// Inner converter used to handle individual enum values. + /// The converter that reads and writes each item of the list. /// private readonly EnumCacheJson _inner = new(); /// - /// Reads a JSON array of enum string values and converts them into a list of enum values. + /// Reads a JSON array of strings and gets the enum value for each string from EnumCache. /// - /// The JSON reader. - /// The type to convert into. - /// Serialization options. - /// A list of enum values. - /// Thrown if the JSON is not an array. + /// The JSON reader, at the start of the array. + /// The type to read. The method does not use it. + /// The serializer options. The method gives them to the item converter. + /// The list of enum values, in the same order as the array. + /// The JSON value is not an array. public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var list = new List(); @@ -116,11 +122,11 @@ public override List Read(ref Utf8JsonReader reader, Type typeToConvert, Json } /// - /// Writes a list of enum values as a JSON array of strings. + /// Writes a list of enum values as a JSON array of strings with their names from EnumCache. /// /// The JSON writer. /// The list of enum values to write. - /// Serialization options. + /// The serializer options. The method gives them to the item converter. public override void Write(Utf8JsonWriter writer, List value, JsonSerializerOptions options) { writer.WriteStartArray(); diff --git a/src/Json/EnumNameJson.cs b/src/Json/EnumNameJson.cs new file mode 100644 index 0000000..e60517d --- /dev/null +++ b/src/Json/EnumNameJson.cs @@ -0,0 +1,48 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace PolyMod.Json; + +/// +/// The JSON converter that reads and writes an enum value as its C# member name. +/// The JSON form is a string, for example "Linear". +/// +/// +/// Use this converter for enums that mods cannot extend and that EnumCache does not have. +/// +/// The enum type to convert. +public class EnumNameJson : JsonConverter where TEnum : struct, Enum +{ + /// + /// Reads a JSON string and gets the enum value with that member name. The name is not case-sensitive. + /// The method uses Enum.TryParse, so it also accepts numeric strings. + /// + /// The JSON reader, at a string token. + /// The type to read. The method does not use it. + /// The serializer options. The method does not use them. + /// The enum value that has the name in the JSON string. + /// The JSON value is null or is not a member name of . The message shows the valid names. + public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + string? enumName = reader.GetString(); + + if (enumName != null && Enum.TryParse(enumName, true, out TEnum parsedValue)) + { + return parsedValue; + } + + string validNames = string.Join(", ", Enum.GetNames()); + throw new JsonException($"Unknown {typeof(TEnum).Name} value '{enumName}'. Valid values: {validNames}"); + } + + /// + /// Writes the enum value as a JSON string with its C# member name. + /// + /// The JSON writer. + /// The enum value to write. + /// The serializer options. The method does not use them. + public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.ToString()); + } +} diff --git a/src/Json/JsonMerger.cs b/src/Json/JsonMerger.cs index 44eb212..e14edab 100644 --- a/src/Json/JsonMerger.cs +++ b/src/Json/JsonMerger.cs @@ -4,16 +4,28 @@ namespace PolyMod.Json; /// -/// Provides functionality to merge JSON objects, with special handling for arrays. +/// The merge of a JSON patch into a JSON object, for example a GLD patch into the game logic data. /// +/// +/// +/// Objects merge recursively. A value in the patch replaces the value in the original, and a null value in the patch sets the value to null. +/// +/// +/// Arrays have special rules. A string that starts with + adds the string without the + to the original array. +/// A string that starts with - removes all equal strings from the original array. +/// In an array with the name skins, a plain string also adds the string. +/// If an array has none of these items, the patch array replaces the original array. +/// If an array has some of these items, the merge ignores the other plain strings in it. +/// +/// public static class JsonMerger { /// - /// Merges a patch JObject into an original JObject. + /// Merges a patch into an original JSON object. The method changes and . /// - /// The original JObject. - /// The patch JObject to merge. - /// The merged JObject. + /// The JSON object to change. + /// The JSON object with the changes. + /// The object, after the merge. public static JObject Merge(JObject original, JObject patch) { patch = MergeRecursive(original, patch); @@ -22,11 +34,13 @@ public static JObject Merge(JObject original, JObject patch) } /// - /// Recursively applies custom merging logic to arrays. + /// Replaces each array in the patch with the result of , at all levels of the patch. + /// If the original does not have a matching array or object, the method uses an empty one. + /// After this method, a normal merge with array replacement gives the correct arrays. /// - /// - /// - /// + /// The JSON object that the patch applies to. + /// The JSON object with the changes. The method changes this object. + /// The object, with the merged arrays. private static JObject MergeRecursive(JObject original, JObject patch) { foreach (var property in patch.Properties().ToArray().ToList()) @@ -61,12 +75,15 @@ private static JObject MergeRecursive(JObject original, JObject patch) } /// - /// Merges two JArrays, with special handling for adding and removing elements. + /// Merges a patch array into a copy of an original array. + /// A string that starts with + adds the string without the +. A string that starts with - removes all equal strings. + /// The method adds all items that are not strings. It ignores plain strings, but adds them if is true. + /// If the patch has no + strings, no - strings, and no plain strings in a skins array, the method gives a copy of the patch array. /// - /// The original JArray. - /// The patch JArray to merge. - /// A flag to indicate if the array is a 'skins' array, which has special merging logic. - /// The merged JArray. + /// The original array. The method does not change it. + /// The patch array. + /// True if the array has the name skins. Then plain strings add to the original array. + /// A new array with the merged items. private static JArray MergeArrays(JArray original, JArray patch, bool isSkins) { var result = new JArray(original); @@ -83,13 +100,13 @@ private static JArray MergeArrays(JArray original, JArray patch, bool isSkins) string str = token.ToString(); - if (str.StartsWith("+")) + if (str.StartsWith('+')) { string value = str.Substring(1); result.Add(value); hasCustomValues = true; } - else if (str.StartsWith("-")) + else if (str.StartsWith('-')) { string value = str.Substring(1); var toRemove = result._values.ToArray() diff --git a/src/Json/Vector2Json.cs b/src/Json/Vector2Json.cs index 1957c4d..ef66d56 100644 --- a/src/Json/Vector2Json.cs +++ b/src/Json/Vector2Json.cs @@ -5,17 +5,19 @@ namespace PolyMod.Json; /// -/// Converts a to and from a JSON array of two numbers. +/// The JSON converter that reads and writes a . +/// The JSON form is an array of two numbers, x and y, for example [0.5, -1]. /// public class Vector2Json : JsonConverter { /// - /// Reads and converts the JSON to a . + /// Reads a JSON array of two numbers and makes a from them. /// - /// The reader. - /// The type to convert. - /// An object that specifies serialization options to use. - /// The converted value. + /// The JSON reader, at the start of the array. + /// The type to read. The method does not use it. + /// The serializer options. The method does not use them. + /// The vector with the first number as x and the second number as y. + /// The JSON value is not an array, an item is not a number, or the array does not have exactly two items. public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { List values = new(); @@ -33,11 +35,11 @@ public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, Json } /// - /// Writes a specified value as JSON. + /// Writes a as a JSON array of two numbers, x and y. /// - /// The writer to write to. - /// The value to convert to JSON. - /// An object that specifies serialization options to use. + /// The JSON writer. + /// The vector to write. + /// The serializer options. The method does not use them. public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options) { writer.WriteStartArray(); diff --git a/src/Json/VersionJson.cs b/src/Json/VersionJson.cs index 21c6c81..fe97094 100644 --- a/src/Json/VersionJson.cs +++ b/src/Json/VersionJson.cs @@ -4,28 +4,30 @@ namespace PolyMod.Json; /// -/// Converts a to and from a JSON string. +/// The JSON converter that reads and writes a . +/// The JSON form is a version string, for example "1.2.3". /// public class VersionJson : JsonConverter { /// - /// Reads and converts the JSON to a . + /// Reads a JSON string and makes a from it. + /// The constructor throws an exception if the string is null or is not a valid version. /// - /// The reader. - /// The type to convert. - /// An object that specifies serialization options to use. - /// The converted value. + /// The JSON reader, at a string token. + /// The type to read. The method does not use it. + /// The serializer options. The method does not use them. + /// The version from the JSON string. public override Version? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(reader.GetString()!); } /// - /// Writes a specified value as JSON. + /// Writes a as a JSON string, for example "1.2.3". /// - /// The writer to write to. - /// The value to convert to JSON. - /// An object that specifies serialization options to use. + /// The JSON writer. + /// The version to write. + /// The serializer options. The method does not use them. public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString()); diff --git a/src/Loader.cs b/src/Loader.cs index 87d5a76..51967b6 100644 --- a/src/Loader.cs +++ b/src/Loader.cs @@ -1,3 +1,4 @@ +using System.Globalization; using BepInEx.Logging; using Cpp2IL.Core.Extensions; using Il2CppSystem.Linq; @@ -6,12 +7,9 @@ using PolyMod.Json; using PolyMod.Managers; using Polytopia.Data; -using PolytopiaBackendBase.Game; using System.Diagnostics; -using System.Globalization; using System.IO.Compression; using System.Reflection; -using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using UnityEngine; @@ -20,14 +18,35 @@ namespace PolyMod; /// -/// Handles loading of mods and their assets. +/// The methods that register mods, sort them, load their files and apply their GLD data. /// public static class Loader { + private static readonly JsonSerializerOptions manifestJsonOptions = new() + { + Converters = { new VersionJson() }, + }; + + private static readonly JsonSerializerOptions spriteInfoJsonOptions = new() + { + Converters = { new Vector2Json() }, + }; + + private static readonly JsonSerializerOptions prefabJsonOptions = new() + { + Converters = { new Vector2Json() }, + PropertyNameCaseInsensitive = true, + }; + + /// + /// The C# type that PolyMod uses for one GLD data category. + /// + /// The C# type of the data category. To make EnumCache mappings, this type must be an enum. + /// If true, makes EnumCache mappings for new entries of the category. If false, it only calls the type handlers. internal record TypeMapping(Type type, bool shouldCreateCache = true); /// - /// Mappings from JSON data types to their corresponding C# types. + /// The type mappings of the GLD data categories, keyed by the category name in the GLD, for example unitData. /// internal static Dictionary typeMappings = new() { @@ -47,13 +66,20 @@ internal record TypeMapping(Type type, bool shouldCreateCache = true); }; /// - /// List of custom game modes to be added. - /// - internal static List gamemodes = new(); - - /// - /// Handlers for processing specific data types during mod loading. + /// The type handlers that calls for each GLD entry, keyed by the C# type of the data category. /// + /// + /// Each handler gets the JSON object of the entry and a flag. + /// The flag is true when calls the handler just after it made a new EnumCache mapping for the entry. + /// The flag is false in the second pass, in which calls the handler for all entries of the category. + /// + /// : in the first pass, adds the tribe to and gives it a new style and climate. In the second pass, makes EnumCache mappings for new skins, makes a flood tile effect for each new skin of a tribe with the Flooded ability, changes the skin ids to indexes, and keeps the tribe preview. + /// UnitData.Type: in the second pass, adds the embarksTo value to Main.embarkNames and changes the weapon name to its index. + /// ImprovementData.Type: in the second pass, adds the improvement to the prefabs to make if prefab is true. It also adds the attractsResource, attractsToTerrain and infoOverride values to the related dictionaries. + /// ResourceData.Type: in the second pass, adds the resource to the prefabs to make if prefab is true. + /// SkinData: changes the name of the entry to lowercase. + /// + /// internal static readonly Dictionary>> typeHandlers = new() { [typeof(TribeType)] = new List>() { @@ -77,12 +103,16 @@ internal record TypeMapping(Type type, bool shouldCreateCache = true); string skinId = skin.ToString(); if (!Enum.TryParse(skinId, ignoreCase: true, out _)) { - SkinType skinValue = (SkinType)Registry.autoidx; + int index = Registry.GetAutoIndex(typeof(SkinType)); + SkinType skinValue = (SkinType)index; + EnumCache.AddMapping(skinId.ToLowerInvariant(), skinValue); EnumCache.AddMapping(skinId.ToLowerInvariant(), skinValue); - Registry.skinInfo.Add(new Visual.SkinInfo(Registry.autoidx, skinId, null)); - Plugin.logger.LogInfo("Created mapping for skinType with id " + skinId + " and index " + Registry.autoidx); - Registry.autoidx++; + + Registry.skinInfo.Add(new Visual.SkinInfo(index, skinId, null)); + Plugin.logger.LogInfo("Created mapping for skinType with id " + skinId + " and index " + index); + Registry.IncrementAutoIndex(typeof(SkinType)); + if(token["tribeAbilities"] != null) { JArray tribeAbilities = token["tribeAbilities"].Cast(); @@ -98,11 +128,14 @@ out TribeAbility.Type tribeAbilityType ) && tribeAbilityType == TribeAbility.Type.Flooded) { string tileEffectId = skinId.ToLowerInvariant() + "_flood"; - EnumCache.AddMapping(tileEffectId, (TileData.EffectType)Registry.autoidx); - EnumCache.AddMapping(tileEffectId, (TileData.EffectType)Registry.autoidx); - Visual.customFloodingSkins.Add((TileData.EffectType)Registry.autoidx, skinValue); - Plugin.logger.LogInfo("Created mapping for tileEffect with id " + tileEffectId + " and index " + Registry.autoidx); - Registry.autoidx++; + int autoidx = Registry.GetAutoIndex(typeof(TileData.EffectType)); + + TileData.EffectType effectType = (TileData.EffectType)autoidx; + EnumCache.AddMapping(tileEffectId, effectType); + EnumCache.AddMapping(tileEffectId, effectType); + Visual.customFloodingSkins.Add(effectType, skinValue); + Plugin.logger.LogInfo("Created mapping for tileEffect with id " + tileEffectId + " and index " + autoidx); + Registry.IncrementAutoIndex(typeof(TileData.EffectType)); } } } @@ -114,7 +147,7 @@ out TribeAbility.Type tribeAbilityType if (modifiedSkins.Contains(skin.id)) { modifiedSkins.Remove(skin.id); - modifiedSkins.Add(skin.idx.ToString()); + modifiedSkins.Add(skin.idx.ToString(CultureInfo.InvariantCulture)); } } JArray newSkins = new JArray(); @@ -126,7 +159,7 @@ out TribeAbility.Type tribeAbilityType } if (token["preview"] != null) { - Visual.PreviewTile[] preview = JsonSerializer.Deserialize(token["preview"].ToString())!; + TribePreviews.PreviewTile[] preview = JsonSerializer.Deserialize(token["preview"].ToString())!; Registry.tribePreviews[Util.GetJTokenName(token)] = preview; } } @@ -135,19 +168,8 @@ out TribeAbility.Type tribeAbilityType [typeof(UnitData.Type)] = new List>() { new((token, duringEnumCacheCreation) => { - if(duringEnumCacheCreation) + if(!duringEnumCacheCreation) { - if (token["prefab"] == null) - { - Registry.prefabNames.Add((int)token["idx"], EnumCache.GetName(UnitData.Type.Scout).ToLowerInvariant()); - } - } - else - { - if (token["prefab"] != null) - { - Registry.prefabNames.Add((int)token["idx"], token["prefab"].ToString().ToLowerInvariant()); - } if (token["embarksTo"] != null) { string unitId = Util.GetJTokenName(token); @@ -170,34 +192,31 @@ out TribeAbility.Type tribeAbilityType new((token, duringEnumCacheCreation) => { if (duringEnumCacheCreation) + return; + + if (token["prefab"] != null && (bool)token["prefab"]) { - ImprovementData.Type improvementPrefabType = ImprovementData.Type.CustomsHouse; - if (token["prefab"] != null) + bool levels = false; + if(token["maxLevel"] != null && (int)token["maxLevel"] > 0) { - string prefabId = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(token["prefab"]!.ToString()); - if (Enum.TryParse(prefabId, out ImprovementData.Type parsedType)) - improvementPrefabType = parsedType; + levels = true; } - if(token["idx"] != null) - PrefabManager.improvements.TryAdd((ImprovementData.Type)(int)token["idx"], PrefabManager.improvements[improvementPrefabType]); + Prefabs.improvementPrefabInfosToCreate[(ImprovementData.Type)(int)token["idx"]] = levels; } - else + string improvementId = Util.GetJTokenName(token); + if (token["attractsResource"] != null) { - string improvementId = Util.GetJTokenName(token); - if (token["attractsResource"] != null) - { - string attractsId = token["attractsResource"].ToString(); - Main.attractsResourceNames[improvementId] = attractsId; - } - if (token["attractsToTerrain"] != null) - { - string attractsId = token["attractsToTerrain"].ToString(); - Main.attractsTerrainNames[improvementId] = attractsId; - } - if(token["infoOverride"] != null) - { - Loc.buildingsInfoOverrides[improvementId] = Loc.ReplaceDashesWithDots(token["infoOverride"].ToString()); - } + string attractsId = token["attractsResource"].ToString(); + Main.attractsResourceNames[improvementId] = attractsId; + } + if (token["attractsToTerrain"] != null) + { + string attractsId = token["attractsToTerrain"].ToString(); + Main.attractsTerrainNames[improvementId] = attractsId; + } + if(token["infoOverride"] != null) + { + Loc.buildingsInfoOverrides[improvementId] = Loc.ReplaceDashesWithDots(token["infoOverride"].ToString()); } }) }, @@ -206,16 +225,11 @@ out TribeAbility.Type tribeAbilityType new((token, duringEnumCacheCreation) => { if (duringEnumCacheCreation) + return; + + if (token["prefab"] != null && (bool)token["prefab"]) { - ResourceData.Type resourcePrefabType = ResourceData.Type.Game; - if (token["prefab"] != null) - { - string prefabId = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(token["prefab"]!.ToString()); - if (Enum.TryParse(prefabId, out ResourceData.Type parsedType)) - resourcePrefabType = parsedType; - } - if(token["idx"] != null) - PrefabManager.resources.TryAdd((ResourceData.Type)(int)token["idx"], PrefabManager.resources[resourcePrefabType]); + Prefabs.resourcePrefabsInfosToCreate.Add((ResourceData.Type)(int)token["idx"]); } }) }, @@ -224,55 +238,43 @@ out TribeAbility.Type tribeAbilityType new((token, duringEnumCacheCreation) => { var prop = token.Parent.Cast(); - prop.Replace(new JProperty(prop.Name.ToLower(), prop.Value)); + prop.Replace(new JProperty(prop.Name.ToLowerInvariant(), prop.Value)); }) }, }; /// - /// Represents information for a custom game mode button. - /// - /// The index of the game mode. - /// The action to perform when the button is clicked. - /// The index of the button in the UI. - /// The sprite for the button. - /// The name of the sprite for the button. - public record GameModeButtonsInformation(int gameModeIndex, UIButtonBase.ButtonAction action, int? buttonIndex, Sprite? sprite, string? spriteName); - - /// - /// Adds a new game mode button. + /// Adds a type mapping for a GLD data category. makes EnumCache mappings for new entries of this category. + /// If already contains the category name, the method does nothing. /// - /// The unique identifier for the game mode. - /// The action to perform when the button is clicked. - /// The boolean which decides if GameMode should appear in the menu. - /// The sprite for the button. - /// The name of the sprite for the button. - public static void AddGameMode(string id, UIButtonBase.ButtonAction action, bool shouldShowInMenu = true, Sprite? sprite = null, string? spriteName = null) - { - EnumCache.AddMapping(id, (GameMode)Registry.gameModesAutoidx); - EnumCache.AddMapping(id, (GameMode)Registry.gameModesAutoidx); - if (shouldShowInMenu) - gamemodes.Add(new GameModeButtonsInformation(Registry.gameModesAutoidx, action, null, sprite, spriteName)); - Registry.gameModesAutoidx++; - } - - /// - /// Adds a new data type for patching. - /// - /// The identifier for the data type in JSON. - /// "The C# type corresponding to the identifier. + /// The name of the data category in the GLD, for example unitData. + /// The C# enum type of the data category. public static void AddPatchDataType(string typeId, Type type) { if (!typeMappings.ContainsKey(typeId)) typeMappings.Add(typeId, new TypeMapping(type)); } + /// + /// Adds a type mapping for a GLD data category. + /// If already contains the category name, the method does nothing. + /// + /// The name of the data category in the GLD, for example unitData. + /// The C# type of the data category. + /// If true, makes EnumCache mappings for new entries of the category. If false, it only calls the type handlers. public static void AddPatchDataType(string typeId, Type type, bool shouldCreateCache) { if (!typeMappings.ContainsKey(typeId)) typeMappings.Add(typeId, new TypeMapping(type, shouldCreateCache)); } + /// + /// Adds a type handler for a C# type to . + /// A type mapping for the type must exist in . + /// If no type mapping exists, the method writes a warning to the log and does not add the handler. + /// + /// The C# type of the data category. + /// The handler to add. It gets the JSON object of a GLD entry and a flag. The flag is true when just made a new EnumCache mapping for the entry. public static void AddTypeHandler(Type type, Action handler) { string typeString = type.ToString(); @@ -290,9 +292,20 @@ public static void AddTypeHandler(Type type, Action handler) } /// - /// Loads all mods from the mods directory. + /// Finds the mods in and adds them to a dictionary. /// - /// A dictionary to populate with the loaded mods. + /// + /// The method makes the mods directory if it does not exist. + /// A mod can be a directory, a .polymod file or a .zip file. + /// The method reads all files of the mod and gets the manifest from manifest.json at the root. + /// It does not add a mod if the manifest is missing, not valid, or has an id that the dictionary already contains. + /// A manifest is not valid if it has no id, no version or no authors. + /// A manifest is also not valid if the id is polytopia or contains characters other than lowercase letters and underscores. + /// The method also does not add a mod that the configuration disables. + /// For each mod that it does not add, the method writes an error to the log. + /// The method gives each added mod the status and then calls . + /// + /// The dictionary to which the method adds the mods, keyed by the mod id. internal static void RegisterMods(Dictionary mods) { Directory.CreateDirectory(Plugin.MODS_PATH); @@ -346,6 +359,11 @@ ref manifest Plugin.logger.LogError($"Mod id {manifest.id} is invalid in {modContainer}"); continue; } + if (Plugin.config.disabledMods.Contains(manifest.id)) + { + Plugin.logger.LogInfo($"Mod {manifest.id} is disabled, skipping"); + continue; + } if (manifest.version == null) { Plugin.logger.LogError($"Mod version not found in {modContainer}"); @@ -373,34 +391,49 @@ ref manifest CheckDependencies(mods); } + /// + /// Adds one file of a mod to the file list, or reads it as the manifest. + /// If the file is manifest.json at the root of the mod, the method parses it into and does not add it to the list. + /// + /// The path of the file, relative to the root of the mod. + /// The contents of the file. + /// The file list of the mod. + /// The manifest of the mod. The method sets it when the file is manifest.json. private static void ProcessModFile(string fullName, byte[] bytes, List files, ref Mod.Manifest? manifest) { if (fullName == "manifest.json") { manifest = JsonSerializer.Deserialize( bytes, - new JsonSerializerOptions() - { - Converters = { new VersionJson() }, - } + manifestJsonOptions ); return; } files.Add(new(fullName, bytes)); } - internal static void LoadMods(Dictionary mods, out bool dependencyCycle) + /// + /// Sorts the registered mods and loads their assemblies, sprite info files and language files. + /// + /// + /// The method uses . + /// First, it sorts the mods with . If there is a dependency cycle, the method stops. + /// For each mod with the status , it loads the .dll files, the sprite info files and the language files. + /// A sprite info file has the name sprites.json or sprites_*.json. + /// A language file has the name language.json or language_*.json. + /// At the end, it calls Compatibility.ComputeChecksums. + /// + /// Set to true if the mods have a dependency cycle, false otherwise. + internal static void LoadMods(out bool dependencyCycle) { dependencyCycle = !SortMods(Registry.mods); if (dependencyCycle) return; - StringBuilder checksumString = new(); foreach (var (id, mod) in Registry.mods) { if (mod.status != Mod.Status.Success) continue; foreach (var file in mod.files) { - checksumString.Append(JsonSerializer.Serialize(file)); if (Path.GetExtension(file.name) == ".dll") { LoadAssemblyFile(mod, file); @@ -421,15 +454,20 @@ internal static void LoadMods(Dictionary mods, out bool dependencyC ); } } - if (!mod.client && id != "polytopia") - { - checksumString.Append(id); - checksumString.Append(mod.version.ToString()); - } } - Compatibility.HashSignatures(checksumString); - + Compatibility.ComputeChecksums(Registry.mods); } + + /// + /// Checks the dependencies of each mod in a dictionary. + /// + /// + /// A dependency fails if the dictionary does not contain it, or if its version is out of the permitted range. + /// For a required dependency that fails, the method writes an error to the log. + /// It also sets the status of the mod to . + /// For an optional dependency that fails, the method only writes a warning to the log. + /// + /// The mods to check, keyed by the mod id. internal static void CheckDependencies(Dictionary mods) { foreach (var (id, mod) in mods) @@ -437,13 +475,13 @@ internal static void CheckDependencies(Dictionary mods) foreach (var dependency in mod.dependencies ?? Array.Empty()) { string? message = null; - if (!mods.ContainsKey(dependency.id)) + if (!mods.TryGetValue(dependency.id, out Mod? dependencyMod)) { message = $"Dependency {dependency.id} not found"; } else { - Version version = mods[dependency.id].version; + Version version = dependencyMod.version; if ( (dependency.min != null && version < dependency.min) || @@ -470,10 +508,17 @@ internal static void CheckDependencies(Dictionary mods) } /// - /// Sorts mods based on their dependencies using a topological sort. + /// Sorts the mods in a dictionary so that each mod comes after its dependencies. /// - /// The dictionary of mods to sort. - /// True if the mods could be sorted (no circular dependencies), false otherwise. + /// + /// The method uses a topological sort on the mods with the status . + /// It ignores dependencies that are not in the dictionary or that do not have the status . + /// If the sort succeeds, the method replaces the contents of the dictionary. + /// The sorted mods come first, then the mods with a different status. + /// If there is a dependency cycle, the method does not change the dictionary. + /// + /// The mods to sort, keyed by the mod id. + /// True if the sort succeeds, false if the mods have a dependency cycle. internal static bool SortMods(Dictionary mods) { Stopwatch s = new(); @@ -535,10 +580,19 @@ internal static bool SortMods(Dictionary mods) } /// - /// Loads an assembly file from a mod. + /// Loads a .dll file of a mod as an assembly and starts its code. /// - /// The mod the assembly belongs to. - /// The assembly file to load. + /// + /// If the assembly has a subclass of , the method makes an instance of the first one. + /// It calls Initialize and then Load on that instance, and does nothing more. + /// If the assembly has no such subclass, the method calls each static Load(ManualLogSource) method and each static Load() method in the assembly. + /// If a static Load method or the constructor of the subclass throws an exception, the method writes an error to the log. + /// It also sets the status of the mod to . + /// The method catches only exceptions of the type . + /// For this reason, it does not catch an exception from Initialize or from Load on a instance. + /// + /// The mod that contains the file. + /// The .dll file to load. public static void LoadAssemblyFile(Mod mod, Mod.File file) { try @@ -584,9 +638,14 @@ public static void LoadAssemblyFile(Mod mod, Mod.File file) } /// - /// Loads a localization file from a mod. + /// Loads a localization file of a mod and adds its terms to the game localization. /// - /// The mod the localization file belongs to. + /// + /// The file is a JSON object. Each key is a term name, and each value is an object that maps language names to texts. + /// The method gives the data to Loc.BuildAndLoadLocalization. + /// If an error occurs, the method writes the error to the log. + /// + /// The mod that contains the file. /// The localization file to load. public static void LoadLocalizationFile(Mod mod, Mod.File file) { @@ -602,6 +661,17 @@ public static void LoadLocalizationFile(Mod mod, Mod.File file) } } + /// + /// Loads a language file of a mod and adds it to Loc.languagesToAdd. + /// + /// + /// The file is a JSON object that maps term names to texts. + /// If an error occurs, the method writes the error to the log. + /// An error occurs, for example, when a different file already added the same language code. + /// + /// The mod that contains the file. + /// The language file to load. + /// The language code from the file name. It is the text after language_, or an empty string for language.json. public static void LoadLanguageFile(Mod mod, Mod.File file, string languageName) { try @@ -620,74 +690,46 @@ public static void LoadLanguageFile(Mod mod, Mod.File file, string languageName) } /// - /// Loads a sprite file from a mod. - /// - /// The mod the sprite file belongs to. - /// The sprite file to load. - public static void LoadSpriteFile(Mod mod, Mod.File file) - { - string name = Path.GetFileNameWithoutExtension(file.name); - Vector2 pivot = name.Split("_")[0] switch - { - "field" => new(0.5f, 0.0f), - "mountain" => new(0.5f, -0.375f), - _ => new(0.5f, 0.5f), - }; - float pixelsPerUnit = 2112f; - if (Registry.spriteInfos.ContainsKey(name)) - { - Visual.SpriteInfo spriteData = Registry.spriteInfos[name]; - pivot = spriteData.pivot ?? pivot; - pixelsPerUnit = spriteData.pixelsPerUnit ?? pixelsPerUnit; - } - Sprite sprite = Visual.BuildSprite(file.bytes, pivot, pixelsPerUnit); - GameManager.GetSpriteAtlasManager().cachedSprites.TryAdd("Heads", new()); - GameManager.GetSpriteAtlasManager().cachedSprites["Heads"].Add(name, sprite); - Registry.sprites.Add(name, sprite); - } - - /// - /// Updates a sprite with new information. + /// Loads a PNG file of a mod as a texture and adds it to . + /// The key is the lowercase file name without the extension. + /// The method does not make a sprite. Visual.CreateSprites makes the sprites later. /// - /// The name of the sprite to update. - public static void UpdateSprite(string name) + /// The mod that contains the file. The method does not use this parameter. + /// The PNG file to load. + public static void LoadTextureFile(Mod mod, Mod.File file) { - if (Registry.spriteInfos.ContainsKey(name) && Registry.sprites.ContainsKey(name)) - { - Visual.SpriteInfo spriteData = Registry.spriteInfos[name]; - Sprite sprite = Visual.BuildSpriteWithTexture( - Registry.sprites[name].texture, - spriteData.pivot, - spriteData.pixelsPerUnit - ); - GameManager.GetSpriteAtlasManager().cachedSprites["Heads"][name] = sprite; - Registry.sprites[name] = sprite; - } + string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); + Texture2D texture2D = Visual.BuildTexture(file.bytes); + Registry.textures[name] = texture2D; } /// - /// Loads a sprite info file from a mod. + /// Loads a sprite info file of a mod and adds its sprite infos to . /// - /// The mod the sprite info file belongs to. + /// + /// The method changes each sprite name and each sprite origin name to lowercase. + /// A sprite info replaces an existing sprite info with the same name. + /// If an error occurs, the method writes the error to the log. + /// + /// The mod that contains the file. /// The sprite info file to load. - /// A dictionary of sprite information, or null if an error occurred. + /// The sprite infos from the file, keyed by the sprite name as the file gives it, or null if an error occurs. public static Dictionary? LoadSpriteInfoFile(Mod mod, Mod.File file) { try { var deserialized = JsonSerializer.Deserialize>( file.bytes, - new JsonSerializerOptions() - { - Converters = { new Vector2Json() }, - } + spriteInfoJsonOptions ); if (deserialized != null) { foreach (var kvp in deserialized) { - Registry.spriteInfos[kvp.Key] = kvp.Value; + if (kvp.Value.spriteOrigin?.name != null) + kvp.Value.spriteOrigin.name = kvp.Value.spriteOrigin.name.ToLowerInvariant(); + Registry.spriteInfos[kvp.Key.ToLowerInvariant()] = kvp.Value; } } @@ -702,181 +744,149 @@ public static void UpdateSprite(string name) } /// - /// Loads an audio file from a mod. + /// Loads an audio file of a mod and adds it to . /// - /// The mod the audio file belongs to. + /// + /// The method uses Audio.BuildAudioClip to make the audio clip. + /// It puts the clip on a new audio source that stays loaded when the scene changes. + /// The key is the lowercase file name without the extension. + /// If an error occurs, the method writes the error to the log. + /// + /// The mod that contains the file. /// The audio file to load. - public static void LoadAudioFile(Mod mod, Mod.File file) + private static void LoadAudioFile(Mod mod, Mod.File file) { - // AudioSource audioSource = new GameObject().AddComponent(); - // GameObject.DontDestroyOnLoad(audioSource); - // audioSource.clip = Managers.Audio.BuildAudioClip(file.bytes); - // Registry.audioClips.Add(Path.GetFileNameWithoutExtension(file.name), audioSource); - // TODO: issue #71 + string name = Path.GetFileNameWithoutExtension(file.name).ToLowerInvariant(); + try + { + AudioClip clip = Managers.Audio.BuildAudioClip(file.bytes, name); + AudioSource audioSource = new GameObject($"PolyModAudio_{name}").AddComponent(); + UnityEngine.Object.DontDestroyOnLoad(audioSource.gameObject); + audioSource.clip = clip; + Registry.audioClips[name] = audioSource; + + Plugin.logger.LogInfo( + $"Registered audio {name} file from {mod.id} mod" + + $" ({clip.channels}ch {clip.frequency}Hz {clip.length:F2}s)." + ); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading audio {name} file from {mod.id} mod: {e.Message}"); + } } /// - /// Loads a prefab info file from a mod and creates a new unit prefab. + /// Loads a prefabs file of a mod. + /// The method adds its unit, improvement and resource prefab infos to the lists in Prefabs. + /// If the file contains JSON null, the method does nothing. + /// If an error occurs, the method writes the error to the log. /// - /// The mod the prefab info file belongs to. - /// The prefab info file to load. - public static void LoadPrefabInfoFile(Mod mod, Mod.File file) + /// The mod that contains the file. + /// The prefabs file to load. + public static void LoadPrefabsFile(Mod mod, Mod.File file) { try { - var prefab = JsonSerializer.Deserialize(file.bytes, new JsonSerializerOptions - { - Converters = { new Vector2Json() }, - PropertyNameCaseInsensitive = true, - }); - if (prefab == null || prefab.type != Visual.PrefabType.Unit || prefab.visualParts.Count == 0) - return; - - if (Registry.unitPrefabs.Keys.Any(pref => pref.name == prefab.name)) - { - Plugin.logger.LogInfo($"Prefab {prefab.name} already exists, skipping."); - } - var baseUnit = PrefabManager.GetPrefab(UnitData.Type.Warrior, TribeType.Imperius, SkinType.Default); - if (baseUnit == null) - return; - - var unitInstance = GameObject.Instantiate(baseUnit); - if (unitInstance == null) + var prefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); + if (prefab == null) return; - var spriteContainer = unitInstance.transform.GetChild(0); - var material = ClearExistingPartsAndExtractMaterial(spriteContainer); - - var visualParts = ApplyVisualParts(prefab, spriteContainer, material); - - Transform? headPositionMarker = null; - foreach (var vp in visualParts) - { - if (vp.visualPart.gameObject.name == prefab.headPositionMarker) - { - headPositionMarker = vp.visualPart.gameObject.transform; - break; - } - } - - unitInstance.headPositionMarker = headPositionMarker ?? visualParts[0].visualPart.transform; + Prefabs.unitInfos.AddRange(prefab.units); + Prefabs.improvementInfos.AddRange(prefab.improvements); + Prefabs.resourceInfos.AddRange(prefab.resources); - var svr = unitInstance.GetComponent(); - svr.visualParts = visualParts.ToArray(); - - GameObject.DontDestroyOnLoad(unitInstance.gameObject); - Registry.unitPrefabs.Add(prefab, unitInstance.GetComponent()); - - Plugin.logger.LogInfo($"Registered prefab {prefab.name} info from {mod.id} mod."); + Plugin.logger.LogInfo($"Registered prefabs {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); } catch (Exception e) { - Plugin.logger.LogError($"Error on loading prefab {Path.GetFileNameWithoutExtension(file.name)} info from {mod.id} mod: {e.StackTrace}."); + Plugin.logger.LogError($"Error on loading prefabs {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); } } /// - /// Clears existing visual parts from a prefab and extracts the material. + /// Loads a unit prefab file of a mod and adds its unit prefab info to Prefabs.unitInfos. + /// If the file contains JSON null, the method does nothing. + /// If an error occurs, the method writes the error to the log. /// - /// The transform containing the sprite parts. - /// The material of the original sprite parts. - private static Material? ClearExistingPartsAndExtractMaterial(Transform spriteContainer) + /// The mod that contains the file. + /// The unit prefab file to load. + public static void LoadUnitPrefabFile(Mod mod, Mod.File file) { - Material? material = null; - for (int i = 0; i < spriteContainer.childCount; i++) + try { - var child = spriteContainer.GetChild(i); - if (child.gameObject.name == "Head") - { - var renderer = child.GetComponent(); - if (renderer != null) - material = renderer.material; - } - GameObject.Destroy(child.gameObject); + var unitPrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); + if (unitPrefab == null) + return; + + Prefabs.unitInfos.Add(unitPrefab); + + Plugin.logger.LogInfo($"Registered unit prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading unit prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); } - return material; } /// - /// Applies new visual parts to a prefab. + /// Loads an improvement prefab file of a mod and adds its improvement prefab info to Prefabs.improvementInfos. + /// If the file contains JSON null, the method does nothing. + /// If an error occurs, the method writes the error to the log. /// - /// A list of visual part information. - /// The transform to add the parts to. - /// The material to use for the parts. - /// A list of the created visual parts. - private static List ApplyVisualParts( - Visual.PrefabInfo prefab, - Transform spriteContainer, - Material? material) + /// The mod that contains the file. + /// The improvement prefab file to load. + public static void LoadImprovementPrefabFile(Mod mod, Mod.File file) { - if (prefab.visualParts.Count == 0) - return new List(); + try + { + var improvementPrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); + if (improvementPrefab == null) + return; - List parts = new(); + Prefabs.improvementInfos.Add(improvementPrefab); - foreach (var info in prefab.visualParts) + Plugin.logger.LogInfo($"Registered improvement prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) { - parts.Add(CreateVisualPart(info, spriteContainer, material)); + Plugin.logger.LogError($"Error on loading improvement prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); } - - return parts; } /// - /// Creates a single visual part for a prefab. + /// Loads a resource prefab file of a mod and adds its resource prefab info to Prefabs.resourceInfos. + /// If the file contains JSON null, the method does nothing. + /// If an error occurs, the method writes the error to the log. /// - /// The information for the visual part. - /// The parent transform for the part. - /// The material to use for the part. - /// The created visual part. - private static SkinVisualsReference.VisualPart CreateVisualPart( - Visual.VisualPartInfo info, - Transform parent, - Material? material) + /// The mod that contains the file. + /// The resource prefab file to load. + public static void LoadResourcePrefabFile(Mod mod, Mod.File file) { - var visualPartObj = new GameObject(info.gameObjectName); - visualPartObj.transform.SetParent(parent); - visualPartObj.transform.position = info.coordinates; - visualPartObj.transform.localScale = info.scale; - visualPartObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); - - var outlineObj = new GameObject("Outline"); - outlineObj.transform.SetParent(visualPartObj.transform); - outlineObj.transform.position = info.coordinates; - outlineObj.transform.localScale = info.scale; - outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); - - var visualPart = new SkinVisualsReference.VisualPart + try { - DefaultSpriteName = info.baseName, - visualPart = visualPartObj, - outline = outlineObj, - tintable = info.tintable - }; - - var renderer = visualPartObj.AddComponent(); - renderer.material = material; - renderer.sortingLayerName = "Units"; - renderer.sortingOrder = info.tintable ? 0 : 1; - - visualPart.renderer = new SkinVisualsReference.RendererUnion { spriteRenderer = renderer }; - - var outlineRenderer = outlineObj.AddComponent(); - outlineRenderer.material = material; - outlineRenderer.sortingLayerName = "Units"; - outlineRenderer.sortingOrder = -1; + var resourcePrefab = JsonSerializer.Deserialize(file.bytes, prefabJsonOptions); + if (resourcePrefab == null) + return; - visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { spriteRenderer = outlineRenderer }; + Prefabs.resourceInfos.Add(resourcePrefab); - return visualPart; + Plugin.logger.LogInfo($"Registered resource prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod."); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on loading resource prefab {Path.GetFileNameWithoutExtension(file.name)} file from {mod.id} mod: {e.StackTrace}."); + } } /// - /// Loads and applies a game logic data patch from a mod. + /// Merges a GLD patch of a mod into the GLD. + /// The method uses , which changes in place. + /// If an error occurs, the method writes the error to the log and sets the status of the mod to . /// - /// The mod the patch belongs to. - /// The original game logic data. - /// The patch to apply. + /// The mod that contains the patch. + /// The GLD as a JSON object. The method changes this object. + /// The patch to merge. public static void LoadGameLogicDataPatch(Mod mod, JObject gld, JObject patch) { try @@ -893,9 +903,10 @@ public static void LoadGameLogicDataPatch(Mod mod, JObject gld, JObject patch) } /// - /// Loads an asset bundle from a mod. + /// Loads a .bundle file of a mod as an asset bundle and adds it to . + /// The key is the file name without the extension. /// - /// The mod the asset bundle belongs to. + /// The mod that contains the file. The method does not use this parameter. /// The asset bundle file to load. public static void LoadAssetBundle(Mod mod, Mod.File file) { @@ -906,17 +917,18 @@ public static void LoadAssetBundle(Mod mod, Mod.File file) } /// - /// Processes the merged game logic data after all mods have been loaded and patched. + /// Uses the merged GLD to make enum mappings and to fill the PolyMod overrides. + /// The method calls , , and in sequence. + /// If an error occurs, the method writes the error to the log. /// - /// The game logic data object to populate. - /// The root JObject of the merged game logic data. + /// The game logic data. The method does not use this parameter. + /// The root JSON object of the merged GLD. internal static void ProcessGameLogicData(GameLogicData gameLogicData, JObject rootObject) { try { CreateMappings(rootObject); ProcessCustomTribes(); - ProcessPrefabs(); ProcessEmbarkOverrides(); ProcessAttractOverrides(); } @@ -926,6 +938,9 @@ internal static void ProcessGameLogicData(GameLogicData gameLogicData, JObject r } } + /// + /// Adds each tribe in to GameLogicData.legacyTribeTypesOrder, if the list does not contain it. + /// internal static void ProcessCustomTribes() { foreach (var tribe in Registry.customTribes) @@ -938,9 +953,20 @@ internal static void ProcessCustomTribes() } /// - /// Creates EnumCache mappings for custom enum values and invokes type handlers. + /// Makes EnumCache mappings for new GLD entries and calls the type handlers. /// - /// + /// + /// The method does two passes over all entries of all data categories in the GLD. + /// In the first pass, it uses only entries that have an idx, in categories with shouldCreateCache set to true. + /// If the type of the category is not an enum, the method writes a warning to the log and ignores the entry. + /// If idx is -1, the method sets idx to the next free index of the enum type of the category, from . + /// If allowUnsafeIndexes is true, the method also uses an entry with an idx larger than all existing enum values. + /// The method ignores all other entries in the first pass. + /// For each entry that it uses, it calls EnumCache.AddMapping two times. The first call adds the name, and the second call adds the type. + /// Then it calls the type handlers of the category with the flag set to true. + /// In the second pass, the method calls the type handlers for all entries of categories in , with the flag set to false. + /// + /// The root JSON object of the merged GLD. internal static void CreateMappings(JObject rootObject) { foreach (JToken jtoken in rootObject.SelectTokens("$.*.*").ToArray()) @@ -967,8 +993,8 @@ internal static void CreateMappings(JObject rootObject) if ((int)token["idx"] == -1) { - token["idx"] = Registry.autoidx; - Registry.autoidx++; + token["idx"] = Registry.GetAutoIndex(targetType); + Registry.IncrementAutoIndex(targetType); } else if (Plugin.config.allowUnsafeIndexes) { @@ -1026,43 +1052,62 @@ internal static void CreateMappings(JObject rootObject) } /// - /// Processes the prefab registry and populates the PrefabManager with custom prefabs. + /// Loads the prefab files in . /// - internal static void ProcessPrefabs() + /// + /// The method uses the file name to select the load method. + /// It calls for prefabs.json, for unitPrefab.json, + /// for improvementPrefab.json and for resourcePrefab.json. + /// Each of these names can also have a suffix that starts with an underscore, for example unitPrefab_knight.json. + /// The method ignores other files. + /// If an error occurs, the method writes the error to the log and stops. + /// + internal static void ProcessFilesQueue() { - Plugin.logger.LogInfo($"Processing prefabs, count: {Registry.prefabNames.Count}."); - foreach (KeyValuePair item in Registry.prefabNames) + try { - UnitData.Type unitPrefabType = UnitData.Type.Scout; - string prefabId = item.Value; - int hashKey = PrefabManager.GetSkinnedHashKey((UnitData.Type)item.Key, TribeType.None, SkinType.Default); - if (!Enum.TryParse(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(prefabId), out unitPrefabType)) // Existing unit prefabs + foreach ((Mod mod, Mod.File file) in Registry.filesQueueToBeProcessedAfterGLDMerge) { - KeyValuePair prefabInfo = Registry.unitPrefabs.FirstOrDefault( - kv => kv.Key.name == prefabId - ); - if (!EqualityComparer.Default.Equals(prefabInfo.Key, default)) + Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); + if (prefabsMatch.Success) { - Visual.UnitPrefabInfo unitPrefabInfo = new( - EnumCache.GetName((UnitData.Type)item.Key), - EnumCache.GetName(TribeType.None), - EnumCache.GetName(SkinType.Default) - ); - Visual.customPrefabs.Add(unitPrefabInfo, prefabInfo.Value); - Plugin.logger.LogInfo($"Using custom prefab {prefabId} for unit {item.Key}."); + LoadPrefabsFile(mod, file); + continue; + } + + Match unitPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^unitPrefab(?:_(.*))?\.json$"); + if (unitPrefabMatch.Success) + { + LoadUnitPrefabFile(mod, file); + continue; + } + + Match improvementPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^improvementPrefab(?:_(.*))?\.json$"); + if (improvementPrefabMatch.Success) + { + LoadImprovementPrefabFile(mod, file); continue; } + + Match resourcePrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^resourcePrefab(?:_(.*))?\.json$"); + if (resourcePrefabMatch.Success) + { + LoadResourcePrefabFile(mod, file); + continue; + } + } - Plugin.logger.LogInfo($"Using existing prefab {EnumCache.GetName(unitPrefabType)} for unit {item.Key}."); - PrefabManager.units.TryAdd( - hashKey, - PrefabManager.units[PrefabManager.GetSkinnedHashKey(unitPrefabType, TribeType.None, SkinType.Default)] - ); + } + catch (Exception e) + { + Plugin.logger.LogError($"Error on processing post gld merge files queue : {e.StackTrace}"); } } /// - /// Processes embark overrides by mapping original embark unit types to configured overrides. + /// Changes the unit ids in Main.embarkNames to unit types and adds them to Main.embarkOverrides. + /// Each entry maps a unit to the unit that it becomes when it embarks. + /// If a unit id is not valid, the method writes an error to the log and continues with the next entry. /// internal static void ProcessEmbarkOverrides() { @@ -1083,7 +1128,10 @@ internal static void ProcessEmbarkOverrides() } /// - /// Processes attract overrides by mapping improvements to resources and terrain types based on configured overrides. + /// Changes the ids in Main.attractsResourceNames and Main.attractsTerrainNames to enum values. + /// The method adds the results to Main.attractsResourceOverrides and Main.attractsTerrainOverrides. + /// Each entry maps an improvement to the resource that it attracts, or to the terrain on which it attracts resources. + /// If an id is not valid, the method writes an error to the log and continues with the next entry. /// internal static void ProcessAttractOverrides() { diff --git a/src/Managers/Audio.cs b/src/Managers/Audio.cs index 100cec7..c7c7475 100644 --- a/src/Managers/Audio.cs +++ b/src/Managers/Audio.cs @@ -1,23 +1,29 @@ using HarmonyLib; -using Polytopia.Data; using UnityEngine; using PolytopiaBackendBase.Common; namespace PolyMod.Managers; /// -/// Manages custom audio for PolyMod. +/// The manager for custom audio. +/// It replaces game music, nature sounds, and sound effects with the registered audio clips of mods. +/// At this time, is a stub, so the registered clips have no audio data. /// public static class Audio { /// - /// Patches the music data to get custom nature audio clips. + /// A Harmony prefix on MusicData.GetNatureAudioClip. + /// It finds a registered nature audio clip for the tribe and skin. /// + /// The audio clip that the game uses. The patch sets it to the mod clip, if one exists. + /// The tribe of the audio clip. + /// The skin of the audio clip. + /// False if a mod clip exists, which skips the original method. True if not. [HarmonyPrefix] [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetNatureAudioClip))] private static bool MusicData_GetNatureAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) { - AudioClip? audioClip = Registry.GetAudioClip("nature", Util.GetStyle(type, skinType)); + AudioClip? audioClip = Registry.GetAudioClip("nature", type, skinType); if (audioClip != null) { __result = audioClip; @@ -27,13 +33,18 @@ private static bool MusicData_GetNatureAudioClip(ref AudioClip __result, TribeTy } /// - /// Patches the music data to get custom music audio clips. + /// A Harmony prefix on MusicData.GetMusicAudioClip. + /// It finds a registered music audio clip for the tribe and skin. /// + /// The audio clip that the game uses. The patch sets it to the mod clip, if one exists. + /// The tribe of the audio clip. + /// The skin of the audio clip. + /// False if a mod clip exists, which skips the original method. True if not. [HarmonyPrefix] [HarmonyPatch(typeof(MusicData), nameof(MusicData.GetMusicAudioClip))] private static bool MusicData_GetMusicAudioClip(ref AudioClip __result, TribeType type, SkinType skinType) { - AudioClip? audioClip = Registry.GetAudioClip("music", Util.GetStyle(type, skinType)); + AudioClip? audioClip = Registry.GetAudioClip("music", type, skinType); if (audioClip != null) { __result = audioClip; @@ -43,15 +54,20 @@ private static bool MusicData_GetMusicAudioClip(ref AudioClip __result, TribeTyp } /// - /// Patches the audio SFX data to get custom sound effect clips. + /// A Harmony prefix on AudioSFXData.GetClip. + /// It finds a registered audio clip with the name of the sound effect type, for the skin. /// + /// The audio clip that the game uses. The patch sets it to the mod clip, if one exists. + /// The sound effect type. + /// The skin of the audio clip. + /// False if a mod clip exists, which skips the original method. True if not. [HarmonyPrefix] [HarmonyPatch(typeof(AudioSFXData), nameof(AudioSFXData.GetClip))] private static bool AudioSFXData_GetClip(ref AudioClip __result, SFXTypes id, SkinType skinType) { AudioClip? audioClip = Registry.GetAudioClip( EnumCache.GetName(id), - EnumCache.GetName(skinType) + skin: skinType ); if (audioClip != null) { @@ -62,18 +78,19 @@ private static bool AudioSFXData_GetClip(ref AudioClip __result, SFXTypes id, Sk } /// - /// Builds an audio clip from raw byte data. + /// A stub for the method that makes an audio clip from the bytes of an audio file. + /// It does not read the data. It only gives a new empty audio clip. /// - /// The byte data of the audio file. - /// The created audio clip. - public static AudioClip BuildAudioClip(byte[] data) + /// The bytes of the audio file. The method does not use them. + /// The name for the audio clip. The method does not use it. + /// A new empty audio clip with no name and no audio data. + public static AudioClip BuildAudioClip(byte[] data, string name = "polymod_audio") { - // TODO: This is a placeholder. The actual implementation is tracked in issue #71. - return new AudioClip(new()); + return new(); } /// - /// Initializes the Audio manager by patching the necessary methods. + /// Applies all Harmony patches in the class. /// internal static void Init() { diff --git a/src/Managers/AutoUpdate.cs b/src/Managers/AutoUpdate.cs deleted file mode 100644 index 58ea639..0000000 --- a/src/Managers/AutoUpdate.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System.Diagnostics; -using System.IO.Compression; -using System.Text.Json; -using HarmonyLib; -using UnityEngine; - -namespace PolyMod.Managers; - -/// -/// Manages the automatic update process for PolyMod. -/// -internal static class AutoUpdate -{ - /// - /// Checks for updates when the start screen is shown. - /// - [HarmonyPostfix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] - private static void StartScreen_UI2_OnShow() - { - if (!Plugin.config.autoUpdate) return; - if (Environment.GetEnvironmentVariable("WINEPREFIX") != null) - { - Plugin.logger.LogError("Autoupdate is not supported on Wine!"); - return; - } - HttpClient client = new(); - client.DefaultRequestHeaders.Add("User-Agent", "PolyMod"); - try - { - // Fetch release information from GitHub API - var json = JsonDocument.Parse( - client.GetAsync("https://api.github.com/repos/PolyModdingTeam/PolyMod/releases").UnwrapAsync() - .Content.ReadAsStringAsync().UnwrapAsync() - ); - JsonElement? latest = null; - for (int i = 0; i < json.RootElement.GetArrayLength(); i++) - { - var release = json.RootElement[i]; - if (release.GetProperty("prerelease").GetBoolean() && !Plugin.config.updatePrerelease) continue; - latest = release; - break; - } - string newVersion = latest?.GetProperty("tag_name").GetString()!.TrimStart('v')!; - if (newVersion.IsVersionOlderOrEqual(Plugin.VERSION)) return; - - // Determine the correct BepInEx URL for the current OS - string os = Application.platform switch - { - RuntimePlatform.WindowsPlayer => "win", - RuntimePlatform.LinuxPlayer => "linux", - RuntimePlatform.OSXPlayer => "macos", - _ => "unknown", - }; - if (os == "unknown") - { - Plugin.logger.LogError("Unsupported platform for autoupdate!"); - return; - } - string bepinex_url = client - .GetAsync("https://polymod.dev/data/bepinex.txt").UnwrapAsync() - .Content.ReadAsStringAsync().UnwrapAsync() - .Replace("{os}", os); - - // The actual update logic - void Update() - { - Time.timeScale = 0; - - // Download new PolyMod DLL and BepInEx files - File.WriteAllBytes( - Path.Combine(Plugin.BASE_PATH, "PolyMod.new.dll"), - client.GetAsync(latest?.GetProperty("assets")[0].GetProperty("browser_download_url").GetString()!).UnwrapAsync() - .Content.ReadAsByteArrayAsync().UnwrapAsync() - ); - using ZipArchive bepinex = new(client.GetAsync(bepinex_url).UnwrapAsync().Content.ReadAsStream()); - bepinex.ExtractToDirectory(Path.Combine(Plugin.BASE_PATH, "New"), overwriteFiles: true); - - // Create and run the appropriate update script for the OS - ProcessStartInfo info = new() - { - WorkingDirectory = Path.Combine(Plugin.BASE_PATH), - CreateNoWindow = true, - }; - if (Application.platform == RuntimePlatform.WindowsPlayer) - { - string batchPath = Path.Combine(Plugin.BASE_PATH, "update.bat"); - File.WriteAllText(batchPath, $@" - @echo off - echo Waiting for Polytopia.exe to exit... - :waitloop - tasklist | findstr /I ""Polytopia.exe"" >nul - if not errorlevel 1 ( - timeout /T 1 >nul - goto waitloop - ) - - echo Updating... - robocopy ""New"" . /E /MOVE /NFL /NDL /NJH /NJS /NP >nul - rmdir /S /Q ""New"" - del /F /Q ""BepInEx\plugins\PolyMod.dll"" - move /Y ""PolyMod.new.dll"" ""BepInEx\plugins\PolyMod.dll"" - - echo Launching game... - start steam://rungameid/874390 - timeout /T 3 /NOBREAK >nul - exit - "); - info.FileName = "cmd.exe"; - info.Arguments = $"/C start \"\" \"{batchPath}\""; - info.WorkingDirectory = Plugin.BASE_PATH; - info.CreateNoWindow = true; - info.UseShellExecute = false; - } - if (Application.platform == RuntimePlatform.LinuxPlayer || Application.platform == RuntimePlatform.OSXPlayer) - { - string bashPath = Path.Combine(Plugin.BASE_PATH, "update.sh"); - File.WriteAllText(bashPath, $@" - #!/bin/bash - - echo ""Waiting for Polytopia to exit..."" - while pgrep -x ""Polytopia"" > /dev/null; do - sleep 1 - done - - echo ""Updating..."" - mv New/* . && rm -rf New - rm -f BepInEx/plugins/PolyMod.dll - mv -f PolyMod.new.dll BepInEx/plugins/PolyMod.dll - - echo ""Launching game..."" - xdg-open steam://rungameid/874390 & - - sleep 3 - exit 0 - "); - - System.Diagnostics.Process chmod = new System.Diagnostics.Process(); - chmod.StartInfo.FileName = "chmod"; - chmod.StartInfo.Arguments = $"+x \"{bashPath}\""; - chmod.StartInfo.UseShellExecute = false; - chmod.StartInfo.CreateNoWindow = true; - chmod.Start(); - chmod.WaitForExit(); - - info.FileName = "/bin/bash"; - info.Arguments = $"\"{bashPath}\""; - info.WorkingDirectory = Plugin.BASE_PATH; - info.CreateNoWindow = true; - info.UseShellExecute = false; - } - Process.Start(info); - Application.Quit(); - } - - // Show a popup to the user asking if they want to update - PopupManager.GetBasicPopupWithData(new( - Localization.Get("polymod.autoupdate"), - Localization.Get("polymod.autoupdate.description"), - new(new PopupBase.PopupButtonData[] { - new( - "polymod.autoupdate.update", - PopupBase.PopupButtonData.States.None, - (Il2CppSystem.Action)Update - ) - })) - ).Show(); - } - catch (Exception e) - { - Plugin.logger.LogError($"Failed to check updates: {e.Message}"); - } - } - - /// - /// Initializes the AutoUpdate manager by patching the necessary methods. - /// - internal static void Init() - { - Harmony.CreateAndPatchAll(typeof(AutoUpdate)); - } -} \ No newline at end of file diff --git a/src/Managers/Compatibility.cs b/src/Managers/Compatibility.cs index 1d55bb7..524833b 100644 --- a/src/Managers/Compatibility.cs +++ b/src/Managers/Compatibility.cs @@ -1,39 +1,162 @@ using HarmonyLib; -using System.Text; +using Il2CppInterop.Runtime; using UnityEngine; -using UnityEngine.EventSystems; namespace PolyMod.Managers; /// -/// Manages compatibility checks for mods, including checksum verification and version warnings. +/// The compatibility checks for mods. They compare mod checksums with the checksums of saved games. +/// They also show the warnings for an invalid launch and for a new game version. /// internal static class Compatibility { /// - /// The checksum of all loaded mods. + /// The global checksum of all loaded mods that are not client-side mods. /// internal static string checksum = string.Empty; /// - /// Whether the game settings should be reset due to a change in mods. + /// The flag that tells if the tribe and skin selection must go back to the default values. + /// It is true when the global checksum is different from the checksum of the last start. /// internal static bool shouldResetSettings = false; private static bool sawSignatureWarning; + private const string downloadLink = "https://polymod.dev/download/"; /// - /// Hashes the signatures of all loaded mods to create a checksum. + /// Calculates the checksum of each mod and the global checksum. + /// The method uses only the mods that loaded successfully, and skips client-side mods and the polytopia mod. + /// It puts each checksum in and the global checksum in . /// - /// A string builder containing the signatures to hash. - public static void HashSignatures(StringBuilder checksumString) + /// The mods, with their ids as keys. + public static void ComputeChecksums(Dictionary mods) { - checksum = Util.Hash(checksumString); + List signatures = new(); + foreach (var (id, mod) in mods) + { + if (mod.status != Mod.Status.Success) continue; + if (mod.client || id == "polytopia") continue; + + mod.checksum = ComputeModChecksum(mod); + signatures.Add($"{id}:{mod.checksum}"); + } + signatures.Sort(StringComparer.Ordinal); + + checksum = Util.Hash(string.Join("\n", signatures)); + } + + /// + /// Calculates the checksum of one mod from its id, its version, and the names and contents of its files. + /// The method skips directory entries and sorts the files by name, so the order of the files has no effect. + /// + /// The mod to calculate the checksum for. + /// The SHA256 checksum of the mod as a hexadecimal string. + public static string ComputeModChecksum(Mod mod) + { + List entries = new(); + foreach (Mod.File file in mod.files) + { + string name = file.name.Replace('\\', '/'); + if (name.EndsWith('/')) continue; + + entries.Add($"{name}:{Util.HashBytes(file.bytes)}"); + } + entries.Sort(StringComparer.Ordinal); + + return Util.Hash($"{mod.id}:{mod.version}\n{string.Join("\n", entries)}"); + } + + /// + /// Gets the player prefs key that keeps the global checksum for a saved game. + /// + /// The id of the saved game, as a Guid or a string. + /// The player prefs key. + private static string StateChecksumKey(object gameId) + { + return Plugin.STATE_CHECKSUM_KEY_PREFIX + NormalizeGameId(gameId); + } + + /// + /// Changes a game id to one standard text form, so that one saved game always has one key. + /// The game gives ids as a Guid in some methods and as a string in other methods. + /// The method removes the braces and changes all letters to lowercase. + /// + /// The id of the saved game, as a Guid or a string. + /// The game id in lowercase, without braces. + internal static string NormalizeGameId(object gameId) + { + return gameId.ToString()!.Trim('{', '}').ToLowerInvariant(); + } + + /// + /// Gets the path of the legacy .signatures file for a saved game. + /// The file is in the persistent data folder of the game. + /// + /// The id of the saved game, as a Guid or a string. + /// The path of the legacy signature file. + private static string LegacyStateChecksumPath(object gameId) + { + return Path.Combine(Application.persistentDataPath, $"{NormalizeGameId(gameId)}.signatures"); + } + + /// + /// Writes the current global checksum to the player prefs for a saved game. + /// + /// The id of the saved game, as a Guid or a string. + internal static void SaveStateChecksum(object gameId) + { + PlayerPrefs.SetString(StateChecksumKey(gameId), checksum); + PlayerPrefs.Save(); + } + + /// + /// Reads the global checksum that the player prefs keep for a saved game. + /// If the player prefs do not have the checksum, the method reads the legacy signature file. + /// It then writes that checksum to the player prefs and deletes the legacy file. + /// + /// The id of the saved game, as a Guid or a string. + /// The saved checksum, or an empty string if there is no saved checksum. + internal static string ReadStateChecksum(object gameId) + { + string key = StateChecksumKey(gameId); + if (PlayerPrefs.HasKey(key)) + return PlayerPrefs.GetString(key); + + string legacyPath = LegacyStateChecksumPath(gameId); + if (!File.Exists(legacyPath)) + return string.Empty; + + string legacyChecksum = File.ReadAllText(legacyPath); + PlayerPrefs.SetString(key, legacyChecksum); + PlayerPrefs.Save(); + File.Delete(legacyPath); + return legacyChecksum; + } + + /// + /// Deletes the saved checksum of a saved game from the player prefs. + /// It also deletes the legacy signature file if it exists. + /// + /// The id of the saved game, as a Guid or a string. + internal static void DeleteStateChecksum(object gameId) + { + PlayerPrefs.DeleteKey(StateChecksumKey(gameId)); + PlayerPrefs.Save(); + + string legacyPath = LegacyStateChecksumPath(gameId); + if (File.Exists(legacyPath)) + File.Delete(legacyPath); } /// - /// Checks the signature of a saved game to ensure it is compatible with the current mods. + /// Compares the saved checksum of a saved game with the current global checksum. + /// If the checksums are different and debug mode is off, the method shows a mismatch popup. + /// If the saved checksum is empty or cannot be read, the method skips the check. + /// If sawSignatureWarning is true, the method sets it to false and skips the check. /// - /// True if the signatures match or if the check is ignored, false otherwise. + /// The original game action. The method does not use this parameter. + /// The id of the saved game. + /// False if the checksums are different and debug mode is off. True in all other conditions. private static bool CheckSignatures(Action action, Il2CppSystem.Guid gameId) { if (sawSignatureWarning) @@ -46,7 +169,7 @@ private static bool CheckSignatures(Action action, Il2CppSystem.Guid gameId) try { Plugin.logger.LogInfo($"Getting checksum for state {gameId}"); - stateChecksum = File.ReadAllText(Path.Combine(Application.persistentDataPath, $"{gameId}.signatures")); + stateChecksum = ReadStateChecksum(gameId); Plugin.logger.LogInfo($"Checksum found."); } catch @@ -81,12 +204,54 @@ private static bool CheckSignatures(Action action, Il2CppSystem.Guid gameId) } /// - /// Performs compatibility checks when the start screen is shown. + /// + /// Postfix patch for StartScreen_UI2.OnShow. It does the compatibility checks when the start screen opens. + /// If the launch is not valid and the platform is not Android, it shows a popup with the exit and download buttons, and stops. + /// + /// + /// It writes the global checksum to the checksum file. If the checksum changed since the last start, it sets . + /// + /// + /// If the game version is newer than the version of the last warning, it saves the game version and shows a version mismatch popup. + /// If there is no version of the last warning, it uses the game version that PolyMod supports. + /// /// [HarmonyPostfix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] private static void StartScreen_UI2_OnShow() { + if (!Plugin.ValidLaunch && Application.platform != RuntimePlatform.Android) + { + BasicPopup invalidLaunchPopup = PopupManager.GetBasicPopupWithData( + new( + Localization.Get("polymod.title.invalid"), + Localization.Get("polymod.description.invalid"), + new PopupBase.PopupButtonData[] { + new( + "buttons.exitgame", + PopupBase.PopupButtonData.States.None, + callback: (Il2CppSystem.Action)Application.Quit, + closesPopup: false + ), + new( + "buttons.download.launcher", + PopupBase.PopupButtonData.States.None, + callback: DelegateSupport.ConvertDelegate(OpenSite), + closesPopup: false + ) + } + ) + ); + invalidLaunchPopup.IsUnskippable = true; + invalidLaunchPopup.Show(); + + void OpenSite() + { + NativeHelpers.OpenURL(downloadLink, false); + Application.Quit(); + } + return; + } string lastChecksum = checksum; try { @@ -133,8 +298,10 @@ private static void StartScreen_UI2_OnShow() } /// - /// Checks the signature of a pass-and-play game before loading it. + /// Prefix patch for GameInfoPopup.OnMainButtonClicked. It compares the checksum of the game in the popup before the game opens. /// + /// The game info popup. + /// False to stop the game from opening when the checksums are different. True to let the original method run. [HarmonyPrefix] [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.OnMainButtonClicked))] private static bool GameInfoPopup_OnMainButtonClicked(GameInfoPopup __instance) @@ -143,8 +310,11 @@ private static bool GameInfoPopup_OnMainButtonClicked(GameInfoPopup __instance) } /// - /// Checks the signature of a single-player game before resuming it. + /// Prefix patch for StartScreen_UI2.OnResumeButtonLongPress. The game calls that method on a long press of the resume button. + /// The patch compares the checksum of the first single-player saved game before the original method runs. /// + /// The start screen. + /// False to skip the original method when the checksums are different. True to let the original method run. [HarmonyPrefix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnResumeButtonLongPress))] private static bool StartScreen_OnResumeButtonClick(StartScreen_UI2 __instance) @@ -153,57 +323,79 @@ private static bool StartScreen_OnResumeButtonClick(StartScreen_UI2 __instance) } /// - /// Deletes the signature file of a pass-and-play game when it is deleted. + /// Postfix patch for GameInfoPopup.DeletePaPGame. It deletes the saved checksum of the pass-and-play game that the user deleted. /// + /// The game info popup of the deleted game. [HarmonyPostfix] [HarmonyPatch(typeof(GameInfoPopup), nameof(GameInfoPopup.DeletePaPGame))] private static void GameInfoPopup_DeletePaPGame(GameInfoPopup __instance) { - File.Delete(Path.Combine(Application.persistentDataPath, $"{__instance.gameId}.signatures")); + DeleteStateChecksum(__instance.gameId); + } + + /// + /// Prefix patch for LocalSaveFileUtils.DeleteSaveFile. It deletes the saved checksum of the saved game before the game deletes the save file. + /// The original method always runs. + /// + /// The type of the saved game. + /// The id of the saved game. + /// The value that tells the game to delete only the local file. The patch does not use it. + [HarmonyPrefix] + [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteSaveFile))] + private static void LocalSaveFileUtils_DeleteSaveFile(PolytopiaBackendBase.Game.GameType gameType, string gameId, bool localOnly) + { + DeleteStateChecksum(gameId); } /// - /// Deletes the signature file of all singleplayer games when they are deleted. + /// Prefix patch for LocalSaveFileUtils.DeleteAllSaveFilesOfType. It deletes the saved checksums of all saved games of one type. + /// The patch runs before the game deletes the save files. The original method always runs. /// + /// The type of the saved games to delete. + /// The value that tells the game to delete only the local files. The patch does not use it. [HarmonyPrefix] [HarmonyPatch(typeof(LocalSaveFileUtils), nameof(LocalSaveFileUtils.DeleteAllSaveFilesOfType))] private static void LocalSaveFileUtils_DeleteAllSaveFilesOfType(PolytopiaBackendBase.Game.GameType gameType, bool localOnly) { - if (gameType == PolytopiaBackendBase.Game.GameType.SinglePlayer) + foreach (var gameId in LocalSaveFileUtils.GetSaveFiles(gameType)) { - foreach (var gameId in LocalSaveFileUtils.GetSaveFiles(PolytopiaBackendBase.Game.GameType.SinglePlayer)) - { - File.Delete(Path.Combine(Application.persistentDataPath, $"{gameId}.signatures")); - } + DeleteStateChecksum(gameId); } } /// - /// Deletes the signature file of a game when the match ends. + /// Prefix patch for GameManager.MatchEnded. It deletes the saved checksum of the current game when the match ends. + /// The original method always runs. /// + /// The value that tells if the local player won. The patch does not use it. + /// The score details of the match. The patch does not use them. + /// The id of the winner. The patch does not use it. [HarmonyPrefix] [HarmonyPatch(typeof(GameManager), nameof(GameManager.MatchEnded))] private static void GameManager_MatchEnded(bool localPlayerIsWinner, ScoreDetails scoreDetails, byte winnerId) { - File.Delete(Path.Combine(Application.persistentDataPath, $"{GameManager.Client.gameId}.signatures")); + DeleteStateChecksum(GameManager.Client.gameId); } /// - /// Creates a signature file when a new game session is created. + /// Postfix patch for the ClientBase.CreateSession overload that takes game settings and a game id. + /// It writes the current global checksum for the new game. /// + /// The settings of the new game. The patch does not use them. + /// The id of the new game. [HarmonyPostfix] [HarmonyPatch(typeof(ClientBase), nameof(ClientBase.CreateSession), typeof(GameSettings), typeof(Il2CppSystem.Guid))] private static void ClientBase_CreateSession(GameSettings settings, Il2CppSystem.Guid gameId) { - File.WriteAllTextAsync( - Path.Combine(Application.persistentDataPath, $"{gameId}.signatures"), - checksum - ); + SaveStateChecksum(gameId); } /// - /// Resets game settings if necessary when the tribe selector screen is shown. + /// Prefix patch for TribeSelectorScreen.Show. If is true, it calls + /// and sets the flag to false. /// + /// The value that tells the game to show the screen without animation. The patch does not use it. + /// Always true, so the original method always runs. [HarmonyPrefix] [HarmonyPatch(typeof(TribeSelectorScreen), nameof(TribeSelectorScreen.Show))] private static bool TribeSelectorScreen_Show(bool instant = false) @@ -217,7 +409,8 @@ private static bool TribeSelectorScreen_Show(bool instant = false) } /// - /// Restores the preliminary game settings to their default values. + /// Clears the disabled tribes and the selected skins in the preliminary game settings. + /// Then it writes these settings to disk. /// internal static void RestorePreliminaryGameSettings() { @@ -227,7 +420,7 @@ internal static void RestorePreliminaryGameSettings() } /// - /// Initializes the Compatibility manager by patching the necessary methods. + /// Applies all Harmony patches in the class. /// internal static void Init() { diff --git a/src/Managers/Hub.cs b/src/Managers/Hub.cs index 5afdaf9..c8d3eff 100644 --- a/src/Managers/Hub.cs +++ b/src/Managers/Hub.cs @@ -1,47 +1,120 @@ -using System.Text.Json; +using System.Globalization; using Cpp2IL.Core.Extensions; using HarmonyLib; -using I2.Loc; using Il2CppInterop.Runtime; -using TMPro; using UnityEngine; -using UnityEngine.EventSystems; -using UnityEngine.UI; using static PopupBase; -using PolytopiaBackendBase.Common; -using System.Text.Encodings.Web; -using Il2CppSystem.Linq; -using System.Text.RegularExpressions; - namespace PolyMod.Managers; /// -/// Manages the PolyMod hub, including UI elements and popups. +/// The PolyMod hub. It adds the hub button and the version label to the start screen. +/// It shows the hub popup with the list of mods, and the config popup with the PolyMod settings. /// internal static class Hub { + /// + /// A PolyMod setting that the config popup shows and that the user can toggle. + /// + /// The localization key of the button that toggles the setting. + /// The localization key of the setting name. + /// The localization key of the setting description. + /// The function that gets the current state of the setting. + /// The action that changes the setting to the opposite state. + private record Setting( + string buttonKey, + string nameKey, + string descriptionKey, + Func isEnabled, + Action toggle + ); + private const string HEADER_PREFIX = ""; private const string HEADER_POSTFIX = ""; - private const int POPUP_WIDTH = 1400; + + private const string COLOR_MUTED = "#9AA0A6"; + private const string COLOR_ENABLED = "#4CC76A"; + private const string COLOR_DISABLED = "#E36A5B"; + private const string COLOR_WARNING = "#E0A52E"; + private const int CHECKSUM_LENGTH = 12; + private const float HUB_POPUP_WIDTH_SHARE = 0.78f; + private const float HUB_POPUP_MAX_WIDTH = 1400f; + private const float SETTINGS_POPUP_WIDTH_SHARE = 0.5f; + private const float SETTINGS_POPUP_MAX_WIDTH = 900f; + private const float START_SCREEN_MARGIN = 50f; + private const float VERSION_LABEL_FONT_SIZE = 18f; + private const float VERSION_LABEL_GAP = 10f; + /// The distance between the edge of the safe area and the version label. + private const float VERSION_LABEL_MARGIN = 15f; + private const float ROUND_BUTTON_TITLE_GAP = 10f; + private const string INTRO = "intro.mp4"; + + private const KeyCode HOTKEY_MODIFIER = KeyCode.LeftControl; + private const KeyCode HOTKEY_MODIFIER_ALTERNATIVE = KeyCode.RightControl; + private const KeyCode HOTKEY = KeyCode.Tab; + + private static readonly Setting[] SETTINGS = new Setting[] + { + new( + "polymod.hub.config.debug", + "polymod.debug", + "polymod.debug.description", + () => Plugin.config.debug, + () => + { + Plugin.config = Plugin.config with { debug = !Plugin.config.debug }; + Plugin.UpdateConsole(); + } + ), + new( + "polymod.hub.config.coordinates", + "polymod.coordinates", + "polymod.coordinates.description", + () => Plugin.config.showCoordinates, + () => Plugin.config = Plugin.config with { showCoordinates = !Plugin.config.showCoordinates } + ), + }; + private static UIRoundButton_UI2? polyModButton = null; - private static UIRoundButton_UI2? polyModVersion = null; + private static NotificationBadge? brokenModsBadge = null; + private static TextField_UI2? polyModVersion = null; + + private static PopupBase? openPopup = null; /// - /// Whether the configuration popup is currently active. + /// Gets a value that tells if the last popup that the hub opened is still on the screen. + /// If that popup is closed or destroyed, the property removes the reference to it and gives false. /// - public static bool isConfigPopupActive = false; + public static bool IsPopupOpen + { + get + { + if (openPopup != null) + { + try + { + if (openPopup.IsShowing()) return true; + } + catch (Exception) { } + openPopup = null; + } + return false; + } + } /// - /// Patches the splash screen to play a custom intro video. + /// Prefix patch for SplashController.LoadAndPlayClip. It replaces the splash video with the PolyMod intro video. + /// The patch writes the embedded intro.mp4 resource to the persistent data folder and plays that file. + /// The write starts asynchronously and the patch does not wait for it to complete. /// + /// The splash controller that plays the video. + /// Always false, so the original method does not run. [HarmonyPrefix] [HarmonyPatch(typeof(SplashController), nameof(SplashController.LoadAndPlayClip))] private static bool SplashController_LoadAndPlayClip(SplashController __instance) { - string name = "intro.mp4"; - string path = Path.Combine(Application.persistentDataPath, name); - File.WriteAllBytesAsync(path, Plugin.GetResource(name).ReadBytes()); + string path = Path.Combine(Application.persistentDataPath, INTRO); + File.WriteAllBytesAsync(path, Plugin.GetResource(INTRO).ReadBytes()); __instance.lastPlayTime = Time.realtimeSinceStartup; __instance.videoPlayer.url = path; __instance.videoPlayer.Play(); @@ -49,392 +122,401 @@ private static bool SplashController_LoadAndPlayClip(SplashController __instance } /// - /// Patches the popup button container to correctly anchor buttons. + /// Postfix patch for StartScreen_UI2.Init. It makes the PolyMod widgets on the start screen. + /// It adds the hub button with the PolyMod icon and a badge that shows the number of broken mods. + /// It also adds the label with the PolyMod version. + /// If the mods have a dependency cycle, it shows the dependency cycle popup. /// - [HarmonyPostfix] - [HarmonyPatch(typeof(PopupButtonContainer), nameof(PopupButtonContainer.SetButtonData))] - private static void PopupButtonContainer_SetButtonData(PopupButtonContainer __instance) - { - int num = __instance.buttons.Length; - for (int i = 0; i < num; i++) - { - UITextButton uitextButton = __instance.buttons[i]; - Vector2 vector = new((num == 1) ? 0.5f : (i / (num - 1.0f)), 0.5f); - uitextButton.rectTransform.anchorMin = vector; - uitextButton.rectTransform.anchorMax = vector; - uitextButton.rectTransform.pivot = vector; - } - } - + /// The parent transform that the game gives to the start screen. [HarmonyPostfix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.Init))] - private static void StartScreen_UI2_Init(StartScreen_UI2 __instance, RectTransform transform) + private static void StartScreen_UI2_Init(RectTransform transform) { polyModButton = UILibrary.NewRoundButton(transform).SetStyle(UIButtonBase_UI2.ButtonStyle.Suggested); polyModButton.bg.sprite = Visual.BuildSprite(Plugin.GetResource("polymod_icon.png").ReadBytes()); - polyModButton.OnClickedSignal.Add(DelegateSupport.ConvertDelegate(ShowPolyModHub)); + polyModButton.OnClickedSignal.Add(Callback(ShowPolyModHub)); + + brokenModsBadge = UILibrary.NewNotificationBadge(polyModButton.rectTransform).SetValue(CountBrokenMods()); + polyModButton.SetOverlay(brokenModsBadge, UIButtonBase_UI2.OverlayPosition.TopRight); - polyModVersion = UILibrary.NewRoundButton(transform).SetStyle(UIButtonBase_UI2.ButtonStyle.Suggested); + // NewHeaderTinyText is the prefab a round button builds its own title from, so the label + // keeps the game's header font rather than the lighter body font NewText would give it. + polyModVersion = UILibrary.NewHeaderTinyText(transform); + polyModVersion.gameObject.name = "PolyModVersion"; + polyModVersion.textField.fontSize = VERSION_LABEL_FONT_SIZE; + polyModVersion.textField.color = Color.white; polyModVersion.Text = $"PolyMod {Plugin.VERSION}"; - polyModVersion.titleTextField.textField.fontSize = 18f; if (Main.dependencyCycle) - { - BasicPopup popup = PopupManager.GetBasicPopupWithData( - new( - Localization.Get("polymod.cycle"), - Localization.Get("polymod.cycle.description"), - new PopupBase.PopupButtonData[] { - new( - "buttons.exitgame", - PopupBase.PopupButtonData.States.None, - (Il2CppSystem.Action)Application.Quit, - closesPopup: false, - customColorStates: ColorConstants.redButtonColorStates - ) - } - ) - ); - - popup.IsUnskippable = true; - popup.Show(); - } - + ShowDependencyCyclePopup(); } /// - /// Patches the start screen to add the PolyMod hub button and version text. + /// Postfix patch for StartScreen_UI2.RunLayout. It puts the hub button and the version label in position. + /// The hub button goes near the top-right corner of the safe area. + /// The badge on the button shows the current number of broken mods. + /// The version label goes in the bottom-left corner of the safe area. + /// If the label touches the settings button, the patch moves the label above that button. + /// If the widgets do not exist, the patch writes a warning to the log and stops. /// + /// The start screen. + /// The screen size that the game uses for this layout. [HarmonyPostfix] [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RunLayout))] private static void StartScreen_UI2_RunLayout(StartScreen_UI2 __instance, ScreenBase_UI2.ScreenSize screenSize) { - if (polyModButton == null) + if (polyModButton == null || polyModVersion == null) { - Plugin.logger.LogWarning("PolyMod Hub button is null when running layout!"); + Plugin.logger.LogWarning("PolyMod start screen widgets are missing, skipping their layout."); return; } + polyModButton.iconContainer.gameObject.SetActive(false); polyModButton.outline.gameObject.SetActive(false); polyModButton.bg.color = Color.white; + // Setting the text re-runs the button's own layout, which also repositions the badge. polyModButton.Text = Localization.Get("polymod.hub"); - float num = 50f; - polyModButton.SetPosition(screenSize.safeRect.Right - (num * 2.5f), screenSize.safeRect.Top - num); - - if (polyModVersion == null) + float titleDrop = polyModButton.titleTextField == null + ? 0f + : (polyModButton.titleTextField.GetHeight() + ROUND_BUTTON_TITLE_GAP) / 2f; + polyModButton.SetPosition( + screenSize.safeRect.Right - START_SCREEN_MARGIN * 2.5f, + screenSize.safeRect.Top - START_SCREEN_MARGIN - titleDrop + ); + brokenModsBadge?.SetValue(CountBrokenMods()); + + // Anchored by its edges, not its centre, so a longer version string cannot run off screen. + float versionX = screenSize.safeRect.Left + VERSION_LABEL_MARGIN + polyModVersion.GetHalfWidth(); + float versionY = screenSize.safeRect.Bottom + VERSION_LABEL_MARGIN + polyModVersion.GetHalfHeight(); + polyModVersion.SetPosition(versionX, versionY); + + // The bottom row of buttons is centred and of fixed width, so a narrow window walks it into + // the version label. The row is already laid out by now, so lift the label clear of it. + UIRoundButton_UI2 bottomRowStart = __instance.settingsButton; + if (bottomRowStart != null + && polyModVersion.GetRight() + VERSION_LABEL_GAP > bottomRowStart.GetLeft()) { - Plugin.logger.LogWarning("PolyMod Version is null when running layout!"); - return; + polyModVersion.SetPosition( + versionX, + bottomRowStart.GetTop() + polyModVersion.GetHalfHeight() + VERSION_LABEL_GAP + ); } - polyModVersion.iconContainer.gameObject.SetActive(false); - polyModVersion.outline.gameObject.SetActive(false); - polyModVersion.bg.gameObject.SetActive(false); - polyModVersion.SetPosition(screenSize.safeRect.Left + num * 1.15f, screenSize.safeRect.Bottom + num * 1.15f); } /// - /// Patches the game manager to handle key presses for the config popup. + /// Postfix patch for GameManager.Update. It opens the hub popup when the user pushes Ctrl+Tab. + /// The patch does nothing if a popup that the hub opened is still on the screen. /// [HarmonyPostfix] [HarmonyPatch(typeof(GameManager), nameof(GameManager.Update))] private static void GameManager_Update() { - if (Input.GetKey(KeyCode.LeftControl) && Input.GetKeyDown(KeyCode.Tab) && !isConfigPopupActive) + bool modifierHeld = Input.GetKey(HOTKEY_MODIFIER) || Input.GetKey(HOTKEY_MODIFIER_ALTERNATIVE); + if (modifierHeld && Input.GetKeyDown(HOTKEY) && !IsPopupOpen) + ShowPolyModHub(); + } + + /// + /// Shows the hub popup. The popup has a header text, the list of mods, and a footer text. + /// It has the back, Discord, and config buttons. + /// In debug mode, it also has the dump and hot reload buttons, which do not close the popup. + /// + internal static void ShowPolyModHub() + { + BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); + popup.Header = Localization.Get("polymod.hub"); + popup.Description = string.Join( + "\n\n", + Localization.Get("polymod.hub.header", Args(HEADER_PREFIX, HEADER_POSTFIX)), + BuildModList(), + Localization.Get("polymod.hub.footer", Args(HEADER_PREFIX, HEADER_POSTFIX)) + ); + + void OpenDiscord() => NativeHelpers.OpenURL(Plugin.DISCORD_LINK, false); + + List buttons = new() + { + new("buttons.back"), + new("polymod.hub.discord", callback: Callback(OpenDiscord)), + new("polymod.hub.config", callback: Callback(ShowConfigPopup)), + }; + if (Plugin.config.debug) { - ShowConfigPopup(); + buttons.Add(new("polymod.hub.dump", callback: Callback(DumpData), closesPopup: false)); + buttons.Add(new("polymod.hub.hotreload", callback: Callback(HotReload), closesPopup: false)); } + + popup.buttonData = buttons.ToArray(); + openPopup = popup; + popup.ShowSetWidth(HUB_POPUP_WIDTH_SHARE, HUB_POPUP_MAX_WIDTH); } /// - /// Updates sprite information from dumped files. + /// Shows the config popup with the list of PolyMod settings and their states. + /// Each setting has a button that toggles the setting, writes the config to disk, and refreshes the list. + /// These buttons do not close the popup. The back button opens the hub popup again. /// - internal static void UpdateSpriteInfos() + internal static void ShowConfigPopup() { - string message = string.Empty; - Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); + BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); + popup.Header = Localization.Get("polymod.hub.config"); + popup.Description = BuildSettingsList(); - foreach (var file in Directory.GetFiles(Plugin.DUMPED_DATA_PATH)) + List buttons = new() { - string? name = Path.GetFileNameWithoutExtension(file); - List subnames = new(); - if (name.Contains("sprites_")) + new("buttons.back", callback: Callback(ShowPolyModHub)), + }; + foreach (Setting setting in SETTINGS) + { + void OnSettingClicked() { - subnames = name.Split('_').ToList(); - Mod.File spriteInfo = new(Path.GetFileNameWithoutExtension(file), File.ReadAllBytes(file)); - Dictionary? deserialized = Loader.LoadSpriteInfoFile(Registry.mods[subnames[1]], spriteInfo); - if (deserialized != null) - { - foreach (var kvp in deserialized) - { - Loader.UpdateSprite(kvp.Key); - } - message += Localization.Get("polymod.spriteinfo.updated", new Il2CppSystem.Object[] { subnames[1] }); - } + setting.toggle(); + Plugin.WriteConfig(); + popup.Description = BuildSettingsList(); } + buttons.Add(new(setting.buttonKey, callback: Callback(OnSettingClicked), closesPopup: false)); } - if (message == string.Empty) - { - message = Localization.Get("polymod.spriteinfo.notupdated"); - } - NotificationManager.Notify(message); + + popup.buttonData = buttons.ToArray(); + openPopup = popup; + popup.ShowSetWidth(SETTINGS_POPUP_WIDTH_SHARE, SETTINGS_POPUP_MAX_WIDTH); } /// - /// Dump all data. + /// Shows a popup that tells the user that the mods have a dependency cycle. + /// The user cannot skip the popup. Its only button closes the game. /// - internal static void DumpData() + private static void ShowDependencyCyclePopup() { - Directory.CreateDirectory(Plugin.DUMPED_DATA_PATH); - Directory.CreateDirectory(Plugin.LOGIC_DUMP_PATH); - Directory.CreateDirectory(Plugin.LOCALIZATION_DUMP_PATH); - File.WriteAllTextAsync( - Path.Combine(Plugin.LOGIC_DUMP_PATH, "gameLogicData.json"), - PolytopiaDataManager.provider.LoadGameLogicData(VersionManager.GameLogicDataVersion) - ); - File.WriteAllTextAsync( - Path.Combine(Plugin.LOGIC_DUMP_PATH, "avatarData.json"), - PolytopiaDataManager.provider.LoadAvatarData(1337) + BasicPopup popup = PopupManager.GetBasicPopupWithData( + new( + Localization.Get("polymod.cycle"), + Localization.Get("polymod.cycle.description"), + new PopupButtonData[] + { + new( + "buttons.exitgame", + PopupButtonData.States.None, + (Il2CppSystem.Action)Application.Quit, + closesPopup: false, + customColorStates: ColorConstants.redButtonColorStates + ), + } + ) ); - var source = LocalizationManager.Sources[0]; - foreach (var language in source.GetLanguages()) - { - int languageIndex = source.GetLanguageIndex(language); - var dict = new Dictionary(); - - foreach (var term in source.mTerms) - { - var translation = term.GetTranslation(languageIndex); + popup.IsUnskippable = true; + popup.Show(); + } - if (!string.IsNullOrEmpty(translation)) - dict[term.Term] = translation; - } - var options = new JsonSerializerOptions - { - WriteIndented = true, - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping - }; + /// + /// Dumps the game data to disk and shows a popup with the path of the dump folder. + /// The popup has a button that opens the dump folder. If the folder does not open, the method writes an error to the log. + /// + private static void DumpData() + { + Dumper.DumpAll(); + string path = Dumper.RootPath; - string json = JsonSerializer.Serialize(dict, options); + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub.dump"); + popup.Description = Localization.Get("polymod.hub.dumped", Args(path)); - File.WriteAllText( - Path.Combine(Plugin.LOCALIZATION_DUMP_PATH, $"language_{source.mLanguages[languageIndex].Code}.json"), - json - ); - } - foreach (var category in source.GetCategories()) - File.WriteAllTextAsync( - Path.Combine(Plugin.LOCALIZATION_DUMP_PATH, $"localization_{category}.csv"), - source.Export_CSV(category) - ); - foreach (KeyValuePair entry in Registry.mods) + void OpenDumpFolder() { - foreach (Mod.File file in entry.Value.files) + try { - Match spritesMatch = Regex.Match(Path.GetFileName(file.name), @"^sprites(?:_(.*))?\.json$"); - if (spritesMatch.Success) - File.WriteAllBytes( - Path.Combine( - Plugin.DUMPED_DATA_PATH, - $"{Path.GetFileNameWithoutExtension(file.name)}_{entry.Key}.json" - ), - file.bytes - ); + Application.OpenURL(new Uri(path).AbsoluteUri); } - } - foreach (TribeType type in Enum.GetValues(typeof(TribeType))) - { - List previewTiles = new(); - SelectTribePopup popup = PopupManager.GetSelectTribePopup(); - for (int x = -3; x <= 3; x++) + catch (Exception exception) { - for (int y = -7; y <= 7; y++) - { - Vector2Int pos = new Vector2Int(x, y); - if (popup.UIWorldPreview.worldPreviewData.TryGetData(pos, type, out UITileData tileData)) - { - Visual.PreviewTile previewTile = new Visual.PreviewTile - { - x = tileData.Position.x, - y = tileData.Position.y, - terrainType = tileData.terrainType, - resourceType = tileData.resourceType, - unitType = tileData.unitType, - improvementType = tileData.improvementType - }; - previewTiles.Add(previewTile); - } - } + Plugin.logger.LogError($"Could not open the dump folder at {path}: {exception}"); } - File.WriteAllTextAsync( - Path.Combine(Plugin.DUMPED_DATA_PATH, $"preview_{type}.json"), - JsonSerializer.Serialize(previewTiles, new JsonSerializerOptions { WriteIndented = true }) - ); } - NotificationManager.Notify(Localization.Get("polymod.hub.dumped")); + + popup.buttonData = new PopupButtonData[] + { + new("polymod.hub.openfolder", callback: Callback(OpenDumpFolder)), + new("buttons.ok"), + }; + popup.Show(); } /// - /// Shows the configuration popup. + /// Shows a popup that tells the user that hot reload is not available. + /// This method is a stub. It does not reload mods. /// - internal static void ShowConfigPopup() + private static void HotReload() { - BasicPopupLegacy polymodPopup = Visual.GetBasicPopupLegacy(); - polymodPopup.Header = Localization.Get("polymod.hub.config"); - polymodPopup.Description = ""; - polymodPopup.buttonData = CreateConfigPopupButtonData(); - polymodPopup.ShowSetWidth(POPUP_WIDTH); + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub.hotreload"); + popup.Description = Localization.Get("polymod.hotreload.unavailable"); + popup.SetDefaultOkbutton(); + popup.Show(); } - internal static void ShowPolyModHub() + /// + /// Makes the rich text list of mods for the hub popup. + /// The list starts with a summary line that shows the number of loaded mods, the total number of mods, and the short global checksum. + /// An entry for each mod follows the summary line. + /// + /// The rich text list of mods, or a muted text that tells the user that there are no mods. + private static string BuildModList() { - BasicPopupLegacy popup = Visual.GetBasicPopupLegacy(); - popup.Header = Localization.Get("polymod.hub"); - popup.Description = Localization.Get("polymod.hub.header", new Il2CppSystem.Object[] { - HEADER_PREFIX, - HEADER_POSTFIX - }) + "\n\n"; - foreach (var mod in Registry.mods.Values) - { - popup.Description += Localization.Get("polymod.hub.mod", new Il2CppSystem.Object[] { - mod.name, - Localization.Get("polymod.hub.mod.status." - + Enum.GetName(typeof(Mod.Status), mod.status)!.ToLower()), - string.Join(", ", mod.authors), - mod.version.ToString(), - mod.description ?? "" - }); - popup.Description += "\n\n"; - } - popup.Description += Localization.Get("polymod.hub.footer", new Il2CppSystem.Object[] { - HEADER_PREFIX, - HEADER_POSTFIX - }); + if (Registry.mods.Count == 0) + return Muted(Localization.Get("polymod.hub.mods.none")); - void OpenDiscord() + int loaded = 0; + foreach (Mod mod in Registry.mods.Values) { - NativeHelpers.OpenURL(Plugin.DISCORD_LINK, false); + if (mod.status == Mod.Status.Success) loaded++; } - List popupButtons = new() - { - new("buttons.back"), - new( - "polymod.hub.discord", - callback: DelegateSupport.ConvertDelegate(OpenDiscord) - ), - new( - "polymod.hub.config", - callback: DelegateSupport.ConvertDelegate(ShowConfigPopup) - ) - }; - if (Plugin.config.debug) + string summary = Localization.Get( + "polymod.hub.summary", + Args(loaded.ToString(CultureInfo.InvariantCulture), Registry.mods.Count.ToString(CultureInfo.InvariantCulture)) + ); + summary += " " + Localization.Get( + "polymod.hub.checksum", + Args(ShortChecksum(Compatibility.checksum)) + ); + + List blocks = new() { Muted(summary) }; + foreach (Mod mod in Registry.mods.Values) { - popupButtons.Add(new( - "polymod.hub.dump", - callback: DelegateSupport.ConvertDelegate(DumpData), - closesPopup: false - )); - popupButtons.Add(new( - "polymod.hub.spriteinfo.update", - callback: DelegateSupport.ConvertDelegate(UpdateSpriteInfos), - closesPopup: false - )); + blocks.Add(BuildModEntry(mod)); } - popup.buttonData = popupButtons.ToArray(); - popup.ShowSetWidth(POPUP_WIDTH); + return string.Join("\n\n", blocks); } /// - /// Creates the button data for the configuration popup. + /// Gets the first 12 characters of a checksum, which the hub shows. /// - /// An array of popup button data. - internal static PopupButtonData[] CreateConfigPopupButtonData() + /// The full checksum. + /// The first 12 characters of the checksum, the full checksum if it is shorter, or "-" if the checksum is null or empty. + private static string ShortChecksum(string checksum) { - List popupButtons = new() - { - new(Localization.Get("buttons.back"), PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnBackButtonClicked), -1, true, null) - }; + if (string.IsNullOrEmpty(checksum)) return "-"; + + return checksum.Length <= CHECKSUM_LENGTH ? checksum : checksum.Substring(0, CHECKSUM_LENGTH); + } - if (GameManager.Instance.isLevelLoaded) + /// + /// Makes the rich text entry of one mod for the hub popup. + /// The entry shows the name, the version, and the status in its status color. + /// It also shows the authors, the short checksum, and the description when the mod has them. + /// + /// The mod to show. + /// The rich text entry of the mod. + private static string BuildModEntry(Mod mod) + { + string status = Localization.Get( + "polymod.hub.mod.status." + Enum.GetName(mod.status)!.ToLowerInvariant() + ); + string title = $"{mod.name} " + Muted($"v{mod.version}"); + string meta = $"{status}"; + if (mod.authors.Length > 0) { - popupButtons.Add(new PopupButtonData(Localization.Get("polymod.hub.spriteinfo.update"), PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnUpdateSpritesButtonClicked), -1, true, null)); + string authors = Localization.Get( + "polymod.hub.mod.authors", + Args(string.Join(", ", mod.authors)) + ); + meta += " " + Muted($"{authors}"); } - else + if (!string.IsNullOrEmpty(mod.checksum)) { - string debugButtonName = Localization.Get( - Plugin.config.debug ? "polymod.hub.config.disable" : "polymod.hub.config.enable", - new Il2CppSystem.Object[] { Localization.Get("polymod.debug", - new Il2CppSystem.Object[]{}).ToUpperInvariant() } - ); - string autoUpdateButtonName = Localization.Get( - Plugin.config.autoUpdate ? "polymod.hub.config.disable" : "polymod.hub.config.enable", - new Il2CppSystem.Object[] { Localization.Get("polymod.autoupdate", - new Il2CppSystem.Object[]{}).ToUpperInvariant() } + string modChecksum = Localization.Get( + "polymod.hub.mod.checksum", + Args(ShortChecksum(mod.checksum)) ); - string includeAlphasButtonName = Localization.Get( - Plugin.config.updatePrerelease ? "polymod.hub.config.disable" : "polymod.hub.config.enable", - new Il2CppSystem.Object[] { Localization.Get("polymod.autoupdate.alpha", - new Il2CppSystem.Object[]{}).ToUpperInvariant() } - ); - popupButtons.Add(new PopupButtonData(debugButtonName, PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnDebugButtonClicked), -1, true, null)); - popupButtons.Add(new PopupButtonData(autoUpdateButtonName, PopupButtonData.States.None, DelegateSupport.ConvertDelegate(OnAutoUpdateButtonClicked), -1, true, null)); - popupButtons.Add(new PopupButtonData(includeAlphasButtonName, Plugin.config.autoUpdate ? PopupButtonData.States.None : PopupButtonData.States.Disabled, DelegateSupport.ConvertDelegate(OnIncludeAlphasButtonClicked), -1, true, null)); + meta += " " + Muted($"{modChecksum}"); } - return popupButtons.ToArray(); - void OnDebugButtonClicked() - { - Plugin.config = new(debug: !Plugin.config.debug, autoUpdate: Plugin.config.autoUpdate, updatePrerelease: Plugin.config.updatePrerelease); - Plugin.WriteConfig(); - Plugin.UpdateConsole(); - NotificationManager.Notify(Localization.Get( - "polymod.config.setto", - new Il2CppSystem.Object[] { Localization.Get("polymod.debug", - new Il2CppSystem.Object[]{}), Plugin.config.debug } - )); - isConfigPopupActive = false; - } + List lines = new() { title, meta }; + if (!string.IsNullOrWhiteSpace(mod.description)) + lines.Add($"{mod.description}"); - void OnAutoUpdateButtonClicked() - { - Plugin.config = new(debug: Plugin.config.debug, autoUpdate: !Plugin.config.autoUpdate, updatePrerelease: Plugin.config.updatePrerelease); - Plugin.WriteConfig(); - Plugin.UpdateConsole(); - NotificationManager.Notify(Localization.Get( - "polymod.config.setto", - new Il2CppSystem.Object[] { Localization.Get("polymod.autoupdate", - new Il2CppSystem.Object[]{}), Plugin.config.autoUpdate } - )); - isConfigPopupActive = false; - } + return string.Join("\n", lines); + } - void OnIncludeAlphasButtonClicked() + /// + /// Makes the rich text list of settings for the config popup. + /// Each entry shows the setting name, its state in green or red, and a muted description. + /// + /// The rich text list of settings. + private static string BuildSettingsList() + { + List blocks = new(); + foreach (Setting setting in SETTINGS) { - Plugin.config = new(debug: Plugin.config.debug, autoUpdate: Plugin.config.autoUpdate, updatePrerelease: !Plugin.config.updatePrerelease); - Plugin.WriteConfig(); - Plugin.UpdateConsole(); - NotificationManager.Notify(Localization.Get( - "polymod.config.setto", - new Il2CppSystem.Object[] { Localization.Get("polymod.autoupdate.alpha", - new Il2CppSystem.Object[]{}), Plugin.config.updatePrerelease } - )); - isConfigPopupActive = false; + bool enabled = setting.isEnabled(); + string state = Localization.Get(enabled ? "polymod.on" : "polymod.off"); + string color = enabled ? COLOR_ENABLED : COLOR_DISABLED; + blocks.Add( + $"{Localization.Get(setting.nameKey)} {state}\n" + + Muted($"{Localization.Get(setting.descriptionKey)}") + ); } + return string.Join("\n\n", blocks); + } - void OnUpdateSpritesButtonClicked() + /// + /// Puts a text in a rich text color tag with the muted gray color. + /// + /// The text to change. + /// The text in the muted color. + private static string Muted(string text) => $"{text}"; + + /// + /// Gets the color that the hub uses to show a mod status. + /// + /// The status of the mod. + /// Green for , amber for , and red for all other values. + private static string StatusColor(Mod.Status status) => status switch + { + Mod.Status.Success => COLOR_ENABLED, + Mod.Status.DependenciesUnsatisfied => COLOR_WARNING, + _ => COLOR_DISABLED, + }; + + /// + /// Counts the mods that do not have the status. + /// + /// The number of broken mods. + private static int CountBrokenMods() + { + int broken = 0; + foreach (Mod mod in Registry.mods.Values) { - UpdateSpriteInfos(); - isConfigPopupActive = false; + if (mod.status != Mod.Status.Success) broken++; } + return broken; + } + + /// + /// Changes a managed action into an IL2CPP action that popup buttons can use. + /// + /// The managed action. + /// The IL2CPP action that calls . + private static Il2CppSystem.Action Callback(Action callback) + => DelegateSupport.ConvertDelegate(callback)!; - void OnBackButtonClicked() + /// + /// Puts strings into an IL2CPP object array for the format arguments of Localization.Get. + /// + /// The strings to put into the array. + /// The IL2CPP object array with the strings in the same order. + private static Il2CppSystem.Object[] Args(params string[] values) + { + Il2CppSystem.Object[] arguments = new Il2CppSystem.Object[values.Length]; + for (int i = 0; i < values.Length; i++) { - isConfigPopupActive = false; + arguments[i] = values[i]; } + return arguments; } /// - /// Initializes the Hub manager by patching the necessary methods. + /// Applies all Harmony patches in the class. /// internal static void Init() { diff --git a/src/Managers/Loc.cs b/src/Managers/Loc.cs index b3b7d17..9635ae5 100644 --- a/src/Managers/Loc.cs +++ b/src/Managers/Loc.cs @@ -1,3 +1,4 @@ +using System.Globalization; using HarmonyLib; using I2.Loc; using Il2CppInterop.Runtime.InteropTypes.Arrays; @@ -9,16 +10,33 @@ namespace PolyMod.Managers; /// -/// Manages localization for PolyMod. +/// The manager for localization. It adds mod terms and mod languages to the localization of the game. /// public static class Loc { + /// + /// The languages that mods add, keyed by language code. + /// Each value maps term keys to the text in that language. + /// The language key gives the name of the language. + /// internal static Dictionary> languagesToAdd = new(); + /// + /// The localization keys that replace the info text of improvements, keyed by the enum name of the improvement. + /// internal static Dictionary buildingsInfoOverrides = new(); /// - /// Patches the localization getter to handle custom enum values. + /// A Harmony prefix on Localization.Get(string, Il2CppReferenceArray). + /// It finds a custom enum value in the parts of the key, which are separated by dots. + /// A custom enum value is a number that is not less than . + /// The patch gets the enum name of this value from the enum caches of the type mappings in . + /// If more than one enum type has a name for the value, the patch uses the last of these types in . + /// Then it replaces the number in the key with the enum name. + /// If the key has more than one custom value, the patch uses only the last value. /// + /// The localization key. The patch can change it. + /// The format arguments of the localized text. The patch does not use them. + /// Always true, which runs the original method. [HarmonyPrefix] [HarmonyPatch(typeof(Localization), nameof(Localization.Get), typeof(string), typeof(Il2CppReferenceArray))] private static bool Localization_Get(ref string key, Il2CppReferenceArray args) @@ -65,7 +83,7 @@ private static bool Localization_Get(ref string key, Il2CppReferenceArray + /// A Harmony prefix on Localization.Init. + /// If the localization is already initialized, the patch does nothing. + /// If not, it sets the missing language code of Elyrion in the first language source. + /// Then it adds each language in to the source, if the source does not have that language code. + /// It adds the missing terms and sets the text of each term for that language. + /// + /// Always true, which runs the original method. [HarmonyPrefix] [HarmonyPatch(typeof(Localization), nameof(Localization.Init))] private static bool Localization_Init() @@ -120,6 +146,18 @@ private static bool Localization_Init() return true; } + /// + /// A Harmony prefix on BuildingUtils.GetInfo. + /// If has a key for the improvement, the patch gives the localized text of that key. + /// The localization uses the skin of the local player and the tribe of the owner. + /// + /// The info text of the improvement. The patch sets it if an override exists. + /// The skin of the local player. + /// The data of the improvement. + /// The state of the improvement. The patch does not use it. + /// The player that owns the improvement, or null. If null, the patch uses no tribe. + /// The tile of the improvement. The patch does not use it. + /// False if an override exists, which skips the original method. True if not. [HarmonyPrefix] [HarmonyPatch(typeof(BuildingUtils), nameof(BuildingUtils.GetInfo))] private static bool BuildingUtils_GetInfo(ref string __result, SkinType skinOfCurrentLocalPlayer, @@ -130,9 +168,9 @@ private static bool BuildingUtils_GetInfo(ref string __result, SkinType skinOfCu tribe = owner.tribe; string key = EnumCache.GetName(improvementData.type); - if (buildingsInfoOverrides.ContainsKey(key)) + if (buildingsInfoOverrides.TryGetValue(key, out string? buildingInfoOverride)) { - __result = Localization.GetSkinned(skinOfCurrentLocalPlayer, tribe, buildingsInfoOverrides[key]); + __result = Localization.GetSkinned(skinOfCurrentLocalPlayer, tribe, buildingInfoOverride); return false; } @@ -140,15 +178,19 @@ private static bool BuildingUtils_GetInfo(ref string __result, SkinType skinOfCu } /// - /// Builds and loads localization data from a dictionary. + /// Adds the terms of a mod localization file to the first language source of the game. + /// The method changes each key with . + /// It adds the TribeSkins/ prefix to a key that starts with tribeskins. + /// For each game language, the term gets the text in that language. + /// If that text does not exist, the term gets the English text, or else the term name. /// - /// A dictionary containing the localization data. + /// The terms, keyed by term key. Each value maps language names to text. internal static void BuildAndLoadLocalization(Dictionary> localization) { foreach (var (key, data) in localization) { string name = ReplaceDashesWithDots(key); - if (name.StartsWith("tribeskins")) name = "TribeSkins/" + name; + if (name.StartsWith("tribeskins", StringComparison.Ordinal)) name = "TribeSkins/" + name; TermData term = LocalizationManager.Sources[0].AddTerm(name); List strings = new(); foreach (string language in LocalizationManager.GetAllLanguages(false)) @@ -159,6 +201,14 @@ internal static void BuildAndLoadLocalization(Dictionary + /// Changes a key from a mod into a localization key. + /// The method replaces each underscore with a dot. Then it replaces each pair of dots with one underscore. + /// Thus, one underscore becomes a dot, and two underscores become one underscore. + /// The method does not change dashes. + /// + /// The key from the mod. + /// The localization key. internal static string ReplaceDashesWithDots(string key) { string name = key.Replace("_", "."); @@ -166,7 +216,7 @@ internal static string ReplaceDashesWithDots(string key) } /// - /// Initializes the Loc manager by patching the necessary methods. + /// Applies all Harmony patches in the class. /// internal static void Init() { diff --git a/src/Managers/Main.cs b/src/Managers/Main.cs index f271e77..833af19 100644 --- a/src/Managers/Main.cs +++ b/src/Managers/Main.cs @@ -1,9 +1,7 @@ using BepInEx.Unity.IL2CPP.Logging; using HarmonyLib; -using Il2CppSystem.Linq; using Newtonsoft.Json.Linq; using Polytopia.Data; -using PolytopiaBackendBase.Game; using System.Diagnostics; using System.Text.Json; using System.Text.RegularExpressions; @@ -13,65 +11,85 @@ namespace PolyMod.Managers; /// -/// The main manager for PolyMod, responsible for initializing the mod and patching game logic. +/// The main manager of PolyMod. It registers and loads the mods, and it patches game logic. /// public static class Main { + private static readonly string[] polytopiaAuthors = { "Midjiwan AB" }; + + /// + /// The flag that shows that the mod dependencies contain a cycle. + /// When it is true, loads only the PolyMod localization. + /// internal static bool dependencyCycle; /// - /// The maximum tier for technology, used to extend the tech tree. + /// The highest tech tier that gets an ID in TechItem.techTierFirebaseId. + /// adds the IDs for the tiers from 0 to this value. /// internal const int MAX_TECH_TIER = 100; /// - /// A stopwatch to measure the time taken to load mods. + /// The stopwatch that measures the time to register and load the mods. + /// It measures the sum of the time in and in . /// internal static readonly Stopwatch stopwatch = new(); /// - /// Whether the mod has been fully initialized. + /// The flag that shows that ran. + /// uses it to call only one time. /// internal static bool fullyInitialized; /// - /// A dictionary mapping unit IDs to the IDs of the units they embark into. + /// The embark overrides from the GLD, by ID. + /// The key is the ID of a unit, and the value is the ID of the unit that it embarks into. /// internal static Dictionary embarkNames = new(); /// - /// A dictionary mapping unit types to the types of the units they embark into. + /// The embark overrides, by unit type. + /// The key is the type of a unit, and the value is the type of the unit that it embarks into. /// internal static Dictionary embarkOverrides = new(); /// - /// Whether an embark action is currently being executed. + /// The flag that shows that an EmbarkAction runs now. + /// sets it to true, and sets it to false. /// internal static bool currentlyEmbarking = false; /// - /// A dictionary mapping improvement IDs to the IDs of the resources they attract. + /// The resources that improvements attract, by ID, from the GLD. + /// The key is the ID of an improvement, and the value is the ID of the resource. /// internal static Dictionary attractsResourceNames = new(); /// - /// A dictionary mapping improvement IDs to the IDs of the terrain types they attract resources on. + /// The terrains on which improvements make attracted resources, by ID, from the GLD. + /// The key is the ID of an improvement, and the value is the ID of the terrain. /// internal static Dictionary attractsTerrainNames = new(); /// - /// A dictionary mapping improvement types to the types of the resources they attract. + /// The resources that improvements attract, by type. + /// If an improvement is not in this lookup, uses the Game resource. /// internal static Dictionary attractsResourceOverrides = new(); /// - /// A dictionary mapping improvement types to the types of the terrain they attract resources on. + /// The terrains on which improvements make attracted resources, by type. + /// If an improvement is not in this lookup, uses the Forest terrain. /// internal static Dictionary attractsTerrainOverrides = new(); /// - /// Patches the game logic data parsing to load PolyMod content. + /// Patches GameLogicData.AddGameLogicPlaceholders as a prefix. + /// Calls the first time that the game parses the GLD. + /// The original method always runs after this prefix. /// + /// The game logic data that the game parses. + /// The root JSON object of the GLD. merges the mod patches into it. [HarmonyPrefix] [HarmonyPatch(typeof(GameLogicData), nameof(GameLogicData.AddGameLogicPlaceholders))] private static void GameLogicData_AddGameLogicPlaceholders(GameLogicData __instance, ref JObject rootObject) @@ -84,8 +102,15 @@ private static void GameLogicData_AddGameLogicPlaceholders(GameLogicData __insta } /// - /// Patches the purchase manager to unlock custom skins. + /// Patches PurchaseManager.IsSkinUnlocked as a prefix. + /// Unlocks all custom skins. /// + /// Set to true when the skin is a custom skin, otherwise false. + /// The skin to check. + /// + /// False when the skin ID is or more and the skin is not SkinType.Test. + /// Then the original method does not run. True for all other skins, so the original method runs. + /// [HarmonyPrefix] [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.IsSkinUnlocked))] private static bool PurchaseManager_IsSkinUnlockedInternal(ref bool __result, SkinType skinType) @@ -95,8 +120,11 @@ private static bool PurchaseManager_IsSkinUnlockedInternal(ref bool __result, Sk } /// - /// Patches the purchase manager to unlock custom tribes. + /// Patches PurchaseManager.IsTribeUnlocked as a postfix. + /// Unlocks all custom tribes. /// + /// Set to true when the tribe ID is or more. Other tribes keep the original result. + /// The tribe to check. [HarmonyPostfix] [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.IsTribeUnlocked))] private static void PurchaseManager_IsTribeUnlocked(ref bool __result, TribeType type) @@ -105,8 +133,12 @@ private static void PurchaseManager_IsTribeUnlocked(ref bool __result, TribeType } /// - /// Patches the steam purchase manager to unlock custom content. + /// Patches SteamPlatformPurchaseManager.IsProductUnlocked as a prefix. + /// Gives true for a null product. Other products use the original method. /// + /// Set to true when is null, otherwise false. + /// The product to check. + /// False when is null, so the original method does not run. Otherwise true. [HarmonyPrefix] [HarmonyPatch(typeof(SteamPlatformPurchaseManager), nameof(SteamPlatformPurchaseManager.IsProductUnlocked))] private static bool SteamPlatformPurchaseManager_IsProductUnlocked(ref bool __result, IAPProduct iapProduct) @@ -116,8 +148,11 @@ private static bool SteamPlatformPurchaseManager_IsProductUnlocked(ref bool __re } /// - /// Patches the purchase manager to add custom tribes to the list of unlocked tribes. + /// Patches PurchaseManager.GetUnlockedTribes as a postfix. + /// Adds each tribe in to the list of unlocked tribes. /// + /// The list of unlocked tribes. The method adds the custom tribes to it. + /// The value from the original call. The method does not use it. [HarmonyPostfix] [HarmonyPatch(typeof(PurchaseManager), nameof(PurchaseManager.GetUnlockedTribes))] private static void PurchaseManager_GetUnlockedTribes( @@ -129,8 +164,13 @@ private static void PurchaseManager_GetUnlockedTribes( } /// - /// Patches the Unity log callback to filter out spammy messages. + /// Patches IL2CPPUnityLogSource.UnityLogCallback as a prefix. + /// Stops Unity log messages that contain a text from . /// + /// The text of the log message. + /// The exception text of the log message. The method does not use it. + /// The type of the log message. The method does not use it. + /// False when the message contains a text to ignore, so the message is not logged. Otherwise true. [HarmonyPrefix] [HarmonyPatch(typeof(IL2CPPUnityLogSource), nameof(IL2CPPUnityLogSource.UnityLogCallback))] private static bool IL2CPPUnityLogSource_UnityLogCallback(string logLine, string exception, LogType type) @@ -144,73 +184,22 @@ private static bool IL2CPPUnityLogSource_UnityLogCallback(string logLine, string } /// - /// Patches the game mode screen to add custom game modes. - /// - [HarmonyPrefix] - [HarmonyPatch(typeof(GameModeScreen), nameof(GameModeScreen.Init))] - private static void GameModeScreen_Init(GameModeScreen __instance) - { - List list = __instance.buttons.ToList(); - for (int i = 0; i < Loader.gamemodes.Count; i++) - { - var item = Loader.gamemodes[i]; - var button = GameObject.Instantiate(__instance.buttons[2]); - list.Add(button); - Sprite? sprite = item.sprite; - if (item.sprite == null && item.spriteName != null) - { - sprite = Registry.GetSprite(item.spriteName); - } - Loader.gamemodes[i] = new Loader.GameModeButtonsInformation(item.gameModeIndex, item.action, __instance.buttons.Length, sprite, item.spriteName); - } - - var newArray = list.ToArray(); - for (int i = 0; i < __instance.buttons.Length; i++) - { - if (newArray[i] != null) newArray[i].OnClicked = __instance.buttons[i].OnClicked; - } - - for (int i = 0; i < Loader.gamemodes.Count; i++) - { - if (Loader.gamemodes[i].buttonIndex != null) - newArray[Loader.gamemodes[i].buttonIndex!.Value].OnClicked = Loader.gamemodes[i].action; - } - - __instance.buttons = newArray; - - for (int i = 0; i < __instance.buttons.Length; i++) - { - GamemodeButton button = __instance.buttons[i]; - var newData = button.gamemodeData.ToList(); - foreach (var info in Loader.gamemodes) - { - string id = EnumCache.GetName((GameMode)info.gameModeIndex).ToLower(); - newData.Add(new GamemodeButton.GamemodeButtonData() - { - gameMode = (GameMode)info.gameModeIndex, - id = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(id), - descriptionKey = "gamemode." + id + ".description.button", - headerKey = "gamemode." + id + ".caps", - icon = info.sprite - }); - } - button.gamemodeData = newData.ToArray(); - - for (int j = 0; j < Loader.gamemodes.Count; j++) - { - Loader.GameModeButtonsInformation info = Loader.gamemodes[j]; - - if (info.buttonIndex == i) - { - button.SetGamemode(info.buttonIndex.Value); - } - } - } - } - - /// - /// Patches the tech view to correctly display the tech tree with custom technologies. + /// Patches TechView.CreateNode as a prefix. + /// Replaces the original method with a version that calculates the angle between branches of the tech tree. /// + /// + /// The original method uses a fixed angle of 72 degrees between branches. + /// This method divides 360 by the number of techs that the Basic tech unlocks for the tribe of the local player. + /// The division uses integers, so the angle has no decimal part. + /// For each tech that unlocks, the method makes a tech item with the tribe override of the tech. + /// It calls CreateNode again for each tech that unlocks more techs. + /// At the end, it calls OnItemsRefreshed if it is set. + /// + /// The tech view that makes the tree. + /// The tech whose unlocked techs become the new nodes. + /// The tech item of , or null for the root of the tree. + /// The angle of the parent item, in degrees. + /// Always false, so the original method does not run. [HarmonyPrefix] [HarmonyPatch(typeof(TechView), nameof(TechView.CreateNode))] public static bool TechView_CreateNode(TechView __instance, TechData data, TechItem parentItem, float angle) @@ -245,8 +234,12 @@ public static bool TechView_CreateNode(TechView __instance, TechData data, TechI } /// - /// Patches the embark action to set a flag indicating that an embark is in progress. + /// Patches EmbarkAction.Execute as a prefix. + /// Sets to true. /// + /// The embark action. The method does not use it. + /// The game state. The method does not use it. + /// Always true, so the original method runs. [HarmonyPrefix] [HarmonyPatch(typeof(EmbarkAction), nameof(EmbarkAction.Execute))] private static bool EmbarkAction_Execute_Prefix(EmbarkAction __instance, GameState gameState) @@ -256,8 +249,21 @@ private static bool EmbarkAction_Execute_Prefix(EmbarkAction __instance, GameSta } /// - /// Patches the unit training method to handle custom embark units. + /// Patches ActionUtils.TrainUnit as a prefix. + /// Changes the trained unit to the embark override during an embark action. /// + /// + /// The method does nothing if the tile or the unit on the tile is null. + /// If is true, it finds the type of the unit on the tile in . + /// If the type is there, it replaces with the data of the override type. + /// Then it sets to false. + /// + /// The unit state that the original method gives. The method does not change it. + /// The game state. + /// The player that trains the unit. The method does not use it. + /// The tile of the unit that embarks. + /// The data of the unit to train. The method can replace it. + /// Always true, so the original method runs. [HarmonyPrefix] [HarmonyPatch(typeof(ActionUtils), nameof(ActionUtils.TrainUnit))] private static bool ActionUtils_TrainUnit(ref UnitState __result, GameState gameState, PlayerState playerState, TileData tile, ref UnitData unitData) @@ -279,8 +285,23 @@ private static bool ActionUtils_TrainUnit(ref UnitState __result, GameState game } /// - /// Patches the start turn action to handle the 'Attract' ability for custom improvements. + /// Patches StartTurnAction.Execute as a postfix. + /// Replaces the resource actions of the Attract improvement ability with actions that use the PolyMod attract overrides. /// + /// + /// First, the method removes all CreateResource actions from the action stack. + /// Then it finds each tile of the player that has an improvement with the Attract ability. + /// The improvement must have an age that is a multiple of its growth rate, and the turn must be more than 0. + /// For each such tile, the method finds the first tile in the area with radius 1 that has no improvement and no resource. + /// That tile must also belong to the player and have the target terrain. + /// On that tile, the method adds a CreateResourceAction with the reason Attract. + /// + /// The resource comes from , and the default is Game. + /// The target terrain comes from , and the default is Forest. + /// + /// + /// The start turn action. It gives the ID of the player. + /// The game state. [HarmonyPostfix] [HarmonyPatch(typeof(StartTurnAction), nameof(StartTurnAction.Execute))] private static void StartTurnAction_Execute(StartTurnAction __instance, GameState state) @@ -334,44 +355,130 @@ private static void StartTurnAction_Execute(StartTurnAction __instance, GameStat } /// - /// Patches the unit creation method to handle custom unit prefabs. + /// Patches GamePlayerSummary.Serialize as a prefix. + /// Sets the tribe to TribeType.None when the tribe ID is 255 or more. /// + /// + /// The summary writes the tribe as one byte, and a custom tribe ID does not fit in one byte. + /// The original method then writes TribeType.None. + /// Because of this, game summaries in the menu do not show the icon of a custom tribe. + /// + /// The player summary to write. + /// Always true, so the original method runs. [HarmonyPrefix] - [HarmonyPatch(typeof(Unit), nameof(Unit.CreateUnit))] - private static bool Unit_CreateUnit(Unit __instance, UnitData unitData, TribeType tribe, SkinType unitSkin) + [HarmonyPatch(typeof(GamePlayerSummary), nameof(GamePlayerSummary.Serialize))] + private static bool GamePlayerSummary_Serialize(GamePlayerSummary __instance) { - Unit unit = PrefabManager.GetPrefab(unitData.type, tribe, unitSkin); - if (unit == null) Console.Write("THIS FUCKING SHIT IS NULL WHAT THE FUCK"); + if ((int)__instance.TribeType >= byte.MaxValue) + { + __instance.TribeType = TribeType.None; + } + return true; } /// - /// Initializes the Main manager. + /// Patches PlayerState.Deserialize as a postfix. + /// Sets the climate of a player with a custom tribe to the tribe value. /// + /// + /// The player state reads the climate as one byte, and a custom climate ID does not fit in one byte. + /// The method sets the climate when the tribe ID is or more. + /// + /// The player state that the original method read. + /// The reader of the data. The method does not use it. + /// The version of the data. The method does not use it. + [HarmonyPostfix] + [HarmonyPatch(typeof(PlayerState), nameof(PlayerState.Deserialize))] + private static void PlayerState_Deserialize(PlayerState __instance, Il2CppSystem.IO.BinaryReader reader, int version) + { + if ((int)__instance.tribe >= Plugin.AUTOIDX_STARTS_FROM) + { + __instance.climate = __instance.tribe; + } + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(AchievementManager), nameof(AchievementManager.CheckAchievements))] + [HarmonyPatch(typeof(AchievementManager), nameof(AchievementManager.CheckHoudini))] + private static bool AchievementManager_CheckAchievementsAndHoudini() + { + return false; + } + + [HarmonyPrefix] + [HarmonyPatch(typeof(AchievementManager), nameof(AchievementManager.IsAchievementValid))] + private static bool IsAchievementValid(ref bool __result, Achievement achievement, GameState gameState) + { + __result = false; + return false; + } + + /// + /// Applies the Harmony patches of this class, then registers and loads the mods. + /// + /// + /// First, the method makes the folder if it does not exist. + /// The method adds the game itself as the mod polytopia with the status Success. + /// Then it calls and . + /// It keeps the dependency cycle result in . + /// The method measures its time with . + /// internal static void Init() { stopwatch.Start(); + Directory.CreateDirectory(Plugin.PERSISTENT_DATA_PATH); Harmony.CreateAndPatchAll(typeof(Main)); Mod.Manifest polytopia = new( "polytopia", "The Battle of Polytopia", null, new(Application.version.ToString()), - new string[] { "Midjiwan AB" }, + polytopiaAuthors, Array.Empty() ); Registry.mods.Add(polytopia.id, new(polytopia, Mod.Status.Success, new())); Loader.RegisterMods(Registry.mods); - Loader.LoadMods(Registry.mods, out var cycle); + Loader.LoadMods(out var cycle); dependencyCycle = cycle; stopwatch.Stop(); } /// - /// Loads all mod content. + /// Patches the getter of Application.persistentDataPath as a postfix. + /// Replaces the path with . + /// + /// Set to . + [HarmonyPostfix] + [HarmonyPatch(typeof(UnityEngine.Application), nameof(UnityEngine.Application.persistentDataPath), MethodType.Getter)] + private static void Application_persistentDataPath_get(ref string __result) + { + __result = Plugin.PERSISTENT_DATA_PATH; + } + + /// + /// Loads the content of all mods that have the status Success. /// - /// The game logic data to patch. - /// The JSON object representing the game logic data. + /// + /// First, the method loads the PolyMod localization. If is true, it stops there. + /// Then it reads the files of each mod and uses the file name or the file extension to select the action: + /// + /// localization.json and localization_*.json: calls . + /// patch.json and patch_*.json: reads the file as JSON and merges it into with . + /// prefabs, unitPrefab, improvementPrefab, and resourcePrefab JSON files: adds the file to . + /// Files with the extension .png: calls . + /// Files with the extension .bundle: calls . + /// + /// The method stops reading the files of a mod when the status of the mod is not Success. + /// It does not load .wav files. + /// + /// After all mods, the method fills TechItem.techTierFirebaseId with IDs for the tiers from 0 to . + /// Then it calls , , , and . + /// Last, it writes the load time to the log. + /// + /// + /// The game logic data that the game parses. + /// The root JSON object of the GLD. The method merges the mod patches into it. internal static void Load(GameLogicData gameLogicData, JObject json) { stopwatch.Start(); @@ -398,38 +505,57 @@ internal static void Load(GameLogicData gameLogicData, JObject json) if (patchMatch.Success) { var patchText = new StreamReader(new MemoryStream(file.bytes)).ReadToEnd(); - var template = new Api.GldConfigTemplate(patchText, mod.id); - var text = template.Render(); - if (text is null) - { - mod.status = Mod.Status.Error; - continue; - } + // var template = new Api.GldConfigTemplate(patchText, mod.id); + // var text = template.Render(); + // if (text is null) + // { + // mod.status = Mod.Status.Error; + // continue; + // } Loader.LoadGameLogicDataPatch( mod, json, - JObject.Parse(text) + JObject.Parse(patchText) ); continue; } - Match prefabMatch = Regex.Match(Path.GetFileName(file.name), @"^prefab(?:_(.*))?\.json$"); - if (prefabMatch.Success) + + Match prefabsMatch = Regex.Match(Path.GetFileName(file.name), @"^prefabs(?:_(.*))?\.json$"); + if (prefabsMatch.Success) { - Loader.LoadPrefabInfoFile( - mod, - file - ); + Registry.filesQueueToBeProcessedAfterGLDMerge.Add((mod, file)); + continue; + } + + Match unitPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^unitPrefab(?:_(.*))?\.json$"); + if (unitPrefabMatch.Success) + { + Registry.filesQueueToBeProcessedAfterGLDMerge.Add((mod, file)); + continue; + } + + Match improvementPrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^improvementPrefab(?:_(.*))?\.json$"); + if (improvementPrefabMatch.Success) + { + Registry.filesQueueToBeProcessedAfterGLDMerge.Add((mod, file)); + continue; + } + + Match resourcePrefabMatch = Regex.Match(Path.GetFileName(file.name), @"^resourcePrefab(?:_(.*))?\.json$"); + if (resourcePrefabMatch.Success) + { + Registry.filesQueueToBeProcessedAfterGLDMerge.Add((mod, file)); continue; } switch (Path.GetExtension(file.name)) { case ".png": - Loader.LoadSpriteFile(mod, file); - break; - case ".wav": - Loader.LoadAudioFile(mod, file); + Loader.LoadTextureFile(mod, file); break; + // case ".wav": + // Loader.LoadAudioFile(mod, file); + // break; case ".bundle": Loader.LoadAssetBundle(mod, file); break; @@ -442,6 +568,9 @@ internal static void Load(GameLogicData gameLogicData, JObject json) TechItem.techTierFirebaseId.Add($"tech_research_{i}"); } Loader.ProcessGameLogicData(gameLogicData, json); + Loader.ProcessFilesQueue(); + Visual.CreateSprites(); + Prefabs.CreatePrefabs(); stopwatch.Stop(); Plugin.logger.LogInfo($"Loaded all mods in {stopwatch.ElapsedMilliseconds}ms"); } diff --git a/src/Managers/Prefabs.cs b/src/Managers/Prefabs.cs new file mode 100644 index 0000000..9cd35eb --- /dev/null +++ b/src/Managers/Prefabs.cs @@ -0,0 +1,923 @@ +using HarmonyLib; +using Polytopia.Data; +using PolytopiaBackendBase.Common; +using UnityEngine; +using static PrefabManager; +using static SkinVisualsReference; + +namespace PolyMod.Managers; + +/// +/// The manager that makes custom unit, improvement, and resource prefabs from mod data. +/// It also replaces the unit prefab lookup of . +/// +public static class Prefabs +{ + /// + /// The lookup of unit prefabs by . + /// It contains the unit prefabs of the game and the custom unit prefabs that are not UI overrides. + /// also adds fallback prefabs to it. + /// + internal static Dictionary unitsNew = new(); + /// + /// The lookup of unit prefabs for each OverrideCondition, for example Christmas. + /// The key is the condition, and the value gives the prefab for each unit type. + /// It contains only the override prefabs of the game. + /// + internal static Dictionary> unitOverridesNew = new(); // maybe in the future will implement + /// + /// The lookup of unit prefabs that the UI shows in place of the usual unit prefab, by . + /// It contains the UI override prefabs of the game and the custom prefabs that have set. + /// + internal static Dictionary unitUIOverridesNew = new(); + + /// + /// The shared material of the first unit sprite renderer that finds. + /// Custom unit visual parts and their outlines use this material. + /// + internal static Material? cachedUnitMaterial; + /// + /// The loaded material that has the name . + /// Custom improvement and resource visual parts use this material. + /// + internal static Material? cachedSharedMaterial; + /// + /// The name of the material that finds and keeps in . + /// + internal const string CACHED_SHARED_MATERIAL_NAME = "SpriteMaterial"; + + /// + /// The descriptions of the custom unit prefabs from the mod prefab files. + /// makes one prefab for each item. + /// + public static List unitInfos = new(); + + /// + /// The descriptions of the custom resource prefabs. + /// It contains the items from the mod prefab files and the default items that adds. + /// makes one prefab for each item. + /// + public static List resourceInfos = new(); + + /// + /// The descriptions of the custom improvement prefabs. + /// It contains the items from the mod prefab files and the default items that adds. + /// makes one prefab for each item. + /// + public static List improvementInfos = new(); + /// + /// The improvement types that get a default prefab. + /// The loader adds each GLD improvement that has the prefab value set to true. + /// The value is true when the GLD maxLevel of the improvement is more than 0. + /// + internal static Dictionary improvementPrefabInfosToCreate = new(); + /// + /// The resource types that get a default prefab. + /// The loader adds each GLD resource that has the prefab value set to true. + /// + internal static List resourcePrefabsInfosToCreate = new(); + + private static List weaponInfos = new(); + private static Dictionary weaponProjectilesCache = new(); + private static Dictionary weaponAnimTimeCache = new() + { + {UnitData.WeaponEnum.Sting, 0.5f}, + {UnitData.WeaponEnum.IceArrow, 1f}, + {UnitData.WeaponEnum.Gun, 1.5f}, // __instance.Sway(); __instance.Tile.SpawnDarkPuff(); + {UnitData.WeaponEnum.FireBlow, 2f}, // __instance.Tile.SpawnDarkPuff(); + {UnitData.WeaponEnum.Poison, 2f}, // __instance.Tile.SpawnPoison(__instance.Owner.GetVisualSkin()); + {UnitData.WeaponEnum.Pierce, 1f}, + {UnitData.WeaponEnum.Water, 1.5f}, // __instance.Sway(); __instance.Tile.SpawnPuff(); + }; + + /// + /// Patches PrefabManager.Awake as a postfix. + /// Fills the PolyMod unit lookups from the prefab lists of the game. + /// + /// + /// The method clears , , and . + /// Then it adds the unit prefabs, the unit override prefabs, and the unit UI override prefabs of the game. + /// If is null, it keeps the shared material of the first unit sprite renderer that it finds. + /// The method also clears the custom unit prefabs that added before. + /// + /// The that the game starts. + [HarmonyPostfix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.Awake))] + private static void PrefabManager_Awake_Postfix(PrefabManager __instance) + { + unitsNew.Clear(); + unitOverridesNew.Clear(); + unitUIOverridesNew.Clear(); + + foreach (UnitPrefabData unitPrefabData in __instance.unitPrefabs) + { + if (cachedUnitMaterial == null) + { + SkinVisualsReference skinVisualsReference = unitPrefabData.prefab.GetComponent(); + if (skinVisualsReference != null && skinVisualsReference.visualParts != null) + { + foreach (VisualPart currentPart in skinVisualsReference.visualParts) + { + if (currentPart.visualPart == null) + { + continue; + } + + SpriteRenderer headSpriteRenderer = currentPart.visualPart.GetComponent(); + if (headSpriteRenderer != null) + { + cachedUnitMaterial = headSpriteRenderer.sharedMaterial; + break; + } + } + } + } + unitsNew[new SkinnedKey(unitPrefabData.type, unitPrefabData.tribe, unitPrefabData.skin)] = unitPrefabData.prefab; + } + + foreach (UnitOverridePrefabData unitOverridePrefabData in __instance.unitOverridePrefabs) + { + if (!unitOverridesNew.TryGetValue(unitOverridePrefabData.overrideCondition, out Dictionary? overridesForCondition)) + { + overridesForCondition = new Dictionary(); + unitOverridesNew[unitOverridePrefabData.overrideCondition] = overridesForCondition; + } + overridesForCondition[unitOverridePrefabData.type] = unitOverridePrefabData.prefab; + } + + foreach (UnitPrefabData unitUIOverridePrefabData in __instance.unitUIOverridePrefabs) + { + unitUIOverridesNew[new SkinnedKey(unitUIOverridePrefabData.type, unitUIOverridePrefabData.tribe, unitUIOverridePrefabData.skin)] = unitUIOverridePrefabData.prefab; + } + + Plugin.logger.LogInfo($"Built lookups: {unitsNew.Count} units, {unitUIOverridesNew.Count} UI overrides"); + } + + /// + /// Patches PrefabManager.HasUIUnitOverride as a prefix. + /// Replaces the original check with a check in . + /// + /// Set to true when contains the key, otherwise false. + /// The unit type. + /// The tribe. + /// The skin. + /// Always false, so the original method does not run. + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.HasUIUnitOverride))] + public static bool HasUIUnitOverride(ref bool __result, UnitData.Type unitType, TribeType tribe, SkinType skin) + { + __result = unitUIOverridesNew.ContainsKey(new SkinnedKey(unitType, tribe, skin)); + return false; + } + + /// + /// Patches PrefabManager.GetUnitOrUiOverride as a prefix. + /// Replaces the original method with a lookup in the PolyMod unit lookups. + /// + /// + /// The method first finds the key in . + /// If the key is not there, it uses . + /// + /// Set to the UI override prefab, or to the usual unit prefab. + /// The unit type. + /// The tribe. + /// The skin. + /// Always false, so the original method does not run. + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetUnitOrUiOverride))] + public static bool GetUnitOrUiOverride(ref Unit __result, UnitData.Type unitType, TribeType tribe, SkinType skin) + { + if (unitUIOverridesNew.TryGetValue(new SkinnedKey(unitType, tribe, skin), out Unit? uiOverridePrefab)) + { + __result = uiOverridePrefab; + } + else + { + __result = ResolveUnitPrefab(unitType, tribe, skin); + } + return false; + } + + /// + /// Patches PrefabManager.GetPrefab(UnitData.Type, TribeType, SkinType) as a prefix. + /// Replaces the original method with . + /// + /// Set to the unit prefab that gives. + /// The unit type. + /// The tribe. + /// The skin. + /// Always false, so the original method does not run. + [HarmonyPrefix] + [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), new Type[] { typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) })] + public static bool PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) + { + __result = ResolveUnitPrefab(type, tribe, skin); + return false; + } + + /// + /// Patches SkinVisualsReference.SetupVisualPart as a postfix. + /// Does the outline check for the visual part again and sets hasValidOutline. + /// + /// + /// If the outline is not a child of the visual part object, the method uses the first child as the outline. + /// It does this only when the visual part object has children. + /// Then it sets hasValidOutline to true only when the outline name is the default sprite name plus _Outline. + /// + /// The visual part that the original method configured. + /// The value from the original call. The method does not use it. + [HarmonyPostfix] // prolly remove later + [HarmonyPatch(typeof(SkinVisualsReference), nameof(SkinVisualsReference.SetupVisualPart))] + public static void SetupVisualPart(ref VisualPart visualSetting, bool isImprovement) + { + bool flag = false; + flag = visualSetting.outline != null && visualSetting.outline.transform.parent == visualSetting.visualPart.transform; + if (!flag && visualSetting.visualPart.transform.childCount > 0) + { + visualSetting.outline = visualSetting.visualPart.transform.GetChild(0).gameObject; + flag = true; + } + bool flag2 = false; + if (flag) + { + string defaultSpriteName = visualSetting.DefaultSpriteName; + if (visualSetting.outline != null && visualSetting.outline.name == defaultSpriteName + "_Outline") + { + flag2 = true; + } + } + visualSetting.hasValidOutline = flag2; + } + + // [HarmonyPrefix] // overrides again....... + // [HarmonyPatch(typeof(Unit), nameof(Unit.IsProjectile))] + // private static bool Unit_IsProjectile(ref bool __result, UnitData.WeaponEnum weapon) + // { + // if(!weaponProjectilesCache.ContainsKey(weapon)) + // return true; + + // __result = weaponProjectilesCache[weapon]; + // return false; + // } + + // [HarmonyPrefix] // overrides again....... + // [HarmonyPatch(typeof(Unit), nameof(Unit.Attack))] + // private static bool Unit_Attack(Unit __instance, WorldCoordinates target, bool moveToTarget, Action onComplete) + // { + // UnitData.WeaponEnum weaponEnum = __instance.unitData.weapon; + // List weaponPrefabInfos = weaponInfos.Where(weaponInfo => weaponInfo.weaponEnum == weaponEnum).ToList(); + // if(weaponPrefabInfos.Count == 0) + // return true; + + // WeaponPrefabInfo weaponPrefabInfo = weaponPrefabInfos.Last(); + // float chebyshevDistance = MapDataExtensions.ChebyshevDistance(__instance.Tile.Coordinates, target); + + // float animationTime = 0.2f + chebyshevDistance * 0.05f; + // Tile targetTile = MapRenderer.Current.GetTileInstance(target); + + // WeaponGFX pooledObject = ObjectPool.GetPooledObject(GetPrefab(weaponEnum).gameObject); + // pooledObject.IsUsed = true; + // Vector3 center = SkinVisualsRenderer.GetSpriteBounds(__instance.skinVisuals).center; + // pooledObject.transform.position = __instance.transform.position + center; + // pooledObject.SetSkin(__instance.Owner.GetVisualSkin()); + + // if ((bool)targetTile.Unit) + // { + // targetTile.Unit.Flipped = targetTile.Unit.UnitState.flipped; + // } + // __instance.Flipped = __instance.UnitState.flipped; + + // if(weaponPrefabInfo.weaponPuffInfo != null) + // { + // animationTime *= weaponPrefabInfo.weaponPuffInfo.animationMultiplier; + // if(weaponPrefabInfo.weaponPuffInfo.sway) + // __instance.Sway(); + // } + // if (Unit.IsProjectile(weaponEnum)) + // { + // if(weaponPrefabInfo.weaponPuffInfo != null && weaponPrefabInfo.weaponPuffInfo!.animationDelegate != null) + // pooledObject.AnimateRanged(animationTime, target, DelegateSupport.ConvertDelegate(weaponPrefabInfo.weaponPuffInfo!.animationDelegate!)); + // else + // pooledObject.AnimateRanged(animationTime, target); + // } + // else + // { + // pooledObject.AnimateCloseRangeAttack(0.2f); + // } + + // if (__instance.unitData.GetRange() < 2) + // { + // __instance.AnimateMeleeAttackMovement(targetTile, moveToTarget, onComplete); + // } + // else + // { + // GameManager.DelayCall((int)(animationTime * 1000f), onComplete); + // } + + // return false; + // } + + // [HarmonyPrefix] // testing....... + // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateCloseRangeAttack))] + // public static bool WeaponGFX_AnimateCloseRangeAttack(ref float animTime, Action onComplete) + // { + // animTime = 100000f; + // return true; + // } + + // [HarmonyPrefix] // testing....... + // [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.AnimateRanged))] + // public static bool WeaponGFX_AnimateRanged(ref float animTime, WorldCoordinates to, Action onComplete) + // { + // animTime = 100000f; + // return true; + // } + + /// + /// Finds the unit prefab for a unit type, a tribe, and a skin. + /// + /// + /// The method tries these steps in this sequence: + /// + /// If it is the Christmas season, it uses the Christmas override prefab for the unit type. + /// It uses the prefab in for the exact key. + /// If the skin is not SkinType.Default or the tribe is not TribeType.None, it tries the key with no tribe, then the key with the default skin, then the key with no tribe and the default skin. It adds the prefab that it finds to for the exact key. + /// It writes a log message and uses the prefab for the default unit type with no tribe and the default skin. + /// + /// + /// The unit type. + /// The tribe. + /// The skin. + /// The unit prefab, or null if the last step also finds no prefab. + private static Unit ResolveUnitPrefab(UnitData.Type unitType, TribeType tribeType, SkinType skinType) + { + if (SeasonManager.IsChristmas() + && unitOverridesNew.TryGetValue(OverrideCondition.Christmas, out Dictionary? christmasOverrides) + && christmasOverrides.TryGetValue(unitType, out Unit? christmasPrefab) + && christmasPrefab != null) + { + return christmasPrefab; + } + + SkinnedKey exactKey = new SkinnedKey(unitType, tribeType, skinType); + if (unitsNew.TryGetValue(exactKey, out Unit? exactPrefab)) + { + return exactPrefab; + } + + if (skinType != SkinType.Default || tribeType != TribeType.None) + { + SkinnedKey noTribeKey = new SkinnedKey(unitType, TribeType.None, skinType); + SkinnedKey defaultSkinKey = new SkinnedKey(unitType, tribeType, SkinType.Default); + SkinnedKey noTribeDefaultSkinKey = new SkinnedKey(unitType, TribeType.None, SkinType.Default); + + if (unitsNew.TryGetValue(noTribeKey, out Unit? fallbackPrefab) + || unitsNew.TryGetValue(defaultSkinKey, out fallbackPrefab) + || unitsNew.TryGetValue(noTribeDefaultSkinKey, out fallbackPrefab)) + { + unitsNew[exactKey] = fallbackPrefab; + return fallbackPrefab; + } + } + + Plugin.logger.LogInfo($"Couldn't find prefab for type: {unitType}"); + unitsNew.TryGetValue(new SkinnedKey(default, TribeType.None, SkinType.Default), out Unit? lastResortPrefab); + return lastResortPrefab!; + } + + /// + /// Makes all custom prefabs from the mod data. calls this method after the mod files are loaded. + /// + /// + /// First, the method finds the material and keeps it in . + /// Then it adds a default description to for each item in . + /// It also adds a default description to for each item in . + /// Each default description has one visual part, and its sprite name is the EnumCache name of the type. + /// Last, it makes one prefab for each item in , , and . + /// + internal static void CreatePrefabs() + { + // get materials + Material[] allLoadedMaterials = Resources.FindObjectsOfTypeAll(); + foreach (Material loadedMaterial in allLoadedMaterials) + { + // Plugin.logger.LogInfo($"Material: {loadedMaterial.name}, shader: {loadedMaterial.shader.name}"); + + if (loadedMaterial.name == CACHED_SHARED_MATERIAL_NAME) + { + cachedSharedMaterial = loadedMaterial; + GameObject.DontDestroyOnLoad(cachedSharedMaterial); + break; + } + } + + // creates dummy improvements. those have one visual part, and default name is the enum cache name of the type + foreach (KeyValuePair improvementInfo in improvementPrefabInfosToCreate) + { + ImprovementData.Type improvementType = improvementInfo.Key; + improvementInfos.Add( + new ImprovementPrefabInfo() + { + improvementType = improvementType, + visualParts = new() + { + new() + { + defaultSpriteName = EnumCache.GetName(improvementType), + levels = improvementInfo.Value, + } + } + } + ); + } + + // creates dummy resources. those have one visual part, and default name is the enum cache name of the type + foreach (ResourceData.Type resourceType in resourcePrefabsInfosToCreate) + { + resourceInfos.Add( + new ResourcePrefabInfo() + { + resourceType = resourceType, + visualParts = new() + { + new() + { + defaultSpriteName = EnumCache.GetName(resourceType), + } + } + } + ); + } + + foreach (var unitPrefabInfo in unitInfos) + { + ProcessUnitPrefabInfo(unitPrefabInfo); + } + + foreach (var improvementPrefabInfo in improvementInfos) + { + ProcessImprovementPrefabInfo(improvementPrefabInfo); + } + + foreach (var resourcePrefabInfo in resourceInfos) + { + ProcessResourcePrefabInfo(resourcePrefabInfo); + } + } + + #region Units + /// + /// Makes a unit prefab from a and adds it to a unit lookup. + /// + /// + /// The method makes a copy of the default Imperius Warrior prefab. + /// It removes the sprite container of the copy and adds an empty SpriteContainer object. + /// Then it adds the visual parts from . + /// The head position marker is the visual part with the name . + /// If no visual part has this name, the method uses the first visual part that it made. + /// If the description has no visual parts, the method uses the SpriteContainer object. + /// + /// The method keeps the prefab when the scene changes. + /// If is true, it adds the prefab to , otherwise to . + /// The key is . + /// If the method cannot get the Warrior prefab or make a copy, it does nothing. + /// + /// + /// The description of the unit prefab. + internal static void ProcessUnitPrefabInfo(UnitPrefabInfo unitPrefabInfo) + { + // maybe just init new unit? hmmmmm will try later + var baseUnit = PrefabManager.GetPrefab(UnitData.Type.Warrior, TribeType.Imperius, SkinType.Default); + if (baseUnit == null) + return; + + var unitInstance = GameObject.Instantiate(baseUnit); + if (unitInstance == null) + return; + + GameObject.Destroy(unitInstance.spriteContainer.gameObject); + + var spriteContainerObj = new GameObject("SpriteContainer"); + spriteContainerObj.transform.SetParent(unitInstance.transform, false); + var spriteContainer = spriteContainerObj.transform; + unitInstance.spriteContainer = spriteContainer; + + var visualParts = ApplyUnitVisualParts(unitPrefabInfo, spriteContainer); + + Transform? headPositionMarker = null; + foreach (var vp in visualParts) + { + if (vp.visualPart.gameObject.name == unitPrefabInfo.headPositionMarker) + { + headPositionMarker = vp.visualPart.gameObject.transform; + break; + } + } + + unitInstance.headPositionMarker = headPositionMarker + ?? (visualParts.Count > 0 ? visualParts[0].visualPart.transform : spriteContainer); + + var svr = unitInstance.GetComponent(); + svr.visualParts = visualParts.ToArray(); + + GameObject.DontDestroyOnLoad(unitInstance.gameObject); + + if (unitPrefabInfo.uiOverride) + { + unitUIOverridesNew[unitPrefabInfo.skinnedKey] = unitInstance; + return; + } + unitsNew[unitPrefabInfo.skinnedKey] = unitInstance; + } + + /// + /// Makes the visual parts of a custom unit prefab. + /// + /// + /// The method makes the visual parts with , from the last item of to the first. + /// It does not change the description. + /// The first part gets the sorting order 0, and each next part gets a sorting order that is 1 more. + /// The outline sorting order starts at minus the number of parts and increases by 1 for each part, to a maximum of -1. + /// and replace these values when they are set. + /// + /// The description of the unit prefab. + /// The transform that becomes the parent of the visual parts. + /// The visual parts, or an empty list if the description has no visual parts. + private static List ApplyUnitVisualParts( + UnitPrefabInfo unitPrefabInfo, + Transform spriteContainer) + { + List parts = new(); + List visualPartInfos = unitPrefabInfo.visualParts; + + if (visualPartInfos.Count == 0) + return parts; + + int nextPartSortingOrder = 0; + int nextOutlineSortingOrder = -visualPartInfos.Count; + for (int i = visualPartInfos.Count - 1; i >= 0; i--) + { + VisualPartInfo info = visualPartInfos[i]; + parts.Add(CreateUnitVisualPart(info, spriteContainer, info.sortingOrderOverride ?? nextPartSortingOrder, info.outlineSortingOrderOverride ?? nextOutlineSortingOrder)); + if (nextOutlineSortingOrder < -1) + { + nextOutlineSortingOrder++; + } + nextPartSortingOrder++; + } + + return parts; + } + + /// + /// Makes one visual part of a custom unit prefab, with its outline. + /// + /// + /// The visual part object has the name . + /// The outline object has the same name plus _Outline, and it is a child of the visual part object. + /// The method sets the world position and the z rotation in degrees of both objects from the description. + /// It deactivates the outline object, which keeps the outline hidden in the UI. + /// Both objects get a SpriteRenderer that uses in the Units sorting layer. + /// + /// The description of the visual part. + /// The transform that becomes the parent of the visual part object. + /// The sorting order of the visual part renderer. + /// The sorting order of the outline renderer. + /// The visual part. + private static SkinVisualsReference.VisualPart CreateUnitVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder) + { + var visualPartObj = new GameObject(info.defaultSpriteName); + visualPartObj.transform.SetParent(parent); + + var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); + outlineObj.transform.SetParent(visualPartObj.transform); + + visualPartObj.transform.position = info.coordinates; + outlineObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + // this bs was hunting me for so long. that is the thing which makes outline hidden in ui + outlineObj.SetActive(false); + + var visualPart = info.ToVisualPart(false); + visualPart.visualPart = visualPartObj; + visualPart.outline = outlineObj; + + var renderer = visualPartObj.AddComponent(); + renderer.material = cachedUnitMaterial; + renderer.sortingOrder = visualPartSortingOrder; + renderer.sortingLayerName = "Units"; + visualPart.renderer = new SkinVisualsReference.RendererUnion { spriteRenderer = renderer }; + + var outlineRenderer = outlineObj.AddComponent(); + outlineRenderer.material = cachedUnitMaterial; + outlineRenderer.sortingOrder = outlineSortingOrder; + outlineRenderer.sortingLayerName = "Units"; + visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { spriteRenderer = outlineRenderer }; + + return visualPart; + } + + #endregion + #region Improvements + /// + /// Makes an improvement prefab from an and puts it in PrefabManager.improvements. + /// + /// + /// The method makes a copy of the Lumber Hut prefab and removes all children of the copy. + /// Then it adds the visual parts from . + /// It keeps the prefab when the scene changes. + /// The prefab replaces the prefab of the same improvement type in PrefabManager.improvements. + /// If is null, or the method cannot get the Lumber Hut prefab or make a copy, it does nothing. + /// + /// The description of the improvement prefab. + internal static void ProcessImprovementPrefabInfo(ImprovementPrefabInfo improvementPrefabInfo) + { + if (improvementPrefabInfo.improvementType == null) + return; + + var baseBuilding = PrefabManager.GetPrefab(ImprovementData.Type.LumberHut); + if (baseBuilding == null) + return; + + var buildingInstance = GameObject.Instantiate(baseBuilding); + if (buildingInstance == null) + return; + + Transform buildingTransform = buildingInstance.transform; + for (int childIndex = buildingTransform.childCount - 1; childIndex >= 0; childIndex--) + { + GameObject.Destroy(buildingTransform.GetChild(childIndex).gameObject); + } + + var visualParts = ApplyBuildingVisualParts(improvementPrefabInfo, buildingTransform); + + var svr = buildingInstance.GetComponent(); + svr.visualParts = visualParts.ToArray(); + + GameObject.DontDestroyOnLoad(buildingInstance.gameObject); + + PrefabManager.improvements[(Polytopia.Data.ImprovementData.Type)improvementPrefabInfo.improvementType] = buildingInstance; + } + + /// + /// Makes the visual parts of a custom improvement prefab. + /// + /// + /// The method makes the visual parts in the sequence of with . + /// The first part gets the sorting order 0, and each next part gets a sorting order that is 1 more. + /// The outline sorting order starts at minus the number of parts and increases by 1 for each part, to a maximum of -1. + /// The method does not use or . + /// + /// The description of the improvement prefab. + /// The transform that becomes the parent of the visual parts. + /// The visual parts, or an empty list if the description has no visual parts. + private static List ApplyBuildingVisualParts( + ImprovementPrefabInfo improvementPrefabInfo, + Transform spriteContainer) + { + List parts = new(); + List visualPartInfos = improvementPrefabInfo.visualParts; + + if (visualPartInfos.Count == 0) + return parts; + + int nextPartSortingOrder = 0; + int nextOutlineSortingOrder = -visualPartInfos.Count; + foreach (var info in visualPartInfos) + { + parts.Add(CreateBuildingVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder, improvementPrefabInfo.needsOutlines)); + if (nextOutlineSortingOrder < -1) + { + nextOutlineSortingOrder++; + } + nextPartSortingOrder++; + } + + return parts; + } + + /// + /// Makes one visual part of a custom improvement prefab, with its outline. + /// + /// + /// The visual part object has the name . + /// The outline object has the same name plus _Outline, and it is a child of the visual part object. + /// The method sets the world position and the z rotation in degrees of both objects from the description. + /// It deactivates the outline object. + /// The visual part object gets a PolytopiaSpriteRenderer from . + /// The outline object gets a renderer only when is true. + /// + /// The description of the visual part. + /// The transform that becomes the parent of the visual part object. + /// The sorting order of the visual part renderer. + /// The sorting order of the outline renderer. + /// True to add a renderer to the outline object. + /// The visual part, marked as an improvement part. + private static SkinVisualsReference.VisualPart CreateBuildingVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder, + bool needsOutline = false) + { + var visualPartObj = new GameObject(info.defaultSpriteName); + visualPartObj.transform.SetParent(parent); + + var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); + outlineObj.transform.SetParent(visualPartObj.transform); + + visualPartObj.transform.position = outlineObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + outlineObj.SetActive(false); + + var visualPart = info.ToVisualPart(true); + visualPart.visualPart = visualPartObj; + visualPart.outline = outlineObj; + + var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); + visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; + + if (needsOutline) + { + var outlineRenderer = AddPolytopiaSpriteRenderer(outlineObj, outlineSortingOrder); + visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = outlineRenderer }; + } + + return visualPart; + } + + /// + /// Adds a MeshFilter, a MeshRenderer, and a PolytopiaSpriteRenderer to an object. + /// + /// + /// The mesh renderer does not cast or receive shadows, and it does not use light probes or reflection probes. + /// The method sets the sorting layer and the sorting order of the sprite renderer. + /// If is not null, the sprite renderer uses it as the shared material. + /// + /// The object that gets the components. + /// The sorting order of the sprite renderer. + /// The name of the sorting layer of the sprite renderer. The default is Terrain. + /// The new PolytopiaSpriteRenderer. + private static PolytopiaSpriteRenderer AddPolytopiaSpriteRenderer(GameObject targetGameObject, int sortingOrder, string sortingLayerName = "Terrain") + { + MeshFilter meshFilter = targetGameObject.AddComponent(); + MeshRenderer meshRenderer = targetGameObject.AddComponent(); + meshRenderer.receiveShadows = false; + meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + meshRenderer.lightProbeUsage = UnityEngine.Rendering.LightProbeUsage.Off; + meshRenderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off; + + PolytopiaSpriteRenderer polytopiaSpriteRenderer = targetGameObject.AddComponent(); + polytopiaSpriteRenderer.meshFilter = meshFilter; + polytopiaSpriteRenderer.meshRenderer = meshRenderer; + + polytopiaSpriteRenderer.SortingLayer = SortingLayer.NameToID(sortingLayerName); + polytopiaSpriteRenderer.SortingOrder = sortingOrder; + if (cachedSharedMaterial != null) + { + polytopiaSpriteRenderer.SharedMaterial = cachedSharedMaterial; + } + return polytopiaSpriteRenderer; + } + + #endregion + #region Resources + + /// + /// Makes a resource prefab from a and puts it in PrefabManager.resources. + /// + /// + /// The method makes a copy of the Game resource prefab and removes all children of the copy. + /// Then it adds the visual parts from . + /// It keeps the prefab when the scene changes. + /// The prefab replaces the prefab of the same resource type in PrefabManager.resources. + /// If is null, or the method cannot get the Game prefab or make a copy, it does nothing. + /// + /// The description of the resource prefab. + internal static void ProcessResourcePrefabInfo(ResourcePrefabInfo resourcePrefabInfo) + { + if (resourcePrefabInfo.resourceType == null) + return; + + var baseResource = PrefabManager.GetPrefab(ResourceData.Type.Game); + if (baseResource == null) + return; + + var resourceInstance = GameObject.Instantiate(baseResource); + if (resourceInstance == null) + return; + + Transform resourceTransform = resourceInstance.transform; + for (int childIndex = resourceTransform.childCount - 1; childIndex >= 0; childIndex--) + { + GameObject.Destroy(resourceTransform.GetChild(childIndex).gameObject); + } + + var visualParts = ApplyResourceVisualParts(resourcePrefabInfo, resourceTransform); + + var svr = resourceInstance.GetComponent(); + svr.visualParts = visualParts.ToArray(); + + GameObject.DontDestroyOnLoad(resourceInstance.gameObject); + + PrefabManager.resources[(Polytopia.Data.ResourceData.Type)resourcePrefabInfo.resourceType] = resourceInstance; + } + + /// + /// Makes the visual parts of a custom resource prefab. + /// + /// + /// The method makes the visual parts in the sequence of with . + /// The first part gets the sorting order 0, and each next part gets a sorting order that is 1 more. + /// The outline sorting order starts at minus the number of parts and increases by 1 for each part, to a maximum of -1. + /// The method does not use or . + /// + /// The description of the resource prefab. + /// The transform that becomes the parent of the visual parts. + /// The visual parts, or an empty list if the description has no visual parts. + private static List ApplyResourceVisualParts( + ResourcePrefabInfo resourcePrefabInfo, + Transform spriteContainer) + { + List parts = new(); + List visualPartInfos = resourcePrefabInfo.visualParts; + + if (visualPartInfos.Count == 0) + return parts; + + int nextPartSortingOrder = 0; + int nextOutlineSortingOrder = -visualPartInfos.Count; + foreach (var info in visualPartInfos) + { + parts.Add(CreateResourceVisualPart(info, spriteContainer, nextPartSortingOrder, nextOutlineSortingOrder)); + if (nextOutlineSortingOrder < -1) + { + nextOutlineSortingOrder++; + } + nextPartSortingOrder++; + } + + return parts; + } + + /// + /// Makes one visual part of a custom resource prefab, with its outline. + /// + /// + /// The visual part object has the name . + /// The outline object has the same name plus _Outline, and it is a child of the visual part object. + /// The method sets the world position and the z rotation in degrees of both objects from the description. + /// It deactivates the outline object. + /// Both objects get a PolytopiaSpriteRenderer from . + /// + /// The description of the visual part. + /// The transform that becomes the parent of the visual part object. + /// The sorting order of the visual part renderer. + /// The sorting order of the outline renderer. + /// The visual part. + private static SkinVisualsReference.VisualPart CreateResourceVisualPart( + VisualPartInfo info, + Transform parent, + int visualPartSortingOrder, + int outlineSortingOrder) + { + var visualPartObj = new GameObject(info.defaultSpriteName); + visualPartObj.transform.SetParent(parent); + + var outlineObj = new GameObject($"{info.defaultSpriteName}_Outline"); + outlineObj.transform.SetParent(visualPartObj.transform); + + visualPartObj.transform.position = outlineObj.transform.position = info.coordinates; + visualPartObj.transform.rotation = outlineObj.transform.rotation = Quaternion.Euler(0f, 0f, info.rotation); + + outlineObj.SetActive(false); + + var visualPart = info.ToVisualPart(false); + visualPart.visualPart = visualPartObj; + visualPart.outline = outlineObj; + + var renderer = AddPolytopiaSpriteRenderer(visualPartObj, visualPartSortingOrder); + visualPart.renderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = renderer }; + + var outlineRenderer = AddPolytopiaSpriteRenderer(outlineObj, outlineSortingOrder); + visualPart.outlineRenderer = new SkinVisualsReference.RendererUnion { polytopiaSpriteRenderer = outlineRenderer }; + + return visualPart; + } + + #endregion + + /// + /// Applies the Harmony patches of this class. + /// + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(Prefabs)); + } +} diff --git a/src/Managers/TribePreviews.cs b/src/Managers/TribePreviews.cs new file mode 100644 index 0000000..e920e28 --- /dev/null +++ b/src/Managers/TribePreviews.cs @@ -0,0 +1,287 @@ +using HarmonyLib; +using Polytopia.Data; +using UnityEngine; +using Il2CppSystem.Linq; +using PolyMod.Json; +using System.Text.Json.Serialization; +using PolytopiaBackendBase.Common; + +namespace PolyMod.Managers; + +/// +/// The manager for the world previews that the tribe selection screen shows. +/// It changes the preview maps of tribes with the preview tiles from mods. +/// +public static class TribePreviews +{ + /// + /// The changes to one tile of a tribe preview map. A mod gives these changes in the preview field of a tribe. + /// + public class PreviewTile + { + /// The x coordinate of the tile. If it is null, PolyMod does not change a tile. + [JsonInclude] + public int? x = null; + /// The y coordinate of the tile. If it is null, PolyMod does not change a tile. + [JsonInclude] + public int? y = null; + /// The new terrain type of the tile. If it is None, PolyMod keeps the terrain. + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public Polytopia.Data.TerrainData.Type terrainType = Polytopia.Data.TerrainData.Type.None; + /// + /// The new resource type on the tile. If it is null, PolyMod keeps the resource. + /// If it is None, PolyMod removes the resource. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ResourceData.Type? resourceType = null; + /// + /// The new unit type on the tile. If it is null, PolyMod keeps the unit. + /// If it is None, PolyMod removes the unit. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public UnitData.Type? unitType = null; + /// + /// The new improvement type on the tile. If it is null, PolyMod keeps the improvement. + /// If it is None, PolyMod removes the improvement. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ImprovementData.Type? improvementType = null; + /// + /// The new effect types on the tile. If the list is empty, PolyMod keeps the effects. + /// If not, the list replaces all effects of the tile. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheListJson))] + public List tileEffects = new(); + } + + /// + /// The data that PolyMod uses to make the preview of one tribe. + /// + /// + /// The index of the preview in TribePreviewRegistry.saveStateDatas. + /// For a tribe without a game preview, it is the index of the fallback preview. + /// + /// The game preview that PolyMod changes. + /// The tile changes from the mod. + public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); + + /// + /// A Harmony postfix on TribePreviewRegistry.PreloadTribePreviews. + /// It applies the preview tiles in to the preview of each tribe. + /// The preview of a tribe has the name worldpreview_ and the tribe name. + /// If the game has a preview with that name, the patch replaces it with the changed copy. + /// If not, the patch changes a copy of the fallback preview and adds it to the list of previews. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(TribePreviewRegistry), nameof(TribePreviewRegistry.PreloadTribePreviews))] + public static void PreloadTribePreviews() + { + Dictionary previewSaveStateDatas = new(); + + SaveStateData fallbackSaveStateData = TribePreviewRegistry.saveStateDatas[TribePreviewRegistry.fallbackStateIndex]; + foreach (string tribe in Registry.tribePreviews.Keys) + { + string previewId = "worldpreview_" + tribe; + PreviewTile[] customPreview = Registry.tribePreviews[tribe]; + previewSaveStateDatas[previewId] = new(TribePreviewRegistry.fallbackStateIndex, fallbackSaveStateData, customPreview); + } + + for (int i = 0; i < TribePreviewRegistry.saveStateDatas.Length; i++) + { + SaveStateData saveStateData = TribePreviewRegistry.saveStateDatas[i]; + if (previewSaveStateDatas.TryGetValue(saveStateData.name, out PreviewInfo? existingPreview)) + { + previewSaveStateDatas[saveStateData.name] = new(i, saveStateData, existingPreview.customPreview); + } + } + + foreach (string previewId in previewSaveStateDatas.Keys) + { + var data = previewSaveStateDatas[previewId]; + SaveStateData? customSaveStateData = ApplyCustomPreview(previewId, data.saveStateData, data.customPreview); + if (customSaveStateData == null) + continue; + + if (data.arrayIdx == TribePreviewRegistry.fallbackStateIndex) + { + List saveStateDatas = TribePreviewRegistry.saveStateDatas.ToList(); + saveStateDatas.Add(customSaveStateData); + TribePreviewRegistry.saveStateDatas = saveStateDatas.ToArray(); + } + else + { + TribePreviewRegistry.saveStateDatas[data.arrayIdx] = customSaveStateData; + } + } + } + + /// + /// Makes a changed copy of a preview with the given tile changes. + /// The method reads the game state from the compressed bytes of the preview and changes the tiles. + /// It skips a tile change without coordinates or with coordinates that are not on the map. + /// A new unit belongs to the current player and can move and attack. + /// A new improvement starts at level 0, and the current player is its founder. + /// + /// The name of the new preview. + /// The preview to copy. The method does not change it. + /// The tile changes to apply. + /// The new preview, or null if the method cannot read the bytes of the original preview. + private static SaveStateData? ApplyCustomPreview(string previewId, SaveStateData originalPreview, PreviewTile[] preview) + { + SaveStateData? saveStateData = null; + if (DiskSerializationHelpers.FromLZ4CompressedByteArray( + originalPreview.byteArray, out ClientSerializationWrapper clientSerializationWrapper, out int version)) + { + GameState currentGameState = clientSerializationWrapper.GetCurrentGameState(); + foreach (var previewTile in preview) + { + if (previewTile.x == null || previewTile.y == null) + continue; + + WorldCoordinates coordinates = new((int)previewTile.x, (int)previewTile.y); + TileData? tileData = currentGameState.Map.GetTile(coordinates); + if (tileData == null) + continue; + + if (previewTile.terrainType != Polytopia.Data.TerrainData.Type.None) + tileData.terrain = previewTile.terrainType; + + if (previewTile.resourceType != null) + { + ResourceState? resourceState = null; + ResourceData.Type resourceType = (ResourceData.Type)previewTile.resourceType; + if (resourceType != ResourceData.Type.None) + { + resourceState = new ResourceState { type = resourceType }; + } + tileData.resource = resourceState; + } + + if (previewTile.unitType != null) + { + tileData.unit = null; + if (previewTile.unitType != Polytopia.Data.UnitData.Type.None && + currentGameState.TryGetPlayer(currentGameState.CurrentPlayer, out PlayerState playerState) && + currentGameState.GameLogicData.TryGetData((UnitData.Type)previewTile.unitType, out UnitData unitData)) + { + UnitState unitState = ActionUtils.TrainUnit(currentGameState, playerState, tileData, unitData); + unitState.moved = false; + unitState.attacked = false; + } + } + + + if (previewTile.improvementType != null) + { + tileData.improvement = null; + ImprovementData.Type improvementType = (ImprovementData.Type)previewTile.improvementType; + if ( + previewTile.improvementType != ImprovementData.Type.None && + currentGameState.GameLogicData.TryGetData( + improvementType, + out ImprovementData improvementData) + ) + { + tileData.improvement = new ImprovementState + { + type = improvementData.type, + borderSize = (ushort)improvementData.borderSize, + level = 0, + xp = 0, + production = 1, + founded = (ushort)currentGameState.CurrentTurn, + baseScore = (ushort)improvementData.GetScoreReward(), + founder = currentGameState.CurrentPlayer + }; + } + } + + if (previewTile.tileEffects.Count > 0) + tileData.effects = new(); + + foreach (TileData.EffectType tileEffect in previewTile.tileEffects) + { + tileData.AddEffect(tileEffect); + } + } + + saveStateData = ScriptableObject.CreateInstance(); + saveStateData.name = previewId; + saveStateData.byteArray = DiskSerializationHelpers.ToLZ4CompressedByteArray(clientSerializationWrapper, version); + } + + return saveStateData; + } + + /// + /// A Harmony postfix on SelectTribePopup.SetBackground. + /// If the showCoordinates setting is on, it replaces the world preview image with a new snapshot. + /// The snapshot uses two times the camera size, so it shows a larger area of the preview map. + /// If the snapshot fails, the patch writes a warning to the log. + /// + /// The tribe selection popup. + [HarmonyPostfix] + [HarmonyPatch(typeof(SelectTribePopup), nameof(SelectTribePopup.SetBackground))] + private static void SelectTribePopup_SetBackground(SelectTribePopup __instance) + { + if (!Plugin.config.showCoordinates) + return; + + try + { + TribeType tribeType = (__instance.mixTribeData != null) ? __instance.mixTribeData.type : __instance.tribeData.type; + + __instance.mapSnapshot = new SpriteCamera.SnapshotMapData(); + __instance.mapSnapshot.LoadMapState( + TribePreviewRegistry.GetTribePreviewData(tribeType, __instance.SkinType) + ); + + float width = __instance.worldPreviewRawImage.rectTransform.GetWidth(); + float height = __instance.worldPreviewRawImage.rectTransform.GetHeight(); + + int tribeColor = PolytopiaDataManager.GetGameLogicData( + VersionManager.GameLogicDataVersion + ).GetTribeColor( + tribeType, + __instance.SkinType + ); + + var instance = SpriteCamera.instance; + float baseOrthographicCameraSize = instance.spriteCamera.orthographicSize; + + instance.spriteCamera.orthographicSize = (float)baseOrthographicCameraSize * 2; + + Texture2D texture2D = SpriteCamera.TakeSnapshotOfMapState( + __instance.mapSnapshot, + width, + height, + tribeType, + __instance.SkinType, + tribeType, + tribeColor + ); + + instance.spriteCamera.orthographicSize = baseOrthographicCameraSize; + + __instance.worldPreviewRawImage.texture = texture2D; + __instance.worldPreviewRawImage.color = Color.white; + } + catch (Exception ex) + { + Plugin.logger.LogWarning($"Failed to load debug tribe preview {ex.Message}"); + } + } + + /// + /// Applies all Harmony patches in the class. + /// + internal static void Init() + { + Harmony.CreateAndPatchAll(typeof(TribePreviews)); + } +} diff --git a/src/Managers/Visual.cs b/src/Managers/Visual.cs index 6f68ce6..123ba8f 100644 --- a/src/Managers/Visual.cs +++ b/src/Managers/Visual.cs @@ -1,374 +1,562 @@ -using System.Reflection; using HarmonyLib; using Polytopia.Data; using UnityEngine; -using UnityEngine.U2D; -using UnityEngine.UI; using Il2CppSystem.Linq; -using PolyMod.Json; -using System.Text.Json.Serialization; using PolytopiaBackendBase.Common; -using Il2CppInterop.Runtime; +using System.Text.Json.Serialization; +using PolyMod.Json; using TMPro; namespace PolyMod.Managers; /// -/// Manages visual aspects of the game, including sprites, UI, and in-game objects. +/// The manager for sprites, textures, terrain graphics, and popups. +/// It also contains the Harmony patches that change how the game shows these items. /// public static class Visual { /// - /// Represents a tile in a tribe preview. + /// The settings that PolyMod uses to make a sprite, such as the pivot and the pixels per unit. + /// A mod gives these settings in a sprites.json file. /// - public class PreviewTile + public class SpriteInfo { - /// The x-coordinate of the tile. + /// + /// The number of texture pixels in one world unit. + /// If this value is null, PolyMod uses 2112 for a mod texture and the original value for a game sprite. + /// [JsonInclude] - public int? x = null; - /// The y-coordinate of the tile. - [JsonInclude] - public int? y = null; - /// The terrain type of the tile. + public float? pixelsPerUnit; + + /// + /// The pivot of the sprite, as a fraction of the sprite size. + /// If this value is null, PolyMod uses a preset pivot for a mod texture and the original pivot for a game sprite. + /// [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public Polytopia.Data.TerrainData.Type terrainType = Polytopia.Data.TerrainData.Type.None; - /// The resource type on the tile. + public Vector2? pivot; + + /// + /// The source of the sprite image. + /// If this value is null, PolyMod uses the mod texture that has the same name as the sprite. + /// [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ResourceData.Type? resourceType = null; - /// The unit type on the tile. + public SpriteOrigin? spriteOrigin = null; + + /// + /// If true, PolyMod changes the image into a white silhouette with a border before it makes the sprite. + /// [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public UnitData.Type? unitType = null; - /// The improvement type on the tile. + public bool transformToOutline = false; + + /// + /// The radius of the Gaussian blur that PolyMod applies to the image. + /// If this value is null, PolyMod does not apply a blur. + /// [JsonInclude] - [JsonConverter(typeof(EnumCacheJson))] - public ImprovementData.Type? improvementType = null; + public float? gaussianBlurRadius = null; + + /// + /// Makes a new with the given settings. + /// + /// The number of texture pixels in one world unit, or null to use the default value. + /// The pivot of the sprite, or null to use the default pivot. + /// If true, the image changes into a white silhouette with a border. + /// The source of the sprite image, or null to use the texture with the same name. + /// The radius of the Gaussian blur, or null for no blur. + public SpriteInfo(float? pixelsPerUnit, Vector2? pivot, bool transformToOutline = false, SpriteOrigin? spriteOrigin = null, float? gaussianBlurRadius = null) + { + this.pixelsPerUnit = pixelsPerUnit; + this.pivot = pivot; + this.spriteOrigin = spriteOrigin; + this.transformToOutline = transformToOutline; + this.gaussianBlurRadius = gaussianBlurRadius; + } } - /// Represents information about a sprite, such as its pivot and pixels per unit. - public record SpriteInfo(float? pixelsPerUnit, Vector2? pivot); + /// + /// The source of the image for a sprite that a describes. + /// + public class SpriteOrigin + { + /// + /// The name of the source image. + /// For , it is the name of a mod texture. + /// For , it is the name of a game sprite. + /// + [JsonInclude] + public string? name; - /// Represents information about a custom skin. - public record SkinInfo(int idx, string id, SkinData? skinData); + /// + /// The type of the source. The default value is . + /// + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public OriginType originType = OriginType.Outer; + } - /// A dictionary of custom widths for basic popups. - public static Dictionary basicPopupWidths = new(); - /// Represents information about a unit prefab. - public struct UnitPrefabInfo + /// + /// The types of source for the image of a sprite. + /// + public enum OriginType { - public UnitPrefabInfo(string type, string tribe, string skin) - { - this.type = type; - this.tribe = tribe; - this.skin = skin; - } - public string type; - public string tribe; - public string skin; + /// The image comes from a texture in a mod. + Outer, // Outer means sprite comes from a mod, and not from game's files + /// The image comes from a sprite in the game files. + Inner // Inner means sprite is to be fetched from game's files } + + /// + /// The data about a custom skin that a mod adds. + /// + /// The enum value that PolyMod gives to the skin. + /// The ID of the skin in the GLD. + /// The skin data, or null if PolyMod did not make it. + public record SkinInfo(int idx, string id, SkinData? skinData); + + /// + /// The custom widths of shown popups, keyed by the Unity instance ID of the popup. + /// PolyMod removes an entry when the popup closes. + /// + public static Dictionary basicPopupWidths = new(); + + /// + /// The custom width settings of one popup. + /// + /// The popup that uses the custom width. + /// The share of the usable screen width, from 0 to 1. A value of 0 or less gives a fixed width. + /// The maximum width in canvas units. With a fixed width, this is the width of the popup. + public record PopupWidth(BasicPopupLegacy popup, float share, float maximum); + private const int BASIC_POPUP_LEGACY_ID = 29; - public static Dictionary customPrefabs = new(); - private static UnitData.Type currentUnitTypeUI = UnitData.Type.None; - private static TribeType attackerTribe = TribeType.None; + /// - /// A dictionary of skin types of tribes, which can flood tiles, keyed by custom flood tile effect. + /// The width of the game's own popups, in canvas units. + /// A popup with a screen share never gets a smaller width than this value. /// - internal static Dictionary customFloodingSkins = new(); - private static bool isTakingSnapshot = false; - private static float? baseOrthographicCameraSize = null; + private const float DEFAULT_POPUP_WIDTH = 402f; - /// The type of a custom prefab. - public enum PrefabType - { - Unit, - Improvement, - Resource - } + /// + /// The horizontal gap between two popup buttons in one row, in canvas units. + /// If a button and this gap do not fit in the row, the button goes to a new row. + /// + private const float POPUP_BUTTON_GAP = 8f; - /// Represents information about a custom prefab. - public record PrefabInfo - { - public PrefabType type { get; init; } - public string name { get; init; } - public List visualParts { get; init; } - public string headPositionMarker { get; init; } + /// + /// The vertical gap between two rows of popup buttons, in canvas units. + /// + private const float POPUP_BUTTON_ROW_GAP = 10f; - [JsonConstructor] - public PrefabInfo( - PrefabType type, - List visualParts, - string name = "", - string headPositionMarker = "") - { - this.type = type; - this.name = name.ToLowerInvariant(); - this.visualParts = visualParts; - this.headPositionMarker = headPositionMarker; - } - } + private const byte INVISIBLE_ALPHA = 2; + private const int ALPHA_BLEED_RINGS = 16; + private const int PREMULTIPLIED_MIN_EDGE_PIXELS = 64; + private const float PREMULTIPLIED_MAX_OUTLIER_SHARE = 0.005f; + + /// + /// The custom skins that can flood tiles, keyed by the custom flood tile effect of each skin. + /// The loader adds an entry for each custom skin that has the Flooded tribe ability. + /// + internal static Dictionary customFloodingSkins = new(); + + private static readonly Color WEEKLY_CHALLENGE_DISABLED_COLOR = new(0.42f, 0.42f, 0.42f, 1f); - /// Represents information about a visual part of a prefab. - public record VisualPartInfo( - string gameObjectName, - string baseName, - float rotation = 0f, - Vector2 coordinates = new Vector2(), - Vector2 scale = new Vector2(), - bool tintable = false - ); - private static bool enableOutlines = false; - private static bool seenWarningWCPopup = false; - public record PreviewInfo(int arrayIdx, SaveStateData saveStateData, PreviewTile[] customPreview); + private static Dictionary? cachedSpriteDataReverse = null; + private static Dictionary cachedReversedNames = new(); #region General - /// A placeholder patch for the TechItem.SetupComplete method. + /// + /// A Harmony postfix on TechItem.SetupComplete. It is empty and does not change the game. + /// [HarmonyPostfix] [HarmonyPatch(typeof(TechItem), nameof(TechItem.SetupComplete))] private static void TechItem_SetupComplete() { } - /// Patches the sprite atlas manager to load custom sprites. - [HarmonyPrefix] - [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), typeof(string), typeof(string), typeof(SpriteCallback))] - private static bool SpriteAtlasManager_LoadSprite(SpriteAtlasManager __instance, string atlas, string sprite, SpriteCallback completion) + /// + /// Fills the cache that maps game sprite names to PolyMod enum names. + /// The cache contains the names of terrain, resource, and improvement sprites. + /// The wetland sprite name maps to the field name with the _flooded suffix. + /// Unknown terrain and placeholder sprite names are not in the cache. + /// + internal static void CacheSpriteNames() { - bool found = false; - __instance.LoadSpriteAtlas(atlas, (Il2CppSystem.Action)GetAtlas); - - return !found; - - void GetAtlas(SpriteAtlas spriteAtlas) + cachedSpriteDataReverse = new(); + foreach (Polytopia.Data.TerrainData.Type terrainType in Enum.GetValues()) { - if (spriteAtlas != null) + string result = SpriteData.TerrainToString(terrainType); + if (terrainType == Polytopia.Data.TerrainData.Type.Wetland) { - List names = sprite.Split('_').ToList(); - List filteredNames = new List(names); - string style = ""; - foreach (string item in names) - { - string upperitem = char.ToUpper(item[0]) + item[1..]; - if (EnumCache.TryGetType(item, out TribeType tribe) || EnumCache.TryGetType(item, out SkinType skin) - || EnumCache.TryGetType(upperitem, out TribeType tribeUpper) || EnumCache.TryGetType(upperitem, out SkinType skinUpper)) - { - filteredNames.Remove(item); - style = item; - continue; - } - } - string name = string.Join("_", filteredNames); - Sprite? newSprite = Registry.GetSprite(name, style); - if (newSprite != null) - { - completion?.Invoke(atlas, sprite, newSprite); - found = true; - } + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(Polytopia.Data.TerrainData.Type.Field) + "_flooded"); + continue; } + + if (result == SpriteData.TILE_UNKNOWN) + continue; + + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(terrainType)); } - } - /// Patches the sprite atlas manager to look up custom sprites. - [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.DoSpriteLookup))] - private static void SpriteAtlasManager_DoSpriteLookup(ref SpriteAtlasManager.SpriteLookupResult __result, SpriteAtlasManager __instance, string baseName, TribeType tribe, SkinType skin, int level) - { - baseName = Util.FormatSpriteName(baseName); + foreach (ResourceData.Type resourceType in Enum.GetValues()) + { + string result = SpriteData.ResourceToString(resourceType); + if (result == SpriteData.IMPROVEMENT_PLACEHOLDER) + continue; - Sprite? sprite = Registry.GetSprite(baseName, Util.GetStyle(tribe, skin), level); - if (sprite != null) - __result.sprite = sprite; - } + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(resourceType)); + } - #endregion - #region Units + foreach (ImprovementData.Type improvementType in Enum.GetValues()) + { + string result = SpriteData.ImprovementToString(improvementType); + if (result == SpriteData.IMPROVEMENT_PLACEHOLDER) + continue; - /// Enables outlines when the interaction bar is shown. - [HarmonyPrefix] - [HarmonyPatch(typeof(InteractionBar), nameof(InteractionBar.Show))] - private static bool InteractionBar_Show(InteractionBar __instance, bool instant, bool force) + cachedSpriteDataReverse.TryAdd(result, EnumCache.GetName(improvementType)); + } + } + /// + /// Changes a game sprite name into a name that uses PolyMod enum names. + /// The method replaces each cached game sprite name in the text with its enum name. + /// It fills the name cache on the first call and keeps each result in a second cache. + /// + /// The sprite name that the game uses. + /// The sprite name with enum names. If no part matches, the method gives the same name. + internal static string FormatSpriteName(string baseName) { - enableOutlines = true; - return true; + if (cachedSpriteDataReverse == null) + CacheSpriteNames(); + + if (cachedReversedNames.TryGetValue(baseName, out string? cachedReversedName)) + return cachedReversedName; + + string formattedName = baseName; + foreach (var valuePair in cachedSpriteDataReverse!) + { + formattedName = formattedName.Replace(valuePair.Key, valuePair.Value); + } + cachedReversedNames[baseName] = formattedName; + return formattedName; } - /// Prevents outlines from being created when they are disabled. - [HarmonyPrefix] - [HarmonyPatch(typeof(UISpriteDuplicator), nameof(UISpriteDuplicator.CreateImage), typeof(SpriteRenderer), typeof(Transform), typeof(Transform), typeof(float), typeof(Vector2), typeof(bool))] - private static bool UISpriteDuplicator_CreateImage(SpriteRenderer spriteRenderer, Transform source, Transform destination, float scale, Vector2 offset, bool forceFullAlpha) + /// + /// A Harmony postfix on SpriteAtlasManager.TrySolveSpriteNameForLevelSprites. + /// It always sets the result to true, because a false result makes the original sprite lookup fail. + /// + /// The result of the original method. The patch sets it to true. + /// The sprite atlas manager. + /// The sprite name variants that the original method examines. + /// The level of the sprite. + /// The sprite name that the original method found. The patch does not change it. + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.TrySolveSpriteNameForLevelSprites))] + private static void SpriteAtlasManager_TrySolveSpriteNameForLevelSprites( + ref bool __result, + SpriteAtlasManager __instance, + Il2CppInterop.Runtime.InteropTypes.Arrays.Il2CppStringArray spriteNameVariants, int level, ref string result) { - return !(spriteRenderer.sortingOrder == -1 && !enableOutlines); + if (!__result) __result = true; // will crash original lookup if false.... } - /// Disables outlines after the interaction bar is shown. + /// + /// A Harmony postfix on SpriteAtlasManager.DoSpriteLookup. + /// It replaces the sprite and the outline sprite in the result with registered mod sprites. + /// First, it uses the original sprite name. Then it uses the name from , if that name is different. + /// A sprite from the second name replaces a sprite from the first name. + /// + /// The lookup result of the original method. The patch can change its sprites. + /// The sprite atlas manager. + /// The sprite name that the game looks for. + /// The tribe of the sprite. + /// The skin of the sprite. + /// The level of the sprite. [HarmonyPostfix] - [HarmonyPatch(typeof(InteractionBar), nameof(InteractionBar.Show))] - private static void InteractionBar_Show_Postfix(InteractionBar __instance, bool instant, bool force) + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.DoSpriteLookup))] + private static void SpriteAtlasManager_DoSpriteLookup( + ref SpriteAtlasManager.SpriteLookupResult __result, + SpriteAtlasManager __instance, + string baseName, TribeType tribe, SkinType skin, int level) { - enableOutlines = false; + ApplyRegisteredSprites(ref __result, baseName, tribe, skin, level); + + string formattedName = FormatSpriteName(baseName); + if (formattedName != baseName) + { + ApplyRegisteredSprites(ref __result, formattedName, tribe, skin, level); + } } - /// Sets the current unit type being rendered in the UI. - [HarmonyPrefix] - [HarmonyPatch(typeof(UIUnitRenderer), nameof(UIUnitRenderer.CreateUnit))] - private static bool UIUnitRenderer_CreateUnit_Prefix(UIUnitRenderer __instance) + /// + /// Puts the registered mod sprite and outline sprite for a name into a lookup result. + /// If the registry has no sprite of a type, the method keeps the sprite of that type in the result. + /// + /// The lookup result to change. + /// The sprite name to find in the registry. + /// The tribe of the sprite. + /// The skin of the sprite. + /// The level of the sprite. + private static void ApplyRegisteredSprites( + ref SpriteAtlasManager.SpriteLookupResult lookupResult, + string spriteName, TribeType tribe, SkinType skin, int level) { - currentUnitTypeUI = __instance.unitType; - return true; + Sprite? registeredSprite = Registry.GetSprite(spriteName, tribe, skin, level); + if (registeredSprite != null) + lookupResult.sprite = registeredSprite; + + Sprite? registeredOutlineSprite = Registry.GetSprite(spriteName, tribe, skin, level, true); + if (registeredOutlineSprite != null) + lookupResult.outlineSprite = registeredOutlineSprite; } - /// Resets the current unit type being rendered in the UI. + /// + /// A Harmony postfix on SpriteAtlasManager.GetSprite(string, string). + /// If the original method found no sprite, the patch gives the registered mod sprite with the lowercase name. + /// + /// The sprite that the original method found. The patch sets it only if it is null. + /// The name of the sprite. [HarmonyPostfix] - [HarmonyPatch(typeof(UIUnitRenderer), nameof(UIUnitRenderer.CreateUnit))] - private static void UIUnitRenderer_CreateUnit_Postfix(UIUnitRenderer __instance) + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.GetSprite), new Type[] { typeof(string), typeof(string) })] + private static void SpriteAtlasManager_GetSprite(ref Sprite __result, string spriteName) { - currentUnitTypeUI = UnitData.Type.None; + if (__result != null || string.IsNullOrEmpty(spriteName)) return; + if (Registry.sprites.TryGetValue(spriteName.ToLowerInvariant(), out Sprite? sprite)) + __result = sprite; } - /// Skins the visual parts of a unit with custom sprites. + /// + /// A Harmony postfix on MapDataExtensions.GenerateShoreLines. + /// For each visible shoreline of a tile, it sets the sprite suffix from the skin and effects of the adjacent tile. + /// + /// The map that has the shorelines. [HarmonyPostfix] - [HarmonyPatch(typeof(SkinVisualsRenderer), nameof(SkinVisualsRenderer.SkinWorldObject))] - private static void SkinVisualsRenderer_SkinWorldObject( - SkinVisualsRenderer.SkinWorldType type, - SkinVisualsReference skinVisuals, - SkinVisualsTransientData transientSkinData, - bool checkOutlines, - int level) - { - if (type != SkinVisualsRenderer.SkinWorldType.Unit || skinVisuals == null || - skinVisuals.visualParts == null || transientSkinData == null) - return; + [HarmonyPatch(typeof(MapDataExtensions), nameof(MapDataExtensions.GenerateShoreLines))] + private static void MapDataExtensions_GenerateShoreLines(MapData map) + { + int width = map.Width; + var tiles = map.Tiles; + for (int i = 0; i < tiles.Length; i++) + { + TileData.Shorelines shorelines = tiles[i].shorelines; + if (!shorelines.any) continue; - Unit unit = skinVisuals.gameObject.GetComponent(); + if (shorelines.S.visible) SetShorelineSuffix(tiles[i - width], shorelines.S); + if (shorelines.N.visible) SetShorelineSuffix(tiles[i + width], shorelines.N); + if (shorelines.W.visible) SetShorelineSuffix(tiles[i - 1], shorelines.W); + if (shorelines.E.visible) SetShorelineSuffix(tiles[i + 1], shorelines.E); + } + } - string unitTypeName = EnumCache.GetName(UnitData.Type.Warrior); + /// + /// Sets the sprite suffix of a shoreline from the skin and effects of a tile. + /// The suffix is _swamp for a swamp skin or a swamped tile. + /// For a different custom or tribe skin, the suffix is an underscore and the skin name. + /// A custom flood effect on the tile replaces the suffix with the name of the related skin. + /// If no rule applies, the suffix is empty. + /// + /// The tile that gives the skin and the effects. + /// The shoreline to change. + private static void SetShorelineSuffix(TileData neighbour, TileData.Shoreline shoreline) + { + string suffix = neighbour.Skin == SkinType.Swamp || neighbour.HasEffect(TileData.EffectType.Swamped) + ? "_swamp" + : ""; + if (neighbour.Skin != SkinType.None && neighbour.Skin != SkinType.Default && neighbour.Skin != SkinType.Swamp) + suffix = "_" + EnumCache.GetName(neighbour.Skin); + foreach (var effectToSkin in customFloodingSkins) + { + if (neighbour.HasEffect(effectToSkin.Key)) + { + suffix = "_" + EnumCache.GetName(effectToSkin.Value); + break; + } + } + shoreline.spriteExt = suffix; + } - if (unit != null && unit.UnitData != null) - unitTypeName = EnumCache.GetName(unit.unitData.type); - if (currentUnitTypeUI != UnitData.Type.None) - unitTypeName = EnumCache.GetName(currentUnitTypeUI); + /// + /// A Harmony prefix on SpriteAtlasManager.LoadSprite(string, string, SpriteCallback). + /// It finds a registered mod sprite with the name from , and then with the original name. + /// If it finds a sprite, it calls the callback with that sprite. + /// + /// The name of the atlas. + /// The name of the sprite. + /// The callback that gets the sprite. + /// False if the patch found a mod sprite, which skips the original method. True if not. + [HarmonyPrefix] // its obsolete so may be removed soon by midjiwan + [HarmonyPatch(typeof(SpriteAtlasManager), nameof(SpriteAtlasManager.LoadSprite), new Type[] { typeof(string), typeof(string), typeof(SpriteCallback) })] + private static bool LoadSprite(string atlas, string sprite, SpriteCallback completion) + { + string formattedName = FormatSpriteName(sprite); - string style = Util.GetStyle(transientSkinData.unitSettings.tribe, transientSkinData.unitSettings.skin); + Sprite? resolvedSprite = Registry.GetSprite(formattedName); - foreach (var visualPart in skinVisuals.visualParts) + if (resolvedSprite == null && formattedName != sprite) { - if (visualPart.visualPart != null) - UpdateVisualPart(visualPart, $"{visualPart.visualPart.name}_{unitTypeName}", style); + resolvedSprite = Registry.GetSprite(sprite); } - } - [HarmonyPostfix] - [HarmonyPatch(typeof(PrefabManager), nameof(PrefabManager.GetPrefab), - typeof(UnitData.Type), typeof(TribeType), typeof(SkinType) - )] - private static void PrefabManager_GetPrefab(ref Unit __result, UnitData.Type type, TribeType tribe, SkinType skin) - { - UnitPrefabInfo unitPrefabInfo = new( - EnumCache.GetName(type), - EnumCache.GetName(TribeType.None), - EnumCache.GetName(SkinType.Default) - ); - if (customPrefabs.ContainsKey( - unitPrefabInfo - )) + if (resolvedSprite == null) { - __result = customPrefabs[unitPrefabInfo]; + return true; } - } - #endregion - #region Level + completion.Invoke(atlas, sprite, resolvedSprite); + return false; + } - /// Updates the visual parts of a resource with custom sprites. + /// + /// A Harmony postfix on SpriteData.TerrainToString. + /// For a custom terrain type, it replaces the sprite name with the enum name of the terrain. + /// + /// The sprite name that the original method gives. + /// The terrain type. [HarmonyPostfix] - [HarmonyPatch(typeof(Resource), nameof(Resource.UpdateObject), typeof(MapRenderContext), typeof(SkinVisualsTransientData))] - private static void Resource_UpdateObject(Resource __instance, MapRenderContext ctx, SkinVisualsTransientData transientSkinData) + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.TerrainToString))] + private static void SpriteData_TerrainToString(ref string __result, Polytopia.Data.TerrainData.Type terrain) { - if (__instance.data != null) - { - string style = Util.GetStyle(__instance.tile.data.climate, __instance.tile.data.Skin); - string name = EnumCache.GetName(__instance.tile.data.resource.type); + if ((int)terrain >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(terrain); + } - foreach (SkinVisualsReference.VisualPart visualPart in __instance.GetSkinVisualsReference().visualParts) - { - UpdateVisualPart(visualPart, name, style); - } - } + /// + /// A Harmony postfix on SpriteData.ResourceToString. + /// For a custom resource type, it replaces the sprite name with the enum name of the resource. + /// + /// The sprite name that the original method gives. + /// The resource type. + [HarmonyPostfix] + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ResourceToString))] + private static void SpriteData_ResourceToString(ref string __result, ResourceData.Type resource) + { + if ((int)resource >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(resource); } - /// Updates a building with a custom sprite. + /// + /// A Harmony postfix on SpriteData.ImprovementToString. + /// For a custom improvement type, it replaces the sprite name with the enum name of the improvement. + /// + /// The sprite name that the original method gives. + /// The improvement type. [HarmonyPostfix] - [HarmonyPatch(typeof(Building), nameof(Building.UpdateObject), typeof(MapRenderContext), typeof(SkinVisualsTransientData))] - private static void Building_UpdateObject(Building __instance, MapRenderContext ctx, SkinVisualsTransientData transientSkinData) + [HarmonyPatch(typeof(SpriteData), nameof(SpriteData.ImprovementToString))] + private static void SpriteData_ImprovementToString(ref string __result, ImprovementData.Type improvement) { - string style = Util.GetStyle(transientSkinData.foundingTribeSettings.tribe, transientSkinData.foundingTribeSettings.skin); - string name = EnumCache.GetName(__instance.tile.data.improvement.type); - Sprite? sprite = Registry.GetSprite(name, style, __instance.Level); - if (sprite != null) - { - __instance.Sprite = sprite; - } + if ((int)improvement >= Plugin.AUTOIDX_STARTS_FROM) + __result = EnumCache.GetName(improvement); } - /// Updates the terrain graphics with custom sprites. + #endregion + #region Level + + /// + /// A Harmony postfix on Tile.RenderDebug. + /// If the showCoordinates setting is on, it adds a child object with white text that shows the tile coordinates. + /// The text uses the terrain sorting layer, above the tile. + /// + /// The tile. [HarmonyPostfix] - [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] - private static void TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, Tile tile) + [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] + public static void Tile_RenderDebug(Tile __instance) { - string terrain = EnumCache.GetName(tile.data.terrain) ?? string.Empty; + if (!Plugin.config.showCoordinates) + return; + + GameObject textObj = new GameObject("CoordinateText"); + textObj.transform.SetParent(__instance.transform); + textObj.transform.localPosition = new Vector3(0, 0.0f, 0); + + TextMeshPro textMesh = textObj.AddComponent(); + textMesh.text = __instance.Data.coordinates.ToString(); + textMesh.fontSize = 3; + textMesh.alignment = TextAlignmentOptions.Center; + textMesh.color = Color.white; - TribeType tribe = tile.data.climate; - SkinType skinType = tile.data.Skin; + MeshRenderer renderer = textObj.GetComponent(); + renderer.sortingLayerID = MeshCache.TERRAIN_LAYER_ID; + renderer.sortingOrder = __instance.Depth + 10; + } - string flood = ""; - if ( - tile.data.effects.Contains(TileData.EffectType.Flooded) || - (tribe == TribeType.Aquarion && tile.data.terrain == Polytopia.Data.TerrainData.Type.Mountain) - ) // TODO: Check all tribes with flooded abil instead of Aquarion only. + /// + /// Gets the terrain sprite name for a land tile. + /// A tile that is not flooded uses the field sprite name. + /// A flooded tile uses the wetland sprite name. + /// A swamped tile adds the _swamp suffix to the wetland name. + /// A tile with a custom flood effect adds an underscore and the name of the related skin. + /// + /// The data of the tile. + /// The terrain sprite name for the tile. + private static string GetLandSpriteName(TileData tileData) + { + if (!tileData.HasEffect(TileData.EffectType.Flooded)) { - foreach (var effect in tile.data.effects) - { - if (customFloodingSkins.ContainsKey(effect)) - { - skinType = customFloodingSkins[effect]; - break; - } - } - flood = "_flooded"; + return SpriteData.TerrainToString(Polytopia.Data.TerrainData.Type.Field); } - if (tile.data.terrain is Polytopia.Data.TerrainData.Type.Forest or Polytopia.Data.TerrainData.Type.Mountain) - { - string propertyName = terrain.ToLower(); - terrain = "field"; - PropertyInfo? rendererProperty = tile.GetType().GetProperty(propertyName + "Renderer", - BindingFlags.Public | BindingFlags.Instance); + string wetlandSpriteName = SpriteData.TerrainToString(Polytopia.Data.TerrainData.Type.Wetland); + + if (tileData.HasEffect(TileData.EffectType.Swamped)) + { + return wetlandSpriteName + "_swamp"; + } - if (rendererProperty != null) + foreach (TileData.EffectType effectType in tileData.effects) + { + if (customFloodingSkins.TryGetValue(effectType, out SkinType skinType)) { - PolytopiaSpriteRenderer? renderer = (PolytopiaSpriteRenderer?)rendererProperty.GetValue(tile); - if (renderer != null) - { - Sprite? additionalSprite = Registry.GetSprite(propertyName + flood, Util.GetStyle(tribe, skinType)); - if (additionalSprite != null) - { - renderer.Sprite = additionalSprite; - rendererProperty.SetValue(tile, renderer); - } - } + return $"{wetlandSpriteName}_{EnumCache.GetName(skinType)}"; } } - Sprite? sprite = Registry.GetSprite(terrain + flood, Util.GetStyle(tribe, skinType)); - if (sprite != null) + return wetlandSpriteName; + } + + /// + /// A Harmony prefix on TerrainRenderer.UpdateGraphics that replaces the original method. + /// Water, ocean, and ice tiles use the sprite names from the sprite sets of the renderer. + /// Other tiles use the name from . + /// The patch finds the sprite for the climate and skin, and sets it if the lookup has a sprite. + /// It also changes the desaturation of the sprite when the requested state is different. + /// + /// The terrain renderer. + /// The tile to show. + /// The tribe that gives the climate of the tile. + /// The skin of the tile. + /// If true, the renderer shows the sprite without color saturation. + /// Always false, which skips the original method. + [HarmonyPrefix] + [HarmonyPatch(typeof(TerrainRenderer), nameof(TerrainRenderer.UpdateGraphics))] + private static bool TerrainRenderer_UpdateGraphics(TerrainRenderer __instance, Tile tile, TribeType climate, SkinType skin, bool shouldDesaturate) + { + + string spriteName = tile.Data.terrain switch + { + Polytopia.Data.TerrainData.Type.Water => __instance.waterSprites.GetSpriteName(tile), + Polytopia.Data.TerrainData.Type.Ocean => __instance.oceanSprites.GetSpriteName(tile), + Polytopia.Data.TerrainData.Type.Ice => __instance.iceSprites.GetSpriteName(tile), + _ => GetLandSpriteName(tile.Data), + }; + + SpriteAtlasManager.SpriteLookupResult spriteLookupResult = GameManager.GetSpriteAtlasManager().DoSpriteLookup(spriteName, climate, skin); + if (spriteLookupResult.HasSprite()) + { + __instance.spriteRenderer.Sprite = spriteLookupResult.sprite; + } + if (shouldDesaturate != __instance.isDesaturated) { - __instance.spriteRenderer.Sprite = sprite; + TerrainMaterialHelper.SetSpriteSaturated(__instance.SpriteRenderer, shouldDesaturate); + __instance.isDesaturated = shouldDesaturate; } + + return false; } - /// Adds custom flood tile effect when tile is flooded for custom aqua skins. + /// + /// A Harmony postfix on TileData.Flood. + /// If the skin of the player is in , it adds the custom flood effect of that skin to the tile. + /// + /// The tile that is flooded. + /// The player that floods the tile. [HarmonyPostfix] [HarmonyPatch(typeof(TileData), nameof(TileData.Flood))] private static void TileData_Flood(TileData __instance, PlayerState playerState) @@ -380,7 +568,16 @@ private static void TileData_Flood(TileData __instance, PlayerState playerState) } } - /// Removes custom flood effect loc from tile tip header. + /// + /// A Harmony postfix on TileTipGenerator.GetTileTipHeader. + /// It removes the localized name of each custom flood effect on the tile from the header text. + /// + /// The header text that the original method gives. + /// The data of the tile. + /// The skin that the localization uses. + /// The player whose tribe the localization uses. + /// The state of the game. The patch does not use it. + /// The game logic data. The patch does not use it. [HarmonyPostfix] [HarmonyPatch(typeof(TileTipGenerator), nameof(TileTipGenerator.GetTileTipHeader))] public static void GetTileTipHeader(ref string __result, TileData tileData, SkinType skin, @@ -396,573 +593,985 @@ public static void GetTileTipHeader(ref string __result, TileData tileData, Skin } } - /// Forces an update of the mesh for a PolytopiaSpriteRenderer with a custom sprite. + /// + /// A Harmony postfix on PolytopiaSpriteRenderer.ForceUpdateMesh. + /// For a renderer that has a sprite and no atlas name, it sets a material property block on the mesh renderer. + /// The block sets _MainTex to the sprite texture and sets _Flip to no flip. + /// + /// The sprite renderer. [HarmonyPostfix] [HarmonyPatch(typeof(PolytopiaSpriteRenderer), nameof(PolytopiaSpriteRenderer.ForceUpdateMesh))] private static void PolytopiaSpriteRenderer_ForceUpdateMesh(PolytopiaSpriteRenderer __instance) { - if (__instance.sprite != null && string.IsNullOrEmpty(__instance.atlasName)) - { - MaterialPropertyBlock materialPropertyBlock = new(); - materialPropertyBlock.SetVector("_Flip", new Vector4(1f, 1f, 0f, 0f)); - materialPropertyBlock.SetTexture("_MainTex", __instance.sprite.texture); - __instance.meshRenderer.SetPropertyBlock(materialPropertyBlock); - } + if (__instance.sprite == null || !string.IsNullOrEmpty(__instance.atlasName)) + return; + + MaterialPropertyBlock materialPropertyBlock = new(); + materialPropertyBlock.SetVector("_Flip", new Vector4(1f, 1f, 0f, 0f)); + materialPropertyBlock.SetTexture("_MainTex", __instance.sprite.texture); + __instance.meshRenderer.SetPropertyBlock(materialPropertyBlock); } + #endregion + #region Popups + + /// + /// A Harmony postfix on PopupBase.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines. + /// It applies the custom width of the popup, if the popup has one. + /// + /// The popup. [HarmonyPostfix] - [HarmonyPatch(typeof(Tile), nameof(Tile.Render), typeof(MapRenderContext), typeof(SkinVisualsTransientData))] - private static void Tile_Render(Tile __instance, MapRenderContext ctx, SkinVisualsTransientData transientSkinningData) + [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines))] + private static void PopupBase_RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(PopupBase __instance) { - Sprite? sprite = Registry.GetSprite("hidden"); - if (sprite != null) - { - __instance.fogOfWarRenderer.atlasName = ""; - __instance.fogOfWarRenderer.sprite = sprite; - __instance.fogOfWarRenderer.spriteRenderer.sprite = sprite; - } + UpdateWidth(__instance); } - #endregion - #region Tribe Preview + /// + /// Applies the custom width from to a popup. + /// If the popup is a BasicPopupLegacy with a button container, the method also arranges the buttons again. + /// If the popup has no custom width, the method does nothing. + /// + /// The popup to change. + private static void UpdateWidth(PopupBase popup) + { + if (!basicPopupWidths.TryGetValue(popup.GetInstanceID(), out PopupWidth? width)) return; + popup.rectTransform.SetWidth(GetResponsivePopupWidth(width.share, width.maximum)); + BasicPopupLegacy? legacy = popup.TryCast(); + if (legacy != null && legacy.buttonContainer != null) + LayoutPopupButtons(legacy.buttonContainer); + } + + /// + /// A Harmony postfix on SystemEvents.ScreenSizeChanged. + /// It refreshes the size of each shown popup that has a custom width. + /// [HarmonyPostfix] - [HarmonyPatch(typeof(TribePreviewRegistry), nameof(TribePreviewRegistry.PreloadTribePreviews))] - public static void PreloadTribePreviews() + [HarmonyPatch(typeof(SystemEvents), nameof(SystemEvents.ScreenSizeChanged))] + private static void SystemEvents_ScreenSizeChanged() { - Dictionary previewSaveStateDatas = new(); - - SaveStateData fallbackSaveStateData = TribePreviewRegistry.saveStateDatas[TribePreviewRegistry.fallbackStateIndex]; - foreach (string tribe in Registry.tribePreviews.Keys) - { - string previewId = GetTribePreviewName(tribe); - PreviewTile[] customPreview = Registry.tribePreviews[tribe]; - previewSaveStateDatas[previewId] = new(TribePreviewRegistry.fallbackStateIndex, fallbackSaveStateData, customPreview); - } + RelayoutSizedPopups(); + } - for (int i = 0; i < TribePreviewRegistry.saveStateDatas.Length; i++) - { - SaveStateData saveStateData = TribePreviewRegistry.saveStateDatas[i]; - if (previewSaveStateDatas.ContainsKey(saveStateData.name)) - { - previewSaveStateDatas[saveStateData.name] = new(i, saveStateData, previewSaveStateDatas[saveStateData.name].customPreview); - } - } + /// + /// A Harmony postfix on SystemEvents.SafeAreaChanged. + /// It refreshes the size of each shown popup that has a custom width. + /// + [HarmonyPostfix] + [HarmonyPatch(typeof(SystemEvents), nameof(SystemEvents.SafeAreaChanged))] + private static void SystemEvents_SafeAreaChanged() + { + RelayoutSizedPopups(); + } - foreach (string previewId in previewSaveStateDatas.Keys) + /// + /// Refreshes the size of each shown popup in . + /// The method calls RefreshHeightWhenHeightIsKnownAndDontUseCoroutines with the safe screen height. + /// It writes an error to the log for each popup that fails, and continues with the next popup. + /// + private static void RelayoutSizedPopups() + { + foreach (PopupWidth width in new List(basicPopupWidths.Values)) { - var data = previewSaveStateDatas[previewId]; - SaveStateData? customSaveStateData = ApplyCustomPreview(previewId, data.saveStateData, data.customPreview); - if (customSaveStateData == null) - continue; - - if (data.arrayIdx == TribePreviewRegistry.fallbackStateIndex) + try { - List saveStateDatas = TribePreviewRegistry.saveStateDatas.ToList(); - saveStateDatas.Add(customSaveStateData); - TribePreviewRegistry.saveStateDatas = saveStateDatas.ToArray(); + if (width.popup == null || !width.popup.IsShowing()) continue; + width.popup.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(ScreenManager.SafeHeight); } - else + catch (Exception exception) { - TribePreviewRegistry.saveStateDatas[data.arrayIdx] = customSaveStateData; + Plugin.logger.LogError($"Could not lay a popup out after a screen size change: {exception}"); } } } - private static string GetTribePreviewName(string tribeType) + /// + /// Changes a share of the usable screen width into a popup width in canvas units. + /// The method changes the safe screen width from screen pixels to canvas units with the UI scale of the game. + /// If is 0 or less, the method gives as a fixed width. + /// + /// The share of the usable width, from 0 to 1. + /// The maximum width in canvas units. It keeps text easy to read on wide screens. + /// + /// The width in canvas units, rounded to an integer. + /// For a share above 0, the width is not smaller than the width of the game's own popups. + /// + public static int GetResponsivePopupWidth(float share, float maximum) { - return "worldpreview_" + tribeType; + if (share <= 0f) return Mathf.RoundToInt(maximum); + float usable = ScreenManager.SafeWidth * UICanvasScalerHelper.GetInvertedUIScale(); + float width = Mathf.Min(usable * share, maximum); + return Mathf.RoundToInt(Mathf.Max(width, DEFAULT_POPUP_WIDTH)); } - private static SaveStateData? ApplyCustomPreview(string previewId, SaveStateData originalPreview, PreviewTile[] preview) + /// + /// A Harmony postfix on PopupButtonContainer.SetButtonData. + /// It replaces the button positions that the game sets with the positions from . + /// The game puts all buttons in one row, so buttons can show on top of each other in a narrow popup. + /// The patch applies to the buttons of all popups. + /// + /// The button container of the popup. + [HarmonyPostfix] + [HarmonyPatch(typeof(PopupButtonContainer), nameof(PopupButtonContainer.SetButtonData))] + private static void PopupButtonContainer_SetButtonData(PopupButtonContainer __instance) { - SaveStateData? saveStateData = null; - if (DiskSerializationHelpers.FromLZ4CompressedByteArray( - originalPreview.byteArray, out ClientSerializationWrapper clientSerializationWrapper, out int version)) - { - GameState currentGameState = clientSerializationWrapper.GetCurrentGameState(); - foreach (var previewTile in preview) - { - if (previewTile.x == null || previewTile.y == null) - continue; + LayoutPopupButtons(__instance); + } - WorldCoordinates coordinates = new((int)previewTile.x, (int)previewTile.y); - TileData? tileData = currentGameState.Map.GetTile(coordinates); - if (tileData == null) - continue; + /// + /// Arranges the buttons of a popup in rows that fit the width of the container. + /// All rows have the height of the highest button, with between them. + /// The method sets the height of the container to the height of all rows, and puts the first row at the top. + /// If the container has no buttons or no width, the method does nothing. + /// + /// The button container of the popup. + internal static void LayoutPopupButtons(PopupButtonContainer container) + { + if (container.buttons == null || container.buttons.Length == 0) return; - if (previewTile.terrainType != Polytopia.Data.TerrainData.Type.None) - tileData.terrain = previewTile.terrainType; + float available = container.rectTransform.rect.width; + if (available <= 0f) return; - if (previewTile.resourceType != null) - { - ResourceState? resourceState = null; - ResourceData.Type resourceType = (ResourceData.Type)previewTile.resourceType; - if (resourceType != ResourceData.Type.None) - { - resourceState = new ResourceState { type = resourceType }; - } - tileData.resource = resourceState; - } - - if (previewTile.unitType != null) - { - tileData.unit = null; - if (previewTile.unitType != Polytopia.Data.UnitData.Type.None && - currentGameState.TryGetPlayer(currentGameState.CurrentPlayer, out PlayerState playerState) && - currentGameState.GameLogicData.TryGetData((UnitData.Type)previewTile.unitType, out UnitData unitData)) - { - UnitState unitState = ActionUtils.TrainUnit(currentGameState, playerState, tileData, unitData); - unitState.moved = false; - unitState.attacked = false; - } - } + List> rows = PackButtonsIntoRows(container, available); + float rowHeight = 0f; + foreach (UITextButton button in container.buttons) + { + rowHeight = Mathf.Max(rowHeight, button.rectTransform.rect.height); + } + float stackHeight = rows.Count * rowHeight + (rows.Count - 1) * POPUP_BUTTON_ROW_GAP; - if (previewTile.improvementType != null) - { - tileData.improvement = null; - ImprovementData.Type improvementType = (ImprovementData.Type)previewTile.improvementType; - if ( - previewTile.improvementType != ImprovementData.Type.None && - currentGameState.GameLogicData.TryGetData( - improvementType, - out ImprovementData improvementData) - ) - { - tileData.improvement = new ImprovementState - { - type = improvementData.type, - borderSize = (ushort)improvementData.borderSize, - level = 0, - xp = 0, - production = 1, - founded = (ushort)currentGameState.CurrentTurn, - baseScore = (ushort)improvementData.GetScoreReward(), - founder = currentGameState.CurrentPlayer - }; - } - } - } + // The container sits at the bottom of the popup with a bottom pivot, so it grows upwards. + container.rectTransform.SetHeight(stackHeight); - saveStateData = ScriptableObject.CreateInstance(); - saveStateData.name = previewId; - saveStateData.byteArray = DiskSerializationHelpers.ToLZ4CompressedByteArray(clientSerializationWrapper, version); + for (int row = 0; row < rows.Count; row++) + { + float offsetY = stackHeight / 2f - rowHeight / 2f - row * (rowHeight + POPUP_BUTTON_ROW_GAP); + PlaceButtonRow(rows[row], offsetY); } - - return saveStateData; } - [HarmonyPrefix] - [HarmonyPatch(typeof(SpriteCamera), nameof(SpriteCamera.TakeSnapshotOfMapState))] - private static bool SpriteCamera_TakeSnapshotOfMapState(ref Texture2D __result, SpriteCamera.SnapshotMapData mapSnapshot, - float w, float h, TribeType tribe, SkinType skin, TribeType climate, int color, bool clearMapAfterwards) + /// + /// Puts the buttons of a container into rows, in their original sequence. + /// The method adds each button to the current row. + /// If the button and the gap do not fit in the remaining width, the method starts a new row. + /// A row always contains at least one button, also if that button is wider than the container. + /// + /// The button container of the popup. + /// The width of the container, in canvas units. + /// The rows of buttons, from the first row to the last row. + private static List> PackButtonsIntoRows(PopupButtonContainer container, float available) { - if (!Plugin.config.debug) - return true; - - var instance = SpriteCamera.instance; - if (baseOrthographicCameraSize == null) - baseOrthographicCameraSize = instance.spriteCamera.orthographicSize; - - instance.spriteCamera.orthographicSize = (float)baseOrthographicCameraSize * 2; - isTakingSnapshot = true; + List> rows = new() { new() }; + float rowWidth = 0f; + foreach (UITextButton button in container.buttons) + { + float width = button.rectTransform.rect.width; + if (rows[^1].Count > 0 && rowWidth + POPUP_BUTTON_GAP + width > available) + { + rows.Add(new()); + rowWidth = 0f; + } + rowWidth += (rows[^1].Count > 0 ? POPUP_BUTTON_GAP : 0f) + width; + rows[^1].Add(button); + } + return rows; + } - return true; + /// + /// Puts one row of buttons across the width of the container. + /// The method anchors each button to a fraction of the container width, from the left edge to the right edge. + /// A row with one button goes to the center. + /// + /// The buttons in the row. + /// The vertical position of the row from the center of the container, in canvas units. + private static void PlaceButtonRow(List row, float offsetY) + { + for (int i = 0; i < row.Count; i++) + { + // Anchoring to a fraction of the container keeps the row spread as the popup resizes, + // which is how the game places the buttons of its own popups. + Vector2 anchor = new((row.Count == 1) ? 0.5f : (i / (row.Count - 1.0f)), 0.5f); + RectTransform rect = row[i].rectTransform; + rect.anchorMin = anchor; + rect.anchorMax = anchor; + rect.pivot = anchor; + rect.anchoredPosition = new Vector2(0f, offsetY); + } } + /// + /// A Harmony postfix on PopupBase.Hide. + /// It removes the entry of the popup from . + /// + /// The popup that closes. [HarmonyPostfix] - [HarmonyPatch(typeof(SpriteCamera), nameof(SpriteCamera.TakeSnapshotOfMapState))] - private static void SpriteCamera_TakeSnapshotOfMapState_Postfix(ref Texture2D __result, SpriteCamera.SnapshotMapData mapSnapshot, - float w, float h, TribeType tribe, SkinType skin, TribeType climate, int color, bool clearMapAfterwards) + [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.Hide))] + private static void PopupBase_Hide(PopupBase __instance) { - if (isTakingSnapshot) - isTakingSnapshot = false; + basicPopupWidths.Remove(__instance.GetInstanceID()); } + /// + /// A Harmony postfix on StartScreen_UI2.OnShow. + /// It calls to make the sprites that use game sprites as a source. + /// [HarmonyPostfix] - [HarmonyPatch(typeof(Tile), nameof(Tile.RenderDebug))] - public static void Tile_RenderDebug(Tile __instance) + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnShow))] + private static void StartScreen_UI2_OnShow() { - if (!isTakingSnapshot) - return; + CreateInnerOriginSprites(); + } - GameObject textObj = new GameObject("CoordinateText"); - textObj.transform.SetParent(__instance.transform); - textObj.transform.localPosition = new Vector3(0, 0.0f, 0); + /// + /// A Harmony prefix on StartScreen_UI2.OnWeeklyChallengeClicked. + /// It shows a popup that tells the player that the weekly challenge is only for the game without mods. + /// The popup has one OK button. + /// + /// Always false, which skips the original method. + [HarmonyPrefix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnWeeklyChallengeClicked))] + private static bool StartScreen_OnWeeklyChallengeClicked() + { + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub"); + popup.Description = Localization.Get( + "polymod.wc.vanillaonly", + new Il2CppSystem.Object[] { Localization.Get("weeklychallenge", Array.Empty()) } + ); + popup.buttonData = new PopupBase.PopupButtonData[] { new("buttons.ok") }; + popup.Show(); + return false; + } - TextMeshPro textMesh = textObj.AddComponent(); - textMesh.text = __instance.Data.coordinates.ToString(); - textMesh.fontSize = 3; - textMesh.alignment = TextAlignmentOptions.Center; - textMesh.color = Color.white; + /// + /// A Harmony postfix on StartScreen_UI2.RefreshWeeklyChallengeButton. + /// It sets all colors of the weekly challenge button to gray, to show that the button is not available. + /// If the start screen has no weekly challenge button, the patch does nothing. + /// + /// The start screen. + [HarmonyPostfix] + [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.RefreshWeeklyChallengeButton))] + private static void StartScreen_RefreshWeeklyChallengeButton(StartScreen_UI2 __instance) + { + WeeklyChallengesButton weeklyChallengeButton = __instance.weeklyChallengeButton; + if (weeklyChallengeButton == null) + return; - MeshRenderer renderer = textObj.GetComponent(); - renderer.sortingLayerID = MeshCache.TERRAIN_LAYER_ID; - renderer.sortingOrder = __instance.Depth + 10; + weeklyChallengeButton.SetColors( + WEEKLY_CHALLENGE_DISABLED_COLOR, + WEEKLY_CHALLENGE_DISABLED_COLOR, + WEEKLY_CHALLENGE_DISABLED_COLOR + ); } - #endregion - #region UI - - /// Provides custom sprites for improvements in the UI. [HarmonyPostfix] - [HarmonyPatch(typeof(UIUtils), nameof(UIUtils.GetImprovementSprite), typeof(ImprovementData.Type), typeof(TribeType), typeof(SkinType), typeof(SpriteAtlasManager))] - private static void UIUtils_GetImprovementSprite(ref Sprite __result, ImprovementData.Type improvement, TribeType tribe, SkinType skin, SpriteAtlasManager atlasManager) + [HarmonyPatch(typeof(ThroneRoomScreen_UI2), nameof(ThroneRoomScreen_UI2.RunLayout))] + private static void ThroneRoomScreen_UI2_RunLayout(ThroneRoomScreen_UI2 __instance) { - Sprite? sprite = Registry.GetSprite(EnumCache.GetName(improvement), Util.GetStyle(tribe, skin)); - if (sprite != null) + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + foreach (Achievement achievement in GameManager.GetAchievementManager().GetAchievements()) { - __result = sprite; + if (!__instance.achievementButtons.TryGetValue(achievement.type, out UIRoundButton_UI2 button)) + continue; + + button.SetSprite(spriteAtlasManager.GetSprite(achievement.GetSpriteName() + "_bw", "UI")); + button.SetStyle(UIButtonBase_UI2.ButtonStyle.Disabled); } } - /// Provides custom sprites for improvements in the UI. - [HarmonyPostfix] - [HarmonyPatch(typeof(UIUtils), nameof(UIUtils.GetImprovementSprite), typeof(SkinVisualsTransientData), typeof(ImprovementData.Type), typeof(SpriteAtlasManager))] - private static void UIUtils_GetImprovementSprite_2(ref Sprite __result, SkinVisualsTransientData data, ImprovementData.Type improvement, SpriteAtlasManager atlasManager) + [HarmonyPrefix] + [HarmonyPatch(typeof(ThroneRoomScreen_UI2), nameof(ThroneRoomScreen_UI2.OnAchievementButtonCliced))] + private static bool ThroneRoomScreen_UI2_OnAchievementButtonCliced() { - UIUtils_GetImprovementSprite(ref __result, improvement, data.foundingTribeSettings.tribe, data.foundingTribeSettings.skin, atlasManager); + BasicPopup popup = PopupManager.GetBasicPopup(); + popup.Header = Localization.Get("polymod.hub"); + popup.Description = Localization.Get( + "polymod.achi.vanillaonly", + new Il2CppSystem.Object[] { Localization.Get("throne.achievements", Array.Empty()) } + ); + popup.buttonData = new PopupBase.PopupButtonData[] { new("buttons.ok") }; + popup.Show(); + return false; } - /// Provides custom sprites for resources in the UI. + private const string MIGHTYLEADER = "mightyleader"; + + /// + /// A Harmony postfix on PopupContentBuilder.GetMightyLeaderTopImage. + /// It replaces the image with the registered mightyleader sprite for the tribe and visual skin of the player, if one exists. + /// + /// The image that the original method gives. + /// The player that the popup is for. [HarmonyPostfix] - [HarmonyPatch(typeof(UIUtils), nameof(UIUtils.GetResourceSprite))] - private static void UIUtils_GetResourceSprite(ref Sprite __result, SkinVisualsTransientData data, ResourceData.Type resource, SpriteAtlasManager atlasManager) + [HarmonyPatch(typeof(PopupContentBuilder), nameof(PopupContentBuilder.GetMightyLeaderTopImage))] + public static void PopupContentBuilder_GetMightyLeaderTopImage(ref Sprite __result, PlayerState player) { - Sprite? sprite = Registry.GetSprite(EnumCache.GetName(resource), Util.GetStyle(data.tileClimateSettings.tribe, data.tileClimateSettings.skin)); + Sprite? sprite = Registry.GetSprite(MIGHTYLEADER, player.tribe, player.GetVisualSkin()); if (sprite != null) - { __result = sprite; - } + } + + /// + /// Shows a popup with a fixed custom width. + /// The method adds the width to and then shows the popup. + /// + /// The popup to show. + /// The width of the popup, in canvas units. + public static void ShowSetWidth(this BasicPopupLegacy self, int width) + { + basicPopupWidths[self.GetInstanceID()] = new(self, 0f, width); + self.Show(); + } + + /// + /// Shows a popup with a width that is a share of the usable screen width. + /// The method adds the width settings to and then shows the popup. + /// calculates the width. + /// + /// The popup to show. + /// The share of the usable screen width, from 0 to 1. + /// The maximum width of the popup, in canvas units. + public static void ShowSetWidth(this BasicPopupLegacy self, float share, float maximum) + { + basicPopupWidths[self.GetInstanceID()] = new(self, share, maximum); + self.Show(); } #endregion - #region Houses - /// Provides custom sprites for houses in the city view. - [HarmonyPostfix] - [HarmonyPatch(typeof(CityRenderer), nameof(CityRenderer.GetHouse))] - private static void CityRenderer_GetHouse(ref PolytopiaSpriteRenderer __result, CityRenderer __instance, TribeType tribe, int type, SkinType skinType) + /// + /// Makes a new BasicPopupLegacy from the popup prefab of the game. + /// The method copies the button container of the "What's new" popup into the new popup. + /// It sets the popup ID to basicPopupLegacy and calls Init on the popup. + /// It also puts the popup in front of the other popups. + /// + /// The new popup. It is not shown. + internal static BasicPopupLegacy GetBasicPopupLegacy() { - PolytopiaSpriteRenderer polytopiaSpriteRenderer = __result; + WhatsNewPopup whatsNewPopup = PopupManager.GetWhatsNewPopup(); + BasicPopupLegacy original = PopupManager.instance.popupPrefabs[BASIC_POPUP_LEGACY_ID].Cast(); + BasicPopupLegacy basicPopupLegacy = UnityEngine.Object.Instantiate(original, PopupManager.instance.transform); + basicPopupLegacy.buttonContainer = GameObject.Instantiate(whatsNewPopup.buttonContainer, basicPopupLegacy.transform); + basicPopupLegacy.popupId = "basicPopupLegacy"; + basicPopupLegacy.popupManager = PopupManager.instance; + basicPopupLegacy.Init(); + basicPopupLegacy.identifier = null; + basicPopupLegacy.rectTransform.SetAsLastSibling(); + return basicPopupLegacy; + } - if (type != __instance.HOUSE_WORKSHOP && type != __instance.HOUSE_PARK) + /// + /// Makes a texture from the bytes of an image file, such as a PNG file. + /// If the image looks premultiplied, the method changes it back to straight alpha. + /// The method also copies color into the transparent pixels near the edges of the image. + /// The texture uses trilinear filter mode, clamp wrap mode, and mipmaps. + /// + /// The bytes of the image file. + /// The new texture. + public static Texture2D BuildTexture(byte[] data) + { + Texture2D texture = new(1, 1, TextureFormat.RGBA32, true); + texture.LoadImage(data); + Color32[] pixels = texture.GetPixels32(); + if (LooksPremultiplied(pixels)) + Unpremultiply(pixels); + BleedAlphaEdges(pixels, texture.width, texture.height); + texture.SetPixels32(pixels); + texture.filterMode = FilterMode.Trilinear; + texture.wrapMode = TextureWrapMode.Clamp; + texture.Apply(); + return texture; + } + + /// + /// Finds if the pixels of an image look premultiplied by alpha. + /// The method examines only the pixels that are partly transparent. + /// In a premultiplied image, no color channel of such a pixel is more than its alpha. + /// + /// The pixels of the image. + /// + /// True if the image has at least 64 partly transparent pixels, and not more than 0.5% of them have a color channel above alpha. + /// False if not. + /// + internal static bool LooksPremultiplied(Color32[] pixels) + { + int edge = 0; + int brighterThanAlpha = 0; + foreach (Color32 pixel in pixels) { - Sprite? sprite = Registry.GetSprite("house", Util.GetStyle(tribe, skinType), type); - if (sprite != null) - { - polytopiaSpriteRenderer.Sprite = sprite; - TerrainMaterialHelper.SetSpriteSaturated(polytopiaSpriteRenderer, __instance.IsEnemyCity); - __result = polytopiaSpriteRenderer; - } + if (pixel.a == 0 || pixel.a == 255) continue; + edge++; + if (Math.Max(pixel.r, Math.Max(pixel.g, pixel.b)) > pixel.a) + brighterThanAlpha++; } + return edge >= PREMULTIPLIED_MIN_EDGE_PIXELS + && brighterThanAlpha <= edge * PREMULTIPLIED_MAX_OUTLIER_SHARE; } - /// Provides custom sprites for houses in the UI city renderer. - [HarmonyPostfix] - [HarmonyPatch(typeof(UICityRenderer), nameof(UICityRenderer.GetResource))] - private static void UICityRenderer_GetResource(ref GameObject __result, string baseName, TribeType tribe, SkinType skin) + /// + /// Changes premultiplied pixels to straight alpha in the same array. + /// The method divides the color channels of each partly transparent pixel by its alpha, with a maximum of 255. + /// It does not change fully transparent pixels and fully opaque pixels. + /// + /// The pixels to change. + internal static void Unpremultiply(Color32[] pixels) + { + for (int i = 0; i < pixels.Length; i++) + { + byte alpha = pixels[i].a; + if (alpha == 0 || alpha == byte.MaxValue) continue; + pixels[i] = new Color32( + (byte)Math.Min(byte.MaxValue, pixels[i].r * byte.MaxValue / alpha), + (byte)Math.Min(byte.MaxValue, pixels[i].g * byte.MaxValue / alpha), + (byte)Math.Min(byte.MaxValue, pixels[i].b * byte.MaxValue / alpha), + alpha + ); + } + } + + /// + /// Copies the color of visible pixels into the adjacent transparent pixels, in the same array. + /// This stops dark edges around a sprite when the GPU filters the texture. + /// A pixel with an alpha of 2 or less has no color for this method. + /// The method spreads the color one pixel at a time, for a maximum of 16 pixels from the visible area. + /// It keeps the alpha of each pixel. + /// If all pixels or no pixels are visible, the method does nothing. + /// + /// The pixels of the image, row by row. + /// The width of the image, in pixels. + /// The height of the image, in pixels. + internal static void BleedAlphaEdges(Color32[] pixels, int width, int height) { - Image imageComponent = __result.GetComponent(); - string[] tokens = baseName.Split('_'); - if (tokens.Length > 0) + bool[] hasColour = new bool[pixels.Length]; + List frontier = new(); + for (int i = 0; i < pixels.Length; i++) + { + if (pixels[i].a <= INVISIBLE_ALPHA) continue; + hasColour[i] = true; + frontier.Add(i); + } + if (frontier.Count == 0 || frontier.Count == pixels.Length) return; + + for (int ring = 0; ring < ALPHA_BLEED_RINGS && frontier.Count > 0; ring++) { - if (tokens[0] == "House") + List nextFrontier = new(); + foreach (int index in frontier) { - int level = 0; - if (tokens.Length > 1) - { - _ = int.TryParse(tokens[1], out level); - } + int x = index % width; + int y = index / width; + Color32 source = pixels[index]; - Sprite? sprite = Registry.GetSprite("house", Util.GetStyle(tribe, skin), level); - if (sprite == null) + for (int offsetY = -1; offsetY <= 1; offsetY++) { - return; + int neighbourY = y + offsetY; + if (neighbourY < 0 || neighbourY >= height) continue; + + for (int offsetX = -1; offsetX <= 1; offsetX++) + { + int neighbourX = x + offsetX; + if (neighbourX < 0 || neighbourX >= width) continue; + + int neighbour = neighbourY * width + neighbourX; + if (hasColour[neighbour]) continue; + + hasColour[neighbour] = true; + pixels[neighbour] = new Color32( + source.r, source.g, source.b, pixels[neighbour].a + ); + nextFrontier.Add(neighbour); + } } - imageComponent.sprite = sprite; - imageComponent.SetNativeSize(); } + frontier = nextFrontier; } } - #endregion - #region Icons + /// + /// Makes a sprite from the bytes of an image file. + /// The method makes the texture with and the sprite with . + /// + /// The bytes of the image file. + /// The pivot of the sprite, as a fraction of the sprite size. If null, the pivot is the center. + /// The number of texture pixels in one world unit. + /// If true, the image changes into a white silhouette with a border. + /// The radius of the Gaussian blur, or null for no blur. + /// The new sprite. + public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) + { + return BuildSpriteWithTexture(BuildTexture(data), pivot, pixelsPerUnit, transformToOutline, gaussianBlurRadius); + } - /// Provides custom sprites for UI icons. - [HarmonyPostfix] - [HarmonyPatch(typeof(UIIconData), nameof(UIIconData.GetImage))] - private static void UIIconData_GetImage(ref Image __result, string id) + /// + /// Makes a sprite that uses all of a texture. + /// If is true, the method first changes the texture with . + /// Then, if the blur radius is not null, it applies . + /// + /// The texture for the sprite. + /// The pivot of the sprite, as a fraction of the sprite size. If null, the pivot is the center. + /// The number of texture pixels in one world unit. If null, the method uses 2112. + /// If true, the image changes into a white silhouette with a border. + /// The radius of the Gaussian blur, or null for no blur. + /// The new sprite. + public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = null, float? pixelsPerUnit = 2112f, bool transformToOutline = false, float? gaussianBlurRadius = null) { - Sprite? sprite; - if (GameManager.LocalPlayer != null) - { - sprite = Registry.GetSprite(id, Util.GetStyle(GameManager.LocalPlayer.tribe, GameManager.LocalPlayer.skinType)); - } - else - { - sprite = Registry.GetSprite(id); - } - if (sprite != null) - { - __result.sprite = sprite; - __result.useSpriteMesh = true; - __result.SetNativeSize(); - } + if (transformToOutline) texture = TransformToOutline(texture); + + if (gaussianBlurRadius != null) texture = ApplyGaussianBlur(texture, gaussianBlurRadius.Value); + + return Sprite.Create( + texture, + new(0, 0, texture.width, texture.height), + pivot ?? new(0.5f, 0.5f), + pixelsPerUnit ?? 2112f + ); ; } - /// Provides custom sprites for face icons in the game info row. - [HarmonyPostfix] - [HarmonyPatch(typeof(GameInfoRow), nameof(GameInfoRow.LoadFaceIcon), typeof(TribeType), typeof(SkinType))] - private static void GameInfoRow_LoadFaceIcon(GameInfoRow __instance, TribeType type, SkinType skinType) + /// + /// Makes a silhouette texture with a border from the visible pixels of a texture. + /// The new texture is larger than the source texture by the border size on each side. + /// Each pixel within the border size of a visible source pixel gets the given color. + /// All other pixels are transparent. + /// A source pixel is visible if its alpha is more than 0.01. + /// + /// The texture that gives the shape. + /// The width of the border around the shape, in pixels. + /// The color of the silhouette. If null, the method uses white. + /// A new RGBA32 texture without mipmaps. + public static Texture2D TransformToOutline(Texture2D sourceTexture, int borderSizeInPixels = 8, Color? color = null) { - string style = EnumCache.GetName(type); + Plugin.logger.LogInfo("Transforming texture to outline..."); + if (color == null) + color = Color.white; - if (style == "None") + int sourceWidthInPixels = sourceTexture.width; + int sourceHeightInPixels = sourceTexture.height; + int outputWidthInPixels = sourceWidthInPixels + borderSizeInPixels * 2; + int outputHeightInPixels = sourceHeightInPixels + borderSizeInPixels * 2; + + Color[] sourcePixels = sourceTexture.GetPixels(); + bool[] filledMask = new bool[outputWidthInPixels * outputHeightInPixels]; + int borderSquared = borderSizeInPixels * borderSizeInPixels; + + for (int pixelY = 0; pixelY < sourceHeightInPixels; pixelY++) { - for (int i = 0; i < 20; i++) + for (int pixelX = 0; pixelX < sourceWidthInPixels; pixelX++) { - type += byte.MaxValue + 1; - style = EnumCache.GetName(type); + if (sourcePixels[pixelY * sourceWidthInPixels + pixelX].a <= 0.01f) continue; + + int centerX = pixelX + borderSizeInPixels; + int centerY = pixelY + borderSizeInPixels; - if (style != "None") + for (int offsetY = -borderSizeInPixels; offsetY <= borderSizeInPixels; offsetY++) { - break; + for (int offsetX = -borderSizeInPixels; offsetX <= borderSizeInPixels; offsetX++) + { + if (offsetX * offsetX + offsetY * offsetY > borderSquared) continue; + + filledMask[(centerY + offsetY) * outputWidthInPixels + (centerX + offsetX)] = true; + } } } } - Sprite? sprite = Registry.GetSprite("head", Util.GetStyle(type, skinType)); - - if (sprite != null) + Color[] outputPixels = new Color[filledMask.Length]; + for (int pixelIndex = 0; pixelIndex < outputPixels.Length; pixelIndex++) { - __instance.SetFaceIcon(sprite); + outputPixels[pixelIndex] = filledMask[pixelIndex] ? color.Value : Color.clear; } - if (__instance.icon.sprite == null) - { - __instance.LoadFaceIcon(SpriteData.SpecialFaceIcon.neutral); - } + Texture2D whiteSilhouetteTexture = new Texture2D(outputWidthInPixels, outputHeightInPixels, TextureFormat.RGBA32, false); + whiteSilhouetteTexture.SetPixels(outputPixels); + whiteSilhouetteTexture.Apply(); + return whiteSilhouetteTexture; } - /// Provides custom sprites for player info icons. - [HarmonyPostfix] - [HarmonyPatch(typeof(PlayerInfoIcon), nameof(PlayerInfoIcon.SetData), typeof(TribeType), typeof(SkinType), typeof(SpriteData.SpecialFaceIcon), typeof(Color), typeof(DiplomacyRelationState), typeof(PlayerInfoIcon.Mood))] - private static void PlayerInfoIcon_SetData(PlayerInfoIcon __instance, TribeType tribe, SkinType skin, SpriteData.SpecialFaceIcon face, Color color, DiplomacyRelationState diplomacyState, PlayerInfoIcon.Mood mood) + /// + /// Makes the weights of a one-dimensional Gaussian kernel. The sum of the weights is 1. + /// + /// The standard deviation of the Gaussian function, in pixels. + /// The number of weights on each side of the center weight. + /// An array of 2 * kernelRadiusInPixels + 1 weights. + private static float[] BuildGaussianKernelWeights(float sigma, int kernelRadiusInPixels) { - if (face == SpriteData.SpecialFaceIcon.tribe) + float[] kernelWeights = new float[kernelRadiusInPixels * 2 + 1]; + float kernelWeightSum = 0f; + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) { - Sprite? sprite = Registry.GetSprite("head", Util.GetStyle(tribe, skin)); - if (sprite != null) - { - __instance.HeadImage.sprite = sprite; - Vector2 size = sprite.rect.size; - __instance.HeadImage.rectTransform.sizeDelta = size * __instance.rectTransform.GetHeight() / 512f; - } + int distanceFromCenter = kernelIndex - kernelRadiusInPixels; + kernelWeights[kernelIndex] = MathF.Exp(-(distanceFromCenter * distanceFromCenter) / (2f * sigma * sigma)); + kernelWeightSum += kernelWeights[kernelIndex]; } + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + kernelWeights[kernelIndex] /= kernelWeightSum; + } + return kernelWeights; } - #endregion - #region Popups - - /// Updates the width of a basic popup if a custom width is set. - [HarmonyPostfix] - [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.RefreshHeightWhenHeightIsKnownAndDontUseCoroutines))] - private static void PopupBase_RefreshHeightWhenHeightIsKnownAndDontUseCoroutines(PopupBase __instance) + /// + /// Changes a value from the range 0 to 1 into a byte from 0 to 255, rounded to the nearest integer. + /// The method clamps values that are out of the range. + /// + /// The value to change. + /// The byte value. + private static byte ConvertUnitFloatToByte(float unitValue) { - UpdateWidth(__instance); + return (byte)Math.Clamp(unitValue * 255f + 0.5f, 0f, 255f); } - private static void UpdateWidth(PopupBase __instance) + // basically ai generated as my bs was working, but 15 times slower + /// + /// Makes a blurred copy of a texture with a Gaussian blur. + /// The method blurs the rows and then the columns, on more than one thread. + /// It blurs premultiplied colors, so transparent pixels do not make the edges dark. + /// At the edges of the texture, the method uses the nearest edge pixel. + /// The standard deviation is half of the radius, and the kernel reaches three standard deviations. + /// + /// The texture to blur. The method does not change it. + /// The radius of the blur, in pixels. + /// A new RGBA32 texture without mipmaps. + public static Texture2D ApplyGaussianBlur(Texture2D sourceTexture, float radius = 2f) { - int id = __instance.GetInstanceID(); - if (basicPopupWidths.ContainsKey(id)) - __instance.rectTransform.SetWidth(basicPopupWidths[id]); - } + Plugin.logger.LogInfo($"Applying blur with radius {radius}..."); + int textureWidthInPixels = sourceTexture.width; + int textureHeightInPixels = sourceTexture.height; - /// Sets the attacker's tribe before a unit attacks. - [HarmonyPrefix] - [HarmonyPatch(typeof(Unit), nameof(Unit.Attack))] - private static bool Unit_Attack(Unit __instance, WorldCoordinates target, bool moveToTarget, Il2CppSystem.Action onComplete) - { - if (__instance.Owner != null) + float sigma = Math.Max(radius / 2f, 0.01f); + int kernelRadiusInPixels = Math.Max(1, (int)MathF.Ceiling(sigma * 3f)); + float[] kernelWeights = BuildGaussianKernelWeights(sigma, kernelRadiusInPixels); + + Color32[] sourcePixels = sourceTexture.GetPixels32(); + int totalPixelCount = sourcePixels.Length; + const float byteToUnitFloat = 1f / 255f; + + float[] premultipliedChannels = new float[totalPixelCount * 4]; + for (int pixelIndex = 0; pixelIndex < totalPixelCount; pixelIndex++) { - attackerTribe = __instance.Owner.tribe; + Color32 sourcePixel = sourcePixels[pixelIndex]; + float alpha = sourcePixel.a * byteToUnitFloat; + int channelOffset = pixelIndex * 4; + premultipliedChannels[channelOffset + 0] = sourcePixel.r * byteToUnitFloat * alpha; + premultipliedChannels[channelOffset + 1] = sourcePixel.g * byteToUnitFloat * alpha; + premultipliedChannels[channelOffset + 2] = sourcePixel.b * byteToUnitFloat * alpha; + premultipliedChannels[channelOffset + 3] = alpha; } - return true; - } - /// Sets the skin of a weapon's graphics, using custom sprites if available. - [HarmonyPostfix] - [HarmonyPatch(typeof(WeaponGFX), nameof(WeaponGFX.SetSkin))] - private static void WeaponGFX_SetSkin(WeaponGFX __instance, SkinType skinType) - { - if (attackerTribe != TribeType.None) + float[] horizontallyBlurredChannels = new float[premultipliedChannels.Length]; + Parallel.For(0, textureHeightInPixels, pixelY => { - Sprite? sprite = Registry.GetSprite(__instance.defaultSprite.name, Util.GetStyle(attackerTribe, skinType)); - if (sprite != null) + int rowStartPixelIndex = pixelY * textureWidthInPixels; + for (int pixelX = 0; pixelX < textureWidthInPixels; pixelX++) { - __instance.spriteRenderer.sprite = sprite; + float accumulatedRed = 0f, accumulatedGreen = 0f, accumulatedBlue = 0f, accumulatedAlpha = 0f; + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + int sampleX = pixelX + kernelIndex - kernelRadiusInPixels; + if (sampleX < 0) sampleX = 0; + else if (sampleX >= textureWidthInPixels) sampleX = textureWidthInPixels - 1; + + int sampleOffset = (rowStartPixelIndex + sampleX) * 4; + float kernelWeight = kernelWeights[kernelIndex]; + accumulatedRed += premultipliedChannels[sampleOffset + 0] * kernelWeight; + accumulatedGreen += premultipliedChannels[sampleOffset + 1] * kernelWeight; + accumulatedBlue += premultipliedChannels[sampleOffset + 2] * kernelWeight; + accumulatedAlpha += premultipliedChannels[sampleOffset + 3] * kernelWeight; + } + int outputOffset = (rowStartPixelIndex + pixelX) * 4; + horizontallyBlurredChannels[outputOffset + 0] = accumulatedRed; + horizontallyBlurredChannels[outputOffset + 1] = accumulatedGreen; + horizontallyBlurredChannels[outputOffset + 2] = accumulatedBlue; + horizontallyBlurredChannels[outputOffset + 3] = accumulatedAlpha; } - attackerTribe = TribeType.None; - } + }); + + Color32[] blurredPixels = new Color32[totalPixelCount]; + Parallel.For(0, textureHeightInPixels, pixelY => + { + for (int pixelX = 0; pixelX < textureWidthInPixels; pixelX++) + { + float accumulatedRed = 0f, accumulatedGreen = 0f, accumulatedBlue = 0f, accumulatedAlpha = 0f; + for (int kernelIndex = 0; kernelIndex < kernelWeights.Length; kernelIndex++) + { + int sampleY = pixelY + kernelIndex - kernelRadiusInPixels; + if (sampleY < 0) sampleY = 0; + else if (sampleY >= textureHeightInPixels) sampleY = textureHeightInPixels - 1; + + int sampleOffset = (sampleY * textureWidthInPixels + pixelX) * 4; + float kernelWeight = kernelWeights[kernelIndex]; + accumulatedRed += horizontallyBlurredChannels[sampleOffset + 0] * kernelWeight; + accumulatedGreen += horizontallyBlurredChannels[sampleOffset + 1] * kernelWeight; + accumulatedBlue += horizontallyBlurredChannels[sampleOffset + 2] * kernelWeight; + accumulatedAlpha += horizontallyBlurredChannels[sampleOffset + 3] * kernelWeight; + } + + Color32 blurredPixel = default; + if (accumulatedAlpha > 0.0001f) + { + blurredPixel.r = ConvertUnitFloatToByte(accumulatedRed / accumulatedAlpha); + blurredPixel.g = ConvertUnitFloatToByte(accumulatedGreen / accumulatedAlpha); + blurredPixel.b = ConvertUnitFloatToByte(accumulatedBlue / accumulatedAlpha); + blurredPixel.a = ConvertUnitFloatToByte(accumulatedAlpha); + } + blurredPixels[pixelY * textureWidthInPixels + pixelX] = blurredPixel; + } + }); + + Texture2D blurredTexture = new Texture2D(textureWidthInPixels, textureHeightInPixels, TextureFormat.RGBA32, false); + blurredTexture.SetPixels32(blurredPixels); + blurredTexture.Apply(); + return blurredTexture; } - /// Removes a popup's custom width when it is hidden. - [HarmonyPostfix] - [HarmonyPatch(typeof(PopupBase), nameof(PopupBase.Hide))] - private static void PopupBase_Hide(PopupBase __instance) + /// + /// The sprite names and sprite infos of the sprites that have an origin. + /// fills this list, and makes the sprites and clears it. + /// + internal static List> pendingInnerOriginSpriteInfos = new(); + + /// + /// Gets the default pivot for a sprite from the part of its name before the first underscore. + /// + /// The name of the sprite. + /// + /// The pivot (0.5, 0) for field, the pivot (0.5, -0.375) for mountain, and the center for all other names. + /// + private static Vector2 GetPivotPreset(string spriteName) { - basicPopupWidths.Remove(__instance.GetInstanceID()); + return spriteName.Split("_")[0] switch + { + "field" => new Vector2(0.5f, 0.0f), + "mountain" => new Vector2(0.5f, -0.375f), + _ => new Vector2(0.5f, 0.5f), + }; } - [HarmonyPrefix] - [HarmonyPatch(typeof(StartScreen_UI2), nameof(StartScreen_UI2.OnWeeklyChallengeClicked))] - private static bool StartScreen_OnWeeklyChallengeClicked(StartScreen_UI2 __instance) + /// + /// Adds a sprite to the Heads cache of the sprite atlas manager and to . + /// If a sprite with the same name exists, the method replaces it. + /// The method writes the sprite name to the log. + /// + /// The sprite atlas manager of the game. + /// The name of the sprite. + /// The sprite to add. + internal static void RegisterSprite(SpriteAtlasManager spriteAtlasManager, string spriteName, Sprite sprite) { - if (seenWarningWCPopup) - return true; + Plugin.logger.LogInfo($"Registering sprite {spriteName}"); + spriteAtlasManager.cachedSprites.TryAdd("Heads", new()); + spriteAtlasManager.cachedSprites["Heads"][spriteName] = sprite; + Registry.sprites[spriteName] = sprite; + } - BasicPopup popup = PopupManager.GetBasicPopup(); - popup.Header = Localization.Get("polymod.hub"); - popup.Description = Localization.Get("polymod.wc.warning", new Il2CppSystem.Object[] { Localization.Get("weeklychallenge", new Il2CppSystem.Object[] { }) }); + /// + /// Makes and registers the sprites from mod textures. + /// First, the method makes a sprite for each entry in . + /// If the entry has an origin name, the method uses the texture with that name. Otherwise, it uses the texture with the sprite name. + /// It skips an entry without a texture, and keeps entries for . + /// Then it makes a sprite with the default settings for each texture that does not have a registered sprite with the same name. + /// A texture that only an origin name uses therefore also gets a sprite with its own name. + /// + public static void CreateSprites() + { + Plugin.logger.LogInfo("Creating sprites with outer origin..."); + pendingInnerOriginSpriteInfos.Clear(); - void WCProceed() + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + const float defaultPixelsPerUnit = 2112f; + + foreach (var (spriteName, spriteInfo) in Registry.spriteInfos) { - seenWarningWCPopup = true; - __instance.OnWeeklyChallengeClicked(); + if (spriteInfo.spriteOrigin?.originType == OriginType.Inner) + { + pendingInnerOriginSpriteInfos.Add(new(spriteName, spriteInfo)); + continue; + } + + string textureName = spriteInfo.spriteOrigin?.name ?? spriteName; + if (!Registry.textures.TryGetValue(textureName, out Texture2D? texture)) + continue; + + Vector2 pivot = spriteInfo.pivot ?? GetPivotPreset(spriteName); + float pixelsPerUnit = spriteInfo.pixelsPerUnit ?? defaultPixelsPerUnit; + + Sprite sprite = BuildSpriteWithTexture( + texture, + pivot, + pixelsPerUnit, + spriteInfo.transformToOutline, + spriteInfo.gaussianBlurRadius + ); + RegisterSprite(spriteAtlasManager, spriteName, sprite); } - List popupButtons = new() + + foreach (var (textureName, texture) in Registry.textures) { - new("buttons.back"), - new( - "polymod.wc.proceed", - PopupBase.PopupButtonData.States.None, - callback: DelegateSupport.ConvertDelegate(WCProceed), - customColorStates: ColorConstants.redButtonColorStates - ) - }; - popup.buttonData = popupButtons.ToArray(); - popup.Show(); - return false; + if (Registry.sprites.ContainsKey(textureName)) + continue; + + Sprite sprite = BuildSpriteWithTexture(texture, GetPivotPreset(textureName), defaultPixelsPerUnit); + RegisterSprite(spriteAtlasManager, textureName, sprite); + } } - /// Shows a basic popup with a custom width. - public static void ShowSetWidth(this BasicPopupLegacy self, int width) + /// + /// Changes a sprite into PNG bytes and a sprite info. + /// The method draws the sprite into a new texture with and encodes that texture as PNG. + /// + /// The sprite to change. + /// The PNG bytes, and a sprite info with the pixels per unit and the pivot of the sprite. + internal static (byte[], SpriteInfo) SpriteToPng(Sprite sprite) { - basicPopupWidths.Add(self.GetInstanceID(), width); - self.Show(); - } + Texture2D bakedTexture = BakeSpriteToTexture(sprite); - // [HarmonyPrefix] - // [HarmonyPatch(typeof(BasicPopup), nameof(BasicPopup.SetButtonData))] - // public static bool SetButtonData(BasicPopup __instance, PopupBase.PopupButtonData[] buttonDatas, bool updateOmniCursor) - // { - // if (buttonDatas == null) - // { - // __instance.SetDefaultOkbutton(); - // return false; - // } - // foreach (var buttonData in buttonDatas) - // { - // var MainButton = __instance.createButton(buttonData.text, buttonData.callback, UIButtonBase_UI2.ButtonStyle.Suggested); - // MainButton.OnClickedSignal.Add(DelegateSupport.ConvertDelegate(__instance.Hide)); - // } - // __instance.RunLayout(); - // return false; - // } + byte[] pngBytes = ImageConversion.EncodeToPNG(bakedTexture); + UnityEngine.Object.Destroy(bakedTexture); - #endregion + Vector2 normalizedPivot = GetNormalizedPivot(sprite); - internal static BasicPopupLegacy GetBasicPopupLegacy() - { - WhatsNewPopup whatsNewPopup = PopupManager.GetWhatsNewPopup(); - BasicPopupLegacy original = PopupManager.instance.popupPrefabs[BASIC_POPUP_LEGACY_ID].Cast(); - BasicPopupLegacy basicPopupLegacy = UnityEngine.Object.Instantiate(original, PopupManager.instance.transform); - basicPopupLegacy.buttonContainer = GameObject.Instantiate(whatsNewPopup.buttonContainer, basicPopupLegacy.transform); - basicPopupLegacy.popupId = "basicPopupLegacy"; - basicPopupLegacy.popupManager = PopupManager.instance; - basicPopupLegacy.Init(); - basicPopupLegacy.identifier = null; - basicPopupLegacy.rectTransform.SetAsLastSibling(); - return basicPopupLegacy; + return (pngBytes, new SpriteInfo(sprite.pixelsPerUnit, normalizedPivot)); } - /// Updates a visual part with a custom sprite. - private static void UpdateVisualPart(SkinVisualsReference.VisualPart? visualPart, string name, string style) + /// + /// Gets the pivot of a sprite as a fraction of the sprite size. + /// + /// The sprite. + /// The pivot, with values from 0 to 1 for a pivot in the sprite rectangle. + private static Vector2 GetNormalizedPivot(Sprite sourceSprite) { - if (visualPart == null || visualPart.visualPart == null) - return; - - Sprite? sprite = Registry.GetSprite(name, style) ?? Registry.GetSprite(visualPart.visualPart.name, style); + return new Vector2( + sourceSprite.pivot.x / sourceSprite.rect.width, + sourceSprite.pivot.y / sourceSprite.rect.height + ); + } - if (sprite != null && visualPart.renderer != null) + /// + /// Draws the mesh of a sprite into a new texture that has the size of the sprite rectangle. + /// The method uses the Sprites/Default shader and a temporary render texture. + /// It changes the pixels to straight alpha and copies color into the transparent edge pixels. + /// It sets the active render texture back to the previous value. + /// + /// The sprite to draw. It can be a part of an atlas. + /// A new RGBA32 texture without mipmaps, with clamp wrap mode. + private static Texture2D BakeSpriteToTexture(Sprite sourceSprite) + { + Texture2D atlasTexture = sourceSprite.texture; + int spriteWidth = (int)sourceSprite.rect.width; + int spriteHeight = (int)sourceSprite.rect.height; + float sourcePixelsPerUnit = sourceSprite.pixelsPerUnit; + Vector2 sourcePivotInPixels = sourceSprite.pivot; + + var meshVertices = sourceSprite.vertices; + var meshUvs = sourceSprite.uv; + var meshTriangles = sourceSprite.triangles; + + RenderTexture renderTexture = RenderTexture.GetTemporary( + spriteWidth, spriteHeight, 0, + RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); + RenderTexture previousActiveRenderTexture = RenderTexture.active; + RenderTexture.active = renderTexture; + GL.Clear(true, true, Color.clear); + + Material spriteMaterial = new Material(Shader.Find("Sprites/Default")); + spriteMaterial.mainTexture = atlasTexture; + spriteMaterial.SetPass(0); + + GL.PushMatrix(); + GL.LoadPixelMatrix(0, spriteWidth, 0, spriteHeight); + GL.Begin(GL.TRIANGLES); + for (int triangleCornerIndex = 0; triangleCornerIndex < meshTriangles.Length; triangleCornerIndex++) { - if (visualPart.renderer.spriteRenderer != null) - visualPart.renderer.spriteRenderer.sprite = sprite; - else if (visualPart.renderer.polytopiaSpriteRenderer != null) - visualPart.renderer.polytopiaSpriteRenderer.sprite = sprite; + int vertexIndex = meshTriangles[triangleCornerIndex]; + Vector2 uv = meshUvs[vertexIndex]; + Vector2 vertex = meshVertices[vertexIndex]; + + GL.TexCoord(new Vector3(uv.x, uv.y, 0)); + GL.Vertex3( + vertex.x * sourcePixelsPerUnit + sourcePivotInPixels.x, + vertex.y * sourcePixelsPerUnit + sourcePivotInPixels.y, + 0); } + GL.End(); + GL.PopMatrix(); - Sprite? outlineSprite = Registry.GetSprite($"{name}_outline", style) ?? Registry.GetSprite($"{visualPart.visualPart.name}_outline", style); + Texture2D bakedTexture = new Texture2D(spriteWidth, spriteHeight, TextureFormat.RGBA32, false); + bakedTexture.ReadPixels(new Rect(0, 0, spriteWidth, spriteHeight), 0, 0); - if (outlineSprite != null && visualPart.outlineRenderer != null) - { - if (visualPart.outlineRenderer.spriteRenderer != null) - visualPart.outlineRenderer.spriteRenderer.sprite = outlineSprite; - else if (visualPart.outlineRenderer.polytopiaSpriteRenderer != null) - visualPart.outlineRenderer.polytopiaSpriteRenderer.sprite = outlineSprite; - } + Color32[] bakedPixels = bakedTexture.GetPixels32(); + Unpremultiply(bakedPixels); + BleedAlphaEdges(bakedPixels, spriteWidth, spriteHeight); + bakedTexture.SetPixels32(bakedPixels); + + bakedTexture.Apply(); + bakedTexture.wrapMode = TextureWrapMode.Clamp; + + RenderTexture.active = previousActiveRenderTexture; + RenderTexture.ReleaseTemporary(renderTexture); + UnityEngine.Object.Destroy(spriteMaterial); + + return bakedTexture; } - /// Builds a sprite from raw byte data. - /// The raw byte data of the image. - /// The pivot point of the sprite. - /// The number of pixels per unit for the sprite. - /// The created sprite. - public static Sprite BuildSprite(byte[] data, Vector2? pivot = null, float pixelsPerUnit = 2112f) + /// + /// Makes and registers the sprites in , and then clears that list. + /// For each entry, the method finds the game sprite with the origin name. + /// If the game sprite does not exist, it writes a warning to the log and skips the entry. + /// If the entry has a pivot, pixels per unit, an outline or a blur, the method makes a new sprite with these settings. + /// A setting that the entry does not have comes from the game sprite. + /// Without these settings, the method registers the game sprite with no changes. + /// + public static void CreateInnerOriginSprites() { - Texture2D texture = new(1, 1, TextureFormat.RGBA32, true); - texture.LoadImage(data); - Color[] pixels = texture.GetPixels(); - for (int i = 0; i < pixels.Length; i++) + Plugin.logger.LogInfo($"Creating sprites with inner origin..."); + SpriteAtlasManager spriteAtlasManager = GameManager.GetSpriteAtlasManager(); + + foreach (KeyValuePair spriteInfoPair in pendingInnerOriginSpriteInfos) { - pixels[i] = new Color(pixels[i].r, pixels[i].g, pixels[i].b, pixels[i].a); - } - texture.SetPixels(pixels); - texture.filterMode = FilterMode.Trilinear; - texture.Apply(); - return BuildSpriteWithTexture(texture, pivot, pixelsPerUnit); - } + string spriteName = spriteInfoPair.Key; + SpriteInfo spriteInfo = spriteInfoPair.Value; - /// Builds a sprite from a texture. - /// The texture to create the sprite from. - /// The pivot point of the sprite. - /// The number of pixels per unit for the sprite. - /// The created sprite. - public static Sprite BuildSpriteWithTexture(Texture2D texture, Vector2? pivot = null, float? pixelsPerUnit = 2112f) - { - return Sprite.Create( - texture, - new(0, 0, texture.width, texture.height), - pivot ?? new(0.5f, 0.5f), - pixelsPerUnit ?? 2112f - ); - } + Sprite originalSprite = spriteAtlasManager + .DoSpriteLookup(spriteInfo.spriteOrigin!.name, TribeType.None, SkinType.Default) + .sprite; - private const string MIGHTYLEADER = "mightyleader"; + if (originalSprite == null) + { + Plugin.logger.LogWarning($"Inner origin sprite '{spriteInfo.spriteOrigin.name}' not found for '{spriteName}'"); + continue; + } - [HarmonyPostfix] - [HarmonyPatch(typeof(PopupContentBuilder), nameof(PopupContentBuilder.GetMightyLeaderTopImage))] - public static void PopupContentBuilder_GetMightyLeaderTopImage(ref Sprite __result, PlayerState player) - { - Sprite? sprite = Registry.GetSprite(MIGHTYLEADER, Util.GetStyle(player.tribe, player.GetVisualSkin())); - if(sprite != null) - __result = sprite; + bool hasPivotOverride = spriteInfo.pivot != null; + bool hasPixelsPerUnitOverride = spriteInfo.pixelsPerUnit != null; + bool hasEffect = spriteInfo.transformToOutline || spriteInfo.gaussianBlurRadius != null; + + Sprite sprite = originalSprite; + + if (hasPivotOverride || hasPixelsPerUnitOverride || hasEffect) + { + Vector2 normalizedOriginalPivot = new( + originalSprite.pivot.x / originalSprite.rect.width, + originalSprite.pivot.y / originalSprite.rect.height + ); + + Vector2 finalPivot = hasPivotOverride ? spriteInfo.pivot!.Value : normalizedOriginalPivot; + float finalPixelsPerUnit = hasPixelsPerUnitOverride ? spriteInfo.pixelsPerUnit!.Value : originalSprite.pixelsPerUnit; + bool transformToOutline = spriteInfo.transformToOutline; + float? gaussianBlurRadius = spriteInfo.gaussianBlurRadius; + + Texture2D bakedTexture = BakeSpriteToTexture(originalSprite); + sprite = BuildSpriteWithTexture(bakedTexture, finalPivot, finalPixelsPerUnit, transformToOutline, gaussianBlurRadius); + sprite.name = spriteName; + } + + RegisterSprite(spriteAtlasManager, spriteName, sprite); + } + + pendingInnerOriginSpriteInfos.Clear(); } - /// Initializes the Visual manager by patching the necessary methods. + /// + /// Applies all Harmony patches in the class. + /// internal static void Init() { Harmony.CreateAndPatchAll(typeof(Visual)); diff --git a/src/Mod.cs b/src/Mod.cs index 5c5de5b..b1742f9 100644 --- a/src/Mod.cs +++ b/src/Mod.cs @@ -1,69 +1,72 @@ namespace PolyMod; /// -/// Represents a mod in the PolyMod framework. +/// A mod that PolyMod found in the mods directory, or the base game entry with the id polytopia. /// public class Mod { /// - /// Represents a dependency of a mod. + /// A dependency of a mod on a different mod, as the manifest gives it. /// - /// The unique identifier of the dependency. - /// The minimum compatible version of the dependency, or null for no minimum. - /// The maximum compatible version of the dependency, or null for no maximum. - /// Whether the dependency is required for the mod to function. + /// The id of the mod that this mod needs. + /// The lowest version of the dependency that is permitted, or null for no lower limit. + /// The highest version of the dependency that is permitted, or null for no upper limit. + /// + /// If true, the mod gets the status when the dependency is missing or has a bad version. + /// If false, PolyMod only writes a warning to the log. + /// public record Dependency(string id, Version? min, Version? max, bool required = true); /// - /// Represents the manifest of a mod, containing metadata. + /// The data from the manifest.json file of a mod. /// - /// The unique identifier of the mod. - /// The name of the mod. - /// A description of the mod. + /// The id of the mod. It must contain only lowercase letters and underscores, and it must not be polytopia. + /// The name of the mod to show, or null to use the id. + /// The description of the mod, or null. /// The version of the mod. - /// The authors of the mod. - /// The dependencies of the mod. - /// Whether the mod is client-side only. + /// The names of the authors of the mod. The array must not be empty. + /// The dependencies of the mod, or null for no dependencies. + /// If true, the mod is client-side only and PolyMod does not include it in the mod checksum. public record Manifest(string id, string? name, string? description, Version version, string[] authors, Dependency[]? dependencies, bool client = false); /// - /// Represents a file included in a mod. + /// A file in a mod, other than manifest.json. /// - /// The name of the file. - /// The content of the file as a byte array. + /// The path of the file, relative to the root of the mod directory or archive. + /// The contents of the file. public record File(string name, byte[] bytes); /// - /// Represents the loading status of a mod. + /// The load status of a mod. /// public enum Status { /// - /// The mod was loaded successfully. + /// The mod has no errors. PolyMod loads its files. /// Success, /// - /// An error occurred while loading the mod. + /// An error occurred when PolyMod loaded the mod. /// Error, /// - /// The mod's dependencies were not satisfied. + /// A required dependency of the mod is missing or has a version that is not permitted. /// DependenciesUnsatisfied, } /// - /// The unique identifier of the mod. + /// The id of the mod. /// public string id; /// - /// The name of the mod. + /// The name of the mod to show. If the manifest has no name, this is the id. /// public string? name; /// - /// A description of the mod. + /// The description of the mod, or null. /// public string? description; @@ -73,36 +76,43 @@ public enum Status public Version version; /// - /// The authors of the mod. + /// The names of the authors of the mod. /// public string[] authors; /// - /// The dependencies of the mod. + /// The dependencies of the mod, or null. /// public Dependency[]? dependencies; /// - /// Whether the mod is client-side only. + /// If true, the mod is client-side only and PolyMod does not include it in the mod checksum. /// public bool client; /// - /// The loading status of the mod. + /// The load status of the mod. /// public Status status; /// - /// The files included in the mod. + /// The files of the mod. This list does not contain manifest.json. /// public List files; /// - /// Initializes a new instance of the class. + /// The SHA-256 checksum of the mod, as a hexadecimal string. + /// PolyMod makes it from the id, the version, and the name and contents of each file. + /// It stays empty for client-side mods, for the base game entry, and for mods that do not have the status . /// - /// The manifest of the mod. - /// The loading status of the mod. - /// The files included in the mod. + public string checksum = string.Empty; + + /// + /// Makes a mod from a manifest. + /// + /// The manifest that gives the id, name, description, version, authors, dependencies and client value. + /// The initial load status of the mod. + /// The files of the mod. public Mod(Manifest manifest, Status status, List files) { id = manifest.id; diff --git a/src/NullableFix.cs b/src/NullableFix.cs deleted file mode 100644 index adc6cdf..0000000 --- a/src/NullableFix.cs +++ /dev/null @@ -1,49 +0,0 @@ -#nullable disable - -namespace System.Runtime.CompilerServices -{ - /// - /// A polyfill for the Nullable attribute, which is used by the compiler for nullable reference type analysis. - /// - [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] - public sealed class NullableAttribute : System.Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// The nullable flags. - public NullableAttribute(byte b) { } - - /// - /// Initializes a new instance of the class. - /// - /// The nullable flags. - public NullableAttribute(byte[] b) { } - } - - /// - /// A polyfill for the NullableContext attribute, which is used by the compiler for nullable reference type analysis. - /// - [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false)] - public sealed class NullableContextAttribute : System.Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// The nullable context flags. - public NullableContextAttribute(byte b) { } - } - - /// - /// A polyfill for the NullablePublicOnly attribute, which is used by the compiler for nullable reference type analysis. - /// - [System.AttributeUsage(System.AttributeTargets.Module)] - public sealed class NullablePublicOnlyAttribute : System.Attribute - { - /// - /// Initializes a new instance of the class. - /// - /// Whether to apply nullable analysis to public members only. - public NullablePublicOnlyAttribute(bool b) { } - } -} diff --git a/src/Plugin.cs b/src/Plugin.cs index c273eb4..e4a7598 100644 --- a/src/Plugin.cs +++ b/src/Plugin.cs @@ -1,86 +1,136 @@ -using System.Reflection; +using System.IO.Pipes; +using System.Reflection; using System.Text.Json; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using PolyMod.Managers; -using UnityEngine; namespace PolyMod; /// -/// Main plugin class for PolyMod. +/// The BepInEx plugin of PolyMod. BepInEx loads this plugin and calls . /// [BepInPlugin("com.polymod", "PolyMod", VERSION)] public partial class Plugin : BepInEx.Unity.IL2CPP.BasePlugin { /// - /// Represents the configuration for PolyMod. + /// Gets or sets the token that the PolyMod launcher sends, or null if PolyMod did not get a token. /// - /// Whether to enable debug mode. - /// Whether to automatically update PolyMod. - /// Whether to include pre-release versions when updating. + internal static string? Token { get; set; } + /// + /// Gets or sets a value that tells if the game start is valid. + /// sets this value. + /// If it is false, PolyMod shows an error popup on the start screen, but not on Android. + /// + internal static bool ValidLaunch { get; set; } = false; + /// + /// Gets or sets a value that is true when the PolyMod launcher tells PolyMod not to start. + /// If it is true, stops before it starts the managers. + /// + internal static bool Disabled { get; set; } = false; + + /// + /// The configuration of PolyMod. PolyMod reads it from and writes it to the same file. + /// + /// If true, PolyMod shows the BepInEx console. + /// If true, PolyMod shows the coordinates of the tiles. + /// If true, a mod can give a fixed idx to a new enum value, if the idx is larger than all existing values of the enum. + /// A device id value. No code in PolyMod reads this value at this time. internal record PolyConfig( bool debug = false, - bool autoUpdate = true, - bool updatePrerelease = false, - bool allowUnsafeIndexes = false - ); + bool showCoordinates = false, + bool allowUnsafeIndexes = false, + string overrideDeviceId = "" + ) + { + /// + /// Gets the ids of the mods that PolyMod does not register. + /// + public List disabledMods { get; init; } = new(); + }; /// - /// The starting index for automatically assigned IDs. + /// The first index that PolyMod gives to an automatically indexed enum value. + /// PolyMod also uses this value to identify enum values that mods add. /// internal const int AUTOIDX_STARTS_FROM = 1000; /// - /// The key used to store the last version for which the incompatibility warning was shown. + /// The player prefs key that keeps the last game version for which PolyMod showed the incompatibility warning. /// internal const string INCOMPATIBILITY_WARNING_LAST_VERSION_KEY = "INCOMPATIBILITY_WARNING_LAST_VERSION"; /// - /// The base path for PolyMod files. + /// The prefix of the player prefs keys that keep the mod checksum of each saved game. + /// + internal const string STATE_CHECKSUM_KEY_PREFIX = "POLYMOD_STATE_CHECKSUM_"; + + /// + /// The maximum time, in milliseconds, that waits to connect to the PolyMod launcher. + /// + internal const int LAUNCH_DATA_TIMEOUT = 2000; + + /// + /// The root directory of PolyMod files. This is the parent directory of the BepInEx root directory. /// public static readonly string BASE_PATH = Path.Combine(BepInEx.Paths.BepInExRootPath, ".."); /// - /// The path to the mods directory. + /// The path of the directory that contains the mods. /// public static readonly string MODS_PATH = Path.Combine(BASE_PATH, "Mods"); /// - /// The path to the directory where game data is dumped. + /// The path of the directory to which PolyMod writes the dumped game data. /// public static readonly string DUMPED_DATA_PATH = Path.Combine(BASE_PATH, "DumpedData"); /// - /// The path to the directory where localization is dumped. + /// The path of the directory to which PolyMod writes the dumped GLD and avatar data. /// public static readonly string LOGIC_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Logic"); /// - /// The path to the directory where gameLogicData and avatarData are dumped. + /// The path of the directory to which PolyMod writes the dumped localization. /// public static readonly string LOCALIZATION_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Localization"); /// - /// The path to the PolyMod configuration file. + /// The path of the directory to which PolyMod writes the dumped sprites and sprite infos. + /// + public static readonly string SPRITES_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Sprites"); + + /// + /// The path of the directory to which PolyMod writes the dumped prefab data. + /// + public static readonly string PREFABS_DUMP_PATH = Path.Combine(DUMPED_DATA_PATH, "Prefabs"); + + /// + /// The path of the PolyMod configuration file, PolyMod.json. /// internal static readonly string CONFIG_PATH = Path.Combine(BASE_PATH, "PolyMod.json"); /// - /// The path to the checksum file. + /// The path of the file that keeps the mod checksum of the last game start. /// internal static readonly string CHECKSUM_PATH = Path.Combine(BASE_PATH, "CHECKSUM"); + /// + /// The path of the directory that PolyMod gives to the game as Application.persistentDataPath. + /// + internal static readonly string PERSISTENT_DATA_PATH = Path.Combine(BASE_PATH, "PersistentData"); + /// /// The link to the PolyMod Discord server. /// internal static readonly string DISCORD_LINK = "https://discord.gg/eWPdhWtfVy"; /// - /// A list of log messages to ignore. + /// The text parts of Unity log messages that PolyMod does not write to the log. + /// If a log message contains one of these texts, PolyMod removes the message. /// internal static readonly List LOG_MESSAGES_IGNORE = new() { @@ -94,19 +144,27 @@ internal static readonly string CHECKSUM_PATH #pragma warning disable CS8618 /// - /// The PolyMod configuration. + /// The current configuration of PolyMod. reads it from . /// internal static PolyConfig config; /// - /// The logger instance for PolyMod. + /// The BepInEx log source of PolyMod. /// internal static ManualLogSource logger; #pragma warning restore CS8618 /// - /// The entry point for the plugin. + /// Starts PolyMod. BepInEx calls this method when it loads the plugin. /// + /// + /// The method reads the configuration from . + /// If the file is missing or not valid, it uses the default configuration. + /// Then it writes the configuration back to the file and updates the console. + /// It sets the BepInEx Logging.Disk.WriteUnityLog setting to true and calls . + /// If is true, the method stops there. + /// Otherwise, it starts the PolyMod managers. + /// public override void Load() { try @@ -122,23 +180,65 @@ public override void Load() logger = Log; ConfigFile.CoreConfig[new("Logging.Disk", "WriteUnityLog")].BoxedValue = true; - AutoUpdate.Init(); + CaptureLaunchData(); + + if (Disabled) + return; Compatibility.Init(); Audio.Init(); Loc.Init(); + Visual.Init(); - Hub.Init(); + Prefabs.Init(); + TribePreviews.Init(); + Hub.Init(); Main.Init(); } /// - /// Gets a resource stream from the assembly. + /// Gets the launch data from the PolyMod launcher through the named pipe PolyMod.Launcher. + /// + /// + /// The method waits a maximum of milliseconds to connect. + /// It reads one line of JSON and sets , and from it. + /// If the line is empty, the method stops and does not change these values. + /// If an error occurs, the method sets to false. + /// + internal static void CaptureLaunchData() + { + try + { + using var client = new NamedPipeClientStream( + ".", "PolyMod.Launcher", PipeDirection.In, PipeOptions.CurrentUserOnly); + client.Connect(LAUNCH_DATA_TIMEOUT); + + using var reader = new StreamReader(client); + var line = reader.ReadLine(); + if (string.IsNullOrEmpty(line)) return; + using var doc = JsonDocument.Parse(line); + var root = doc.RootElement; + + ValidLaunch = root.GetProperty("validLaunch").GetBoolean(); + Disabled = root.GetProperty("disabled").GetBoolean(); + Token = root.GetProperty("token").GetString() ?? ""; + } + catch + { + ValidLaunch = false; + } + + ValidLaunch = true; // IN THIS 2.0 ALPHA LAUNCH IS ALWAYS VALID!!!!!!!!!!! + } + + /// + /// Opens a stream to a resource that is embedded in the PolyMod assembly. + /// The full resource name is PolyMod.resources. followed by . /// - /// The ID of the resource. - /// The resource stream. + /// The file name of the resource, for example localization.json. + /// The stream of the resource. The value is null if the resource does not exist. internal static Stream GetResource(string id) { return Assembly.GetExecutingAssembly().GetManifestResourceStream( @@ -147,7 +247,7 @@ internal static Stream GetResource(string id) } /// - /// Writes the configuration to disk. + /// Writes the current as JSON to . /// internal static void WriteConfig() { @@ -155,7 +255,9 @@ internal static void WriteConfig() } /// - /// Updates the console based on the debug configuration. + /// Shows or hides the BepInEx console. The debug value of controls this. + /// If debug is true, the method makes the console. + /// If debug is false, the method detaches the console on Windows and does nothing on other operating systems. /// internal static void UpdateConsole() { @@ -163,8 +265,9 @@ internal static void UpdateConsole() { ConsoleManager.CreateConsole(); } - else + else if (OperatingSystem.IsWindows()) { + // BepInEx's Unix console driver throws unsupported on detach. Off-Windows there is no separate console window, so there is nothing to detach. ConsoleManager.DetachConsole(); } } diff --git a/src/PolyMod.csproj b/src/PolyMod.csproj index dd635e6..bfd2886 100644 --- a/src/PolyMod.csproj +++ b/src/PolyMod.csproj @@ -5,7 +5,7 @@ enable IL2CPP PolyMod - 1.2.19 + 2.0.0-pre 2.18.0.16751 PolyModdingTeam The Battle of Polytopia's mod loader. @@ -17,7 +17,7 @@ - + all diff --git a/src/Prefabs/OtherPrefabInfo.cs b/src/Prefabs/OtherPrefabInfo.cs new file mode 100644 index 0000000..d2ec8e5 --- /dev/null +++ b/src/Prefabs/OtherPrefabInfo.cs @@ -0,0 +1,234 @@ + +using System.Text.Json.Serialization; +using PolyMod.Json; +using Polytopia.Data; +using DG.Tweening; + +namespace PolyMod; + +/// +/// The base description of a prefab that PolyMod makes from mod JSON. +/// +public class BasePrefabInfo +{ + /// + /// The descriptions of the visual parts of the prefab. + /// + [JsonInclude] + public List visualParts = new(); +} +/// +/// The description of a custom unit prefab. +/// It comes from the units list of a prefabs file or from a unitPrefab file. +/// +public class UnitPrefabInfo : BasePrefabInfo +{ + /// + /// The unit type, the tribe, and the skin that the prefab is for. + /// + [JsonInclude] + public SkinnedKey skinnedKey; + + /// + /// The name of the visual part that is the head position marker of the unit. + /// If no visual part has this name, PolyMod uses the first visual part that it makes. + /// + [JsonInclude] + public string headPositionMarker = ""; + + /// + /// The flag that makes the prefab a UI override. + /// When it is true, the UI shows this prefab in place of the usual unit prefab. + /// + [JsonInclude] + public bool uiOverride = false; +} + +/// +/// The description of a custom improvement prefab. +/// It comes from the improvements list of a prefabs file or from an improvementPrefab file. +/// PolyMod also makes a default description for each GLD improvement that has the prefab value set to true. +/// +public class ImprovementPrefabInfo : BasePrefabInfo +{ + /// + /// The improvement type that the prefab is for. + /// If it is null, PolyMod does not make the prefab. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ImprovementData.Type? improvementType = null; + + /// + /// The flag that adds a renderer to the outline of each visual part. + /// When it is false, the outline objects have no renderer. + /// + [JsonInclude] + public bool needsOutlines = false; +} + +/// +/// The description of a custom resource prefab. +/// It comes from the resources list of a prefabs file or from a resourcePrefab file. +/// PolyMod also makes a default description for each GLD resource that has the prefab value set to true. +/// +public class ResourcePrefabInfo : BasePrefabInfo +{ + /// + /// The resource type that the prefab is for. + /// If it is null, PolyMod does not make the prefab. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public ResourceData.Type? resourceType = null; +} + +/// +/// The description of a custom weapon prefab. +/// PolyMod does not read or use this type now. +/// +internal class WeaponPrefabInfo +{ + /// + /// The weapon type that the prefab is for. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal UnitData.WeaponEnum? weaponEnum = null; + + /// + /// The name of the sprite of the weapon. + /// + [JsonInclude] + internal string spriteName = ""; + + /// + /// The DOTween path type of the weapon movement. + /// + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + internal PathType pathType = PathType.CatmullRom; + + /// + /// The DOTween path mode of the weapon movement. + /// + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + internal PathMode pathMode = PathMode.Sidescroller2D; + + /// + /// The DOTween path resolution of the weapon movement. + /// + [JsonInclude] + internal int pathResolution = 10; + + /// + /// The DOTween ease of the weapon movement. + /// + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + internal Ease pathEase = Ease.Linear; + + /// + /// The look-ahead offset of the weapon movement. + /// + [JsonInclude] + internal float lookAheadOffset = 0.01f; + + /// + /// The handle angle offset of the weapon path. + /// + [JsonInclude] + internal float handleAngleOffset = 0.3f; + + /// + /// The sound effect of the weapon. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal SFXTypes sfxType = SFXTypes.None; + + /// + /// The puff settings of the weapon, or null. + /// + [JsonInclude] + internal WeaponPuffInfo? weaponPuffInfo = null; + + /// + /// The ranged attack settings of the weapon, or null. + /// + [JsonInclude] + internal WeaponRangedInfo? weaponRangedInfo = null; +} + +/// +/// The puff settings of a custom weapon. +/// PolyMod does not use this type now. +/// +internal class WeaponPuffInfo +{ + /// + /// The flag that makes the attacking unit sway. + /// + [JsonInclude] + internal bool sway = false; + + /// + /// The value that multiplies the animation time of the attack. + /// + internal float animationMultiplier = 1f; + + /// + /// The action to call at the start of the attack, or null. + /// + internal Action? initialDelegate = null; + + /// + /// The action to call during the ranged animation, or null. + /// + internal Action? animationDelegate = null; + + // [JsonInclude] Nuh uh, I wont do ts + // public List puffsToSpawn = new(); +} + +/// +/// The ranged attack settings of a custom weapon. +/// PolyMod does not use this type now. +/// +internal class WeaponRangedInfo +{ + /// + /// The center offset of the ranged attack. + /// + [JsonInclude] + internal float centerOffset = 0.15f; +} + +/// +/// The description of a custom GFX prefab. +/// PolyMod does not use this type now. +/// +internal class GFXPrefabInfo +{ + /// + /// The GFX type that the prefab is for. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal GFXType? gfxType = null; +} + +/// +/// The description of a custom unit effect prefab. +/// PolyMod does not use this type now. +/// +internal class UnitEffectPrefabInfo +{ + /// + /// The unit effect that the prefab is for. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + internal UnitEffect? unitEffect = null; +} diff --git a/src/Prefabs/PrefabsInfo.cs b/src/Prefabs/PrefabsInfo.cs new file mode 100644 index 0000000..bd33633 --- /dev/null +++ b/src/Prefabs/PrefabsInfo.cs @@ -0,0 +1,32 @@ + +using System.Text.Json.Serialization; + +namespace PolyMod; + +/// +/// The content of a prefabs file of a mod. +/// The dumper also writes the prefabs of the game in this format. +/// +public class PrefabsInfo +{ + /// + /// The descriptions of the unit prefabs. + /// + [JsonInclude] + public List units = new(); + + /// + /// The descriptions of the improvement prefabs. + /// + [JsonInclude] + public List improvements = new(); + + /// + /// The descriptions of the resource prefabs. + /// + [JsonInclude] + public List resources = new(); + + // [JsonInclude] + private List weapons = new(); +} diff --git a/src/Prefabs/SkinnedKey.cs b/src/Prefabs/SkinnedKey.cs new file mode 100644 index 0000000..6134779 --- /dev/null +++ b/src/Prefabs/SkinnedKey.cs @@ -0,0 +1,100 @@ +using System.Text.Json.Serialization; +using PolyMod.Json; +using Polytopia.Data; +using PolytopiaBackendBase.Common; + +namespace PolyMod; + +/// +/// The key of a unit prefab: a unit type, a tribe, and a skin. +/// +public readonly struct SkinnedKey : IEquatable +{ + /// + /// Gets the unit type. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public UnitData.Type unitType { get; } + + /// + /// Gets the tribe. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public TribeType tribeType { get; } + + /// + /// Gets the skin. + /// + [JsonInclude] + [JsonConverter(typeof(EnumCacheJson))] + public SkinType skinType { get; } + + /// + /// Makes a key from a unit type, a tribe, and a skin. + /// + /// The unit type. + /// The tribe. + /// The skin. + [JsonConstructor] + public SkinnedKey(UnitData.Type unitType, TribeType tribeType, SkinType skinType) + { + this.unitType = unitType; + this.tribeType = tribeType; + this.skinType = skinType; + } + + /// + /// Compares this key with another key. + /// + /// The key to compare. + /// True when the unit type, the tribe, and the skin are all equal, otherwise false. + public bool Equals(SkinnedKey other) + { + return unitType == other.unitType + && tribeType == other.tribeType + && skinType == other.skinType; + } + + /// + /// Compares this key with an object. + /// + /// The object to compare. + /// True when the object is a that is equal to this key, otherwise false. + public override bool Equals(object? obj) + { + return obj is SkinnedKey otherKey && Equals(otherKey); + } + + /// + /// Gets the hash code of the key. + /// + /// A hash code that combines the unit type, the tribe, and the skin. + public override int GetHashCode() + { + return HashCode.Combine((int)unitType, (int)tribeType, (int)skinType); + } + + /// + /// Compares two keys. + /// + /// The first key. + /// The second key. + /// True when the keys are equal, otherwise false. + public static bool operator ==(SkinnedKey left, SkinnedKey right) + { + return left.Equals(right); + } + + /// + /// Compares two keys. + /// + /// The first key. + /// The second key. + /// True when the keys are not equal, otherwise false. + public static bool operator !=(SkinnedKey left, SkinnedKey right) + { + return !left.Equals(right); + } +} diff --git a/src/Prefabs/VisualPartInfo.cs b/src/Prefabs/VisualPartInfo.cs new file mode 100644 index 0000000..1ec55f3 --- /dev/null +++ b/src/Prefabs/VisualPartInfo.cs @@ -0,0 +1,135 @@ +using System.Text.Json.Serialization; +using PolyMod.Json; +using UnityEngine; + +namespace PolyMod; + +/// +/// The description of one visual part of a prefab, as mod JSON gives it. +/// +public class VisualPartInfo +{ + /// + /// The default sprite name of the visual part. + /// PolyMod also uses it as the name of the visual part object. + /// + [JsonInclude] + public string? defaultSpriteName; + + /// + /// The logic that selects the skin of the sprite. The default is UseTribe. + /// + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public SkinVisualsReference.SkinningLogic skinningLogic = SkinVisualsReference.SkinningLogic.UseTribe; + + /// + /// The logic that selects the skin of the sprite for an improvement. The default is FoundingTribe. + /// Only improvements use this value. + /// + [JsonInclude] + [JsonConverter(typeof(EnumNameJson))] + public SkinVisualsReference.ImprovementSkinningLogic improvementSkinningLogic = SkinVisualsReference.ImprovementSkinningLogic.FoundingTribe; // improvement specific + + /// + /// The world position of the visual part. + /// + [JsonInclude] + public Vector2 coordinates = new Vector2(0, 0); + + /// + /// The rotation of the visual part around the z axis, in degrees. + /// + [JsonInclude] + public float rotation = 0f; + + /// + /// The flag that lets the game tint the sprite with the team color. + /// + [JsonInclude] + public bool tintable = false; + + /// + /// The flag that makes the sprite change with the level of the improvement. + /// Only improvements use this value. + /// + [JsonInclude] + public bool levels = false; // improvement specific + + /// + /// The sorting order of the visual part renderer, or null to use the calculated sorting order. + /// Only unit prefabs use this value. + /// + [JsonInclude] + public int? sortingOrderOverride = null; + + /// + /// The sorting order of the outline renderer, or null to use the calculated sorting order. + /// Only unit prefabs use this value. + /// + [JsonInclude] + public int? outlineSortingOrderOverride = null; + + /// + /// Makes a game visual part from this description. + /// + /// + /// The method copies the sprite name, the tint flag, the skin logic values, and the level flag. + /// It does not make the objects or the renderers of the visual part. + /// + /// True to mark the visual part as an improvement part. + /// The new visual part. + public SkinVisualsReference.VisualPart ToVisualPart(bool isImprovement) + { + return new SkinVisualsReference.VisualPart + { + DefaultSpriteName = defaultSpriteName, + tintable = tintable, + skinLogic = skinningLogic, + improvementSkinLogic = improvementSkinningLogic, + levels = levels, + isImprovement = isImprovement, + }; + } + + /// + /// Sets all values of this description from a game visual part. + /// + /// + /// The sorting orders come from the SpriteRenderer of the visual part object and of the outline object. + /// If an object has no SpriteRenderer, its sorting order is null. + /// gets the world position of the visual part object. + /// gets the world rotation of the visual part object around the z axis, in degrees. + /// + /// The visual part to copy. Its visual part object must not be null. + public void CopyFromVisualPart(SkinVisualsReference.VisualPart visualPart) + { + int? sortingOrderOverride = null; + SpriteRenderer spriteRenderer = visualPart.visualPart.GetComponent(); + if (spriteRenderer != null) + { + sortingOrderOverride = spriteRenderer.sortingOrder; + } + + int? outlineSortingOrderOverride = null; + + if (visualPart.outline != null) + { + spriteRenderer = visualPart.outline.GetComponent(); + if (spriteRenderer != null) + { + outlineSortingOrderOverride = spriteRenderer.sortingOrder; + } + } + + coordinates = visualPart.visualPart.transform.position; + rotation = visualPart.visualPart.transform.eulerAngles.z; + defaultSpriteName = visualPart.DefaultSpriteName; + tintable = visualPart.tintable; + skinningLogic = visualPart.skinLogic; + improvementSkinningLogic = visualPart.improvementSkinLogic; + levels = visualPart.levels; + this.sortingOrderOverride = sortingOrderOverride; + this.outlineSortingOrderOverride = outlineSortingOrderOverride; + } +} diff --git a/src/Registry.cs b/src/Registry.cs index 4468130..8077cc6 100644 --- a/src/Registry.cs +++ b/src/Registry.cs @@ -1,124 +1,220 @@ +using System.Globalization; using LibCpp2IL; using PolyMod.Managers; -using PolytopiaBackendBase.Game; using UnityEngine; using PolytopiaBackendBase.Common; namespace PolyMod; /// -/// A central registry for storing and accessing modded content. +/// The central store of the mods and the mod content that PolyMod loads. /// public static class Registry { - /// - /// The next available index for automatically assigned IDs. - /// - public static int autoidx = Plugin.AUTOIDX_STARTS_FROM; + // internal static int autoidx = Plugin.AUTOIDX_STARTS_FROM; /// - /// A dictionary of all loaded sprites, keyed by their name. + /// The next free index for automatically indexed enum values, keyed by the enum type. + /// Each enum type, for example tribes, units, skins and tile effects, has its own counter. + /// A counter starts at . + /// Values of different enum types can therefore be the same number. /// - public static Dictionary sprites = new(); + internal static Dictionary autoindexes = new(); /// - /// A dictionary of all loaded audio clips, keyed by their name. + /// Gets the next free index for an automatically indexed value of an enum type. + /// The method does not change the counter. Call after you use the index. + /// If the type has no counter yet, the method makes one that starts at . /// - public static Dictionary audioClips = new(); + /// The enum type. + /// The next free index for the type. + public static int GetAutoIndex(Type type) + { + if(!autoindexes.TryGetValue(type, out int value)) + { + autoindexes[type] = value = Plugin.AUTOIDX_STARTS_FROM; + } + return value; + } /// - /// A dictionary of all loaded mods, keyed by their ID. + /// Increases the next free index of an enum type by 1. + /// If the type has no counter yet, the method makes one that starts at and then increases it. /// - public static Dictionary mods = new(); + /// The enum type. + public static void IncrementAutoIndex(Type type) + { + if(!autoindexes.ContainsKey(type)) + autoindexes[type] = Plugin.AUTOIDX_STARTS_FROM; + autoindexes[type]++; + } /// - /// A dictionary of tribe previews, keyed by tribe name. + /// The sprites that PolyMod made from mod textures, keyed by the lowercase sprite name. /// - public static Dictionary tribePreviews = new(); + internal static Dictionary sprites = new(); /// - /// A dictionary of sprite information, keyed by sprite name. + /// The textures from the PNG files of mods, keyed by the lowercase file name without the extension. /// - public static Dictionary spriteInfos = new(); + internal static Dictionary textures = new(); /// - /// A dictionary of prefab names, keyed by their enum value. + /// The audio sources of mod audio files, keyed by the lowercase file name without the extension. + /// Each audio source holds one audio clip. /// - public static Dictionary prefabNames = new(); + internal static Dictionary audioClips = new(); /// - /// A dictionary of custom unit prefabs, keyed by their prefab info. + /// All registered mods, keyed by the mod id. + /// This dictionary also contains the base game entry with the id polytopia. /// - public static Dictionary unitPrefabs = new(); + internal static Dictionary mods = new(); /// - /// A dictionary of custom resource prefabs, keyed by their prefab info. + /// The custom preview tiles of tribes, keyed by the tribe id from the GLD. /// - public static Dictionary resourcePrefabs = new(); + internal static Dictionary tribePreviews = new(); /// - /// A dictionary of custom improvement prefabs, keyed by their prefab info. + /// The sprite infos from the sprites.json and sprites_*.json files of mods, keyed by the lowercase sprite name. /// - public static Dictionary improvementsPrefabs = new(); + internal static Dictionary spriteInfos = new(); /// - /// A dictionary of loaded asset bundles, keyed by their name. + /// The asset bundles from the .bundle files of mods, keyed by the file name without the extension. /// - public static Dictionary assetBundles = new(); + internal static Dictionary assetBundles = new(); /// - /// A list of custom tribes. + /// The tribe types of the custom tribes that mods add. /// - public static List customTribes = new(); + internal static List customTribes = new(); /// - /// A list of custom skin information. + /// The skin infos of the custom skins that mods add. /// - public static List skinInfo = new(); + internal static List skinInfo = new(); /// - /// The next available index for climate styles. + /// The next free value for the style and the climate of a custom tribe. + /// The counter starts at the value of the last member. /// - public static int climateAutoidx = (int)Enum.GetValues(typeof(TribeType)).Cast().Last(); + internal static int climateAutoidx = (int)Enum.GetValues().Last(); /// - /// The next available index for game modes. + /// The prefab files that PolyMod loads after it merges the GLD patches. + /// Each entry contains the mod and one of its files. A mod can have more than one entry. /// - public static int gameModesAutoidx = Enum.GetValues(typeof(GameMode)).Length; + internal static List<(Mod mod, Mod.File file)> filesQueueToBeProcessedAfterGLDMerge = new(); /// - /// Gets a sprite from the registry, trying to find the best match. + /// Gets the mod sprite that is the best match for a base name, a tribe, a skin and a level. + /// The method changes the tribe and the skin to their EnumCache names and calls . /// - /// The name of the sprite. - /// The style of the sprite (e.g., tribe or skin). - /// The level of the sprite (e.g., for cities). - /// The requested sprite, or null if not found. The lookup priority is: name_style_level, name__level, name_style_, name__. - public static Sprite? GetSprite(string name, string style = "", int level = 0) + /// The base name of the sprite. + /// The tribe of the sprite, or for no tribe. + /// The skin of the sprite, or for no skin. + /// The level of the sprite, or -1 for no level. + /// If true, the method finds the outline variant of the sprite. + /// The sprite that is the best match, or null if no sprite matches. + public static Sprite? GetSprite(string baseName, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default, int level = -1, bool outline = false) + { + string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); + string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); + string levelText = (level == -1) ? "" : level.ToString(CultureInfo.InvariantCulture); + return GetSpriteByText(baseName, tribeText, skinText, levelText, outline); + } + /// + /// Gets the mod sprite that is the best match for a base name, a tribe text, a skin text and a level text. + /// + /// + /// The method changes the base name, the tribe text and the skin text to lowercase. + /// If the level text is not empty, the method adds _level to the base name. + /// Then it tries these names in sequence: base, base_tribe, base_skin and base_tribe_skin. + /// If is true, the method adds _outline to each name. + /// A sprite that the method finds later replaces a sprite that it found before. + /// The result is the sprite with the most specific name that exists in . + /// + /// The base name of the sprite. + /// The tribe part of the sprite name, or an empty string. + /// The skin part of the sprite name, or an empty string. + /// The level part of the sprite name, or an empty string for no level. + /// If true, the method finds the outline variant of the sprite. + /// The sprite that is the best match, or null if no sprite matches. + public static Sprite? GetSpriteByText(string baseName, string tribeText = "", string skinText = "", string levelText = "", bool outline = false) { Sprite? sprite = null; - name = name.ToLower(); - style = style.ToLower(); - // This looks backwards, but GetOrDefault returns the provided default value if the key isn't found. - // This means `sprite` is updated sequentially, and the last, most-specific match is the one that is kept. - sprite = sprites.GetOrDefault($"{name}__", sprite); - sprite = sprites.GetOrDefault($"{name}_{style}_", sprite); - sprite = sprites.GetOrDefault($"{name}__{level}", sprite); - sprite = sprites.GetOrDefault($"{name}_{style}_{level}", sprite); + baseName = baseName.ToLowerInvariant(); + tribeText = tribeText.ToLowerInvariant(); + skinText = skinText.ToLowerInvariant(); + + List spriteNameVariants = new(); + + if (levelText != string.Empty) + baseName += $"_{levelText}"; + + spriteNameVariants.Add(baseName); + spriteNameVariants.Add(baseName + "_" + tribeText); + spriteNameVariants.Add(baseName + "_" + skinText); + spriteNameVariants.Add(baseName + "_" + tribeText + "_" + skinText); + + foreach (string spriteName in spriteNameVariants) + { + sprite = sprites.GetOrDefault(outline ? spriteName + "_outline" : spriteName, sprite); + } + return sprite; } /// - /// Gets an audio clip from the registry. + /// Gets the mod audio clip that is the best match for a name, a tribe and a skin. + /// The method changes the tribe and the skin to their EnumCache names and calls . + /// + /// The base name of the audio clip. + /// The tribe of the audio clip, or for no tribe. + /// The skin of the audio clip, or for no skin. + /// The audio clip that is the best match, or null if no audio clip matches. + public static AudioClip? GetAudioClip(string name, TribeType tribe = TribeType.None, SkinType skin = SkinType.Default) + { + string tribeText = (tribe == TribeType.None) ? "" : EnumCache.GetName(tribe); + string skinText = (skin == SkinType.Default) ? "" : EnumCache.GetName(skin); + return GetAudioClipByText(name, tribeText, skinText); + } + + /// + /// Gets the mod audio clip that is the best match for a base name, a tribe text and a skin text. /// - /// The name of the audio clip. - /// The style of the audio clip. - /// The requested audio clip, or null if not found. - public static AudioClip? GetAudioClip(string name, string style) + /// + /// The method changes all three texts to lowercase. + /// Then it tries these names in sequence: base, base_tribe, base_skin and base_tribe_skin. + /// An audio source that the method finds later replaces an audio source that it found before. + /// The result is the clip of the audio source with the most specific name that exists in . + /// + /// The base name of the audio clip. + /// The tribe part of the audio name, or an empty string. + /// The skin part of the audio name, or an empty string. + /// The clip of the audio source that is the best match, or null if no audio source matches. + private static AudioClip? GetAudioClipByText(string baseName, string tribeText = "", string skinText = "") { AudioSource? audioSource = null; - name = name.ToLower(); - style = style.ToLower(); - audioSource = audioClips.GetOrDefault($"{name}_{style}", audioSource); + baseName = baseName.ToLowerInvariant(); + tribeText = tribeText.ToLowerInvariant(); + skinText = skinText.ToLowerInvariant(); + + List audioNameVariants = new() + { + baseName, + baseName + "_" + tribeText, + baseName + "_" + skinText, + baseName + "_" + tribeText + "_" + skinText, + }; + + foreach (string audioName in audioNameVariants) + { + audioSource = audioClips.GetOrDefault(audioName, audioSource); + } + if (audioSource == null) return null; return audioSource.clip; } diff --git a/src/Util.cs b/src/Util.cs index aef2ebb..8ede6b2 100644 --- a/src/Util.cs +++ b/src/Util.cs @@ -1,23 +1,23 @@ +using System.Globalization; using System.Security.Cryptography; using System.Text; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Injection; using Newtonsoft.Json.Linq; -using Polytopia.Data; -using PolytopiaBackendBase.Common; namespace PolyMod; /// -/// A collection of utility methods for the PolyMod framework. +/// The helper methods that PolyMod uses for types, hashes, JSON tokens, tasks and versions. /// internal static class Util { /// - /// Wraps a managed type for use in the Il2Cpp runtime. + /// Gets the Il2Cpp type of a managed type. + /// If the managed type is not registered in Il2Cpp, the method registers it first. /// - /// The type to wrap. - /// The Il2Cpp representation of the type. + /// The managed type. + /// The Il2CppSystem.Type of . internal static Il2CppSystem.Type WrapType() where T : class { if (!ClassInjector.IsTypeRegisteredInIl2Cpp()) @@ -26,67 +26,80 @@ internal static Il2CppSystem.Type WrapType() where T : class } /// - /// Computes the SHA256 hash of an object's string representation. + /// Gets the SHA-256 hash of the string value of an object. + /// The method uses ToString on the object and UTF-8 to make the bytes. /// /// The object to hash. - /// The hexadecimal string representation of the hash. + /// The hash as an uppercase hexadecimal string. internal static string Hash(object data) { return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(data.ToString()!))); } /// - /// Gets the name of a JToken from its path. + /// Gets the SHA-256 hash of a byte array. /// - /// The JToken. - /// The part of the path to retrieve, from the end. - /// The name of the JToken. + /// The bytes to hash. + /// The hash as an uppercase hexadecimal string. + internal static string HashBytes(byte[] data) + { + return Convert.ToHexString(SHA256.HashData(data)); + } + + /// + /// Gets one part of the path of a JSON token. + /// The method splits the path at each dot and counts the parts from the end. + /// + /// The JSON token. + /// The position of the part from the end of the path. The value 1 gives the last part. + /// The part of the path at position from the end. internal static string GetJTokenName(JToken token, int n = 1) { return token.Path.Split('.')[^n]; } /// - /// Converts an Il2CppSystem.Version to a System.Version. + /// Changes an Il2CppSystem.Version to a . + /// The method parses the string value of the Il2Cpp version. /// - /// The Il2CppSystem.Version to convert. - /// The equivalent System.Version. + /// The Il2Cpp version to change. + /// A with the same value. internal static Version Cast(this Il2CppSystem.Version self) { return new(self.ToString()); } /// - /// Synchronously unwraps the result of a Task. + /// Waits for a task to complete and gets its result. + /// The method blocks the thread that calls it. /// - /// The result type of the Task. - /// The Task to unwrap. - /// The result of the Task. + /// The type of the result of the task. + /// The task to wait for. + /// The result of the task. internal static T UnwrapAsync(this Task self) { return self.GetAwaiter().GetResult(); } /// - /// Removes the revision component from a Version. + /// Makes a copy of a version without the revision part. /// - /// The Version to modify. - /// A new Version with the revision set to -1. + /// The version to copy. + /// A new version with the same major, minor and build parts, and no revision part. internal static Version CutRevision(this Version self) { return new(self.Major, self.Minor, self.Build); } /// - /// Compares two version strings to see if the first is older or equal to the second. - /// Pre-release tags follow semantic-version rules: the part after the first dash is - /// split on dots, purely numeric identifiers compare numerically and sort before - /// alphanumeric ones, and a longer identifier list is newer. A version with a - /// pre-release tag is always older than the same version without one. + /// Compares two version strings. + /// The method first compares the core versions, which are the parts before the first dash. + /// If the core versions are equal, it compares the pre-release tags with semantic version rules. + /// A version with a pre-release tag is older than the same version without a tag. /// /// The first version string. /// The second version string. - /// True if version1 is older or equal to version2, false otherwise. + /// True if is older than or equal to , false if it is newer. internal static bool IsVersionOlderOrEqual(this string version1, string version2) { Version core1 = ParseVersion(version1, out string? pre1); @@ -98,6 +111,13 @@ internal static bool IsVersionOlderOrEqual(this string version1, string version2 return ComparePreRelease(pre1, pre2) <= 0; } + /// + /// Splits a version string into a core version and a pre-release tag. + /// The pre-release tag is the text after the first dash. + /// + /// The version string to parse. + /// The pre-release tag, or null if there is no dash or no text after the dash. + /// The core version, which is the text before the first dash. private static Version ParseVersion(string version, out string? preRelease) { int dash = version.IndexOf('-'); @@ -112,6 +132,15 @@ private static Version ParseVersion(string version, out string? preRelease) return new Version(version[..dash]); } + /// + /// Compares two pre-release tags with semantic version rules. + /// A null tag (no pre-release) is newer than a tag that is not null. + /// The method splits each tag at the dots and compares the identifiers in sequence. + /// If all shared identifiers are equal, the tag with more identifiers is newer. + /// + /// The first pre-release tag, or null. + /// The second pre-release tag, or null. + /// A negative value if is older, zero if the tags are equal, or a positive value if is newer. private static int ComparePreRelease(string? left, string? right) { if (left == null && right == null) return 0; @@ -130,84 +159,23 @@ private static int ComparePreRelease(string? left, string? right) return leftIds.Length.CompareTo(rightIds.Length); } + /// + /// Compares two identifiers of a pre-release tag. + /// The method compares two numeric identifiers as numbers. + /// A numeric identifier is older than an identifier that contains other characters. + /// The method compares two identifiers that are not numeric by ordinal string order. + /// + /// The first identifier. + /// The second identifier. + /// A negative value if is older, zero if the identifiers are equal, or a positive value if is newer. private static int CompareIdentifier(string left, string right) { bool leftNumeric = left.Length > 0 && left.All(char.IsDigit); bool rightNumeric = right.Length > 0 && right.All(char.IsDigit); if (leftNumeric && rightNumeric) - return long.Parse(left).CompareTo(long.Parse(right)); + return long.Parse(left, CultureInfo.InvariantCulture).CompareTo(long.Parse(right, CultureInfo.InvariantCulture)); if (leftNumeric) return -1; if (rightNumeric) return 1; return string.Compare(left, right, StringComparison.Ordinal); } - - /// - /// Gets the style name for a tribe and skin combination. - /// - /// The tribe. - /// The skin. - /// The style name. - internal static string GetStyle(TribeType tribe, SkinType skin) - { - return skin != SkinType.Default ? EnumCache.GetName(skin) : EnumCache.GetName(tribe); - } - - /// - /// Formats a sprite name to match the enum naming convention. - /// This is a workaround for inconsistencies in the game's sprite naming. - /// - /// The original sprite name. - /// The formatted sprite name. - internal static string FormatSpriteName(string baseName) // I cant believe i had to do this shit #MIDJIWANFIXYOURSHITCODE - { - // This method is necessary because the sprite names in the game's data do not always - // match the names in the corresponding enums. This method replaces the hardcoded sprite - // names with the enum names to ensure consistency. - baseName = baseName.Replace(SpriteData.IMPROVEMENT_AQUA_FARM, EnumCache.GetName(ImprovementData.Type.Aquafarm)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_ATOLL, EnumCache.GetName(ImprovementData.Type.Atoll)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_BURN_FOREST, EnumCache.GetName(ImprovementData.Type.BurnForest)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_CLEAR_FOREST, EnumCache.GetName(ImprovementData.Type.ClearForest)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_CUSTOMS_HOUSE, EnumCache.GetName(ImprovementData.Type.CustomsHouse)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_FARM, EnumCache.GetName(ImprovementData.Type.Farm)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_FOREST_TEMPLE, EnumCache.GetName(ImprovementData.Type.ForestTemple)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_FORGE, EnumCache.GetName(ImprovementData.Type.Forge)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_GROW_FOREST, EnumCache.GetName(ImprovementData.Type.GrowForest)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_ICE_BANK, EnumCache.GetName(ImprovementData.Type.IceBank)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_ICE_PORT, EnumCache.GetName(ImprovementData.Type.Outpost)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_ICE_TEMPLE, EnumCache.GetName(ImprovementData.Type.IceTemple)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_LUMBER_HUT, EnumCache.GetName(ImprovementData.Type.LumberHut)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_MARKET, EnumCache.GetName(ImprovementData.Type.Market)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_MINE, EnumCache.GetName(ImprovementData.Type.Mine)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_MOUNTAIN_TEMPLE, EnumCache.GetName(ImprovementData.Type.MountainTemple)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_PORT, EnumCache.GetName(ImprovementData.Type.Port)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_ROAD, EnumCache.GetName(ImprovementData.Type.Road)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_RUIN, EnumCache.GetName(ImprovementData.Type.Ruin)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_SANCTUARY, EnumCache.GetName(ImprovementData.Type.Sanctuary)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_SAWMILL, EnumCache.GetName(ImprovementData.Type.Sawmill)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_TEMPLE, EnumCache.GetName(ImprovementData.Type.Temple)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_WATER_TEMPLE, EnumCache.GetName(ImprovementData.Type.WaterTemple)); - baseName = baseName.Replace(SpriteData.IMPROVEMENT_WINDMILL, EnumCache.GetName(ImprovementData.Type.Windmill)); - - baseName = baseName.Replace(SpriteData.RESOURCE_AQUACROP, EnumCache.GetName(ResourceData.Type.AquaCrop)); - baseName = baseName.Replace(SpriteData.RESOURCE_CROP, EnumCache.GetName(ResourceData.Type.Crop)); - baseName = baseName.Replace(SpriteData.RESOURCE_FISH, EnumCache.GetName(ResourceData.Type.Fish)); - baseName = baseName.Replace(SpriteData.RESOURCE_FRUIT, EnumCache.GetName(ResourceData.Type.Fruit)); - baseName = baseName.Replace(SpriteData.RESOURCE_GAME, EnumCache.GetName(ResourceData.Type.Game)); - baseName = baseName.Replace(SpriteData.RESOURCE_METAL, EnumCache.GetName(ResourceData.Type.Metal)); - baseName = baseName.Replace(SpriteData.RESOURCE_SPORES, EnumCache.GetName(ResourceData.Type.Spores)); - baseName = baseName.Replace(SpriteData.RESOURCE_STARFISH, EnumCache.GetName(ResourceData.Type.Starfish)); - baseName = baseName.Replace(SpriteData.RESOURCE_WHALE, EnumCache.GetName(ResourceData.Type.Whale)); - - baseName = baseName.Replace(SpriteData.TILE_FIELD, EnumCache.GetName(TerrainData.Type.Field)); - baseName = baseName.Replace(SpriteData.TILE_FOREST, EnumCache.GetName(TerrainData.Type.Forest)); - baseName = baseName.Replace(SpriteData.TILE_ICE, EnumCache.GetName(TerrainData.Type.Ice)); - baseName = baseName.Replace(SpriteData.TILE_MOUNTAIN, EnumCache.GetName(TerrainData.Type.Mountain)); - baseName = baseName.Replace(SpriteData.TILE_OCEAN, EnumCache.GetName(TerrainData.Type.Ocean)); - baseName = baseName.Replace(SpriteData.TILE_UNKNOWN, EnumCache.GetName(TerrainData.Type.Field)); - baseName = baseName.Replace(SpriteData.TILE_WATER, EnumCache.GetName(TerrainData.Type.Water)); - baseName = baseName.Replace(SpriteData.TILE_WETLAND, EnumCache.GetName(TerrainData.Type.Field) + "_flooded"); - - baseName = baseName.Replace("UI_", ""); - return baseName; - } } diff --git a/tests/CompatibilityTests.cs b/tests/CompatibilityTests.cs new file mode 100644 index 0000000..8768a6e --- /dev/null +++ b/tests/CompatibilityTests.cs @@ -0,0 +1,134 @@ +using System.Text; +using PolyMod; +using PolyMod.Managers; + +namespace Tests; + +public class CompatibilityTests +{ + private static Mod MakeModWithFiles(string id, Version version, params (string Name, string Content)[] files) + { + List modFiles = new(); + foreach ((string name, string content) in files) + modFiles.Add(new Mod.File(name, Encoding.UTF8.GetBytes(content))); + + Mod.Manifest manifest = new(id, null, null, version, new[] { "author" }, null); + return new Mod(manifest, Mod.Status.Success, modFiles); + } + + // The launcher computes this same value from the mod's .polymod archive. If this literal has to + // change, PolyModLauncher's ModChecksum must change with it or multiplayer checks will disagree. + [Fact] + public void ModChecksumMatchesTheLauncher() + { + Mod mod = MakeModWithFiles( + "testmod", + new Version(1, 2, 3), + ("sprites.json", "{\"a\":1}"), + ("nested/thing.txt", "hello world"), + ("code.dll", "not really a dll")); + + Assert.Equal( + "34A44D3156F856C4A6CACB16379B529E797230E7F1DB9A32E1E3682D416405AC", + Compatibility.ComputeModChecksum(mod)); + } + + [Fact] + public void ModChecksumIgnoresFileOrder() + { + Mod ordered = MakeModWithFiles( + "testmod", + new Version(1, 0, 0), + ("a.txt", "first"), + ("b.txt", "second")); + Mod reversed = MakeModWithFiles( + "testmod", + new Version(1, 0, 0), + ("b.txt", "second"), + ("a.txt", "first")); + + Assert.Equal( + Compatibility.ComputeModChecksum(ordered), + Compatibility.ComputeModChecksum(reversed)); + } + + [Fact] + public void ModChecksumChangesWithFileContents() + { + Mod original = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "first")); + Mod edited = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "firsT")); + + Assert.NotEqual( + Compatibility.ComputeModChecksum(original), + Compatibility.ComputeModChecksum(edited)); + } + + [Fact] + public void ModChecksumChangesWithVersion() + { + Mod original = MakeModWithFiles("testmod", new Version(1, 0, 0), ("a.txt", "first")); + Mod bumped = MakeModWithFiles("testmod", new Version(1, 0, 1), ("a.txt", "first")); + + Assert.NotEqual( + Compatibility.ComputeModChecksum(original), + Compatibility.ComputeModChecksum(bumped)); + } + + [Fact] + public void GlobalChecksumIgnoresClientOnlyMods() + { + Mod shared = MakeModWithFiles("sharedmod", new Version(1, 0, 0), ("a.txt", "first")); + + Dictionary withoutClient = new() { { shared.id, shared } }; + Compatibility.ComputeChecksums(withoutClient); + string before = Compatibility.checksum; + + Mod clientOnly = MakeModWithFiles("clientmod", new Version(1, 0, 0), ("b.txt", "second")); + clientOnly.client = true; + + Dictionary withClient = new() + { + { shared.id, shared }, + { clientOnly.id, clientOnly }, + }; + Compatibility.ComputeChecksums(withClient); + + Assert.Equal(before, Compatibility.checksum); + } + + // The game deletes saves through APIs that hand the id over as a Guid in some places and as a + // string in others. If those produced different keys the stored checksum would never be purged. + [Fact] + public void GameIdNormalizesAcrossTheFormsTheGameUses() + { + Guid gameId = Guid.Parse("3F2504E0-4F89-11D3-9A0C-0305E82C3301"); + string expected = "3f2504e0-4f89-11d3-9a0c-0305e82c3301"; + + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId)); + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString())); + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString().ToUpperInvariant())); + Assert.Equal(expected, Compatibility.NormalizeGameId(gameId.ToString("B"))); + } + + [Fact] + public void GlobalChecksumIgnoresModOrder() + { + Mod first = MakeModWithFiles("alpha", new Version(1, 0, 0), ("a.txt", "first")); + Mod second = MakeModWithFiles("beta", new Version(1, 0, 0), ("b.txt", "second")); + + Compatibility.ComputeChecksums(new Dictionary + { + { first.id, first }, + { second.id, second }, + }); + string ordered = Compatibility.checksum; + + Compatibility.ComputeChecksums(new Dictionary + { + { second.id, second }, + { first.id, first }, + }); + + Assert.Equal(ordered, Compatibility.checksum); + } +}