feat: 初回コミット (GameLauncher)

This commit is contained in:
armonica committed 2026-10-01 09:42:02 +09:00
commit 7ac4dbc825
45 files changed
+9779

No files matched your search

+608
View File
@@ -0,0 +1,608 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using GameLauncher.Models;
namespace GameLauncher.Services
{
/// <summary>
/// ASAR アーカイブ内のファイルエントリ情報
/// </summary>
public class AsarFileEntry
{
public string RelativePath { get; set; } = string.Empty;
public long Offset { get; set; }
public long Size { get; set; }
}
/// <summary>
/// ASAR の解析結果情報
/// </summary>
public class AsarInspectResult
{
public bool IsValid { get; set; }
public bool IsTkoolGame { get; set; }
public bool IsTyranoGame { get; set; }
public TkoolEngineType EngineType { get; set; } = TkoolEngineType.Unknown;
public string Title { get; set; } = string.Empty;
public string? RelativePluginsJsPath { get; set; }
public string? RelativeIndexPath { get; set; }
public long TotalFilesCount { get; set; }
public long TotalUnpackedBytes { get; set; }
public List<AsarFileEntry> FileEntries { get; set; } = [];
}
/// <summary>
/// Electron 等で利用される app.asar 形式アーカイブの解析・解凍・復元を
/// 外部ツール不要かつ純粋な C# のみで安全・高速に行うサービス
/// </summary>
public class AsarArchiveService
{
/// <summary>ASARバックアップファイルの拡張子</summary>
public const string AsarBackupSuffix = ".original_launcher_backup";
/// <summary>
/// 指定されたゲームフォルダ配下に app.asar または解凍済みバックアップが存在するか検索します。
/// </summary>
/// <param name="gameRootDir">ゲームのルートディレクトリ</param>
/// <param name="asarPath">見つかった asar ファイルパス(または元の asar パス)</param>
/// <param name="isExtracted">現在解凍済み状態かどうか</param>
/// <returns>ASARパッケージが存在するかどうか</returns>
public static bool FindAsarPackage(string gameRootDir, out string? asarPath, out bool isExtracted, out string? extractedDirPath)
{
asarPath = null;
isExtracted = false;
extractedDirPath = null;
if (string.IsNullOrEmpty(gameRootDir) || !Directory.Exists(gameRootDir))
{
return false;
}
// 検索候補パス: resources\app.asar または 直下の app.asar
var candidate1 = Path.Combine(gameRootDir, "resources", "app.asar");
var candidate2 = Path.Combine(gameRootDir, "app.asar");
// 1. 未解凍の app.asar が存在する場合
if (File.Exists(candidate1))
{
asarPath = candidate1;
extractedDirPath = Path.Combine(gameRootDir, "resources", "app");
isExtracted = Directory.Exists(extractedDirPath) && File.Exists(Path.Combine(extractedDirPath, "package.json"));
return true;
}
if (File.Exists(candidate2))
{
asarPath = candidate2;
extractedDirPath = Path.Combine(gameRootDir, "app");
isExtracted = Directory.Exists(extractedDirPath) && File.Exists(Path.Combine(extractedDirPath, "package.json"));
return true;
}
// 2. 既に解凍済みで、app.asar がリネームバックアップされている場合
var backup1 = candidate1 + AsarBackupSuffix;
var appDir1 = Path.Combine(gameRootDir, "resources", "app");
if (File.Exists(backup1) && Directory.Exists(appDir1))
{
asarPath = candidate1;
extractedDirPath = appDir1;
isExtracted = true;
return true;
}
var backup2 = candidate2 + AsarBackupSuffix;
var appDir2 = Path.Combine(gameRootDir, "app");
if (File.Exists(backup2) && Directory.Exists(appDir2))
{
asarPath = candidate2;
extractedDirPath = appDir2;
isExtracted = true;
return true;
}
return false;
}
/// <summary>
/// ASAR ファイルのヘッダを解析し、ツクールゲームであるかの判定やタイトル・plugins.js位置を抽出します。
/// </summary>
/// <param name="asarFilePath">app.asar ファイルの物理パス(またはバックアップパス)</param>
/// <param name="includeFileList">全ファイルエントリの収集を行うかどうか(解凍時用)</param>
public AsarInspectResult InspectAsar(string asarFilePath, bool includeFileList = false)
{
var result = new AsarInspectResult();
// バックアップファイルが指定された場合も対応
var targetFile = asarFilePath;
if (!File.Exists(ToExtendedPath(targetFile)) && File.Exists(ToExtendedPath(targetFile + AsarBackupSuffix)))
{
targetFile = asarFilePath + AsarBackupSuffix;
}
if (!File.Exists(ToExtendedPath(targetFile)))
{
return result;
}
try
{
using var fs = new FileStream(ToExtendedPath(targetFile), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var br = new BinaryReader(fs);
if (fs.Length < 16) return result;
uint u1 = br.ReadUInt32();
uint headerSize = br.ReadUInt32();
uint u3 = br.ReadUInt32();
uint jsonSize = br.ReadUInt32();
// 妥当性チェック
if (u1 != 4 || jsonSize == 0 || jsonSize > 100_000_000 || jsonSize > fs.Length)
{
return result;
}
long dataOffset = 8 + (long)headerSize;
byte[] jsonBytes = br.ReadBytes((int)jsonSize);
string jsonStr = Encoding.UTF8.GetString(jsonBytes);
using var doc = JsonDocument.Parse(jsonStr);
if (!doc.RootElement.TryGetProperty("files", out var filesRoot))
{
return result;
}
result.IsValid = true;
// ツクール特有ファイルを探す
string? systemJsonRelative = null;
long systemJsonOffset = -1;
long systemJsonSize = -1;
string? packageJsonRelative = null;
long packageJsonOffset = -1;
long packageJsonSize = -1;
TraverseFiles(filesRoot, "", dataOffset, fs.Length, result, includeFileList,
ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize,
ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize);
if (!string.IsNullOrEmpty(result.RelativePluginsJsPath))
{
result.IsTkoolGame = true;
}
else if (result.IsTyranoGame)
{
result.EngineType = TkoolEngineType.Tyrano;
result.RelativePluginsJsPath = result.RelativeIndexPath ?? "index.html";
}
// タイトルの抽出(System.json または package.json から)
if (systemJsonOffset >= 0 && systemJsonSize > 0 && systemJsonSize < 5_000_000)
{
try
{
fs.Seek(dataOffset + systemJsonOffset, SeekOrigin.Begin);
byte[] sBytes = new byte[systemJsonSize];
fs.ReadExactly(sBytes, 0, (int)systemJsonSize);
string sJson = Encoding.UTF8.GetString(sBytes);
var match = Regex.Match(sJson, @"""gameTitle""\s*:\s*""([^""]+)""");
if (match.Success && !string.IsNullOrWhiteSpace(match.Groups[1].Value))
{
result.Title = match.Groups[1].Value.Trim();
}
}
catch { }
}
if (string.IsNullOrEmpty(result.Title) && packageJsonOffset >= 0 && packageJsonSize > 0 && packageJsonSize < 5_000_000)
{
try
{
fs.Seek(dataOffset + packageJsonOffset, SeekOrigin.Begin);
byte[] pBytes = new byte[packageJsonSize];
fs.ReadExactly(pBytes, 0, (int)packageJsonSize);
string pJson = Encoding.UTF8.GetString(pBytes);
var matchTitle = Regex.Match(pJson, @"""title""\s*:\s*""([^""]+)""");
if (matchTitle.Success && !string.IsNullOrWhiteSpace(matchTitle.Groups[1].Value) &&
!matchTitle.Groups[1].Value.Contains("ティラノスタジオ", StringComparison.OrdinalIgnoreCase))
{
result.Title = matchTitle.Groups[1].Value.Trim();
}
else
{
var matchDesc = Regex.Match(pJson, @"""description""\s*:\s*""([^""]+)""");
if (matchDesc.Success && !string.IsNullOrWhiteSpace(matchDesc.Groups[1].Value) &&
!matchDesc.Groups[1].Value.Contains("Electron for RPG", StringComparison.OrdinalIgnoreCase) &&
!matchDesc.Groups[1].Value.Contains("TyranoScript", StringComparison.OrdinalIgnoreCase) &&
!matchDesc.Groups[1].Value.Contains("ティラノスクリプト", StringComparison.OrdinalIgnoreCase))
{
result.Title = matchDesc.Groups[1].Value.Trim();
}
else
{
var matchName = Regex.Match(pJson, @"""name""\s*:\s*""([^""]+)""");
if (matchName.Success && !string.IsNullOrWhiteSpace(matchName.Groups[1].Value) &&
!matchName.Groups[1].Value.Equals("aigisfull", StringComparison.OrdinalIgnoreCase) &&
!matchName.Groups[1].Value.Contains("tyrano", StringComparison.OrdinalIgnoreCase))
{
result.Title = matchName.Groups[1].Value.Trim();
}
}
}
}
catch { }
}
}
catch
{
// 解析失敗時は無効
result.IsValid = false;
}
return result;
}
private void TraverseFiles(
JsonElement element,
string currentPath,
long dataOffset,
long fileLength,
AsarInspectResult result,
bool includeFileList,
ref string? systemJsonRelative,
ref long systemJsonOffset,
ref long systemJsonSize,
ref string? packageJsonRelative,
ref long packageJsonOffset,
ref long packageJsonSize)
{
if (element.ValueKind != JsonValueKind.Object) return;
foreach (var prop in element.EnumerateObject())
{
string name = prop.Name;
string path = string.IsNullOrEmpty(currentPath) ? name : $"{currentPath}/{name}";
var val = prop.Value;
if (val.TryGetProperty("files", out var subFiles))
{
TraverseFiles(subFiles, path, dataOffset, fileLength, result, includeFileList,
ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize,
ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize);
}
else
{
// ファイルエントリ
long offset = 0;
if (val.TryGetProperty("offset", out var offProp))
{
if (offProp.ValueKind == JsonValueKind.String && long.TryParse(offProp.GetString(), out var o))
offset = o;
else if (offProp.ValueKind == JsonValueKind.Number && offProp.TryGetInt64(out var oNum))
offset = oNum;
}
long size = 0;
if (val.TryGetProperty("size", out var sizeProp) && sizeProp.ValueKind == JsonValueKind.Number)
{
sizeProp.TryGetInt64(out size);
}
// 異常値チェック(ダミーエントリや破損エントリのガード)
if (offset < 0 || size < 0 || dataOffset + offset + size > fileLength)
{
continue;
}
result.TotalFilesCount++;
result.TotalUnpackedBytes += size;
if (includeFileList)
{
result.FileEntries.Add(new AsarFileEntry
{
RelativePath = path,
Offset = offset,
Size = size
});
}
// plugins.js の検出
if (name.Equals("plugins.js", StringComparison.OrdinalIgnoreCase))
{
result.RelativePluginsJsPath = path;
}
// エンジン種別判定 (rmmz_core.js -> MZ, rpg_core.js -> MV, tyrano -> Tyrano)
if (name.Equals("rmmz_core.js", StringComparison.OrdinalIgnoreCase))
{
result.EngineType = TkoolEngineType.MZ;
}
else if (name.Equals("rpg_core.js", StringComparison.OrdinalIgnoreCase) && result.EngineType == TkoolEngineType.Unknown)
{
result.EngineType = TkoolEngineType.MV;
}
else if (name.Equals("tyrano.js", StringComparison.OrdinalIgnoreCase) ||
path.Contains("data/scenario", StringComparison.OrdinalIgnoreCase) ||
name.Equals("KeyConfig.js", StringComparison.OrdinalIgnoreCase))
{
result.IsTyranoGame = true;
}
if (name.Equals("index.html", StringComparison.OrdinalIgnoreCase) && result.RelativeIndexPath == null)
{
result.RelativeIndexPath = path;
}
// タイトル抽出用
if (name.Equals("System.json", StringComparison.OrdinalIgnoreCase) && systemJsonOffset < 0)
{
systemJsonRelative = path;
systemJsonOffset = offset;
systemJsonSize = size;
}
else if (name.Equals("package.json", StringComparison.OrdinalIgnoreCase) &&
!path.Contains("node_modules", StringComparison.OrdinalIgnoreCase))
{
// ルートの package.json または project/package.json を最優先
if (packageJsonOffset < 0 || path.Equals("package.json", StringComparison.OrdinalIgnoreCase))
{
packageJsonRelative = path;
packageJsonOffset = offset;
packageJsonSize = size;
}
}
}
}
}
/// <summary>
/// Windowsの260文字制限(MAX_PATH)や予約デバイス名(CON, PRN, AUX, NUL, COM1-9, LPT1-9等)による
/// Win32例外(ハンドルが無効です。: '\\.\con' 等)を回避するため、拡張パスプレフィックス \\?\ を付与します。
/// </summary>
public static string ToExtendedPath(string path)
{
if (string.IsNullOrEmpty(path)) return path;
// Windows 環境以外はそのまま
if (!OperatingSystem.IsWindows()) return path;
// 既に \\?\ または \\.\ で始まっている場合はそのまま
if (path.StartsWith(@"\\?\", StringComparison.Ordinal) || path.StartsWith(@"\\.\", StringComparison.Ordinal))
{
return path;
}
// 区切り文字を Windows 標準のバックスラッシュに統一
string normalized = path.Replace('/', '\\');
// ドライブ文字付き絶対パス (例: C:\..., Z:\...) の場合
// ※ここで Path.GetFullPath を通すと、ファイル名が con.png などの場合に Win32 が '\\.\con' に解決してしまうため、
//  直接 \\?\ を前置することで予約デバイス名の解決を完全にバイパスします。
if (normalized.Length >= 2 && char.IsLetter(normalized[0]) && normalized[1] == ':')
{
return @"\\?\" + normalized;
}
// UNC パス (例: \\server\share\...) の場合
if (normalized.StartsWith(@"\\", StringComparison.Ordinal))
{
return @"\\?\UNC\" + normalized.Substring(2);
}
// 相対パスの場合は安全に絶対パスを取得してからプレフィックスを付与
try
{
string full = Path.GetFullPath(normalized);
if (full.StartsWith(@"\\?\", StringComparison.Ordinal) || full.StartsWith(@"\\.\", StringComparison.Ordinal))
{
return full;
}
if (full.StartsWith(@"\\", StringComparison.Ordinal))
{
return @"\\?\UNC\" + full.Substring(2);
}
return @"\\?\" + full;
}
catch
{
return path;
}
}
/// <summary>
/// ASAR ファイルを解凍し、outputDir に展開します。
/// 展開成功後、元の app.asar を app.asar.original_launcher_backup にリネームして
/// Electron が確実に解凍先 app フォルダを読み込んで起動するように準備します。
/// </summary>
public async Task<(bool Success, string Message)> ExtractAsarAsync(
string asarPath,
string outputDir,
IProgress<(long extractedBytes, long totalBytes, int currentFileIndex, int totalFiles, string currentFileName)>? progress = null,
CancellationToken ct = default)
{
return await Task.Run(() =>
{
var targetAsar = asarPath;
var backupAsar = asarPath + AsarBackupSuffix;
if (!File.Exists(ToExtendedPath(targetAsar)))
{
if (File.Exists(ToExtendedPath(backupAsar)))
{
targetAsar = backupAsar;
}
else
{
return (false, $"解凍対象の asar ファイルが見つかりません: {asarPath}");
}
}
// ヘッダ詳細解析
var inspect = InspectAsar(targetAsar, includeFileList: true);
if (!inspect.IsValid || inspect.FileEntries.Count == 0)
{
return (false, "asar ファイルのヘッダ解析に失敗したか、ファイルが含まれていません。");
}
try
{
// 拡張パス(\\?\)を適用した出力先ルートディレクトリ
string extOutputDir = ToExtendedPath(Path.GetFullPath(outputDir));
if (!Directory.Exists(extOutputDir))
{
Directory.CreateDirectory(extOutputDir);
}
byte[] buffer = new byte[128 * 1024]; // 128KB バッファ
long extractedBytes = 0;
long totalBytes = inspect.TotalUnpackedBytes;
int totalFiles = inspect.FileEntries.Count;
int skippedFilesCount = 0;
List<string> errorDetails = [];
using (var fs = new FileStream(ToExtendedPath(targetAsar), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var br = new BinaryReader(fs))
{
uint u1 = br.ReadUInt32();
uint headerSize = br.ReadUInt32();
long dataOffset = 8 + (long)headerSize;
for (int i = 0; i < inspect.FileEntries.Count; i++)
{
if (ct.IsCancellationRequested)
{
return (false, "解凍処理が中断されました。");
}
var entry = inspect.FileEntries[i];
// extOutputDir (\\?\C:\...) と entry.RelativePath を結合
// ※先頭に \\?\ が付いているため、con.png や aux.mp3 などの予約デバイス名があっても
//  Win32 による \\.\con への置換が発生せず、正常にファイル作成が可能
string destFilePath = Path.Combine(extOutputDir, entry.RelativePath.Replace('/', Path.DirectorySeparatorChar));
string? parentDir = Path.GetDirectoryName(destFilePath);
if (!string.IsNullOrEmpty(parentDir) && !Directory.Exists(parentDir))
{
Directory.CreateDirectory(parentDir);
}
// ファイル書き込み
try
{
fs.Seek(dataOffset + entry.Offset, SeekOrigin.Begin);
long remaining = entry.Size;
using (var outFs = new FileStream(destFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
while (remaining > 0)
{
int toRead = (int)Math.Min(remaining, buffer.Length);
int read = fs.Read(buffer, 0, toRead);
if (read == 0) break;
outFs.Write(buffer, 0, read);
remaining -= read;
extractedBytes += read;
progress?.Report((extractedBytes, totalBytes, i + 1, totalFiles, Path.GetFileName(entry.RelativePath)));
}
}
}
catch (Exception fileEx)
{
// 予約文字や排他ロック等の例外が発生した場合、解凍全体を止めずに警告として記録
skippedFilesCount++;
if (errorDetails.Count < 5)
{
errorDetails.Add($"{entry.RelativePath} ({fileEx.Message})");
}
}
}
} // ここで fs と br が確実に Dispose されてファイルハンドルが解放される
// 展開が正常完了したら、元の app.asar をリネームバックアップする
// (これにより Electron は同階層の解凍 app フォルダを最優先で読み込み、改造プラグインが確実に動作する)
string extAsarPath = ToExtendedPath(asarPath);
string extBackupAsar = ToExtendedPath(backupAsar);
if (File.Exists(extAsarPath) && !asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase))
{
if (File.Exists(extBackupAsar))
{
File.Delete(extBackupAsar);
}
File.Move(extAsarPath, extBackupAsar);
}
string summary = $"ASARの解凍が完了しました。(全 {totalFiles} ファイル展開完了)";
if (skippedFilesCount > 0)
{
summary += $" ※一部ファイル({skippedFilesCount}件)の展開をスキップ: {string.Join(", ", errorDetails)}";
}
return (true, summary);
}
catch (Exception ex)
{
return (false, $"ASAR解凍中にエラーが発生しました: {ex.Message}");
}
}, ct);
}
/// <summary>
/// 解凍された app フォルダを安全に削除し、バックアップされていた app.asar を元の名前に復元します。
/// これによりゲームは完全にオリジナルの app.asar 実行状態へ戻ります。
/// </summary>
public async Task<(bool Success, string Message)> RestoreAsarAsync(string asarPath, string extractedDir, CancellationToken ct = default)
{
return await Task.Run(() =>
{
var backupAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase)
? asarPath
: asarPath + AsarBackupSuffix;
var originalAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase)
? asarPath.Substring(0, asarPath.Length - AsarBackupSuffix.Length)
: asarPath;
string extExtractedDir = ToExtendedPath(extractedDir);
string extBackupAsar = ToExtendedPath(backupAsar);
string extOriginalAsar = ToExtendedPath(originalAsar);
try
{
// 1. 解凍ディレクトリの削除(con.png等の特殊名を含むフォルダも拡張パスで安全に削除)
if (!string.IsNullOrEmpty(extExtractedDir) && Directory.Exists(extExtractedDir))
{
Directory.Delete(extExtractedDir, true);
}
// 2. バックアップした asar を元の名前に戻す
if (File.Exists(extBackupAsar))
{
if (File.Exists(extOriginalAsar))
{
File.Delete(extOriginalAsar);
}
File.Move(extBackupAsar, extOriginalAsar);
}
return (true, "ゲームを元の app.asar 形式に復元しました。(解凍フォルダは綺麗に削除されました)");
}
catch (Exception ex)
{
return (false, $"復元処理中にエラーが発生しました: {ex.Message}");
}
}, ct);
}
}
}
+447
View File
@@ -0,0 +1,447 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using GameLauncher.Models;
namespace GameLauncher.Services.Codecs
{
/// <summary>
/// Easy Save 3 (ES3) 形式のセーブデータ(.sd, .es3, .save, .dat)用コーデック
/// </summary>
public class EasySave3Codec : ISaveDataCodec
{
public string CodecName => "Easy Save 3 (ES3) コーデック";
public bool RequiresPassword => false;
public string? PasswordPromptMessage => "暗号化パスワードが設定されている場合は入力してください(未設定・既定の場合は空欄):";
// キャッシュ用の最新平文JSONノード
private JsonNode? _cachedRootNode;
private bool _wasEncrypted;
private string? _usedPassword;
public bool CanHandle(UnityGameItem game, SaveFileEntry file)
{
var ext = Path.GetExtension(file.FilePath).ToLowerInvariant();
if (ext is ".sd" or ".es3" or ".save" or ".dat")
{
// ES3 の特徴:ファイル名が 0.sd, s.sd, h.sd, SaveFile.es3 など、またはファイルサイズが適度
if (file.FileName.EndsWith(".sd", StringComparison.OrdinalIgnoreCase) ||
file.FileName.EndsWith(".es3", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null)
{
var list = new List<SaveDataPropertyEntry>();
if (!File.Exists(filePath)) return list;
byte[] fileBytes = File.ReadAllBytes(filePath);
if (fileBytes.Length == 0) return list;
string? jsonText = null;
_wasEncrypted = false;
_usedPassword = null;
// 1. まず平文 JSON または Gzip 解凍を試みる
try
{
string text = Encoding.UTF8.GetString(fileBytes);
if (text.TrimStart().StartsWith("{") || text.TrimStart().StartsWith("["))
{
jsonText = text;
}
}
catch { }
// 2. Gzip 圧縮の解凍を試みる
if (jsonText == null && fileBytes.Length > 2 && fileBytes[0] == 0x1F && fileBytes[1] == 0x8B)
{
try
{
using var ms = new MemoryStream(fileBytes);
using var gzip = new GZipStream(ms, CompressionMode.Decompress);
using var reader = new StreamReader(gzip, Encoding.UTF8);
jsonText = reader.ReadToEnd();
}
catch { }
}
// 3. パスワード指定または既定パスワードによる AES 復号を試みる
if (jsonText == null)
{
var candidatePasswords = new List<string>();
if (!string.IsNullOrEmpty(optionalPassword))
{
candidatePasswords.Add(optionalPassword);
}
candidatePasswords.AddRange(new[] { "Moodkie", "password", "", "SaveData" });
foreach (var pwd in candidatePasswords)
{
var decrypted = TryDecryptAes(fileBytes, pwd);
if (!string.IsNullOrEmpty(decrypted))
{
jsonText = decrypted;
_wasEncrypted = true;
_usedPassword = pwd;
break;
}
}
}
if (string.IsNullOrEmpty(jsonText))
{
// JSON展開ができなかった場合、バイナリキー・バリュー形式として先頭・重要オフセットを抽出
return ExtractBinaryPropertiesFallback(fileBytes);
}
// JSON からプロパティを再帰的に展開
try
{
_cachedRootNode = JsonNode.Parse(jsonText);
if (_cachedRootNode is JsonObject rootObj)
{
FlattenJsonObject(rootObj, "", list);
}
else if (_cachedRootNode is JsonArray rootArr)
{
FlattenJsonArray(rootArr, "Array", list);
}
}
catch
{
return ExtractBinaryPropertiesFallback(fileBytes);
}
return list;
}
private void FlattenJsonObject(JsonObject obj, string prefix, List<SaveDataPropertyEntry> list)
{
foreach (var kvp in obj)
{
string key = string.IsNullOrEmpty(prefix) ? kvp.Key : $"{prefix}.{kvp.Key}";
var node = kvp.Value;
if (node == null)
{
list.Add(new SaveDataPropertyEntry
{
Key = key,
Category = string.IsNullOrEmpty(prefix) ? "ルート" : prefix,
Type = "null",
EditValue = "null",
RawData = key
});
}
else if (node is JsonValue val)
{
string type = "String";
if (val.TryGetValue(out int intVal)) type = "Int";
else if (val.TryGetValue(out long longVal)) type = "Long";
else if (val.TryGetValue(out double dblVal)) type = "Float";
else if (val.TryGetValue(out bool boolVal)) type = "Bool";
list.Add(new SaveDataPropertyEntry
{
Key = key,
Category = string.IsNullOrEmpty(prefix) ? "基本変数" : prefix,
Type = type,
EditValue = val.ToString() ?? "",
RawData = key
});
}
else if (node is JsonObject childObj)
{
// ES3 特有の構造: { "__type": "...", "value": ... } の場合は中身を直接展開
if (childObj.ContainsKey("value") && childObj["value"] is JsonValue directVal)
{
string type = childObj["__type"]?.ToString() ?? "Object";
list.Add(new SaveDataPropertyEntry
{
Key = key,
Category = prefix,
Type = type,
EditValue = directVal.ToString() ?? "",
RawData = key + ".value"
});
}
else
{
FlattenJsonObject(childObj, key, list);
}
}
else if (node is JsonArray childArr)
{
if (childArr.Count <= 20)
{
FlattenJsonArray(childArr, key, list);
}
else
{
list.Add(new SaveDataPropertyEntry
{
Key = key,
Category = prefix,
Type = $"配列[{childArr.Count}]",
EditValue = childArr.ToJsonString(),
Description = "要素数が多いためJSON形式で直接編集できます",
RawData = key
});
}
}
}
}
private void FlattenJsonArray(JsonArray arr, string prefix, List<SaveDataPropertyEntry> list)
{
for (int i = 0; i < arr.Count; i++)
{
string key = $"{prefix}[{i}]";
var node = arr[i];
if (node is JsonValue val)
{
list.Add(new SaveDataPropertyEntry
{
Key = key,
Category = prefix,
Type = "要素",
EditValue = val.ToString() ?? "",
RawData = key
});
}
else if (node is JsonObject childObj)
{
FlattenJsonObject(childObj, key, list);
}
}
}
private List<SaveDataPropertyEntry> ExtractBinaryPropertiesFallback(byte[] bytes)
{
var list = new List<SaveDataPropertyEntry>();
list.Add(new SaveDataPropertyEntry
{
Key = "FileSize",
Category = "ファイル情報",
Type = "Int",
EditValue = bytes.Length.ToString(),
Description = "ファイルサイズ (bytes)"
});
// 先頭 128 バイトから 4 バイト整数と ASCII 文字列を検出してプロパティ化
int limit = Math.Min(bytes.Length - 4, 128);
for (int i = 0; i < limit; i += 4)
{
int val = BitConverter.ToInt32(bytes, i);
list.Add(new SaveDataPropertyEntry
{
Key = $"Offset_0x{i:X2}",
Category = "バイナリ変数 (4バイト)",
Type = "Int32",
EditValue = val.ToString(),
Description = $"16進数オフセット 0x{i:X2} の数値",
RawData = i
});
}
return list;
}
public bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null)
{
try
{
if (_cachedRootNode != null)
{
// JSON の値を更新
foreach (var prop in properties)
{
if (prop.RawData is string keyPath)
{
UpdateJsonNodeByPath(_cachedRootNode, keyPath, prop.EditValue, prop.Type);
}
}
var options = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
string updatedJson = _cachedRootNode.ToJsonString(options);
byte[] outputBytes = Encoding.UTF8.GetBytes(updatedJson);
// もともと暗号化されていた場合は再暗号化
if (_wasEncrypted)
{
string pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword : (_usedPassword ?? "Moodkie");
outputBytes = EncryptAes(outputBytes, pwd);
}
// バックアップ作成
if (File.Exists(filePath))
{
File.Copy(filePath, filePath + ".bak", overwrite: true);
}
File.WriteAllBytes(filePath, outputBytes);
return true;
}
else
{
// バイナリオフセット書き換え
byte[] fileBytes = File.ReadAllBytes(filePath);
foreach (var prop in properties)
{
if (prop.RawData is int offset && offset + 4 <= fileBytes.Length)
{
if (int.TryParse(prop.EditValue, out int val))
{
var b = BitConverter.GetBytes(val);
Array.Copy(b, 0, fileBytes, offset, 4);
}
}
}
if (File.Exists(filePath))
{
File.Copy(filePath, filePath + ".bak", overwrite: true);
}
File.WriteAllBytes(filePath, fileBytes);
return true;
}
}
catch
{
return false;
}
}
private void UpdateJsonNodeByPath(JsonNode root, string path, string newValue, string type)
{
try
{
// ドットと角括弧でパスを分割
var parts = path.Split(new[] { '.', '[', ']' }, StringSplitOptions.RemoveEmptyEntries);
JsonNode? current = root;
for (int i = 0; i < parts.Length - 1; i++)
{
if (current is JsonObject obj && obj.ContainsKey(parts[i]))
{
current = obj[parts[i]];
}
else if (current is JsonArray arr && int.TryParse(parts[i], out int arrIdx) && arrIdx < arr.Count)
{
current = arr[arrIdx];
}
else
{
return;
}
}
string lastKey = parts[^1];
if (current is JsonObject finalObj)
{
finalObj[lastKey] = ParseJsonValue(newValue, type);
}
else if (current is JsonArray finalArr && int.TryParse(lastKey, out int finalIdx) && finalIdx < finalArr.Count)
{
finalArr[finalIdx] = ParseJsonValue(newValue, type);
}
}
catch { }
}
private JsonNode? ParseJsonValue(string value, string type)
{
if (type == "Int" && int.TryParse(value, out int i)) return JsonValue.Create(i);
if (type == "Long" && long.TryParse(value, out long l)) return JsonValue.Create(l);
if (type == "Float" && double.TryParse(value, out double d)) return JsonValue.Create(d);
if (type == "Bool" && bool.TryParse(value, out bool b)) return JsonValue.Create(b);
if (type == "null") return null;
try
{
// JSON オブジェクトや配列としてパース可能か試みる
if (value.StartsWith("{") || value.StartsWith("["))
{
return JsonNode.Parse(value);
}
}
catch { }
return JsonValue.Create(value);
}
private string? TryDecryptAes(byte[] data, string password)
{
try
{
byte[] rawUtf8 = Encoding.UTF8.GetBytes(password);
var key16 = new byte[16];
Array.Copy(rawUtf8, key16, Math.Min(rawUtf8.Length, 16));
if (data.Length > 16)
{
var iv = new byte[16];
Array.Copy(data, 0, iv, 0, 16);
var cipher = new byte[data.Length - 16];
Array.Copy(data, 16, cipher, 0, cipher.Length);
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = key16;
aes.IV = iv;
using var dec = aes.CreateDecryptor();
byte[] plain = dec.TransformFinalBlock(cipher, 0, cipher.Length);
string text = Encoding.UTF8.GetString(plain);
if (text.Contains("{") || text.Contains("__type") || text.Contains("version"))
{
return text;
}
}
}
catch { }
return null;
}
private byte[] EncryptAes(byte[] plainBytes, string password)
{
byte[] rawUtf8 = Encoding.UTF8.GetBytes(password);
var key16 = new byte[16];
Array.Copy(rawUtf8, key16, Math.Min(rawUtf8.Length, 16));
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = key16;
aes.GenerateIV();
using var enc = aes.CreateEncryptor();
byte[] cipher = enc.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
var result = new byte[aes.IV.Length + cipher.Length];
Array.Copy(aes.IV, 0, result, 0, aes.IV.Length);
Array.Copy(cipher, 0, result, aes.IV.Length, cipher.Length);
return result;
}
}
}
+29
View File
@@ -0,0 +1,29 @@
using System.Collections.Generic;
using GameLauncher.Models;
namespace GameLauncher.Services.Codecs
{
/// <summary>
/// バイナリ/暗号化セーブデータのGUI編集用デコーダー・エンコーダーインターフェース
/// </summary>
public interface ISaveDataCodec
{
/// <summary>コーデックの識別名称(例: "Easy Save 3 (ES3)", "YU-RIS セーブデータ")</summary>
string CodecName { get; }
/// <summary>このコーデックで指定ファイルを処理可能か判定</summary>
bool CanHandle(UnityGameItem game, SaveFileEntry file);
/// <summary>セーブファイルからGUI編集用プロパティ一覧をロード・解析</summary>
List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null);
/// <summary>GUI編集されたプロパティ一覧をファイルへ再エンコード・保存</summary>
bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null);
/// <summary>復号にパスワードやキーが必要かどうか</summary>
bool RequiresPassword { get; }
/// <summary>パスワード入力時の案内メッセージ</summary>
string? PasswordPromptMessage { get; }
}
}
+135
View File
@@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using GameLauncher.Models;
namespace GameLauncher.Services.Codecs
{
/// <summary>
/// YU-RIS エンジン形式のセーブデータ(YSSD シグネチャ)用コーデック
/// </summary>
public class YurisSaveCodec : ISaveDataCodec
{
public string CodecName => "YU-RIS セーブデータ (YSSD) コーデック";
public bool RequiresPassword => false;
public string? PasswordPromptMessage => null;
public bool CanHandle(UnityGameItem game, SaveFileEntry file)
{
if (!File.Exists(file.FilePath)) return false;
try
{
using var fs = File.OpenRead(file.FilePath);
if (fs.Length < 16) return false;
var magic = new byte[4];
fs.ReadExactly(magic);
// "YSSD" (0x59 0x53 0x53 0x44)
return magic[0] == 0x59 && magic[1] == 0x53 && magic[2] == 0x53 && magic[3] == 0x44;
}
catch
{
return false;
}
}
public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null)
{
var list = new List<SaveDataPropertyEntry>();
if (!File.Exists(filePath)) return list;
byte[] bytes = File.ReadAllBytes(filePath);
if (bytes.Length < 16) return list;
int headerSize = BitConverter.ToInt32(bytes, 4);
int version = BitConverter.ToInt32(bytes, 8);
list.Add(new SaveDataPropertyEntry
{
Key = "Signature",
Category = "ヘッダー情報",
Type = "String",
EditValue = "YSSD (YU-RIS Save Data)",
Description = "セーブ識別子"
});
list.Add(new SaveDataPropertyEntry
{
Key = "HeaderSize",
Category = "ヘッダー情報",
Type = "Int32",
EditValue = headerSize.ToString(),
Description = "ヘッダーサイズ"
});
list.Add(new SaveDataPropertyEntry
{
Key = "SaveVersion",
Category = "ヘッダー情報",
Type = "Int32",
EditValue = version.ToString(),
Description = "セーブバージョン番号"
});
// 16バイト以降の変数領域から、4バイト整数および文字列をスキャン
int offset = 16;
int varIndex = 0;
while (offset + 4 <= bytes.Length && varIndex < 100)
{
int val = BitConverter.ToInt32(bytes, offset);
list.Add(new SaveDataPropertyEntry
{
Key = $"Var_{varIndex:D3} (0x{offset:X4})",
Category = "ゲーム変数 / フラグ",
Type = "Int32",
EditValue = val.ToString(),
Description = $"オフセット 0x{offset:X4} の4バイト値",
RawData = offset
});
offset += 4;
varIndex++;
}
return list;
}
public bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null)
{
try
{
byte[] bytes = File.ReadAllBytes(filePath);
foreach (var prop in properties)
{
if (prop.RawData is int offset && offset + 4 <= bytes.Length)
{
if (int.TryParse(prop.EditValue, out int val))
{
var b = BitConverter.GetBytes(val);
Array.Copy(b, 0, bytes, offset, 4);
}
}
}
if (File.Exists(filePath))
{
File.Copy(filePath, filePath + ".bak", overwrite: true);
}
File.WriteAllBytes(filePath, bytes);
return true;
}
catch
{
return false;
}
}
}
}
File diff suppressed because it is too large. Load diff
+118
View File
@@ -0,0 +1,118 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using GameLauncher.Models;
using GameLauncher.Services.Codecs;
namespace GameLauncher.Services
{
/// <summary>
/// 各種セーブデータコーデックの統括管理および未対応時のAIプロンプト自動生成を行うマネージャ
/// </summary>
public class SaveDataCodecManager
{
public static readonly SaveDataCodecManager Instance = new();
private readonly List<ISaveDataCodec> _codecs = [];
public SaveDataCodecManager()
{
// コーデックの登録
_codecs.Add(new EasySave3Codec());
_codecs.Add(new YurisSaveCodec());
}
/// <summary>
/// 指定されたゲームおよびセーブファイルに対応するコーデックを検索します。
/// </summary>
public ISaveDataCodec? FindCodec(UnityGameItem game, SaveFileEntry file)
{
foreach (var codec in _codecs)
{
if (codec.CanHandle(game, file))
{
return codec;
}
}
return null;
}
/// <summary>
/// 未対応セーブデータについて、Antigravity IDE に依頼できる安全なプロンプトを自動生成します。
/// </summary>
public string GenerateAntigravityPrompt(UnityGameItem game, SaveFileEntry file)
{
// ポリシー配慮: 会社名・タイトル名からセンシティブ表現を除去/安全な別名に変換
string safeGameName = SanitizeForPrompt(string.IsNullOrEmpty(game.ProductName) ? game.FolderName : game.ProductName);
string safeCompany = SanitizeForPrompt(game.CompanyName);
if (string.IsNullOrEmpty(safeCompany)) safeCompany = "UnknownDeveloper";
string fileName = Path.GetFileName(file.FilePath);
string ext = Path.GetExtension(file.FilePath).ToLowerInvariant();
// 先頭32バイトのHexダンプを取得
string hexDump = "";
try
{
if (File.Exists(file.FilePath))
{
byte[] bytes = File.ReadAllBytes(file.FilePath);
int count = Math.Min(32, bytes.Length);
var hexList = new List<string>();
for (int i = 0; i < count; i++)
{
hexList.Add(bytes[i].ToString("X2"));
}
hexDump = string.Join(" ", hexList);
}
}
catch { }
var sb = new StringBuilder();
sb.AppendLine("【GameLauncher セーブデータGUI編集プラグイン追加リクエスト】");
sb.AppendLine("GameLauncher で管理している以下のゲームのバイナリセーブデータについて、GUIで閲覧・編集できるようにコーデック(ISaveDataCodec)の実装を追加してください。");
sb.AppendLine();
sb.AppendLine("■ 対象ゲーム情報:");
sb.AppendLine($"- 開発元/サークル: {safeCompany}");
sb.AppendLine($"- 作品名/識別子: {safeGameName}");
sb.AppendLine($"- バックエンド形式: {game.BackendBadgeText} (Unity {game.UnityVersion})");
sb.AppendLine($"- ゲームフォルダ: {game.RootDirectory}");
sb.AppendLine();
sb.AppendLine("■ セーブファイル情報:");
sb.AppendLine($"- ファイル名: {fileName} (拡張子: {ext})");
sb.AppendLine($"- 保存先パス: {file.FilePath}");
sb.AppendLine($"- ファイルサイズ: {file.FileSize} bytes");
sb.AppendLine($"- 先頭バイト列 (Hex): {hexDump}");
sb.AppendLine();
sb.AppendLine("■ 実装要件:");
sb.AppendLine("1. 上記セーブデータの内部構造(暗号化方式、シリアライズ形式、変数テーブルなど)を解析してください。");
sb.AppendLine("2. `Services/Codecs/` 配下に新規の `ISaveDataCodec` 実装クラスを作成し、`SaveDataCodecManager` に登録してください。");
sb.AppendLine("3. GameLauncher のセーブエディタ画面で、プロパティ一覧(所持金、ステータス、フラグ等)をGUI上で閲覧・編集・保存できるようにしてください。");
sb.AppendLine("4. 実装完了後はプロジェクトをビルドし、単一ファイル発行を行ってください。");
return sb.ToString();
}
/// <summary>
/// AIプロンプト向けに文字列を安全・中立的な表現にサニタイズ
/// </summary>
private static string SanitizeForPrompt(string input)
{
if (string.IsNullOrWhiteSpace(input)) return "Game";
// 記号や括弧を取り除き、英数字と安全な文字のみを抽出
var sanitized = Regex.Replace(input, @"[\[\]【】()()~~★☆!!??]", " ").Trim();
// 過度な空白の整理
sanitized = Regex.Replace(sanitized, @"\s+", " ");
if (sanitized.Length > 30)
{
sanitized = sanitized[..30];
}
return string.IsNullOrEmpty(sanitized) ? "UnityGame" : sanitized;
}
}
}
+456
View File
@@ -0,0 +1,456 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using GameLauncher.Helpers;
using GameLauncher.Models;
namespace GameLauncher.Services
{
/// <summary>
/// ツクールスクリプト改造プラグインの動的検出・適用・復元・管理を行うサービス
/// </summary>
public class TkoolModService
{
/// <summary>バックアップファイルのサフィックス</summary>
public const string BackupSuffix = ".original_launcher_backup";
/// <summary>
/// 過去のバージョンで使用されていたレガシープラグイン名一覧(完全削除・復元互換用)
/// 以前改造されたゲームの検知、復元時のクリーンアップ、新改造適用時の旧ゴミ削除に使用します。
/// </summary>
public static readonly string[] LegacyPluginNames =
[
"SpeedUp",
"Antigravity_GameTweaks",
"DropItem99",
"TurnStartFullRecover",
"BattleTurnRecover",
"MaxGainGold",
"MaxGainExp",
"InstantMessage"
];
private List<ModPluginDefinition> _availablePlugins = [];
/// <summary>現在認識されている利用可能なプラグイン一覧</summary>
public IReadOnlyList<ModPluginDefinition> AvailablePlugins => _availablePlugins;
public TkoolModService()
{
LoadAvailablePlugins();
}
/// <summary>
/// exe と同一階層にある plugins フォルダの物理パスを取得します。
/// </summary>
public static string GetPluginsDirectory()
{
// 1. 実行ファイルと同じ物理ディレクトリ
var exeDir = AppPathHelper.GetExeDirectory();
var primary = Path.Combine(exeDir, "plugins");
if (Directory.Exists(primary))
{
return primary;
}
// 2. 本番配置フォルダ(Z:\自作ソフト\GameLauncher\plugins)
const string prodPath = @"Z:\自作ソフト\GameLauncher\plugins";
if (Directory.Exists(prodPath))
{
return prodPath;
}
// 3. AppContext.BaseDirectory 配下のフォールバック
var baseDir = AppContext.BaseDirectory;
var cand1 = Path.Combine(baseDir, "plugins");
if (Directory.Exists(cand1)) return cand1;
return primary;
}
/// <summary>
/// exe と同階層の plugins フォルダから動的にプラグイン一覧を読み込みます。
/// </summary>
public List<ModPluginDefinition> LoadAvailablePlugins()
{
var list = new List<ModPluginDefinition>();
var pluginsDir = GetPluginsDirectory();
if (Directory.Exists(pluginsDir))
{
foreach (var file in Directory.EnumerateFiles(pluginsDir, "*.js"))
{
try
{
list.Add(ModPluginDefinition.FromFile(file));
}
catch { }
}
}
_availablePlugins = list;
return list;
}
/// <summary>
/// 現在有効なプラグイン名と旧レガシープラグイン名のすべてを合算した除去対象プラグイン名セットを取得します。
/// </summary>
public static HashSet<string> GetAllManagedPluginNames(IEnumerable<ModPluginDefinition>? currentPlugins = null)
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// 過去のレガシープラグイン名をすべて含める
foreach (var leg in LegacyPluginNames)
{
set.Add(leg);
}
// 現在のプラグイン群を含める
if (currentPlugins != null)
{
foreach (var p in currentPlugins)
{
set.Add(p.Id);
}
}
else
{
var dir = GetPluginsDirectory();
if (Directory.Exists(dir))
{
foreach (var file in Directory.EnumerateFiles(dir, "*.js"))
{
set.Add(Path.GetFileNameWithoutExtension(file));
}
}
}
return set;
}
/// <summary>
/// 指定されたゲームに対して、現在のチェック状態に応じた改造の適用または復元を行います。
/// </summary>
public (bool Success, string Message) ApplyOrRestoreMod(TkoolGameItem game, Dictionary<string, bool>? defaultSettings = null)
{
if (string.IsNullOrEmpty(game.PluginsJsPath) || !File.Exists(game.PluginsJsPath))
{
return (false, "plugins.js が見つかりません。");
}
try
{
if (game.ApplyMod)
{
return ApplyMod(game, defaultSettings);
}
else
{
return RestoreOriginal(game);
}
}
catch (Exception ex)
{
return (false, $"スクリプト処理中にエラーが発生しました: {ex.Message}");
}
}
/// <summary>
/// 改造プラグインを適用します。
/// </summary>
public (bool Success, string Message) ApplyMod(TkoolGameItem game, Dictionary<string, bool>? defaultSettings = null)
{
var pluginsJsPath = game.PluginsJsPath;
var pluginsDir = game.PluginsDirPath;
if (string.IsNullOrEmpty(pluginsDir))
{
pluginsDir = Path.Combine(Path.GetDirectoryName(pluginsJsPath)!, "plugins");
game.PluginsDirPath = pluginsDir;
}
if (!Directory.Exists(pluginsDir))
{
Directory.CreateDirectory(pluginsDir);
}
var backupPath = pluginsJsPath + BackupSuffix;
// 1. バックアップが存在しない場合、バックアップを作成する
if (!File.Exists(backupPath))
{
string currentContent = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
// 既に改造プラグイン(新旧問わず)が埋め込まれている場合はクリーンアップしたものをバックアップとして保持
string cleanContent = CleanManagedPluginsFromContent(currentContent);
File.WriteAllText(backupPath, cleanContent, new UTF8Encoding(false));
}
// 2. バックアップ(クリーン状態)を元に編集を開始
string baseContent = File.ReadAllText(backupPath, Encoding.UTF8);
// 最新の動的プラグイン一覧を取得
if (_availablePlugins.Count == 0)
{
LoadAvailablePlugins();
}
// 有効化対象のプラグインを取得
var pluginsToEnable = _availablePlugins
.Where(p => game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: true))
.ToList();
// 3. ゲーム側の plugins ディレクトリから不要な旧プラグインや無効プラグインを安全に掃除
var allManaged = GetAllManagedPluginNames(_availablePlugins);
var enabledIds = new HashSet<string>(pluginsToEnable.Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
foreach (var pluginId in allManaged)
{
// 有効対象ではないプラグインファイル(旧プラグインや今回OFFにしたプラグイン)を削除
if (!enabledIds.Contains(pluginId))
{
var targetFile = Path.Combine(pluginsDir, $"{pluginId}.js");
if (File.Exists(targetFile))
{
try { File.Delete(targetFile); } catch { }
}
}
}
// 4. 有効対象のプラグインファイルをゲーム側へ配置
foreach (var plugin in pluginsToEnable)
{
CopyPluginToGame(plugin, pluginsDir);
}
// 5. plugins.js をパース・再構築して有効プラグインを追加
var pluginNamesToAdd = pluginsToEnable.Select(p => p.Id).ToList();
string updatedContent = RebuildPluginsJs(baseContent, pluginNamesToAdd);
// 6. 保存
File.WriteAllText(pluginsJsPath, updatedContent, new UTF8Encoding(false));
game.IsModded = true;
return (true, $"ツクールスクリプト改造を正常に適用しました。(有効プラグイン: {pluginsToEnable.Count}個)");
}
/// <summary>
/// 改造を解除し、ゲームを改造前のオリジナル状態に復元します。
/// 旧レガシープラグインも含めて完全にクリーンアップします。
/// </summary>
public (bool Success, string Message) RestoreOriginal(TkoolGameItem game)
{
var pluginsJsPath = game.PluginsJsPath;
var pluginsDir = game.PluginsDirPath;
var backupPath = pluginsJsPath + BackupSuffix;
// 1. バックアップが存在する場合はバックアップから復元(再構築を通すことで壊れたバックアップも修復)
if (File.Exists(backupPath))
{
string backupContent = File.ReadAllText(backupPath, Encoding.UTF8);
string cleanContent = RebuildPluginsJs(backupContent, null);
File.WriteAllText(pluginsJsPath, cleanContent, new UTF8Encoding(false));
}
else
{
// バックアップがなくても、現在の plugins.js から新旧すべての管理プラグインを綺麗に除去
string currentContent = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
string cleanContent = RebuildPluginsJs(currentContent, null);
File.WriteAllText(pluginsJsPath, cleanContent, new UTF8Encoding(false));
}
// 2. ゲーム側の plugins フォルダから新旧すべてのプラグインファイルを安全に削除(ゴミを残さない)
if (!string.IsNullOrEmpty(pluginsDir) && Directory.Exists(pluginsDir))
{
var allManaged = GetAllManagedPluginNames(_availablePlugins);
foreach (var pluginName in allManaged)
{
var targetFile = Path.Combine(pluginsDir, $"{pluginName}.js");
if (File.Exists(targetFile))
{
try { File.Delete(targetFile); } catch { /* 削除不可時は無視 */ }
}
}
}
game.IsModded = false;
return (true, "ゲームを改造前のオリジナル状態に正常に復元しました。(旧プラグインも完全削除済み)");
}
/// <summary>
/// plugins.js のテキストから新旧すべての管理対象プラグインの登録記述を除去します。
/// </summary>
public static string CleanManagedPluginsFromContent(string content)
{
return RebuildPluginsJs(content, null);
}
/// <summary>
/// plugins.js の内容を構文レベルで解析し、新旧管理対象プラグインの完全除去および新規追加を行って
/// 正常な JavaScript 配列構文として再構築します。
/// </summary>
public static string RebuildPluginsJs(string content, IReadOnlyList<string>? pluginsToAdd = null)
{
if (string.IsNullOrWhiteSpace(content))
{
return content;
}
int arrayStart = content.IndexOf('[');
int arrayEnd = content.LastIndexOf(']');
if (arrayStart == -1 || arrayEnd == -1 || arrayEnd <= arrayStart)
{
return content;
}
string prefix = content.Substring(0, arrayStart + 1);
string inner = content.Substring(arrayStart + 1, arrayEnd - arrayStart - 1);
string suffix = content.Substring(arrayEnd);
// 新旧すべてのプラグイン名を除去対象とする
var managedSet = GetAllManagedPluginNames();
var keptObjects = new List<string>();
int i = 0;
while (i < inner.Length)
{
// 次のオブジェクト開始 '{' を探す
while (i < inner.Length && inner[i] != '{')
{
i++;
}
if (i >= inner.Length) break;
int objStart = i;
int depth = 0;
bool inString = false;
bool isEscaped = false;
while (i < inner.Length)
{
char c = inner[i];
if (isEscaped)
{
isEscaped = false;
}
else if (c == '\\')
{
if (inString) isEscaped = true;
}
else if (c == '"')
{
inString = !inString;
}
else if (!inString)
{
if (c == '{') depth++;
else if (c == '}')
{
depth--;
if (depth == 0)
{
i++; // '}' を含める
break;
}
}
}
i++;
}
if (depth == 0)
{
string objText = inner.Substring(objStart, i - objStart).Trim();
// このオブジェクトが新旧管理対象プラグインかどうか判定
var match = Regex.Match(objText, @"""name""\s*:\s*""([^""]+)""");
if (match.Success && managedSet.Contains(match.Groups[1].Value))
{
// 管理対象プラグインのため除外
continue;
}
keptObjects.Add(objText);
}
}
// 追加対象のプラグインを登録
if (pluginsToAdd != null)
{
foreach (var pluginName in pluginsToAdd)
{
keptObjects.Add($"{{\"name\":\"{pluginName}\",\"status\":true,\"description\":\"\",\"parameters\":{{}}}}");
}
}
// 綺麗な JavaScript 配列として再構築
var sb = new StringBuilder();
sb.Append(prefix.TrimEnd()).AppendLine();
for (int k = 0; k < keptObjects.Count; k++)
{
sb.Append(keptObjects[k]);
if (k < keptObjects.Count - 1)
{
sb.Append(",");
}
sb.AppendLine();
}
sb.Append(suffix.TrimStart());
return sb.ToString();
}
/// <summary>
/// プラグインファイルをゲーム側の plugins ディレクトリへコピーします。
/// </summary>
private void CopyPluginToGame(ModPluginDefinition plugin, string targetDir)
{
var destinationPath = Path.Combine(targetDir, plugin.FileName);
// 1. 指定ファイルの物理パスからコピー
if (!string.IsNullOrEmpty(plugin.FilePath) && File.Exists(plugin.FilePath))
{
File.Copy(plugin.FilePath, destinationPath, true);
return;
}
// 2. plugins ディレクトリからのコピーを試行
var localPluginPath = Path.Combine(GetPluginsDirectory(), plugin.FileName);
if (File.Exists(localPluginPath))
{
File.Copy(localPluginPath, destinationPath, true);
return;
}
throw new FileNotFoundException($"プラグインファイルが見つかりません: {plugin.FileName} (参照先: {GetPluginsDirectory()})");
}
/// <summary>
/// 現在 plugins.js に改造プラグイン(新旧問わず)が記述されているか判定します。
/// </summary>
public static bool CheckIsModded(string pluginsJsPath)
{
if (string.IsNullOrEmpty(pluginsJsPath) || !File.Exists(pluginsJsPath))
return false;
try
{
string content = File.ReadAllText(pluginsJsPath);
var allManaged = GetAllManagedPluginNames();
foreach (var pluginName in allManaged)
{
if (content.Contains($"\"name\":\"{pluginName}\""))
{
return true;
}
}
}
catch
{
// 読み取り失敗時は false
}
return false;
}
}
}
+352
View File
@@ -0,0 +1,352 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using GameLauncher.Models;
namespace GameLauncher.Services
{
/// <summary>
/// ティラノスクリプトゲームの個別改造設定オプション
/// </summary>
public class TyranoModOptions
{
public bool UnlockAllCg { get; set; } = true;
public bool FastMessage { get; set; } = true;
public bool EnableDevTools { get; set; } = true;
public bool ShowCheatMenu { get; set; } = true;
}
/// <summary>
/// ティラノスクリプト(TyranoScript)ゲームのMOD適用・解除・管理を行うサービス
/// </summary>
public class TyranoModService
{
public const string ModScriptFileName = "tyrano_launcher_mod.js";
public const string IndexBackupSuffix = ".original_launcher_backup";
/// <summary>
/// index.html に改造スクリプトが適用されているかどうか判定します。
/// </summary>
public static bool CheckIsModded(string indexPath)
{
if (string.IsNullOrEmpty(indexPath))
return false;
string extPath = AsarArchiveService.ToExtendedPath(indexPath);
if (!File.Exists(extPath))
return false;
try
{
string content = File.ReadAllText(extPath);
return content.Contains(ModScriptFileName);
}
catch
{
return false;
}
}
/// <summary>
/// ティラノスクリプトゲームに改造スクリプトを適用します。
/// </summary>
public (bool Success, string Message) ApplyMod(TkoolGameItem game, Dictionary<string, bool>? pluginSettings)
{
var rawIndexPath = game.PluginsJsPath; // ティラノの場合は index.html パス
if (string.IsNullOrEmpty(rawIndexPath))
{
return (false, "index.html が見つかりません。ASARを解凍してください。");
}
var indexPath = AsarArchiveService.ToExtendedPath(rawIndexPath);
if (!File.Exists(indexPath))
{
return (false, "index.html が見つかりません。ASARを解凍してください。");
}
try
{
var dir = Path.GetDirectoryName(indexPath)!;
var backupPath = indexPath + IndexBackupSuffix;
// 1. バックアップの作成(存在しない場合)
if (!File.Exists(backupPath))
{
string originalContent = File.ReadAllText(indexPath, Encoding.UTF8);
// 既にタグが含まれていた場合は除去したものをバックアップとする
string cleanContent = RemoveScriptTag(originalContent);
File.WriteAllText(backupPath, cleanContent, new UTF8Encoding(false));
}
// 2. 有効化する機能の判定
bool unlockCg = game.IsPluginEnabled("TyranoUnlockAllCg", pluginSettings, fallbackVal: true);
bool fastMsg = game.IsPluginEnabled("TyranoFastMessage", pluginSettings, fallbackVal: true);
bool devTools = game.IsPluginEnabled("TyranoDevTools", pluginSettings, fallbackVal: true);
bool cheatMenu = game.IsPluginEnabled("TyranoCheatMenu", pluginSettings, fallbackVal: true);
// 3. tyrano_launcher_mod.js を生成して配置
string modJsContent = BuildModScript(unlockCg, fastMsg, devTools, cheatMenu);
string modJsPath = Path.Combine(dir, ModScriptFileName);
File.WriteAllText(modJsPath, modJsContent, new UTF8Encoding(false));
// 4. index.html にスクリプトタグを注入
string baseContent = File.ReadAllText(backupPath, Encoding.UTF8);
string injectedContent = InjectScriptTag(baseContent);
File.WriteAllText(indexPath, injectedContent, new UTF8Encoding(false));
game.IsModded = true;
return (true, "ティラノスクリプト用改造を正常に適用しました。(全CG解放/高速化/DevTools/チートメニュー)");
}
catch (Exception ex)
{
return (false, $"ティラノ改造適用中にエラーが発生しました: {ex.Message}");
}
}
/// <summary>
/// ティラノスクリプトゲームの改造を解除し、元のオリジナル状態に復元します。
/// </summary>
public (bool Success, string Message) RestoreOriginal(TkoolGameItem game)
{
var rawIndexPath = game.PluginsJsPath;
if (string.IsNullOrEmpty(rawIndexPath))
{
return (false, "index.html のパスが設定されていません。");
}
var indexPath = AsarArchiveService.ToExtendedPath(rawIndexPath);
try
{
var dir = Path.GetDirectoryName(indexPath)!;
var backupPath = indexPath + IndexBackupSuffix;
var modJsPath = Path.Combine(dir, ModScriptFileName);
// 1. index.html の復元
if (File.Exists(backupPath))
{
File.Copy(backupPath, indexPath, true);
}
else if (File.Exists(indexPath))
{
string content = File.ReadAllText(indexPath, Encoding.UTF8);
string clean = RemoveScriptTag(content);
File.WriteAllText(indexPath, clean, new UTF8Encoding(false));
}
// 2. tyrano_launcher_mod.js の削除
if (File.Exists(modJsPath))
{
try { File.Delete(modJsPath); } catch { }
}
game.IsModded = false;
return (true, "ティラノスクリプトの改造を解除し、オリジナル状態に復元しました。");
}
catch (Exception ex)
{
return (false, $"復元中にエラーが発生しました: {ex.Message}");
}
}
private static string InjectScriptTag(string html)
{
string tag = $"<script type=\"text/javascript\" src=\"./{ModScriptFileName}\"></script>";
if (html.Contains(ModScriptFileName))
{
return html;
}
if (html.Contains("</body>", StringComparison.OrdinalIgnoreCase))
{
return Regex.Replace(html, @"(</body>)", tag + "\n$1", RegexOptions.IgnoreCase);
}
else if (html.Contains("</html>", StringComparison.OrdinalIgnoreCase))
{
return Regex.Replace(html, @"(</html>)", tag + "\n$1", RegexOptions.IgnoreCase);
}
return html + "\n" + tag;
}
private static string RemoveScriptTag(string html)
{
return Regex.Replace(html, @"<script[^>]*src=""\./" + Regex.Escape(ModScriptFileName) + @"""[^>]*></script>\r?\n?", "", RegexOptions.IgnoreCase);
}
private static string BuildModScript(bool unlockCg, bool fastMessage, bool devTools, bool cheatMenu)
{
var sb = new StringBuilder();
sb.AppendLine("/* =============================================================== */");
sb.AppendLine("/* GameLauncher - TyranoScript Mod Plugin */");
sb.AppendLine("/* =============================================================== */");
sb.AppendLine("(function() {");
sb.AppendLine(" 'use strict';");
sb.AppendLine(" console.log('[GameLauncher] TyranoScript Mod active.');");
// 1. DevTools
if (devTools)
{
sb.AppendLine(@"
// F12キーで開発者ツールを開く
window.addEventListener('keydown', function(e) {
if (e.key === 'F12') {
try {
if (typeof require !== 'undefined') {
var electron = require('electron');
var remote = electron.remote || (electron.remote ? electron.remote : null);
var win = remote ? remote.getCurrentWindow() : null;
if (win && win.webContents) {
if (win.webContents.isDevToolsOpened()) win.webContents.closeDevTools();
else win.webContents.openDevTools({ mode: 'detach' });
}
} else if (typeof nw !== 'undefined') {
nw.Window.get().showDevTools();
}
} catch (err) {
console.warn('[GameLauncher] DevTools open failed:', err);
}
}
});");
}
sb.AppendLine(@"
function onTyranoReady() {
if (!window.TYRANO || !window.TYRANO.kag) {
setTimeout(onTyranoReady, 100);
return;
}
var kag = window.TYRANO.kag;
console.log('[GameLauncher] TYRANO.kag detected.');");
// 2. FastMessage
if (fastMessage)
{
sb.AppendLine(@"
// メッセージ高速化・ウェイト短縮
try {
if (kag.config) {
kag.config.defaultAutoSpeed = 10;
kag.config.defaultSkipSpeed = 5;
}
if (kag.stat && kag.stat.ch_speed !== undefined) {
kag.stat.ch_speed = 0;
}
if (kag.ftag && kag.ftag.master_tag && kag.ftag.master_tag.wait) {
var origWait = kag.ftag.master_tag.wait.start;
kag.ftag.master_tag.wait.start = function(pm) {
if (pm && pm.time) pm.time = Math.min(pm.time, 50);
return origWait.apply(this, arguments);
};
}
} catch (e) {
console.warn('[GameLauncher] FastMessage hook error:', e);
}");
}
// 3. UnlockAllCg
if (unlockCg)
{
sb.AppendLine(@"
// 全CG・全回想フラグの全開放
try {
function unlockFlags() {
if (kag.variable && kag.variable.sf) {
var sf = kag.variable.sf;
for (var key in sf) {
if (sf.hasOwnProperty(key)) {
var val = sf[key];
if (typeof val === 'object' && val !== null) {
for (var sub in val) {
if (val.hasOwnProperty(sub)) {
if (typeof val[sub] === 'boolean') val[sub] = true;
else if (typeof val[sub] === 'number' && val[sub] === 0) val[sub] = 1;
}
}
}
}
}
console.log('[GameLauncher] System variables (sf) unlocked for CG/scenes.');
}
}
setTimeout(unlockFlags, 1000);
setTimeout(unlockFlags, 3000);
} catch (e) {
console.warn('[GameLauncher] UnlockAllCg error:', e);
}");
}
// 4. CheatMenu
if (cheatMenu)
{
sb.AppendLine(@"
// 画面上フローティングチートメニュー
try {
var btn = document.createElement('div');
btn.innerHTML = '⚙ チート';
btn.style.cssText = 'position:fixed;top:10px;right:10px;z-index:999999;background:rgba(20,20,30,0.85);color:#00B894;padding:6px 12px;border-radius:6px;font-size:12px;cursor:pointer;border:1px solid #00B894;font-family:sans-serif;user-select:none;font-weight:bold;box-shadow:0 2px 6px rgba(0,0,0,0.5);';
var modal = document.createElement('div');
modal.style.cssText = 'display:none;position:fixed;top:45px;right:10px;width:340px;max-height:480px;background:rgba(24,24,32,0.96);border:1px solid #555;border-radius:8px;z-index:999999;padding:12px;overflow-y:auto;color:#E0E0E6;font-size:12px;font-family:sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.7);';
btn.onclick = function() {
if (modal.style.display === 'none') {
renderVars();
modal.style.display = 'block';
} else {
modal.style.display = 'none';
}
};
function renderVars() {
modal.innerHTML = '<div style=""font-weight:bold;margin-bottom:8px;border-bottom:1px solid #444;padding-bottom:4px;display:flex;justify-content:space-between;""><span>🎮 ゲーム内変数 (f) エディタ</span><span id=""_tkl_close"" style=""cursor:pointer;color:#bbb;"">✕</span></div><div id=""_tkl_list""></div>';
document.getElementById('_tkl_close').onclick = function() { modal.style.display = 'none'; };
var list = document.getElementById('_tkl_list');
var f = (kag.stat && kag.stat.f) ? kag.stat.f : (kag.variable ? kag.variable.f : null);
if (!f || Object.keys(f).length === 0) {
list.innerHTML = '<div style=""color:#888;"">変数(f)が見つかりません。ゲームを開始してからお試しください。</div>';
return;
}
for (var k in f) {
if (!f.hasOwnProperty(k)) continue;
var val = f[k];
if (typeof val === 'number' || typeof val === 'string' || typeof val === 'boolean') {
(function(key, currentVal) {
var row = document.createElement('div');
row.style.cssText = 'display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;';
var nameSpan = document.createElement('span');
nameSpan.innerText = key;
nameSpan.style.cssText = 'max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#FAB1A0;';
var input = document.createElement('input');
input.value = currentVal;
input.style.cssText = 'width:120px;background:#16161E;color:#fff;border:1px solid #444;border-radius:4px;padding:2px 4px;font-size:11px;';
input.onchange = function() {
var n = Number(input.value);
f[key] = isNaN(n) ? input.value : n;
console.log('[GameLauncher] Updated f.' + key + ' =', f[key]);
};
row.appendChild(nameSpan);
row.appendChild(input);
list.appendChild(row);
})(k, val);
}
}
}
document.body.appendChild(btn);
document.body.appendChild(modal);
} catch (e) {
console.warn('[GameLauncher] CheatMenu error:', e);
}");
}
sb.AppendLine(" }");
sb.AppendLine(" setTimeout(onTyranoReady, 300);");
sb.AppendLine("})();");
return sb.ToString();
}
}
}
+683
View File
@@ -0,0 +1,683 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using GameLauncher.Helpers;
using GameLauncher.Models;
namespace GameLauncher.Services
{
/// <summary>
/// UnityのPlayerPrefs(レジストリ)およびセーブファイル(LocalLow / ゲームフォルダ)の編集・バックアップを行うサービス
/// </summary>
public class UnitySaveManagerService
{
// ====================================================================
// 1. PlayerPrefs (レジストリ) 管理機能
// ====================================================================
/// <summary>
/// レジストリ(HKCU\Software\[CompanyName]\[ProductName])からPlayerPrefsエントリ一覧を取得します。
/// </summary>
public List<PlayerPrefsEntry> GetPlayerPrefs(string registryPath)
{
var list = new List<PlayerPrefsEntry>();
if (string.IsNullOrEmpty(registryPath)) return list;
try
{
using var key = Registry.CurrentUser.OpenSubKey(registryPath, writable: false);
if (key == null) return list;
var valueNames = key.GetValueNames();
foreach (var name in valueNames)
{
try
{
var kind = key.GetValueKind(name);
var rawValue = key.GetValue(name);
// キー名から "_h[数字]" のハッシュサフィックスを抽出・除去
string cleanKey = name;
var match = Regex.Match(name, @"^(.*)_h\d+$");
if (match.Success)
{
cleanKey = match.Groups[1].Value;
}
PlayerPrefsType type = PlayerPrefsType.Int;
if (kind == RegistryValueKind.DWord)
{
type = PlayerPrefsType.Int;
}
else if (kind == RegistryValueKind.String)
{
type = PlayerPrefsType.String;
}
else if (kind == RegistryValueKind.Binary)
{
type = PlayerPrefsType.Binary;
}
var entry = new PlayerPrefsEntry
{
RawKey = name,
CleanKey = cleanKey,
Type = type,
Value = rawValue
};
list.Add(entry);
}
catch { }
}
}
catch { }
// キー名昇順でソート
return list.OrderBy(e => e.CleanKey, StringComparer.OrdinalIgnoreCase).ToList();
}
/// <summary>
/// PlayerPrefsのエントリ値をレジストリに更新保存します。
/// </summary>
public bool SavePlayerPref(string registryPath, PlayerPrefsEntry entry)
{
if (string.IsNullOrEmpty(registryPath) || string.IsNullOrEmpty(entry.RawKey))
return false;
try
{
using var key = Registry.CurrentUser.CreateSubKey(registryPath, writable: true);
if (key == null) return false;
switch (entry.Type)
{
case PlayerPrefsType.Int:
if (int.TryParse(entry.EditValue, out int intVal))
{
key.SetValue(entry.RawKey, intVal, RegistryValueKind.DWord);
entry.Value = intVal;
entry.IsModified = false;
return true;
}
break;
case PlayerPrefsType.Float:
if (float.TryParse(entry.EditValue, out float floatVal))
{
// UnityのPlayerPrefsではfloatは4バイトバイナリとして格納される
byte[] floatBytes = BitConverter.GetBytes(floatVal);
key.SetValue(entry.RawKey, floatBytes, RegistryValueKind.Binary);
entry.Value = floatBytes;
entry.IsModified = false;
return true;
}
break;
case PlayerPrefsType.String:
// 文字列として直接格納するか、UTF-8バイト列(末尾0)として格納
// 既存のレジストリ型に合わせる
var existingKind = RegistryValueKind.Unknown;
try { existingKind = key.GetValueKind(entry.RawKey); } catch { }
if (existingKind == RegistryValueKind.Binary)
{
var bytes = Encoding.UTF8.GetBytes(entry.EditValue + "\0");
key.SetValue(entry.RawKey, bytes, RegistryValueKind.Binary);
entry.Value = bytes;
}
else
{
key.SetValue(entry.RawKey, entry.EditValue, RegistryValueKind.String);
entry.Value = entry.EditValue;
}
entry.IsModified = false;
return true;
case PlayerPrefsType.Binary:
// Hex文字列のパース(例: "AA BB CC" または "AABBCC")
var hexClean = entry.EditValue.Replace(" ", "").Replace("-", "");
if (hexClean.Length % 2 == 0)
{
byte[] rawBytes = Convert.FromHexString(hexClean);
key.SetValue(entry.RawKey, rawBytes, RegistryValueKind.Binary);
entry.Value = rawBytes;
entry.IsModified = false;
return true;
}
break;
}
}
catch { }
return false;
}
/// <summary>
/// PlayerPrefsに新規キーを追加します。
/// </summary>
public bool AddPlayerPref(string registryPath, string keyName, PlayerPrefsType type, string value, out string outRawKey)
{
outRawKey = string.Empty;
if (string.IsNullOrEmpty(registryPath) || string.IsNullOrWhiteSpace(keyName))
return false;
try
{
// Unityハッシュの付加
uint hash = CalculateUnityHash(keyName);
string rawKey = $"{keyName}_h{hash}";
outRawKey = rawKey;
using var key = Registry.CurrentUser.CreateSubKey(registryPath, writable: true);
if (key == null) return false;
switch (type)
{
case PlayerPrefsType.Int:
int.TryParse(value, out int intVal);
key.SetValue(rawKey, intVal, RegistryValueKind.DWord);
return true;
case PlayerPrefsType.Float:
float.TryParse(value, out float floatVal);
byte[] floatBytes = BitConverter.GetBytes(floatVal);
key.SetValue(rawKey, floatBytes, RegistryValueKind.Binary);
return true;
case PlayerPrefsType.String:
var bytes = Encoding.UTF8.GetBytes(value + "\0");
key.SetValue(rawKey, bytes, RegistryValueKind.Binary);
return true;
case PlayerPrefsType.Binary:
var hexClean = value.Replace(" ", "").Replace("-", "");
if (hexClean.Length % 2 == 0)
{
byte[] rawBytes = Convert.FromHexString(hexClean);
key.SetValue(rawKey, rawBytes, RegistryValueKind.Binary);
return true;
}
break;
}
}
catch { }
return false;
}
/// <summary>
/// PlayerPrefsのエントリをレジストリから削除します。
/// </summary>
public bool DeletePlayerPref(string registryPath, string rawKey)
{
if (string.IsNullOrEmpty(registryPath) || string.IsNullOrEmpty(rawKey))
return false;
try
{
using var key = Registry.CurrentUser.OpenSubKey(registryPath, writable: true);
if (key != null)
{
key.DeleteValue(rawKey, throwOnMissingValue: false);
return true;
}
}
catch { }
return false;
}
/// <summary>
/// UnityのPlayerPrefsキー用ハッシュ値(MurmurHash2 32bit)を算出します。
/// </summary>
public static uint CalculateUnityHash(string key)
{
byte[] data = Encoding.UTF8.GetBytes(key);
const uint m = 0x5bd1e995;
const int r = 24;
uint h = (uint)data.Length;
int length = data.Length;
int currentIndex = 0;
while (length >= 4)
{
uint k = BitConverter.ToUInt32(data, currentIndex);
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
currentIndex += 4;
length -= 4;
}
switch (length)
{
case 3:
h ^= (uint)(data[currentIndex + 2] << 16);
h ^= (uint)(data[currentIndex + 1] << 8);
h ^= data[currentIndex];
h *= m;
break;
case 2:
h ^= (uint)(data[currentIndex + 1] << 8);
h ^= data[currentIndex];
h *= m;
break;
case 1:
h ^= data[currentIndex];
h *= m;
break;
}
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
/// <summary>
/// PlayerPrefsレジストリキー全体を .reg ファイルおよび JSON ファイルとしてバックアップします。
/// </summary>
public string? BackupRegistry(string registryPath, string backupDir)
{
if (string.IsNullOrEmpty(registryPath)) return null;
try
{
if (!Directory.Exists(backupDir))
{
Directory.CreateDirectory(backupDir);
}
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var regBackupFile = Path.Combine(backupDir, $"PlayerPrefs_{timestamp}.reg");
// reg.exe を用いて .reg ファイルを正確に出力
var fullRegKey = $@"HKEY_CURRENT_USER\{registryPath}";
var psi = new ProcessStartInfo
{
FileName = "reg.exe",
Arguments = $"export \"{fullRegKey}\" \"{regBackupFile}\" /y",
CreateNoWindow = true,
UseShellExecute = false
};
using var proc = Process.Start(psi);
proc?.WaitForExit(3000);
// JSONバックアップも併せて出力
var entries = GetPlayerPrefs(registryPath);
var jsonBackupFile = Path.Combine(backupDir, $"PlayerPrefs_{timestamp}.json");
var serializableList = entries.Select(e => new
{
e.RawKey,
e.CleanKey,
Type = e.Type.ToString(),
e.EditValue
});
var json = JsonSerializer.Serialize(serializableList, new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
File.WriteAllText(jsonBackupFile, json);
return File.Exists(regBackupFile) ? regBackupFile : jsonBackupFile;
}
catch
{
return null;
}
}
/// <summary>
/// .reg ファイルからレジストリを復元します。
/// </summary>
public bool RestoreRegistry(string regFilePath)
{
if (!File.Exists(regFilePath)) return false;
try
{
var psi = new ProcessStartInfo
{
FileName = "reg.exe",
Arguments = $"import \"{regFilePath}\"",
CreateNoWindow = true,
UseShellExecute = false
};
using var proc = Process.Start(psi);
proc?.WaitForExit(3000);
return proc?.ExitCode == 0;
}
catch
{
return false;
}
}
/// <summary>
/// Windows標準のレジストリエディタ(regedit)を起動して該当キーを表示します。
/// </summary>
public void OpenRegistryEditor(string registryPath)
{
try
{
// regedit の「前回開いたキー」を更新
var fullKey = $@"Computer\HKEY_CURRENT_USER\{registryPath}";
using (var lastKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Regedit"))
{
lastKey?.SetValue("LastKey", fullKey);
}
Process.Start(new ProcessStartInfo("regedit.exe") { UseShellExecute = true });
}
catch { }
}
// ====================================================================
// 2. ディスク上のセーブファイル(LocalLow / ゲームフォルダ)管理機能
// ====================================================================
/// <summary>
/// ゲームに関連するディスク上のセーブファイルをすべて探索して取得します。
/// </summary>
public List<SaveFileEntry> GetSaveFiles(UnityGameItem game)
{
var list = new List<SaveFileEntry>();
// 1. LocalLow フォルダ
if (!string.IsNullOrEmpty(game.LocalLowPath) && Directory.Exists(game.LocalLowPath))
{
try
{
var files = Directory.EnumerateFiles(game.LocalLowPath, "*", SearchOption.AllDirectories);
foreach (var f in files)
{
var fileName = Path.GetFileName(f);
// ログファイルは除外(Player.log, Player-prev.log)
if (fileName.StartsWith("Player", StringComparison.OrdinalIgnoreCase) && fileName.EndsWith(".log", StringComparison.OrdinalIgnoreCase))
continue;
var fi = new FileInfo(f);
list.Add(new SaveFileEntry
{
FileName = fileName,
FilePath = f,
FileSize = fi.Length,
LastModified = fi.LastWriteTime,
LocationType = "LocalLow",
IsTextOrJson = CheckIsTextOrJson(f)
});
}
}
catch { }
}
// 2. ゲーム本体フォルダ及びサブフォルダ
if (Directory.Exists(game.RootDirectory))
{
try
{
// ルート直下
CollectCandidateFiles(game.RootDirectory, "ゲームフォルダ", list);
// Save / SaveData / saves / savedata サブフォルダ
var subNames = new[] { "Save", "SaveData", "saves", "savedata", "Save_Data" };
foreach (var sub in subNames)
{
var subPath = Path.Combine(game.RootDirectory, sub);
if (Directory.Exists(subPath))
{
CollectCandidateFiles(subPath, "ゲームフォルダ/" + sub, list, isStrict: false);
}
}
// Dataフォルダ直下のセーブファイル候補
if (!string.IsNullOrEmpty(game.DataDirectoryPath) && Directory.Exists(game.DataDirectoryPath))
{
CollectCandidateFiles(game.DataDirectoryPath, "Dataフォルダ", list);
}
}
catch { }
}
// 更新日時降順でソート
return list.OrderByDescending(f => f.LastModified).ToList();
}
private void CollectCandidateFiles(string dir, string locationLabel, List<SaveFileEntry> list, bool isStrict = true)
{
try
{
var files = Directory.EnumerateFiles(dir);
foreach (var f in files)
{
var fileName = Path.GetFileName(f);
// 既に同パスが登録されていればスキップ
if (list.Any(x => x.FilePath.Equals(f, StringComparison.OrdinalIgnoreCase)))
continue;
// システムファイルや実行ファイル等は除外
var ext = Path.GetExtension(f).ToLowerInvariant();
if (ext is ".exe" or ".dll" or ".config" or ".manifest" or ".txt" or ".log" or ".info" or ".resS" or ".assets")
{
// readmeやapp.info等はセーブファイルではない
if (!fileName.Contains("save", StringComparison.OrdinalIgnoreCase))
continue;
}
if (isStrict)
{
// セーブファイル候補のフィルタ
bool isCandidate = fileName.Contains("save", StringComparison.OrdinalIgnoreCase) ||
ext is ".sav" or ".save" or ".savegame" or ".dat";
if (!isCandidate) continue;
}
var fi = new FileInfo(f);
list.Add(new SaveFileEntry
{
FileName = fileName,
FilePath = f,
FileSize = fi.Length,
LastModified = fi.LastWriteTime,
LocationType = locationLabel,
IsTextOrJson = CheckIsTextOrJson(f)
});
}
}
catch { }
}
/// <summary>
/// ファイルがテキストまたはJSON形式か判定します。
/// </summary>
public bool CheckIsTextOrJson(string filePath)
{
try
{
var ext = Path.GetExtension(filePath).ToLowerInvariant();
if (ext is ".json" or ".xml" or ".txt" or ".ini" or ".yaml" or ".yml")
return true;
// ファイルの先頭512バイトを検査
using var fs = File.OpenRead(filePath);
var buffer = new byte[Math.Min(512, fs.Length)];
int read = fs.Read(buffer, 0, buffer.Length);
if (read == 0) return true;
// ヌル文字がほとんど無ければテキスト判定
int nullCount = buffer.Take(read).Count(b => b == 0);
return nullCount == 0;
}
catch
{
return false;
}
}
/// <summary>
/// セーブファイルをテキストとして読み出します。
/// </summary>
public string ReadSaveFileText(string filePath)
{
if (!File.Exists(filePath)) return string.Empty;
return File.ReadAllText(filePath, Encoding.UTF8);
}
/// <summary>
/// セーブファイルにテキストを書き込みます(書き込み前に自動で .bak バックアップを作成)。
/// </summary>
public bool WriteSaveFileText(string filePath, string newContent)
{
try
{
if (File.Exists(filePath))
{
// 自動バックアップ作成
var bakPath = filePath + ".bak";
File.Copy(filePath, bakPath, overwrite: true);
}
File.WriteAllText(filePath, newContent, Encoding.UTF8);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 単一のセーブファイルをバックアップフォルダへコピー保存します。
/// </summary>
public string? BackupSaveFile(string filePath, string backupDir)
{
if (!File.Exists(filePath)) return null;
try
{
if (!Directory.Exists(backupDir))
{
Directory.CreateDirectory(backupDir);
}
var fileName = Path.GetFileName(filePath);
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var destName = $"{Path.GetFileNameWithoutExtension(fileName)}_{timestamp}{Path.GetExtension(fileName)}";
var destPath = Path.Combine(backupDir, destName);
File.Copy(filePath, destPath, overwrite: true);
return destPath;
}
catch
{
return null;
}
}
/// <summary>
/// バックアップファイルからセーブファイルを復元します。
/// </summary>
public bool RestoreSaveFile(string backupFilePath, string targetFilePath)
{
if (!File.Exists(backupFilePath)) return false;
try
{
// 現在のファイルを退避
if (File.Exists(targetFilePath))
{
var tempBak = targetFilePath + ".pre_restore_bak";
File.Copy(targetFilePath, tempBak, overwrite: true);
}
File.Copy(backupFilePath, targetFilePath, overwrite: true);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// ゲーム専用のバックアップ一覧を取得します。
/// </summary>
public List<SaveBackupEntry> GetBackupList(UnityGameItem game)
{
var list = new List<SaveBackupEntry>();
var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
if (!Directory.Exists(backupDir)) return list;
try
{
var files = Directory.EnumerateFiles(backupDir);
foreach (var f in files)
{
var fi = new FileInfo(f);
var ext = fi.Extension.ToLowerInvariant();
string type = ext switch
{
".reg" => "レジストリ (.reg)",
".json" => "JSONバックアップ",
_ => "ファイルバックアップ"
};
list.Add(new SaveBackupEntry
{
Name = fi.Name,
BackupPath = f,
Timestamp = fi.LastWriteTime,
BackupType = type,
Note = $"{fi.Length / 1024.0:F1} KB"
});
}
}
catch { }
return list.OrderByDescending(b => b.Timestamp).ToList();
}
/// <summary>
/// エクスプローラーで指定フォルダを開きます。
/// </summary>
public static void OpenFolderInExplorer(string folderPath)
{
try
{
if (Directory.Exists(folderPath))
{
Process.Start(new ProcessStartInfo
{
FileName = folderPath,
UseShellExecute = true
});
}
else if (File.Exists(folderPath))
{
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = $"/select,\"{folderPath}\"",
UseShellExecute = true
});
}
}
catch { }
}
}
}