機能追加: Bakin・NW.jsエンジンおよびセーブ編集対応、ES3パスワード解決機能とRPGツクールMZ修正サービスの追加
This commit is contained in:
1 parent
f50976a6c0
commit
152abae1f8
33 files changed
+11356
-175
No files matched your search
@@ -0,0 +1,252 @@
|
||||
// Engines/Bakin/BakinDetector.cs — RPG Developer Bakin (Smile Game Builder 系 YUKRDATA) ゲーム検出ヘルパー
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Windows.Media;
|
||||
using GameLauncher.Engines.Tkool;
|
||||
using GameLauncher.Engines.Unity;
|
||||
|
||||
namespace GameLauncher.Engines.Bakin
|
||||
{
|
||||
/// <summary>
|
||||
/// RPG Developer Bakin / Smile Game Builder 系ゲームの検出およびメタデータ解決を行うヘルパークラス。
|
||||
/// </summary>
|
||||
public static class BakinDetector
|
||||
{
|
||||
#region □変数(Private)
|
||||
|
||||
private static readonly HashSet<string> ExcludedExeNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"bakinplayer.exe",
|
||||
"notification_helper.exe",
|
||||
"crashpad_handler.exe",
|
||||
"elevate.exe",
|
||||
"UnityCrashHandler32.exe",
|
||||
"UnityCrashHandler64.exe"
|
||||
};
|
||||
|
||||
#endregion
|
||||
|
||||
#region □メソッド(Public)
|
||||
|
||||
/// <summary>
|
||||
/// 指定されたディレクトリが RPG Developer Bakin 製ゲームであるかを判定します。
|
||||
/// </summary>
|
||||
/// <param name="dirPath">対象ディレクトリパス</param>
|
||||
/// <returns>Bakin ゲームであれば true</returns>
|
||||
public static bool IsBakinGame(string dirPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dirPath) || !Directory.Exists(dirPath))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var dataSubDir = Path.Combine(dirPath, "data");
|
||||
|
||||
// data/ サブフォルダまたはルート直下に Bakin 固有ファイルが存在するか確認
|
||||
if (File.Exists(Path.Combine(dataSubDir, "bakinplayer.exe")) ||
|
||||
File.Exists(Path.Combine(dataSubDir, "bakinengine.dll")) ||
|
||||
File.Exists(Path.Combine(dataSubDir, "data.rbpack")) ||
|
||||
File.Exists(Path.Combine(dirPath, "bakinplayer.exe")) ||
|
||||
File.Exists(Path.Combine(dirPath, "bakinengine.dll")) ||
|
||||
File.Exists(Path.Combine(dirPath, "data.rbpack")))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定ディレクトリ内の RPG Developer Bakin ゲームを検出し、TkoolGameItem を生成します。
|
||||
/// </summary>
|
||||
/// <param name="dirPath">ゲームフォルダの絶対パス</param>
|
||||
/// <param name="folderName">フォルダ名</param>
|
||||
/// <param name="folderModified">フォルダ更新日時</param>
|
||||
/// <param name="iconLoader">アイコン読み込み関数</param>
|
||||
/// <returns>検出されたゲームアイテム。該当しない場合は null</returns>
|
||||
public static TkoolGameItem? DetectBakinGame(
|
||||
string dirPath,
|
||||
string folderName,
|
||||
DateTime? folderModified,
|
||||
Func<string?, string?, ImageSource?>? iconLoader)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!BakinDetector.IsBakinGame(dirPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var exePath = BakinDetector.FindBakinExecutable(dirPath, folderName);
|
||||
string title = folderName;
|
||||
if (!string.IsNullOrEmpty(exePath))
|
||||
{
|
||||
var exeName = Path.GetFileNameWithoutExtension(exePath);
|
||||
if (!string.IsNullOrWhiteSpace(exeName) &&
|
||||
!string.Equals(exeName, "bakinplayer", StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(exeName, "Game", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
title = folderName;
|
||||
}
|
||||
}
|
||||
|
||||
ImageSource? icon = null;
|
||||
if (iconLoader != null)
|
||||
{
|
||||
icon = iconLoader(exePath, dirPath);
|
||||
}
|
||||
|
||||
bool hasSave = BakinSaveService.HasAnySaveData(dirPath);
|
||||
|
||||
return new TkoolGameItem
|
||||
{
|
||||
Title = title,
|
||||
FolderName = folderName,
|
||||
RootDirectory = dirPath,
|
||||
ExecutablePath = exePath ?? string.Empty,
|
||||
EngineType = TkoolEngineType.Bakin,
|
||||
IsModded = false,
|
||||
ApplyMod = false,
|
||||
HasSaveData = hasSave,
|
||||
IconImage = icon,
|
||||
FolderLastModified = folderModified
|
||||
};
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bakin ゲームの起動用実行ファイル(ランチャー .exe または bakinplayer.exe)を検索します。
|
||||
/// </summary>
|
||||
/// <param name="dirPath">ゲームルートディレクトリ</param>
|
||||
/// <param name="folderName">フォルダ名(省略可)</param>
|
||||
/// <returns>実行ファイルのフルパス。見つからない場合は null</returns>
|
||||
public static string? FindBakinExecutable(string dirPath, string? folderName = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dirPath) || !Directory.Exists(dirPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var topExes = Directory.GetFiles(dirPath, "*.exe", SearchOption.TopDirectoryOnly)
|
||||
.Where(p => !BakinDetector.IsExcludedLauncherCandidate(p))
|
||||
.ToList();
|
||||
|
||||
if (topExes.Count == 1)
|
||||
{
|
||||
return topExes[0];
|
||||
}
|
||||
|
||||
if (topExes.Count > 1)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(folderName))
|
||||
{
|
||||
var match = topExes.FirstOrDefault(p =>
|
||||
folderName.Contains(Path.GetFileNameWithoutExtension(p), StringComparison.OrdinalIgnoreCase) ||
|
||||
Path.GetFileNameWithoutExtension(p).Contains(folderName, StringComparison.OrdinalIgnoreCase));
|
||||
if (match != null)
|
||||
{
|
||||
return match;
|
||||
}
|
||||
}
|
||||
|
||||
return topExes
|
||||
.OrderByDescending(p =>
|
||||
{
|
||||
try { return new FileInfo(p).Length; } catch { return 0L; }
|
||||
})
|
||||
.First();
|
||||
}
|
||||
|
||||
var dataPlayer = Path.Combine(dirPath, "data", "bakinplayer.exe");
|
||||
if (File.Exists(dataPlayer))
|
||||
{
|
||||
return dataPlayer;
|
||||
}
|
||||
|
||||
var rootPlayer = Path.Combine(dirPath, "bakinplayer.exe");
|
||||
if (File.Exists(rootPlayer))
|
||||
{
|
||||
return rootPlayer;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 無視
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Bakin ゲームのセーブデータ格納ディレクトリ (`data/savedata` または `savedata`) を解決します。
|
||||
/// </summary>
|
||||
/// <param name="dirPath">ゲームルートディレクトリ</param>
|
||||
/// <returns>セーブデータディレクトリのフルパス</returns>
|
||||
public static string ResolveSaveDirectory(string dirPath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dirPath))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var dataSaveDir = Path.Combine(dirPath, "data", "savedata");
|
||||
if (Directory.Exists(dataSaveDir))
|
||||
{
|
||||
return dataSaveDir;
|
||||
}
|
||||
|
||||
var rootSaveDir = Path.Combine(dirPath, "savedata");
|
||||
if (Directory.Exists(rootSaveDir))
|
||||
{
|
||||
return rootSaveDir;
|
||||
}
|
||||
|
||||
if (Directory.Exists(Path.Combine(dirPath, "data")))
|
||||
{
|
||||
return dataSaveDir;
|
||||
}
|
||||
|
||||
return rootSaveDir;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region □メソッド(Private)
|
||||
|
||||
private static bool IsExcludedLauncherCandidate(string exePath)
|
||||
{
|
||||
var fileName = Path.GetFileName(exePath);
|
||||
if (BakinDetector.ExcludedExeNames.Contains(fileName))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (fileName.StartsWith("unins", StringComparison.OrdinalIgnoreCase) ||
|
||||
fileName.Contains("setup", StringComparison.OrdinalIgnoreCase) ||
|
||||
fileName.Contains("config", StringComparison.OrdinalIgnoreCase) ||
|
||||
fileName.Contains("軽量化", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// Engines/Bakin/BakinEngineModule.cs — RPG Developer Bakin エンジンモジュール実装
|
||||
using GameLauncher.Engines.Common;
|
||||
using GameLauncher.Helpers;
|
||||
using GameLauncher.Models;
|
||||
|
||||
namespace GameLauncher.Engines.Bakin
|
||||
{
|
||||
/// <summary>
|
||||
/// RPG Developer Bakin エンジン用の <see cref="IEngineModule"/> 実装クラス。
|
||||
/// </summary>
|
||||
public sealed class BakinEngineModule : IEngineModule
|
||||
{
|
||||
#region □プロパティ(Public)
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string EngineName => EngineDetectionHelper.EngineBakin;
|
||||
|
||||
#endregion
|
||||
|
||||
#region □メソッド(Public)
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool Detect(string gameDirectory)
|
||||
{
|
||||
return BakinDetector.IsBakinGame(gameDirectory);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool ApplyMod(string gameDirectory, ModPluginDefinition plugin)
|
||||
{
|
||||
// Bakin はセーブデータエディタ方式で改造を行うため、スクリプト注入は不要
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool IsModApplied(string gameDirectory)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public string ResolveToolPath(string toolFileName)
|
||||
{
|
||||
return AppPathHelper.ResolveEngineTool(this.EngineName, toolFileName) ?? string.Empty;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
<Window x:Class="GameLauncher.Engines.Bakin.BakinSaveEditorDialog"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="🛠 RPG Developer Bakin セーブデータ改造エディタ"
|
||||
Width="1040" Height="740"
|
||||
MinWidth="820" MinHeight="560"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Background="#141720"
|
||||
Foreground="#ECEFF4">
|
||||
<Window.Resources>
|
||||
<Style x:Key="DarkButtonStyle" TargetType="Button">
|
||||
<Setter Property="Background" Value="#2563EB"/>
|
||||
<Setter Property="Foreground" Value="White"/>
|
||||
<Setter Property="BorderBrush" Value="#3B82F6"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="Padding" Value="12,6"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border Background="{TemplateBinding Background}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
CornerRadius="5"
|
||||
Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Opacity" Value="0.9"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Opacity" Value="0.45"/>
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Window.Resources>
|
||||
|
||||
<Grid Margin="16">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- 1. ヘッダー&セーブファイル選択 -->
|
||||
<Border Grid.Row="0" Background="#1E2332" BorderBrush="#2A3142" BorderThickness="1" CornerRadius="8" Padding="14,10" Margin="0,0,0,10">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0,0,0,8">
|
||||
<TextBlock Text="🛠 RPG Developer Bakin セーブデータ改造エディタ (YUKRDATA .sgs)" FontSize="16" FontWeight="Bold" Foreground="#FDCB6E" VerticalAlignment="Center"/>
|
||||
<TextBlock x:Name="GameTitleText" Text="" FontSize="13" Foreground="#A5B1C2" VerticalAlignment="Center" Margin="14,0,0,0"/>
|
||||
</StackPanel>
|
||||
|
||||
<Grid Grid.Row="1">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Grid.Column="0" Text="対象セーブ:" VerticalAlignment="Center" Foreground="#ECEFF4" FontWeight="SemiBold" Margin="0,0,10,0"/>
|
||||
<ComboBox x:Name="SaveFileComboBox" Grid.Column="1"
|
||||
DisplayMemberPath="SummaryText"
|
||||
SelectionChanged="SaveFileComboBox_SelectionChanged"
|
||||
Height="30" VerticalContentAlignment="Center"
|
||||
Margin="0,0,8,0"/>
|
||||
<Button Grid.Column="2" Content="🔄 再読込" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#334155" BorderBrush="#475569"
|
||||
Click="ReloadButton_Click" Margin="0,0,8,0"/>
|
||||
<Button Grid.Column="3" Content="📂 セーブフォルダを開く" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#334155" BorderBrush="#475569"
|
||||
Click="OpenFolderButton_Click"/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 2. ワンクリック・クイック改造バー -->
|
||||
<Border Grid.Row="1" Background="#1A2436" BorderBrush="#D97706" BorderThickness="1" CornerRadius="8" Padding="12,8" Margin="0,0,0,10">
|
||||
<WrapPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock Text="⚡ クイック改造:" Foreground="#FBBF24" FontWeight="Bold" VerticalAlignment="Center" Margin="0,0,10,0"/>
|
||||
<Button Content="💰 所持金 MAX (9,999,999)" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#059669" BorderBrush="#10B981" Padding="10,4" Margin="0,2,6,2"
|
||||
Click="QuickMaxMoney_Click"/>
|
||||
<Button Content="⚡ 行動力 MAX (999)" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#D97706" BorderBrush="#F59E0B" Padding="10,4" Margin="0,2,6,2"
|
||||
Click="QuickMaxActionPoints_Click"/>
|
||||
<Button Content="💪 全員 Lv99 & ステータス MAX" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#7C3AED" BorderBrush="#8B5CF6" Padding="10,4" Margin="0,2,6,2"
|
||||
Click="QuickMaxPartyStats_Click"/>
|
||||
<Button Content="🎒 所持品×99 & 全アイテム/レシピ習得" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#0284C7" BorderBrush="#38BDF8" Padding="10,4" Margin="0,2,6,2"
|
||||
Click="QuickMaxItems_Click"/>
|
||||
<Button Content="🔓 動画・回想解放フラグ 全ON" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#DB2777" BorderBrush="#F472B6" Padding="10,4" Margin="0,2,0,2"
|
||||
Click="QuickUnlockAllGallery_Click"/>
|
||||
</WrapPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 3. 検索・カテゴリ絞り込み・一括変更バー -->
|
||||
<Border Grid.Row="2" Background="#1E2332" BorderBrush="#2A3142" BorderThickness="1" CornerRadius="8" Padding="12,8" Margin="0,0,0,10">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="210"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="100"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="90"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Grid.Column="0" Text="分類:" VerticalAlignment="Center" Foreground="#A5B1C2" Margin="0,0,6,0"/>
|
||||
<ComboBox x:Name="CategoryFilterComboBox" Grid.Column="1" Height="28" VerticalContentAlignment="Center"
|
||||
SelectionChanged="FilterChanged" Margin="0,0,10,0"/>
|
||||
|
||||
<TextBlock Grid.Column="2" Text="検索:" VerticalAlignment="Center" Foreground="#A5B1C2" Margin="0,0,6,0"/>
|
||||
<TextBox x:Name="KeywordFilterTextBox" Grid.Column="3" Height="28" VerticalContentAlignment="Center"
|
||||
Background="#141720" Foreground="#ECEFF4" BorderBrush="#3B4252" Padding="6,0"
|
||||
ToolTip="項目名・変数名・GUID等で絞り込みます"
|
||||
TextChanged="FilterChanged" Margin="0,0,10,0"/>
|
||||
|
||||
<TextBlock Grid.Column="4" Text="現在値一致:" VerticalAlignment="Center" Foreground="#A5B1C2" Margin="0,0,6,0"/>
|
||||
<TextBox x:Name="ExactValueFilterTextBox" Grid.Column="5" Height="28" VerticalContentAlignment="Center"
|
||||
Background="#141720" Foreground="#38BDF8" BorderBrush="#3B4252" Padding="6,0"
|
||||
ToolTip="指定した値と完全一致する項目だけをピンポイント抽出します(例: 500)"
|
||||
TextChanged="FilterChanged" Margin="0,0,12,0"/>
|
||||
|
||||
<TextBlock Grid.Column="6" Text="一括値:" VerticalAlignment="Center" Foreground="#A5B1C2" Margin="0,0,6,0"/>
|
||||
<TextBox x:Name="BulkValueTextBox" Grid.Column="7" Height="28" VerticalContentAlignment="Center"
|
||||
Background="#141720" Foreground="#00E676" BorderBrush="#3B4252" Padding="6,0"
|
||||
Text="99" Margin="0,0,6,0"/>
|
||||
<Button Grid.Column="8" Content="表示中へ一括反映" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#334155" BorderBrush="#475569" Padding="10,4"
|
||||
Click="ApplyBulkValue_Click"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 4. メイン編集グリッド -->
|
||||
<Border Grid.Row="3" Background="#141720" BorderBrush="#2A3142" BorderThickness="1" CornerRadius="6">
|
||||
<DataGrid x:Name="EntriesDataGrid"
|
||||
AutoGenerateColumns="False"
|
||||
CanUserAddRows="False"
|
||||
CanUserDeleteRows="False"
|
||||
Background="#141720"
|
||||
RowBackground="#1E2332"
|
||||
AlternatingRowBackground="#191D2A"
|
||||
Foreground="#ECEFF4"
|
||||
GridLinesVisibility="Horizontal"
|
||||
HorizontalGridLinesBrush="#2A3142"
|
||||
BorderBrush="#2A3142"
|
||||
HeadersVisibility="Column"
|
||||
SelectionMode="Single"
|
||||
RowHeight="30">
|
||||
<DataGrid.Resources>
|
||||
<Style TargetType="DataGridColumnHeader">
|
||||
<Setter Property="Background" Value="#252B3D"/>
|
||||
<Setter Property="Foreground" Value="#FDCB6E"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Padding" Value="10,6"/>
|
||||
<Setter Property="BorderBrush" Value="#2A3142"/>
|
||||
<Setter Property="BorderThickness" Value="0,0,1,1"/>
|
||||
</Style>
|
||||
</DataGrid.Resources>
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="カテゴリ" Binding="{Binding Category}" Width="195" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="項目名 / ステータス・変数・アイテム名" Binding="{Binding DisplayKey}" Width="*" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="型" Binding="{Binding ValueType}" Width="75" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="変更前の値" Binding="{Binding OriginalValueText}" Width="125" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="✏️ 編集後の値 (ダブルクリックで変更)" Binding="{Binding ValueText, UpdateSourceTrigger=PropertyChanged}" Width="210">
|
||||
<DataGridTextColumn.ElementStyle>
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="#00E5FF"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Padding" Value="6,0"/>
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
</Style>
|
||||
</DataGridTextColumn.ElementStyle>
|
||||
<DataGridTextColumn.EditingElementStyle>
|
||||
<Style TargetType="TextBox">
|
||||
<Setter Property="Background" Value="#0F172A"/>
|
||||
<Setter Property="Foreground" Value="#00E676"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Padding" Value="4,2"/>
|
||||
</Style>
|
||||
</DataGridTextColumn.EditingElementStyle>
|
||||
</DataGridTextColumn>
|
||||
<DataGridTextColumn Header="内部識別子" Binding="{Binding InternalKey}" Width="170" IsReadOnly="True"/>
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</Border>
|
||||
|
||||
<!-- 5. フッター&保存・バックアップ復元ボタン -->
|
||||
<Grid Grid.Row="4" Margin="0,12,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock x:Name="StatusTextBlock" Grid.Column="0"
|
||||
Text="セーブデータを選択してください。"
|
||||
Foreground="#00E676" VerticalAlignment="Center" TextWrapping="NoWrap" TextTrimming="CharacterEllipsis"/>
|
||||
|
||||
<Button x:Name="RestoreBackupButton" Grid.Column="1"
|
||||
Content="⏪ バックアップから復元"
|
||||
Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#B45309" BorderBrush="#F59E0B"
|
||||
Click="RestoreBackupButton_Click" Margin="10,0,8,0"/>
|
||||
|
||||
<Button x:Name="SaveButton" Grid.Column="2"
|
||||
Content="💾 変更をセーブデータに保存"
|
||||
Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#059669" BorderBrush="#10B981"
|
||||
Click="SaveButton_Click" Margin="0,0,8,0"/>
|
||||
|
||||
<Button Grid.Column="3" Content="閉じる"
|
||||
Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#334155" BorderBrush="#475569"
|
||||
Click="CloseButton_Click"/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -0,0 +1,510 @@
|
||||
// Engines/Bakin/BakinSaveEditorDialog.xaml.cs — RPG Developer Bakin セーブデータ改造エディタ ウィンドウ
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using GameLauncher.Engines.Tkool;
|
||||
|
||||
namespace GameLauncher.Engines.Bakin
|
||||
{
|
||||
/// <summary>
|
||||
/// RPG Developer Bakin (YUKRDATA .sgs) セーブデータの閲覧・編集・クイックチート・バックアップ復元を行うダイアログウィンドウ。
|
||||
/// </summary>
|
||||
public partial class BakinSaveEditorDialog : Window
|
||||
{
|
||||
#region □定数(Private)
|
||||
|
||||
private const string AllCategoriesLabel = "すべて表示";
|
||||
|
||||
#endregion
|
||||
|
||||
#region □変数(Private)
|
||||
|
||||
private readonly TkoolGameItem _game;
|
||||
private List<BakinSaveFileInfo> _saveFiles = new();
|
||||
private BakinSaveDocument? _currentDoc;
|
||||
private ICollectionView? _entriesView;
|
||||
private bool _suppressFilterEvents;
|
||||
|
||||
#endregion
|
||||
|
||||
#region □コンストラクタ
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="BakinSaveEditorDialog"/> の新しいインスタンスを初期化します。
|
||||
/// </summary>
|
||||
/// <param name="game">対象の Bakin ゲームアイテム</param>
|
||||
public BakinSaveEditorDialog(TkoolGameItem game)
|
||||
{
|
||||
this.InitializeComponent();
|
||||
this._game = game ?? throw new ArgumentNullException(nameof(game));
|
||||
this.GameTitleText.Text = $"— {this._game.Title}";
|
||||
this.LoadSaveFileList();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region □イベント
|
||||
|
||||
private void SaveFileComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (this.SaveFileComboBox.SelectedItem is BakinSaveFileInfo selected)
|
||||
{
|
||||
this.LoadSelectedSaveFile(selected.FilePath);
|
||||
}
|
||||
}
|
||||
|
||||
private void ReloadButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
string? currentPath = (this.SaveFileComboBox.SelectedItem as BakinSaveFileInfo)?.FilePath;
|
||||
this.LoadSaveFileList(currentPath);
|
||||
}
|
||||
|
||||
private void OpenFolderButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
var saveDir = BakinDetector.ResolveSaveDirectory(this._game.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(saveDir) && Directory.Exists(saveDir))
|
||||
{
|
||||
Process.Start(new ProcessStartInfo { FileName = saveDir, UseShellExecute = true });
|
||||
}
|
||||
else if (Directory.Exists(this._game.RootDirectory))
|
||||
{
|
||||
Process.Start(new ProcessStartInfo { FileName = this._game.RootDirectory, UseShellExecute = true });
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(this, $"フォルダを開けませんでした:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
}
|
||||
|
||||
private void QuickMaxMoney_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int updated = 0;
|
||||
foreach (var entry in this._currentDoc.Entries)
|
||||
{
|
||||
if (entry.InternalKey == "Party.Money")
|
||||
{
|
||||
entry.ValueText = "9999999";
|
||||
updated++;
|
||||
}
|
||||
else if (entry.InternalKey == "Party.InventoryMax")
|
||||
{
|
||||
if (int.TryParse(entry.ValueText, out int curMax) && curMax < 999)
|
||||
{
|
||||
entry.ValueText = "999";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.EntriesDataGrid.Items.Refresh();
|
||||
this.StatusTextBlock.Text = updated > 0
|
||||
? "💰 所持金を 9,999,999 に設定しました。「💾 変更をセーブデータに保存」を押すと確定します。"
|
||||
: "⚠️ このセーブファイルには所持金データが含まれていません(Save_00.sgs 等の通常セーブを選択してください)。";
|
||||
}
|
||||
|
||||
private void QuickMaxActionPoints_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int updated = 0;
|
||||
foreach (var entry in this._currentDoc.Entries)
|
||||
{
|
||||
if (entry.Category == BakinSaveService.CategoryVariables &&
|
||||
(entry.DisplayKey.Contains("行動力", StringComparison.OrdinalIgnoreCase) ||
|
||||
entry.DisplayKey.Contains("AP", StringComparison.OrdinalIgnoreCase) ||
|
||||
entry.DisplayKey.Contains("スタミナ", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
entry.ValueText = "999";
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
|
||||
this.EntriesDataGrid.Items.Refresh();
|
||||
this.StatusTextBlock.Text = updated > 0
|
||||
? $"⚡ 行動力・最大行動力関連の変数 ({updated} 件) を 999 に設定しました。「💾 変更をセーブデータに保存」を押すと確定します。"
|
||||
: "⚠️ 行動力関連の変数が見つかりませんでした。";
|
||||
}
|
||||
|
||||
private void QuickMaxPartyStats_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int updated = 0;
|
||||
foreach (var entry in this._currentDoc.Entries)
|
||||
{
|
||||
if (entry.Category != BakinSaveService.CategoryParty)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.InternalKey.EndsWith(".Level", StringComparison.Ordinal))
|
||||
{
|
||||
entry.ValueText = "99";
|
||||
updated++;
|
||||
}
|
||||
else if (entry.InternalKey.EndsWith(".Exp", StringComparison.Ordinal))
|
||||
{
|
||||
entry.ValueText = "9999999";
|
||||
updated++;
|
||||
}
|
||||
else if (entry.InternalKey.EndsWith(".HP", StringComparison.Ordinal) ||
|
||||
entry.InternalKey.EndsWith(".MaxHP", StringComparison.Ordinal) ||
|
||||
entry.InternalKey.EndsWith(".MP", StringComparison.Ordinal) ||
|
||||
entry.InternalKey.EndsWith(".MaxMP", StringComparison.Ordinal))
|
||||
{
|
||||
entry.ValueText = "9999";
|
||||
updated++;
|
||||
}
|
||||
else if (entry.InternalKey.EndsWith(".Power", StringComparison.Ordinal) ||
|
||||
entry.InternalKey.EndsWith(".Vitality", StringComparison.Ordinal) ||
|
||||
entry.InternalKey.EndsWith(".Magic", StringComparison.Ordinal) ||
|
||||
entry.InternalKey.EndsWith(".Speed", StringComparison.Ordinal))
|
||||
{
|
||||
entry.ValueText = "999";
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
|
||||
this.EntriesDataGrid.Items.Refresh();
|
||||
this.StatusTextBlock.Text = updated > 0
|
||||
? $"💪 パーティ・控えメンバー全員の Lv99 / HP・MP 9999 / 各能力 999 ({updated} 項目) を設定しました。"
|
||||
: "⚠️ パーティメンバーのステータス項目が見つかりませんでした。";
|
||||
}
|
||||
|
||||
private void QuickMaxItems_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int itemUpdated = 0;
|
||||
int flagUpdated = 0;
|
||||
|
||||
foreach (var entry in this._currentDoc.Entries)
|
||||
{
|
||||
if (entry.Category == BakinSaveService.CategoryItems)
|
||||
{
|
||||
entry.ValueText = "99";
|
||||
itemUpdated++;
|
||||
}
|
||||
else if (entry.Category == BakinSaveService.CategoryVariables)
|
||||
{
|
||||
if (entry.InternalKey.Contains("(dbGetAllItems)", StringComparison.OrdinalIgnoreCase) ||
|
||||
entry.InternalKey.Contains("(dbLearnAll)", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
entry.ValueText = "1";
|
||||
flagUpdated++;
|
||||
}
|
||||
else if (entry.InternalKey.Contains("(dbGetAllItemsAmount)", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
entry.ValueText = "99";
|
||||
flagUpdated++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.EntriesDataGrid.Items.Refresh();
|
||||
this.StatusTextBlock.Text = $"🎒 所持アイテム ({itemUpdated} 枠) を ×99 に設定し、全アイテム/全レシピ習得変数 ({flagUpdated} 件) を有効化しました。";
|
||||
}
|
||||
|
||||
private void QuickUnlockAllGallery_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int updated = 0;
|
||||
foreach (var entry in this._currentDoc.Entries)
|
||||
{
|
||||
if (entry.ValueType != "Double" && entry.ValueType != "Int32")
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.Category == BakinSaveService.CategoryCrossSave ||
|
||||
entry.DisplayKey.Contains("動画", StringComparison.OrdinalIgnoreCase) ||
|
||||
entry.DisplayKey.Contains("解放", StringComparison.OrdinalIgnoreCase) ||
|
||||
entry.DisplayKey.Contains("回想", StringComparison.OrdinalIgnoreCase) ||
|
||||
entry.DisplayKey.Contains("ギャラリー", StringComparison.OrdinalIgnoreCase) ||
|
||||
entry.DisplayKey.Contains("CG", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
entry.ValueText = "1";
|
||||
updated++;
|
||||
}
|
||||
}
|
||||
|
||||
this.EntriesDataGrid.Items.Refresh();
|
||||
this.StatusTextBlock.Text = updated > 0
|
||||
? $"🔓 動画・回想・クロスセーブ解放フラグ ({updated} 件) をすべて ON(1) に設定しました(Save_xx.sgs にも同時反映されます)。"
|
||||
: "⚠️ 解放フラグ系の変数が見つかりませんでした。";
|
||||
}
|
||||
|
||||
private void FilterChanged(object sender, EventArgs e)
|
||||
{
|
||||
if (this._suppressFilterEvents || this._entriesView == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this._entriesView.Refresh();
|
||||
this.UpdateFilteredCountStatus();
|
||||
}
|
||||
|
||||
private void ApplyBulkValue_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._entriesView == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
string bulkVal = this.BulkValueTextBox.Text.Trim();
|
||||
if (string.IsNullOrEmpty(bulkVal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
foreach (var obj in this._entriesView)
|
||||
{
|
||||
if (obj is BakinSaveEntry entry)
|
||||
{
|
||||
entry.ValueText = bulkVal;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
this.EntriesDataGrid.Items.Refresh();
|
||||
this.StatusTextBlock.Text = $"✏️ 現在表示中の {count} 件の項目に「{bulkVal}」を一括設定しました。";
|
||||
}
|
||||
|
||||
private void SaveButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
this.EntriesDataGrid.CommitEdit(DataGridEditingUnit.Cell, true);
|
||||
this.EntriesDataGrid.CommitEdit(DataGridEditingUnit.Row, true);
|
||||
|
||||
string backupPath = BakinSaveService.SaveSaveData(
|
||||
this._currentDoc,
|
||||
this._game.FolderName,
|
||||
this._game.RootDirectory);
|
||||
|
||||
this.EntriesDataGrid.Items.Refresh();
|
||||
string fileName = Path.GetFileName(this._currentDoc.FilePath);
|
||||
this.StatusTextBlock.Text = $"✅ 「{fileName}」を保存しました!(バックアップ作成済み: {Path.GetFileName(backupPath)})";
|
||||
|
||||
MessageBox.Show(
|
||||
this,
|
||||
$"セーブデータ「{fileName}」への保存が完了しました!\n" +
|
||||
(string.IsNullOrEmpty(this._currentDoc.CompanionCrossSavePath) ? string.Empty : "(※クロスセーブ Save_xx.sgs の変更も同時に保存されました)\n") +
|
||||
$"\n自動バックアップ保存先:\n{backupPath}",
|
||||
"セーブデータ保存完了",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Information);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(
|
||||
this,
|
||||
$"セーブデータの保存中にエラーが発生しました:\n{ex.Message}",
|
||||
"保存エラー",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void RestoreBackupButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
string fileName = Path.GetFileName(this._currentDoc.FilePath);
|
||||
var ask = MessageBox.Show(
|
||||
this,
|
||||
$"「{fileName}」を最新のバックアップから復元しますか?\n(現在の未保存の編集内容は破棄されます)",
|
||||
"バックアップ復元の確認",
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Question);
|
||||
|
||||
if (ask != MessageBoxResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var (success, message) = BakinSaveService.RestoreLatestBackup(
|
||||
this._currentDoc.FilePath,
|
||||
this._game.FolderName,
|
||||
this._game.RootDirectory);
|
||||
|
||||
if (success)
|
||||
{
|
||||
this.LoadSelectedSaveFile(this._currentDoc.FilePath);
|
||||
this.StatusTextBlock.Text = $"⏪ {message.Replace("\n", " ")}";
|
||||
MessageBox.Show(this, message, "復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show(this, message, "復元案内", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
}
|
||||
|
||||
private void CloseButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
this.Close();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region □メソッド(Private)
|
||||
|
||||
private void LoadSaveFileList(string? preferFilePath = null)
|
||||
{
|
||||
this._saveFiles = BakinSaveService.FindSaveFiles(this._game.RootDirectory);
|
||||
this.SaveFileComboBox.ItemsSource = this._saveFiles;
|
||||
|
||||
if (this._saveFiles.Count == 0)
|
||||
{
|
||||
this._currentDoc = null;
|
||||
this.EntriesDataGrid.ItemsSource = null;
|
||||
this.SaveButton.IsEnabled = false;
|
||||
this.RestoreBackupButton.IsEnabled = false;
|
||||
this.StatusTextBlock.Text = "⚠️ セーブデータ (data/savedata/Save_*.sgs) が見つかりません。一度ゲーム内でセーブを作成してください。";
|
||||
return;
|
||||
}
|
||||
|
||||
this.SaveButton.IsEnabled = true;
|
||||
this.RestoreBackupButton.IsEnabled = true;
|
||||
|
||||
BakinSaveFileInfo? target = null;
|
||||
if (!string.IsNullOrEmpty(preferFilePath))
|
||||
{
|
||||
target = this._saveFiles.FirstOrDefault(f => string.Equals(f.FilePath, preferFilePath, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
// デフォルトでは Save_00.sgs 等の通常セーブを優先選択
|
||||
target ??= this._saveFiles.FirstOrDefault(f => !f.IsCrossSave) ?? this._saveFiles[0];
|
||||
this.SaveFileComboBox.SelectedItem = target;
|
||||
}
|
||||
|
||||
private void LoadSelectedSaveFile(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
this._currentDoc = BakinSaveService.LoadSaveData(filePath);
|
||||
|
||||
this._suppressFilterEvents = true;
|
||||
var categories = new List<string> { BakinSaveEditorDialog.AllCategoriesLabel };
|
||||
categories.AddRange(this._currentDoc.Entries.Select(e => e.Category).Distinct());
|
||||
string? prevCat = this.CategoryFilterComboBox.SelectedItem as string;
|
||||
this.CategoryFilterComboBox.ItemsSource = categories;
|
||||
this.CategoryFilterComboBox.SelectedItem = (prevCat != null && categories.Contains(prevCat))
|
||||
? prevCat
|
||||
: BakinSaveEditorDialog.AllCategoriesLabel;
|
||||
this._suppressFilterEvents = false;
|
||||
|
||||
this._entriesView = CollectionViewSource.GetDefaultView(this._currentDoc.Entries);
|
||||
this._entriesView.Filter = this.FilterEntry;
|
||||
this.EntriesDataGrid.ItemsSource = this._entriesView;
|
||||
|
||||
this.UpdateFilteredCountStatus();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.StatusTextBlock.Text = $"❌ 読み込みエラー: {ex.Message}";
|
||||
MessageBox.Show(
|
||||
this,
|
||||
$"セーブデータの読み込み中にエラーが発生しました:\n{ex.Message}",
|
||||
"読み込みエラー",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private bool FilterEntry(object obj)
|
||||
{
|
||||
if (obj is not BakinSaveEntry entry)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 1. カテゴリフィルタ
|
||||
if (this.CategoryFilterComboBox.SelectedItem is string cat &&
|
||||
!string.Equals(cat, BakinSaveEditorDialog.AllCategoriesLabel, StringComparison.Ordinal))
|
||||
{
|
||||
if (!string.Equals(entry.Category, cat, StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. キーワード検索フィルタ
|
||||
string kw = this.KeywordFilterTextBox.Text.Trim();
|
||||
if (!string.IsNullOrEmpty(kw))
|
||||
{
|
||||
bool matchDisplay = entry.DisplayKey.Contains(kw, StringComparison.OrdinalIgnoreCase);
|
||||
bool matchInternal = entry.InternalKey.Contains(kw, StringComparison.OrdinalIgnoreCase);
|
||||
bool matchCategory = entry.Category.Contains(kw, StringComparison.OrdinalIgnoreCase);
|
||||
bool matchValue = entry.ValueText.Contains(kw, StringComparison.OrdinalIgnoreCase);
|
||||
if (!matchDisplay && !matchInternal && !matchCategory && !matchValue)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 現在値完全一致フィルタ
|
||||
string exact = this.ExactValueFilterTextBox.Text.Trim();
|
||||
if (!string.IsNullOrEmpty(exact))
|
||||
{
|
||||
if (!string.Equals(entry.ValueText.Trim(), exact, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void UpdateFilteredCountStatus()
|
||||
{
|
||||
if (this._currentDoc == null || this._entriesView == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int total = this._currentDoc.Entries.Count;
|
||||
int visible = this._entriesView.Cast<object>().Count();
|
||||
string fileName = Path.GetFileName(this._currentDoc.FilePath);
|
||||
this.StatusTextBlock.Text = $"📂 読込完了: {fileName} — 全 {total} 項目中 {visible} 項目を表示中(ダブルクリックまたはクイック改造ボタンで編集できます)";
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -29,6 +29,9 @@ namespace GameLauncher.Engines.Common
|
||||
/// <summary>Canonical engine name for generic NW.js packaged games.</summary>
|
||||
public const string EngineNwjs = "Nwjs";
|
||||
|
||||
/// <summary>Canonical engine name for RPG Developer Bakin games.</summary>
|
||||
public const string EngineBakin = "Bakin";
|
||||
|
||||
/// <summary>Canonical engine name for Enigma Virtual Box packed applications.</summary>
|
||||
public const string EngineEvb = "Evb";
|
||||
|
||||
@@ -80,6 +83,11 @@ namespace GameLauncher.Engines.Common
|
||||
return EngineNwjs;
|
||||
}
|
||||
|
||||
if (Matches(value, "Bakin", "RPGDeveloperBakin", "SmileGameBuilder", "SGB"))
|
||||
{
|
||||
return EngineBakin;
|
||||
}
|
||||
|
||||
if (Matches(value, "Evb", "Enigma", "EnigmaVB", "EnigmaVirtualBox"))
|
||||
{
|
||||
return EngineEvb;
|
||||
@@ -129,6 +137,12 @@ namespace GameLauncher.Engines.Common
|
||||
return EngineEvb;
|
||||
}
|
||||
|
||||
// RPG Developer Bakin: data/bakinplayer.exe, bakinengine.dll, or data.rbpack.
|
||||
if (Engines.Bakin.BakinDetector.IsBakinGame(gameDirectory))
|
||||
{
|
||||
return EngineBakin;
|
||||
}
|
||||
|
||||
// RPG Maker MV/MZ: www/ folder or a Game.exe next to nw.js package files.
|
||||
var wwwDir = Path.Combine(gameDirectory, "www");
|
||||
if (Directory.Exists(wwwDir))
|
||||
|
||||
@@ -89,8 +89,10 @@ namespace GameLauncher.Engines.Evb
|
||||
}
|
||||
}
|
||||
|
||||
// First exe at the top level, then one level deeper.
|
||||
var top = Directory.GetFiles(outputDirectory, "*.exe", SearchOption.TopDirectoryOnly);
|
||||
// First exe at the top level, then one level deeper (excluding helper/installer exes).
|
||||
var top = Directory.GetFiles(outputDirectory, "*.exe", SearchOption.TopDirectoryOnly)
|
||||
.Where(f => !IsExcludedHelperExe(Path.GetFileName(f)))
|
||||
.ToArray();
|
||||
if (top.Length > 0)
|
||||
{
|
||||
return top[0];
|
||||
@@ -98,7 +100,9 @@ namespace GameLauncher.Engines.Evb
|
||||
|
||||
foreach (var sub in Directory.GetDirectories(outputDirectory))
|
||||
{
|
||||
var nested = Directory.GetFiles(sub, "*.exe", SearchOption.TopDirectoryOnly);
|
||||
var nested = Directory.GetFiles(sub, "*.exe", SearchOption.TopDirectoryOnly)
|
||||
.Where(f => !IsExcludedHelperExe(Path.GetFileName(f)))
|
||||
.ToArray();
|
||||
if (nested.Length > 0)
|
||||
{
|
||||
return nested[0];
|
||||
@@ -113,6 +117,17 @@ namespace GameLauncher.Engines.Evb
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsExcludedHelperExe(string? fileName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(fileName)) return true;
|
||||
return fileName.StartsWith("unins", StringComparison.OrdinalIgnoreCase) ||
|
||||
fileName.StartsWith("UnityCrashHandler", StringComparison.OrdinalIgnoreCase) ||
|
||||
fileName.Equals("notification_helper.exe", StringComparison.OrdinalIgnoreCase) ||
|
||||
fileName.Equals("crashpad_handler.exe", StringComparison.OrdinalIgnoreCase) ||
|
||||
fileName.Equals("elevate.exe", StringComparison.OrdinalIgnoreCase) ||
|
||||
fileName.Equals("nacl64.exe", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when the game folder already holds a completed EVB extraction.
|
||||
/// A non-empty output folder is NOT enough: the run may have been interrupted,
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
using System;
|
||||
// Engines/Nwjs/NwjsDetector.cs — 汎用 NW.js ゲーム検出およびメタデータ解決ヘルパー
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Windows.Media;
|
||||
using GameLauncher.Engines.Common;
|
||||
using GameLauncher.Engines.Tkool;
|
||||
using GameLauncher.Engines.Unity;
|
||||
using GameLauncher.Models;
|
||||
@@ -14,10 +13,12 @@ using GameLauncher.Models;
|
||||
namespace GameLauncher.Engines.Nwjs
|
||||
{
|
||||
/// <summary>
|
||||
/// 汎用 NW.js (Node-Webkit) アプリケーション/ゲームの検出およびアイテム生成を行うヘルパークラス
|
||||
/// 汎用 NW.js (Node-Webkit) アプリケーション/ゲームの検出およびアイテム生成を行うヘルパークラス。
|
||||
/// </summary>
|
||||
public static class NwjsDetector
|
||||
{
|
||||
#region □変数(Private)
|
||||
|
||||
private static readonly HashSet<string> ExcludedExeNames = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"notification_helper.exe",
|
||||
@@ -25,6 +26,10 @@ namespace GameLauncher.Engines.Nwjs
|
||||
"elevate.exe"
|
||||
};
|
||||
|
||||
#endregion
|
||||
|
||||
#region □メソッド(Public)
|
||||
|
||||
/// <summary>
|
||||
/// 指定されたディレクトリが汎用 NW.js ゲームであるかを判定します。
|
||||
/// ツクール(MV/MZ/RGSS)、ティラノスクリプト、ウディタ、SRPG Studio など既存エンジン形式は除外します。
|
||||
@@ -69,7 +74,7 @@ namespace GameLauncher.Engines.Nwjs
|
||||
}
|
||||
|
||||
// package.json に main や window 記述があるか確認
|
||||
if (TryReadPackageJson(dirPath, out _, out _, out var main, out _))
|
||||
if (NwjsDetector.TryReadPackageJson(dirPath, out _, out _, out var main, out _))
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(main) && File.Exists(Path.Combine(dirPath, main)))
|
||||
{
|
||||
@@ -101,12 +106,12 @@ namespace GameLauncher.Engines.Nwjs
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!IsNwjsGame(dirPath))
|
||||
if (!NwjsDetector.IsNwjsGame(dirPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
TryReadPackageJson(dirPath, out var windowTitle, out var packageName, out var mainFile, out var iconRelPath);
|
||||
NwjsDetector.TryReadPackageJson(dirPath, out var windowTitle, out var packageName, out var mainFile, out var iconRelPath);
|
||||
|
||||
// タイトルの決定: window.title > index.html の <title> > package.json の name > フォルダ名
|
||||
string title = string.Empty;
|
||||
@@ -121,7 +126,7 @@ namespace GameLauncher.Engines.Nwjs
|
||||
? Path.Combine(dirPath, mainFile)
|
||||
: Path.Combine(dirPath, "index.html");
|
||||
|
||||
title = ExtractHtmlTitle(htmlPath);
|
||||
title = NwjsDetector.ExtractHtmlTitle(htmlPath);
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(title) && !string.IsNullOrWhiteSpace(packageName))
|
||||
@@ -135,7 +140,7 @@ namespace GameLauncher.Engines.Nwjs
|
||||
}
|
||||
|
||||
// 実行ファイルの探索
|
||||
var exePath = FindNwjsExecutable(dirPath, title, packageName);
|
||||
var exePath = NwjsDetector.FindNwjsExecutable(dirPath, title, packageName);
|
||||
|
||||
// アイコンの取得
|
||||
ImageSource? icon = null;
|
||||
@@ -144,17 +149,29 @@ namespace GameLauncher.Engines.Nwjs
|
||||
icon = iconLoader(exePath, dirPath);
|
||||
}
|
||||
|
||||
string entryHtmlPath = NwjsDetector.ResolveEntryHtmlPath(dirPath, mainFile);
|
||||
string entryDirPath = !string.IsNullOrEmpty(entryHtmlPath)
|
||||
? (Path.GetDirectoryName(entryHtmlPath) ?? dirPath)
|
||||
: dirPath;
|
||||
bool isModded = !string.IsNullOrEmpty(entryHtmlPath) && NwjsModService.CheckIsModded(entryHtmlPath);
|
||||
var saveFiles = NwjsSaveService.FindSaveFiles(dirPath, folderName);
|
||||
string saveDirPath = saveFiles.Count > 0
|
||||
? (Path.GetDirectoryName(saveFiles[0].FilePath) ?? dirPath)
|
||||
: string.Empty;
|
||||
|
||||
return new TkoolGameItem
|
||||
{
|
||||
Title = title,
|
||||
FolderName = folderName,
|
||||
RootDirectory = dirPath,
|
||||
ExecutablePath = exePath ?? string.Empty,
|
||||
PluginsJsPath = string.Empty,
|
||||
PluginsDirPath = string.Empty,
|
||||
PluginsJsPath = entryHtmlPath,
|
||||
PluginsDirPath = entryDirPath,
|
||||
EngineType = TkoolEngineType.Nwjs,
|
||||
IsModded = false,
|
||||
ApplyMod = false,
|
||||
IsModded = isModded,
|
||||
ApplyMod = isModded,
|
||||
HasSaveData = saveFiles.Count > 0,
|
||||
// セーブデータ有無
|
||||
IconImage = icon,
|
||||
FolderLastModified = folderModified
|
||||
};
|
||||
@@ -165,6 +182,50 @@ namespace GameLauncher.Engines.Nwjs
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// NW.js ゲームのエントリ HTML ファイル(index.html 等)の絶対パスを解決します。
|
||||
/// </summary>
|
||||
/// <param name="dirPath">ゲームルートディレクトリ</param>
|
||||
/// <param name="mainFromPackage">package.json の main フィールド(省略可)</param>
|
||||
/// <returns>存在する HTML ファイルのフルパス。見つからない場合は空文字列</returns>
|
||||
public static string ResolveEntryHtmlPath(string dirPath, string? mainFromPackage = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(dirPath) || !Directory.Exists(dirPath))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(mainFromPackage))
|
||||
{
|
||||
NwjsDetector.TryReadPackageJson(dirPath, out _, out _, out mainFromPackage, out _);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(mainFromPackage))
|
||||
{
|
||||
string candidate = Path.Combine(dirPath, mainFromPackage.TrimStart('/', '\\'));
|
||||
string ext = Path.GetExtension(candidate);
|
||||
if ((ext.Equals(".html", StringComparison.OrdinalIgnoreCase) || ext.Equals(".htm", StringComparison.OrdinalIgnoreCase)) &&
|
||||
File.Exists(candidate))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
string rootIndex = Path.Combine(dirPath, "index.html");
|
||||
if (File.Exists(rootIndex))
|
||||
{
|
||||
return rootIndex;
|
||||
}
|
||||
|
||||
string wwwIndex = Path.Combine(dirPath, "www", "index.html");
|
||||
if (File.Exists(wwwIndex))
|
||||
{
|
||||
return wwwIndex;
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// NW.js ゲーム用の実行可能ファイル(.exe)を探索します。
|
||||
/// notification_helper.exe などの Chromium 内部ユーティリティを除外し、ゲーム本体の exe を特定します。
|
||||
@@ -185,10 +246,12 @@ namespace GameLauncher.Engines.Nwjs
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (ExcludedExeNames.Contains(fileName))
|
||||
|
||||
if (NwjsDetector.ExcludedExeNames.Contains(fileName))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
})
|
||||
.ToList();
|
||||
@@ -244,6 +307,10 @@ namespace GameLauncher.Engines.Nwjs
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region □メソッド(Private)
|
||||
|
||||
/// <summary>
|
||||
/// package.json を読み込み、主要な設定値を抽出します。
|
||||
/// </summary>
|
||||
@@ -328,5 +395,7 @@ namespace GameLauncher.Engines.Nwjs
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,260 @@
|
||||
<Window x:Class="GameLauncher.Engines.Nwjs.NwjsSaveEditorDialog"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
Title="🛠 NW.js セーブデータ改造エディタ"
|
||||
Width="980" Height="720"
|
||||
MinWidth="780" MinHeight="560"
|
||||
WindowStartupLocation="CenterOwner"
|
||||
Background="#141720"
|
||||
Foreground="#ECEFF4">
|
||||
<Window.Resources>
|
||||
<Style x:Key="DarkButtonStyle" TargetType="Button">
|
||||
<Setter Property="Background" Value="#2563EB"/>
|
||||
<Setter Property="Foreground" Value="White"/>
|
||||
<Setter Property="BorderBrush" Value="#3B82F6"/>
|
||||
<Setter Property="BorderThickness" Value="1"/>
|
||||
<Setter Property="Padding" Value="12,6"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border Background="{TemplateBinding Background}"
|
||||
BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}"
|
||||
CornerRadius="5"
|
||||
Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
|
||||
</Border>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Opacity" Value="0.9"/>
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Opacity" Value="0.45"/>
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Window.Resources>
|
||||
|
||||
<Grid Margin="16">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- 1. ヘッダー&セーブファイル選択 -->
|
||||
<Border Grid.Row="0" Background="#1E2332" BorderBrush="#2A3142" BorderThickness="1" CornerRadius="8" Padding="14,10" Margin="0,0,0,10">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0,0,0,8">
|
||||
<TextBlock Text="🛠 NW.js セーブデータ改造エディタ" FontSize="16" FontWeight="Bold" Foreground="#00E5FF" VerticalAlignment="Center"/>
|
||||
<TextBlock x:Name="GameTitleText" Text="" FontSize="13" Foreground="#A5B1C2" VerticalAlignment="Center" Margin="14,0,0,0"/>
|
||||
</StackPanel>
|
||||
|
||||
<Grid Grid.Row="1">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Grid.Column="0" Text="対象ファイル:" VerticalAlignment="Center" Foreground="#ECEFF4" FontWeight="SemiBold" Margin="0,0,10,0"/>
|
||||
<ComboBox x:Name="SaveFileComboBox" Grid.Column="1"
|
||||
DisplayMemberPath="SummaryText"
|
||||
SelectionChanged="SaveFileComboBox_SelectionChanged"
|
||||
Height="30" VerticalContentAlignment="Center"
|
||||
Margin="0,0,8,0"/>
|
||||
<Button Grid.Column="2" Content="🔄 再読込" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#334155" BorderBrush="#475569"
|
||||
Click="ReloadButton_Click" Margin="0,0,8,0"/>
|
||||
<Button Grid.Column="3" Content="📂 フォルダを開く" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#334155" BorderBrush="#475569"
|
||||
Click="OpenFolderButton_Click"/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 2. ワンクリック・クイック改造バー -->
|
||||
<Border Grid.Row="1" Background="#1A2436" BorderBrush="#2563EB" BorderThickness="1" CornerRadius="8" Padding="12,8" Margin="0,0,0,10">
|
||||
<WrapPanel Orientation="Horizontal" VerticalAlignment="Center">
|
||||
<TextBlock Text="⚡ クイック改造:" Foreground="#38BDF8" FontWeight="Bold" VerticalAlignment="Center" Margin="0,0,10,0"/>
|
||||
<Button Content="💰 所持金 MAX (9,999,999)" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#059669" BorderBrush="#10B981" Padding="10,4" Margin="0,2,6,2"
|
||||
Click="QuickMaxGold_Click"/>
|
||||
<Button Content="🧾 借金を 0 にする" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#D97706" BorderBrush="#F59E0B" Padding="10,4" Margin="0,2,6,2"
|
||||
Click="QuickZeroDebt_Click"/>
|
||||
<Button Content="❤️ スタミナ/HP 全快 (999)" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#7C3AED" BorderBrush="#8B5CF6" Padding="10,4" Margin="0,2,6,2"
|
||||
Click="QuickMaxStamina_Click"/>
|
||||
<Button Content="🎒 所持アイテム数 ×99" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#0284C7" BorderBrush="#38BDF8" Padding="10,4" Margin="0,2,6,2"
|
||||
Click="QuickMaxItems_Click"/>
|
||||
<Button Content="🔓 全スイッチ・ギャラリー解放ON" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#DB2777" BorderBrush="#F472B6" Padding="10,4" Margin="0,2,0,2"
|
||||
Click="QuickUnlockAllSwitches_Click"/>
|
||||
</WrapPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 3. 検索・カテゴリ絞り込み・一括変更バー -->
|
||||
<Border Grid.Row="2" Background="#1E2332" BorderBrush="#2A3142" BorderThickness="1" CornerRadius="8" Padding="12,8" Margin="0,0,0,10">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="180"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="110"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="90"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock Grid.Column="0" Text="分類:" VerticalAlignment="Center" Foreground="#A5B1C2" Margin="0,0,6,0"/>
|
||||
<ComboBox x:Name="CategoryFilterComboBox" Grid.Column="1" Height="28" VerticalContentAlignment="Center"
|
||||
SelectionChanged="FilterChanged" Margin="0,0,10,0"/>
|
||||
|
||||
<TextBlock Grid.Column="2" Text="検索:" VerticalAlignment="Center" Foreground="#A5B1C2" Margin="0,0,6,0"/>
|
||||
<TextBox x:Name="KeywordFilterTextBox" Grid.Column="3" Height="28" VerticalContentAlignment="Center"
|
||||
Background="#141720" Foreground="#ECEFF4" BorderBrush="#3B4252" Padding="6,0"
|
||||
ToolTip="項目名や変数番号・パスで絞り込みます"
|
||||
TextChanged="FilterChanged" Margin="0,0,10,0"/>
|
||||
|
||||
<TextBlock Grid.Column="4" Text="現在値一致:" VerticalAlignment="Center" Foreground="#A5B1C2" Margin="0,0,6,0"/>
|
||||
<TextBox x:Name="ExactValueFilterTextBox" Grid.Column="5" Height="28" VerticalContentAlignment="Center"
|
||||
Background="#141720" Foreground="#38BDF8" BorderBrush="#3B4252" Padding="6,0"
|
||||
ToolTip="指定した値と完全一致する項目だけをピンポイント抽出します(例: 100)"
|
||||
TextChanged="FilterChanged" Margin="0,0,12,0"/>
|
||||
|
||||
<TextBlock Grid.Column="6" Text="一括値:" VerticalAlignment="Center" Foreground="#A5B1C2" Margin="0,0,6,0"/>
|
||||
<TextBox x:Name="BulkValueTextBox" Grid.Column="7" Height="28" VerticalContentAlignment="Center"
|
||||
Background="#141720" Foreground="#00E676" BorderBrush="#3B4252" Padding="6,0"
|
||||
Text="999" Margin="0,0,6,0"/>
|
||||
<Button Grid.Column="8" Content="表示中へ一括反映" Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#334155" BorderBrush="#475569" Padding="10,4"
|
||||
Click="ApplyBulkValue_Click"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 4. メイン編集タブ(GUIテーブル / JSONテキスト直接編集) -->
|
||||
<TabControl x:Name="EditorTabControl" Grid.Row="3" Background="#1E2332" BorderBrush="#2A3142"
|
||||
SelectionChanged="EditorTabControl_SelectionChanged">
|
||||
<TabItem Header="📊 ステータス・変数・アイテム一覧 (GUI編集)" Foreground="#141720" FontWeight="Bold">
|
||||
<Grid Background="#141720">
|
||||
<DataGrid x:Name="EntriesDataGrid"
|
||||
AutoGenerateColumns="False"
|
||||
CanUserAddRows="False"
|
||||
CanUserDeleteRows="False"
|
||||
Background="#141720"
|
||||
RowBackground="#1E2332"
|
||||
AlternatingRowBackground="#191D2A"
|
||||
Foreground="#ECEFF4"
|
||||
GridLinesVisibility="Horizontal"
|
||||
HorizontalGridLinesBrush="#2A3142"
|
||||
BorderBrush="#2A3142"
|
||||
HeadersVisibility="Column"
|
||||
SelectionMode="Single"
|
||||
RowHeight="30">
|
||||
<DataGrid.Resources>
|
||||
<Style TargetType="DataGridColumnHeader">
|
||||
<Setter Property="Background" Value="#252B3D"/>
|
||||
<Setter Property="Foreground" Value="#38BDF8"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Padding" Value="10,6"/>
|
||||
<Setter Property="BorderBrush" Value="#2A3142"/>
|
||||
<Setter Property="BorderThickness" Value="0,0,1,1"/>
|
||||
</Style>
|
||||
</DataGrid.Resources>
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="カテゴリ" Binding="{Binding Category}" Width="165" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="項目名 / 変数・ステータス名" Binding="{Binding DisplayKey}" Width="*" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="型" Binding="{Binding ValueType}" Width="75" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="変更前の値" Binding="{Binding OriginalValueText}" Width="130" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="✏️ 編集後の値 (ダブルクリックで変更)" Binding="{Binding ValueText, UpdateSourceTrigger=PropertyChanged}" Width="210">
|
||||
<DataGridTextColumn.ElementStyle>
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="#00E5FF"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Padding" Value="6,0"/>
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
</Style>
|
||||
</DataGridTextColumn.ElementStyle>
|
||||
<DataGridTextColumn.EditingElementStyle>
|
||||
<Style TargetType="TextBox">
|
||||
<Setter Property="Background" Value="#0F172A"/>
|
||||
<Setter Property="Foreground" Value="#00E676"/>
|
||||
<Setter Property="FontWeight" Value="Bold"/>
|
||||
<Setter Property="Padding" Value="4,2"/>
|
||||
</Style>
|
||||
</DataGridTextColumn.EditingElementStyle>
|
||||
</DataGridTextColumn>
|
||||
<DataGridTextColumn Header="内部パス" Binding="{Binding JsonPath}" Width="150" IsReadOnly="True"/>
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
|
||||
<TabItem Header="📝 JSON ソース直接編集 (上級者向け)" Foreground="#141720" FontWeight="Bold">
|
||||
<Grid Background="#141720" Margin="4">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Grid.Row="0"
|
||||
Text="💡 復号・展開されたセーブデータの JSON 全文を直接編集できます(GameCreator の暗号化 .gcdata も保存時に自動で再暗号化されます)。"
|
||||
Foreground="#A5B1C2" FontSize="12" Margin="4,4,4,6"/>
|
||||
<TextBox x:Name="RawJsonTextBox" Grid.Row="1"
|
||||
AcceptsReturn="True" AcceptsTab="True"
|
||||
VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"
|
||||
FontFamily="Consolas, Meiryo UI" FontSize="13"
|
||||
Background="#0F172A" Foreground="#E2E8F0" BorderBrush="#334155"
|
||||
Padding="10"/>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
|
||||
<!-- 5. フッター&保存・バックアップ復元ボタン -->
|
||||
<Grid Grid.Row="4" Margin="0,12,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<TextBlock x:Name="StatusTextBlock" Grid.Column="0"
|
||||
Text="セーブデータを選択してください。"
|
||||
Foreground="#00E676" VerticalAlignment="Center" TextWrapping="NoWrap" TextTrimming="CharacterEllipsis"/>
|
||||
|
||||
<Button x:Name="RestoreBackupButton" Grid.Column="1"
|
||||
Content="⏪ バックアップから復元"
|
||||
Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#B45309" BorderBrush="#F59E0B"
|
||||
Click="RestoreBackupButton_Click" Margin="10,0,8,0"/>
|
||||
|
||||
<Button x:Name="SaveButton" Grid.Column="2"
|
||||
Content="💾 変更をセーブデータに保存"
|
||||
Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#059669" BorderBrush="#10B981"
|
||||
Click="SaveButton_Click" Margin="0,0,8,0"/>
|
||||
|
||||
<Button Grid.Column="3" Content="閉じる"
|
||||
Style="{StaticResource DarkButtonStyle}"
|
||||
Background="#334155" BorderBrush="#475569"
|
||||
Click="CloseButton_Click"/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -0,0 +1,504 @@
|
||||
// Engines/Nwjs/NwjsSaveEditorDialog.xaml.cs — NW.js セーブデータ改造エディタダイアログ
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using GameLauncher.Engines.Tkool;
|
||||
|
||||
namespace GameLauncher.Engines.Nwjs
|
||||
{
|
||||
/// <summary>
|
||||
/// NW.js 分類ゲーム(GameCreator .gcdata 暗号化セーブおよびカスタム HTML5/JS .json セーブ)の
|
||||
/// ステータス・変数・所持品・フラグを編集・バックアップ・復元するダイアログウィンドウ。
|
||||
/// </summary>
|
||||
public partial class NwjsSaveEditorDialog : Window
|
||||
{
|
||||
#region □定数(Private)
|
||||
|
||||
/// <summary>
|
||||
/// カテゴリフィルタの「すべて表示」項目文字列。
|
||||
/// </summary>
|
||||
private const string AllCategoriesLabel = "すべて表示";
|
||||
|
||||
#endregion
|
||||
|
||||
#region □変数(Private)
|
||||
|
||||
private readonly TkoolGameItem _game;
|
||||
private List<NwjsSaveFileInfo> _saveFiles = new List<NwjsSaveFileInfo>();
|
||||
private NwjsLoadedSaveDocument? _currentDoc;
|
||||
private List<NwjsSaveEntryItem> _filteredEntries = new List<NwjsSaveEntryItem>();
|
||||
private bool _isSuppressingEvents;
|
||||
|
||||
#endregion
|
||||
|
||||
#region □コンストラクタ
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="NwjsSaveEditorDialog"/> クラスの新しいインスタンスを初期化します。
|
||||
/// </summary>
|
||||
/// <param name="game">編集対象の NW.js ゲームアイテム</param>
|
||||
public NwjsSaveEditorDialog(TkoolGameItem game)
|
||||
{
|
||||
this._game = game ?? throw new ArgumentNullException(nameof(game));
|
||||
this.InitializeComponent();
|
||||
this.GameTitleText.Text = $"— {this._game.Title}";
|
||||
this.LoadSaveFileList();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region □イベント
|
||||
|
||||
private void SaveFileComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (this._isSuppressingEvents)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.SaveFileComboBox.SelectedItem is NwjsSaveFileInfo selectedFile)
|
||||
{
|
||||
this.LoadSelectedSaveFile(selectedFile);
|
||||
}
|
||||
}
|
||||
|
||||
private void ReloadButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
this.LoadSaveFileList();
|
||||
}
|
||||
|
||||
private void OpenFolderButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
string targetDir = this._game.RootDirectory;
|
||||
if (this.SaveFileComboBox.SelectedItem is NwjsSaveFileInfo selectedFile && !string.IsNullOrEmpty(selectedFile.FilePath))
|
||||
{
|
||||
string? dir = Path.GetDirectoryName(selectedFile.FilePath);
|
||||
if (!string.IsNullOrEmpty(dir) && Directory.Exists(dir))
|
||||
{
|
||||
targetDir = dir;
|
||||
}
|
||||
}
|
||||
|
||||
if (Directory.Exists(targetDir))
|
||||
{
|
||||
try
|
||||
{
|
||||
Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = targetDir,
|
||||
UseShellExecute = true
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(this, $"フォルダを開けませんでした:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void FilterChanged(object sender, EventArgs e)
|
||||
{
|
||||
if (this._isSuppressingEvents)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.ApplyFilter();
|
||||
}
|
||||
|
||||
private void EditorTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (this._isSuppressingEvents || this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ReferenceEquals(e.Source, this.EditorTabControl))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// タブ2 (JSON直接編集) に切り替えた際、GUIテーブルでの変更をJSON文字列に同期する
|
||||
if (this.EditorTabControl.SelectedIndex == 1)
|
||||
{
|
||||
string updatedJson = NwjsSaveService.ApplyEntriesToDocument(this._currentDoc);
|
||||
this.RawJsonTextBox.Text = updatedJson;
|
||||
}
|
||||
}
|
||||
|
||||
private void QuickMaxGold_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
foreach (NwjsSaveEntryItem item in this._currentDoc.Entries)
|
||||
{
|
||||
if (item.ValueType == "Number" &&
|
||||
(item.JsonPath.EndsWith("money", StringComparison.OrdinalIgnoreCase) ||
|
||||
item.JsonPath.EndsWith("gold", StringComparison.OrdinalIgnoreCase) ||
|
||||
item.DisplayKey.Contains("所持金", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
item.ValueText = "9999999";
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
this.RefreshGridAndStatus(count > 0
|
||||
? $"💰 所持金項目 ({count} 件) を 9,999,999 に設定しました。「💾 変更をセーブデータに保存」で確定します。"
|
||||
: "ℹ️ このセーブファイル内に直接の所持金プロパティ (gold / money) が見つかりませんでした。数値変数またはゲーム内チート [F10] をご利用ください。");
|
||||
}
|
||||
|
||||
private void QuickZeroDebt_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
foreach (NwjsSaveEntryItem item in this._currentDoc.Entries)
|
||||
{
|
||||
if (item.ValueType == "Number" &&
|
||||
(item.JsonPath.EndsWith("debt", StringComparison.OrdinalIgnoreCase) ||
|
||||
item.DisplayKey.Contains("借金残高", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
item.ValueText = "0";
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
this.RefreshGridAndStatus(count > 0
|
||||
? $"🧾 借金項目 ({count} 件) を 0 に設定しました。「💾 変更をセーブデータに保存」で確定します。"
|
||||
: "ℹ️ このセーブファイル内に借金プロパティ (debt) はありません。");
|
||||
}
|
||||
|
||||
private void QuickMaxStamina_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
foreach (NwjsSaveEntryItem item in this._currentDoc.Entries)
|
||||
{
|
||||
if (item.ValueType == "Number" &&
|
||||
(item.JsonPath.EndsWith("stamina", StringComparison.OrdinalIgnoreCase) ||
|
||||
item.JsonPath.EndsWith("maxStamina", StringComparison.OrdinalIgnoreCase) ||
|
||||
item.JsonPath.EndsWith(".hp", StringComparison.OrdinalIgnoreCase) ||
|
||||
item.JsonPath.EndsWith(".maxHp", StringComparison.OrdinalIgnoreCase) ||
|
||||
item.JsonPath.EndsWith(".mp", StringComparison.OrdinalIgnoreCase) ||
|
||||
item.JsonPath.EndsWith(".maxMp", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
item.ValueText = "999";
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
this.RefreshGridAndStatus(count > 0
|
||||
? $"❤️ スタミナ・HP/MP 項目 ({count} 件) を 999 に設定しました。「💾 変更をセーブデータに保存」で確定します。"
|
||||
: "ℹ️ 該当するスタミナ・HPプロパティが見つかりませんでした。変数検索またはゲーム内チート [F10] をご利用ください。");
|
||||
}
|
||||
|
||||
private void QuickMaxItems_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
foreach (NwjsSaveEntryItem item in this._currentDoc.Entries)
|
||||
{
|
||||
if (item.Category == "🎒 所持アイテム" && item.ValueType == "Number")
|
||||
{
|
||||
item.ValueText = "99";
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
this.RefreshGridAndStatus(count > 0
|
||||
? $"🎒 所持アイテム ({count} 件) の個数を 99 に設定しました。「💾 変更をセーブデータに保存」で確定します。"
|
||||
: "ℹ️ 現在所持しているアイテムエントリが 0 件です(新規アイテムの入手はゲーム内チートメニュー [F10] から行えます)。");
|
||||
}
|
||||
|
||||
private void QuickUnlockAllSwitches_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
foreach (NwjsSaveEntryItem item in this._currentDoc.Entries)
|
||||
{
|
||||
if (item.JsonPath.Equals("userUnlockAll", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
item.ValueText = "true";
|
||||
count++;
|
||||
}
|
||||
else if (item.Category.Contains("スイッチ", StringComparison.OrdinalIgnoreCase) ||
|
||||
item.Category.Contains("フラグ", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
item.ValueText = item.ValueType == "Boolean" ? "true" : "1";
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
this.RefreshGridAndStatus(count > 0
|
||||
? $"🔓 スイッチ・解放フラグ ({count} 件) を ON に設定しました。「💾 変更をセーブデータに保存」で確定します。"
|
||||
: "ℹ️ 対象のスイッチ・解放フラグ項目が見つかりませんでした。");
|
||||
}
|
||||
|
||||
private void ApplyBulkValue_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null || this._filteredEntries.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
string bulkVal = this.BulkValueTextBox.Text?.Trim() ?? string.Empty;
|
||||
if (string.IsNullOrEmpty(bulkVal))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
foreach (NwjsSaveEntryItem item in this._filteredEntries)
|
||||
{
|
||||
item.ValueText = bulkVal;
|
||||
count++;
|
||||
}
|
||||
|
||||
this.RefreshGridAndStatus($"✏️ 現在表示中の {count} 件の項目に「{bulkVal}」を一括設定しました。");
|
||||
}
|
||||
|
||||
private void SaveButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
this.EntriesDataGrid.CommitEdit(DataGridEditingUnit.Cell, true);
|
||||
this.EntriesDataGrid.CommitEdit(DataGridEditingUnit.Row, true);
|
||||
|
||||
string jsonToSave;
|
||||
if (this.EditorTabControl.SelectedIndex == 1)
|
||||
{
|
||||
jsonToSave = this.RawJsonTextBox.Text;
|
||||
}
|
||||
else
|
||||
{
|
||||
jsonToSave = NwjsSaveService.ApplyEntriesToDocument(this._currentDoc);
|
||||
this.RawJsonTextBox.Text = jsonToSave;
|
||||
}
|
||||
|
||||
NwjsSaveService.SaveToFile(this._currentDoc.FileInfo, this._game.RootDirectory, jsonToSave, createBackup: true);
|
||||
|
||||
foreach (NwjsSaveEntryItem entry in this._currentDoc.Entries)
|
||||
{
|
||||
if (entry.IsModified)
|
||||
{
|
||||
entry.InitializeValue(entry.ValueText);
|
||||
}
|
||||
}
|
||||
|
||||
this.RestoreBackupButton.IsEnabled = this._currentDoc.FileInfo.HasBackup;
|
||||
this.StatusTextBlock.Text = $"✔ 保存完了: {this._currentDoc.FileInfo.DisplayName} (初回バックアップ保護済み)";
|
||||
MessageBox.Show(
|
||||
this,
|
||||
$"セーブデータを保存しました!\n\n対象: {this._currentDoc.FileInfo.DisplayName}\n※元のセーブデータは自動バックアップされています。",
|
||||
"セーブデータ保存完了",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Information);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(
|
||||
this,
|
||||
$"セーブデータの保存中にエラーが発生しました:\n{ex.Message}",
|
||||
"保存エラー",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void RestoreBackupButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentDoc == null || !this._currentDoc.FileInfo.HasBackup)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
MessageBoxResult res = MessageBox.Show(
|
||||
this,
|
||||
$"バックアップから元のセーブデータを復元しますか?\n\n対象: {this._currentDoc.FileInfo.DisplayName}",
|
||||
"バックアップ復元の確認",
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Question);
|
||||
|
||||
if (res != MessageBoxResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (NwjsSaveService.RestoreBackup(this._currentDoc.FileInfo))
|
||||
{
|
||||
this.LoadSelectedSaveFile(this._currentDoc.FileInfo);
|
||||
this.StatusTextBlock.Text = $"⏪ バックアップから復元しました: {this._currentDoc.FileInfo.DisplayName}";
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(
|
||||
this,
|
||||
$"バックアップの復元に失敗しました:\n{ex.Message}",
|
||||
"復元エラー",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void CloseButton_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
this.Close();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region □メソッド(Private)
|
||||
|
||||
private void LoadSaveFileList()
|
||||
{
|
||||
this._isSuppressingEvents = true;
|
||||
try
|
||||
{
|
||||
string? previousPath = (this.SaveFileComboBox.SelectedItem as NwjsSaveFileInfo)?.FilePath;
|
||||
this._saveFiles = NwjsSaveService.FindSaveFiles(this._game.RootDirectory, this._game.FolderName);
|
||||
this.SaveFileComboBox.ItemsSource = this._saveFiles;
|
||||
|
||||
if (this._saveFiles.Count == 0)
|
||||
{
|
||||
this._currentDoc = null;
|
||||
this.EntriesDataGrid.ItemsSource = null;
|
||||
this.RawJsonTextBox.Text = string.Empty;
|
||||
this.SaveButton.IsEnabled = false;
|
||||
this.RestoreBackupButton.IsEnabled = false;
|
||||
this.StatusTextBlock.Text = "⚠️ セーブファイルが見つかりません。ゲームを起動して一度セーブを作成するか、ゲーム内チート [F10] をご利用ください。";
|
||||
return;
|
||||
}
|
||||
|
||||
NwjsSaveFileInfo? target = null;
|
||||
if (!string.IsNullOrEmpty(previousPath))
|
||||
{
|
||||
target = this._saveFiles.FirstOrDefault(f => string.Equals(f.FilePath, previousPath, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
target ??= this._saveFiles[0];
|
||||
this.SaveFileComboBox.SelectedItem = target;
|
||||
this._isSuppressingEvents = false;
|
||||
this.LoadSelectedSaveFile(target);
|
||||
}
|
||||
finally
|
||||
{
|
||||
this._isSuppressingEvents = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void LoadSelectedSaveFile(NwjsSaveFileInfo fileInfo)
|
||||
{
|
||||
try
|
||||
{
|
||||
this._currentDoc = NwjsSaveService.LoadSaveFile(fileInfo, this._game.RootDirectory);
|
||||
this.RawJsonTextBox.Text = this._currentDoc.FormattedJson;
|
||||
this.SaveButton.IsEnabled = true;
|
||||
this.RestoreBackupButton.IsEnabled = fileInfo.HasBackup;
|
||||
|
||||
// カテゴリ一覧を更新
|
||||
this._isSuppressingEvents = true;
|
||||
var categories = new List<string> { NwjsSaveEditorDialog.AllCategoriesLabel };
|
||||
categories.AddRange(this._currentDoc.Entries.Select(x => x.Category).Distinct());
|
||||
this.CategoryFilterComboBox.ItemsSource = categories;
|
||||
this.CategoryFilterComboBox.SelectedIndex = 0;
|
||||
this._isSuppressingEvents = false;
|
||||
|
||||
this.ApplyFilter();
|
||||
string formatLabel = fileInfo.FormatKind == NwjsSaveFormatKind.GameCreatorGcData
|
||||
? "GameCreator 暗号化セーブ (.gcdata 復号済)"
|
||||
: "JSON セーブデータ";
|
||||
this.StatusTextBlock.Text = $"✔ 読込完了: {fileInfo.DisplayName} [{formatLabel}] — 全 {this._currentDoc.Entries.Count} 項目";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._currentDoc = null;
|
||||
this.EntriesDataGrid.ItemsSource = null;
|
||||
this.RawJsonTextBox.Text = string.Empty;
|
||||
this.SaveButton.IsEnabled = false;
|
||||
this.RestoreBackupButton.IsEnabled = false;
|
||||
this.StatusTextBlock.Text = $"❌ 読込エラー: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyFilter()
|
||||
{
|
||||
if (this._currentDoc == null)
|
||||
{
|
||||
this._filteredEntries = new List<NwjsSaveEntryItem>();
|
||||
this.EntriesDataGrid.ItemsSource = null;
|
||||
return;
|
||||
}
|
||||
|
||||
string selectedCategory = this.CategoryFilterComboBox.SelectedItem as string ?? NwjsSaveEditorDialog.AllCategoriesLabel;
|
||||
string keyword = this.KeywordFilterTextBox.Text?.Trim() ?? string.Empty;
|
||||
string exactVal = this.ExactValueFilterTextBox.Text?.Trim() ?? string.Empty;
|
||||
|
||||
IEnumerable<NwjsSaveEntryItem> query = this._currentDoc.Entries;
|
||||
|
||||
if (!string.Equals(selectedCategory, NwjsSaveEditorDialog.AllCategoriesLabel, StringComparison.Ordinal))
|
||||
{
|
||||
query = query.Where(x => string.Equals(x.Category, selectedCategory, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(keyword))
|
||||
{
|
||||
query = query.Where(x =>
|
||||
x.DisplayKey.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
|
||||
x.JsonPath.Contains(keyword, StringComparison.OrdinalIgnoreCase) ||
|
||||
x.ValueText.Contains(keyword, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(exactVal))
|
||||
{
|
||||
query = query.Where(x => string.Equals(x.ValueText.Trim(), exactVal, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
this._filteredEntries = query.ToList();
|
||||
this.EntriesDataGrid.ItemsSource = this._filteredEntries;
|
||||
}
|
||||
|
||||
private void RefreshGridAndStatus(string message)
|
||||
{
|
||||
this.EntriesDataGrid.Items.Refresh();
|
||||
if (this._currentDoc != null && this.EditorTabControl.SelectedIndex == 1)
|
||||
{
|
||||
this.RawJsonTextBox.Text = NwjsSaveService.ApplyEntriesToDocument(this._currentDoc);
|
||||
}
|
||||
|
||||
this.StatusTextBlock.Text = message;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -105,6 +105,7 @@ namespace GameLauncher.Engines.Tkool
|
||||
private bool _applyMod = true;
|
||||
private bool _hasCustomApplyMod;
|
||||
private bool _isInitializingApplyMod;
|
||||
private bool _hasSaveData;
|
||||
private ModPluginOptions _modOptions = new();
|
||||
|
||||
// app.asar 関連プロパティ
|
||||
@@ -130,6 +131,20 @@ namespace GameLauncher.Engines.Tkool
|
||||
private string? _evbBackupPath;
|
||||
private string _evbUnderlyingEngine = string.Empty;
|
||||
|
||||
/// <summary>セーブデータ検出フラグ</summary>
|
||||
public override bool HasSaveData
|
||||
{
|
||||
get => this._hasSaveData;
|
||||
set
|
||||
{
|
||||
if (this._hasSaveData != value)
|
||||
{
|
||||
this._hasSaveData = value;
|
||||
this.OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Enigma Virtual Box でパックされた exe を持つゲームかどうか</summary>
|
||||
public override bool IsEvbPacked
|
||||
{
|
||||
@@ -306,6 +321,7 @@ namespace GameLauncher.Engines.Tkool
|
||||
TkoolEngineType.Wolf => GameEngineKind.Wolf,
|
||||
TkoolEngineType.SrpgStudio => GameEngineKind.SrpgStudio,
|
||||
TkoolEngineType.Nwjs => GameEngineKind.Nwjs,
|
||||
TkoolEngineType.Bakin => GameEngineKind.Bakin,
|
||||
TkoolEngineType.Other => GameEngineKind.Other,
|
||||
_ => GameEngineKind.Tkool
|
||||
};
|
||||
@@ -331,17 +347,18 @@ namespace GameLauncher.Engines.Tkool
|
||||
public override bool IsSrpgStudio => this.EngineType == TkoolEngineType.SrpgStudio;
|
||||
public override bool IsRgss => this.EngineType is TkoolEngineType.VX or TkoolEngineType.VXAce;
|
||||
public override bool IsNwjs => this.EngineType == TkoolEngineType.Nwjs;
|
||||
public override bool IsBakin => this.EngineType == TkoolEngineType.Bakin;
|
||||
public override bool IsOther => this.EngineType == TkoolEngineType.Other;
|
||||
|
||||
/// <summary>
|
||||
/// スクリプト改造(プラグイン注入など)が適用可能な状態かどうか。
|
||||
/// 該当ゲームが改造非対応(ウディタ・SRPG・NW.js・その他・未解凍状態など)の場合は false を返します。
|
||||
/// 該当ゲームが改造非対応(ウディタ・SRPG・Bakin・NW.js・その他・未解凍状態など)の場合は false を返します。
|
||||
/// </summary>
|
||||
public override bool CanApplyScriptMod
|
||||
{
|
||||
get
|
||||
{
|
||||
if (this.IsWolf || this.IsNwjs || this.IsSrpgStudio || this.IsOther)
|
||||
if (this.IsWolf || this.IsSrpgStudio || this.IsBakin || this.IsOther)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -365,7 +382,7 @@ namespace GameLauncher.Engines.Tkool
|
||||
}
|
||||
return !string.IsNullOrEmpty(this.PluginsJsPath) && File.Exists(this.PluginsJsPath);
|
||||
}
|
||||
if (this.IsMV || this.IsMZ || this.IsTyrano)
|
||||
if (this.IsMV || this.IsMZ || this.IsTyrano || this.IsNwjs)
|
||||
{
|
||||
return !string.IsNullOrEmpty(this.PluginsJsPath) && File.Exists(this.PluginsJsPath);
|
||||
}
|
||||
@@ -385,6 +402,7 @@ namespace GameLauncher.Engines.Tkool
|
||||
TkoolEngineType.Tyrano => "ティラノ",
|
||||
TkoolEngineType.Wolf => "ウディタ",
|
||||
TkoolEngineType.SrpgStudio => "SRPG",
|
||||
TkoolEngineType.Bakin => "Bakin",
|
||||
_ => string.Empty
|
||||
};
|
||||
|
||||
@@ -398,6 +416,7 @@ namespace GameLauncher.Engines.Tkool
|
||||
TkoolEngineType.Tyrano => new SolidColorBrush(Color.FromRgb(0xD3, 0x54, 0x00)),
|
||||
TkoolEngineType.Wolf => new SolidColorBrush(Color.FromRgb(0x8B, 0x57, 0x1E)),
|
||||
TkoolEngineType.SrpgStudio => new SolidColorBrush(Color.FromRgb(0x1E, 0x7A, 0x5F)),
|
||||
TkoolEngineType.Bakin => new SolidColorBrush(Color.FromRgb(0xD9, 0x77, 0x06)),
|
||||
_ => Brushes.Transparent
|
||||
};
|
||||
|
||||
@@ -562,6 +581,7 @@ namespace GameLauncher.Engines.Tkool
|
||||
this.OnPropertyChanged(nameof(this.IsSrpgStudio));
|
||||
this.OnPropertyChanged(nameof(this.IsRgss));
|
||||
this.OnPropertyChanged(nameof(this.IsNwjs));
|
||||
this.OnPropertyChanged(nameof(this.IsBakin));
|
||||
this.OnPropertyChanged(nameof(this.IsOther));
|
||||
this.OnPropertyChanged(nameof(this.NwjsBadgeText));
|
||||
this.OnPropertyChanged(nameof(this.NwjsBadgeVisibility));
|
||||
@@ -583,6 +603,44 @@ namespace GameLauncher.Engines.Tkool
|
||||
}
|
||||
}
|
||||
|
||||
// ================= ツクールMZ関連プロパティ =================
|
||||
private bool _mzPixiErrorFix = true;
|
||||
private bool _mzSpineErrorFix = true;
|
||||
|
||||
/// <summary>
|
||||
/// ツクールMZ専用: Pixi.jsのテクスチャ参照エラー(Cannot read property 'valid' of null)修復およびDevTools有効化フラグ。
|
||||
/// 初期値は true(チェックON)
|
||||
/// </summary>
|
||||
public override bool MzPixiErrorFix
|
||||
{
|
||||
get => this._mzPixiErrorFix;
|
||||
set
|
||||
{
|
||||
if (this._mzPixiErrorFix != value)
|
||||
{
|
||||
this._mzPixiErrorFix = value;
|
||||
this.OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ツクールMZ専用: Spineアニメーション未定義エラー(Animation not found: 0_idle 等)修復フラグ。
|
||||
/// 初期値は true(チェックON)
|
||||
/// </summary>
|
||||
public override bool MzSpineErrorFix
|
||||
{
|
||||
get => this._mzSpineErrorFix;
|
||||
set
|
||||
{
|
||||
if (this._mzSpineErrorFix != value)
|
||||
{
|
||||
this._mzSpineErrorFix = value;
|
||||
this.OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ================= WOLF RPGエディター関連プロパティ =================
|
||||
private bool _wolfProxyDll = false;
|
||||
private double _wolfSpeedMultiplier = 3.0;
|
||||
@@ -919,6 +977,15 @@ namespace GameLauncher.Engines.Tkool
|
||||
new() { Id = "RgssWindowResizeExternal", Name = "🪟 外部ツールでウィンドウ拡大 (Win32 API / Sizer等)", Description = "ゲーム側は無改造のまま、ランチャーがゲームウィンドウを検出してディスプレイに収まる最大の整数倍へ拡大します。外部ツールパス設定があればそちらを優先起動します。(既定OFF)" }
|
||||
];
|
||||
|
||||
/// <summary>NW.js (GameCreator / HTML5・JS) 用スクリプト改造定義一覧</summary>
|
||||
public static readonly ModPluginDefinition[] DefaultNwjsPlugins =
|
||||
[
|
||||
new() { Id = "NwjsCheatMenu", Name = "🎛 ゲーム内ステータス・変数・所持金チートメニュー ([F10] / 画面右上ボタン)", Description = "画面右上の『⚙ チート [F10]』ボタンまたはF10キーで、所持金・ステータス・変数・スイッチ・所持アイテムをリアルタイムに検索・書き換えできるオーバーレイメニューを表示します(GameCreator / HTML5ステート / 汎用NW.js自動認識)。" },
|
||||
new() { Id = "NwjsSpeedHack", Name = "⚡ ゲーム倍速・高速化ショートカット ([F6] 倍速切替 / [Ctrl] 5倍速ブースト)", Description = "F6キーでゲーム速度を 1x → 2x → 3x → 5x に切り替え、Ctrlキー押下中は一時的に5倍速へ加速します(LayaAir/GameCreatorタイマー・アニメーション・動画再生速度対応)。" },
|
||||
new() { Id = "NwjsUnlockGallery", Name = "🔓 全CG・ギャラリー・回想フラグの自動解放", Description = "GalleryStoreやGameCreatorのワールド永続スイッチ(life.gcdata)、localStorage内のギャラリー・回想解放フラグを解放します。" },
|
||||
new() { Id = "NwjsDevTools", Name = "🛠 開発者ツール (F12) の有効化", Description = "F12キーでNW.js / Chromiumの開発者ツールコンソールを開けるようにします。" }
|
||||
];
|
||||
|
||||
/// <summary>SRPG Studio用スクリプト改造定義一覧</summary>
|
||||
public static readonly ModPluginDefinition[] DefaultSrpgPlugins =
|
||||
[
|
||||
@@ -936,14 +1003,18 @@ namespace GameLauncher.Engines.Tkool
|
||||
this._commonPluginOptions.Clear();
|
||||
this._specificPluginOptions.Clear();
|
||||
|
||||
if (this.EngineType is TkoolEngineType.Wolf or TkoolEngineType.Nwjs)
|
||||
if (this.EngineType is TkoolEngineType.Wolf or TkoolEngineType.Bakin or TkoolEngineType.Other)
|
||||
{
|
||||
this.OnPropertyChanged(nameof(this.HasSpecificPlugins));
|
||||
return;
|
||||
}
|
||||
|
||||
IEnumerable<ModPluginDefinition> targetDefs;
|
||||
if (this.EngineType == TkoolEngineType.Tyrano)
|
||||
if (this.IsNwjs)
|
||||
{
|
||||
targetDefs = TkoolGameItem.DefaultNwjsPlugins;
|
||||
}
|
||||
else if (this.EngineType == TkoolEngineType.Tyrano)
|
||||
{
|
||||
targetDefs = DefaultTyranoPlugins;
|
||||
}
|
||||
@@ -1032,6 +1103,7 @@ namespace GameLauncher.Engines.Tkool
|
||||
TkoolEngineType.Wolf => "WOLF RPGエディター",
|
||||
TkoolEngineType.SrpgStudio => "SRPG Studio",
|
||||
TkoolEngineType.Nwjs => "NW.js",
|
||||
TkoolEngineType.Bakin => "RPG Developer Bakin",
|
||||
_ => "ツクール/ティラノ"
|
||||
};
|
||||
}
|
||||
|
||||
@@ -225,7 +225,7 @@ namespace GameLauncher.Engines.Tkool
|
||||
// ※ResourceLoaderFix はリソース読み込み不具合の必須救済プラグインのため、常に有効化・先頭配置
|
||||
var fixPlugin = this._availablePlugins.FirstOrDefault(p => string.Equals(p.Id, "ResourceLoaderFix", StringComparison.OrdinalIgnoreCase));
|
||||
var pluginsToEnable = this._availablePlugins
|
||||
.Where(p => string.Equals(p.Id, "ResourceLoaderFix", StringComparison.OrdinalIgnoreCase) || game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: true))
|
||||
.Where(p => string.Equals(p.Id, "ResourceLoaderFix", StringComparison.OrdinalIgnoreCase) || game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: p.DefaultEnabled))
|
||||
.ToList();
|
||||
|
||||
// ResourceLoaderFix を最優先(先頭)に配置して、他プラグイン実行前のリソース要求も確実に救済
|
||||
|
||||
@@ -0,0 +1,747 @@
|
||||
// Engines/Tkool/TkoolMzFixService.cs
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace GameLauncher.Engines.Tkool
|
||||
{
|
||||
/// <summary>
|
||||
/// RPGツクールMZ専用のPixi.js・Spineエラー修復およびDevTools有効化サービス。
|
||||
/// マップ移動時に発生する Pixi.js の "Cannot read property 'valid' of null" クラッシュ、
|
||||
/// および Spine の "Animation not found" クラッシュを防止し、開発者ツール(DevTools)の制限を解除します。
|
||||
/// </summary>
|
||||
public static class TkoolMzFixService
|
||||
{
|
||||
#region □定数(Private)
|
||||
|
||||
private const string BackupSuffix = ".bak";
|
||||
private const string SpineFixMarker = "/* GameLauncher_SpineFix */";
|
||||
|
||||
#endregion
|
||||
|
||||
#region □メソッド(Public)
|
||||
|
||||
/// <summary>
|
||||
/// 指定されたゲームディレクトリに対して、Pixi.js のエラー修復および DevTools 有効化を適用します。
|
||||
/// </summary>
|
||||
/// <param name="rootDir">ゲームのルートディレクトリ</param>
|
||||
/// <returns>処理成否およびメッセージ</returns>
|
||||
public static (bool Success, string Message) ApplyMzPixiFix(string rootDir)
|
||||
{
|
||||
if (string.IsNullOrEmpty(rootDir) || !Directory.Exists(rootDir))
|
||||
{
|
||||
return (false, "ゲームディレクトリが存在しません。");
|
||||
}
|
||||
|
||||
int patchedCount = 0;
|
||||
var sb = new StringBuilder();
|
||||
|
||||
// 1. package.json の --disable-devtools 除去
|
||||
var packageJsonPath = Path.Combine(rootDir, "package.json");
|
||||
if (File.Exists(packageJsonPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (PatchPackageJson(packageJsonPath))
|
||||
{
|
||||
patchedCount++;
|
||||
sb.Append("DevTools有効化, ");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
sb.Append($"package.json修復失敗({ex.Message}), ");
|
||||
}
|
||||
}
|
||||
|
||||
// 2. js/libs/pixi.js の null安全パッチ適用
|
||||
var pixiJsPath = Path.Combine(rootDir, "js", "libs", "pixi.js");
|
||||
if (File.Exists(pixiJsPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (PatchPixiJs(pixiJsPath))
|
||||
{
|
||||
patchedCount++;
|
||||
sb.Append("pixi.js安全化, ");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
sb.Append($"pixi.js修復失敗({ex.Message}), ");
|
||||
}
|
||||
}
|
||||
|
||||
// 3. js/libs/pixi-picture.js の null安全パッチ適用
|
||||
var pixiPicturePath = Path.Combine(rootDir, "js", "libs", "pixi-picture.js");
|
||||
if (File.Exists(pixiPicturePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (PatchPixiPictureJs(pixiPicturePath))
|
||||
{
|
||||
patchedCount++;
|
||||
sb.Append("pixi-picture.js安全化, ");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
sb.Append($"pixi-picture.js修復失敗({ex.Message}), ");
|
||||
}
|
||||
}
|
||||
|
||||
if (patchedCount > 0)
|
||||
{
|
||||
var summary = sb.ToString().TrimEnd(' ', ',');
|
||||
return (true, $"ツクールMZ修復パッチを適用しました: [{summary}]");
|
||||
}
|
||||
|
||||
return (true, "ツクールMZ修復パッチは既に適用済みです。");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// バックアップファイルからオリジナル状態への復元を行います。
|
||||
/// </summary>
|
||||
/// <param name="rootDir">ゲームのルートディレクトリ</param>
|
||||
/// <returns>処理成否およびメッセージ</returns>
|
||||
public static (bool Success, string Message) RestoreMzPixiFix(string rootDir)
|
||||
{
|
||||
if (string.IsNullOrEmpty(rootDir) || !Directory.Exists(rootDir))
|
||||
{
|
||||
return (false, "ゲームディレクトリが存在しません。");
|
||||
}
|
||||
|
||||
int restoredCount = 0;
|
||||
|
||||
// 1. package.json の復元
|
||||
var packageJsonPath = Path.Combine(rootDir, "package.json");
|
||||
var packageJsonBak = packageJsonPath + BackupSuffix;
|
||||
if (File.Exists(packageJsonBak))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Copy(packageJsonBak, packageJsonPath, true);
|
||||
restoredCount++;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// 2. js/libs/pixi.js の復元
|
||||
var pixiJsPath = Path.Combine(rootDir, "js", "libs", "pixi.js");
|
||||
var pixiJsBak = pixiJsPath + BackupSuffix;
|
||||
if (File.Exists(pixiJsBak))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Copy(pixiJsBak, pixiJsPath, true);
|
||||
restoredCount++;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// 3. js/libs/pixi-picture.js の復元
|
||||
var pixiPicturePath = Path.Combine(rootDir, "js", "libs", "pixi-picture.js");
|
||||
var pixiPictureBak = pixiPicturePath + BackupSuffix;
|
||||
if (File.Exists(pixiPictureBak))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Copy(pixiPictureBak, pixiPicturePath, true);
|
||||
restoredCount++;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
return (true, $"ツクールMZ修復パッチを元に戻しました(復元ファイル数: {restoredCount})");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定されたゲームディレクトリに対して、Spineアニメーション未定義エラー(Animation not found 等)の修復パッチを適用します。
|
||||
/// </summary>
|
||||
/// <param name="rootDir">ゲームのルートディレクトリ</param>
|
||||
/// <returns>処理成否およびメッセージ</returns>
|
||||
public static (bool Success, string Message) ApplyMzSpineFix(string rootDir)
|
||||
{
|
||||
if (string.IsNullOrEmpty(rootDir) || !Directory.Exists(rootDir))
|
||||
{
|
||||
return (false, "ゲームディレクトリが存在しません。");
|
||||
}
|
||||
|
||||
bool hasTargetFile = false;
|
||||
int patchedCount = 0;
|
||||
var sb = new StringBuilder();
|
||||
|
||||
// 1. js/libs/pixi-spine.js の未定義アニメーション安全化パッチ適用
|
||||
var pixiSpinePath = Path.Combine(rootDir, "js", "libs", "pixi-spine.js");
|
||||
if (File.Exists(pixiSpinePath))
|
||||
{
|
||||
hasTargetFile = true;
|
||||
try
|
||||
{
|
||||
if (PatchPixiSpineJs(pixiSpinePath))
|
||||
{
|
||||
patchedCount++;
|
||||
sb.Append("pixi-spine.js安全化, ");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
sb.Append($"pixi-spine.js修復失敗({ex.Message}), ");
|
||||
}
|
||||
}
|
||||
|
||||
// 2. js/plugins/PictureSpine.js のスケルトン整合・null安全化パッチ適用
|
||||
var pictureSpinePath = Path.Combine(rootDir, "js", "plugins", "PictureSpine.js");
|
||||
if (File.Exists(pictureSpinePath))
|
||||
{
|
||||
hasTargetFile = true;
|
||||
try
|
||||
{
|
||||
if (PatchPictureSpineJs(pictureSpinePath))
|
||||
{
|
||||
patchedCount++;
|
||||
sb.Append("PictureSpine.js安全化, ");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
sb.Append($"PictureSpine.js修復失敗({ex.Message}), ");
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasTargetFile)
|
||||
{
|
||||
return (true, string.Empty);
|
||||
}
|
||||
|
||||
if (patchedCount > 0)
|
||||
{
|
||||
var summary = sb.ToString().TrimEnd(' ', ',');
|
||||
return (true, $"ツクールMZ Spine修復パッチを適用しました: [{summary}]");
|
||||
}
|
||||
|
||||
return (true, "ツクールMZ Spine修復パッチは既に適用済みです。");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spine修復パッチのバックアップファイルからオリジナル状態への復元を行います。
|
||||
/// </summary>
|
||||
/// <param name="rootDir">ゲームのルートディレクトリ</param>
|
||||
/// <returns>処理成否およびメッセージ</returns>
|
||||
public static (bool Success, string Message) RestoreMzSpineFix(string rootDir)
|
||||
{
|
||||
if (string.IsNullOrEmpty(rootDir) || !Directory.Exists(rootDir))
|
||||
{
|
||||
return (false, "ゲームディレクトリが存在しません。");
|
||||
}
|
||||
|
||||
int restoredCount = 0;
|
||||
|
||||
var pixiSpinePath = Path.Combine(rootDir, "js", "libs", "pixi-spine.js");
|
||||
var pixiSpineBak = pixiSpinePath + BackupSuffix;
|
||||
if (File.Exists(pixiSpineBak))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Copy(pixiSpineBak, pixiSpinePath, true);
|
||||
restoredCount++;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
var pictureSpinePath = Path.Combine(rootDir, "js", "plugins", "PictureSpine.js");
|
||||
var pictureSpineBak = pictureSpinePath + BackupSuffix;
|
||||
if (File.Exists(pictureSpineBak))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Copy(pictureSpineBak, pictureSpinePath, true);
|
||||
restoredCount++;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
if (restoredCount == 0)
|
||||
{
|
||||
return (true, string.Empty);
|
||||
}
|
||||
|
||||
return (true, $"ツクールMZ Spine修復パッチを元に戻しました(復元ファイル数: {restoredCount})");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region □メソッド(Private)
|
||||
|
||||
private static bool PatchPackageJson(string path)
|
||||
{
|
||||
string content = File.ReadAllText(path, Encoding.UTF8);
|
||||
if (!content.Contains("--disable-devtools"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var bakPath = path + BackupSuffix;
|
||||
if (!File.Exists(bakPath))
|
||||
{
|
||||
File.Copy(path, bakPath, true);
|
||||
}
|
||||
|
||||
string updated = content.Replace("--disable-devtools", string.Empty);
|
||||
updated = updated.Replace(" ", " ");
|
||||
File.WriteAllText(path, updated, new UTF8Encoding(true));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool PatchPixiJs(string path)
|
||||
{
|
||||
string content = File.ReadAllText(path, Encoding.UTF8);
|
||||
bool modified = false;
|
||||
|
||||
var bakPath = path + BackupSuffix;
|
||||
if (!File.Exists(bakPath))
|
||||
{
|
||||
File.Copy(path, bakPath, true);
|
||||
}
|
||||
|
||||
// A. AbstractBatchRenderer.prototype.render
|
||||
if (content.Contains("if (!element._texture.valid) {"))
|
||||
{
|
||||
content = content.Replace("if (!element._texture.valid) {", "if (!element || !element._texture || !element._texture.valid) {");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// B. SpriteMaskFilter.prototype.apply
|
||||
if (content.Contains("var maskSprite = this.maskSprite;\n\t var tex = maskSprite._texture;\n\t if (!tex.valid) {"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"var maskSprite = this.maskSprite;\n\t var tex = maskSprite._texture;\n\t if (!tex.valid) {",
|
||||
"var maskSprite = this.maskSprite;\n\t var tex = maskSprite ? maskSprite._texture : null;\n\t if (!tex || !tex.valid) {");
|
||||
modified = true;
|
||||
}
|
||||
else if (content.Contains("var maskSprite = this.maskSprite;\r\n\t var tex = maskSprite._texture;\r\n\t if (!tex.valid) {"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"var maskSprite = this.maskSprite;\r\n\t var tex = maskSprite._texture;\r\n\t if (!tex.valid) {",
|
||||
"var maskSprite = this.maskSprite;\r\n\t var tex = maskSprite ? maskSprite._texture : null;\r\n\t if (!tex || !tex.valid) {");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// C. Texture constructor
|
||||
if (content.Contains("if (!baseTexture.valid) {\n\t baseTexture.once('loaded', _this.onBaseTextureUpdated, _this);"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"if (!baseTexture.valid) {\n\t baseTexture.once('loaded', _this.onBaseTextureUpdated, _this);",
|
||||
"if (!baseTexture || !baseTexture.valid) {\n\t if (baseTexture) baseTexture.once('loaded', _this.onBaseTextureUpdated, _this);");
|
||||
modified = true;
|
||||
}
|
||||
else if (content.Contains("if (!baseTexture.valid) {\r\n\t baseTexture.once('loaded', _this.onBaseTextureUpdated, _this);"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"if (!baseTexture.valid) {\r\n\t baseTexture.once('loaded', _this.onBaseTextureUpdated, _this);",
|
||||
"if (!baseTexture || !baseTexture.valid) {\r\n\t if (baseTexture) baseTexture.once('loaded', _this.onBaseTextureUpdated, _this);");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// D. Texture.prototype.onBaseTextureUpdated
|
||||
if (content.Contains("if (!this.baseTexture.valid) {"))
|
||||
{
|
||||
content = content.Replace("if (!this.baseTexture.valid) {", "if (!this.baseTexture || !this.baseTexture.valid) {");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// E. Graphics
|
||||
if (content.Contains("if (fill && !fill.texture.baseTexture.valid)"))
|
||||
{
|
||||
content = content.Replace("if (fill && !fill.texture.baseTexture.valid)", "if (fill && (!fill.texture || !fill.texture.baseTexture || !fill.texture.baseTexture.valid))");
|
||||
modified = true;
|
||||
}
|
||||
if (content.Contains("if (line && !line.texture.baseTexture.valid)"))
|
||||
{
|
||||
content = content.Replace("if (line && !line.texture.baseTexture.valid)", "if (line && (!line.texture || !line.texture.baseTexture || !line.texture.baseTexture.valid))");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// F. Sprite.prototype texture setter
|
||||
if (content.Contains("if (value.baseTexture.valid) {\n\t this._onTextureUpdate();\n\t }\n\t else {\n\t value.once('update', this._onTextureUpdate, this);"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"if (value.baseTexture.valid) {\n\t this._onTextureUpdate();\n\t }\n\t else {\n\t value.once('update', this._onTextureUpdate, this);",
|
||||
"if (value.baseTexture && value.baseTexture.valid) {\n\t this._onTextureUpdate();\n\t }\n\t else if (value.baseTexture) {\n\t value.once('update', this._onTextureUpdate, this);");
|
||||
modified = true;
|
||||
}
|
||||
else if (content.Contains("if (value.baseTexture.valid) {\r\n\t this._onTextureUpdate();\r\n\t }\r\n\t else {\r\n\t value.once('update', this._onTextureUpdate, this);"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"if (value.baseTexture.valid) {\r\n\t this._onTextureUpdate();\r\n\t }\r\n\t else {\r\n\t value.once('update', this._onTextureUpdate, this);",
|
||||
"if (value.baseTexture && value.baseTexture.valid) {\r\n\t this._onTextureUpdate();\r\n\t }\r\n\t else if (value.baseTexture) {\r\n\t value.once('update', this._onTextureUpdate, this);");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// H. Texture constructor: baseTexture null safety (Cannot read property 'on' of null)
|
||||
if (content.Contains("if (baseTexture instanceof Texture) {\n\t baseTexture = baseTexture.baseTexture;\n\t }"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"if (baseTexture instanceof Texture) {\n\t baseTexture = baseTexture.baseTexture;\n\t }",
|
||||
"if (baseTexture instanceof Texture) {\n\t baseTexture = baseTexture.baseTexture;\n\t }\n\t if (!baseTexture) {\n\t baseTexture = new BaseTexture();\n\t }");
|
||||
modified = true;
|
||||
}
|
||||
else if (content.Contains("if (baseTexture instanceof Texture) {\r\n\t baseTexture = baseTexture.baseTexture;\r\n\t }"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"if (baseTexture instanceof Texture) {\r\n\t baseTexture = baseTexture.baseTexture;\r\n\t }",
|
||||
"if (baseTexture instanceof Texture) {\r\n\t baseTexture = baseTexture.baseTexture;\r\n\t }\r\n\t if (!baseTexture) {\r\n\t baseTexture = new BaseTexture();\r\n\t }");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// I. Texture constructor: noFrame on update safety
|
||||
if (content.Contains("if (_this.noFrame) {\n\t baseTexture.on('update', _this.onBaseTextureUpdated, _this);\n\t }"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"if (_this.noFrame) {\n\t baseTexture.on('update', _this.onBaseTextureUpdated, _this);\n\t }",
|
||||
"if (_this.noFrame && baseTexture) {\n\t baseTexture.on('update', _this.onBaseTextureUpdated, _this);\n\t }");
|
||||
modified = true;
|
||||
}
|
||||
else if (content.Contains("if (_this.noFrame) {\r\n\t baseTexture.on('update', _this.onBaseTextureUpdated, _this);\r\n\t }"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"if (_this.noFrame) {\r\n\t baseTexture.on('update', _this.onBaseTextureUpdated, _this);\r\n\t }",
|
||||
"if (_this.noFrame && baseTexture) {\r\n\t baseTexture.on('update', _this.onBaseTextureUpdated, _this);\r\n\t }");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// G. Mesh.prototype texture setter
|
||||
if (content.Contains("if (value.baseTexture.valid) {\n\t this.textureUpdated();\n\t }\n\t else {\n\t value.once('update', this.textureUpdated, this);"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"if (value.baseTexture.valid) {\n\t this.textureUpdated();\n\t }\n\t else {\n\t value.once('update', this.textureUpdated, this);",
|
||||
"if (value && value.baseTexture && value.baseTexture.valid) {\n\t this.textureUpdated();\n\t }\n\t else if (value && value.baseTexture) {\n\t value.once('update', this.textureUpdated, this);");
|
||||
modified = true;
|
||||
}
|
||||
else if (content.Contains("if (value.baseTexture.valid) {\r\n\t this.textureUpdated();\r\n\t }\r\n\t else {\r\n\t value.once('update', this.textureUpdated, this);"))
|
||||
{
|
||||
content = content.Replace(
|
||||
"if (value.baseTexture.valid) {\r\n\t this.textureUpdated();\r\n\t }\r\n\t else {\r\n\t value.once('update', this.textureUpdated, this);",
|
||||
"if (value && value.baseTexture && value.baseTexture.valid) {\r\n\t this.textureUpdated();\r\n\t }\r\n\t else if (value && value.baseTexture) {\r\n\t value.once('update', this.textureUpdated, this);");
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (modified)
|
||||
{
|
||||
File.WriteAllText(path, content, new UTF8Encoding(true));
|
||||
}
|
||||
|
||||
return modified;
|
||||
}
|
||||
|
||||
private static bool PatchPixiPictureJs(string path)
|
||||
{
|
||||
string content = File.ReadAllText(path, Encoding.UTF8);
|
||||
if (!content.Contains("if (!sprite.texture.valid) {"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var bakPath = path + BackupSuffix;
|
||||
if (!File.Exists(bakPath))
|
||||
{
|
||||
File.Copy(path, bakPath, true);
|
||||
}
|
||||
|
||||
string updated = content.Replace("if (!sprite.texture.valid) {", "if (!sprite || !sprite.texture.valid) {");
|
||||
File.WriteAllText(path, updated, new UTF8Encoding(true));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool PatchPixiSpineJs(string path)
|
||||
{
|
||||
string content = File.ReadAllText(path, Encoding.UTF8);
|
||||
if (content.Contains(SpineFixMarker))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string updated = content;
|
||||
bool modified = false;
|
||||
|
||||
const string setAnimReplacement =
|
||||
"var animation = this.data.skeletonData.findAnimation(animationName);\n" +
|
||||
" if (!animation) {\n" +
|
||||
" animation = typeof __glResolveSpineAnim === \"function\" ? __glResolveSpineAnim(this, trackIndex, animationName) : null;\n" +
|
||||
" if (!animation) {\n" +
|
||||
" if (typeof console !== \"undefined\" && console.warn) { console.warn(\"[GameLauncher SpineFix] Animation not found, using empty:\", animationName, \"track:\", trackIndex); }\n" +
|
||||
" return typeof this.setEmptyAnimation === \"function\" ? this.setEmptyAnimation(trackIndex, 0) : null;\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" return this.setAnimationWith(trackIndex, animation, loop);";
|
||||
|
||||
var setAnimRegex = new Regex(
|
||||
@"(?:var|let|const)\s+animation\s*=\s*this\.data\.skeletonData\.findAnimation\(animationName\);\s*if\s*\(\s*(?:animation\s*==\s*null|!animation)\s*\)\s*\{?\s*throw\s+new\s+Error\([""']Animation not found:\s*[""']\s*\+\s*animationName\);\s*\}?\s*return\s+this\.setAnimationWith\(trackIndex,\s*animation,\s*loop\);",
|
||||
RegexOptions.Singleline);
|
||||
|
||||
string afterSet = setAnimRegex.Replace(updated, _ => setAnimReplacement);
|
||||
if (!string.Equals(afterSet, updated, StringComparison.Ordinal))
|
||||
{
|
||||
updated = afterSet;
|
||||
modified = true;
|
||||
}
|
||||
|
||||
const string addAnimReplacement =
|
||||
"var animation = this.data.skeletonData.findAnimation(animationName);\n" +
|
||||
" if (!animation) {\n" +
|
||||
" animation = typeof __glResolveSpineAnim === \"function\" ? __glResolveSpineAnim(this, trackIndex, animationName) : null;\n" +
|
||||
" if (!animation) {\n" +
|
||||
" if (typeof console !== \"undefined\" && console.warn) { console.warn(\"[GameLauncher SpineFix] Animation not found, using empty:\", animationName, \"track:\", trackIndex); }\n" +
|
||||
" return typeof this.addEmptyAnimation === \"function\" ? this.addEmptyAnimation(trackIndex, 0, delay) : null;\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" return this.addAnimationWith(trackIndex, animation, loop, delay);";
|
||||
|
||||
var addAnimRegex = new Regex(
|
||||
@"(?:var|let|const)\s+animation\s*=\s*this\.data\.skeletonData\.findAnimation\(animationName\);\s*if\s*\(\s*(?:animation\s*==\s*null|!animation)\s*\)\s*\{?\s*throw\s+new\s+Error\([""']Animation not found:\s*[""']\s*\+\s*animationName\);\s*\}?\s*return\s+this\.addAnimationWith\(trackIndex,\s*animation,\s*loop,\s*delay\);",
|
||||
RegexOptions.Singleline);
|
||||
|
||||
string afterAdd = addAnimRegex.Replace(updated, _ => addAnimReplacement);
|
||||
if (!string.Equals(afterAdd, updated, StringComparison.Ordinal))
|
||||
{
|
||||
updated = afterAdd;
|
||||
modified = true;
|
||||
}
|
||||
|
||||
const string setMixReplacement =
|
||||
"var from = this.skeletonData.findAnimation(fromName);\n" +
|
||||
" if (!from) return;\n" +
|
||||
" var to = this.skeletonData.findAnimation(toName);\n" +
|
||||
" if (!to) return;\n" +
|
||||
" this.setMixWith(from, to, duration);";
|
||||
|
||||
var setMixRegex = new Regex(
|
||||
@"(?:var|let|const)\s+from\s*=\s*this\.skeletonData\.findAnimation\(fromName\);\s*if\s*\(\s*(?:from\s*==\s*null|!from)\s*\)\s*\{?\s*throw\s+new\s+Error\([""']Animation not found:\s*[""']\s*\+\s*fromName\);\s*\}?\s*(?:var|let|const)\s+to\s*=\s*this\.skeletonData\.findAnimation\(toName\);\s*if\s*\(\s*(?:to\s*==\s*null|!to)\s*\)\s*\{?\s*throw\s+new\s+Error\([""']Animation not found:\s*[""']\s*\+\s*toName\);\s*\}?\s*this\.setMixWith\(from,\s*to,\s*duration\);",
|
||||
RegexOptions.Singleline);
|
||||
|
||||
string afterMix = setMixRegex.Replace(updated, _ => setMixReplacement);
|
||||
if (!string.Equals(afterMix, updated, StringComparison.Ordinal))
|
||||
{
|
||||
updated = afterMix;
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!modified)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var bakPath = path + BackupSuffix;
|
||||
if (!File.Exists(bakPath))
|
||||
{
|
||||
File.Copy(path, bakPath, true);
|
||||
}
|
||||
|
||||
const string helperBlock =
|
||||
SpineFixMarker + "\n" +
|
||||
"function __glResolveSpineAnim(state, trackIndex, animationName) {\n" +
|
||||
" try {\n" +
|
||||
" var sd = state && state.data && state.data.skeletonData;\n" +
|
||||
" var anims = sd && sd.animations;\n" +
|
||||
" if (!Array.isArray(anims) || anims.length === 0) return null;\n" +
|
||||
" var req = String(animationName == null ? \"\" : animationName);\n" +
|
||||
" var alt = req.indexOf(\"chimpo\") >= 0 ? req.replace(/chimpo/g, \"chinpo\") : (req.indexOf(\"chinpo\") >= 0 ? req.replace(/chinpo/g, \"chimpo\") : \"\");\n" +
|
||||
" var find = function (fn) {\n" +
|
||||
" for (var i = 0; i < anims.length; i++) {\n" +
|
||||
" if (anims[i] && fn(anims[i])) return anims[i];\n" +
|
||||
" }\n" +
|
||||
" return null;\n" +
|
||||
" };\n" +
|
||||
" var found = find(function (a) { return a.name === req || (alt && a.name === alt); })\n" +
|
||||
" || find(function (a) { return typeof a.name === \"string\" && (a.name.endsWith(\"/\" + req) || (alt && a.name.endsWith(\"/\" + alt))); });\n" +
|
||||
" if (found) return found;\n" +
|
||||
" var isMainTrack = Number(trackIndex) === 0 || /idle/i.test(req);\n" +
|
||||
" if (isMainTrack) {\n" +
|
||||
" found = find(function (a) { return /(?:^|\\/)0_idle$/i.test(a.name); })\n" +
|
||||
" || find(function (a) { return /(?:^|\\/)idle$/i.test(a.name); })\n" +
|
||||
" || find(function (a) { return /idle/i.test(a.name); })\n" +
|
||||
" || find(function (a) { return /^(?:0\\/|0_move\\/|0_)/i.test(a.name); });\n" +
|
||||
" if (found) return found;\n" +
|
||||
" }\n" +
|
||||
" if (Number(trackIndex) === 1 || /^1_face/i.test(req)) {\n" +
|
||||
" found = find(function (a) { return /(?:^|\\/)1_face_normal$/i.test(a.name); })\n" +
|
||||
" || find(function (a) { return /(?:^|\\/)1_face_/i.test(a.name); });\n" +
|
||||
" if (found) return found;\n" +
|
||||
" }\n" +
|
||||
" found = find(function (a) { return a.name === \"none\"; });\n" +
|
||||
" if (found) return found;\n" +
|
||||
" if (Number(trackIndex) === 0) return anims[0];\n" +
|
||||
" } catch (e) {}\n" +
|
||||
" return null;\n" +
|
||||
"}\n";
|
||||
|
||||
string newline = content.Contains("\r\n") ? "\r\n" : "\n";
|
||||
string normalizedHelper = helperBlock.Replace("\n", newline);
|
||||
updated = normalizedHelper + updated;
|
||||
|
||||
File.WriteAllText(path, updated, new UTF8Encoding(true));
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool PatchPictureSpineJs(string path)
|
||||
{
|
||||
string content = File.ReadAllText(path, Encoding.UTF8);
|
||||
if (content.Contains(SpineFixMarker))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string updated = content;
|
||||
bool modified = false;
|
||||
|
||||
// 1. Game_Spine.setAnimation: velo_damage状態で通常立ち絵系アニメが指定された場合のスケルトン自動復旧
|
||||
var setAnimRegex = new Regex(
|
||||
@"setAnimation\s*\(\s*id\s*,\s*animations\s*,\s*\.\.\.args\s*\)\s*\{\s*\[id,\s*animations,\s*args\]\s*=\s*convars\(\s*\[id,\s*animations,\s*args\]\s*\);",
|
||||
RegexOptions.Singleline);
|
||||
|
||||
const string setAnimReplacement =
|
||||
"setAnimation(id, animations, ...args) {\n" +
|
||||
" " + SpineFixMarker + "\n" +
|
||||
" [id, animations, args] = convars([id, animations, args]);\n" +
|
||||
" if (Number(id) === 0 && typeof this._skeleton === 'string' && /^velo_damage_\\d+$/.test(this._skeleton)) {\n" +
|
||||
" let _firstAnim = Array.isArray(animations) ? animations[0] : animations;\n" +
|
||||
" let _animBase = typeof _firstAnim === 'string' ? _firstAnim.split(/\\s*\\/\\s*/)[0].trim() : '';\n" +
|
||||
" if (/^0_(?:idle|low|yoin|shy|talk|bind)/i.test(_animBase)) {\n" +
|
||||
" let _targetSkel = (typeof $gameParty !== 'undefined' && $gameParty && $gameParty.members && $gameParty.members()[0] && $gameParty.members()[0].hp === 0) ? 'velo_hunou' : 'velo_normal';\n" +
|
||||
" if (typeof Game_Spine !== 'undefined' && Game_Spine.fullName && Game_Spine.fullName(_targetSkel)) {\n" +
|
||||
" this._skeleton = _targetSkel + '_' + Date.now();\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" }";
|
||||
|
||||
string afterSetAnim = setAnimRegex.Replace(updated, _ => setAnimReplacement);
|
||||
if (!string.Equals(afterSetAnim, updated, StringComparison.Ordinal))
|
||||
{
|
||||
updated = afterSetAnim;
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// 1.5. Sprite_Spine.updateSkeleton: スケルトン切り替え破棄前に未発火のswitchイベントを完了させ、イベントループ停止を防止
|
||||
var updateSkelRegex = new Regex(
|
||||
@"updateSkeleton\s*\(\s*spine\s*\)\s*\{\s*if\s*\(\s*spine\s*\)\s*\{\s*if\s*\(\s*spine\.skeleton\s*!=\s*this\._skeleton\s*\)\s*\{\s*this\.init\(\s*\);",
|
||||
RegexOptions.Singleline);
|
||||
|
||||
const string updateSkelReplacement =
|
||||
"updateSkeleton(spine) {\n" +
|
||||
" if (spine) {\n" +
|
||||
" if (spine.skeleton != this._skeleton) {\n" +
|
||||
" try {\n" +
|
||||
" if (this._data && this._data.state && Array.isArray(this._data.state.tracks) && typeof $gameSwitches !== 'undefined') {\n" +
|
||||
" for (let _glEntry of this._data.state.tracks) {\n" +
|
||||
" if (!_glEntry || !_glEntry.animation || !Array.isArray(_glEntry.animation.timelines)) continue;\n" +
|
||||
" for (let _glTl of _glEntry.animation.timelines) {\n" +
|
||||
" if (!_glTl || !Array.isArray(_glTl.events) || !_glTl.frames || typeof _glTl.frames.length !== 'number') continue;\n" +
|
||||
" for (let _glIdx = 0; _glIdx < _glTl.events.length; _glIdx++) {\n" +
|
||||
" if (_glTl.frames[_glIdx] < _glEntry.trackTime) continue;\n" +
|
||||
" let _glEv = _glTl.events[_glIdx];\n" +
|
||||
" let _glStr = _glEv && _glEv.stringValue;\n" +
|
||||
" if (!_glStr) continue;\n" +
|
||||
" for (let _glTok of String(_glStr).replace(/ +/, '').split(/,/)) {\n" +
|
||||
" if (_glTok.match(/^([!~]?)switch:(\\d+)$/i)) {\n" +
|
||||
" let _glType = RegExp.$1.replace('!', 'off').replace('~', 'reverse') || 'on';\n" +
|
||||
" let _glSwId = Number(RegExp.$2);\n" +
|
||||
" let _glVal = _glType == 'on' ? true : _glType == 'off' ? false : !$gameSwitches.value(_glSwId);\n" +
|
||||
" $gameSwitches.setValue(_glSwId, _glVal);\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" } catch (_glErr) {}\n" +
|
||||
" this.init();";
|
||||
|
||||
string afterUpdateSkel = updateSkelRegex.Replace(updated, _ => updateSkelReplacement);
|
||||
if (!string.Equals(afterUpdateSkel, updated, StringComparison.Ordinal))
|
||||
{
|
||||
updated = afterUpdateSkel;
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// 2. updateSkin: findSkin null安全化
|
||||
var skinRegex = new Regex(
|
||||
@"skin\.addSkin\(\s*this\._data\.skeleton\.data\.findSkin\(\s*name\s*\)\s*\);",
|
||||
RegexOptions.Singleline);
|
||||
|
||||
const string skinReplacement =
|
||||
"let _glSkin = this._data.skeleton.data.findSkin(name);\n" +
|
||||
" if (_glSkin) skin.addSkin(_glSkin);";
|
||||
|
||||
string afterSkin = skinRegex.Replace(updated, _ => skinReplacement);
|
||||
if (!string.Equals(afterSkin, updated, StringComparison.Ordinal))
|
||||
{
|
||||
updated = afterSkin;
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// 3. updateAnimation: entry null安全化
|
||||
var entryRegex = new Regex(
|
||||
@"entry\.timeScale\s*=\s*animation\.timeScale;\s*entry\.alpha\s*=\s*animation\.alpha;\s*entry\.plainAlpha\s*=\s*animation\.alpha;\s*spine\.setPlayData\(\s*entry\s*\);",
|
||||
RegexOptions.Singleline);
|
||||
|
||||
const string entryReplacement =
|
||||
"if (entry) {\n" +
|
||||
" entry.timeScale = animation.timeScale;\n" +
|
||||
" entry.alpha = animation.alpha;\n" +
|
||||
" entry.plainAlpha = animation.alpha;\n" +
|
||||
" spine.setPlayData(entry);\n" +
|
||||
" }";
|
||||
|
||||
string afterEntry = entryRegex.Replace(updated, _ => entryReplacement);
|
||||
if (!string.Equals(afterEntry, updated, StringComparison.Ordinal))
|
||||
{
|
||||
updated = afterEntry;
|
||||
modified = true;
|
||||
}
|
||||
|
||||
// 4. restoreAnimation: animations.find(...).duration および entry の null安全化
|
||||
var restoreRegex = new Regex(
|
||||
@"data\.trackTime\s*%=\s*this\._data\.spineData\.animations\.find\(\s*animation\s*=>\s*animation\.name\s*==\s*data\.name\s*\)\.duration;",
|
||||
RegexOptions.Singleline);
|
||||
|
||||
const string restoreReplacement =
|
||||
"let _glAnim = this._data.spineData.animations.find(animation => animation.name == data.name);\n" +
|
||||
" data.trackTime = (_glAnim && _glAnim.duration) ? (data.trackTime % _glAnim.duration) : 0;";
|
||||
|
||||
string afterRestore = restoreRegex.Replace(updated, _ => restoreReplacement);
|
||||
if (!string.Equals(afterRestore, updated, StringComparison.Ordinal))
|
||||
{
|
||||
updated = afterRestore;
|
||||
modified = true;
|
||||
}
|
||||
|
||||
var restoreEntryRegex = new Regex(
|
||||
@"(entry\s*=\s*this\._data\.state\.(?:setAnimation|addAnimation)\([^;]+\);)\s*(entry\.alpha\s*=)",
|
||||
RegexOptions.Singleline);
|
||||
|
||||
string afterRestoreEntry = restoreEntryRegex.Replace(updated, "$1\n if (!entry) break;\n $2");
|
||||
if (!string.Equals(afterRestoreEntry, updated, StringComparison.Ordinal))
|
||||
{
|
||||
updated = afterRestoreEntry;
|
||||
modified = true;
|
||||
}
|
||||
|
||||
if (!modified)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var bakPath = path + BackupSuffix;
|
||||
if (!File.Exists(bakPath))
|
||||
{
|
||||
File.Copy(path, bakPath, true);
|
||||
}
|
||||
|
||||
File.WriteAllText(path, updated, new UTF8Encoding(true));
|
||||
return true;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
SrpgStudio,
|
||||
Evb,
|
||||
Nwjs,
|
||||
Bakin,
|
||||
Other
|
||||
}
|
||||
|
||||
@@ -28,6 +29,7 @@
|
||||
Wolf,
|
||||
SrpgStudio,
|
||||
Nwjs,
|
||||
Bakin,
|
||||
Other,
|
||||
Unknown
|
||||
}
|
||||
|
||||
@@ -480,8 +480,9 @@ namespace GameLauncher.Engines.Unity
|
||||
if (isStrict)
|
||||
{
|
||||
// セーブファイル候補のフィルタ
|
||||
// .sd / .es3 は Easy Save 3 の標準拡張子(0.sd, s.sd, h.sd などファイル名に "save" を含まない)
|
||||
bool isCandidate = fileName.Contains("save", StringComparison.OrdinalIgnoreCase) ||
|
||||
ext is ".sav" or ".save" or ".savegame" or ".dat";
|
||||
ext is ".sav" or ".save" or ".savegame" or ".dat" or ".sd" or ".es3";
|
||||
|
||||
if (!isCandidate) continue;
|
||||
}
|
||||
|
||||
@@ -131,6 +131,25 @@ namespace GameLauncher.Helpers
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// bool 値・bool? 値が true の場合に Visible、false または null の場合に Collapsed を返すコンバーター。
|
||||
/// セーブエディタのセルテンプレートで、型ごとに表示するエディタを切り替える用途に使用します。
|
||||
/// </summary>
|
||||
public class BoolToVisibilityConverter : IValueConverter
|
||||
{
|
||||
public static readonly BoolToVisibilityConverter Instance = new();
|
||||
|
||||
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
return value is true ? Visibility.Visible : Visibility.Collapsed;
|
||||
}
|
||||
|
||||
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
|
||||
{
|
||||
return value is Visibility v && v == Visibility.Visible;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// bool値が true の場合に Visible、false または null の場合に Collapsed を返すコンバーター
|
||||
/// </summary>
|
||||
|
||||
+82
-1
@@ -380,6 +380,7 @@
|
||||
<RadioButton x:Name="tabSrpg" Style="{StaticResource NavTabRadioButton}" Content="SRPG" ToolTip="SRPG Studio" GroupName="MainEngineTabs" Checked="EngineTab_Checked" Padding="9,5"/>
|
||||
<RadioButton x:Name="tabUnity" Style="{StaticResource NavTabRadioButton}" Content="Unity" ToolTip="Unity" GroupName="MainEngineTabs" Checked="EngineTab_Checked" Padding="9,5"/>
|
||||
<RadioButton x:Name="tabNwjs" Style="{StaticResource NavTabRadioButton}" Content="NW.js" ToolTip="NW.js" GroupName="MainEngineTabs" Checked="EngineTab_Checked" Padding="9,5"/>
|
||||
<RadioButton x:Name="tabBakin" Style="{StaticResource NavTabRadioButton}" Content="Bakin" ToolTip="RPG Developer Bakin" GroupName="MainEngineTabs" Checked="EngineTab_Checked" Padding="9,5"/>
|
||||
<RadioButton x:Name="tabOther" Style="{StaticResource NavTabRadioButton}" Content="その他" ToolTip="その他(エンジン不問)" GroupName="MainEngineTabs" Checked="EngineTab_Checked" Padding="9,5"/>
|
||||
</WrapPanel>
|
||||
</Border>
|
||||
@@ -1007,6 +1008,36 @@
|
||||
<TextBlock Text="チェックONで改造プラグインを適用して起動します。チェックOFFで改造前の状態に完全復元して起動します。"
|
||||
FontSize="11" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="24,4,0,10"/>
|
||||
|
||||
<!-- ツクールMZ専用: 今回の対応(マップ移動エラー修復&DevTools有効化) -->
|
||||
<Border Margin="0,0,0,10" Background="#1D2436" BorderBrush="#00CEC9" BorderThickness="1.2" CornerRadius="6" Padding="10,8">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding SelectedItem.IsMZ, ElementName=lstGames}" Value="True">
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<StackPanel>
|
||||
<CheckBox x:Name="chkMzPixiErrorFix"
|
||||
IsChecked="{Binding SelectedItem.MzPixiErrorFix, ElementName=lstGames, Mode=TwoWay}"
|
||||
FontSize="13" FontWeight="Bold" Foreground="#81ECEC">
|
||||
<TextBlock Text="🛠 マップ移動エラー修復 & DevTools有効化 (Pixi.js / NW.js)" Margin="4,0,0,0"/>
|
||||
</CheckBox>
|
||||
<TextBlock Text="Pixi.js のテクスチャ参照バグ(Cannot read property 'valid' of null)を修復し、F8/F12での開発者ツール表示を有効化します。"
|
||||
FontSize="10.5" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="22,3,0,0"/>
|
||||
<CheckBox x:Name="chkMzSpineErrorFix"
|
||||
IsChecked="{Binding SelectedItem.MzSpineErrorFix, ElementName=lstGames, Mode=TwoWay}"
|
||||
FontSize="13" FontWeight="Bold" Foreground="#81ECEC" Margin="0,8,0,0">
|
||||
<TextBlock Text="🛠 Spineアニメ未定義エラー修復 (Animation not found: 0_idle 等)" Margin="4,0,0,0"/>
|
||||
</CheckBox>
|
||||
<TextBlock Text="pixi-spine.js / PictureSpine.js の未定義アニメーション参照クラッシュ(Animation not found: 0_idle 等)を安全にフォールバック修復します。"
|
||||
FontSize="10.5" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="22,3,0,0"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- 個別プラグインアコーディオン -->
|
||||
<Expander Header="プラグイン個別設定(詳細)" IsExpanded="False" Foreground="{StaticResource TextSecondary}" FontSize="12">
|
||||
<StackPanel Margin="4,8,0,0">
|
||||
@@ -1097,6 +1128,57 @@
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- ================= NW.js 専用セーブデータ編集&ガイドセクション ================= -->
|
||||
<Border Background="#1E1E2E" BorderBrush="#00CEC9" BorderThickness="1.5" CornerRadius="8" Padding="14" Margin="0,0,0,14">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding SelectedItem.IsNwjs, ElementName=lstGames}" Value="True">
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<StackPanel>
|
||||
<Button x:Name="btnOpenNwjsSaveEditor" Style="{StaticResource EditorBigButton}" Height="42" Margin="0,0,0,10" Click="btnOpenNwjsSaveEditor_Click">
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
|
||||
<TextBlock Text="🛠" FontSize="16" Margin="0,0,8,0" VerticalAlignment="Center"/>
|
||||
<TextBlock Text="NW.js セーブデータを編集する (.gcdata / .json)" FontSize="13" FontWeight="Bold" VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<TextBlock Text="GameCreator暗号化セーブ (.gcdata) およびHTML5 JSONセーブの所持金・ステータス・変数・アイテム・ギャラリー解放フラグを直接編集できます。"
|
||||
FontSize="10" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="2,0,0,6"/>
|
||||
<StackPanel Orientation="Horizontal" Margin="2,0,0,0">
|
||||
<TextBlock Text="・[F10] / 右上ボタン: ゲーム内チートメニュー" FontSize="10" Foreground="#81ECEC" Margin="0,0,12,0"/>
|
||||
<TextBlock Text="・[F6]: 倍速切替 / [Ctrl]: 5倍速" FontSize="10" Foreground="#FFEAA7"/>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<!-- ================= RPG Developer Bakin 専用セーブデータ編集セクション ================= -->
|
||||
<Border Background="#1E1E2E" BorderBrush="#FDCB6E" BorderThickness="1.5" CornerRadius="8" Padding="14" Margin="0,0,0,14">
|
||||
<Border.Style>
|
||||
<Style TargetType="Border">
|
||||
<Setter Property="Visibility" Value="Collapsed"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding SelectedItem.IsBakin, ElementName=lstGames}" Value="True">
|
||||
<Setter Property="Visibility" Value="Visible"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</Border.Style>
|
||||
<StackPanel>
|
||||
<Button x:Name="btnOpenBakinSaveEditor" Style="{StaticResource EditorBigButton}" Height="42" Margin="0,0,0,10" Click="btnOpenBakinSaveEditor_Click">
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
|
||||
<TextBlock Text="🛠" FontSize="16" Margin="0,0,8,0" VerticalAlignment="Center"/>
|
||||
<TextBlock Text="Bakin セーブデータを編集する (Save_XX.sgs)" FontSize="13" FontWeight="Bold" VerticalAlignment="Center"/>
|
||||
</StackPanel>
|
||||
</Button>
|
||||
<TextBlock Text="RPG Developer Bakin (YUKRDATA .sgs) 形式セーブの所持金・行動力・パーティ全員のステータス・所持アイテム数・全変数・回想/動画解放フラグ(Save_xx.sgs)を直接編集・バックアップ復元できます。"
|
||||
FontSize="10" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="2,0,0,0"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
<!-- ================= WOLF RPGエディター専用セクション ================= -->
|
||||
<Border Background="#1E1E2E" BorderBrush="{StaticResource AccentWolf}" BorderThickness="1.5" CornerRadius="8" Padding="14" Margin="0,0,0,14">
|
||||
<Border.Style>
|
||||
@@ -1410,4 +1492,3 @@
|
||||
</Border>
|
||||
</Grid>
|
||||
</Window>
|
||||
|
||||
+217
-8
@@ -24,6 +24,7 @@ using GameLauncher.Engines.Tyrano;
|
||||
using GameLauncher.Engines.Wolf;
|
||||
using GameLauncher.Engines.Unity;
|
||||
using GameLauncher.Engines.Nwjs;
|
||||
using GameLauncher.Engines.Bakin;
|
||||
using GameLauncher.Engines.Common;
|
||||
using GameLauncher.Engines.Evb;
|
||||
|
||||
@@ -150,6 +151,7 @@ namespace GameLauncher
|
||||
case 8: this.tabSrpg.IsChecked = true; break;
|
||||
case 9: this.tabNwjs.IsChecked = true; break;
|
||||
case 10: this.tabOther.IsChecked = true; break;
|
||||
case 11: this.tabBakin.IsChecked = true; break;
|
||||
default: this.tabAll.IsChecked = true; break;
|
||||
}
|
||||
|
||||
@@ -185,6 +187,7 @@ namespace GameLauncher
|
||||
else if (this.tabWolf.IsChecked == true) tabIndex = 7;
|
||||
else if (this.tabSrpg.IsChecked == true) tabIndex = 8;
|
||||
else if (this.tabNwjs.IsChecked == true) tabIndex = 9;
|
||||
else if (this.tabBakin.IsChecked == true) tabIndex = 11;
|
||||
else if (this.tabOther.IsChecked == true) tabIndex = 10;
|
||||
|
||||
this._config.SelectedTab = tabIndex;
|
||||
@@ -245,6 +248,15 @@ namespace GameLauncher
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var nwjsPlugin in TkoolGameItem.DefaultNwjsPlugins)
|
||||
{
|
||||
if (!this._config.DefaultPluginSettings.ContainsKey(nwjsPlugin.Id))
|
||||
{
|
||||
this._config.DefaultPluginSettings[nwjsPlugin.Id] = nwjsPlugin.DefaultEnabled;
|
||||
modified = true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var rgssPlugin in TkoolGameItem.DefaultRgssPlugins)
|
||||
{
|
||||
if (!this._config.DefaultPluginSettings.ContainsKey(rgssPlugin.Id))
|
||||
@@ -331,6 +343,7 @@ namespace GameLauncher
|
||||
int wolfCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsWolf);
|
||||
int srpgCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsSrpgStudio);
|
||||
int nwjsCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsNwjs);
|
||||
int bakinCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsBakin);
|
||||
int unityCount = this._games.Count(g => g is UnityGameItem);
|
||||
|
||||
this.AppendLog($"キャッシュから計 {this._games.Count} 件(ツクールMV/MZ: {tkoolCount}, ツクールVX系: {rgssCount}, ティラノ: {tyranoCount}, ウディタ: {wolfCount}, SRPG Studio: {srpgCount}, NW.js: {nwjsCount}, Unity: {unityCount})を即時表示しました。(待たずに即起動可能です)");
|
||||
@@ -577,6 +590,10 @@ namespace GameLauncher
|
||||
{
|
||||
if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.Nwjs) return false;
|
||||
}
|
||||
else if (this.tabBakin.IsChecked == true)
|
||||
{
|
||||
if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.Bakin) return false;
|
||||
}
|
||||
else if (this.tabOther.IsChecked == true)
|
||||
{
|
||||
if (!game.IsOther) return false;
|
||||
@@ -588,7 +605,7 @@ namespace GameLauncher
|
||||
if (this.chkFilterAsarOnly.IsChecked == true && (game is not TkoolGameItem tgAsar || !tgAsar.IsAsar)) return false;
|
||||
if (this.chkFilterRgssOnly.IsChecked == true && (game is not TkoolGameItem tgRgss || !tgRgss.HasRgssArchive)) return false;
|
||||
if (this.chkFilterSrpgOnly.IsChecked == true && (game is not TkoolGameItem tgSrpg || !tgSrpg.HasSrpgArchive)) return false;
|
||||
if (this.chkFilterSaveOnly.IsChecked == true && (game is not UnityGameItem ugSave || !ugSave.HasSaveData)) return false;
|
||||
if (this.chkFilterSaveOnly.IsChecked == true && !game.HasSaveData) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -643,18 +660,19 @@ namespace GameLauncher
|
||||
|
||||
int total = this._games.Count;
|
||||
int visible = this._gamesView?.Count ?? 0;
|
||||
int tkoolCount = this._games.Count(g => g is TkoolGameItem tg && tg.EngineType != TkoolEngineType.Tyrano && !tg.IsRgss && !tg.IsWolf && !tg.IsSrpgStudio && !tg.IsNwjs && !tg.IsOther);
|
||||
int tkoolCount = this._games.Count(g => g is TkoolGameItem tg && tg.EngineType != TkoolEngineType.Tyrano && !tg.IsRgss && !tg.IsWolf && !tg.IsSrpgStudio && !tg.IsNwjs && !tg.IsBakin && !tg.IsOther);
|
||||
int rgssCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsRgss);
|
||||
int tyranoCount = this._games.Count(g => g is TkoolGameItem tg && tg.EngineType == TkoolEngineType.Tyrano);
|
||||
int wolfCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsWolf);
|
||||
int srpgCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsSrpgStudio);
|
||||
int nwjsCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsNwjs);
|
||||
int bakinCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsBakin);
|
||||
int unityCount = this._games.Count(g => g is UnityGameItem);
|
||||
int otherCount = this._games.Count(g => g.IsOther);
|
||||
int bookmarkCount = this._games.Count(g => g.IsBookmarked);
|
||||
|
||||
this.lblStatusSummary.Text = $"総ゲーム数: {total} 件 | 表示: {visible} 件 | ★ ブックマーク: {bookmarkCount} 件";
|
||||
this.lblStatusBreakdown.Text = $"(ツクールMV/MZ: {tkoolCount}, ツクールVX系: {rgssCount}, ティラノ: {tyranoCount}, ウディタ: {wolfCount}, SRPG Studio: {srpgCount}, NW.js: {nwjsCount}, Unity: {unityCount}, その他: {otherCount})";
|
||||
this.lblStatusBreakdown.Text = $"(ツクールMV/MZ: {tkoolCount}, ツクールVX系: {rgssCount}, ティラノ: {tyranoCount}, ウディタ: {wolfCount}, SRPG Studio: {srpgCount}, NW.js: {nwjsCount}, Bakin: {bakinCount}, Unity: {unityCount}, その他: {otherCount})";
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -732,14 +750,19 @@ namespace GameLauncher
|
||||
? tkoolItem.ResolveLaunchExecutable()
|
||||
: game.ExecutablePath;
|
||||
|
||||
// 直下にexeが無い場合やパスが変わっていた場合はサブフォルダ内を再探索して救済
|
||||
if (string.IsNullOrEmpty(effectiveExe) || !File.Exists(effectiveExe))
|
||||
// 直下にexeが無い場合やパスが変わっていた場合、または補助exe(notification_helper.exe等)だった場合は再探索して救済
|
||||
if (string.IsNullOrEmpty(effectiveExe) || !File.Exists(effectiveExe) || GameScannerService.IsExcludedExe(effectiveExe))
|
||||
{
|
||||
var foundExe = GameScannerService.FindGameExecutable(game.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(foundExe) && File.Exists(foundExe))
|
||||
{
|
||||
effectiveExe = foundExe;
|
||||
game.ExecutablePath = foundExe;
|
||||
var refreshedIcon = GameScannerService.LoadIcon(foundExe, game.RootDirectory);
|
||||
if (refreshedIcon != null)
|
||||
{
|
||||
game.IconImage = refreshedIcon;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -861,6 +884,12 @@ namespace GameLauncher
|
||||
}
|
||||
}
|
||||
// スクリプト改造の適用または復元(ティラノ)
|
||||
// スクリプト改造の適用または復元(NW.js)
|
||||
else if (tg.IsNwjs)
|
||||
{
|
||||
this.ApplyOrRestoreNwjsMod(tg);
|
||||
}
|
||||
// スクリプト改造の適用または復元(ティラノ)
|
||||
else if (tg.EngineType == TkoolEngineType.Tyrano)
|
||||
{
|
||||
if (tg.ApplyMod)
|
||||
@@ -875,6 +904,10 @@ namespace GameLauncher
|
||||
}
|
||||
}
|
||||
// その他のゲーム(ツクール以外のゲーム)
|
||||
else if (tg.IsBakin)
|
||||
{
|
||||
this.AppendLog($"[Bakin起動] {tg.Title} を起動します...");
|
||||
}
|
||||
else if (tg.IsOther)
|
||||
{
|
||||
this.AppendLog($"[その他起動] {tg.Title} を起動します...");
|
||||
@@ -884,6 +917,44 @@ namespace GameLauncher
|
||||
{
|
||||
var (success, msg) = this._modService.ApplyOrRestoreMod(tg, this._config.DefaultPluginSettings);
|
||||
this.AppendLog($"[ツクール改造処理] {tg.Title}: {msg}");
|
||||
|
||||
// ツクールMZかつMzPixiErrorFixが有効な場合、マップ移動エラー修復&DevTools有効化を適用
|
||||
if (tg.IsMZ)
|
||||
{
|
||||
if (tg.MzPixiErrorFix)
|
||||
{
|
||||
var (fixSuccess, fixMsg) = TkoolMzFixService.ApplyMzPixiFix(tg.RootDirectory);
|
||||
if (fixSuccess)
|
||||
{
|
||||
this.AppendLog($"[MZエラー修復] {tg.Title}: {fixMsg}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var (restoreSuccess, restoreMsg) = TkoolMzFixService.RestoreMzPixiFix(tg.RootDirectory);
|
||||
if (restoreSuccess)
|
||||
{
|
||||
this.AppendLog($"[MZエラー修復解除] {tg.Title}: {restoreMsg}");
|
||||
}
|
||||
}
|
||||
|
||||
if (tg.MzSpineErrorFix)
|
||||
{
|
||||
var (spineFixSuccess, spineFixMsg) = TkoolMzFixService.ApplyMzSpineFix(tg.RootDirectory);
|
||||
if (spineFixSuccess && !string.IsNullOrEmpty(spineFixMsg))
|
||||
{
|
||||
this.AppendLog($"[MZ Spine修復] {tg.Title}: {spineFixMsg}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var (spineRestoreSuccess, spineRestoreMsg) = TkoolMzFixService.RestoreMzSpineFix(tg.RootDirectory);
|
||||
if (spineRestoreSuccess && !string.IsNullOrEmpty(spineRestoreMsg))
|
||||
{
|
||||
this.AppendLog($"[MZ Spine修復解除] {tg.Title}: {spineRestoreMsg}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.StartGameProcess(tg);
|
||||
@@ -914,14 +985,19 @@ namespace GameLauncher
|
||||
? evbItem.ResolveLaunchExecutable()
|
||||
: game.ExecutablePath;
|
||||
|
||||
// 直下にexeが無い場合やパスが変わっていた場合はサブフォルダ内を探索して救済
|
||||
if (string.IsNullOrEmpty(launchExe) || !File.Exists(launchExe))
|
||||
// 直下にexeが無い場合やパスが変わっていた場合、または補助exe(notification_helper.exe等)だった場合はサブフォルダ内を探索して救済
|
||||
if (string.IsNullOrEmpty(launchExe) || !File.Exists(launchExe) || GameScannerService.IsExcludedExe(launchExe))
|
||||
{
|
||||
var foundExe = GameScannerService.FindGameExecutable(game.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(foundExe) && File.Exists(foundExe))
|
||||
{
|
||||
launchExe = foundExe;
|
||||
game.ExecutablePath = foundExe;
|
||||
var refreshedIcon = GameScannerService.LoadIcon(foundExe, game.RootDirectory);
|
||||
if (refreshedIcon != null)
|
||||
{
|
||||
game.IconImage = refreshedIcon;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -942,7 +1018,7 @@ namespace GameLauncher
|
||||
// ツクール/ティラノ等のWebランタイム(NW.js / Chromium)ゲームの場合、
|
||||
// GameLauncher.exe のあるフォルダ配下の Profiles フォルダに隔離した専用プロファイルディレクトリを指定して起動
|
||||
// ※RGSS(DirectX/Ruby)やウディタ、Unity等のネイティブアプリには引数を付与しない
|
||||
if (game is TkoolGameItem tg && !tg.IsRgss && !tg.IsWolf)
|
||||
if (game is TkoolGameItem tg && !tg.IsRgss && !tg.IsWolf && !tg.IsBakin && !tg.IsSrpgStudio && !tg.IsOther)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -1425,7 +1501,134 @@ namespace GameLauncher
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyOrRestoreNwjsMod(TkoolGameItem tg)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(tg.PluginsJsPath) || !File.Exists(tg.PluginsJsPath))
|
||||
{
|
||||
tg.PluginsJsPath = NwjsDetector.ResolveEntryHtmlPath(tg.RootDirectory);
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(tg.PluginsJsPath) || !File.Exists(tg.PluginsJsPath))
|
||||
{
|
||||
this.AppendLog($"[NW.js改造スキップ] {tg.Title}: エントリHTMLが見つからないため通常起動します。");
|
||||
return;
|
||||
}
|
||||
|
||||
if (tg.ApplyMod)
|
||||
{
|
||||
var pluginOpts = TkoolGameItem.DefaultNwjsPlugins
|
||||
.Select(def => new ModPluginOptionItem
|
||||
{
|
||||
Definition = def,
|
||||
IsEnabled = tg.IsPluginEnabled(def.Id, this._config.DefaultPluginSettings, def.DefaultEnabled)
|
||||
})
|
||||
.ToList();
|
||||
|
||||
NwjsModService.ApplyMod(tg, tg.PluginsJsPath, pluginOpts);
|
||||
tg.IsModded = NwjsModService.CheckIsModded(tg.PluginsJsPath);
|
||||
this.AppendLog($"[NW.js改造適用] {tg.Title}: 改造スクリプトを適用しました ([F10]チートメニュー / [F6]倍速 / [F12]DevTools)。");
|
||||
}
|
||||
else
|
||||
{
|
||||
NwjsModService.RestoreOriginal(tg, tg.PluginsJsPath);
|
||||
tg.IsModded = false;
|
||||
this.AppendLog($"[NW.js復元] {tg.Title}: オリジナルの状態へ復元しました。");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
this.AppendLog($"[NW.js改造エラー] {tg.Title}: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void btnOpenBakinSaveEditor_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this.lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsBakin)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
this.AppendLog($"[Bakinセーブエディタ起動] {tg.Title} のセーブエディタを開きます...");
|
||||
var dlg = new BakinSaveEditorDialog(tg)
|
||||
{
|
||||
Owner = this
|
||||
};
|
||||
dlg.ShowDialog();
|
||||
|
||||
tg.HasSaveData = BakinSaveService.HasAnySaveData(tg.RootDirectory);
|
||||
this._scannerService.SaveCache(this._games);
|
||||
this._scannerService.SaveBookmarks(this._games);
|
||||
this.AppendLog($"[Bakinセーブエディタ終了] {tg.Title} のセーブエディタを閉じました。");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(this, $"Bakin セーブエディタの起動中にエラーが発生しました:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
this.AppendLog($"[Bakinセーブエディタエラー] {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void btnOpenNwjsSaveEditor_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this.lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsNwjs)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
this.AppendLog($"[NW.jsセーブエディタ起動] {tg.Title} のセーブエディタを開きます...");
|
||||
var dlg = new NwjsSaveEditorDialog(tg)
|
||||
{
|
||||
Owner = this
|
||||
};
|
||||
dlg.ShowDialog();
|
||||
|
||||
tg.HasSaveData = NwjsSaveService.HasAnySaveData(tg.RootDirectory, tg.FolderName);
|
||||
this._scannerService.SaveCache(this._games);
|
||||
this._scannerService.SaveBookmarks(this._games);
|
||||
this.AppendLog($"[NW.jsセーブエディタ終了] {tg.Title} のセーブエディタを閉じました。");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(this, $"NW.js セーブエディタの起動中にエラーが発生しました:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
this.AppendLog($"[NW.jsセーブエディタエラー] {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private void RestoreOriginalMod(TkoolGameItem tg)
|
||||
{
|
||||
if (tg.IsNwjs)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(tg.PluginsJsPath))
|
||||
{
|
||||
tg.PluginsJsPath = NwjsDetector.ResolveEntryHtmlPath(tg.RootDirectory);
|
||||
}
|
||||
|
||||
NwjsModService.RestoreOriginal(tg, tg.PluginsJsPath);
|
||||
tg.IsModded = false;
|
||||
this._scannerService.SaveCache(this._games);
|
||||
this._scannerService.SaveBookmarks(this._games);
|
||||
string msg = "NW.js 改造スクリプトを解除し、元の index.html へ復元しました。";
|
||||
this.AppendLog($"[改造解除] {tg.Title}: {msg}");
|
||||
MessageBox.Show(msg, "改造解除・復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"復元中にエラーが発生しました:\n{ex.Message}", "復元エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.RestoreNonNwjsOriginalMod(tg);
|
||||
}
|
||||
|
||||
private void RestoreNonNwjsOriginalMod(TkoolGameItem tg)
|
||||
{
|
||||
var (Success, Message) = tg.IsRgss
|
||||
? this._rgssModService.RestoreOriginal(tg)
|
||||
@@ -1433,6 +1636,12 @@ namespace GameLauncher
|
||||
? this._tyranoModService.RestoreOriginal(tg)
|
||||
: this._modService.RestoreOriginal(tg));
|
||||
|
||||
if (tg.IsMZ)
|
||||
{
|
||||
TkoolMzFixService.RestoreMzPixiFix(tg.RootDirectory);
|
||||
TkoolMzFixService.RestoreMzSpineFix(tg.RootDirectory);
|
||||
}
|
||||
|
||||
tg.IsModded = false;
|
||||
this.AppendLog($"[改造解除] {tg.Title}: {Message}");
|
||||
|
||||
|
||||
+18
-1
@@ -221,6 +221,9 @@ namespace GameLauncher.Models
|
||||
/// <summary>NW.js汎用ゲームか</summary>
|
||||
public virtual bool IsNwjs => false;
|
||||
|
||||
/// <summary>RPG Developer Bakinか</summary>
|
||||
public virtual bool IsBakin => false;
|
||||
|
||||
/// <summary>その他のゲームエンジンか</summary>
|
||||
public virtual bool IsOther => false;
|
||||
|
||||
@@ -351,7 +354,7 @@ namespace GameLauncher.Models
|
||||
/// <summary>Unity LocalLowパス</summary>
|
||||
public virtual string LocalLowPath => string.Empty;
|
||||
|
||||
/// <summary>Unity セーブデータ検出フラグ</summary>
|
||||
/// <summary>セーブデータ検出フラグ</summary>
|
||||
public virtual bool HasSaveData
|
||||
{
|
||||
get => false;
|
||||
@@ -449,6 +452,20 @@ namespace GameLauncher.Models
|
||||
get => false;
|
||||
set { }
|
||||
}
|
||||
|
||||
/// <summary>ツクールMZ専用: Pixi.jsエラー修復およびDevTools有効化フラグ(初期状態: true)</summary>
|
||||
public virtual bool MzPixiErrorFix
|
||||
{
|
||||
get => true;
|
||||
set { }
|
||||
}
|
||||
|
||||
/// <summary>ツクールMZ専用: Spineアニメーション未定義エラー(Animation not found: 0_idle 等)修復フラグ(初期状態: true)</summary>
|
||||
public virtual bool MzSpineErrorFix
|
||||
{
|
||||
get => true;
|
||||
set { }
|
||||
}
|
||||
/// <summary>
|
||||
/// スクリプト改造(プラグイン注入など)が適用可能な状態かどうか。
|
||||
/// 該当ゲームが改造非対応(ウディタ・SRPG・NW.js・その他・未解凍状態など)の場合は false を返し、
|
||||
|
||||
@@ -58,6 +58,7 @@ namespace GameLauncher.Models
|
||||
"ShopMaxBuy" => false,
|
||||
"AlwaysMaxHp" => false,
|
||||
"AlwaysMaxMp" => false,
|
||||
"SpineDebugTrace" => false,
|
||||
_ => true
|
||||
};
|
||||
|
||||
@@ -93,6 +94,7 @@ namespace GameLauncher.Models
|
||||
"MessageInstant" => "メッセージ瞬間表示 (ウェイトスキップ)",
|
||||
"AlwaysMaxHp" => "HP常時MAX (プリンセスシナジー専用)",
|
||||
"AlwaysMaxMp" => "MP常時MAX (プリンセスシナジー専用)",
|
||||
"SpineDebugTrace" => "Spine診断ログ出力 (save/spine_debug_trace.log)",
|
||||
_ => !string.IsNullOrEmpty(desc) ? $"{id} ({desc})" : id
|
||||
};
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ namespace GameLauncher.Models
|
||||
private string _editValue = string.Empty;
|
||||
private bool _isModified;
|
||||
private string _description = string.Empty;
|
||||
private ValueKind _kind = ValueKind.Unknown;
|
||||
|
||||
public event PropertyChangedEventHandler? PropertyChanged;
|
||||
|
||||
@@ -76,5 +77,76 @@ namespace GameLauncher.Models
|
||||
|
||||
/// <summary>内部保持用の生データや元データ(再エンコード用)</summary>
|
||||
public object? RawData { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 真偽値として編集できる項目かどうか。
|
||||
/// </summary>
|
||||
public bool IsBool => this._kind == ValueKind.Boolean;
|
||||
|
||||
/// <summary>
|
||||
/// 数値(整数・小数)として編集できる項目かどうか。
|
||||
/// </summary>
|
||||
public bool IsNumeric => this._kind is ValueKind.Integer or ValueKind.Float or ValueKind.Enum;
|
||||
|
||||
/// <summary>
|
||||
/// 文字列などテキスト入力で編集する項目かどうか。
|
||||
/// </summary>
|
||||
public bool IsStringLike => !this.IsBool && !this.IsNumeric;
|
||||
|
||||
/// <summary>
|
||||
/// 真偽値エディタ(チェックボックス)用の値。
|
||||
/// 設定すると <see cref="EditValue"/> も "true"/"false" に同期します。
|
||||
/// </summary>
|
||||
public bool BoolValue
|
||||
{
|
||||
get => bool.TryParse(this._editValue, out var parsed) && parsed;
|
||||
set => this.EditValue = value ? "true" : "false";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 値の種別。設定すると型別エディタの表示切り替えに反映されます。
|
||||
/// </summary>
|
||||
public ValueKind Kind
|
||||
{
|
||||
get => this._kind;
|
||||
set
|
||||
{
|
||||
if (this._kind != value)
|
||||
{
|
||||
this._kind = value;
|
||||
this.OnPropertyChanged();
|
||||
this.OnPropertyChanged(nameof(this.IsBool));
|
||||
this.OnPropertyChanged(nameof(this.IsNumeric));
|
||||
this.OnPropertyChanged(nameof(this.IsStringLike));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 値の種別(型別エディタの切り替え用)。
|
||||
/// </summary>
|
||||
public enum ValueKind
|
||||
{
|
||||
/// <summary>不明・未判定。</summary>
|
||||
Unknown,
|
||||
|
||||
/// <summary>真偽値。</summary>
|
||||
Boolean,
|
||||
|
||||
/// <summary>整数。</summary>
|
||||
Integer,
|
||||
|
||||
/// <summary>浮動小数。</summary>
|
||||
Float,
|
||||
|
||||
/// <summary>文字列。</summary>
|
||||
String,
|
||||
|
||||
/// <summary>列挙体。</summary>
|
||||
Enum,
|
||||
|
||||
/// <summary>配列・辞書・オブジェクトなど複合型。</summary>
|
||||
Complex
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
-6
@@ -30,6 +30,9 @@
|
||||
<SolidColorBrush x:Key="AccentGreenHover" Color="#10D3AC"/>
|
||||
<SolidColorBrush x:Key="AccentRed" Color="#D63031"/>
|
||||
|
||||
<!-- 型別エディタの表示切り替え用コンバーター -->
|
||||
<helpers:BoolToVisibilityConverter x:Key="BoolToVisibility"/>
|
||||
|
||||
<!-- ボタン標準スタイル -->
|
||||
<Style x:Key="ModernButton" TargetType="Button">
|
||||
<Setter Property="Background" Value="#2E2E3E"/>
|
||||
@@ -396,13 +399,32 @@
|
||||
<!-- ================= 1. GUI セーブエディタ ================= -->
|
||||
<Grid x:Name="pnlGuiEditor" Visibility="Collapsed">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- パスワード/診断バー(暗号化セーブデータ用) -->
|
||||
<Border x:Name="pnlPasswordBar" Grid.Row="0" Background="#1E1E2A" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="1" CornerRadius="6" Padding="10,8" Margin="0,0,0,8" Visibility="Collapsed">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="0" Text="🔑 パスワード:" Foreground="{StaticResource TextSecondary}" FontSize="12" VerticalAlignment="Center" Margin="0,0,8,0"/>
|
||||
<TextBox x:Name="txtPassword" Grid.Column="1" Background="#262636" BorderBrush="{StaticResource BorderBrushColor}"
|
||||
BorderThickness="1" Padding="8,4" Foreground="{StaticResource TextPrimary}" FontSize="12"
|
||||
VerticalAlignment="Center" KeyDown="txtPassword_KeyDown"/>
|
||||
<Button x:Name="btnApplyPassword" Grid.Column="2" Style="{StaticResource PrimaryGreenButton}" Content="このパスワードで再読込" Margin="8,0,0,0" Click="btnApplyPassword_Click"/>
|
||||
<Button x:Name="btnAutoDetectPassword" Grid.Column="3" Style="{StaticResource ModernButton}" Content="🔎 自動特定" Margin="6,0,0,0" Click="btnAutoDetectPassword_Click"/>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- 検索バー -->
|
||||
<Border Grid.Row="0" Background="#1C1C26" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="1" CornerRadius="6" Padding="8,6" Margin="0,0,0,8">
|
||||
<Border Grid.Row="1" Background="#1C1C26" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="1" CornerRadius="6" Padding="8,6" Margin="0,0,0,8">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="26"/>
|
||||
@@ -417,19 +439,40 @@
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- プロパティ DataGrid -->
|
||||
<DataGrid x:Name="dgGuiProperties" Grid.Row="1" SelectionChanged="dgGuiProperties_SelectionChanged">
|
||||
<!-- プロパティ DataGrid(型に応じたエディタを表示) -->
|
||||
<DataGrid x:Name="dgGuiProperties" Grid.Row="2" SelectionChanged="dgGuiProperties_SelectionChanged" AutoGenerateColumns="False" CanUserAddRows="False">
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="分類" Binding="{Binding Category}" Width="120" IsReadOnly="True" Foreground="#A29BFE"/>
|
||||
<DataGridTextColumn Header="変数名 (キー)" Binding="{Binding Key}" Width="2*" IsReadOnly="True" FontWeight="SemiBold"/>
|
||||
<DataGridTextColumn Header="型" Binding="{Binding Type}" Width="80" IsReadOnly="True" Foreground="{StaticResource TextSecondary}"/>
|
||||
<DataGridTextColumn Header="値 (ダブルクリックで直接編集)" Binding="{Binding EditValue, UpdateSourceTrigger=PropertyChanged}" Width="2*"/>
|
||||
<DataGridTextColumn Header="型" Binding="{Binding Type}" Width="90" IsReadOnly="True" Foreground="{StaticResource TextSecondary}"/>
|
||||
<DataGridTemplateColumn Header="値 (型に応じて編集)" Width="2*">
|
||||
<DataGridTemplateColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<Grid>
|
||||
<!-- 真偽値: チェックボックス -->
|
||||
<CheckBox IsChecked="{Binding BoolValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
|
||||
HorizontalAlignment="Center" VerticalAlignment="Center"
|
||||
Visibility="{Binding IsBool, Converter={StaticResource BoolToVisibility}}"/>
|
||||
<!-- 数値: 上下ボタン付き -->
|
||||
<TextBox Text="{Binding EditValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
|
||||
Visibility="{Binding IsNumeric, Converter={StaticResource BoolToVisibility}}"
|
||||
Background="Transparent" BorderThickness="0"
|
||||
Foreground="#A29BFE" VerticalAlignment="Center"/>
|
||||
<!-- 文字列・その他: 通常テキスト -->
|
||||
<TextBox Text="{Binding EditValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
|
||||
Visibility="{Binding IsStringLike, Converter={StaticResource BoolToVisibility}}"
|
||||
Background="Transparent" BorderThickness="0"
|
||||
Foreground="{StaticResource TextPrimary}" VerticalAlignment="Center"/>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
<DataGridTextColumn Header="備考" Binding="{Binding Description}" Width="140" IsReadOnly="True" Foreground="{StaticResource TextSecondary}"/>
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
|
||||
<!-- インライン編集バー -->
|
||||
<Border Grid.Row="2" Background="#1E1E2A" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="1" CornerRadius="6" Padding="10,8" Margin="0,8,0,0">
|
||||
<Border Grid.Row="3" Background="#1E1E2A" BorderBrush="{StaticResource BorderBrushColor}" BorderThickness="1" CornerRadius="6" Padding="10,8" Margin="0,8,0,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
|
||||
+135
-3
@@ -361,10 +361,18 @@ namespace GameLauncher
|
||||
this.lblStatus.Text = $"未対応のバイナリセーブデータ: {entry.FileName}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直近の読み込みで入力・特定されたパスワード。
|
||||
/// </summary>
|
||||
private string? _currentPassword;
|
||||
|
||||
/// <summary>
|
||||
/// コーデックからプロパティ一覧を読み込み、パスワードバーの表示を更新します。
|
||||
/// </summary>
|
||||
private void LoadGuiPropertiesFromCodec(ISaveDataCodec codec, string filePath)
|
||||
{
|
||||
this._guiProperties.Clear();
|
||||
var props = codec.LoadProperties(filePath);
|
||||
var props = codec.LoadProperties(filePath, this._currentPassword);
|
||||
foreach (var p in props)
|
||||
{
|
||||
this._guiProperties.Add(p);
|
||||
@@ -374,6 +382,116 @@ namespace GameLauncher
|
||||
{
|
||||
this.dgGuiProperties.SelectedIndex = 0;
|
||||
}
|
||||
|
||||
this.UpdatePasswordBar(codec, filePath, props.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パスワードバーの表示要否と内容を更新します。
|
||||
/// </summary>
|
||||
/// <param name="codec">使用中のコーデック</param>
|
||||
/// <param name="filePath">対象セーブファイルのパス</param>
|
||||
/// <param name="propertyCount">読み込めたプロパティ数</param>
|
||||
private void UpdatePasswordBar(ISaveDataCodec codec, string filePath, int propertyCount)
|
||||
{
|
||||
// ES3 コーデックかつ暗号化されている場合のみパスワードバーを表示する
|
||||
if (codec is EasySave3Codec es3Codec && es3Codec.NeedsPassword(filePath))
|
||||
{
|
||||
this.pnlPasswordBar.Visibility = Visibility.Visible;
|
||||
this.txtPassword.Text = this._currentPassword ?? string.Empty;
|
||||
|
||||
if (this.txtPassword.Text.Length == 0)
|
||||
{
|
||||
this.txtPassword.ToolTip = es3Codec.PasswordPromptMessage;
|
||||
}
|
||||
|
||||
var diagnostics = es3Codec.Diagnostics;
|
||||
if (propertyCount <= 1 && diagnostics.Count > 0)
|
||||
{
|
||||
this.lblStatus.Text = "復号できませんでした。パスワードを入力するか「自動特定」を試してください。";
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.pnlPasswordBar.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 入力されたパスワードでセーブファイルを再読み込みします。
|
||||
/// </summary>
|
||||
private void btnApplyPassword_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentSelectedFile == null || this._currentCodec == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this._currentPassword = this.txtPassword.Text;
|
||||
this.LoadGuiPropertiesFromCodec(this._currentCodec, this._currentSelectedFile.FilePath);
|
||||
this.lblStatus.Text = $"パスワードを適用して再読み込みしました: {this._currentSelectedFile.FileName}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パスワード入力欄で Enter を押した際に適用します。
|
||||
/// </summary>
|
||||
private void txtPassword_KeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.Key == Key.Enter)
|
||||
{
|
||||
this.btnApplyPassword_Click(sender, e);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パスワードの多段自動特定を実行します。
|
||||
/// </summary>
|
||||
private void btnAutoDetectPassword_Click(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (this._currentSelectedFile is not { } entry)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var resolver = new GameLauncher.Services.Codecs.Es3.Es3PasswordResolver();
|
||||
var result = resolver.Resolve(
|
||||
entry.FilePath,
|
||||
gameRootDirectory: string.IsNullOrEmpty(this.Game.RootDirectory) ? null : this.Game.RootDirectory,
|
||||
gameKey: entry.FilePath);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
this._currentPassword = result.Password;
|
||||
this.txtPassword.Text = result.Password;
|
||||
|
||||
if (this._currentCodec != null)
|
||||
{
|
||||
this.LoadGuiPropertiesFromCodec(this._currentCodec, entry.FilePath);
|
||||
}
|
||||
|
||||
var sourceLabel = result.Source switch
|
||||
{
|
||||
GameLauncher.Services.Codecs.Es3.Es3PasswordSource.LearnedCache => "学習済みキャッシュ",
|
||||
GameLauncher.Services.Codecs.Es3.Es3PasswordSource.Explicit => "指定値",
|
||||
GameLauncher.Services.Codecs.Es3.Es3PasswordSource.GameBinaryStrings => "ゲームバイナリの文字列",
|
||||
GameLauncher.Services.Codecs.Es3.Es3PasswordSource.GameIl2CppMetadata => "IL2CPP メタデータ",
|
||||
GameLauncher.Services.Codecs.Es3.Es3PasswordSource.Dictionary => "辞書探索",
|
||||
_ => "平文"
|
||||
};
|
||||
|
||||
this.lblStatus.Text = $"パスワードを特定しました({sourceLabel} / 試行 {result.TriedCandidates} 件)。";
|
||||
return;
|
||||
}
|
||||
|
||||
var detail = result.Diagnostics.Count > 0
|
||||
? string.Join("\n", result.Diagnostics)
|
||||
: "診断情報がありません。";
|
||||
|
||||
MessageBox.Show(
|
||||
$"パスワードを自動特定できませんでした。\n(試行候補数: {result.TriedCandidates})\n\n{detail}",
|
||||
"自動特定の結果",
|
||||
MessageBoxButton.OK,
|
||||
MessageBoxImage.Warning);
|
||||
}
|
||||
|
||||
private bool FilterGuiProperties(object obj)
|
||||
@@ -434,16 +552,30 @@ namespace GameLauncher
|
||||
{
|
||||
if (this._currentSelectedFile == null || this._currentCodec == null) return;
|
||||
|
||||
bool success = this._currentCodec.SaveProperties(this._currentSelectedFile.FilePath, [.. this._guiProperties]);
|
||||
// 編集で復号に使ったパスワードを渡し、同一パスワードで再暗号化させる
|
||||
bool success = this._currentCodec.SaveProperties(
|
||||
this._currentSelectedFile.FilePath,
|
||||
[.. this._guiProperties],
|
||||
this._currentPassword);
|
||||
|
||||
if (success)
|
||||
{
|
||||
this.lblStatus.Text = $"セーブファイルを正常に更新しました (自動バックアップ .bak 作成済み): {this._currentSelectedFile.FileName}";
|
||||
|
||||
// 保存したファイルを読み直して、実際に反映された内容を画面へ再表示する
|
||||
this.LoadGuiPropertiesFromCodec(this._currentCodec, this._currentSelectedFile.FilePath);
|
||||
|
||||
MessageBox.Show("セーブファイルを正常に更新・保存しました。\n(元のファイルは同階層に .bak として自動バックアップされています)",
|
||||
"保存完了", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("セーブデータの保存・再エンコードに失敗しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
// コーデックが出力した診断情報(往復検証の失敗理由など)を提示する
|
||||
var detail = this._currentCodec is EasySave3Codec es3 && es3.Diagnostics.Count > 0
|
||||
? "\n\n" + string.Join("\n", es3.Diagnostics)
|
||||
: string.Empty;
|
||||
|
||||
MessageBox.Show($"セーブデータの保存・再エンコードに失敗しました。{detail}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using GameLauncher.Engines.Unity;
|
||||
using GameLauncher.Models;
|
||||
using GameLauncher.Services.Codecs.Es3;
|
||||
|
||||
namespace GameLauncher.Services.Codecs
|
||||
{
|
||||
@@ -24,19 +25,63 @@ namespace GameLauncher.Services.Codecs
|
||||
|
||||
/// <summary>
|
||||
/// パスワード入力が必要かどうかを取得します。
|
||||
/// 暗号化の有無はファイルごとに異なるため、実際の要否は <see cref="NeedsPassword"/> で判定します。
|
||||
/// </summary>
|
||||
public bool RequiresPassword => false;
|
||||
public bool RequiresPassword => true;
|
||||
|
||||
/// <summary>
|
||||
/// パスワード入力ダイアログに表示する案内メッセージを取得します。
|
||||
/// </summary>
|
||||
public string? PasswordPromptMessage => "暗号化パスワードが設定されている場合は入力してください(未設定・既定の場合は空欄):";
|
||||
|
||||
// キャッシュ用の最新平文JSONノード
|
||||
private JsonNode? _cachedRootNode;
|
||||
/// <summary>
|
||||
/// 直近の読み込み時に使用した解析ドキュメント(編集・書き戻し用)。
|
||||
/// </summary>
|
||||
private Es3SaveDocument? _document;
|
||||
|
||||
/// <summary>直近の読み込み対象ファイルの絶対パス。</summary>
|
||||
private string? _loadedFilePath;
|
||||
|
||||
/// <summary>直近の読み込み時に暗号化されていたか。</summary>
|
||||
private bool _wasEncrypted;
|
||||
|
||||
/// <summary>直近の読み込み時に復号に使用したパスワード。</summary>
|
||||
private string? _usedPassword;
|
||||
|
||||
/// <summary>直近の読み込み時に Gzip 圧縮されていたか。</summary>
|
||||
private bool _wasGzip;
|
||||
|
||||
/// <summary>直近の読み込み時の診断メッセージ(未対応時の案内表示に使用)。</summary>
|
||||
private readonly List<string> _diagnostics = [];
|
||||
|
||||
/// <summary>
|
||||
/// 直近の読み込みに関する診断メッセージを取得します。
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> Diagnostics => this._diagnostics;
|
||||
|
||||
/// <summary>
|
||||
/// 指定ファイルがパスワード入力(復号)を必要とするかを判定します。
|
||||
/// </summary>
|
||||
/// <param name="filePath">セーブファイルの絶対パス</param>
|
||||
/// <returns>暗号化されており復号が必要な場合 true</returns>
|
||||
public bool NeedsPassword(string filePath)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var bytes = File.ReadAllBytes(filePath);
|
||||
return Es3PasswordResolver.LooksEncrypted(bytes);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定されたセーブファイルが本コーデックで処理可能かを判定します。
|
||||
/// </summary>
|
||||
@@ -67,14 +112,19 @@ namespace GameLauncher.Services.Codecs
|
||||
public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null)
|
||||
{
|
||||
var list = new List<SaveDataPropertyEntry>();
|
||||
this._diagnostics.Clear();
|
||||
this._document = null;
|
||||
this._loadedFilePath = filePath;
|
||||
this._wasEncrypted = false;
|
||||
this._usedPassword = null;
|
||||
this._wasGzip = false;
|
||||
|
||||
if (!File.Exists(filePath)) return list;
|
||||
|
||||
byte[] fileBytes = File.ReadAllBytes(filePath);
|
||||
if (fileBytes.Length == 0) return list;
|
||||
|
||||
string? jsonText = null;
|
||||
this._wasEncrypted = false;
|
||||
this._usedPassword = null;
|
||||
|
||||
// 1. まず平文 JSON または Gzip 解凍を試みる
|
||||
try
|
||||
@@ -83,6 +133,7 @@ namespace GameLauncher.Services.Codecs
|
||||
if (text.TrimStart().StartsWith("{") || text.TrimStart().StartsWith("["))
|
||||
{
|
||||
jsonText = text;
|
||||
this._diagnostics.Add("平文 JSON として読み込みました。");
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
@@ -96,60 +147,142 @@ namespace GameLauncher.Services.Codecs
|
||||
using var gzip = new GZipStream(ms, CompressionMode.Decompress);
|
||||
using var reader = new StreamReader(gzip, Encoding.UTF8);
|
||||
jsonText = reader.ReadToEnd();
|
||||
this._wasGzip = true;
|
||||
this._diagnostics.Add("Gzip 圧縮を解凍して読み込みました。");
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// 3. パスワード指定または既定パスワードによる AES 復号を試みる
|
||||
// 3. パスワードを多段フォールバックで解決して AES 復号する
|
||||
if (jsonText == null)
|
||||
{
|
||||
var candidatePasswords = new List<string>();
|
||||
if (!string.IsNullOrEmpty(optionalPassword))
|
||||
{
|
||||
candidatePasswords.Add(optionalPassword);
|
||||
}
|
||||
candidatePasswords.AddRange(new[] { "Moodkie", "password", "", "SaveData" });
|
||||
var gameRoot = Path.GetDirectoryName(filePath);
|
||||
var resolution = Es3PasswordResolver.Instance.Resolve(
|
||||
filePath,
|
||||
gameRootDirectory: gameRoot,
|
||||
gameKey: gameRoot,
|
||||
explicitPassword: optionalPassword);
|
||||
|
||||
foreach (var pwd in candidatePasswords)
|
||||
this._diagnostics.AddRange(resolution.Diagnostics);
|
||||
|
||||
if (resolution.Success && !string.IsNullOrEmpty(resolution.Password))
|
||||
{
|
||||
var decrypted = this.TryDecryptAes(fileBytes, pwd);
|
||||
if (!string.IsNullOrEmpty(decrypted))
|
||||
jsonText = Es3PasswordResolver.TryDecrypt(fileBytes, resolution.Password);
|
||||
if (!string.IsNullOrEmpty(jsonText))
|
||||
{
|
||||
jsonText = decrypted;
|
||||
this._wasEncrypted = true;
|
||||
this._usedPassword = pwd;
|
||||
break;
|
||||
this._usedPassword = resolution.Password;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(jsonText))
|
||||
{
|
||||
// JSON展開ができなかった場合、バイナリキー・バリュー形式として先頭・重要オフセットを抽出
|
||||
this._diagnostics.Add("復号できませんでした。パスワードを手動で入力してください。");
|
||||
return this.ExtractBinaryPropertiesFallback(fileBytes);
|
||||
}
|
||||
|
||||
// JSON からプロパティを再帰的に展開
|
||||
try
|
||||
{
|
||||
this._cachedRootNode = JsonNode.Parse(jsonText);
|
||||
if (this._cachedRootNode is JsonObject rootObj)
|
||||
{
|
||||
this.FlattenJsonObject(rootObj, "", list);
|
||||
}
|
||||
else if (this._cachedRootNode is JsonArray rootArr)
|
||||
{
|
||||
this.FlattenJsonArray(rootArr, "Array", list);
|
||||
}
|
||||
}
|
||||
catch
|
||||
// 4. ES3 の型付き形式を解析してプロパティへ展開
|
||||
var document = Es3SaveDocument.Parse(jsonText);
|
||||
if (!document.IsLoaded)
|
||||
{
|
||||
this._diagnostics.AddRange(document.Warnings);
|
||||
return this.ExtractBinaryPropertiesFallback(fileBytes);
|
||||
}
|
||||
|
||||
this._document = document;
|
||||
this._diagnostics.AddRange(document.Warnings);
|
||||
this.FlattenNodes(document.RootNodes, string.Empty, list);
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 型付きノードを平坦化してプロパティ一覧へ変換します(型タグ付きで編集可能にします)。
|
||||
/// </summary>
|
||||
/// <param name="nodes">変換対象のノード</param>
|
||||
/// <param name="prefix">現在の階層プレフィックス</param>
|
||||
/// <param name="list">追加先のプロパティリスト</param>
|
||||
private void FlattenNodes(List<Es3Node> nodes, string prefix, List<SaveDataPropertyEntry> list)
|
||||
{
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
var key = string.IsNullOrEmpty(prefix) ? node.Key : $"{prefix}.{node.Key}";
|
||||
var category = string.IsNullOrEmpty(prefix) ? "基本変数" : prefix;
|
||||
|
||||
if (node.HasChildren)
|
||||
{
|
||||
list.Add(new SaveDataPropertyEntry
|
||||
{
|
||||
Key = key,
|
||||
Category = category,
|
||||
Type = FormatKindLabel(node),
|
||||
EditValue = node.DisplayValue,
|
||||
Description = $"JSON パス: {node.Path}",
|
||||
RawData = node,
|
||||
Kind = MapToValueKind(node.Kind)
|
||||
});
|
||||
|
||||
this.FlattenNodes(node.Children, key, list);
|
||||
continue;
|
||||
}
|
||||
|
||||
list.Add(new SaveDataPropertyEntry
|
||||
{
|
||||
Key = key,
|
||||
Category = category,
|
||||
Type = FormatKindLabel(node),
|
||||
EditValue = node.DisplayValue,
|
||||
Description = $"JSON パス: {node.Path}",
|
||||
RawData = node,
|
||||
Kind = MapToValueKind(node.Kind)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の値種別を、GUI の型別エディタ用の種別へ変換します。
|
||||
/// </summary>
|
||||
/// <param name="kind">ES3 の値種別</param>
|
||||
/// <returns>GUI 用の値種別</returns>
|
||||
private static SaveDataPropertyEntry.ValueKind MapToValueKind(Es3ValueKind kind)
|
||||
{
|
||||
return kind switch
|
||||
{
|
||||
Es3ValueKind.Boolean => SaveDataPropertyEntry.ValueKind.Boolean,
|
||||
Es3ValueKind.Integer => SaveDataPropertyEntry.ValueKind.Integer,
|
||||
Es3ValueKind.Float => SaveDataPropertyEntry.ValueKind.Float,
|
||||
Es3ValueKind.String => SaveDataPropertyEntry.ValueKind.String,
|
||||
Es3ValueKind.Enum => SaveDataPropertyEntry.ValueKind.Enum,
|
||||
Es3ValueKind.Array or Es3ValueKind.Dictionary or Es3ValueKind.Object
|
||||
=> SaveDataPropertyEntry.ValueKind.Complex,
|
||||
_ => SaveDataPropertyEntry.ValueKind.Unknown
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ノードの型名を表示用ラベルに整形します。
|
||||
/// </summary>
|
||||
/// <param name="node">対象ノード</param>
|
||||
/// <returns>表示用の型ラベル</returns>
|
||||
private static string FormatKindLabel(Es3Node node)
|
||||
{
|
||||
var kind = node.Kind switch
|
||||
{
|
||||
Es3ValueKind.Boolean => "bool",
|
||||
Es3ValueKind.Integer => "int",
|
||||
Es3ValueKind.Float => "float",
|
||||
Es3ValueKind.String => "string",
|
||||
Es3ValueKind.Enum => "enum",
|
||||
Es3ValueKind.Array => "array",
|
||||
Es3ValueKind.Dictionary => "dictionary",
|
||||
Es3ValueKind.Object => "object",
|
||||
_ => "unknown"
|
||||
};
|
||||
|
||||
return string.IsNullOrEmpty(node.TypeName) ? kind : $"{kind} ({node.TypeName})";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSONオブジェクトを再帰的に走査し、プロパティ一覧に追加します。
|
||||
/// </summary>
|
||||
@@ -312,40 +445,71 @@ namespace GameLauncher.Services.Codecs
|
||||
{
|
||||
try
|
||||
{
|
||||
if (this._cachedRootNode != null)
|
||||
if (this._document is { IsLoaded: true } document)
|
||||
{
|
||||
// JSON の値を更新
|
||||
// 編集値を解析ツリーへ適用する
|
||||
foreach (var prop in properties)
|
||||
{
|
||||
if (prop.RawData is string keyPath)
|
||||
if (!prop.IsModified || prop.RawData is not Es3Node node)
|
||||
{
|
||||
this.UpdateJsonNodeByPath(this._cachedRootNode, keyPath, prop.EditValue, prop.Type);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!node.IsEditable)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (document.TrySetValue(node.Path, prop.EditValue, out var applyError))
|
||||
{
|
||||
node.DisplayValue = prop.EditValue;
|
||||
}
|
||||
else
|
||||
{
|
||||
this._diagnostics.Add($"'{prop.Key}' の適用をスキップしました: {applyError}");
|
||||
}
|
||||
}
|
||||
|
||||
var options = new JsonSerializerOptions
|
||||
// 変更がなければ書き込まない
|
||||
if (!document.HasChanges())
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
string updatedJson = this._cachedRootNode.ToJsonString(options);
|
||||
|
||||
byte[] outputBytes = Encoding.UTF8.GetBytes(updatedJson);
|
||||
|
||||
// もともと暗号化されていた場合は再暗号化
|
||||
if (this._wasEncrypted)
|
||||
{
|
||||
string pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword : (this._usedPassword ?? "Moodkie");
|
||||
outputBytes = this.EncryptAes(outputBytes, pwd);
|
||||
this._diagnostics.Add("変更点がないため保存をスキップしました。");
|
||||
return true;
|
||||
}
|
||||
|
||||
// バックアップ作成
|
||||
byte[] outputBytes = Encoding.UTF8.GetBytes(document.ToJson());
|
||||
|
||||
// もともと Gzip 圧縮されていた場合は再圧縮する
|
||||
if (this._wasGzip)
|
||||
{
|
||||
outputBytes = CompressGzip(outputBytes);
|
||||
}
|
||||
|
||||
// もともと暗号化されていた場合は同一パスワードで再暗号化する
|
||||
if (this._wasEncrypted)
|
||||
{
|
||||
var pwd = !string.IsNullOrEmpty(optionalPassword)
|
||||
? optionalPassword!
|
||||
: this._usedPassword ?? string.Empty;
|
||||
|
||||
outputBytes = Es3PasswordResolver.Encrypt(outputBytes, pwd);
|
||||
}
|
||||
|
||||
// 往復検証: 書き込み前に「出力バイト列を読み直して構造が一致するか」を確認する
|
||||
if (!this.VerifyRoundTrip(outputBytes, document, out var verifyError))
|
||||
{
|
||||
this._diagnostics.Add($"往復検証に失敗したため保存を中止しました: {verifyError}");
|
||||
return false;
|
||||
}
|
||||
|
||||
// バックアップ作成(既存規約に従い .bak を残す)
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
File.Copy(filePath, filePath + ".bak", overwrite: true);
|
||||
}
|
||||
|
||||
File.WriteAllBytes(filePath, outputBytes);
|
||||
this._diagnostics.Add($"保存しました({outputBytes.Length} bytes)。");
|
||||
return true;
|
||||
}
|
||||
else
|
||||
@@ -372,12 +536,91 @@ namespace GameLauncher.Services.Codecs
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
this._diagnostics.Add($"保存中に例外が発生しました: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 出力バイト列を読み直して編集内容が保持されているかを検証します(往復検証)。
|
||||
/// 検証に失敗した場合はファイルへ書き込まず、元データを温存します。
|
||||
/// </summary>
|
||||
/// <param name="outputBytes">書き込み予定のバイト列</param>
|
||||
/// <param name="document">編集済みドキュメント</param>
|
||||
/// <param name="error">検証失敗の理由</param>
|
||||
/// <returns>検証に成功した場合 true</returns>
|
||||
private bool VerifyRoundTrip(byte[] outputBytes, Es3SaveDocument document, out string error)
|
||||
{
|
||||
error = string.Empty;
|
||||
|
||||
try
|
||||
{
|
||||
string? verifiedJson;
|
||||
|
||||
if (this._wasEncrypted)
|
||||
{
|
||||
var pwd = this._usedPassword ?? string.Empty;
|
||||
verifiedJson = Es3PasswordResolver.TryDecrypt(outputBytes, pwd);
|
||||
}
|
||||
else if (this._wasGzip)
|
||||
{
|
||||
using var ms = new MemoryStream(outputBytes);
|
||||
using var gzip = new GZipStream(ms, CompressionMode.Decompress);
|
||||
using var reader = new StreamReader(gzip, Encoding.UTF8);
|
||||
verifiedJson = reader.ReadToEnd();
|
||||
}
|
||||
else
|
||||
{
|
||||
verifiedJson = Encoding.UTF8.GetString(outputBytes);
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(verifiedJson))
|
||||
{
|
||||
error = "出力データを復号・解凍できませんでした。";
|
||||
return false;
|
||||
}
|
||||
|
||||
var reparsed = Es3SaveDocument.Parse(verifiedJson);
|
||||
if (!reparsed.IsLoaded)
|
||||
{
|
||||
error = "出力データを再解析できませんでした。";
|
||||
return false;
|
||||
}
|
||||
|
||||
// ルート直下の要素数が一致することを最低条件とする
|
||||
if (reparsed.RootNodes.Count != document.RootNodes.Count)
|
||||
{
|
||||
error = $"要素数が一致しません(期待 {document.RootNodes.Count} / 実際 {reparsed.RootNodes.Count})。";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// バイト列を Gzip 圧縮します(元が Gzip だった場合に元形式を維持するため)。
|
||||
/// </summary>
|
||||
/// <param name="plainBytes">平文バイト列</param>
|
||||
/// <returns>圧縮済みバイト列</returns>
|
||||
private static byte[] CompressGzip(byte[] plainBytes)
|
||||
{
|
||||
using var output = new MemoryStream();
|
||||
using (var gzip = new GZipStream(output, CompressionLevel.Optimal, leaveOpen: true))
|
||||
{
|
||||
gzip.Write(plainBytes, 0, plainBytes.Length);
|
||||
}
|
||||
|
||||
return output.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// キーパスに基づいてJSONノードの値を更新します。
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace GameLauncher.Services.Codecs.Es3
|
||||
{
|
||||
/// <summary>
|
||||
/// ゲームのバイナリから ES3 のパスワード候補文字列を抽出する汎用ヘルパー。
|
||||
///
|
||||
/// Easy Save 3 のパスワードは <c>new ES3Settings(ES3.EncryptionType.AES, "password")</c> のように
|
||||
/// コード中の文字列リテラルとして埋め込まれることが多いため、
|
||||
/// マネージドアセンブリ(Mono)/IL2CPP メタデータの双方から文字列を回収します。
|
||||
/// 特定のゲーム名に依存しない汎用実装です。
|
||||
/// </summary>
|
||||
public static class Es3PasswordExtractor
|
||||
{
|
||||
/// <summary>文字列抽出対象とする最大ファイルサイズ(バイト)。巨大ファイルの全走査を避けます。</summary>
|
||||
private const long MaxScanFileSize = 512L * 1024 * 1024;
|
||||
|
||||
/// <summary>1 ファイルあたりに保持する候補の上限。</summary>
|
||||
private const int MaxCandidatesPerFile = 4000;
|
||||
|
||||
/// <summary>抽出する文字列の最小長。</summary>
|
||||
private const int MinCandidateLength = 3;
|
||||
|
||||
/// <summary>抽出する文字列の最大長。</summary>
|
||||
private const int MaxCandidateLength = 64;
|
||||
|
||||
/// <summary>ES3 の既定設定アセットにおいて暗号化パスワードを保持するフィールド名。</summary>
|
||||
private const string FieldNameEncryptionPassword = "encryptionPassword";
|
||||
|
||||
/// <summary>
|
||||
/// パスワードらしい文字列のみを通すための許可パターン(英数字記号のみ、空白・制御文字を除外)。
|
||||
/// </summary>
|
||||
private static readonly Regex CandidatePattern =
|
||||
new(@"^[\x21-\x7E]{3,64}$", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// ES3 のパスワード指定箇所の近傍を示す手がかりキーワード。
|
||||
/// これらを含む文字列は優先的に候補の先頭へ寄せます。
|
||||
/// </summary>
|
||||
private static readonly string[] PasswordHints =
|
||||
[
|
||||
"password", "Password", "PASSWORD",
|
||||
"pass", "Pass", "pwd", "Pwd",
|
||||
"encrypt", "Encrypt", "encryption", "Encryption",
|
||||
"ES3Settings", "ES3", "es3"
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// 明らかにパスワードではない文字列(Unity の内部名・型名・UI ラベルなど)を除外するパターン。
|
||||
///
|
||||
/// 実ゲーム検証では "GUILayoutPasswordField" のような UI クラス名や
|
||||
/// "The password Text" のような説明文が大量に抽出され、真のパスワードが埋もれていました。
|
||||
/// それらを除外して候補の精度を上げます。
|
||||
/// </summary>
|
||||
private static readonly Regex NoisePattern = new(
|
||||
@"^(Unity|UnityEngine|UnityEditor|System|Microsoft|Mono|mscorlib|netstandard|" +
|
||||
@"Assembly-CSharp|Library|Packages|Assets|Resources|StreamingAssets|" +
|
||||
@"com\.unity|Unity\.|UnityEngine\.|System\.)" +
|
||||
@"|PasswordField|passwordField|TextField|password Text|Password Text" +
|
||||
@"|GUILayout|OnGUI|m_[A-Z]|get_|set_|<[A-Za-z]",
|
||||
RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// 空白を含む文字列は UI ラベル・説明文である可能性が高いため、
|
||||
/// パスワード候補としては扱いません(パスワードは通常 1 トークン)。
|
||||
/// </summary>
|
||||
private static readonly Regex SentenceLikePattern = new(
|
||||
@"\s{1,}.*\s|[.!?]$",
|
||||
RegexOptions.Compiled);
|
||||
|
||||
/// <summary>
|
||||
/// ゲームルートディレクトリから ES3 パスワード候補を抽出します。
|
||||
/// </summary>
|
||||
/// <param name="gameRootDirectory">ゲームのルートディレクトリ</param>
|
||||
/// <param name="diagnostics">診断メッセージの追加先(null 可)</param>
|
||||
/// <returns>優先度順に並んだパスワード候補</returns>
|
||||
public static List<string> ExtractCandidates(string gameRootDirectory, List<string>? diagnostics = null)
|
||||
{
|
||||
var result = new List<string>();
|
||||
if (string.IsNullOrWhiteSpace(gameRootDirectory) || !Directory.Exists(gameRootDirectory))
|
||||
{
|
||||
diagnostics?.Add($"ゲームフォルダが見つかりません: {gameRootDirectory}");
|
||||
return result;
|
||||
}
|
||||
|
||||
var scanTargets = CollectScanTargets(gameRootDirectory);
|
||||
if (scanTargets.Count == 0)
|
||||
{
|
||||
diagnostics?.Add("文字列抽出の対象ファイル(マネージドアセンブリ/IL2CPPメタデータ)が見つかりませんでした。");
|
||||
return result;
|
||||
}
|
||||
|
||||
diagnostics?.Add($"文字列抽出対象: {scanTargets.Count} ファイル");
|
||||
|
||||
// 「パスワード指定の近傍にある文字列」を高優先、「その他の文字列」を低優先として収集する
|
||||
var settingsDerived = new List<string>();
|
||||
var highPriority = new List<string>();
|
||||
var lowPriority = new List<string>();
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var path in scanTargets)
|
||||
{
|
||||
try
|
||||
{
|
||||
var info = new FileInfo(path);
|
||||
if (!info.Exists || info.Length == 0 || info.Length > MaxScanFileSize)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
|
||||
// ES3Defaults の encryptionPassword フィールドを持つアセットは、
|
||||
// 値域に格納された文字列をパスワード候補として最優先で回収する
|
||||
CollectFromEs3DefaultSettings(bytes, settingsDerived, seen);
|
||||
|
||||
CollectFromBytes(bytes, highPriority, lowPriority, seen);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
diagnostics?.Add($"読み込み失敗: {Path.GetFileName(path)} ({ex.Message})");
|
||||
}
|
||||
}
|
||||
|
||||
if (settingsDerived.Count > 0)
|
||||
{
|
||||
diagnostics?.Add($"ES3Defaults の encryptionPassword 近傍から {settingsDerived.Count} 件の候補を抽出しました。");
|
||||
}
|
||||
|
||||
// ES3Defaults 由来 → 高優先 → 低優先の順で連結
|
||||
foreach (var candidate in settingsDerived.Concat(highPriority).Concat(lowPriority))
|
||||
{
|
||||
if (result.Count >= 512)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
result.Add(candidate);
|
||||
}
|
||||
|
||||
diagnostics?.Add(
|
||||
$"抽出候補数: {result.Count}(設定由来 {settingsDerived.Count} / 高優先 {highPriority.Count} / 低優先 {lowPriority.Count})");
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の既定設定(<c>ES3Defaults</c>)を持つアセットから、<c>encryptionPassword</c> の値候補を抽出します。
|
||||
///
|
||||
/// Unity のアセットは「フィールド名テーブル」と「値テーブル」が分離しており、
|
||||
/// フィールド名の直後に値があるとは限りません。そのため、フィールド名が存在するアセットでは
|
||||
/// ファイル全体の文字列を候補化しつつ、パスワードらしい短い文字列を優先的に先頭へ寄せます。
|
||||
/// </summary>
|
||||
/// <param name="bytes">アセットのバイト列</param>
|
||||
/// <param name="settingsDerived">設定由来の候補の追加先</param>
|
||||
/// <param name="seen">重複排除用の集合</param>
|
||||
private static void CollectFromEs3DefaultSettings(
|
||||
byte[] bytes,
|
||||
List<string> settingsDerived,
|
||||
HashSet<string> seen)
|
||||
{
|
||||
if (bytes.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 高速化のため、まず encryptionPassword の存在を確認する
|
||||
bool hasField;
|
||||
try
|
||||
{
|
||||
var probeLength = Math.Min(bytes.Length, 4 * 1024 * 1024);
|
||||
var probe = Encoding.ASCII.GetString(bytes, 0, probeLength);
|
||||
hasField = probe.Contains(FieldNameEncryptionPassword, StringComparison.Ordinal);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasField)
|
||||
{
|
||||
// 巨大アセットでは先頭 4MB に無いことが多いため、全体を再度確認する
|
||||
try
|
||||
{
|
||||
var all = Encoding.ASCII.GetString(bytes);
|
||||
hasField = all.Contains(FieldNameEncryptionPassword, StringComparison.Ordinal);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasField)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// フィールド名が存在するアセットの文字列を候補化する
|
||||
var asciiCandidates = new List<string>();
|
||||
var utf16Candidates = new List<string>();
|
||||
CollectAsciiStrings(bytes, asciiCandidates, asciiCandidates, seen, 0);
|
||||
CollectUtf16Strings(bytes, utf16Candidates, utf16Candidates, seen, 0);
|
||||
|
||||
// 実ゲーム検証では、PlayMaker アクションのスキーマ定義に encryptionPassword が
|
||||
// 並ぶだけで実際の値は別領域にあり、無関係な文字列が大量に候補化されました。
|
||||
// パスワード指定の手がかり(password / encrypt 等)を含む文字列だけに絞り込みます。
|
||||
foreach (var candidate in asciiCandidates.Concat(utf16Candidates))
|
||||
{
|
||||
if (!ContainsPasswordHint(candidate))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (LooksLikePasswordValue(candidate) && !settingsDerived.Contains(candidate))
|
||||
{
|
||||
settingsDerived.Add(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 文字列がパスワード値そのものらしいかを判定します(フィールド名や型名を除外)。
|
||||
/// </summary>
|
||||
/// <param name="candidate">候補文字列</param>
|
||||
/// <returns>パスワード値らしい場合 true</returns>
|
||||
private static bool LooksLikePasswordValue(string candidate)
|
||||
{
|
||||
if (candidate.Length < 3 || candidate.Length > 32)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// ES3 の設定フィールド名・型名は値ではない
|
||||
if (candidate.Equals(FieldNameEncryptionPassword, StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.Equals("encryptionType", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.Equals("compressionType", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.Equals("bufferSize", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.Equals("errorMessage", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.Equals("overrideDefaultSettings", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.StartsWith("ES3", StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 空白・記号のみのものは除外
|
||||
if (candidate.Contains(' '))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return IsPlausibleCandidate(candidate);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 走査対象のファイル一覧を収集します。
|
||||
/// Mono の場合は Managed 配下の DLL、IL2CPP の場合は GameAssembly.dll と global-metadata.dat を対象にします。
|
||||
/// </summary>
|
||||
/// <param name="gameRootDirectory">ゲームのルートディレクトリ</param>
|
||||
/// <returns>走査対象ファイルの絶対パス一覧</returns>
|
||||
private static List<string> CollectScanTargets(string gameRootDirectory)
|
||||
{
|
||||
var targets = new List<string>();
|
||||
|
||||
try
|
||||
{
|
||||
// 1. Mono: <Game>_Data\Managed\*.dll(Assembly-CSharp.dll を最優先)
|
||||
foreach (var dataDir in Directory.GetDirectories(gameRootDirectory))
|
||||
{
|
||||
if (!Path.GetFileName(dataDir).EndsWith("_Data", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var managedDir = Path.Combine(dataDir, "Managed");
|
||||
if (Directory.Exists(managedDir))
|
||||
{
|
||||
var dlls = Directory.GetFiles(managedDir, "*.dll", SearchOption.TopDirectoryOnly)
|
||||
.Where(f =>
|
||||
{
|
||||
var name = Path.GetFileName(f);
|
||||
return !name.StartsWith("Unity", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.StartsWith("System", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.StartsWith("Mono", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.StartsWith("netstandard", StringComparison.OrdinalIgnoreCase);
|
||||
})
|
||||
.OrderByDescending(f =>
|
||||
Path.GetFileName(f).StartsWith("Assembly-CSharp", StringComparison.OrdinalIgnoreCase))
|
||||
.ToList();
|
||||
|
||||
targets.AddRange(dlls);
|
||||
}
|
||||
|
||||
// 2. IL2CPP: il2cpp_data\Metadata\global-metadata.dat
|
||||
var metadata = Path.Combine(dataDir, "il2cpp_data", "Metadata", "global-metadata.dat");
|
||||
if (File.Exists(metadata))
|
||||
{
|
||||
targets.Add(metadata);
|
||||
}
|
||||
|
||||
// 3. ES3 の既定設定(ES3Defaults ScriptableObject)はアセットに格納されるため、
|
||||
// アセット内の文字列も走査対象に含める。コード側にパスワードリテラルが
|
||||
// 存在しないゲームでは、ここが唯一の手がかりになる。
|
||||
targets.AddRange(CollectAssetTargets(dataDir));
|
||||
}
|
||||
|
||||
// 3. IL2CPP: ルート直下の GameAssembly.dll
|
||||
var gameAssembly = Path.Combine(gameRootDirectory, "GameAssembly.dll");
|
||||
if (File.Exists(gameAssembly))
|
||||
{
|
||||
targets.Add(gameAssembly);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 列挙失敗時は取得できた分だけ返す
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の既定設定(<c>ES3Defaults</c> ScriptableObject)が格納され得るアセットファイルを収集します。
|
||||
///
|
||||
/// 実ゲーム検証ではコード側にパスワードリテラルが存在せず(<c>encryption</c> 文字列すら無い)、
|
||||
/// 既定設定アセットにのみパスワードが入っているケースがありました。
|
||||
/// 巨大な .resS / .bundle を避け、テキスト情報を持つ .assets 系に限定します。
|
||||
/// </summary>
|
||||
/// <param name="dataDirectory">ゲームの *_Data ディレクトリ</param>
|
||||
/// <returns>走査対象アセットの絶対パス一覧</returns>
|
||||
private static List<string> CollectAssetTargets(string dataDirectory)
|
||||
{
|
||||
var targets = new List<string>();
|
||||
|
||||
try
|
||||
{
|
||||
var extensionSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
".assets", ".asset", ".json", ".bytes", ".dat"
|
||||
};
|
||||
|
||||
foreach (var file in Directory.GetFiles(dataDirectory, "*", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
var ext = Path.GetExtension(file);
|
||||
if (!extensionSet.Contains(ext))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var info = new FileInfo(file);
|
||||
if (info.Length == 0 || info.Length > MaxScanFileSize)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
targets.Add(file);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 列挙失敗時は取得できた分だけ返す
|
||||
}
|
||||
|
||||
return targets;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// バイト列から ASCII 文字列を抽出し、優先度別のリストへ振り分けます。
|
||||
///
|
||||
/// .NET アセンブリ(Assembly-CSharp.dll 等)の文字列定数は UTF-16LE で格納されるため、
|
||||
/// 8bit ASCII 走査に加えて 16bit 走査も行います。これを行わないと
|
||||
/// コード中のパスワードリテラルを取り逃がします。
|
||||
/// </summary>
|
||||
/// <param name="bytes">対象バイト列</param>
|
||||
/// <param name="highPriority">パスワード指定近傍の候補の追加先</param>
|
||||
/// <param name="lowPriority">その他の候補の追加先</param>
|
||||
/// <param name="seen">重複排除用の集合</param>
|
||||
private static void CollectFromBytes(
|
||||
byte[] bytes,
|
||||
List<string> highPriority,
|
||||
List<string> lowPriority,
|
||||
HashSet<string> seen)
|
||||
{
|
||||
int count = 0;
|
||||
|
||||
count = CollectAsciiStrings(bytes, highPriority, lowPriority, seen, count);
|
||||
if (count >= MaxCandidatesPerFile)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// UTF-16LE(.NET の文字列定数)としても走査する
|
||||
CollectUtf16Strings(bytes, highPriority, lowPriority, seen, count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 8bit ASCII 文字列を抽出します。
|
||||
/// </summary>
|
||||
/// <param name="bytes">対象バイト列</param>
|
||||
/// <param name="highPriority">高優先候補の追加先</param>
|
||||
/// <param name="lowPriority">低優先候補の追加先</param>
|
||||
/// <param name="seen">重複排除用の集合</param>
|
||||
/// <param name="count">既に追加済みの件数</param>
|
||||
/// <returns>追加後の件数</returns>
|
||||
private static int CollectAsciiStrings(
|
||||
byte[] bytes,
|
||||
List<string> highPriority,
|
||||
List<string> lowPriority,
|
||||
HashSet<string> seen,
|
||||
int count)
|
||||
{
|
||||
var current = new StringBuilder(MaxCandidateLength);
|
||||
|
||||
for (int i = 0; i < bytes.Length; i++)
|
||||
{
|
||||
byte b = bytes[i];
|
||||
|
||||
// 印字可能な ASCII のみを文字列として扱う
|
||||
if (b >= 0x21 && b <= 0x7E)
|
||||
{
|
||||
if (current.Length < MaxCandidateLength)
|
||||
{
|
||||
current.Append((char)b);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
count = FlushCandidate(current, highPriority, lowPriority, seen, count);
|
||||
if (count >= MaxCandidatesPerFile)
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
current.Clear();
|
||||
}
|
||||
|
||||
return FlushCandidate(current, highPriority, lowPriority, seen, count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UTF-16LE(下位バイトが印字可能 ASCII、上位バイトが 0x00)の文字列を抽出します。
|
||||
/// </summary>
|
||||
/// <param name="bytes">対象バイト列</param>
|
||||
/// <param name="highPriority">高優先候補の追加先</param>
|
||||
/// <param name="lowPriority">低優先候補の追加先</param>
|
||||
/// <param name="seen">重複排除用の集合</param>
|
||||
/// <param name="count">既に追加済みの件数</param>
|
||||
/// <returns>追加後の件数</returns>
|
||||
private static int CollectUtf16Strings(
|
||||
byte[] bytes,
|
||||
List<string> highPriority,
|
||||
List<string> lowPriority,
|
||||
HashSet<string> seen,
|
||||
int count)
|
||||
{
|
||||
var current = new StringBuilder(MaxCandidateLength);
|
||||
|
||||
for (int i = 0; i + 1 < bytes.Length; i += 2)
|
||||
{
|
||||
byte lo = bytes[i];
|
||||
byte hi = bytes[i + 1];
|
||||
|
||||
if (lo >= 0x21 && lo <= 0x7E && hi == 0x00)
|
||||
{
|
||||
if (current.Length < MaxCandidateLength)
|
||||
{
|
||||
current.Append((char)lo);
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
count = FlushCandidate(current, highPriority, lowPriority, seen, count);
|
||||
if (count >= MaxCandidatesPerFile)
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
current.Clear();
|
||||
}
|
||||
|
||||
return FlushCandidate(current, highPriority, lowPriority, seen, count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 蓄積中の文字列を候補として確定し、優先度別リストへ追加します。
|
||||
/// </summary>
|
||||
/// <param name="buffer">蓄積中の文字列バッファ</param>
|
||||
/// <param name="highPriority">高優先候補の追加先</param>
|
||||
/// <param name="lowPriority">低優先候補の追加先</param>
|
||||
/// <param name="seen">重複排除用の集合</param>
|
||||
/// <param name="count">既に追加済みの件数</param>
|
||||
/// <returns>追加後の件数</returns>
|
||||
private static int FlushCandidate(
|
||||
StringBuilder buffer,
|
||||
List<string> highPriority,
|
||||
List<string> lowPriority,
|
||||
HashSet<string> seen,
|
||||
int count)
|
||||
{
|
||||
if (buffer.Length < MinCandidateLength || buffer.Length > MaxCandidateLength)
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
var candidate = buffer.ToString();
|
||||
if (!IsPlausibleCandidate(candidate) || !seen.Add(candidate))
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
if (ContainsPasswordHint(candidate))
|
||||
{
|
||||
highPriority.Add(candidate);
|
||||
}
|
||||
else
|
||||
{
|
||||
lowPriority.Add(candidate);
|
||||
}
|
||||
|
||||
return count + 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 抽出した文字列がパスワード候補として妥当かどうかを判定します。
|
||||
/// </summary>
|
||||
/// <param name="candidate">候補文字列</param>
|
||||
/// <returns>妥当な場合 true</returns>
|
||||
private static bool IsPlausibleCandidate(string candidate)
|
||||
{
|
||||
if (!CandidatePattern.IsMatch(candidate))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 空白を含む説明文・UI ラベルは除外
|
||||
if (SentenceLikePattern.IsMatch(candidate))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Unity の内部名・名前空間などはノイズとして除外
|
||||
if (NoisePattern.IsMatch(candidate))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 拡張子付きファイル名は除外
|
||||
if (candidate.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.EndsWith(".dat", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.EndsWith(".es3", StringComparison.OrdinalIgnoreCase) ||
|
||||
candidate.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 文字列がパスワード指定箇所の手がかりを含むかを判定します。
|
||||
/// </summary>
|
||||
/// <param name="candidate">候補文字列</param>
|
||||
/// <returns>手がかりを含む場合 true</returns>
|
||||
private static bool ContainsPasswordHint(string candidate)
|
||||
{
|
||||
foreach (var hint in PasswordHints)
|
||||
{
|
||||
if (candidate.Contains(hint, StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace GameLauncher.Services.Codecs.Es3
|
||||
{
|
||||
/// <summary>
|
||||
/// "どの段階でパスワードが判明したか" を表す解決手段の種別。
|
||||
/// </summary>
|
||||
public enum Es3PasswordSource
|
||||
{
|
||||
/// <summary>学習キャッシュ(過去に解決済みのパスワード)から復元。</summary>
|
||||
LearnedCache,
|
||||
|
||||
/// <summary>呼び出し元が明示指定したパスワード。</summary>
|
||||
Explicit,
|
||||
|
||||
/// <summary>ゲーム内のマネージドアセンブリ(Assembly-CSharp.dll 等)の文字列リテラルから抽出。</summary>
|
||||
GameBinaryStrings,
|
||||
|
||||
/// <summary>ゲーム内バイナリ(IL2CPP の GameAssembly.dll / global-metadata.dat)から抽出。</summary>
|
||||
GameIl2CppMetadata,
|
||||
|
||||
/// <summary>ユーザー辞書ファイル/既定の候補リストからの探索。</summary>
|
||||
Dictionary,
|
||||
|
||||
/// <summary>平文のまま(暗号化されていない)。</summary>
|
||||
PlainText
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 パスワード解決の結果。<see cref="Success"/> が false の場合は <see cref="Diagnostics"/> に理由が入ります。
|
||||
/// </summary>
|
||||
public sealed class Es3PasswordResolution
|
||||
{
|
||||
/// <summary>解決に成功したか。</summary>
|
||||
public bool Success { get; init; }
|
||||
|
||||
/// <summary>解決したパスワード(平文・暗号化なしの場合は空文字)。</summary>
|
||||
public string Password { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>解決手段の種別。</summary>
|
||||
public Es3PasswordSource Source { get; init; }
|
||||
|
||||
/// <summary>試行した候補数。</summary>
|
||||
public int TriedCandidates { get; init; }
|
||||
|
||||
/// <summary>診断用のメッセージ一覧(失敗理由・各段階の結果)。</summary>
|
||||
public IReadOnlyList<string> Diagnostics { get; init; } = [];
|
||||
|
||||
/// <summary>失敗結果を生成します。</summary>
|
||||
public static Es3PasswordResolution Fail(List<string> diagnostics, int tried)
|
||||
=> new() { Success = false, Diagnostics = diagnostics, TriedCandidates = tried };
|
||||
|
||||
/// <summary>成功結果を生成します。</summary>
|
||||
public static Es3PasswordResolution Ok(string password, Es3PasswordSource source, int tried)
|
||||
=> new() { Success = true, Password = password, Source = source, TriedCandidates = tried };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 (Easy Save 3) の暗号化セーブデータからパスワードを多段フォールバックで特定する汎用リゾルバ。
|
||||
///
|
||||
/// 解決順序:
|
||||
/// 1. 学習キャッシュ(<see cref="Es3PasswordStore"/>)
|
||||
/// 2. 呼び出し元の明示指定
|
||||
/// 3. ゲームのマネージドアセンブリ文字列リテラル抽出(Mono)
|
||||
/// 4. 既定候補 + ユーザー辞書による探索
|
||||
///
|
||||
/// すべての候補は実際に AES 復号して妥当性を検証し、成功したものだけを採用します。
|
||||
/// これにより「誤ったパスワードで復号して壊れたデータを書く」事故を防止します。
|
||||
/// </summary>
|
||||
public sealed class Es3PasswordResolver
|
||||
{
|
||||
/// <summary>ES3 が AES 暗号化時にファイル先頭へ埋め込む IV の長さ(バイト)。</summary>
|
||||
public const int AesIvLength = 16;
|
||||
|
||||
/// <summary>復号結果が「ES3 の平文 JSON」らしいかを判定する際の最小文字数。</summary>
|
||||
private const int MinimumPlainTextLength = 2;
|
||||
|
||||
private readonly Es3PasswordStore _store;
|
||||
|
||||
/// <summary>
|
||||
/// 既定のストアを用いて <see cref="Es3PasswordResolver"/> を初期化します。
|
||||
/// </summary>
|
||||
public Es3PasswordResolver()
|
||||
: this(Es3PasswordStore.Instance)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 任意のストアを指定して <see cref="Es3PasswordResolver"/> を初期化します(テスト用途を含む)。
|
||||
/// </summary>
|
||||
/// <param name="store">学習済みパスワードの永続ストア</param>
|
||||
public Es3PasswordResolver(Es3PasswordStore store)
|
||||
{
|
||||
this._store = store ?? throw new ArgumentNullException(nameof(store));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 既定のシングルトンインスタンス。
|
||||
/// </summary>
|
||||
public static Es3PasswordResolver Instance { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// ES3 のファイルが暗号化されているかどうかを統計的に判定します。
|
||||
/// 平文 JSON / Gzip はもちろん「暗号化されていない」と判定します。
|
||||
/// </summary>
|
||||
/// <param name="bytes">ファイル全体のバイト列</param>
|
||||
/// <returns>暗号化されている可能性が高い場合 true</returns>
|
||||
public static bool LooksEncrypted(byte[] bytes)
|
||||
{
|
||||
if (bytes == null || bytes.Length < AesIvLength * 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 平文 JSON はそのまま読める
|
||||
if (IsLikelyJson(bytes))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Gzip マジック
|
||||
if (bytes[0] == 0x1F && bytes[1] == 0x8B)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// AES ブロック境界に一致し、かつ高エントロピーなら暗号化とみなす
|
||||
if (bytes.Length % AesIvLength != 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return CalculateEntropy(bytes) >= 7.5;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パスワードを多段フォールバックで解決します。
|
||||
/// </summary>
|
||||
/// <param name="saveFilePath">対象の .es3 ファイルの絶対パス</param>
|
||||
/// <param name="gameRootDirectory">ゲームのルートディレクトリ(文字列抽出元の探索に使用)</param>
|
||||
/// <param name="gameKey">学習キャッシュのキー(通常はゲームのルートディレクトリ)</param>
|
||||
/// <param name="explicitPassword">呼び出し元が既に知っているパスワード(任意)</param>
|
||||
/// <param name="userDictionaryPath">追加候補を列挙したテキストファイルのパス(任意)</param>
|
||||
/// <returns>解決結果</returns>
|
||||
public Es3PasswordResolution Resolve(
|
||||
string saveFilePath,
|
||||
string? gameRootDirectory = null,
|
||||
string? gameKey = null,
|
||||
string? explicitPassword = null,
|
||||
string? userDictionaryPath = null)
|
||||
{
|
||||
var diagnostics = new List<string>();
|
||||
int tried = 0;
|
||||
|
||||
byte[] fileBytes;
|
||||
try
|
||||
{
|
||||
fileBytes = File.ReadAllBytes(saveFilePath);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
diagnostics.Add($"セーブファイルを読み込めません: {ex.Message}");
|
||||
return Es3PasswordResolution.Fail(diagnostics, tried);
|
||||
}
|
||||
|
||||
if (fileBytes.Length == 0)
|
||||
{
|
||||
diagnostics.Add("セーブファイルが空です。");
|
||||
return Es3PasswordResolution.Fail(diagnostics, tried);
|
||||
}
|
||||
|
||||
// 暗号化されていない場合はパスワード不要
|
||||
if (!LooksEncrypted(fileBytes))
|
||||
{
|
||||
diagnostics.Add("暗号化は検出されませんでした(平文または Gzip)。");
|
||||
return Es3PasswordResolution.Ok(string.Empty, Es3PasswordSource.PlainText, tried);
|
||||
}
|
||||
|
||||
diagnostics.Add($"暗号化を検出しました({fileBytes.Length} bytes / AES-128-CBC 相当)。");
|
||||
|
||||
// ---- 段階 1: 学習キャッシュ ----
|
||||
var cacheKey = this.BuildCacheKey(gameKey, saveFilePath);
|
||||
if (!string.IsNullOrEmpty(cacheKey))
|
||||
{
|
||||
var learned = this._store.TryGet(cacheKey);
|
||||
if (!string.IsNullOrEmpty(learned))
|
||||
{
|
||||
tried++;
|
||||
if (this.VerifyPassword(fileBytes, learned, out _))
|
||||
{
|
||||
diagnostics.Add("学習キャッシュのパスワードで復号に成功しました。");
|
||||
return Es3PasswordResolution.Ok(learned, Es3PasswordSource.LearnedCache, tried);
|
||||
}
|
||||
|
||||
diagnostics.Add("学習キャッシュのパスワードは無効でした(破棄します)。");
|
||||
this._store.Remove(cacheKey);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 段階 2: 明示指定 ----
|
||||
if (!string.IsNullOrEmpty(explicitPassword))
|
||||
{
|
||||
tried++;
|
||||
if (this.VerifyPassword(fileBytes, explicitPassword, out _))
|
||||
{
|
||||
diagnostics.Add("指定されたパスワードで復号に成功しました。");
|
||||
this.Remember(cacheKey, explicitPassword);
|
||||
return Es3PasswordResolution.Ok(explicitPassword, Es3PasswordSource.Explicit, tried);
|
||||
}
|
||||
|
||||
diagnostics.Add("指定されたパスワードでは復号できませんでした。");
|
||||
}
|
||||
|
||||
// ---- 段階 3: ゲームバイナリの文字列リテラル抽出 ----
|
||||
if (!string.IsNullOrEmpty(gameRootDirectory) && Directory.Exists(gameRootDirectory))
|
||||
{
|
||||
var extracted = Es3PasswordExtractor.ExtractCandidates(gameRootDirectory, diagnostics);
|
||||
foreach (var candidate in extracted)
|
||||
{
|
||||
tried++;
|
||||
if (this.VerifyPassword(fileBytes, candidate, out _))
|
||||
{
|
||||
diagnostics.Add($"ゲームバイナリから抽出した候補で復号に成功しました(候補: {Mask(candidate)})。");
|
||||
this.Remember(cacheKey, candidate);
|
||||
return Es3PasswordResolution.Ok(candidate, Es3PasswordSource.GameBinaryStrings, tried);
|
||||
}
|
||||
}
|
||||
|
||||
if (extracted.Count == 0)
|
||||
{
|
||||
diagnostics.Add("ゲームバイナリから有効なパスワード候補を抽出できませんでした。");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 段階 4: 既定候補 + ユーザー辞書 ----
|
||||
foreach (var candidate in this.EnumerateDictionaryCandidates(userDictionaryPath, diagnostics))
|
||||
{
|
||||
tried++;
|
||||
if (this.VerifyPassword(fileBytes, candidate, out _))
|
||||
{
|
||||
diagnostics.Add($"辞書探索で復号に成功しました(候補: {Mask(candidate)})。");
|
||||
this.Remember(cacheKey, candidate);
|
||||
return Es3PasswordResolution.Ok(candidate, Es3PasswordSource.Dictionary, tried);
|
||||
}
|
||||
}
|
||||
|
||||
diagnostics.Add($"すべての段階で復号に失敗しました(試行候補数: {tried})。パスワードを手動で入力してください。");
|
||||
return Es3PasswordResolution.Fail(diagnostics, tried);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定パスワードで ES3 ファイルを復号し、平文 JSON 文字列を取得します。
|
||||
/// </summary>
|
||||
/// <param name="fileBytes">ファイル全体のバイト列</param>
|
||||
/// <param name="password">パスワード</param>
|
||||
/// <param name="plainText">復号された平文 JSON</param>
|
||||
/// <returns>復号に成功した場合 true</returns>
|
||||
public bool VerifyPassword(byte[] fileBytes, string password, out string plainText)
|
||||
{
|
||||
plainText = string.Empty;
|
||||
var plain = TryDecrypt(fileBytes, password);
|
||||
if (plain == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
plainText = plain;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の AES-128-CBC 形式で復号を試みます。
|
||||
/// ファイル先頭 16 バイトを IV、残りを暗号文として扱い、鍵はパスワード UTF-8 の先頭 16 バイトをゼロ埋めします。
|
||||
/// </summary>
|
||||
/// <param name="fileBytes">ファイル全体のバイト列</param>
|
||||
/// <param name="password">パスワード</param>
|
||||
/// <returns>復号された平文 JSON。失敗時は null</returns>
|
||||
public static string? TryDecrypt(byte[] fileBytes, string password)
|
||||
{
|
||||
if (fileBytes == null || fileBytes.Length <= AesIvLength)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var iv = new byte[AesIvLength];
|
||||
Array.Copy(fileBytes, 0, iv, 0, AesIvLength);
|
||||
|
||||
var cipher = new byte[fileBytes.Length - AesIvLength];
|
||||
Array.Copy(fileBytes, AesIvLength, cipher, 0, cipher.Length);
|
||||
|
||||
using var aes = Aes.Create();
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
aes.Key = DeriveKey(password);
|
||||
aes.IV = iv;
|
||||
|
||||
using var decryptor = aes.CreateDecryptor();
|
||||
var plain = decryptor.TransformFinalBlock(cipher, 0, cipher.Length);
|
||||
|
||||
var text = Encoding.UTF8.GetString(plain);
|
||||
return IsPlausiblePlainText(text) ? text : null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 平文バイト列を ES3 の AES-128-CBC 形式で暗号化します(IV を先頭に付与)。
|
||||
/// </summary>
|
||||
/// <param name="plainBytes">平文バイト列</param>
|
||||
/// <param name="password">パスワード</param>
|
||||
/// <returns>IV + 暗号文のバイト列</returns>
|
||||
public static byte[] Encrypt(byte[] plainBytes, string password)
|
||||
{
|
||||
using var aes = Aes.Create();
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
aes.Key = DeriveKey(password);
|
||||
aes.GenerateIV();
|
||||
|
||||
using var encryptor = aes.CreateEncryptor();
|
||||
var cipher = encryptor.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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パスワード文字列から AES-128 用の 16 バイト鍵を導出します。
|
||||
/// </summary>
|
||||
/// <param name="password">パスワード</param>
|
||||
/// <returns>16 バイトの鍵</returns>
|
||||
private static byte[] DeriveKey(string password)
|
||||
{
|
||||
var raw = Encoding.UTF8.GetBytes(password ?? string.Empty);
|
||||
var key = new byte[16];
|
||||
Array.Copy(raw, key, Math.Min(raw.Length, key.Length));
|
||||
return key;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 復号結果が ES3 の平文として妥当かを判定します。
|
||||
/// </summary>
|
||||
/// <param name="text">復号された文字列</param>
|
||||
/// <returns>妥当な場合 true</returns>
|
||||
private static bool IsPlausiblePlainText(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text) || text.Length < MinimumPlainTextLength)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var trimmed = text.TrimStart();
|
||||
if (trimmed.StartsWith('{') || trimmed.StartsWith('['))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// ES3 の内部シリアライズ形式は "__type" を必ず含む
|
||||
return text.Contains("__type", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// バイト列が平文 JSON かどうかを判定します。
|
||||
/// </summary>
|
||||
/// <param name="bytes">対象バイト列</param>
|
||||
/// <returns>平文 JSON と判断できる場合 true</returns>
|
||||
private static bool IsLikelyJson(byte[] bytes)
|
||||
{
|
||||
try
|
||||
{
|
||||
int length = Math.Min(bytes.Length, 64);
|
||||
var head = Encoding.UTF8.GetString(bytes, 0, length).TrimStart();
|
||||
return head.StartsWith('{') || head.StartsWith('[');
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// バイト列のシャノンエントロピー(bits/byte)を算出します。
|
||||
/// </summary>
|
||||
/// <param name="bytes">対象バイト列</param>
|
||||
/// <returns>エントロピー値</returns>
|
||||
private static double CalculateEntropy(byte[] bytes)
|
||||
{
|
||||
var frequency = new int[256];
|
||||
foreach (var b in bytes)
|
||||
{
|
||||
frequency[b]++;
|
||||
}
|
||||
|
||||
double entropy = 0.0;
|
||||
foreach (var count in frequency)
|
||||
{
|
||||
if (count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
double p = (double)count / bytes.Length;
|
||||
entropy -= p * Math.Log2(p);
|
||||
}
|
||||
|
||||
return entropy;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 学習キャッシュ用のキーを生成します。
|
||||
/// </summary>
|
||||
/// <param name="gameKey">ゲーム識別キー</param>
|
||||
/// <param name="saveFilePath">セーブファイルパス</param>
|
||||
/// <returns>キャッシュキー</returns>
|
||||
private string BuildCacheKey(string? gameKey, string saveFilePath)
|
||||
{
|
||||
var key = !string.IsNullOrWhiteSpace(gameKey)
|
||||
? gameKey!
|
||||
: Path.GetDirectoryName(saveFilePath) ?? string.Empty;
|
||||
|
||||
return key.Trim();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解決済みパスワードを学習キャッシュへ保存します。
|
||||
/// </summary>
|
||||
/// <param name="cacheKey">キャッシュキー</param>
|
||||
/// <param name="password">パスワード</param>
|
||||
private void Remember(string? cacheKey, string password)
|
||||
{
|
||||
if (string.IsNullOrEmpty(cacheKey))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this._store.Set(cacheKey, password);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 辞書段階で試行する候補列挙子を返します(既定候補 → ユーザー辞書の順)。
|
||||
/// </summary>
|
||||
/// <param name="userDictionaryPath">ユーザー辞書ファイルのパス</param>
|
||||
/// <param name="diagnostics">診断メッセージの追加先</param>
|
||||
/// <returns>候補の列挙</returns>
|
||||
private IEnumerable<string> EnumerateDictionaryCandidates(string? userDictionaryPath, List<string> diagnostics)
|
||||
{
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
foreach (var candidate in GetBuiltInCandidates())
|
||||
{
|
||||
if (seen.Add(candidate))
|
||||
{
|
||||
yield return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(userDictionaryPath))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (!File.Exists(userDictionaryPath))
|
||||
{
|
||||
diagnostics.Add($"ユーザー辞書が見つかりません: {userDictionaryPath}");
|
||||
yield break;
|
||||
}
|
||||
|
||||
string[] lines;
|
||||
try
|
||||
{
|
||||
lines = File.ReadAllLines(userDictionaryPath, Encoding.UTF8);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
diagnostics.Add($"ユーザー辞書の読み込みに失敗しました: {ex.Message}");
|
||||
yield break;
|
||||
}
|
||||
|
||||
diagnostics.Add($"ユーザー辞書を適用します({lines.Length} 行): {userDictionaryPath}");
|
||||
|
||||
foreach (var line in lines)
|
||||
{
|
||||
var candidate = line.Trim();
|
||||
if (candidate.Length == 0 || candidate.StartsWith('#'))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (seen.Add(candidate))
|
||||
{
|
||||
yield return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Easy Save 3 でよく使われる既定のパスワード候補を返します。
|
||||
/// </summary>
|
||||
/// <returns>既定候補の並び</returns>
|
||||
private static IEnumerable<string> GetBuiltInCandidates()
|
||||
{
|
||||
// 空文字(パスワード未設定のまま暗号化されたケース)を最初に試す
|
||||
yield return string.Empty;
|
||||
yield return "password";
|
||||
yield return "Password";
|
||||
yield return "PASSWORD";
|
||||
yield return "Moodkie";
|
||||
yield return "moodkie";
|
||||
yield return "EasySave";
|
||||
yield return "easysave";
|
||||
yield return "EasySave3";
|
||||
yield return "es3";
|
||||
yield return "ES3";
|
||||
yield return "SaveData";
|
||||
yield return "savedata";
|
||||
yield return "Save";
|
||||
yield return "save";
|
||||
yield return "secret";
|
||||
yield return "Secret";
|
||||
yield return "123456";
|
||||
yield return "1234567890";
|
||||
yield return "admin";
|
||||
yield return "test";
|
||||
yield return "game";
|
||||
yield return "Game";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 診断ログ用にパスワードをマスクします(先頭 2 文字のみ残す)。
|
||||
/// </summary>
|
||||
/// <param name="password">パスワード</param>
|
||||
/// <returns>マスク済み文字列</returns>
|
||||
private static string Mask(string password)
|
||||
{
|
||||
if (string.IsNullOrEmpty(password))
|
||||
{
|
||||
return "(空)";
|
||||
}
|
||||
|
||||
if (password.Length <= 2)
|
||||
{
|
||||
return new string('*', password.Length);
|
||||
}
|
||||
|
||||
return password[..2] + new string('*', Math.Min(password.Length - 2, 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using GameLauncher.Helpers;
|
||||
|
||||
namespace GameLauncher.Services.Codecs.Es3
|
||||
{
|
||||
/// <summary>
|
||||
/// ES3 のパスワード特定結果を「ゲーム単位」で永続化する学習キャッシュ。
|
||||
///
|
||||
/// 一度解決したパスワードを保存しておくことで、次回以降は自動適用できます。
|
||||
/// 保存先は exe 直下の <c>es3-passwords.json</c> で、キャッシュ破棄やブックマークとは独立に管理します。
|
||||
/// </summary>
|
||||
public sealed class Es3PasswordStore
|
||||
{
|
||||
/// <summary>永続化ファイル名。</summary>
|
||||
private const string FileName = "es3-passwords.json";
|
||||
|
||||
/// <summary>既定のシングルトンインスタンス。</summary>
|
||||
public static Es3PasswordStore Instance { get; } = new();
|
||||
|
||||
private readonly object _syncRoot = new();
|
||||
private readonly string _filePath;
|
||||
private Dictionary<string, string>? _entries;
|
||||
|
||||
/// <summary>
|
||||
/// exe 直下の既定パスを用いて <see cref="Es3PasswordStore"/> を初期化します。
|
||||
/// </summary>
|
||||
public Es3PasswordStore()
|
||||
: this(Path.Combine(AppPathHelper.GetExeDirectory(), FileName))
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 任意のファイルパスを指定して <see cref="Es3PasswordStore"/> を初期化します(テスト用途を含む)。
|
||||
/// </summary>
|
||||
/// <param name="filePath">永続化ファイルの絶対パス</param>
|
||||
public Es3PasswordStore(string filePath)
|
||||
{
|
||||
this._filePath = filePath;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 永続化ファイルのパスを取得します。
|
||||
/// </summary>
|
||||
public string FilePath => this._filePath;
|
||||
|
||||
/// <summary>
|
||||
/// 指定キーに対応する学習済みパスワードを取得します。
|
||||
/// </summary>
|
||||
/// <param name="key">ゲーム単位のキー(通常はゲームのルートディレクトリ)</param>
|
||||
/// <returns>保存済みパスワード。未登録の場合は null</returns>
|
||||
public string? TryGet(string key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
lock (this._syncRoot)
|
||||
{
|
||||
var entries = this.LoadEntries();
|
||||
return entries.TryGetValue(Normalize(key), out var password) ? password : null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 学習済みパスワードを保存します。
|
||||
/// </summary>
|
||||
/// <param name="key">ゲーム単位のキー</param>
|
||||
/// <param name="password">保存するパスワード(空文字も有効な値として保存します)</param>
|
||||
public void Set(string key, string password)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (this._syncRoot)
|
||||
{
|
||||
var entries = this.LoadEntries();
|
||||
entries[Normalize(key)] = password ?? string.Empty;
|
||||
this.SaveEntries(entries);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定キーの学習済みパスワードを削除します。
|
||||
/// </summary>
|
||||
/// <param name="key">ゲーム単位のキー</param>
|
||||
/// <returns>削除できた場合 true</returns>
|
||||
public bool Remove(string key)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (this._syncRoot)
|
||||
{
|
||||
var entries = this.LoadEntries();
|
||||
if (!entries.Remove(Normalize(key)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
this.SaveEntries(entries);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存済みエントリのスナップショットを取得します(表示・診断用)。
|
||||
/// </summary>
|
||||
/// <returns>キーとパスワードの読み取り専用ディクショナリ</returns>
|
||||
public IReadOnlyDictionary<string, string> Snapshot()
|
||||
{
|
||||
lock (this._syncRoot)
|
||||
{
|
||||
return new Dictionary<string, string>(this.LoadEntries(), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 永続化ファイルを読み込みます。壊れている場合は空のディクショナリを返します。
|
||||
/// </summary>
|
||||
/// <returns>読み込んだエントリ</returns>
|
||||
private Dictionary<string, string> LoadEntries()
|
||||
{
|
||||
if (this._entries != null)
|
||||
{
|
||||
return this._entries;
|
||||
}
|
||||
|
||||
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
try
|
||||
{
|
||||
if (File.Exists(this._filePath))
|
||||
{
|
||||
var json = File.ReadAllText(this._filePath, Encoding.UTF8);
|
||||
if (!string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
var loaded = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
|
||||
if (loaded != null)
|
||||
{
|
||||
foreach (var kvp in loaded)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(kvp.Key))
|
||||
{
|
||||
result[Normalize(kvp.Key)] = kvp.Value ?? string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 破損ファイルは無視し、空の状態から再構築する
|
||||
result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
this._entries = result;
|
||||
return this._entries;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// エントリを永続化ファイルへ書き出します。
|
||||
/// </summary>
|
||||
/// <param name="entries">書き出すエントリ</param>
|
||||
private void SaveEntries(Dictionary<string, string> entries)
|
||||
{
|
||||
try
|
||||
{
|
||||
var directory = Path.GetDirectoryName(this._filePath);
|
||||
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
var options = new JsonSerializerOptions { WriteIndented = true };
|
||||
var json = JsonSerializer.Serialize(entries, options);
|
||||
|
||||
// BOM なし UTF-8 で保存する
|
||||
File.WriteAllText(this._filePath, json, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 保存失敗は致命的ではないため握りつぶす(次回再度解決を試みる)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// キーを比較用に正規化します(パス区切りと大文字小文字の揺れを吸収)。
|
||||
/// </summary>
|
||||
/// <param name="key">元のキー</param>
|
||||
/// <returns>正規化済みキー</returns>
|
||||
private static string Normalize(string key)
|
||||
{
|
||||
var trimmed = key.Trim();
|
||||
try
|
||||
{
|
||||
return Path.GetFullPath(trimmed).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,891 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace GameLauncher.Services.Codecs.Es3
|
||||
{
|
||||
/// <summary>
|
||||
/// ES3 のシリアライズ要素が持つ「型」の種別。
|
||||
/// ES3 は <c>{ "__type": "System.Int32", "value": 42 }</c> 形式で値を格納するため、
|
||||
/// この列挙子で GUI 側へ型情報を伝えます。
|
||||
/// </summary>
|
||||
public enum Es3ValueKind
|
||||
{
|
||||
/// <summary>不明・未判定。</summary>
|
||||
Unknown,
|
||||
|
||||
/// <summary>真偽値。</summary>
|
||||
Boolean,
|
||||
|
||||
/// <summary>整数(Int32 / Int64 / UInt32 等)。</summary>
|
||||
Integer,
|
||||
|
||||
/// <summary>浮動小数(Single / Double / Decimal)。</summary>
|
||||
Float,
|
||||
|
||||
/// <summary>文字列。</summary>
|
||||
String,
|
||||
|
||||
/// <summary>列挙体。</summary>
|
||||
Enum,
|
||||
|
||||
/// <summary>配列。</summary>
|
||||
Array,
|
||||
|
||||
/// <summary>辞書(キーと値の組)。</summary>
|
||||
Dictionary,
|
||||
|
||||
/// <summary>入れ子オブジェクト。</summary>
|
||||
Object
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 ファイル内の 1 項目を表す型付きノード。
|
||||
/// JSON ツリー上の位置(<see cref="Path"/>)を保持するため、編集後の書き戻しが安全に行えます。
|
||||
/// </summary>
|
||||
public sealed class Es3Node
|
||||
{
|
||||
/// <summary>キー名(辞書・オブジェクトの子の場合)。</summary>
|
||||
public string Key { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>親をたどる JSON パス(例: <c>$.player.stats.hp</c>)。</summary>
|
||||
public string Path { get; set; } = "$";
|
||||
|
||||
/// <summary>ES3 が示す型名(例: <c>System.Int32</c>、<c>System.Collections.Generic.List`1</c>)。</summary>
|
||||
public string TypeName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>判定した値種別。</summary>
|
||||
public Es3ValueKind Kind { get; set; } = Es3ValueKind.Unknown;
|
||||
|
||||
/// <summary>現在の値(文字列化した表示・編集用の値)。</summary>
|
||||
public string DisplayValue { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>元の JSON 値(書き戻し時の型再現に使用)。</summary>
|
||||
public JsonNode? OriginalNode { get; set; }
|
||||
|
||||
/// <summary>配列・辞書・オブジェクトの場合の子要素。</summary>
|
||||
public List<Es3Node> Children { get; } = [];
|
||||
|
||||
/// <summary>子要素を持つか。</summary>
|
||||
public bool HasChildren => this.Children.Count > 0;
|
||||
|
||||
/// <summary>エディタで直接値を編集できる型か。</summary>
|
||||
public bool IsEditable => this.Kind is Es3ValueKind.Boolean
|
||||
or Es3ValueKind.Integer
|
||||
or Es3ValueKind.Float
|
||||
or Es3ValueKind.String
|
||||
or Es3ValueKind.Enum;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 (Easy Save 3) のセーブデータ本体(復号後の JSON)を解析し、
|
||||
/// キー名・型・値を読み取るとともに、編集結果を安全に書き戻すパーサ/ライタ。
|
||||
///
|
||||
/// ES3 の内部形式は次の 2 通りが混在します:
|
||||
/// <c>{ "key": { "__type": "System.Int32", "value": 100 } }</c>
|
||||
/// <c>{ "key": { "__type": "System.Collections.Generic.Dictionary`2[...]", "value": { ... } } }</c>
|
||||
/// 本クラスは両形式を展開し、編集後は元の型情報を保持したまま再構築します。
|
||||
/// </summary>
|
||||
public sealed class Es3SaveDocument
|
||||
{
|
||||
/// <summary>ES3 が型情報を格納するプロパティ名。</summary>
|
||||
public const string TypePropertyName = "__type";
|
||||
|
||||
/// <summary>ES3 が値を格納するプロパティ名。</summary>
|
||||
public const string ValuePropertyName = "value";
|
||||
|
||||
/// <summary>解析対象のルート JSON オブジェクト(編集はこのインスタンスを直接書き換えます)。</summary>
|
||||
private JsonNode? _root;
|
||||
|
||||
/// <summary>復号直後の JSON 文字列(差分検出・バックアップ用)。</summary>
|
||||
public string OriginalJson { get; private set; } = string.Empty;
|
||||
|
||||
/// <summary>解析に成功したか。</summary>
|
||||
public bool IsLoaded => this._root != null;
|
||||
|
||||
/// <summary>解析時の警告(解釈できなかった要素など)。</summary>
|
||||
public List<string> Warnings { get; } = [];
|
||||
|
||||
/// <summary>ルート直下の項目一覧。</summary>
|
||||
public List<Es3Node> RootNodes { get; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の平文 JSON 文字列を解析してドキュメントを構築します。
|
||||
/// </summary>
|
||||
/// <param name="json">復号済みの平文 JSON</param>
|
||||
/// <returns>解析されたドキュメント</returns>
|
||||
public static Es3SaveDocument Parse(string json)
|
||||
{
|
||||
var document = new Es3SaveDocument { OriginalJson = json ?? string.Empty };
|
||||
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
{
|
||||
document.Warnings.Add("平文 JSON が空です。");
|
||||
return document;
|
||||
}
|
||||
|
||||
JsonNode? root;
|
||||
try
|
||||
{
|
||||
root = JsonNode.Parse(json, documentOptions: new JsonDocumentOptions
|
||||
{
|
||||
AllowTrailingCommas = true,
|
||||
CommentHandling = JsonCommentHandling.Skip,
|
||||
MaxDepth = 256
|
||||
});
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
document.Warnings.Add($"JSON 解析に失敗しました: {ex.Message}");
|
||||
return document;
|
||||
}
|
||||
|
||||
if (root == null)
|
||||
{
|
||||
document.Warnings.Add("JSON のルートが null です。");
|
||||
return document;
|
||||
}
|
||||
|
||||
document._root = root;
|
||||
document.BuildTree(root, "$", string.Empty);
|
||||
return document;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析ツリーを走査してルート直下の項目一覧を構築します。
|
||||
/// </summary>
|
||||
/// <param name="root">JSON ルート</param>
|
||||
/// <param name="path">ルートパス</param>
|
||||
/// <param name="key">キー名</param>
|
||||
private void BuildTree(JsonNode root, string path, string key)
|
||||
{
|
||||
if (root is JsonObject rootObject)
|
||||
{
|
||||
foreach (var kvp in rootObject)
|
||||
{
|
||||
var childPath = $"{path}.{kvp.Key}";
|
||||
var node = this.CreateNode(kvp.Key, childPath, kvp.Value);
|
||||
if (node != null)
|
||||
{
|
||||
this.RootNodes.Add(node);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (root is JsonArray rootArray)
|
||||
{
|
||||
for (int i = 0; i < rootArray.Count; i++)
|
||||
{
|
||||
var childPath = $"{path}[{i}]";
|
||||
var node = this.CreateNode($"[{i}]", childPath, rootArray[i]);
|
||||
if (node != null)
|
||||
{
|
||||
this.RootNodes.Add(node);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.Warnings.Add($"ルート要素を解釈できませんでした({root.GetValueKind()})。");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSON ノードから型付きの <see cref="Es3Node"/> を生成します。
|
||||
/// </summary>
|
||||
/// <param name="key">キー名</param>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <param name="node">対象ノード</param>
|
||||
/// <returns>生成されたノード。解釈不能な場合は null</returns>
|
||||
private Es3Node? CreateNode(string key, string path, JsonNode? node)
|
||||
{
|
||||
var result = new Es3Node
|
||||
{
|
||||
Key = key,
|
||||
Path = path,
|
||||
OriginalNode = node
|
||||
};
|
||||
|
||||
if (node == null)
|
||||
{
|
||||
result.Kind = Es3ValueKind.Unknown;
|
||||
result.DisplayValue = "null";
|
||||
return result;
|
||||
}
|
||||
|
||||
switch (node.GetValueKind())
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
this.PopulateObject(result, path, node.AsObject());
|
||||
return result;
|
||||
|
||||
case JsonValueKind.Array:
|
||||
result.Kind = Es3ValueKind.Array;
|
||||
result.TypeName = "System.Array";
|
||||
PopulateArray(result, path, node.AsArray());
|
||||
return result;
|
||||
|
||||
case JsonValueKind.String:
|
||||
result.Kind = Es3ValueKind.String;
|
||||
result.TypeName = "System.String";
|
||||
result.DisplayValue = node.GetValue<string>();
|
||||
return result;
|
||||
|
||||
case JsonValueKind.Number:
|
||||
PopulateNumber(result, node);
|
||||
return result;
|
||||
|
||||
case JsonValueKind.True:
|
||||
case JsonValueKind.False:
|
||||
result.Kind = Es3ValueKind.Boolean;
|
||||
result.TypeName = "System.Boolean";
|
||||
result.DisplayValue = node.GetValue<bool>() ? "true" : "false";
|
||||
return result;
|
||||
|
||||
case JsonValueKind.Null:
|
||||
result.Kind = Es3ValueKind.Unknown;
|
||||
result.DisplayValue = "null";
|
||||
return result;
|
||||
|
||||
default:
|
||||
result.Kind = Es3ValueKind.Unknown;
|
||||
result.DisplayValue = node.ToJsonString();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSON オブジェクトが ES3 の型付き要素か、単なる入れ子オブジェクトかを判定して展開します。
|
||||
/// </summary>
|
||||
/// <param name="target">構築対象のノード</param>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <param name="jsonObject">対象の JSON オブジェクト</param>
|
||||
private void PopulateObject(Es3Node target, string path, JsonObject jsonObject)
|
||||
{
|
||||
// ES3 の型付き要素(__type と value を持つ)か判定
|
||||
bool isTyped = jsonObject.ContainsKey(TypePropertyName);
|
||||
|
||||
if (isTyped)
|
||||
{
|
||||
target.TypeName = jsonObject[TypePropertyName]?.GetValue<string>() ?? string.Empty;
|
||||
var inner = jsonObject[ValuePropertyName];
|
||||
|
||||
if (inner == null)
|
||||
{
|
||||
target.Kind = MapTypeNameToKind(target.TypeName);
|
||||
target.DisplayValue = "null";
|
||||
return;
|
||||
}
|
||||
|
||||
var innerKind = inner.GetValueKind();
|
||||
|
||||
if (innerKind == JsonValueKind.Object)
|
||||
{
|
||||
// 辞書・入れ子オブジェクト
|
||||
var innerObject = inner.AsObject();
|
||||
target.Kind = LooksLikeDictionary(innerObject, target.TypeName)
|
||||
? Es3ValueKind.Dictionary
|
||||
: Es3ValueKind.Object;
|
||||
|
||||
foreach (var kvp in innerObject)
|
||||
{
|
||||
var childPath = $"{path}.{kvp.Key}";
|
||||
var child = this.CreateNode(kvp.Key, childPath, kvp.Value);
|
||||
if (child != null)
|
||||
{
|
||||
target.Children.Add(child);
|
||||
}
|
||||
}
|
||||
|
||||
target.DisplayValue = $"({target.Children.Count} 項目)";
|
||||
return;
|
||||
}
|
||||
|
||||
if (innerKind == JsonValueKind.Array)
|
||||
{
|
||||
target.Kind = Es3ValueKind.Array;
|
||||
PopulateArray(target, path, inner.AsArray());
|
||||
return;
|
||||
}
|
||||
|
||||
// プリミティブ値
|
||||
target.Kind = MapTypeNameToKind(target.TypeName);
|
||||
target.DisplayValue = FormatScalar(inner, target.Kind);
|
||||
return;
|
||||
}
|
||||
|
||||
// 型情報なしの入れ子オブジェクト
|
||||
target.Kind = Es3ValueKind.Object;
|
||||
target.TypeName = "System.Object";
|
||||
|
||||
foreach (var kvp in jsonObject)
|
||||
{
|
||||
var childPath = $"{path}.{kvp.Key}";
|
||||
var child = this.CreateNode(kvp.Key, childPath, kvp.Value);
|
||||
if (child != null)
|
||||
{
|
||||
target.Children.Add(child);
|
||||
}
|
||||
}
|
||||
|
||||
target.DisplayValue = $"({target.Children.Count} 項目)";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 配列を走査して子要素を追加します。
|
||||
/// </summary>
|
||||
/// <param name="target">構築対象のノード</param>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <param name="array">対象の JSON 配列</param>
|
||||
private static void PopulateArray(Es3Node target, string path, JsonArray array)
|
||||
{
|
||||
for (int i = 0; i < array.Count; i++)
|
||||
{
|
||||
var childPath = $"{path}[{i}]";
|
||||
var elementNode = array[i];
|
||||
|
||||
var child = new Es3Node
|
||||
{
|
||||
Key = $"[{i}]",
|
||||
Path = childPath,
|
||||
OriginalNode = elementNode
|
||||
};
|
||||
|
||||
if (elementNode == null)
|
||||
{
|
||||
child.Kind = Es3ValueKind.Unknown;
|
||||
child.DisplayValue = "null";
|
||||
}
|
||||
else if (elementNode.GetValueKind() == JsonValueKind.Object &&
|
||||
elementNode.AsObject().ContainsKey(TypePropertyName))
|
||||
{
|
||||
// 配列要素が型付き要素の場合は再帰的に展開する
|
||||
var innerObject = elementNode.AsObject();
|
||||
child.TypeName = innerObject[TypePropertyName]?.GetValue<string>() ?? string.Empty;
|
||||
var inner = innerObject[ValuePropertyName];
|
||||
|
||||
if (inner != null && inner.GetValueKind() == JsonValueKind.Object)
|
||||
{
|
||||
child.Kind = Es3ValueKind.Object;
|
||||
foreach (var kvp in inner.AsObject())
|
||||
{
|
||||
var grandChild = new Es3Node
|
||||
{
|
||||
Key = kvp.Key,
|
||||
Path = $"{childPath}.{kvp.Key}",
|
||||
OriginalNode = kvp.Value,
|
||||
Kind = MapValueKind(kvp.Value),
|
||||
DisplayValue = FormatScalar(kvp.Value, MapValueKind(kvp.Value))
|
||||
};
|
||||
child.Children.Add(grandChild);
|
||||
}
|
||||
|
||||
child.DisplayValue = $"({child.Children.Count} 項目)";
|
||||
}
|
||||
else
|
||||
{
|
||||
child.Kind = MapTypeNameToKind(child.TypeName);
|
||||
child.DisplayValue = inner == null ? "null" : FormatScalar(inner, child.Kind);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
child.Kind = MapValueKind(elementNode);
|
||||
child.DisplayValue = FormatScalar(elementNode, child.Kind);
|
||||
}
|
||||
|
||||
target.Children.Add(child);
|
||||
}
|
||||
|
||||
target.DisplayValue = $"({target.Children.Count} 件)";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数値ノードの型情報と表示値を設定します。
|
||||
/// </summary>
|
||||
/// <param name="target">構築対象のノード</param>
|
||||
/// <param name="node">数値ノード</param>
|
||||
private void PopulateNumber(Es3Node target, JsonNode node)
|
||||
{
|
||||
var raw = node.ToJsonString();
|
||||
|
||||
if (raw.Contains('.') || raw.Contains('e', StringComparison.OrdinalIgnoreCase) &&
|
||||
!raw.Contains("0x", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
target.Kind = Es3ValueKind.Float;
|
||||
target.TypeName = "System.Single";
|
||||
}
|
||||
else
|
||||
{
|
||||
target.Kind = Es3ValueKind.Integer;
|
||||
target.TypeName = "System.Int32";
|
||||
}
|
||||
|
||||
target.DisplayValue = raw;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ES3 の型名から値種別を推定します。
|
||||
/// </summary>
|
||||
/// <param name="typeName">ES3 の型名</param>
|
||||
/// <returns>推定した値種別</returns>
|
||||
public static Es3ValueKind MapTypeNameToKind(string typeName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(typeName))
|
||||
{
|
||||
return Es3ValueKind.Unknown;
|
||||
}
|
||||
|
||||
var normalized = typeName.Replace(" ", string.Empty);
|
||||
|
||||
if (normalized.Contains("System.Boolean", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Boolean;
|
||||
}
|
||||
|
||||
if (normalized.Contains("System.Single", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Double", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Decimal", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Float;
|
||||
}
|
||||
|
||||
if (normalized.Contains("System.Int", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.UInt", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Byte", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Int64", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Int16", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Integer;
|
||||
}
|
||||
|
||||
if (normalized.Contains("System.String", StringComparison.Ordinal) ||
|
||||
normalized.Contains("System.Char", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.String;
|
||||
}
|
||||
|
||||
if (normalized.Contains("Dictionary", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Dictionary;
|
||||
}
|
||||
|
||||
if (normalized.Contains("[]", StringComparison.Ordinal) ||
|
||||
normalized.Contains("List`1", StringComparison.Ordinal) ||
|
||||
normalized.Contains("HashSet", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Array;
|
||||
}
|
||||
|
||||
if (normalized.Contains("System.Enum", StringComparison.Ordinal))
|
||||
{
|
||||
return Es3ValueKind.Enum;
|
||||
}
|
||||
|
||||
return Es3ValueKind.Object;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 辞書形式(キーと値の組)かどうかを推定します。
|
||||
/// </summary>
|
||||
/// <param name="jsonObject">対象オブジェクト</param>
|
||||
/// <param name="typeName">型名</param>
|
||||
/// <returns>辞書と判断できる場合 true</returns>
|
||||
private static bool LooksLikeDictionary(JsonObject jsonObject, string typeName)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(typeName) &&
|
||||
typeName.Contains("Dictionary", StringComparison.Ordinal))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// ES3 の辞書は {"key": "...", "value": ...} の対を持つ
|
||||
return jsonObject.ContainsKey("key") && jsonObject.ContainsKey(ValuePropertyName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// JSON 値の種別を簡易判定します。
|
||||
/// </summary>
|
||||
/// <param name="node">対象ノード</param>
|
||||
/// <returns>判定した値種別</returns>
|
||||
private static Es3ValueKind MapValueKind(JsonNode? node)
|
||||
{
|
||||
if (node == null)
|
||||
{
|
||||
return Es3ValueKind.Unknown;
|
||||
}
|
||||
|
||||
return node.GetValueKind() switch
|
||||
{
|
||||
JsonValueKind.Object => Es3ValueKind.Object,
|
||||
JsonValueKind.Array => Es3ValueKind.Array,
|
||||
JsonValueKind.String => Es3ValueKind.String,
|
||||
JsonValueKind.Number => node.ToJsonString().Contains('.')
|
||||
? Es3ValueKind.Float
|
||||
: Es3ValueKind.Integer,
|
||||
JsonValueKind.True or JsonValueKind.False => Es3ValueKind.Boolean,
|
||||
_ => Es3ValueKind.Unknown
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// スカラー値を表示用文字列へ整形します。
|
||||
/// </summary>
|
||||
/// <param name="node">対象ノード</param>
|
||||
/// <param name="kind">値種別</param>
|
||||
/// <returns>表示用文字列</returns>
|
||||
private static string FormatScalar(JsonNode? node, Es3ValueKind kind)
|
||||
{
|
||||
if (node == null)
|
||||
{
|
||||
return "null";
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return kind switch
|
||||
{
|
||||
Es3ValueKind.Boolean => node.GetValue<bool>() ? "true" : "false",
|
||||
Es3ValueKind.String => node.GetValue<string>(),
|
||||
Es3ValueKind.Enum => node.GetValueKind() == JsonValueKind.Number
|
||||
? node.ToJsonString()
|
||||
: node.GetValue<string>(),
|
||||
_ => node.ToJsonString()
|
||||
};
|
||||
}
|
||||
catch
|
||||
{
|
||||
return node.ToJsonString();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定パスのノードへ編集値を適用します。
|
||||
/// </summary>
|
||||
/// <param name="path">JSON パス(<see cref="Es3Node.Path"/>)</param>
|
||||
/// <param name="newValue">新しい値(表示文字列)</param>
|
||||
/// <param name="error">失敗理由</param>
|
||||
/// <returns>適用に成功した場合 true</returns>
|
||||
public bool TrySetValue(string path, string newValue, out string error)
|
||||
{
|
||||
error = string.Empty;
|
||||
|
||||
if (this._root == null)
|
||||
{
|
||||
error = "ドキュメントが読み込まれていません。";
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!this.TryResolveParent(path, out var parent, out var key, out error))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 既存ノードから型情報を取得
|
||||
var existing = this.FindNode(path);
|
||||
var kind = existing?.Kind ?? Es3ValueKind.String;
|
||||
var typeName = existing?.TypeName ?? "System.String";
|
||||
|
||||
if (existing != null && !existing.IsEditable)
|
||||
{
|
||||
error = $"型 {typeName} は直接編集できません。";
|
||||
return false;
|
||||
}
|
||||
|
||||
JsonNode? parsed = this.BuildValueNode(newValue, kind, typeName, out error);
|
||||
if (parsed == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// ES3 の型付き要素として書き戻す
|
||||
if (parent is JsonObject parentObject && parentObject.ContainsKey(TypePropertyName))
|
||||
{
|
||||
parentObject[ValuePropertyName] = parsed;
|
||||
}
|
||||
else if (parent is JsonObject plainObject)
|
||||
{
|
||||
plainObject[key] = parsed;
|
||||
}
|
||||
else if (parent is JsonArray array && int.TryParse(key, out int index) &&
|
||||
index >= 0 && index < array.Count)
|
||||
{
|
||||
array[index] = parsed;
|
||||
}
|
||||
else
|
||||
{
|
||||
error = "書き戻し先の親要素を特定できませんでした。";
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = $"書き戻しに失敗しました: {ex.Message}";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 編集後の JSON を文字列として取得します。
|
||||
/// </summary>
|
||||
/// <returns>整形済み JSON 文字列</returns>
|
||||
public string ToJson()
|
||||
{
|
||||
if (this._root == null)
|
||||
{
|
||||
return this.OriginalJson;
|
||||
}
|
||||
|
||||
return this._root.ToJsonString(new JsonSerializerOptions { WriteIndented = false });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 元の JSON から変更があったかを判定します。
|
||||
/// </summary>
|
||||
/// <returns>変更がある場合 true</returns>
|
||||
public bool HasChanges()
|
||||
{
|
||||
if (this._root == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return !string.Equals(this.ToJson(), this.OriginalJson, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パスから親ノードと最終キーを解決します。
|
||||
/// </summary>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <param name="parent">親ノード</param>
|
||||
/// <param name="key">最終キー(配列の場合はインデックス文字列)</param>
|
||||
/// <param name="error">失敗理由</param>
|
||||
/// <returns>解決に成功した場合 true</returns>
|
||||
private bool TryResolveParent(string path, out JsonNode? parent, out string key, out string error)
|
||||
{
|
||||
parent = null;
|
||||
key = string.Empty;
|
||||
error = string.Empty;
|
||||
|
||||
if (path == "$")
|
||||
{
|
||||
error = "ルート要素は編集できません。";
|
||||
return false;
|
||||
}
|
||||
|
||||
var segments = SplitPath(path);
|
||||
if (segments.Count < 2)
|
||||
{
|
||||
error = $"パスの解析に失敗しました: {path}";
|
||||
return false;
|
||||
}
|
||||
|
||||
JsonNode? current = this._root;
|
||||
|
||||
for (int i = 1; i < segments.Count - 1; i++)
|
||||
{
|
||||
if (current == null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
current = Descend(current, segments[i], out _);
|
||||
}
|
||||
|
||||
if (current == null)
|
||||
{
|
||||
error = $"パス {path} を解決できませんでした。";
|
||||
return false;
|
||||
}
|
||||
|
||||
key = segments[^1];
|
||||
parent = current;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// パス文字列をセグメントへ分割します。
|
||||
/// </summary>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <returns>セグメント一覧(先頭は "$")</returns>
|
||||
private static List<string> SplitPath(string path)
|
||||
{
|
||||
var segments = new List<string>();
|
||||
var buffer = new StringBuilder();
|
||||
|
||||
foreach (var ch in path)
|
||||
{
|
||||
if (ch == '.' || ch == '[' || ch == ']')
|
||||
{
|
||||
if (buffer.Length > 0)
|
||||
{
|
||||
segments.Add(buffer.ToString());
|
||||
buffer.Clear();
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
buffer.Append(ch);
|
||||
}
|
||||
|
||||
if (buffer.Length > 0)
|
||||
{
|
||||
segments.Add(buffer.ToString());
|
||||
}
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定キーで子要素へ降下します(ES3 の型付き要素は value を透過します)。
|
||||
/// </summary>
|
||||
/// <param name="current">現在のノード</param>
|
||||
/// <param name="key">キー</param>
|
||||
/// <param name="found">見つかった子ノード</param>
|
||||
/// <returns>降下先ノード。見つからない場合は null</returns>
|
||||
private static JsonNode? Descend(JsonNode current, string key, out JsonNode? found)
|
||||
{
|
||||
found = null;
|
||||
|
||||
if (current is JsonObject obj)
|
||||
{
|
||||
// ES3 の型付き要素は value の中身を透過的に扱う
|
||||
if (obj.ContainsKey(TypePropertyName) && obj[ValuePropertyName] is JsonNode inner)
|
||||
{
|
||||
return Descend(inner, key, out found);
|
||||
}
|
||||
|
||||
if (obj.TryGetPropertyValue(key, out var child))
|
||||
{
|
||||
found = child;
|
||||
return child;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if (current is JsonArray array && int.TryParse(key, out int index) &&
|
||||
index >= 0 && index < array.Count)
|
||||
{
|
||||
found = array[index];
|
||||
return array[index];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定パスに対応するノードを探索します。
|
||||
/// </summary>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <returns>見つかったノード。見つからない場合は null</returns>
|
||||
private Es3Node? FindNode(string path)
|
||||
{
|
||||
return FindNodeRecursive(this.RootNodes, path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ノードツリーを再帰的に探索します。
|
||||
/// </summary>
|
||||
/// <param name="nodes">探索対象</param>
|
||||
/// <param name="path">JSON パス</param>
|
||||
/// <returns>見つかったノード</returns>
|
||||
private static Es3Node? FindNodeRecursive(List<Es3Node> nodes, string path)
|
||||
{
|
||||
foreach (var node in nodes)
|
||||
{
|
||||
if (node.Path == path)
|
||||
{
|
||||
return node;
|
||||
}
|
||||
|
||||
var found = FindNodeRecursive(node.Children, path);
|
||||
if (found != null)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 編集値から実際の JSON ノードを構築します。
|
||||
/// </summary>
|
||||
/// <param name="newValue">編集された値文字列</param>
|
||||
/// <param name="kind">型種別</param>
|
||||
/// <param name="typeName">ES3 の型名</param>
|
||||
/// <param name="error">失敗理由</param>
|
||||
/// <returns>構築された JSON ノード。失敗時は null</returns>
|
||||
private JsonNode? BuildValueNode(string newValue, Es3ValueKind kind, string typeName, out string error)
|
||||
{
|
||||
error = string.Empty;
|
||||
|
||||
switch (kind)
|
||||
{
|
||||
case Es3ValueKind.Boolean:
|
||||
if (bool.TryParse(newValue, out var boolValue))
|
||||
{
|
||||
return JsonValue.Create(boolValue);
|
||||
}
|
||||
|
||||
if (newValue.Trim() == "1")
|
||||
{
|
||||
return JsonValue.Create(true);
|
||||
}
|
||||
|
||||
if (newValue.Trim() == "0")
|
||||
{
|
||||
return JsonValue.Create(false);
|
||||
}
|
||||
|
||||
error = $"真偽値として解釈できません: {newValue}";
|
||||
return null;
|
||||
|
||||
case Es3ValueKind.Integer:
|
||||
if (long.TryParse(newValue.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var longValue))
|
||||
{
|
||||
return JsonValue.Create(longValue);
|
||||
}
|
||||
|
||||
error = $"整数として解釈できません: {newValue}";
|
||||
return null;
|
||||
|
||||
case Es3ValueKind.Float:
|
||||
if (double.TryParse(newValue.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var doubleValue))
|
||||
{
|
||||
return JsonValue.Create(doubleValue);
|
||||
}
|
||||
|
||||
error = $"小数として解釈できません: {newValue}";
|
||||
return null;
|
||||
|
||||
case Es3ValueKind.Enum:
|
||||
// 列挙体は元が数値なら数値、文字列なら文字列として保持する
|
||||
if (long.TryParse(newValue.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var enumNumeric))
|
||||
{
|
||||
return JsonValue.Create(enumNumeric);
|
||||
}
|
||||
|
||||
return JsonValue.Create(newValue);
|
||||
|
||||
case Es3ValueKind.String:
|
||||
return JsonValue.Create(newValue);
|
||||
|
||||
default:
|
||||
error = $"型 {typeName} は直接編集できません。";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+407
-80
@@ -22,6 +22,7 @@ using GameLauncher.Engines.Tyrano;
|
||||
using GameLauncher.Engines.Wolf;
|
||||
using GameLauncher.Engines.Unity;
|
||||
using GameLauncher.Engines.Nwjs;
|
||||
using GameLauncher.Engines.Bakin;
|
||||
using GameLauncher.Engines.Common;
|
||||
using GameLauncher.Engines.Evb;
|
||||
|
||||
@@ -66,6 +67,8 @@ namespace GameLauncher.Services
|
||||
public string? RgssArchivePath { get; set; }
|
||||
public bool HasWolfArchive { get; set; }
|
||||
public bool IsWolfExtracted { get; set; }
|
||||
public bool MzPixiErrorFix { get; set; } = true;
|
||||
public bool MzSpineErrorFix { get; set; } = true;
|
||||
public bool WolfProxyDll { get; set; }
|
||||
public double WolfSpeedMultiplier { get; set; } = 3.0;
|
||||
public bool HasSrpgArchive { get; set; }
|
||||
@@ -118,8 +121,10 @@ namespace GameLauncher.Services
|
||||
/// <summary>
|
||||
/// エンジン判定ロジックのバージョン。判定条件を変更したらこの値をインクリメントすると、
|
||||
/// 既存キャッシュは自動的に無効化され、次回起動時に再スキャンされます。
|
||||
/// v3: Unity製ゲームが「その他」として誤分類されたままキャッシュに残る問題を解消するため、
|
||||
/// Unity証拠(UnityPlayer.dll / *_Data / UnityCrashHandler*.exe)を再評価して再分類します。
|
||||
/// </summary>
|
||||
private const int CurrentEngineLogicVersion = 2;
|
||||
private const int CurrentEngineLogicVersion = 3;
|
||||
|
||||
static GameScannerService()
|
||||
{
|
||||
@@ -162,42 +167,63 @@ namespace GameLauncher.Services
|
||||
}
|
||||
if (entries != null)
|
||||
{
|
||||
bool cacheRepaired = false;
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
if (entry.EngineKind == (int)GameEngineKind.Unity)
|
||||
{
|
||||
var exePath = entry.ExecutablePath;
|
||||
if (!string.IsNullOrEmpty(exePath) && IsExcludedExe(exePath))
|
||||
{
|
||||
exePath = FindGameExecutable(entry.RootDirectory) ?? string.Empty;
|
||||
if (exePath != entry.ExecutablePath)
|
||||
{
|
||||
cacheRepaired = true;
|
||||
}
|
||||
}
|
||||
|
||||
list.Add(new UnityGameItem
|
||||
{
|
||||
Title = entry.Title,
|
||||
FolderName = entry.FolderName,
|
||||
RootDirectory = entry.RootDirectory,
|
||||
ExecutablePath = entry.ExecutablePath,
|
||||
ExecutablePath = exePath,
|
||||
DataDirectoryPath = entry.DataDirectoryPath,
|
||||
CompanyName = entry.CompanyName,
|
||||
ProductName = entry.ProductName,
|
||||
BackendType = (UnityBackendType)entry.UnityBackendType,
|
||||
UnityVersion = entry.UnityVersion,
|
||||
LastLaunched = entry.LastLaunched,
|
||||
FolderLastModified = entry.FolderLastModified,
|
||||
FolderLastModified = exePath != entry.ExecutablePath ? null : entry.FolderLastModified,
|
||||
IsBookmarked = entry.IsBookmarked,
|
||||
HasSaveData = entry.HasSaveData
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
var exePath = entry.ExecutablePath;
|
||||
if (!string.IsNullOrEmpty(exePath) && IsExcludedExe(exePath))
|
||||
{
|
||||
exePath = FindGameExecutable(entry.RootDirectory) ?? string.Empty;
|
||||
if (exePath != entry.ExecutablePath)
|
||||
{
|
||||
cacheRepaired = true;
|
||||
}
|
||||
}
|
||||
|
||||
var item = new TkoolGameItem
|
||||
{
|
||||
Title = entry.Title,
|
||||
FolderName = entry.FolderName,
|
||||
RootDirectory = entry.RootDirectory,
|
||||
ExecutablePath = entry.ExecutablePath,
|
||||
ExecutablePath = exePath,
|
||||
PluginsJsPath = entry.PluginsJsPath,
|
||||
PluginsDirPath = entry.PluginsDirPath,
|
||||
EngineType = (TkoolEngineType)entry.TkoolEngineType,
|
||||
HasCustomApplyMod = entry.HasCustomApplyMod,
|
||||
ApplyMod = entry.ApplyMod,
|
||||
LastLaunched = entry.LastLaunched,
|
||||
FolderLastModified = entry.FolderLastModified,
|
||||
FolderLastModified = exePath != entry.ExecutablePath ? null : entry.FolderLastModified,
|
||||
IsBookmarked = entry.IsBookmarked,
|
||||
IsModded = entry.IsModded,
|
||||
IsAsar = entry.IsAsar,
|
||||
@@ -210,6 +236,8 @@ namespace GameLauncher.Services
|
||||
RgssArchivePath = entry.RgssArchivePath,
|
||||
HasWolfArchive = entry.HasWolfArchive,
|
||||
IsWolfExtracted = entry.IsWolfExtracted,
|
||||
MzPixiErrorFix = entry.MzPixiErrorFix,
|
||||
MzSpineErrorFix = entry.MzSpineErrorFix,
|
||||
WolfProxyDll = entry.WolfProxyDll,
|
||||
WolfSpeedMultiplier = entry.WolfSpeedMultiplier > 0 ? entry.WolfSpeedMultiplier : 3.0,
|
||||
HasSrpgArchive = entry.HasSrpgArchive,
|
||||
@@ -223,18 +251,53 @@ namespace GameLauncher.Services
|
||||
IsEvbExtracted = entry.IsEvbExtracted,
|
||||
EvbExtractedDirPath = entry.EvbExtractedDirPath,
|
||||
EvbBackupPath = entry.EvbBackupPath,
|
||||
EvbUnderlyingEngine = entry.EvbUnderlyingEngine
|
||||
EvbUnderlyingEngine = entry.EvbUnderlyingEngine,
|
||||
HasSaveData = entry.HasSaveData
|
||||
};
|
||||
if (entry.PluginSettings != null)
|
||||
{
|
||||
item.PluginSettings = new Dictionary<string, bool>(entry.PluginSettings, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
if (item.IsOther && BakinDetector.IsBakinGame(item.RootDirectory))
|
||||
{
|
||||
item.EngineType = TkoolEngineType.Bakin;
|
||||
item.HasSaveData = BakinSaveService.HasAnySaveData(item.RootDirectory);
|
||||
var bakinExe = BakinDetector.FindBakinExecutable(item.RootDirectory, item.FolderName);
|
||||
if (!string.IsNullOrEmpty(bakinExe))
|
||||
{
|
||||
item.ExecutablePath = bakinExe;
|
||||
}
|
||||
cacheRepaired = true;
|
||||
}
|
||||
else if (item.IsBakin)
|
||||
{
|
||||
bool bakinHasSave = BakinSaveService.HasAnySaveData(item.RootDirectory);
|
||||
if (item.HasSaveData != bakinHasSave)
|
||||
{
|
||||
item.HasSaveData = bakinHasSave;
|
||||
cacheRepaired = true;
|
||||
}
|
||||
}
|
||||
if (item.IsNwjs && string.IsNullOrEmpty(item.PluginsJsPath))
|
||||
{
|
||||
item.PluginsJsPath = NwjsDetector.ResolveEntryHtmlPath(item.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(item.PluginsJsPath))
|
||||
{
|
||||
item.PluginsDirPath = Path.GetDirectoryName(item.PluginsJsPath) ?? item.RootDirectory;
|
||||
item.IsModded = NwjsModService.CheckIsModded(item.PluginsJsPath);
|
||||
cacheRepaired = true;
|
||||
}
|
||||
}
|
||||
|
||||
// 起動時のUIブロックを防ぐため、ディスクI/O(実在検証・誤判定修正)はバックグラウンドの
|
||||
// VerifyAndEnrichGamesAsync に任せ、ここではキャッシュJSONから純粋にメモリ復元します。
|
||||
list.Add(item);
|
||||
}
|
||||
}
|
||||
if (cacheRepaired)
|
||||
{
|
||||
this.SaveCache(list);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
@@ -484,6 +547,8 @@ namespace GameLauncher.Services
|
||||
RgssArchivePath = tg.RgssArchivePath,
|
||||
HasWolfArchive = tg.HasWolfArchive,
|
||||
IsWolfExtracted = tg.IsWolfExtracted,
|
||||
MzPixiErrorFix = tg.MzPixiErrorFix,
|
||||
MzSpineErrorFix = tg.MzSpineErrorFix,
|
||||
WolfProxyDll = tg.WolfProxyDll,
|
||||
WolfSpeedMultiplier = tg.WolfSpeedMultiplier,
|
||||
HasSrpgArchive = tg.HasSrpgArchive,
|
||||
@@ -500,7 +565,8 @@ namespace GameLauncher.Services
|
||||
IsEvbExtracted = tg.IsEvbExtracted,
|
||||
EvbExtractedDirPath = tg.EvbExtractedDirPath,
|
||||
EvbBackupPath = tg.EvbBackupPath,
|
||||
EvbUnderlyingEngine = tg.EvbUnderlyingEngine
|
||||
EvbUnderlyingEngine = tg.EvbUnderlyingEngine,
|
||||
HasSaveData = tg.HasSaveData
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -521,6 +587,27 @@ namespace GameLauncher.Services
|
||||
/// ブックマーク対象ゲームの識別キーを正規化します。
|
||||
/// タイトル変動に耐えるため、RootDirectory をフルパス化し末尾セパレータを除去した文字列をキーとします。
|
||||
/// </summary>
|
||||
private static bool NwjsEnsureMeta(TkoolGameItem tg, ref int cacheNeedsSave)
|
||||
{
|
||||
if (string.IsNullOrEmpty(tg.PluginsJsPath) || !File.Exists(tg.PluginsJsPath))
|
||||
{
|
||||
tg.PluginsJsPath = NwjsDetector.ResolveEntryHtmlPath(tg.RootDirectory);
|
||||
tg.PluginsDirPath = !string.IsNullOrEmpty(tg.PluginsJsPath)
|
||||
? (Path.GetDirectoryName(tg.PluginsJsPath) ?? tg.RootDirectory)
|
||||
: tg.RootDirectory;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
|
||||
bool nwjsHasSave = NwjsSaveService.HasAnySaveData(tg.RootDirectory, tg.FolderName);
|
||||
if (tg.HasSaveData != nwjsHasSave)
|
||||
{
|
||||
tg.HasSaveData = nwjsHasSave;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static string NormalizeBookmarkKey(string rootDirectory)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(rootDirectory))
|
||||
@@ -656,9 +743,14 @@ namespace GameLauncher.Services
|
||||
return;
|
||||
}
|
||||
|
||||
// キャッシュのフォルダ更新日時と完全一致している場合、内部構成(exe/plugins/アーカイブ/EVB等)は不変のため
|
||||
// 重いディスクI/O(EVBバイナリ解析、plugins.js読み取り、wolf走査等)を完全にスキップして超高速化
|
||||
bool isUnchanged = game.FolderLastModified.HasValue && game.FolderLastModified.Value == currentLastWrite;
|
||||
// キャッシュのフォルダ更新日時と完全一致しており、かつ実行ファイルが有効(除外対象でない)な場合、
|
||||
// 内部構成(exe/plugins/アーカイブ/EVB等)は不変のため重いディスクI/Oをスキップして超高速化
|
||||
bool hasInvalidExe = string.IsNullOrEmpty(game.ExecutablePath) ||
|
||||
!File.Exists(game.ExecutablePath) ||
|
||||
IsExcludedExe(game.ExecutablePath);
|
||||
bool isUnchanged = !hasInvalidExe &&
|
||||
game.FolderLastModified.HasValue &&
|
||||
game.FolderLastModified.Value == currentLastWrite;
|
||||
if (isUnchanged)
|
||||
{
|
||||
// 未ロードのアイコンのみ必要に応じてロード
|
||||
@@ -674,18 +766,19 @@ namespace GameLauncher.Services
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新があった、または初回検証の場合は更新日時を最新化
|
||||
// 更新があった、または初回検証・実行ファイル修復が必要な場合は更新日時を最新化
|
||||
game.FolderLastModified = currentLastWrite;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
|
||||
if (game is UnityGameItem ug)
|
||||
{
|
||||
if (!File.Exists(ug.ExecutablePath))
|
||||
if (!File.Exists(ug.ExecutablePath) || IsExcludedExe(ug.ExecutablePath))
|
||||
{
|
||||
var recovered = FindGameExecutable(ug.RootDirectory);
|
||||
var recovered = this.FindUnityExecutable(ug.RootDirectory, ug.DataDirectoryPath);
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
ug.ExecutablePath = recovered;
|
||||
ug.IconImage = null;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
else
|
||||
@@ -777,15 +870,16 @@ namespace GameLauncher.Services
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
|
||||
// 実在検証
|
||||
// 実在検証および除外対象exe(notification_helper.exe等)からの自動修復
|
||||
if (tg.IsWolf)
|
||||
{
|
||||
if (!File.Exists(tg.ExecutablePath))
|
||||
if (!File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
|
||||
{
|
||||
var recovered = FindGameExecutable(tg.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
tg.IconImage = null;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
else
|
||||
@@ -814,12 +908,13 @@ namespace GameLauncher.Services
|
||||
}
|
||||
else if (tg.IsSrpgStudio)
|
||||
{
|
||||
if (!File.Exists(tg.ExecutablePath))
|
||||
if (!File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
|
||||
{
|
||||
var recovered = FindGameExecutable(tg.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
tg.IconImage = null;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
else
|
||||
@@ -874,6 +969,17 @@ namespace GameLauncher.Services
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
if (string.IsNullOrEmpty(tg.ExecutablePath) || !File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
|
||||
{
|
||||
var recovered = this.FindTkoolExecutable(tg.RootDirectory, tg.AsarExtractedDirPath ?? tg.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
tg.IconImage = null;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (tg.IsRgss)
|
||||
{
|
||||
@@ -887,6 +993,18 @@ namespace GameLauncher.Services
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(tg.ExecutablePath) || !File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
|
||||
{
|
||||
var recovered = FindRgssExecutable(tg.RootDirectory, tg.RootDirectory) ?? FindGameExecutable(tg.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
tg.IconImage = null;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
}
|
||||
|
||||
if (tg.IsRgssExtracted != scriptExists)
|
||||
{
|
||||
tg.IsRgssExtracted = scriptExists;
|
||||
@@ -894,23 +1012,77 @@ namespace GameLauncher.Services
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
}
|
||||
else if (tg.IsNwjs)
|
||||
else if (tg.IsNwjs && NwjsEnsureMeta(tg, ref cacheNeedsSave))
|
||||
{
|
||||
if (!File.Exists(tg.ExecutablePath) && !File.Exists(Path.Combine(tg.RootDirectory, "package.json")))
|
||||
{
|
||||
onGameRemoved(tg);
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (tg.IsEvbPacked || tg.IsStandaloneExePackage || tg.IsOther)
|
||||
{
|
||||
if (!File.Exists(tg.ExecutablePath))
|
||||
if (!File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
|
||||
{
|
||||
var recovered = FindGameExecutable(tg.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
tg.IconImage = null;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
else if (!File.Exists(Path.Combine(tg.RootDirectory, "package.json")))
|
||||
{
|
||||
onGameRemoved(tg);
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (tg.IsBakin)
|
||||
{
|
||||
if (!File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
|
||||
{
|
||||
var recovered = BakinDetector.FindBakinExecutable(tg.RootDirectory, tg.FolderName) ?? FindGameExecutable(tg.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
tg.IconImage = null;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
else if (!BakinDetector.IsBakinGame(tg.RootDirectory))
|
||||
{
|
||||
onGameRemoved(tg);
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
bool bakinSave = BakinSaveService.HasAnySaveData(tg.RootDirectory);
|
||||
if (tg.HasSaveData != bakinSave)
|
||||
{
|
||||
tg.HasSaveData = bakinSave;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
}
|
||||
else if (tg.IsEvbPacked || tg.IsStandaloneExePackage || tg.IsOther)
|
||||
{
|
||||
// 「その他」としてキャッシュされていても、Unityの強い証拠があれば Unity として再分類する。
|
||||
// (旧バージョンの判定でその他扱いになったまま残った項目の自己修復用)
|
||||
if (tg.IsOther && HasStrongUnityEvidence(tg.RootDirectory))
|
||||
{
|
||||
var promoted = this.DetectUnityGameInDirectory(tg.RootDirectory);
|
||||
if (promoted != null)
|
||||
{
|
||||
// ユーザー設定(ブックマーク・ラベル等)は従来の項目から引き継ぐ
|
||||
promoted.IsBookmarked = tg.IsBookmarked;
|
||||
promoted.LastLaunched = tg.LastLaunched;
|
||||
promoted.FolderLastModified = tg.FolderLastModified;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(promoted);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
|
||||
{
|
||||
var recovered = FindGameExecutable(tg.RootDirectory);
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
tg.IconImage = null;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
else
|
||||
@@ -929,6 +1101,19 @@ namespace GameLauncher.Services
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(tg.ExecutablePath) || !File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
|
||||
{
|
||||
var jsDir = Path.GetDirectoryName(tg.PluginsJsPath) ?? tg.RootDirectory;
|
||||
var recovered = this.FindTkoolExecutable(tg.RootDirectory, jsDir);
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
tg.IconImage = null;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// フォルダ更新日時
|
||||
@@ -944,7 +1129,7 @@ namespace GameLauncher.Services
|
||||
}
|
||||
|
||||
// 改造状態の確認
|
||||
if (tg.IsWolf || tg.IsNwjs)
|
||||
if (tg.IsWolf)
|
||||
{
|
||||
tg.IsModded = false;
|
||||
}
|
||||
@@ -958,7 +1143,11 @@ namespace GameLauncher.Services
|
||||
}
|
||||
else if (File.Exists(tg.PluginsJsPath))
|
||||
{
|
||||
if (tg.EngineType == TkoolEngineType.Tyrano)
|
||||
if (tg.IsNwjs)
|
||||
{
|
||||
tg.IsModded = NwjsModService.CheckIsModded(tg.PluginsJsPath);
|
||||
}
|
||||
else if (tg.EngineType == TkoolEngineType.Tyrano)
|
||||
{
|
||||
tg.IsModded = TyranoModService.CheckIsModded(tg.PluginsJsPath);
|
||||
}
|
||||
@@ -1604,6 +1793,12 @@ namespace GameLauncher.Services
|
||||
}
|
||||
|
||||
// 8. 汎用 NW.js ゲームの検出
|
||||
// 8. 汎用 NW.js ゲームの検出 / 9. RPG Developer Bakin ゲームの検出
|
||||
var bakinGame = BakinDetector.DetectBakinGame(dirPath, folderName, folderModified, (exe, dir) => LoadIcon(exe, dir));
|
||||
if (bakinGame != null)
|
||||
{
|
||||
return bakinGame;
|
||||
}
|
||||
var nwjsGame = NwjsDetector.DetectNwjsGame(dirPath, folderName, folderModified, (exe, dir) => LoadIcon(exe, dir));
|
||||
if (nwjsGame != null)
|
||||
{
|
||||
@@ -1738,11 +1933,10 @@ namespace GameLauncher.Services
|
||||
}
|
||||
}
|
||||
|
||||
// unins* を除外した最初のexe
|
||||
// 除外対象以外の最初のexe
|
||||
foreach (var exe in exes)
|
||||
{
|
||||
var name = Path.GetFileName(exe);
|
||||
if (name.StartsWith("unins", StringComparison.OrdinalIgnoreCase))
|
||||
if (IsExcludedExe(exe))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -1993,11 +2187,7 @@ namespace GameLauncher.Services
|
||||
var exes = Directory.GetFiles(targetDir, "*.exe", SearchOption.TopDirectoryOnly);
|
||||
foreach (var exe in exes)
|
||||
{
|
||||
var name = Path.GetFileName(exe);
|
||||
if (!name.Contains("unins", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.Contains("config", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.Contains("setup", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.Contains("patch", StringComparison.OrdinalIgnoreCase))
|
||||
if (!IsExcludedExe(exe))
|
||||
{
|
||||
exePath = exe;
|
||||
break;
|
||||
@@ -2185,11 +2375,7 @@ namespace GameLauncher.Services
|
||||
var exes = Directory.GetFiles(targetDir, "*.exe", SearchOption.TopDirectoryOnly);
|
||||
foreach (var exe in exes)
|
||||
{
|
||||
var name = Path.GetFileName(exe);
|
||||
if (!name.Contains("unins", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.Contains("config", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.Contains("setup", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.Contains("patch", StringComparison.OrdinalIgnoreCase))
|
||||
if (!IsExcludedExe(exe))
|
||||
{
|
||||
exePath = exe;
|
||||
break;
|
||||
@@ -2576,10 +2762,7 @@ namespace GameLauncher.Services
|
||||
var exes = Directory.GetFiles(searchDir, "*.exe", SearchOption.TopDirectoryOnly);
|
||||
foreach (var exe in exes)
|
||||
{
|
||||
var name = Path.GetFileName(exe);
|
||||
if (!name.Contains("unins", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.Contains("extractor", StringComparison.OrdinalIgnoreCase) &&
|
||||
!name.Contains("patch", StringComparison.OrdinalIgnoreCase))
|
||||
if (!IsExcludedExe(exe))
|
||||
{
|
||||
return exe;
|
||||
}
|
||||
@@ -2814,8 +2997,15 @@ namespace GameLauncher.Services
|
||||
if (File.Exists(p)) return p;
|
||||
}
|
||||
|
||||
var folderName = Path.GetFileName(rootDir.TrimEnd('\\', '/'));
|
||||
if (!string.IsNullOrEmpty(folderName))
|
||||
{
|
||||
var namedExe = Path.Combine(rootDir, folderName + ".exe");
|
||||
if (File.Exists(namedExe) && !IsExcludedExe(namedExe)) return namedExe;
|
||||
}
|
||||
|
||||
var exes = Directory.GetFiles(rootDir, "*.exe", SearchOption.TopDirectoryOnly)
|
||||
.Where(f => !Path.GetFileName(f).StartsWith("unins", StringComparison.OrdinalIgnoreCase))
|
||||
.Where(f => !IsExcludedExe(f))
|
||||
.ToList();
|
||||
|
||||
if (exes.Count > 0) return exes[0];
|
||||
@@ -2823,8 +3013,14 @@ namespace GameLauncher.Services
|
||||
var parent = Path.GetDirectoryName(jsDir);
|
||||
if (parent != null && parent != rootDir)
|
||||
{
|
||||
foreach (var cand in candidates)
|
||||
{
|
||||
var p = Path.Combine(parent, cand);
|
||||
if (File.Exists(p)) return p;
|
||||
}
|
||||
|
||||
var pExes = Directory.GetFiles(parent, "*.exe", SearchOption.TopDirectoryOnly)
|
||||
.Where(f => !Path.GetFileName(f).StartsWith("unins", StringComparison.OrdinalIgnoreCase))
|
||||
.Where(f => !IsExcludedExe(f))
|
||||
.ToList();
|
||||
if (pExes.Count > 0) return pExes[0];
|
||||
}
|
||||
@@ -2950,7 +3146,7 @@ namespace GameLauncher.Services
|
||||
if (File.Exists(standardGameExe)) return standardGameExe;
|
||||
|
||||
var exeFiles = Directory.GetFiles(gameRoot, "*.exe", SearchOption.TopDirectoryOnly)
|
||||
.Where(f => !Regex.IsMatch(Path.GetFileName(f), @"(unins|setup|crash|handler|UnityCrash|設定|アンインストール)", RegexOptions.IgnoreCase))
|
||||
.Where(f => !IsExcludedExe(f))
|
||||
.ToList();
|
||||
|
||||
if (exeFiles.Count > 0)
|
||||
@@ -3122,6 +3318,11 @@ namespace GameLauncher.Services
|
||||
/// </summary>
|
||||
public static ImageSource? LoadCachedThumbnailFast(string? exePath, string? fallbackDir = null)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(exePath) && IsExcludedExe(exePath) && !string.IsNullOrEmpty(fallbackDir))
|
||||
{
|
||||
exePath = FindGameExecutable(fallbackDir);
|
||||
}
|
||||
|
||||
var keyPath = !string.IsNullOrEmpty(exePath) ? exePath : fallbackDir;
|
||||
if (string.IsNullOrEmpty(keyPath))
|
||||
{
|
||||
@@ -3138,6 +3339,13 @@ namespace GameLauncher.Services
|
||||
|
||||
if (File.Exists(thumbPath))
|
||||
{
|
||||
// 過去に汎用白紙アイコン(<=600 bytes)がキャッシュされており、かつフォルダ内に公式アイコン画像がある場合は再生成させる
|
||||
var fi = new FileInfo(thumbPath);
|
||||
if (fi.Length <= 600 && TryFindGameIconPng(fallbackDir, exePath) != null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var bmp = new BitmapImage();
|
||||
bmp.BeginInit();
|
||||
bmp.UriSource = new Uri(thumbPath);
|
||||
@@ -3155,12 +3363,26 @@ namespace GameLauncher.Services
|
||||
|
||||
public static ImageSource? LoadIcon(string? exePath, string? fallbackDir = null)
|
||||
{
|
||||
if ((!string.IsNullOrEmpty(exePath) && IsExcludedExe(exePath)) || (string.IsNullOrEmpty(exePath) && !string.IsNullOrEmpty(fallbackDir)))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(fallbackDir))
|
||||
{
|
||||
var resolved = FindGameExecutable(fallbackDir);
|
||||
if (!string.IsNullOrEmpty(resolved))
|
||||
{
|
||||
exePath = resolved;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var keyPath = !string.IsNullOrEmpty(exePath) ? exePath : fallbackDir;
|
||||
if (string.IsNullOrEmpty(keyPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var gameIconPng = TryFindGameIconPng(fallbackDir, exePath);
|
||||
|
||||
// 1. サムネイルキャッシュフォルダから即座にロードを試行
|
||||
string? thumbPath = null;
|
||||
try
|
||||
@@ -3173,22 +3395,45 @@ namespace GameLauncher.Services
|
||||
|
||||
if (File.Exists(thumbPath))
|
||||
{
|
||||
var bmp = new BitmapImage();
|
||||
bmp.BeginInit();
|
||||
bmp.UriSource = new Uri(thumbPath);
|
||||
bmp.CacheOption = BitmapCacheOption.OnLoad;
|
||||
bmp.DecodePixelWidth = 88;
|
||||
bmp.EndInit();
|
||||
bmp.Freeze();
|
||||
return bmp;
|
||||
var fi = new FileInfo(thumbPath);
|
||||
// キャッシュが600バイト超、または代替アイコンPNGが存在しない場合はキャッシュを使用
|
||||
if (fi.Length > 600 || gameIconPng == null)
|
||||
{
|
||||
var bmp = new BitmapImage();
|
||||
bmp.BeginInit();
|
||||
bmp.UriSource = new Uri(thumbPath);
|
||||
bmp.CacheOption = BitmapCacheOption.OnLoad;
|
||||
bmp.DecodePixelWidth = 88;
|
||||
bmp.EndInit();
|
||||
bmp.Freeze();
|
||||
return bmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
// 2. キャッシュに存在しない場合はアイコンまたは画像を抽出
|
||||
// 2. キャッシュに存在しない(または白紙キャッシュ更新)場合はアプリアイコンPNGまたはexeアイコンを抽出
|
||||
BitmapSource? bitmapSource = null;
|
||||
|
||||
if (!string.IsNullOrEmpty(exePath) && File.Exists(exePath))
|
||||
// 2-1. ゲームフォルダ内の高解像度アイコンPNG (www/icon/icon.png, icon/icon.png, package.json指定等) を優先試行
|
||||
if (!string.IsNullOrEmpty(gameIconPng) && File.Exists(gameIconPng))
|
||||
{
|
||||
try
|
||||
{
|
||||
var bmp = new BitmapImage();
|
||||
bmp.BeginInit();
|
||||
bmp.UriSource = new Uri(gameIconPng);
|
||||
bmp.CacheOption = BitmapCacheOption.OnLoad;
|
||||
bmp.DecodePixelWidth = 88;
|
||||
bmp.EndInit();
|
||||
bmp.Freeze();
|
||||
bitmapSource = bmp;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
// 2-2. 実行ファイルから関連付けアイコンを抽出
|
||||
if (bitmapSource == null && !string.IsNullOrEmpty(exePath) && File.Exists(exePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -3205,25 +3450,6 @@ namespace GameLauncher.Services
|
||||
catch { }
|
||||
}
|
||||
|
||||
if (bitmapSource == null && !string.IsNullOrEmpty(fallbackDir) && Directory.Exists(fallbackDir))
|
||||
{
|
||||
var png = Path.Combine(fallbackDir, "icon.png");
|
||||
if (File.Exists(png))
|
||||
{
|
||||
try
|
||||
{
|
||||
var bmp = new BitmapImage();
|
||||
bmp.BeginInit();
|
||||
bmp.UriSource = new Uri(png);
|
||||
bmp.CacheOption = BitmapCacheOption.OnLoad;
|
||||
bmp.EndInit();
|
||||
bmp.Freeze();
|
||||
bitmapSource = bmp;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 取得できたアイコンをサムネイルキャッシュフォルダへ保存
|
||||
if (bitmapSource != null && !string.IsNullOrEmpty(thumbPath))
|
||||
{
|
||||
@@ -3237,6 +3463,91 @@ namespace GameLauncher.Services
|
||||
return bitmapSource;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ゲームディレクトリ内からアプリアイコン画像(package.jsonのicon指定、www/icon/icon.png、icon/icon.png、icon.png等)を探索します。
|
||||
/// </summary>
|
||||
private static string? TryFindGameIconPng(string? fallbackDir, string? exePath)
|
||||
{
|
||||
var searchDirs = new List<string>();
|
||||
if (!string.IsNullOrEmpty(fallbackDir) && Directory.Exists(fallbackDir))
|
||||
{
|
||||
searchDirs.Add(fallbackDir);
|
||||
}
|
||||
if (!string.IsNullOrEmpty(exePath))
|
||||
{
|
||||
var exeDir = Path.GetDirectoryName(exePath);
|
||||
if (!string.IsNullOrEmpty(exeDir) && Directory.Exists(exeDir) &&
|
||||
!searchDirs.Contains(exeDir, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
searchDirs.Add(exeDir);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var baseDir in searchDirs)
|
||||
{
|
||||
try
|
||||
{
|
||||
// 1. package.json の window.icon 指定を確認
|
||||
var pkgPaths = new[]
|
||||
{
|
||||
Path.Combine(baseDir, "package.json"),
|
||||
Path.Combine(baseDir, "www", "package.json")
|
||||
};
|
||||
foreach (var pkgPath in pkgPaths)
|
||||
{
|
||||
if (File.Exists(pkgPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(pkgPath));
|
||||
if (doc.RootElement.TryGetProperty("window", out var win) &&
|
||||
win.ValueKind == JsonValueKind.Object &&
|
||||
win.TryGetProperty("icon", out var iconProp) &&
|
||||
iconProp.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
var relIcon = iconProp.GetString();
|
||||
if (!string.IsNullOrWhiteSpace(relIcon))
|
||||
{
|
||||
var pkgDir = Path.GetDirectoryName(pkgPath)!;
|
||||
var resolvedFromPkg = Path.Combine(pkgDir, relIcon.Replace('/', Path.DirectorySeparatorChar));
|
||||
if (File.Exists(resolvedFromPkg))
|
||||
{
|
||||
return resolvedFromPkg;
|
||||
}
|
||||
var resolvedFromBase = Path.Combine(baseDir, relIcon.Replace('/', Path.DirectorySeparatorChar));
|
||||
if (File.Exists(resolvedFromBase))
|
||||
{
|
||||
return resolvedFromBase;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 定型のアイコン配置パスを確認
|
||||
var candidates = new[]
|
||||
{
|
||||
Path.Combine(baseDir, "www", "icon", "icon.png"),
|
||||
Path.Combine(baseDir, "icon", "icon.png"),
|
||||
Path.Combine(baseDir, "www", "icon.png"),
|
||||
Path.Combine(baseDir, "icon.png")
|
||||
};
|
||||
foreach (var cand in candidates)
|
||||
{
|
||||
if (File.Exists(cand))
|
||||
{
|
||||
return cand;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void SaveBitmapSourceToPng(BitmapSource source, string filePath)
|
||||
{
|
||||
try
|
||||
@@ -3353,10 +3664,26 @@ namespace GameLauncher.Services
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool IsExcludedExe(string filePath)
|
||||
/// <summary>
|
||||
/// ゲーム本体ではない補助ツール・インストーラ・通知ヘルパー・設定用実行ファイルかどうかを判定します。
|
||||
/// </summary>
|
||||
public static bool IsExcludedExe(string? filePath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(filePath))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var fileName = Path.GetFileName(filePath);
|
||||
return Regex.IsMatch(fileName, @"^(unins|setup|install|crash|handler|UnityCrash|設定|Config|updater|patch)", RegexOptions.IgnoreCase);
|
||||
if (string.IsNullOrWhiteSpace(fileName))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
return Regex.IsMatch(
|
||||
fileName,
|
||||
@"^(unins|setup|install|crash|handler|UnityCrash|notification_helper|crashpad_handler|elevate|nacl64|nwjc|payload|minidump_stackwalk|extractor|設定|環境設定|エンジン設定|Config|updater|patch|アンインストール)|((設定|環境設定|エンジン設定|Config|Setup|Installer|Updater)\.exe$)",
|
||||
RegexOptions.IgnoreCase);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -259,5 +259,59 @@
|
||||
};
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 5. グローバル例外ロギング & デバッグ補助(スタックトレース追跡)
|
||||
// =========================================================================
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('error', function(event) {
|
||||
try {
|
||||
var err = event.error || event;
|
||||
var msg = '[' + new Date().toISOString() + '] Uncaught Error:\nMessage: ' + event.message + '\nFile: ' + event.filename + ':' + event.lineno + ':' + event.colno + '\nStack:\n' + (err.stack || 'No stack') + '\n\n';
|
||||
if (fs) {
|
||||
fs.appendFileSync('error_trace.log', msg, 'utf8');
|
||||
}
|
||||
console.error('[GameLauncher Error Hook]', msg);
|
||||
} catch (ex) { }
|
||||
});
|
||||
|
||||
window.addEventListener('unhandledrejection', function(event) {
|
||||
try {
|
||||
var reason = event.reason;
|
||||
var msg = '[' + new Date().toISOString() + '] Unhandled Promise Rejection:\n' + (reason ? (reason.stack || reason) : 'Unknown') + '\n\n';
|
||||
if (fs) {
|
||||
fs.appendFileSync('error_trace.log', msg, 'utf8');
|
||||
}
|
||||
console.error('[GameLauncher Promise Error Hook]', msg);
|
||||
} catch (ex) { }
|
||||
});
|
||||
|
||||
// F12 / F8 キーで DevTools をトグル可能にする
|
||||
window.addEventListener('keydown', function(event) {
|
||||
if (event.key === 'F12' || event.keyCode === 123 || event.key === 'F8' || event.keyCode === 119) {
|
||||
if (typeof nw !== 'undefined' && nw.Window && nw.Window.get) {
|
||||
try {
|
||||
nw.Window.get().showDevTools();
|
||||
} catch (e) { }
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 6. Pixi.js / RMMZ Tilemap & Sprite の null 安全保護
|
||||
// =========================================================================
|
||||
if (typeof PIXI !== 'undefined') {
|
||||
if (PIXI.Sprite && PIXI.Sprite.prototype) {
|
||||
var _Sprite_prototype_destroy = PIXI.Sprite.prototype.destroy;
|
||||
PIXI.Sprite.prototype.destroy = function(options) {
|
||||
try {
|
||||
_Sprite_prototype_destroy.call(this, options);
|
||||
} catch (e) {
|
||||
console.warn('[GameLauncher] Sprite.destroy error suppressed:', e);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[GameLauncher] ResourceLoaderFix プラグインが正常にロードされました。');
|
||||
})();
|
||||
@@ -0,0 +1,317 @@
|
||||
/*:
|
||||
* @target MZ
|
||||
* @plugindesc Spine処理およびイベント進行の診断ログを save/spine_debug_trace.log へ出力します(調査完了後に削除・無効化可能)。
|
||||
* @author GameLauncher
|
||||
*/
|
||||
|
||||
(() => {
|
||||
'use strict';
|
||||
|
||||
let fs = null;
|
||||
let path = null;
|
||||
try {
|
||||
fs = require('fs');
|
||||
path = require('path');
|
||||
} catch (e) {
|
||||
return;
|
||||
}
|
||||
|
||||
function resolveLogPath() {
|
||||
const candidates = [];
|
||||
try {
|
||||
if (typeof StorageManager !== 'undefined' && typeof StorageManager.fileDirectoryPath === 'function') {
|
||||
candidates.push(StorageManager.fileDirectoryPath());
|
||||
}
|
||||
} catch (e) {}
|
||||
try {
|
||||
if (typeof process !== 'undefined' && typeof process.cwd === 'function') {
|
||||
candidates.push(path.join(process.cwd(), 'save'));
|
||||
}
|
||||
} catch (e) {}
|
||||
for (const dir of candidates) {
|
||||
if (!dir) continue;
|
||||
try {
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
return path.join(dir, 'spine_debug_trace.log');
|
||||
} catch (e) {}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const logFilePath = resolveLogPath();
|
||||
if (!logFilePath) return;
|
||||
|
||||
try {
|
||||
if (fs.existsSync(logFilePath) && fs.statSync(logFilePath).size > 5 * 1024 * 1024) {
|
||||
fs.renameSync(logFilePath, logFilePath + '.old');
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
function frame() {
|
||||
return (typeof Graphics !== 'undefined' && typeof Graphics.frameCount === 'number') ? Graphics.frameCount : -1;
|
||||
}
|
||||
|
||||
function writeLog(tag, msg, detail) {
|
||||
try {
|
||||
const ts = new Date().toISOString();
|
||||
let line = `[${ts}][F:${frame()}][${tag}] ${msg}`;
|
||||
if (detail !== undefined) {
|
||||
try {
|
||||
line += ' | ' + (typeof detail === 'string' ? detail : JSON.stringify(detail));
|
||||
} catch (e) {
|
||||
line += ' | [unserializable]';
|
||||
}
|
||||
}
|
||||
fs.appendFileSync(logFilePath, line + '\r\n', 'utf8');
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
writeLog('INIT', 'SpineDebugTrace 起動', { logFilePath });
|
||||
|
||||
// グローバルエラー・警告フック
|
||||
window.addEventListener('error', (ev) => {
|
||||
const err = ev && ev.error ? ev.error : ev;
|
||||
writeLog('WINDOW_ERROR', ev && ev.message ? ev.message : 'unknown', {
|
||||
file: ev && ev.filename,
|
||||
line: ev && ev.lineno,
|
||||
stack: err && err.stack ? String(err.stack) : ''
|
||||
});
|
||||
});
|
||||
|
||||
window.addEventListener('unhandledrejection', (ev) => {
|
||||
const r = ev && ev.reason;
|
||||
writeLog('UNHANDLED_REJECTION', r && r.message ? r.message : String(r), {
|
||||
stack: r && r.stack ? String(r.stack) : ''
|
||||
});
|
||||
});
|
||||
|
||||
const _origWarn = console.warn;
|
||||
console.warn = function (...args) {
|
||||
try {
|
||||
const text = args.map(a => typeof a === 'string' ? a : String(a)).join(' ');
|
||||
if (/SpineFix|Animation not found|GameLauncher|Error|Spine/i.test(text)) {
|
||||
writeLog('CONSOLE_WARN', text);
|
||||
}
|
||||
} catch (e) {}
|
||||
return _origWarn.apply(this, args);
|
||||
};
|
||||
|
||||
const _origError = console.error;
|
||||
console.error = function (...args) {
|
||||
try {
|
||||
const text = args.map(a => typeof a === 'string' ? a : (a && a.stack ? a.stack : String(a))).join(' ');
|
||||
writeLog('CONSOLE_ERROR', text);
|
||||
} catch (e) {}
|
||||
return _origError.apply(this, args);
|
||||
};
|
||||
|
||||
// SceneManager.catchException フック
|
||||
if (typeof SceneManager !== 'undefined' && SceneManager.catchException) {
|
||||
const _catchEx = SceneManager.catchException;
|
||||
SceneManager.catchException = function (e) {
|
||||
writeLog('SCENE_EXCEPTION', e && e.message ? e.message : String(e), {
|
||||
stack: e && e.stack ? String(e.stack) : ''
|
||||
});
|
||||
return _catchEx.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
|
||||
// スイッチ・変数監視
|
||||
const watchSwitches = new Set([8, 10, 11, 15, 20, 21, 50, 51, 58, 521]);
|
||||
const watchVars = new Set([51, 54, 55, 100, 101, 102]);
|
||||
|
||||
const _swSetValue = Game_Switches.prototype.setValue;
|
||||
Game_Switches.prototype.setValue = function (switchId, value) {
|
||||
const prev = this.value(switchId);
|
||||
const res = _swSetValue.apply(this, arguments);
|
||||
const next = this.value(switchId);
|
||||
if (watchSwitches.has(Number(switchId)) && prev !== next) {
|
||||
writeLog('SWITCH', `S[${switchId}] ${prev} -> ${next}`);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
const _varSetValue = Game_Variables.prototype.setValue;
|
||||
Game_Variables.prototype.setValue = function (variableId, value) {
|
||||
const prev = this.value(variableId);
|
||||
const res = _varSetValue.apply(this, arguments);
|
||||
const next = this.value(variableId);
|
||||
if (watchVars.has(Number(variableId)) && prev !== next) {
|
||||
writeLog('VAR', `V[${variableId}] ${JSON.stringify(prev)} -> ${JSON.stringify(next)}`);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
// BattleManager フェーズ監視
|
||||
let _lastBattlePhase = '';
|
||||
const _bmUpdate = BattleManager.update;
|
||||
BattleManager.update = function () {
|
||||
if (this._phase !== _lastBattlePhase) {
|
||||
_lastBattlePhase = this._phase;
|
||||
writeLog('BATTLE_PHASE', `phase=${this._phase}`, {
|
||||
busy: this.isBusy ? this.isBusy() : null,
|
||||
troopRunning: typeof $gameTroop !== 'undefined' && $gameTroop && $gameTroop._interpreter ? $gameTroop._interpreter.isRunning() : null
|
||||
});
|
||||
}
|
||||
return _bmUpdate.apply(this, arguments);
|
||||
};
|
||||
|
||||
// Game_Interpreter 監視(セットアップ・コマンド実行・例外・停滞スナップショット)
|
||||
const _giSetup = Game_Interpreter.prototype.setup;
|
||||
Game_Interpreter.prototype.setup = function (list, eventId) {
|
||||
const res = _giSetup.apply(this, arguments);
|
||||
writeLog('INTERP_SETUP', `depth=${this._depth} eventId=${eventId || this._eventId} len=${list ? list.length : 0}`);
|
||||
return res;
|
||||
};
|
||||
|
||||
const _giTerminate = Game_Interpreter.prototype.terminate;
|
||||
Game_Interpreter.prototype.terminate = function () {
|
||||
writeLog('INTERP_END', `depth=${this._depth} eventId=${this._eventId}`);
|
||||
return _giTerminate.apply(this, arguments);
|
||||
};
|
||||
|
||||
const _giExec = Game_Interpreter.prototype.executeCommand;
|
||||
Game_Interpreter.prototype.executeCommand = function () {
|
||||
const cmd = this.currentCommand();
|
||||
const idx = this._index;
|
||||
try {
|
||||
if (cmd) {
|
||||
if (cmd.code === 117) {
|
||||
writeLog('INTERP_CE', `depth=${this._depth} idx=${idx} call CE[${cmd.parameters[0]}]`);
|
||||
} else if (cmd.code === 355) {
|
||||
const line = String(cmd.parameters[0] || '');
|
||||
if (/spine|setSkeleton|setAnimation|setSkin|PluginManager/i.test(line)) {
|
||||
writeLog('INTERP_SCRIPT', `depth=${this._depth} idx=${idx}`, line);
|
||||
}
|
||||
}
|
||||
}
|
||||
return _giExec.apply(this, arguments);
|
||||
} catch (e) {
|
||||
writeLog('INTERP_ERROR', `depth=${this._depth} idx=${idx} code=${cmd ? cmd.code : -1} err=${e && e.message}`, {
|
||||
stack: e && e.stack ? String(e.stack) : ''
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
|
||||
// 停滞監視(バトル中のインタープリタや並列イベントが30フレーム以上止まっているように見える場合のスナップショット)
|
||||
let _lastSnapshotFrame = -999;
|
||||
const _sbUpdate = Scene_Base.prototype.update;
|
||||
Scene_Base.prototype.update = function () {
|
||||
const res = _sbUpdate.apply(this, arguments);
|
||||
try {
|
||||
const f = frame();
|
||||
if (f - _lastSnapshotFrame >= 60 && typeof $gameSwitches !== 'undefined' && $gameSwitches) {
|
||||
const s15 = $gameSwitches.value(15);
|
||||
const s20 = $gameSwitches.value(20);
|
||||
const s51 = $gameSwitches.value(51);
|
||||
const troopInterp = typeof $gameTroop !== 'undefined' && $gameTroop && $gameTroop._interpreter;
|
||||
const running = troopInterp && troopInterp.isRunning();
|
||||
if (s15 || s20 || s51 || running) {
|
||||
_lastSnapshotFrame = f;
|
||||
const cmd = running ? troopInterp.currentCommand() : null;
|
||||
let pic1Spine = null;
|
||||
try {
|
||||
const p1 = $gameScreen && $gameScreen.picture(1);
|
||||
if (p1 && p1._spine) {
|
||||
pic1Spine = {
|
||||
skel: p1._spine._skeleton,
|
||||
track0: p1._spine._track && p1._spine._track[0] ? p1._spine._track[0].list.map(x => x.name) : null,
|
||||
play0: p1._spine._playData && p1._spine._playData[0] ? p1._spine._playData[0].map(x => x.name + ':' + x.state + '@' + Number(x.trackTime).toFixed(2)) : null
|
||||
};
|
||||
}
|
||||
} catch (e) {}
|
||||
writeLog('SNAPSHOT', `phase=${BattleManager._phase} troopRun=${running} idx=${troopInterp ? troopInterp._index : -1} code=${cmd ? cmd.code : -1}`, {
|
||||
S15: s15, S20: s20, S51: s51,
|
||||
V54: $gameVariables ? $gameVariables.value(54) : null,
|
||||
V55: $gameVariables ? $gameVariables.value(55) : null,
|
||||
V102: $gameVariables ? $gameVariables.value(102) : null,
|
||||
pic1Spine
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
return res;
|
||||
};
|
||||
|
||||
// PictureSpine フック (Game_Spine & Sprite_Spine)
|
||||
function hookPictureSpine() {
|
||||
if (typeof Game_Spine !== 'undefined' && !Game_Spine.__glTraceHooked) {
|
||||
Game_Spine.__glTraceHooked = true;
|
||||
const _gsSetSkel = Game_Spine.prototype.setSkeleton;
|
||||
Game_Spine.prototype.setSkeleton = function (name) {
|
||||
const before = this._skeleton;
|
||||
const res = _gsSetSkel.apply(this, arguments);
|
||||
writeLog('GS_SETSKEL', `name=${name} (${before} -> ${this._skeleton})`);
|
||||
return res;
|
||||
};
|
||||
const _gsSetAnim = Game_Spine.prototype.setAnimation;
|
||||
Game_Spine.prototype.setAnimation = function (id, animations, ...args) {
|
||||
const before = this._skeleton;
|
||||
const res = _gsSetAnim.apply(this, arguments);
|
||||
writeLog('GS_SETANIM', `track=${id} anim=${JSON.stringify(animations)} args=${JSON.stringify(args)} skel=${before}->${this._skeleton}`);
|
||||
return res;
|
||||
};
|
||||
}
|
||||
if (typeof Sprite_Spine !== 'undefined' && !Sprite_Spine.__glTraceHooked) {
|
||||
Sprite_Spine.__glTraceHooked = true;
|
||||
const _ssUpdate = Sprite_Spine.prototype.update;
|
||||
Sprite_Spine.prototype.update = function () {
|
||||
try {
|
||||
return _ssUpdate.apply(this, arguments);
|
||||
} catch (e) {
|
||||
writeLog('SS_UPDATE_ERROR', e && e.message ? e.message : String(e), {
|
||||
picId: this._pictureId,
|
||||
skel: this._skeleton,
|
||||
stack: e && e.stack ? String(e.stack) : ''
|
||||
});
|
||||
throw e;
|
||||
}
|
||||
};
|
||||
const _ssUpdSkel = Sprite_Spine.prototype.updateSkeleton;
|
||||
Sprite_Spine.prototype.updateSkeleton = function (spine) {
|
||||
const prevSkel = this._skeleton;
|
||||
const nextSkel = spine ? spine.skeleton : null;
|
||||
const res = _ssUpdSkel.apply(this, arguments);
|
||||
if (nextSkel && nextSkel !== prevSkel) {
|
||||
writeLog('SS_UPDSKEL', `pic=${this._pictureId} ${prevSkel} -> ${this._skeleton} (target=${nextSkel}, hasData=${!!this._data})`);
|
||||
}
|
||||
return res;
|
||||
};
|
||||
const _ssUpdAnim = Sprite_Spine.prototype.updateAnimation;
|
||||
Sprite_Spine.prototype.updateAnimation = function (spine) {
|
||||
const changed = spine && spine.track !== this._track;
|
||||
const res = _ssUpdAnim.apply(this, arguments);
|
||||
if (changed) {
|
||||
try {
|
||||
const tracks = this._data && this._data.state ? this._data.state.tracks.map(t => t && t.animation ? t.animation.name : null) : null;
|
||||
writeLog('SS_UPDANIM', `pic=${this._pictureId} skel=${this._skeleton}`, { tracks });
|
||||
} catch (e) {}
|
||||
}
|
||||
return res;
|
||||
};
|
||||
const _ssOnEvent = Sprite_Spine.prototype.onEvent;
|
||||
Sprite_Spine.prototype.onEvent = function (entry, event) {
|
||||
writeLog('SS_EVENT', `pic=${this._pictureId} anim=${entry && entry.animation ? entry.animation.name : '?'} ev=${event && event.data ? event.data.name : '?'} str=${event ? event.stringValue : ''}`);
|
||||
return _ssOnEvent.apply(this, arguments);
|
||||
};
|
||||
const _ssOnComplete = Sprite_Spine.prototype.onComplete;
|
||||
Sprite_Spine.prototype.onComplete = function (entry) {
|
||||
if (entry && !entry.loop) {
|
||||
writeLog('SS_COMPLETE', `pic=${this._pictureId} track=${entry.trackIndex} anim=${entry.animation ? entry.animation.name : '?'}`);
|
||||
}
|
||||
return _ssOnComplete.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const _smInit = SceneManager.initialize;
|
||||
SceneManager.initialize = function () {
|
||||
const res = _smInit.apply(this, arguments);
|
||||
hookPictureSpine();
|
||||
return res;
|
||||
};
|
||||
hookPictureSpine();
|
||||
})();
|
||||
Reference in new issue
Block a user