using System.IO; using AIImages.Components; using UnityEngine; using Verse; namespace AIImages.Helpers { /// /// Вспомогательный класс для работы с портретами персонажей /// public static class PawnPortraitHelper { /// /// Получить компонент портрета пешки /// public static PawnPortraitComp GetPortraitComp(Pawn pawn) { return pawn?.TryGetComp(); } /// /// Сохранить путь к портрету на пешке /// public static void SavePortraitPath(Pawn pawn, string path) { var comp = GetPortraitComp(pawn); if (comp != null) { comp.PortraitPath = path; Log.Message($"[AI Images] Saved portrait path for {pawn.Name}: {path}"); } } /// /// Получить путь к портрету пешки /// public static string GetPortraitPath(Pawn pawn) { var comp = GetPortraitComp(pawn); return comp?.PortraitPath; } /// /// Есть ли у пешки сохраненный портрет /// public static bool HasPortrait(Pawn pawn) { var comp = GetPortraitComp(pawn); return comp != null && comp.HasPortrait; } /// /// Загрузить портрет пешки как текстуру /// public static Texture2D LoadPortrait(Pawn pawn) { string path = GetPortraitPath(pawn); if (string.IsNullOrEmpty(path) || !File.Exists(path)) { return null; } try { byte[] imageData = File.ReadAllBytes(path); Texture2D texture = new Texture2D(2, 2); texture.LoadImage(imageData); return texture; } catch (System.Exception ex) { Log.Warning($"[AI Images] Failed to load portrait for {pawn.Name}: {ex.Message}"); return null; } } /// /// Очистить портрет пешки /// public static void ClearPortrait(Pawn pawn) { var comp = GetPortraitComp(pawn); if (comp != null) { comp.PortraitPath = null; } } /// /// Очистить все сгенерированные портреты /// public static int ClearAllPortraits(string savePath) { int deletedCount = 0; // Очищаем компоненты всех пешек if (Current.Game != null && Current.Game.Maps != null) { foreach (var map in Current.Game.Maps) { foreach (var pawn in map.mapPawns.AllPawns) { var comp = GetPortraitComp(pawn); if (comp != null && comp.HasPortrait) { comp.PortraitPath = null; } } } } // Удаляем файлы из директории string fullPath = Path.Combine(GenFilePaths.SaveDataFolderPath, savePath); if (Directory.Exists(fullPath)) { try { var files = Directory.GetFiles(fullPath, "*.png"); foreach (var file in files) { try { File.Delete(file); deletedCount++; } catch (System.Exception ex) { Log.Warning($"[AI Images] Failed to delete file {file}: {ex.Message}"); } } Log.Message($"[AI Images] Deleted {deletedCount} portrait files"); } catch (System.Exception ex) { Log.Error($"[AI Images] Error cleaning portraits directory: {ex.Message}"); } } return deletedCount; } } }