refactor: reorganize engine-based structure and add agent rules
- Engines/ 配下へエンジン別に再編 (Common/Rgss/Tkool/Tyrano/Wolf/Unity/Nwjs) - ゲーム個別処理を Engines/<Engine>/Games/<GameName>/ へ分離し、共通処理から明示呼び出し - 外部ツールを Engines/<Engine>/Tools/ へ移動し、AppPathHelper 経由で解決 - 旧 Tools/ 直下参照と不要な参照ファイル/バックアップを削除 - エージェント規則 AGENTS.md を追加し、README から参照 - publish.ps1 を Engines/<Engine>/Tools/ の再帰配置に対応
This commit is contained in:
1 parent
0d11039ee9
commit
8cea2a147d
47 files changed
+2976
-176
No files matched your search
@@ -0,0 +1,209 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using GameLauncher.Helpers;
|
||||
using GameLauncher.Models;
|
||||
using GameLauncher.Engines.Tkool;
|
||||
|
||||
namespace GameLauncher.Engines.Wolf
|
||||
{
|
||||
/// <summary>
|
||||
/// ウディタ(WOLF RPGエディター)の Data.wolf アーカイブの解凍・抽出・状態管理サービス
|
||||
/// </summary>
|
||||
public class WolfArchiveService
|
||||
{
|
||||
/// <summary>
|
||||
/// 指定されたゲームフォルダ内に Data.wolf または .wolf アーカイブが存在するか判定します。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定されたゲームフォルダ内に Data.wolf の解凍先フォルダ(Data フォルダ)が存在するか判定します。
|
||||
/// </summary>
|
||||
public bool IsExtracted(string gameDirectory)
|
||||
{
|
||||
if (string.IsNullOrEmpty(gameDirectory) || !Directory.Exists(gameDirectory))
|
||||
return false;
|
||||
|
||||
var dataDir = Path.Combine(gameDirectory, "Data");
|
||||
return Directory.Exists(dataDir);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 有効な Wolf 解凍ツールの実行ファイルパスを取得します。
|
||||
/// </summary>
|
||||
public string? ResolveExtractorPath(string? customPath)
|
||||
{
|
||||
// 1. ユーザー指定パス
|
||||
if (!string.IsNullOrWhiteSpace(customPath) && File.Exists(customPath))
|
||||
{
|
||||
return customPath;
|
||||
}
|
||||
|
||||
// 2. エンジン別ツールフォルダ (Engines\Wolf\Tools\UberWolfCli.exe) を優先解決
|
||||
foreach (var toolName in new[] { "UberWolfCli.exe", "UberWolf.exe", "WolfDec.exe" })
|
||||
{
|
||||
var resolved = AppPathHelper.ResolveEngineTool("Wolf", toolName);
|
||||
if (!string.IsNullOrEmpty(resolved) && File.Exists(resolved))
|
||||
{
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Data.wolf を解凍・抽出します。
|
||||
/// </summary>
|
||||
public async Task<(bool success, string message)> ExtractArchiveAsync(
|
||||
TkoolGameItem game,
|
||||
string? customExtractorPath,
|
||||
IProgress<string>? 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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解凍された Data フォルダを Backups フォルダに退避し、元の Data.wolf 優先読み込み状態に復元します。
|
||||
/// </summary>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using GameLauncher.Helpers;
|
||||
using GameLauncher.Models;
|
||||
using GameLauncher.Engines.Tkool;
|
||||
|
||||
namespace GameLauncher.Engines.Wolf
|
||||
{
|
||||
/// <summary>
|
||||
/// ウディタ(WOLF RPGエディター)向けのプロキシDLL(メモリフック/スピードハック)
|
||||
/// およびデバッグモード(テストプレイモード)管理サービス
|
||||
/// </summary>
|
||||
public class WolfModService
|
||||
{
|
||||
public const string ProxyDllName = "version.dll";
|
||||
public const string ConfigFileName = "speedhack_config.json";
|
||||
public const string GameExeBackupSuffix = ".original_launcher_backup";
|
||||
|
||||
/// <summary>
|
||||
/// プロキシDLL(version.dll)がゲームフォルダ内に配置されているか判定します。
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// プロキシDLL(メモリフック/スピードハック)をゲームフォルダに適用します。
|
||||
/// </summary>
|
||||
/// <param name="game">対象のウディタゲーム</param>
|
||||
/// <param name="baseSpeed">基本スピード倍率(1.0〜10.0)</param>
|
||||
/// <param name="toggleSpeed">F6キー押下時のトグルスピード倍率(3.0など)</param>
|
||||
/// <param name="holdSpeed">Ctrlキー押下時の早送り倍率(5.0など)</param>
|
||||
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(Engines\\Wolf\\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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// プロキシDLLをゲームフォルダから削除し、初期状態に完全復元します。
|
||||
/// </summary>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 全ての改造(プロキシDLL、パッチ等)を解除し、ゲームを完全に元に戻します。
|
||||
/// </summary>
|
||||
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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// speedhack-rs の version.dll の配置パスを探索・解決します。
|
||||
/// </summary>
|
||||
private string? ResolveProxyDllPath()
|
||||
{
|
||||
// エンジン別ツールフォルダ (Engines\Wolf\Tools\speedhack-i686\version.dll) を優先解決
|
||||
var resolved = AppPathHelper.ResolveEngineTool("Wolf", Path.Combine("speedhack-i686", ProxyDllName));
|
||||
if (!string.IsNullOrEmpty(resolved) && File.Exists(resolved))
|
||||
{
|
||||
return resolved;
|
||||
}
|
||||
|
||||
// 互換: プロキシDLL直置きのケース
|
||||
var direct = AppPathHelper.ResolveEngineTool("Wolf", ProxyDllName);
|
||||
if (!string.IsNullOrEmpty(direct) && File.Exists(direct))
|
||||
{
|
||||
return direct;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// speedhack_config.json の JSON 文字列を生成します。
|
||||
/// </summary>
|
||||
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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.Engines.Wolf
|
||||
{
|
||||
/// <summary>
|
||||
/// ウディタ(WOLF RPGエディター)セーブデータ内の1つの変数項目
|
||||
/// </summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ウディタセーブデータ内の可変データベース項目
|
||||
/// </summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ウディタセーブデータ内の文字列項目
|
||||
/// </summary>
|
||||
public class WolfStringItem
|
||||
{
|
||||
public int Offset { get; set; }
|
||||
public int Length { get; set; }
|
||||
public string Value { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パース済みウディタセーブデータ
|
||||
/// </summary>
|
||||
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<WolfVariableItem> Variables { get; set; } = [];
|
||||
public List<WolfDbItem> DatabaseItems { get; set; } = [];
|
||||
public List<WolfStringItem> Strings { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// WOLF RPGエディターのセーブデータ(SaveXX.sav)の復号・暗号化・解析・編集サービス
|
||||
/// </summary>
|
||||
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 { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定されたゲームディレクトリからセーブデータファイル一覧を取得します。
|
||||
/// </summary>
|
||||
public List<string> GetSaveFiles(string gameDirectory)
|
||||
{
|
||||
var result = new List<string>();
|
||||
if (string.IsNullOrEmpty(gameDirectory) || !Directory.Exists(gameDirectory))
|
||||
return result;
|
||||
|
||||
var searchDirs = new List<string> { 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 暗号化されたウディタセーブデータを復号します。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 復号状態のウディタセーブデータを暗号化します(チェックサム自動更新付き)。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// セーブファイルを読み込み、復号してパースします。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 文字列の検出スキャン
|
||||
/// </summary>
|
||||
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 { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 変数テーブルのスキャン(32bit整数群)
|
||||
/// </summary>
|
||||
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
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// セーブファイルをバックアップしてから上書き保存します。
|
||||
/// バックアップは必ず Z:\自作ソフト\GameLauncher\Backups に保存されます。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// セーブデータのバックアップを作成します。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// セーブデータを JSON 形式でエクスポートします。
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSON 形式の編集内容をセーブデータモデルへインポート・反映します。
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user