Files
Jiaqi Liu 5d0f564a00 Add a standalone battle editor and battle system for PAL3 and PAL3A (#99)
* build: migrate C# formatting and add offscreen editor test support

Host IMGUI tests on a detached panel without creating a native editor window.

* feat(core): decode native battle records, geometry and animation metadata

Read the two game variants’ battle tables and model data, with binary-reader and original-resource coverage.

* feat(battle): implement deterministic combat rules and action settlement

Implement actors, inventory, formation, action timing, status interruption, AI, stage ownership and deterministic replay. Keep the domain and its regression suite independent of Unity.

* feat(battle): project native HUD state and input commands

Add the presentation assembly and tests for command routing, lineup selection, floating numbers and stage messages.

* feat(rendering): add battle lighting, actor appearance and native shadows

Support baked and toon lighting, actor and weapon rendering, display refresh rate and resource ownership.

* feat(effects): drive battle effects through shared resource previews

Bind battle control nodes to action owners. Share preview lighting, geometry and effect resources with the existing Unity editors.

* refactor(game): isolate story battle targeting and actor lifetimes

Preserve scene ownership, bound story battle targeting and stop debug attacks when their actor leaves the scene.

* feat(editor): compile original game data into battle scenarios

Build per-variant animation and ability catalogs, encounter music, scene lighting profiles, random parties, equipment and test inventory from the original resources.

* feat(editor): play battle sessions with animated previews and synced media

Drive the preview scene, camera, effects, hit feedback, result choreography, music and movies from simulation snapshots and events.

* feat(editor): add the battle workbench, native HUD and input controls

Expose scenario authoring, replay, diagnostics, responsive command menus and mouse, touch and gamepad targeting. Include the editor workflow and HUD integration tests.
2026-11-21 22:28:47 +08:00

544 lines
25 KiB
C#

// ------------------------------------------------------------------------
// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved.
// See LICENSE file in the project root for license information.
// ------------------------------------------------------------------------
namespace Pal3.Game.Effect.Runtime
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Core.DataReader;
using Core.DataReader.Data;
using Core.DataReader.Cvd;
using Core.DataReader.Par;
using Core.DataReader.Pol;
using Core.FileSystem;
using Data;
using Engine.Core.Implementation;
using Engine.Core.Abstraction;
using UnityEngine;
using Rendering.Native;
using UnityEngine.Rendering;
public sealed class EffectResources : IDisposable
{
private readonly ICpkFileSystem _fileSystem;
private readonly int _codepage;
private readonly Dictionary<string, Texture2D> _textures = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, ParticleFile> _particles = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, byte[]> _particleBytes = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, ParticleFile> _overrideParticles = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, ParticleShapeFile> _shapes = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, PolFile> _polModels = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, SparFile> _sparFiles = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, CvdFile> _models = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<(string, int, int, bool, int, int), Material> _materials = new();
private readonly Dictionary<int, string[]> _diagnostics = new();
private readonly HashSet<string> _missingBattleTextures = new(StringComparer.OrdinalIgnoreCase);
public IReadOnlyCollection<string> MissingBattleTextures => _missingBattleTextures;
private readonly Dictionary<int, string[]> _battleDiagnostics = new();
private readonly Dictionary<int, string[]> _battleOverrideDiagnostics = new();
private readonly Dictionary<int, string[]> _overrideDiagnostics = new();
private EffectOverrides _cachedOverrides;
private string _cachedOverridesJson;
private EffectDefinitionFile _definitions;
public EffectDefinitionFile Definitions => _definitions ??= Read<EffectDefinitionFile>("cbdata\\flexeff.data", new EffectDefinitionFileReader());
public string GameVariant => Definitions.EffectDefinitions.Length == 2048 ? "PAL3A" : "PAL3";
public string OverridesPath => $"Effects/{GameVariant}Overrides";
public EffectResources(ICpkFileSystem fileSystem, int codepage = 936)
{
_fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
_codepage = codepage;
}
public static string Normalize(string path)
{
path = path.Replace('/', '\\');
return path.StartsWith("basedata.cpk\\", StringComparison.OrdinalIgnoreCase) ? path : "basedata.cpk\\" + path;
}
public byte[] Bytes(string path) => _fileSystem.ReadAllBytes(Normalize(path));
public T Read<T>(string path, IFileReader<T> reader) => reader.Read(Bytes(path), _codepage);
public ITextureResourceProvider ModelTextureProvider(string file) => new ModelTextures(this, file);
private sealed class ModelTextures : ITextureResourceProvider
{
private readonly EffectResources _owner;
private readonly string _file;
public ModelTextures(EffectResources owner, string file)
{
_owner = owner;
_file = file;
}
public string GetTexturePath(string name) => RelativeTo(_file, name);
public ITexture2D GetTexture(string name) => GetTexture(name, out _);
public ITexture2D GetTexture(string name, out bool hasAlphaChannel)
{
hasAlphaChannel = true;
return new UnityTexture2D(_owner.Texture(GetTexturePath(name)));
}
}
public ParticleFile Particle(string path, EffectOverrides edits = null)
{
path = Normalize(path);
if (!_particles.TryGetValue(path, out ParticleFile file))
{
if (!_particleBytes.TryGetValue(path, out byte[] bytes))
_particleBytes[path] = bytes = Bytes(path);
_particles[path] = file = ((IFileReader<ParticleFile>)new ParticleFileReader()).Read(bytes, _codepage);
}
if (edits != null && edits.HasParticleEdits(path))
{
RefreshOverrideCache(edits);
if (!_overrideParticles.TryGetValue(path, out ParticleFile copy))
{
copy = ((IFileReader<ParticleFile>)new ParticleFileReader()).Read(_particleBytes[path], _codepage);
edits.ApplyParticle(path, copy);
_overrideParticles[path] = copy;
}
return copy;
}
return file;
}
private void RefreshOverrideCache(EffectOverrides edits)
{
// Public override fields also support scripts, Undo and the native
// Inspector. A content stamp catches those edits without relying on
// every caller to manually invalidate a revision counter.
string json = JsonUtility.ToJson(edits);
if (ReferenceEquals(edits, _cachedOverrides) && json == _cachedOverridesJson)
return;
_cachedOverrides = edits;
_cachedOverridesJson = json;
_overrideDiagnostics.Clear();
_battleOverrideDiagnostics.Clear();
_overrideParticles.Clear();
}
internal ParticleShapeFile ParticleShape(string particlePath, string shapePath)
{
string primary = RelativeTo(particlePath, shapePath);
string relativeShape = shapePath.Replace('/', '\\');
if (GameVariant == "PAL3A" &&
Normalize(primary).StartsWith("basedata.cpk\\effect\\gbParticle\\csf\\", StringComparison.OrdinalIgnoreCase) &&
relativeShape.StartsWith("csf\\", StringComparison.OrdinalIgnoreCase) &&
!_fileSystem.FileExists(Normalize(primary)))
return Shape("effect\\" + relativeShape);
return Shape(primary);
}
private ParticleShapeFile Shape(string path)
{
if (!_shapes.TryGetValue(path, out ParticleShapeFile file))
_shapes.Add(path, file = Read(path, new ParticleShapeFileReader()));
return file;
}
public SparFile Spar(string path)
{
if (!_sparFiles.TryGetValue(path, out SparFile file))
_sparFiles.Add(path, file = Read(path, new SparFileReader()));
return file;
}
public PolFile PolModel(string path)
{
if (!_polModels.TryGetValue(path, out PolFile file))
_polModels.Add(path, file = Read(path, new PolFileReader()));
return file;
}
public CvdFile Model(string path)
{
if (!_models.TryGetValue(path, out CvdFile file))
_models.Add(path, file = Read(path, new CvdFileReader()));
return file;
}
public static string RelativeTo(string file, string relative)
{
file = file.Replace('/', '\\');
int slash = file.LastIndexOf('\\');
return (slash < 0 ? "" : file[..(slash + 1)]) + relative.Replace('/', '\\');
}
public string ResolveTexture(string path)
{
path = Normalize(path);
string dds = Path.ChangeExtension(path, ".dds");
if (_fileSystem.FileExists(dds))
return dds;
if (_fileSystem.FileExists(path))
return path;
throw new FileNotFoundException($"Original effect texture not found: {path}", path);
}
public Texture2D Texture(string path)
{
path = ResolveTexture(path);
if (_textures.TryGetValue(path, out Texture2D cached))
return cached;
Texture2D texture;
if (path.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
{
texture = new Texture2D(2, 2, TextureFormat.RGBA32, false);
if (!texture.LoadImage(Bytes(path), true))
{
Destroy(texture);
throw new InvalidDataException($"Invalid image {path}");
}
}
else
{
var provider = new TextureProvider(_fileSystem, new TextureLoaderFactory(), new UnityTextureFactory(),
"basedata.cpk", usage: TextureUsage.Sprite);
texture = provider.GetTexture(path["basedata.cpk\\".Length..])?.NativeObject as Texture2D;
if (texture == null)
throw new InvalidDataException($"Could not load original effect texture {path}");
}
texture.name = path;
texture.wrapMode = TextureWrapMode.Repeat;
texture.hideFlags = HideFlags.DontSave;
_textures.Add(path, texture);
return texture;
}
public Material Material(string texture, bool additive, bool noZ, int alphaMode = 0) =>
RenderMaterial(texture, alphaMode == 1 ? BlendMode.One : BlendMode.SrcAlpha,
additive ? BlendMode.One : BlendMode.OneMinusSrcAlpha, noZ, alphaMode, CullMode.Off);
public Material EffectTextureMaterial(string path, bool additive, bool noZ, bool battleContext)
{
try
{
return Material(path, additive, noZ);
}
catch (FileNotFoundException) when (battleContext)
{
// The native quad/grid/cylinder/trail/explosive loaders ignore
// gbTexture::LoadTexture's failure. A null D3D9 stage-0
// texture disables texturing and leaves the vertex RGBA.
_missingBattleTextures.Add(Normalize(path));
return Material("", additive, noZ);
}
}
// gfxscript/Particle{1,2,3,NotBlend}.gbf: both color and alpha modulate.
public Material SparMaterial(string texture, int shader) => shader switch
{
1 => RenderMaterial(texture, BlendMode.SrcAlpha, BlendMode.DstAlpha, false, 0, CullMode.Back),
2 => RenderMaterial(texture, BlendMode.SrcAlpha, BlendMode.OneMinusSrcColor, false, 0, CullMode.Back),
3 => RenderMaterial(texture, BlendMode.SrcColor, BlendMode.OneMinusSrcColor, false, 0, CullMode.Back),
_ => RenderMaterial(texture, BlendMode.One, BlendMode.Zero, false, 0, CullMode.Back)
};
private Material RenderMaterial(string texture, BlendMode source, BlendMode destination, bool noZ, int alphaMode, CullMode cull)
{
var key = (texture, (int)source, (int)destination, noZ, alphaMode, (int)cull);
if (_materials.TryGetValue(key, out Material cached))
return cached;
Shader shader = Shader.Find("Pal3/Effect");
if (shader == null || !shader.isSupported)
throw new InvalidOperationException("Effect URP shader is unavailable");
var material = new Material(shader) { name = $"Original {texture}", hideFlags = HideFlags.DontSave };
try
{
material.mainTexture = string.IsNullOrEmpty(texture) ? Texture2D.whiteTexture : Texture(texture);
}
catch
{
Destroy(material);
throw;
}
material.SetInt("_SrcBlend", (int)source);
material.SetInt("_DstBlend", (int)destination);
material.SetInt("_Cull", (int)cull);
material.SetInt("_ZTest", (int)(noZ ? CompareFunction.Always : CompareFunction.LessEqual));
material.SetFloat("_AlphaMode", alphaMode);
_materials.Add(key, material);
return material;
}
// Validate the complete callback closure before choosing this backend.
public string[] Diagnose(int groupId, EffectOverrides edits = null, bool battleContext = false)
{
if (edits != null)
RefreshOverrideCache(edits);
Dictionary<int, string[]> cache = battleContext ? edits == null ? _battleDiagnostics : _battleOverrideDiagnostics : edits == null ? _diagnostics : _overrideDiagnostics;
if (cache.TryGetValue(groupId, out string[] cached))
return cached;
var errors = new List<string>();
var visiting = new HashSet<int>();
var done = new HashSet<int>();
void ModelTextures(string path, CvdGeometryNode node)
{
if (node.IsGeometryNode)
foreach (CvdMeshSection section in node.Mesh.MeshSections)
{
string name = section.Material.TextureFileNames[0];
if (!string.IsNullOrEmpty(name))
ResolveTexture(RelativeTo(path, name));
}
foreach (CvdGeometryNode child in node.Children)
ModelTextures(path, child);
}
void Visit(int id)
{
if (done.Contains(id))
return;
if (!visiting.Add(id))
{
errors.Add($"Recursive callback cycle at group {id}");
return;
}
if (id < 0 || id >= Definitions.Groups.Length)
{
errors.Add($"Group {id} is outside flexeff");
visiting.Remove(id);
return;
}
EffectGroupObject[] objects = Definitions.Groups[id].Objects;
for (int index = 0; index < objects.Length; index++)
{
EffectGroupObject obj = objects[index];
Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d);
try
{
EffectTask[] tasks = obj.Tasks;
if (!EffectOverrides.Resolve(edits, id, index, ref d, ref tasks))
continue;
string kind = EffectClass.Name(d.ClassNameCrc);
switch (kind)
{
case "callback":
foreach (EffectTask t in tasks)
foreach (var child in t.Callbacks())
Visit(child.groupId);
break;
case "audio":
break;
case "action":
case "camera":
case "quake":
case "bink":
if (!battleContext)
errors.Add($"Group {id}, {d.TypeName}: unsupported original class {kind} without a combat context");
break;
case "time":
if (!battleContext)
errors.Add($"Group {id}, {d.TypeName}: unsupported original class {kind} without a combat context");
else if (tasks.Any(task => !BattleControlNode.SupportsTimeTask(task)))
errors.Add($"Group {id}, {d.TypeName}: unsupported time task parameters");
break;
case "S-Particle":
SparFile spar = Spar(d.ParticleFileName);
foreach (SparGroup sg in spar.Groups)
{
SparEmitter.Validate(sg);
ResolveTexture(RelativeTo(d.ParticleFileName, sg.Texture));
}
break;
case "particle":
ParticleFile p = Particle(d.ParticleFileName, edits);
foreach (ParticleDescription pd in p.Particles)
ResolveTexture(RelativeTo(d.ParticleFileName, pd.Texture));
foreach (ParticleEmitter e in p.Emitters)
if (e.Shape == 2)
ParticleShape(d.ParticleFileName, e.ShapePath);
break;
case "quad":
case "cylinder":
case "meteor":
case "shock":
case "grid":
case "explosive":
try
{
ResolveTexture(d.TextureName);
}
catch (FileNotFoundException) when (battleContext) { _missingBattleTextures.Add(Normalize(d.TextureName)); }
break;
case "model":
if (d.TextureName.EndsWith(".pol", StringComparison.OrdinalIgnoreCase))
{
foreach (PolMesh mesh in PolModel(d.TextureName).Meshes)
foreach (PolTexture texture in mesh.Textures)
foreach (string name in texture.Material.TextureFileNames)
if (!string.IsNullOrEmpty(name))
ResolveTexture(RelativeTo(d.TextureName, name));
}
else if (d.TextureName.EndsWith(".cvd", StringComparison.OrdinalIgnoreCase))
{
foreach (CvdGeometryNode node in Model(d.TextureName).RootNodes)
ModelTextures(d.TextureName, node);
}
else
throw new NotSupportedException($"Unknown original model format: {d.TextureName}");
break;
default:
errors.Add($"Group {id}, {d.TypeName}: unsupported original class {kind}");
break;
}
}
catch (Exception ex)
{
errors.Add($"Group {id}, {d.TypeName}: {ex.Message}");
}
}
visiting.Remove(id);
done.Add(id);
}
Visit(groupId);
string[] result = errors.ToArray();
cache[groupId] = result;
return result;
}
public IEnumerable<string> BinkMovies(int groupId, EffectOverrides edits = null)
{
EffectGroupObject[] objects = Definitions.Groups[groupId].Objects;
for (int index = 0; index < objects.Length; index++)
{
Definitions.TryGetType(objects[index].TypeCrc, out EffectDefinition definition);
EffectTask[] tasks = objects[index].Tasks;
if (!EffectOverrides.Resolve(edits, groupId, index, ref definition, ref tasks) || EffectClass.Name(definition.ClassNameCrc) != "bink")
continue;
foreach (EffectTask task in tasks)
if (task.XStretchSpeed != 0)
yield return definition.VideoFileNamePrefix + ((int)MathF.Round(task.XStretchSpeed)).ToString("000") + ".bik";
}
}
public IEnumerable<int> Preload(int groupId, EffectOverrides edits = null, bool battleContext = false)
{
var seen = new HashSet<int>();
var pending = new Stack<int>();
pending.Push(groupId);
while (pending.Count > 0)
{
int id = pending.Pop();
if (!seen.Add(id))
continue;
EffectGroupObject[] objects = Definitions.Groups[id].Objects;
for (int index = 0; index < objects.Length; index++)
{
EffectGroupObject obj = objects[index];
Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d);
EffectTask[] tasks = obj.Tasks;
if (!EffectOverrides.Resolve(edits, id, index, ref d, ref tasks))
continue;
string kind = EffectClass.Name(d.ClassNameCrc);
if (kind == "callback")
foreach (EffectTask t in tasks)
foreach (var child in t.Callbacks())
pending.Push(child.groupId);
else if (kind == "particle")
foreach (ParticleDescription p in Particle(d.ParticleFileName, edits).Particles)
Texture(RelativeTo(d.ParticleFileName, p.Texture));
else if (kind == "S-Particle")
foreach (SparGroup group in Spar(d.ParticleFileName).Groups)
Texture(RelativeTo(d.ParticleFileName, group.Texture));
else if (battleContext && kind is "quad" or "grid" or "cylinder" or "meteor" or "shock" or "explosive")
EffectTextureMaterial(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored, true);
else if (kind is not ("audio" or "model" or "action" or "camera" or "quake" or "bink" or "time"))
Texture(d.TextureName);
yield return id;
}
}
}
public void TrimUnusedRenderAssets(IEnumerable<GameObject> liveRoots)
{
var materials = new HashSet<Material>();
var textures = new HashSet<Texture>();
foreach (GameObject root in liveRoots)
{
if (root == null)
continue;
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
foreach (Material material in renderer.sharedMaterials)
Keep(material);
// Combat phase copies borrow live cache materials as their
// update source; renderer references alone only see the copies.
foreach (GameBoxBattleRenderPhase phase in root.GetComponentsInChildren<GameBoxBattleRenderPhase>(true))
foreach (Material material in phase.SourceMaterials)
Keep(material);
}
void Keep(Material material)
{
if (material == null)
return;
materials.Add(material);
foreach (int property in material.GetTexturePropertyNameIDs())
{
Texture texture = material.GetTexture(property);
if (texture != null)
textures.Add(texture);
}
}
foreach (var key in _materials.Where(p => !materials.Contains(p.Value)).Select(p => p.Key).ToArray())
{
Destroy(_materials[key]);
_materials.Remove(key);
}
foreach (string key in _textures.Where(p => !textures.Contains(p.Value)).Select(p => p.Key).ToArray())
{
Destroy(_textures[key]);
_textures.Remove(key);
}
}
public void Dispose()
{
foreach (Material m in _materials.Values)
Destroy(m);
foreach (Texture2D t in _textures.Values)
Destroy(t);
_materials.Clear();
_textures.Clear();
_particles.Clear();
_particleBytes.Clear();
_overrideParticles.Clear();
_shapes.Clear();
_models.Clear();
_polModels.Clear();
_sparFiles.Clear();
_diagnostics.Clear();
_overrideDiagnostics.Clear();
_battleOverrideDiagnostics.Clear();
_battleDiagnostics.Clear();
_missingBattleTextures.Clear();
_cachedOverrides = null;
_cachedOverridesJson = null;
}
public static void Destroy(UnityEngine.Object value)
{
if (value == null)
return;
if (Application.isPlaying)
UnityEngine.Object.Destroy(value);
else
UnityEngine.Object.DestroyImmediate(value);
}
}
}