diff --git a/Services/WolfArchiveService.cs b/Services/WolfArchiveService.cs new file mode 100644 index 0000000..baeaca2 --- /dev/null +++ b/Services/WolfArchiveService.cs @@ -0,0 +1,217 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GameLauncher.Helpers; +using GameLauncher.Models; + +namespace GameLauncher.Services +{ + /// + /// ウディタ(WOLF RPGエディター)の Data.wolf アーカイブの解凍・抽出・状態管理サービス + /// + public class WolfArchiveService + { + /// + /// 指定されたゲームフォルダ内に Data.wolf または .wolf アーカイブが存在するか判定します。 + /// + public bool HasWolfArchive(string gameDirectory) + { + if (string.IsNullOrEmpty(gameDirectory) || !Directory.Exists(gameDirectory)) + return false; + + var dataWolf = Path.Combine(gameDirectory, "Data.wolf"); + if (File.Exists(dataWolf)) return true; + + try + { + return Directory.EnumerateFiles(gameDirectory, "*.wolf", SearchOption.TopDirectoryOnly).Any(); + } + catch + { + return false; + } + } + + /// + /// 指定されたゲームフォルダ内に Data.wolf の解凍先フォルダ(Data フォルダ)が存在するか判定します。 + /// + public bool IsExtracted(string gameDirectory) + { + if (string.IsNullOrEmpty(gameDirectory) || !Directory.Exists(gameDirectory)) + return false; + + var dataDir = Path.Combine(gameDirectory, "Data"); + return Directory.Exists(dataDir); + } + + /// + /// 有効な Wolf 解凍ツールの実行ファイルパスを取得します。 + /// + public string? ResolveExtractorPath(string? customPath) + { + // 1. ユーザー指定パス + if (!string.IsNullOrWhiteSpace(customPath) && File.Exists(customPath)) + { + return customPath; + } + + // 2. ランチャー直下の Tools\UberWolfCli.exe + var exeDir = AppPathHelper.GetExeDirectory(); + var candidates = new[] + { + Path.Combine(exeDir, "Tools", "UberWolfCli.exe"), + Path.Combine(exeDir, "Tools", "UberWolf.exe"), + Path.Combine(exeDir, "Tools", "WolfDec.exe"), + @"C:\VS2026\GameLauncher\Tools\UberWolfCli.exe", + @"Z:\自作ソフト\GameLauncher\Tools\UberWolfCli.exe" + }; + + foreach (var candidate in candidates) + { + if (File.Exists(candidate)) + { + return candidate; + } + } + + return null; + } + + /// + /// Data.wolf を解凍・抽出します。 + /// + public async Task<(bool success, string message)> ExtractArchiveAsync( + TkoolGameItem game, + string? customExtractorPath, + IProgress? progress = null) + { + var gameDir = game.RootDirectory; + if (!Directory.Exists(gameDir)) + { + return (false, "ゲームのルートディレクトリが見つかりません。"); + } + + var extractorPath = ResolveExtractorPath(customExtractorPath); + if (string.IsNullOrEmpty(extractorPath) || !File.Exists(extractorPath)) + { + return (false, "Wolf RPG アーカイブ解凍ツール(UberWolfCli.exe / WolfDec.exe)が見つかりません。設定ダイアログからツールのパスを指定してください。"); + } + + // 解凍対象の探索 (Data.wolf または Game.exe) + var targetFile = Path.Combine(gameDir, "Data.wolf"); + if (!File.Exists(targetFile)) + { + var wolfFiles = Directory.GetFiles(gameDir, "*.wolf"); + if (wolfFiles.Length > 0) + { + targetFile = wolfFiles[0]; + } + else + { + targetFile = Path.Combine(gameDir, "Game.exe"); + } + } + + if (!File.Exists(targetFile)) + { + return (false, "解凍対象の Data.wolf または Game.exe が見つかりません。"); + } + + progress?.Report($"[解凍開始] ツール: {Path.GetFileName(extractorPath)} 対象: {Path.GetFileName(targetFile)}"); + + try + { + // UberWolfCli.exe の場合は -o (上書き) -u (プロテクト解除) を渡す + var isUberWolf = Path.GetFileName(extractorPath).Contains("UberWolf", StringComparison.OrdinalIgnoreCase); + var arguments = isUberWolf + ? $"-o -u \"{targetFile}\"" + : $"\"{targetFile}\""; + + var psi = new ProcessStartInfo + { + FileName = extractorPath, + Arguments = arguments, + WorkingDirectory = gameDir, + CreateNoWindow = true, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + + using var process = new Process { StartInfo = psi }; + var outputLog = new System.Text.StringBuilder(); + + process.OutputDataReceived += (_, e) => + { + if (!string.IsNullOrEmpty(e.Data)) + { + outputLog.AppendLine(e.Data); + progress?.Report(e.Data); + } + }; + process.ErrorDataReceived += (_, e) => + { + if (!string.IsNullOrEmpty(e.Data)) + { + outputLog.AppendLine(e.Data); + progress?.Report($"[情報] {e.Data}"); + } + }; + + process.Start(); + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + + await process.WaitForExitAsync(); + + var dataDir = Path.Combine(gameDir, "Data"); + if (Directory.Exists(dataDir) && Directory.EnumerateFileSystemEntries(dataDir).Any()) + { + progress?.Report($"[解凍完了] Data フォルダへの抽出に成功しました: {dataDir}"); + return (true, "Data.wolf の解凍・抽出が完了しました。Data フォルダのファイルを直接編集・改造できます。"); + } + else + { + return (false, $"解凍処理は終了しましたが、Data フォルダが確認できませんでした。\nログ: {outputLog}"); + } + } + catch (Exception ex) + { + return (false, $"解凍処理中に例外が発生しました: {ex.Message}"); + } + } + + /// + /// 解凍された Data フォルダを Backups フォルダに退避し、元の Data.wolf 優先読み込み状態に復元します。 + /// + public (bool success, string message) RestoreArchiveState(TkoolGameItem game) + { + var gameDir = game.RootDirectory; + var dataDir = Path.Combine(gameDir, "Data"); + + if (!Directory.Exists(dataDir)) + { + return (true, "Data フォルダは存在しないため、既に元のアーカイブ読み込み状態です。"); + } + + try + { + // バックアップ保存先(Backups フォルダ) + var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory); + var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + var backupDataDir = Path.Combine(backupDir, $"Data_Extracted_{timestamp}"); + + // Data フォルダを Backups へ移動(元に戻す) + Directory.Move(dataDir, backupDataDir); + + return (true, $"解凍されていた Data フォルダを Backups フォルダへ退避しました。\n(退避先: {backupDataDir})\n元の Data.wolf アーカイブ優先読み込みに復元されました。"); + } + catch (Exception ex) + { + return (false, $"復元処理中にエラーが発生しました: {ex.Message}"); + } + } + } +} diff --git a/Services/WolfModService.cs b/Services/WolfModService.cs new file mode 100644 index 0000000..2cbb3b2 --- /dev/null +++ b/Services/WolfModService.cs @@ -0,0 +1,224 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Text.Json; +using GameLauncher.Helpers; +using GameLauncher.Models; + +namespace GameLauncher.Services +{ + /// + /// ウディタ(WOLF RPGエディター)向けのプロキシDLL(メモリフック/スピードハック) + /// およびデバッグモード(テストプレイモード)管理サービス + /// + public class WolfModService + { + public const string ProxyDllName = "version.dll"; + public const string ConfigFileName = "speedhack_config.json"; + public const string GameExeBackupSuffix = ".original_launcher_backup"; + + /// + /// プロキシDLL(version.dll)がゲームフォルダ内に配置されているか判定します。 + /// + public bool IsProxyDllInstalled(TkoolGameItem game) + { + if (string.IsNullOrEmpty(game.RootDirectory) || !Directory.Exists(game.RootDirectory)) + return false; + + var dllPath = Path.Combine(game.RootDirectory, ProxyDllName); + return File.Exists(dllPath); + } + + /// + /// プロキシDLL(メモリフック/スピードハック)をゲームフォルダに適用します。 + /// + /// 対象のウディタゲーム + /// 基本スピード倍率(1.0〜10.0) + /// F6キー押下時のトグルスピード倍率(3.0など) + /// Ctrlキー押下時の早送り倍率(5.0など) + public (bool success, string message) ApplyProxyDll( + TkoolGameItem game, + double baseSpeed = 1.0, + double toggleSpeed = 3.0, + double holdSpeed = 5.0) + { + var gameDir = game.RootDirectory; + if (!Directory.Exists(gameDir)) + return (false, "ゲームディレクトリが見つかりません。"); + + try + { + // 1. プロキシDLL本体の探索 (Tools\speedhack-i686\version.dll) + var sourceDllPath = ResolveProxyDllPath(); + if (string.IsNullOrEmpty(sourceDllPath) || !File.Exists(sourceDllPath)) + { + return (false, "プロキシDLL(Tools\\speedhack-i686\\version.dll)が見つかりません。"); + } + + var targetDllPath = Path.Combine(gameDir, ProxyDllName); + var targetConfigPath = Path.Combine(gameDir, ConfigFileName); + + // 2. 元々同名DLLが存在していた場合は Backups フォルダに退避 + var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory); + var backupDllPath = Path.Combine(backupDir, ProxyDllName + GameExeBackupSuffix); + + if (File.Exists(targetDllPath) && !File.Exists(backupDllPath)) + { + File.Copy(targetDllPath, backupDllPath, overwrite: true); + } + + // 3. プロキシDLLをコピー配置 + File.Copy(sourceDllPath, targetDllPath, overwrite: true); + + // 4. speedhack_config.json の生成・書き込み + var configContent = GenerateSpeedhackConfig(baseSpeed, toggleSpeed, holdSpeed); + File.WriteAllText(targetConfigPath, configContent, new UTF8Encoding(false)); + + game.WolfProxyDll = true; + game.IsModded = true; + return (true, $"プロキシDLL(version.dll)を配置しました。\n・[F6] キー: {toggleSpeed:0.#}倍速 トグル\n・[Ctrl] キー: {holdSpeed:0.#}倍速 早送り\n・通常速度: {baseSpeed:0.#}倍"); + } + catch (Exception ex) + { + return (false, $"プロキシDLLの適用に失敗しました: {ex.Message}"); + } + } + + /// + /// プロキシDLLをゲームフォルダから削除し、初期状態に完全復元します。 + /// + public (bool success, string message) RemoveProxyDll(TkoolGameItem game) + { + var gameDir = game.RootDirectory; + if (!Directory.Exists(gameDir)) + return (false, "ゲームディレクトリが見つかりません。"); + + try + { + var targetDllPath = Path.Combine(gameDir, ProxyDllName); + var targetConfigPath = Path.Combine(gameDir, ConfigFileName); + + var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory); + var backupDllPath = Path.Combine(backupDir, ProxyDllName + GameExeBackupSuffix); + + // 1. プロキシDLLの削除またはオリジナル復元 + if (File.Exists(backupDllPath)) + { + File.Copy(backupDllPath, targetDllPath, overwrite: true); + try { File.Delete(backupDllPath); } catch { } + } + else if (File.Exists(targetDllPath)) + { + File.Delete(targetDllPath); + } + + // 2. 設定ファイルの削除 + if (File.Exists(targetConfigPath)) + { + try { File.Delete(targetConfigPath); } catch { } + } + + game.WolfProxyDll = false; + game.IsModded = false; + return (true, "プロキシDLL(version.dll)を解除し、ゲームを元の状態に復元しました。"); + } + catch (Exception ex) + { + return (false, $"プロキシDLLの解除に失敗しました: {ex.Message}"); + } + } + + /// + /// デバッグ(テストプレイ)モード用の起動コマンドライン引数を取得します。 + /// ウディタ公式仕様の引数(Test_Of_Main Use_Debug_Window) + /// + public string GetDebugArguments(bool useDebugWindow = true) + { + return useDebugWindow ? "Test_Of_Main Use_Debug_Window" : "Test_Of_Main"; + } + + /// + /// 全ての改造(プロキシDLL、パッチ等)を解除し、ゲームを完全に元に戻します。 + /// + public (bool success, string message) RestoreAllMods(TkoolGameItem game) + { + var sb = new StringBuilder(); + + // 1. プロキシDLLの解除 + var (dllSuccess, dllMsg) = RemoveProxyDll(game); + sb.AppendLine(dllMsg); + + // 2. Game.exe バックアップからの復元(存在する場合) + var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory); + var backupExePath = Path.Combine(backupDir, "Game.exe" + GameExeBackupSuffix); + var gameExePath = Path.Combine(game.RootDirectory, "Game.exe"); + + if (File.Exists(backupExePath)) + { + try + { + File.Copy(backupExePath, gameExePath, overwrite: true); + sb.AppendLine("・Game.exe をオリジナルバックアップから復元しました。"); + } + catch (Exception ex) + { + sb.AppendLine($"・Game.exe の復元中にエラーが発生しました: {ex.Message}"); + } + } + + return (true, sb.ToString().Trim()); + } + + /// + /// speedhack-rs の version.dll の配置パスを探索・解決します。 + /// + private string? ResolveProxyDllPath() + { + var exeDir = AppPathHelper.GetExeDirectory(); + var candidates = new[] + { + Path.Combine(exeDir, "Tools", "speedhack-i686", ProxyDllName), + Path.Combine(exeDir, "Tools", ProxyDllName), + @"C:\VS2026\GameLauncher\Tools\speedhack-i686\version.dll", + @"Z:\自作ソフト\GameLauncher\Tools\speedhack-i686\version.dll" + }; + + foreach (var path in candidates) + { + if (File.Exists(path)) return path; + } + + return null; + } + + /// + /// speedhack_config.json の JSON 文字列を生成します。 + /// + private string GenerateSpeedhackConfig(double baseSpeed, double toggleSpeed, double holdSpeed) + { + var obj = new + { + console = false, + base_speed = baseSpeed, + speed_states = new object[] + { + new + { + keys = new[] { "F6" }, + speed = toggleSpeed, + is_toggle = true + }, + new + { + keys = new[] { "Control" }, + speed = holdSpeed, + is_toggle = false + } + } + }; + + return JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true }); + } + } +} diff --git a/Services/WolfSaveService.cs b/Services/WolfSaveService.cs new file mode 100644 index 0000000..c329532 --- /dev/null +++ b/Services/WolfSaveService.cs @@ -0,0 +1,401 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using GameLauncher.Helpers; + +namespace GameLauncher.Services +{ + /// + /// ウディタ(WOLF RPGエディター)セーブデータ内の1つの変数項目 + /// + public class WolfVariableItem + { + public string Category { get; set; } = "通常変数"; + public int Index { get; set; } + public string DisplayName { get; set; } = string.Empty; + public int Value { get; set; } + public int Offset { get; set; } + } + + /// + /// ウディタセーブデータ内の可変データベース項目 + /// + public class WolfDbItem + { + public string TypeName { get; set; } = string.Empty; + public int TypeId { get; set; } + public int DataId { get; set; } + public string DataName { get; set; } = string.Empty; + public int FieldId { get; set; } + public string FieldName { get; set; } = string.Empty; + public bool IsString { get; set; } + public int NumberValue { get; set; } + public string StringValue { get; set; } = string.Empty; + public int Offset { get; set; } + } + + /// + /// ウディタセーブデータ内の文字列項目 + /// + public class WolfStringItem + { + public int Offset { get; set; } + public int Length { get; set; } + public string Value { get; set; } = string.Empty; + } + + /// + /// パース済みウディタセーブデータ + /// + public class WolfSaveData + { + public string FilePath { get; set; } = string.Empty; + public string FileName { get; set; } = string.Empty; + public string GameTitle { get; set; } = string.Empty; + public ushort FileVersion { get; set; } + public bool IsUtf8 { get; set; } + public byte[] RawDecryptedBytes { get; set; } = []; + public List Variables { get; set; } = []; + public List DatabaseItems { get; set; } = []; + public List Strings { get; set; } = []; + } + + /// + /// WOLF RPGエディターのセーブデータ(SaveXX.sav)の復号・暗号化・解析・編集サービス + /// + public class WolfSaveService + { + private const int START_OFFSET = 0x14; + private static readonly uint[] INC_STEPS = [1, 2, 5]; + private static readonly uint[] ENC_INC_STEPS = [5, 2, 1]; + + static WolfSaveService() + { + // Shift-JIS (932) のサポート登録 + try + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + } + catch { } + } + + /// + /// 指定されたゲームディレクトリからセーブデータファイル一覧を取得します。 + /// + public List GetSaveFiles(string gameDirectory) + { + var result = new List(); + if (string.IsNullOrEmpty(gameDirectory) || !Directory.Exists(gameDirectory)) + return result; + + var searchDirs = new List { gameDirectory }; + var saveSubDir = Path.Combine(gameDirectory, "Save"); + if (Directory.Exists(saveSubDir)) searchDirs.Add(saveSubDir); + var saveSubDir2 = Path.Combine(gameDirectory, "save"); + if (Directory.Exists(saveSubDir2) && !searchDirs.Contains(saveSubDir2)) searchDirs.Add(saveSubDir2); + + foreach (var dir in searchDirs) + { + try + { + var files = Directory.GetFiles(dir, "*.sav") + .OrderBy(f => Path.GetFileName(f), StringComparer.OrdinalIgnoreCase); + result.AddRange(files); + } + catch { } + } + + return result.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + } + + /// + /// 暗号化されたウディタセーブデータを復号します。 + /// + public byte[] Decrypt(byte[] encryptedData) + { + if (encryptedData == null || encryptedData.Length < START_OFFSET) + return encryptedData ?? []; + + byte[] copy = (byte[])encryptedData.Clone(); + byte[] seeds = [copy[0], copy[3], copy[9]]; + + for (int i = 0; i < seeds.Length; i++) + { + uint state = seeds[i]; + int inc = (int)INC_STEPS[i]; + + for (int j = START_OFFSET; j < copy.Length; j += inc) + { + state = state * 214013 + 2531011; + int r = (int)((state >> 16) & 0x7FFF); + byte xor = (byte)((r >> 12) & 0xFF); + copy[j] ^= xor; + } + } + + return copy; + } + + /// + /// 復号状態のウディタセーブデータを暗号化します(チェックサム自動更新付き)。 + /// + public byte[] Encrypt(byte[] plainData) + { + if (plainData == null || plainData.Length < START_OFFSET) + return plainData ?? []; + + byte[] copy = (byte[])plainData.Clone(); + + // 1. チェックサムの再計算 (オフセット 0x14 からの総和を 0x02 に格納) + byte checksum = 0; + for (int i = START_OFFSET; i < copy.Length; i++) + { + checksum += copy[i]; + } + copy[0x02] = checksum; + + // 2. 暗号化 (seeds は copy[9], copy[3], copy[0] の逆順、インクリメントも 5, 2, 1) + byte[] seeds = [copy[9], copy[3], copy[0]]; + + for (int i = 0; i < seeds.Length; i++) + { + uint state = seeds[i]; + int inc = (int)ENC_INC_STEPS[i]; + + for (int j = START_OFFSET; j < copy.Length; j += inc) + { + state = state * 214013 + 2531011; + int r = (int)((state >> 16) & 0x7FFF); + byte xor = (byte)((r >> 12) & 0xFF); + copy[j] ^= xor; + } + } + + return copy; + } + + /// + /// セーブファイルを読み込み、復号してパースします。 + /// + public WolfSaveData LoadSave(string filePath) + { + if (!File.Exists(filePath)) + throw new FileNotFoundException($"セーブデータファイルが見つかりません: {filePath}"); + + byte[] rawBytes = File.ReadAllBytes(filePath); + byte[] decrypted = Decrypt(rawBytes); + + var result = new WolfSaveData + { + FilePath = filePath, + FileName = Path.GetFileName(filePath), + RawDecryptedBytes = decrypted + }; + + if (decrypted.Length < 0x20) return result; + + // 文字エンコーディング判定 (オフセット6が 0x55 なら UTF-8, それ以外は Shift-JIS) + result.IsUtf8 = (decrypted[6] == 0x55); + Encoding enc = result.IsUtf8 ? Encoding.UTF8 : Encoding.GetEncoding(932); + + // ゲームタイトルの取得 (オフセット 0x15 からの文字列) + if (decrypted[0x14] == 0x19 && decrypted.Length > 0x17) + { + ushort titleLen = BitConverter.ToUInt16(decrypted, 0x15); + if (titleLen > 1 && 0x17 + titleLen <= decrypted.Length) + { + result.GameTitle = enc.GetString(decrypted, 0x17, titleLen - 1).Trim('\0'); + int nextOffset = 0x17 + titleLen; + if (nextOffset + 2 <= decrypted.Length) + { + result.FileVersion = BitConverter.ToUInt16(decrypted, nextOffset); + } + } + } + + // セーブデータ内の全文字列スキャン + ScanStrings(result, decrypted, enc); + + // セーブデータ内の通常変数スキャン + ScanVariables(result, decrypted); + + return result; + } + + /// + /// 文字列の検出スキャン + /// + private void ScanStrings(WolfSaveData model, byte[] data, Encoding enc) + { + for (int i = START_OFFSET; i < data.Length - 4; i++) + { + uint strLen = BitConverter.ToUInt32(data, i); + if (strLen >= 2 && strLen <= 128 && i + 4 + strLen <= data.Length) + { + // 末尾がNULL終端かチェック + if (data[i + 4 + strLen - 1] == 0) + { + try + { + string s = enc.GetString(data, i + 4, (int)strLen - 1); + // 意味のあるテキストか判定(2文字以上の文字、制御文字を含まない) + if (s.Length >= 2 && !s.Any(c => char.IsControl(c) && c != '\r' && c != '\n' && c != '\t')) + { + model.Strings.Add(new WolfStringItem + { + Offset = i + 4, + Length = (int)strLen - 1, + Value = s + }); + } + } + catch { } + } + } + } + } + + /// + /// 変数テーブルのスキャン(32bit整数群) + /// + private void ScanVariables(WolfSaveData model, byte[] data) + { + // 4バイト境界に沿って整数値を抽出(特に100以上の意味ありそうな数値やステータス) + int varIdx = 0; + for (int i = 0x50; i < data.Length - 4; i += 4) + { + int val = BitConverter.ToInt32(data, i); + // 範囲制限(極端に大きなゴミデータや負の値のノイズを適度にフィルタ) + if (val >= 0 && val <= 999999999) + { + model.Variables.Add(new WolfVariableItem + { + Category = "通常・内部変数", + Index = varIdx++, + DisplayName = $"変数 [0x{i:X5}]", + Value = val, + Offset = i + }); + } + } + } + + /// + /// セーブファイルをバックアップしてから上書き保存します。 + /// バックアップは必ず Z:\自作ソフト\GameLauncher\Backups に保存されます。 + /// + public string SaveToFile(WolfSaveData model, string folderName, string rootDirectory) + { + if (model == null || model.RawDecryptedBytes == null || model.RawDecryptedBytes.Length == 0) + throw new InvalidOperationException("保存対象のデータが空です。"); + + // 1. バックアップ作成 (Backups フォルダへ) + string? backupPath = BackupSaveFile(model.FilePath, folderName, rootDirectory); + + // 2. 変数・項目の変更を RawDecryptedBytes に書き戻し + foreach (var item in model.Variables) + { + if (item.Offset >= START_OFFSET && item.Offset + 4 <= model.RawDecryptedBytes.Length) + { + byte[] valBytes = BitConverter.GetBytes(item.Value); + Buffer.BlockCopy(valBytes, 0, model.RawDecryptedBytes, item.Offset, 4); + } + } + + // 3. 暗号化 & チェックサム再計算 + byte[] encrypted = Encrypt(model.RawDecryptedBytes); + + // 4. アトミック書き込み + string tempFile = model.FilePath + ".tmp_" + Guid.NewGuid().ToString("N"); + File.WriteAllBytes(tempFile, encrypted); + File.Move(tempFile, model.FilePath, overwrite: true); + + return backupPath ?? string.Empty; + } + + /// + /// セーブデータのバックアップを作成します。 + /// + public string? BackupSaveFile(string saveFilePath, string folderName, string rootDirectory) + { + if (!File.Exists(saveFilePath)) return null; + + try + { + var backupDir = AppPathHelper.GetGameBackupDirectory(folderName, rootDirectory); + if (!Directory.Exists(backupDir)) + { + Directory.CreateDirectory(backupDir); + } + + var fileName = Path.GetFileNameWithoutExtension(saveFilePath); + var ext = Path.GetExtension(saveFilePath); + var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + var destName = $"{fileName}_{timestamp}{ext}"; + var destPath = Path.Combine(backupDir, destName); + + File.Copy(saveFilePath, destPath, overwrite: true); + return destPath; + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[WolfSaveService] Backup error: {ex.Message}"); + return null; + } + } + + /// + /// セーブデータを JSON 形式でエクスポートします。 + /// + public void ExportToJson(WolfSaveData model, string jsonFilePath) + { + var dto = new + { + model.FileName, + model.GameTitle, + model.FileVersion, + model.IsUtf8, + Variables = model.Variables.Select(v => new { v.Offset, v.DisplayName, v.Value }), + Strings = model.Strings.Select(s => new { s.Offset, s.Length, s.Value }) + }; + + var options = new JsonSerializerOptions { WriteIndented = true }; + string json = JsonSerializer.Serialize(dto, options); + File.WriteAllText(jsonFilePath, json, Encoding.UTF8); + } + + /// + /// JSON 形式の編集内容をセーブデータモデルへインポート・反映します。 + /// + public void ImportFromJson(WolfSaveData model, string jsonFilePath) + { + if (!File.Exists(jsonFilePath)) + throw new FileNotFoundException($"JSONファイルが見つかりません: {jsonFilePath}"); + + string json = File.ReadAllText(jsonFilePath, Encoding.UTF8); + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + + if (root.TryGetProperty("Variables", out var varsElement) && varsElement.ValueKind == JsonValueKind.Array) + { + var varDict = model.Variables.ToDictionary(v => v.Offset, v => v); + foreach (var item in varsElement.EnumerateArray()) + { + if (item.TryGetProperty("Offset", out var offsetProp) && + item.TryGetProperty("Value", out var valProp)) + { + int offset = offsetProp.GetInt32(); + int val = valProp.GetInt32(); + if (varDict.TryGetValue(offset, out var entry)) + { + entry.Value = val; + } + } + } + } + } + } +} diff --git a/WolfSaveEditorDialog.xaml b/WolfSaveEditorDialog.xaml new file mode 100644 index 0000000..00df37b --- /dev/null +++ b/WolfSaveEditorDialog.xaml @@ -0,0 +1,322 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +