From a1430bbdbc6c664d89f6d2301b590ca029ff801a Mon Sep 17 00:00:00 2001 From: uduki Date: Tue, 6 Oct 2026 01:19:04 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20SRPG=20Studio=E5=AF=BE=E5=BF=9C?= =?UTF-8?q?=EF=BC=88data.dts=E8=A7=A3=E5=87=8D=E3=83=BB=E6=94=B9=E9=80=A0?= =?UTF-8?q?=E3=80=81=E3=83=97=E3=83=AD=E3=82=AD=E3=82=B7DLL=E5=80=8D?= =?UTF-8?q?=E9=80=9F=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Services/SrpgArchiveService.cs | 329 ++++++++++++++ Services/SrpgModService.cs | 757 +++++++++++++++++++++++++++++++++ 2 files changed, 1086 insertions(+) create mode 100644 Services/SrpgArchiveService.cs create mode 100644 Services/SrpgModService.cs diff --git a/Services/SrpgArchiveService.cs b/Services/SrpgArchiveService.cs new file mode 100644 index 0000000..5ecac66 --- /dev/null +++ b/Services/SrpgArchiveService.cs @@ -0,0 +1,329 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GameLauncher.Helpers; + +namespace GameLauncher.Services +{ + /// + /// SRPG Studio の data.dts アーカイブ解凍・抽出および再構築(再パック)サービス + /// 外部ツール Tools/SRPG_Unpacker.exe を利用して安全に展開・再構築を行います。 + /// バックアップはすべて Z:\自作ソフト\GameLauncher\Backups に保存されます。 + /// + public class SrpgArchiveService + { + public const string ExtractedDirName = "data_extracted"; + public const string ArchiveFileName = "data.dts"; + public const string ToolExeName = "SRPG_Unpacker.exe"; + + /// + /// SRPG_Unpacker.exe のフルパスを取得します。 + /// + public static string? GetToolPath() + { + var exeDir = AppPathHelper.GetExeDirectory(); + var path = Path.Combine(exeDir, "Tools", ToolExeName); + if (File.Exists(path)) return path; + + // プロジェクトルート等フォールバック + var fallback = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Tools", ToolExeName); + if (File.Exists(fallback)) return fallback; + + return null; + } + + /// + /// data.dts アーカイブが存在するか判定します。 + /// + public static bool HasDataDts(string gameDir) + { + return File.Exists(Path.Combine(gameDir, ArchiveFileName)); + } + + /// + /// 解凍済みフォルダ (data_extracted または Script & Plugin) が存在するか判定します。 + /// + public static bool IsExtracted(string gameDir) + { + var extractedDir = Path.Combine(gameDir, ExtractedDirName); + if (Directory.Exists(extractedDir)) return true; + + var scriptDir = Path.Combine(gameDir, "Script"); + var pluginDir = Path.Combine(gameDir, "Plugin"); + return Directory.Exists(scriptDir) && Directory.Exists(pluginDir); + } + + /// + /// 解凍先フォルダパスを取得します。 + /// + public static string GetExtractedDirectory(string gameDir) + { + var extractedDir = Path.Combine(gameDir, ExtractedDirName); + if (Directory.Exists(extractedDir)) return extractedDir; + + var scriptDir = Path.Combine(gameDir, "Script"); + if (Directory.Exists(scriptDir)) return gameDir; + + return extractedDir; + } + + /// + /// data.dts を解凍・抽出します。 + /// 実行前に data.dts を Backups フォルダにバックアップします。 + /// + public async Task<(bool Success, string Message)> UnpackDataDtsAsync(string gameDir, IProgress? progress = null) + { + return await Task.Run(() => + { + try + { + var dtsPath = Path.Combine(gameDir, ArchiveFileName); + if (!File.Exists(dtsPath)) + { + return (false, "data.dts が見つかりません。"); + } + + var tool = GetToolPath(); + if (tool == null) + { + return (false, $"解凍ツール ({ToolExeName}) が Tools フォルダに見つかりません。"); + } + + progress?.Report("data.dts のバックアップを作成中..."); + var backupDir = AppPathHelper.GetBackupsDirectory(); + var gameFolderName = Path.GetFileName(gameDir.TrimEnd('\\', '/')); + var timeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + var targetBackupDir = Path.Combine(backupDir, "SRPGStudio", $"{gameFolderName}_{timeStamp}"); + Directory.CreateDirectory(targetBackupDir); + + var backupFile = Path.Combine(targetBackupDir, ArchiveFileName); + File.Copy(dtsPath, backupFile, overwrite: true); + + var outDir = Path.Combine(gameDir, ExtractedDirName); + if (!Directory.Exists(outDir)) + { + Directory.CreateDirectory(outDir); + } + + progress?.Report("SRPG_Unpacker でアーカイブを解凍中..."); + var psi = new ProcessStartInfo + { + FileName = tool, + Arguments = $"\"{dtsPath}\" -o \"{outDir}\"", + WorkingDirectory = gameDir, + CreateNoWindow = true, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + + using var proc = Process.Start(psi); + if (proc == null) + { + return (false, "解凍プロセスの起動に失敗しました。"); + } + + string stdout = proc.StandardOutput.ReadToEnd(); + string stderr = proc.StandardError.ReadToEnd(); + proc.WaitForExit(); + + if (proc.ExitCode == 0) + { + progress?.Report("解凍が正常に完了しました。"); + return (true, $"data.dts を正常に {ExtractedDirName} フォルダへ展開しました。\n(バックアップ: {backupFile})"); + } + else + { + return (false, $"解凍処理でエラーが発生しました。(Code: {proc.ExitCode})\n{stderr}\n{stdout}"); + } + } + catch (Exception ex) + { + return (false, $"解凍処理中に例外が発生しました: {ex.Message}"); + } + }); + } + + /// + /// 解凍されたフォルダから data.dts を再構築(再パック)します。 + /// + public async Task<(bool Success, string Message)> RepackDataDtsAsync(string gameDir, IProgress? progress = null) + { + return await Task.Run(() => + { + try + { + var extractedDir = GetExtractedDirectory(gameDir); + if (!Directory.Exists(extractedDir)) + { + return (false, "展開済みフォルダが見つかりません。先に解凍を行ってください。"); + } + + var tool = GetToolPath(); + if (tool == null) + { + return (false, $"ツール ({ToolExeName}) が見つかりません。"); + } + + var dtsPath = Path.Combine(gameDir, ArchiveFileName); + var tempOutputDts = Path.Combine(gameDir, "data_temp_repack.dts"); + + progress?.Report("アーカイブを再構築(再パック)中..."); + var psi = new ProcessStartInfo + { + FileName = tool, + Arguments = $"\"{extractedDir}\" -o \"{tempOutputDts}\"", + WorkingDirectory = gameDir, + CreateNoWindow = true, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + + using var proc = Process.Start(psi); + if (proc == null) + { + return (false, "再パックプロセスの起動に失敗しました。"); + } + + string stdout = proc.StandardOutput.ReadToEnd(); + string stderr = proc.StandardError.ReadToEnd(); + proc.WaitForExit(); + + if (proc.ExitCode == 0 && File.Exists(tempOutputDts)) + { + // 既存の data.dts をバックアップした上で置き換え + if (File.Exists(dtsPath)) + { + var backupDir = AppPathHelper.GetBackupsDirectory(); + var gameFolderName = Path.GetFileName(gameDir.TrimEnd('\\', '/')); + var timeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + var targetBackupDir = Path.Combine(backupDir, "SRPGStudio", $"{gameFolderName}_{timeStamp}_repack_prev"); + Directory.CreateDirectory(targetBackupDir); + File.Copy(dtsPath, Path.Combine(targetBackupDir, ArchiveFileName), overwrite: true); + + File.Delete(dtsPath); + } + + File.Move(tempOutputDts, dtsPath); + progress?.Report("再パック完了。data.dts を更新しました。"); + return (true, "data.dts の再構築(再パック)が正常に完了しました。"); + } + else + { + if (File.Exists(tempOutputDts)) File.Delete(tempOutputDts); + return (false, $"再パック処理でエラーが発生しました。(Code: {proc.ExitCode})\n{stderr}\n{stdout}"); + } + } + catch (Exception ex) + { + return (false, $"再パック処理中に例外が発生しました: {ex.Message}"); + } + }); + } + + /// + /// 最新のバックアップから data.dts を復元します。 + /// + public async Task<(bool Success, string Message)> RevertBackupAsync(string gameDir) + { + return await Task.Run(() => + { + try + { + var backupDir = AppPathHelper.GetBackupsDirectory(); + var gameFolderName = Path.GetFileName(gameDir.TrimEnd('\\', '/')); + var targetBase = Path.Combine(backupDir, "SRPGStudio"); + if (!Directory.Exists(targetBase)) + { + return (false, "バックアップフォルダが見つかりません。"); + } + + // gameFolderName で始まるフォルダのうち最も新しいものを検索 + var dirs = Directory.GetDirectories(targetBase, $"{gameFolderName}_*") + .OrderByDescending(d => d) + .ToList(); + + if (dirs.Count == 0) + { + return (false, "該当するバックアップが見つかりません。"); + } + + foreach (var d in dirs) + { + var bakFile = Path.Combine(d, ArchiveFileName); + if (File.Exists(bakFile)) + { + var dstFile = Path.Combine(gameDir, ArchiveFileName); + File.Copy(bakFile, dstFile, overwrite: true); + return (true, $"バックアップ ({Path.GetFileName(d)}) から data.dts を正常に復元しました。"); + } + } + + return (false, "バックアップファイルが見つかりませんでした。"); + } + catch (Exception ex) + { + return (false, $"復元処理中に例外が発生しました: {ex.Message}"); + } + }); + } + + /// + /// 解凍されたフォルダ (data_extracted) を Backups フォルダへ安全に退避し、 + /// ゲームディレクトリ内を元の data.dts のみの状態に復元します。 + /// + public (bool Success, string Message) RestoreExtractedState(string gameDir) + { + try + { + var extractedDir = Path.Combine(gameDir, ExtractedDirName); + if (!Directory.Exists(extractedDir)) + { + return (true, "解凍フォルダは存在しません。"); + } + + var backupDir = AppPathHelper.GetBackupsDirectory(); + var gameFolderName = Path.GetFileName(gameDir.TrimEnd('\\', '/')); + var timeStamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); + var targetBackupDir = Path.Combine(backupDir, "SRPGStudio", $"{gameFolderName}_{timeStamp}_extracted_evacuated"); + + Directory.CreateDirectory(targetBackupDir); + var dst = Path.Combine(targetBackupDir, ExtractedDirName); + + // ディレクトリ移動(別ドライブ考慮でフォールバック) + try + { + Directory.Move(extractedDir, dst); + } + catch + { + // コピー後に削除 + CopyDirectory(extractedDir, dst); + Directory.Delete(extractedDir, true); + } + + return (true, $"解凍フォルダ ({ExtractedDirName}) を Backups フォルダへ退避しました。"); + } + catch (Exception ex) + { + return (false, $"解凍フォルダ退避中にエラーが発生しました: {ex.Message}"); + } + } + + private static void CopyDirectory(string sourceDir, string targetDir) + { + Directory.CreateDirectory(targetDir); + foreach (var file in Directory.GetFiles(sourceDir)) + { + File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)), true); + } + foreach (var subDir in Directory.GetDirectories(sourceDir)) + { + CopyDirectory(subDir, Path.Combine(targetDir, Path.GetFileName(subDir))); + } + } + } +} diff --git a/Services/SrpgModService.cs b/Services/SrpgModService.cs new file mode 100644 index 0000000..9269d06 --- /dev/null +++ b/Services/SrpgModService.cs @@ -0,0 +1,757 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using GameLauncher.Helpers; +using GameLauncher.Models; + +namespace GameLauncher.Services +{ + /// + /// SRPG Studio ゲームの機能拡張(プロキシDLL・倍速機能、Modスクリプト注入・再構築)サービス + /// + public class SrpgModService + { + public const string ProxyDllName = "version.dll"; + public const string ConfigFileName = "speedhack_config.json"; + public const string ModScriptFileName = "99_AntigravityMod.js"; + + private readonly SrpgArchiveService _archiveService = new(); + + /// + /// プロキシDLL(version.dll)および設定ファイルをゲームディレクトリに配置し、倍速機能を有効化します。 + /// + public bool EnableProxyDll(string gameDir, double speedMultiplier = 3.0) + { + try + { + var srcDll = Path.Combine(AppPathHelper.GetExeDirectory(), "Tools", "speedhack-i686", ProxyDllName); + if (!File.Exists(srcDll)) + { + srcDll = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Tools", "speedhack-i686", ProxyDllName); + } + + if (!File.Exists(srcDll)) + { + return false; + } + + var dstDll = Path.Combine(gameDir, ProxyDllName); + File.Copy(srcDll, dstDll, overwrite: true); + + var config = new + { + speed = Math.Max(1.0, speedMultiplier), + toggle_key = "F6", + fast_key = "Control", + fast_multiplier = 5.0 + }; + var json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true }); + File.WriteAllText(Path.Combine(gameDir, ConfigFileName), json, Encoding.UTF8); + + return true; + } + catch + { + return false; + } + } + + /// + /// プロキシDLLおよび設定ファイルを削除し、通常動作に戻します。 + /// + public bool DisableProxyDll(string gameDir) + { + try + { + var dstDll = Path.Combine(gameDir, ProxyDllName); + if (File.Exists(dstDll)) + { + File.Delete(dstDll); + } + + var configFile = Path.Combine(gameDir, ConfigFileName); + if (File.Exists(configFile)) + { + File.Delete(configFile); + } + + return true; + } + catch + { + return false; + } + } + + /// + /// プロキシDLLが適用されているか確認します。 + /// + public static bool IsProxyDllEnabled(string gameDir) + { + return File.Exists(Path.Combine(gameDir, ProxyDllName)); + } + + /// + /// プラグイン改造が適用されているか確認します。 + /// + public static bool IsModScriptApplied(string gameDir) + { + var extractedDir = SrpgArchiveService.GetExtractedDirectory(gameDir); + var modJs = Path.Combine(extractedDir, "Plugin", ModScriptFileName); + return File.Exists(modJs); + } + + /// + /// 選択されたModオプションから JavaScript スクリプトコードを生成します。 + /// + public string GenerateModScript(TkoolGameItem item) + { + var sb = new StringBuilder(); + sb.AppendLine("/* ========================================================================= */"); + sb.AppendLine("/* Antigravity GameLauncher - SRPG Studio 統合拡張プラグイン */"); + sb.AppendLine("/* ========================================================================= */"); + sb.AppendLine("(function() {"); + sb.AppendLine(" 'use strict';"); + sb.AppendLine(); + + // 1. 武器・アイテム耐久度無限 + if (item.IsPluginEnabled("SrpgInfDurability")) + { + sb.AppendLine(" // [チート] 武器・アイテム耐久度無限"); + sb.AppendLine(" if (typeof ItemControl !== 'undefined') {"); + sb.AppendLine(" if (ItemControl.decreaseLimit) {"); + sb.AppendLine(" var _orig_decreaseLimit = ItemControl.decreaseLimit;"); + sb.AppendLine(" ItemControl.decreaseLimit = function(unit, item) {"); + sb.AppendLine(" if (unit && unit.getUnitType && unit.getUnitType() === UnitType.PLAYER) {"); + sb.AppendLine(" return; // 味方ユニットの耐久度は消費しない"); + sb.AppendLine(" }"); + sb.AppendLine(" return _orig_decreaseLimit.call(this, unit, item);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (ItemControl.isItemBroken) {"); + sb.AppendLine(" ItemControl.isItemBroken = function(item) {"); + sb.AppendLine(" return false; // 武器破損を防止"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" }"); + sb.AppendLine(" if (typeof DataConfig !== 'undefined' && DataConfig.isWeaponInfinity) {"); + sb.AppendLine(" DataConfig.isWeaponInfinity = function() { return true; };"); + sb.AppendLine(" }"); + sb.AppendLine(); + } + + // 2. 獲得経験値最大化(即レベルアップ / 100Exp固定) + if (item.IsPluginEnabled("SrpgExpBoost")) + { + sb.AppendLine(" // [チート] 獲得経験値最大化 (戦闘・アイテム使用時即レベルアップ)"); + sb.AppendLine(" if (typeof ExperienceCalculator !== 'undefined') {"); + sb.AppendLine(" if (ExperienceCalculator.calculateExperience) {"); + sb.AppendLine(" ExperienceCalculator.calculateExperience = function(data) {"); + sb.AppendLine(" return 100;"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (ExperienceCalculator.getBestExperience) {"); + sb.AppendLine(" ExperienceCalculator.getBestExperience = function(unit, exp) {"); + sb.AppendLine(" return 100;"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" }"); + sb.AppendLine(); + } + + // 共通ユーティリティ: 味方ユニット判定関数 + sb.AppendLine(" // [共通] 味方ユニット判定 (敵以外はすべて味方・自軍として扱う)"); + sb.AppendLine(" function __antigravity_isPlayerSide(unit) {"); + sb.AppendLine(" if (!unit) return false;"); + sb.AppendLine(" try {"); + sb.AppendLine(" var ut = (typeof unit.getUnitType === 'function') ? unit.getUnitType() : -1;"); + sb.AppendLine(" // 敵 (1 = UnitType.ENEMY) 以外は味方/自軍とみなす"); + sb.AppendLine(" if (ut === 1) return false;"); + sb.AppendLine(" return true;"); + sb.AppendLine(" } catch (e) { return true; }"); + sb.AppendLine(" }"); + sb.AppendLine(); + sb.AppendLine(" // [共通] 移動力ブースト対象判定 (敵以外 = 自軍・同盟軍。敵は除外)"); + sb.AppendLine(" function __antigravity_isMovTarget(unit) {"); + sb.AppendLine(" if (!unit) return false;"); + sb.AppendLine(" try {"); + sb.AppendLine(" return (typeof unit.getUnitType === 'function') && unit.getUnitType() !== 1;"); + sb.AppendLine(" } catch (e) { return false; }"); + sb.AppendLine(" }"); + sb.AppendLine(); + + // 3. 所持金最大化 & ターン開始時全回復 + bool hasMaxGold = item.IsPluginEnabled("SrpgMaxGold"); + bool hasRecoverHp = item.IsPluginEnabled("SrpgTurnRecoverHp"); + + if (hasMaxGold || hasRecoverHp) + { + sb.AppendLine(" // [チート] 味方全回復関数 & 所持金最大化関数"); + if (hasRecoverHp) + { + sb.AppendLine(" function __antigravity_healAllUnits() {"); + sb.AppendLine(" try {"); + sb.AppendLine(" var processedUnits = [];"); + sb.AppendLine(" var unitList = [];"); + sb.AppendLine(); + sb.AppendLine(" // 1. 各種リストから自軍ユニットを収集"); + sb.AppendLine(" if (typeof PlayerList !== 'undefined') {"); + sb.AppendLine(" if (typeof PlayerList.getSortieList === 'function') {"); + sb.AppendLine(" var sList = PlayerList.getSortieList();"); + sb.AppendLine(" if (sList && sList.getCount) { for (var i = 0; i < sList.getCount(); i++) unitList.push(sList.getData(i)); }"); + sb.AppendLine(" }"); + sb.AppendLine(" if (typeof PlayerList.getAliveList === 'function') {"); + sb.AppendLine(" var aList = PlayerList.getAliveList();"); + sb.AppendLine(" if (aList && aList.getCount) { for (var i = 0; i < aList.getCount(); i++) unitList.push(aList.getData(i)); }"); + sb.AppendLine(" }"); + sb.AppendLine(" }"); + sb.AppendLine(" if (typeof TurnControl !== 'undefined' && typeof TurnControl.getActorList === 'function') {"); + sb.AppendLine(" var tList = TurnControl.getActorList();"); + sb.AppendLine(" if (tList && tList.getCount) { for (var i = 0; i < tList.getCount(); i++) unitList.push(tList.getData(i)); }"); + sb.AppendLine(" }"); + sb.AppendLine(); + sb.AppendLine(" // 2. マップ上の全座標を走査 (ゲスト・NPC・未登録ユニットも100%捕捉)"); + sb.AppendLine(" if (typeof CurrentMap !== 'undefined' && typeof PosChecker !== 'undefined') {"); + sb.AppendLine(" try {"); + sb.AppendLine(" var mapW = CurrentMap.getWidth();"); + sb.AppendLine(" var mapH = CurrentMap.getHeight();"); + sb.AppendLine(" for (var mx = 0; mx < mapW; mx++) {"); + sb.AppendLine(" for (var my = 0; my < mapH; my++) {"); + sb.AppendLine(" var mu = PosChecker.getUnitFromPos(mx, my);"); + sb.AppendLine(" if (mu) unitList.push(mu);"); + sb.AppendLine(" } "); + sb.AppendLine(" }"); + sb.AppendLine(" } catch (eScan) {}"); + sb.AppendLine(" }"); + sb.AppendLine(); + sb.AppendLine(" // 3. 敵以外の全ユニットのHPを最大化"); + sb.AppendLine(" for (var j = 0; j < unitList.length; j++) {"); + sb.AppendLine(" var u = unitList[j];"); + sb.AppendLine(" if (!u || typeof u.setHp !== 'function' || typeof u.getId !== 'function') continue;"); + sb.AppendLine(" var uid = u.getId();"); + sb.AppendLine(" if (processedUnits.indexOf(uid) !== -1) continue;"); + sb.AppendLine(" processedUnits.push(uid);"); + sb.AppendLine(); + sb.AppendLine(" if (!__antigravity_isPlayerSide(u)) continue;"); + sb.AppendLine(); + sb.AppendLine(" try {"); + sb.AppendLine(" var maxHp = 0;"); + sb.AppendLine(" if (typeof ParamBonus !== 'undefined' && typeof ParamBonus.getMhp === 'function') {"); + sb.AppendLine(" maxHp = ParamBonus.getMhp(u);"); + sb.AppendLine(" }"); + sb.AppendLine(" if (maxHp <= 0 && typeof RealBonus !== 'undefined' && typeof RealBonus.getMhp === 'function') {"); + sb.AppendLine(" maxHp = RealBonus.getMhp(u);"); + sb.AppendLine(" }"); + sb.AppendLine(" if (maxHp <= 0) maxHp = 99;"); + sb.AppendLine(" u.setHp(maxHp);"); + sb.AppendLine(" } catch (e2) {}"); + sb.AppendLine(" }"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" }"); + sb.AppendLine(); + } + + if (hasMaxGold) + { + sb.AppendLine(" function __antigravity_maxGold() {"); + sb.AppendLine(" try {"); + sb.AppendLine(" if (typeof root !== 'undefined' && root.getMetaSession) {"); + sb.AppendLine(" var meta = root.getMetaSession();"); + sb.AppendLine(" if (meta && meta.setGold) { meta.setGold(999999); }"); + sb.AppendLine(" }"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" }"); + sb.AppendLine(); + } + + if (hasRecoverHp) + { + sb.AppendLine(" // ターン開始時自動回復フローへの介入 (公式のターン開始回復で確実に最大HP全快)"); + sb.AppendLine(" if (typeof RecoveryAllFlowEntry !== 'undefined') {"); + sb.AppendLine(" if (RecoveryAllFlowEntry._getRecoveryValue) {"); + sb.AppendLine(" var _orig_RecoveryAllFlowEntry_getRecoveryValue = RecoveryAllFlowEntry._getRecoveryValue;"); + sb.AppendLine(" RecoveryAllFlowEntry._getRecoveryValue = function(unit) {"); + sb.AppendLine(" try {"); + sb.AppendLine(" if (__antigravity_isPlayerSide(unit)) {"); + sb.AppendLine(" var mhp = (typeof ParamBonus !== 'undefined' && ParamBonus.getMhp) ? ParamBonus.getMhp(unit) : 99;"); + sb.AppendLine(" return Math.max(mhp, 999);"); + sb.AppendLine(" }"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return _orig_RecoveryAllFlowEntry_getRecoveryValue.call(this, unit);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (RecoveryAllFlowEntry._completeMemberData) {"); + sb.AppendLine(" var _orig_RecoveryAllFlowEntry_completeMemberData = RecoveryAllFlowEntry._completeMemberData;"); + sb.AppendLine(" RecoveryAllFlowEntry._completeMemberData = function(turnChange) {"); + sb.AppendLine(" try { __antigravity_healAllUnits(); } catch (e) {}"); + sb.AppendLine(" return _orig_RecoveryAllFlowEntry_completeMemberData.call(this, turnChange);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" }"); + sb.AppendLine(); + } + + sb.AppendLine(" // A. プレイヤーターン開始時に実行 (PlayerTurn.openTurnCycle)"); + sb.AppendLine(" if (typeof PlayerTurn !== 'undefined' && PlayerTurn.openTurnCycle) {"); + sb.AppendLine(" var _orig_PlayerTurn_openTurnCycle = PlayerTurn.openTurnCycle;"); + sb.AppendLine(" PlayerTurn.openTurnCycle = function() {"); + sb.AppendLine(" var result = _orig_PlayerTurn_openTurnCycle.call(this);"); + sb.AppendLine(" try {"); + if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();"); + if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return result;"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(); + sb.AppendLine(" // A2. プレイヤー行動中サイクル (PlayerTurn.moveTurnCycle - セーブロード直後にも即座に反映)"); + sb.AppendLine(" if (typeof PlayerTurn !== 'undefined' && PlayerTurn.moveTurnCycle) {"); + sb.AppendLine(" var _orig_PlayerTurn_moveTurnCycle = PlayerTurn.moveTurnCycle;"); + sb.AppendLine(" PlayerTurn.moveTurnCycle = function() {"); + sb.AppendLine(" try {"); + if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();"); + if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return _orig_PlayerTurn_moveTurnCycle.call(this);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(); + sb.AppendLine(" // B. ターン切替処理時 (TurnChangeEnd.doLastAction & TurnChangeStart.doLastAction)"); + sb.AppendLine(" if (typeof TurnChangeEnd !== 'undefined' && TurnChangeEnd.doLastAction) {"); + sb.AppendLine(" var _orig_TurnChangeEnd_doLastAction = TurnChangeEnd.doLastAction;"); + sb.AppendLine(" TurnChangeEnd.doLastAction = function() {"); + sb.AppendLine(" _orig_TurnChangeEnd_doLastAction.call(this);"); + sb.AppendLine(" try {"); + if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();"); + if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (typeof TurnChangeStart !== 'undefined' && TurnChangeStart.doLastAction) {"); + sb.AppendLine(" var _orig_TurnChangeStart_doLastAction = TurnChangeStart.doLastAction;"); + sb.AppendLine(" TurnChangeStart.doLastAction = function() {"); + sb.AppendLine(" _orig_TurnChangeStart_doLastAction.call(this);"); + sb.AppendLine(" try {"); + if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();"); + if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(); + sb.AppendLine(" // B2. ターンロゴ表示時 (BaseTurnLogoFlowEntry.doMainAction)"); + sb.AppendLine(" if (typeof BaseTurnLogoFlowEntry !== 'undefined' && BaseTurnLogoFlowEntry.doMainAction) {"); + sb.AppendLine(" var _orig_BaseTurnLogoFlowEntry_doMainAction = BaseTurnLogoFlowEntry.doMainAction;"); + sb.AppendLine(" BaseTurnLogoFlowEntry.doMainAction = function(isMusic) {"); + sb.AppendLine(" var res = _orig_BaseTurnLogoFlowEntry_doMainAction.call(this, isMusic);"); + sb.AppendLine(" try {"); + if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();"); + if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return res;"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(); + sb.AppendLine(" // C. マップ開始時 (CurrentMap.prepareMap)"); + sb.AppendLine(" if (typeof CurrentMap !== 'undefined' && CurrentMap.prepareMap) {"); + sb.AppendLine(" var _orig_CurrentMap_prepareMap = CurrentMap.prepareMap;"); + sb.AppendLine(" CurrentMap.prepareMap = function() {"); + sb.AppendLine(" _orig_CurrentMap_prepareMap.call(this);"); + sb.AppendLine(" try {"); + if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();"); + if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(); + sb.AppendLine(" // D. ユニット移動選択画面開始時 (MapSequenceArea.openSequence)"); + sb.AppendLine(" if (typeof MapSequenceArea !== 'undefined' && MapSequenceArea.openSequence) {"); + sb.AppendLine(" var _orig_MapSequenceArea_openSequence = MapSequenceArea.openSequence;"); + sb.AppendLine(" MapSequenceArea.openSequence = function(parentTurnObject) {"); + sb.AppendLine(" try {"); + if (hasRecoverHp) sb.AppendLine(" __antigravity_healAllUnits();"); + if (hasMaxGold) sb.AppendLine(" __antigravity_maxGold();"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return _orig_MapSequenceArea_openSequence.call(this, parentTurnObject);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(); + } + + // 4. 味方移動力最大化 (マップ全域移動可能: 99固定) + if (item.IsPluginEnabled("SrpgMoveBoost")) + { + sb.AppendLine(" // [チート] 自軍ユニットの移動可能範囲最大化 (移動力99)"); + sb.AppendLine(" if (typeof ParamBonus !== 'undefined' && ParamBonus.getMov) {"); + sb.AppendLine(" var _orig_ParamBonus_getMov = ParamBonus.getMov;"); + sb.AppendLine(" ParamBonus.getMov = function(unit) {"); + sb.AppendLine(" try {"); + sb.AppendLine(" if (__antigravity_isMovTarget(unit)) return 99;"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return _orig_ParamBonus_getMov.call(this, unit);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (typeof RealBonus !== 'undefined' && RealBonus.getMov) {"); + sb.AppendLine(" var _orig_RealBonus_getMov = RealBonus.getMov;"); + sb.AppendLine(" RealBonus.getMov = function(unit) {"); + sb.AppendLine(" try {"); + sb.AppendLine(" if (__antigravity_isMovTarget(unit)) return 99;"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return _orig_RealBonus_getMov.call(this, unit);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (typeof UnitParameter !== 'undefined' && UnitParameter.MOV && UnitParameter.MOV.getUnitValue) {"); + sb.AppendLine(" var _orig_UnitParameter_MOV_getUnitValue = UnitParameter.MOV.getUnitValue;"); + sb.AppendLine(" UnitParameter.MOV.getUnitValue = function(unit) {"); + sb.AppendLine(" try {"); + sb.AppendLine(" if (__antigravity_isMovTarget(unit)) return 99;"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return _orig_UnitParameter_MOV_getUnitValue.call(this, unit);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (typeof UnitRangePanel !== 'undefined') {"); + sb.AppendLine(" if (UnitRangePanel._getRangeMov) {"); + sb.AppendLine(" var _orig_UnitRangePanel_getRangeMov = UnitRangePanel._getRangeMov;"); + sb.AppendLine(" UnitRangePanel._getRangeMov = function(unit) {"); + sb.AppendLine(" try {"); + sb.AppendLine(" if (__antigravity_isMovTarget(unit)) return 99;"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return _orig_UnitRangePanel_getRangeMov.call(this, unit);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (UnitRangePanel.getUnitAttackRange) {"); + sb.AppendLine(" var _orig_UnitRangePanel_getUnitAttackRange = UnitRangePanel.getUnitAttackRange;"); + sb.AppendLine(" UnitRangePanel.getUnitAttackRange = function(unit) {"); + sb.AppendLine(" var obj = _orig_UnitRangePanel_getUnitAttackRange.call(this, unit);"); + sb.AppendLine(" try {"); + sb.AppendLine(" if (obj && __antigravity_isMovTarget(unit)) {"); + sb.AppendLine(" obj.mov = 99;"); + sb.AppendLine(" }"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return obj;"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (UnitRangePanel._setRangeData) {"); + sb.AppendLine(" var _orig_UnitRangePanel_setRangeData = UnitRangePanel._setRangeData;"); + sb.AppendLine(" UnitRangePanel._setRangeData = function() {"); + sb.AppendLine(" try {"); + sb.AppendLine(" if (this._unit && __antigravity_isMovTarget(this._unit)) {"); + sb.AppendLine(" var attackRange = this.getUnitAttackRange(this._unit);"); + sb.AppendLine(" var isWeapon = attackRange.endRange !== 0;"); + sb.AppendLine(" if (isWeapon) {"); + sb.AppendLine(" this._simulator.startSimulationWeapon(this._unit, 99, attackRange.startRange, attackRange.endRange);"); + sb.AppendLine(" } else {"); + sb.AppendLine(" this._simulator.startSimulation(this._unit, 99);"); + sb.AppendLine(" }"); + sb.AppendLine(" this._setLight(isWeapon);"); + sb.AppendLine(" return;"); + sb.AppendLine(" }"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return _orig_UnitRangePanel_setRangeData.call(this);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (UnitRangePanel._setRepeatRangeData) {"); + sb.AppendLine(" var _orig_UnitRangePanel_setRepeatRangeData = UnitRangePanel._setRepeatRangeData;"); + sb.AppendLine(" UnitRangePanel._setRepeatRangeData = function() {"); + sb.AppendLine(" try {"); + sb.AppendLine(" if (this._unit && __antigravity_isMovTarget(this._unit)) {"); + sb.AppendLine(" var attackRange = this.getUnitAttackRange(this._unit);"); + sb.AppendLine(" var isWeapon = attackRange.endRange !== 0;"); + sb.AppendLine(" if (isWeapon) {"); + sb.AppendLine(" this._simulator.startSimulationWeapon(this._unit, 99, attackRange.startRange, attackRange.endRange);"); + sb.AppendLine(" } else {"); + sb.AppendLine(" this._simulator.startSimulation(this._unit, 99);"); + sb.AppendLine(" }"); + sb.AppendLine(" this._setLight(isWeapon);"); + sb.AppendLine(" return;"); + sb.AppendLine(" }"); + sb.AppendLine(" } catch (e) {}"); + sb.AppendLine(" return _orig_UnitRangePanel_setRepeatRangeData.call(this);"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" }"); + sb.AppendLine(); + } + + // 5. 敵撃破時アイテム100%ドロップ + if (item.IsPluginEnabled("SrpgItemAllDrop")) + { + sb.AppendLine(" // [チート] 敵撃破時アイテム100%ドロップ"); + sb.AppendLine(" if (typeof ItemDropControl !== 'undefined' && ItemDropControl.isDropAllowed) {"); + sb.AppendLine(" ItemDropControl.isDropAllowed = function(unit) {"); + sb.AppendLine(" return true;"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(" if (typeof DropTrophyControl !== 'undefined' && DropTrophyControl.isDropAllowed) {"); + sb.AppendLine(" DropTrophyControl.isDropAllowed = function(unit) {"); + sb.AppendLine(" return true;"); + sb.AppendLine(" };"); + sb.AppendLine(" }"); + sb.AppendLine(); + } + + sb.AppendLine("})();"); + return sb.ToString(); + } + + public const string ModStartTag = "// >>> ANTIGRAVITY_MOD_START >>>"; + public const string ModEndTag = "// <<< ANTIGRAVITY_MOD_END <<<"; + + /// + /// 既存スクリプトファイルへModコードを注入(または更新)します。 + /// + private static void InjectModToExistingScript(string scriptPath, string modCode) + { + if (!File.Exists(scriptPath)) return; + + try + { + string content = File.ReadAllText(scriptPath, Encoding.UTF8); + int startIdx = content.IndexOf(ModStartTag, StringComparison.Ordinal); + if (startIdx >= 0) + { + int endIdx = content.IndexOf(ModEndTag, StringComparison.Ordinal); + if (endIdx > startIdx) + { + content = content.Substring(0, startIdx).TrimEnd() + "\n\n" + modCode + "\n"; + File.WriteAllText(scriptPath, content, Encoding.UTF8); + return; + } + } + + content = content.TrimEnd() + "\n\n" + modCode + "\n"; + File.WriteAllText(scriptPath, content, Encoding.UTF8); + } + catch { } + } + + /// + /// 既存スクリプトファイルから注入されたModコードを削除します。 + /// + private static void RemoveModFromExistingScript(string scriptPath) + { + if (!File.Exists(scriptPath)) return; + + try + { + string content = File.ReadAllText(scriptPath, Encoding.UTF8); + int startIdx = content.IndexOf(ModStartTag, StringComparison.Ordinal); + if (startIdx >= 0) + { + int endIdx = content.IndexOf(ModEndTag, StringComparison.Ordinal); + if (endIdx > startIdx) + { + endIdx += ModEndTag.Length; + content = content.Remove(startIdx, endIdx - startIdx).TrimEnd() + "\n"; + File.WriteAllText(scriptPath, content, Encoding.UTF8); + } + } + } + catch { } + } + + /// + /// Modスクリプトを展開フォルダ内の既存スクリプト群に注入し、data.dts を再構築します。 + /// (SRPG_Unpackerの仕様上、新規ファイル名は無視されるため、既存ファイルへの確実な注入を行います) + /// + public async Task<(bool Success, string Message)> ApplyModAndRepackAsync(TkoolGameItem item, IProgress? progress = null) + { + var gameDir = item.RootDirectory; + + // 1. まだ解凍されていない場合は解凍を実行 + if (!SrpgArchiveService.IsExtracted(gameDir)) + { + progress?.Report("アーカイブ(data.dts)を初回展開中..."); + var unpackRes = await _archiveService.UnpackDataDtsAsync(gameDir, progress); + if (!unpackRes.Success) + { + return unpackRes; + } + } + + var extractedDir = SrpgArchiveService.GetExtractedDirectory(gameDir); + progress?.Report("Modスクリプトを生成中..."); + var modBody = GenerateModScript(item); + var jsContent = $"{ModStartTag}\n{modBody}\n{ModEndTag}"; + + // 2. 既存のスクリプトへ注入 + // (Pluginフォルダ内の既存スクリプトは全標準スクリプト読み込み完了後に実行されるため最優先で注入) + var mainScript = Path.Combine(extractedDir, "Script", "map", "map-playerturn.js"); + var turnChangeScript = Path.Combine(extractedDir, "Script", "map", "map-turnchange.js"); + var pluginDir = Path.Combine(extractedDir, "Plugin"); + + progress?.Report("スクリプトへModコードを注入中..."); + InjectModToExistingScript(mainScript, jsContent); + InjectModToExistingScript(turnChangeScript, jsContent); + + if (Directory.Exists(pluginDir)) + { + var existingPlugin = Directory.GetFiles(pluginDir, "*.js") + .FirstOrDefault(f => !Path.GetFileName(f).StartsWith("99_AntigravityMod", StringComparison.OrdinalIgnoreCase)); + if (existingPlugin != null) + { + InjectModToExistingScript(existingPlugin, jsContent); + } + } + + try + { + var directPluginDir = Path.Combine(gameDir, "Plugin"); + if (!Directory.Exists(directPluginDir)) Directory.CreateDirectory(directPluginDir); + File.WriteAllText(Path.Combine(directPluginDir, ModScriptFileName), jsContent, Encoding.UTF8); + } + catch { } + + // 3. data.dts を再パック + progress?.Report("Modを適用した data.dts を再構築中..."); + var repackRes = await _archiveService.RepackDataDtsAsync(gameDir, progress); + if (repackRes.Success) + { + item.IsModded = true; + item.IsSrpgExtracted = true; + return (true, "SRPG Studio 改造プラグインの注入とアーカイブ再構築が完了しました!"); + } + else + { + return repackRes; + } + } + + /// + /// Modスクリプトの注入を解除し、data.dts を再構築(またはバックアップから復元)します。 + /// + public async Task<(bool Success, string Message)> RemoveModAndRepackAsync(TkoolGameItem item, IProgress? progress = null) + { + var gameDir = item.RootDirectory; + var extractedDir = SrpgArchiveService.GetExtractedDirectory(gameDir); + + // 1. 注入したスクリプトからModコードを削除 + var targets = new List + { + Path.Combine(extractedDir, "Script", "map", "map-playerturn.js"), + Path.Combine(extractedDir, "Script", "map", "map-turnchange.js"), + Path.Combine(extractedDir, "Script", "singleton", "singleton-system.js") + }; + var pluginDir = Path.Combine(extractedDir, "Plugin"); + if (Directory.Exists(pluginDir)) + { + foreach (var f in Directory.GetFiles(pluginDir, "*.js")) + { + targets.Add(f); + } + } + + foreach (var target in targets) + { + RemoveModFromExistingScript(target); + } + + var modJsPath = Path.Combine(pluginDir, ModScriptFileName); + if (File.Exists(modJsPath)) File.Delete(modJsPath); + + try + { + var directModJs = Path.Combine(gameDir, "Plugin", ModScriptFileName); + if (File.Exists(directModJs)) File.Delete(directModJs); + } + catch { } + + // 2. バックアップが存在すればバックアップ復元を試行 + progress?.Report("オリジナルバックアップから data.dts を復元中..."); + var revertRes = await _archiveService.RevertBackupAsync(gameDir); + if (revertRes.Success) + { + item.IsModded = false; + return (true, "改造プラグインを解除し、元のアーカイブへ復元しました。"); + } + + // バックアップが無い場合は Mod解除状態で再パック + progress?.Report("Mod解除状態でアーカイブを再構築中..."); + var repackRes = await _archiveService.RepackDataDtsAsync(gameDir, progress); + if (repackRes.Success) + { + item.IsModded = false; + return (true, "改造プラグインを解除し、アーカイブを再構築しました。"); + } + + return repackRes; + } + + /// + /// SRPG Studio ゲームに対するすべての改造(プロキシDLL・プラグイン改造・解凍データ等)を完全に解除し、 + /// 元の安全な状態に復元します。 + /// + public async Task<(bool Success, string Message)> RestoreAllModsAsync(TkoolGameItem item, IProgress? progress = null) + { + var logs = new List(); + var gameDir = item.RootDirectory; + + // 1. プロキシDLL解除 + if (IsProxyDllEnabled(gameDir)) + { + DisableProxyDll(gameDir); + logs.Add("・プロキシDLL (version.dll) を解除しました"); + } + + // 2. 注入コードおよびModプラグインの削除 + var extractedDir = SrpgArchiveService.GetExtractedDirectory(gameDir); + var targets = new List + { + Path.Combine(extractedDir, "Script", "map", "map-playerturn.js"), + Path.Combine(extractedDir, "Script", "singleton", "singleton-system.js") + }; + var pluginDir = Path.Combine(extractedDir, "Plugin"); + if (Directory.Exists(pluginDir)) + { + foreach (var f in Directory.GetFiles(pluginDir, "*.js")) targets.Add(f); + } + foreach (var t in targets) RemoveModFromExistingScript(t); + + var modJsPath = Path.Combine(pluginDir, ModScriptFileName); + if (File.Exists(modJsPath)) + { + File.Delete(modJsPath); + logs.Add($"・Modプラグインスクリプト ({ModScriptFileName}) を削除しました"); + } + + try + { + var directModJs = Path.Combine(gameDir, "Plugin", ModScriptFileName); + if (File.Exists(directModJs)) + { + File.Delete(directModJs); + } + } + catch { } + + // 3. バックアップからの data.dts 復元 + progress?.Report("バックアップから元の data.dts を復元中..."); + var revertRes = await _archiveService.RevertBackupAsync(gameDir); + if (revertRes.Success) + { + logs.Add($"・{revertRes.Message}"); + } + else + { + logs.Add("・元の data.dts バックアップは適用不要または存在しませんでした"); + } + + // 4. 解凍フォルダの退避 + var restoreExtractedRes = _archiveService.RestoreExtractedState(gameDir); + if (restoreExtractedRes.Success && !restoreExtractedRes.Message.Contains("存在しません")) + { + logs.Add($"・{restoreExtractedRes.Message}"); + } + + // 5. フラグ更新 + item.SrpgProxyDll = false; + item.IsModded = false; + item.IsSrpgExtracted = false; + + string summary = logs.Count > 0 ? string.Join("\n", logs) : "解除対象の改造はありませんでした。"; + return (true, summary); + } + } +}