diff --git a/.editorconfig b/.editorconfig index bafaa5ae..a65cb239 100644 --- a/.editorconfig +++ b/.editorconfig @@ -45,7 +45,7 @@ csharp_preserve_single_line_statements = false csharp_preserve_single_line_blocks = false # SDK whitespace formatting does not enforce spacing between members. -# These targeted StyleCop rules also run through tools/format-csharp.py. +# These targeted StyleCop rules also run through tools/CodeStyle. dotnet_diagnostic.SA1107.severity = warning dotnet_diagnostic.SA1502.severity = warning dotnet_diagnostic.SA1507.severity = warning diff --git a/.github/CI.md b/.github/CI.md index 7e29c1ff..14254cd3 100644 --- a/.github/CI.md +++ b/.github/CI.md @@ -12,19 +12,25 @@ badges prefer the default branch and can keep showing old push builds after a workflow switches to PR-only triggers. The badge links filter the build history to pull requests as well. -The separate `Code style` workflow verifies changed owned C# files with the SDK's -`dotnet format`, using `.editorconfig` and the SDK pinned in `global.json`. -It combines whitespace formatting with pinned StyleCop layout rules SA1107, SA1502, -SA1507 and SA1516 to enforce separate statements, multiline blocks and blank lines -between members. StyleCop is restored only into the temporary formatting project. +The separate `Code style` workflow runs the .NET CLI in `tools/CodeStyle`, using +`.editorconfig` and the SDK pinned in `global.json`. +It calls the SDK's `dotnet format` for whitespace and StyleCop 1.3.180 layout rules +SA1107, SA1502, SA1507 and SA1516 to enforce separate statements, multiline blocks +and blank lines between members. StyleCop is restored only into the temporary +formatting project. It parses both PAL3 and PAL3A conditional branches without Unity or game data. -Run `python3 tools/format-csharp.py` locally to format current changes, then -`python3 tools/format-csharp.py --check` to verify them. CI selects PR changes with +Run `dotnet run --project tools/CodeStyle --` locally to format current changes, +then `dotnet run --project tools/CodeStyle -- --check` to verify them. +The formatter and its tests require no Python, Unity installation or game data. +CI runs `dotnet test tools/CodeStyle.Tests`, then uses the SDK's +`dotnet format whitespace --verify-no-changes` on both `tools/CodeStyle` and +`tools/CodeStyle.Tests` to check the tool's own sources. Finally, it selects PR changes with `--check --base `; `--all` is an explicit full-source audit, not the default. Default and `--base` runs apply formatting only to changed lines and deletion boundaries, preserving existing formatting elsewhere. Explicit file/directory paths and `--all` format whole files. Check mode operates on temporary copies. This checks whitespace and layout, not semantic correctness or Unity behavior. +See the [tool README](../tools/CodeStyle/README.md) for commands and scope. Codacy is not part of this repository's CI. Its repository webhook is disabled; there is no Codacy workflow or Codacy-required branch protection check. Re-enabling diff --git a/.github/workflows/build-pal3a-mono-android.yml b/.github/workflows/build-pal3a-mono-android.yml index d96ef963..3c05cdae 100644 --- a/.github/workflows/build-pal3a-mono-android.yml +++ b/.github/workflows/build-pal3a-mono-android.yml @@ -29,12 +29,11 @@ jobs: with: fetch-depth: 0 lfs: true - - name: Switch define symbol from PAL3 to PAL3A - uses: jacobtomlinson/gha-find-replace@v3 - with: - find: "PAL3" - replace: "PAL3A" - include: "**ProjectSettings.asset" + - name: Switch project settings from PAL3 to PAL3A + run: | + settings=ProjectSettings/ProjectSettings.asset + sed -E 's/PAL3([^[:alnum:]_]|$)/PAL3A\1/g' "$settings" > "$settings.tmp" + mv "$settings.tmp" "$settings" - name: Replace PAL3 game icon with PAL3A one uses: jacobtomlinson/gha-find-replace@v3 with: diff --git a/.github/workflows/build-pal3a-mono-ios.yml b/.github/workflows/build-pal3a-mono-ios.yml index 0c297dc8..a8dc7568 100644 --- a/.github/workflows/build-pal3a-mono-ios.yml +++ b/.github/workflows/build-pal3a-mono-ios.yml @@ -20,12 +20,11 @@ jobs: with: fetch-depth: 0 lfs: true - - name: Switch define symbol from PAL3 to PAL3A - uses: jacobtomlinson/gha-find-replace@v3 - with: - find: "PAL3" - replace: "PAL3A" - include: "**ProjectSettings.asset" + - name: Switch project settings from PAL3 to PAL3A + run: | + settings=ProjectSettings/ProjectSettings.asset + sed -E 's/PAL3([^[:alnum:]_]|$)/PAL3A\1/g' "$settings" > "$settings.tmp" + mv "$settings.tmp" "$settings" - name: Replace PAL3 game icon with PAL3A one uses: jacobtomlinson/gha-find-replace@v3 with: diff --git a/.github/workflows/build-pal3a-mono-linux.yml b/.github/workflows/build-pal3a-mono-linux.yml index 602759e9..361bdc38 100644 --- a/.github/workflows/build-pal3a-mono-linux.yml +++ b/.github/workflows/build-pal3a-mono-linux.yml @@ -20,12 +20,11 @@ jobs: with: fetch-depth: 0 lfs: true - - name: Switch define symbol from PAL3 to PAL3A - uses: jacobtomlinson/gha-find-replace@v3 - with: - find: "PAL3" - replace: "PAL3A" - include: "**ProjectSettings.asset" + - name: Switch project settings from PAL3 to PAL3A + run: | + settings=ProjectSettings/ProjectSettings.asset + sed -E 's/PAL3([^[:alnum:]_]|$)/PAL3A\1/g' "$settings" > "$settings.tmp" + mv "$settings.tmp" "$settings" - name: Replace PAL3 game icon with PAL3A one uses: jacobtomlinson/gha-find-replace@v3 with: diff --git a/.github/workflows/build-pal3a-mono-macos.yml b/.github/workflows/build-pal3a-mono-macos.yml index ea9a332e..9394f9a5 100644 --- a/.github/workflows/build-pal3a-mono-macos.yml +++ b/.github/workflows/build-pal3a-mono-macos.yml @@ -20,12 +20,11 @@ jobs: with: fetch-depth: 0 lfs: true - - name: Switch define symbol from PAL3 to PAL3A - uses: jacobtomlinson/gha-find-replace@v3 - with: - find: "PAL3" - replace: "PAL3A" - include: "**ProjectSettings.asset" + - name: Switch project settings from PAL3 to PAL3A + run: | + settings=ProjectSettings/ProjectSettings.asset + sed -E 's/PAL3([^[:alnum:]_]|$)/PAL3A\1/g' "$settings" > "$settings.tmp" + mv "$settings.tmp" "$settings" - name: Replace PAL3 game icon with PAL3A one uses: jacobtomlinson/gha-find-replace@v3 with: diff --git a/.github/workflows/build-pal3a-mono-windows.yml b/.github/workflows/build-pal3a-mono-windows.yml index d20df774..cc0fe22d 100644 --- a/.github/workflows/build-pal3a-mono-windows.yml +++ b/.github/workflows/build-pal3a-mono-windows.yml @@ -21,12 +21,11 @@ jobs: with: fetch-depth: 0 lfs: true - - name: Switch define symbol from PAL3 to PAL3A - uses: jacobtomlinson/gha-find-replace@v3 - with: - find: "PAL3" - replace: "PAL3A" - include: "**ProjectSettings.asset" + - name: Switch project settings from PAL3 to PAL3A + run: | + settings=ProjectSettings/ProjectSettings.asset + sed -E 's/PAL3([^[:alnum:]_]|$)/PAL3A\1/g' "$settings" > "$settings.tmp" + mv "$settings.tmp" "$settings" - name: Replace PAL3 game icon with PAL3A one uses: jacobtomlinson/gha-find-replace@v3 with: diff --git a/.github/workflows/code-style.yml b/.github/workflows/code-style.yml index 40cea5b5..c6bfdf96 100644 --- a/.github/workflows/code-style.yml +++ b/.github/workflows/code-style.yml @@ -22,8 +22,23 @@ jobs: with: global-json-file: global.json - name: Test formatter enforcement - run: python3 tools/tests/test-format-csharp.py + run: dotnet test tools/CodeStyle.Tests + - name: Verify .NET tool source formatting + run: | + dotnet format whitespace tools/CodeStyle --no-restore --verify-no-changes + dotnet format whitespace tools/CodeStyle.Tests --no-restore --verify-no-changes - name: Verify changed C# formatting env: BASE_REF: ${{ github.event.pull_request.base.sha }} - run: python3 tools/format-csharp.py --check --base "$BASE_REF" + run: dotnet run --project tools/CodeStyle -- --check --base "$BASE_REF" + + battle-rules: + name: Battle rules (PAL3 and PAL3A) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7.0.1 + - uses: actions/setup-dotnet@v5.3.0 + with: + global-json-file: global.json + - name: Run engine-independent battle tests + run: dotnet test tools/Battle.Tests diff --git a/.gitignore b/.gitignore index 30615b12..05210977 100644 --- a/.gitignore +++ b/.gitignore @@ -89,3 +89,8 @@ crashlytics-build.properties /Assets/Resources/Prefabs/VFX.meta /Assets/Resources/Materials/ /Assets/Resources/Materials.meta + +# Standalone .NET developer tools +/tools/**/bin/ +/tools/**/obj/ +/tools/**/TestResults/ diff --git a/Assets/Rendering/Toon/Pal3ToonDepth.hlsl b/Assets/Rendering/Toon/Pal3ToonDepth.hlsl index d68bcc6d..8bf730ce 100644 --- a/Assets/Rendering/Toon/Pal3ToonDepth.hlsl +++ b/Assets/Rendering/Toon/Pal3ToonDepth.hlsl @@ -10,6 +10,8 @@ struct ToonDepthVaryings float4 positionCS : SV_POSITION; #if defined(PAL3_TOON_CUTOUT) float2 uv : TEXCOORD0; + float2 lightmapUV : TEXCOORD2; + float4 paintedVertexColor : TEXCOORD3; #endif #if defined(PAL3_TOON_DEPTH_NORMALS) half3 normalWS : TEXCOORD1; @@ -28,6 +30,8 @@ ToonDepthVaryings ToonDepthVertex(ToonAttributes input) #endif #if defined(PAL3_TOON_CUTOUT) output.uv = TRANSFORM_TEX(input.uv, _MainTex); + output.lightmapUV = TRANSFORM_TEX(input.lightmapUV, _ShadowTex); + output.paintedVertexColor = ToonPaintedVertexColor(input.color); #endif return output; } @@ -39,7 +43,14 @@ half ToonDepthFragment(ToonDepthVaryings input) : SV_Target #endif { #if defined(PAL3_TOON_CUTOUT) - clip(SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv).a - _Threshold); + half4 color = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv); + half alpha = color.a; + if (_UnlitBackground > 0.5) + { + half4 lightmap = _HasShadowTex > 0.5 ? SAMPLE_TEXTURE2D(_ShadowTex, sampler_ShadowTex, input.lightmapUV) : 1.0; + alpha = ToonPaintedTextureStages(color, lightmap, input.paintedVertexColor).a; + } + clip(alpha - _Threshold); #endif #if defined(PAL3_TOON_DEPTH_NORMALS) float3 normalWS = SafeNormalize(input.normalWS); diff --git a/Assets/Rendering/Toon/Pal3ToonForward.hlsl b/Assets/Rendering/Toon/Pal3ToonForward.hlsl index fe8d71df..751b5efc 100644 --- a/Assets/Rendering/Toon/Pal3ToonForward.hlsl +++ b/Assets/Rendering/Toon/Pal3ToonForward.hlsl @@ -19,6 +19,7 @@ struct ToonVaryings float3 positionWS : TEXCOORD2; half3 normalWS : TEXCOORD3; float fogFactor : TEXCOORD4; + float4 paintedVertexColor : TEXCOORD5; UNITY_VERTEX_OUTPUT_STEREO }; @@ -33,6 +34,7 @@ ToonVaryings ToonVertex(ToonAttributes input) output.uv = TRANSFORM_TEX(input.uv, _MainTex); output.lightmapUV = TRANSFORM_TEX(input.lightmapUV, _ShadowTex); output.fogFactor = ComputeFogFactor(output.positionCS.z); + output.paintedVertexColor = ToonPaintedVertexColor(input.color); return output; } @@ -148,29 +150,53 @@ half4 ToonFragment(ToonVaryings input) : SV_Target { UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input); half4 color = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv); + half3 selectionTexture = color.rgb; + half classificationAlpha = color.a; + half4 lightmap = 1.0; + if (_HasShadowTex > 0.5) + lightmap = SAMPLE_TEXTURE2D(_ShadowTex, sampler_ShadowTex, input.lightmapUV); + if (_UnlitBackground > 0.5) + { + color = ToonPaintedTextureStages(color, lightmap, input.paintedVertexColor); + classificationAlpha = color.a; + } #if defined(PAL3_TOON_CUTOUT) - clip(color.a - _Threshold); + clip(classificationAlpha - _Threshold); #elif defined(PAL3_TOON_TRANSPARENT) - if (color.a >= _Threshold || (color.a <= 0.0 && _Threshold <= 1.0)) + if (classificationAlpha >= _Threshold || (classificationAlpha <= 0.0 && _Threshold <= 1.0)) discard; #endif - half3 baked = 1.0; - if (_HasShadowTex > 0.5) - baked = SAMPLE_TEXTURE2D(_ShadowTex, sampler_ShadowTex, input.lightmapUV).rgb * _LightmapScale; + if (_UnlitBackground > 0.5) + { + color.rgb *= _TintColor.rgb; + color.rgb *= _BackgroundBrightness; + } + else + { + half3 baked = _HasShadowTex > 0.5 ? lightmap.rgb * _LightmapScale : 1.0; + color *= _TintColor; + #if defined(PAL3_TOON_WATER) + // The first frame defines opacity for the full water animation. + color.a = _Alpha; + #endif + #if defined(PAL3_TOON_TRANSPARENT) + if (_ReceiveLighting < 0.5) + color.rgb *= baked; + else + #endif + color.rgb = ShadeToon(color.rgb, baked, input.positionCS, input.positionWS, SafeNormalize(input.normalWS)); + } - color *= _TintColor; - #if defined(PAL3_TOON_WATER) - // The first frame defines opacity for the full water animation. - color.a = _Alpha; + #if !defined(PAL3_TOON_CUTOUT) && !defined(PAL3_TOON_TRANSPARENT) && !defined(PAL3_TOON_WATER) + // Opaque painted POL layers must remain opaque in the preview target. + if (_UnlitBackground > 0.5) + color.a = 1.0; #endif - #if defined(PAL3_TOON_TRANSPARENT) - if (_ReceiveLighting < 0.5) - color.rgb *= baked; - else + #if !defined(PAL3_TOON_WATER) + if (_BattleSelection >= 0) + color.rgb = selectionTexture * _BattleSelection; #endif - color.rgb = ShadeToon(color.rgb, baked, input.positionCS, input.positionWS, SafeNormalize(input.normalWS)); - color.rgb = MixFog(color.rgb, input.fogFactor); return color; } diff --git a/Assets/Rendering/Toon/Pal3ToonInput.hlsl b/Assets/Rendering/Toon/Pal3ToonInput.hlsl index 02c60dd3..4ff63420 100644 --- a/Assets/Rendering/Toon/Pal3ToonInput.hlsl +++ b/Assets/Rendering/Toon/Pal3ToonInput.hlsl @@ -13,16 +13,22 @@ SAMPLER(sampler_MainTex); TEXTURE2D(_ShadowTex); SAMPLER(sampler_ShadowTex); +float _GbVertexColor; + CBUFFER_START(UnityPerMaterial) float4 _MainTex_ST; float4 _ShadowTex_ST; half4 _TintColor; + half _BattleSelection; float _Threshold; float _HasShadowTex; float _LightmapScale; float _ReceiveLighting; float _ReceiveShadows; float _IsCharacter; + float _UnlitBackground; + float _BackgroundBrightness; + float _SourceDiffuseAlpha; #if defined(PAL3_TOON_WATER) float _Alpha; #endif @@ -32,9 +38,27 @@ struct ToonAttributes { float4 positionOS : POSITION; float3 normalOS : NORMAL; + float4 color : COLOR; float2 uv : TEXCOORD0; float2 lightmapUV : TEXCOORD1; UNITY_VERTEX_INPUT_INSTANCE_ID }; +float4 ToonPaintedVertexColor(float4 vertexColor) +{ + float4 color = _GbVertexColor > 0.5 ? vertexColor : float4(1, 1, 1, _SourceDiffuseAlpha); + color.a *= _TintColor.a; + return color; +} + +half4 ToonPaintedTextureStages(half4 mainColor, half4 lightmap, float4 vertexColor) +{ + // Original static POL stages. Painted surfaces remain independent of scene lights. + vertexColor = saturate(vertexColor); + if (_HasShadowTex > 0.5) + return saturate(half4(lightmap.rgb * mainColor.rgb * 2, + lightmap.a * mainColor.a * vertexColor.a * 2)); + return saturate(mainColor * vertexColor); +} + #endif diff --git a/Assets/Rendering/Toon/Resources/Pal3ToonCutout.shader b/Assets/Rendering/Toon/Resources/Pal3ToonCutout.shader index 011e210e..72ce4821 100644 --- a/Assets/Rendering/Toon/Resources/Pal3ToonCutout.shader +++ b/Assets/Rendering/Toon/Resources/Pal3ToonCutout.shader @@ -7,13 +7,18 @@ Shader "Pal3/ToonCutout" { Properties { + [HideInInspector] _ReceiveLighting ("Receive Lighting", Float) = 1 _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _BattleSelection ("Battle selection luminance", Float) = -1 _TintColor ("Tint Color", Color) = (1, 1, 1, 1) _ShadowTex ("Baked Shadow", 2D) = "white" {} _HasShadowTex ("Has Baked Shadow", Float) = 0 _LightmapScale ("Baked Light Scale", Float) = 1.666667 _ReceiveShadows ("Receive Shadows", Float) = 1 [HideInInspector] _IsCharacter ("Character", Float) = 0 + [HideInInspector] _UnlitBackground ("Painted background", Float) = 0 + [HideInInspector] _BackgroundBrightness ("Background brightness", Float) = 1 + [HideInInspector] _SourceDiffuseAlpha ("Original POL diffuse alpha", Float) = 1 _Threshold ("Alpha Cutoff", Float) = 1 } diff --git a/Assets/Rendering/Toon/Resources/Pal3ToonOpaque.shader b/Assets/Rendering/Toon/Resources/Pal3ToonOpaque.shader index b596454f..f444e3ea 100644 --- a/Assets/Rendering/Toon/Resources/Pal3ToonOpaque.shader +++ b/Assets/Rendering/Toon/Resources/Pal3ToonOpaque.shader @@ -7,13 +7,19 @@ Shader "Pal3/ToonOpaque" { Properties { + [HideInInspector] _Threshold ("Alpha Cutoff", Float) = 1 + [HideInInspector] _ReceiveLighting ("Receive Lighting", Float) = 1 _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _BattleSelection ("Battle selection luminance", Float) = -1 _TintColor ("Tint Color", Color) = (1, 1, 1, 1) _ShadowTex ("Baked Shadow", 2D) = "white" {} _HasShadowTex ("Has Baked Shadow", Float) = 0 _LightmapScale ("Baked Light Scale", Float) = 1.666667 _ReceiveShadows ("Receive Shadows", Float) = 1 [HideInInspector] _IsCharacter ("Character", Float) = 0 + [HideInInspector] _UnlitBackground ("Painted background", Float) = 0 + [HideInInspector] _BackgroundBrightness ("Background brightness", Float) = 1 + [HideInInspector] _SourceDiffuseAlpha ("Original POL diffuse alpha", Float) = 1 } SubShader diff --git a/Assets/Rendering/Toon/Resources/Pal3ToonTransparent.shader b/Assets/Rendering/Toon/Resources/Pal3ToonTransparent.shader index 714198ba..86aba76a 100644 --- a/Assets/Rendering/Toon/Resources/Pal3ToonTransparent.shader +++ b/Assets/Rendering/Toon/Resources/Pal3ToonTransparent.shader @@ -8,12 +8,16 @@ Shader "Pal3/ToonTransparent" Properties { _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _BattleSelection ("Battle selection luminance", Float) = -1 _TintColor ("Tint Color", Color) = (1, 1, 1, 1) _ShadowTex ("Baked Shadow", 2D) = "white" {} _HasShadowTex ("Has Baked Shadow", Float) = 0 _LightmapScale ("Baked Light Scale", Float) = 1.666667 _ReceiveShadows ("Receive Shadows", Float) = 1 [HideInInspector] _IsCharacter ("Character", Float) = 0 + [HideInInspector] _UnlitBackground ("Painted background", Float) = 0 + [HideInInspector] _BackgroundBrightness ("Background brightness", Float) = 1 + [HideInInspector] _SourceDiffuseAlpha ("Original POL diffuse alpha", Float) = 1 _Threshold ("Alpha Cutoff", Float) = 1 _ReceiveLighting ("Receive Lighting", Float) = 1 [Enum(UnityEngine.Rendering.BlendMode)] _BlendSrcFactor ("Source Blend Factor", Int) = 5 diff --git a/Assets/Rendering/Toon/Resources/Pal3ToonWater.shader b/Assets/Rendering/Toon/Resources/Pal3ToonWater.shader index 520851b7..76448099 100644 --- a/Assets/Rendering/Toon/Resources/Pal3ToonWater.shader +++ b/Assets/Rendering/Toon/Resources/Pal3ToonWater.shader @@ -7,12 +7,19 @@ Shader "Pal3/ToonWater" { Properties { + [HideInInspector] _Threshold ("Alpha Cutoff", Float) = 1 + [HideInInspector] _ReceiveLighting ("Receive Lighting", Float) = 1 + [HideInInspector] _IsCharacter ("Character", Float) = 0 + [HideInInspector] _BattleSelection ("Battle selection luminance", Float) = -1 _MainTex ("Texture", 2D) = "white" {} _ShadowTex ("Baked Shadow", 2D) = "white" {} _HasShadowTex ("Has Baked Shadow", Float) = 0 _LightmapScale ("Baked Light Scale", Float) = 1.428571 _Alpha ("Opacity", Range(0, 1)) = 0.5 _ReceiveShadows ("Receive Shadows", Float) = 1 + [HideInInspector] _UnlitBackground ("Painted background", Float) = 0 + [HideInInspector] _BackgroundBrightness ("Background brightness", Float) = 1 + [HideInInspector] _SourceDiffuseAlpha ("Original POL diffuse alpha", Float) = 1 [HideInInspector] _TintColor ("Tint Color", Color) = (1, 1, 1, 1) } diff --git a/Assets/Resources/Shaders/GameBoxNativeLighting.hlsl b/Assets/Resources/Shaders/GameBoxNativeLighting.hlsl new file mode 100644 index 00000000..daca203c --- /dev/null +++ b/Assets/Resources/Shaders/GameBoxNativeLighting.hlsl @@ -0,0 +1,70 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +#ifndef PAL3_GAMEBOX_NATIVE_LIGHTING_INCLUDED +#define PAL3_GAMEBOX_NATIVE_LIGHTING_INCLUDED + +float _GbVertexUnits; +float _GbVertexColor; +float _GbLightCount; +float4 _GbLightPosition0; +float4 _GbLightPosition1; +float4 _GbLightDiffuse0; +float4 _GbLightDiffuse1; +float4 _GbLightAmbient0; +float4 _GbLightAmbient1; +float4 _GbLightAttenuation0; +float4 _GbLightAttenuation1; +float4x4 _GbSourceFromRenderer; + +float3 GameBoxVertexLight(float3 position, float3 normal, float3 lightPosition, + float3 diffuse, float3 ambient, float3 attenuation) +{ + float3 delta = lightPosition - position; + float distanceSquared = dot(delta, delta); + float distance = sqrt(distanceSquared); + float3 direction = delta / max(distance, 0.000001); + float strength = rcp(max(dot(attenuation, float3(1, distance, distanceSquared)), 0.000001)); + return strength * max(dot(normal, direction), 0) * _GbMaterialDiffuse.rgb * diffuse + + _GbMaterialAmbient.rgb * (ambient + 0.2); +} + +float4 GameBoxVertexColor(float3 position, float3 normal, float4 vertexColor) +{ + if (_GbVertexColor > 0.5) + return float4(vertexColor.rgb, vertexColor.a * (_GbNativeLighting > 0.5 ? _TintColor.a : 1)); + if (_GbNativeLighting < 0.5) + return 1; + float3 color = _GbMaterialAmbient.rgb * 0.2; + // CVD geometry bakes its animated node matrix into vertex positions. + // Undo that matrix for the original node-local light/normal calculation. + position = mul(_GbSourceFromRenderer, float4(position, 1)).xyz * _GbVertexUnits; + if (_GbLightCount > 0.5) + color = GameBoxVertexLight(position, normal, _GbLightPosition0.xyz, + _GbLightDiffuse0.rgb, _GbLightAmbient0.rgb, _GbLightAttenuation0.xyz); + if (_GbLightCount > 1.5) + color += GameBoxVertexLight(position, normal, _GbLightPosition1.xyz, + _GbLightDiffuse1.rgb, _GbLightAmbient1.rgb, _GbLightAttenuation1.xyz); + // Preserve the native, unnormalized interpolated morph normal. + return float4(color, _GbMaterialDiffuse.a * _TintColor.a); +} + +half4 GameBoxTextureStages(half4 mainColor, half4 lightmap, float4 vertexColor, float hasLightmap) +{ + if (_GbNativeLighting < 0.5) + return mainColor; + vertexColor = saturate(vertexColor); + if (hasLightmap > 0.5) + { + half3 firstStage = lightmap.rgb; + if (_GbLightCount > 0.5 && _GbVertexColor < 0.5) + firstStage = saturate(firstStage + vertexColor.rgb); + return saturate(half4(firstStage * mainColor.rgb * 2, + lightmap.a * mainColor.a * vertexColor.a * 2)); + } + return saturate(mainColor * vertexColor); +} + +#endif diff --git a/Assets/Resources/Shaders/GameBoxNativeLighting.hlsl.meta b/Assets/Resources/Shaders/GameBoxNativeLighting.hlsl.meta new file mode 100644 index 00000000..1e725b10 --- /dev/null +++ b/Assets/Resources/Shaders/GameBoxNativeLighting.hlsl.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 506edd8164c54d5a8bbe5294ca720df5 diff --git a/Assets/Resources/Shaders/Pal3BattleShadow.shader b/Assets/Resources/Shaders/Pal3BattleShadow.shader new file mode 100644 index 00000000..84c09dbe --- /dev/null +++ b/Assets/Resources/Shaders/Pal3BattleShadow.shader @@ -0,0 +1,58 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +Shader "Pal3/BattleShadow" +{ + Properties + { + _MainTex ("Original shadow texture", 2D) = "white" {} + [Enum(UnityEngine.Rendering.BlendMode)] _SrcBlend ("Source blend", Float) = 2 + [Enum(UnityEngine.Rendering.BlendMode)] _DstBlend ("Destination blend", Float) = 0 + } + SubShader + { + Tags { "RenderPipeline" = "UniversalPipeline" "Queue" = "Transparent+1" "RenderType" = "Transparent" } + Pass + { + Tags { "LightMode" = "SRPDefaultUnlit" } + Blend [_SrcBlend] [_DstBlend] + ZTest LEqual + ZWrite Off + Cull Off + HLSLPROGRAM + #pragma vertex Vert + #pragma fragment Frag + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + TEXTURE2D(_MainTex); + SAMPLER(sampler_MainTex); + + struct Attributes + { + float3 positionOS : POSITION; + float2 uv : TEXCOORD0; + }; + + struct Varyings + { + float4 positionCS : SV_POSITION; + float2 uv : TEXCOORD0; + }; + + Varyings Vert(Attributes input) + { + Varyings output; + output.positionCS = TransformObjectToHClip(input.positionOS); + output.uv = input.uv; + return output; + } + + half4 Frag(Varyings input) : SV_Target + { + return SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv); + } + ENDHLSL + } + } +} diff --git a/Assets/Resources/Shaders/Pal3BattleShadow.shader.meta b/Assets/Resources/Shaders/Pal3BattleShadow.shader.meta new file mode 100644 index 00000000..0630caee --- /dev/null +++ b/Assets/Resources/Shaders/Pal3BattleShadow.shader.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: aab071a0286c4b91a964c543ba090aee diff --git a/Assets/Resources/Shaders/Pal3BattleTrail.shader b/Assets/Resources/Shaders/Pal3BattleTrail.shader new file mode 100644 index 00000000..c1032748 --- /dev/null +++ b/Assets/Resources/Shaders/Pal3BattleTrail.shader @@ -0,0 +1,66 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +Shader "Hidden/Pal3/BattleTrail" +{ + Properties + { + _MainTex ("History", 2D) = "black" {} + _Diffuse ("Original diffuse", Vector) = (1, 1, 1, 1) + } + SubShader + { + Tags { "RenderPipeline" = "UniversalPipeline" } + Pass + { + Blend SrcAlpha One + ZTest Always + ZWrite Off + Cull Off + HLSLPROGRAM + #pragma vertex Vert + #pragma fragment Frag + #include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl" + TEXTURE2D(_MainTex); + SAMPLER(sampler_MainTex); + + CBUFFER_START(UnityPerMaterial) + float4 _MainTex_TexelSize; + float4 _Diffuse; + CBUFFER_END + + struct Attributes + { + float4 positionOS : POSITION; + float2 uv : TEXCOORD0; + }; + + struct Varyings + { + float4 positionCS : SV_POSITION; + float2 uv : TEXCOORD0; + }; + + Varyings Vert(Attributes input) + { + Varyings output; + output.positionCS = TransformObjectToHClip(input.positionOS.xyz); + output.uv = input.uv; + #if UNITY_UV_STARTS_AT_TOP + if (_MainTex_TexelSize.y < 0) + output.uv.y = 1 - output.uv.y; + #endif + output.uv.y *= .75; + return output; + } + + float4 Frag(Varyings input) : SV_Target + { + return float4(SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, input.uv).rgb * _Diffuse.rgb, _Diffuse.a); + } + ENDHLSL + } + } +} diff --git a/Assets/Resources/Shaders/Pal3BattleTrail.shader.meta b/Assets/Resources/Shaders/Pal3BattleTrail.shader.meta new file mode 100644 index 00000000..2feabc37 --- /dev/null +++ b/Assets/Resources/Shaders/Pal3BattleTrail.shader.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0f5b735021d84bea9f91e0a6f9ef3d87 diff --git a/Assets/Resources/Shaders/Pal3OriginalEffect.shader b/Assets/Resources/Shaders/Pal3Effect.shader similarity index 98% rename from Assets/Resources/Shaders/Pal3OriginalEffect.shader rename to Assets/Resources/Shaders/Pal3Effect.shader index 3b79142a..8b6cd6bd 100644 --- a/Assets/Resources/Shaders/Pal3OriginalEffect.shader +++ b/Assets/Resources/Shaders/Pal3Effect.shader @@ -3,7 +3,7 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -Shader "Pal3/OriginalEffect" +Shader "Pal3/Effect" { Properties { diff --git a/Assets/Resources/Shaders/Pal3OriginalEffect.shader.meta b/Assets/Resources/Shaders/Pal3Effect.shader.meta similarity index 100% rename from Assets/Resources/Shaders/Pal3OriginalEffect.shader.meta rename to Assets/Resources/Shaders/Pal3Effect.shader.meta diff --git a/Assets/Resources/Shaders/Pal3Opaque.shader b/Assets/Resources/Shaders/Pal3Opaque.shader index 8f93cb50..a1b4830d 100644 --- a/Assets/Resources/Shaders/Pal3Opaque.shader +++ b/Assets/Resources/Shaders/Pal3Opaque.shader @@ -8,6 +8,10 @@ Shader "Pal3/Opaque" Properties { _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _GbNativeLighting ("Original battle lighting", Float) = 0 + [HideInInspector] _GbMaterialDiffuse ("Original material diffuse", Vector) = (1, 1, 1, 1) + [HideInInspector] _GbMaterialAmbient ("Original material ambient", Vector) = (1, 1, 1, 1) + [HideInInspector] _BattleSelection ("Battle selection luminance", Float) = -1 _TintColor ("Tint color", Color) = (1.0, 1.0, 1.0, 1.0) _HasShadowTex ("Has Shadow Texture", Range(0, 1)) = 0.0 @@ -35,6 +39,8 @@ Shader "Pal3/Opaque" struct appdata_t { float4 vertex : POSITION; + float3 normal : NORMAL; + float4 color : COLOR; float2 texcoord0 : TEXCOORD0; float2 texcoord1 : TEXCOORD1; UNITY_VERTEX_INPUT_INSTANCE_ID @@ -46,6 +52,7 @@ Shader "Pal3/Opaque" float2 texcoord0 : TEXCOORD0; float2 texcoord1 : TEXCOORD1; float fogFactor : TEXCOORD7; + float4 nativeColor : TEXCOORD2; UNITY_VERTEX_OUTPUT_STEREO }; @@ -55,19 +62,26 @@ Shader "Pal3/Opaque" SAMPLER(sampler_ShadowTex); CBUFFER_START(UnityPerMaterial) + float _GbNativeLighting; + float4 _GbMaterialDiffuse; + float4 _GbMaterialAmbient; float4 _MainTex_ST; float4 _TintColor; + float _BattleSelection; float _HasShadowTex; float4 _ShadowTex_ST; float _LightmapScale; CBUFFER_END + #include "GameBoxNativeLighting.hlsl" + v2f vert(appdata_t v) { v2f o; UNITY_SETUP_INSTANCE_ID(v); UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); o.vertex = TransformObjectToHClip(v.vertex.xyz); + o.nativeColor = GameBoxVertexColor(v.vertex.xyz, v.normal, v.color); o.texcoord0 = TRANSFORM_TEX(v.texcoord0, _MainTex); o.texcoord1 = TRANSFORM_TEX(v.texcoord1, _ShadowTex); o.fogFactor = ComputeFogFactor(o.vertex.z); @@ -77,15 +91,28 @@ Shader "Pal3/Opaque" half4 frag(v2f i) : SV_Target { half4 color = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.texcoord0); - if(_HasShadowTex > 0.5f) + half3 selectionTexture = color.rgb; + if (_GbNativeLighting > 0.5) + { + half4 lightmap = _HasShadowTex > 0.5 ? SAMPLE_TEXTURE2D(_ShadowTex, sampler_ShadowTex, i.texcoord1) : 1; + color = GameBoxTextureStages(color, lightmap, i.nativeColor, _HasShadowTex); + } + else if (_GbVertexColor > 0.5) + color *= i.nativeColor; + if(_HasShadowTex > 0.5f && _GbNativeLighting < 0.5) { color.rgb *= SAMPLE_TEXTURE2D(_ShadowTex, sampler_ShadowTex, i.texcoord1).rgb * _LightmapScale; } - color *= _TintColor; + if (_GbNativeLighting > 0.5) + color.rgb *= _TintColor.rgb; + else + color *= _TintColor; + if (_BattleSelection >= 0) + color.rgb = selectionTexture * _BattleSelection; color.rgb = MixFog(color.rgb, i.fogFactor); return color; } ENDHLSL } } -} \ No newline at end of file +} diff --git a/Assets/Resources/Shaders/Pal3Transparent.shader b/Assets/Resources/Shaders/Pal3Transparent.shader index bd23a296..bbe78f6b 100644 --- a/Assets/Resources/Shaders/Pal3Transparent.shader +++ b/Assets/Resources/Shaders/Pal3Transparent.shader @@ -8,6 +8,10 @@ Shader "Pal3/Transparent" Properties { _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _GbNativeLighting ("Original battle lighting", Float) = 0 + [HideInInspector] _GbMaterialDiffuse ("Original material diffuse", Vector) = (1, 1, 1, 1) + [HideInInspector] _GbMaterialAmbient ("Original material ambient", Vector) = (1, 1, 1, 1) + [HideInInspector] _BattleSelection ("Battle selection luminance", Float) = -1 _TintColor ("Tint color", Color) = (1.0, 1.0, 1.0, 1.0) _Threshold ("Transparent Threshold", Range(0, 1)) = 1.0 @@ -43,6 +47,8 @@ Shader "Pal3/Transparent" struct appdata_t { float4 vertex : POSITION; + float3 normal : NORMAL; + float4 color : COLOR; float2 texcoord0 : TEXCOORD0; float2 texcoord1 : TEXCOORD1; UNITY_VERTEX_INPUT_INSTANCE_ID @@ -54,6 +60,7 @@ Shader "Pal3/Transparent" float2 texcoord0 : TEXCOORD0; float2 texcoord1 : TEXCOORD1; float fogFactor : TEXCOORD7; + float4 nativeColor : TEXCOORD2; UNITY_VERTEX_OUTPUT_STEREO }; @@ -63,20 +70,27 @@ Shader "Pal3/Transparent" SAMPLER(sampler_ShadowTex); CBUFFER_START(UnityPerMaterial) + float _GbNativeLighting; + float4 _GbMaterialDiffuse; + float4 _GbMaterialAmbient; float4 _MainTex_ST; float _Threshold; float _HasShadowTex; float4 _ShadowTex_ST; float _LightmapScale; float4 _TintColor; + float _BattleSelection; CBUFFER_END + #include "GameBoxNativeLighting.hlsl" + v2f vert(appdata_t v) { v2f o; UNITY_SETUP_INSTANCE_ID(v); UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); o.vertex = TransformObjectToHClip(v.vertex.xyz); + o.nativeColor = GameBoxVertexColor(v.vertex.xyz, v.normal, v.color); o.texcoord0 = TRANSFORM_TEX(v.texcoord0, _MainTex); o.texcoord1 = TRANSFORM_TEX(v.texcoord1, _ShadowTex); o.fogFactor = ComputeFogFactor(o.vertex.z); @@ -86,20 +100,33 @@ Shader "Pal3/Transparent" half4 frag(v2f i) : SV_Target { half4 color = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.texcoord0); + half3 selectionTexture = color.rgb; + if (_GbNativeLighting > 0.5) + { + half4 lightmap = _HasShadowTex > 0.5 ? SAMPLE_TEXTURE2D(_ShadowTex, sampler_ShadowTex, i.texcoord1) : 1; + color = GameBoxTextureStages(color, lightmap, i.nativeColor, _HasShadowTex); + } + else if (_GbVertexColor > 0.5) + color *= i.nativeColor; if (color.a >= _Threshold || (color.a <= 0.0 && _Threshold <= 1.0)) { discard; } - if(_HasShadowTex > 0.5f) + if(_HasShadowTex > 0.5f && _GbNativeLighting < 0.5) { color.rgb *= SAMPLE_TEXTURE2D(_ShadowTex, sampler_ShadowTex, i.texcoord1).rgb * _LightmapScale; } - color *= _TintColor; + if (_GbNativeLighting > 0.5) + color.rgb *= _TintColor.rgb; + else + color *= _TintColor; + if (_BattleSelection >= 0) + color.rgb = selectionTexture * _BattleSelection; color.rgb = MixFog(color.rgb, i.fogFactor); return color; } ENDHLSL } } -} \ No newline at end of file +} diff --git a/Assets/Resources/Shaders/Pal3TransparentOpaquePart.shader b/Assets/Resources/Shaders/Pal3TransparentOpaquePart.shader index b139c3f7..c9879c2e 100644 --- a/Assets/Resources/Shaders/Pal3TransparentOpaquePart.shader +++ b/Assets/Resources/Shaders/Pal3TransparentOpaquePart.shader @@ -8,6 +8,10 @@ Shader "Pal3/TransparentOpaquePart" Properties { _MainTex ("Texture", 2D) = "white" {} + [HideInInspector] _GbNativeLighting ("Original battle lighting", Float) = 0 + [HideInInspector] _GbMaterialDiffuse ("Original material diffuse", Vector) = (1, 1, 1, 1) + [HideInInspector] _GbMaterialAmbient ("Original material ambient", Vector) = (1, 1, 1, 1) + [HideInInspector] _BattleSelection ("Battle selection luminance", Float) = -1 _TintColor ("Tint color", Color) = (1.0, 1.0, 1.0, 1.0) _Threshold ("Transparent Threshold", Range(0, 1)) = 1.0 @@ -37,6 +41,8 @@ Shader "Pal3/TransparentOpaquePart" struct appdata_t { float4 vertex : POSITION; + float3 normal : NORMAL; + float4 color : COLOR; float2 texcoord0 : TEXCOORD0; float2 texcoord1 : TEXCOORD1; UNITY_VERTEX_INPUT_INSTANCE_ID @@ -48,6 +54,7 @@ Shader "Pal3/TransparentOpaquePart" float2 texcoord0 : TEXCOORD0; float2 texcoord1 : TEXCOORD1; float fogFactor : TEXCOORD7; + float4 nativeColor : TEXCOORD2; UNITY_VERTEX_OUTPUT_STEREO }; @@ -57,20 +64,27 @@ Shader "Pal3/TransparentOpaquePart" SAMPLER(sampler_ShadowTex); CBUFFER_START(UnityPerMaterial) + float _GbNativeLighting; + float4 _GbMaterialDiffuse; + float4 _GbMaterialAmbient; float4 _MainTex_ST; float _Threshold; float _HasShadowTex; float4 _ShadowTex_ST; float _LightmapScale; float4 _TintColor; + float _BattleSelection; CBUFFER_END + #include "GameBoxNativeLighting.hlsl" + v2f vert(appdata_t v) { v2f o; UNITY_SETUP_INSTANCE_ID(v); UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); o.vertex = TransformObjectToHClip(v.vertex.xyz); + o.nativeColor = GameBoxVertexColor(v.vertex.xyz, v.normal, v.color); o.texcoord0 = TRANSFORM_TEX(v.texcoord0, _MainTex); o.texcoord1 = TRANSFORM_TEX(v.texcoord1, _ShadowTex); o.fogFactor = ComputeFogFactor(o.vertex.z); @@ -80,17 +94,30 @@ Shader "Pal3/TransparentOpaquePart" half4 frag(v2f i) : SV_Target { half4 color = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, i.texcoord0); + half3 selectionTexture = color.rgb; + if (_GbNativeLighting > 0.5) + { + half4 lightmap = _HasShadowTex > 0.5 ? SAMPLE_TEXTURE2D(_ShadowTex, sampler_ShadowTex, i.texcoord1) : 1; + color = GameBoxTextureStages(color, lightmap, i.nativeColor, _HasShadowTex); + } + else if (_GbVertexColor > 0.5) + color *= i.nativeColor; clip(color.a - _Threshold); - if(_HasShadowTex > 0.5f) + if(_HasShadowTex > 0.5f && _GbNativeLighting < 0.5) { color.rgb *= SAMPLE_TEXTURE2D(_ShadowTex, sampler_ShadowTex, i.texcoord1).rgb * _LightmapScale; } - color *= _TintColor; + if (_GbNativeLighting > 0.5) + color.rgb *= _TintColor.rgb; + else + color *= _TintColor; + if (_BattleSelection >= 0) + color.rgb = selectionTexture * _BattleSelection; color.rgb = MixFog(color.rgb, i.fogFactor); return color; } ENDHLSL } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Editor/BattleEditor.meta b/Assets/Scripts/Editor/BattleEditor.meta new file mode 100644 index 00000000..c9116ad9 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 19e3efa591f1d44319abe806fd3ea5ff +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring.meta b/Assets/Scripts/Editor/BattleEditor/Authoring.meta new file mode 100644 index 00000000..f2ec8df3 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 982b02ad3fe144eb8e3323a7990f2807 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleAiGUI.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleAiGUI.cs new file mode 100644 index 00000000..47fa54d2 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleAiGUI.cs @@ -0,0 +1,52 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using Battle; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattleEditorWindow + { + private void DrawAiControls(BattleSession combat, BattleActorSnapshot actor) + { + if (combat.Definitions == null) + return; + GUILayout.Label("原版 AI 配置", EditorStyles.boldLabel); + int flags = combat.GetAiProfile(actor.Id); + string[] labels = { "普攻", "仙术", "特技", "物品", "万全", "自动" }; + int changed = flags; + using (new EditorGUI.DisabledScope(combat.Status != BattleSessionStatus.Running)) + using (new EditorGUILayout.HorizontalScope()) + for (int bit = 0; bit < labels.Length; bit++) + { + int mask = 1 << bit; + bool enabled = GUILayout.Toggle((flags & mask) != 0, labels[bit]); + changed = enabled ? changed | mask : changed & ~mask; + } + if (changed != flags) + Try(() => combat.SetAiProfile(actor.Id, changed)); + if (actor.Side != BattleSide.Ally) + return; + using (new EditorGUI.DisabledScope(combat.Status != BattleSessionStatus.Running || combat.WaitingActor != actor.Id)) + using (new EditorGUILayout.HorizontalScope()) + { + if (DrawerButton("F · 自动普攻")) + Try(() => + { + combat.RequestAiNormal(actor.Id); + _session.SyncBattle(); + }); + if (DrawerButton("R · 重复上次指令")) + Try(() => + { + combat.RequestAiRepeat(actor.Id); + _session.SyncBattle(); + }); + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleAiGUI.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleAiGUI.cs.meta new file mode 100644 index 00000000..cf02f7f7 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleAiGUI.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: edfd0dc849d44594a87c2d4375ea0b87 diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGUI.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGUI.cs new file mode 100644 index 00000000..7e939118 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGUI.cs @@ -0,0 +1,541 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Battle.Presentation; + using Core.Contract.Enums; + using ResourceBrowser; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattleEditorWindow + { + private static readonly string[] AttributeLabels = { "精上限", "气上限", "神上限", "攻击", "防御", "速度", "幸运", "水", "火", "风", "雷", "土" }; + private readonly ResourceObjectView _dataView = new(); + private int _dataTable, _dataIndex, _equipmentSlot; + private string _dataSearch = ""; + + private void CreateRandomExample() + { + if (!CanReplace()) + return; + BattleScenario example = _session.CreateRandomExample(); + // Construct the replacement before changing the draft or its asset ownership. + _session.Start(example); + Undo.ClearUndo(_draft); + _asset = null; + _initializeTestInventory = false; + _savedJson = BattleScenarioJson.Serialize(new BattleScenario { Variant = BattleData.Variant }); + Edit("Create random battle example", () => _draft.Scenario = example); + _previewJson = _draftJson; + _selected = example.Participants.FirstOrDefault()?.InstanceId; + _drawer = WorkspaceDrawer.None; + } + + private void SyncHudBattle() + { + _session.SyncBattle(); + Repaint(); + } + + private void SelectHudActor(string id) + { + _selected = id; + _action = null; + Repaint(); + } + + private void DrawRoster() + { + GUILayout.Label("参战者", EditorStyles.boldLabel); + _rosterScroll = EditorGUILayout.BeginScrollView(_rosterScroll, GUILayout.Height(Mathf.Min(230, 62 + Scenario.Participants.Count * 34))); + try + { + foreach (BattleSide side in Enum.GetValues(typeof(BattleSide))) + { + GUILayout.Label(side == BattleSide.Ally ? "我方" : "敌方", EditorStyles.boldLabel); + foreach (BattleParticipant actor in Scenario.Participants.ToArray()) + { + if (actor.Side != side) + continue; + using (new EditorGUILayout.HorizontalScope()) + { + bool selected = actor.InstanceId == _selected; + if (GUILayout.Toggle(selected, ActorLabel(actor), Theme.Roster) != selected) + { + _selected = actor.InstanceId; + _configurationPage = 1; + _action = null; + } + GUILayout.Space(4); + if (DrawerButton("×", GUILayout.Width(24))) + Edit("Remove participant", () => Scenario.Participants.Remove(actor)); + } + } + } + } + finally + { + EditorGUILayout.EndScrollView(); + } + _addParticipant = Section("add-participant", "添加角色/怪物"); + if (!_addParticipant) + return; + _addSide = (BattleSide)EditorGUILayout.EnumPopup("加入阵营", _addSide); + _search = EditorGUILayout.TextField("搜索 ID/名称", _search); + if (_session.Data == null) + { + GUILayout.Label("请先加载原版数据。"); + return; + } + int[] candidates = RosterCandidates(_session.Data, _addSide, _search, Scenario.Participants); + _addActor = Mathf.Clamp(_addActor, 0, Math.Max(0, candidates.Length - 1)); + _addActor = EditorGUILayout.Popup(_addActor, candidates.Select(id => $"{id} · {_session.Data.Database.CombatActorInfos[id].Name}").ToArray()); + using (new EditorGUI.DisabledScope(candidates.Length == 0)) + if (DrawerButton("添加到" + (_addSide == BattleSide.Ally ? "我方" : "敌方"))) + Try(() => + { + if (Scenario.Participants.Count(actor => actor.Side == _addSide) >= (_addSide == BattleSide.Ally ? 4 : 6)) + throw new InvalidOperationException("当前阵营已达原版参战人数上限。"); + BattleSlot slot = Enum.GetValues(typeof(BattleSlot)).Cast().First(value => !Scenario.Participants.Any(actor => actor.Side == _addSide && actor.Slot == value)); + BattleParticipant actor = _session.Data.CreateTestParticipant(candidates[_addActor], _addSide, slot); + Edit("Add participant", () => Scenario.Participants.Add(actor)); + _selected = actor.InstanceId; + _configurationPage = 1; + }); + } + + private static int[] RosterCandidates(BattleData data, BattleSide side, string search, IEnumerable roster) + { + var allyIdentities = new HashSet(roster.Where(actor => actor?.Side == BattleSide.Ally) + .Select(actor => BattleData.PlayerIdentity(actor.ActorId))); + return data.Database.CombatActorInfos.OrderBy(pair => pair.Key) + .Where(pair => pair.Key > 0 && data.CombatRosterDenial(pair.Key, side) == null && + (side == BattleSide.Enemy || !allyIdentities.Contains(BattleData.PlayerIdentity(pair.Key))) && + ($"{pair.Key} {pair.Value.Name} {pair.Value.ModelId}").IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0) + .Select(pair => pair.Key).ToArray(); + } + + private string ActorLabel(BattleParticipant actor) + { + string name = _session.Data?.Database.CombatActorInfos.TryGetValue(actor.ActorId, out var info) == true ? info.Name : actor.ActorId.ToString(); + return $"{name} ({actor.ActorId}) · {actor.Slot}"; + } + + private void DrawDataCatalog() + { + if (_session.Data == null) + { + GUILayout.Label("请先加载原版数据。"); + return; + } + int table = DrawerTabs("tabs:catalog", _dataTable, new[] { "技能", "物品", "合击", "状态" }); + if (table != _dataTable) + { + _dataTable = table; + _dataIndex = 0; + _dataSearch = ""; + _dataView.Reset(); + } + var database = _session.Data.Database; + (int id, string name, object record)[] records = _dataTable switch + { + 0 => database.SkillInfos.OrderBy(pair => pair.Key).Select(pair => (pair.Key, pair.Value.Name, (object)pair.Value)).ToArray(), + 1 => database.GameItemInfos.OrderBy(pair => pair.Key).Select(pair => (pair.Key, pair.Value.Name, (object)pair.Value)).ToArray(), + 2 => database.ComboSkillInfos.OrderBy(pair => pair.Key).Select(pair => (pair.Key, pair.Value.Name, (object)pair.Value)).ToArray(), + _ => Enum.GetValues(typeof(ActorCombatStateType)).Cast().Select(state => ((int)state, state.ToString(), (object)state)).ToArray(), + }; + _dataSearch = EditorGUILayout.TextField("搜索 ID/名称", _dataSearch); + records = records.Where(record => $"{record.id} {record.name}".IndexOf(_dataSearch, StringComparison.OrdinalIgnoreCase) >= 0).ToArray(); + if (records.Length == 0) + return; + int previous = _dataIndex; + _dataIndex = EditorGUILayout.Popup(Mathf.Clamp(_dataIndex, 0, records.Length - 1), records.Select(record => $"{record.id} · {record.name}").ToArray()); + if (previous != _dataIndex) + _dataView.Reset(); + var selected = records[_dataIndex]; + BattleParticipant actor = Scenario.Participants.FirstOrDefault(participant => participant.InstanceId == _selected); + using (new EditorGUI.DisabledScope((_dataTable == 0 || _dataTable == 3) && actor == null)) + { + if (_dataTable == 0 && selected.id > 0 && DrawerButton("加入选中角色的初始技能")) + Edit("Add initial skill", () => + { + if (actor.Skills.All(skill => skill.Id != selected.id)) + actor.Skills.Add(new BattleSkill { Id = selected.id, Mastered = true }); + }); + if (_dataTable == 3 && BattleStatusRules.SupportsInitialState((BattleState)selected.id) && DrawerButton("加入选中角色的初始状态")) + Edit("Add initial status", () => + { + if (actor.Statuses.All(state => state.Id != selected.id)) + actor.Statuses.Add(new BattleStatus { Id = selected.id }); + }); + } + if (_dataTable == 1 && selected.id > 0) + { + if (DrawerButton("放入本局物品(+1)")) + Edit("Add battle item", () => + { + BattleItem item = Scenario.Items.FirstOrDefault(entry => entry.Id == selected.id); + if (item == null) + Scenario.Items.Add(new BattleItem { Id = selected.id }); + else if (item.Count < int.MaxValue) + item.Count++; + }); + _equipmentSlot = EditorGUILayout.Popup("装备槽位", _equipmentSlot, new[] { "武器", "帽子", "衣服", "鞋子", "饰品一", "饰品二" }); + using (new EditorGUI.DisabledScope(actor == null)) + if (DrawerButton("装备到选中角色(开局校验类型与适用者)")) + Edit("Set battle equipment", () => + { + if (actor.Equipment.Length != 6) + actor.Equipment = new int[6]; + actor.Equipment[_equipmentSlot] = selected.id; + if (_equipmentSlot == 0) + actor.MagicSword = selected.id == BattleMagicSwordRules.WeaponId ? actor.MagicSword ?? new BattleMagicSword() : null; + }); + } + _dataView.Draw(selected.record, DrawerWidth - 30); + } + + private void DrawScenario(BattleScenario scenario) + { + GUILayout.Label("配置作品:" + Scenario.Variant, EditorStyles.boldLabel); + if (_session.Data != null) + { + int index = Array.FindIndex(_session.Data.Scenes, name => name.Equals(Scenario.Scene, StringComparison.OrdinalIgnoreCase)); + int selected = EditorGUILayout.Popup("战斗场景", index, _session.Data.Scenes); + if (selected >= 0 && selected != index) + { + Edit("Set battle scene", () => + { + scenario.Scene = _session.Data.Scenes[selected]; + scenario.SceneElement = (int)_session.Data.SceneMap.CombatSceneElementTypeInfo.GetValueOrDefault(scenario.Scene); + }); + } + } + else + Field(scenario, "Scene", "战斗场景"); + ElementType element = (ElementType)EditorGUILayout.EnumPopup("场景五灵(阵位关系)", (ElementType)scenario.SceneElement); + if ((int)element != scenario.SceneElement) + Edit("Set scene element", () => scenario.SceneElement = (int)element); +#if PAL3A + ElementType fieldElement = (ElementType)EditorGUILayout.EnumPopup("初始五灵法阵", (ElementType)scenario.FiveSpiritElement); + if ((int)fieldElement != scenario.FiveSpiritElement) + Edit("Set five spirit element", () => scenario.FiveSpiritElement = (int)fieldElement); + int force = EditorGUILayout.Popup("法阵所属", scenario.FiveSpiritForce, new[] { "无", "我方", "敌方" }); + if (force != scenario.FiveSpiritForce) + Edit("Set five spirit force", () => scenario.FiveSpiritForce = force); +#endif + + BattleParticipant[] allies = scenario.Participants.Where(actor => actor.Side == BattleSide.Ally).ToArray(); + string[] ignoredChoices = new[] { "无" }.Concat(allies.Select(ActorLabel)).ToArray(); + int ignoredBefore = Array.FindIndex(allies, actor => actor.InstanceId == scenario.EnemyAiIgnoredActor) + 1; + if (ignoredBefore == 0 && !string.IsNullOrEmpty(scenario.EnemyAiIgnoredActor)) + ignoredBefore = -1; + int ignoredNext = EditorGUILayout.Popup("敌方 AI 忽略目标", ignoredBefore, ignoredChoices); + if (ignoredNext >= 0 && ignoredNext != ignoredBefore) + Edit("Set ignored AI actor", () => scenario.EnemyAiIgnoredActor = ignoredNext == 0 ? "" : allies[ignoredNext - 1].InstanceId); + Field(scenario, "Encounter", "遭遇类型"); + if (Section("rules", "高级战斗规则")) + { + Field(scenario, "Seed", "随机种子"); + Field(scenario, "RoundLimit", "Boss 回合限制"); + GUILayout.Label("-1 不限;0 立即判定。", EditorStyles.wordWrappedMiniLabel); + Field(scenario, "ScriptBattle", "剧情战斗"); + Field(scenario, "MustFail", "必败战斗"); + Field(scenario, "GameOverOnDefeat", "败北结束游戏"); + +#if PAL3A + BattlePal3AState pal3A = scenario.Pal3A; + if (pal3A?.SpiritWheel?.Charges is { Length: 5 } charges) + { + string[] spiritNames = { "水", "火", "风", "雷", "土" }; + for (int elementIndex = 0; elementIndex < 5; elementIndex++) + { + int index = elementIndex; + int charge = EditorGUILayout.IntSlider("五灵轮 · " + spiritNames[index], charges[index], 0, 9); + if (charge != charges[index]) + Edit("Set spirit wheel charge", () => charges[index] = charge); + } + Field(pal3A, "SpiritVisualSeed", "摄灵表现随机种子"); + Field(pal3A, "NangongStartsTransformed", "南宫煌开局炎兽形态"); + Field(pal3A, "PengxuStartsTransformed", "王蓬絮开局仙兽形态"); + Field(pal3A, "PreserveLiaoRiLosses", "继承燎日累计损失"); + if (pal3A.PreserveLiaoRiLosses) + { + Field(pal3A, "HpLoss", "累计精请求损失"); + Field(pal3A, "MpLoss", "累计神请求损失"); + } + } + else + Field(scenario, "Pal3A", "问情篇初始状态"); +#endif + } + if (!Section("presentation", "音乐、渲染与相机")) + return; + GUILayout.Label("音乐留空按场景自动选择;NONE 为静音,也可填写原始曲号。", EditorStyles.wordWrappedMiniLabel); + Field(scenario, "Music", "战斗音乐"); + int renderMode = EditorGUILayout.Popup("光影模式", scenario.ToonRendering ? 1 : 0, new[] { "原版光影", "实时光照 + Toon" }); + if ((renderMode == 1) != scenario.ToonRendering) + Edit("Set battle render mode", () => scenario.ToonRendering = renderMode == 1); + GUILayout.Label(scenario.ToonRendering ? "Unity 实时光照与 Toon 材质。" : "原始烘焙光影、顶点色与角色光照;关闭 Unity 实时灯。", EditorStyles.wordWrappedMiniLabel); + Field(scenario, "MotionBlur", "原版镜头拖影"); + Field(scenario, "Camera", "相机覆盖"); + + if (_session.Preview != null && DrawerButton("将当前视角保存到配置")) + { + _session.Preview.View.GetCamera(out Vector3 position, out Vector3 target, out float fov); + Edit("Capture preview camera", () => Scenario.Camera = new BattleCamera { Override = true, Position = Point(position), Target = Point(target), FieldOfView = fov }); + } + } + + private void DrawParticipant(BattleParticipant actor) + { + GUILayout.Label(ActorLabel(actor), EditorStyles.boldLabel); + GUILayout.Label("实例:" + actor.InstanceId, EditorStyles.wordWrappedMiniLabel); + BattleSlot slot = (BattleSlot)EditorGUILayout.EnumPopup("阵位(占用时交换)", actor.Slot); + if (slot != actor.Slot) + Edit("Swap battle slots", () => + { + BattleParticipant other = Scenario.Participants.FirstOrDefault(candidate => candidate != actor && candidate.Side == actor.Side && candidate.Slot == slot); + if (other != null) + other.Slot = actor.Slot; + actor.Slot = slot; + }); + + Field(actor, "Level", "等级"); + if (Section("actor-details", "成长与显示位置")) + { + Field(actor, "Model", "模型覆盖"); + Field(actor, "Experience", "当前经验"); + Field(actor, "Love", "好感度"); + GUILayout.Label(actor.AttributeSource switch + { + BattleAttributeSource.ExplicitEffective => "显式有效属性:下面的数值直接作为本局最终属性,装备不重复加成。", + BattleAttributeSource.BaseWithEquipment => "基础属性加装备:下面提供裸装基础数值,开局按原版计算装备加成。", + _ => "原版等级属性:按角色和等级从已核实的原版成长数据生成属性;无法核实的角色会明确拒绝。" + }, EditorStyles.wordWrappedMiniLabel); + Field(actor, "OverridePosition", "覆盖显示位置"); + if (actor.OverridePosition) + Field(actor, "Position", "位置(Unity 单位)"); + else if (_session.Data != null) + EditorGUILayout.LabelField("原始位置", _session.Data.Position(actor, Scenario.SceneElement).ToString("F2")); + } + if (Section("attributes", "初始属性与精气神")) + { + Field(actor, "AttributeSource", "属性来源"); + using (new EditorGUI.DisabledScope(actor.AttributeSource == BattleAttributeSource.LevelGrowth)) + for (int i = 0; i < (actor.Attributes?.Length ?? 0) && i < AttributeLabels.Length; i++) + { + int index = i; + int value = EditorGUILayout.IntField(AttributeLabels[index], actor.Attributes[index]); + if (value != actor.Attributes[index]) + Edit("Set initial attribute", () => actor.Attributes[index] = value); + } + for (int i = 0; i < (actor.Vitals?.Length ?? 0) && i < 3; i++) + { + int index = i; + int value = EditorGUILayout.IntField(new[] { "当前精", "当前气", "当前神" }[index], actor.Vitals[index]); + if (value != actor.Vitals[index]) + Edit("Set initial vitals", () => actor.Vitals[index] = value); + } + } + if (Section("equipment", "装备与魔剑")) + { + Field(actor, "Equipment", "装备 ID"); + if (actor.Equipment is { Length: > 0 } && actor.Equipment[0] == BattleMagicSwordRules.WeaponId) + { + if (actor.MagicSword == null) + { + if (DrawerButton("建立魔剑培养快照(发布默认值)")) + Edit("Capture magic sword defaults", () => actor.MagicSword = new BattleMagicSword()); + } + else + Field(actor, "MagicSword", "魔剑培养与初始能量"); + } + else if (actor.MagicSword != null && DrawerButton("移除未装备的魔剑快照")) + Edit("Remove unequipped magic sword snapshot", () => actor.MagicSword = null); + } + if (Section("skills", $"初始技能({actor.Skills.Count})")) + Field(actor, "Skills", "技能列表"); + if (Section("statuses", $"初始状态({actor.Statuses.Count})")) + Field(actor, "Statuses", "状态列表"); + GUILayout.Label("掌握必须显式设置;技能、状态与装备按本作原始数据及已验证的规则校验,不可用原因显示在实战指令和诊断中。", EditorStyles.wordWrappedMiniLabel); + } + + private void Field(object owner, string name, string label) + { + BattleScenarioTypedFields.Field(owner, name, label, Edit, Theme.Button); + GUILayout.Space(2); + } + + private static BattlePoint Point(Vector3 value) => new() { X = value.x, Y = value.y, Z = value.z }; + + private void DrawCanvas(Rect available, bool newBattleKey) + { + BattlePreview preview = _session.Preview; + EditorGUI.DrawRect(available, new Color(0.12f, 0.12f, 0.12f)); + if (preview == null) + { + DrawWelcome(available); + return; + } + preview.View.ExpandReferenceFraming = _expandCamera; + preview.DamageNumberColorMode = _damageNumberColor; + Rect rect = _originalAspect ? BattleHudLayout.ContentRect(available) : available; + // The game supports landscape and square canvases. A tall tool + // window or an open drawer must not create a portrait battle HUD. + if (rect.height > rect.width) + rect = new Rect(rect.x, rect.center.y - rect.width / 2, rect.width, rect.width); + preview.View.SetViewportContext(rect); + EditorGUI.DrawRect(available, Color.black); + if (Event.current.type == EventType.MouseMove && rect.Contains(Event.current.mousePosition)) + Repaint(); + Event inputEvent = Event.current; + BattleSession battle = _session.Battle; + bool coAttackBlocksHud = battle?.IsCoAttackPresentationBlockingInput == true; + bool ownsKeyboard = GUIUtility.keyboardControl == 0 && !EditorGUIUtility.editingTextField; + // Unity sends a separate character event for Tab. Let the key-code event + // drive the HUD and consume the character before IMGUI assigns focus. + bool battleOwnsTab = !DraftPending && ownsKeyboard && (battle?.Status == BattleSessionStatus.Running || + _session.ResultPresentation is { Completed: false }); + if (battleOwnsTab && inputEvent.type == EventType.KeyDown && + inputEvent.keyCode == KeyCode.None && inputEvent.character is '\t' or '\x19') + inputEvent.Use(); + bool canReadKey = BattleHudView.CanReadBattleKey(inputEvent); + bool clickedCanvas = inputEvent.type == EventType.MouseDown && rect.Contains(inputEvent.mousePosition); + if (!DraftPending && _session.ResultPresentation is { Completed: false } resultInput && (canReadKey || clickedCanvas)) + { + if (clickedCanvas) + { + BattleHudView.TakeGuiKeyboardFocus(); + if (inputEvent.button == 1 && resultInput.StatisticsVisible) + resultInput.CloseStatistics(); + } + _session.SkipResultStep(); + inputEvent.Use(); + } + else if (!DraftPending && battle != null && (canReadKey || coAttackBlocksHud && clickedCanvas)) + { + if (coAttackBlocksHud && clickedCanvas) + BattleHudView.TakeGuiKeyboardFocus(); + bool skipped = battle.IsModalPresentation + ? canReadKey && inputEvent.keyCode == KeyCode.Escape && battle.SkipModalPresentation() + : coAttackBlocksHud && (clickedCanvas || newBattleKey) && battle.SkipCoAttackPresentation(); + if (skipped) + { + _session.SyncBattle(); + Repaint(); + } + if (battle.IsModalPresentation || skipped || coAttackBlocksHud) + inputEvent.Use(); + } + if (!DraftPending && battle?.Status == BattleSessionStatus.Running && canReadKey && !newBattleKey && BattleHudView.KeyboardIntent(inputEvent.keyCode) is { } repeated && + repeated.Kind is BattleHudIntentKind.Confirm or BattleHudIntentKind.Back && inputEvent.type == EventType.KeyDown) + inputEvent.Use(); + void DrawHud() + { + using var input = new EditorGUI.DisabledScope(DraftPending || coAttackBlocksHud); + _hud.Draw(_session.Battle, _session.Data, preview, rect, + SyncHudBattle, SelectHudActor, _hudSafeInsets, Repaint, new BattleHudInteractionProfile(_touchHud)); + } + if (_session.Battle != null && Event.current.type != EventType.Repaint) + DrawHud(); + if (battleOwnsTab && + inputEvent.keyCode == KeyCode.Tab && BattleHudView.CanReadBattleKey(inputEvent)) + inputEvent.Use(); + if (_session.Battle == null && Event.current.type == EventType.MouseDown && Event.current.button == 0 && rect.Contains(Event.current.mousePosition)) + { + string picked = preview.InstanceAt(Event.current.mousePosition, rect); + if (picked != null) + SelectHudActor(picked); + } + if (_session.Battle != null) + _hud.PreparePointers(_session.Battle, _session.Data, preview); + if (_session.Battle != null && BattleHudView.CanReadBattleKey(Event.current) && + Event.current.keyCode is KeyCode.F or KeyCode.R && rect.Contains(Event.current.mousePosition)) + Event.current.Use(); + // Native list/scrollbar controls get first refusal before the + // battle canvas accepts any remaining pointer gesture. + if (_session.Battle != null) + _hud.CompleteGuiInput(Event.current, rect); + preview.View.Draw(rect, allowCameraInput: _session.Battle == null); + if (_session.Battle?.IsPreparingPresentation == true) + { + GUI.Label(rect, "正在准备战斗影片…", Theme.WelcomeText); + return; + } + if (battle == null || _debugBattle && !battle.IsModalPresentation) + preview.DrawLabels(rect, _selected); + if (_session.Battle != null) + preview.DrawBattleOverlay(_session.Battle, rect, _hudSafeInsets, BattleHudView.ElementWheelVisible(_session.Battle, _hud.Presenter), _hud.NavigationFocusedControl); + if (_session.Battle != null) + preview.DrawBattleNumbers(_session.Battle, rect, _hudSafeInsets); + if (_session.Battle != null && Event.current.type == EventType.Repaint) + DrawHud(); + if (_session.Battle != null) + preview.DrawBattleMessages(_session.Battle, rect, _hudSafeInsets); + if (_session.Battle != null) + preview.DrawSwordSparks(rect, _hudSafeInsets); + if (_session.Battle?.CoAttackScreenOpacity > 0) + { + uint value = _session.Battle.CoAttackScreenColor; + Color color = new((value >> 16 & 255) / 255f, (value >> 8 & 255) / 255f, + (value & 255) / 255f, _session.Battle.CoAttackScreenOpacity); + EditorGUI.DrawRect(rect, color); + } + if (_session.ResultPresentation != null) + preview.DrawResultOverlay(_session.ResultPresentation, rect, _hudSafeInsets); + } + + private void DrawActions(BattlePreview preview) + { + BattleScenario captured = _session.CapturedScenario; + BattleParticipant actor = captured.Participants.FirstOrDefault(candidate => candidate.InstanceId == _selected); + if (actor == null) + { + GUILayout.Label("选择参战者以预览动作。", EditorStyles.miniLabel); + return; + } + string[] actions = _session.Data.Actions(actor).Select(action => action.ActionName).ToArray(); + int index = Array.IndexOf(actions, _action); + if (index < 0) + index = Math.Max(0, Array.IndexOf(actions, _session.Data.IdleAction(actor))); + using (new EditorGUILayout.HorizontalScope()) + { + index = EditorGUILayout.Popup("动作", index, actions, GUILayout.Height(BattleEditorTheme.ControlHeight)); + _action = actions[index]; + GUILayout.Space(6); + if (DrawerButton("演示动作", GUILayout.Width(80))) + Try(() => + { + preview.PlayAction(actor.InstanceId, _action); + _session.IsPlaying = true; + }); + } + BattleParticipant[] targets = captured.Participants.Where(candidate => candidate.Side != actor.Side).ToArray(); + int target = Math.Max(0, Array.FindIndex(targets, candidate => candidate.InstanceId == _target)); + using (new EditorGUILayout.HorizontalScope()) + { + target = EditorGUILayout.Popup("攻击目标", target, targets.Select(ActorLabel).ToArray(), GUILayout.Height(BattleEditorTheme.ControlHeight)); + if (targets.Length > 0) + _target = targets[target].InstanceId; + GUILayout.Space(6); + using (new EditorGUI.DisabledScope(targets.Length == 0)) + if (DrawerButton("普攻演示", GUILayout.Width(80))) + Try(() => + { + preview.PlayAttack(actor.InstanceId, _target); + _session.IsPlaying = true; + }); + } + GUILayout.Label("动画标记(仅显示,不触发结算):" + string.Join(" · ", preview.AnimationMarkers(actor.InstanceId)), EditorStyles.wordWrappedMiniLabel); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGUI.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGUI.cs.meta new file mode 100644 index 00000000..b2924740 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGUI.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7b86182be927449b8a97708a4755a61f \ No newline at end of file diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadInput.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadInput.cs new file mode 100644 index 00000000..db98ea99 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadInput.cs @@ -0,0 +1,322 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using Battle.Presentation; + using UnityEditor; + using UnityEngine.InputSystem; + using UnityEngine.InputSystem.Controls; + using UnityEngine.InputSystem.LowLevel; + + // Input actions intentionally ignore Editor updates. Use the editor's + // existing event stream and flush once after its native input update. + public sealed class BattleEditorGamepadInput : IDisposable + { + private readonly Func _canReceive; + private readonly Action _dispatch; + private readonly Func _clock; + private readonly Action _collect; + private readonly Dictionary _devices = new(); + private readonly List _iteration = new(); + private readonly List _ready = new(); + private readonly List _deviceChangePoints = new(); + private Gamepad _pointingDevice; + private int _suspensionVersion; + private DeviceState _collectingState; + private long _eventSequence; + private bool _disposed; + + private readonly struct PendingIntent + { + public readonly DeviceState State; + public readonly BattleEditorGamepadState Policy; + public readonly BattleEditorGamepadIntent Intent; + public readonly Gamepad PointingDevice; + public readonly int NavigationVersion, SuspensionVersion; + + public PendingIntent(DeviceState state, BattleEditorGamepadIntent intent) + { + State = state; + Policy = state.Policy; + PointingDevice = null; + Intent = intent; + NavigationVersion = Policy.NavigationVersion; + SuspensionVersion = Policy.SuspensionVersion; + } + + public PendingIntent(Gamepad device, BattleEditorGamepadIntent intent, int suspensionVersion) + { + State = null; + Policy = null; + PointingDevice = device; + Intent = intent; + NavigationVersion = 0; + SuspensionVersion = suspensionVersion; + } + } + + private PendingIntent PointingReset(Gamepad device) + { + return new PendingIntent(device, new BattleEditorGamepadIntent(BattleEditorGamepadIntentKind.Point, + BattleHudDirection.Neutral, false, ++_eventSequence * 2, + BattleHudDirection.Neutral), _suspensionVersion); + } + + private sealed class DeviceState + { + public readonly Gamepad Device; + + public BattleEditorGamepadState Policy + { + get; private set; + } + + private bool _baselineDirty; + private float _stickX, _stickY; + private bool _up, _down, _left, _right; + private BattleEditorGamepadButtons _buttons; + private readonly (ButtonControl Control, BattleEditorGamepadButtons Button)[] _controls; + + public BattleEditorGamepadSnapshot Snapshot => new(_stickX, _stickY, (_right ? 1 : 0) - (_left ? 1 : 0), (_up ? 1 : 0) - (_down ? 1 : 0), _buttons); + + public DeviceState(Gamepad device) + { + Device = device; + _controls = new[] + { + (device.buttonSouth, BattleEditorGamepadButtons.Confirm), + (device.buttonEast, BattleEditorGamepadButtons.Cancel), + (device.buttonWest, BattleEditorGamepadButtons.Primary), + (device.buttonNorth, BattleEditorGamepadButtons.Repeat), + (device.leftShoulder, BattleEditorGamepadButtons.PreviousSection), + (device.rightShoulder, BattleEditorGamepadButtons.NextSection), + (device.startButton, BattleEditorGamepadButtons.Transport) + }; + RebuildBaseline(); + } + + public void MarkReset() + { + // ResetDevice notifies listeners before replacing its state, + // so reading controls from that callback would cache old data. + _baselineDirty = true; + Policy.Suspend(); + } + + public void EnsureBaseline() + { + if (_baselineDirty) + RebuildBaseline(); + } + + private void RebuildBaseline() + { + _stickX = Device.leftStick.x.ReadValue(); + _stickY = Device.leftStick.y.ReadValue(); + _up = Device.dpad.up.isPressed; + _down = Device.dpad.down.isPressed; + _left = Device.dpad.left.isPressed; + _right = Device.dpad.right.isPressed; + _buttons = BattleEditorGamepadButtons.None; + foreach ((ButtonControl control, BattleEditorGamepadButtons button) in _controls) + if (control.isPressed) + _buttons |= button; + Policy = new BattleEditorGamepadState(Snapshot); + _baselineDirty = false; + } + + public void Read(InputEventPtr input) + { + // Read actual layout controls rather than assuming GPAD state + // memory. Partial delta events retain every absent control. + if (Device.leftStick.x.ReadValueFromEvent(input, out float x)) + _stickX = x; + if (Device.leftStick.y.ReadValueFromEvent(input, out float y)) + _stickY = y; + ReadButton(Device.dpad.up, input, ref _up); + ReadButton(Device.dpad.down, input, ref _down); + ReadButton(Device.dpad.left, input, ref _left); + ReadButton(Device.dpad.right, input, ref _right); + foreach ((ButtonControl control, BattleEditorGamepadButtons button) in _controls) + if (control.ReadValueFromEvent(input, out float value)) + _buttons = control.IsValueConsideredPressed(value) ? _buttons | button : _buttons & ~button; + } + + private static void ReadButton(ButtonControl control, InputEventPtr input, ref bool pressed) + { + if (control.ReadValueFromEvent(input, out float value)) + pressed = control.IsValueConsideredPressed(value); + } + } + + public BattleEditorGamepadInput(Func canReceive, Action dispatch, Func clock = null) + { + _canReceive = canReceive ?? throw new ArgumentNullException(nameof(canReceive)); + _dispatch = dispatch ?? throw new ArgumentNullException(nameof(dispatch)); + _clock = clock ?? (() => EditorApplication.timeSinceStartup); + _collect = Collect; + foreach (Gamepad gamepad in Gamepad.all) + _devices[gamepad.deviceId] = new DeviceState(gamepad); + InputSystem.onEvent += OnEvent; + InputSystem.onAfterUpdate += OnAfterUpdate; + InputSystem.onDeviceChange += OnDeviceChange; + } + + private void OnEvent(InputEventPtr input, InputDevice device) + { + if (_disposed || device is not Gamepad gamepad || !gamepad.enabled || !(input.IsA() || input.IsA())) + return; + if (!_devices.TryGetValue(gamepad.deviceId, out DeviceState state)) + _devices.Add(gamepad.deviceId, state = new DeviceState(gamepad)); + state.EnsureBaseline(); + BattleEditorGamepadSnapshot before = state.Snapshot; + state.Read(input); + BattleEditorGamepadSnapshot snapshot = state.Snapshot; + bool canReceive = InputState.currentUpdateType == InputUpdateType.Editor && !input.handled && _canReceive(); + if (canReceive && (snapshot.Buttons & ~before.Buttons) != BattleEditorGamepadButtons.None) + foreach (DeviceState other in _devices.Values) + if (!ReferenceEquals(other, state)) + other.Policy.SealNavigation(); + state.Policy.Sample(snapshot, canReceive, ++_eventSequence); + // Keep the full state event available to Unity and other tools. + } + + private void OnAfterUpdate() + { + if (_disposed || InputState.currentUpdateType != InputUpdateType.Editor) + return; + _iteration.Clear(); + _ready.Clear(); + foreach (DeviceState state in _devices.Values) + _iteration.Add(state); + double now = _clock(); + foreach (DeviceState state in _iteration) + { + if (_disposed) + break; + if (!state.Device.added || !state.Device.enabled) + { + state.Policy.Suspend(); + continue; + } + state.EnsureBaseline(); + _collectingState = state; + state.Policy.Advance(now, _canReceive(), _collect); + } + _collectingState = null; + _ready.AddRange(_deviceChangePoints); + _deviceChangePoints.Clear(); + // Native arrival order also applies across controllers. Device + // dictionary order must never decide which menu a Confirm sees. + _ready.Sort((left, right) => left.Intent.Sequence.CompareTo(right.Intent.Sequence)); + foreach (PendingIntent pending in _ready) + { + if (_disposed) + break; + DeviceState state = pending.State; + if (state == null) + { + if (pending.SuspensionVersion != _suspensionVersion || !_canReceive()) + continue; + if (UpdatePointingOwner(pending.PointingDevice, pending.Intent)) + _dispatch(pending.Intent); + continue; + } + if (!state.Device.added || !state.Device.enabled || !ReferenceEquals(state.Policy, pending.Policy) || + state.Policy.SuspensionVersion != pending.SuspensionVersion || + pending.Intent.IsRepeat && state.Policy.NavigationVersion != pending.NavigationVersion) + continue; + if (!_canReceive()) + { + state.Policy.Suspend(); + continue; + } + // A preceding Confirm may have opened another page and reset + // navigation. This later fresh gesture is still a new gesture. + state.Policy.NotifyDispatched(pending.Intent, now); + if (UpdatePointingOwner(state.Device, pending.Intent)) + _dispatch(pending.Intent); + } + } + + private bool UpdatePointingOwner(Gamepad device, BattleEditorGamepadIntent intent) + { + if (intent.PointingDirection is not { } direction) + return true; + if (intent.IsRepeat && _pointingDevice != device) + return false; + if (intent.Kind != BattleEditorGamepadIntentKind.Point || direction != BattleHudDirection.Neutral) + { + _pointingDevice = device; + return true; + } + // Releases and device resets only clear the controller that is + // currently pointing. Another controller may have taken over. + if (_pointingDevice != device) + return false; + _pointingDevice = null; + return true; + } + + private void Collect(BattleEditorGamepadIntent intent) + { + if (_collectingState != null) + _ready.Add(new PendingIntent(_collectingState, intent)); + } + + private void OnDeviceChange(InputDevice device, InputDeviceChange change) + { + if (device is Gamepad gamepad && change is InputDeviceChange.Removed or InputDeviceChange.Disconnected or + InputDeviceChange.Disabled or InputDeviceChange.SoftReset or InputDeviceChange.HardReset) + { + if (_canReceive() && _devices.TryGetValue(device.deviceId, out DeviceState pendingState)) + pendingState.Policy.CapturePendingPointing(intent => + { + // Preserve the accepted position and its original order, + // but never revive a command or a list step after reset. + var point = new BattleEditorGamepadIntent(BattleEditorGamepadIntentKind.Point, intent.Direction, + false, intent.Sequence, intent.PointingDirection); + _deviceChangePoints.Add(new PendingIntent(gamepad, point, _suspensionVersion)); + }); + _deviceChangePoints.Add(PointingReset(gamepad)); + } + if (change is InputDeviceChange.Removed or InputDeviceChange.Disconnected) + _devices.Remove(device.deviceId); + else if ((change is InputDeviceChange.Disabled or InputDeviceChange.SoftReset or InputDeviceChange.HardReset) && _devices.TryGetValue(device.deviceId, out DeviceState state)) + state.MarkReset(); + } + + public void Suspend() + { + _suspensionVersion++; + _pointingDevice = null; + _deviceChangePoints.Clear(); + foreach (DeviceState state in _devices.Values) + state.Policy.Suspend(); + } + + public void ResetNavigation() + { + foreach (DeviceState state in _devices.Values) + state.Policy.ResetNavigation(); + } + + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + InputSystem.onEvent -= OnEvent; + InputSystem.onAfterUpdate -= OnAfterUpdate; + InputSystem.onDeviceChange -= OnDeviceChange; + _devices.Clear(); + _pointingDevice = null; + _deviceChangePoints.Clear(); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadInput.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadInput.cs.meta new file mode 100644 index 00000000..31ac111c --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadInput.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 76ae6f1a2e254b688684213e5cb0aac2 diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadState.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadState.cs new file mode 100644 index 00000000..152fe281 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadState.cs @@ -0,0 +1,350 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using Battle.Presentation; + + public enum BattleEditorGamepadIntentKind + { + Navigate, Confirm, Cancel, PreviousSection, NextSection, Primary, Repeat, Transport, Point + } + + public readonly struct BattleEditorGamepadIntent + { + public BattleEditorGamepadIntentKind Kind + { + get; + } + + public BattleHudDirection Direction + { + get; + } + + // Null denotes an intent without a native device-position snapshot. + public BattleHudDirection? PointingDirection + { + get; + } + + public bool IsRepeat + { + get; + } + + internal long Sequence + { + get; + } + + public BattleEditorGamepadIntent(BattleEditorGamepadIntentKind kind, BattleHudDirection direction = BattleHudDirection.Down, bool isRepeat = false, BattleHudDirection? pointingDirection = null) + : this(kind, direction, isRepeat, 0, pointingDirection) + { + } + + internal BattleEditorGamepadIntent(BattleEditorGamepadIntentKind kind, BattleHudDirection direction, bool isRepeat, long sequence, BattleHudDirection? pointingDirection = null) + { + Kind = kind; + Direction = direction; + PointingDirection = pointingDirection; + IsRepeat = isRepeat; + Sequence = sequence; + } + } + + [Flags] + public enum BattleEditorGamepadButtons + { + None = 0, Confirm = 1, Cancel = 2, PreviousSection = 4, NextSection = 8, + Primary = 16, Repeat = 32, Transport = 64 + } + + public readonly struct BattleEditorGamepadSnapshot + { + public float StickX + { + get; + } + + public float StickY + { + get; + } + + public int DpadX + { + get; + } + + public int DpadY + { + get; + } + + public BattleEditorGamepadButtons Buttons + { + get; + } + + public BattleEditorGamepadSnapshot(float stickX = 0, float stickY = 0, int dpadX = 0, int dpadY = 0, BattleEditorGamepadButtons buttons = BattleEditorGamepadButtons.None) + { + StickX = stickX; + StickY = stickY; + DpadX = Math.Sign(dpadX); + DpadY = Math.Sign(dpadY); + Buttons = buttons; + } + } + + // Pure UI timing and gesture policy. Simulation speed and Input System + // settings do not affect its clock, button edges, or repeat intervals. + public sealed class BattleEditorGamepadState + { + public const double RepeatDelay = .35; + public const double RepeatInterval = .10; + public const float StickEnter = .5f; + public const float StickExit = .35f; + private const double SectorWidth = Math.PI / 4; + private const double SectorHysteresis = Math.PI / 36; + private static readonly (BattleEditorGamepadButtons Button, BattleEditorGamepadIntentKind Intent)[] ButtonPriority = + { + (BattleEditorGamepadButtons.Cancel, BattleEditorGamepadIntentKind.Cancel), + (BattleEditorGamepadButtons.Transport, BattleEditorGamepadIntentKind.Transport), + (BattleEditorGamepadButtons.PreviousSection, BattleEditorGamepadIntentKind.PreviousSection), + (BattleEditorGamepadButtons.NextSection, BattleEditorGamepadIntentKind.NextSection), + (BattleEditorGamepadButtons.Primary, BattleEditorGamepadIntentKind.Primary), + (BattleEditorGamepadButtons.Repeat, BattleEditorGamepadIntentKind.Repeat), + (BattleEditorGamepadButtons.Confirm, BattleEditorGamepadIntentKind.Confirm) + }; + + private readonly List _pending = new(); + private readonly List _draining = new(); + private BattleEditorGamepadSnapshot _snapshot; + private BattleHudDirection? _direction; + private BattleEditorGamepadIntent? _navigationPulse; + private long _sequence; + private int? _stickSector; + private bool _navigationArmed, _pointingArmed; + private double _nextRepeat = double.PositiveInfinity; + private double _lastTime = double.NegativeInfinity; + + internal int NavigationVersion + { + get; private set; + } + + internal int SuspensionVersion + { + get; private set; + } + + public BattleEditorGamepadState(BattleEditorGamepadSnapshot initial = default) + { + _snapshot = initial; + _navigationArmed = _pointingArmed = Neutral(initial); + } + + private static bool Neutral(BattleEditorGamepadSnapshot snapshot) => snapshot.DpadX == 0 && snapshot.DpadY == 0 && + snapshot.StickX * snapshot.StickX + snapshot.StickY * snapshot.StickY < StickExit * StickExit; + + public void Sample(BattleEditorGamepadSnapshot snapshot, bool canReceive, long sequence = 0) + { + if (sequence <= 0) + sequence = ++_sequence; + else + _sequence = Math.Max(_sequence, sequence); + BattleHudDirection? previousDirection = ReadDirection(); + BattleEditorGamepadButtons rising = snapshot.Buttons & ~_snapshot.Buttons; + bool buttonPressed = TryButton(rising, out BattleEditorGamepadIntentKind button); + bool wasNeutral = Neutral(_snapshot); + bool freshDpad = _snapshot.DpadX == 0 && _snapshot.DpadY == 0 && (snapshot.DpadX != 0 || snapshot.DpadY != 0); + if (canReceive && (wasNeutral || freshDpad)) + _navigationArmed = _pointingArmed = true; + _snapshot = snapshot; + if (!canReceive) + { + Suspend(); + return; + } + BattleHudDirection? sampledDirection = ReadDirection(); + BattleHudDirection pointingDirection = sampledDirection ?? BattleHudDirection.Neutral; + if (buttonPressed && button != BattleEditorGamepadIntentKind.Confirm) + { + // A button is a stream-order barrier. Earlier directions stay + // earlier; coincident Cancel/transport wins over navigation. + SealNavigation(); + _pending.Add(new BattleEditorGamepadIntent(button, BattleHudDirection.Down, false, sequence * 2 + 1, pointingDirection)); + ResetHeldNavigation(); + return; + } + if (_pointingArmed && sampledDirection != previousDirection) + { + // Axis components may coalesce, but a release preserves the + // preceding list step and immediately points the wheel home. + if (wasNeutral || !sampledDirection.HasValue) + SealNavigation(); + BattleEditorGamepadIntentKind kind = _navigationArmed && sampledDirection.HasValue + ? BattleEditorGamepadIntentKind.Navigate : BattleEditorGamepadIntentKind.Point; + _navigationPulse = new BattleEditorGamepadIntent(kind, pointingDirection, false, sequence * 2, pointingDirection); + } + if (buttonPressed) + { + // Direction and Confirm in one state event navigate first. + // Separate events retain their actual order and every edge. + SealNavigation(); + _pending.Add(new BattleEditorGamepadIntent(button, BattleHudDirection.Down, false, sequence * 2 + 1, pointingDirection)); + } + } + + internal void SealNavigation() + { + if (!_navigationPulse.HasValue) + return; + _pending.Add(_navigationPulse.Value); + _navigationPulse = null; + } + + internal void CapturePendingPointing(Action collect) + { + SealNavigation(); + foreach (BattleEditorGamepadIntent intent in _pending) + if (intent.Kind is BattleEditorGamepadIntentKind.Navigate or BattleEditorGamepadIntentKind.Point) + collect(intent); + } + + public void Suspend() + { + _pending.Clear(); + _navigationPulse = null; + SuspensionVersion++; + _pointingArmed = false; + _stickSector = null; + ResetHeldNavigation(); + } + + public void ResetNavigation() + { + // A context change invalidates held repeats, not fresh events that + // have already arrived later in the same input stream. + SealNavigation(); + ResetHeldNavigation(); + } + + private void ResetHeldNavigation() + { + _navigationArmed = false; + _direction = null; + _nextRepeat = double.PositiveInfinity; + NavigationVersion++; + } + + internal void NotifyDispatched(BattleEditorGamepadIntent intent, double now) + { + if (intent.Kind == BattleEditorGamepadIntentKind.Navigate) + { + _navigationArmed = true; + _direction = intent.Direction; + _nextRepeat = now + (intent.IsRepeat ? RepeatInterval : RepeatDelay); + } + else if (intent.Kind is not (BattleEditorGamepadIntentKind.Confirm or BattleEditorGamepadIntentKind.Point)) + ResetHeldNavigation(); + } + + public void Advance(double now, bool canReceive, Action dispatch) + { + if (!double.IsFinite(now)) + throw new ArgumentOutOfRangeException(nameof(now)); + if (dispatch == null) + throw new ArgumentNullException(nameof(dispatch)); + if (now < _lastTime) + _nextRepeat = now + RepeatDelay; + _lastTime = now; + if (!canReceive) + { + Suspend(); + return; + } + if (Neutral(_snapshot)) + _navigationArmed = _pointingArmed = true; + SealNavigation(); + _draining.Clear(); + _draining.AddRange(_pending); + _pending.Clear(); + int suspension = SuspensionVersion; + foreach (BattleEditorGamepadIntent intent in _draining) + { + if (suspension != SuspensionVersion) + break; + NotifyDispatched(intent, now); + dispatch(intent); + } + if (suspension != SuspensionVersion) + return; + BattleHudDirection? direction = ReadDirection(); + if (!direction.HasValue) + { + _direction = null; + _nextRepeat = double.PositiveInfinity; + } + else if (_draining.Count == 0 && _navigationArmed && _direction == direction && now + 1e-9 >= _nextRepeat) + { + // Fresh events always precede a timed repeat. Never replay a + // backlog after a stalled editor update. + var repeat = new BattleEditorGamepadIntent(BattleEditorGamepadIntentKind.Navigate, direction.Value, true, long.MaxValue, direction.Value); + NotifyDispatched(repeat, now); + dispatch(repeat); + } + } + + private static bool TryButton(BattleEditorGamepadButtons pressed, out BattleEditorGamepadIntentKind kind) + { + foreach ((BattleEditorGamepadButtons button, BattleEditorGamepadIntentKind intent) in ButtonPriority) + if ((pressed & button) != 0) + { + kind = intent; + return true; + } + kind = default; + return false; + } + + private BattleHudDirection? ReadDirection() + { + double magnitude = _snapshot.StickX * _snapshot.StickX + _snapshot.StickY * _snapshot.StickY; + if (magnitude < StickExit * StickExit || !_stickSector.HasValue && magnitude < StickEnter * StickEnter) + _stickSector = null; + else + { + double angle = Math.Atan2(_snapshot.StickY, _snapshot.StickX); + if (_stickSector is int previous) + { + double difference = Math.Atan2(Math.Sin(angle - previous * SectorWidth), Math.Cos(angle - previous * SectorWidth)); + if (Math.Abs(difference) > SectorWidth / 2 + SectorHysteresis) + _stickSector = Sector(angle); + } + else + _stickSector = Sector(angle); + } + int? sector = _snapshot.DpadX != 0 || _snapshot.DpadY != 0 ? Sector(Math.Atan2(_snapshot.DpadY, _snapshot.DpadX)) : _stickSector; + return sector switch + { + 0 => BattleHudDirection.Right, + 1 => BattleHudDirection.UpRight, + 2 => BattleHudDirection.Up, + 3 => BattleHudDirection.UpLeft, + 4 => BattleHudDirection.Left, + 5 => BattleHudDirection.DownLeft, + 6 => BattleHudDirection.Down, + 7 => BattleHudDirection.DownRight, + _ => null + }; + } + + private static int Sector(double angle) => ((int)Math.Floor(angle / SectorWidth + .5) % 8 + 8) % 8; + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadState.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadState.cs.meta new file mode 100644 index 00000000..a58a03be --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorGamepadState.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2766a987b42441b4b733cd089bf647fb diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorTheme.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorTheme.cs new file mode 100644 index 00000000..76cf0933 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorTheme.cs @@ -0,0 +1,139 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using UnityEditor; + using UnityEngine; + + // Local style copies preserve the host Editor skin and never mutate its + // shared styles. All measurements are logical points; IMGUI handles Retina. + internal sealed class BattleEditorTheme + { + public const float ControlHeight = 24; + public const float CanvasTop = 32; + public const float GroupSpacing = 8; + + public bool ProSkin { get; } = EditorGUIUtility.isProSkin; + + public GUIStyle Button + { + get; + } + + public GUIStyle PrimaryButton + { + get; + } + + public GUIStyle ToolbarButton + { + get; + } + + public GUIStyle Popup + { + get; + } + + public GUIStyle Tabs + { + get; + } + + public GUIStyle TabLeft + { + get; + } + + public GUIStyle TabMiddle + { + get; + } + + public GUIStyle TabRight + { + get; + } + + public GUIStyle Section + { + get; + } + + public GUIStyle Title + { + get; + } + + public GUIStyle Metadata + { + get; + } + + public GUIStyle WelcomeTitle + { + get; + } + + public GUIStyle WelcomeText + { + get; + } + + public GUIStyle Roster + { + get; + } + + public Color Header => ProSkin ? new Color(.18f, .18f, .18f) : new Color(.78f, .78f, .78f); + public Color Surface => ProSkin ? new Color(.235f, .235f, .235f) : new Color(.82f, .82f, .82f); + public Color Border => ProSkin ? new Color(.12f, .12f, .12f) : new Color(.57f, .57f, .57f); + public Color Accent => ProSkin ? new Color(.5f, .75f, 1) : new Color(.64f, .81f, 1); + + public BattleEditorTheme() + { + Button = Control(EditorStyles.miniButton); + PrimaryButton = new GUIStyle(Button) { fontStyle = FontStyle.Bold }; + ToolbarButton = Control(EditorStyles.toolbarButton); + Popup = Control(EditorStyles.popup); + Popup.alignment = TextAnchor.MiddleLeft; + Popup.padding = new RectOffset(6, 18, 0, 0); + Tabs = Control(EditorStyles.miniButton); + Tabs.margin = new RectOffset(0, 0, 0, 0); + TabLeft = Control(EditorStyles.miniButtonLeft); + TabMiddle = Control(EditorStyles.miniButtonMid); + TabRight = Control(EditorStyles.miniButtonRight); + Section = new GUIStyle(EditorStyles.foldoutHeader) + { + fixedHeight = ControlHeight, + margin = new RectOffset(0, 0, 0, 0), + fontSize = 11 + }; + Title = new GUIStyle(EditorStyles.boldLabel) { alignment = TextAnchor.MiddleLeft, fontSize = 12 }; + Metadata = new GUIStyle(EditorStyles.miniLabel) + { + alignment = TextAnchor.MiddleLeft, + normal = { textColor = ProSkin ? new Color(.65f, .65f, .65f) : new Color(.3f, .3f, .3f) } + }; + WelcomeTitle = new GUIStyle(EditorStyles.boldLabel) { alignment = TextAnchor.MiddleCenter, fontSize = 20, wordWrap = true }; + WelcomeText = new GUIStyle(EditorStyles.wordWrappedLabel) { alignment = TextAnchor.MiddleCenter }; + // The canvas stays dark in both Editor skins. + WelcomeTitle.normal.textColor = new Color(.88f, .88f, .88f); + WelcomeText.normal.textColor = new Color(.76f, .76f, .76f); + Roster = new GUIStyle(Button) { alignment = TextAnchor.MiddleLeft, padding = new RectOffset(8, 8, 0, 0) }; + } + + private static GUIStyle Control(GUIStyle source) => new(source) + { + fixedHeight = ControlHeight, + fixedWidth = 0, + fontSize = 11, + alignment = TextAnchor.MiddleCenter, + margin = new RectOffset(2, 2, 2, 2), + padding = new RectOffset(8, 8, 0, 0) + }; + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorTheme.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorTheme.cs.meta new file mode 100644 index 00000000..6fe0d389 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorTheme.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 417d983af0594eab9f0e4107498b28ab diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.Gamepad.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.Gamepad.cs new file mode 100644 index 00000000..49c3fdc2 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.Gamepad.cs @@ -0,0 +1,96 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using Battle; + using Battle.Presentation; + using UnityEditor; + + public sealed partial class BattleEditorWindow + { + private Func _gamepadFocusedWindow = () => focusedWindow; + private (BattleSession Battle, string Controller, BattleHudPage Page, int Category, string FormationActor, string AiActor)? _gamepadContext; + + private bool CanReceiveGamepad() => _session != null && _gamepadFocusedWindow() == this && !DraftPending && + !EditorApplication.isPlayingOrWillChangePlaymode && !EditorGUIUtility.editingTextField; + + private (BattleSession Battle, string Controller, BattleHudPage Page, int Category, string FormationActor, string AiActor) CurrentGamepadContext() => + (_session.Battle, _session.Battle?.WaitingActor, _hud.Presenter.Page, _hud.Presenter.Category, _hud.Presenter.FormationActor, _hud.Presenter.AiActor); + + private bool GamepadPresentationBlocksHud => _session?.Battle is { } battle && + (battle.IsModalPresentation || battle.IsCoAttackPresentationBlockingInput); + + private void ReceiveGamepad(BattleEditorGamepadIntent input) + { + if (!CanReceiveGamepad()) + return; + if (_session.IsReplaying) + { + if (input.Kind == BattleEditorGamepadIntentKind.Cancel) + { + _session.CancelReplay(); + Repaint(); + } + return; + } + if (input.Kind == BattleEditorGamepadIntentKind.Transport) + { + // Start never opens an OS dialog or applies an authoring draft. + if (PrimaryAction() is WorkspaceAction.Start or WorkspaceAction.Pause or WorkspaceAction.Resume or WorkspaceAction.Restart) + { + RunPrimaryAction(); + _gamepadContext = null; + _gamepadInput?.ResetNavigation(); + } + return; + } + if (_session.ResultPresentation is { Completed: false } result) + { + if (input.Kind is BattleEditorGamepadIntentKind.Confirm or BattleEditorGamepadIntentKind.Cancel) + { + if (input.Kind == BattleEditorGamepadIntentKind.Cancel && result.StatisticsVisible) + result.CloseStatistics(); + _session.SkipResultStep(); + _gamepadInput?.ResetNavigation(); + Repaint(); + } + return; + } + if (GamepadPresentationBlocksHud) + { + BattleSession battle = _session.Battle; + if ((input.Kind is BattleEditorGamepadIntentKind.Confirm or BattleEditorGamepadIntentKind.Cancel) && + (battle.IsModalPresentation ? battle.SkipModalPresentation() : battle.SkipCoAttackPresentation())) + { + _session.SyncBattle(); + Repaint(); + } + return; + } + if (_session.Battle?.Status != BattleSessionStatus.Running) + return; + _hud.BindBattle(_session.Battle, _session.Data, _session.Preview, SyncHudBattle, SelectHudActor, Repaint); + var before = CurrentGamepadContext(); + bool contextChanged = _gamepadContext.HasValue && _gamepadContext.Value != before; + if (contextChanged) + _gamepadInput?.ResetNavigation(); + _gamepadContext = before; + // A repeat from the previous actor or mouse-selected page must not + // move the new page. A fresh button edge remains fully usable. + if (contextChanged && input.IsRepeat) + return; + _hud.TakeGamepadInput(_session.Battle); + before = CurrentGamepadContext(); + _hud.SendGamepadIntent(input); + var after = CurrentGamepadContext(); + if (after != before) + _gamepadInput?.ResetNavigation(); + _gamepadContext = after; + Repaint(); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.Gamepad.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.Gamepad.cs.meta new file mode 100644 index 00000000..1df00b0d --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.Gamepad.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4e7ef64cd7124fbeb743fa35348935e6 diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.cs new file mode 100644 index 00000000..72522382 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.cs @@ -0,0 +1,667 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using Battle; + using Battle.Presentation; + using Engine.Utilities; + using UnityEditor; + using UnityEngine; + using UnityEngine.UIElements; + + public sealed partial class BattleEditorWindow : EditorWindow + { + [SerializeField] private BattleScenarioAsset _draft; + [SerializeField] private BattleScenarioAsset _asset; + [SerializeField] private string _draftJson = ""; + [SerializeField] private string _savedJson = ""; + [SerializeField] private string _root = ""; + [SerializeField] private string _authoringVariant = ""; + [SerializeField] private List _variantDrafts = new(); + [SerializeField] private bool _initializeTestInventory; + [SerializeField] private int _codepage = 936; + private BattleEditorSession _session; + private BattleEditorGamepadInput _gamepadInput; + private double _lastTime; + private Task _reconnect; + private CancellationTokenSource _reconnectCancellation; + private bool _gamepadPresentationBlocked; + private bool _currentDraftDirty; + private readonly DisplayFramePacer _repaintPacer = new(); + private string _error, _selected, _target, _action, _search = "", _previewJson; + [SerializeField] private bool _autoAllies; + [SerializeField] private bool _autoEnemies = true; + private int _addActor; + private BattleSide _addSide = BattleSide.Enemy; + private Vector2 _rosterScroll, _inspectorScroll; + private readonly List _log = new(); + private readonly BattleHudView _hud = new(); + [UnityEngine.Serialization.FormerlySerializedAs("_debugCombat")] + [SerializeField] private bool _debugBattle; + [SerializeField] private bool _originalAspect; + [SerializeField] private bool _expandCamera = true; + [SerializeField] private bool _touchHud; + [SerializeField] private Vector4 _hudSafeInsets = new(8, 8, 8, 8); + + private BattleScenario Scenario => _draft.Scenario; + +#if PAL3A + [MenuItem("PAL3A/Battle Editor", priority = 31)] +#else + [MenuItem("PAL3/Battle Editor", priority = 31)] +#endif + public static void Open() => GetWindow("Battle Editor"); + + private void OnEnable() + { + titleContent = new GUIContent("Battle Editor"); + wantsMouseMove = true; + minSize = new Vector2(960, 640); + saveChangesMessage = "保存战斗配置后再关闭?"; + NormalizeDrafts(); + VariantDraft state = RestoreAuthoringVariant(BattleData.Variant); + if (_draft == null) + { + _draft = CreateInstance(); + _draft.hideFlags = HideFlags.HideAndDontSave; + _draft.Scenario = new BattleScenario { Variant = BattleData.Variant }; + if (_draftJson.Length == 0 && _asset == null) + _initializeTestInventory = true; + } + if (_draftJson.Length > 0) + _draft.Scenario = BattleScenarioJson.RestoreDraft(_draftJson); + if (_savedJson.Length == 0) + _savedJson = BattleScenarioJson.Serialize(Scenario); + _session = new BattleEditorSession(); + _session.PreviewReleased += _hud.Release; + _gamepadInput?.Dispose(); + _gamepadInput = new BattleEditorGamepadInput(CanReceiveGamepad, ReceiveGamepad); + _hud.PointerTookControl += ReleaseGamepadInput; + _hud.KeyboardTookControl += ReleaseGamepadInput; + _lastTime = EditorApplication.timeSinceStartup; + Undo.undoRedoPerformed += OnUndo; + EditorApplication.projectChanged += OnAuthoringProjectChanged; + EditorApplication.update += Tick; + EditorApplication.playModeStateChanged += OnPlayMode; + if (!string.IsNullOrEmpty(state.ConnectionRoot)) + BeginReconnect(state.ConnectionRoot, state.ConnectionCodepage); + UpdateDirty(); + } + + public void CreateGUI() => rootVisualElement.Add(new IMGUIContainer(DrawWindow) { style = { flexGrow = 1 } }); + + [Serializable] + private sealed class VariantDraft + { + public string Variant; + public string DraftJson; + public string SavedJson; + public string Root; + public int Codepage; + public string ConnectionRoot; + public int ConnectionCodepage; + public bool InitializeTestInventory; + public BattleScenarioAsset Asset; + } + + private static string CanonicalDraftJson(string json) => string.IsNullOrEmpty(json) ? "" : BattleScenarioJson.Serialize(BattleScenarioJson.RestoreDraft(json)); + + private void NormalizeDrafts() + { + // Repair the old field-only codec before migrating either side of + // the dirty comparison into a different variant's stored state. + _draftJson = CanonicalDraftJson(_draftJson); + _savedJson = CanonicalDraftJson(_savedJson); + if (_draft != null && _draftJson.Length > 0) + _draft.Scenario = BattleScenarioJson.RestoreDraft(_draftJson); + foreach (VariantDraft state in _variantDrafts) + { + state.DraftJson = CanonicalDraftJson(state.DraftJson); + state.SavedJson = CanonicalDraftJson(state.SavedJson); + } + } + + private void StoreAuthoringVariant() + { + if (_draft != null) + _draftJson = BattleScenarioJson.Serialize(Scenario); + if (string.IsNullOrEmpty(_authoringVariant)) + return; + VariantDraft state = CurrentVariantDraft(); + state.DraftJson = _draftJson; + state.SavedJson = _savedJson; + state.Asset = _asset; + state.Root = _root; + state.Codepage = _codepage; + state.InitializeTestInventory = _initializeTestInventory; + } + + private VariantDraft CurrentVariantDraft() + { + VariantDraft state = _variantDrafts.FirstOrDefault(value => value.Variant == _authoringVariant); + if (state == null) + { + state = new VariantDraft { Variant = _authoringVariant }; + _variantDrafts.Add(state); + } + return state; + } + + private VariantDraft RestoreAuthoringVariant(string variant) + { + // Migrate windows serialized before variant ownership was recorded. + if (string.IsNullOrEmpty(_authoringVariant)) + _authoringVariant = _draft != null ? Scenario.Variant : _draftJson.Length > 0 ? BattleScenarioJson.RestoreDraft(_draftJson).Variant : variant; + if (_authoringVariant != variant) + { + CancelReconnect(); + StoreAuthoringVariant(); + VariantDraft state = _variantDrafts.FirstOrDefault(value => value.Variant == variant); + _draftJson = state?.DraftJson ?? ""; + _savedJson = state?.SavedJson ?? ""; + _asset = state?.Asset; + _root = state?.Root ?? ""; + _codepage = state?.Codepage ?? 936; + _initializeTestInventory = state?.InitializeTestInventory ?? true; + if (_draft != null) + { + Undo.ClearUndo(_draft); + _draft.Scenario = _draftJson.Length > 0 ? BattleScenarioJson.RestoreDraft(_draftJson) : new BattleScenario { Variant = variant }; + } + _selected = _target = _action = _previewJson = _error = null; + } + _authoringVariant = variant; + bool needsDefaults = string.IsNullOrEmpty(_root) && !_variantDrafts.Any(value => value.Variant == variant); + VariantDraft current = CurrentVariantDraft(); + // Windows serialized before reconnect settings were stored also start + // from the shared default once. Pending edits stay in Root/Codepage. + if (current.ConnectionCodepage == 0) + (current.ConnectionRoot, current.ConnectionCodepage) = DefaultConnection(variant); + if (needsDefaults) + (_root, _codepage) = (current.ConnectionRoot, current.ConnectionCodepage); + return current; + } + + private static (string Root, int Codepage) DefaultConnection(string variant) => + (EditorPrefs.GetString(variant + ".BattleEditor.Path", Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", variant))), + EditorPrefs.GetInt(variant + ".BattleEditor.Codepage", 936)); + + private void OnDisable() + { + CancelReconnect(); + _hud.SetInputFocus(false); + _hud.PointerTookControl -= ReleaseGamepadInput; + _hud.KeyboardTookControl -= ReleaseGamepadInput; + _gamepadInput?.Dispose(); + _gamepadInput = null; + Undo.undoRedoPerformed -= OnUndo; + EditorApplication.projectChanged -= OnAuthoringProjectChanged; + EditorApplication.update -= Tick; + EditorApplication.playModeStateChanged -= OnPlayMode; + StoreAuthoringVariant(); + BattleEditorSession session = _session; + _session = null; + if (session != null) + session.PreviewReleased -= _hud.Release; + try + { + _hud.Release(); + } + finally + { + session?.Dispose(); + } + } + + private void OnDestroy() + { + if (_draft != null) + DestroyImmediate(_draft); + } + + private void OnPlayMode(PlayModeStateChange state) + { + if (state is PlayModeStateChange.ExitingEditMode or PlayModeStateChange.ExitingPlayMode) + _session?.Stop(); + } + + private void OnLostFocus() + { + _heldBattleKeys.Clear(); + _hud.SetInputFocus(false); + _gamepadInput?.Suspend(); + } + + private void OnFocus() => _hud.SetInputFocus(true); + + private void ReleaseGamepadInput() => _gamepadInput?.Suspend(); + + private void OnUndo() + { + string previousDraft = _draftJson; + // Early Undo records predate the first data connection. Preserve + // the generated baseline when restoring an unbound snapshot. + if (_draft != null && _asset == null && string.IsNullOrEmpty(Scenario.DataFingerprint) && !string.IsNullOrEmpty(_savedJson)) + { + BattleScenario baseline = BattleScenarioJson.RestoreDraft(_savedJson); + if (!string.IsNullOrEmpty(baseline.DataFingerprint)) + ApplyTestInventoryDefaults(Scenario, baseline); + } + UpdateDirty(); + if (_draftJson != previousDraft) + PauseForDraftChange(); + Repaint(); + } + + private void OnAuthoringProjectChanged() + { + UpdateDirty(); + Repaint(); + } + + private void Tick() + { + CompleteReconnect(); + double now = EditorApplication.timeSinceStartup; + if (_session?.IsReplaying == true) + Try(_session.TickReplay, pauseOnError: false, clearErrorOnSuccess: false); + else if (_session?.IsPlaying == true) + { + Try(() => _session.Tick((float)Math.Clamp(now - _lastTime, 0, 0.1)), clearErrorOnSuccess: false); + } + _lastTime = now; + bool blocksHud = GamepadPresentationBlocksHud; + if (blocksHud && !_gamepadPresentationBlocked) + _gamepadInput?.ResetNavigation(); + _gamepadPresentationBlocked = blocksHud; + if ((_session?.IsReplaying == true || _session?.IsPlaying == true || _session?.Preview != null && focusedWindow == this) && + _repaintPacer.TryAdvance(now, DisplayFrameRate.RefreshRate)) + Repaint(); + } + + private void Try(Action action, bool pauseOnError = true, bool clearErrorOnSuccess = true) + { + try + { + action(); + if (clearErrorOnSuccess) + _error = null; + } + catch (ExitGUIException) + { + throw; + } + catch (Exception ex) + { + _error = ex.Message; + if (pauseOnError && _session != null) + _session.IsPlaying = false; + Log(_error); + } + } + + private void Log(string message) + { + _log.Add(message); + if (_log.Count > 100) + _log.RemoveAt(0); + } + + private void LoadData() + { + ConnectData(_root, _codepage); + EditorPrefs.SetString(BattleData.Variant + ".BattleEditor.Path", _root); + EditorPrefs.SetInt(BattleData.Variant + ".BattleEditor.Codepage", _codepage); + } + + private void TryLoadData() => Try(LoadData, pauseOnError: false); + + private void ConnectData(string root, int codepage) + { + CancelReconnect(); + _session.Load(root, codepage); + DataConnected(); + } + + private void BeginReconnect(string root, int codepage) + { + CancelReconnect(); + _reconnectCancellation = new CancellationTokenSource(); + CancellationToken cancellation = _reconnectCancellation.Token; + _reconnect = Task.Run(() => Directory.Exists(root) ? new BattleData(root, codepage, cancellation) : null, cancellation); + } + + private void CompleteReconnect() + { + if (_reconnect is not { IsCompleted: true } reconnect) + return; + _reconnect = null; + _reconnectCancellation.Dispose(); + _reconnectCancellation = null; + Try(() => + { + BattleData data = reconnect.GetAwaiter().GetResult(); + if (data == null) + return; + if (_session.Data != null) + { + data.Dispose(); + return; + } + _session.UseData(data); + DataConnected(); + }, pauseOnError: false, clearErrorOnSuccess: false); + Repaint(); + } + + private void CancelReconnect() + { + if (_reconnect == null) + return; + Task reconnect = _reconnect; + CancellationTokenSource cancellation = _reconnectCancellation; + _reconnect = null; + _reconnectCancellation = null; + cancellation.Cancel(); + _ = reconnect.ContinueWith(completed => + { + try + { + if (completed.IsCompletedSuccessfully) + completed.Result?.Dispose(); + _ = completed.Exception; + } + finally + { + cancellation.Dispose(); + } + }, TaskScheduler.Default); + } + + private void DataConnected() + { + if (_initializeTestInventory) + { + BattleScenario defaults = BattleTestLoadoutBuilder.CreateScenario(_session.Data); + BattleScenario baseline = BattleScenarioJson.RestoreDraft(_savedJson); + ApplyTestInventoryDefaults(baseline, defaults); + _savedJson = BattleScenarioJson.Serialize(baseline); + ApplyTestInventoryDefaults(Scenario, defaults); + _initializeTestInventory = false; + UpdateDirty(); + } + _validation = null; + VariantDraft state = CurrentVariantDraft(); + state.ConnectionRoot = _session.Data.Resources.Root; + state.ConnectionCodepage = _session.Data.Resources.Codepage; + Log($"{BattleData.Variant}: {_session.Data.Scenes.Length} 个战场,{_session.Data.Database.CombatActorInfos.Count} 个角色;只读加载 basedata.cpk。"); + } + + private static void ApplyTestInventoryDefaults(BattleScenario scenario, BattleScenario defaults) + { + if (scenario.Items.Count == 0) + { + scenario.Items = defaults.Items; + if (scenario.TreasureUses.Count == 0) + scenario.TreasureUses = defaults.TreasureUses; + } + scenario.DataFingerprint = defaults.DataFingerprint; + } + + private bool CurrentDraftDirty => _currentDraftDirty; + + private IEnumerable DirtyVariants() => _variantDrafts.Where(state => !string.IsNullOrEmpty(state.DraftJson) && + state.DraftJson != (state.Asset != null ? BattleScenarioJson.Serialize(state.Asset.Scenario) : state.SavedJson)); + + private void UpdateDirty() + { + if (_draft == null) + return; + _validation = null; + StoreAuthoringVariant(); + string[] dirty = DirtyVariants().Select(state => state.Variant).ToArray(); + _currentDraftDirty = dirty.Contains(_authoringVariant); + hasUnsavedChanges = dirty.Length > 0; + saveChangesMessage = "保存以下作品的战斗配置后再关闭?" + string.Join("、", dirty); + } + + private void Edit(string label, Action change) + { + PauseForDraftChange(); + Undo.RecordObject(_draft, label); + change(); + EditorUtility.SetDirty(_draft); + UpdateDirty(); + } + + private bool CanReplace() + { + if (!CurrentDraftDirty) + return true; + int answer = EditorUtility.DisplayDialogComplex("战斗配置尚未保存", "保存当前配置后再继续?", "保存", "取消", "放弃"); + if (answer == 1) + return false; + if (answer == 0) + { + Try(() => SaveScenario(false)); + return !CurrentDraftDirty; + } + return true; + } + + private void NewScenario() + { + if (!CanReplace()) + return; + _session.Stop(); + Undo.ClearUndo(_draft); + _asset = null; + _draft.Scenario = BattleTestLoadoutBuilder.CreateScenario(_session.Data); + _initializeTestInventory = _session.Data == null; + _savedJson = BattleScenarioJson.Serialize(Scenario); + UpdateDirty(); + _selected = null; + _drawer = WorkspaceDrawer.Configuration; + _configurationPage = 1; + } + + private void LoadAsset(BattleScenarioAsset asset) + { + if (asset == null || asset.Scenario == null) + return; + CheckAuthoringVersion(asset.Scenario); + if (asset == _asset || !CanReplace()) + return; + _session.Stop(); + Undo.ClearUndo(_draft); + _asset = asset; + _initializeTestInventory = false; + _draft.Scenario = asset.Scenario.Copy(); + _savedJson = BattleScenarioJson.Serialize(Scenario); + UpdateDirty(); + _selected = null; + } + + // EditorWindow calls this for its close/save flow. Every draft named + // in the close prompt must be saved before the window can be destroyed. + public override void SaveChanges() => Try(() => SaveDrafts(SelectScenarioPath)); + + private void SaveDrafts(Func pickPath) + { + StoreAuthoringVariant(); + try + { + var planned = new List<(VariantDraft State, BattleScenario Scenario, string Path)>(); + var newPaths = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (VariantDraft state in DirtyVariants()) + { + BattleScenario scenario = BattleScenarioJson.RestoreDraft(state.DraftJson); + if (scenario.Version != BattleScenario.CurrentVersion || scenario.Variant is not ("PAL3" or "PAL3A") || scenario.Variant != state.Variant) + throw new InvalidDataException("Unsupported battle draft: " + state.Variant + ". The draft and preset have been kept unchanged."); + string path = null; + if (state.Asset == null) + { + path = pickPath(scenario.Variant); + if (path == null) + return; + if (!newPaths.Add(path)) + throw new IOException("请为每个作品选择不同的预设路径。"); + } + planned.Add((state, scenario, path)); + } + foreach (var (state, scenario, path) in planned) + { + BattleScenarioAsset destination = WriteScenario(scenario, state.Asset, path); + state.Asset = destination; + state.SavedJson = state.DraftJson; + state.InitializeTestInventory = false; + if (state.Variant == _authoringVariant) + { + _asset = destination; + _savedJson = state.SavedJson; + _initializeTestInventory = false; + } + } + base.SaveChanges(); + } + finally + { + UpdateDirty(); + } + } + + private void SaveScenario(bool saveAs) + { + CheckAuthoringVersion(Scenario); + BattleScenarioAsset destination = saveAs ? null : _asset; + string path = destination == null ? SelectScenarioPath(Scenario.Variant) : null; + if (destination == null && path == null) + return; + destination = WriteScenario(Scenario, destination, path); + _asset = destination; + _initializeTestInventory = false; + _savedJson = BattleScenarioJson.Serialize(Scenario); + UpdateDirty(); + } + + private static string SelectScenarioPath(string variant) + { + string path = EditorUtility.SaveFilePanelInProject("保存 " + variant + " 战斗配置", "BattleScenario", "asset", "选择自有预设保存位置"); + if (path.Length == 0) + return null; + if (AssetDatabase.LoadMainAssetAtPath(path) != null) + throw new IOException("该路径已有资产,请选择新路径或直接保存当前预设。"); + return path; + } + + private BattleScenarioAsset WriteScenario(BattleScenario scenario, BattleScenarioAsset destination, string path) + { + if (destination == null) + { + destination = CreateInstance(); + try + { + destination.Scenario = scenario.Copy(); + AssetDatabase.CreateAsset(destination, path); + } + catch + { + if (!EditorUtility.IsPersistent(destination)) + DestroyImmediate(destination); + throw; + } + } + else + { + destination.Scenario = scenario.Copy(); + EditorUtility.SetDirty(destination); + } + AssetDatabase.SaveAssetIfDirty(destination); + Log("已保存 " + AssetDatabase.GetAssetPath(destination)); + return destination; + } + + private static void CheckAuthoringVersion(BattleScenario scenario) + { + if (scenario.Version != BattleScenario.CurrentVersion || scenario.Variant != BattleData.Variant) + throw new InvalidDataException($"This editor supports {BattleData.Variant} scenario version {BattleScenario.CurrentVersion}. The draft and existing asset have been kept unchanged."); + } + + public override void DiscardChanges() + { + PauseForDraftChange(); + foreach (VariantDraft state in _variantDrafts.Where(state => state.Variant != _authoringVariant)) + { + state.DraftJson = BattleScenarioJson.Serialize(state.Asset != null ? state.Asset.Scenario : new BattleScenario { Variant = state.Variant }); + state.SavedJson = state.DraftJson; + state.InitializeTestInventory = state.Asset == null; + } + _draft.Scenario = _asset != null ? _asset.Scenario.Copy() : BattleTestLoadoutBuilder.CreateScenario(_session?.Data); + _initializeTestInventory = _asset == null && _session?.Data == null; + _savedJson = BattleScenarioJson.Serialize(Scenario); + base.DiscardChanges(); + UpdateDirty(); + } + + private void StartPreview() + { + _session.Start(Scenario); + _previewJson = BattleScenarioJson.Serialize(Scenario); + Log("动作预览已启动;在诊断面板选择角色、动作或攻击目标。此模式只演示动画。"); + } + + private void ExportReport() + { + string path = EditorUtility.SaveFilePanel("导出战斗配置与诊断", "", "battle-preview", "json"); + if (path.Length == 0) + return; + var report = new PreviewReport + { + Scenario = Scenario.Copy(), + Captured = _session.CapturedScenario, + Diagnostics = (_session.Data?.Validate(Scenario, forBattle: true) ?? Scenario.Validate()).Concat(_session.Preview?.Diagnostics ?? new List()) + .Concat(_error == null ? Array.Empty() : new[] { _error }).Distinct().ToArray(), + }; + report.Inputs = _session.Battle?.Inputs.ToArray(); + report.Events = _session.Battle?.Events.ToArray(); + report.Result = _session.Battle?.Result; + report.FinalTick = _session.Battle?.Tick ?? 0; + report.Definitions = _session.Battle?.Definitions; + report.Actors = _session.Battle?.Actors.ToArray(); + report.Inventory = _session.Battle?.Inventory.ToArray(); + report.Money = _session.Battle?.Money ?? Scenario.Money; + report.Pal3A = _session.Battle?.Definitions.Variant == "PAL3A" ? _session.Battle.Pal3AState : null; + ResourceBrowser.ResourceCatalog.WriteTextFile(path, + Newtonsoft.Json.JsonConvert.SerializeObject(report, Newtonsoft.Json.Formatting.Indented), _session.Data?.Resources.Root); + Log("已导出 " + path); + } + + // JSON export DTO; Unity does not persist this report. + private sealed class PreviewReport + { + public int FormatVersion = 2; + + public BattleScenario Scenario; + public BattleScenario Captured; + public string[] Diagnostics; + public long FinalTick; + public BattleInput[] Inputs; + public BattleEvent[] Events; + public BattleResult Result; + public BattleDefinitions Definitions; + public BattleActorSnapshot[] Actors; + public BattleItemSnapshot[] Inventory; + public int Money; + public BattlePal3AStateSnapshot Pal3A; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.cs.meta new file mode 100644 index 00000000..68ac04e6 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWindow.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 84eeee9e564d34db0b1179ea68e39ca3 \ No newline at end of file diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWorkbench.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWorkbench.cs new file mode 100644 index 00000000..1e04a84f --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWorkbench.cs @@ -0,0 +1,633 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using Battle; + using Battle.Presentation; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattleEditorWindow + { + private const float DrawerWidth = 360; + + private enum WorkspaceDrawer + { + None, Configuration, Diagnostics, Connection + } + + private enum WorkspaceAction + { + Connect, Random, Configure, Start, Pause, Resume, Restart, Apply + } + + [SerializeField] private WorkspaceDrawer _drawer; + [SerializeField] private int _configurationPage; + [SerializeField] private int _diagnosticPage; + [SerializeField] private BattleDamageNumberColorMode _damageNumberColor; + private bool _addParticipant; + private string[] _validation; + private readonly Dictionary _sections = new(); + private readonly Dictionary _workspaceControls = new(); + private Rect _workspaceCanvasRect; + private Rect _welcomeRect; + private Vector2 _workspaceGuiScreenOrigin; + private int _assetPickerId; + private Action _showAssetPicker = (asset, id) => + EditorGUIUtility.ShowObjectPicker(asset, false, "", id); + + private BattleEditorTheme _theme; + + private BattleEditorTheme Theme => _theme != null && _theme.ProSkin == EditorGUIUtility.isProSkin ? _theme : _theme = new BattleEditorTheme(); + + private void RememberControl(string id, Rect rect) + { + if (Event.current.type == EventType.Repaint) + _workspaceControls[id] = new Rect(GUIUtility.GUIToScreenPoint(rect.position) - _workspaceGuiScreenOrigin, rect.size); + } + + private bool DraftPending => _session?.Preview != null && _previewJson != _draftJson; + + private void PauseForDraftChange() + { + if (_session != null) + { + _session.CancelReplay(); + _session.IsPlaying = false; + } + } + + private string[] Validation() + { + if (_validation == null) + { + if (BattleScenarioEditing.NeedsRepair(Scenario)) + _validation = new[] { "配置缺少必需内容,请先修复。" }; + else + _validation = (_session.Data?.Validate(Scenario, forBattle: true) ?? Scenario.Validate()).ToArray(); + } + return _validation; + } + + private WorkspaceAction PrimaryAction() + { + if (_session.Data == null) + return WorkspaceAction.Connect; + if (BattleScenarioEditing.NeedsRepair(Scenario)) + return WorkspaceAction.Configure; + if (Scenario.Participants.Count == 0 && string.IsNullOrEmpty(Scenario.Scene)) + return WorkspaceAction.Random; + if (Validation().Length > 0) + return WorkspaceAction.Configure; + if (DraftPending) + return WorkspaceAction.Apply; + if (_session.Battle == null) + return WorkspaceAction.Start; + if (_session.ResultPresentation?.Completed == true || + _session.Battle.Status is BattleSessionStatus.Aborted or BattleSessionStatus.Faulted || + _session.Battle.Status == BattleSessionStatus.Completed && _session.ResultPresentation == null) + return WorkspaceAction.Restart; + return _session.IsPlaying ? WorkspaceAction.Pause : WorkspaceAction.Resume; + } + + private string PrimaryLabel() => PrimaryAction() switch + { + WorkspaceAction.Connect => "选择数据目录", + WorkspaceAction.Random => "创建随机战斗", + WorkspaceAction.Configure => "检查配置", + WorkspaceAction.Start => "开始测试", + WorkspaceAction.Pause => "暂停", + WorkspaceAction.Resume => _session.Battle.Status == BattleSessionStatus.Completed ? "继续结果" : "继续测试", + WorkspaceAction.Restart => "重新测试", + _ => "应用并重新开始", + }; + + private void RunPrimaryAction() + { + switch (PrimaryAction()) + { + case WorkspaceAction.Connect: + ChooseDataFolder(true); + break; + case WorkspaceAction.Random: + Try(CreateRandomExample); + break; + case WorkspaceAction.Configure: + _drawer = WorkspaceDrawer.Configuration; + _inspectorScroll = Vector2.zero; + break; + case WorkspaceAction.Pause: + _session.IsPlaying = false; + break; + case WorkspaceAction.Resume: + _session.IsPlaying = true; + break; + default: + Try(() => + { + StartBattle(); + _session.IsPlaying = true; + }); + break; + } + Repaint(); + } + + private readonly HashSet _heldBattleKeys = new(); + + private void DrawWindow() + { + Event input = Event.current; + if (input.rawType == EventType.KeyUp) + _heldBattleKeys.Remove(input.keyCode); + bool newBattleKey = BattleHudView.IsBattleKey(input) && _heldBattleKeys.Add(input.keyCode); + if (Event.current.type == EventType.MouseDown) + ReleaseGamepadInput(); + if (_draft == null || _session == null) + return; + if (Event.current.type == EventType.Repaint) + { + _workspaceControls.Clear(); + _workspaceGuiScreenOrigin = GUIUtility.GUIToScreenPoint(Vector2.zero); + } + _assetPickerId = GUIUtility.GetControlID(0x42617474, FocusType.Passive); + HandleAssetPicker(); + bool replaying = _session.IsReplaying; + if (replaying && input.type == EventType.KeyDown && input.keyCode == KeyCode.Escape) + { + _session.CancelReplay(); + input.Use(); + } + using var disabled = new EditorGUI.DisabledScope(EditorApplication.isPlayingOrWillChangePlaymode || replaying); + DrawWorkspaceToolbar(); + bool drawerVisible = _drawer != WorkspaceDrawer.None; + float drawerLeft = position.width - DrawerWidth - 8; + _workspaceCanvasRect = new Rect(8, BattleEditorTheme.CanvasTop, drawerVisible ? drawerLeft - 16 : position.width - 16, Mathf.Max(100, position.height - BattleEditorTheme.CanvasTop - 8)); + DrawCanvas(_workspaceCanvasRect, newBattleKey); + if (DraftPending || replaying) + { + var banner = new Rect(_workspaceCanvasRect.x + 12, _workspaceCanvasRect.y + 8, _workspaceCanvasRect.width - 24, 30); + EditorGUI.DrawRect(banner, new Color(0.12f, 0.12f, 0.12f, .96f)); + GUI.Label(banner, replaying ? "正在重放战斗记录…" : "配置已修改 · 画布保留上次测试,应用配置后继续操作", + BattleHudCanvas.LabelStyle(11, Color.white, alignment: TextAnchor.MiddleCenter)); + if (replaying && !EditorApplication.isPlayingOrWillChangePlaymode) + { + GUI.enabled = true; + try + { + if (GUI.Button(new Rect(banner.xMax - 72, banner.y + 3, 66, 24), "取消")) + _session.CancelReplay(); + } + finally + { + GUI.enabled = false; + } + } + } + if (drawerVisible) + DrawDrawer(new Rect(drawerLeft, BattleEditorTheme.CanvasTop, DrawerWidth, _workspaceCanvasRect.height)); + } + + private bool WorkspaceButton(string id, Rect rect, string label, bool selected = false, bool primary = false, bool toolbar = false) + { + RememberControl(id, rect); + Color previous = GUI.backgroundColor; + try + { + if (primary) + GUI.backgroundColor = Theme.Accent; + return GUI.Toggle(rect, selected, label, primary ? Theme.PrimaryButton : toolbar ? Theme.ToolbarButton : Theme.Button) != selected; + } + finally + { + GUI.backgroundColor = previous; + } + } + + private bool DrawerButton(string label, params GUILayoutOption[] options) => GUILayout.Button(label, Theme.Button, options); + + private int DrawerTabs(string id, int selected, string[] labels) + { + Rect rect = GUILayoutUtility.GetRect(GUIContent.none, Theme.Tabs, + GUILayout.Height(BattleEditorTheme.ControlHeight), GUILayout.ExpandWidth(true)); + RememberControl(id, rect); + int navigationId = GUIUtility.GetControlID(id.GetHashCode(), FocusType.Keyboard, rect); + Event input = Event.current; + if (GUI.enabled && input.type == EventType.MouseDown && input.button == 0 && rect.Contains(input.mousePosition)) + GUIUtility.keyboardControl = navigationId; + // GUILayout.Toolbar resolves built-in Left/Mid/Right styles by + // name, discarding the local height. Use those native textures + // through our own style copies so their actual pixels stay 24pt. + float[] widths = labels.Select(label => Theme.Tabs.CalcSize(new GUIContent(label)).x).ToArray(); + float total = widths.Sum(); + float extra = Math.Max(0, rect.width - total) / labels.Length; + float x = rect.x; + int next = selected; + for (int index = 0; index < labels.Length; index++) + { + float width = total > rect.width ? widths[index] * rect.width / total : widths[index] + extra; + GUIStyle style = index == 0 ? Theme.TabLeft : index == labels.Length - 1 ? Theme.TabRight : Theme.TabMiddle; + float pixels = EditorGUIUtility.pixelsPerPoint; + float left = Mathf.Round(x * pixels) / pixels; + float right = Mathf.Round((x + width) * pixels) / pixels; + var tabRect = new Rect(left, rect.y, right - left, rect.height); + RememberControl(id.Replace("tabs:", "tab:") + ":" + index, tabRect); + if (GUI.Toggle(tabRect, selected == index, labels[index], style) && selected != index) + next = index; + x += width; + } + if (GUI.enabled && input.type == EventType.KeyDown && input.keyCode is KeyCode.LeftArrow or KeyCode.RightArrow && + GUIUtility.keyboardControl == navigationId && !EditorGUIUtility.editingTextField) + { + next = (selected + (input.keyCode == KeyCode.LeftArrow ? labels.Length - 1 : 1)) % labels.Length; + GUI.changed = true; + input.Use(); + } + return next; + } + + private void DrawWorkspaceToolbar() + { + const float y = 4, gap = 6, height = BattleEditorTheme.ControlHeight; + EditorGUI.DrawRect(new Rect(0, 0, position.width, BattleEditorTheme.CanvasTop), Theme.Header); + EditorGUI.DrawRect(new Rect(0, BattleEditorTheme.CanvasTop - 1, position.width, 1), Theme.Border); + if (WorkspaceButton("file", new Rect(8, y, 50, height), "文件 ▾", toolbar: true)) + ShowFileMenu(); + string connection = _reconnect != null ? "正在连接… ▾" : _session.Data == null ? "连接数据 ▾" : "数据已连接 ▾"; + if (WorkspaceButton("connection", new Rect(64, y, 92, height), connection, + _drawer == WorkspaceDrawer.Connection, toolbar: true)) + ToggleDrawer(WorkspaceDrawer.Connection); + ToolbarSeparator(162, y, height); + GUI.Label(new Rect(174, y, 42, height), BattleData.Variant, Theme.Title); + + // Keep the primary action at the right edge in every test state. + // Only the document title absorbs changes in available width. + float primaryX = position.width - 8 - 120; + float runX = primaryX - (_session.Preview != null ? 44 + gap : 0) - (_session.Battle != null ? 52 + gap : 0); + float toolsX = runX - 12 - 72 * 2 - gap; + string name = (_asset != null ? _asset.name : "未命名战斗") + (CurrentDraftDirty ? " *" : ""); + GUI.Label(new Rect(222, y, Mathf.Max(0, toolsX - 234), height), + new GUIContent(name, _asset != null ? AssetDatabase.GetAssetPath(_asset) : "使用文件菜单保存为战斗预设"), Theme.Metadata); + if (WorkspaceButton("configuration", new Rect(toolsX, y, 72, height), "编辑配置", + _drawer == WorkspaceDrawer.Configuration, toolbar: true)) + ToggleDrawer(WorkspaceDrawer.Configuration); + if (WorkspaceButton("diagnostics", new Rect(toolsX + 72 + gap, y, 72, height), + _error == null ? "诊断工具" : "诊断 · !", _drawer == WorkspaceDrawer.Diagnostics, toolbar: true)) + { + ToggleDrawer(WorkspaceDrawer.Diagnostics); + if (_error != null) + { + _drawer = WorkspaceDrawer.Diagnostics; + _diagnosticPage = 2; + _inspectorScroll = Vector2.zero; + } + } + ToolbarSeparator(runX - 7, y, height); + float x = runX; + if (_session.Preview != null) + { + if (WorkspaceButton("stop", new Rect(x, y, 44, height), "停止", toolbar: true)) + _session.Stop(); + x += 44 + gap; + } + if (_session.Battle != null) + { + float[] speeds = { 1f, 2f, 4f }; + int old = Array.IndexOf(speeds, _session.Speed); + if (old < 0) + { + old = speeds.Length; + speeds = speeds.Append(_session.Speed).ToArray(); + } + var speedRect = new Rect(x, y, 52, height); + RememberControl("speed", speedRect); + int next = EditorGUI.Popup(speedRect, old, speeds.Select(speed => $"{speed:0.##}×").ToArray(), Theme.Popup); + if (old != next) + _session.Speed = speeds[next]; + } + if (WorkspaceButton("primary", new Rect(primaryX, y, 120, height), PrimaryLabel(), primary: true)) + RunPrimaryAction(); + } + + private void ToolbarSeparator(float x, float y, float height) => + EditorGUI.DrawRect(new Rect(x, y + 5, 1, height - 10), Theme.Border); + + private void ToggleDrawer(WorkspaceDrawer drawer) + { + _drawer = _drawer == drawer ? WorkspaceDrawer.None : drawer; + Repaint(); + } + + private void DrawWelcome(Rect canvas) + { + float width = Mathf.Min(400, canvas.width - 40); + _welcomeRect = new Rect(canvas.center.x - width / 2, canvas.center.y - 92, width, 184); + WorkspaceAction action = PrimaryAction(); + string text = action switch + { + WorkspaceAction.Connect => $"连接 {BattleData.Variant} 原版数据,配置并测试一场战斗。", + WorkspaceAction.Random => "随机生成场景与双方队伍,或从预设开始。", + WorkspaceAction.Configure => Validation().FirstOrDefault() ?? "在右侧配置场景与双方队伍。", + _ => $"场景 {Scenario.Scene} · 我方 {Scenario.Participants.Count(p => p.Side == BattleSide.Ally)} 人 · 敌方 {Scenario.Participants.Count(p => p.Side == BattleSide.Enemy)} 人", + }; + GUI.Label(new Rect(_welcomeRect.x, _welcomeRect.y + 8, width, 34), "战斗编辑器", Theme.WelcomeTitle); + GUI.Label(new Rect(_welcomeRect.x, _welcomeRect.y + 50, width, 36), text, Theme.WelcomeText); + const float buttonWidth = 224; + float x = _welcomeRect.center.x - buttonWidth / 2; + if (WorkspaceButton("welcome-primary", new Rect(x, _welcomeRect.y + 102, buttonWidth, BattleEditorTheme.ControlHeight), PrimaryLabel(), primary: true)) + RunPrimaryAction(); + bool needsRoster = (Scenario.Participants?.Count ?? 0) == 0; + using (new EditorGUI.DisabledScope(_session.Data == null)) + if (WorkspaceButton("welcome-manual", new Rect(x, _welcomeRect.y + 136, 108, BattleEditorTheme.ControlHeight), + needsRoster ? "手动配置" : "编辑配置")) + { + _drawer = WorkspaceDrawer.Configuration; + _configurationPage = needsRoster ? 1 : 0; + } + if (WorkspaceButton("welcome-open", new Rect(x + 116, _welcomeRect.y + 136, 108, BattleEditorTheme.ControlHeight), "打开预设…")) + OpenAssetPicker(); + } + + private void DrawDrawer(Rect rect) + { + GUI.Box(rect, GUIContent.none, EditorStyles.helpBox); + GUILayout.BeginArea(new Rect(rect.x + 10, rect.y + 8, rect.width - 20, rect.height - 16)); + float previous = EditorGUIUtility.labelWidth; + EditorGUIUtility.labelWidth = 142; + try + { + Rect header = GUILayoutUtility.GetRect(0, BattleEditorTheme.ControlHeight, GUILayout.ExpandWidth(true)); + GUI.Label(new Rect(header.x, header.y, header.width - 32, header.height), _drawer switch + { + WorkspaceDrawer.Configuration => "战斗配置", + WorkspaceDrawer.Diagnostics => "诊断工具", + _ => "连接原版数据" + }, Theme.Title); + if (WorkspaceButton("drawer-close", new Rect(header.xMax - 24, header.y, 24, header.height), "×")) + ToggleDrawer(_drawer); + GUILayout.Space(6); + if (_drawer == WorkspaceDrawer.Configuration) + _configurationPage = DrawerTabs("tabs:configuration", _configurationPage, new[] { "场景", "队伍", "物品" }); + if (_drawer == WorkspaceDrawer.Diagnostics) + _diagnosticPage = DrawerTabs("tabs:diagnostics", _diagnosticPage, new[] { "观察", "资源表", "日志" }); + GUILayout.Space(6); + using var scroll = new EditorGUILayout.ScrollViewScope(_inspectorScroll); + _inspectorScroll = scroll.scrollPosition; + GUILayout.Space(2); + if (_drawer == WorkspaceDrawer.Connection) + DrawConnection(); + else if (_drawer == WorkspaceDrawer.Diagnostics) + DrawDiagnostics(); + else + DrawConfiguration(); + } + finally + { + EditorGUIUtility.labelWidth = previous; + GUILayout.EndArea(); + } + } + + private void DrawConfiguration() + { + if (_session.Data == null) + { + EditorGUILayout.HelpBox("请先连接原版数据,再选择战斗场景和添加参战者。", MessageType.Info); + if (DrawerButton("连接原版数据")) + _drawer = WorkspaceDrawer.Connection; + } + if (BattleScenarioEditing.NeedsRepair(Scenario)) + { + EditorGUILayout.HelpBox("配置缺少必需内容。修复会保留已有字段并移除空元素,可撤销。", MessageType.Warning); + if (DrawerButton("修复缺失配置")) + Edit("Repair battle authoring fields", () => _draft.Scenario = BattleScenarioEditing.Repair(Scenario)); + return; + } + foreach (string message in Validation().Take(3)) + EditorGUILayout.HelpBox(message, MessageType.Warning); + if (_session.Data != null && Scenario.DataFingerprint != _session.Data.Fingerprint) + { + if (DrawerButton("将配置绑定到当前数据")) + Edit("Bind battle data", () => Scenario.DataFingerprint = _session.Data.Fingerprint); + } + if (_configurationPage == 0) + DrawScenario(Scenario); + else if (_configurationPage == 1) + { + DrawRoster(); + GUILayout.Space(10); + BattleParticipant actor = Scenario.Participants.FirstOrDefault(p => p.InstanceId == _selected); + if (actor != null) + DrawParticipant(actor); + else + GUILayout.Label("选择上方参战者编辑等级、阵位与初始状态。", EditorStyles.wordWrappedMiniLabel); + } + else + { + Field(Scenario, "Money", "本局金钱"); + Field(Scenario, "TreasureUses", "仙宝 ID/剩余次数(0–255)"); + Field(Scenario, "Items", "物品 ID/数量"); + EditorGUILayout.HelpBox("只影响本次测试,不写入正式背包或存档。可在诊断的资源表中查找物品并加入配置。", MessageType.Info); + } + } + + private bool Section(string id, string title) + { + GUILayout.Space(BattleEditorTheme.GroupSpacing); + Rect rect = EditorGUILayout.GetControlRect(false, BattleEditorTheme.ControlHeight); + RememberControl("section:" + id, rect); + float labelWidth = EditorGUIUtility.labelWidth; + bool value; + try + { + EditorGUIUtility.labelWidth = rect.width; + value = EditorGUI.Foldout(rect, _sections.GetValueOrDefault(id), title, true, Theme.Section); + } + finally + { + EditorGUIUtility.labelWidth = labelWidth; + } + _sections[id] = value; + if (value) + GUILayout.Space(4); + return value; + } + + private void DrawConnection() + { + if (_session.Data != null) + { + GUILayout.Label("当前连接", EditorStyles.boldLabel); + EditorGUILayout.SelectableLabel(_session.Data.Resources.Root, EditorStyles.wordWrappedMiniLabel, GUILayout.Height(44)); + GUILayout.Label(_session.Data.Resources.Codepage == 950 ? "繁體中文 · 950" : "简体中文 · 936", EditorStyles.miniLabel); + } + GUILayout.Space(8); + GUILayout.Label("数据目录", EditorStyles.boldLabel); + _root = EditorGUILayout.TextField(_root); + if (DrawerButton("浏览目录…")) + ChooseDataFolder(false); + _codepage = EditorGUILayout.Popup("文字编码", _codepage == 950 ? 1 : 0, new[] { "简体 936", "繁體 950" }) == 0 ? 936 : 950; + EditorGUILayout.HelpBox($"选择 {BattleData.Variant} 中直接包含 basedata 的目录。加载成功后会停止当前测试,保留战斗配置。", MessageType.Info); + if (DrawerButton("加载数据")) + TryLoadData(); + if (_error != null) + EditorGUILayout.HelpBox(_error, MessageType.Error); + } + + private void ChooseDataFolder(bool load) + { + _drawer = WorkspaceDrawer.Connection; + string path = EditorUtility.OpenFolderPanel("选择 " + BattleData.Variant + " 数据目录", _root, ""); + if (path.Length == 0) + return; + _root = path; + if (load) + TryLoadData(); + } + + private void DrawDiagnostics() + { + if (_diagnosticPage == 1) + { + if (BattleScenarioEditing.NeedsRepair(Scenario)) + EditorGUILayout.HelpBox("先修复配置,再从资源表加入字段。", MessageType.Warning); + else + DrawDataCatalog(); + return; + } + if (_diagnosticPage == 2) + { + if (_error != null) + EditorGUILayout.HelpBox(_error, MessageType.Error); + foreach (string message in Validation()) + EditorGUILayout.HelpBox(message, MessageType.Warning); + foreach (string message in _session.Preview?.Diagnostics ?? Array.Empty()) + EditorGUILayout.HelpBox(message, MessageType.Warning); + GUILayout.Label(string.Join("\n", _log), EditorStyles.wordWrappedMiniLabel); + if (_session.Battle != null) + GUILayout.Label(string.Join("\n", _session.Battle.Events.Skip(Math.Max(0, _session.Battle.Events.Count - 50))), EditorStyles.wordWrappedMiniLabel); + if (DrawerButton("导出配置与诊断…")) + Try(ExportReport); + return; + } + DrawDisplaySettings(); + if (_session.Data == null || BattleScenarioEditing.NeedsRepair(Scenario)) + return; + if (DraftPending) + EditorGUILayout.HelpBox("画布使用修改前的配置。应用并重新开始后,调试命令恢复可用。", MessageType.Info); + using (new EditorGUI.DisabledScope(DraftPending)) + { + if (_session.Battle != null) + { + if (DrawerButton("单步(一个逻辑步)")) + Try(_session.StepBattle); + if (Section("live-inspection", "当前测试状态与调试命令")) + DrawBattleBody(); + } + if (_session.Preview != null && _session.Battle == null) + { + GUILayout.Label("动作预览", EditorStyles.boldLabel); + using (new EditorGUILayout.HorizontalScope()) + { + if (DrawerButton(_session.IsPlaying ? "暂停动作" : "播放动作")) + { + if (!_session.IsPlaying && _session.Preview.Time >= _session.Preview.Duration) + _session.Preview.Sample(0); + _session.IsPlaying = !_session.IsPlaying; + } + GUILayout.Space(6); + if (DrawerButton("单步动作")) + { + _session.IsPlaying = false; + Try(() => _session.Preview.Sample(_session.Preview.Time + 0.02f)); + } + } + float speed = EditorGUILayout.Slider("预览倍速", _session.Speed, 0.1f, 4); + if (speed != _session.Speed) + _session.Speed = speed; + float time = EditorGUILayout.Slider("时间", _session.Preview.Time, 0, _session.Preview.Duration); + if (time != _session.Preview.Time) + { + _session.IsPlaying = false; + Try(() => _session.Preview.Sample(time)); + } + DrawActions(_session.Preview); + } + } + if (Section("preview-tools", "动作与测试工具")) + { + GUILayout.Label("动作预览会替换当前测试,只播放动画。", EditorStyles.wordWrappedMiniLabel); + if (DrawerButton("建立动作预览")) + Try(StartPreview); + _autoAllies = EditorGUILayout.Toggle("下次开局我方自动", _autoAllies); + _autoEnemies = EditorGUILayout.Toggle("下次开局敌方自动", _autoEnemies); + if (_session.Preview != null && !DraftPending && DrawerButton("重开当前测试快照")) + Try(_session.Restart); + } + } + + private void DrawDisplaySettings() + { + if (!Section("display", "画布与操作设置")) + return; + _originalAspect = EditorGUILayout.Toggle("原版 4:3 画布", _originalAspect); + _expandCamera = EditorGUILayout.Toggle("扩展原版视野", _expandCamera); + _touchHud = EditorGUILayout.Toggle("触屏操作", _touchHud); + _hudSafeInsets = EditorGUILayout.Vector4Field("安全区 左/上/右/下", _hudSafeInsets); + int color = EditorGUILayout.Popup("受击数字颜色", (int)_damageNumberColor, new[] { "原版蓝色", "黄色", "白色" }); + _damageNumberColor = (BattleDamageNumberColorMode)color; + _debugBattle = EditorGUILayout.Toggle("显示角色调试标签", _debugBattle); + if (_session.Preview != null && DrawerButton("镜头回到全景")) + _session.Preview.View.Frame(); + } + + private void ShowFileMenu() + { + var menu = new GenericMenu(); + bool editable = !EditorApplication.isPlayingOrWillChangePlaymode; + AddFileAction(menu, "新建战斗", () => Try(NewScenario), editable); + AddFileAction(menu, "打开预设…", OpenAssetPicker, editable); + if (_session.Data != null && editable) + menu.AddItem(new GUIContent("创建随机战斗"), false, () => Try(CreateRandomExample)); + else + menu.AddDisabledItem(new GUIContent("创建随机战斗")); + menu.AddSeparator(""); + AddFileAction(menu, "保存", () => Try(() => SaveScenario(false)), editable); + AddFileAction(menu, "另存为…", () => Try(() => SaveScenario(true)), editable); + menu.AddSeparator(""); + menu.AddItem(new GUIContent("导出配置与诊断…"), false, () => Try(ExportReport)); + menu.ShowAsContext(); + } + + private static void AddFileAction(GenericMenu menu, string label, GenericMenu.MenuFunction action, bool enabled) + { + if (enabled) + menu.AddItem(new GUIContent(label), false, action); + else + menu.AddDisabledItem(new GUIContent(label)); + } + + private void OpenAssetPicker() + { + _showAssetPicker(_asset, _assetPickerId); + } + + private void HandleAssetPicker() + { + if (Event.current.commandName == "ObjectSelectorClosed" && EditorGUIUtility.GetObjectPickerControlID() == _assetPickerId) + { + var asset = EditorGUIUtility.GetObjectPickerObject() as BattleScenarioAsset; + if (asset != null) + Try(() => LoadAsset(asset)); + Event.current.Use(); + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWorkbench.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWorkbench.cs.meta new file mode 100644 index 00000000..bc9cba7b --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleEditorWorkbench.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1f7c7960157d4bde852d6597a6363ca7 diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioAsset.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioAsset.cs new file mode 100644 index 00000000..d6f8fa02 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioAsset.cs @@ -0,0 +1,22 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using Battle; + using UnityEngine; + + [CreateAssetMenu(menuName = BattleData.Variant + "/Battle scenario", fileName = "BattleScenario")] + public sealed class BattleScenarioAsset : ScriptableObject, ISerializationCallbackReceiver + { + [NonSerialized] public BattleScenario Scenario = new() { Variant = BattleData.Variant }; + [SerializeField, HideInInspector] private string _scenarioJson = ""; + + public void OnBeforeSerialize() => _scenarioJson = Scenario == null ? "" : BattleScenarioJson.Serialize(Scenario); + + public void OnAfterDeserialize() => Scenario = string.IsNullOrEmpty(_scenarioJson) ? new BattleScenario { Variant = BattleData.Variant } : BattleScenarioJson.Deserialize(_scenarioJson); + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioAsset.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioAsset.cs.meta new file mode 100644 index 00000000..7db1f2d4 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioAsset.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 777cc6aa6f58e42999315727852ab67a \ No newline at end of file diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioEditing.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioEditing.cs new file mode 100644 index 00000000..ac2dc8b4 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioEditing.cs @@ -0,0 +1,60 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Linq; + using Battle; + + // Invalid imports remain inspectable; restoring the required authoring graph + // is explicit and undoable, rather than silently changing data while drawing. + public static class BattleScenarioEditing + { + public static bool NeedsRepair(BattleScenario scenario) => scenario == null || + scenario.Participants == null || scenario.Items == null || scenario.TreasureUses == null || + scenario.Camera == null || scenario.Pal3A?.SpiritWheel?.Charges is not { Length: 5 } || + scenario.Participants.Any(actor => actor == null || actor.Skills == null || actor.Statuses == null || + actor.Attributes is not { Length: 12 } || actor.Vitals is not { Length: 3 } || actor.Equipment is not { Length: 6 } || + actor.Skills.Any(skill => skill == null) || actor.Statuses.Any(state => state == null)) || + scenario.Items.Any(item => item == null) || scenario.TreasureUses.Any(item => item == null); + + public static BattleScenario Repair(BattleScenario scenario) + { + scenario ??= new BattleScenario(); + scenario.Camera ??= new BattleCamera(); + scenario.Pal3A ??= new BattlePal3AState(); + scenario.Pal3A.SpiritWheel ??= new BattleSpiritWheel(); + scenario.Pal3A.SpiritWheel.Charges = Resize(scenario.Pal3A.SpiritWheel.Charges, 5); + scenario.Participants ??= new(); + scenario.Items ??= new(); + scenario.TreasureUses ??= new(); + scenario.Participants.RemoveAll(actor => actor == null); + scenario.Items.RemoveAll(item => item == null); + scenario.TreasureUses.RemoveAll(item => item == null); + foreach (BattleParticipant actor in scenario.Participants) + { + actor.Skills ??= new(); + actor.Statuses ??= new(); + actor.Skills.RemoveAll(skill => skill == null); + actor.Statuses.RemoveAll(state => state == null); + actor.Attributes = Resize(actor.Attributes, 12); + actor.Vitals = Resize(actor.Vitals, 3); + actor.Equipment = Resize(actor.Equipment, 6); + } + return scenario; + } + + private static int[] Resize(int[] values, int length) + { + if (values?.Length == length) + return values; + var repaired = new int[length]; + if (values != null) + Array.Copy(values, repaired, Math.Min(values.Length, length)); + return repaired; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioEditing.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioEditing.cs.meta new file mode 100644 index 00000000..2bf5b31e --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioEditing.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4bef801fb57244918610e0fe626aa58b diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioJson.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioJson.cs new file mode 100644 index 00000000..6219c453 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioJson.cs @@ -0,0 +1,68 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using Battle; + using Newtonsoft.Json; + using Newtonsoft.Json.Linq; + + // Unity's inline class serialization turns absent optional snapshots into + // new objects. Keep the engine-independent authoring contract as JSON so + // null sword state survives assets, Undo, domain reload and reports. + public static class BattleScenarioJson + { + private static readonly JsonSerializerSettings Settings = new() + { + ObjectCreationHandling = ObjectCreationHandling.Replace, + TypeNameHandling = TypeNameHandling.None + }; + + private const string FormatProperty = "$battleScenarioFormat"; + + public static string Serialize(BattleScenario scenario) + { + if (scenario == null) + return "null"; + JObject document = JObject.FromObject(scenario, JsonSerializer.Create(Settings)); + document.AddFirst(new JProperty(FormatProperty, 1)); + return document.ToString(Formatting.None); + } + + public static BattleScenario Deserialize(string json) => Decode(JObject.Parse(json)); + + private static BattleScenario Decode(JObject document) + { + BattleScenario scenario = document.ToObject(JsonSerializer.Create(Settings)); + if (document.GetValue(nameof(BattleScenario.Participants), StringComparison.OrdinalIgnoreCase) is JArray participants) + for (int index = 0; index < participants.Count; index++) + if (participants[index] is JObject actor && + actor.GetValue(nameof(BattleParticipant.InstanceId), StringComparison.OrdinalIgnoreCase) == null) + scenario.Participants[index].InstanceId = null; + return scenario; + } + + // Only the old window codec needs repair. New authored invalid values + // remain visible to validation instead of being silently normalized. + public static BattleScenario RestoreDraft(string json) + { + JObject document = JObject.Parse(json); + BattleScenario scenario = Decode(document); + bool canonical = document[FormatProperty] != null || + document.SelectToken("Camera.Position.IsFinite") != null; + if (!canonical && document["Participants"] is JArray participants) + foreach (JToken participant in participants) + canonical |= participant.SelectToken("Position.IsFinite") != null; + if (!canonical && scenario.Participants != null) + foreach (BattleParticipant actor in scenario.Participants) + if (actor != null && (scenario.Variant != "PAL3" || actor.Equipment is not { Length: > 0 } || + actor.Equipment[0] != BattleMagicSwordRules.WeaponId || + actor.UsesNativeDefaultWeapon && BattleLoadoutRules.PlayerIdentity("PAL3", actor.ActorId) != 0)) + actor.MagicSword = null; + return scenario; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioJson.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioJson.cs.meta new file mode 100644 index 00000000..66b7076f --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioJson.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7c2bfeb6071b4932b01f957aed0180f1 diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioTypedFields.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioTypedFields.cs new file mode 100644 index 00000000..f35de21e --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioTypedFields.cs @@ -0,0 +1,214 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.Reflection; + using Battle; + using UnityEditor; + using UnityEngine; + + // The authoring DTO stays outside Unity's inline serializer. Every write + // goes through the window's transaction, including boxed struct writeback. + public static class BattleScenarioTypedFields + { + private static readonly Dictionary Expanded = new(); + private static readonly Dictionary Fields = new(); + + public static void Field(object owner, string fieldName, string label, Action edit, GUIStyle buttonStyle = null) + { + if (owner == null || edit == null) + throw new ArgumentNullException(owner == null ? nameof(owner) : nameof(edit)); + FieldInfo field = owner.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.Public) + ?? throw new ArgumentException("Unknown authoring field: " + fieldName, nameof(fieldName)); + if (field.IsInitOnly) + throw new ArgumentException("The authoring field is read-only.", nameof(fieldName)); + string identity = owner is BattleParticipant actor ? actor.InstanceId : owner.GetType().FullName; + Draw(field.FieldType, field.GetValue(owner), value => field.SetValue(owner, value), label, + identity + "." + fieldName, edit, new List(), 0, buttonStyle); + } + + private static void Draw(Type type, object value, Action assign, string label, string path, + Action edit, List ancestors, int depth, GUIStyle buttonStyle) + { + if (type == typeof(string)) + { + EditorGUI.BeginChangeCheck(); + string next = EditorGUILayout.TextField(label, (string)value ?? ""); + if (EditorGUI.EndChangeCheck()) + edit(label, () => assign(next)); + return; + } + if (type.IsEnum) + { + EditorGUI.BeginChangeCheck(); + Enum next = EditorGUILayout.EnumPopup(label, (Enum)value); + if (EditorGUI.EndChangeCheck()) + edit(label, () => assign(next)); + return; + } + if (type.IsPrimitive || type == typeof(decimal)) + { + DrawScalar(type, value, assign, label, edit); + return; + } + if (value == null) + { + using var row = new EditorGUILayout.HorizontalScope(); + EditorGUILayout.LabelField(label, "未配置", GUILayout.Height(buttonStyle?.fixedHeight ?? EditorGUIUtility.singleLineHeight)); + if (GUILayout.Button("创建", buttonStyle ?? GUI.skin.button, GUILayout.Width(48))) + edit(label, () => assign(Create(type))); + return; + } + if (depth >= 12 || !type.IsValueType && ancestors.Exists(parent => ReferenceEquals(parent, value))) + { + EditorGUILayout.LabelField(label, type.Name); + return; + } + using (new EditorGUILayout.HorizontalScope()) + { + bool expanded = !Expanded.TryGetValue(path, out bool stored) || stored; + Rect header = EditorGUILayout.GetControlRect(false, buttonStyle?.fixedHeight ?? EditorGUIUtility.singleLineHeight); + Expanded[path] = EditorGUI.Foldout(header, expanded, label, true); + bool optional = type == typeof(BattleMagicSword); + string action = value is IList ? "清空" : optional ? "移除" : "重置"; + if (!type.IsValueType && GUILayout.Button(action, buttonStyle ?? GUI.skin.button, GUILayout.Width(48))) + { + edit(label, () => + { + if (value is Array array) + { + var cleared = (Array)array.Clone(); + Array.Clear(cleared, 0, cleared.Length); + assign(cleared); + } + else if (value is IList list) + { + list.Clear(); + assign(list); + } + else + assign(optional ? null : Create(type)); + }); + return; + } + if (!Expanded[path]) + return; + } + ancestors.Add(value); + int previousIndent = EditorGUI.indentLevel; + EditorGUI.indentLevel++; + try + { + if (value is IList list) + DrawList(type, list, assign, label, path, edit, ancestors, depth, buttonStyle); + else + { + if (!Fields.TryGetValue(type, out FieldInfo[] fields)) + Fields[type] = fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public); + foreach (FieldInfo field in fields) + { + if (field.IsInitOnly || field.IsLiteral || field.IsNotSerialized) + continue; + Draw(field.FieldType, field.GetValue(value), replacement => + { + field.SetValue(value, replacement); + assign(value); + }, ObjectNames.NicifyVariableName(field.Name), path + "." + field.Name, edit, ancestors, depth + 1, buttonStyle); + } + } + } + finally + { + EditorGUI.indentLevel = previousIndent; + ancestors.RemoveAt(ancestors.Count - 1); + } + } + + private static void DrawList(Type type, IList list, Action assign, string label, string path, + Action edit, List ancestors, int depth, GUIStyle buttonStyle) + { + Type element = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0]; + int count = list.Count; + for (int index = 0; index < count; index++) + { + int slot = index; + using var row = new EditorGUILayout.VerticalScope(EditorStyles.helpBox); + Draw(element, list[slot], value => + { + list[slot] = value; + assign(list); + }, "元素 " + slot, path + "[" + slot + "]", edit, ancestors, depth + 1, buttonStyle); + if (!type.IsArray && GUILayout.Button("删除元素", buttonStyle ?? GUI.skin.button, GUILayout.Width(80))) + { + edit(label, () => + { + list.RemoveAt(slot); + assign(list); + }); + return; + } + } + if (!type.IsArray && GUILayout.Button("添加元素", buttonStyle ?? GUI.skin.button)) + edit(label, () => + { + list.Add(Create(element)); + assign(list); + }); + } + + private static object Create(Type type) => type == typeof(string) ? "" : + type.IsArray ? Array.CreateInstance(type.GetElementType(), 0) : Activator.CreateInstance(type); + + private static void DrawScalar(Type type, object value, Action assign, string label, Action edit) + { + EditorGUI.BeginChangeCheck(); + object next; + if (type == typeof(bool)) + next = EditorGUILayout.Toggle(label, (bool)value); + else if (type == typeof(float)) + next = EditorGUILayout.FloatField(label, (float)value); + else if (type == typeof(double)) + next = EditorGUILayout.DoubleField(label, (double)value); + else if (type == typeof(decimal)) + { + string text = EditorGUILayout.TextField(label, ((decimal)value).ToString(CultureInfo.InvariantCulture)); + next = decimal.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal number) ? number : value; + } + else if (type == typeof(ulong)) + { + string text = EditorGUILayout.TextField(label, value.ToString()); + next = ulong.TryParse(text, out ulong number) ? number : value; + } + else if (type == typeof(char)) + { + string text = EditorGUILayout.TextField(label, value.ToString()); + next = text.Length == 0 ? '\0' : text[0]; + } + else + { + long number = EditorGUILayout.LongField(label, Convert.ToInt64(value)); + next = IntegerValue(type, number); + } + if (EditorGUI.EndChangeCheck() && !Equals(next, value)) + edit(label, () => assign(next)); + } + + private static object IntegerValue(Type type, long number) + { + (long minimum, long maximum) = type == typeof(byte) ? (byte.MinValue, byte.MaxValue) : + type == typeof(sbyte) ? (sbyte.MinValue, sbyte.MaxValue) : + type == typeof(short) ? (short.MinValue, short.MaxValue) : + type == typeof(ushort) ? (ushort.MinValue, ushort.MaxValue) : + type == typeof(uint) ? (uint.MinValue, uint.MaxValue) : + type == typeof(int) ? (int.MinValue, int.MaxValue) : (long.MinValue, long.MaxValue); + return Convert.ChangeType(Math.Clamp(number, minimum, maximum), type, CultureInfo.InvariantCulture); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioTypedFields.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioTypedFields.cs.meta new file mode 100644 index 00000000..3984f5c2 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleScenarioTypedFields.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a1830535980b498e9d14bffa78ccd877 diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleSimulationGUI.cs b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleSimulationGUI.cs new file mode 100644 index 00000000..f0dbf496 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleSimulationGUI.cs @@ -0,0 +1,297 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattleEditorWindow + { + private BattleAction _battleAction; + private int _battleAbility; + private string _commandActor; + private string _protectionController, _protectionSelection; + + private void StartBattle() + { + _session.StartBattle(Scenario, _autoAllies, _autoEnemies); + _previewJson = BattleScenarioJson.Serialize(Scenario); + _commandActor = null; + Log("战斗已创建;技能、物品、装备、状态与局内成长使用已校验的原版规则。未覆盖语义会明确拒绝,完整边界见诊断。使用顶部主操作播放,或在诊断中单步。"); + } + + private void DrawBattleBody() + { + BattleSession combat = _session.Battle; + var participants = combat.Actors.ToDictionary(actor => actor.Id, actor => combat.CaptureParticipant(actor.Id)); + string Label(string id) => id != null && participants.TryGetValue(id, out BattleParticipant actor) ? ActorLabel(actor) : id; + GUILayout.Label($"战场 {combat.ActiveScene} · Boss 回合 {combat.BossRounds}", EditorStyles.wordWrappedMiniLabel); + if (combat.Definitions.Variant == "PAL3A" && combat.FiveSpiritElement != 0) + GUILayout.Label($"五灵法阵:{(Core.Contract.Enums.ElementType)combat.FiveSpiritElement} · {(combat.FiveSpiritForce == 1 ? "我方" : "敌方")}", EditorStyles.wordWrappedMiniLabel); + if (combat.Definitions.Variant == "PAL3A") + GUILayout.Label("五灵轮(水/火/风/雷/土):" + string.Join("/", combat.Pal3AState.SpiritWheel.Charges) + + $" · 炎兽 {combat.Pal3AState.SpiritWheel.NangongRounds} 回合 · 累计精请求 {combat.Pal3AState.HpLoss} · 神请求 {combat.Pal3AState.MpLoss}", EditorStyles.wordWrappedMiniLabel); + GUILayout.Label($"本局金钱 {combat.Money} · 物品 {string.Join("、", combat.Inventory.Select(item => $"{AbilityName(combat, item.Id, true)} ×{item.Count}"))}", EditorStyles.wordWrappedMiniLabel); + EditorGUILayout.HelpBox("原版 AI 使用同一套技能、物品、资源和状态规则;可逐角色配置,或手动下令后重放记录。", MessageType.Info); + using (new EditorGUILayout.HorizontalScope()) + { + using (new EditorGUI.DisabledScope(combat.Status != BattleSessionStatus.Running)) + { + foreach (BattleSide side in Enum.GetValues(typeof(BattleSide))) + { + bool before = combat.IsAutomatic(side); + bool automatic; + using (new EditorGUI.DisabledScope(combat.ActiveFormationController != null)) + automatic = GUILayout.Toggle(before, (side == BattleSide.Ally ? "我方" : "敌方") + "自动"); + if (before != automatic) + combat.SetAutomatic(side, automatic); + } + } + } + using (new EditorGUILayout.HorizontalScope()) + { + using (new EditorGUI.DisabledScope(combat.Status != BattleSessionStatus.Running)) + { + if (DrawerButton("下一命中")) + Try(() => _session.AdvanceTo(BattleEventKind.Hit)); + if (DrawerButton("下一行动结束")) + Try(() => _session.AdvanceTo(BattleEventKind.ActionEnded)); + if (DrawerButton("中止战斗")) + { + combat.Abort(); + _session.SyncBattle(); + } + } + if (DrawerButton("重放记录")) + Try(_session.BeginReplay, pauseOnError: false); + } + if (combat.Result != null) + { + if (_session.ResultPresentation is { } presentation) + { + using (new EditorGUILayout.HorizontalScope()) + { + using (new EditorGUI.DisabledScope(!presentation.CanSkip)) + if (DrawerButton("跳过当前提示")) + _session.SkipResultStep(); + if (DrawerButton("重播结果演出")) + Try(_session.ReplayResults, pauseOnError: false); + } + } + DrawBattleResult(combat.Result, Label); + } + else if (combat.ActiveFormationController is { } controller) + DrawFormationControl(combat, controller, Label); + else if (combat.WaitingActor is { } waiting) + DrawBattleCommand(combat, waiting, Label); + if (combat.FleeResult is { } fleeResult) + EditorGUILayout.HelpBox(fleeResult.Success ? "逃跑成功" : "逃跑失败", MessageType.Info); + foreach (BattleActorSnapshot actor in combat.Actors) + { + Rect row = EditorGUILayout.GetControlRect(false, 20); + EditorGUI.ProgressBar(row, actor.Gauge / (float)BattleSession.FullGauge, + $"{Label(actor.Id)} · 精 {actor.Hp}/{actor.MaxHp} · 气 {actor.Sp}/{actor.MaxSp} · 神 {actor.Mp}/{actor.MaxMp} · {actor.Pose}{(actor.Ready ? " · 就绪" : "")}"); + if (Event.current.type == EventType.MouseDown && row.Contains(Event.current.mousePosition)) + { + _selected = actor.Id; + Event.current.Use(); + } + if (actor.Pose is BattlePose.Casting or BattlePose.Fleeing) + { + Rect cast = EditorGUILayout.GetControlRect(false, 16); + string action = actor.Pose == BattlePose.Fleeing ? "逃跑等待" : AbilityName(combat, actor.AbilityId, false); + EditorGUI.ProgressBar(cast, actor.CastGauge / (float)BattleSession.FullCastGauge, $"第二槽 {actor.CastGauge}/{BattleSession.FullCastGauge} · {action}"); + } + } + if (combat.Actors.FirstOrDefault(actor => actor.Id == _selected) is { } selected) + { + GUILayout.Label($"{Label(selected.Id)} · 等级 {selected.Level} · 经验 {selected.Experience} · 回合 {selected.Rounds} · 好感 {selected.Love}", EditorStyles.boldLabel); + GUILayout.Label("当前属性:" + string.Join(" · ", selected.Attributes.Select((value, index) => $"{AttributeLabels[index]} {value}")), EditorStyles.wordWrappedMiniLabel); + GUILayout.Label("状态:" + (selected.States.Count == 0 ? "无" : string.Join("、", selected.States.Select(state => $"{state.State}({(state.Permanent ? "永久" : $"{state.RemainingRounds}回合")}{(state.LatentRounds > 0 ? $",潜伏{state.LatentRounds}" : "")})"))), EditorStyles.wordWrappedMiniLabel); + if (selected.MagicSword is { } sword) + GUILayout.Label($"魔剑:{AbilityName(combat, sword.SkillId, false)} · 能量 {sword.Energy:F2}/200 · 净化 {sword.PurificationCount} 次", EditorStyles.wordWrappedMiniLabel); + GUILayout.Label("技能熟练:" + string.Join("、", selected.Skills.Select(skill => $"{AbilityName(combat, skill.Id, false)} Lv{skill.Level} · {skill.Uses}次{(skill.Mastered ? " · 掌握" : "")}")), EditorStyles.wordWrappedMiniLabel); + DrawAiControls(combat, selected); + if (selected.ActionId != 0 && DrawerButton("取消所选角色行动(调试,保留已消耗资源)")) + Try(() => + { + combat.CancelAction(selected.Id); + _session.SyncBattle(); + }); + } + } + + private void DrawFormationControl(BattleSession combat, string controller, Func label) + { + GUILayout.Label("阵法 · " + label(controller), EditorStyles.boldLabel); + GUILayout.Label("可连续调整阵位;确认时只清操作者的第一槽。最终还原原阵型不耗条。", EditorStyles.wordWrappedMiniLabel); + foreach (BattleActorSnapshot actor in combat.Actors.Where(actor => actor.Side == BattleSide.Ally)) + { + string denied = combat.CanSwapFormation(actor.Id, actor.Slot); + using (new EditorGUI.DisabledScope(denied != null)) + { + BattleSlot next = (BattleSlot)EditorGUILayout.EnumPopup(label(actor.Id), actor.Slot); + if (next != actor.Slot) + Try(() => + { + string reason = combat.CanSwapFormation(actor.Id, next); + if (reason != null) + throw new InvalidOperationException(reason); + combat.SwapFormation(actor.Id, next); + _session.SyncBattle(); + }); + } + if (denied != null) + GUILayout.Label(denied, EditorStyles.wordWrappedMiniLabel); + } + if (DrawerButton("确认阵型")) + Try(() => + { + combat.EndFormation(controller); + _session.SyncBattle(); + }); + } + + private bool DrawProtectionControl(BattleSession combat, string controller, Func label) + { + if (combat.CanSetProtection(controller, null) != null) + return false; + string[] targets = new[] { (string)null }.Concat(combat.Actors.Where(actor => actor.Side == BattleSide.Ally && + combat.CanSetProtection(controller, actor.Id) == null).Select(actor => actor.Id)).ToArray(); + if (_protectionController != controller) + { + _protectionController = controller; + _protectionSelection = combat.ProtectionTarget; + } + using (new EditorGUILayout.HorizontalScope()) + { + int selected = Math.Max(0, Array.IndexOf(targets, _protectionSelection)); + selected = EditorGUILayout.Popup("援护对象", selected, targets.Select(id => id == null ? "不援护" : label(id)).ToArray(), GUILayout.Height(BattleEditorTheme.ControlHeight)); + _protectionSelection = targets[selected]; + using var disabled = new EditorGUI.DisabledScope(_protectionSelection == combat.ProtectionTarget); + if (DrawerButton("确认援护", GUILayout.Width(90))) + { + bool changed = combat.SetProtection(controller, _protectionSelection); + _session.SyncBattle(); + return changed; + } + } + return false; + } + + private void DrawBattleCommand(BattleSession combat, string waiting, Func label) + { + BattleActorSnapshot actor = combat.Actors.First(candidate => candidate.Id == waiting); + if (_commandActor != waiting) + { + _commandActor = waiting; + _battleAction = BattleAction.Attack; + _battleAbility = 0; + } + GUILayout.Label("等待 " + label(waiting), EditorStyles.boldLabel); + if (actor.Side == BattleSide.Ally) + { + string lineupReason = combat.CanBeginFormation(waiting); + using (new EditorGUI.DisabledScope(lineupReason != null)) + if (DrawerButton("阵法换位")) + Try(() => combat.BeginFormation(waiting)); + if (lineupReason != null) + GUILayout.Label(lineupReason, EditorStyles.wordWrappedMiniLabel); + if (DrawProtectionControl(combat, waiting, label)) + return; + } + _battleAction = (BattleAction)DrawerTabs("tabs:battle-action", (int)_battleAction, combat.Definitions.Variant == "PAL3A" ? new[] { "普攻", "防御", "技能", "物品", "逃跑", "炎兽变身" } : new[] { "普攻", "防御", "技能", "物品", "逃跑" }); + BattleAbilityDefinition ability = null; + if (_battleAction is BattleAction.Skill or BattleAction.Item) + { + bool item = _battleAction == BattleAction.Item; + IReadOnlyDictionary definitions = item ? combat.Definitions.Items : combat.Definitions.Skills; + int[] ids = (item ? combat.Inventory.Where(entry => entry.Count > 0).Select(entry => entry.Id) : actor.Skills.Select(skill => skill.Id) + .Concat(actor.MagicSword is { SkillId: > 0 } sword ? new[] { sword.SkillId } : Array.Empty())).Distinct().ToArray(); + int selected = Math.Max(0, Array.IndexOf(ids, _battleAbility)); + selected = EditorGUILayout.Popup(item ? "本局物品" : "已学技能", selected, ids.Select(id => + { + if (item) + return $"{AbilityName(combat, id, true)} ×{combat.Inventory.First(entry => entry.Id == id).Count}"; + if (actor.MagicSword?.SkillId == id) + return $"{AbilityName(combat, id, false)} · 魔剑 {actor.MagicSword.Energy:F2}/200"; + BattleSkillSnapshot skill = actor.Skills.First(entry => entry.Id == id); + return $"{AbilityName(combat, id, false)} · Lv{skill.Level} · {skill.Uses}次{(skill.Mastered ? " · 掌握" : "")}"; + }).ToArray()); + _battleAbility = ids.Length > 0 ? ids[selected] : 0; + if (definitions.TryGetValue(_battleAbility, out ability)) + GUILayout.Label($"范围:{ability.Range}{(ability.Revives ? " · 可选择死亡角色" : "")}", EditorStyles.wordWrappedMiniLabel); + else + GUILayout.Label(item ? "本局没有可用物品。" : "此角色未配置技能。", EditorStyles.wordWrappedMiniLabel); + } + int abilityId = _battleAction is BattleAction.Skill or BattleAction.Item ? _battleAbility : 0; + var query = new BattleCommand(waiting, _battleAction, abilityId: abilityId); + BattleActorSnapshot[] targets = combat.GetTargetCandidates(query).ToArray(); + if (targets.Length > 0) + { + int targetIndex = Math.Max(0, Array.FindIndex(targets, target => target.Id == _target)); + targetIndex = EditorGUILayout.Popup("合法目标/范围中心", targetIndex, targets.Select(target => label(target.Id) + (target.Alive ? "" : " · 死亡")).ToArray()); + _target = targets[targetIndex].Id; + } + else + _target = null; + var command = new BattleCommand(waiting, _battleAction, _target, abilityId); + string reason = combat.CanSubmit(command); + BattleCostEstimate[] costs = combat.GetCostEstimate(command).ToArray(); + if (costs.Length > 0) + GUILayout.Label("消耗预估:" + string.Join(" · ", costs.Select(cost => $"{ResourceName(cost.Resource)} 需求{cost.Required}/实付{cost.Payable}/持有{cost.Available}")), EditorStyles.wordWrappedMiniLabel); + if (_battleAction == BattleAction.Item && ability != null) + GUILayout.Label($"消耗预估:物品 1 件/持有 {combat.Inventory.FirstOrDefault(item => item.Id == ability.Id)?.Count ?? 0} 件", EditorStyles.wordWrappedMiniLabel); + if (reason != null) + EditorGUILayout.HelpBox(reason, MessageType.Warning); + using (new EditorGUI.DisabledScope(reason != null)) + if (DrawerButton("执行指令")) + Try(() => + { + combat.Submit(command); + _session.SyncBattle(); + }); + GUILayout.Label("输入选择与校验不会扣资源或消耗随机数;配置草稿的修改在下次开局生效。", EditorStyles.wordWrappedMiniLabel); + } + + private static string AbilityName(BattleSession combat, int id, bool item) + { + var definitions = item ? combat.Definitions.Items : combat.Definitions.Skills; + return definitions.TryGetValue(id, out BattleAbilityDefinition ability) ? $"{ability.Name} ({id})" : id.ToString(); + } + + private static string ResourceName(int resource) => resource switch + { + 0 => "精", + 1 => "气", + 2 => "神", + 10 => "金钱", + 16 => "蛊", + _ => $"资源{resource}" + }; + + private static void DrawBattleResult(BattleResult result, Func label) + { + GUILayout.Label($"{result.Status} · 胜方:{result.Winner?.ToString() ?? "无"} · {(result.Escaped ? "已逃跑 · " : "")}{result.Reason}", EditorStyles.boldLabel); + GUILayout.Label($"本局金钱 {result.MoneyBefore} → {result.MoneyAfter}", EditorStyles.wordWrappedMiniLabel); + if (result.Pal3A != null) + GUILayout.Label("五灵轮:" + string.Join("/", result.Pal3A.SpiritWheel.Charges) + $" · 累计精请求 {result.Pal3A.HpLoss} · 神请求 {result.Pal3A.MpLoss}", EditorStyles.wordWrappedMiniLabel); + foreach (BattleActorReward reward in result.Rewards ?? Array.Empty()) + { + GUILayout.Label($"{label(reward.Actor)}:经验 +{reward.ExperienceGained}({reward.ExperienceBefore} → {reward.ExperienceAfter}),等级 {reward.LevelBefore} → {reward.LevelAfter}", EditorStyles.wordWrappedMiniLabel); + if (reward.AttributesBefore != null && reward.AttributesAfter != null) + GUILayout.Label("属性成长:" + string.Join(" · ", reward.AttributesBefore.Select((before, index) => (before, after: reward.AttributesAfter[index], index)) + .Where(value => value.before != value.after).Select(value => $"{AttributeLabels[value.index]} {value.before} → {value.after}")), EditorStyles.wordWrappedMiniLabel); + } + GUILayout.Label("掉落:" + string.Join("、", (result.Loot ?? Array.Empty()).Select(item => $"{item.Id} ×{item.Count}")), EditorStyles.wordWrappedMiniLabel); + GUILayout.Label("结算只保留在本次独立战斗报告中。", EditorStyles.wordWrappedMiniLabel); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Authoring/BattleSimulationGUI.cs.meta b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleSimulationGUI.cs.meta new file mode 100644 index 00000000..94920089 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Authoring/BattleSimulationGUI.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d275724c54f441e3bdc76f46b61c8d49 diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog.meta b/Assets/Scripts/Editor/BattleEditor/Catalog.meta new file mode 100644 index 00000000..2f5b98ef --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 217fe13c1b454337aa7542f9228a5361 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAbilityCatalog.cs b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAbilityCatalog.cs new file mode 100644 index 00000000..32e7b5de --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAbilityCatalog.cs @@ -0,0 +1,243 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using Core.Contract.Enums; + using Core.DataReader.Dat; + using Engine.Extensions; + + public sealed partial class BattleAnimationCatalog : IBattleAbilityEffects, IBattleAbilityBodyAnimations, IBattleEffectActorAnimations + { + private readonly Dictionary<(string, int, bool), BattleAbilityStageProfile> _abilityStages = new(); + + public BattleAbilityStageProfile AbilityStage(string actor, BattleAbilityDefinition ability) + { + if (ability == null || !_participants.TryGetValue(actor, out BattleParticipant participant) || + !ability.IsItem && ability.SkillTypeId == 4) + throw new ArgumentException("An ordinary ability stage needs its captured actor and original ability."); + var key = (actor, ability.Id, ability.IsItem); + if (_abilityStages.TryGetValue(key, out BattleAbilityStageProfile captured)) + return captured; + if (!_linkers.SkillIdToEffectGroupMap.TryGetValue(ability.Id, out EffectGroupInfo[] groups) || groups.Length != 2) + throw new NotSupportedException($"Ability {ability.Id} has no original two-group effect linker."); + bool main = _actors[actor].Main; + BattleAbilityStageKind kind = ability.IsItem ? BattleAbilityStageKind.Item : ability.IsMagic || !main ? BattleAbilityStageKind.Magic : BattleAbilityStageKind.Skill; + bool npcItemIdle = BattleData.Variant == "PAL3A" && !main && ability.IsItem; + bool noBody = npcItemIdle || ability.IsTreasure || BattleData.Variant == "PAL3A" && kind == BattleAbilityStageKind.Skill && ability.Id is 4102 or 4103 or 4108 or 4507; + int bodyTicks = 0; + bool retainedBody = false; + if (!noBody) + { + if (_data.TryActionPath(participant, AbilityClip(participant, ability), out string path)) + { + BattleAnimationMetadata body = _data.GetAnimationMetadata(path); + bodyTicks = ToTicks(body.TotalGameBoxTicks / (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / ActivePlaybackRate); + } + else + retainedBody = true; + } + BattleMovementKind? approach = null, returning = null; + if (kind == BattleAbilityStageKind.Skill && main) + { +#if PAL3 + approach = ability.Id switch + { + 4101 or 4304 => BattleMovementKind.Teleport, + 4205 => BattleMovementKind.Fly, + 4505 => BattleMovementKind.Run, + _ => null + }; + returning = Priority(actor) switch + { + 1 or 3 => BattleMovementKind.Fly, + 2 => BattleMovementKind.Teleport, + _ => BattleMovementKind.Run + }; + +#else + approach = ability.Id switch + { + 4101 => BattleMovementKind.Teleport, + 4504 or 4505 => BattleMovementKind.Run, + 4506 => BattleMovementKind.Fly, + _ => null + }; + returning = Priority(actor) switch + { + 0 => ability.Id is 4101 or 4107 or 4108 ? BattleMovementKind.Run : null, + 4 => ability.Id is 4504 or 4505 or 4506 ? BattleMovementKind.Run : BattleMovementKind.Teleport, + _ => BattleMovementKind.Run + }; + +#endif + } + BattleAbilityWorkBoundary work = ability.IsTreasure ? BattleAbilityWorkBoundary.WorkTimeAndFirstGroupFinished : + kind == BattleAbilityStageKind.Skill && ability.Id == 4101 ? BattleAbilityWorkBoundary.WorkTimeAndBodyIdle : BattleAbilityWorkBoundary.WorkTime; + bool opposing = kind switch + { + BattleAbilityStageKind.Item => ability.ItemType == 2, + BattleAbilityStageKind.Magic => ability.SkillTypeId == 2, + _ => (int)ability.Range > 2 + }; + var profile = new BattleAbilityStageProfile(kind, CaptureAbilityBinding(groups[0]), CaptureAbilityBinding(groups[1]), + groups[0].WorkTimeInSeconds, work, bodyTicks, opposing, approach, returning, retainedBody, npcItemIdle); + _abilityStages.Add(key, profile); + return profile; + } + + private static BattleAbilityEffectBinding CaptureAbilityBinding(EffectGroupInfo group) => new(group.EffGroupId, group.WaitDurationInSeconds, + (group.IsCenteredAroundCaster ? 1 : 0) | (group.IsCenteredAroundReceiver ? 2 : 0) | (group.IsCasterActor ? 4 : 0) | (group.IsReceiverActor ? 8 : 0), + new BattleMovementPoint(group.EffectGameBoxPosition.X, group.EffectGameBoxPosition.Y, group.EffectGameBoxPosition.Z)); + + public IReadOnlyList AbilityMovement(BattleActorSnapshot source, BattleActorSnapshot target, + BattleAbilityDefinition ability, BattleDefinitions definitions, bool returning) + { + if (source == null || ability == null || definitions == null) + throw new ArgumentNullException(source == null ? nameof(source) : ability == null ? nameof(ability) : nameof(definitions)); + BattleAbilityStageProfile profile = AbilityStage(source.Id, ability); + BattleMovementKind kind = (returning ? profile.ReturnKind : profile.ApproachKind) ?? throw new InvalidOperationException("This original ability has no corresponding movement task."); + BattleMovementPoint destination = source.Home; + if (!returning) + { + if (target == null) + throw new InvalidOperationException("This original ability approaches one explicit target."); + float radius = AbilityRadius(source, definitions) + AbilityRadius(target, definitions); +#if PAL3A + BattlePhysicalStageProfile sourceProfile = Physical(source.Id); + int identity = sourceProfile.Identity; + int weapon = sourceProfile.WeaponType; + float extra = identity switch + { + 0 => 40, + 1 => 50, + 2 => 40, + 3 => 32, + _ => 0 + }; + bool extended = identity switch + { + 0 => weapon == 1, + 1 => weapon == 3, + 2 => weapon == 6, + 3 => weapon == 7, + _ => false + }; + if (extended) + radius += extra; + if (_participants[target.Id].ActorId == 706) + radius -= extra; + +#endif + if (_participants[source.Id].ActorId is 7364 or 7381) + radius *= 2; + float x = source.Position.X - target.Home.X, y = source.Position.Y - target.Home.Y, z = source.Position.Z - target.Home.Z; + double length = Math.Sqrt((double)x * x + (double)y * y + (double)z * z); + BattleMovementPoint normal = length < (double)0.005f ? new BattleMovementPoint(0, 1, 0) : + new BattleMovementPoint((float)(x / length), (float)(y / length), (float)(z / length)); + destination = new BattleMovementPoint(target.Home.X + normal.X * radius, target.Home.Y + normal.Y * radius, target.Home.Z + normal.Z * radius); + } + if (kind != BattleMovementKind.Fly) + return Array.AsReadOnly(new[] { new BattleMovementPlan(kind, source.Position, destination) }); + string moving = AbilityMovementAction(source.Id, ability, kind, returning); + BattleAnimationMetadata model = _data.GetAnimationMetadata(_data.ActionPath(_participants[source.Id], moving)); + int? Marker(BattlePhysicalMarkerKind markerKind) + { + var matches = model.AnimationEvents.Where(marker => PhysicalMarkerKind(marker.Name) == markerKind).ToArray(); + if (matches.Length > 1) + throw new NotSupportedException($"Animation {moving} has multiple {markerKind} markers."); + return matches.Length == 0 ? null : Math.Max(0, checked((int)Math.Ceiling(matches[0].GameBoxTick / + (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / ActivePlaybackRate / BattleSession.StepSeconds))); + } + int? up = Marker(BattlePhysicalMarkerKind.FlyUp); + if (!up.HasValue) + throw new NotSupportedException($"Animation {moving} has no takeoff marker."); + int? down = Marker(BattlePhysicalMarkerKind.FlyDown); + int over = Marker(BattlePhysicalMarkerKind.Over) ?? ToTicks(model.TotalGameBoxTicks / (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / ActivePlaybackRate); + return Array.AsReadOnly(new[] { new BattleMovementPlan(kind, source.Position, destination, up, down, over) }); + } + + private float AbilityRadius(BattleActorSnapshot actor, BattleDefinitions definitions) + { + int identity = PhysicalIdentity(_participants[actor.Id]); + float adjustment = identity == (BattleData.Variant == "PAL3" ? 1 : 3) ? 10f : 0f; + if (actor.NativeAnimationHalfDepth.HasValue) + return actor.NativeAnimationHalfDepth.Value - adjustment; + string clip = Clip(actor, definitions) ?? _data.IdleAction(_participants[actor.Id]); + BattleAnimationMetadata model = _data.GetAnimationMetadata(_data.ActionPath(_participants[actor.Id], clip)); + if (!model.HasBounds) + throw new InvalidOperationException("An original combat radius requires the current MV3 collision bounds."); + return (model.MaximumZ - model.MinimumZ) * 0.5f - adjustment; + } + + public string EffectActor(uint modelCrc) + { + var hash = new Core.DataReader.Cpk.Crc32Hash(); + hash.Init(); + return _participants.Values.OrderBy(actor => actor.Side == BattleSide.Enemy ? 5 + (int)actor.Slot : Priority(actor.InstanceId)) + .FirstOrDefault(actor => (hash.Compute(_data.Model(actor), _data.Resources.Codepage) == modelCrc || + hash.Compute(_data.Model(actor).ToLowerInvariant(), _data.Resources.Codepage) == modelCrc))?.InstanceId; + } + + public int? AbilityNativeAction(string actor, BattleAbilityDefinition ability) + { + if (ability.SkillTypeId == 4) + return 40; + BattleAbilityStageProfile profile = AbilityStage(actor, ability); + if (profile.NpcItemIdle) + return null; + if (!profile.RetainsBody && profile.BodyAnimationTicks == 0) + return null; + bool main = _actors[actor].Main; + if (!main && !ability.IsItem) + { + uint[] skills = _data.Database.CombatActorInfos[_participants[actor].ActorId].SkillIds; + return skills.Length > 1 && skills[1] == ability.Id ? 56 : skills.Length > 2 && skills[2] == ability.Id ? 57 : 55; + } + if (ability.IsItem) + return AbilityClip(_participants[actor], ability) == ActorConstants.ActionToNameMap[ActorActionType.UseItemRecover] ? 38 : 39; + if (ability.IsMagic) + return 35; + return ability.Id == (BattleData.Variant == "PAL3" ? 4101 : 4106) ? 37 : 36; + } + + public BattlePhysicalAnimation AbilityBody(string actor, BattleAbilityDefinition ability) + { + if (ability.SkillTypeId == 4) + return CompilePhysicalAnimation(_participants[actor], ActorConstants.ActionToNameMap[ActorActionType.WeaponSkill]); + BattleAbilityStageProfile profile = AbilityStage(actor, ability); + if (profile.NpcItemIdle) + { + string idle = ActorConstants.ActionToNameMap[ActorActionType.PreAttack]; + return _data.TryActionPath(_participants[actor], idle, out _) ? CompilePhysicalAnimation(_participants[actor], idle) : null; + } + if (!profile.RetainsBody && profile.BodyAnimationTicks == 0) + return null; + string clip = AbilityClip(_participants[actor], ability); + return _data.TryActionPath(_participants[actor], clip, out _) ? CompilePhysicalAnimation(_participants[actor], clip) : null; + } + + public BattlePhysicalAnimation AbilityMovementBody(string actor, BattleAbilityDefinition ability, BattleMovementKind kind, bool returning) + { + string clip = AbilityMovementAction(actor, ability, kind, returning); + return CompilePhysicalAnimation(_participants[actor], clip); + } + + private string AbilityMovementAction(string actor, BattleAbilityDefinition ability, BattleMovementKind kind, bool returning) => + kind == BattleMovementKind.Teleport ? _data.IdleAction(_participants[actor]) : + BattleData.Variant == "PAL3A" && !returning && ability.Id == 4506 ? "z22" : _actors[actor].Clips[BattlePose.Moving]; + + public BattlePhysicalAnimation ExternalBody(BattleActorSnapshot actor, string requested, BattleDefinitions definitions) => + _data.TryActionPath(_participants[actor.Id], requested, out _) ? CompilePhysicalAnimation(_participants[actor.Id], requested) : null; + + public string AbilityMovementClip(BattleActorSnapshot actor) => + BattleData.Variant == "PAL3A" && actor.AbilityId == 4506 && actor.Movement?.Plan.Kind == BattleMovementKind.Fly ? "z22" : null; + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAbilityCatalog.cs.meta b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAbilityCatalog.cs.meta new file mode 100644 index 00000000..96ebe2e3 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAbilityCatalog.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 74019725c6f145d292bfbef0889c26c8 diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.Results.cs b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.Results.cs new file mode 100644 index 00000000..d22d8c3e --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.Results.cs @@ -0,0 +1,36 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System.Collections.Generic; + using System.Collections.ObjectModel; + using Battle; + using Core.Contract.Constants; + using Core.Contract.Enums; + + public sealed partial class BattleAnimationCatalog + { + public IReadOnlyDictionary ResultBodyAnimations(BattleParticipant participant) + { + var result = new Dictionary + { + [32] = CompilePhysicalAnimation(participant, _data.IdleAction(participant)), + [42] = CompilePhysicalAnimation(participant, ActorConstants.ActionToNameMap[ActorActionType.Defence]), + [45] = CompilePhysicalAnimation(participant, ActorConstants.ActionToNameMap[ActorActionType.Freeze]), + [46] = CompilePhysicalAnimation(participant, ActorConstants.ActionToNameMap[ActorActionType.Dying]), + [47] = CompilePhysicalAnimation(participant, ActorConstants.ActionToNameMap[ActorActionType.Dead]), + [49] = CompilePhysicalAnimation(participant, ActorConstants.ActionToNameMap[ActorActionType.Win]) + }; +#if PAL3A + int identity = PhysicalIdentity(participant); + int weapon = participant.Equipment.Length > 0 && participant.Equipment[0] != 0 ? (int)_data.Database.GameItemInfos[participant.Equipment[0]].WeaponType : 0; + bool alternateLevelUp = identity == 1 && weapon == 3 || identity == 4 && weapon == 8; + result[59] = CompilePhysicalAnimation(participant, alternateLevelUp ? "z162" : ActorConstants.ActionToNameMap[ActorActionType.LevelUp]); +#endif + return new ReadOnlyDictionary(result); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.Results.cs.meta b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.Results.cs.meta new file mode 100644 index 00000000..3d68fab5 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.Results.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f8119d208c5946d19ad62aa3e8073177 diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.cs b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.cs new file mode 100644 index 00000000..38b61f51 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.cs @@ -0,0 +1,364 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using Core.Contract.Enums; + using Core.DataReader.Dat; + using Engine.Extensions; + using UnityEngine; + + // Compiles resource metadata once. It owns no scene objects and never observes the mutable editor draft. + public sealed partial class BattleAnimationCatalog : IBattleCatalog, IBattleAbilityTimings, IBattleStageGeometry, IBattleMagicSwordTimings, IBattleDodgeTimings + { +#if PAL3 + private const double ActivePlaybackRate = 1.3f; +#else + private const double ActivePlaybackRate = 1.0; +#endif + + private sealed class ActorDefinition + { + public bool Main; + public int Priority, Sp, Divisor = 1; + public Vector3 Home; + public readonly Dictionary Clips = new(); + public Dictionary Durations = new(); + } + + private readonly Dictionary _actors = new(StringComparer.Ordinal); + private readonly Dictionary<(string Source, string Target), BattleAttackPlan> _initialAttacks = new(); + private readonly Dictionary<(string, int, bool), (string Clip, AttackTiming Timing)> _abilities = new(); + private readonly Dictionary _participants; + private readonly BattleData _data; + private readonly int _sceneElement; + private readonly EffectLinkerFile _linkers; + + public List Diagnostics { get; } = new(); + + public BattleAnimationCatalog(BattleData data, BattleSetup setup, BattleDefinitions definitions = null) + : this(data, setup, definitions, data.Read("basedata.cpk\\cbdata\\efflinker.dat", new EffectLinkerFileReader())) + { + } + + private BattleAnimationCatalog(BattleData data, BattleSetup setup, BattleDefinitions definitions, EffectLinkerFile linkers) + { + _data = data; + _linkers = linkers; + BattleScenario scenario = setup.CreateInstance(); + _sceneElement = scenario.SceneElement; + _participants = scenario.Participants.ToDictionary(actor => actor.InstanceId, StringComparer.Ordinal); + foreach (BattleParticipant actor in scenario.Participants) + { + var info = data.Database.CombatActorInfos[actor.ActorId]; + bool main = info.Type == CombatActorType.MainActor; + if (data.CombatRosterDenial(actor.ActorId, actor.Side) is string rosterDenial) + throw new NotSupportedException(rosterDenial); + int divisor = 1; + if (main && (actor.Equipment.Length == 0 || actor.Equipment[0] == 0)) + throw new NotSupportedException($"Actor {actor.ActorId}: choose a compatible basic weapon before starting combat."); + if (main && actor.Equipment.Length > 0 && actor.Equipment[0] != 0) + { + var weapon = data.Database.GameItemInfos[actor.Equipment[0]]; + PlayerActorId identity = (PlayerActorId)PhysicalIdentity(actor); + if (weapon.Type != ItemType.Weapon || !BattleLoadoutRules.IsNativeDefaultWeapon(BattleData.Variant, actor) && !weapon.ApplicableActors.Contains(identity)) + throw new ArgumentException($"Actor {actor.ActorId}: slot 0 must contain a compatible weapon."); + divisor = Math.Max(1, weapon.AttackHitCount); + } + var definition = new ActorDefinition + { + Main = main, + Home = data.Position(actor, _sceneElement), + Sp = Math.Max(0, info.SpImpactValue), + Divisor = divisor, + Priority = main ? PhysicalIdentity(actor) : (int)actor.Slot + }; + _actors.Add(actor.InstanceId, definition); + AddClip(BattlePose.Idle, data.IdleAction(actor)); + AddClip(BattlePose.Attacking, data.AttackAction(actor)); + AddClip(BattlePose.Moving, ActorConstants.ActionToNameMap[main ? ActorActionType.AttackMove : ActorActionType.NpcWalk]); + AddClip(BattlePose.Hurt, ActorConstants.ActionToNameMap[main ? ActorActionType.BeAttack : ActorActionType.NpcBeAttacked]); + if (main) + { + AddClip(BattlePose.Dodging, ActorConstants.ActionToNameMap[ActorActionType.Dodge]); + AddClip(BattlePose.GuardEntry, ActorConstants.ActionToNameMap[ActorActionType.StartDefence]); + AddClip(BattlePose.Guard, ActorConstants.ActionToNameMap[ActorActionType.Defence]); + AddClip(BattlePose.Dead, ActorConstants.ActionToNameMap[ActorActionType.Dead]); + AddClip(BattlePose.Fleeing, ActorConstants.ActionToNameMap[ActorActionType.Flee]); + } + else + { + definition.Clips[BattlePose.Dodging] = definition.Clips[BattlePose.Idle]; + definition.Durations[BattlePose.Dodging] = definition.Durations[BattlePose.Idle]; + definition.Clips[BattlePose.GuardEntry] = definition.Clips[BattlePose.Idle]; + definition.Durations[BattlePose.GuardEntry] = 1; + definition.Clips[BattlePose.Guard] = definition.Clips[BattlePose.Idle]; + definition.Durations[BattlePose.Guard] = definition.Durations[BattlePose.Idle]; + } + + void AddClip(BattlePose pose, string name) + { + definition.Clips[pose] = name; + if (!data.TryActionPath(actor, name, out string path)) + { + if (pose == BattlePose.Idle) + throw new InvalidOperationException($"Actor {actor.ActorId}: missing initial animation {name}."); + return; + } + BattleAnimationMetadata clip = data.GetAnimationMetadata(path); + double rate = pose == BattlePose.Idle ? 0.65f : ActivePlaybackRate; + definition.Durations[pose] = ToTicks(clip.TotalGameBoxTicks / (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / rate); + } + } + foreach (BattleParticipant source in scenario.Participants) + foreach (BattleParticipant target in scenario.Participants.Where(target => target.InstanceId != source.InstanceId)) + InitialAttack(source.InstanceId, target.InstanceId); + if (definitions != null) + foreach (BattleParticipant actor in scenario.Participants) + foreach (BattleAbilityDefinition ability in actor.Skills.Select(skill => definitions.Skills.GetValueOrDefault(skill.Id)) + .Concat(actor.MagicSword == null ? Array.Empty() : new[] { definitions.Skills.GetValueOrDefault(actor.MagicSword.SkillId) }) + .Concat(scenario.Items.Select(item => definitions.Items.GetValueOrDefault(item.Id))).Where(ability => ability != null)) + try + { + Ability(actor.InstanceId, ability); + } + catch (Exception ex) + { + Diagnostics.Add($"Actor {actor.ActorId}, ability {ability.Id}: {ex.Message}"); + } + } + + public static Vector3 UnityPosition(BattleMovementPoint point) => + new(-point.X / UnityPrimitivesConvertor.GameBoxUnitToUnityUnit, + point.Y / UnityPrimitivesConvertor.GameBoxUnitToUnityUnit, + point.Z / UnityPrimitivesConvertor.GameBoxUnitToUnityUnit); + + private static BattleMovementPoint NativePosition(Vector3 point) => + new(-point.x * UnityPrimitivesConvertor.GameBoxUnitToUnityUnit, + point.y * UnityPrimitivesConvertor.GameBoxUnitToUnityUnit, + point.z * UnityPrimitivesConvertor.GameBoxUnitToUnityUnit); + + public BattleMovementPoint InitialHome(string actor) => NativePosition(_actors[actor].Home); + + public BattleMovementPoint FormationHome(string actor, BattleSlot slot) => + NativePosition(_data.FormationPosition(_participants[actor].Side, slot, _sceneElement)); + + public BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint sourceHome, BattleMovementPoint targetHome) + { + return CompilePhysicalAttackPlan(source, target, sourceHome, targetHome); + } + + public IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint currentHome, + BattleMovementPoint destination, bool passThroughMidpoint) + { + BattleParticipant participant = _participants[actor]; + int identity = Priority(actor); + BattleMovementKind kind = identity == 2 ? BattleMovementKind.Teleport : BattleMovementKind.Run; +#if PAL3 + if (identity is 1 or 3) + kind = BattleMovementKind.Fly; +#endif + if (passThroughMidpoint) + { + if (BattleData.Variant != "PAL3" || identity is not (0 or 4)) + throw new ArgumentException("The original crossing route is limited to PAL3 identities 0 and 4."); + float x = currentHome.X - destination.X; + float z = currentHome.Z - destination.Z; + float length = MathF.Sqrt(x * x + z * z); + var normal = length < 0.005f ? new BattleMovementPoint(0, 1, 0) : new BattleMovementPoint(z / length, 0, -x / length); + var midpoint = new BattleMovementPoint((currentHome.X + destination.X) / 2 + normal.X * 30, + (currentHome.Y + destination.Y) / 2 + normal.Y * 30, (currentHome.Z + destination.Z) / 2 + normal.Z * 30); + return Array.AsReadOnly(new[] + { + new BattleMovementPlan(BattleMovementKind.Run, currentHome, midpoint), + new BattleMovementPlan(BattleMovementKind.Run, midpoint, destination) + }); + } + if (kind != BattleMovementKind.Fly) + { + if (kind == BattleMovementKind.Teleport) + _data.ActionPath(participant, ActorConstants.ActionToNameMap[ActorActionType.PreAttack]); + return Array.AsReadOnly(new[] { new BattleMovementPlan(kind, currentHome, destination) }); + } + BattleAnimationMetadata clip = _data.GetAnimationMetadata(_data.ActionPath(participant, _actors[actor].Clips[BattlePose.Moving])); + int? Marker(string name) + { + var markers = clip.AnimationEvents.Where(marker => marker.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).ToArray(); + if (markers.Length == 0) + return null; + if (markers.Length != 1) + throw new NotSupportedException("Formation movement needs one native " + name + " marker."); + return Math.Max(0, checked((int)Math.Ceiling(markers[0].GameBoxTick / + (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / ActivePlaybackRate / BattleSession.StepSeconds))); + } + int? up = Marker("flyup"), down = Marker("flydown"); + int over = Marker("over") ?? ToTicks(clip.TotalGameBoxTicks / (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / ActivePlaybackRate); + if (!up.HasValue) + throw new NotSupportedException("PAL3 flying formation movement has no verified flyup marker."); + return Array.AsReadOnly(new[] { new BattleMovementPlan(kind, currentHome, destination, + flyUpTick: up, flyDownTick: down, overTick: over) }); + } + + public AttackTiming Attack(string source, string target) => InitialAttack(source, target).Timing; + + private BattleAttackPlan InitialAttack(string source, string target) + { + if (!_initialAttacks.TryGetValue((source, target), out BattleAttackPlan plan)) + { + plan = PlanAttack(source, target, InitialHome(source), InitialHome(target)); + _initialAttacks.Add((source, target), plan); + } + return plan; + } + + private void InvalidateInitialAttacks(string actor) + { + foreach (var key in _initialAttacks.Keys.Where(key => key.Source == actor || key.Target == actor).ToArray()) + _initialAttacks.Remove(key); + } + + public BattleMagicSwordStageProfile MagicSword(string actor, BattleAbilityDefinition ability) + { + if (BattleData.Variant != "PAL3" || ability.IsItem || ability.SkillTypeId != 4 || + !BattleMagicSwordRules.IsSupportedSkill(ability.Id) || _participants[actor].MagicSword?.SkillId != ability.Id || + _participants[actor].Equipment[0] != BattleMagicSwordRules.WeaponId) + throw new NotSupportedException("A magic sword stage requires the captured PAL3 weapon skill."); + if (!_linkers.SkillIdToEffectGroupMap.TryGetValue(ability.Id, out EffectGroupInfo[] groups) || groups.Length != 2) + throw new NotSupportedException("The weapon skill has no verified original effect linker."); + if (groups.Any(group => group.IsCenteredAroundCaster || group.IsCenteredAroundReceiver || group.IsCasterActor || group.IsReceiverActor)) + throw new NotSupportedException("The original weapon skill uses an unverified effect placement mode."); + string clip = ActorConstants.ActionToNameMap[ActorActionType.WeaponSkill]; + BattleAnimationMetadata model = _data.GetAnimationMetadata(_data.ActionPath(_participants[actor], clip)); + int body = ToTicks(model.TotalGameBoxTicks / (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / ActivePlaybackRate); + return new BattleMagicSwordStageProfile(groups[0].EffGroupId, groups[1].EffGroupId, + groups[0].WaitDurationInSeconds, groups[1].WaitDurationInSeconds, body, + new BattleMovementPoint(groups[0].EffectGameBoxPosition.X, groups[0].EffectGameBoxPosition.Y, groups[0].EffectGameBoxPosition.Z), + new BattleMovementPoint(groups[1].EffectGameBoxPosition.X, groups[1].EffectGameBoxPosition.Y, groups[1].EffectGameBoxPosition.Z)); + } + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) + { + var key = (actor, ability.Id, ability.IsItem); + if (_abilities.TryGetValue(key, out var cached)) + return cached.Timing; + BattleParticipant participant = _participants[actor]; + if (!ability.IsItem && ability.SkillTypeId == 4) + { + BattleMagicSwordStageProfile profile = MagicSword(actor, ability); + // Only the body duration is used. The dedicated stage waits for group 1 completion. + var body = new AttackTiming(0, profile.BodyAnimationTicks, new[] { 0 }, bodyAnimationTicks: profile.BodyAnimationTicks); + _abilities.Add(key, (ActorConstants.ActionToNameMap[ActorActionType.WeaponSkill], body)); + return body; + } + BattleAbilityStageProfile ordinary = AbilityStage(actor, ability); + string clip = ordinary.RetainsBody ? null : ordinary.BodyAnimationTicks == 0 ? _data.IdleAction(participant) : AbilityClip(participant, ability); + int preparation = ordinary.Kind == BattleAbilityStageKind.Item ? 1 : ordinary.Kind == BattleAbilityStageKind.Magic ? 2 : 3; + int hit = Math.Max(0, checked((int)Math.Ceiling(ordinary.WorkSeconds / BattleSession.StepSeconds))); + int end = Math.Max(1, Math.Max(hit, ordinary.BodyAnimationTicks)); + var timing = new AttackTiming(0, end, new[] { hit }, preparationTicks: preparation, + bodyAnimationTicks: ordinary.BodyAnimationTicks, nativeWorkTimeSeconds: ordinary.WorkSeconds); + _abilities.Add(key, (clip, timing)); + return timing; + } + + private string AbilityClip(BattleParticipant actor, BattleAbilityDefinition ability) + { + bool main = _actors[actor.InstanceId].Main; +#if PAL3A + if (main && !ability.IsItem && !ability.IsMagic && ability.Id == 4506) + return "z171"; +#endif + ActorActionType action; + if (!main && !ability.IsItem) + { + uint[] skills = _data.Database.CombatActorInfos[actor.ActorId].SkillIds; + action = skills.Length > 1 && skills[1] == ability.Id ? ActorActionType.NpcMagic2 + : skills.Length > 2 && skills[2] == ability.Id ? ActorActionType.NpcMagic3 : ActorActionType.NpcMagic1; + } + else if (ability.IsItem) + { + bool Recover(int attribute) => ability.ItemType == 1 && ability.Attributes.Any(effect => effect.Attribute == attribute && + (effect.Mode == BattleValueMode.RecoverToMax || effect.Mode is BattleValueMode.Absolute or BattleValueMode.Percentage && effect.Value > 0)); + bool recover = Recover(0); +#if PAL3A + recover |= Recover(2) || ability.ItemType == 1 && ability.States.Any(state => state.State is not (BattleState.Dying or BattleState.Death)); +#endif + action = recover ? ActorActionType.UseItemRecover : ActorActionType.UseItemAttack; + } + else + { +#if PAL3 + bool second = ability.Id == 4101; +#else + bool second = ability.Id == 4106; +#endif + action = ability.IsMagic ? ActorActionType.Magic : second ? ActorActionType.Skill2 : ActorActionType.Skill1; + } + return ActorConstants.ActionToNameMap[action]; + } + + public string Clip(BattleActorSnapshot actor, BattleDefinitions definitions) + { + if (AbilityMovementClip(actor) is { } movingClip) + return movingClip; + if (actor.Pose == BattlePose.Repositioning && actor.Movement?.Finished == false) + return actor.Movement.Plan.Kind == BattleMovementKind.Teleport + ? ActorConstants.ActionToNameMap[ActorActionType.PreAttack] : _actors[actor.Id].Clips[BattlePose.Moving]; + if (actor.Pose == BattlePose.Casting) + { + return ActorConstants.ActionToNameMap[_actors[actor.Id].Main ? ActorActionType.MagicWait : ActorActionType.NpcMagic1]; + } + if (actor.Pose is BattlePose.UsingSkill or BattlePose.UsingItem) + { + var abilities = actor.CurrentAction == BattleAction.Item ? definitions.Items : definitions.Skills; + BattleAbilityDefinition ability = abilities[actor.AbilityId]; + Ability(actor.Id, ability); + return _abilities[(actor.Id, actor.AbilityId, ability.IsItem)].Clip; + } + return Clip(actor.Id, actor.Pose); + } + + private static int ToTicks(double seconds) => Math.Max(1, checked((int)Math.Ceiling(seconds / BattleSession.StepSeconds))); + + public double PlaybackRate(BattleActorSnapshot actor) => + actor.Pose == BattlePose.Repositioning && actor.Movement?.Plan.Kind == BattleMovementKind.Teleport + ? 0.65f : PlaybackRate(actor.Id, actor.Pose); + + public double PlaybackRate(string actor, BattlePose pose) => pose == BattlePose.Idle || + pose == BattlePose.Guard && !_actors[actor].Main ? 0.65f : ActivePlaybackRate; + + public static bool IsBasicEnemy(BattleData data, int actorId) + { + if (!data.Database.CombatActorInfos.TryGetValue(actorId, out var actor) || actor.Type == CombatActorType.MainActor || actorId == 7366 || + !data.Database.SkillInfos.TryGetValue((int)actor.NormalAttackModeId, out var mode)) + return false; + return mode.TargetRangeType is TargetRangeType.FirstPartySingle or TargetRangeType.EnemyPartySingle && + mode.CombatStateImpactTypes.Count == 0 && mode.SpecialSkillId == 0; + } + + public int GuardEntry(string actor) => _actors[actor].Durations.GetValueOrDefault(BattlePose.GuardEntry, 1); + + public int Dodge(string actor) => _actors[actor].Durations.GetValueOrDefault(BattlePose.Dodging, 1); + + public int Hurt(string actor) => _actors[actor].Durations.GetValueOrDefault(BattlePose.Hurt, 1); + + public int SpImpact(string actor) => _actors[actor].Sp; + + public int Priority(string actor) => _actors[actor].Priority; + + public int DamageDivisor(string actor) => _actors[actor].Divisor; + + public Vector3 Approach(string source, string target) => UnityPosition(InitialAttack(source, target).Approach); + + public string Clip(string actor, BattlePose pose) => _actors[actor].Clips.GetValueOrDefault(pose == BattlePose.Returning ? BattlePose.Moving : pose); + + public int Duration(string actor, BattlePose pose) => _actors[actor].Durations.GetValueOrDefault(pose); + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.cs.meta b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.cs.meta new file mode 100644 index 00000000..21a0a0c9 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleAnimationCatalog.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0e648b09101b41bd9822b8a036ded99d diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleBodyAudioCatalog.cs b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleBodyAudioCatalog.cs new file mode 100644 index 00000000..1cf652a3 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleBodyAudioCatalog.cs @@ -0,0 +1,20 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using Battle; + + public sealed partial class BattleAnimationCatalog : IBattleBodyAudioCatalog + { + public BattleBodySoundProfile BodySounds(string actor) + { + var participant = _participants[actor]; + var properties = _data.Database.CombatActorInfos[participant.ActorId].Properties; + return new BattleBodySoundProfile(properties?.Length > 0 ? (int)properties[0] : 0, + properties?.Length > 1 ? (int)properties[1] : 0); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleBodyAudioCatalog.cs.meta b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleBodyAudioCatalog.cs.meta new file mode 100644 index 00000000..ffef7ce0 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleBodyAudioCatalog.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 60e30ddc314f4b75a413a93e7f7ed077 diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleCoAttackCatalog.cs b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleCoAttackCatalog.cs new file mode 100644 index 00000000..7647bdc5 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleCoAttackCatalog.cs @@ -0,0 +1,43 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Pal3.Battle; + using Pal3.Core.DataReader.Dat; + + public sealed partial class BattleAnimationCatalog : IBattleCoAttackTimings + { + private readonly Dictionary _coAttacks = new(); + + public BattleMovementPoint CoAttackHome(string actor, BattleSlot slot) => + NativePosition(_data.FormationPosition(_participants[actor].Side, slot, 0)); + + public BattleComboStageProfile CoAttack(string actor, BattleComboDefinition combo) + { + if (combo == null || !_participants.ContainsKey(actor)) + throw new ArgumentException("The original combo needs a captured source actor and definition."); + if (_coAttacks.TryGetValue(combo.Id, out BattleComboStageProfile cached)) + return cached; + if (!_linkers.SkillIdToEffectGroupMap.TryGetValue(combo.Id, out EffectGroupInfo[] groups) || groups.Length != 2) + throw new NotSupportedException($"Combo {combo.Id} has no original two-group effect linker."); + // All shipped combo linkers place their groups in scene coordinates. + // Reject unsupported authored placements before the source gauge changes. + if (groups.Any(group => group.IsCenteredAroundCaster || group.IsCenteredAroundReceiver || group.IsCasterActor || group.IsReceiverActor)) + throw new NotSupportedException($"Combo {combo.Id} has an unverified actor-relative effect placement."); + var enemyCenter = NativePosition(_data.FormationPosition(BattleSide.Enemy, BattleSlot.Center, 0)); + static BattleMovementPoint Origin(EffectGroupInfo group) => + new(group.EffectGameBoxPosition.X, group.EffectGameBoxPosition.Y, group.EffectGameBoxPosition.Z); + var profile = new BattleComboStageProfile(groups[0].EffGroupId, groups[1].EffGroupId, + groups[0].WaitDurationInSeconds, groups[1].WaitDurationInSeconds, groups[0].WorkTimeInSeconds, + Origin(groups[0]), Origin(groups[1]), enemyCenter); + _coAttacks.Add(combo.Id, profile); + return profile; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleCoAttackCatalog.cs.meta b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleCoAttackCatalog.cs.meta new file mode 100644 index 00000000..df31006a --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleCoAttackCatalog.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e349a4299ec847789c4c32d7bfe6452e diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleElementWheelCatalog.cs b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleElementWheelCatalog.cs new file mode 100644 index 00000000..2f541e20 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleElementWheelCatalog.cs @@ -0,0 +1,66 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using Battle; + using Engine.Extensions; + + public sealed partial class BattleAnimationCatalog : IBattleElementWheelTimings + { + private readonly Dictionary<(string Actor, string Model, int Skill), BattleAbilityStageProfile> _elementWheelStages = new(); + private readonly Dictionary<(string Actor, string Model, int Skill), AttackTiming> _elementWheelTimings = new(); + private readonly Dictionary<(string Actor, string Model, int Skill), BattlePhysicalAnimation> _elementWheelBodies = new(); + + public BattleAbilityStageProfile ElementWheelStage(string actor, BattleAbilityDefinition ability) + { + if (BattleData.Variant != "PAL3A" || ability == null || ability.Id is < 264 or > 268 || + !_participants.TryGetValue(actor, out BattleParticipant participant) || PhysicalIdentity(participant) != 0) + throw new ArgumentException("The original element wheel requires Nangong Huang and its field skill."); + var key = (actor, _data.Model(participant), ability.Id); + if (_elementWheelStages.TryGetValue(key, out BattleAbilityStageProfile captured)) + return captured; + if (!_linkers.SkillIdToEffectGroupMap.TryGetValue(ability.Id, out var groups) || groups.Length != 2) + throw new NotSupportedException("The element wheel needs its two original linker groups."); + int bodyTicks = 0; + bool retainedBody = !_data.TryActionPath(participant, "z24", out string path); + if (!retainedBody) + { + BattleAnimationMetadata body = _data.GetAnimationMetadata(path); + bodyTicks = ToTicks(body.TotalGameBoxTicks / (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / ActivePlaybackRate); + } + captured = new BattleAbilityStageProfile(BattleAbilityStageKind.ElementWheel, CaptureAbilityBinding(groups[0]), CaptureAbilityBinding(groups[1]), + groups[0].WorkTimeInSeconds, BattleAbilityWorkBoundary.WorkTime, bodyTicks, false, retainsBody: retainedBody); + _elementWheelStages.Add(key, captured); + return captured; + } + + public AttackTiming ElementWheel(string actor, BattleAbilityDefinition ability) + { + BattleAbilityStageProfile profile = ElementWheelStage(actor, ability); + var key = (actor, _data.Model(_participants[actor]), ability.Id); + if (_elementWheelTimings.TryGetValue(key, out AttackTiming captured)) + return captured; + int hit = Math.Max(0, checked((int)Math.Ceiling(profile.WorkSeconds / BattleSession.StepSeconds))); + captured = new AttackTiming(0, Math.Max(1, Math.Max(hit, profile.BodyAnimationTicks)), new[] { hit }, + bodyAnimationTicks: profile.BodyAnimationTicks, nativeWorkTimeSeconds: profile.WorkSeconds); + _elementWheelTimings.Add(key, captured); + return captured; + } + + public BattlePhysicalAnimation ElementWheelBody(string actor, BattleAbilityDefinition ability) + { + BattleAbilityStageProfile profile = ElementWheelStage(actor, ability); + var key = (actor, _data.Model(_participants[actor]), ability.Id); + if (_elementWheelBodies.TryGetValue(key, out BattlePhysicalAnimation captured)) + return captured; + captured = profile.RetainsBody ? null : CompilePhysicalAnimation(_participants[actor], "z24"); + _elementWheelBodies.Add(key, captured); + return captured; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleElementWheelCatalog.cs.meta b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleElementWheelCatalog.cs.meta new file mode 100644 index 00000000..3e3cb917 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleElementWheelCatalog.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 05bb74ccb4f04d1da86102b3d436f750 diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleMonsterCatalog.cs b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleMonsterCatalog.cs new file mode 100644 index 00000000..1ec361ba --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleMonsterCatalog.cs @@ -0,0 +1,106 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Runtime.CompilerServices; + using Battle; + + public sealed partial class BattleAnimationCatalog : IBattleMonsterFactory + { + private readonly ConditionalWeakTable _preparedMonsters = new(); + + public BattleMonsterCreation Prepare(int nativeIndex, int actorId, string instanceId) + { + if (nativeIndex < 5 || nativeIndex > 10 || string.IsNullOrWhiteSpace(instanceId)) + throw new ArgumentException("A native enemy slot and stable instance ID are required."); + BattleParticipant participant = _data.CreateParticipant(actorId, BattleSide.Enemy, (BattleSlot)(nativeIndex - 5)); + participant.InstanceId = instanceId; + participant.Statuses.Clear(); + BattleActorDefinition original = BattleDefinitionCompiler.Actor(_data, participant, BattleData.Variant); + // Released CreateMonster zeroes the role and installs poison + // immunity only; it does not replay LoadRoleData's initial states. + var definition = new BattleActorDefinition(new BattleActorData + { + InstanceId = instanceId, + Identity = original.Identity, + Boss = original.Boss, + Equipment = original.Equipment.ToArray(), + ImmuneStates = original.ImmuneStates.ToArray(), + PermanentStates = original.PermanentStates.Where(state => state == BattleState.PoisonResist).ToArray(), + PhysicalAttackElements = original.PhysicalAttackElements, + PhysicalDefenseElements = original.PhysicalDefenseElements, + PhysicalAttackElementValues = original.PhysicalAttackElementValues.ToArray(), + PhysicalDefenseElementValues = original.PhysicalDefenseElementValues.ToArray(), + NormalAttackMode = original.NormalAttackMode, + NormalAttackRange = original.NormalAttackRange, + ExperienceReward = original.ExperienceReward, + MoneyReward = original.MoneyReward, + LootItem = original.LootItem, + LootCount = original.LootCount, + CorpseItem = original.CorpseItem, + CorpseSkill = original.CorpseSkill, + CorpsePercent = original.CorpsePercent, + EscapePercent = original.EscapePercent, + StealableMoney = original.StealableMoney, + StealableItemId = original.StealableItemId, + StealableItemCount = original.StealableItemCount, + GrowthUnsupportedReason = original.GrowthUnsupportedReason, + UnsupportedReason = original.UnsupportedReason, + }); + var creation = new BattleMonsterCreation(nativeIndex, participant, definition); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + DataFingerprint = _data.Fingerprint, + Scene = "prepared-native-monster", + SceneElement = _sceneElement, + Participants = _participants.Values.Where(actor => actor.InstanceId != instanceId).Select(actor => actor.Copy()).ToList() + }; + scenario.Participants.Add(participant); + var setup = new BattleSetup(scenario); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, setup); + var prepared = new BattleAnimationCatalog(_data, setup, definitions, _linkers); + // Force both movement/body and ability metadata to be captured + // before a live slot is changed or any source action is cancelled. + _ = prepared.Physical(instanceId); + foreach (BattleSkill skill in participant.Skills) + if (definitions.Skills.TryGetValue(skill.Id, out BattleAbilityDefinition ability) && ability.SkillTypeId != 4 && + string.IsNullOrEmpty(ability.UnsupportedReason) && skill.Id != (BattleData.Variant == "PAL3" ? 7711 : 7714)) + { + _ = prepared.Ability(instanceId, ability); + _ = prepared.AbilityStage(instanceId, ability); + } + _preparedMonsters.Add(creation, prepared); + return creation; + } + + public void Commit(BattleMonsterCreation creation) + { + if (creation == null || !_preparedMonsters.TryGetValue(creation, out BattleAnimationCatalog prepared)) + throw new ArgumentException("The monster was not prepared by this catalog.", nameof(creation)); + _preparedMonsters.Remove(creation); + string instanceId = creation.Participant.InstanceId; + _participants[instanceId] = prepared._participants[instanceId]; + _actors[instanceId] = prepared._actors[instanceId]; + _physicalProfiles[instanceId] = prepared._physicalProfiles[instanceId]; + foreach (var key in _abilities.Keys.Where(key => key.Item1 == instanceId).ToArray()) + _abilities.Remove(key); + foreach (var key in _abilityStages.Keys.Where(key => key.Item1 == instanceId).ToArray()) + _abilityStages.Remove(key); + foreach (var pair in prepared._abilities.Where(pair => pair.Key.Item1 == instanceId)) + _abilities[pair.Key] = pair.Value; + foreach (var pair in prepared._abilityStages.Where(pair => pair.Key.Item1 == instanceId)) + _abilityStages[pair.Key] = pair.Value; + InvalidateInitialAttacks(instanceId); + foreach (var pair in prepared._initialAttacks.Where(pair => pair.Key.Source == instanceId || pair.Key.Target == instanceId)) + _initialAttacks.Add(pair.Key, pair.Value); + Diagnostics.AddRange(prepared.Diagnostics); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattleMonsterCatalog.cs.meta b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleMonsterCatalog.cs.meta new file mode 100644 index 00000000..cc8ee83a --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattleMonsterCatalog.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 013fde954ab74e0bb75dd861994b9dde diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePal3AFormCatalog.cs b/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePal3AFormCatalog.cs new file mode 100644 index 00000000..1ecc9916 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePal3AFormCatalog.cs @@ -0,0 +1,72 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using Core.Contract.Enums; + using Engine.Extensions; + + public sealed partial class BattleAnimationCatalog : IBattlePal3AFormCatalog + { + private readonly Dictionary _pal3AOriginalModels = new(StringComparer.Ordinal); + private readonly Dictionary<(string Actor, bool Transformed), BattlePhysicalAnimation> _pal3AFormClips = new(); + + public BattlePhysicalAnimation FormChangeAnimation(string actorId, bool transformed) + { + if (BattleData.Variant != "PAL3A" || !_participants.TryGetValue(actorId, out BattleParticipant actor) || + actor.ActorId is not (101 or 103)) + throw new ArgumentException("This actor has no original PAL3A hero form.", nameof(actorId)); + if (_pal3AFormClips.TryGetValue((actorId, transformed), out BattlePhysicalAnimation captured)) + return captured; + if (!_pal3AOriginalModels.ContainsKey(actorId)) + _pal3AOriginalModels.Add(actorId, _data.Model(actor)); + BattleParticipant candidate = actor.Copy(); + candidate.Model = transformed ? actor.ActorId == 101 ? "107" : "106" : _pal3AOriginalModels[actorId]; + captured = CompilePhysicalAnimation(candidate, "z20"); + _pal3AFormClips.Add((actorId, transformed), captured); + return captured; + } + + public void ActivatePal3AForm(string actorId, BattlePal3AFormKind kind) + { + if (BattleData.Variant != "PAL3A" || !_participants.TryGetValue(actorId, out BattleParticipant actor)) + throw new ArgumentException("The original PAL3A form actor is missing.", nameof(actorId)); + if (!_pal3AOriginalModels.ContainsKey(actorId)) + _pal3AOriginalModels.Add(actorId, _data.Model(actor)); + // Only this session's selected model changes. Every compiled clip and + // physical profile remains immutable and no live Unity object enters it. + BattleParticipant candidate = actor.Copy(); + candidate.Model = kind switch + { + BattlePal3AFormKind.NangongFireBeast when actor.ActorId == 101 => "107", + BattlePal3AFormKind.PengxuFairyBeast when actor.ActorId == 103 => "106", + BattlePal3AFormKind.Human => _pal3AOriginalModels[actorId], + _ => throw new ArgumentException("The selected form belongs to another hero.", nameof(kind)) + }; + ActorDefinition definition = _actors[actorId]; + var durations = new Dictionary(); + foreach (var pair in definition.Clips) + if (_data.TryActionPath(candidate, pair.Value, out string path)) + { + BattleAnimationMetadata clip = _data.GetAnimationMetadata(path); + double rate = pair.Key == BattlePose.Idle ? .65f : ActivePlaybackRate; + durations[pair.Key] = ToTicks(clip.TotalGameBoxTicks / (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / rate); + } + actor.Model = candidate.Model; + definition.Durations = durations; + _physicalProfiles.Remove(actorId); + InvalidateInitialAttacks(actorId); + foreach (var key in _abilities.Keys.Where(key => key.Item1 == actorId).ToArray()) + _abilities.Remove(key); + foreach (var key in _abilityStages.Keys.Where(key => key.Item1 == actorId).ToArray()) + _abilityStages.Remove(key); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePal3AFormCatalog.cs.meta b/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePal3AFormCatalog.cs.meta new file mode 100644 index 00000000..a981c141 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePal3AFormCatalog.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ebd344f22fbf4095a1abf041660da603 diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePhysicalCatalog.cs b/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePhysicalCatalog.cs new file mode 100644 index 00000000..e525e24b --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePhysicalCatalog.cs @@ -0,0 +1,108 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using Core.Contract.Enums; + using Core.DataReader.Mv3; + using Engine.Extensions; + + public sealed partial class BattleAnimationCatalog : IBattlePhysicalTimings + { + private readonly Dictionary _physicalProfiles = new(StringComparer.Ordinal); + + private static int PhysicalIdentity(BattleParticipant actor) => actor.Side == BattleSide.Enemy ? -1 : BattleData.PlayerIdentity(actor.ActorId); + + public BattlePhysicalStageProfile Physical(string actor) + { + if (_physicalProfiles.TryGetValue(actor, out BattlePhysicalStageProfile cached)) + return cached; + BattleParticipant participant = _participants[actor]; + int identity = PhysicalIdentity(participant); + int weapon = 0, count = 1; + if (identity >= 0 && participant.Equipment.Length > 0 && participant.Equipment[0] != 0) + { + var item = _data.Database.GameItemInfos[participant.Equipment[0]]; + weapon = (int)item.WeaponType; + count = item.AttackHitCount; + } + var animations = new Dictionary(); + foreach (var pair in _actors[actor].Clips) + animations[pair.Key] = CompilePhysicalAnimation(participant, pair.Value); + if (participant.Side == BattleSide.Ally) + { + animations[BattlePose.Dying] = CompilePhysicalAnimation(participant, ActorConstants.ActionToNameMap[ActorActionType.Dying]); + animations[BattlePose.Sleeping] = CompilePhysicalAnimation(participant, ActorConstants.ActionToNameMap[ActorActionType.Freeze]); + animations[BattlePose.GuardHurt] = CompilePhysicalAnimation(participant, ActorConstants.ActionToNameMap[ActorActionType.DefenceBeAttack]); + } + animations[BattlePose.Casting] = CompilePhysicalAnimation(participant, ActorConstants.ActionToNameMap[participant.Side == BattleSide.Ally ? ActorActionType.MagicWait : ActorActionType.NpcMagic1]); + animations[BattlePose.Attacking] = CompilePhysicalAnimation(participant, _data.AttackAction(participant)); + var profile = new BattlePhysicalStageProfile(BattleData.Variant, participant.ActorId, identity, weapon, count, animations, thrownStart: BattleData.Variant == "PAL3A" ? CompilePhysicalAnimation(participant, "z021") : null, + thrownReturn: BattleData.Variant == "PAL3A" ? CompilePhysicalAnimation(participant, "z022") : null); + _physicalProfiles.Add(actor, profile); + return profile; + } + + private BattlePhysicalAnimation CompilePhysicalAnimation(BattleParticipant actor, string clipName) + { + if (!_data.TryActionPath(actor, clipName, out string path)) + return null; + BattleAnimationMetadata clip = _data.GetAnimationMetadata(path); + if (!clip.HasBounds) + throw new NotSupportedException($"Actor {actor.ActorId}, clip {clipName}: original collision bounds are missing."); + float minimum = clip.MinimumZ; + float maximum = clip.MaximumZ; + var markers = new List(); + foreach (Mv3AnimationEvent marker in clip.AnimationEvents) + { + int tick = Math.Max(0, checked((int)Math.Ceiling(marker.GameBoxTick / + (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / ActivePlaybackRate / BattleSession.StepSeconds))); + markers.Add(new BattlePhysicalMarker(tick, PhysicalMarkerKind(marker.Name), marker.GameBoxTick, marker.Name)); + } + int duration = ToTicks(clip.TotalGameBoxTicks / (double)UnityPrimitivesConvertor.GameBoxTicksPerSecond / ActivePlaybackRate); + return new BattlePhysicalAnimation(clipName, duration, (maximum - minimum) / 2f, markers, clip.TotalGameBoxTicks); + } + + private static BattlePhysicalMarkerKind PhysicalMarkerKind(string name) => name.ToLowerInvariant() switch + { + "work" => BattlePhysicalMarkerKind.Work, + "work1" => BattlePhysicalMarkerKind.Work1, + "work2" => BattlePhysicalMarkerKind.Work2, + "work3" => BattlePhysicalMarkerKind.Work3, + "over" => BattlePhysicalMarkerKind.Over, + "flyup" or "sjump" => BattlePhysicalMarkerKind.FlyUp, + "flydown" or "ejump" => BattlePhysicalMarkerKind.FlyDown, + "start" => BattlePhysicalMarkerKind.Start, + "catched" => BattlePhysicalMarkerKind.Catched, + "throwed" => BattlePhysicalMarkerKind.Throwed, + _ => BattlePhysicalMarkerKind.Other + }; + + private BattleAttackPlan CompilePhysicalAttackPlan(string source, string target, BattleMovementPoint sourceHome, BattleMovementPoint targetHome) + { + BattlePhysicalStageProfile profile = Physical(source); + BattlePhysicalAnimation animation = profile.Animation(BattlePose.Attacking); + int[] work = (animation?.Markers ?? Array.Empty()).Where(marker => marker.Kind <= (BattleData.Variant == "PAL3A" ? BattlePhysicalMarkerKind.Work3 : BattlePhysicalMarkerKind.Work1)) + .Select(marker => marker.Tick).ToArray(); + // Travel is a native body task, not a precomputed linear duration. This + // compatibility timeline exposes only the clip's real work messages. + var timing = new AttackTiming(0, Math.Max(animation?.DurationTicks ?? 1, work.DefaultIfEmpty(0).Max()), work, allowEmptyHits: true); + var direction = BattleMovement.NormalizeDirection(new BattleMovementPoint(sourceHome.X - targetHome.X, + sourceHome.Y - targetHome.Y, sourceHome.Z - targetHome.Z)); + float distance = profile.Radius(BattlePose.Idle) + Physical(target).Radius(BattlePose.Idle); + if (profile.ResourceId is 7364 or 7381) + distance *= 2; + bool stationary = profile.Approach().Count == 1 && profile.Approach()[0] == BattlePhysicalBodyKind.TurnToRole || profile.UsesThrownWeapon; + var approach = stationary ? sourceHome : new BattleMovementPoint(targetHome.X + direction.X * distance, + targetHome.Y + direction.Y * distance, targetHome.Z + direction.Z * distance); + return new BattleAttackPlan(timing, sourceHome, approach, targetHome); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePhysicalCatalog.cs.meta b/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePhysicalCatalog.cs.meta new file mode 100644 index 00000000..dc3ba033 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Catalog/BattlePhysicalCatalog.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a68a93c9c1894bc282dca11b7e4e667a diff --git a/Assets/Scripts/Editor/BattleEditor/Data.meta b/Assets/Scripts/Editor/BattleEditor/Data.meta new file mode 100644 index 00000000..7b71a6b5 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2f2fe36b7f174d9db12dc2cfc84239de +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleAnimationMetadata.cs b/Assets/Scripts/Editor/BattleEditor/Data/BattleAnimationMetadata.cs new file mode 100644 index 00000000..9468eeea --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleAnimationMetadata.cs @@ -0,0 +1,56 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Core.DataReader.Mv3; + + // Catalogs need timing, markers and source collision bounds, not the + // expanded rendering geometry or regenerated normals of every keyframe. + public sealed class BattleAnimationMetadata + { + public uint TotalGameBoxTicks + { + get; + } + + public IReadOnlyList AnimationEvents + { + get; + } + + public bool HasBounds + { + get; + } + + public float MinimumZ + { + get; + } + + public float MaximumZ + { + get; + } + + public BattleAnimationMetadata(Mv3File source) + { + if (source == null) + throw new ArgumentNullException(nameof(source)); + TotalGameBoxTicks = source.TotalGameBoxTicks; + AnimationEvents = Array.AsReadOnly(source.AnimationEvents.ToArray()); + HasBounds = source.Meshes.Length > 0; + if (HasBounds) + { + MinimumZ = source.Meshes.Min(mesh => mesh.GameBoxBoundsMin.Z); + MaximumZ = source.Meshes.Max(mesh => mesh.GameBoxBoundsMax.Z); + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleAnimationMetadata.cs.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleAnimationMetadata.cs.meta new file mode 100644 index 00000000..777016d4 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleAnimationMetadata.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9cb112473f844644acda2ba7f0ac62c7 diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleData.AnimationMetadata.cs b/Assets/Scripts/Editor/BattleEditor/Data/BattleData.AnimationMetadata.cs new file mode 100644 index 00000000..2a98ced4 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleData.AnimationMetadata.cs @@ -0,0 +1,39 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.IO; + using Core.DataReader.Mv3; + + public sealed partial class BattleData + { + private readonly Dictionary _animationMetadata = new(StringComparer.OrdinalIgnoreCase); + private bool _animationMetadataDisposed; + + public BattleAnimationMetadata GetAnimationMetadata(string path) + { + if (_animationMetadataDisposed) + throw new ObjectDisposedException(nameof(BattleData)); + var entry = Resources.Find(path) ?? throw new FileNotFoundException("Missing battle animation: " + path); + if (_animationMetadata.TryGetValue(entry.Path, out BattleAnimationMetadata metadata)) + return metadata; + // Keep full reader validation on the first read. Only the small + // immutable projection survives in this data owner's cache. + Mv3File model = Read(entry.Path, new Mv3FileReader()); + metadata = new BattleAnimationMetadata(model); + _animationMetadata.Add(entry.Path, metadata); + return metadata; + } + + private void DisposeAnimationMetadata() + { + _animationMetadataDisposed = true; + _animationMetadata.Clear(); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleData.AnimationMetadata.cs.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleData.AnimationMetadata.cs.meta new file mode 100644 index 00000000..0c6abaea --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleData.AnimationMetadata.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 809766256dd84117a68c82c254d30eba diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleData.cs b/Assets/Scripts/Editor/BattleEditor/Data/BattleData.cs new file mode 100644 index 00000000..ea6fe389 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleData.cs @@ -0,0 +1,332 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Threading; + using System.Security.Cryptography; + using System.Text; + using Battle; + using Core.Contract.Constants; + using Core.Contract.Enums; + using Core.DataReader; + using Core.DataReader.Gdb; + using Core.DataReader.Ini; + using Core.DataReader.Txt; + using Core.Primitives; + using Engine.Extensions; + using ResourceBrowser; + using UnityEngine; + + // Read-only original-data adapter. No runtime service registrations or original-data writes. + public sealed partial class BattleData : IDisposable + { +#if PAL3A + public const string Variant = "PAL3A"; +#else + public const string Variant = "PAL3"; +#endif + + public ResourceCatalog Resources + { + get; + } + + public GdbFile Database + { + get; + } + + public CombatConfigFile Layout + { + get; + } + + public CombatCameraConfigFile Cameras + { + get; + } + + public CombatScnFile SceneMap + { + get; + } + + public string[] Scenes + { + get; + } + + public string Fingerprint + { + get; + } + + private readonly Dictionary _actions = new(StringComparer.OrdinalIgnoreCase); + + public BattleData(string root, int codepage, CancellationToken cancellation = default) + { + Resources = ResourceCatalog.OpenBaseData(root, codepage, cancellation); + try + { + string database = $"basedata.cpk\\cbdata\\{Variant}_Softstar.gdb"; + string detected = Resources.Find("basedata.cpk\\cbdata\\PAL3A_Softstar.gdb") != null ? "PAL3A" : "PAL3"; + if (detected != Variant || Resources.Find(database) == null) + throw new InvalidDataException($"This is not {Variant} data. Use Switch Variant before loading the other game."); + cancellation.ThrowIfCancellationRequested(); + Database = Read(database, new GdbFileReader()); + cancellation.ThrowIfCancellationRequested(); + Layout = Read("basedata.cpk\\datascript\\combat.ini", new CombatConfigFileReader()); + Cameras = Read("basedata.cpk\\datascript\\cbCam.ini", new CombatCameraConfigFileReader()); + SceneMap = Read("basedata.cpk\\datascript\\combatScn.txt", new CombatScnFileReader()); + Scenes = Resources.Entries.Where(entry => entry.Extension == ".pol" && + entry.Path.StartsWith("basedata.cpk\\cbscene\\", StringComparison.OrdinalIgnoreCase) && + Path.GetFileNameWithoutExtension(entry.Name).Equals(entry.Path.Split('\\')[^2], StringComparison.OrdinalIgnoreCase)) + .Select(entry => entry.Path.Split('\\')[^2]).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(name => name, StringComparer.Ordinal).ToArray(); + using var hash = SHA256.Create(); + using var content = new MemoryStream(); + foreach (string path in new[] { database, "basedata.cpk\\datascript\\combat.ini", "basedata.cpk\\datascript\\cbCam.ini", "basedata.cpk\\datascript\\combatScn.txt" }) + { + cancellation.ThrowIfCancellationRequested(); + byte[] bytes = Bytes(path); + content.Write(bytes, 0, bytes.Length); + } + Fingerprint = BitConverter.ToString(hash.ComputeHash(content.ToArray())).Replace("-", "").ToLowerInvariant(); + } + catch + { + Resources.Dispose(); + throw; + } + } + + public byte[] Bytes(string path) + { + ResourceEntry entry = Resources.Find(path) ?? throw new FileNotFoundException("Missing battle dependency: " + path); + return Resources.Read(entry); + } + + public T Read(string path, IFileReader reader) => reader.Read(Bytes(path), Resources.Codepage); + + public string Model(BattleParticipant actor) + { + if (!string.IsNullOrWhiteSpace(actor.Model)) + return actor.Model; + CombatActorInfo info = Database.CombatActorInfos[actor.ActorId]; + return info.Type == CombatActorType.MainActor || string.IsNullOrEmpty(info.ModelId) || info.ModelId.Equals("Null", StringComparison.OrdinalIgnoreCase) + ? actor.ActorId.ToString() : info.ModelId; + } + + public static int PlayerIdentity(int actorId) => BattleLoadoutRules.PlayerIdentity(Variant, actorId); + + public ActorAction[] Actions(BattleParticipant actor) + { + string model = Model(actor); + if (_actions.TryGetValue(model, out ActorAction[] cached)) + return cached; + string path = FileConstants.GetActorFolderVirtualPath(model) + model + ".ini"; + byte[] bytes = Bytes(path); + if (bytes.Length < 6 || Encoding.ASCII.GetString(bytes, 0, 6) != ";#MV3#") + throw new NotSupportedException("Battle preview requires an MV3 action configuration: " + path); + ActorAction[] actions = new Mv3ConfigFileReader().Read(bytes, Resources.Codepage).ActorActions; + _actions[model] = actions; + return actions; + } + + public bool TryActionPath(BattleParticipant actor, string action, out string path) + { + ActorAction[] actions = Actions(actor); + int index = Array.FindIndex(actions, item => item.ActionName.Equals(action, StringComparison.OrdinalIgnoreCase)); + path = index < 0 ? null : FileConstants.GetActorFolderVirtualPath(Model(actor)) + actions[index].ActionFileName; + return path != null && Resources.Find(path) != null; + } + + public string ActionPath(BattleParticipant actor, string action) + { + ActorAction[] actions = Actions(actor); + int index = Array.FindIndex(actions, item => item.ActionName.Equals(action, StringComparison.OrdinalIgnoreCase)); + if (index < 0) + throw new InvalidOperationException($"Actor {actor.ActorId} has no action {action}."); + return FileConstants.GetActorFolderVirtualPath(Model(actor)) + actions[index].ActionFileName; + } + + public string IdleAction(BattleParticipant actor) + { + string[] preferred = Database.CombatActorInfos[actor.ActorId].Type == CombatActorType.MainActor + ? new[] { ActorConstants.ActionToNameMap[ActorActionType.PreAttack], "z1" } : new[] { "z1", "z2" }; + return preferred.FirstOrDefault(name => Actions(actor).Any(action => action.ActionName.Equals(name, StringComparison.OrdinalIgnoreCase))) + ?? Actions(actor).First().ActionName; + } + + public string AttackAction(BattleParticipant actor) + { + if (Database.CombatActorInfos[actor.ActorId].Type != CombatActorType.MainActor) + return ActorConstants.ActionToNameMap[ActorActionType.NpcAttack]; + int identity = PlayerIdentity(actor.ActorId); + int weapon = actor.Equipment is { Length: > 0 } && actor.Equipment[0] != 0 ? (int)Database.GameItemInfos[actor.Equipment[0]].WeaponType : 0; + bool second = Variant == "PAL3" ? identity == 2 && weapon == 7 || identity == 3 && weapon == 4 || identity == 4 && weapon == 2 + : identity == 1 && weapon == 4 || identity == 2 && weapon == 6 || identity == 4 && weapon == 9; + return ActorConstants.ActionToNameMap[second ? ActorActionType.Attack2 : ActorActionType.Attack1]; + } + + public Vector3 Position(BattleParticipant actor, int sceneElement) => actor.OverridePosition + ? new Vector3(actor.Position.X, actor.Position.Y, actor.Position.Z) + : FormationPosition(actor.Side, actor.Slot, sceneElement); + + internal Vector3 FormationPosition(BattleSide side, BattleSlot slot, int sceneElement) + { + if (side == BattleSide.Enemy) + return Layout.ActorGameBoxPositions[5 + (int)slot].ToUnityPosition(); + if (slot == BattleSlot.Center) + { + var center = Layout.AllyFormationConfig.CenterGameBoxPosition; + return new GameBoxVector3(center.X, 0, center.Z).ToUnityPosition(); + } + // combat.ini places Thunder before Wind in the neutral allied lineup. + BattleSlot initial = BattleTargetRules.InitialAllySlot(slot, sceneElement); + int role = initial switch + { + BattleSlot.Thunder => 2, + BattleSlot.Wind => 3, + _ => (int)initial, + }; + return Layout.ActorGameBoxPositions[role].ToUnityPosition(); + } + + public BattleParticipant CreateParticipant(int actorId, BattleSide side, BattleSlot slot) + { + CombatActorInfo info = Database.CombatActorInfos[actorId]; + var actor = new BattleParticipant + { + ActorId = actorId, + Side = side, + Slot = slot, + Level = Math.Clamp(info.Level, 1, 100), + Experience = Math.Max(0, info.Experience), + Attributes = Enumerable.Range(0, 12).Select(index => Math.Max(0, info.AttributeValues[(ActorAttributeType)index])).ToArray(), + Skills = info.SkillIds.Select((id, index) => (id, index)).Where(entry => entry.id != 0).GroupBy(entry => entry.id) + .Select(group => new BattleSkill + { + Id = (int)group.Key, + Level = info.Type != CombatActorType.MainActor && group.First().index == 3 ? 4 : + group.First().index < info.SkillLevels.Length ? Math.Max(1, (int)info.SkillLevels[group.First().index]) : 1 + }).ToList(), + }; + actor.Vitals = actor.Attributes.Take(3).ToArray(); + string model = Model(actor); + if (ActorConstants.MainActorWeaponMap.TryGetValue(model, out string weapon)) + actor.Equipment[0] = Database.GameItemInfos.Where(pair => pair.Value.Type == ItemType.Weapon && pair.Value.ModelName == weapon && + pair.Value.ApplicableActors.Contains((PlayerActorId)PlayerIdentity(actorId))) + .Select(pair => pair.Key).OrderBy(id => id).FirstOrDefault(); + if (actor.Equipment[0] == 0 && info.Type == CombatActorType.MainActor) + actor.Equipment[0] = Database.GameItemInfos.Where(pair => pair.Value.Type == ItemType.Weapon && + pair.Value.ApplicableActors.Contains((PlayerActorId)PlayerIdentity(actorId)) && + (int)pair.Value.WeaponType > 0 && pair.Key != BattleMagicSwordRules.WeaponId) + .Select(pair => pair.Key).OrderBy(id => id).FirstOrDefault(); + if (actor.Equipment[0] == BattleMagicSwordRules.WeaponId) + { + // A newly added participant has no magic-sword cultivation snapshot yet. + GameItemInfo original = Database.GameItemInfos[actor.Equipment[0]]; + actor.Equipment[0] = Database.GameItemInfos.Where(pair => pair.Value.Type == ItemType.Weapon && + pair.Value.WeaponType == original.WeaponType && (int)pair.Value.ItemSpecialType == 0 && + pair.Value.ApplicableActors.Intersect(original.ApplicableActors).Any()) + .Select(pair => pair.Key).OrderBy(id => id).FirstOrDefault(); + } + return actor; + } + + public BattleParticipant CreateTestParticipant(int actorId, BattleSide side, BattleSlot slot) => + BattleTestLoadoutBuilder.Create(this, actorId, side, slot); + + public string CombatRosterDenial(int actorId, BattleSide side) + { + if (!Database.CombatActorInfos.TryGetValue(actorId, out CombatActorInfo info)) + return $"角色 {actorId}:原版数据中不存在。"; + bool main = info.Type == CombatActorType.MainActor; + if (main != (side == BattleSide.Ally)) + return $"角色 {actorId}({info.Name}):战斗仅支持主角加入我方、怪物加入敌方;其他组合可用于动作预览。"; + if (main && PlayerIdentity(actorId) < 0) + return $"角色 {actorId}({info.Name}):此主角形态尚不支持独立开战,请选择标准主角;仍可用于动作预览。"; + return null; + } + + public List Validate(BattleScenario scenario, bool forBattle = false) + { + List errors = scenario.Validate(); + if (scenario.Variant != Variant) + errors.Add($"Scenario is {scenario.Variant}; current Unity Variant is {Variant}."); + if (scenario.DataFingerprint != Fingerprint) + errors.Add("Scenario data fingerprint differs. Explicitly rebind the scenario to this data before previewing."); + if (!Scenes.Contains(scenario.Scene, StringComparer.OrdinalIgnoreCase)) + errors.Add("Combat scene is missing: " + scenario.Scene); + if (scenario.Participants == null) + return errors; + var allyIdentities = new HashSet(); + foreach (BattleParticipant actor in scenario.Participants.Where(actor => actor != null)) + { + if (!Database.CombatActorInfos.ContainsKey(actor.ActorId)) + { + errors.Add("Unknown actor: " + actor.ActorId); + continue; + } + if (forBattle) + { + if (CombatRosterDenial(actor.ActorId, actor.Side) is string reason) + errors.Add(reason); + else if (actor.Side == BattleSide.Ally && !allyIdentities.Add(PlayerIdentity(actor.ActorId))) + errors.Add($"角色 {actor.ActorId}:同一主角只能参加一次战斗。"); + } + try + { + string idle = IdleAction(actor); + if (!TryActionPath(actor, idle, out string idlePath)) + errors.Add($"Actor {actor.ActorId}: missing initial action {idle} ({idlePath})."); + // Original INIs include optional, absent actions. GotoAction + // can fail while the current animation continues; validate + // actual requested dependencies when compiling their task. + } + catch (Exception ex) + { + errors.Add(ex.Message); + } + if (actor.Skills != null) + foreach (BattleSkill skill in actor.Skills.Where(skill => skill != null)) + if (!Database.SkillInfos.ContainsKey(skill.Id)) + errors.Add("Unknown skill: " + skill.Id); + if (actor.Equipment != null) + foreach (int item in actor.Equipment.Where(id => id != 0)) + if (!Database.GameItemInfos.ContainsKey(item)) + errors.Add("Unknown equipment: " + item); + } + if (scenario.Items != null) + foreach (BattleItem item in scenario.Items.Where(item => item != null)) + if (!Database.GameItemInfos.ContainsKey(item.Id)) + errors.Add("Unknown item: " + item.Id); + return errors; + } + + public BattleSetup Capture(BattleScenario scenario, bool forBattle = false) + { + if (scenario == null) + throw new ArgumentNullException(nameof(scenario)); + List errors = Validate(scenario, forBattle); + if (errors.Count > 0) + throw new ArgumentException(string.Join("\n", errors), nameof(scenario)); + BattleScenario prepared = scenario.Copy(); + prepared.Participants = scenario.Participants.Select(actor => BattleLoadoutRules.Prepare(Variant, actor)).ToList(); + return new BattleSetup(prepared); + } + + public void Dispose() + { + DisposeAnimationMetadata(); + Resources.Dispose(); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleData.cs.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleData.cs.meta new file mode 100644 index 00000000..4e845f2c --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleData.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: bd72c1bab960a49e8b8cbdd173703cf1 \ No newline at end of file diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleDefinitionCompiler.cs b/Assets/Scripts/Editor/BattleEditor/Data/BattleDefinitionCompiler.cs new file mode 100644 index 00000000..3f29cd98 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleDefinitionCompiler.cs @@ -0,0 +1,438 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using Core.Contract.Enums; + using Core.DataReader.Gdb; + + public static partial class BattleDefinitionCompiler + { + public static BattleDefinitions Build(BattleData data, BattleSetup setup) + { + if (data == null || setup == null) + throw new ArgumentNullException(data == null ? nameof(data) : nameof(setup)); + BattleScenario scenario = setup.CreateInstance(); + if (scenario.Variant != BattleData.Variant) + throw new ArgumentException("The scenario and original database variants differ.", nameof(setup)); + BattleMagicSwordSnapshot cultivation = scenario.Variant == "PAL3" + ? (scenario.Participants.FirstOrDefault(actor => actor.Side == BattleSide.Ally && BattleData.PlayerIdentity(actor.ActorId) == 0)?.MagicSword + ?? new BattleMagicSword()).Capture() : null; + return new BattleDefinitions(scenario.Variant, data.Fingerprint, + data.Database.SkillOrder.Where(id => id > 0).Select(id => Skill(data.Database.SkillInfos[id])), + data.Database.GameItemInfos.Values.Where(item => item.Id > 0).Select(Item), + scenario.Participants.Select(actor => Actor(data, actor, scenario.Variant, cultivation)), + data.Database.ComboSkillOrder.Select(id => Combo(data.Database.ComboSkillInfos[id]))); + } + + private static BattleComboDefinition Combo(ComboSkillInfo combo) => new(combo.Name, + new BattleComboRequirement(checked((int)combo.Id), checked((int)combo.SkillId), + combo.MainActorRequirements.Select(id => checked((int)id)), + combo.ElementPositionRequirements.Select(position => (int)position), + combo.WeaponTypeRequirements.Select(weapon => (int)weapon), combo.AuxiliaryStateConditions), + (int)combo.TargetRangeType, + Enumerable.Range(0, 12).Select(index => combo.AttributeImpacts.TryGetValue((ActorAttributeType)index, out AttributeImpact effect) ? (int)effect.Value : 0), +#if PAL3A + combo.PowerMultiplierPercentage +#else + 0 +#endif + ); + + private static BattleAbilityDefinition Skill(SkillInfo skill) + { + var reasons = new List(); + int type = (int)skill.Type; + bool fiveSpirit = BattleData.Variant == "PAL3A" && skill.Id is >= 264 and <= 268; + bool pal3ASpecial = BattleData.Variant == "PAL3A" && BattlePal3ARules.IsDedicatedAbility(checked((int)skill.Id)); + BattleSpecialHandler handler = BattleSpecialRules.AbilityHandler(BattleData.Variant, checked((int)skill.Id), false, type is >= 1 and <= 3, skill.SpecialSkillId); + if (type < 0 || type > 4) + reasons.Add("Unknown original skill type " + type + "."); + if (type == 4 && (BattleData.Variant != "PAL3" || !BattleMagicSwordRules.IsSupportedSkill(checked((int)skill.Id)))) + reasons.Add("Unknown original weapon skill."); + if (skill.SpecialSkillId != 0 && handler == BattleSpecialHandler.None) + reasons.Add("Original special skill handler " + skill.SpecialSkillId + " is not implemented."); + int elements = Elements(skill.ElementAttributes); + if ((elements & (elements - 1)) != 0 && type is not (1 or 2 or 3 or 4)) + reasons.Add("Composite elements are unverified for this skill type."); + if (!BattleSpecialRules.SupportsSuccessRate(BattleData.Variant, checked((int)skill.Id), skill.SuccessRateLevel)) + reasons.Add("Original success formula " + skill.SuccessRateLevel + " is not implemented."); + BattleAttributeEffect[] attributes = Attributes(skill.AttributeImpacts, reasons); + BattleStatusEffect[] states = SkillStates(skill.CombatStateImpactTypes, reasons); + if (attributes.Length == 0 && states.Length == 0 && skill.SpecialSkillId == 0 && handler != BattleSpecialHandler.GenericOnly && !fiveSpirit && !pal3ASpecial) + reasons.Add("No verified generic effect is described by this original skill record."); + var costs = new List(); + if (skill.SpConsumeValue != 0) + costs.Add(new BattleCost(1, (BattleValueMode)skill.SpConsumeImpactType, skill.SpConsumeValue)); + if (skill.MpConsumeValue != 0) + costs.Add(new BattleCost(2, (BattleValueMode)skill.MpConsumeImpactType, skill.MpConsumeValue)); + if (skill.SpecialConsumeType != -1) + { + costs.Add(new BattleCost(skill.SpecialConsumeType, (BattleValueMode)skill.SpecialConsumeImpactType, skill.SpecialConsumeValue)); + if (skill.SpecialConsumeType is not (10 or 16) && !(skill.SpecialConsumeType == 0 && BattleSpecialRules.UsesAbsoluteHpCost(BattleData.Variant, checked((int)skill.Id)))) + reasons.Add("Original special resource consumption requires a dedicated handler."); + } + var unlocks = new List(); + for (int index = 0; index < skill.CompositeSkillIds.Length; index++) + { + if (skill.CompositeSkillIds[index] == 0) + continue; + unlocks.Add(new BattleSkillUnlock(checked((int)skill.CompositeSkillIds[index]), checked((int)skill.CompositeRequiredSkillIds[index]), + skill.CompositeRequiredSkillLevels[index], skill.CompositeRequiredCurrentSkillLevels[index], skill.CompositeRequiredActorLevels[index])); + } + return new BattleAbilityDefinition(new BattleAbilityData + { + Id = checked((int)skill.Id), + Name = skill.Name, + IsMagic = type is >= 1 and <= 3 || fiveSpirit, + SkillTypeId = type, + Range = Range(skill.TargetRangeType, reasons), + ElementMask = elements, + SuccessRate = skill.SuccessRateLevel, + SpellRank = skill.Level, + NextSkillRequiredProficiency = skill.NextSkillRequiredProficiency, + LearningLevel = skill.LearningActorLevel, + NextSkillId = checked((int)skill.NextSkillId), + UsesBeforeLevelUp = skill.CumulativeUseThresholds.Select(value => (int)value).ToArray(), + Attributes = attributes, + States = states, + Costs = costs.ToArray(), + ApplicableIdentities = skill.ApplicableActors.Select(identity => (int)identity).ToArray(), + SpecialEffect = skill.SpecialSkillId, + Handler = handler, + Unlocks = unlocks.ToArray(), + UnsupportedReason = string.Join(" ", reasons) + }); + } + + internal static BattleAbilityDefinition Item(GameItemInfo item) + { + var reasons = new List(); + int type = (int)item.Type; + BattleSpecialHandler handler = BattleSpecialRules.AbilityHandler(BattleData.Variant, checked((int)item.Id), true, false, (int)item.ItemSpecialType); + if (type is not (1 or 2 or 3)) + reasons.Add("This original item category has no combat use command."); + if ((int)item.ItemSpecialType != 0 && handler == BattleSpecialHandler.None) + reasons.Add("Original item special handler " + (int)item.ItemSpecialType + " is not implemented."); +#if PAL3A + if (type is 1 or 2 or 3 && item.UnresolvedValue2FC != 0) + reasons.Add("The combat item uses an unresolved original value at +0x2fc."); +#endif + return new BattleAbilityDefinition(new BattleAbilityData + { + Id = checked((int)item.Id), + Name = item.Name, + IsItem = true, + IsTreasure = BattleSpecialRules.IsTreasure(BattleData.Variant, checked((int)item.Id)), + ItemType = type, + AiNullCureOperation = item.CombatStates.TryGetValue(ActorCombatStateType.ExpIncrease, out ItemCombatStateValue lastState) ? lastState.Flags : 0, + BattleUsable = item.PlaceOfUseType is PlaceOfUseType.Combat or PlaceOfUseType.Anywhere, + Range = Range(item.TargetRangeType, reasons), + ElementMask = Elements(item.ElementAttributes), + Attributes = Attributes(item.AttributeImpacts, reasons), + States = ItemStates(item, reasons), + ApplicableIdentities = item.ApplicableActors.Select(identity => (int)identity).ToArray(), + SpecialEffect = (int)item.ItemSpecialType, + Handler = handler, + UnsupportedReason = string.Join(" ", reasons) + }); + } + + internal static BattleActorDefinition Actor(BattleData data, BattleParticipant actor, string variant, BattleMagicSwordSnapshot cultivation = null) + { + CombatActorInfo info = data.Database.CombatActorInfos[actor.ActorId]; + bool main = info.Type == CombatActorType.MainActor; + int identity = BattleData.PlayerIdentity(actor.ActorId); + var reasons = new List(); + var equipment = new List(); + for (int slot = 0; slot < actor.Equipment.Length; slot++) + { + int id = actor.Equipment[slot]; + if (id == 0) + continue; + if (slot > 5 || !data.Database.GameItemInfos.TryGetValue(id, out GameItemInfo item)) + { + reasons.Add("Unknown equipment ID/slot " + id + "/" + slot + "."); + continue; + } + equipment.Add(Equipment(item, slot, identity, actor.MagicSword, + slot == 0 && BattleLoadoutRules.IsNativeDefaultWeapon(variant, actor), cultivation)); + } + var permanent = new HashSet(); + var initialStates = new List(); + if (!main) + { + foreach (var state in info.CombatStateImpactTypes.OrderBy(state => (int)state.Key)) + { + if ((int)state.Value == 0) + continue; + if ((int)state.Key < 23) + initialStates.Add((BattleState)state.Key); + else if (state.Key == ActorCombatStateType.PoisonResist) + permanent.Add(BattleState.PoisonResist); + } + } + if (!main && !string.IsNullOrEmpty(info.ModelId) && info.ModelId.StartsWith("b", StringComparison.OrdinalIgnoreCase)) + permanent.Add(BattleState.PoisonResist); + foreach (BattleEquipmentDefinition item in equipment.Where(item => item.Slot != 0)) + { + if (item.States.Any(state => state.State == BattleState.PoisonResist && state.Value != 0)) + permanent.Add(BattleState.PoisonResist); + } + if (actor.MagicSword != null && (variant != "PAL3" || identity != 0 || actor.Side != BattleSide.Ally)) + reasons.Add("Only PAL3 Jingtian can own the captured magic sword."); + if (main && identity < 0) + reasons.Add("This main-character form needs its original transformation rules."); + if (!main && info.SpecialActionId > 0) + reasons.Add("Original actor special action " + info.SpecialActionId + " needs a dedicated handler."); + bool moneyShield = variant == "PAL3" && actor.Equipment.Length >= 6 && actor.Equipment[1] == 80015 && actor.Equipment[2] == 84018 && actor.Equipment[3] == 83012 && + (actor.Equipment[4] == 8153 && actor.Equipment[5] == 8154 || actor.Equipment[4] == 8154 && actor.Equipment[5] == 8153); + BattleTargetRange normalRange = BattleTargetRange.None; + if (main) + { + BattleEquipmentDefinition weapon = equipment.FirstOrDefault(item => item.Slot == 0); + if (weapon == null) + reasons.Add("A verified physical attack range requires an equipped weapon."); + else + { + try + { + normalRange = BattlePhysicalAttackModes.WeaponRange(variant, (int)data.Database.GameItemInfos[weapon.Id].WeaponType, identity); + } + catch (NotSupportedException exception) + { + reasons.Add(exception.Message); + } + catch (ArgumentOutOfRangeException exception) + { + reasons.Add(exception.Message); + } + } + } + else + { + string unsupportedMode = BattlePhysicalAttackModes.UnsupportedReason(variant, checked((int)info.NormalAttackModeId)); + if (!string.IsNullOrEmpty(unsupportedMode)) + reasons.Add(unsupportedMode); + if (string.IsNullOrEmpty(unsupportedMode)) + normalRange = BattlePhysicalAttackModes.Range(checked((int)info.NormalAttackModeId)); + } + int attackElements = main ? equipment.Where(item => item.Slot == 0).Aggregate(0, (mask, item) => mask | item.ElementMask) : ActorElements(info); + int defenseElements = main ? equipment.Where(item => item.Slot != 0).Aggregate(0, (mask, item) => mask | item.ElementMask) : ActorElements(info); + var thresholds = new int[101]; + for (int level = 1; level < 100; level++) + thresholds[level] = data.Layout.LevelExperienceTable[level]; + thresholds[100] = int.MaxValue; + return new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = identity, + MagicSword = actor.MagicSword?.Capture(), + Boss = info.ModelId?.StartsWith("b", StringComparison.OrdinalIgnoreCase) == true, + CorpseItem = checked((int)info.CorpseId), + CorpseSkill = checked((int)info.CorpseSkillId), + CorpsePercent = info.CorpseSuccessRate, + Equipment = equipment.ToArray(), + PermanentStates = permanent.ToArray(), + InitialStates = initialStates.ToArray(), + PhysicalAttackElements = attackElements, + PhysicalDefenseElements = defenseElements, + PhysicalAttackElementValues = ElementValues(info, equipment, main, true), + PhysicalDefenseElementValues = ElementValues(info, equipment, main, false), + NormalAttackMode = checked((int)info.NormalAttackModeId), + NormalAttackRange = normalRange, + ExperienceReward = info.Experience, + MoneyReward = info.MoneyWhenKilled, + LootItem = checked((int)info.NormalLoot), + LootCount = info.NormalLootCount, + EscapePercent = (int)info.EscapeRate, + StealableMoney = Math.Max(0, (int)info.StealableMoneyAmount), + StealableItemId = checked((int)info.StealableItemId), + StealableItemCount = Math.Max(0, (int)info.StealableItemCount), + MoneyShield = moneyShield, + ExperienceThresholds = main ? thresholds : Array.Empty(), + AttributesByLevel = main && identity >= 0 ? Growth(info, identity, variant) : Array.Empty(), + GrowthUnsupportedReason = main && identity >= 0 ? "" : "Original player level growth is unavailable for this actor form.", + UnsupportedReason = string.Join(" ", reasons) + }); + } + + private static BattleEquipmentDefinition Equipment(GameItemInfo item, int slot, int identity, BattleMagicSword magicSword, + bool nativeDefault = false, BattleMagicSwordSnapshot cultivation = null) + { + var reasons = new List(); + int expected = slot switch + { + 0 => 11, + 1 => 8, + 2 => 7, + 3 => 9, + _ => 10 + }; + if ((int)item.Type != expected) + reasons.Add("The original item type does not match this equipment slot."); + if (identity < 0 || !nativeDefault && !item.ApplicableActors.Contains((PlayerActorId)identity)) + reasons.Add("This character cannot equip the original item."); + int special = (int)item.ItemSpecialType; + if (!BattleSpecialRules.SupportsEquipmentSpecial(BattleData.Variant, checked((int)item.Id), slot, special)) + reasons.Add("Original equipment special handler " + special + " is not implemented."); + if (item.Id == BattleMagicSwordRules.WeaponId && slot == 0 && + (BattleData.Variant != "PAL3" || identity == 0 && magicSword == null || identity != 0 && !nativeDefault)) + reasons.Add("Weapon 6603 needs PAL3 Jingtian and its original cultivation snapshot."); + BattleStatusEffect[] states = slot == 0 ? ItemStates(item, reasons) : PassiveEquipmentStates(item); + var recovery = new int[3]; + if (slot != 0) + { + for (int attribute = 0; attribute < 3; attribute++) + recovery[attribute] = item.AttributeImpacts.TryGetValue((ActorAttributeType)attribute, out AttributeImpact effect) ? effect.Value : 0; + } + return new BattleEquipmentDefinition(new BattleEquipmentData + { + Id = checked((int)item.Id), + Slot = slot, + WeaponType = slot == 0 ? (int)item.WeaponType : 0, + MagicSwordCultivation = nativeDefault && item.Id == BattleMagicSwordRules.WeaponId && identity != 0 + ? cultivation ?? new BattleMagicSword().Capture() : null, + StartupInvisibility = BattleData.Variant == "PAL3" && slot >= 4 && item.Id == 8114, + AttackStealPercent = slot != 0 && special == 23 ? 5 : 0, + Name = item.Name, + Attributes = Attributes(item.AttributeImpacts, reasons), + States = states, + ElementMask = Elements(item.ElementAttributes), + SpSaving = slot == 0 ? 0 : item.SpSavingPercentage, + MpSaving = slot == 0 ? 0 : item.MpSavingPercentage, + CriticalBonus = slot == 0 ? 0 : item.CriticalAttackAmplifyPercentage, + PhysicalReflectionPassive = slot >= 4 && item.Id == (BattleData.Variant == "PAL3" ? 8110 : 8108), + TechniqueSuccessBonus = slot == 0 ? 0 : item.SpecialSkillSuccessRate, + SpecialEffect = special, + RecoveryPerRound = recovery, + UnsupportedReason = string.Join(" ", reasons) + }); + } + + private static BattleAttributeEffect[] Attributes(Dictionary source, List reasons) + { + var result = new List(); + foreach (var pair in source.OrderBy(pair => (int)pair.Key)) + { + int mode = (int)pair.Value.Type; + if (mode < 0 || mode > 3) + reasons.Add("Unknown attribute mode " + mode + "."); + else + result.Add(new BattleAttributeEffect((int)pair.Key, (BattleValueMode)mode, pair.Value.Value)); + } + return result.ToArray(); + } + + private static BattleStatusEffect[] SkillStates(Dictionary source, List reasons) + { + var result = new List(); + foreach (var pair in source.OrderBy(pair => (int)pair.Key)) + { + int value = (int)pair.Value; + if (value is 1 or 2) + result.Add(new BattleStatusEffect((BattleState)pair.Key, value == 2, value)); + else if (value != 0) + reasons.Add("Unknown original state operation " + value + "."); + } + return result.ToArray(); + } + + private static BattleStatusEffect[] PassiveEquipmentStates(GameItemInfo item) + { + // Both released nonweapon initializers read only the poison-resist + // signed word at +0x2ee. Any nonzero value grants the permanent state; + // its Flags byte and all other state fields are ignored here. + return item.CombatStates.TryGetValue(ActorCombatStateType.PoisonResist, out ItemCombatStateValue resistance) && resistance.Value != 0 + ? new[] { new BattleStatusEffect(BattleState.PoisonResist, false, resistance.Value) } + : Array.Empty(); + } + + private static BattleStatusEffect[] ItemStates(GameItemInfo item, List reasons) + { + var result = new List(); + foreach (var pair in item.CombatStates.OrderBy(pair => (int)pair.Key)) + { + int value = pair.Value.Value; + if (item.Type == ItemType.Weapon) + { + // For weapons the byte is an enable flag, the short is a + // probability; the native handler always adds the first hit. + if (pair.Value.Flags != 0) + result.Add(new BattleStatusEffect((BattleState)pair.Key, false, value)); + } + else if (value is 1 or 2) + result.Add(new BattleStatusEffect((BattleState)pair.Key, value == 2, value)); + else if (value != 0) + reasons.Add("Unknown original item state value " + value + "."); + } + return result.ToArray(); + } + + private static BattleTargetRange Range(TargetRangeType range, List reasons) + { + int value = (int)range; + if (value < 0 || value > 6) + { + reasons.Add("Unknown original target range " + value + "."); + return BattleTargetRange.None; + } + return (BattleTargetRange)value; + } + + private static int Elements(IEnumerable source) => source.Aggregate(0, (mask, element) => mask | (1 << (int)element)); + + private static int ActorElements(CombatActorInfo info) => info.ElementAttributeValues.Aggregate(0, (mask, pair) => pair.Value == 0 ? mask : mask | (1 << ((int)pair.Key - 1))); + + private static int[] ElementValues(CombatActorInfo info, IEnumerable equipment, bool main, bool attack) + { + if (!main) + return Enumerable.Range(1, 5).Select(index => info.ElementAttributeValues[(ElementType)index]).ToArray(); + var result = new int[5]; + foreach (BattleEquipmentDefinition item in equipment.Where(item => attack ? item.Slot == 0 : item.Slot != 0)) + { + for (int element = 0; element < 5; element++) + { + if ((item.ElementMask & (1 << element)) != 0) + result[element]++; + } + } + return result; + } + + private static int[][] Growth(CombatActorInfo info, int identity, string variant) + { + var result = new int[101][]; + result[0] = new int[12]; + for (int level = 1; level <= 100; level++) + { + int[] values = Enumerable.Range(0, 12).Select(index => info.AttributeValues[(ActorAttributeType)index]).ToArray(); + if (variant == "PAL3") + { + values[0] = level * new[] { 8, 7, 9, 7, 9 }[identity] + new[] { 80, 75, 80, 60, 100 }[identity]; + values[1] = BattleBasicRules.Round((float)(Math.Sqrt(level) * 9 + new[] { 8, 6, 7, 5, 9 }[identity])); + values[2] = level * new[] { 4, 5, 4, 6, 4 }[identity] + new[] { 25, 25, 22, 30, 20 }[identity]; + values[3] = BattleBasicRules.Round(level * new[] { 4.5f, 4f, 4.5f, 4f, 5f }[identity] + new[] { 26, 24, 20, 22, 35 }[identity]); + values[4] = BattleBasicRules.Round(level * new[] { 3.3f, 3f, 3.5f, 3f, 3f }[identity] + new[] { 17, 13, 16, 16, 18 }[identity]); + } + else + { + values[0] = level * new[] { 8, 9, 7, 9, 9 }[identity] + new[] { 70, 80, 65, 85, 90 }[identity]; + values[1] = level + new[] { 8, 12, 6, 16, 10 }[identity]; + values[2] = level * new[] { 4, 3, 8, 6, 5 }[identity] + new[] { 20, 16, 40, 30, 24 }[identity]; + values[3] = BattleBasicRules.Round(level * new[] { 5f, 5.5f, 4.5f, 6f, 6f }[identity] + new[] { 20, 25, 18, 30, 28 }[identity]); + values[4] = BattleBasicRules.Round(level * new[] { 4f, 4f, 4f, 5f, 5f }[identity] + new[] { 18, 14, 16, 17, 20 }[identity]); + } + result[level] = values; + } + return result; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleDefinitionCompiler.cs.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleDefinitionCompiler.cs.meta new file mode 100644 index 00000000..68bacf9e --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleDefinitionCompiler.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1b16c66fbeb546ccaa63685ba6253469 diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleMusicResolver.cs b/Assets/Scripts/Editor/BattleEditor/Data/BattleMusicResolver.cs new file mode 100644 index 00000000..c546514c --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleMusicResolver.cs @@ -0,0 +1,41 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Core.Contract.Constants; + using Battle; + + // Standalone battles have no story city. Reverse the native scene table, and + // make the editor's deterministic choice explicit when that context is ambiguous. + public static class BattleMusicResolver + { + public static string Resolve(BattleData data, BattleScenario scenario, ICollection diagnostics) + { + if (!string.IsNullOrWhiteSpace(scenario.Music)) + return scenario.Music.Trim(); + var candidates = data.SceneMap.CombatSceneMapInfo + .Where(pair => pair.Value.Values.Contains(scenario.Scene, StringComparer.OrdinalIgnoreCase)) + .Select(pair => pair.Key.Split('_')[0]) + .Where(MusicConstants.CombatMusicInfo.ContainsKey) + .Select(city => MusicConstants.CombatMusicInfo[city]) + .GroupBy(track => track, StringComparer.OrdinalIgnoreCase) + .OrderByDescending(group => group.Count()).ThenBy(group => group.Key, StringComparer.Ordinal) + .ToArray(); + if (candidates.Length > 0) + { + if (candidates.Length > 1) + diagnostics?.Add($"Battle scene {scenario.Scene} is shared by story areas with different music. Editor default: {candidates[0].Key}; set Music to override."); + return candidates[0].Key; + } + string fallback = MusicConstants.CombatMusicInfo.Values.First(); + diagnostics?.Add($"Battle scene {scenario.Scene} has no regular story-area music mapping. Editor fallback: {fallback}; set Music to override."); + return fallback; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleMusicResolver.cs.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleMusicResolver.cs.meta new file mode 100644 index 00000000..f0760c56 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleMusicResolver.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 58cf9a136d5e4841be5269b5f545defa diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomEquipmentBuilder.cs b/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomEquipmentBuilder.cs new file mode 100644 index 00000000..2b75afa0 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomEquipmentBuilder.cs @@ -0,0 +1,83 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.Contract.Enums; + + // Original items have no equipment-level field. This editor-only tier is + // a relative ranking of actual attribute bonuses at level 50, per character + // and slot. It is authoring convenience, not an original equip restriction. + public sealed class BattleRandomEquipmentBuilder + { + private readonly BattleData _data; + private readonly Dictionary<(int actor, int slot), int[]> _tiers = new(); + + public BattleRandomEquipmentBuilder(BattleData data) => _data = data ?? throw new ArgumentNullException(nameof(data)); + + public void Equip(BattleParticipant actor, Random random) + { + if (actor == null || random == null) + throw new ArgumentNullException(actor == null ? nameof(actor) : nameof(random)); + if (actor.Side != BattleSide.Ally || BattleData.PlayerIdentity(actor.ActorId) < 0) + return; + actor.Equipment = new int[6]; + actor.UsesNativeDefaultWeapon = false; + actor.MagicSword = null; + for (int slot = 0; slot < actor.Equipment.Length; slot++) + { + int[] tiers = Tiers(actor.ActorId, slot); + if (tiers.Length == 0) + continue; + int center = (int)Math.Round((Math.Clamp(actor.Level, 1, 100) - 1) / 99d * (tiers.Length - 1)); + int radius = tiers.Length < 4 ? 0 : Math.Max(1, tiers.Length / 10); + int first = Math.Max(0, center - radius), last = Math.Min(tiers.Length - 1, center + radius); + int[] choices = tiers.Skip(first).Take(last - first + 1) + .Where(id => slot != 5 || id != actor.Equipment[4]).ToArray(); + actor.Equipment[slot] = choices.Length > 0 ? choices[random.Next(choices.Length)] : tiers[center]; + } + // Statuses are deliberately untouched. Weapon effects and armor + // passives are compiled and settled by the normal battle rules. + } + + private int[] Tiers(int actorId, int slot) + { + if (_tiers.TryGetValue((actorId, slot), out int[] cached)) + return cached; + int identity = BattleData.PlayerIdentity(actorId); + int type = slot switch + { + 0 => 11, + 1 => 8, + 2 => 7, + 3 => 9, + _ => 10 + }; + BattleParticipant probe = _data.CreateParticipant(actorId, BattleSide.Ally, BattleSlot.Water); + probe.Level = 50; + probe.AttributeSource = BattleAttributeSource.LevelGrowth; + probe.Equipment = new int[6]; + BattleActorDefinition bare = BattleDefinitionCompiler.Actor(_data, probe, BattleData.Variant); + int[] baseline = BattleAttributeCalculator.Calculate(probe, bare, BattleData.Variant); + var ranked = new List<(int id, double score, int price)>(); + foreach (var item in _data.Database.GameItemInfos.Values.Where(item => (int)item.Type == type && + item.Id != BattleMagicSwordRules.WeaponId && item.ApplicableActors.Contains((PlayerActorId)identity))) + { + probe.Equipment[slot] = checked((int)item.Id); + BattleActorDefinition definition = BattleDefinitionCompiler.Actor(_data, probe, BattleData.Variant); + if (definition.Equipment.Any(equipment => equipment.UnsupportedReason.Length > 0)) + continue; + int[] equipped = BattleAttributeCalculator.Calculate(probe, definition, BattleData.Variant); + double score = Enumerable.Range(0, 12).Sum(index => (equipped[index] - baseline[index]) / (double)Math.Max(1, baseline[index])); + ranked.Add((checked((int)item.Id), score, item.Price)); + } + return _tiers[(actorId, slot)] = ranked.OrderBy(item => item.score).ThenBy(item => item.price).ThenBy(item => item.id).Select(item => item.id).ToArray(); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomEquipmentBuilder.cs.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomEquipmentBuilder.cs.meta new file mode 100644 index 00000000..c1a43a14 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomEquipmentBuilder.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cea1bffc0a6849488d32f10649fd8fc4 diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomExampleBuilder.cs b/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomExampleBuilder.cs new file mode 100644 index 00000000..68b16fc6 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomExampleBuilder.cs @@ -0,0 +1,107 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using Core.Contract.Enums; + + // Uses a separate authoring RNG: generating examples never consumes battle RNG. + public sealed class BattleRandomExampleBuilder + { + private readonly BattleData _data; + private readonly int[] _allies; + private readonly IGrouping[] _enemyLevels; + private readonly BattleRandomEquipmentBuilder _equipment; + + public BattleRandomExampleBuilder(BattleData data) + { + _data = data ?? throw new ArgumentNullException(nameof(data)); + _equipment = new BattleRandomEquipmentBuilder(data); + _allies = ActorConstants.MainActorCombatActorIdMap.Values.OrderBy(id => id) + .Where(id => Available(id, BattleSide.Ally)).ToArray(); + _enemyLevels = data.Database.CombatActorInfos.OrderBy(pair => pair.Key) + .Where(pair => pair.Key > 0 && pair.Value.Type != CombatActorType.MainActor && + pair.Value.Level is >= 1 and <= 100 && pair.Value.AttributeValues[ActorAttributeType.Hp] > 0 && + pair.Value.SpecialActionId == 0 && data.Database.SkillInfos.ContainsKey((int)pair.Value.NormalAttackModeId)) + .Select(pair => pair.Key).Where(id => Available(id, BattleSide.Enemy)) + .GroupBy(id => data.Database.CombatActorInfos[id].Level).ToArray(); + if (_allies.Length == 0 || _enemyLevels.Length == 0 || data.Scenes.Length == 0) + throw new InvalidOperationException("No complete original-data roster or battle scene is available for random examples."); + } + + private bool Available(int id, BattleSide side) + { + if (!_data.Database.CombatActorInfos.ContainsKey(id)) + return false; + BattleParticipant actor = _data.CreateParticipant(id, side, BattleSlot.Water); + try + { + return _data.TryActionPath(actor, _data.IdleAction(actor), out _); + } + catch (Exception error) when (error is FileNotFoundException or DirectoryNotFoundException or InvalidDataException or + NotSupportedException or InvalidOperationException or FormatException) + { + // An incomplete resource set can still supply other test participants. + return false; + } + } + + public BattleScenario Create(Random random) + { + if (random == null) + throw new ArgumentNullException(nameof(random)); + BattleScenario example = BattleTestLoadoutBuilder.CreateScenario(_data); + example.Scene = _data.Scenes[random.Next(_data.Scenes.Length)]; + example.Seed = random.Next(); + example.SceneElement = (int)_data.SceneMap.CombatSceneElementTypeInfo.GetValueOrDefault(example.Scene); + IGrouping level = _enemyLevels[random.Next(_enemyLevels.Length)]; + int[] enemies = level.ToArray(); + int[] allies = Shuffle(_allies, random); + BattleSlot[] slots = Shuffle((BattleSlot[])Enum.GetValues(typeof(BattleSlot)), random); + int allyCount = Math.Min(4, allies.Length); + for (int index = 0; index < allyCount; index++) + { + BattleParticipant actor = _data.CreateTestParticipant(allies[index], BattleSide.Ally, slots[index]); + actor.Level = Math.Min(100, level.Key + 3); + actor.AttributeSource = BattleAttributeSource.LevelGrowth; + // The reader indexes by actual level; the original final level uses INT_MAX. + actor.Experience = actor.Level < _data.Layout.LevelExperienceTable.Length ? _data.Layout.LevelExperienceTable[actor.Level] : int.MaxValue; + _equipment.Equip(actor, random); + example.Participants.Add(actor); + } + slots = Shuffle(slots, random); + int enemyCount = random.Next(1, 7); + for (int index = 0; index < enemyCount; index++) + example.Participants.Add(_data.CreateParticipant(enemies[random.Next(enemies.Length)], BattleSide.Enemy, slots[index])); + + // Compile growth and equipment through the same adapter as a real battle. + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, _data.Capture(example)); + foreach (BattleParticipant actor in example.Participants.Where(actor => actor.Side == BattleSide.Ally)) + { + BattleActorDefinition definition = definitions.Actors[actor.InstanceId]; + actor.Attributes = BattleAttributeCalculator.Calculate(actor, definition, example.Variant); + actor.Vitals = actor.Attributes.Take(3).ToArray(); + } + return example; + } + + private static T[] Shuffle(IEnumerable source, Random random) + { + T[] values = source.ToArray(); + for (int index = values.Length - 1; index > 0; index--) + { + int other = random.Next(index + 1); + (values[index], values[other]) = (values[other], values[index]); + } + return values; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomExampleBuilder.cs.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomExampleBuilder.cs.meta new file mode 100644 index 00000000..177300cc --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleRandomExampleBuilder.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: aef3a87b82f8420ea162edc21bca9368 diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleSceneAppearance.cs b/Assets/Scripts/Editor/BattleEditor/Data/BattleSceneAppearance.cs new file mode 100644 index 00000000..f4c907fa --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleSceneAppearance.cs @@ -0,0 +1,118 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using Core.DataReader.Pol; + using Game.Rendering.Renderer; + using Game.Rendering.Toon; + + public readonly struct BattleSurfaceOverride + { + public int NodeIndex + { + get; + } + + public int MaterialGroupIndex + { + get; + } + + public string NodeName + { + get; + } + + public string Texture + { + get; + } + + public PolSurfaceAppearance Appearance + { + get; + } + + public BattleSurfaceOverride(int nodeIndex, int materialGroupIndex, string nodeName, string texture, PolSurfaceAppearance appearance) + { + if (nodeIndex < 0) + throw new ArgumentOutOfRangeException(nameof(nodeIndex), "Surface override indices cannot be negative."); + if (materialGroupIndex < 0) + throw new ArgumentOutOfRangeException(nameof(materialGroupIndex), "Surface override indices cannot be negative."); + if (string.IsNullOrWhiteSpace(nodeName) || string.IsNullOrWhiteSpace(texture)) + throw new ArgumentException("A surface override requires its expected node name and texture."); + appearance.Validate(); + NodeIndex = nodeIndex; + MaterialGroupIndex = materialGroupIndex; + NodeName = nodeName; + Texture = texture; + Appearance = appearance; + } + } + + /// Captured visual choices with explicit, resource-validated surface overrides. + public sealed class BattleSceneAppearance + { + public ToonLightingProfile Lighting + { + get; + } + + public IReadOnlyList Surfaces + { + get; + } + + public BattleSceneAppearance(ToonLightingProfile lighting, IEnumerable surfaces = null) + { + lighting.Validate(); + BattleSurfaceOverride[] captured = surfaces?.ToArray() ?? Array.Empty(); + var selected = new HashSet<(int Node, int Group)>(); + foreach (BattleSurfaceOverride surface in captured) + { + // A value type's default value also needs validation at this boundary. + if (surface.NodeIndex < 0 || surface.MaterialGroupIndex < 0 || + string.IsNullOrWhiteSpace(surface.NodeName) || string.IsNullOrWhiteSpace(surface.Texture)) + throw new ArgumentException("A surface override requires nonnegative indices, a node name and a texture.", nameof(surfaces)); + surface.Appearance.Validate(); + if (!selected.Add((surface.NodeIndex, surface.MaterialGroupIndex))) + throw new ArgumentException("Duplicate surface override selection.", nameof(surfaces)); + } + Lighting = lighting; + Surfaces = Array.AsReadOnly(captured); + } + + public Func ResolveSurfaces(PolFile model) + { + if (model == null) + throw new ArgumentNullException(nameof(model)); + if (Surfaces.Count == 0) + return null; + var selected = new Dictionary<(int Node, int Group), PolSurfaceAppearance>(); + foreach (BattleSurfaceOverride surface in Surfaces) + { + int node = surface.NodeIndex; + int group = surface.MaterialGroupIndex; + if (model.Meshes == null || model.NodeDescriptions == null || + node >= model.Meshes.Length || node >= model.NodeDescriptions.Length || + !string.Equals(model.NodeDescriptions[node].Name, surface.NodeName, StringComparison.Ordinal)) + throw new InvalidDataException($"Surface override node does not match this POL: {node} ({surface.NodeName})."); + PolTexture[] groups = model.Meshes[node].Textures; + if (groups == null || group >= groups.Length || + groups[group].Material.TextureFileNames == null || + !groups[group].Material.TextureFileNames.Contains(surface.Texture, StringComparer.OrdinalIgnoreCase)) + throw new InvalidDataException($"Surface override material does not match this POL: node {node}, group {group}, texture {surface.Texture}."); + selected.Add((node, group), surface.Appearance); + } + // The resolver owns this dictionary; neither authored arrays nor mutable POL arrays are captured. + return (node, group) => selected.TryGetValue((node, group), out PolSurfaceAppearance appearance) ? appearance : null; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleSceneAppearance.cs.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleSceneAppearance.cs.meta new file mode 100644 index 00000000..378a9bc1 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleSceneAppearance.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a7a517c79d104d25b015f3fe76114124 diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleTestLoadoutBuilder.cs b/Assets/Scripts/Editor/BattleEditor/Data/BattleTestLoadoutBuilder.cs new file mode 100644 index 00000000..1e534ed1 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleTestLoadoutBuilder.cs @@ -0,0 +1,50 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Linq; + using Battle; + using Core.Contract.Enums; + + // Editor-only initial state: unlock legal personal skills without changing + // growth, costs, equipment, form restrictions or the original-data factory. + public static class BattleTestLoadoutBuilder + { + // A test inventory belongs to a newly authored scenario, never to a + // loaded preset or the game's persistent inventory. + public static BattleScenario CreateScenario(BattleData data) + { + var scenario = new BattleScenario { Variant = BattleData.Variant, DataFingerprint = data?.Fingerprint ?? "" }; + if (data == null) + return scenario; + foreach (BattleAbilityDefinition item in data.Database.GameItemInfos.Values.Where(item => item.Id > 0) + .Select(BattleDefinitionCompiler.Item).Where(item => item.BattleUsable && item.Supported).OrderBy(item => item.Id)) + { + scenario.Items.Add(new BattleItem { Id = item.Id, Count = 99 }); + if (item.IsTreasure) + scenario.TreasureUses.Add(new BattleItem { Id = item.Id, Count = 3 }); + } + return scenario; + } + + public static BattleParticipant Create(BattleData data, int actorId, BattleSide side, BattleSlot slot) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + BattleParticipant actor = data.CreateParticipant(actorId, side, slot); + int identity = BattleData.PlayerIdentity(actorId); + if (side != BattleSide.Ally || identity < 0 || data.Database.CombatActorInfos[actorId].Type != CombatActorType.MainActor) + return actor; + actor.Skills = data.Database.SkillOrder.Where(id => id > 0).Select(id => data.Database.SkillInfos[id]) + .Where(skill => (int)skill.Type is >= 0 and <= 3 && skill.ApplicableActors.Contains((PlayerActorId)identity)) + .Select(skill => new BattleSkill { Id = checked((int)skill.Id), Level = 4, Mastered = true }).ToList(); + // Weapon magic is selected through the captured magic sword. The + // PAL3A five-spirit wheel and Nangong form use their own commands. + return actor; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleTestLoadoutBuilder.cs.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleTestLoadoutBuilder.cs.meta new file mode 100644 index 00000000..8a4771db --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleTestLoadoutBuilder.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0422cd1eba8743e295f93f98c118b606 diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingCatalog.cs b/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingCatalog.cs new file mode 100644 index 00000000..5a109490 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingCatalog.cs @@ -0,0 +1,136 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.IO; + using Game.Rendering.Renderer; + using Game.Rendering.Toon; + using Newtonsoft.Json; + using UnityEditor; + using UnityEngine; + + /// Authored visual choices for battle resources, not original binary fields or gameplay rules. + public static class BattleToonLightingCatalog + { + private sealed class Document + { + public int schemaVersion = 0; + public Entry[] profiles = null; + } + + private sealed class Entry + { + public string variant = null; + public string scene = null; + public string label = null; + public float[] keyEuler = null; + public float temperature = float.NaN; + public float[] tint = null; + public float intensity = float.NaN; + public float shadowStrength = float.NaN; + public float characterFill = float.NaN; + public float contrast = float.NaN; + public float bakedStrength = float.NaN; + public float contactStrength = float.NaN; + public bool night = false; + public bool indoors = false; + public BackgroundSurface[] backgroundSurfaces = null; + public SurfaceReference[] geometricNormalSurfaces = null; + + public BattleSceneAppearance Capture() + { + if (keyEuler == null || keyEuler.Length != 3 || tint == null || tint.Length != 3) + throw new InvalidDataException("A scene lighting entry requires three rotation and tint components."); + foreach (float value in keyEuler) + if (!float.IsFinite(value) || Math.Abs(value) > 360) + throw new InvalidDataException("Scene lighting rotation is not finite or is outside one revolution."); + if (!float.IsFinite(temperature) || temperature < 1000 || temperature > 12000) + throw new InvalidDataException("Scene lighting temperature must be between 1000K and 12000K."); + foreach (float value in tint) + if (!float.IsFinite(value) || value < 0 || value > 1) + throw new InvalidDataException("Scene lighting tint must be finite and between zero and one."); + Color kelvin = Mathf.CorrelatedColorTemperatureToRGB(temperature); + Color color = new(kelvin.r * tint[0], kelvin.g * tint[1], kelvin.b * tint[2], 1); + var lighting = new ToonLightingProfile(Quaternion.Euler(keyEuler[0], keyEuler[1], keyEuler[2]), color, + intensity, shadowStrength, characterFill, contrast, bakedStrength, contactStrength, night, indoors); + var surfaces = new List(); + if (backgroundSurfaces != null) + foreach (BackgroundSurface surface in backgroundSurfaces) + { + if (surface == null) + throw new InvalidDataException("A background surface cannot be null."); + surfaces.Add(surface.Capture(PolSurfaceAppearance.Painted(surface.brightness))); + } + if (geometricNormalSurfaces != null) + foreach (SurfaceReference surface in geometricNormalSurfaces) + { + if (surface == null) + throw new InvalidDataException("A geometric-normal surface cannot be null."); + surfaces.Add(surface.Capture(PolSurfaceAppearance.RecalculateNormals)); + } + return new BattleSceneAppearance(lighting, surfaces); + } + } + + private class SurfaceReference + { + public int nodeIndex = -1; + public int materialGroupIndex = -1; + public string nodeName = null; + public string texture = null; + + public BattleSurfaceOverride Capture(PolSurfaceAppearance appearance) => + new(nodeIndex, materialGroupIndex, nodeName, texture, appearance); + } + + private sealed class BackgroundSurface : SurfaceReference + { + public float brightness = 1; + } + + private const string ProfileAssetPath = "Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingProfiles.json"; + + private static string _text; + private static Dictionary _profiles; + + public static ToonLightingProfile Resolve(string variant, string scene) => ResolveScene(variant, scene).Lighting; + + public static BattleSceneAppearance ResolveScene(string variant, string scene) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown battle lighting variant.", nameof(variant)); + TextAsset asset = AssetDatabase.LoadAssetAtPath(ProfileAssetPath); + if (asset == null) + throw new FileNotFoundException("Battle Editor lighting profiles could not be loaded.", ProfileAssetPath); + string text = asset.text; + if (_profiles == null || text != _text) + { + Dictionary candidate = Parse(text); + _profiles = candidate; + _text = text; + } + return _profiles.TryGetValue(variant + "/" + scene, out BattleSceneAppearance profile) ? profile : new BattleSceneAppearance(ToonLightingProfile.Default); + } + + private static Dictionary Parse(string text) + { + var profiles = new Dictionary(StringComparer.OrdinalIgnoreCase); + var document = JsonConvert.DeserializeObject(text, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error, TypeNameHandling = TypeNameHandling.None }); + if (document == null || document.schemaVersion != 1 || document.profiles == null) + throw new InvalidDataException("Unsupported or incomplete battle lighting document."); + foreach (Entry entry in document.profiles) + { + if (entry == null || entry.variant is not ("PAL3" or "PAL3A") || string.IsNullOrWhiteSpace(entry.scene)) + throw new InvalidDataException("A scene lighting entry requires a supported variant and scene ID."); + if (!profiles.TryAdd(entry.variant + "/" + entry.scene, entry.Capture())) + throw new InvalidDataException("Duplicate battle lighting profile: " + entry.variant + "/" + entry.scene); + } + return profiles; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingCatalog.cs.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingCatalog.cs.meta new file mode 100644 index 00000000..c04fcad3 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingCatalog.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 98266e20dc584762865a01d6ff39ba00 diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingProfiles.json b/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingProfiles.json new file mode 100644 index 00000000..c4f85584 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingProfiles.json @@ -0,0 +1,3434 @@ +{ + "schemaVersion": 1, + "profiles": [ + { + "variant": "PAL3", + "scene": "Z01", + "label": "Z01", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.98, + 0.96 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "4.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 1, + "nodeName": "Plane01", + "texture": "5.tga" + }, + { + "nodeIndex": 0, + "materialGroupIndex": 1, + "nodeName": "Sphere01", + "texture": "3.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z02", + "label": "Z02", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7500, + "tint": [ + 0.96, + 0.98, + 1 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z03", + "label": "Z03", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 0.98, + 1, + 1 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z04", + "label": "Z04", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 0.85, + "shadowStrength": 0.95, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.75, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z04A", + "label": "Z04A", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "4.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z05", + "label": "Z05", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 1, + "nodeName": "Mesh07", + "texture": "5.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Mesh08", + "texture": "6.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z06", + "label": "Z06", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "1.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "2.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 1, + "nodeName": "Plane01", + "texture": "3.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z07", + "label": "Z07", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7500, + "tint": [ + 0.94, + 0.98, + 1 + ], + "intensity": 0.95, + "shadowStrength": 0.95, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "geometricNormalSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Cylinder01", + "texture": "m23-3-02.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z08", + "label": "Z08", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 58, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "1.tga" + }, + { + "nodeIndex": 58, + "materialGroupIndex": 1, + "nodeName": "Plane01", + "texture": "2.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z09", + "label": "Z09", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z10", + "label": "Z10", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.9, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.55, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z11", + "label": "Z11", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 5500, + "tint": [ + 1, + 0.98, + 0.95 + ], + "intensity": 0.95, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "4.tga" + }, + { + "nodeIndex": 21, + "materialGroupIndex": 1, + "nodeName": "kuang", + "texture": "3.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 21, + "materialGroupIndex": 0, + "nodeName": "kuang", + "texture": "M03-01.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z12", + "label": "Z12", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.8, + "contrast": 1, + "bakedStrength": 0.6, + "contactStrength": 1.1, + "night": false, + "indoors": true + }, + { + "variant": "PAL3", + "scene": "Z13", + "label": "Z13", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 4500, + "tint": [ + 1, + 0.97, + 0.93 + ], + "intensity": 1.05, + "shadowStrength": 0.95, + "characterFill": 0.8, + "contrast": 1, + "bakedStrength": 0.6, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z14", + "label": "Z14", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7500, + "tint": [ + 0.96, + 1, + 1 + ], + "intensity": 0.9, + "shadowStrength": 0.95, + "characterFill": 0.8, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z15", + "label": "Z15", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 0.98, + 0.98, + 1 + ], + "intensity": 1.1, + "shadowStrength": 0.95, + "characterFill": 0.75, + "contrast": 1, + "bakedStrength": 0.45, + "contactStrength": 0.9, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z16", + "label": "Z16", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 5700, + "tint": [ + 1, + 0.98, + 0.96 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.8, + "contrast": 1, + "bakedStrength": 0.55, + "contactStrength": 1.1, + "night": false, + "indoors": true + }, + { + "variant": "PAL3", + "scene": "Z17", + "label": "Z17", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z19", + "label": "Z19", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z20", + "label": "Z20", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "geometricNormalSurfaces": [ + { + "nodeIndex": 70, + "materialGroupIndex": 0, + "nodeName": "kuang", + "texture": "01.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z21", + "label": "Z21", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "6.tga" + }, + { + "nodeIndex": 0, + "materialGroupIndex": 1, + "nodeName": "Plane01", + "texture": "7.tga" + }, + { + "nodeIndex": 9, + "materialGroupIndex": 1, + "nodeName": "Object01", + "texture": "5.tga" + }, + { + "nodeIndex": 9, + "materialGroupIndex": 2, + "nodeName": "Object01", + "texture": "4.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z22", + "label": "Z22", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.99, + 0.98 + ], + "intensity": 1.05, + "shadowStrength": 0.9, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.55, + "contactStrength": 1.05, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "1.tga" + }, + { + "nodeIndex": 40, + "materialGroupIndex": 2, + "nodeName": "kuang", + "texture": "2.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 40, + "materialGroupIndex": 0, + "nodeName": "kuang", + "texture": "4.tga" + }, + { + "nodeIndex": 40, + "materialGroupIndex": 1, + "nodeName": "kuang", + "texture": "5.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z23", + "label": "Z23", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 6800, + "tint": [ + 1, + 0.98, + 0.96 + ], + "intensity": 1, + "shadowStrength": 0.85, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 99, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "1.tga" + }, + { + "nodeIndex": 99, + "materialGroupIndex": 1, + "nodeName": "Plane01", + "texture": "2.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z24", + "label": "Z24", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "tian", + "texture": "2.tga" + }, + { + "nodeIndex": 9, + "materialGroupIndex": 1, + "nodeName": "kuang", + "texture": "1.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 9, + "materialGroupIndex": 0, + "nodeName": "kuang", + "texture": "dimian-03.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z25", + "label": "Z25", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 30, + "materialGroupIndex": 0, + "nodeName": "tian", + "texture": "2.tga" + }, + { + "nodeIndex": 31, + "materialGroupIndex": 1, + "nodeName": "kuang", + "texture": "1.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 31, + "materialGroupIndex": 0, + "nodeName": "kuang", + "texture": "dimian-03.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z26", + "label": "Z26", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 0.8, + "shadowStrength": 0.95, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.8, + "contactStrength": 1.1, + "night": false, + "indoors": true + }, + { + "variant": "PAL3", + "scene": "Z27", + "label": "Z27", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 8000, + "tint": [ + 0.95, + 0.98, + 1 + ], + "intensity": 1.15, + "shadowStrength": 0.85, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.7, + "contactStrength": 1.0, + "night": true, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z28", + "label": "Z28", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 0.98, + 1, + 1 + ], + "intensity": 0.92, + "shadowStrength": 0.9, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.0, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "yun.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "yun.tga" + }, + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "Plane02", + "texture": "yun.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z29", + "label": "Z29", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 4500, + "tint": [ + 1, + 0.97, + 0.93 + ], + "intensity": 0.85, + "shadowStrength": 0.95, + "characterFill": 0.8, + "contrast": 1, + "bakedStrength": 0.7, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z30", + "label": "Z30", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.98, + 0.96 + ], + "intensity": 1, + "shadowStrength": 0.85, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.6, + "contactStrength": 1.05, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 15, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "2.tga" + }, + { + "nodeIndex": 37, + "materialGroupIndex": 1, + "nodeName": "kuang", + "texture": "1.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 37, + "materialGroupIndex": 0, + "nodeName": "kuang", + "texture": "M02_1_19.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z31", + "label": "Z31", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z32", + "label": "Z32", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 4500, + "tint": [ + 1, + 0.97, + 0.93 + ], + "intensity": 1.15, + "shadowStrength": 0.9, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.55, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z33", + "label": "Z33", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 1, + 0.98, + 0.96 + ], + "intensity": 1, + "shadowStrength": 0.9, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "99.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z34", + "label": "Z34", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 0.96, + 1, + 1 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z35", + "label": "Z35", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.6, + "contactStrength": 1.1, + "night": false, + "indoors": true + }, + { + "variant": "PAL3", + "scene": "Z36", + "label": "Z36", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 5500, + "tint": [ + 1, + 0.98, + 0.96 + ], + "intensity": 0.95, + "shadowStrength": 0.95, + "characterFill": 0.8, + "contrast": 1, + "bakedStrength": 0.6, + "contactStrength": 1.25, + "night": false, + "indoors": true + }, + { + "variant": "PAL3", + "scene": "Z37", + "label": "Z37", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 0.98, + 1, + 1 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "5.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Object01", + "texture": "4.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 1, + "nodeName": "Object01", + "texture": "3.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z38", + "label": "Z38", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 0.85, + "shadowStrength": 0.95, + "characterFill": 0.8, + "contrast": 1, + "bakedStrength": 0.8, + "contactStrength": 1.1, + "night": false, + "indoors": true + }, + { + "variant": "PAL3", + "scene": "Z39", + "label": "Z39", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 1, + 0.96, + 1 + ], + "intensity": 0.9, + "shadowStrength": 0.95, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.85, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Cylinder02", + "texture": "m25-3-06.tga" + }, + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "Plane03", + "texture": "m25-3-06.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z40", + "label": "Z40", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "5.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Object01", + "texture": "3.tga" + }, + { + "nodeIndex": 3, + "materialGroupIndex": 0, + "nodeName": "Plane02", + "texture": "4.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z41", + "label": "Z41", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 0.94, + 1, + 0.98 + ], + "intensity": 0.9, + "shadowStrength": 0.95, + "characterFill": 0.8, + "contrast": 1, + "bakedStrength": 0.6, + "contactStrength": 1.1, + "night": false, + "indoors": false + }, + { + "variant": "PAL3", + "scene": "Z42", + "label": "Z42", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 1, + "shadowStrength": 0.95, + "characterFill": 0.9, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "1.tga" + }, + { + "nodeIndex": 3, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "2.tga" + }, + { + "nodeIndex": 3, + "materialGroupIndex": 1, + "nodeName": "Plane01", + "texture": "3.tga" + }, + { + "nodeIndex": 4, + "materialGroupIndex": 0, + "nodeName": "Object01", + "texture": "2.tga" + }, + { + "nodeIndex": 4, + "materialGroupIndex": 1, + "nodeName": "Object01", + "texture": "3.tga" + }, + { + "nodeIndex": 5, + "materialGroupIndex": 0, + "nodeName": "yun1", + "texture": "4.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z43", + "label": "Z43", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7200, + "tint": [ + 0.98, + 0.96, + 1 + ], + "intensity": 0.95, + "shadowStrength": 0.95, + "characterFill": 0.8, + "contrast": 1, + "bakedStrength": 0.7, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "geometricNormalSurfaces": [ + { + "nodeIndex": 6, + "materialGroupIndex": 0, + "nodeName": "Mesh01", + "texture": "M08_2-01.tga" + } + ] + }, + { + "variant": "PAL3", + "scene": "Z44", + "label": "Z44", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 0.97, + 1, + 1 + ], + "intensity": 1, + "shadowStrength": 0.9, + "characterFill": 0.85, + "contrast": 1, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Cylinder02", + "texture": "m25-3-06.tga" + }, + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "Plane03", + "texture": "m25-3-06.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M01A", + "label": "草地纹理和石径清晰", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 0.9, + "shadowStrength": 0.82, + "characterFill": 0.82, + "contrast": 0.85, + "bakedStrength": 0.65, + "contactStrength": 1.0, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 8, + "materialGroupIndex": 0, + "nodeName": "Cylinder01", + "texture": "9.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M01B", + "label": "山坡地纹仍可读,Toon地面比原生略白,角色同样偏白", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 0.85, + "shadowStrength": 0.8, + "characterFill": 0.8, + "contrast": 0.8, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 8, + "materialGroupIndex": 0, + "nodeName": "Cylinder02", + "texture": "bj.tga" + }, + { + "nodeIndex": 9, + "materialGroupIndex": 0, + "nodeName": "Object01", + "texture": "9.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M02", + "label": "灰石墙/地和金色八卦台可读,Toon台面较黄亮,人物肤色与紫白服装过亮,室内链柱暗部完整", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6800, + "tint": [ + 1, + 1, + 1 + ], + "intensity": 0.8, + "shadowStrength": 0.65, + "characterFill": 0.75, + "contrast": 0.75, + "bakedStrength": 0.65, + "contactStrength": 1.0, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M02a", + "label": "逐图与M02一致的石室平台构图", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6800, + "tint": [ + 1, + 1, + 1 + ], + "intensity": 0.8, + "shadowStrength": 0.65, + "characterFill": 0.75, + "contrast": 0.75, + "bakedStrength": 0.65, + "contactStrength": 1.0, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M03A", + "label": "沙地颗粒与石块未糊,青绿水体保留", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 0.88, + "shadowStrength": 0.82, + "characterFill": 0.8, + "contrast": 0.8, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 13, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "beij.tga" + }, + { + "nodeIndex": 35, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "9.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M03B", + "label": "花草与根须保真,原生青绿亮斑仍在", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6500, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 0.9, + "shadowStrength": 0.75, + "characterFill": 0.82, + "contrast": 0.8, + "bakedStrength": 0.5, + "contactStrength": 1.0, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 37, + "materialGroupIndex": 0, + "nodeName": "Cylinder01", + "texture": "2.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M04A", + "label": "紫晶矿洞的晶体分面、碎木和紫色地纹完整,Toon石墙尚清楚", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7600, + "tint": [ + 0.92, + 0.88, + 1 + ], + "intensity": 0.75, + "shadowStrength": 0.65, + "characterFill": 0.68, + "contrast": 0.85, + "bakedStrength": 0.65, + "contactStrength": 1.0, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M04B", + "label": "冰紫岩地、洞壁和紫晶分面清楚,Toon暖白人物脱离冷紫环境", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7600, + "tint": [ + 0.92, + 0.88, + 1 + ], + "intensity": 0.72, + "shadowStrength": 0.65, + "characterFill": 0.68, + "contrast": 0.8, + "bakedStrength": 0.65, + "contactStrength": 1.0, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M05A", + "label": "蓝色鳞纹地砖、金属边钉完整", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7400, + "tint": [ + 0.94, + 0.97, + 1 + ], + "intensity": 0.78, + "shadowStrength": 0.65, + "characterFill": 0.72, + "contrast": 0.85, + "bakedStrength": 0.7, + "contactStrength": 1.25, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M05B", + "label": "金属悬桥绿纹和铆钉清晰,Toon绿纹比原生稍灰,人物明显亮于桥", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 1, + 1, + 1 + ], + "intensity": 0.8, + "shadowStrength": 0.7, + "characterFill": 0.72, + "contrast": 0.85, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M05C", + "label": "浅蓝石桥裂纹仍可见,Toon两端白色雕纹台和人物较亮", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 0.96, + 0.98, + 1 + ], + "intensity": 0.75, + "shadowStrength": 0.7, + "characterFill": 0.72, + "contrast": 0.75, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M05D", + "label": "浅白地砖和粉紫云纹在Toon仍清晰,但台面整体更白,人物偏白", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6800, + "tint": [ + 1, + 1, + 1 + ], + "intensity": 0.74, + "shadowStrength": 0.68, + "characterFill": 0.72, + "contrast": 0.8, + "bakedStrength": 0.65, + "contactStrength": 0.95, + "night": false, + "indoors": true, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "di.tga" + }, + { + "nodeIndex": 0, + "materialGroupIndex": 1, + "nodeName": "Plane01", + "texture": "bj.tga" + }, + { + "nodeIndex": 6, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "di.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M06A", + "label": "骨刺、枯木、黄沙颗粒保真", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 5600, + "tint": [ + 1, + 0.98, + 0.94 + ], + "intensity": 1.05, + "shadowStrength": 0.75, + "characterFill": 0.8, + "contrast": 0.65, + "bakedStrength": 0.5, + "contactStrength": 1.0, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 27, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "6.tga" + }, + { + "nodeIndex": 28, + "materialGroupIndex": 5, + "nodeName": "Object01", + "texture": "bj.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M06B", + "label": "整片沙地在Toon更接近褐黄而不是原生亮黄", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 5600, + "tint": [ + 1, + 0.98, + 0.94 + ], + "intensity": 1.0, + "shadowStrength": 0.78, + "characterFill": 0.8, + "contrast": 0.7, + "bakedStrength": 0.5, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 24, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "6.tga" + }, + { + "nodeIndex": 25, + "materialGroupIndex": 1, + "nodeName": "Cylinder02", + "texture": "bj.tga", + "brightness": 0.86 + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 25, + "materialGroupIndex": 0, + "nodeName": "Cylinder02", + "texture": "di.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M06C", + "label": "冰纹、碎晶和紫蓝壁面清晰", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 8500, + "tint": [ + 0.9, + 0.95, + 1 + ], + "intensity": 0.85, + "shadowStrength": 0.55, + "characterFill": 0.7, + "contrast": 0.65, + "bakedStrength": 0.45, + "contactStrength": 0.85, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "m06d", + "label": "白冰地面仍见细颗粒,Toon冰柱顶面较白且皮肤偏暖,背面大面积阴影显重", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 8500, + "tint": [ + 0.9, + 0.94, + 1 + ], + "intensity": 0.8, + "shadowStrength": 0.55, + "characterFill": 0.7, + "contrast": 0.65, + "bakedStrength": 0.45, + "contactStrength": 0.85, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M07A", + "label": "土黄石刻台、壁画和青水未失纹理", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 6000, + "tint": [ + 1, + 0.98, + 0.94 + ], + "intensity": 0.78, + "shadowStrength": 0.65, + "characterFill": 0.72, + "contrast": 0.8, + "bakedStrength": 0.65, + "contactStrength": 0.95, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M07B", + "label": "白玉台面还有云纹,但Toon明显发亮偏白,人物高光亦强", + "keyEuler": [ + 72, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 1, + 1, + 1 + ], + "intensity": 0.65, + "shadowStrength": 0.45, + "characterFill": 0.7, + "contrast": 0.7, + "bakedStrength": 0.65, + "contactStrength": 0.7, + "night": false, + "indoors": true, + "backgroundSurfaces": [ + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "beij2.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M07C", + "label": "青绿斜坡与铆钉、兽纹内墙可读,Toon角色偏亮,走廊保持冷青", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7200, + "tint": [ + 1, + 1, + 1 + ], + "intensity": 0.75, + "shadowStrength": 0.6, + "characterFill": 0.72, + "contrast": 0.8, + "bakedStrength": 0.65, + "contactStrength": 0.95, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "m08a", + "label": "荧光橙坑与蓝紫花纹在两模式均保留,Toon地面稍黄、肤色偏白,前景树影变重", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7200, + "tint": [ + 0.94, + 0.95, + 1 + ], + "intensity": 0.82, + "shadowStrength": 0.65, + "characterFill": 0.72, + "contrast": 0.85, + "bakedStrength": 0.55, + "contactStrength": 1.0, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 15, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "111.tga" + }, + { + "nodeIndex": 49, + "materialGroupIndex": 1, + "nodeName": "Cylinder01", + "texture": "m08_tex_shi bi2.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 11, + "nodeName": "Object16", + "texture": "6.tga" + }, + { + "nodeIndex": 0, + "materialGroupIndex": 14, + "nodeName": "Object16", + "texture": "m08_tex_23.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "m08b", + "label": "灰紫土路、青水与荧光花完整", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7600, + "tint": [ + 0.92, + 0.95, + 1 + ], + "intensity": 0.78, + "shadowStrength": 0.6, + "characterFill": 0.72, + "contrast": 0.8, + "bakedStrength": 0.55, + "contactStrength": 1.0, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 42, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "111.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M09", + "label": "土黄院地、裂墙和八卦石纹清晰", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 6200, + "tint": [ + 1, + 0.98, + 0.95 + ], + "intensity": 0.85, + "shadowStrength": 0.68, + "characterFill": 0.78, + "contrast": 0.8, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3A", + "scene": "m09a", + "label": "土黄地面、八卦石纹与裂墙保持清晰,Toon地面略亮,人物肤色奶白,墙/台面投影比原生更硬", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 6200, + "tint": [ + 1, + 0.98, + 0.95 + ], + "intensity": 0.85, + "shadowStrength": 0.68, + "characterFill": 0.78, + "contrast": 0.8, + "bakedStrength": 0.65, + "contactStrength": 1.25, + "night": false, + "indoors": false + }, + { + "variant": "PAL3A", + "scene": "M10a", + "label": "灰蓝粗石/冰质路径和青色链柱纹理完整", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7600, + "tint": [ + 0.96, + 0.98, + 1 + ], + "intensity": 0.85, + "shadowStrength": 0.7, + "characterFill": 0.75, + "contrast": 0.85, + "bakedStrength": 0.65, + "contactStrength": 1, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "cylinder01", + "texture": "lhm001.tga" + }, + { + "nodeIndex": 52, + "materialGroupIndex": 0, + "nodeName": "object01", + "texture": "lhm002.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M10B", + "label": "橙红岩面和金黄符文纹理完整,Toon亮部稍平、暗沟仍清楚", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 5600, + "tint": [ + 1, + 0.97, + 0.91 + ], + "intensity": 0.8, + "shadowStrength": 0.65, + "characterFill": 0.7, + "contrast": 0.85, + "bakedStrength": 0.7, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Cylinder01", + "texture": "lhm003.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Object01", + "texture": "lhm004.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M10Ba", + "label": "独立核对后与M10B同为橙红符文通道", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 5600, + "tint": [ + 1, + 0.97, + 0.91 + ], + "intensity": 0.8, + "shadowStrength": 0.65, + "characterFill": 0.7, + "contrast": 0.85, + "bakedStrength": 0.7, + "contactStrength": 1.25, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Cylinder01", + "texture": "lhm003.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Object01", + "texture": "lhm004.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "m11a", + "label": "熔岩环绕的封闭石台和机械侧墙清楚", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 4500, + "tint": [ + 1, + 0.9, + 0.78 + ], + "intensity": 0.7, + "shadowStrength": 0.55, + "characterFill": 0.6, + "contrast": 0.8, + "bakedStrength": 0.7, + "contactStrength": 0.85, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "m12A", + "label": "浅青石板、镶边和桥面细纹完整,Toon板面稍白、肤色奶白", + "keyEuler": [ + 72, + -30, + 0 + ], + "temperature": 7400, + "tint": [ + 0.95, + 1, + 1 + ], + "intensity": 0.85, + "shadowStrength": 0.5, + "characterFill": 0.75, + "contrast": 0.7, + "bakedStrength": 0.6, + "contactStrength": 0.9, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Cone01", + "texture": "a.tga" + }, + { + "nodeIndex": 4, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "B.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "m12b", + "label": "阴阳圆纹、台阶裂缝和青石细纹完整,发亮圆纹在原生已较亮", + "keyEuler": [ + 72, + -30, + 0 + ], + "temperature": 7400, + "tint": [ + 0.95, + 1, + 1 + ], + "intensity": 0.85, + "shadowStrength": 0.5, + "characterFill": 0.75, + "contrast": 0.7, + "bakedStrength": 0.6, + "contactStrength": 0.9, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "B.tga" + }, + { + "nodeIndex": 6, + "materialGroupIndex": 0, + "nodeName": "Cone01", + "texture": "a.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "m12c", + "label": "浅青长台的细纹、边缘黑纹和围栏清楚,Toon台面更白、肤色过白,人物剪影较原生更重", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 7400, + "tint": [ + 0.95, + 1, + 1 + ], + "intensity": 0.8, + "shadowStrength": 0.55, + "characterFill": 0.72, + "contrast": 0.75, + "bakedStrength": 0.6, + "contactStrength": 0.9, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "B.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "m13a", + "label": "红色裂石悬台", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 4800, + "tint": [ + 1, + 0.94, + 0.88 + ], + "intensity": 0.76, + "shadowStrength": 0.62, + "characterFill": 0.52, + "contrast": 0.72, + "bakedStrength": 0.78, + "contactStrength": 0.9, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "b.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Cone01", + "texture": "a.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "m13b", + "label": "红黑龙纹悬台", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 4700, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 0.74, + "shadowStrength": 0.6, + "characterFill": 0.5, + "contrast": 0.7, + "bakedStrength": 0.8, + "contactStrength": 0.9, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Cone01", + "texture": "a.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "m13c", + "label": "红黑龙纹多层台", + "keyEuler": [ + 58, + -30, + 0 + ], + "temperature": 4700, + "tint": [ + 1, + 0.94, + 0.86 + ], + "intensity": 0.73, + "shadowStrength": 0.6, + "characterFill": 0.5, + "contrast": 0.7, + "bakedStrength": 0.82, + "contactStrength": 0.95, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "b.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Cone01", + "texture": "a.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "m14a", + "label": "蓝水背景浅沙环台", + "keyEuler": [ + 70, + -30, + 0 + ], + "temperature": 8200, + "tint": [ + 0.9, + 0.98, + 1 + ], + "intensity": 0.87, + "shadowStrength": 0.62, + "characterFill": 0.58, + "contrast": 0.58, + "bakedStrength": 0.76, + "contactStrength": 0.85, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "lhm0001.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Plane02", + "texture": "w0001.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 3, + "materialGroupIndex": 1, + "nodeName": "Object02", + "texture": "M14-1lu.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "m14b", + "label": "青绿圆台与蓝水环幕", + "keyEuler": [ + 72, + -30, + 0 + ], + "temperature": 8500, + "tint": [ + 0.88, + 0.98, + 1 + ], + "intensity": 0.83, + "shadowStrength": 0.6, + "characterFill": 0.56, + "contrast": 0.58, + "bakedStrength": 0.76, + "contactStrength": 0.82, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "w0001.tga" + }, + { + "nodeIndex": 3, + "materialGroupIndex": 0, + "nodeName": "Sphere02", + "texture": "B.tga" + }, + { + "nodeIndex": 117, + "materialGroupIndex": 0, + "nodeName": "Cone01", + "texture": "a.tga" + }, + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "Plane02", + "texture": "w0001.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M15A", + "label": "绿纹树干与蓝色水面", + "keyEuler": [ + 65, + -25, + 0 + ], + "temperature": 6800, + "tint": [ + 0.94, + 1, + 0.94 + ], + "intensity": 0.86, + "shadowStrength": 0.68, + "characterFill": 0.56, + "contrast": 0.68, + "bakedStrength": 0.8, + "contactStrength": 1, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "beij.tga" + }, + { + "nodeIndex": 3, + "materialGroupIndex": 0, + "nodeName": "sky", + "texture": "bj2.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M15Aa", + "label": "绿纹树干与蓝色水面变体", + "keyEuler": [ + 65, + -25, + 0 + ], + "temperature": 6800, + "tint": [ + 0.94, + 1, + 0.94 + ], + "intensity": 0.86, + "shadowStrength": 0.68, + "characterFill": 0.56, + "contrast": 0.68, + "bakedStrength": 0.8, + "contactStrength": 1, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "beij.tga" + }, + { + "nodeIndex": 3, + "materialGroupIndex": 0, + "nodeName": "sky", + "texture": "bj2.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M15B", + "label": "浅绿石路与蓝花沟", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 6800, + "tint": [ + 0.96, + 1, + 0.96 + ], + "intensity": 0.9, + "shadowStrength": 0.65, + "characterFill": 0.58, + "contrast": 0.6, + "bakedStrength": 0.7, + "contactStrength": 0.9, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 1, + "nodeName": "Plane01", + "texture": "bj.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "sky", + "texture": "bj2.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M15C", + "label": "浅白绿纹大石台", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 7000, + "tint": [ + 0.95, + 1, + 0.97 + ], + "intensity": 0.82, + "shadowStrength": 0.62, + "characterFill": 0.54, + "contrast": 0.6, + "bakedStrength": 0.72, + "contactStrength": 0.9, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "plane01", + "texture": "bj.tga" + }, + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "plane03", + "texture": "bj2.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M16A", + "label": "交错树干与浅蓝云幕", + "keyEuler": [ + 65, + -20, + 0 + ], + "temperature": 7000, + "tint": [ + 0.95, + 1, + 0.94 + ], + "intensity": 0.8, + "shadowStrength": 0.65, + "characterFill": 0.52, + "contrast": 0.65, + "bakedStrength": 0.82, + "contactStrength": 1, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "sky", + "texture": "5.tga" + }, + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "beij.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M16B", + "label": "黑背景内凹树干", + "keyEuler": [ + 74, + -20, + 0 + ], + "temperature": 6500, + "tint": [ + 0.94, + 1, + 0.9 + ], + "intensity": 0.63, + "shadowStrength": 0.52, + "characterFill": 0.42, + "contrast": 0.82, + "bakedStrength": 0.9, + "contactStrength": 1, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M16C", + "label": "云中绿木环台与青池", + "keyEuler": [ + 70, + -30, + 0 + ], + "temperature": 7600, + "tint": [ + 0.9, + 0.99, + 1 + ], + "intensity": 0.88, + "shadowStrength": 0.62, + "characterFill": 0.56, + "contrast": 0.58, + "bakedStrength": 0.75, + "contactStrength": 0.9, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "sky", + "texture": "5.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "6.tga" + }, + { + "nodeIndex": 2, + "materialGroupIndex": 0, + "nodeName": "Object01", + "texture": "5.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M17", + "label": "绿光边纹的暗色通道", + "keyEuler": [ + 74, + -20, + 0 + ], + "temperature": 6700, + "tint": [ + 0.91, + 1, + 0.88 + ], + "intensity": 0.72, + "shadowStrength": 0.52, + "characterFill": 0.46, + "contrast": 0.82, + "bakedStrength": 0.9, + "contactStrength": 1.05, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M18A", + "label": "粉红流纹的多层长廊", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 5400, + "tint": [ + 1, + 0.94, + 0.94 + ], + "intensity": 0.9, + "shadowStrength": 0.55, + "characterFill": 0.5, + "contrast": 0.58, + "bakedStrength": 0.68, + "contactStrength": 0.9, + "night": false, + "indoors": true, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "bj1.tga" + }, + { + "nodeIndex": 31, + "materialGroupIndex": 0, + "nodeName": "Plane03", + "texture": "di.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M18Aa", + "label": "粉红流纹的多层长廊变体", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 5400, + "tint": [ + 1, + 0.94, + 0.94 + ], + "intensity": 0.9, + "shadowStrength": 0.55, + "characterFill": 0.5, + "contrast": 0.58, + "bakedStrength": 0.68, + "contactStrength": 0.9, + "night": false, + "indoors": true, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "bj1.tga" + }, + { + "nodeIndex": 31, + "materialGroupIndex": 0, + "nodeName": "Plane03", + "texture": "di.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M18B", + "label": "红色坑纹与棕墙回廊", + "keyEuler": [ + 76, + -20, + 0 + ], + "temperature": 4200, + "tint": [ + 1, + 0.93, + 0.84 + ], + "intensity": 0.73, + "shadowStrength": 0.5, + "characterFill": 0.46, + "contrast": 0.72, + "bakedStrength": 0.82, + "contactStrength": 1, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M19A", + "label": "暗蓝天幕的石路庭院", + "keyEuler": [ + 65, + -30, + 0 + ], + "temperature": 8200, + "tint": [ + 0.9, + 0.96, + 1 + ], + "intensity": 0.82, + "shadowStrength": 0.62, + "characterFill": 0.58, + "contrast": 0.55, + "bakedStrength": 0.76, + "contactStrength": 0.9, + "night": true, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 32, + "materialGroupIndex": 0, + "nodeName": "bi", + "texture": "beij.tga" + }, + { + "nodeIndex": 34, + "materialGroupIndex": 0, + "nodeName": "Plane03", + "texture": "beij2.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M19B", + "label": "壁灯土黄石室", + "keyEuler": [ + 78, + -20, + 0 + ], + "temperature": 3900, + "tint": [ + 1, + 0.94, + 0.84 + ], + "intensity": 0.63, + "shadowStrength": 0.48, + "characterFill": 0.43, + "contrast": 0.72, + "bakedStrength": 0.88, + "contactStrength": 0.95, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M19C", + "label": "黑岩熔裂平台", + "keyEuler": [ + 70, + -30, + 0 + ], + "temperature": 3700, + "tint": [ + 1, + 0.91, + 0.78 + ], + "intensity": 0.76, + "shadowStrength": 0.5, + "characterFill": 0.48, + "contrast": 0.68, + "bakedStrength": 0.8, + "contactStrength": 0.95, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 3, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "beij.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "M19D", + "label": "深紫刻纹与熔岩沟石室", + "keyEuler": [ + 76, + -20, + 0 + ], + "temperature": 3800, + "tint": [ + 1, + 0.91, + 0.8 + ], + "intensity": 0.68, + "shadowStrength": 0.5, + "characterFill": 0.46, + "contrast": 0.72, + "bakedStrength": 0.84, + "contactStrength": 1, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "m19e", + "label": "红晶金边圆形石台", + "keyEuler": [ + 72, + -25, + 0 + ], + "temperature": 4300, + "tint": [ + 1, + 0.94, + 0.85 + ], + "intensity": 0.76, + "shadowStrength": 0.55, + "characterFill": 0.48, + "contrast": 0.62, + "bakedStrength": 0.8, + "contactStrength": 0.9, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "m19f", + "label": "红晶金边圆形石台变体", + "keyEuler": [ + 72, + -25, + 0 + ], + "temperature": 4300, + "tint": [ + 1, + 0.94, + 0.85 + ], + "intensity": 0.75, + "shadowStrength": 0.55, + "characterFill": 0.48, + "contrast": 0.62, + "bakedStrength": 0.8, + "contactStrength": 0.9, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M20", + "label": "青蓝砖石室", + "keyEuler": [ + 78, + -20, + 0 + ], + "temperature": 4800, + "tint": [ + 1, + 0.93, + 0.84 + ], + "intensity": 0.66, + "shadowStrength": 0.48, + "characterFill": 0.46, + "contrast": 0.74, + "bakedStrength": 0.88, + "contactStrength": 0.95, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "M20a", + "label": "青蓝砖石室变体", + "keyEuler": [ + 78, + -20, + 0 + ], + "temperature": 4800, + "tint": [ + 1, + 0.93, + 0.84 + ], + "intensity": 0.66, + "shadowStrength": 0.48, + "characterFill": 0.46, + "contrast": 0.74, + "bakedStrength": 0.88, + "contactStrength": 0.95, + "night": false, + "indoors": true + }, + { + "variant": "PAL3A", + "scene": "q01", + "label": "白墙红柱院落", + "keyEuler": [ + 65, + -35, + 0 + ], + "temperature": 6900, + "tint": [ + 0.97, + 1, + 1 + ], + "intensity": 1.03, + "shadowStrength": 0.6, + "characterFill": 0.55, + "contrast": 0.42, + "bakedStrength": 0.56, + "contactStrength": 0.82, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 1, + "nodeName": "Cone01", + "texture": "A.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "b.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Cone01", + "texture": "di.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "q02a", + "label": "云雾包围的浅石平台", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 7200, + "tint": [ + 0.96, + 0.99, + 1 + ], + "intensity": 0.9, + "shadowStrength": 0.58, + "characterFill": 0.52, + "contrast": 0.5, + "bakedStrength": 0.66, + "contactStrength": 0.82, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Cylinder02", + "texture": "Q02a_05.tga" + }, + { + "nodeIndex": 0, + "materialGroupIndex": 1, + "nodeName": "Cylinder02", + "texture": "q02a_03.tga" + }, + { + "nodeIndex": 0, + "materialGroupIndex": 2, + "nodeName": "Cylinder02", + "texture": "Q02a_02.tga" + }, + { + "nodeIndex": 0, + "materialGroupIndex": 3, + "nodeName": "Cylinder02", + "texture": "Q02a_04.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Object01", + "texture": "Q02a_05.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "q04", + "label": "紫蓝天幕的灰草庭院", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 8500, + "tint": [ + 0.87, + 0.94, + 1 + ], + "intensity": 0.9, + "shadowStrength": 0.55, + "characterFill": 0.55, + "contrast": 0.42, + "bakedStrength": 0.68, + "contactStrength": 0.85, + "night": true, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 1, + "nodeName": "Cone01", + "texture": "a.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "B.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Cone01", + "texture": "b04_sha1.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "q08", + "label": "黄沙木桩营地", + "keyEuler": [ + 65, + -30, + 0 + ], + "temperature": 5700, + "tint": [ + 1, + 0.97, + 0.88 + ], + "intensity": 0.88, + "shadowStrength": 0.62, + "characterFill": 0.5, + "contrast": 0.55, + "bakedStrength": 0.72, + "contactStrength": 0.85, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 1, + "nodeName": "Cone01", + "texture": "A.tga" + }, + { + "nodeIndex": 1, + "materialGroupIndex": 0, + "nodeName": "Sphere01", + "texture": "B.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Cone01", + "texture": "b08_sha1.tga" + } + ] + }, + { + "variant": "PAL3A", + "scene": "q09", + "label": "竹林草地", + "keyEuler": [ + 68, + -30, + 0 + ], + "temperature": 7300, + "tint": [ + 0.93, + 1, + 0.96 + ], + "intensity": 1.04, + "shadowStrength": 0.6, + "characterFill": 0.5, + "contrast": 0.36, + "bakedStrength": 0.48, + "contactStrength": 0.82, + "night": false, + "indoors": false, + "backgroundSurfaces": [ + { + "nodeIndex": 0, + "materialGroupIndex": 0, + "nodeName": "Plane01", + "texture": "1.tga" + } + ], + "geometricNormalSurfaces": [ + { + "nodeIndex": 40, + "materialGroupIndex": 0, + "nodeName": "kuang", + "texture": "4.tga" + }, + { + "nodeIndex": 40, + "materialGroupIndex": 1, + "nodeName": "kuang", + "texture": "5.tga" + } + ] + } + ] +} diff --git a/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingProfiles.json.meta b/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingProfiles.json.meta new file mode 100644 index 00000000..4e50fcc9 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingProfiles.json.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e080c25ae0b246b08ca48b5ea96e732f diff --git a/Assets/Scripts/Editor/BattleEditor/Hud.meta b/Assets/Scripts/Editor/BattleEditor/Hud.meta new file mode 100644 index 00000000..5133c783 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4bb30d78c6ab41ea919be2d54d2e0d91 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudCanvas.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudCanvas.cs new file mode 100644 index 00000000..1cf07a6d --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudCanvas.cs @@ -0,0 +1,97 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using UnityEngine; + using UnityEditor; + + public readonly struct BattleHudCanvas : IDisposable + { + private static readonly Dictionary<(bool ProSkin, int Size, Color Color, bool Tight, bool Wrap, TextAnchor? Alignment), GUIStyle> Labels = new(); + + private readonly Matrix4x4 _matrix; + private readonly Color _color; + + public BattleHudCanvas(BattleHudViewport viewport) : this(viewport.SafeRect, viewport.Scale) + { + } + + public BattleHudCanvas(Rect area, float scale) + { + _matrix = GUI.matrix; + _color = GUI.color; + // Clip bounds must be established in the scaled coordinate system. + // Scaling after BeginGroup leaves a physical-sized clip over a + // reference-sized canvas and cuts the lower/right-hand controls. + GUI.matrix = _matrix * Matrix4x4.Scale(new Vector3(scale, scale, 1)); + GUI.BeginGroup(new Rect(area.position / scale, area.size / scale)); + } + + public void Dispose() + { + GUI.EndGroup(); + GUI.color = _color; + GUI.matrix = _matrix; + } + + public static void DrawVitalNumber(Rect track, int value, string kind) + { + // CCBDisplayChain::ShowRoleState uses the current value. Both + // state/result callers publish these offsets and RGBQUAD colors. + // Pixel2FloatY and gbNumFont::Flush make +5 the lower baseline; + // the native number glyph extends upward by 12 * 1.3 pixels. + int x = kind == "GP" ? 31 : kind == "MP" ? 23 : 22; + Color color = kind == "GP" ? new Color32(251, 224, 162, 255) : kind == "MP" ? new Color32(250, 168, 213, 255) : new Color32(160, 188, 250, 255); + GUI.Label(new Rect(track.x + x, track.y + 5 - 15.6f, track.width - x, 15.6f), + value.ToString(), LabelStyle(12, color, tight: true)); + } + + internal static GUIStyle LabelStyle(int size, Color color, bool tight = false, bool wrap = false, TextAnchor? alignment = null) + { + var key = (EditorGUIUtility.isProSkin, size, color, tight, wrap, alignment); + if (Labels.TryGetValue(key, out GUIStyle cached)) + return cached; + var style = new GUIStyle(EditorStyles.label) + { + fontSize = size, + clipping = TextClipping.Clip, + richText = false, + wordWrap = wrap + }; + if (alignment.HasValue) + style.alignment = alignment.Value; + if (tight) + { + style.padding = new RectOffset(); + style.alignment = TextAnchor.UpperLeft; + } + // Keep the native text color when Unity uses a hover or keyboard state. + foreach (GUIStyleState state in new[] { style.normal, style.hover, style.active, style.focused, + style.onNormal, style.onHover, style.onActive, style.onFocused }) + { + state.textColor = color; + state.background = null; + } + return Labels[key] = style; + } + + public static Rect ProgressFill(Rect track, float fraction, bool result) + { + // UIProgressBar::Render plus released state/result radius settings. + float inset = result ? 1 : 0; + float width = result ? 81 : 76; + return new Rect(track.x + inset, track.y + 2, width * Mathf.Clamp01(fraction), 7); + } + + // Original UI images have power-of-two padding. TGA row zero enters + // Unity at v=0, so the native top-left crop uses the lower UV range. + public static Rect SpriteUv(Texture2D texture, Vector2 nativeSize) => new(0, 0, + Math.Min(nativeSize.x, texture.width) / texture.width, + Math.Min(nativeSize.y, texture.height) / texture.height); + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudCanvas.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudCanvas.cs.meta new file mode 100644 index 00000000..5f105cad --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudCanvas.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e8842a54a264424b906094aab0af83c4 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudDenialText.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudDenialText.cs new file mode 100644 index 00000000..0c32bf9d --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudDenialText.cs @@ -0,0 +1,158 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using Battle; + using Battle.Presentation; + + // Domain reasons remain diagnostics. Only known messages and typed cost + // estimates cross this boundary into the player's description panel. + public static class BattleHudDenialText + { + public static string ForAbility(BattleSession session, BattleHudPresenter presenter, BattleAbilityDefinition ability, bool detailed = false) + { + if (presenter == null || ability == null) + return detailed ? "当前无法使用。" : "当前无法使用"; + BattleAction action = ability.IsItem ? BattleAction.Item : BattleAction.Skill; + string reason = presenter.Reason(action, ability.Id); + IReadOnlyList costs = IsResourceDenial(reason) && session != null && presenter.Controller != null + ? session.GetCostEstimate(new BattleCommand(presenter.Controller, action, abilityId: ability.Id)) : null; + return Format(reason, costs, detailed); + } + + public static string Format(string reason, IEnumerable costs = null, bool detailed = false) + { + if (reason == null) + return null; + if (IsResourceDenial(reason)) + { + // Keep the same first failing cost and pre-savings requirement + // as CanSubmit; parsing the diagnostic would lose this context. + if (costs != null) + foreach (BattleCostEstimate cost in costs) + if (cost.Required > cost.Available) + { + string resource = ResourceName(cost.Resource); + if (resource == null) + return detailed ? "施放所需资源不足。" : "所需资源不足"; + if (detailed) + return $"{resource}不足:需要 {cost.Required},当前 {cost.Available}。"; + string brief = $"{resource}不足:需{cost.Required},现{cost.Available}"; + return FitsBriefLine(brief) ? brief : resource + "不足"; + } + return detailed ? "施放所需资源不足。" : "所需资源不足"; + } + string text = reason switch + { + "先启用 AI,再设置此项。" => "先启用 AI,再设置此项。", + "等待角色就绪" or "Actor is not ready." or "The protection controller is not ready." => "等待角色就绪。", + "An earlier actor is waiting for input." => "请先为前一位角色下达指令。", + "The battle has ended." => "战斗已经结束。", + "The original combat movie is playing." => "请等待战斗动画结束。", + "The encounter outcome is resolving." => "正在结算战斗结果。", + "Finish formation control before submitting an action." => "请先完成阵位调整。", + "定/眠期间不能行动。" => "定/眠期间不能行动。", + "乱/狂期间由原版异常状态 AI 接管。" => "乱/狂期间不能手动下达指令。", + "禁期间不能使用物品。" => "禁期间不能使用物品。", + "封期间不能施放仙术。" => "封期间不能施放仙术。", + "There is no legal target." => "没有可选目标。", + "Choose a legal target for this action." => "请选择可用目标。", + "Choose a scene element before resolving allied rows or columns." => "请先设置战场五灵属性。", + "This actor has not mastered the skill." => "尚未学会此技能。", + "This skill belongs to another character." => "此角色不能使用该技能。", + "The original skill proficiency must be 1–4." => "技能熟练等级无效,暂时无法使用。", + "This item cannot be used in combat." => "此物品不能在战斗中使用。", + "Original enemies cannot use inventory items." => "敌方不能使用背包物品。", + "No item remains in this battle inventory." => "此物品已用完或已被其他指令占用。", + "The magic sword energy must be greater than 199.9." => "魔剑能量不足。", + "This actor has no captured magic sword with the selected weapon skill." => "请装备拥有此魔剑技的魔剑。", + "Transformation is exclusive to PAL3A." => "此版本无法变身。", + "The original form transition is still running." => "请等待变身结束。", + "Only Nangong Huang's human form can request the fire beast transformation." => "只有人形的南宫煌可以炎兽变身。", + "All five spirit wheel charges must reach three." => "五灵轮各系均需充能至少三次。", + "朱仙变 requires Wang Pengxu's human form." => "只有人形的王蓬絮可以使用朱仙变。", + "朱仙变 requires full SP before equipment savings." => "气满后才能使用朱仙变。", + "摄灵法阵 requires Nangong Huang in native slot zero." => "只有南宫煌可以使用摄灵法阵。", + "The original fire beast form permits only physical attack, defense, or escape." => "炎兽形态只能普通攻击、防御或逃跑。", + "The original fairy beast form permits only magic, defense, or escape." => "朱仙形态只能施放仙术、防御或逃跑。", + "Choose a PAL3A five-spirit wheel element." => "请选择五灵轮属性。", + "Choose the current controller." or "Choose the current ready controller." or "Choose the current ready allied controller." => "请先选择当前就绪角色。", + "The spirit wheel needs Nangong Huang as the current ready controller." => "请等待南宫煌就绪。", + "This spirit wheel element needs nine charges." => "此系五灵轮需充能九次。", + "A formation panel is already open." => "请先完成当前阵位调整。", + "Open the formation panel first." => "请先打开阵位面板。", + "Only an allied participant can change formation." => "只有我方角色可以调整阵位。", + "Unknown formation slot." => "请选择可用阵位。", + "The protection target is missing." => "请选择援护对象。", + "Original protection requires the living player in native slot 0 at the center." => "援护者须存活并位于中央阵位。", + "Unknown skill or item." => "此技能或物品暂时无法使用。", + "This ability has an unsupported resource cost." => "此技能的消耗暂未支持。", + "The original form animation catalog is missing." or + "The original spirit wheel presentation is missing." or + "Spirit capture needs the original screen-space wheel layout." or + "This attribute effect needs its original dedicated battle handler." or + "This ability contains an unverified target range or derived/passive state operation." or + "The magic sword needs its original effect completion director." or + "This ability requires its original effect completion director." or + "The ability has no verified action timeline." or + "This ability requires a dedicated repeated-effect timeline." => "此技能暂时无法使用。", + "Random formation needs the original scene's formation positions." => "此战场暂时无法使用阵位变化。", + "This treasure has no original usage counter in the selected variant." => "此仙宝在当前版本暂时无法使用。", + _ => "当前无法使用。" + }; + return detailed ? text : BriefReason(text); + } + + private static string BriefReason(string text) => text switch + { + "先启用 AI,再设置此项。" => "请先启用AI", + "请先为前一位角色下达指令。" => "等待前位角色指令", + "乱/狂期间不能手动下达指令。" => "乱/狂期间自动行动", + "技能熟练等级无效,暂时无法使用。" => "技能熟练等级无效", + "此物品不能在战斗中使用。" => "战斗中不可使用", + "此物品已用完或已被其他指令占用。" => "此物品无可用数量", + "请装备拥有此魔剑技的魔剑。" => "未装备相应魔剑技", + "只有人形的南宫煌可以炎兽变身。" => "仅人形南宫煌可变身", + "五灵轮各系均需充能至少三次。" => "五灵轮各系需三次", + "只有人形的王蓬絮可以使用朱仙变。" => "仅人形王蓬絮可使用", + "只有南宫煌可以使用摄灵法阵。" => "仅南宫煌可使用", + "炎兽形态只能普通攻击、防御或逃跑。" => "炎兽仅可攻、防、逃", + "朱仙形态只能施放仙术、防御或逃跑。" => "朱仙仅可术、防、逃", + "只有我方角色可以调整阵位。" => "仅我方可调整阵位", + "援护者须存活并位于中央阵位。" => "援护者须存活且居中", + "此技能或物品暂时无法使用。" => "当前暂不可使用", + "此战场暂时无法使用阵位变化。" => "当前无法变化阵位", + "此仙宝在当前版本暂时无法使用。" => "当前无法使用此仙宝", + _ => text.TrimEnd('。') + }; + + // The narrowest native description band is 140 pixels at a 14-pixel + // font. Large amounts keep their complete explanation in the tooltip. + private static bool FitsBriefLine(string text) + { + int cells = 0; + foreach (char character in text) + cells += character < 0x80 ? 1 : 2; + return cells <= 20; + } + + private static bool IsResourceDenial(string reason) => reason?.StartsWith("Resource ", StringComparison.Ordinal) == true; + + private static string ResourceName(int resource) => resource switch + { + 0 => "精", + 1 => "气", + 2 => "神", + 7 => "速度", + 8 => "运气", + 10 => "金钱", + 16 => "蛊", + _ => null + }; + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudDenialText.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudDenialText.cs.meta new file mode 100644 index 00000000..b33b8475 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudDenialText.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6ef0a4cf7dc2457da5942addbd58221f diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudInteractionProfile.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudInteractionProfile.cs new file mode 100644 index 00000000..739d32cd --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudInteractionProfile.cs @@ -0,0 +1,40 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using UnityEngine; + + public readonly struct BattleHudInteractionProfile + { + public bool Touch + { + get; + } + + public float MenuScale + { + get; + } + + public float HitPadding + { + get; + } + + public BattleHudInteractionProfile(bool touch, float menuScale = 1.2f, float hitPadding = 6) + { + if (!float.IsFinite(menuScale) || menuScale < 1 || menuScale > 2 || !float.IsFinite(hitPadding) || hitPadding < 0 || hitPadding > 32) + throw new ArgumentException("Interaction dimensions must be finite and bounded."); + Touch = touch; + MenuScale = menuScale; + HitPadding = hitPadding; + } + + public float ScaleFor(BattleHudViewport viewport) => !Touch ? 1 : Math.Max(1, + Math.Min(MenuScale, (viewport.SafeRect.height - 109 * viewport.Scale - 16) / (322 * viewport.Scale))); + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudInteractionProfile.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudInteractionProfile.cs.meta new file mode 100644 index 00000000..19fe7bc3 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudInteractionProfile.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 766350910cda4b0eafa43c19b515cfa8 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudLayout.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudLayout.cs new file mode 100644 index 00000000..7692e92f --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudLayout.cs @@ -0,0 +1,126 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Linq; + using Battle; + using Battle.Presentation; + using UnityEngine; + + public sealed class BattleHudLayout + { + public bool IsPal3A + { + get; + } + + public float AttackSequenceX => IsPal3A ? 410 : 483; + + public float AttackSequenceY => IsPal3A ? 14 : 10; + + public float ListHeight => IsPal3A ? 226 : 206; + + public BattleHudLayout(string variant) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown battle HUD variant.", nameof(variant)); + IsPal3A = variant == "PAL3A"; + } + + public static Rect ContentRect(Rect available) + { + float scale = Math.Max(0, Math.Min(available.width / 800, available.height / 600)); + Vector2 size = new(800 * scale, 600 * scale); + return new Rect(available.center - size / 2, size); + } + + public static Vector2 ToCanvas(Vector2 point, Rect content) => new((point.x - content.x) * 800 / content.width, + (point.y - content.y) * 600 / content.height); + + public static Vector2 ToViewport(Vector2 point, Rect content) => new(content.x + point.x * content.width / 800, + content.y + point.y * content.height / 600); + + public static bool Hit(Rect canvasRect, Vector2 point, Rect content) => content.width > 0 && content.height > 0 && + content.Contains(point) && canvasRect.Contains(ToCanvas(point, content)); + + public static Rect StateCard(int index, int page = 0) => new(new[] { 0f, 207, 403, 600 }[index - page * 4], 491, 200, 106); + + public Vector2 AttackPortrait(int gauge, int castGauge, bool casting) + { + float x = AttackSequenceX - 3 - 20; + x += casting ? 199 + Mathf.Clamp01(castGauge / (float)BattleSession.FullCastGauge) * 90 : + Mathf.Clamp01(gauge / (float)BattleSession.FullGauge) * 197; + return new Vector2(x, AttackSequenceY - 2); + } + + public string StateFace(int identity) => IsPal3A ? "state/tx" + (identity + 1) : "state/" + Pal3Name(identity); + + public string StateName(int identity) => IsPal3A ? "state/wz_" + new[] { "ngh", "wh", "px", "xx", "lyg" }[identity] : + "state/" + Pal3Name(identity) + "name"; + + public string FormationFace(int identity, bool disabled) => IsPal3A ? "control/Lineup/" + + new[] { "zngh", "zwh", "zpx", "zxx", "zlyg" }[identity] + (disabled ? "02" : "01") : + "control/Lineup/" + Pal3Name(identity) + (disabled ? "_d" : ""); + + public string AiName(int identity) => "control/AI/" + (IsPal3A ? new[] { "w2", "w3", "w4", "w5", "w6" }[identity] : Pal3Name(identity)); + + public string ProtectionFace(int identity) => IsPal3A ? identity switch + { + 1 => "control/Protect/yhwh", + 2 => "control/Protect/yhpx", + _ => null + } : identity switch + { + 1 => "control/Protect/xuejian", + 2 => "control/Protect/longkui", + 3 => "control/Protect/zixuan", + _ => null + }; + + public static Vector2 FormationPosition(BattleSlot slot) => slot switch + { + BattleSlot.Water => new Vector2(104, 188), + BattleSlot.Fire => new Vector2(46, 148), + BattleSlot.Wind => new Vector2(136, 87), + BattleSlot.Thunder => new Vector2(65, 87), + BattleSlot.Earth => new Vector2(156, 148), + BattleSlot.Center => new Vector2(104, 131), + _ => throw new ArgumentOutOfRangeException(nameof(slot)) + }; + + // PAL3 CBUIPos.h and PAL3A released 0x5ebf5c..0x5ebfbc + // publish the same status rectangles inside each native state card. + public static Rect? StatusRect(BattleState state) => state switch + { + BattleState.AttackIncrease or BattleState.AttackDecrease => new Rect(15, 85, 22, 23), + BattleState.DefenseIncrease or BattleState.DefenseDecrease => new Rect(39, 85, 22, 23), + BattleState.SpeedIncrease or BattleState.SpeedDecrease => new Rect(63, 85, 22, 23), + BattleState.LuckIncrease or BattleState.LuckDecrease => new Rect(87, 85, 22, 23), + BattleState.Paralysis or BattleState.Seal or BattleState.Forbidden or BattleState.Sleep or BattleState.Chaos or BattleState.Madness => new Rect(111, 88, 16, 16), + BattleState.Reflection => new Rect(111, 88, 20, 17), + BattleState.Evade => new Rect(111, 88, 18, 18), + BattleState.Barrier => new Rect(111, 88, 19, 17), + BattleState.Invisible => new Rect(111, 88, 18, 17), + BattleState.PoisonResist => new Rect(131, 88, 37, 17), + _ => null + }; + + public static float StatusLuminance(double seconds) => (200 + Mathf.RoundToInt(MathF.Sin((float)seconds * 12) * 50)) / 255f; + + public static Color FaceTint(BattleActorSnapshot actor, bool darkDead = true) + { + uint value = darkDead && actor.Hp <= 0 ? 0xff505050 : actor.States.Any(state => state.LatentRounds == 0 && state.State == BattleState.PoisonWater) ? 0xff399aad : + actor.States.Any(state => state.LatentRounds == 0 && state.State == BattleState.PoisonFire) ? 0xffde7531 : + actor.States.Any(state => state.LatentRounds == 0 && state.State == BattleState.PoisonThunder) ? 0xffa466ea : + actor.States.Any(state => state.LatentRounds == 0 && state.State == BattleState.PoisonWind) ? 0xff52b66b : + actor.States.Any(state => state.LatentRounds == 0 && state.State == BattleState.PoisonEarth) ? 0xffd6ae5a : 0xffffffff; + return new Color((value >> 16 & 255) / 255f, (value >> 8 & 255) / 255f, (value & 255) / 255f, 1); + } + + private static string Pal3Name(int identity) => new[] { "jingtian", "xuejian", "longkui", "zixuan", "changqing" }[identity]; + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudLayout.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudLayout.cs.meta new file mode 100644 index 00000000..e87850dc --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudLayout.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 551d2e519a2242b0982f8f79f8134e07 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudText.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudText.cs new file mode 100644 index 00000000..34c6e43b --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudText.cs @@ -0,0 +1,129 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using Battle.Presentation; + using UnityEngine; + + public readonly struct BattleHudTextGlyph + { + public string Text + { + get; + } + + public int Column + { + get; + } + + public int Row + { + get; + } + + public BattleHudTextGlyph(string text, int column, int row) + { + Text = text; + Column = column; + Row = row; + } + } + + public static class BattleHudText + { + // ProcSkillList / ProcMagicList / ProcItemList pass only the suffix + // after the final '$' to UIStatic. '#' is ordinary text here. + public static string Description(string value) + { + int separator = value?.LastIndexOf('$') ?? -1; + return separator < 0 ? string.Empty : value[(separator + 1)..]; + } + + // Match the compact native strip without the larger Editor font metrics. + public const int DescriptionFontSize = 14; + + public static Rect AbilityPanelBounds(BattleHudPage page, bool pal3A) => page switch + { + BattleHudPage.Skills => new Rect(10, 237, 256, 256), + BattleHudPage.Magic => new Rect(10, pal3A ? 258 : 276, 249, pal3A ? 226 : 206), + BattleHudPage.Items => new Rect(10, pal3A ? 258 : 278, 249, pal3A ? 226 : 206), + _ => throw new ArgumentOutOfRangeException(nameof(page)) + }; + + // Effective UIStatic text rectangles include its native eight-pixel + // border. PAL3A uses a separate Skill description child and taller lists. + public static Rect DescriptionBounds(BattleHudPage page, bool pal3A) => page switch + { + BattleHudPage.Skills => pal3A ? new Rect(47, 233, 192, 23) : new Rect(47, 227, 201, 21), + BattleHudPage.Magic => pal3A ? new Rect(48, 202, 193, 16) : new Rect(48, 178, 193, 20), + BattleHudPage.Items => pal3A ? new Rect(45, 204, 184, 24) : new Rect(45, 178, 184, 24), + _ => throw new ArgumentOutOfRangeException(nameof(page)) + }; + + public static Rect ListBounds(BattleHudPage page, bool pal3A) => page switch + { + BattleHudPage.Skills => pal3A ? new Rect(39, 92, 208, 136) : new Rect(39, 110, 202, 116), + BattleHudPage.Magic => pal3A ? new Rect(39, 78, 214, 119) : new Rect(39, 78, 202, 97), + BattleHudPage.Items => new Rect(39, 78, 202, pal3A ? 118 : 97), + _ => throw new ArgumentOutOfRangeException(nameof(page)) + }; + + // UIDrawText uses half-width ASCII cells, full-width Chinese cells, + // literal backslash-n/backslash-t escapes and a font-height bottom gate. + public static IReadOnlyList Layout(string value, float width, float height, int fontSize) + { + if (fontSize <= 0 || !float.IsFinite(width) || !float.IsFinite(height)) + throw new ArgumentOutOfRangeException(nameof(fontSize)); + var result = new List(); + if (string.IsNullOrEmpty(value) || width <= 0 || height < fontSize) + return result; + int column = 0, row = 0; + for (int index = 0; index < value.Length; index++) + { + char current = value[index]; + if (current == '\\') + { + if (++index == value.Length) + break; + if (value[index] == 'n') + { + row++; + column = 0; + } + else if (value[index] == 't') + column = (column + 8) / 8 * 8; + continue; + } + if (current == '\0') + break; + int cells = current < 127 ? 1 : 2; + if ((column + cells) * fontSize / 2f > width) + { + column = 0; + row++; + } + if ((row + 1) * fontSize > height) + break; + // Actual ASCII control bytes are not the backslash escapes. + // They consume one native cell but add no visible glyph ink. + if (current < 32) + { + column += cells; + continue; + } + string glyph = current.ToString(); + if (char.IsHighSurrogate(current) && index + 1 < value.Length && char.IsLowSurrogate(value[index + 1])) + glyph += value[++index]; + result.Add(new BattleHudTextGlyph(glyph, column, row)); + column += cells; + } + return result; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudText.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudText.cs.meta new file mode 100644 index 00000000..b58da77b --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudText.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8eae1890fb8142afbc4a365b82552c84 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Audio.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Audio.cs new file mode 100644 index 00000000..da387bc9 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Audio.cs @@ -0,0 +1,50 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using Battle.Presentation; + + public sealed partial class BattleHudView + { + private void PlayMenuSound(string sound) + { + if (_hasInputFocus && _preview?.Audio is { PlaybackEnabled: true, Muted: false } audio) + { + audio.Play(sound); + } + } + + private void PlayInputSounds(BattleHudIntent intent, BattleHudPage previousPage, string previousController, + string previousFocus, int previousCategory, bool accepted) + { + if (!accepted && _presenter.ActivatedControl != null && _presenter.Message != null) + { + PlayMenuSound("wa004"); + return; + } + bool activate = accepted && intent.Kind is BattleHudIntentKind.Confirm or BattleHudIntentKind.PointerUp; + string control = intent.ControlId ?? previousFocus; + bool categoryChanged = previousPage is BattleHudPage.Magic or BattleHudPage.Items && previousCategory != _presenter.Category; + if (activate) + { + if (control?.StartsWith("ability:", StringComparison.Ordinal) == true) + PlayMenuSound("wa002"); + else if (previousPage is BattleHudPage.Commands or BattleHudPage.Formation or BattleHudPage.Ai || + control?.StartsWith("category:", StringComparison.Ordinal) == true) + PlayMenuSound("wa001"); + } + else if (accepted && categoryChanged) + PlayMenuSound("wa001"); + // World target selection has no window-pop sound. Returning to a + // list or the command wheel opens that native panel once again. + if (_presenter.Controller != null && + (_presenter.Page != previousPage || _presenter.Controller != previousController) && + _presenter.Page != BattleHudPage.Targets) + PlayMenuSound("wa003"); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Audio.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Audio.cs.meta new file mode 100644 index 00000000..0c72ad2a --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Audio.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b6156467ac35460cabd64521d007d922 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Commands.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Commands.cs new file mode 100644 index 00000000..d7f343e1 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Commands.cs @@ -0,0 +1,202 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Linq; + using Battle; + using Battle.Presentation; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattleHudView + { + private void DrawCommands() + { + Sprite("control/back", new Rect(10, 225, 256, 256)); + BattleActorSnapshot actor = _battle.Actors.First(value => value.Id == _presenter.Controller); + // CCBControlWindow creates the sword before the ordinary controls; + // the overlapping formation/item buttons retain their top layer. + if (!_layout.IsPal3A && actor.MagicSword is { SkillId: > 0 } sword && sword.Energy > 199.9f) + SpriteButton("control/mj", new Rect(0, 410, 84, 84), tooltip: "魔剑技", disabledImage: false); + SpriteButton("control/attack", new Rect(63, 381, 46, 46), tooltip: "击 · 普通攻击"); + SpriteButton("control/skill", new Rect(67, 322, 46, 46), tooltip: "技 · 特技"); + SpriteButton("control/magic", new Rect(12, 378, 46, 46), tooltip: "术 · 仙术"); + SpriteButton("control/item", new Rect(66, 433, 46, 46), tooltip: "物 · 恢复/攻击/仙宝"); + SpriteButton("control/defence", new Rect(121, 378, 46, 46), tooltip: "防 · 防御"); + SpriteButton("control/flee", new Rect(100, 417, 46, 46), tooltip: "逃 · 等待逃跑"); + SpriteButton("control/lineup", new Rect(29, 417, 46, 46), tooltip: "阵 · 拖动角色换位"); + SpriteButton("control/ai", new Rect(29, 346, 46, 46), tooltip: "AI · 战斗策略"); + SpriteButton("control/protect", new Rect(100, 346, 46, 46), tooltip: "护 · 援护对象"); + } + + public static bool ElementWheelVisible(BattleSession combat, BattleHudPresenter presenter) => combat != null && combat.Definitions?.Variant == "PAL3A" && + combat.Status == BattleSessionStatus.Running && presenter.Page == BattleHudPage.Commands && presenter.Controller != null && + combat.Actors.First(actor => actor.Id == presenter.Controller).NativeIndex == 0; + + private void DrawWheelControls() + { + if (!ElementWheelVisible(_battle, _presenter)) + return; + for (int core = 0; core < 5; core++) + { + int skill = core switch + { + 2 => 267, + 3 => 266, + _ => 264 + core + }; + BattleSpiritRect native = BattlePreview.SpiritWheelTarget(core); + Vector2 position = _viewport.ToCanvas(_viewport.NativeToViewport(new Vector2(native.Left, native.Top))); + Rect rect = new(position.x, position.y, native.Right - native.Left, native.Bottom - native.Top); + string id = "wheel:" + skill; + int ui = core switch + { + 2 => 3, + 3 => 2, + _ => core + }; + int tier = _battle.Pal3AState.SpiritWheel.Charges[core] / 3; + string image = (tier < 3 ? "unwt" : "wt") + (4 - ui) + (tier < 3 ? tier : 0); + RegisterControl(id, rect, SpriteTexture("control/" + image)); + GUI.Label(rect, new GUIContent("", _battle.Definitions.Skills.TryGetValue(skill, out BattleAbilityDefinition ability) ? ability.Name + " · " + (rect.Contains(_pointer) ? _presenter.WheelReason(skill) ?? "五灵轮" : "五灵轮") : "五灵轮")); + } + Vector2 center = _viewport.ToCanvas(_viewport.NativeToViewport(new Vector2(739, 28))); + Rect beast = new(center.x, center.y, 45, 37); + if (_presenter.Reason(BattleAction.Transform) == null) + { + SpriteButton("control/bs", beast, tooltip: "炎兽变身", disabledImage: false); + } + else + RegisterControl("transform", beast, SpriteTexture("control/unbs")); + } + + private void DrawAbilities() + { + bool item = _presenter.Page == BattleHudPage.Items; + bool magic = _presenter.Page == BattleHudPage.Magic; + string folder = item ? "ItemList" : magic ? "MagicList" : "SkillList"; + Rect panel = BattleHudText.AbilityPanelBounds(_presenter.Page, _layout.IsPal3A); + Sprite("control/" + folder + "/" + (item ? "ItemPanel" : magic ? "MagicPanel" : "SkillPanel"), panel); + string[] tabs = item ? new[] { "recover", "attack", "treasure" } : magic ? + new[] { "water", "fire", "thunder", "wind", "earth", "double" } : Array.Empty(); + string[] labels = item ? new[] { "恢复", "攻击", "仙宝" } : new[] { "水", "火", "雷", "风", "土", "双系" }; + for (int index = 0; index < tabs.Length; index++) + SpriteButton("control/" + folder + "/" + tabs[index], new Rect(panel.x + 40 + index * 32, panel.y + 27, 32, 32), + tooltip: labels[index], selected: _presenter.Category == index); + BattleHudAbility[] abilities = _presenter.Abilities().ToArray(); + Rect list = BattleHudText.ListBounds(_presenter.Page, _layout.IsPal3A); + list.position += panel.position; + float height = list.height; + const float rowHeight = 19; + string focus = _renderFocusedId; + int focusedIndex = Array.FindIndex(abilities, row => "ability:" + row.Definition.Id == focus); + if (_scrollFocus != focus && focusedIndex >= 0) + { + float rowTop = focusedIndex * rowHeight; + _listScroll.y = Math.Clamp(_listScroll.y, Math.Max(0, rowTop + rowHeight - list.height), rowTop); + _scrollFocus = focus; + } + RegisterTouchList(list, Math.Max(height, abilities.Length * rowHeight)); + _listScroll = GUI.BeginScrollView(list, _listScroll, new Rect(0, 0, list.width - 15, Math.Max(height, abilities.Length * rowHeight)), false, false); + BattleHudAbility hovered = null, focused = null; + GUIStyle availableStyle = BattleHudCanvas.LabelStyle(13, new Color(5 / 255f, 5 / 255f, 0)); + GUIStyle deniedStyle = BattleHudCanvas.LabelStyle(13, new Color(.35f, .37f, .35f)); + try + { + for (int index = 0; index < abilities.Length; index++) + { + BattleHudAbility row = abilities[index]; + Rect rect = new(0, index * rowHeight, list.width - 16, rowHeight); + string controlId = "ability:" + row.Definition.Id; + Rect hit = new(list.x + rect.x, list.y + rect.y - _listScroll.y, rect.width, rect.height); + if (hit.yMax > list.y && hit.y < list.yMax) + { + float low = Math.Max(hit.y, list.y); + float high = Math.Min(hit.yMax, list.yMax); + RegisterControl(controlId, new Rect(hit.x, low, hit.width, high - low)); + } + bool hover = !_navigationInput && list.Contains(_pointer) && rect.Contains(_pointer - list.position + _listScroll); + if (hover || focus == controlId) + { + EditorGUI.DrawRect(rect, new Color(1, .8f, .3f, .22f)); + if (hover) + hovered = row; + if (focus == controlId) + focused = row; + } + GUIStyle style = row.Denied == null ? availableStyle : deniedStyle; + float nameWidth = magic ? 96 : Math.Min(150, rect.width - 43); + GUI.Label(new Rect(rect.x, rect.y, nameWidth, rect.height), row.Definition.Name, style); + if (magic) + { + int cost = row.Definition.Costs.Where(value => value.Resource == 2).Sum(value => value.Value); + GUI.Label(new Rect(rect.x + 96, rect.y, 37, rect.height), cost.ToString(), style); + GUI.Label(new Rect(rect.x + 133, rect.y, 50, rect.height), $"{row.Level}/{row.Uses:00}", style); + } + else + { + int cost = row.Definition.Costs.Where(value => value.Resource == 1).Sum(value => value.Value); + GUI.Label(new Rect(rect.x + nameWidth, rect.y, rect.width - nameWidth, rect.height), item ? row.Count.ToString() : cost.ToString(), style); + } + if (row.Denied != null) + { + string rowTooltip = BattleHudDenialText.ForAbility(_battle, _presenter, row.Definition, detailed: true); + GUI.Label(rect, new GUIContent("", rowTooltip), GUIStyle.none); + // Match the clipped, scaled geometry used by row hover. + if (hover) + GUI.tooltip = rowTooltip; + } + } + + } + finally + { + GUI.EndScrollView(); + } + BattleHudAbility described = hovered ?? focused; + string description = abilities.Length == 0 ? "此分类没有可用条目" : described != null ? Description(described.Definition) : ""; + string tooltip = described != null ? BattleHudDenialText.ForAbility(_battle, _presenter, described.Definition, detailed: true) ?? description : description; + DrawDescription(description, tooltip, panel, item); + } + + private string _descriptionText; + private string _descriptionTooltip; + private Rect _descriptionRect; + + private void DrawDescription(string text, string tooltip, Rect panel, bool item) + { + Rect area = BattleHudText.DescriptionBounds(_presenter.Page, _layout.IsPal3A); + area.position += panel.position; + const int size = BattleHudText.DescriptionFontSize; + GUIStyle style = BattleHudCanvas.LabelStyle(size, + item ? new Color(5 / 255f, 5 / 255f, 0) : new Color(0, 0, 0, 0x90 / 255f), tight: true); + _descriptionText = text; + _descriptionTooltip = tooltip; + _descriptionRect = new Rect(_pageOffset + area.position * _pageScale, area.size * _pageScale); + GUI.BeginGroup(area); + try + { + foreach (BattleHudTextGlyph glyph in BattleHudText.Layout(text, area.width, area.height, size)) + GUI.Label(new Rect(glyph.Column * size / 2f, glyph.Row * size, size, size), glyph.Text, style); + } + finally + { + GUI.EndGroup(); + } + GUI.Label(area, new GUIContent("", tooltip), GUIStyle.none); + } + + private string Description(BattleAbilityDefinition ability) + { + string text = ability.IsItem ? _data.Database.GameItemInfos.TryGetValue(ability.Id, out var item) ? item.Description : "" : + _data.Database.SkillInfos.TryGetValue(ability.Id, out var skill) ? skill.Description : ""; + string denied = BattleHudDenialText.ForAbility(_battle, _presenter, ability); + return denied ?? BattleHudText.Description(text); + } + + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Commands.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Commands.cs.meta new file mode 100644 index 00000000..0a6743ab --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Commands.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c4d3d85ec5214afdbd607a9af6d49a21 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Configuration.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Configuration.cs new file mode 100644 index 00000000..a9322436 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Configuration.cs @@ -0,0 +1,88 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Linq; + using Battle; + using Battle.Presentation; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattleHudView + { + private void DrawFormation() + { + Vector2 origin = new(19, 232); + Sprite("control/Lineup/back", new Rect(origin.x, origin.y, 230, 250)); + GUI.Label(new Rect(19, 192, 320, 36), "阵法 · 拖动头像换位\n右键或确认结束;原阵型不耗条", Small); + foreach (BattleSlot slot in Enum.GetValues(typeof(BattleSlot))) + { + Vector2 point = origin + BattleHudLayout.FormationPosition(slot); + Rect drop = new(point.x, point.y, 40, 38); + RegisterControl("slot:" + (int)slot, drop); + if (_presenter.CapturedPointerId.HasValue && _presenter.FormationActor != null && drop.Contains(_pointer)) + EditorGUI.DrawRect(drop, new Color(1, 1, 0, .2f)); + } + foreach (BattleActorSnapshot actor in _battle.Actors.Where(actor => actor.Side == BattleSide.Ally)) + { + Vector2 point = origin + BattleHudLayout.FormationPosition(actor.Slot); + Rect rect = new(point.x, point.y, 40, 38); + RegisterControl("actor:" + actor.Id, rect); + int identity = BattleData.PlayerIdentity(actor.ActorId); + bool enabled = _battle.CanSwapFormation(actor.Id, actor.Slot) == null; + if (identity is >= 0 and < 5) + { + Color saved = GUI.color; + if (_navigationInput && _presenter.FocusedId == "actor:" + actor.Id) + GUI.color *= new Color(1, 1, 1, .65f + .35f * Mathf.Sin((float)UnityEditor.EditorApplication.timeSinceStartup * 7.8f)); + Sprite(_layout.FormationFace(identity, !enabled), rect); + GUI.color = saved; + } + else + GUI.Label(rect, ActorName(actor), Small); + } + if (_navigationInput && _presenter.FormationActor != null && _presenter.FocusedId?.StartsWith("slot:", StringComparison.Ordinal) == true) + { + BattleActorSnapshot moving = _battle.Actors.First(actor => actor.Id == _presenter.FormationActor); + int identity = BattleData.PlayerIdentity(moving.ActorId); + BattleSlot slot = (BattleSlot)int.Parse(_presenter.FocusedId[5..]); + Color saved = GUI.color; + GUI.color *= new Color(1, 1, 1, .65f); + if (identity is >= 0 and < 5) + Sprite(_layout.FormationFace(identity, false), new Rect(origin + BattleHudLayout.FormationPosition(slot), new Vector2(40, 38))); + GUI.color = saved; + } + TextButton(new Rect(80, 460, 100, 20), "确认阵型", controlId: "end"); + } + + private static readonly Rect AiPanelBounds = new(24, 316, 158, 158); + + private void DrawAi() + { + BattleActorSnapshot[] actors = _battle.Actors.ToArray(); + BattleActorSnapshot selected = actors.FirstOrDefault(actor => actor.Id == _presenter.AiActor) ?? actors.First(); + Sprite("control/AI/back", AiPanelBounds); + int identity = BattleData.PlayerIdentity(selected.ActorId); + if (identity is >= 0 and < 5) + Sprite(_layout.AiName(identity), new Rect(81, 347, 38, 16)); + else + GUI.Label(new Rect(35, 343, 130, 20), ActorName(selected), Small); + int flags = _presenter.AiFlags(selected.Id); + string[] sprites = { "attack", "magic", "skill", "item", "affirmative", "ai" }; + string[] labels = { "普攻", "仙术", "特技", "物品", "全力/万全", "自动" }; + Vector2[] offsets = { new(7, 48), new(78, 73), new(7, 73), new(78, 48), new(7, 98), new(78, 98) }; + for (int bit = 0; bit < sprites.Length; bit++) + { + Vector2 at = new Vector2(24, 316) + offsets[bit]; + SpriteButton("control/AI/" + sprites[bit], new Rect(at.x, at.y, 73, 25), selected: bit == 4 ? (flags & 16) == 0 : (flags & 1 << bit) != 0, + tooltip: labels[bit], disabledImage: false); + } + SpriteButton("control/AI/ok", new Rect(59, 443, 92, 26)); + + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Configuration.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Configuration.cs.meta new file mode 100644 index 00000000..44fe40b9 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Configuration.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: aaa689581acf45ea95ca0c109bda862d diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Dismiss.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Dismiss.cs new file mode 100644 index 00000000..afe585da --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Dismiss.cs @@ -0,0 +1,116 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using Battle.Presentation; + using UnityEngine; + + public sealed partial class BattleHudView + { + private int? _outsidePointer; + private Vector2 _outsideStart; + private BattleHudPage _outsidePage; + private bool _outsideDragged; + private readonly HashSet _retiredPointers = new(); + + private bool AbilityMenuOpen => _presenter.Controller != null && + _presenter.Page is BattleHudPage.Skills or BattleHudPage.Magic or BattleHudPage.Items; + + private Vector2 CommandPageOrigin(float scale) => new(0, _viewport.CanvasSize.y - 118 - 482 * scale); + + private Rect AbilityMenuViewport() + { + Rect panel = BattleHudText.AbilityPanelBounds(_presenter.Page, _layout.IsPal3A); + Rect list = BattleHudText.ListBounds(_presenter.Page, _layout.IsPal3A); + list.position += panel.position; + Rect description = BattleHudText.DescriptionBounds(_presenter.Page, _layout.IsPal3A); + description.position += panel.position; + // PAL3A's scrollbar extends four pixels beyond its panel image. + Rect bounds = Rect.MinMaxRect(Math.Min(panel.xMin, list.xMin), Math.Min(panel.yMin, list.yMin), + Math.Max(panel.xMax, Math.Max(list.xMax, description.xMax)), Math.Max(panel.yMax, Math.Max(list.yMax, description.yMax))); + return CommandPanelViewport(bounds); + } + + private Rect CommandPanelViewport(Rect bounds) + { + float scale = _interaction.ScaleFor(_viewport); + return new Rect(_viewport.ToViewport(CommandPageOrigin(scale) + bounds.position * scale), bounds.size * (scale * _viewport.Scale)); + } + + private bool IsOutsideMenu(Vector2 point, string control) + { + if (!_viewport.Viewport.Contains(point)) + return false; + if (AbilityMenuOpen) + return !AbilityMenuViewport().Contains(point); + return _presenter.Page == BattleHudPage.Ai && control == null && !CommandPanelViewport(AiPanelBounds).Contains(point); + } + + // Capture the whole outside tap so its release cannot activate a + // control on the parent page or start a camera/actor operation. + private bool OutsideMenuGesture(BattleHudIntentKind phase, int pointer, Vector2 point, string control) + { + if (_outsidePointer.HasValue) + { + if (_outsidePointer != pointer) + { + if (phase != BattleHudIntentKind.PointerDown) + return false; + _retiredPointers.Add(pointer); + return true; + } + if ((point - _outsideStart).sqrMagnitude > 64) + _outsideDragged = true; + if (phase is BattleHudIntentKind.PointerUp or BattleHudIntentKind.PointerCancel) + { + bool back = phase == BattleHudIntentKind.PointerUp && !_outsideDragged && + _presenter.Page == _outsidePage && IsOutsideMenu(point, control); + _outsidePointer = null; + _outsideDragged = false; + if (back) + Dispatch(new BattleHudIntent(BattleHudIntentKind.Back)); + } + return true; + } + if (phase != BattleHudIntentKind.PointerDown || _presenter.CapturedPointerId.HasValue || + _touchCandidatePointer.HasValue || !IsOutsideMenu(point, control)) + return false; + _touchTargetArmed = null; + _pointerTarget = null; + _outsidePointer = pointer; + _outsideStart = point; + _outsidePage = _presenter.Page; + _outsideDragged = false; + return true; + } + + private bool ConsumeRetiredPointer(BattleHudIntentKind phase, int pointer) + { + if (!_retiredPointers.Contains(pointer)) + return false; + if (phase == BattleHudIntentKind.PointerDown) + { + // The previous release may have happened outside this window. + // A fresh press starts a new gesture even if its ID is reused. + _retiredPointers.Remove(pointer); + return false; + } + if (phase is BattleHudIntentKind.PointerUp or BattleHudIntentKind.PointerCancel) + _retiredPointers.Remove(pointer); + return true; + } + + private void ResetOutsideGesture() + { + if (_outsidePointer is int pointer) + _retiredPointers.Add(pointer); + _outsidePointer = null; + _outsideDragged = false; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Dismiss.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Dismiss.cs.meta new file mode 100644 index 00000000..116bceca --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Dismiss.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ca23c0d117f24bb0a5b3e23060fe2511 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.GuiInput.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.GuiInput.cs new file mode 100644 index 00000000..3d5548cc --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.GuiInput.cs @@ -0,0 +1,124 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using Battle.Presentation; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattleHudView + { + private int _guiPointerControl, _guiCapturedControl; + + private bool OwnsGuiPointer => _guiCapturedControl != 0 && GUIUtility.hotControl == _guiCapturedControl; + + private bool ForeignGuiPointer => GUIUtility.hotControl != 0 && !OwnsGuiPointer; + + private void PrepareGuiInput() + { + // Request this at the same place on every GUI pass, independently + // of the command page or the controls drawn by that page. + _guiPointerControl = GUIUtility.GetControlID(0x42617448, FocusType.Passive); + if (_guiCapturedControl != 0 && !OwnsGuiPointer) + CancelInput(); + // A native scrollbar can claim the mouse after the HUD processed + // the press. Its drag and release bypass the HUD input handler. + if (ForeignGuiPointer && _touchCandidatePointer == 0 && !_presenter.CapturedPointerId.HasValue) + ResetTouchGesture(); + } + + private void CaptureGuiPointer() + { + if (_guiPointerControl != 0 && GUIUtility.hotControl == 0) + { + _guiCapturedControl = _guiPointerControl; + GUIUtility.hotControl = _guiCapturedControl; + } + } + + private void ReleaseGuiPointer() + { + if (OwnsGuiPointer) + GUIUtility.hotControl = 0; + _guiCapturedControl = 0; + } + + internal static bool CanReadBattleKey(Event input) => GUIUtility.keyboardControl == 0 && + !EditorGUIUtility.editingTextField && IsBattleKey(input); + + internal static void TakeGuiKeyboardFocus() + { + GUIUtility.keyboardControl = 0; + EditorGUIUtility.editingTextField = false; + } + + private void HandleGuiInput(Event input, Rect content) + { + if (_inputEnabled && !ForeignGuiPointer && CanReadBattleKey(input) && KeyboardIntent(input.keyCode) is { } keyIntent) + { + TakeNavigationInput(); + Dispatch(keyIntent); + input.Use(); + } + if (!ForeignGuiPointer && input.button == 0 && input.type is EventType.MouseDown or EventType.MouseMove or EventType.MouseDrag or EventType.MouseUp) + { + EventType type = input.type; + bool captured = OwnsGuiPointer; + try + { + BattleHudIntentKind phase = type == EventType.MouseDown ? BattleHudIntentKind.PointerDown : + type == EventType.MouseUp ? BattleHudIntentKind.PointerUp : BattleHudIntentKind.PointerMove; + if (SendPointer(phase, 0, input.mousePosition)) + { + if (type == EventType.MouseDown) + { + if (content.Contains(input.mousePosition)) + TakeGuiKeyboardFocus(); + CaptureGuiPointer(); + } + input.Use(); + } + else if (captured && type != EventType.MouseMove) + input.Use(); + } + finally + { + if (type == EventType.MouseUp) + ReleaseGuiPointer(); + } + } + if (_inputEnabled && !ForeignGuiPointer && _presenter.Controller != null && _presenter.Page != BattleHudPage.Commands && + input.type == EventType.MouseDown && input.button == 1 && _viewport.SafeRect.Contains(input.mousePosition) && + Dispatch(new BattleHudIntent(BattleHudIntentKind.Back))) + { + TakeGuiKeyboardFocus(); + input.Use(); + } + } + + internal void CompleteGuiInput(Event input, Rect content) + { + if (ForeignGuiPointer || !OwnsGuiPointer && !content.Contains(input.mousePosition)) + return; + switch (input.type) + { + case EventType.MouseDown when input.button == 0: + TakeGuiKeyboardFocus(); + CaptureGuiPointer(); + input.Use(); + break; + case EventType.MouseUp when input.button == 0: + ReleaseGuiPointer(); + input.Use(); + break; + case EventType.MouseDrag when input.button == 0: + case EventType.ScrollWheel: + input.Use(); + break; + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.GuiInput.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.GuiInput.cs.meta new file mode 100644 index 00000000..a690988f --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.GuiInput.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 763887a5567541029ede241ae16633c4 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Input.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Input.cs new file mode 100644 index 00000000..a64cd0b7 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Input.cs @@ -0,0 +1,493 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle.Presentation; + using UnityEngine; + + public sealed partial class BattleHudView + { + private readonly List<(string Id, Rect Rect)> _hitControls = new(); + private readonly HashSet _interactiveControls = new(StringComparer.Ordinal); + private readonly Dictionary<(string Id, Rect Rect), SpriteHitRegion> _spriteHitRegions = new(); + private readonly Dictionary _spritePixels = new(); + private Action _repaint; + + private sealed class SpritePixels + { + public readonly Color32[] Pixels; + public readonly int Width; + public readonly int Height; + + public SpritePixels(Texture2D texture) + { + Pixels = texture.GetPixels32(); + Width = texture.width; + Height = texture.height; + } + + // UIButtonEX/UIButtonEXA use an alpha threshold of six for their + // visible surface; the older eighteen threshold is commented out. + public bool Opaque(int x, int y) => x >= 0 && x < Width && y >= 0 && y < Height && Pixels[y * Width + x].a >= 6; + } + + private readonly struct SpriteHitRegion + { + private readonly SpritePixels _pixels; + private readonly Rect _rect; + private readonly Vector2 _nativeSize; + + public SpriteHitRegion(SpritePixels pixels, Rect rect, Vector2 nativeSize) + { + _pixels = pixels; + _rect = rect; + _nativeSize = nativeSize; + } + + public bool Contains(Vector2 point) + { + if (!_rect.Contains(point)) + return false; + Vector2 local = point - _rect.position; + return _pixels.Opaque(Mathf.FloorToInt(local.x * _nativeSize.x / _rect.width), + Mathf.CeilToInt(_nativeSize.y) - 1 - Mathf.FloorToInt(local.y * _nativeSize.y / _rect.height)); + } + + public float DistanceSquared(Vector2 point, float padding) + { + Vector2 scale = new(_rect.width / _nativeSize.x, _rect.height / _nativeSize.y); + Vector2 local = point - _rect.position; + int left = Math.Max(0, Mathf.FloorToInt((local.x - padding) / scale.x)); + int right = Math.Min(Mathf.CeilToInt(_nativeSize.x) - 1, Mathf.FloorToInt((local.x + padding) / scale.x)); + int top = Math.Max(0, Mathf.FloorToInt((local.y - padding) / scale.y)); + int bottom = Math.Min(Mathf.CeilToInt(_nativeSize.y) - 1, Mathf.FloorToInt((local.y + padding) / scale.y)); + float distance = float.PositiveInfinity; + for (int y = top; y <= bottom; y++) + for (int x = left; x <= right; x++) + { + // GUI's top edge samples the top of the cropped UV + // region, while GetPixels32 starts at texture row zero. + if (!_pixels.Opaque(x, Mathf.CeilToInt(_nativeSize.y) - 1 - y)) + continue; + var pixel = new Rect(_rect.position + new Vector2(x * scale.x, y * scale.y), scale); + distance = Math.Min(distance, RectangleDistanceSquared(pixel, point)); + } + return distance; + } + } + + private void ClearHitControls() + { + _hitControls.Clear(); + _spriteHitRegions.Clear(); + } + + private static float RectangleDistanceSquared(Rect rect, Vector2 point) + { + float x = Math.Max(rect.xMin - point.x, Math.Max(0, point.x - rect.xMax)); + float y = Math.Max(rect.yMin - point.y, Math.Max(0, point.y - rect.yMax)); + return x * x + y * y; + } + + private void RegisterControl(string id, Rect rect, Texture2D sprite = null) + { + if (id == null || Event.current.type != EventType.Repaint) + return; + if (sprite != null) + rect.size = new Vector2(Math.Min(rect.width, sprite.width), Math.Min(rect.height, sprite.height)); + Vector2 nativeSize = rect.size; + rect = new Rect(_pageOffset + rect.position * _pageScale, rect.size * _pageScale); + _hitControls.Add((id, rect)); + if (sprite != null) + { + if (!_spritePixels.TryGetValue(sprite, out SpritePixels pixels)) + _spritePixels.Add(sprite, pixels = new SpritePixels(sprite)); + _spriteHitRegions[(id, rect)] = new SpriteHitRegion(pixels, rect, nativeSize); + } + } + + private string HitControl(Vector2 point, bool slotsOnly, bool inspectMagicRows = false) + { + _interactiveControls.Clear(); + foreach (BattleHudFocus item in _presenter.FocusItems()) + if (item.Enabled || inspectMagicRows && item.Id.StartsWith("ability:", StringComparison.Ordinal)) + _interactiveControls.Add(item.Id); + // Inside an ability list, padding must not turn a disabled row or + // scrollbar press into a neighbouring command. + bool expanded = _interaction.Touch && !(AbilityMenuOpen && _touchPanel.Contains(_viewport.ToViewport(point))); + float padding = _interaction.HitPadding / _viewport.Scale; + float nearest = padding * padding; + string id = null; + for (int i = _hitControls.Count - 1; i >= 0; i--) + { + var control = _hitControls[i]; + if ((!_interactiveControls.Contains(control.Id) && !control.Id.StartsWith("inspect:", StringComparison.Ordinal)) || + (slotsOnly && !control.Id.StartsWith("slot:", StringComparison.Ordinal))) + continue; + bool sprite = _spriteHitRegions.TryGetValue(control, out SpriteHitRegion region); + if (sprite ? region.Contains(point) : control.Rect.Contains(point)) + return control.Id; + if (!expanded) + continue; + float distance = sprite ? region.DistanceSquared(point, padding) : RectangleDistanceSquared(control.Rect, point); + if (distance <= nearest && (id == null || distance < nearest)) + { + nearest = distance; + id = control.Id; + } + } + return id; + } + + public bool SendPointer(BattleHudIntentKind phase, int pointerId, Vector2 viewportPoint) + { + if (ConsumeRetiredPointer(phase, pointerId)) + return true; + if (!_inputEnabled) + return false; + if (phase == BattleHudIntentKind.PointerDown && + (_presenter.CapturedPointerId == pointerId || _touchCandidatePointer == pointerId || + _touchWorldPointer == pointerId || _outsidePointer == pointerId)) + { + // A fresh press proves that the old release was lost. End that + // gesture without consuming this new press/release pair. + CancelInput(); + _retiredPointers.Remove(pointerId); + } + if (phase == BattleHudIntentKind.PointerDown && + (_outsidePointer.HasValue && _outsidePointer != pointerId || + _touchCandidatePointer.HasValue && _touchCandidatePointer != pointerId || + _presenter.CapturedPointerId.HasValue && _presenter.CapturedPointerId != pointerId)) + { + _retiredPointers.Add(pointerId); + return true; + } + if (phase == BattleHudIntentKind.PointerDown && !_viewport.Viewport.Contains(viewportPoint)) + return false; + if (phase == BattleHudIntentKind.PointerDown || phase == BattleHudIntentKind.PointerMove && + (!_lastPointer.HasValue || (_lastPointer.Value - viewportPoint).sqrMagnitude > .01f)) + { + if (_navigationInput) + PointerTookControl?.Invoke(); + _navigationInput = false; + _lastPointer = viewportPoint; + } + Vector2 point = _viewport.ToCanvas(viewportPoint); + bool slotsOnly = _presenter.CapturedPointerId == pointerId && _presenter.FormationActor != null && phase != BattleHudIntentKind.PointerDown; + string id = slotsOnly ? HitControl(point, true) : null; + string actor = null; + if (WorldSelectionOpen) + { + var actors = WorldSelectionActors(); + actor = _preview.PickActor(viewportPoint, _viewport.Viewport, _battle.Actors.Select(value => value.Id)); + if (actor == null && _interaction.Touch && _viewport.Viewport.Contains(viewportPoint)) + actor = actors.Where(target => _preview.TryActorSelectionPoint(target.Actor, _viewport.Viewport, out Vector2 center) && Vector2.Distance(center, viewportPoint) <= 28) + .OrderBy(target => + { + _preview.TryActorSelectionPoint(target.Actor, _viewport.Viewport, out Vector2 center); + return Vector2.Distance(center, viewportPoint); + }).Select(target => target.Actor).FirstOrDefault(); + id = actor == null ? null : actors.FirstOrDefault(target => target.Actor == actor).Control; + // The original AI flag panel still owns its native controls. + if (_presenter.Page == BattleHudPage.Ai) + id = HitControl(point, false) ?? (CommandPanelViewport(AiPanelBounds).Contains(viewportPoint) ? null : id); + } + if (OutsideMenuGesture(phase, pointerId, viewportPoint, id)) + return true; + if (TouchGesture(phase, pointerId, viewportPoint)) + return true; + if (WorldSelectionOpen) + { + if (id == null && phase == BattleHudIntentKind.PointerDown) + { + _pointerTarget = null; + _touchTargetArmed = null; + _touchWorldPreview = null; + _touchWorldPointer = null; + _presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerCancel, pointerId: pointerId)); + if (_presenter.Page is BattleHudPage.Targets or BattleHudPage.Protection) + Dispatch(new BattleHudIntent(BattleHudIntentKind.Back)); + _retiredPointers.Add(pointerId); + return true; + } + if (!_navigationInput || phase == BattleHudIntentKind.PointerDown || + phase == BattleHudIntentKind.PointerMove && (!_lastPointer.HasValue || (_lastPointer.Value - viewportPoint).sqrMagnitude > .01f)) + _pointerTarget = id == null ? null : actor; + } + else + id ??= HitControl(point, false, inspectMagicRows: phase == BattleHudIntentKind.PointerMove && + _presenter.Page == BattleHudPage.Magic); + if (_navigationInput && phase == BattleHudIntentKind.PointerMove) + return false; + if (_interaction.Touch && WorldSelectionOpen) + { + bool worldControl = id != null && (id.StartsWith("target:", StringComparison.Ordinal) || id.StartsWith("protect:", StringComparison.Ordinal) || id.StartsWith("ai-actor:", StringComparison.Ordinal)); + if (phase == BattleHudIntentKind.PointerDown) + { + if (_touchWorldPointer == pointerId) + { + _presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerCancel, pointerId: pointerId)); + _touchTargetArmed = null; + } + _touchWorldPointer = null; + _touchWorldPreview = null; + if (worldControl) + { + _touchTargetConfirm = _presenter.Page == BattleHudPage.Targets || _touchTargetArmed == id; + _touchTargetArmed = null; + _touchWorldPreview = id; + _touchWorldPointer = pointerId; + _touchWorldStart = viewportPoint; + _touchWorldDragged = false; + } + else + _touchTargetArmed = null; + } + if (_touchWorldPointer == pointerId && phase is BattleHudIntentKind.PointerMove or BattleHudIntentKind.PointerUp && + (viewportPoint - _touchWorldStart).sqrMagnitude > 64) + _touchWorldDragged = true; + if (_touchWorldPointer == pointerId && phase is BattleHudIntentKind.PointerUp or BattleHudIntentKind.PointerCancel) + { + bool valid = phase == BattleHudIntentKind.PointerUp && !_touchWorldDragged && id == _touchWorldPreview; + bool confirm = valid && _touchTargetConfirm; + _touchWorldPointer = null; + _touchWorldPreview = null; + _touchTargetConfirm = false; + if (!confirm) + { + _presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerCancel, pointerId: pointerId)); + _touchTargetArmed = valid ? id : null; + if (valid) + _presenter.SetFocus(id); + _repaint?.Invoke(); + return true; + } + } + } + if (phase == BattleHudIntentKind.PointerDown && !_presenter.CapturedPointerId.HasValue && + id?.StartsWith("inspect:", StringComparison.Ordinal) == true) + { + // Inspector selection is an editor tool operation, separate from + // the presenter's recorded battle commands and focus navigation. + _selectActor?.Invoke(id[8..]); + _repaint?.Invoke(); + return true; + } + if (phase == BattleHudIntentKind.PointerMove && !_presenter.CapturedPointerId.HasValue) + { + bool inspected = _presenter.InspectAbilityRow(id); + bool focused = id != null && _presenter.SetFocus(id); + if (inspected) + _changed?.Invoke(); + else if (focused) + _repaint?.Invoke(); + return inspected || focused; + } + bool captured = _presenter.CapturedPointerId == pointerId; + bool accepted = Dispatch(new BattleHudIntent(phase, id, pointerId)); + return accepted || captured; + } + + internal static bool IsBattleKey(Event input) => input.type == EventType.KeyDown && + (input.modifiers & (EventModifiers.Command | EventModifiers.Control | EventModifiers.Alt)) == 0 && + input.keyCode is not (KeyCode.None or KeyCode.LeftShift or KeyCode.RightShift or KeyCode.LeftControl or KeyCode.RightControl or + KeyCode.LeftAlt or KeyCode.RightAlt or KeyCode.LeftCommand or KeyCode.RightCommand or KeyCode.CapsLock or KeyCode.AltGr); + + public event Action PointerTookControl; + + public event Action KeyboardTookControl; + + private bool _navigationInput; + private BattleHudDirection? _gamepadPointingDirection; + private Vector2? _lastPointer; + private string _touchTargetArmed; + private string _pointerTarget; + private bool _touchTargetConfirm; + private int? _touchWorldPointer; + private Vector2 _touchWorldStart; + private string _touchWorldPreview; + private bool _touchWorldDragged; + + public void TakeNavigationInput(Battle.BattleSession combat = null) + { + KeyboardTookControl?.Invoke(); + TakeNavigationInputCore(combat); + } + + public void TakeGamepadInput(Battle.BattleSession combat = null) + { + TakeNavigationInputCore(combat); + } + + private void TakeNavigationInputCore(Battle.BattleSession combat) + { + _gamepadPointingDirection = null; + CancelInput(); + if (combat != null) + { + if (_battle != combat) + ClearHitControls(); + _battle = combat; + Synchronize(combat); + } + _navigationInput = true; + _pointerTarget = null; + SetInputFocus(true); + } + + public bool SendIntent(BattleHudIntent intent) => Dispatch(intent); + + public bool SendGamepadIntent(BattleEditorGamepadIntent input) + { + BattleHudDirection? pointingDirection = input.PointingDirection; + _gamepadPointingDirection = pointingDirection; + BattleHudIntent? intent = input.Kind switch + { + BattleEditorGamepadIntentKind.Point when _presenter.Page == BattleHudPage.Commands => new BattleHudIntent(BattleHudIntentKind.Navigate, direction: input.Direction), + BattleEditorGamepadIntentKind.Navigate => new BattleHudIntent(BattleHudIntentKind.Navigate, direction: input.Direction), + BattleEditorGamepadIntentKind.Confirm => new BattleHudIntent(BattleHudIntentKind.Confirm), + BattleEditorGamepadIntentKind.Cancel => new BattleHudIntent(BattleHudIntentKind.Back), + BattleEditorGamepadIntentKind.PreviousSection => new BattleHudIntent(BattleHudIntentKind.CyclePrevious), + BattleEditorGamepadIntentKind.NextSection => new BattleHudIntent(BattleHudIntentKind.CycleNext), + BattleEditorGamepadIntentKind.Primary => new BattleHudIntent(BattleHudIntentKind.Primary), + BattleEditorGamepadIntentKind.Repeat => new BattleHudIntent(BattleHudIntentKind.Repeat), + _ => null + }; + BattleHudPage before = _presenter.Page; + if (intent?.Kind == BattleHudIntentKind.Confirm && before == BattleHudPage.Commands && + pointingDirection.HasValue && (pointingDirection != BattleHudDirection.Neutral || CommandRingFocused())) + ApplyGamepadPointing(); + bool accepted = intent.HasValue && Dispatch(intent.Value); + if (before != BattleHudPage.Commands && _presenter.Page == BattleHudPage.Commands) + ApplyGamepadPointing(); + return accepted; + } + + private bool CommandRingFocused() + { + string focus = _presenter.FocusedId; + foreach (BattleHudFocus item in _presenter.FocusItems()) + if (item.Id == focus) + return item.Column is >= 0 and <= 2 && item.Row is >= 0 and <= 2; + return false; + } + + private void ApplyGamepadPointing() + { + if (_navigationInput && _hasInputFocus && _gamepadPointingDirection is BattleHudDirection direction && + _presenter.Page == BattleHudPage.Commands) + _presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: direction)); + } + + private bool Dispatch(BattleHudIntent intent) + { + if (!_inputEnabled) + return false; + if (intent.Kind == BattleHudIntentKind.Back) + CancelInput(); + if (intent.Kind == BattleHudIntentKind.Navigate && + _presenter.Page is BattleHudPage.Targets or BattleHudPage.Protection) + PublishFocusLayout(); + int before = _battle.RecordedInputCount; + string message = _presenter.Message; + BattleHudPage page = _presenter.Page; + string controller = _presenter.Controller; + string focused = _presenter.FocusedId; + int category = _presenter.Category; + bool accepted = _presenter.Handle(intent); + PlayInputSounds(intent, page, controller, focused, category, accepted); + if (_battle.RecordedInputCount != before) + _changed?.Invoke(); + else if (accepted || message != _presenter.Message || page != _presenter.Page) + _repaint?.Invoke(); + return accepted || _presenter.ActivatedControl != null || page != _presenter.Page || message != _presenter.Message; + } + + public static BattleHudIntent? KeyboardIntent(KeyCode key) => key switch + { + KeyCode.UpArrow or KeyCode.W => new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Up), + KeyCode.DownArrow or KeyCode.S => new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Down), + KeyCode.LeftArrow or KeyCode.A => new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Left), + KeyCode.RightArrow or KeyCode.D => new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Right), + KeyCode.Keypad7 or KeyCode.Q => new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.UpLeft), + KeyCode.Keypad9 or KeyCode.E => new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.UpRight), + KeyCode.Keypad1 or KeyCode.Z => new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.DownLeft), + KeyCode.Keypad3 or KeyCode.C => new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.DownRight), + KeyCode.Keypad5 or KeyCode.X => new BattleHudIntent(BattleHudIntentKind.Primary), + KeyCode.Tab => new BattleHudIntent(BattleHudIntentKind.CycleNext), + KeyCode.Return or KeyCode.KeypadEnter or KeyCode.Space => new BattleHudIntent(BattleHudIntentKind.Confirm), + KeyCode.Escape => new BattleHudIntent(BattleHudIntentKind.Back), + KeyCode.F => new BattleHudIntent(BattleHudIntentKind.Normal), + KeyCode.R => new BattleHudIntent(BattleHudIntentKind.Repeat), + _ => null + }; + + public void SetInputFocus(bool active) + { + _hasInputFocus = active; + if (!active) + _gamepadPointingDirection = null; + _inputEnabled = active && _battle?.Status == Battle.BattleSessionStatus.Running && !_battle.IsModalPresentation; + if (!active) + CancelInput(); + } + + public void CancelInput() + { + ReleaseGuiPointer(); + _pointerTarget = null; + if (_touchCandidatePointer is int touch) + _retiredPointers.Add(touch); + if (_presenter.CapturedPointerId is int captured) + _retiredPointers.Add(captured); + ResetTouchGesture(); + ResetOutsideGesture(); + _touchTargetArmed = null; + _touchTargetConfirm = false; + _touchWorldPointer = null; + _touchWorldPreview = null; + if (_presenter.CapturedPointerId is int pointer) + _presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerCancel, pointerId: pointer)); + } + + private static string ControlId(string resource) => resource switch + { + "control/attack" => "attack", + "control/skill" => "skills", + "control/magic" => "magic", + "control/item" => "items", + "control/defence" => "defend", + "control/flee" => "flee", + "control/lineup" => "formation", + "control/protect" => "protection", + "control/ai" => "ai", + "control/mj" => "sword", + "control/bs" => "transform", + "control/AI/attack" => "flag:0", + "control/AI/magic" => "flag:1", + "control/AI/skill" => "flag:2", + "control/AI/item" => "flag:3", + "control/ItemList/recover" => "category:0", + "control/ItemList/attack" => "category:1", + "control/ItemList/treasure" => "category:2", + "control/MagicList/water" => "category:0", + "control/MagicList/fire" => "category:1", + "control/MagicList/thunder" => "category:2", + "control/MagicList/wind" => "category:3", + "control/MagicList/earth" => "category:4", + "control/MagicList/double" => "category:5", + "control/AI/affirmative" => "flag:4", + "control/AI/ai" => "flag:5", + "control/AI/ok" => "end", + "control/Protect/ok" => "end", + _ => null + }; + + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Input.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Input.cs.meta new file mode 100644 index 00000000..7f053c43 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Input.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 06027f512d2c46ee993b1c1e9d6dc3ff diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Pointers.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Pointers.cs new file mode 100644 index 00000000..e6343b51 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Pointers.cs @@ -0,0 +1,115 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Battle.Presentation; + using Core.DataReader.Cvd; + using Game.Rendering.Native; + using Game.Rendering.Renderer; + using ResourceBrowser; + using UnityEngine; + using UnityEditor; + + public sealed partial class BattleHudView + { + private ResourceModelPreview _pointerOwner; + private readonly Dictionary _pointers = new(StringComparer.Ordinal); + private CvdFile _pointerModel; + + public static IReadOnlyList PointerActors(BattleSession combat, BattleHudPresenter presenter) + { + if (combat == null || combat.IsModalPresentation || combat.Status != BattleSessionStatus.Running || presenter.Controller == null) + return Array.Empty(); + string focus = presenter.FocusedId; + string selectedActor = presenter.Page == BattleHudPage.Ai ? (focus?.StartsWith("ai-actor:", StringComparison.Ordinal) == true ? focus[9..] : presenter.AiActor) : + presenter.Page == BattleHudPage.Protection ? (focus?.StartsWith("protect:", StringComparison.Ordinal) == true ? focus[8..] : presenter.ProtectionSelection) : presenter.Controller; + IEnumerable selected = presenter.Page == BattleHudPage.Targets ? presenter.Affected : + presenter.Page != BattleHudPage.Formation ? combat.Actors.Where(actor => actor.Id == selectedActor) : Array.Empty(); + return selected.Select(actor => actor.Id).ToArray(); + } + + private void ReleasePointers() + { + if (_pointerOwner?.Root != null) + foreach (var pointer in _pointers.Values) + if (pointer.Object != null) + _pointerOwner.ReleaseCompositeObject(pointer.Object); + _pointers.Clear(); + _pointerOwner = null; + _pointerModel = null; + } + + private static void SetPointerVisible(GameObject target, bool visible) + { + // CvdModelRenderer disposes on MonoBehaviour.OnDisable. Visibility + // must keep the model alive for selection changes and paused redraws. + foreach (Renderer renderer in target.GetComponentsInChildren(true)) + renderer.enabled = visible; + } + + public void PreparePointers(BattleSession combat, BattleData data, BattlePreview preview, double? presentationSeconds = null) + { + Synchronize(combat); + if (_pointerOwner != preview.View) + { + if (_pointerOwner?.Root != null) + foreach (var old in _pointers.Values) + if (old.Object != null) + _pointerOwner.ReleaseCompositeObject(old.Object); + _pointers.Clear(); + _pointerOwner = preview.View; + _pointerModel = null; + } + if (_pointerOwner.Root == null) + { + _pointers.Clear(); + return; + } + double seconds = presentationSeconds ?? EditorApplication.timeSinceStartup; + bool previewTargets = WorldSelectionOpen && (_navigationInput || + _interaction.Touch && (_touchTargetArmed != null || _touchWorldPreview != null) || !_interaction.Touch && _pointerTarget != null); + string[] selected = WorldSelectionOpen && !previewTargets ? Array.Empty() : PointerActors(combat, _presenter).ToArray(); + preview.SetSelection(previewTargets ? selected : Array.Empty(), seconds); + foreach (var pointer in _pointers.Values) + if (pointer.Object != null) + SetPointerVisible(pointer.Object, false); + foreach (string id in selected) + { + if (!preview.TryHudPointerPose(combat, id, out Vector3 position, out float scale, seconds)) + continue; + if (!_pointers.TryGetValue(id, out var pointer)) + { + const string path = "basedata.cpk\\ui\\combat\\pointer\\pointer.cvd"; + _pointerModel ??= data.Read(path, new CvdFileReader()); + GameObject target = _pointerOwner.CreateObject("Battle selection pointer " + id); + try + { + pointer = (target, _pointerOwner.SetHierarchicalModel(target, path, _pointerModel)); + _pointers.Add(id, pointer); + } + catch + { + _pointerOwner.ReleaseCompositeObject(target); + throw; + } + BattleActorSnapshot actor = combat.Actors.First(actor => actor.Id == id); + if (!_pointerOwner.UsesToonRendering) + GameBoxBattleRenderPhase.Apply(target, GameBoxBattleRenderOrder.Actor(combat.Variant == "PAL3A", + actor.Side == BattleSide.Ally, actor.ActorId)); + } + SetPointerVisible(pointer.Object, true); + pointer.Object.transform.SetPositionAndRotation(position, Quaternion.identity); + pointer.Object.transform.localScale = new Vector3(1, scale, 1); + float duration = _pointerModel.AnimationDuration; + pointer.Renderer.SetCurrentTime(duration > 0 ? (float)(seconds % duration) : 0); + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Pointers.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Pointers.cs.meta new file mode 100644 index 00000000..bde74237 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Pointers.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 023b902792ba417e887a91ab6bdb7562 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.SceneField.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.SceneField.cs new file mode 100644 index 00000000..6720ba82 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.SceneField.cs @@ -0,0 +1,29 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using UnityEngine; + + public sealed partial class BattleHudView + { + private void DrawSceneField() + { + if (!_layout.IsPal3A || _battle.FiveSpiritElement is < 1 or > 5) + return; + int resource = _battle.FiveSpiritElement switch + { + 3 => 3, + 4 => 2, + _ => _battle.FiveSpiritElement - 1 + }; + // The released UI creates six overlapping widgets with allied + // defaults. Field updates hide all six, replace the selected + // element's image for force 1/2, then show that widget only. + string force = _battle.FiveSpiritForce == 2 ? "e" : "w"; + Sprite($"control/{force}_sx{resource}", new Rect(_viewport.CanvasSize.x - 56, 81, 45, 60)); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.SceneField.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.SceneField.cs.meta new file mode 100644 index 00000000..c489d233 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.SceneField.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 359a3693f6bf40698cdce8e9d26a60be diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.State.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.State.cs new file mode 100644 index 00000000..9de379f2 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.State.cs @@ -0,0 +1,140 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Battle; + using Battle.Presentation; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattleHudView + { + private void DrawStateCards(IReadOnlyList actors) + { + int index = 0; + foreach (BattleActorSnapshot actor in actors) + { + if (actor.Side != BattleSide.Ally) + continue; + Rect card = _viewport.StateCard(index); + bool sword = !_layout.IsPal3A && index % 4 == 0; + Sprite(sword ? "state/StatePanel0" : "state/StatePanel", new Rect(card.x, card.y, 157, 106)); + int identity = BattleData.PlayerIdentity(actor.ActorId); + if (identity is >= 0 and < 5) + { + float faceX = _layout.IsPal3A ? 33 : sword ? 43 : 33; + Color previous = GUI.color; + GUI.color *= BattleHudLayout.FaceTint(actor); + Sprite(_layout.StateFace(identity), new Rect(card.x + faceX, card.y + 14, 64, _layout.IsPal3A ? 93 : 82)); + GUI.color = previous; + Sprite(_layout.StateName(identity), new Rect(card.x + (sword ? 38 : 24), card.y + 39, 20, _layout.IsPal3A ? 50 : 32)); + } + else + GUI.Label(new Rect(card.x + 8, card.y + 7, 105, 20), ActorName(actor), Small); + float offset = sword ? 12 : 0; + DrawVital(card.x + 107 + offset, card.y + 28, actor.Hp, actor.MaxHp, "HP"); + DrawVital(card.x + 116 + offset, card.y + 54, actor.Sp, actor.MaxSp, "GP"); + DrawVital(card.x + 109 + offset, card.y + 82, actor.Mp, actor.MaxMp, "MP"); + if (sword) + { + Rect bar = new(card.x + 12, card.y + 17, 30, 86); + Sprite("state/swordbar", bar); + float fraction = Mathf.Clamp01((actor.MagicSword?.Energy ?? 0) / 200); + if (fraction > 0) + { + GUI.BeginGroup(new Rect(bar.x, bar.y + bar.height * (1 - fraction), bar.width, bar.height * fraction)); + try + { + Sprite("state/sword", new Rect(0, -bar.height * (1 - fraction), bar.width, bar.height)); + } + finally + { + GUI.EndGroup(); + } + } + } + foreach (BattleStatusSnapshot state in actor.States.Where(state => state.LatentRounds == 0)) + { + string resource = StateResource(state.State); + if (resource == null || BattleHudLayout.StatusRect(state.State) is not { } icon) + continue; + icon.position += card.position; + Color previous = GUI.color; + float luminance = BattleHudLayout.StatusLuminance(_battle.SimulationTick * BattleSession.StepSeconds); + GUI.color *= new Color(luminance, luminance, luminance, 1); + Sprite("state/specstate/" + resource, icon); + GUI.color = previous; + GUI.Label(icon, new GUIContent("", state.State + (state.Permanent ? "" : $" · {state.RemainingRounds}回合"))); + } + GUI.Label(card, new GUIContent("", $"{ActorName(actor)} · {actor.Slot} · {actor.Pose}\n精 {actor.Hp}/{actor.MaxHp} · 气 {actor.Sp}/{actor.MaxSp} · 神 {actor.Mp}/{actor.MaxMp}\n状态:" + string.Join("、", actor.States.Select(state => state.State.ToString())))); + RegisterControl("inspect:" + actor.Id, card); + index++; + } + } + + private void DrawVital(float x, float y, int value, int maximum, string name) + { + Sprite("state/ProgBar", new Rect(x, y, 85, 12)); + float fraction = maximum > 0 ? Mathf.Clamp01(value / (float)maximum) : 0; + if (fraction > 0) + Sprite("state/ProgBar_" + name, BattleHudCanvas.ProgressFill(new Rect(x, y, 85, 12), fraction, false)); + BattleHudCanvas.DrawVitalNumber(new Rect(x, y, 85, 12), value, name); + } + + private void DrawSequence(IReadOnlyList actors) + { + float extraWidth = _viewport.CanvasSize.x - 800; + Sprite("AttackSequen/Back", new Rect(_layout.AttackSequenceX + extraWidth, _layout.AttackSequenceY, 320, 32)); + foreach (BattleActorSnapshot actor in actors) + { + if (!actor.Alive || actor.Escaped) + continue; + Vector2 point = _layout.AttackPortrait(actor.Gauge, actor.CastGauge, actor.Pose is BattlePose.Casting or BattlePose.Fleeing); + point.x += extraWidth; + Rect rect = new(point.x, point.y, 64, 64); + string model = _preview.ActorModel(actor.Id); + if (model != null && !_sequenceSprites.TryGetValue(model, out _)) + { + string path = $"basedata.cpk\\ui\\combat\\attacksequen\\{model}.tga"; + _sequenceSprites[model] = _data.Resources.Find(path) != null ? "attacksequen/" + model : null; + } + if (model != null && _sequenceSprites[model] is { } sprite) + Sprite(sprite, rect); + else + GUI.Label(new Rect(point.x + 8, point.y + 9, 48, 28), ActorName(actor), Small); + GUI.Label(rect, new GUIContent("", $"{ActorName(actor)} · 第一槽 {actor.Gauge}/{BattleSession.FullGauge} · 第二槽 {actor.CastGauge}/{BattleSession.FullCastGauge}")); + RegisterControl("inspect:" + actor.Id, rect); + } + } + + private static string StateResource(BattleState state) => state switch + { + BattleState.AttackIncrease => "attackinc", + BattleState.AttackDecrease => "attackdec", + BattleState.DefenseIncrease => "defenceinc", + BattleState.DefenseDecrease => "defencedec", + BattleState.SpeedIncrease => "speedinc", + BattleState.SpeedDecrease => "speeddec", + BattleState.LuckIncrease => "luckinc", + BattleState.LuckDecrease => "luckdec", + BattleState.Paralysis => "stable", + BattleState.Seal => "blank", + BattleState.Forbidden => "forbid", + BattleState.Sleep => "sleep", + BattleState.Chaos => "chaos", + BattleState.Madness => "mad", + BattleState.Reflection => "mirror", + BattleState.Evade => "wall", + BattleState.Barrier => "bound", + BattleState.Invisible => "hermit", + BattleState.PoisonResist => "immunity", + _ => null + }; + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.State.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.State.cs.meta new file mode 100644 index 00000000..2332b090 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.State.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ede86be1babf41a2b316051ac2e6b971 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Touch.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Touch.cs new file mode 100644 index 00000000..1ed788fa --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Touch.cs @@ -0,0 +1,91 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Linq; + using Battle.Presentation; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattleHudView + { + private BattleHudInteractionProfile _interaction; + private Rect _touchPanel; + private float _touchScrollLimit; + private int? _touchCandidatePointer, _touchScrollPointer; + private Vector2 _touchStart, _touchPrevious; + private BattleHudPage _touchPressedPage; + + private float _touchPanelScale = 1; + + private void RegisterTouchList(Rect list, float contentHeight) + { + _touchPanel = new Rect(_viewport.ToViewport(_pageOffset + list.position * _pageScale), list.size * (_viewport.Scale * _pageScale)); + _touchPanelScale = _viewport.Scale * _pageScale; + _touchScrollLimit = Math.Max(0, contentHeight - list.height); + } + + private bool TouchGesture(BattleHudIntentKind phase, int pointerId, Vector2 point) + { + if (!_interaction.Touch) + return false; + // A scrollbar may have accepted the unclaimed press after this + // dispatcher. Keep its drag and release with the native owner. + if (ForeignGuiPointer && !_presenter.CapturedPointerId.HasValue) + { + ResetTouchGesture(); + return false; + } + if (_touchCandidatePointer.HasValue && _touchCandidatePointer != pointerId) + return true; + if (phase == BattleHudIntentKind.PointerDown && !_presenter.CapturedPointerId.HasValue && !_touchCandidatePointer.HasValue && _touchPanel.Contains(point)) + { + _touchCandidatePointer = pointerId; + _touchStart = _touchPrevious = point; + _touchPressedPage = _presenter.Page; + } + if (_touchCandidatePointer != pointerId) + return false; + if (_touchPressedPage != _presenter.Page) + { + ResetTouchGesture(); + return false; + } + if (phase == BattleHudIntentKind.PointerMove) + { + if (!_touchScrollPointer.HasValue && _touchPressedPage != BattleHudPage.Formation && _touchScrollLimit > 0 && Math.Abs(point.y - _touchStart.y) > 8 && (!_presenter.CapturedPointerId.HasValue || _presenter.CapturedPointerId == pointerId)) + { + _presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerCancel, pointerId: pointerId)); + _touchScrollPointer = pointerId; + // Pointer focus is not a navigation request: keep the + // next repaint from scrolling back to the pressed row. + _scrollFocus = _presenter.FocusedId; + } + if (_touchScrollPointer == pointerId) + { + _listScroll.y = Mathf.Clamp(_listScroll.y - (point.y - _touchPrevious.y) / Math.Max(.001f, _touchPanelScale), 0, _touchScrollLimit); + _touchPrevious = point; + _repaint?.Invoke(); + return true; + } + } + if (phase is BattleHudIntentKind.PointerUp or BattleHudIntentKind.PointerCancel) + { + bool scrolling = _touchScrollPointer == pointerId; + ResetTouchGesture(); + return scrolling; + } + return false; + } + + private void ResetTouchGesture() + { + _touchCandidatePointer = _touchScrollPointer = null; + } + + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Touch.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Touch.cs.meta new file mode 100644 index 00000000..9c14d612 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.Touch.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e14363bb7aaa43399f577000951a3375 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.WorldSelection.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.WorldSelection.cs new file mode 100644 index 00000000..8bb416ad --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.WorldSelection.cs @@ -0,0 +1,42 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Linq; + using Battle; + using Battle.Presentation; + using UnityEngine; + + public sealed partial class BattleHudView + { + private bool WorldSelectionOpen => _presenter.Page is BattleHudPage.Targets or BattleHudPage.Protection or BattleHudPage.Ai; + + private (string Control, string Actor)[] WorldSelectionActors() => _presenter.Page switch + { + BattleHudPage.Targets => _presenter.Targets.Select(actor => ("target:" + actor.Id, actor.Id)).ToArray(), + BattleHudPage.Protection => _battle.Actors.Where(actor => actor.Side == BattleSide.Ally && _battle.CanSetProtection(_presenter.Controller, actor.Id) == null) + .Select(actor => ("protect:" + actor.Id, actor.Id)).ToArray(), + BattleHudPage.Ai => _battle.Actors.Select(actor => ("ai-actor:" + actor.Id, actor.Id)).ToArray(), + _ => Array.Empty<(string, string)>() + }; + + private void PublishFocusLayout() + { + if (_preview == null || _viewport.Scale <= 0) + return; + var world = WorldSelectionActors() + .Select(entry => (entry.Control, Projected: _preview.TryActorSelectionPoint(entry.Actor, _viewport.Viewport, out Vector2 screen), Screen: screen)) + .Where(entry => entry.Projected) + .Select(entry => + { + Vector2 point = _viewport.ToCanvas(entry.Screen); + return (Id: entry.Control, X: point.x, Y: point.y); + }); + _presenter.SetFocusLayout(_hitControls.Select(control => (control.Id, control.Rect.center.x, control.Rect.center.y)).Concat(world)); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.WorldSelection.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.WorldSelection.cs.meta new file mode 100644 index 00000000..1de30f8e --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.WorldSelection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2ecd1280fd734acc96a935e7dfb0d85b diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.cs new file mode 100644 index 00000000..6afabd10 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.cs @@ -0,0 +1,303 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Battle; + using Battle.Presentation; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattleHudView + { + private readonly BattleHudPresenter _presenter = new(); + private BattleSession _battle; + private BattleData _data; + private BattlePreview _preview; + private BattleHudLayout _layout; + private readonly Dictionary _spriteTextures = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _sequenceSprites = new(StringComparer.OrdinalIgnoreCase); + private Action _changed; + private Action _selectActor; + private Vector2 _listScroll; + private bool _inputEnabled; + private Vector2 _pointer; + private BattleHudViewport _viewport; + private Vector2 _pageOffset; + private float _pageScale = 1; + private System.Collections.Generic.IReadOnlyList _renderFocus = Array.Empty(); + private string _renderFocusedId; + private bool _hasInputFocus = true; + private BattleHudPage _layoutPage; + private int _layoutCategory; + private string _scrollFocus; + + public BattleHudPresenter Presenter => _presenter; + + public void Release() + { + CancelInput(); + ReleasePointers(); + ClearHitControls(); + _spritePixels.Clear(); + _spriteTextures.Clear(); + _sequenceSprites.Clear(); + _presenter.Synchronize(null); + _presenter.SetFocusLayout(Array.Empty<(string, float, float)>()); + _battle = null; + _data = null; + _preview = null; + _selectionOwner = null; + _gamepadPointingContext = null; + _changed = _repaint = null; + _selectActor = null; + _renderFocus = Array.Empty(); + _renderFocusedId = _scrollFocus = null; + _gamepadPointingDirection = null; + _inputEnabled = _navigationInput = false; + _listScroll = Vector2.zero; + } + + public Vector2 GuiScreenOrigin + { + get; private set; + } + + public Rect LastViewport + { + get; private set; + } + + private static GUIStyle Small => BattleHudCanvas.LabelStyle(11, Color.white); + + public void BindBattle(BattleSession combat, BattleData data, BattlePreview preview, Action changed, Action select, Action repaint = null) + { + if (_battle != combat || _data != data || _preview != preview) + { + ClearHitControls(); + _spritePixels.Clear(); + _spriteTextures.Clear(); + _sequenceSprites.Clear(); + _layout = new BattleHudLayout(combat.Variant); + } + _battle = combat; + _data = data; + _preview = preview; + _changed = changed; + _selectActor = select; + _repaint = repaint ?? changed; + Synchronize(combat); + } + + public void Draw(BattleSession combat, BattleData data, BattlePreview preview, Rect content, Action changed, Action select, Vector4 safeInsets = default, Action repaint = null, BattleHudInteractionProfile interaction = default) + { + if (content.width < 16 || content.height < 16) + return; + PrepareGuiInput(); + GuiScreenOrigin = GUIUtility.GUIToScreenPoint(Vector2.zero); + LastViewport = content; + _viewport = new BattleHudViewport(content, safeInsets); + if (_interaction.Touch != interaction.Touch) + { + CancelInput(); + ClearHitControls(); + } + _interaction = interaction; + BindBattle(combat, data, preview, changed, select, repaint); + bool inputEnabled = combat.Status == BattleSessionStatus.Running && !combat.IsModalPresentation && GUI.enabled && _hasInputFocus; + if (_inputEnabled && !inputEnabled) + CancelInput(); + _inputEnabled = inputEnabled; + if (combat.IsModalPresentation || combat.Status != BattleSessionStatus.Running) + { + HandleGuiInput(Event.current, content); + ClearHitControls(); + return; + } + _lastPointer ??= Event.current.mousePosition; + if (Event.current.type == EventType.ScrollWheel && content.Contains(Event.current.mousePosition) && _navigationInput) + { + PointerTookControl?.Invoke(); + _navigationInput = false; + } + HandleGuiInput(Event.current, content); + if (Event.current.type == EventType.Repaint) + ClearHitControls(); + if (_layoutPage != _presenter.Page || _layoutCategory != _presenter.Category) + { + if (_layoutPage != _presenter.Page) + { + _touchTargetArmed = null; + _touchTargetConfirm = false; + _pointerTarget = null; + } + _layoutPage = _presenter.Page; + _layoutCategory = _presenter.Category; + _listScroll = Vector2.zero; + _touchPanel = default; + _touchScrollLimit = 0; + _scrollFocus = null; + ResetTouchGesture(); + } + _renderFocus = _presenter.FocusItems(); + _renderFocusedId = _presenter.FocusedId; + _pointer = _navigationInput ? new Vector2(float.NegativeInfinity, float.NegativeInfinity) : _viewport.ToCanvas(Event.current.mousePosition); + using (new BattleHudCanvas(_viewport)) + { + DrawWheelControls(); + DrawSceneField(); + IReadOnlyList actors = combat.Actors; + DrawStateCards(actors); + DrawSequence(actors); + } + if (_presenter.Controller != null && _presenter.Page != BattleHudPage.Targets) + DrawCommandPage(); + using (new BattleHudCanvas(_viewport)) + { + if (Event.current.type == EventType.Repaint) + PublishFocusLayout(); + if (_presenter.Message != null) + GUI.Label(new Rect(210, _viewport.CanvasSize.y - 148, Math.Max(100, _viewport.CanvasSize.x - 220), 36), BattleHudDenialText.Format(_presenter.Message, detailed: true), BattleHudCanvas.LabelStyle(13, Color.white, wrap: true)); + } + } + + private void DrawCommandPage() + { + _pageScale = _interaction.ScaleFor(_viewport); + _pageOffset = CommandPageOrigin(_pageScale); + _pointer = (_pointer - _pageOffset) / _pageScale; + float scale = _viewport.Scale * _pageScale; + var area = new Rect(_viewport.ToViewport(_pageOffset), new Vector2(_viewport.SafeRect.width, 600 * scale)); + try + { + using (new BattleHudCanvas(area, scale)) + { + switch (_presenter.Page) + { + case BattleHudPage.Commands: + DrawCommands(); + break; + case BattleHudPage.Skills: + case BattleHudPage.Magic: + case BattleHudPage.Items: + DrawAbilities(); + break; + case BattleHudPage.Formation: + DrawFormation(); + break; + case BattleHudPage.Protection: + // Protection is selected directly on scene actors. + break; + case BattleHudPage.Ai: + DrawAi(); + break; + } + } + } + finally + { + _pointer = _pointer * _pageScale + _pageOffset; + _pageOffset = Vector2.zero; + _pageScale = 1; + } + } + + private BattleSession _selectionOwner; + private (BattleSession Battle, string Controller, BattleHudPage Page)? _gamepadPointingContext; + + private void Synchronize(BattleSession combat) + { + string previousController = _presenter.Controller; + BattleHudPage previousPage = _presenter.Page; + string previousTarget = _presenter.Target; + int? previousPointer = _presenter.CapturedPointerId; + _presenter.Synchronize(combat); + bool controllerChanged = _selectionOwner != combat || previousController != _presenter.Controller; + if (controllerChanged) + { + _selectionOwner = combat; + if (_presenter.Controller != null) + PlayMenuSound("wa003"); + _listScroll = Vector2.zero; + } + if (controllerChanged || previousPage != _presenter.Page || previousTarget != _presenter.Target || + previousPointer != _presenter.CapturedPointerId) + { + if (previousPointer is int pointer) + _retiredPointers.Add(pointer); + CancelInput(); + _pointerTarget = null; + } + var pointingContext = (combat, _presenter.Controller, _presenter.Page); + if (_gamepadPointingContext != pointingContext) + { + _gamepadPointingContext = pointingContext; + ApplyGamepadPointing(); + } + } + + // The native UI uses width/textureWidth UVs, cropping padded textures. + // Stretching the complete power-of-two image shrinks portraits and bars. + private Texture2D SpriteTexture(string name) + { + if (!_spriteTextures.TryGetValue(name, out Texture2D texture)) + { + texture = _preview.View.GetTexture("basedata.cpk\\ui\\combat\\" + name.Replace('/', '\\') + ".tga"); + _spriteTextures.Add(name, texture); + } + return texture; + } + + private void Sprite(string name, Rect rect) + { + Texture2D texture = SpriteTexture(name); + if (texture == null) + return; + rect.width = Math.Min(rect.width, texture.width); + rect.height = Math.Min(rect.height, texture.height); + GUI.DrawTextureWithTexCoords(rect, texture, BattleHudCanvas.SpriteUv(texture, rect.size), true); + } + + // Controls only draw and publish their visible hit rectangles. The + // input dispatcher is the sole path into the shared presenter. + private void SpriteButton(string name, Rect rect, string tooltip = null, bool selected = false, bool disabledImage = true) + { + bool hover = rect.Contains(_pointer); + string control = ControlId(name); + bool enabled = control == null || _renderFocus.Any(item => item.Id == control && item.Enabled); + RegisterControl(control, rect, SpriteTexture(name + "0")); + int frame = !enabled && disabledImage ? 3 : selected || hover || control == _renderFocusedId ? 1 : 0; + Color before = GUI.color; + if (!enabled && !disabledImage) + GUI.color = new Color(1, 1, 1, .4f); + if (_navigationInput && control == _renderFocusedId) + GUI.color *= new Color(1, 1, 1, .7f + .3f * Mathf.Sin((float)UnityEditor.EditorApplication.timeSinceStartup * 7.8f)); + Sprite(name + frame, rect); + GUI.color = before; + GUI.Label(rect, new GUIContent("", tooltip)); + } + + private void TextButton(Rect rect, string text, string controlId) + { + bool enabled = _renderFocus.Any(item => item.Id == controlId && item.Enabled); + RegisterControl(controlId, rect); + Color previous = GUI.color; + if (!enabled || !_inputEnabled) + GUI.color = new Color(1, 1, 1, .4f); + GUIStyle style = new GUIStyle(EditorStyles.miniButton); + if (_navigationInput && controlId == _renderFocusedId) + style.normal = style.onNormal; + GUI.Label(rect, text, style); + GUI.color = previous; + } + + public string NavigationFocusedControl => _navigationInput ? _presenter.FocusedId : null; + + private string ActorName(BattleActorSnapshot actor) => _data.Database.CombatActorInfos.TryGetValue(actor.ActorId, out var info) ? info.Name : actor.ActorId.ToString(); + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.cs.meta new file mode 100644 index 00000000..44ce6aa0 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudView.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 63f19b87c5744982bdfa83058017dc26 diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudViewport.cs b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudViewport.cs new file mode 100644 index 00000000..6a184339 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudViewport.cs @@ -0,0 +1,81 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using UnityEngine; + using Battle; + + public readonly struct BattleHudViewport + { + public Rect Viewport + { + get; + } + + public Rect SafeRect + { + get; + } + + public float Scale + { + get; + } + + public Vector2 CanvasSize => SafeRect.size / Scale; + + public Rect ReferenceRect => BattleHudLayout.ContentRect(SafeRect); + + // Insets are outer-layer GUI points: left, top, right, bottom. + public BattleHudViewport(Rect viewport, Vector4 insets) + { + Viewport = viewport; + float left = Mathf.Clamp(insets.x, 0, Math.Max(0, viewport.width - 1)); + float top = Mathf.Clamp(insets.y, 0, Math.Max(0, viewport.height - 1)); + float right = Mathf.Clamp(insets.z, 0, Math.Max(0, viewport.width - left - 1)); + float bottom = Mathf.Clamp(insets.w, 0, Math.Max(0, viewport.height - top - 1)); + SafeRect = new Rect(viewport.x + left, viewport.y + top, Math.Max(1, viewport.width - left - right), Math.Max(1, viewport.height - top - bottom)); + Scale = Math.Max(.001f, Math.Min(SafeRect.width / 800, SafeRect.height / 600)); + } + + public Vector2 ToCanvas(Vector2 point) => (point - SafeRect.position) / Scale; + + public Vector2 ToViewport(Vector2 point) => SafeRect.position + point * Scale; + + public Vector2 NativeToViewport(Vector2 point) => new Vector2(SafeRect.xMax, SafeRect.y) + (point - new Vector2(800, 0)) * Scale; + + public Vector2 ProjectionReferencePoint(Vector2 native, bool expandReference) => + ProjectionReferencePoint(native, expandReference ? Math.Min(Viewport.width / 800, Viewport.height / 600) : Viewport.width / 800); + + public Vector2 ProjectionReferencePoint(Vector2 native, float projectionScale) => + Viewport.center + (native - new Vector2(400, 300)) * projectionScale; + + public Vector2 SpiritOrbPoint(BattleSpiritOrbSnapshot orb, bool expandReference) => + SpiritOrbPoint(orb, expandReference ? Math.Min(Viewport.width / 800, Viewport.height / 600) : Viewport.width / 800); + + public Vector2 SpiritOrbPoint(BattleSpiritOrbSnapshot orb, float projectionScale) => + SpiritOrbPoint(new Vector2(orb.Position.X, orb.Position.Y), new Vector2(orb.Origin.X, orb.Origin.Y), + new Vector2(orb.Destination.Center.X, orb.Destination.Center.Y), projectionScale); + + public Vector2 SpiritOrbPoint(Vector2 point, Vector2 origin, Vector2 destination, bool expandReference) => + SpiritOrbPoint(point, origin, destination, expandReference ? Math.Min(Viewport.width / 800, Viewport.height / 600) : Viewport.width / 800); + + public Vector2 SpiritOrbPoint(Vector2 point, Vector2 origin, Vector2 destination, float projectionScale) + { + Vector2 travel = destination - origin; + float progress = travel.sqrMagnitude > 0 ? Mathf.Clamp01(Vector2.Dot(point - origin, travel) / travel.sqrMagnitude) : 1; + Vector2 offset = ProjectionReferencePoint(origin, projectionScale) - NativeToViewport(origin); + return NativeToViewport(point) + offset * (1 - progress); + } + + public Rect StateCard(int localIndex) + { + float x = BattleHudLayout.StateCard(localIndex).x + localIndex * (CanvasSize.x - 800) / 3; + return new Rect(x, CanvasSize.y - 109, 200, 106); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudViewport.cs.meta b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudViewport.cs.meta new file mode 100644 index 00000000..d6f1a754 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Hud/BattleHudViewport.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 21f29003e24643e78bee660f6b0f82b8 diff --git a/Assets/Scripts/Editor/BattleEditor/Media.meta b/Assets/Scripts/Editor/BattleEditor/Media.meta new file mode 100644 index 00000000..08dfaf20 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Media.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 08765ab4cc52414f8e4dc2ebc44b7b6b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreview.cs b/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreview.cs new file mode 100644 index 00000000..77b76635 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreview.cs @@ -0,0 +1,512 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using ResourceBrowser; + using UnityEditor; + using UnityEditor.SceneManagement; + using UnityEngine.SceneManagement; + using UnityEngine; + using UnityEngine.Networking; + using Object = UnityEngine.Object; + + // Hidden AudioSources in an owned preview scene work in EditMode. Every + // body, movement, music and movie voice has its own pause/seek/stop handle; + // no battle operation changes Unity's global preview transport or listener. + public sealed class BattleAudioPreview : IDisposable, IBattleMovieAudioTransport + { + private sealed class Request + { + public string File; + public double Start; + public bool Loop; + public float Gain = 1; + } + + private sealed class Decode : IDisposable + { + public UnityWebRequest Request; + public string Temporary; + + public void Dispose() + { + try + { + Request?.Abort(); + } + finally + { + Request?.Dispose(); + } + } + } + + private sealed class Voice + { + public AudioSource Source; + public Request Request; + public double MovieTime; + public bool MoviePlaying = true; + public bool Started, Paused; + } + + private readonly Scene _scene; + private readonly bool _ownsScene; + private readonly GameObject _root; + private readonly Dictionary _voices = new(); + private const string MusicVoice = "music"; + private readonly ResourceCatalog _resources; + private readonly Dictionary _soundFiles = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _missingSounds = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _clips = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _pending = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _desired = new(); + + private readonly string _cache; + private double _time; + private bool _disposed, _muted, _playbackEnabled = true; + private float _musicGain = 1; + + public bool PlaybackEnabled + { + get => _playbackEnabled; + set + { + if (_playbackEnabled == value) + return; + _playbackEnabled = value; + UpdateTransport(true); + } + } + + public bool Muted + { + get => _muted; + set + { + if (_muted == value) + return; + _muted = value; + UpdateTransport(true); + } + } + + public List Diagnostics { get; } = new(); + + public event Action SoundPlayed; + + public BattleAudioPreview(ResourceCatalog resources, Scene scene = default) + { + _resources = resources ?? throw new ArgumentNullException(nameof(resources)); + if (scene.IsValid() && !EditorSceneManager.IsPreviewScene(scene)) + throw new ArgumentException("Battle audio requires an editor preview scene.", nameof(scene)); + _ownsScene = !scene.IsValid(); + _scene = _ownsScene ? EditorSceneManager.NewPreviewScene() : scene; + _root = new GameObject("Battle audio preview") { hideFlags = HideFlags.HideAndDontSave }; + SceneManager.MoveGameObjectToScene(_root, _scene); + try + { + string directory = Path.Combine(resources.Root, "snd"); + if (Directory.Exists(directory)) + foreach (string path in Directory.EnumerateFiles(directory).Where(path => Path.GetExtension(path).Equals(".wav", StringComparison.OrdinalIgnoreCase))) + _soundFiles.TryAdd(Path.GetFileName(path), path); + string current = resources.Root; + while (current != null && !Directory.Exists(Path.Combine(current, "workspace"))) + current = Directory.GetParent(current)?.FullName; + _cache = current == null ? Path.GetFullPath(Path.Combine(Application.dataPath, "../Library/BattleAudio")) : Path.Combine(current, "workspace", "Cache", "BattleAudio"); + EditorApplication.update += Update; + } + catch + { + if (_ownsScene) + EditorSceneManager.ClosePreviewScene(_scene); + else + Object.DestroyImmediate(_root); + throw; + } + } + + public void SetTime(double seconds) + { + if (!double.IsFinite(seconds) || seconds < 0) + throw new ArgumentOutOfRangeException(nameof(seconds)); + _time = seconds; + foreach (var pair in _desired.ToArray()) + if (!pair.Value.Loop && _clips.TryGetValue(pair.Value.File, out AudioClip clip) && _time - pair.Value.Start >= clip.length) + RemoveVoice(pair.Key); + UpdateTransport(false); + } + + // Native LoadSnd allocates another node when this sound is already + // playing. Decode/cache ownership is shared; one-shot voices are not. + public void Play(string sound) => RequestSound(new object(), sound, false); + + public void PlayMovement(string actor, string sound, bool loop) => RequestSound("movement:" + actor, sound, loop); + + public void StopMovement(string actor) => RemoveVoice("movement:" + actor); + + public void StopBodySounds() + { + foreach (object key in _desired.Keys.Where(key => !Equals(key, MusicVoice)).ToArray()) + { + RemoveVoice(key); + } + } + + private static string Normalize(string sound) + { + if (string.IsNullOrWhiteSpace(sound)) + return ""; + return Path.GetFileName(sound.Replace('\\', '/')).ToLowerInvariant(); + } + + private void RequestSound(object voice, string sound, bool loop) + { + if (_disposed || string.IsNullOrWhiteSpace(sound)) + return; + string name = Normalize(sound); + string file = name.EndsWith(".wav", StringComparison.OrdinalIgnoreCase) ? name : name + ".wav"; + if (!_soundFiles.TryGetValue(file, out string path)) + { + if (_missingSounds.Add(file)) + Diagnostics.Add("Missing battle sound: " + file); + return; + } + Queue(voice, file, path, AudioType.WAV, loop); + } + + public void SetMusic(string music) + { + StopMusic(); + if (_disposed || string.IsNullOrWhiteSpace(music) || music.Equals("NONE", StringComparison.OrdinalIgnoreCase)) + return; + string name = Normalize(music); + string file = name.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase) ? name : name + ".mp3"; + string key = "music:" + file; + string temporary = null; + try + { + RetainMusic(key); + if (_clips.ContainsKey(key) || _pending.ContainsKey(key)) + { + Queue(MusicVoice, key, null, AudioType.MPEG, true); + return; + } + string musicDirectory = Path.Combine(_resources.Root, "music"); + string loose = Directory.Exists(musicDirectory) ? Directory.EnumerateFiles(musicDirectory).FirstOrDefault(path => Path.GetFileName(path).Equals(file, StringComparison.OrdinalIgnoreCase)) : null; + if (loose != null) + { + Queue(MusicVoice, key, loose, AudioType.MPEG, true); + return; + } + string archive = Directory.EnumerateFiles(musicDirectory).Single(path => Path.GetFileName(path).Equals("music.cpk", StringComparison.OrdinalIgnoreCase)); + _resources.FileSystem.Mount(Path.GetRelativePath(_resources.Root, archive), _resources.Codepage); + byte[] bytes = _resources.FileSystem.ReadAllBytes("music.cpk\\music\\" + file); + Directory.CreateDirectory(_cache); + temporary = Path.Combine(_cache, Guid.NewGuid().ToString("N") + ".mp3"); + File.WriteAllBytes(temporary, bytes); + string extracted = temporary; + temporary = null; + Queue(MusicVoice, key, extracted, AudioType.MPEG, true, extracted); + } + catch (Exception ex) + { + Diagnostics.Add("Battle music " + file + ": " + ex.Message); + } + finally + { + DeleteTemporary(temporary); + } + } + + private void RetainMusic(string current) + { + bool Obsolete(string key) => key.StartsWith("music:", StringComparison.Ordinal) && + !key.Equals(current, StringComparison.OrdinalIgnoreCase); + foreach (string key in _pending.Keys.Where(Obsolete).ToArray()) + if (_pending.Remove(key, out Decode decode)) + ReleaseDecode(decode); + foreach (string key in _clips.Keys.Where(Obsolete).ToArray()) + if (_clips.Remove(key, out AudioClip clip)) + Object.DestroyImmediate(clip); + } + + public void SetMusicGain(float gain) + { + if (!float.IsFinite(gain) || gain < 0 || gain > 1) + throw new ArgumentOutOfRangeException(nameof(gain)); + _musicGain = gain; + if (_desired.TryGetValue(MusicVoice, out Request request)) + request.Gain = gain; + if (_voices.TryGetValue(MusicVoice, out Voice voice)) + voice.Source.volume = gain; + } + + public void StopMusic() => RemoveVoice(MusicVoice); + + private void Queue(object voice, string file, string path, AudioType type, bool loop, string temporary = null) + { + var desired = new Request { File = file, Start = _time, Loop = loop, Gain = Equals(voice, MusicVoice) ? _musicGain : 1f }; + _desired[voice] = desired; + if (_clips.TryGetValue(file, out AudioClip clip)) + { + DeleteTemporary(temporary); + StartVoice(voice, desired, clip); + return; + } + if (_pending.ContainsKey(file)) + { + DeleteTemporary(temporary); + return; + } + var decode = new Decode { Temporary = temporary }; + try + { + decode.Request = UnityWebRequestMultimedia.GetAudioClip(new Uri(path).AbsoluteUri, type); + ((DownloadHandlerAudioClip)decode.Request.downloadHandler).streamAudio = false; + decode.Request.SendWebRequest(); + _pending.Add(file, decode); + } + catch + { + _desired.Remove(voice); + ReleaseDecode(decode); + throw; + } + } + + private void Update() + { + foreach (var pair in _pending.Where(pair => pair.Value.Request.isDone).ToArray()) + { + if (_disposed || !_pending.TryGetValue(pair.Key, out Decode current) || !ReferenceEquals(current, pair.Value)) + continue; + _pending.Remove(pair.Key); + Decode decode = pair.Value; + UnityWebRequest request = decode.Request; + AudioClip clip = null; + try + { + if (request.result != UnityWebRequest.Result.Success) + throw new InvalidDataException(request.error); + clip = DownloadHandlerAudioClip.GetContent(request); + if (clip != null) + clip.name = pair.Key; + if (clip == null) + throw new InvalidDataException("The audio decoder returned no clip."); + clip.hideFlags = HideFlags.HideAndDontSave; + AudioClip pcm = clip; + clip = null; + _clips.Add(pair.Key, pcm); + foreach (var voice in _desired.Where(voice => voice.Value.File == pair.Key).ToArray()) + { + // A started voice may synchronously stop/replace this + // battle through SoundPlayed. Honor its current owner. + if (!_desired.TryGetValue(voice.Key, out Request desired) || !ReferenceEquals(desired, voice.Value)) + continue; + if (voice.Value.Loop || _time - voice.Value.Start < pcm.length) + StartVoice(voice.Key, voice.Value, pcm); + else + RemoveVoice(voice.Key); + } + } + catch (Exception ex) + { + Diagnostics.Add(pair.Key + ": " + ex.Message); + foreach (object key in _desired.Where(voice => voice.Value.File == pair.Key).Select(voice => voice.Key).ToArray()) + RemoveVoice(key); + } + finally + { + if (clip != null) + Object.DestroyImmediate(clip); + ReleaseDecode(decode); + } + } + } + + private void StartVoice(object voice, Request request, AudioClip clip, double movieTime = 0, bool moviePlaying = true) + { + RemoveVoiceSource(voice); + var child = new GameObject("Battle voice: " + request.File) { hideFlags = HideFlags.HideAndDontSave }; + child.transform.SetParent(_root.transform, false); + AudioSource source = child.AddComponent(); + source.playOnAwake = false; + source.spatialBlend = 0; + source.clip = clip; + source.loop = request.Loop; + source.volume = request.Gain; + // Keep the transport clock running for background regressions without audible output. + source.mute = Application.isBatchMode; + _voices.Add(voice, new Voice { Source = source, Request = request, MovieTime = movieTime, MoviePlaying = moviePlaying }); + SynchronizeVoice(_voices[voice], true); + if (request.File != "movie" && !Muted && PlaybackEnabled) + SoundPlayed?.Invoke(request.File); + } + + private void RemoveVoice(object voice) + { + _desired.Remove(voice); + RemoveVoiceSource(voice); + } + + private void RemoveVoiceSource(object voice) + { + if (!_voices.Remove(voice, out Voice entry) || entry.Source == null) + return; + entry.Source.Stop(); + Object.DestroyImmediate(entry.Source.gameObject); + } + + public void SynchronizeMovie(object owner, AudioClip clip, double elapsed, bool playing) + { + if (_disposed) + return; + if (!_voices.TryGetValue(owner, out Voice voice)) + { + var request = new Request { File = "movie", Start = _time - elapsed }; + StartVoice(owner, request, clip, elapsed, playing); + voice = _voices[owner]; + } + voice.MovieTime = elapsed; + voice.MoviePlaying = playing; + SynchronizeVoice(voice, false); + } + + public void StopMovie(object owner) => RemoveVoiceSource(owner); + + private void UpdateTransport(bool seek) + { + if (_disposed) + return; + foreach (Voice voice in _voices.Values) + SynchronizeVoice(voice, seek); + } + + private void SynchronizeVoice(Voice voice, bool seek) + { + AudioSource source = voice.Source; + if (source.clip == null || source.clip.samples <= 0 || source.clip.frequency <= 0) + { + source.Stop(); + voice.Started = voice.Paused = false; + return; + } + bool movie = voice.Request.File == "movie"; + bool playing = PlaybackEnabled && !Muted && (!movie || voice.MoviePlaying); + if (!playing) + { + if (voice.Started && !voice.Paused) + { + source.Pause(); + voice.Paused = true; + } + return; + } + double elapsed = movie ? voice.MovieTime : Math.Max(0, _time - voice.Request.Start); + double duration = source.clip.samples / (double)source.clip.frequency; + if (!source.loop && elapsed >= duration) + { + source.Stop(); + voice.Started = voice.Paused = false; + return; + } + int sample = (int)((elapsed % duration) * source.clip.frequency); + // The logical battle clock also moves during silent stepping. A + // resumed voice seeks to that clock instead of replaying old cues. + bool synchronize = seek || !voice.Started || voice.Paused; + // Music and sound effects run on the audio clock. Input callbacks + // can repeat a battle tick, and background editor updates may lag. + // Keep running voices continuous; only movies track video drift. + // Starting or resuming after silent inspection still seeks above. + if (!synchronize && movie) + { + int distance = Math.Abs(source.timeSamples - sample); + if (source.loop) + distance = Math.Min(distance, source.clip.samples - distance); + synchronize = distance > source.clip.frequency / 10; + } + if (synchronize) + source.timeSamples = Math.Clamp(sample, 0, source.clip.samples - 1); + if (!voice.Started) + { + source.Play(); + voice.Started = true; + } + else if (voice.Paused) + { + source.UnPause(); + voice.Paused = false; + } + } + + public void Stop() + { + _desired.Clear(); + foreach (object voice in _voices.Keys.ToArray()) + RemoveVoiceSource(voice); + Decode[] pending = _pending.Values.ToArray(); + _pending.Clear(); + foreach (Decode decode in pending) + ReleaseDecode(decode); + } + + private void ReleaseDecode(Decode decode) + { + try + { + decode.Dispose(); + } + finally + { + DeleteTemporary(decode.Temporary); + } + } + + private void DeleteTemporary(string path) + { + if (path == null) + return; + try + { + File.Delete(path); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + Diagnostics.Add($"Cannot remove temporary battle audio {path}: {error.Message}"); + } + } + + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + EditorApplication.update -= Update; + try + { + Stop(); + } + finally + { + foreach (AudioClip clip in _clips.Values) + Object.DestroyImmediate(clip); + _clips.Clear(); + if (_scene.IsValid()) + { + if (_ownsScene) + EditorSceneManager.ClosePreviewScene(_scene); + else + Object.DestroyImmediate(_root); + } + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreview.cs.meta b/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreview.cs.meta new file mode 100644 index 00000000..e67d136a --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreview.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 243a430dd29c4577841bba8cada98d2f diff --git a/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreviewDevice.cs b/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreviewDevice.cs new file mode 100644 index 00000000..ecd55989 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreviewDevice.cs @@ -0,0 +1,112 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Reflection; + using UnityEditor; + using UnityEngine; + + // AudioUtil has one global preview transport, without per-clip stop or pitch. + // Movies reserve it until release; pending SFX decoders cannot replace their + // soundtrack, and a former owner cannot stop the new owner's audio. + internal static class BattleAudioPreviewDevice + { + private const BindingFlags Static = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + private static readonly Type Utility = typeof(AudioImporter).Assembly.GetType("UnityEditor.AudioUtil"); + private static readonly MethodInfo PlayClip = Find("PlayPreviewClip", typeof(AudioClip), typeof(int), typeof(bool)); + private static readonly MethodInfo PauseClip = Find("PausePreviewClip"); + private static readonly MethodInfo ResumeClip = Find("ResumePreviewClip"); + private static readonly MethodInfo StopClips = Find("StopAllPreviewClips"); + private static readonly MethodInfo SetPosition = Find("SetPreviewClipSamplePosition", typeof(AudioClip), typeof(int)); + private static readonly MethodInfo GetPosition = Find("GetPreviewClipSamplePosition"); + private static object _owner; + private static bool _exclusive; + + public static bool IsAvailable => PlayClip != null && PauseClip != null && ResumeClip != null && + StopClips != null && SetPosition != null && GetPosition != null; + + private static MethodInfo Find(string name, params Type[] parameters) => + Utility?.GetMethod(name, Static, null, parameters, null); + + [InitializeOnLoadMethod] + private static void Initialize() + { + AssemblyReloadEvents.beforeAssemblyReload += Reset; + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; + } + + private static void OnPlayModeStateChanged(PlayModeStateChange state) + { + // These events also run when Enter Play Mode skips domain reload. + if (state is PlayModeStateChange.ExitingEditMode or PlayModeStateChange.ExitingPlayMode) + Reset(); + } + + private static void Reset() + { + try + { + Stop(_owner); + } + catch (Exception error) when (IsUnavailable(error)) + { + // Stop releases the lease before calling the optional editor backend. + } + } + + internal static bool IsUnavailable(Exception error) => + error is NotSupportedException or TypeInitializationException || + error is TargetInvocationException invocation && IsUnavailable(invocation.InnerException); + + public static bool Owns(object owner) => owner != null && ReferenceEquals(_owner, owner); + + public static bool Play(object owner, AudioClip clip, int sample = 0, bool exclusive = false) + { + if (_exclusive && !Owns(owner)) + return false; + if (!IsAvailable) + throw new NotSupportedException("This editor does not expose the battle audio preview controls."); + if (exclusive && _owner != null && !Owns(owner)) + StopClips?.Invoke(null, null); + PlayClip.Invoke(null, new object[] { clip, sample, false }); + _owner = owner; + _exclusive = exclusive; + return true; + } + + public static void Pause(object owner) + { + if (Owns(owner)) + PauseClip?.Invoke(null, null); + } + + public static void Resume(object owner, AudioClip clip, int sample) + { + if (!Owns(owner)) + return; + Seek(owner, clip, sample); + ResumeClip?.Invoke(null, null); + } + + public static int Position(object owner) => Owns(owner) && GetPosition != null ? (int)GetPosition.Invoke(null, null) : -1; + + public static void Seek(object owner, AudioClip clip, int sample) + { + if (Owns(owner)) + SetPosition?.Invoke(null, new object[] { clip, sample }); + } + + public static void Stop(object owner) + { + if (!Owns(owner)) + return; + _owner = null; + _exclusive = false; + StopClips?.Invoke(null, null); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreviewDevice.cs.meta b/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreviewDevice.cs.meta new file mode 100644 index 00000000..9041b5b2 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Media/BattleAudioPreviewDevice.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3097653bc8254d25976ec16e912fcaf0 diff --git a/Assets/Scripts/Editor/BattleEditor/Media/BattleMoviePlayer.cs b/Assets/Scripts/Editor/BattleEditor/Media/BattleMoviePlayer.cs new file mode 100644 index 00000000..68cb0b51 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Media/BattleMoviePlayer.cs @@ -0,0 +1,793 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.ComponentModel; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using Core.DataReader.Cpk; + using Core.FileSystem; + using Game.Effect.Runtime; + using ResourceBrowser; + using UnityEditor; + using UnityEngine; + using UnityEngine.Rendering; + using Object = UnityEngine.Object; + + // EditMode has no reliable VideoPlayer update loop. Decode once outside the + // fixed simulation; present original frames directly on the Bink frame clock. + public sealed class BattleMoviePlayer : IDisposable + { + private sealed class DecodedMovie + { + public string Directory; + public string Name; + public int Width, Height, Frames; + public uint Rate, Divisor; + public bool HasAudio; + + public int FrameBytes => checked(Width * Height * 4); + } + + private sealed class Preparation + { + public DecodedMovie Data; + public string Error; + public bool Missing; + } + + private sealed class Movie : IEffectMovie + { + private readonly BattleMoviePlayer _owner; + private readonly Task _preparation; + private DecodedMovie _data; + private FileStream _frames; + private byte[] _pixels; + private int _frame = -1; + private bool _disposed, _audioPlaying, _audioPaused, _audioUnavailable; + private AudioClip _audio; + public Texture2D Texture; + public double Elapsed; + + public Movie(BattleMoviePlayer owner, string name, Task preparation) + { + _owner = owner; + Name = name; + _preparation = preparation; + } + + private Movie(BattleMoviePlayer owner, DecodedMovie data) : this(owner, data.Name, null) + { + Open(data); + } + + private void Open(DecodedMovie data) + { + _data = data; + try + { + _frames = File.OpenRead(Path.Combine(data.Directory, "video.rgba")); + CheckFrameCount(data, _frames.Length); + _pixels = new byte[data.FrameBytes]; + Texture = new Texture2D(data.Width, data.Height, TextureFormat.RGBA32, false) { hideFlags = HideFlags.DontSave }; + if (data.HasAudio) + _audio = ReadAudio(Path.Combine(data.Directory, "audio.wav"), silent: Application.isBatchMode && _owner._audioTransport == null); + PresentFrame(); + UpdateAudio(); + } + catch + { + Dispose(); + throw; + } + } + + public bool Waiting => !_disposed && _data == null && !_preparation.IsCompleted; + + public bool Finished => _disposed || _data != null && Elapsed + 1e-9 >= _data.Frames * (double)_data.Divisor / _data.Rate; + + public bool HasFrame => _frame >= 0; + + public string Name + { + get; + } + + public void Advance(double seconds) + { + if (_disposed || Waiting) + return; + if (_data == null) + { + Preparation result = CompletedPreparation(_preparation); + if (result.Data == null) + { + Dispose(); + return; + } + Open(result.Data); + } + Elapsed = Math.Min(_data.Frames * (double)_data.Divisor / _data.Rate, Elapsed + seconds); + PresentFrame(); + UpdateAudio(); + } + + private void PresentFrame() + { + int frame = Math.Min(_data.Frames - 1, (int)Math.Floor(Elapsed * _data.Rate / _data.Divisor)); + if (frame == _frame) + return; + _frames.Position = (long)frame * _pixels.Length; + int count = 0; + while (count < _pixels.Length) + { + int read = _frames.Read(_pixels, count, _pixels.Length - count); + if (read == 0) + throw new EndOfStreamException("Incomplete decoded Bink frame."); + count += read; + } + Texture.LoadRawTextureData(_pixels); + Texture.Apply(false, false); + _frame = frame; + } + + public void UpdateAudio() + { + if (_owner.Muted || Finished) + { + StopAudio(); + return; + } + if (_audio == null || _audioUnavailable) + return; + try + { + UpdateTransport(); + } + catch (Exception error) when (BattleAudioPreviewDevice.IsUnavailable(error)) + { + ReportUnavailableAudio(error); + StopAudio(); + } + } + + private void UpdateTransport() + { + if (_owner._audioTransport != null) + { + _owner._audioTransport.SynchronizeMovie(this, _audio, Elapsed, _owner.AudioPlaybackEnabled); + _audioPlaying = _owner.AudioPlaybackEnabled; + _audioPaused = !_owner.AudioPlaybackEnabled; + return; + } + if (!_owner.AudioPlaybackEnabled) + { + if (_audioPlaying) + { + BattleAudioPreviewDevice.Pause(this); + _audioPaused = true; + } + return; + } + int sample = Math.Min(_audio.samples - 1, (int)(Elapsed * _audio.frequency)); + if (!_audioPlaying || !BattleAudioPreviewDevice.Owns(this)) + _audioPlaying = BattleAudioPreviewDevice.Play(this, _audio, sample, exclusive: true); + else if (_audioPaused) + BattleAudioPreviewDevice.Resume(this, _audio, sample); + else + { + int actual = BattleAudioPreviewDevice.Position(this); + if (actual >= 0 && Math.Abs(actual - sample) > _audio.frequency / 10) + BattleAudioPreviewDevice.Seek(this, _audio, sample); + } + _audioPaused = false; + } + + private void StopAudio() + { + _audioPlaying = false; + _audioPaused = false; + try + { + if (_owner._audioTransport != null) + _owner._audioTransport.StopMovie(this); + else + BattleAudioPreviewDevice.Stop(this); + } + catch (Exception error) when (BattleAudioPreviewDevice.IsUnavailable(error)) + { + ReportUnavailableAudio(error); + } + } + + private void ReportUnavailableAudio(Exception error) + { + if (_audioUnavailable) + return; + _audioUnavailable = true; + _owner.Diagnostics.Add($"战斗影片 {Name} 继续静音播放:{error.GetBaseException().Message}"); + } + + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + StopAudio(); + _frames?.Dispose(); + _pixels = null; + if (Texture != null) + Object.DestroyImmediate(Texture); + if (_audio != null) + Object.DestroyImmediate(_audio); + } + } + + private static readonly ConcurrentDictionary DecodeLeases = new(StringComparer.Ordinal); + private static readonly TimeSpan CacheWait = TimeSpan.FromMinutes(2); + private static readonly TimeSpan DecodeWait = TimeSpan.FromMinutes(2); + private readonly string _dataRoot; + private readonly int _codepage; + private readonly CancellationTokenSource _shutdown = new(); + private readonly IBattleMovieAudioTransport _audioTransport; + private readonly string _workspace, _cache, _ffmpeg; + private readonly ResourceModelPreview _preview; + private readonly Dictionary> _prepared = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _reportedFailures = new(StringComparer.OrdinalIgnoreCase); + private readonly List _movies = new(); + private readonly Vector3[] _screenVertices = new Vector3[8]; + private Material _frameMaterial; + private Material _backdrop; + private Mesh _screen; + private MeshRenderer _overlay; + private Vector2 _frameScale; + private bool _muted, _audioPlaybackEnabled = true, _disposed; + + public bool Muted + { + get => _muted; + set + { + _muted = value; + foreach (Movie movie in _movies) + movie.UpdateAudio(); + } + } + + public bool AudioPlaybackEnabled + { + get => _audioPlaybackEnabled; + set + { + _audioPlaybackEnabled = value; + foreach (Movie movie in _movies) + movie.UpdateAudio(); + } + } + + public readonly List MissingMovies = new(); + public readonly List Diagnostics = new(); + + public bool HasDecodedFrame => _movies.Any(movie => !movie.Finished && movie.HasFrame); + + public Texture CurrentTexture => _movies.LastOrDefault(movie => !movie.Finished)?.Texture; + + public bool BlocksBattleTime => _movies.Any(movie => !movie.Finished); + + public bool IsPreparingPlayback => _movies.Any(movie => movie.Waiting); + + public BattleMoviePlayer(BattleData data, ResourceModelPreview preview, IBattleMovieAudioTransport audio = null) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + _dataRoot = data.Resources.FileSystem.GetRootPath(); + _codepage = data.Resources.Codepage; + _audioTransport = audio; + _preview = preview ?? throw new ArgumentNullException(nameof(preview)); + string current = _dataRoot; + while (current != null && !Directory.Exists(Path.Combine(current, "workspace"))) + current = Directory.GetParent(current)?.FullName; + _workspace = current == null ? null : Path.Combine(current, "workspace"); + _cache = Environment.GetEnvironmentVariable("PAL3_BATTLE_MOVIE_CACHE") ?? (_workspace == null ? + Path.GetFullPath(Path.Combine(Application.dataPath, "../Library/BattleMovies")) : Path.Combine(_workspace, "Cache", "BattleMovies")); + string configured = Environment.GetEnvironmentVariable("PAL3_BATTLE_FFMPEG"); + string filename = Application.platform == RuntimePlatform.WindowsEditor ? "ffmpeg.exe" : "ffmpeg"; + _ffmpeg = configured ?? (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator) + .Select(path => Path.Combine(path, filename)).FirstOrDefault(File.Exists) ?? (_workspace == null ? null : Path.Combine(_workspace, "Tools", "ffmpeg", "bin", filename)); + } + + public void Preload(string original) + { + if (_disposed) + throw new ObjectDisposedException(nameof(BattleMoviePlayer)); + if (_prepared.ContainsKey(original)) + return; + string configured = Environment.GetEnvironmentVariable("PAL3_BATTLE_MOVIE_ROOT"); + CancellationToken cancellation = _shutdown.Token; + _prepared.Add(original, Task.Run(() => Prepare(original, configured, cancellation), cancellation)); + } + + internal void ReusePreparedMovies(BattleMoviePlayer previous) + { + foreach (var (name, task) in previous._prepared) + if (task.IsCompletedSuccessfully) + _prepared.TryAdd(name, task); + } + + public IEffectMovie Play(string original) + { + Preload(original); + var movie = new Movie(this, original, _prepared[original]); + _movies.Add(movie); + return movie; + } + + private static bool IsMediaFailure(Exception error) => + error is IOException or InvalidDataException or UnauthorizedAccessException or Win32Exception or OverflowException or TimeoutException; + + private Preparation Prepare(string original, string configured, CancellationToken cancellation) + { + try + { + byte[] bytes = ReadOriginal(original, configured, cancellation); + return bytes == null ? new Preparation { Missing = true, Error = "未找到影片文件。" } : + new Preparation { Data = Decode(original, bytes, cancellation) }; + } + catch (Exception exception) when (IsMediaFailure(exception)) + { + return new Preparation { Error = exception.Message }; + } + } + + private static Preparation CompletedPreparation(Task task) + { + if (task.IsCompletedSuccessfully) + return task.GetAwaiter().GetResult(); + if (task.IsCanceled) + return new Preparation { Error = "影片准备已取消。" }; + return new Preparation { Error = task.Exception.GetBaseException().Message }; + } + + private void ReportFailure(string name, Preparation result) + { + if (result.Error == null || !_reportedFailures.Add(name)) + return; + if (result.Missing) + MissingMovies.Add(name); + Diagnostics.Add($"已跳过战斗影片 {name}:{result.Error}"); + } + + private byte[] ReadOriginal(string original, string configured, CancellationToken cancellation) + { + var roots = new List { _dataRoot }; + if (!string.IsNullOrEmpty(configured)) + roots.Add(configured); + if (_workspace != null) + roots.Add(Path.Combine(Directory.GetParent(_workspace).FullName, BattleData.Variant + " Installation")); + foreach (string root in roots.Distinct()) + { + cancellation.ThrowIfCancellationRequested(); + string loose = Path.Combine(root, original.Replace('\\', Path.DirectorySeparatorChar)); + if (File.Exists(loose)) + return File.ReadAllBytes(loose); + string movieDirectory = Path.Combine(root, "movie"); + if (!Directory.Exists(movieDirectory)) + continue; + var hash = new Crc32Hash(); + hash.Init(); + var files = new CpkFileSystem(root, hash, _codepage); + foreach (string name in new[] { "movie.cpk", "movie_end.cpk" }) + { + string[] archives = Directory.EnumerateFiles(movieDirectory) + .Where(file => Path.GetFileName(file).Equals(name, StringComparison.OrdinalIgnoreCase)).Take(2).ToArray(); + if (archives.Length == 0) + continue; + if (archives.Length > 1) + throw new InvalidDataException($"Multiple archives match {name} in {movieDirectory}."); + string archive = archives[0]; + files.Mount(Path.GetRelativePath(root, archive), _codepage); + string path = name + "\\" + original; + if (files.FileExists(path)) + return files.ReadAllBytes(path); + } + } + return null; + } + + private DecodedMovie Decode(string original, byte[] bytes, CancellationToken cancellation) + { + if (bytes.Length < 44 || bytes[0] != 'B' || bytes[1] != 'I' || bytes[2] != 'K') + throw new InvalidDataException("Invalid original Bink header: " + original); + var result = new DecodedMovie + { + Name = original, + Frames = checked((int)BitConverter.ToUInt32(bytes, 8)), + Width = checked((int)BitConverter.ToUInt32(bytes, 20)), + Height = checked((int)BitConverter.ToUInt32(bytes, 24)), + Rate = BitConverter.ToUInt32(bytes, 28), + Divisor = BitConverter.ToUInt32(bytes, 32), + HasAudio = BitConverter.ToUInt32(bytes, 40) > 0 + }; + if (result.Frames <= 0 || result.Width <= 0 || result.Height <= 0 || result.Rate == 0 || result.Divisor == 0) + throw new InvalidDataException("Invalid original Bink frame clock: " + original); + string hash; + using (SHA256 algorithm = SHA256.Create()) + hash = BitConverter.ToString(algorithm.ComputeHash(bytes)).Replace("-", "").ToLowerInvariant(); + string entry = Path.Combine(_cache, hash); + result.Directory = Path.Combine(entry, "rgba-pcm-v1"); + if (TryReadPublishedMovie(result, out _)) + return result; + SemaphoreSlim decodeLease = DecodeLeases.GetOrAdd(entry, _ => new SemaphoreSlim(1)); + if (!decodeLease.Wait(CacheWait, cancellation)) + throw new TimeoutException("Timed out waiting for the battle movie decoder."); + try + { + Directory.CreateDirectory(entry); + using FileStream lease = LockCacheEntry(entry, cancellation); + if (TryReadPublishedMovie(result, out string cacheError)) + return result; + if (cacheError != null) + File.Delete(Path.Combine(result.Directory, "complete")); + if (_ffmpeg == null || !File.Exists(_ffmpeg)) + { + const string missingDecoder = "Set PAL3_BATTLE_FFMPEG to a local ffmpeg binary for original Bink playback."; + throw new FileNotFoundException(cacheError == null ? missingDecoder : cacheError + " " + missingDecoder, _ffmpeg); + } + string staging = Path.Combine(entry, Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(staging); + try + { + DecodeInto(staging, original, bytes, result.HasAudio, cancellation); + cancellation.ThrowIfCancellationRequested(); + ValidateDecodedFiles(result, staging); + File.WriteAllText(Path.Combine(staging, "complete"), "Original Bink SHA256 " + hash); + if (Directory.Exists(result.Directory)) + Directory.Delete(result.Directory, recursive: true); + Directory.Move(staging, result.Directory); + } + finally + { + if (Directory.Exists(staging)) + Directory.Delete(staging, recursive: true); + } + } + finally + { + decodeLease.Release(); + } + return result; + } + + private static bool TryReadPublishedMovie(DecodedMovie movie, out string error) + { + error = null; + if (!File.Exists(Path.Combine(movie.Directory, "complete"))) + return false; + try + { + ValidateDecodedFiles(movie, movie.Directory); + return true; + } + catch (Exception exception) when (exception is IOException or InvalidDataException) + { + error = exception.Message; + return false; + } + } + + private void DecodeInto(string directory, string original, byte[] bytes, bool hasAudio, CancellationToken cancellation) + { + string input = Path.Combine(directory, "original.bik"); + File.WriteAllBytes(input, bytes); + var startInfo = new ProcessStartInfo(_ffmpeg) + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardError = true + }; + string[] videoArguments = + { + "-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-i", input, + "-map", "0:v:0", "-pix_fmt", "rgba", "-f", "rawvideo", Path.Combine(directory, "video.rgba") + }; + foreach (string argument in videoArguments) + startInfo.ArgumentList.Add(argument); + if (hasAudio) + { + string[] audioArguments = { "-map", "0:a:0", "-ac", "2", "-ar", "48000", "-c:a", "pcm_s16le", Path.Combine(directory, "audio.wav") }; + foreach (string argument in audioArguments) + startInfo.ArgumentList.Add(argument); + } + using var process = new Process { StartInfo = startInfo }; + RunDecoder(process, original, DecodeWait, cancellation); + } + + private static void RunDecoder(Process process, string original, TimeSpan timeout, CancellationToken cancellation) + { + cancellation.ThrowIfCancellationRequested(); + process.Start(); + try + { + Task stderr = process.StandardError.ReadToEndAsync(); + Stopwatch elapsed = Stopwatch.StartNew(); + while (!process.WaitForExit(50)) + { + cancellation.ThrowIfCancellationRequested(); + if (elapsed.Elapsed >= timeout) + throw new TimeoutException("ffmpeg timed out decoding " + original); + } + int remaining = (int)Math.Max(0, Math.Ceiling((timeout - elapsed.Elapsed).TotalMilliseconds)); + if (Task.WaitAny(new Task[] { stderr }, remaining, cancellation) < 0) + throw new TimeoutException("ffmpeg did not close its output for " + original); + string errors = stderr.GetAwaiter().GetResult(); + if (process.ExitCode != 0) + throw new InvalidDataException("ffmpeg could not decode " + original + ": " + errors); + } + finally + { + if (!process.HasExited) + { + try + { + process.Kill(); + } + catch (InvalidOperationException) when (process.HasExited) + { + // It exited just before the cancellation reached it. + } + process.WaitForExit(1000); + } + } + } + + private static FileStream LockCacheEntry(string directory, CancellationToken cancellation) + { + // The cache is shared by Unity processes. The OS releases the writer lease + // even if a batch job terminates while FFmpeg is producing the files. + var lease = new FileStream(Path.Combine(directory, "decode.lock"), FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.ReadWrite); + try + { + Stopwatch wait = Stopwatch.StartNew(); + while (true) + { + cancellation.ThrowIfCancellationRequested(); + try + { + lease.Lock(0, 1); + return lease; + } + catch (IOException exception) + { + if (wait.Elapsed >= CacheWait) + throw new TimeoutException("Timed out waiting for the battle movie cache writer.", exception); + cancellation.WaitHandle.WaitOne(50); + } + } + } + catch + { + lease.Dispose(); + throw; + } + } + + private static void CheckFrameCount(DecodedMovie movie, long bytes) + { + if (bytes != (long)movie.FrameBytes * movie.Frames) + throw new InvalidDataException("Decoded Bink frame count differs from its original header."); + } + + private static void ValidateDecodedFiles(DecodedMovie movie, string directory) + { + CheckFrameCount(movie, new FileInfo(Path.Combine(directory, "video.rgba")).Length); + if (!movie.HasAudio) + return; + using var stream = File.OpenRead(Path.Combine(directory, "audio.wav")); + using var reader = new BinaryReader(stream, Encoding.ASCII); + _ = ReadPcmHeader(reader); + } + + private static AudioClip ReadAudio(string path, bool silent) + { + using var stream = File.OpenRead(path); + using var reader = new BinaryReader(stream, Encoding.ASCII); + (int channels, int rate, int count) = ReadPcmHeader(reader); + var samples = new float[count]; + if (!silent) + for (int index = 0; index < samples.Length; index++) + samples[index] = reader.ReadInt16() / 32768f; + AudioClip clip = AudioClip.Create("Original combat movie", samples.Length / channels, channels, rate, false); + clip.hideFlags = HideFlags.DontSave; + clip.SetData(samples, 0); + return clip; + } + + private static (int channels, int rate, int samples) ReadPcmHeader(BinaryReader reader) + { + Stream stream = reader.BaseStream; + if (new string(reader.ReadChars(4)) != "RIFF") + throw new InvalidDataException("Invalid decoded PCM header."); + reader.ReadUInt32(); + if (new string(reader.ReadChars(4)) != "WAVE") + throw new InvalidDataException("Invalid decoded PCM format."); + int channels = 0, rate = 0, bits = 0; + while (stream.Position + 8 <= stream.Length) + { + string name = new(reader.ReadChars(4)); + uint count = reader.ReadUInt32(); + long end = checked(stream.Position + count + (count & 1)); + if (end > stream.Length) + throw new InvalidDataException("Invalid decoded PCM chunk length."); + if (name == "fmt ") + { + if (count < 16) + throw new InvalidDataException("Invalid decoded PCM format chunk."); + if (reader.ReadUInt16() != 1) + throw new InvalidDataException("Expected signed 16-bit PCM from the local decoder."); + channels = reader.ReadUInt16(); + rate = reader.ReadInt32(); + reader.ReadUInt32(); + reader.ReadUInt16(); + bits = reader.ReadUInt16(); + } + else if (name == "data") + { + if (count == 0 || channels is not (1 or 2) || rate <= 0 || bits != 16 || count % (channels * 2) != 0) + throw new InvalidDataException("Invalid decoded PCM sample data."); + return (channels, rate, (int)(count / 2)); + } + stream.Position = end; + } + throw new InvalidDataException("Decoded movie has no PCM sample chunk."); + } + + public void Advance(double unscaledSeconds) + { + foreach (var (name, preparation) in _prepared) + if (preparation.IsCompleted && !_reportedFailures.Contains(name)) + ReportFailure(name, CompletedPreparation(preparation)); + + double elapsed = unscaledSeconds == (double)(float)Battle.BattleSession.StepSeconds ? Battle.BattleSession.StepSeconds : unscaledSeconds; + foreach (Movie movie in _movies) + { + try + { + movie.Advance(elapsed); + } + catch (Exception exception) when (IsMediaFailure(exception)) + { + movie.Dispose(); + var failure = new Preparation { Error = exception.Message }; + _prepared[movie.Name] = Task.FromResult(failure); + ReportFailure(movie.Name, failure); + } + } + for (int index = _movies.Count - 1; index >= 0; index--) + if (_movies[index].Finished) + { + _movies[index].Dispose(); + _movies.RemoveAt(index); + } + } + + public bool Skip() + { + Movie movie = _movies.LastOrDefault(item => !item.Finished); + if (movie == null) + return false; + movie.Dispose(); + _movies.Remove(movie); + return true; + } + + public void Render(Camera camera) + { + Movie movie = _movies.LastOrDefault(item => !item.Finished); + if (movie?.Texture == null) + { + if (_overlay != null) + _overlay.enabled = false; + return; + } + if (_overlay == null) + CreateOverlay(camera); + + _overlay.enabled = true; + _frameMaterial.mainTexture = movie.Texture; + float distance = camera.nearClipPlane + 0.001f; + float height = camera.orthographic ? camera.orthographicSize : distance * Mathf.Tan(camera.fieldOfView * Mathf.Deg2Rad * 0.5f); + _overlay.transform.localPosition = new Vector3(0, 0, distance); + _overlay.transform.localScale = new Vector3(height * camera.aspect, height, 1); + + float aspect = movie.Texture.width / (float)movie.Texture.height; + var scale = new Vector2(Mathf.Min(1, aspect / camera.aspect), Mathf.Min(1, camera.aspect / aspect)); + if (!_frameScale.Equals(scale)) + { + _frameScale = scale; + SetQuad(4, scale.x, scale.y); + _screen.vertices = _screenVertices; + } + } + + private void CreateOverlay(Camera camera) + { + _frameMaterial = new Material(Shader.Find("Pal3/Effect")) { hideFlags = HideFlags.DontSave, renderQueue = 5000 }; + _frameMaterial.SetInt("_SrcBlend", (int)BlendMode.One); + _frameMaterial.SetInt("_DstBlend", (int)BlendMode.Zero); + _frameMaterial.SetInt("_ZTest", (int)CompareFunction.Always); + _frameMaterial.SetInt("_Cull", (int)CullMode.Off); + _backdrop = new Material(_frameMaterial) + { + hideFlags = HideFlags.DontSave, + renderQueue = 4999, + mainTexture = Texture2D.blackTexture + }; + + SetQuad(0, 1, 1); + _screen = new Mesh { hideFlags = HideFlags.DontSave, vertices = _screenVertices }; + var uv = new[] { new Vector2(0, 1), new Vector2(1, 1), new Vector2(1, 0), new Vector2(0, 0) }; + _screen.uv = uv.Concat(uv).ToArray(); + _screen.colors = Enumerable.Repeat(Color.white, _screenVertices.Length).ToArray(); + _screen.subMeshCount = 2; + _screen.SetTriangles(new[] { 0, 1, 2, 0, 2, 3 }, 0); + _screen.SetTriangles(new[] { 4, 5, 6, 4, 6, 7 }, 1); + + GameObject surface = _preview.CreateObject("Battle movie overlay"); + // Parent to the preview camera so the overlay follows its pose and stays out of stage framing. + surface.transform.SetParent(camera.transform, false); + surface.layer = _preview.Root.layer; + surface.AddComponent().sharedMesh = _screen; + _overlay = surface.AddComponent(); + // URP compares renderer sorting order before material queue. + _overlay.sortingOrder = short.MaxValue; + _overlay.shadowCastingMode = ShadowCastingMode.Off; + _overlay.receiveShadows = false; + _overlay.sharedMaterials = new[] { _backdrop, _frameMaterial }; + } + + private void SetQuad(int offset, float halfWidth, float halfHeight) + { + _screenVertices[offset] = new Vector3(-halfWidth, -halfHeight, 0); + _screenVertices[offset + 1] = new Vector3(halfWidth, -halfHeight, 0); + _screenVertices[offset + 2] = new Vector3(halfWidth, halfHeight, 0); + _screenVertices[offset + 3] = new Vector3(-halfWidth, halfHeight, 0); + } + + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + _shutdown.Cancel(); + // Workers own plain files and processes. Closing a preview must never join them on the UI thread. + _ = Task.WhenAll(_prepared.Values).ContinueWith(done => + { + _ = done.Exception; + _shutdown.Dispose(); + }, TaskScheduler.Default); + foreach (Movie movie in _movies) + movie.Dispose(); + _movies.Clear(); + if (_overlay != null) + Object.DestroyImmediate(_overlay.gameObject); + if (_frameMaterial != null) + Object.DestroyImmediate(_frameMaterial); + if (_backdrop != null) + Object.DestroyImmediate(_backdrop); + if (_screen != null) + Object.DestroyImmediate(_screen); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Media/BattleMoviePlayer.cs.meta b/Assets/Scripts/Editor/BattleEditor/Media/BattleMoviePlayer.cs.meta new file mode 100644 index 00000000..bec3a098 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Media/BattleMoviePlayer.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c3dbc3319fbc4a948b489339fa4f254b diff --git a/Assets/Scripts/Editor/BattleEditor/Media/IBattleMovieAudioTransport.cs b/Assets/Scripts/Editor/BattleEditor/Media/IBattleMovieAudioTransport.cs new file mode 100644 index 00000000..f89e5b3d --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Media/IBattleMovieAudioTransport.cs @@ -0,0 +1,16 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using UnityEngine; + + public interface IBattleMovieAudioTransport + { + void SynchronizeMovie(object owner, AudioClip clip, double elapsed, bool playing); + + void StopMovie(object owner); + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Media/IBattleMovieAudioTransport.cs.meta b/Assets/Scripts/Editor/BattleEditor/Media/IBattleMovieAudioTransport.cs.meta new file mode 100644 index 00000000..f6012526 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Media/IBattleMovieAudioTransport.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b8ce071a36aa4611bf782c2dc321412f diff --git a/Assets/Scripts/Editor/BattleEditor/Pal3.BattleEditor.asmdef b/Assets/Scripts/Editor/BattleEditor/Pal3.BattleEditor.asmdef new file mode 100644 index 00000000..d8fa28d3 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Pal3.BattleEditor.asmdef @@ -0,0 +1,15 @@ +{ + "name": "Pal3.BattleEditor", + "references": [ + "Pal3.Battle", + "Pal3.Core", + "Pal3.Game", + "Engine", + "Pal3.ResourceBrowser.Editor", + "Pal3.Battle.Presentation", + "Unity.InputSystem" + ], + "includePlatforms": [ + "Editor" + ] +} diff --git a/Assets/Scripts/Editor/BattleEditor/Pal3.BattleEditor.asmdef.meta b/Assets/Scripts/Editor/BattleEditor/Pal3.BattleEditor.asmdef.meta new file mode 100644 index 00000000..6dbaa886 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Pal3.BattleEditor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 625ccaeb6611c46e9aaf3da7a621daa8 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/BattleEditor/Preview.meta b/Assets/Scripts/Editor/BattleEditor/Preview.meta new file mode 100644 index 00000000..099d0bbb --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 406a8e67fd6546fca23c2342aaf8094a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraDirector.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraDirector.cs new file mode 100644 index 00000000..46f1f8a6 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraDirector.cs @@ -0,0 +1,123 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using Battle; + using Core.DataReader.Dat; + using Core.Primitives; + using Game.Effect.Runtime; + + // The stage supplies the role-pool lookup (-1 means the five-lineup + // origin) and consumes raw GameBox poses. Rendering conversion stays at + // that boundary; none of the original camera arithmetic uses Unity axes. + public sealed class BattleCameraDirector : IEffectCamera + { + private readonly Action _output; + + public BattleCameraController Controller + { + get; + } + + public bool HasStartedList + { + get; private set; + } + + public BattleCameraDirector(BattleData data, BattleCameraPose initialPose, Func tracePosition, + Action output, float fieldOfView = 50) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + FlexCameraFile file = data.Read("basedata.cpk\\cbdata\\flexcam.dat", new FlexCameraFileReader()); + Controller = new BattleCameraController(Compile(file), initialPose, tracePosition, fieldOfView); + _output = output; + Publish(); + } + + public bool StartList(int index) + { + if (!Controller.StartList(index)) + return false; + // Native lists retain camera ownership after stopping or finishing. + HasStartedList = true; + return true; + } + + public void StopList() => Controller.StopList(); + + public void SetQuake(float amplitude, float frequency, float decay) => Controller.SetQuake(amplitude, frequency, decay); + + public void Advance(double scaledSeconds, double absoluteSeconds) + { + Controller.Advance(scaledSeconds, absoluteSeconds); + Publish(); + } + + public void AdvanceAt(double scaledTime, double absoluteTime, double scaledSeconds, double absoluteSeconds) + { + Controller.AdvanceAt(scaledTime, absoluteTime, scaledSeconds, absoluteSeconds); + Publish(); + } + + public void Publish() => _output?.Invoke(Controller.Pose, Controller.FieldOfView, Controller.TrailEnabled); + + public static IReadOnlyList> Compile(FlexCameraFile file) + { + if (file == null) + throw new ArgumentNullException(nameof(file)); + var pool = new BattleCameraTask[file.Pool.Count]; + for (int i = 0; i < pool.Length; i++) + { + FlexCameraTask original = file.Pool[i]; + pool[i] = new BattleCameraTask + { + Flags = (BattleCameraFlags)(int)original.Flags, + Start = Pose(original.Start), + End = Pose(original.End), + ExpectedSeconds = original.ExpectedSeconds, + Splice = original.Splice, + TraceActor = original.TraceActor, + StartSpeed = original.StartSpeed, + Inertia = original.Inertia, + FirstAccelerationStart = original.FirstAccelerationStart, + SecondAccelerationStart = original.SecondAccelerationStart, + FirstAcceleration = original.FirstAcceleration, + SecondAcceleration = original.SecondAcceleration, + CircleAngle = original.CircleAngle, + AngularSpeed = original.AngularSpeed, + CircleCenter = Point(original.CircleCenter), + CircleEnd = Point(original.CircleEnd), + SwingFrequency = original.SwingFrequency, + SwingAmplitude = original.SwingAmplitude, + TimeCompensation = original.TimeCompensation, + StartFieldOfView = original.StartFieldOfView, + EndFieldOfView = original.EndFieldOfView, + SavedTraceStart = Point(original.SavedTraceStart) + }; + } + var lists = new IReadOnlyList[file.Lists.Count]; + for (int i = 0; i < lists.Length; i++) + { + var list = new List(); + foreach (int index in file.Lists[i]) + { + if (index == -1) + break; + list.Add(pool[index]); + } + lists[i] = list.AsReadOnly(); + } + return Array.AsReadOnly(lists); + } + + public static BattleCameraPose Pose(FlexCameraPose original) => new(Point(original.Position), original.Yaw, original.Pitch, original.Roll); + + private static BattleMovementPoint Point(GameBoxVector3 original) => new(original.X, original.Y, original.Z); + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraDirector.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraDirector.cs.meta new file mode 100644 index 00000000..edcd0ce8 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraDirector.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 82d4622b0b0745398d281cbb20cb243a diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraProjection.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraProjection.cs new file mode 100644 index 00000000..3fe2f9f4 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraProjection.cs @@ -0,0 +1,37 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using Battle; + using UnityEngine; + + // Immutable projection of a published gameplay camera. Editor navigation, + // framing and viewport dimensions have no ownership of capture physics. + public readonly struct BattleCameraProjection + { + private readonly Matrix4x4 _worldToClip; + + public BattleCameraProjection(BattleCameraPose pose, float horizontalFieldOfView) + { + if (!float.IsFinite(horizontalFieldOfView) || horizontalFieldOfView <= 0 || horizontalFieldOfView >= 180) + throw new ArgumentOutOfRangeException(nameof(horizontalFieldOfView)); + const float aspect = 4f / 3; + Vector3 Direction(BattleMovementPoint value) => new(-value.X, value.Y, value.Z); + Quaternion orientation = Quaternion.LookRotation(Direction(pose.Forward), Direction(pose.Up)); + Matrix4x4 view = Matrix4x4.Scale(new Vector3(1, 1, -1)) * + Matrix4x4.TRS(BattleAnimationCatalog.UnityPosition(pose.Position), orientation, Vector3.one).inverse; + Matrix4x4 projection = Matrix4x4.Perspective(Camera.HorizontalToVerticalFieldOfView(horizontalFieldOfView, aspect), aspect, .01f, 10000); + _worldToClip = projection * view; + } + + public BattleSpiritPoint Project(BattleMovementPoint world) + { + Vector3 point = _worldToClip.MultiplyPoint(BattleAnimationCatalog.UnityPosition(world)); + return new BattleSpiritPoint((point.x + 1) * 400, (1 - point.y) * 300); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraProjection.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraProjection.cs.meta new file mode 100644 index 00000000..5ccd67aa --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattleCameraProjection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 89f5dba9f38441749a5f877c3c0e0a49 diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattleDamageNumberColors.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattleDamageNumberColors.cs new file mode 100644 index 00000000..56fb583b --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattleDamageNumberColors.cs @@ -0,0 +1,31 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + public enum BattleDamageNumberColorMode + { + Original, + Yellow, + White + } + + public static class BattleDamageNumberColors + { + public static uint Resolve(uint nativeColor, BattleDamageNumberColorMode mode) + { + // The native projection uniquely assigns this color to HP damage + // and its zero result. Keep all other number kinds unchanged. + if (nativeColor != 0x3232ffu) + return nativeColor; + return mode switch + { + BattleDamageNumberColorMode.Yellow => 0xffff00u, + BattleDamageNumberColorMode.White => 0xffffffu, + _ => nativeColor + }; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattleDamageNumberColors.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattleDamageNumberColors.cs.meta new file mode 100644 index 00000000..ba5d9770 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattleDamageNumberColors.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5f5f51e0134c46c89268c450bcba89d4 diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattleEffectDirector.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattleEffectDirector.cs new file mode 100644 index 00000000..326884dd --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattleEffectDirector.cs @@ -0,0 +1,334 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using Battle; + using Game.Effect.Runtime; + using ResourceBrowser; + using UnityEngine; + using Object = UnityEngine.Object; + + // Native weapon skills use the ATS manager: all child effects advance on the + // absolute clock while the ordinary combat clock is frozen. + public sealed class BattleEffectDirector : IBattleEffectDirector, IBattleEffectPreloader, IBattleModalEffects, IBattlePresentationPreparation, IBattleStagePresentation, IBattleAudio, IBattleMovementAudio, IBattleSpiritCaptureLayout, IBattleEffectContext, IEffectTimeControl, IBattleTimeScale, IDisposable + { + private readonly ResourceModelPreview _preview; + private readonly EffectResources _resources; + private readonly EffectOverrides _overrides; + private BattleSession _session; + private BattleRandom _effectRandom; + private readonly BattleMoviePlayer _movies; + + public Func SpiritProjector + { + get; set; + } + + public BattleSpiritPoint CaptureSpiritOrigin(string actorId, BattleMovementPoint world) => + SpiritProjector?.Invoke(actorId, world) ?? throw new InvalidOperationException("A capture requires its battle camera projection."); + + public BattleSpiritRect SpiritWheelTarget(int coreElement) => BattlePreview.SpiritWheelTarget(coreElement); + + public IEffectCamera Camera + { + get; private set; + } + + public bool BlocksBattleTime => _movies.BlocksBattleTime; + + public bool IsPreparingPlayback => _movies.IsPreparingPlayback; + + internal void ReusePreparedMovies(BattleEffectDirector previous) => _movies.ReusePreparedMovies(previous._movies); + + public bool SkipModalPresentation() => _movies.Skip(); + + public IReadOnlyList MissingMovies => _movies.MissingMovies; + public IReadOnlyList MovieDiagnostics => _movies.Diagnostics; + + public IReadOnlyCollection MissingBattleTextures => _resources.MissingBattleTextures; + + public bool Muted + { + get => _movies.Muted; set => _movies.Muted = value; + } + + public bool AudioPlaybackEnabled + { + get => _movies.AudioPlaybackEnabled; set => _movies.AudioPlaybackEnabled = value; + } + + public void Bind(BattleSession session, IEffectCamera camera) + { + _session = session ?? throw new ArgumentNullException(nameof(session)); + Camera = camera ?? throw new ArgumentNullException(nameof(camera)); + } + + public IEffectActor Actor(int nativeIndex, uint modelCrc = 0) + { + if (_session == null) + throw new InvalidOperationException("A combat actor effect requires a bound battle session."); + string actor = _session.EffectActorId(nativeIndex, modelCrc); + return actor == null ? null : new ActorPort(_session, actor); + } + + public IEffectMovie PlayMovie(string originalPath) => _movies.Play(originalPath); + + public int NextEffectRandom() => (_effectRandom ?? throw new InvalidOperationException("No original effect has started its random stream.")).Next(); + + private sealed class ActorPort : IEffectActor + { + private readonly BattleSession _session; + private readonly string _actor; + + public ActorPort(BattleSession session, string actor) + { + _session = session; + _actor = actor; + } + + public Vector3 Position + { + get + { + BattleMovementPoint p = _session.EffectActor(_actor).Position; + return new Vector3(p.X, p.Y, p.Z); + } + set => _session.SetEffectActorPosition(_actor, new BattleMovementPoint(value.x, value.y, value.z)); + } + + public float FacingDegrees + { + get => _session.EffectActor(_actor).FacingDegrees; set => _session.SetEffectActorFacing(_actor, value); + } + + public float Blend + { + get => _session.EffectActor(_actor).Blend; set => _session.SetEffectActorBlend(_actor, value); + } + + public bool ActionOver => _session.EffectActor(_actor).ActionOver; + + public void SetExternalTask(bool controlled, object owner) => _session.SetEffectActorControlled(_actor, controlled, owner); + + public void SetAction(string action) => _session.SetEffectActorAction(_actor, action); + + public void SetLongBlade(bool enabled) => _session.SetEffectActorBlade(_actor, enabled); + + public void SetWeapons(float left, float right) => _session.SetEffectActorWeapons(_actor, left, right); + } + + private sealed class EffectInstance + { + public EffectPlayer Player; + public bool AbsoluteTime; + } + + private readonly Dictionary _players = new(); + private long _nextHandle, _lastFrame = -1; + private bool _disposed; + private long[] _pendingPlayers; + private int _pendingPlayer; + private double _scaledTime, _absoluteTime; + private readonly Dictionary _timeScales = new(); + + public float TimeScale => _timeScales.Count == 0 ? 1f : _timeScales.Values.Min(); + + void IEffectTimeControl.SetTimeScale(object owner, float scale) => _timeScales[owner] = scale; + + void IEffectTimeControl.ClearTimeScale(object owner) => _timeScales.Remove(owner); + + public bool IsModalPresentationRunning => BlocksBattleTime; + + public event Action SoundRequested; + + public void PlaySound(string sound) => SoundRequested?.Invoke(sound); + + public event Action MovementSoundRequested; + + public event Action MovementSoundStopped; + + public event Action BodySoundsStopped; + + public void PlayMovementSound(string actor, string sound, bool loop) => MovementSoundRequested?.Invoke(actor, sound, loop); + + public void StopMovementSound(string actor) => MovementSoundStopped?.Invoke(actor); + + public void StopBodySounds() => BodySoundsStopped?.Invoke(); + + public event Action StageAdvanced; + + public void AdvanceStage(double scaledSeconds, double absoluteSeconds) => StageAdvanced?.Invoke(scaledSeconds, absoluteSeconds); + + public BattleEffectDirector(BattleData data, ResourceModelPreview preview, IBattleMovieAudioTransport audio = null) + { + if (data == null || preview == null) + throw new ArgumentNullException(data == null ? nameof(data) : nameof(preview)); + _preview = preview; + try + { + _movies = new BattleMoviePlayer(data, preview, audio); + _resources = new EffectResources(data.Resources.FileSystem, data.Resources.Codepage); + _overrides = Resources.Load(_resources.OverridesPath); + } + catch + { + Dispose(); + throw; + } + } + + public void Preload(int groupId) + { + if (_disposed) + throw new ObjectDisposedException(nameof(BattleEffectDirector)); + string[] errors = _resources.Diagnose(groupId, _overrides, battleContext: true); + if (errors.Length > 0) + throw new InvalidDataException(string.Join("\n", errors)); + var visited = new HashSet(); + foreach (int id in _resources.Preload(groupId, _overrides, battleContext: true)) + { + if (!visited.Add(id)) + continue; + foreach (string movie in _resources.BinkMovies(id, _overrides)) + _movies.Preload(movie); + } + } + + public long Start(BattleEffectRequest request) + { + if (_disposed) + throw new ObjectDisposedException(nameof(BattleEffectDirector)); + if (request == null) + throw new ArgumentNullException(nameof(request)); + Preload(request.GroupId); + // The original GT util singleton is separate from combat CUtil. + // Capture one replayable visual stream, retaining it across groups. + _effectRandom ??= new BattleRandom(unchecked((int)request.Seed)); + GameObject root = _preview.CreateObject("Battle effect " + request.GroupId); + EffectPlayer player = null; + try + { + root.transform.localPosition = BattleAnimationCatalog.UnityPosition(request.Origin); + player = root.AddComponent(); + player.AutoAdvance = false; + player.Loop = false; + player.Initialize(_resources, request.GroupId, request.Seed, _overrides, sound => SoundRequested?.Invoke(sound), this, request.AbsoluteTime ? _absoluteTime : _scaledTime, nativeLighting: _preview.NativeLighting); + if (player.Error != null) + throw new InvalidDataException(player.Error); + long handle = checked(++_nextHandle); + _players.Add(handle, new EffectInstance { Player = player, AbsoluteTime = request.AbsoluteTime }); + return handle; + } + catch + { + player?.Dispose(); + Object.DestroyImmediate(root); + throw; + } + } + + public bool IsRunning(long handle) + { + if (!_players.TryGetValue(handle, out EffectInstance instance) || instance.Player == null) + return false; + if (instance.Player.Error != null) + throw new InvalidDataException(instance.Player.Error); + return instance.Player.IsAlive; + } + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + if (_disposed) + throw new ObjectDisposedException(nameof(BattleEffectDirector)); + if (frame < _lastFrame || !float.IsFinite(scaledSeconds) || !float.IsFinite(unscaledSeconds) || scaledSeconds < 0 || unscaledSeconds < 0) + throw new ArgumentException("Effect frames and time deltas must be ordered and finite."); + if (frame == _lastFrame) + return; + _lastFrame = frame; + _movies.Advance(ClockDelta(unscaledSeconds)); + if (BlocksBattleTime) + return; + if (_pendingPlayers != null) + { + if (_players.TryGetValue(_pendingPlayers[_pendingPlayer], out EffectInstance suspended)) + { + if (!suspended.Player.ResumeBattleStep()) + { + if (suspended.Player.Error != null) + throw new InvalidDataException(suspended.Player.Error); + return; + } + if (!suspended.Player.IsAlive) + Stop(_pendingPlayers[_pendingPlayer]); + } + _pendingPlayer++; + } + else + { + _pendingPlayers = _players.Keys.ToArray(); + _pendingPlayer = 0; + _scaledTime += ClockDelta(scaledSeconds); + _absoluteTime += ClockDelta(unscaledSeconds); + } + for (; _pendingPlayer < _pendingPlayers.Length; _pendingPlayer++) + { + long handle = _pendingPlayers[_pendingPlayer]; + if (!_players.TryGetValue(handle, out EffectInstance instance)) + continue; + EffectPlayer player = instance.Player; + if (player == null) + { + _players.Remove(handle); + continue; + } + player.AdvanceTo(instance.AbsoluteTime ? _absoluteTime : _scaledTime, _absoluteTime); + if (player.Error != null) + throw new InvalidDataException(player.Error); + if (BlocksBattleTime) + return; + if (!player.IsAlive) + Stop(handle); + } + _pendingPlayers = null; + } + + private static double ClockDelta(float seconds) => seconds == (float)BattleSession.StepSeconds ? BattleSession.StepSeconds : seconds; + + public void Render(Camera camera) + { + if (_disposed || camera == null) + return; + _movies.Render(camera); + foreach (EffectInstance instance in _players.Values) + if (instance.Player != null) + instance.Player.Render(camera); + } + + public void Stop(long handle) + { + if (_players.Remove(handle, out EffectInstance instance) && instance.Player != null) + { + instance.Player.Dispose(); + Object.DestroyImmediate(instance.Player.gameObject); + } + } + + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + foreach (long handle in _players.Keys.ToArray()) + Stop(handle); + _movies?.Dispose(); + _resources?.Dispose(); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattleEffectDirector.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattleEffectDirector.cs.meta new file mode 100644 index 00000000..42cd65fb --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattleEffectDirector.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 20cb02ce59184c1397f4a978011cd05c diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Corpses.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Corpses.cs new file mode 100644 index 00000000..aa75cc2b --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Corpses.cs @@ -0,0 +1,52 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using Battle; + using Core.DataReader.Pol; + using UnityEngine; + + public sealed partial class BattlePreview + { + private readonly Dictionary _corpses = new(StringComparer.Ordinal); + + private void ApplyCorpses(BattleSession combat) + { + if (combat.Status != BattleSessionStatus.Completed || combat.Result.Winner != BattleSide.Ally && !combat.Result.Escaped) + return; + var center = _data.Layout.AllyFormationConfig.CenterGameBoxPosition; + int ordinal = 0; + foreach (BattleActorSnapshot actor in combat.Actors) + { + if (actor.NativeIndex < 5 || actor.CorpseItem == 0) + continue; + if (!_corpses.TryGetValue(actor.Id, out GameObject model)) + { + var item = _data.Database.GameItemInfos[actor.CorpseItem]; + string path = $"basedata.cpk\\item\\{item.ModelName}\\{item.ModelName}.pol"; + model = View.CreateObject("Corpse " + actor.Id); + try + { + View.AddPolyModel(model, path, _data.Read(path, new PolFileReader()), item.ModelName + item.ImageId + ".tga"); + } + catch + { + View.ReleaseCompositeObject(model); + throw; + } + _corpses.Add(actor.Id, model); + } + // Both published Scene.Render loops use 20 native units at + // successive 60-degree angles, two units above the party center. + double angle = ordinal++ * 60 * (double).01745329238474369f; + model.transform.position = BattleAnimationCatalog.UnityPosition(new BattleMovementPoint( + (float)(center.X + 20 * Math.Sin(angle)), center.Y + 2, (float)(center.Z + 20 * Math.Cos(angle)))); + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Corpses.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Corpses.cs.meta new file mode 100644 index 00000000..38c9a4b4 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Corpses.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c2bbe92d8c4b47408c300d0c0bc5f778 diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HitFeedback.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HitFeedback.cs new file mode 100644 index 00000000..e16e1b02 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HitFeedback.cs @@ -0,0 +1,249 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Engine.Extensions; + using UnityEngine; + using UnityEngine.Rendering; + using Object = UnityEngine.Object; + + public sealed partial class BattlePreview + { + private BattleSession _hitFeedbackOwner; + private IReadOnlyList _hitFeedbackFrames = Array.Empty(); + private readonly List _weaponSparks = new(); + private BattleRandom _weaponSparkRandom; + private double? _lastWeaponSparkTime; + private float _weaponSparkEmissionTime; + private GameObject _hitFlashObject, _weaponSparkObject; + private Mesh _hitFlashMesh, _weaponSparkMesh; + private Material _hitFlashMaterial, _weaponSparkMaterial; + + public IReadOnlyList HitFlashFrames => _hitFeedbackFrames; + + public int WeaponSparkCount => _weaponSparks.Count; + + public void ApplyHitFeedback(BattleSession combat) + { + if (_hitFeedbackOwner != combat) + { + _hitFeedbackOwner = combat; + _weaponSparks.Clear(); + _weaponSparkRandom = new BattleRandom(_scenario.Seed); + _lastWeaponSparkTime = null; + _weaponSparkEmissionTime = 0; + } + _hitFeedbackFrames = combat.Status == BattleSessionStatus.Running ? combat.HitFlashes : Array.Empty(); + } + + private void EnsureHitFeedbackMesh(bool sparks) + { + if (sparks ? _weaponSparkObject != null : _hitFlashObject != null) + return; + Shader shader = Shader.Find("Pal3/Effect"); + if (shader == null) + throw new InvalidOperationException("The battle hit feedback shader is missing."); + Texture texture = View.GetTexture(sparks ? "basedata.cpk\\effect\\flare2.bmp" : "basedata.cpk\\effect\\combat\\100\\z01\\z01.tga"); + GameObject root = null; + Mesh mesh = null; + Material material = null; + try + { + root = View.CreateObject(sparks ? "Original weapon red sparks" : "Original monster hit flashes"); + mesh = new Mesh { name = root.name, hideFlags = HideFlags.HideAndDontSave }; + mesh.MarkDynamic(); + material = new Material(shader) + { + name = root.name, + hideFlags = HideFlags.HideAndDontSave, + mainTexture = texture + }; + material.SetInt("_SrcBlend", (int)BlendMode.SrcAlpha); + material.SetInt("_DstBlend", (int)BlendMode.One); + material.SetInt("_Cull", (int)CullMode.Off); + material.SetInt("_ZTest", (int)CompareFunction.LessEqual); + root.AddComponent().sharedMesh = mesh; + var renderer = root.AddComponent(); + renderer.sharedMaterial = material; + renderer.sortingOrder = sparks ? 2 : 4; + renderer.shadowCastingMode = ShadowCastingMode.Off; + renderer.receiveShadows = false; + renderer.lightProbeUsage = LightProbeUsage.Off; + renderer.reflectionProbeUsage = ReflectionProbeUsage.Off; + renderer.enabled = sparks; + } + catch + { + Object.DestroyImmediate(root); + Object.DestroyImmediate(mesh); + Object.DestroyImmediate(material); + throw; + } + if (sparks) + { + _weaponSparkObject = root; + _weaponSparkMesh = mesh; + _weaponSparkMaterial = material; + } + else + { + _hitFlashObject = root; + _hitFlashMesh = mesh; + _hitFlashMaterial = material; + } + } + + private void RenderHitFeedback(Camera camera, RenderTexture target) + { + if (camera == null || target == null || _hitFeedbackOwner == null || _hitFeedbackOwner.IsModalPresentation) + return; + if (_hitFeedbackFrames.Count > 0) + EnsureHitFeedbackMesh(false); + if (_hitFlashMesh != null) + { + var vertices = new List(); + var uv = new List(); + var colors = new List(); + var indices = new List(); + foreach (BattleHitFlashSnapshot flash in _hitFeedbackFrames) + { + Vector3 P(float x, float z) => BattleAnimationCatalog.UnityPosition(new BattleMovementPoint( + flash.Position.X + x, flash.Position.Y, flash.Position.Z + z)); + float left = flash.Frame % 4 / 4f, bottom = flash.Frame / 4 / 4f; + AppendFeedbackQuad(vertices, uv, colors, indices, + P(-100, 100), P(100, 100), P(100, -100), P(-100, -100), + new Vector2(left, bottom), new Vector2(left + .25f, bottom + .25f), new Color32(255, 255, 255, 255)); + } + UploadHitFeedback(_hitFlashMesh, _hitFlashObject, vertices, uv, colors, indices); + // CEffectSimple is rendered after CTrail::End, so this mesh + // must never participate in the ordinary scene/history pass. + _hitFlashObject.GetComponent().enabled = false; + if (vertices.Count > 0) + { + // CTrail::End clears the original target and depth. Its + // composited target has no depth attachment; the ordinary + // camera target still retains scene occlusion. + _hitFlashMaterial.SetInt("_ZTest", (int)(target.depth == 0 ? CompareFunction.Always : CompareFunction.LessEqual)); + RenderTexture previous = RenderTexture.active; + using var commands = new CommandBuffer { name = "Original post-trail hit flash" }; + try + { + commands.SetRenderTarget(target); + commands.SetViewport(new Rect(0, 0, target.width, target.height)); + // Match URP SetCameraMatrices: this command accepts the + // camera projection and performs the backend conversion. + // Pre-converting it flips Metal's render texture twice. + commands.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix); + commands.DrawMesh(_hitFlashMesh, Matrix4x4.identity, _hitFlashMaterial); + Graphics.ExecuteCommandBuffer(commands); + } + finally + { + RenderTexture.active = previous; + } + } + } + } + + private void RenderWeaponSparks(Camera camera) + { + if (BattleData.Variant != "PAL3" || camera == null || _hitFeedbackOwner == null) + return; + double time = _hitFeedbackOwner.SimulationTick * BattleSession.StepSeconds; + if (_resultBattle != null) + time += Math.Max(0, _bladeFrameTime - _resultStart); + bool newFrame = !_lastWeaponSparkTime.HasValue || _lastWeaponSparkTime.Value != time; + if (newFrame) + { + float delta = _lastWeaponSparkTime.HasValue ? (float)Math.Max(0, time - _lastWeaponSparkTime.Value) : 0; + _lastWeaponSparkTime = time; + foreach (BattleWeaponSpark spark in _weaponSparks) + spark.Advance(delta); + _weaponSparks.RemoveAll(spark => !spark.Alive); + // Render's static timer advances only while Zi Xuan's right + // weapon exists and is drawn. GetLastBladePos returns vertex + // zero of the most recently retained native blade record. + foreach (ActorView actor in _actors.Values) + { + if (!actor.Visible || actor.Actor.Side != BattleSide.Ally) + continue; + BattleActorDefinition definition = _hitFeedbackOwner.Definitions.Actors[actor.Actor.InstanceId]; + if (definition.Identity != 3 || definition.Equipment.FirstOrDefault(item => item.Slot == 0)?.WeaponType != 3 || + !actor.Renderer.RightWeaponVisible || !actor.Renderer.TryGetRightWeaponBladeTip(out Vector3 position)) + continue; + _weaponSparkEmissionTime += delta; + if (_weaponSparkEmissionTime >= .05f) + { + _weaponSparkEmissionTime -= .05f; + if (_weaponSparks.Count < 128) + { + float scale = UnityPrimitivesConvertor.GameBoxUnitToUnityUnit; + _weaponSparks.Add(new BattleWeaponSpark(new BattleMovementPoint(-position.x * scale, position.y * scale, position.z * scale), _weaponSparkRandom)); + } + } + } + } + if (_weaponSparks.Count > 0) + EnsureHitFeedbackMesh(true); + if (_weaponSparkMesh == null) + return; + var vertices = new List(); + var uv = new List(); + var colors = new List(); + var indices = new List(); + float radius = BattleWeaponSpark.Size / 2 / UnityPrimitivesConvertor.GameBoxUnitToUnityUnit; + Vector3 right = camera.transform.right * radius, up = camera.transform.up * radius; + foreach (BattleWeaponSpark spark in _weaponSparks) + { + Vector3 center = BattleAnimationCatalog.UnityPosition(spark.Position); + AppendFeedbackQuad(vertices, uv, colors, indices, + center - right - up, center + right - up, center + right + up, center - right + up, + Vector2.zero, Vector2.one, new Color32(255, 255, 255, spark.Alpha)); + } + UploadHitFeedback(_weaponSparkMesh, _weaponSparkObject, vertices, uv, colors, indices); + } + + private static void AppendFeedbackQuad(List vertices, List uv, List colors, List indices, + Vector3 a, Vector3 b, Vector3 c, Vector3 d, Vector2 minimum, Vector2 maximum, Color32 color) + { + int first = vertices.Count; + vertices.AddRange(new[] { a, b, c, d }); + uv.AddRange(new[] { minimum, new Vector2(maximum.x, minimum.y), maximum, new Vector2(minimum.x, maximum.y) }); + colors.AddRange(new[] { color, color, color, color }); + indices.AddRange(new[] { first, first + 1, first + 2, first, first + 2, first + 3 }); + } + + private static void UploadHitFeedback(Mesh mesh, GameObject root, List vertices, List uv, List colors, List indices) + { + mesh.Clear(); + mesh.SetVertices(vertices); + mesh.SetUVs(0, uv); + mesh.SetColors(colors); + mesh.SetTriangles(indices, 0); + root.GetComponent().enabled = vertices.Count > 0; + } + + private void DisposeHitFeedback() + { + foreach (Mesh mesh in new[] { _hitFlashMesh, _weaponSparkMesh }) + if (mesh != null) + Object.DestroyImmediate(mesh); + foreach (Material material in new[] { _hitFlashMaterial, _weaponSparkMaterial }) + if (material != null) + Object.DestroyImmediate(material); + foreach (GameObject root in new[] { _hitFlashObject, _weaponSparkObject }) + if (root != null) + View.ReleaseCompositeObject(root); + _hitFeedbackFrames = Array.Empty(); + _weaponSparks.Clear(); + _hitFeedbackOwner = null; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HitFeedback.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HitFeedback.cs.meta new file mode 100644 index 00000000..006c8d03 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HitFeedback.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1f2be0365bdf43c286ac077406ddb378 diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HudPointers.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HudPointers.cs new file mode 100644 index 00000000..7fabb636 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HudPointers.cs @@ -0,0 +1,42 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using Battle; + using Engine.Extensions; + using UnityEngine; + + public sealed partial class BattlePreview + { + public bool TryHudPointerPose(BattleSession combat, string id, out Vector3 position, out float scale, double? presentationSeconds = null) + { + position = default; + scale = 1; + if (!_actors.TryGetValue(id, out ActorView actor) || !actor.Visible || actor.Object == null || actor.Model?.Meshes.Length is not > 0) + return false; + // gbMVActorDef.GetCollideOBB unions the current action's stored + // mesh boxes; it does not use the sampled frame or weapon bounds. + Bounds bounds = ActorSelectionBounds(actor); + BattleActorSnapshot state = null; + foreach (BattleActorSnapshot candidate in combat.Actors) + if (candidate.Id == id) + state = candidate; + if (state == null) + return false; + float wave = MathF.Sin((float)(presentationSeconds ?? combat.SimulationTick * BattleSession.StepSeconds) * 10 + state.NativeIndex); + float nativeOffset = 10 + wave * 5 + 6; + if (combat.Definitions.Variant == "PAL3" && state.ActorId == 707) + nativeOffset -= 80; + if (combat.Definitions.Variant == "PAL3A" && state.NativeIndex == 0 && combat.IsPal3ATransformed(id)) + nativeOffset += 16; + position = actor.Object.transform.TransformPoint(bounds.center) + Vector3.up * + (bounds.extents.y + nativeOffset / UnityPrimitivesConvertor.GameBoxUnitToUnityUnit); + scale = 1 + wave / 5; + return true; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HudPointers.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HudPointers.cs.meta new file mode 100644 index 00000000..56f7c614 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.HudPointers.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 41f3f63ba09b411cad6055fe62a73684 diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Lineups.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Lineups.cs new file mode 100644 index 00000000..0aa3cc22 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Lineups.cs @@ -0,0 +1,130 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Battle.Presentation; + using UnityEngine; + using UnityEngine.Rendering; + using Object = UnityEngine.Object; + + public sealed partial class BattlePreview + { + private sealed class LineupView + { + public GameObject Object; + public Mesh Mesh; + public Material Material; + } + + private readonly Dictionary<(BattleSide Side, bool Center), LineupView> _lineups = new(); + + public IReadOnlyList LineupFrames { get; private set; } = Array.Empty(); + + private LineupView Lineup(BattleSide side, bool center) + { + var key = (side, center); + if (_lineups.TryGetValue(key, out LineupView view)) + return view; + view = new LineupView { Object = View.CreateObject("Original " + side + (center ? " lineup center" : " five-spirit lineup")) }; + try + { + Shader shader = Shader.Find("Pal3/Effect") ?? throw new InvalidOperationException("The original effect shader is missing."); + view.Material = new Material(shader) + { + hideFlags = HideFlags.HideAndDontSave, + mainTexture = View.GetTexture("basedata.cpk\\cbscene\\fivelineup" + (center ? "_center" : "") + ".tga") + }; + view.Material.SetInt("_SrcBlend", (int)BlendMode.SrcAlpha); + view.Material.SetInt("_DstBlend", (int)BlendMode.One); + view.Material.SetInt("_ZTest", (int)CompareFunction.LessEqual); + view.Material.SetInt("_Cull", (int)CullMode.Off); + view.Mesh = new Mesh { name = view.Object.name, hideFlags = HideFlags.HideAndDontSave }; + view.Mesh.MarkDynamic(); + view.Object.AddComponent().sharedMesh = view.Mesh; + var renderer = view.Object.AddComponent(); + renderer.sharedMaterial = view.Material; + renderer.sortingOrder = 3; // Native RenderLineup follows effects and sparks, before Trail.End. + renderer.shadowCastingMode = ShadowCastingMode.Off; + renderer.receiveShadows = false; + renderer.lightProbeUsage = LightProbeUsage.Off; + renderer.reflectionProbeUsage = ReflectionProbeUsage.Off; + _lineups.Add(key, view); + return view; + } + catch + { + ReleaseLineup(view); + throw; + } + } + + private void ApplyLineups(BattleSession battle) + { + LineupFrames = BattleLineupProjection.Capture(battle); + foreach (BattleSide side in Enum.GetValues(typeof(BattleSide))) + { + BattleLineupFrame[] frames = LineupFrames.Where(frame => frame.Side == side && frame.Alpha > 0).ToArray(); + UpdateLineup(side, false, frames, battle.SceneElement); + if (side == BattleSide.Ally) + UpdateLineup(side, true, frames, battle.SceneElement); + } + } + + private void UpdateLineup(BattleSide side, bool center, IReadOnlyList frames, int sceneElement) + { + if (frames.Count == 0 && !_lineups.ContainsKey((side, center))) + return; + LineupView view = Lineup(side, center); + var vertices = new List(); + var colors = new List(); + var uv = new List(); + var indices = new List(); + var config = side == BattleSide.Ally ? _data.Layout.AllyFormationConfig : _data.Layout.EnemyFormationConfig; + var origin = new BattleMovementPoint(config.CenterGameBoxPosition.X, config.CenterGameBoxPosition.Y, config.CenterGameBoxPosition.Z); + float roll = side == BattleSide.Ally ? BattleLineupProjection.AllyRoll(config.RollRadians, sceneElement) : config.RollRadians; + uint rgb = center ? BattleLineupProjection.CenterColor(sceneElement) : 0xffffffu; + foreach (BattleLineupFrame frame in frames) + { + int offset = vertices.Count; + for (int corner = 0; corner < 4; corner++) + { + vertices.Add(BattleAnimationCatalog.UnityPosition(BattleLineupProjection.Corner(origin, config.GameBoxRadius, roll, corner, center))); + colors.Add(new Color32((byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb, frame.Alpha)); + } + uv.AddRange(new[] { new Vector2(0, 0), new Vector2(1, 0), new Vector2(1, 1), new Vector2(0, 1) }); + indices.AddRange(new[] { offset, offset + 3, offset + 1, offset + 3, offset + 2, offset + 1 }); + } + view.Mesh.Clear(); + view.Mesh.SetVertices(vertices); + view.Mesh.SetColors(colors); + view.Mesh.SetUVs(0, uv); + view.Mesh.SetTriangles(indices, 0, true); + view.Object.GetComponent().enabled = frames.Count > 0; + } + + private void ReleaseLineup(LineupView view) + { + if (view.Object != null) + View.ReleaseCompositeObject(view.Object); + if (view.Mesh != null) + Object.DestroyImmediate(view.Mesh); + if (view.Material != null) + Object.DestroyImmediate(view.Material); + } + + private void DisposeLineups() + { + foreach (LineupView view in _lineups.Values) + ReleaseLineup(view); + _lineups.Clear(); + LineupFrames = Array.Empty(); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Lineups.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Lineups.cs.meta new file mode 100644 index 00000000..7a06129d --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Lineups.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6fee6947e5994e718ce77113b4b330af diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Messages.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Messages.cs new file mode 100644 index 00000000..0e3fa1f7 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Messages.cs @@ -0,0 +1,105 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Text; + using Battle; + using Battle.Presentation; + using UnityEngine; + + public sealed partial class BattlePreview + { + private Dictionary _battleMessageLanguage; + private BattleSession _messageOwner; + private readonly BattleStageMessageProjection _messageProjection = new(); + + public void ApplyMessages(BattleSession combat) + { + if (_messageOwner != combat) + { + _messageOwner = combat; + _messageProjection.Clear(); + } + _messageProjection.Synchronize(combat.StageMessageReferences, Trail.Enabled); + } + + public string BattleMessageText(BattleStageMessageSnapshot message) + { + if (message.LanguageKey == null) + return message.Text ?? string.Empty; + if (_battleMessageLanguage == null) + { + _battleMessageLanguage = new Dictionary(StringComparer.OrdinalIgnoreCase); + string source = Encoding.GetEncoding(_data.Resources.Codepage).GetString(_data.Bytes("basedata.cpk\\datascript\\lang.txt")); + foreach (string line in source.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) + { + int separator = line.IndexOf('$'); + if (separator < 0 || line.TrimStart().StartsWith(";", StringComparison.Ordinal)) + continue; + int end = line.IndexOf('&', separator + 1); + if (end < 0) + continue; + _battleMessageLanguage[line[..separator].Trim()] = line[(separator + 1)..end].Trim(); + } + } + return _battleMessageLanguage.TryGetValue(message.LanguageKey, out string text) ? text : + throw new InvalidOperationException("Missing original battle message: " + message.LanguageKey); + } + + public static Rect BattleMessageBounds(bool pal3A, float canvasWidth) + { + // PAL3 ships a fixed x=300. PAL3A centers this same 161x57 control + // using integer ClientWidth arithmetic. Keep the PAL3 composition + // in the centered original canvas when extra viewport width exists. + float x = pal3A ? ((int)canvasWidth - 161) / 2 : 300 + (canvasWidth - 800) / 2; + return new Rect(x, 30, 161, 57); + } + + public void DrawBattleMessages(BattleSession combat, Rect viewport, Vector4 safeInsets = default) + { + if (combat == null || combat.IsModalPresentation || combat.Status != BattleSessionStatus.Running || + Event.current.type != EventType.Repaint || viewport.width < 1 || viewport.height < 1) + return; + var context = new BattleHudViewport(viewport, safeInsets); + ApplyMessages(combat); + using (new BattleHudCanvas(context)) + { + Rect bounds = BattleMessageBounds(BattleData.Variant == "PAL3A", context.CanvasSize.x); + foreach (BattleStageMessageSnapshot message in _messageProjection.Messages) + { + GUI.color = Color.white; + string background = message.Side == BattleSide.Ally ? "TricknameBack" : "TricknameBack2"; + Texture2D texture = View.GetTexture("basedata.cpk\\ui\\combat\\" + background + ".tga"); + GUI.DrawTextureWithTexCoords(bounds, texture, BattleHudCanvas.SpriteUv(texture, bounds.size), true); + DrawBattleMessageText(BattleMessageText(message), bounds); + } + } + } + + private void DrawBattleMessageText(string text, Rect bounds) + { + // UIStatic uses an eight-pixel border and UIDrawText's integer + // single-line centering. SetFont(TRUE) selects unicode20.tft. + int width = 0; + foreach (char character in text) + width += BattleNumberFont.Advance(character); + float x = bounds.x + 8 + (145 - width) / 2; + float y = bounds.y + 8 + (41 - BattleNumberFont.Size) / 2; + foreach (char character in text) + { + int advance = BattleNumberFont.Advance(character); + const float inset = .4875f / BattleNumberFont.Size; + bool ascii = advance == BattleNumberFont.Size / 2; + Rect uv = new((ascii ? .25f : 0) + inset, inset, + (ascii ? .5f : 1) - 2 * inset, 1 - 2 * inset); + GUI.DrawTextureWithTexCoords(new Rect(x, y, advance, BattleNumberFont.Size), NumberGlyph(character), uv, true); + x += advance; + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Messages.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Messages.cs.meta new file mode 100644 index 00000000..e16436ef --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Messages.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f18f1c0b42e34810930a23f727757a47 diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Numbers.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Numbers.cs new file mode 100644 index 00000000..bd668417 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Numbers.cs @@ -0,0 +1,135 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.IO; + using Battle; + using Battle.Presentation; + using UnityEngine; + + public sealed partial class BattlePreview + { + private BattleSession _numberOwner; + private BattleNumberProjection _numbers; + private BattleNumberFont _numberFont; + private readonly Dictionary _numberGlyphs = new(); + + public IReadOnlyList NumberFrames => _numbers?.Sample() ?? Array.Empty(); + + public BattleDamageNumberColorMode DamageNumberColorMode + { + get; + set; + } = BattleDamageNumberColorMode.Original; + + public void ApplyNumbers(BattleSession combat) + { + if (_numberOwner != combat) + { + _numberOwner = combat; + _numbers = new BattleNumberProjection(_data.Resources.Codepage == 950 ? "蠱" : "蛊"); + } + if (combat.Status != BattleSessionStatus.Running) + { + _numbers.Clear(); + return; + } + _numbers.Synchronize(combat.Events, combat.SimulationTick); + } + + private Texture2D NumberGlyph(char character) + { + if (_numberGlyphs.TryGetValue(character, out Texture2D texture)) + return texture; + if (_numberFont == null) + { + const string path = "basedata.cpk\\gbdata\\unicode20.tft"; + var entry = _data.Resources.Find(path) ?? throw new FileNotFoundException("Missing original battle font: " + path); + _numberFont = new BattleNumberFont(_data.Resources.Read(entry)); + } + byte[] alpha = _numberFont.GlyphAlpha(character); + var pixels = new Color32[alpha.Length]; + for (int y = 0; y < BattleNumberFont.Size; y++) + for (int x = 0; x < BattleNumberFont.Size; x++) + pixels[(BattleNumberFont.Size - 1 - y) * BattleNumberFont.Size + x] = + new Color32(255, 255, 255, alpha[y * BattleNumberFont.Size + x]); + texture = new Texture2D(BattleNumberFont.Size, BattleNumberFont.Size, TextureFormat.RGBA32, false) + { + name = "Battle number " + (int)character, + hideFlags = HideFlags.HideAndDontSave, + filterMode = FilterMode.Point, + wrapMode = TextureWrapMode.Clamp + }; + texture.SetPixels32(pixels); + texture.Apply(false, true); + _numberGlyphs.Add(character, texture); + return texture; + } + + public static Rect NumberBounds(BattleNumberFrame frame, Vector2 projected, BattleHudViewport viewport) + { + int width = 0; + foreach (char character in frame.Text) + width += BattleNumberFont.Advance(character); + return new Rect(projected.x + frame.OffsetX * viewport.Scale, + projected.y + (frame.OffsetY - BattleNumberFont.Size) * viewport.Scale, + width * viewport.Scale, BattleNumberFont.Size * viewport.Scale); + } + + public void DrawBattleNumbers(BattleSession combat, Rect viewport, Vector4 safeInsets = default) + { + if (combat == null || combat.IsModalPresentation || combat.Status != BattleSessionStatus.Running || + Event.current.type != EventType.Repaint || viewport.width < 1 || viewport.height < 1) + return; + ApplyNumbers(combat); + View.SetViewportContext(viewport); + var context = new BattleHudViewport(viewport, safeInsets); + Color previous = GUI.color; + GUI.BeginGroup(context.SafeRect); + try + { + foreach (BattleNumberFrame frame in NumberFrames) + { + if (frame.Alpha == 0 || !View.Project(BattleAnimationCatalog.UnityPosition(frame.Position), viewport, out Vector2 point)) + continue; + Rect bounds = NumberBounds(frame, point, context); + bounds.position -= context.SafeRect.position; + uint color = BattleDamageNumberColors.Resolve(frame.Color, DamageNumberColorMode); + GUI.color = new Color32((byte)(color >> 16), (byte)(color >> 8), (byte)color, frame.Alpha); + float x = bounds.x; + foreach (char character in frame.Text) + { + int advance = BattleNumberFont.Advance(character); + const float inset = .4875f / BattleNumberFont.Size; + bool ascii = advance == BattleNumberFont.Size / 2; + Rect uv = new((ascii ? .25f : 0) + inset, inset, + (ascii ? .5f : 1) - 2 * inset, 1 - 2 * inset); + GUI.DrawTextureWithTexCoords(new Rect(x, bounds.y, advance * context.Scale, bounds.height), NumberGlyph(character), uv, true); + x += advance * context.Scale; + } + } + } + finally + { + GUI.EndGroup(); + GUI.color = previous; + } + } + + private void DisposeNumbers() + { + foreach (Texture2D texture in _numberGlyphs.Values) + if (texture != null) + UnityEngine.Object.DestroyImmediate(texture); + _numberGlyphs.Clear(); + _numberFont = null; + _numbers?.Clear(); + _numberOwner = null; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Numbers.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Numbers.cs.meta new file mode 100644 index 00000000..94dbc20e --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Numbers.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 592ea5590e094eb29ca033b08c69a303 diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Results.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Results.cs new file mode 100644 index 00000000..87f37cf1 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Results.cs @@ -0,0 +1,268 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.Contract.Enums; + using Game.Rendering.Native; + using UnityEditor; + using UnityEngine; + + public sealed partial class BattlePreview : IBattleResultBodyPort + { + private readonly Dictionary _resultBodies = new(StringComparer.Ordinal); + private BattleSession _resultBattle; + private int _resultStep = -1, _musicStops; + private double _resultStart; + + public void BeginResultPresentation(BattleSession combat, BattleAnimationCatalog catalog, BattleResultPresentation result) + { + _resultBattle = combat; + _resultStart = combat.Tick * BattleSession.StepSeconds; + _resultStep = -1; + _musicStops = 0; + _resultBodies.Clear(); + Camera?.StartList(result.CameraList); + foreach (BattleResultStep award in result.Sequence.Where(step => step.Kind == BattleResultStepKind.Item)) + Audio.Play("wa006"); + bool victory = combat.Result.Winner == BattleSide.Ally && !combat.Result.Escaped; + var beforeSettlement = combat.Result.PreSettlementActors.ToDictionary(actor => actor.Id, StringComparer.Ordinal); + foreach (BattleActorSnapshot actor in result.Actors.Where(actor => actor.Side == BattleSide.Ally)) + { + ActorView view = BattleActorView(combat, actor); + // Settlement preserves actor IDs. Use the presentation snapshot + // as a fallback when the caller omits a pre-settlement actor. + BattleActorSnapshot before = beforeSettlement.GetValueOrDefault(actor.Id) ?? actor; + var state = new BattleResultBodyState(actor.Hp, actor.MaxHp, actor.Guarding, + actor.States.Any(status => status.State == BattleState.Sleep), actor.States.Any(status => status.State == BattleState.Paralysis)); + bool winAction = victory && (BattleData.Variant == "PAL3A" || before.AliveFlag); + _resultBodies.Add(actor.Id, new BattleResultRoleBody(BattleData.Variant, combat.CaptureBodyAnimation(actor.Id), + catalog.ResultBodyAnimations(view.Actor), state, winAction)); + if (winAction) + view.Object.transform.rotation = Quaternion.Euler(0, -BattleFacingRules.Initial(actor.Side), 0); + } + ApplyResultPresentation(result, false); + } + + public void PrepareResultBodyPass() + { + foreach (BattleResultRoleBody body in _resultBodies.Values) + body.PrepareStagePass(); + } + + public bool TryStartLevelUp(string actor) => _resultBodies.TryGetValue(actor, out BattleResultRoleBody body) && body.TryStartLevelUp(); + + public void ApplyResultPresentation(BattleResultPresentation result, bool advance) + { + Time = (float)(_resultStart + result.Tick * BattleSession.StepSeconds); + SetBladeFrameTime(_resultStart + result.Tick * BattleSession.StepSeconds); + Audio.SetTime(Time); + if (advance) + { + Camera?.Advance(BattleSession.StepSeconds, BattleSession.StepSeconds); + Trail.Advance(BattleSession.StepSeconds, BattleSession.StepSeconds); + foreach (var entry in _resultBodies) + { + entry.Value.Step(); + if (!_actors.TryGetValue(entry.Key, out ActorView actor)) + continue; + BattleBodyAnimationBinding binding = entry.Value.Binding; + string clip = binding.CurrentAnimation?.Clip; + if (clip == null) + continue; + if (actor.Action != clip) + SetAction(actor, clip); + actor.Renderer.SampleAnimation((float)binding.CurrentAnimationTimeSeconds); + BattleWeaponVisibility visibility = ResultWeaponVisibility(entry.Key, binding); + actor.Renderer.SetWeaponVisibility(actor.Visible && visibility.Left, actor.Visible && visibility.Right); + actor.Renderer.SampleWeaponBlades(Time, entry.Value.PlaybackRate, + entry.Value.BladeSeconds); + } + } + ApplyResultActors(result.Actors); + Audio.SetMusicGain(result.MusicGain); + if (result.MusicStopCount != _musicStops) + { + Audio.StopMusic(); + _musicStops = result.MusicStopCount; + } + if (_resultStep != result.Index && result.HasExecuted) + { + _resultStep = result.Index; + string sound = result.Current?.Kind switch + { + BattleResultStepKind.WinBanner => "wa012", + BattleResultStepKind.LoseBanner => "wa013", + BattleResultStepKind.LevelUp => "wa014", + BattleResultStepKind.SkillLearned or BattleResultStepKind.SkillImproved => "wa015", + _ => null + }; + if (sound != null) + Audio.Play(sound); + } + } + + private void ApplyResultActors(IReadOnlyList actors) + { + _shadows?.Begin(); + foreach (BattleActorSnapshot state in actors) + { + ActorView actor = BattleActorView(_resultBattle, state); + actor.Visible = actor.Action != null && !state.Escaped && _resultBattle.CoAttackActorVisible(state.Id) && + (state.ModelAliveFlag || state.Side == BattleSide.Ally && state.Hp > 0); + foreach (UnityEngine.Renderer renderer in actor.Renderers) + renderer.enabled = actor.Visible; + BattleWeaponVisibility weapons = _resultBodies.TryGetValue(state.Id, out BattleResultRoleBody body) ? + ResultWeaponVisibility(state.Id, body.Binding) : _resultBattle.WeaponVisibility(state.Id); + actor.Renderer.SetWeaponVisibility(actor.Visible && weapons.Left, actor.Visible && weapons.Right); + float blend = state.Movement?.Blend ?? (state.States.Any(status => status.State == BattleState.Invisible) ? .44f : 1f); + BattleEffectActorSnapshot effect = _resultBattle.EffectActor(state.Id); + if (effect?.HasBlend == true) + blend = effect.Blend; + actor.Renderer.SetOpacity(blend); + if (_shadows != null && GameBoxBattleShadow.IsVisible(BattleData.Variant == "PAL3A", true, state.ModelAliveFlag, + state.Side == BattleSide.Ally, state.Hp, blend)) + _shadows.Add(new GameBoxBattleShadow(actor.Object.transform.position, _shadowRadii[state.Id])); + } + _shadows?.End(); + } + + private BattleWeaponVisibility ResultWeaponVisibility(string actorId, BattleBodyAnimationBinding binding) + { + if (_resultBattle.Definitions?.Actors.TryGetValue(actorId, out BattleActorDefinition definition) != true) + return _resultBattle.WeaponVisibility(actorId); + BattleEquipmentDefinition weapon = definition.Equipment.FirstOrDefault(item => item.Slot == 0); + return BattleWeaponPresentationRules.Visible(BattleData.Variant, definition.Identity, + binding.RequestedNativeActionIndex, weapon?.WeaponType ?? 0, + _resultBattle.Pal3AForm(actorId).Kind != BattlePal3AFormKind.Human, + weapon != null && _resultBattle.WeaponDrawingEnabled(actorId)); + } + + private Texture2D ResultTexture(string name) => View.GetTexture("basedata.cpk\\ui\\combat\\result\\" + name + ".tga"); + + private void ResultSprite(string name, Rect rectangle) + { + Texture2D texture = ResultTexture(name); + GUI.DrawTextureWithTexCoords(rectangle, texture, BattleHudCanvas.SpriteUv(texture, rectangle.size), true); + } + + public void DrawResultOverlay(BattleResultPresentation result, Rect viewport, Vector4 safeInsets = default) + { + if (_resultBattle == null || result == null || result.Completed) + return; + Rect reference = new BattleHudViewport(viewport, safeInsets).ReferenceRect; + if (viewport.width < 16 || viewport.height < 16) + return; + using (new BattleHudCanvas(new BattleHudViewport(reference, default))) + { + if (result.StatisticsVisible) + DrawResultStatistics(result); + BattleResultStep step = result.HasExecuted ? result.Current : null; + if (step?.Kind is BattleResultStepKind.WinBanner or BattleResultStepKind.LoseBanner) + GUI.DrawTexture(new Rect(150, -50, 256, 512), ResultTexture(step.Kind == BattleResultStepKind.WinBanner ? "bigwin" : "biglose"), ScaleMode.StretchToFill, true); + else if (step?.Kind is BattleResultStepKind.LevelUp or BattleResultStepKind.SkillLearned or BattleResultStepKind.SkillImproved or BattleResultStepKind.Money or BattleResultStepKind.Item) + DrawResultPrompt(step); + } + // A scene transition covers the rendered viewport, including areas + // outside the fitted original UI canvas and its safe insets. + if (result.ScreenOpacity > 0) + EditorGUI.DrawRect(viewport, new Color(0, 0, 0, result.ScreenOpacity)); + } + + private void DrawResultStatistics(BattleResultPresentation presentation) + { + BattleResult result = _resultBattle.Result; + int index = 0; + foreach (BattleActorSnapshot actor in presentation.Actors.Where(actor => actor.Side == BattleSide.Ally).OrderBy(actor => actor.NativeIndex)) + { + int y = BattleResultStatistics.CardY(index, presentation.StatisticsSeconds); + using (new GUI.GroupScope(new Rect(index * 200, y, 256, 256))) + { + ResultSprite("back", new Rect(0, 0, 256, 256)); + int identity = BattleData.PlayerIdentity(actor.ActorId); + Color faceColor = GUI.color; + try + { + GUI.color *= BattleHudLayout.FaceTint(actor, false); + ResultSprite("face/" + identity, new Rect(15, -15, 64, 128)); + } + finally + { + GUI.color = faceColor; + } + ResultSprite("face/HP-GP-MP", new Rect(66, 42, 64, 67)); + DrawResultBar(new Rect(83, 46, 85, 12), actor.Hp, actor.MaxHp, "HP"); + DrawResultBar(new Rect(86, 71, 85, 12), actor.Sp, actor.MaxSp, "GP"); + DrawResultBar(new Rect(84, 97, 85, 12), actor.Mp, actor.MaxMp, "MP"); + string name = _data.Database.CombatActorInfos[actor.ActorId].Name; + GUI.Label(new Rect(0, 0, 187, 32), $"{name} {actor.Level} 级", ResultText); + BattleActorReward reward = result.Rewards.FirstOrDefault(reward => reward.Actor == actor.Id); + int exp = BattleResultStatistics.Experience(reward?.ExperienceGained ?? 0, presentation.StatisticsSeconds); + GUI.Label(new Rect(0, 211, 187, 32), exp.ToString(), ResultText); + BattleActorSnapshot before = result.PreSettlementActors.FirstOrDefault(candidate => candidate.Id == actor.Id) ?? actor; + BattleDefinitions definitions = _resultBattle.Definitions; + IReadOnlyList uses = definitions == null ? null : BattleResultStatistics.MagicUseCounts(_resultBattle.Variant, definitions, + definitions.Actors.GetValueOrDefault(actor.Id)?.Identity ?? identity, before.Skills); + foreach ((int group, float x, float row) in new[] { (0, 51f, 108f), (1, 136f, 108f), (2, 51f, 134f), (3, 136f, 134f), (4, 51f, 160f), (5, 136f, 160f) }) + GUI.Label(new Rect(x, row, 64, 32), (uses?[group] ?? 0).ToString(), ResultText); + } + index++; + } + } + + private void DrawResultBar(Rect rect, int value, int maximum, string texture) + { + ResultSprite("face/SLOT", rect); + float fraction = maximum > 0 ? Math.Clamp(value / (float)maximum, 0, 1) : 0; + if (fraction > 0) + ResultSprite("face/" + texture, BattleHudCanvas.ProgressFill(rect, fraction, true)); + BattleHudCanvas.DrawVitalNumber(rect, value, texture); + } + + private void DrawResultPrompt(BattleResultStep step) + { + string actor = step.Actor == null ? "" : _data.Database.CombatActorInfos[_resultBattle.Result.Actors.First(candidate => candidate.Id == step.Actor).ActorId].Name; + string panel = "levelup"; + string ability = _resultBattle.Definitions.Skills.TryGetValue(step.Id, out BattleAbilityDefinition skill) ? skill.Name : step.Id.ToString(); + string text = step.Kind switch + { + BattleResultStepKind.LevelUp => $"{actor}升到 {step.Value} 级", + BattleResultStepKind.SkillLearned => $"{actor}学会 {ability}", + BattleResultStepKind.SkillImproved => $"{actor} {ability} 升到 {step.Value} 级", + BattleResultStepKind.Money => $"得到 {step.Value} 文钱", + BattleResultStepKind.Item => $"得到 {_data.Database.GameItemInfos[step.Id].Name}" + (step.Value == 1 ? "" : " " + step.Value), + _ => "" + }; + Vector2 size = new(233, 64); + if (step.Kind is BattleResultStepKind.Money or BattleResultStepKind.Item) + { + panel = "getitem"; + size = new Vector2(359, 91); + } + else if (skill?.IsMagic == true) + { + panel = skill.ElementMask switch + { + 1 => "waterlvup", + 2 => "firelvup", + 4 => "windlvup", + 8 => "thunderlvup", + 16 => "earthlvup", + _ => "doublelvup" + }; + size = new Vector2(302, 75); + } + Rect bounds = new((800 - size.x) / 2, (600 - size.y) / 2, size.x, size.y); + ResultSprite("panel/" + panel, bounds); + GUI.Label(bounds, text, ResultText); + } + + private static GUIStyle ResultText => BattleHudCanvas.LabelStyle(14, Color.white, alignment: TextAnchor.MiddleCenter); + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Results.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Results.cs.meta new file mode 100644 index 00000000..5d854bf6 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Results.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 91c1d1e8d45b4fcc8637fed8fcd826f0 diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Selection.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Selection.cs new file mode 100644 index 00000000..4180ed94 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Selection.cs @@ -0,0 +1,66 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Engine.Extensions; + using UnityEngine; + + public sealed partial class BattlePreview + { + private static Bounds ActorSelectionBounds(ActorView actor) + { + var bounds = new Bounds(actor.Model.Meshes[0].GameBoxBoundsMin.ToUnityPosition(), Vector3.zero); + foreach (var mesh in actor.Model.Meshes) + { + bounds.Encapsulate(mesh.GameBoxBoundsMin.ToUnityPosition()); + bounds.Encapsulate(mesh.GameBoxBoundsMax.ToUnityPosition()); + } + return bounds; + } + + public bool TryActorSelectionPoint(string id, Rect viewport, out Vector2 point) + { + point = default; + return _actors.TryGetValue(id, out var actor) && actor.Visible && actor.Model?.Meshes.Length > 0 && + View.Project(actor.Object.transform.TransformPoint(ActorSelectionBounds(actor).center), viewport, out point); + } + + public string PickActor(Vector2 point, Rect viewport, IEnumerable candidates) + { + if (!viewport.Contains(point)) + return null; + Ray ray = View.ScreenRay(point, viewport); + float nearest = float.PositiveInfinity; + string picked = null; + foreach (string id in candidates) + { + if (!_actors.TryGetValue(id, out var actor) || !actor.Visible || actor.Model?.Meshes.Length is not > 0) + continue; + Transform transform = actor.Object.transform; + var localRay = new Ray(transform.InverseTransformPoint(ray.origin), transform.InverseTransformVector(ray.direction)); + if (!ActorSelectionBounds(actor).IntersectRay(localRay, out float distance)) + continue; + float depth = Vector3.Distance(ray.origin, transform.TransformPoint(localRay.GetPoint(distance))); + if (depth < nearest) + { + nearest = depth; + picked = id; + } + } + return picked; + } + + public void SetSelection(IReadOnlyCollection actors, double presentationSeconds) + { + float luminance = .65f + .35f * MathF.Sin((float)presentationSeconds * 7.8f); + foreach (var actor in _actors) + actor.Value.Renderer?.SetSelectionLuminance(actors.Contains(actor.Key) ? luminance : -1); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Selection.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Selection.cs.meta new file mode 100644 index 00000000..c9919595 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Selection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1792f9c8f45e47cd9cdf871f263ba687 diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Shadows.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Shadows.cs new file mode 100644 index 00000000..b6ac2231 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Shadows.cs @@ -0,0 +1,123 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.DataReader.Mv3; + using Game.Rendering.Native; + using UnityEngine; + + public sealed partial class BattlePreview + { + private readonly Dictionary _shadowRadii = new(StringComparer.Ordinal); + private GameBoxBattleShadowRenderer _shadows; + private double _bladeFrameTime; + private double? _lastBladeRenderTime; + + // A fixed-step presentation frame is stable across inspector repaints, + // captures and paused playback; rendering never consumes a gameplay step. + private void SetBladeFrameTime(double time) => _bladeFrameTime = time; + + private void InitializeShadows() + { + // Toon uses the body's ShadowCaster pass and the preview key light. + // Native blob shadows and its post-shadow material queues belong + // exclusively to the original rendering mode. + if (_scenario.ToonRendering) + return; + _shadows = new GameBoxBattleShadowRenderer(BattleData.Variant, View.GetTexture("basedata.cpk\\shadow.tga")); + RefreshShadowRadii(true); + View.Rendering += RenderShadows; + } + + private void RefreshShadowRadii(bool initial = false) + { + foreach (ActorView actor in _actors.Values) + _shadowRadii[actor.Actor.InstanceId] = GameBoxBattleShadow.CaptureRadius(initial ? InitialShadowModel(actor) : actor.Model); + } + + private Mv3File InitialShadowModel(ActorView actor) + { + // Released PAL3A Role.Init selects an already transformed body + // before Stage.Init captures its shadow bounds. + string model = BattleData.Variant != "PAL3A" ? null : + actor.Actor.ActorId == 101 && _scenario.Pal3A.NangongStartsTransformed ? "107" : + actor.Actor.ActorId == 103 && _scenario.Pal3A.PengxuStartsTransformed ? "106" : null; + if (model == null) + return actor.Model; + BattleParticipant participant = actor.Actor.Copy(); + participant.Model = model; + string path = _data.ActionPath(participant, _data.IdleAction(participant)); + return ReadActorModel(path); + } + + private void RefreshShadowsForActorReplacement(ActorView previous, ActorView candidate) + { + // Published NewMonster reinitializes every slot. PAL3A form changes + // only replace the body and retain the existing shadow radius. + if (_shadows != null && (previous == null || previous.Generation != candidate.Generation)) + RefreshShadowRadii(); + } + + private void SampleShadows() + { + if (_shadows == null) + return; + _shadows.Begin(); + foreach (ActorView actor in _actors.Values) + _shadows.Add(new GameBoxBattleShadow(actor.Object.transform.position, _shadowRadii[actor.Actor.InstanceId])); + _shadows.End(); + } + + private void ApplyShadows(BattleSession combat) + { + if (_shadows == null) + return; + _shadows.Begin(); + foreach (BattleActorSnapshot actor in combat.Actors) + { + float blend = actor.Movement?.Blend ?? (actor.States.Any(status => status.State == BattleState.Invisible) ? .44f : 1f); + BattleEffectActorSnapshot effect = combat.EffectActor(actor.Id); + if (effect?.HasBlend == true) + blend = effect.Blend; + if (GameBoxBattleShadow.IsVisible(BattleData.Variant == "PAL3A", true, actor.ModelAliveFlag, + actor.Side == BattleSide.Ally, actor.Hp, blend)) + _shadows.Add(new GameBoxBattleShadow(BattleAnimationCatalog.UnityPosition(actor.Position), _shadowRadii[actor.Id])); + } + _shadows.End(); + } + + private static void SetShadowRenderOrder(GameObject root, int order) + { + GameBoxBattleRenderPhase.Apply(root, order); + } + + private void RenderShadows(Camera camera) + { + bool pal3A = BattleData.Variant == "PAL3A"; + View.SetEnvironmentRenderOrder(GameBoxBattleRenderOrder.BeforeShadows); + foreach (ActorView actor in _actors.Values) + SetShadowRenderOrder(actor.Object, GameBoxBattleRenderOrder.Actor(pal3A, actor.Actor.Side == BattleSide.Ally, actor.Actor.ActorId)); + foreach (var pair in _thrownWeapons) + if (_actors.TryGetValue(pair.Key, out ActorView actor)) + SetShadowRenderOrder(pair.Value.Object, GameBoxBattleRenderOrder.Actor(pal3A, actor.Actor.Side == BattleSide.Ally, actor.Actor.ActorId)); + foreach (GameObject corpse in _corpses.Values) + SetShadowRenderOrder(corpse, GameBoxBattleRenderOrder.BeforeShadows); + _shadows?.Render(camera, View.Root.layer); + } + + private void DisposeShadows() + { + if (View != null) + View.Rendering -= RenderShadows; + _shadows?.Dispose(); + _shadows = null; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Shadows.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Shadows.cs.meta new file mode 100644 index 00000000..6e3d21c0 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.Shadows.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e8f9fb29c85d41d6a1b416db0440940a diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SpiritWheel.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SpiritWheel.cs new file mode 100644 index 00000000..fd585f73 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SpiritWheel.cs @@ -0,0 +1,103 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using Battle; + using UnityEngine; + + public sealed partial class BattlePreview + { + // Editor layout uses a stable 800x600 canvas. These released button + // bounds retain the original wheel's core/UI element ordering. Water's + // animated top is fixed at 28 for this authoring view. + public static BattleSpiritRect SpiritWheelTarget(int coreElement) => coreElement switch + { + 0 => new BattleSpiritRect(722, 48, 750, 93), + 1 => new BattleSpiritRect(732, 22, 764, 71), + 2 => new BattleSpiritRect(753, 54, 799, 86), + 3 => new BattleSpiritRect(742, 32, 788, 78), + 4 => new BattleSpiritRect(755, 72, 802, 101), + _ => throw new ArgumentOutOfRangeException(nameof(coreElement)) + }; + + private Texture2D SpiritTexture(int coreElement) + { + int ui = coreElement switch + { + 2 => 3, + 3 => 2, + _ => coreElement + }; + return View.GetTexture($"basedata.cpk\\ui\\combat\\control\\ImbibeNimbus{ui}.tga"); + } + + public void DrawBattleOverlay(BattleSession combat, Rect viewport, Vector4 safeInsets = default, bool wheelControls = true, string focusedControl = null) + { + if (combat.Definitions.Variant != "PAL3A" || combat.IsModalPresentation || combat.Status != BattleSessionStatus.Running) + return; + var context = new BattleHudViewport(viewport, safeInsets); + Rect CanvasRect(float x, float y, float width, float height) + { + Vector2 center = context.NativeToViewport(new Vector2(x + width / 2, y + height / 2)); + Vector2 size = new(width * context.Scale, height * context.Scale); + return new Rect(center - size / 2, size); + } + void Sprite(string name, float x, float y, float width, float height) + { + Texture2D texture = View.GetTexture("basedata.cpk\\ui\\combat\\control\\" + name + ".tga"); + GUI.DrawTextureWithTexCoords(CanvasRect(x, y, width, height), texture, + BattleHudCanvas.SpriteUv(texture, new Vector2(width, height)), true); + } + // Released UI 0x50b63f / 0x513941: a 90x140 padded backdrop, + // followed by five cropped pieces. Charge tiers use unwtN0..2; + // the full tier uses wtN0. Native core order swaps wind/thunder. + Sprite("wll", 710, 20, 90, 140); + if (wheelControls) + { + for (int element = 0; element < 5; element++) + { + BattleSpiritRect target = SpiritWheelTarget(element); + int ui = element switch + { + 2 => 3, + 3 => 2, + _ => element + }; + int tier = combat.Pal3AState.SpiritWheel.Charges[element] / 3; + string image = (tier < 3 ? "unwt" : "wt") + (4 - ui) + (tier < 3 ? tier : 0); + int skill = element switch + { + 2 => 267, + 3 => 266, + _ => 264 + element + }; + Color previous = GUI.color; + try + { + if (focusedControl == "wheel:" + skill) + { + float pulse = .65f + .35f * MathF.Sin((float)UnityEditor.EditorApplication.timeSinceStartup * 7.8f); + GUI.color *= new Color(pulse, pulse, pulse, 1); + } + Sprite(image, target.Left, target.Top, target.Right - target.Left, target.Bottom - target.Top); + } + finally + { + GUI.color = previous; + } + } + Sprite("unbs", 739, 28, 45, 37); + } + foreach (BattleSpiritOrbSnapshot orb in combat.SpiritOrbs) + { + Vector2 point = context.SpiritOrbPoint(orb, View.ReferenceProjectionScale(viewport)); + float size = 32 * context.Scale; + GUI.DrawTexture(new Rect(point.x - size / 2, point.y - size / 2, size, size), SpiritTexture(orb.Element), ScaleMode.ScaleToFit, true); + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SpiritWheel.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SpiritWheel.cs.meta new file mode 100644 index 00000000..04ccb82c --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SpiritWheel.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7d013286a71c435ea31b1eacf445e777 diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SwordSparks.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SwordSparks.cs new file mode 100644 index 00000000..2ca77fd2 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SwordSparks.cs @@ -0,0 +1,92 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Battle.Presentation; + using UnityEngine; + using UnityEngine.Rendering; + using Object = UnityEngine.Object; + + public sealed partial class BattlePreview + { + private BattleSession _swordSparkOwner; + private BattleSwordSparkProjection _swordSparks; + private long _swordSparkTick; + private Material _swordSparkMaterial; + + public IReadOnlyList SwordSparkFrames => _swordSparks?.Frames ?? Array.Empty(); + + private void ApplySwordSparks(BattleSession battle) + { + if (battle.Definitions.Variant != "PAL3" || battle.Status != BattleSessionStatus.Running) + { + _swordSparks?.Clear(); + return; + } + if (_swordSparkOwner != battle || battle.SimulationTick < _swordSparkTick) + { + _swordSparkOwner = battle; + _swordSparks = new BattleSwordSparkProjection(_scenario.Seed); + _swordSparkTick = 0; + } + long elapsed = battle.SimulationTick - _swordSparkTick; + _swordSparkTick = battle.SimulationTick; + if (elapsed == 0) + return; + BattleActorSnapshot actor = battle.Actors.FirstOrDefault(actor => actor.Side == BattleSide.Ally && + actor.NativeIndex == 0 && battle.Definitions.Actors[actor.Id].Identity == 0); + bool visible = actor?.Alive == true && !battle.IsModalPresentation; + _swordSparks.Advance(elapsed * BattleSession.StepSeconds, visible, actor?.MagicSword?.Energy ?? 0); + } + + public void DrawSwordSparks(Rect viewport, Vector4 safeInsets = default) + { + if (_swordSparkOwner?.Status != BattleSessionStatus.Running || _swordSparkOwner.IsModalPresentation || + Event.current.type != EventType.Repaint || viewport.width < 1 || viewport.height < 1) + return; + IReadOnlyList frames = SwordSparkFrames; + if (frames.Count == 0) + return; + if (_swordSparkMaterial == null) + { + Shader shader = Shader.Find("Pal3/Effect") ?? throw new InvalidOperationException("The original effect shader is missing."); + _swordSparkMaterial = new Material(shader) + { + name = "Original magic sword HUD stars", + hideFlags = HideFlags.HideAndDontSave + }; + _swordSparkMaterial.SetInt("_SrcBlend", (int)BlendMode.SrcAlpha); + _swordSparkMaterial.SetInt("_DstBlend", (int)BlendMode.One); + _swordSparkMaterial.SetInt("_ZTest", (int)CompareFunction.Always); + _swordSparkMaterial.SetInt("_Cull", (int)CullMode.Off); + } + Texture2D texture = View.GetTexture("basedata.cpk\\effect\\flareBlue3.bmp"); + var context = new BattleHudViewport(viewport, safeInsets); + using (new BattleHudCanvas(context)) + { + float offsetY = context.StateCard(0).y - BattleHudLayout.StateCard(0).y; + foreach (BattleSwordSparkFrame frame in frames) + Graphics.DrawTexture(new Rect(frame.X, frame.Y + offsetY, frame.Size, frame.Size), texture, + new Rect(0, 0, 1, 1), 0, 0, 0, 0, new Color32(255, 255, 255, frame.Alpha), _swordSparkMaterial); + } + } + + private void DisposeSwordSparks() + { + if (_swordSparkMaterial != null) + Object.DestroyImmediate(_swordSparkMaterial); + _swordSparkMaterial = null; + _swordSparks?.Clear(); + _swordSparks = null; + _swordSparkOwner = null; + _swordSparkTick = 0; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SwordSparks.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SwordSparks.cs.meta new file mode 100644 index 00000000..02c05c8b --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.SwordSparks.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 52ce8f84475944db8bc38acb3fb1e6bf diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.ThrownWeapons.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.ThrownWeapons.cs new file mode 100644 index 00000000..8a639c95 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.ThrownWeapons.cs @@ -0,0 +1,137 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.DataReader.Pol; + using Game.Rendering.Renderer; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed partial class BattlePreview + { + private sealed class ThrownWeaponView + { + internal int Item; + internal GameObject Object; + internal WeaponBlade Blade; + internal double Clock; + internal bool Active; +#if PAL3 + internal bool HasNativeFlush; +#endif + } + + private readonly Dictionary _thrownWeapons = new(StringComparer.Ordinal); + private Material _thrownBladeMaterial; + + // Native stack: Translate, RotateY, RotateX, RotateZ. Mirroring X at the + // rendering boundary reverses Y and Z rotation, retaining the X angle. + public static Quaternion ThrownWeaponRotation(BattleMovementPoint degrees) => + Quaternion.AngleAxis(-degrees.Y, Vector3.up) * Quaternion.AngleAxis(degrees.X, Vector3.right) * + Quaternion.AngleAxis(-degrees.Z, Vector3.forward); + + private void ApplyThrownWeapons(BattleSession combat) + { + var retained = new HashSet(StringComparer.Ordinal); + foreach (BattleThrownWeaponSnapshot projectile in combat.ThrownWeapons) + { + retained.Add(projectile.Actor); + BattleActorSnapshot source = combat.Actors.First(actor => actor.Id == projectile.Actor); + BattleParticipant participant = combat.CaptureParticipant(projectile.Actor); + int weapon = participant.Equipment[0]; + if (_thrownWeapons.TryGetValue(projectile.Actor, out ThrownWeaponView view) && view.Item != weapon) + { + ReleaseThrownWeapon(view); + _thrownWeapons.Remove(projectile.Actor); + view = null; + } + if (view == null) + { + var item = _data.Database.GameItemInfos[weapon]; + string path = $"basedata.cpk\\item\\{item.ModelName}\\{item.ModelName}.pol"; + PolFile model = _data.Read(path, new PolFileReader()); + var candidate = new ThrownWeaponView + { + Item = weapon, + Object = View.CreateObject("Thrown weapon " + projectile.Actor), + Blade = new WeaponBlade(model.TagNodes), + Clock = source.NativePresentationTick * BattleSession.StepSeconds + }; + try + { + View.AddPolyModel(candidate.Object, path, model, item.ModelName + item.ImageId + ".tga"); + } + catch + { + ReleaseThrownWeapon(candidate); + throw; + } + _thrownWeapons.Add(projectile.Actor, view = candidate); + } + view.Object.transform.SetPositionAndRotation(BattleAnimationCatalog.UnityPosition(projectile.Position), + ThrownWeaponRotation(projectile.RotationDegrees)); + foreach (UnityEngine.Renderer renderer in view.Object.GetComponentsInChildren(true)) + renderer.enabled = projectile.Active; + double clock = source.NativePresentationTick * BattleSession.StepSeconds; + // The secondary POL retains BladeRecord's default time scale 1. + view.Active = projectile.Active; +#if PAL3A + view.Blade.Sample(view.Object.transform, projectile.Active, (float)Math.Max(0, clock - view.Clock), 1, .12f); +#endif + view.Clock = clock; + } + foreach (string id in _thrownWeapons.Keys.Where(id => !retained.Contains(id)).ToArray()) + { + ReleaseThrownWeapon(_thrownWeapons[id]); + _thrownWeapons.Remove(id); + } + } + + private void RenderThrownWeaponBlades(Camera camera, float delta, bool newFrame) + { + if (_thrownWeapons.Count == 0) + return; + _thrownBladeMaterial ??= WeaponBlade.CreateMaterial(); + foreach (ThrownWeaponView view in _thrownWeapons.Values) + { +#if PAL3 + bool update = newFrame || !view.HasNativeFlush; + if (update) + view.Blade.SamplePose(view.Object.transform, view.Active, .12f, rebuildMesh: false); + for (int flush = 0; flush < 2; flush++) + { + if (update) + view.Blade.Advance(delta, 1, rebuildMesh: false); + view.Blade.RenderFlush(camera, _thrownBladeMaterial, view.Object.layer, flush, update); + } + view.HasNativeFlush = true; +#else + view.Blade.Render(camera, _thrownBladeMaterial, view.Object.layer); +#endif + } + } + + private void ReleaseThrownWeapon(ThrownWeaponView view) + { + view.Blade.Dispose(); + View.ReleaseCompositeObject(view.Object); + } + + private void DisposeThrownWeapons() + { + foreach (ThrownWeaponView view in _thrownWeapons.Values) + ReleaseThrownWeapon(view); + _thrownWeapons.Clear(); + if (_thrownBladeMaterial != null) + Object.DestroyImmediate(_thrownBladeMaterial); + _thrownBladeMaterial = null; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.ThrownWeapons.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.ThrownWeapons.cs.meta new file mode 100644 index 00000000..7bde1871 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.ThrownWeapons.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 53c4c03b80234f0b944289227e04c0fb diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.cs new file mode 100644 index 00000000..c404b128 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.cs @@ -0,0 +1,567 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using Core.Contract.Enums; + using Core.DataReader.Ini; + using Core.DataReader.Lgt; + using Core.DataReader.Mv3; + using Core.DataReader.Pol; + using Engine.Extensions; + using Game.Rendering.Native; + using Game.Rendering.Renderer; + using ResourceBrowser; + using UnityEngine; + + // Editor-only choreography. It samples geometry and never dispatches gameplay callbacks. + public sealed partial class BattlePreview : IDisposable + { + private sealed class ActorView + { + public BattleParticipant Actor; + public string SequenceModel; + public Renderer[] Renderers; + public BattleSlot DisplaySlot; + public int Generation; + public int FormGeneration; + public bool Visible = true; + public GameObject Object; + public Mv3ModelRenderer Renderer; + public Mv3File Model; + public string Action; + public Vector3 Home; + public Quaternion Rotation; + public float Duration; + public bool Loop = true; + } + + private readonly List _musicDiagnostics = new(); + private readonly List _diagnostics = new(); + private readonly BattleData _data; + private bool _disposed; + private readonly BattleScenario _scenario; + private readonly GameBoxNativeLighting _nativeLighting; + private BattleCameraProjection? _battleProjection; + private readonly Dictionary _actors = new(StringComparer.Ordinal); + private readonly Dictionary _models = new(StringComparer.OrdinalIgnoreCase); + private string _attacker; + private string _environmentScene; + private Vector3 _approach; + private float _travel; + private float _attackDuration; + private string _attackAction, _moveAction; + + public ResourceModelPreview View + { + get; + } + + public BattleEffectDirector Effects + { + get; + } + + public BattleAudioPreview Audio + { + get; + } + + public BattleTrailPreview Trail + { + get; + } + + public BattleCameraDirector Camera + { + get; private set; + } + + public float Time + { + get; private set; + } + + public float Duration { get; private set; } = 5; + + public IReadOnlyList Diagnostics => _diagnostics.Concat(Audio.Diagnostics).Concat(Effects.MovieDiagnostics) + .Concat(Effects.MissingBattleTextures.Select(texture => "缺少战斗贴图:" + texture)).Distinct().ToArray(); + + public BattlePreview(BattleData data, BattleSetup setup) + { + _data = data; + _scenario = setup.CreateInstance(); + try + { + _nativeLighting = _scenario.ToonRendering ? null : new GameBoxNativeLighting(BattleData.Variant); + View = new ResourceModelPreview(data.Resources, _scenario.ToonRendering, _nativeLighting) { LimitToDisplayRefreshRate = true }; + Trail = new BattleTrailPreview(); + View.FrameEffect = Trail; + Audio = new BattleAudioPreview(data.Resources, View.Root.scene) { PlaybackEnabled = false }; + Effects = new BattleEffectDirector(data, View, Audio); + Effects.SpiritProjector = (_, world) => _battleProjection?.Project(world) + ?? throw new InvalidOperationException("Spirit capture requires a published battle camera."); + Effects.SoundRequested += Audio.Play; + Effects.MovementSoundRequested += Audio.PlayMovement; + Effects.MovementSoundStopped += Audio.StopMovement; + Effects.BodySoundsStopped += Audio.StopBodySounds; + View.Rendering += Effects.Render; + View.Rendering += RenderWeaponBlades; + View.Rendering += RenderWeaponSparks; + View.PostComposite += RenderHitFeedback; + Audio.SetMusic(BattleMusicResolver.Resolve(data, _scenario, _musicDiagnostics)); + LoadEnvironment(_scenario.Scene); + foreach (BattleParticipant actor in _scenario.Participants) + { + var view = new ActorView { Actor = actor, SequenceModel = data.Model(actor), DisplaySlot = actor.Slot, Object = View.CreateObject(actor.InstanceId), Home = data.Position(actor, _scenario.SceneElement) }; + bool forward = actor.Side == BattleSide.Ally ? _scenario.Encounter != BattleEncounter.EnemyAmbush : _scenario.Encounter == BattleEncounter.AllyAmbush; + view.Rotation = Quaternion.Euler(0, forward ? -45 : 135, 0); + _actors.Add(actor.InstanceId, view); + SetAction(view, data.IdleAction(actor)); + } + InitializeShadows(); + BattleCamera camera = _scenario.Camera; + if (camera.Override) + View.SetCamera(ToVector(camera.Position), ToVector(camera.Target), camera.FieldOfView); + else if (data.Cameras.DefaultCamConfigs.Length > 0) + { + CombatCameraConfig original = data.Cameras.DefaultCamConfigs[0]; + ApplyCameraPose(new BattleCameraPose(new BattleMovementPoint(original.GameBoxPositionX, + original.GameBoxPositionY, original.GameBoxPositionZ), original.Yaw, original.Pitch, original.Roll), 50, false); + } + Sample(0); + CollectDependencies(); + } + catch + { + Dispose(); + throw; + } + } + + private void LoadEnvironment(string scene) + { + BattleSceneAppearance appearance = _scenario.ToonRendering ? BattleToonLightingCatalog.ResolveScene(BattleData.Variant, scene) : null; + string path = FileConstants.CombatSceneFolderVirtualPath + scene + "\\" + scene; + string geometry = path + ".pol"; + string lights = path + ".lgt"; + PolFile model = _data.Read(geometry, new PolFileReader()); + LgtFile lightData = _nativeLighting != null && _data.Resources.Find(lights) != null ? _data.Read(lights, new LgtFileReader()) : null; + // Both published loaders create a CVD object but never attach + // it during combat rendering. Render the verified scene geometry. + Func surfaces = appearance?.ResolveSurfaces(model); + View.ReplaceEnvironment(_data.Resources.Find(geometry), model, surfaces); + // Bindings select lights during Apply, after this transaction. A + // failed geometry replacement must keep the previous scene's lights. + _nativeLighting?.SetLights(lightData); + if (appearance != null) + View.ConfigureToonLighting(appearance.Lighting); + _environmentScene = scene; + } + + internal string ActorModel(string id) => _actors.TryGetValue(id, out ActorView view) ? view.SequenceModel : null; + + private ActorView BattleActorView(BattleSession combat, BattleActorSnapshot state) + { + int generation = combat.MonsterGeneration(state.Id); + BattlePal3AFormSnapshot form = combat.Pal3AForm(state.Id); + _actors.TryGetValue(state.Id, out ActorView previous); + if (previous != null && previous.Renderer != null && previous.Renderers != null && + previous.Generation == generation && previous.FormGeneration == form.Generation) + return previous; + BattleParticipant participant = combat.CaptureParticipant(state.Id); + string sequenceModel = _data.Model(participant); + if (!string.IsNullOrEmpty(form.Model)) + participant.Model = form.Model; + var candidate = new ActorView + { + Actor = participant, + SequenceModel = sequenceModel, + DisplaySlot = state.Slot, + Generation = generation, + FormGeneration = form.Generation, + Object = View.CreateObject(state.Id), + Home = BattleAnimationCatalog.UnityPosition(state.Home), + Rotation = Quaternion.Euler(0, -state.FacingDegrees, 0) + }; + try + { + SetAction(candidate, _data.IdleAction(participant)); + candidate.Object.transform.SetPositionAndRotation(BattleAnimationCatalog.UnityPosition(state.Position), candidate.Rotation); + } + catch + { + View.ReleaseCompositeObject(candidate.Object); + throw; + } + _actors[state.Id] = candidate; + RefreshShadowsForActorReplacement(previous, candidate); + if (previous != null) + View.ReleaseCompositeObject(previous.Object); + return candidate; + } + + public void BindBattle(BattleSession combat) => BindBattle(combat, null); + + public void BindBattle(BattleSession combat, BattleAnimationCatalog catalog) + { + if (Camera != null) + throw new InvalidOperationException("This preview already owns a battle camera."); + View.GetCamera(out Vector3 position, out Vector3 target, out float fieldOfView); + BattleMovementPoint Native(Vector3 value) => new(-value.x * UnityPrimitivesConvertor.GameBoxUnitToUnityUnit, + value.y * UnityPrimitivesConvertor.GameBoxUnitToUnityUnit, value.z * UnityPrimitivesConvertor.GameBoxUnitToUnityUnit); + BattleMovementPoint direction = Native((target - position).normalized); + var initial = new BattleCameraPose(Native(position), MathF.Atan2(direction.X, -direction.Z), + MathF.Atan2(direction.Y, MathF.Sqrt(direction.X * direction.X + direction.Z * direction.Z)), 0); + if (!_scenario.Camera.Override && _data.Cameras.DefaultCamConfigs.Length > 0) + { + CombatCameraConfig original = _data.Cameras.DefaultCamConfigs[0]; + initial = new BattleCameraPose(new BattleMovementPoint(original.GameBoxPositionX, original.GameBoxPositionY, + original.GameBoxPositionZ), original.Yaw, original.Pitch, original.Roll); + } + BattleMovementPoint TracePosition(int index) + { + if (index == -1) + { + var center = _data.Layout.AllyFormationConfig.CenterGameBoxPosition; + return new BattleMovementPoint(center.X, center.Y, center.Z); + } + string actor = combat.EffectActorId(index); + return actor == null ? default : combat.EffectActor(actor).Position; + } + // Gameplay projection always uses its fixed reference canvas. The + // editor viewport must not change capture physics or list startup. + float horizontalFieldOfView = _scenario.Camera.Override + ? UnityEngine.Camera.VerticalToHorizontalFieldOfView(_scenario.Camera.FieldOfView, 4f / 3) : 50; + Camera = new BattleCameraDirector(_data, initial, TracePosition, ApplyCameraPose, horizontalFieldOfView); + Effects.Bind(combat, Camera); + Effects.StageAdvanced += Camera.Advance; + Effects.StageAdvanced += Trail.Advance; + if (catalog != null) + Effects.StageAdvanced += (_, _) => ApplyBattle(combat, catalog); + if (!_scenario.Camera.Override) + Camera.StartList(_scenario.Encounter == BattleEncounter.EnemyAmbush && _scenario.MotionBlur ? 20 : 0); + } + + private void ApplyCameraPose(BattleCameraPose pose, float fieldOfView, bool trail) + { + _battleProjection = new BattleCameraProjection(pose, fieldOfView); + Trail.Enabled = trail && _scenario.MotionBlur; + Vector3 Direction(BattleMovementPoint point) => new(-point.X, point.Y, point.Z); + // An authored camera stores a Unity vertical angle. Keep that + // framing through binding and idle/quake updates; a successfully + // started native list takes over with GameBox horizontal angles. + if (_scenario.Camera.Override && Camera?.HasStartedList != true) + View.SetCameraOrientation(BattleAnimationCatalog.UnityPosition(pose.Position), Direction(pose.Forward), Direction(pose.Up), _scenario.Camera.FieldOfView); + else + View.SetHorizontalCameraOrientation(BattleAnimationCatalog.UnityPosition(pose.Position), Direction(pose.Forward), Direction(pose.Up), fieldOfView); + } + + private void RenderWeaponBlades(Camera camera) + { + bool published = BattleData.Variant == "PAL3"; + bool newFrame = _lastBladeRenderTime != _bladeFrameTime; + float delta = !_lastBladeRenderTime.HasValue || _bladeFrameTime < _lastBladeRenderTime.Value ? (float)BattleSession.StepSeconds : + (float)(_bladeFrameTime - _lastBladeRenderTime.Value); + foreach (ActorView actor in _actors.Values) + if (published) + actor.Renderer.RenderPublishedWeaponBlades(camera, delta, newFrame, actor.Visible); + else if (actor.Visible) + actor.Renderer.RenderWeaponBlades(camera); + RenderThrownWeaponBlades(camera, delta, newFrame); + _lastBladeRenderTime = _bladeFrameTime; + } + + private Mv3File ReadActorModel(string path) + { + if (!_models.TryGetValue(path, out Mv3File model)) + _models[path] = model = _data.Read(path, new Mv3FileReader(includeNativeNormals: _nativeLighting != null)); + return model; + } + + private void SetAction(ActorView actor, string action) + { + string path = _data.ActionPath(actor.Actor, action); + Mv3File model = ReadActorModel(path); + string weaponPath = null; + string weaponTexture = null; + PolFile weapon = null; + if (model.TagNodes.Length > 0 && actor.Actor.Equipment is { Length: > 0 } && actor.Actor.Equipment[0] != 0) + { + var item = _data.Database.GameItemInfos[actor.Actor.Equipment[0]]; + weaponPath = FileConstants.GetWeaponModelFileVirtualPath(item.ModelName); + weaponTexture = item.ModelName + item.ImageId + ".tga"; + weapon = _data.Read(weaponPath, new PolFileReader()); + } + actor.Renderer = View.SetVertexModel(actor.Object, path, model, weaponPath, weapon, preserveWeaponPresentation: true, weaponTexture: weaponTexture); + actor.Renderers = actor.Object.GetComponentsInChildren(true); + actor.Renderer.UseRenderBladeClock = BattleData.Variant == "PAL3"; + actor.Model = model; + actor.Action = action; + actor.Duration = (float)model.TotalGameBoxTicks / UnityPrimitivesConvertor.GameBoxTicksPerSecond; + } + + public void PlayAction(string instanceId, string action) + { + ResetAuthoringActors(); + ActorView actor = _actors[instanceId]; + SetAction(actor, action); + actor.Loop = false; + Duration = Mathf.Max(0.02f, actor.Duration); + Sample(0); + CollectDependencies(); + } + + public void PlayAttack(string attacker, string target) + { + if (!_actors.TryGetValue(attacker, out ActorView source) || !_actors.TryGetValue(target, out ActorView destination) || source.Actor.Side == destination.Actor.Side) + throw new InvalidOperationException("Select an attacker and an opposing target."); + Vector3 direction = (source.Home - destination.Home).normalized; + if (direction.sqrMagnitude < 0.01f) + throw new InvalidOperationException("Attack preview needs distinct source and target positions."); + string moveAction = ActorConstants.ActionToNameMap[_data.Database.CombatActorInfos[source.Actor.ActorId].Type == CombatActorType.MainActor ? ActorActionType.AttackMove : ActorActionType.NpcRun]; + string attackAction = _data.AttackAction(source.Actor); + ReadActorModel(_data.ActionPath(source.Actor, moveAction)); + ReadActorModel(_data.ActionPath(source.Actor, attackAction)); + + ResetAuthoringActors(); + SetAction(source, attackAction); + source.Loop = false; + _attackAction = source.Action; + _attackDuration = source.Duration; + _moveAction = moveAction; + Vector3 sourceSize = source.Renderer.GetMeshBounds().size; + Vector3 targetSize = destination.Renderer.GetMeshBounds().size; + float separation = Mathf.Max(0.1f, (Mathf.Max(sourceSize.x, sourceSize.z) + Mathf.Max(targetSize.x, targetSize.z)) / 2); + _approach = destination.Home + direction * separation; + _travel = Vector3.Distance(source.Home, _approach) / 12; + _attacker = attacker; + Duration = _travel * 2 + _attackDuration; + Sample(0); + CollectDependencies(); + } + + public void Reset() + { + ResetAuthoringActors(); + Sample(0); + } + + private void ResetAuthoringActors() + { + _attacker = null; + ResetAuthoringWeaponBlades(); + Duration = 5; + foreach (ActorView actor in _actors.Values) + { + string idle = _data.IdleAction(actor.Actor); + if (actor.Action != idle) + SetAction(actor, idle); + actor.Loop = true; + } + } + + private void ResetAuthoringWeaponBlades() + { + _lastBladeRenderTime = null; + foreach (ActorView actor in _actors.Values) + actor.Renderer.ResetWeaponPresentation(); + } + + public void Sample(float time) + { + if (!float.IsFinite(time)) + throw new ArgumentOutOfRangeException(nameof(time)); + float next = Mathf.Clamp(time, 0, Duration); + if (next < Time) + ResetAuthoringWeaponBlades(); + Time = next; + Audio.SetTime(Time); + SetBladeFrameTime(Time); + foreach (ActorView actor in _actors.Values) + { + actor.Object.transform.SetPositionAndRotation(actor.Home, actor.Rotation); + float local = Time; + if (actor.Actor.InstanceId == _attacker) + { + bool returning = Time > _travel + _attackDuration; + bool finished = Time >= Duration; + string action = finished ? _data.IdleAction(actor.Actor) : Time < _travel || returning ? _moveAction : _attackAction; + if (actor.Action != action) + SetAction(actor, action); + if (Time < _travel) + actor.Object.transform.position = Vector3.Lerp(actor.Home, _approach, _travel > 0 ? Time / _travel : 1); + else if (returning) + actor.Object.transform.position = Vector3.Lerp(_approach, actor.Home, _travel > 0 ? (Time - _travel - _attackDuration) / _travel : 1); + else + actor.Object.transform.position = _approach; + if (!finished) + actor.Object.transform.LookAt(returning ? actor.Home : _approach + (_approach - actor.Home).normalized); + local = Time < _travel ? Time : returning ? Time - _travel - _attackDuration : Time - _travel; + local = Time < _travel || returning ? actor.Duration > 0 ? local % actor.Duration : 0 : Mathf.Clamp(local, 0, _attackDuration); + if (finished) + { + actor.Object.transform.rotation = actor.Rotation; + local = 0; + } + } + actor.Renderer.SampleAnimation(actor.Loop && actor.Duration > 0 ? local % actor.Duration : Mathf.Clamp(local, 0, actor.Duration)); + actor.Renderer.SampleWeaponBlades(Time, 1, .12f); + } + SampleShadows(); + } + + public void ApplyBattle(BattleSession combat, BattleAnimationCatalog catalog) + { + Audio.SetTime(combat.Tick * BattleSession.StepSeconds); + Time = (float)(combat.Tick * BattleSession.StepSeconds); + SetBladeFrameTime(combat.Tick * BattleSession.StepSeconds); + Trail.Suspended = combat.IsModalPresentation; + if (_environmentScene != combat.ActiveScene) + LoadEnvironment(combat.ActiveScene); + foreach (BattleActorSnapshot state in combat.Actors) + { + ActorView actor = BattleActorView(combat, state); + actor.DisplaySlot = state.Slot; + BattleEffectActorSnapshot effectActor = combat.EffectActor(state.Id); + // The body binding owns the actual animation, including poses + // such as GuardHurt which have no generic catalog fallback. + string clip = state.NativeAnimationClip ?? effectActor?.Clip ?? catalog.Clip(state, combat.Definitions); + if (state.Side == BattleSide.Enemy && !state.ModelAliveFlag) + clip = null; + actor.Visible = clip != null && !state.Escaped && combat.CoAttackActorVisible(state.Id); + if (clip == null) + { + foreach (Renderer renderer in actor.Renderers) + renderer.enabled = false; +#if PAL3 + actor.Renderer.SampleWeaponBlades(state.NativePresentationTick * BattleSession.StepSeconds, + state.NativePlaybackRate, state.WeaponTrailSeconds); +#endif + continue; // Original monsters disappear; retained blade records still age. + } + if (actor.Action != clip) + SetAction(actor, clip); + foreach (Renderer renderer in actor.Renderers) + renderer.enabled = actor.Visible; + actor.Object.transform.SetPositionAndRotation(BattleAnimationCatalog.UnityPosition(state.Position), + Quaternion.Euler(0, -state.FacingDegrees, 0)); + float opacity = state.Movement?.Blend ?? (state.States.Any(status => status.State == BattleState.Invisible) ? 0.44f : 1f); + if (effectActor?.HasBlend == true) + opacity = effectActor.Blend; + actor.Renderer.SetOpacity(opacity); + BattleWeaponVisibility weapons = combat.WeaponVisibility(state.Id); + actor.Renderer.SetWeaponVisibility(actor.Visible && weapons.Left, actor.Visible && weapons.Right); + float local = (float)(state.PoseTick * BattleSession.StepSeconds * catalog.PlaybackRate(state)); + if (effectActor?.Clip != null) + local = (float)(effectActor.AnimationTick * BattleSession.StepSeconds * catalog.PlaybackRate(state.Id, BattlePose.UsingSkill)); + bool loop = state.Pose is BattlePose.Idle or BattlePose.Guard or BattlePose.Moving or BattlePose.Returning or BattlePose.Casting or BattlePose.Fleeing || state.Pose == BattlePose.Repositioning && state.Movement?.Plan.Kind is BattleMovementKind.Run or BattleMovementKind.Teleport; + if (effectActor?.Clip != null) + loop = false; + if (state.NativeAnimationClip != null) + { + local = (float)state.NativeAnimationSeconds; + loop = false; + } + if (state.Pose == BattlePose.Dead && (actor.Actor.Vitals[0] == 0 || combat.Status != BattleSessionStatus.Running)) + local = actor.Duration; + actor.Renderer.SampleAnimation(loop && actor.Duration > 0 ? local % actor.Duration : Mathf.Clamp(local, 0, actor.Duration)); + actor.Renderer.SampleWeaponBlades(state.NativePresentationTick * BattleSession.StepSeconds, + state.NativePlaybackRate, state.WeaponTrailSeconds); + } + ApplyShadows(combat); + ApplyThrownWeapons(combat); + ApplyCorpses(combat); + ApplyNumbers(combat); + ApplyMessages(combat); + ApplyHitFeedback(combat); + ApplySwordSparks(combat); + ApplyLineups(combat); + CollectDependencies(); + _diagnostics.AddRange(catalog.Diagnostics.Distinct()); + } + + public string[] AnimationMarkers(string instanceId) + { + if (!_actors.TryGetValue(instanceId, out ActorView actor)) + return Array.Empty(); + return actor.Model.AnimationEvents.Select(marker => $"{marker.GameBoxTick / (float)UnityPrimitivesConvertor.GameBoxTicksPerSecond:F3}s · {marker.Name}").ToArray(); + } + + public string InstanceAt(Vector2 point, Rect rect) + { + return _actors.Values.Where(actor => actor.Visible && View.Project(actor.Object.transform.position + Vector3.up, rect, out Vector2 projected) && Vector2.Distance(projected, point) < 24) + .OrderBy(actor => + { + View.Project(actor.Object.transform.position + Vector3.up, rect, out Vector2 projected); + return Vector2.Distance(projected, point); + }) + .Select(actor => actor.Actor.InstanceId).FirstOrDefault(); + } + + public void DrawLabels(Rect rect, string selected) + { + if (rect.width <= 0 || rect.height <= 0) + return; + // Scene labels need a consistent contrast over the rendered world, + // independent of the Editor skin's box textures. + var style = new GUIStyle(GUIStyle.none) + { + font = GUI.skin.label.font, + alignment = TextAnchor.MiddleCenter, + wordWrap = false, + clipping = TextClipping.Clip, + normal = { textColor = Color.white }, + hover = { textColor = Color.white } + }; + foreach (ActorView actor in _actors.Values) + if (actor.Visible && View.Project(actor.Object.transform.position + Vector3.up * 2, rect, out Vector2 point)) + { + string text = $"{(actor.Actor.InstanceId == selected ? "▶ " : "")}{_data.Database.CombatActorInfos[actor.Actor.ActorId].Name} · {actor.DisplaySlot}"; + var content = new GUIContent(text, text); + Vector2 required = style.CalcSize(content); + float width = Math.Min(rect.width, Math.Max(140, required.x + 12)); + float height = Math.Min(rect.height, Math.Max(22, required.y)); + var label = new Rect(Mathf.Clamp(point.x - width / 2, rect.xMin, rect.xMax - width), + Mathf.Clamp(point.y - height / 2, rect.yMin, rect.yMax - height), width, height); + if (Event.current.type == EventType.Repaint) + UnityEditor.EditorGUI.DrawRect(label, new Color(.06f, .07f, .09f, .8f)); + GUI.Label(label, content, style); + } + } + + private void CollectDependencies() + { + _diagnostics.Clear(); + _diagnostics.AddRange(_musicDiagnostics); + _diagnostics.AddRange(View.Dependencies.Where(pair => !pair.Value).Select(pair => "Missing texture dependency: " + pair.Key)); + } + + private static Vector3 ToVector(BattlePoint point) => new(point.X, point.Y, point.Z); + + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + Effects?.Dispose(); + Audio?.Dispose(); + Trail?.Dispose(); + DisposeNumbers(); + DisposeSwordSparks(); + DisposeHitFeedback(); + DisposeLineups(); + DisposeThrownWeapons(); + DisposeShadows(); + View?.Dispose(); + _nativeLighting?.Dispose(); + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.cs.meta new file mode 100644 index 00000000..8d335626 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattlePreview.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 74c73df7814884a87975c0308adb70af \ No newline at end of file diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattleTrailPreview.cs b/Assets/Scripts/Editor/BattleEditor/Preview/BattleTrailPreview.cs new file mode 100644 index 00000000..3f39aca4 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattleTrailPreview.cs @@ -0,0 +1,128 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using Battle; + using ResourceBrowser; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed class BattleTrailPreview : IResourcePreviewFrameEffect, IDisposable + { + private readonly BattleTrailState _state = new(); + private readonly RenderTexture[] _history = new RenderTexture[BattleTrailState.Capacity]; + private RenderTexture _output; + private Material _material; + private bool _disposed; + + public bool Enabled + { + get; set; + } + + public bool Suspended + { + get; set; + } + + private bool Applies => Enabled && !Suspended; + + public Rect Viewport => Applies ? new Rect(0, 0, 1, .75f) : new Rect(0, 0, 1, 1); + + public Vector2Int TargetSize(int requestedWidth, int requestedHeight) => Applies ? new Vector2Int(256, 256) : new Vector2Int(requestedWidth, requestedHeight); + + public void Advance(double scaledSeconds, double absoluteSeconds) => _state.Advance(scaledSeconds); + + public RenderTexture Composite(RenderTexture scene, int requestedWidth, int requestedHeight) + { + if (_disposed) + throw new ObjectDisposedException(nameof(BattleTrailPreview)); + if (!Applies) + return scene; + RenderTexture previous = RenderTexture.active; + try + { + EnsureResources(requestedWidth, requestedHeight); + Graphics.Blit(scene, _history[_state.CurrentTexture]); + RenderTexture.active = _output; + GL.Clear(false, true, Color.black); + for (int order = 0; order < BattleTrailState.Capacity; order++) + { + int alpha = BattleTrailState.AlphaAt(order); + _material.SetVector("_Diffuse", new Vector4((alpha / 2) / 255f, (alpha / 2) / 255f, (alpha / 2) / 255f, alpha / 255f)); + Graphics.Blit(_history[_state.TextureAt(order)], _output, _material); + } + } + finally + { + RenderTexture.active = previous; + } + return _output; + } + + private void EnsureResources(int width, int height) + { + if (_material == null) + { + Shader shader = Shader.Find("Hidden/Pal3/BattleTrail"); + if (shader == null || !shader.isSupported) + throw new InvalidOperationException("The original battle trail shader is unavailable."); + _material = new Material(shader) { hideFlags = HideFlags.HideAndDontSave }; + } + for (int index = 0; index < _history.Length; index++) + if (_history[index] == null) + { + _history[index] = Create(256, 256); + RenderTexture previous = RenderTexture.active; + RenderTexture.active = _history[index]; + GL.Clear(false, true, Color.black); + RenderTexture.active = previous; + } + if (_output != null && _output.width == width && _output.height == height) + return; + Release(_output); + _output = Create(width, height); + } + + private static RenderTexture Create(int width, int height) + { + var texture = new RenderTexture(width, height, 0, RenderTextureFormat.ARGB32) + { + hideFlags = HideFlags.HideAndDontSave, + filterMode = FilterMode.Bilinear, + wrapMode = TextureWrapMode.Clamp + }; + texture.Create(); + return texture; + } + + private static void Release(RenderTexture texture) + { + if (texture == null) + return; + texture.Release(); + Object.DestroyImmediate(texture); + } + + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + Release(_output); + _output = null; + for (int index = 0; index < _history.Length; index++) + { + Release(_history[index]); + _history[index] = null; + } + if (_material != null) + Object.DestroyImmediate(_material); + _material = null; + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Preview/BattleTrailPreview.cs.meta b/Assets/Scripts/Editor/BattleEditor/Preview/BattleTrailPreview.cs.meta new file mode 100644 index 00000000..e17c87b9 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Preview/BattleTrailPreview.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5b6c70182e154034a74ffbd0e8e1dbcd diff --git a/Assets/Scripts/Editor/BattleEditor/README.md b/Assets/Scripts/Editor/BattleEditor/README.md new file mode 100644 index 00000000..ac6fc2d8 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/README.md @@ -0,0 +1,33 @@ +# Battle Editor composition + +This Editor-only assembly adapts original PAL3/PAL3A data and Unity views to the engine-independent battle core. + +| Directory | Responsibility | +| --- | --- | +| `Authoring` | EditorWindow, presets/canonical JSON, Undo and typed draft editing. Missing required fields are repaired explicitly; drawing does not silently normalize imported data. | +| `Data` | Read-only resource/database access, immutable definition compilation, random example generation and scene music selection. | +| `Catalog` | Original animation, ability, body/audio and stage metadata adapters. | +| `Session` | Owns the captured setup, battle session and replaceable preview; failed replacement preserves the previous session. | +| `Preview` | Owns Unity geometry, native lighting, camera, effects, shadows, trails, result bodies and projectiles. All allocations share one failure-cleanup boundary. | +| `Media` | Independent audio/movie ownership and transport; normal-speed playback, pause, silent stepping and disposal. | +| `Hud` | One original HUD layout and hit geometry. Rendering registers controls; pointer/key input enters the semantic Presenter before it can submit commands. | + +`BattleEditorWorkbench` presents one canvas and one optional drawer. The primary action follows connection, validation, running, paused and terminal states. Draft edits, Undo/Redo and discard pause transport; pending draft changes also block commands against the old snapshot until the user applies and restarts. File operations retain draft protection and asset ownership. Actual connection details come from the loaded data, independently of pending path inputs. The canvas extends to the bottom inset without a workflow footer; failed operations expose their diagnostic log from the transport row. + +Continuous background music follows its own audio transport between explicit start, pause/resume and inspection boundaries. Routine battle-state publications never correct a running music voice back to the logical clock; movement/movie timing still follows its presentation markers. + +The live battle, captured initial setup and mutable authoring draft have separate ownership. Native lights are borrowed by original model effects and updated after their render-pose sampling; the preview owns their lifetime. A failed preview constructor disposes partial owners before it escapes. + +Random examples and newly added player allies use `BattleTestLoadoutBuilder`: all personal techniques and magic permitted by the original character data start mastered at level 4, including story-gated skills. Resource costs, equipment, transformation and special command requirements still apply. The original participant factory and imported presets retain their captured skill state. + +Floating numbers project immutable stage activations through the current camera using the original `unicode20.tft` glyphs. Rendering owns its texture cache and consumes no battle randomness. Result prompts use the fitted original UI canvas; the exit fade covers the entire rendered viewport. + +`BattleData` caches immutable animation timing, markers and source collision bounds by full canonical resource path. The first read parses the MV3 without calculating lighting normals. Subsequent catalogs reuse the compact metadata. Only previews using original lighting request per-frame normals. Each data owner has a separate cache and clears it on disposal, including when changing games or resource roots. + +Mouse and keyboard use IMGUI; the focused Editor window also receives Input System gamepad events outside Play Mode. The device adapter, ordered input policy, window context router and engine-independent Presenter have separate responsibilities. State and partial delta events preserve their original order; held navigation repeats after 350 ms at 100 ms intervals. Losing focus, pointer takeover, device reset and page/controller changes suppress stale holds without replaying buttons or consuming the complete native input event. + +The original command ring supports eight directions through D-pad/left stick or keyboard arrows/WASD with Q/E/Z/C diagonals. A/cross or Enter/Space confirms; B/circle, Esc or right-click returns; X selects the center attack command; Y repeats the previous action. LB/RB change list categories or AI roles, and cycle the command ring's complete focus list, including the magic sword, transformation and five-spirit wheel when available. Start controls an already configured test's start/pause/resume/restart without opening file dialogs or applying pending authoring changes. Formation uses actor selection followed by a destination slot; cancelling first leaves the destination stage, then ends formation. Result and skippable cinematic input routes through the session before normal HUD input. + +Target selection, protection and AI actor selection use the world models, without a temporary target roster, rings or name labels. Mouse hover previews the legal affected group and a click applies. One complete tap confirms an eligible command target. Tapping an ineligible target or the background returns to the previous menu. Protection and AI actor selection use a first tap to preview and a second tap on the same actor to confirm. Cancelled contacts, drags, missing releases and secondary contacts cannot submit an action. OBB ray hits and pointer height share the current action's original collision bounds; directional selection uses the camera's projected positions. Original CVD head pointers and the body's original RGB pulse show the selected group. The selection shader preserves alpha and native-light property blocks, excludes tag-node weapons, and works in native and Toon render modes. A separate presentation clock animates selection during editor pause without advancing battle time or randomness. + +Skill, magic and item lists return one level on Esc, right-click or an outside click/tap, without an extra Back button. Pointer gestures retain ownership until release so dismissal does not click through into the camera or the next page. Native menu labels retain readable colors in every IMGUI state, while disabled entries expose localized reasons instead of internal resource identifiers. Simulated-device and pointer API tests are not physical hardware acceptance. Kernel tests live in `Assets/Tests/Battle/Editor`; engine-independent presentation tests live in `Assets/Tests/Battle/Presentation/Editor`. Authoring, HUD and resource integration fixtures remain under `Assets/Tests/BattleEditor/Editor/{Authoring,Hud,Integration}`. Each layer has its own test assembly; existing test namespaces remain stable for saved filters. diff --git a/Assets/Scripts/Editor/BattleEditor/README.md.meta b/Assets/Scripts/Editor/BattleEditor/README.md.meta new file mode 100644 index 00000000..737ec064 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/README.md.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cc08fe19c79c474a93ae4f8d14d108e4 diff --git a/Assets/Scripts/Editor/BattleEditor/Session.meta b/Assets/Scripts/Editor/BattleEditor/Session.meta new file mode 100644 index 00000000..33cac035 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Session.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 814db03cbb2b4b379b2f835a68a1e55e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.Results.cs b/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.Results.cs new file mode 100644 index 00000000..8a883265 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.Results.cs @@ -0,0 +1,81 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using Battle; + + public sealed partial class BattleEditorSession + { + private double _resultAccumulator; + + public BattleResultPresentation ResultPresentation + { + get; private set; + } + + private void ResetResults() + { + ResultPresentation = null; + _resultAccumulator = 0; + } + + private void EnsureResults() + { + if (ResultPresentation != null || Battle?.Status != BattleSessionStatus.Completed) + return; + ResultPresentation = new BattleResultPresentation(Battle.Definitions?.Variant ?? _setup.CreateInstance().Variant, Battle.Result, Battle.Events, Preview); + _resultAccumulator = 0; + Preview.BeginResultPresentation(Battle, _battleCatalog, ResultPresentation); + } + + public void ReplayResults() + { + if (Battle?.Status == BattleSessionStatus.Completed) + BeginReplay(); + } + + public bool SkipResultStep() + { + if (ResultPresentation?.SkipCurrent() != true) + return false; + Preview.ApplyResultPresentation(ResultPresentation, false); + FinishResults(); + return true; + } + + private void StepResults() + { + if (ResultPresentation == null || ResultPresentation.Completed) + return; + Preview.PrepareResultBodyPass(); + ResultPresentation.Step(); + Preview.ApplyResultPresentation(ResultPresentation, true); + FinishResults(); + } + + private void FinishResults() + { + if (ResultPresentation?.Completed != true) + return; + Preview.Audio.Stop(); + _resultAccumulator = 0; + IsPlaying = false; + } + + private void AdvanceResults(double seconds) + { + if (!double.IsFinite(seconds) || seconds < 0 || seconds > 60) + throw new ArgumentOutOfRangeException(nameof(seconds)); + _resultAccumulator += seconds; + while (_resultAccumulator + 1e-12 >= BattleSession.StepSeconds && !ResultPresentation.Completed) + { + _resultAccumulator -= BattleSession.StepSeconds; + StepResults(); + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.Results.cs.meta b/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.Results.cs.meta new file mode 100644 index 00000000..28237428 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.Results.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f5049e0630b244e2a53967e5f802cebd diff --git a/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.cs b/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.cs new file mode 100644 index 00000000..58efcf83 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.cs @@ -0,0 +1,399 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Diagnostics; + using Battle; + + // Owns editor resources and the captured preview. The authoring draft stays outside this owner. + public sealed partial class BattleEditorSession : IDisposable + { + private BattleSetup _setup; + private BattleRandomExampleBuilder _examples; + private readonly Random _exampleRandom = new(); + private BattleAnimationCatalog _battleCatalog; + private bool _initialAutoAllies, _initialAutoEnemies; + private bool _isPlaying; + private IEnumerator _replay; + + internal bool IsReplaying => _replay != null; + + private float _speed = 1; + + internal event Action PreviewReleased; + + public BattleSession Battle + { + get; private set; + } + + public BattleData Data + { + get; private set; + } + + public BattlePreview Preview + { + get; private set; + } + + public bool IsPlaying + { + get => _isPlaying; + set + { + _isPlaying = value && ResultPresentation?.Completed != true; + SyncAudioPlayback(); + } + } + + public float Speed + { + get => _speed; + set + { + if (!float.IsFinite(value) || value <= 0) + throw new ArgumentOutOfRangeException(nameof(value)); + _speed = value; + SyncAudioPlayback(); + } + } + + private void SyncAudioPlayback() + { + if (Preview == null) + return; + // Preview AudioSources own transport and pitch. Editor inspection + // and accelerated simulation deliberately stay silent. + bool realtime = IsPlaying && Speed == 1; + Preview.Audio.PlaybackEnabled = realtime; + Preview.Effects.AudioPlaybackEnabled = realtime; + } + + public BattleScenario CapturedScenario => _setup?.CreateInstance(); + + public void Load(string root, int codepage) => UseData(new BattleData(root, codepage)); + + internal void UseData(BattleData candidate) + { + try + { + Stop(); + Data?.Dispose(); + } + catch + { + candidate.Dispose(); + throw; + } + Data = candidate; + _examples = null; + } + + public BattleScenario CreateRandomExample() + { + if (Data == null) + throw new InvalidOperationException("Load game data first."); + _examples ??= new BattleRandomExampleBuilder(Data); + return _examples.Create(_exampleRandom); + } + + public void Start(BattleScenario scenario) + { + if (Data == null) + throw new InvalidOperationException("Load game data first."); + ReplacePreview(Data.Capture(scenario)); + } + + private void ReplacePreview(BattleSetup setup) + { + var candidate = new BattlePreview(Data, setup); + CommitPreview(candidate, setup, "replaced by preview"); + IsPlaying = false; + } + + public void Restart() + { + if (_setup != null) + { + if (Battle != null) + StartBattle(_setup.CreateInstance(), _initialAutoAllies, _initialAutoEnemies); + else + ReplacePreview(_setup); + } + } + + public void StartBattle(BattleScenario scenario, bool autoAllies = false, bool autoEnemies = false) + { + if (Data == null) + throw new InvalidOperationException("Load game data first."); + var setup = Data.Capture(scenario, forBattle: true); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(Data, setup); + var catalog = new BattleAnimationCatalog(Data, setup, definitions); + var candidate = new BattlePreview(Data, setup); + BattleSession combat; + try + { + combat = new BattleSession(setup, catalog, definitions: definitions, effects: candidate.Effects); + candidate.BindBattle(combat, catalog); + combat.SetAutomatic(BattleSide.Ally, autoAllies); + combat.SetAutomatic(BattleSide.Enemy, autoEnemies); + candidate.ApplyBattle(combat, catalog); + } + catch + { + candidate.Dispose(); + throw; + } + CommitPreview(candidate, setup, "restarted"); + Battle = combat; + _battleCatalog = catalog; + _initialAutoAllies = autoAllies; + _initialAutoEnemies = autoEnemies; + IsPlaying = false; + } + + public void StepBattle() + { + if (Battle == null) + return; + IsPlaying = false; + if (ResultPresentation != null) + StepResults(); + else + { + Battle.Step(); + SyncBattle(); + } + } + + public void AdvanceTo(BattleEventKind boundary, int maxSteps = 30000) + { + if (Battle == null) + return; + IsPlaying = false; + int start = Battle.Events.Count; + for (int i = 0; i < maxSteps && Battle.Status == BattleSessionStatus.Running; i++) + { + long before = Battle.Tick; + Battle.Step(); + if (Battle.Tick == before || Battle.Events.Skip(start).Any(entry => entry.Kind == boundary || boundary == BattleEventKind.Hit && entry.Kind == BattleEventKind.Miss) || + Battle.WaitingActor != null && Battle.Actors.All(actor => actor.ActionId == 0)) + break; + } + SyncBattle(); // Bounded inspection; never invent a victory if every attack misses. + } + + public void SyncBattle() + { + if (Battle == null) + return; + try + { + if (ResultPresentation == null) + Preview?.ApplyBattle(Battle, _battleCatalog); + EnsureResults(); + } + catch (Exception ex) + { + Battle.Fault("presentation: " + ex.Message); + IsPlaying = false; + throw; + } + if (Battle.Status != BattleSessionStatus.Running && (ResultPresentation == null || ResultPresentation.Completed)) + { + Preview?.Audio.Stop(); + IsPlaying = false; + } + } + + public void ReplayBattle() + { + if (Battle == null || IsReplaying) + return; + using IEnumerator replay = ReplayFrames().GetEnumerator(); + while (replay.MoveNext()) + { + } + } + + internal void BeginReplay() + { + if (Battle != null && !IsReplaying) + _replay = ReplayFrames().GetEnumerator(); + } + + internal void TickReplay() + { + IEnumerator replay = _replay; + if (replay == null) + return; + try + { + var slice = Stopwatch.StartNew(); + do + { + if (!replay.MoveNext()) + { + CancelReplay(); + return; + } + } + while (slice.Elapsed.TotalMilliseconds < 6); + } + catch + { + CancelReplay(); + throw; + } + } + + internal void CancelReplay() + { + IEnumerator replay = _replay; + _replay = null; + replay?.Dispose(); + } + + private IEnumerable ReplayFrames() + { + var replayCatalog = new BattleAnimationCatalog(Data, _setup, Battle.Definitions); + bool wasPlaying = IsPlaying; + BattlePreview candidate = null; + bool committed = false; + try + { + IsPlaying = false; + candidate = new BattlePreview(Data, _setup); + candidate.Audio.PlaybackEnabled = false; + candidate.Effects.AudioPlaybackEnabled = false; + candidate.Audio.Muted = true; + candidate.Effects.Muted = true; + candidate.Effects.ReusePreparedMovies(Preview.Effects); + BattleSession replay = null; + foreach (BattleSession frame in BattleReplay.RecreateFrames(_setup, replayCatalog, Battle, candidate.Effects, + created => candidate.BindBattle(created, replayCatalog))) + { + replay = frame; + yield return frame; + } + candidate.ApplyBattle(replay, replayCatalog); + candidate.Audio.Muted = false; + candidate.Effects.Muted = false; + _replay = null; + BattlePreview completed = candidate; + candidate = null; + CommitPreview(completed, _setup, "replaced by replay"); + committed = true; + Battle = replay; + _battleCatalog = replayCatalog; + EnsureResults(); + } + finally + { + if (!committed) + { + try + { + candidate?.Dispose(); + } + finally + { + IsPlaying = wasPlaying; + } + } + } + } + + public void Tick(float elapsed) + { + if (!IsPlaying || Preview == null) + return; + if (!float.IsFinite(elapsed) || elapsed < 0 || !float.IsFinite(Speed) || Speed <= 0) + throw new ArgumentOutOfRangeException(nameof(elapsed)); + if (Battle != null) + { + if (ResultPresentation != null) + AdvanceResults(Math.Min(60, (double)elapsed * Speed)); + else + { + Battle.Advance(Math.Min(60, (double)elapsed * Speed)); + SyncBattle(); + } + return; + } + Preview.Sample(Preview.Time + elapsed * Speed); + if (Preview.Time >= Preview.Duration) + IsPlaying = false; + } + + private void ReleasePreview() + { + BattlePreview previous = Preview; + Preview = null; + try + { + PreviewReleased?.Invoke(); + } + finally + { + previous?.Dispose(); + } + } + + private void CommitPreview(BattlePreview candidate, BattleSetup setup, string reason) + { + try + { + Stop(reason); + } + catch + { + candidate.Dispose(); + throw; + } + Preview = candidate; + _setup = setup; + } + + public void Stop() => Stop("editor stop"); + + private void Stop(string reason) + { + try + { + CancelReplay(); + IsPlaying = false; + Battle?.Abort(reason); + } + finally + { + Battle = null; + ResetResults(); + _battleCatalog = null; + _setup = null; + ReleasePreview(); + } + } + + public void Dispose() + { + try + { + Stop(); + } + finally + { + BattleData data = Data; + Data = null; + data?.Dispose(); + } + } + } +} diff --git a/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.cs.meta b/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.cs.meta new file mode 100644 index 00000000..c8a7ada8 --- /dev/null +++ b/Assets/Scripts/Editor/BattleEditor/Session/BattleEditorSession.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7922c854aceab47349479314e0d68686 \ No newline at end of file diff --git a/Assets/Scripts/Editor/EffectEditor.cs b/Assets/Scripts/Editor/EffectEditor.cs index 68e61de7..4061d4b7 100644 --- a/Assets/Scripts/Editor/EffectEditor.cs +++ b/Assets/Scripts/Editor/EffectEditor.cs @@ -12,7 +12,7 @@ namespace Editor using Pal3.Core.DataReader.Data; using Pal3.Core.DataReader.Par; using Pal3.Core.FileSystem; - using Pal3.Game.Effect.Original; + using Pal3.Game.Effect.Runtime; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; @@ -23,11 +23,11 @@ namespace Editor public sealed class EffectEditor : EditorWindow { - private OriginalEffectResources _resources; - private OriginalEffectPlayer _player; - private OriginalPortalEffect _portal; + private EffectResources _resources; + private EffectPlayer _player; + private PortalEffectPlayer _portal; private uint _portalType; - [SerializeField] private OriginalEffectOverrides _edits; + [SerializeField] private EffectOverrides _edits; [SerializeField] private string _assetPath = "", _savedJson; private GameObject _root; private Scene _scene; @@ -53,7 +53,7 @@ namespace Editor private double _seekAfter; #if PAL3 - [MenuItem("PAL3/Effect Editor")] + [MenuItem("PAL3/Effect Editor", priority = 32)] #endif public static void Open() { @@ -62,7 +62,7 @@ namespace Editor } #if PAL3A - [MenuItem("PAL3A/Effect Editor")] + [MenuItem("PAL3A/Effect Editor", priority = 32)] #endif public static void OpenPal3A() { @@ -78,7 +78,7 @@ namespace Editor int codepage = EditorPrefs.GetInt($"{Variant}.OriginalEffect.Codepage", 936) == 950 ? 950 : 936; if (path == _dataPath && codepage == _codepage || !CanReplaceEdits()) return; - LoadOverrides(Resources.Load($"Effects/{Variant}Overrides")); + LoadOverrides(Resources.Load($"Effects/{Variant}Overrides")); LoadPreferences(); LoadData(); return; @@ -88,7 +88,7 @@ namespace Editor _pal3a = pal3a; _id = pal3a ? 160 : 98; _time = 0; - LoadOverrides(Resources.Load($"Effects/{Variant}Overrides")); + LoadOverrides(Resources.Load($"Effects/{Variant}Overrides")); LoadPreferences(); LoadData(); } @@ -106,7 +106,7 @@ namespace Editor minSize = new Vector2(1050, 640); LoadPreferences(); if (_edits == null) - LoadOverrides(Resources.Load($"Effects/{Variant}Overrides")); + LoadOverrides(Resources.Load($"Effects/{Variant}Overrides")); _edits.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave; saveChangesMessage = "Save the original effect overrides before closing?"; _scene = EditorSceneManager.NewPreviewScene(); @@ -152,14 +152,14 @@ namespace Editor } } - private void LoadOverrides(OriginalEffectOverrides asset) + private void LoadOverrides(EffectOverrides asset) { if (_edits != null) { Undo.ClearUndo(_edits); DestroyImmediate(_edits); } - _edits = asset != null ? Instantiate(asset) : CreateInstance(); + _edits = asset != null ? Instantiate(asset) : CreateInstance(); _edits.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave; _assetPath = asset != null ? AssetDatabase.GetAssetPath(asset) : ""; _savedJson = JsonUtility.ToJson(_edits); @@ -176,7 +176,7 @@ namespace Editor public override void DiscardChanges() { - LoadOverrides(_assetPath.Length > 0 ? AssetDatabase.LoadAssetAtPath(_assetPath) : null); + LoadOverrides(_assetPath.Length > 0 ? AssetDatabase.LoadAssetAtPath(_assetPath) : null); base.DiscardChanges(); RefreshAfterUndo(); } @@ -197,12 +197,12 @@ namespace Editor if (path.Length == 0) return false; var existing = AssetDatabase.LoadMainAssetAtPath(path); - if (existing != null && existing is not OriginalEffectOverrides) + if (existing != null && existing is not EffectOverrides) { - _error = "Choose an OriginalEffectOverrides asset or a new path."; + _error = "Choose an EffectOverrides asset or a new path."; return false; } - var saved = existing as OriginalEffectOverrides; + var saved = existing as EffectOverrides; if (saved != null) { Undo.RecordObject(saved, $"Save {Variant} effect overrides"); @@ -238,7 +238,7 @@ namespace Editor hash.Init(); var fs = new CpkFileSystem(_dataPath, hash, _codepage); fs.Mount("basedata/basedata.cpk", _codepage); - _resources = new OriginalEffectResources(fs, _codepage); + _resources = new EffectResources(fs, _codepage); if (_resources.GameVariant != Variant) throw new InvalidDataException($"The selected directory contains {_resources.GameVariant} data; select the matching variant first."); EditorPrefs.SetString($"{Variant}.OriginalEffect.DataPath", _dataPath); @@ -255,6 +255,8 @@ namespace Editor private void ClearPreview() { + _player?.Dispose(); + _portal?.Dispose(); if (_root != null) DestroyImmediate(_root); _player = null; @@ -276,7 +278,7 @@ namespace Editor SceneManager.MoveGameObjectToScene(_root, _scene); if (_id < 0) { - _portal = _root.AddComponent(); + _portal = _root.AddComponent(); _portal.AutoAdvance = false; _portal.Initialize(_resources, _portalType); } @@ -287,7 +289,7 @@ namespace Editor _error = string.Join("\n", issues); else { - _player = _root.AddComponent(); + _player = _root.AddComponent(); _player.AutoAdvance = false; _player.Initialize(_resources, _id, _seed, _edits); _player.Loop = false; @@ -388,8 +390,8 @@ namespace Editor if (GUILayout.Button("Reload", EditorStyles.toolbarButton, GUILayout.Width(55))) LoadData(); } - var asset = _assetPath.Length > 0 ? AssetDatabase.LoadAssetAtPath(_assetPath) : null; - var selected = (OriginalEffectOverrides)EditorGUILayout.ObjectField("Overrides", asset, typeof(OriginalEffectOverrides), false); + var asset = _assetPath.Length > 0 ? AssetDatabase.LoadAssetAtPath(_assetPath) : null; + var selected = (EffectOverrides)EditorGUILayout.ObjectField("Overrides", asset, typeof(EffectOverrides), false); if (selected != asset && CanReplaceEdits()) { LoadOverrides(selected); @@ -441,7 +443,7 @@ namespace Editor if (GUILayout.Button("Step", GUILayout.Width(50))) { _playing = false; - Advance(OriginalEffectPlayer.FixedStep); + Advance(EffectPlayer.FixedStep); Repaint(); } GUILayout.Label("Speed", GUILayout.Width(40)); @@ -503,7 +505,8 @@ namespace Editor } if (e.type != EventType.Repaint || rect.width < 1 || rect.height < 1) return; - int w = Mathf.Max(1, (int)rect.width), h = Mathf.Max(1, (int)rect.height); + float density = EditorGUIUtility.pixelsPerPoint; + int w = Mathf.Max(1, Mathf.CeilToInt(rect.width * density)), h = Mathf.Max(1, Mathf.CeilToInt(rect.height * density)); if (_target == null || _target.width != w || _target.height != h) { if (_target != null) @@ -539,11 +542,11 @@ namespace Editor _resources.Definitions.TryGetType(source.TypeCrc, out EffectDefinition d); EditorGUILayout.LabelField($"{d.TypeName} / {EffectClass.Name(d.ClassNameCrc)}"); EditorGUILayout.SelectableLabel(d.TextureName ?? "", GUILayout.Height(35)); - OriginalEffectObjectOverride edit = _edits.Find(_id, _objectIndex); + EffectObjectOverride edit = _edits.Find(_id, _objectIndex); if (edit == null && GUILayout.Button("Edit this object")) { Undo.RecordObject(_edits, "Edit original effect"); - edit = new OriginalEffectObjectOverride + edit = new EffectObjectOverride { GroupId = _id, ObjectIndex = _objectIndex, @@ -628,7 +631,7 @@ namespace Editor string[] names = _emitterCurve ? new[] { "Direction", "RandomVelocity", "Emission", "Life" } : new[] { "Size", "Rotation", "Alpha", "Color" }; _curveIndex = EditorGUILayout.Popup("Curve", Mathf.Clamp(_curveIndex, 0, names.Length - 1), names); string name = names[_curveIndex]; - ParticleCurve source = OriginalEffectOverrides.FindCurve(file, _emitterCurve, _particleIndex, name); + ParticleCurve source = EffectOverrides.FindCurve(file, _emitterCurve, _particleIndex, name); var entry = _edits.ParticleCurves.Find(c => string.Equals(c.File, path, StringComparison.OrdinalIgnoreCase) && c.Emitter == _emitterCurve && c.Index == _particleIndex && c.Parameter == name); bool validEntry = entry == null || entry.Channels != null && entry.Channels.Length == source.Channels && entry.Channels.All(c => c != null); @@ -646,7 +649,7 @@ namespace Editor Undo.RecordObject(_edits, "Edit particle curve"); if (entry == null) { - entry = new OriginalParticleCurveOverride + entry = new ParticleCurveOverride { File = path, Parameter = name, diff --git a/Assets/Scripts/Editor/ReleaseBuildPipeline.cs b/Assets/Scripts/Editor/ReleaseBuildPipeline.cs index 64531ccc..84f203d4 100644 --- a/Assets/Scripts/Editor/ReleaseBuildPipeline.cs +++ b/Assets/Scripts/Editor/ReleaseBuildPipeline.cs @@ -34,80 +34,80 @@ namespace Editor private static readonly char DirSeparator = Path.DirectorySeparatorChar; #if PAL3 - [MenuItem("PAL3/Build Pipelines/Build [Windows_arm64] IL2CPP Release Executable")] - #elif PAL3A - [MenuItem("PAL3A/Build Pipelines/Build [Windows_arm64] IL2CPP Release Executable")] - #endif + [MenuItem("PAL3/Build Pipelines/Build [Windows_arm64] IL2CPP Release Executable", priority = 2000)] +#elif PAL3A + [MenuItem("PAL3A/Build Pipelines/Build [Windows_arm64] IL2CPP Release Executable", priority = 2000)] +#endif public static void Build_Windows_arm64() { BuildGame(Pal3BuildTarget.Windows_arm64); } #if PAL3 - [MenuItem("PAL3/Build Pipelines/Build [Windows_x86] IL2CPP Release Executable")] - #elif PAL3A - [MenuItem("PAL3A/Build Pipelines/Build [Windows_x86] IL2CPP Release Executable")] - #endif + [MenuItem("PAL3/Build Pipelines/Build [Windows_x86] IL2CPP Release Executable", priority = 2000)] +#elif PAL3A + [MenuItem("PAL3A/Build Pipelines/Build [Windows_x86] IL2CPP Release Executable", priority = 2000)] +#endif public static void Build_Windows_x86() { BuildGame(Pal3BuildTarget.Windows_x86); } #if PAL3 - [MenuItem("PAL3/Build Pipelines/Build [Windows_x64] IL2CPP Release Executable")] - #elif PAL3A - [MenuItem("PAL3A/Build Pipelines/Build [Windows_x64] IL2CPP Release Executable")] - #endif + [MenuItem("PAL3/Build Pipelines/Build [Windows_x64] IL2CPP Release Executable", priority = 2000)] +#elif PAL3A + [MenuItem("PAL3A/Build Pipelines/Build [Windows_x64] IL2CPP Release Executable", priority = 2000)] +#endif public static void Build_Windows_x64() { BuildGame(Pal3BuildTarget.Windows_x64); } #if PAL3 - [MenuItem("PAL3/Build Pipelines/Build [Linux_x86_x64] IL2CPP Release Executable")] - #elif PAL3A - [MenuItem("PAL3A/Build Pipelines/Build [Linux_x86_x64] IL2CPP Release Executable")] - #endif + [MenuItem("PAL3/Build Pipelines/Build [Linux_x86_x64] IL2CPP Release Executable", priority = 2000)] +#elif PAL3A + [MenuItem("PAL3A/Build Pipelines/Build [Linux_x86_x64] IL2CPP Release Executable", priority = 2000)] +#endif public static void Build_Linux_x86_x64() { BuildGame(Pal3BuildTarget.Linux_x86_x64); } #if PAL3 - [MenuItem("PAL3/Build Pipelines/Build [macOS_arm64_x64] IL2CPP XCode Project")] - #elif PAL3A - [MenuItem("PAL3A/Build Pipelines/Build [macOS_arm64_x64] IL2CPP XCode Project")] - #endif + [MenuItem("PAL3/Build Pipelines/Build [macOS_arm64_x64] IL2CPP XCode Project", priority = 2000)] +#elif PAL3A + [MenuItem("PAL3A/Build Pipelines/Build [macOS_arm64_x64] IL2CPP XCode Project", priority = 2000)] +#endif public static void Build_macOS_arm64_x64() { BuildGame(Pal3BuildTarget.macOS_arm64_x64); } #if PAL3 - [MenuItem("PAL3/Build Pipelines/Build [Android] IL2CPP Release APK")] - #elif PAL3A - [MenuItem("PAL3A/Build Pipelines/Build [Android] IL2CPP Release APK")] - #endif + [MenuItem("PAL3/Build Pipelines/Build [Android] IL2CPP Release APK", priority = 2000)] +#elif PAL3A + [MenuItem("PAL3A/Build Pipelines/Build [Android] IL2CPP Release APK", priority = 2000)] +#endif public static void Build_Android() { BuildGame(Pal3BuildTarget.Android); } #if PAL3 - [MenuItem("PAL3/Build Pipelines/Build [iOS] IL2CPP XCode Project")] - #elif PAL3A - [MenuItem("PAL3A/Build Pipelines/Build [iOS] IL2CPP XCode Project")] - #endif + [MenuItem("PAL3/Build Pipelines/Build [iOS] IL2CPP XCode Project", priority = 2000)] +#elif PAL3A + [MenuItem("PAL3A/Build Pipelines/Build [iOS] IL2CPP XCode Project", priority = 2000)] +#endif public static void Build_iOS() { BuildGame(Pal3BuildTarget.iOS); } #if PAL3 - [MenuItem("PAL3/Build Pipelines/Build All [Windows, Linux, macOS, Android, iOS]")] - #elif PAL3A - [MenuItem("PAL3A/Build Pipelines/Build All [Windows, Linux, macOS, Android, iOS]")] - #endif + [MenuItem("PAL3/Build Pipelines/Build All [Windows, Linux, macOS, Android, iOS]", priority = 2000)] +#elif PAL3A + [MenuItem("PAL3A/Build Pipelines/Build All [Windows, Linux, macOS, Android, iOS]", priority = 2000)] +#endif public static void BuildAll() { BuildGame(Pal3BuildTarget.Windows_arm64 | @@ -120,10 +120,10 @@ namespace Editor } #if PAL3 - [MenuItem("PAL3/Build Pipelines/Zip Release files [Windows, Linux, Android]")] - #elif PAL3A - [MenuItem("PAL3A/Build Pipelines/Zip Release files [Windows, Linux, Android]")] - #endif + [MenuItem("PAL3/Build Pipelines/Zip Release files [Windows, Linux, Android]", priority = 2000)] +#elif PAL3A + [MenuItem("PAL3A/Build Pipelines/Zip Release files [Windows, Linux, Android]", priority = 2000)] +#endif public static void ZipAll() { ZipReleaseFiles(); diff --git a/Assets/Scripts/Editor/ResourceBrowser/IResourcePreviewFrameEffect.cs b/Assets/Scripts/Editor/ResourceBrowser/IResourcePreviewFrameEffect.cs new file mode 100644 index 00000000..37249e23 --- /dev/null +++ b/Assets/Scripts/Editor/ResourceBrowser/IResourcePreviewFrameEffect.cs @@ -0,0 +1,23 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.ResourceBrowser +{ + using UnityEngine; + + // The composite preview owner supplies and disposes optional frame effects. + // Rendering the scene and presenting its output remain separate operations. + public interface IResourcePreviewFrameEffect + { + Vector2Int TargetSize(int requestedWidth, int requestedHeight); + + Rect Viewport + { + get; + } + + RenderTexture Composite(RenderTexture scene, int requestedWidth, int requestedHeight); + } +} diff --git a/Assets/Scripts/Editor/ResourceBrowser/IResourcePreviewFrameEffect.cs.meta b/Assets/Scripts/Editor/ResourceBrowser/IResourcePreviewFrameEffect.cs.meta new file mode 100644 index 00000000..41685d48 --- /dev/null +++ b/Assets/Scripts/Editor/ResourceBrowser/IResourcePreviewFrameEffect.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 23a661bbe30a47d081fddf6e37bdf5e4 diff --git a/Assets/Scripts/Editor/ResourceBrowser/ResourceCatalog.cs b/Assets/Scripts/Editor/ResourceBrowser/ResourceCatalog.cs index 1a06856f..7f51edd2 100644 --- a/Assets/Scripts/Editor/ResourceBrowser/ResourceCatalog.cs +++ b/Assets/Scripts/Editor/ResourceBrowser/ResourceCatalog.cs @@ -12,7 +12,7 @@ namespace Pal3.ResourceBrowser using System.Threading; using Core.DataReader.Cpk; using Core.FileSystem; - using Game.Effect.Original; + using Game.Effect.Runtime; public sealed class ResourceEntry { @@ -117,7 +117,7 @@ namespace Pal3.ResourceBrowser else catalog.Entries.Add(new ResourceEntry(relative, file)); } - using (var effects = new OriginalEffectResources(catalog.FileSystem, codepage)) + using (var effects = new EffectResources(catalog.FileSystem, codepage)) { if (effects.GameVariant != variant) throw new InvalidDataException($"This folder contains {effects.GameVariant}. Use {variant} data, or Switch Variant in the Unity menu."); @@ -140,6 +140,36 @@ namespace Pal3.ResourceBrowser } } + // Battle tools only need basedata; mounting scene/music/movie archives wastes time and memory. + public static ResourceCatalog OpenBaseData(string root, int codepage, CancellationToken cancellation = default) + { + var catalog = new ResourceCatalog(root, codepage); + try + { + cancellation.ThrowIfCancellationRequested(); + string directory = System.IO.Path.Combine(catalog.Root, "basedata"); + string archive = Directory.EnumerateFiles(directory).SingleOrDefault(file => + string.Equals(System.IO.Path.GetFileName(file), "basedata.cpk", StringComparison.OrdinalIgnoreCase)); + if (archive == null) + throw new FileNotFoundException("Select the game data folder directly containing basedata/basedata.cpk."); + catalog.FileSystem.Mount(System.IO.Path.GetRelativePath(catalog.Root, archive), codepage); + foreach (string path in catalog.FileSystem.Search()) + { + cancellation.ThrowIfCancellationRequested(); + var entry = new ResourceEntry(path); + catalog.Entries.Add(entry); + catalog._lookup.TryAdd(entry.Path, entry); + } + catalog.Entries.Sort((a, b) => StringComparer.OrdinalIgnoreCase.Compare(a.Path, b.Path)); + return catalog; + } + catch + { + catalog.Dispose(); + throw; + } + } + public ResourceEntry Find(string path) { path = path.Replace('/', '\\'); @@ -171,6 +201,15 @@ namespace Pal3.ResourceBrowser public void CheckExportDestination(string destination) => CheckOutsideRoot(Root, destination); + // Save dialogs may confirm replacing an existing report, but no output may follow links. + public static void WriteTextFile(string destination, string contents, string sourceRoot = null) + { + if (sourceRoot != null) + CheckOutsideRoot(sourceRoot, destination); + CheckNoLinks(destination); + File.WriteAllText(destination, contents); + } + public static void CheckOutsideRoot(string root, string destination) { string path = System.IO.Path.GetFullPath(destination); @@ -263,8 +302,13 @@ namespace Pal3.ResourceBrowser { for (string path = System.IO.Path.GetFullPath(fullPath); path != null; path = System.IO.Path.GetDirectoryName(path)) { - if ((File.Exists(path) || Directory.Exists(path)) && (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) - throw new IOException($"{message}: {path}"); + try + { + if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) + throw new IOException($"{message}: {path}"); + } + catch (FileNotFoundException) { } + catch (DirectoryNotFoundException) { } if (path == System.IO.Path.GetPathRoot(path)) break; } diff --git a/Assets/Scripts/Editor/ResourceBrowser/ResourceFormats.cs b/Assets/Scripts/Editor/ResourceBrowser/ResourceFormats.cs index 9ef8cfbd..8e00aee1 100644 --- a/Assets/Scripts/Editor/ResourceBrowser/ResourceFormats.cs +++ b/Assets/Scripts/Editor/ResourceBrowser/ResourceFormats.cs @@ -24,7 +24,7 @@ namespace Pal3.ResourceBrowser public static class ResourceFormats { - public static object Read(ResourceEntry entry, byte[] bytes, int codepage) => entry.Extension switch + public static object Read(ResourceEntry entry, byte[] bytes, int codepage, bool includeMv3NativeNormals = false) => entry.Extension switch { ".sce" => Read(new SceFileReader(), bytes, codepage), ".gdb" => Read(new GdbFileReader(), bytes, codepage), @@ -38,7 +38,7 @@ namespace Pal3.ResourceBrowser ".lgt" => Read(new LgtFileReader(), bytes, codepage), ".pol" => Read(new PolFileReader(), bytes, codepage), ".cvd" => Read(new CvdFileReader(), bytes, codepage), - ".mv3" => Read(new Mv3FileReader(), bytes, codepage), + ".mv3" => Read(new Mv3FileReader(includeMv3NativeNormals), bytes, codepage), ".msh" => Read(new MshFileReader(), bytes, codepage), ".mov" => Read(new MovFileReader(), bytes, codepage), ".mtl" => Read(new MtlFileReader(), bytes, codepage), diff --git a/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.Environment.cs b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.Environment.cs new file mode 100644 index 00000000..5186e0b3 --- /dev/null +++ b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.Environment.cs @@ -0,0 +1,96 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.ResourceBrowser +{ + using System; + using System.Collections.Generic; + using Core.DataReader.Pol; + using Engine.Core.Implementation; + using Game.Effect.Runtime; + using Game.Rendering.Renderer; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed partial class ResourceModelPreview + { + private GameObject _environment; + + public PolyModelRenderer AddPolyModel(GameObject target, string resourcePath, PolFile model, string texture = null) + { + if (target == null || !target.transform.IsChildOf(Root.transform)) + throw new ArgumentException("The model must belong to this preview.", nameof(target)); + var renderer = target.AddComponent(); + try + { + renderer.Render(model, new ModelTextures(this, DirectoryOf(resourcePath), texture), _materials, + isStaticObject: false, textureFactory: new UnityTextureFactory(), animateWater: false); + _renderers.Add(renderer); + return renderer; + } + catch + { + renderer.Dispose(); + Object.DestroyImmediate(renderer); + throw; + } + } + + public void ReplaceEnvironment(ResourceEntry geometry, PolFile model, Func surfaceAppearance = null) + { + if (geometry == null || model == null) + throw new ArgumentException("A preview environment requires its original geometry and resource paths."); + GameObject candidate = NewObject("Battle environment " + geometry.Name, Root.transform); + var renderers = new List(); + try + { + var poly = candidate.AddComponent(); + renderers.Add(poly); + poly.Render(model, new ModelTextures(this, DirectoryOf(geometry.Path)), _materials, + isStaticObject: true, textureFactory: new UnityTextureFactory(), animateWater: false, surfaceAppearance: surfaceAppearance); + } + catch + { + foreach (IDisposable renderer in renderers) + renderer.Dispose(); + Object.DestroyImmediate(candidate); + throw; + } + if (_environment != null) + ReleaseCompositeObject(_environment); + _environment = candidate; + _renderers.AddRange(renderers); + } + + public void SetEnvironmentRenderOrder(int order) + { + if (_environment == null) + return; + foreach (Renderer renderer in _environment.GetComponentsInChildren(true)) + renderer.sortingOrder = order; + } + + // Composite objects have no entries in the stand-alone resource sampler. + // Their renderers return materials to the shared owner and release meshes. + public void ReleaseCompositeObject(GameObject target) + { + if (target == null || !target.transform.IsChildOf(Root.transform)) + throw new ArgumentException("The object must belong to this composite preview.", nameof(target)); + DisposeEffects(target); + foreach (MonoBehaviour component in target.GetComponentsInChildren(true)) + if (component is IDisposable renderer && _renderers.Remove(renderer)) + renderer.Dispose(); + Object.DestroyImmediate(target); + } + + private static void DisposeEffects(GameObject root) + { + foreach (EffectPlayer player in root.GetComponentsInChildren(true)) + player.Dispose(); + foreach (PortalEffectPlayer portal in root.GetComponentsInChildren(true)) + portal.Dispose(); + } + } +} diff --git a/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.Environment.cs.meta b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.Environment.cs.meta new file mode 100644 index 00000000..442a14c6 --- /dev/null +++ b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.Environment.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: dcf20f857e9344259d20a19eb52eb1ad diff --git a/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudModels.cs b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudModels.cs new file mode 100644 index 00000000..67030c18 --- /dev/null +++ b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudModels.cs @@ -0,0 +1,52 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.ResourceBrowser +{ + using System; + using Core.DataReader.Cvd; + using Game.Rendering.Renderer; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed partial class ResourceModelPreview + { + // Composite models share this owner's scene, materials and texture cache. + // No camera framing or stand-alone resource animation is performed here. + public CvdModelRenderer SetHierarchicalModel(GameObject target, string resourcePath, CvdFile model) + { + if (Root == null) + throw new ObjectDisposedException(nameof(ResourceModelPreview)); + if (target == null || !target.transform.IsChildOf(Root.transform)) + throw new ArgumentException("The model must belong to this preview.", nameof(target)); + if (model == null) + throw new ArgumentNullException(nameof(model)); + CvdModelRenderer previous = target.GetComponentInChildren(); + GameObject geometry = NewObject("Hierarchical geometry", target.transform); + var renderer = geometry.AddComponent(); + try + { + renderer.Init(model, new ModelTextures(this, DirectoryOf(resourcePath)), _materials); + renderer.SetCurrentTime(0); + } + catch + { + renderer.Dispose(); + Object.DestroyImmediate(geometry); + throw; + } + if (previous != null) + { + _renderers.Remove(previous); + previous.Dispose(); + Object.DestroyImmediate(previous.gameObject); + } + _renderers.Add(renderer); + foreach (Transform child in geometry.GetComponentsInChildren(true)) + child.gameObject.hideFlags = HideFlags.HideAndDontSave; + return renderer; + } + } +} diff --git a/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudModels.cs.meta b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudModels.cs.meta new file mode 100644 index 00000000..40305d21 --- /dev/null +++ b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudModels.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4c54f1db22224eecb31df0d391746780 diff --git a/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudViewport.cs b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudViewport.cs new file mode 100644 index 00000000..8b850cc6 --- /dev/null +++ b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudViewport.cs @@ -0,0 +1,29 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.ResourceBrowser +{ + using UnityEngine; + + public sealed partial class ResourceModelPreview + { + public bool ExpandReferenceFraming + { + get; set; + } + + public void SetViewportContext(Rect viewport) + { + if (viewport.width >= 1 && viewport.height >= 1) + ConfigureCamera(Mathf.CeilToInt(viewport.width), Mathf.CeilToInt(viewport.height), new Rect(0, 0, 1, 1)); + } + + public float ReferenceProjectionScale(Rect viewport) => !_horizontalFieldOfView.HasValue ? viewport.height / 600 : + ExpandReferenceFraming ? Mathf.Min(viewport.width / 800, viewport.height / 600) : viewport.width / 800; + + public static float PreviewVerticalFieldOfView(float nativeHorizontalFieldOfView, float aspect, bool expandReference) => + Camera.HorizontalToVerticalFieldOfView(nativeHorizontalFieldOfView, expandReference ? Mathf.Min(aspect, 4f / 3) : aspect); + } +} diff --git a/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudViewport.cs.meta b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudViewport.cs.meta new file mode 100644 index 00000000..ccc8f53b --- /dev/null +++ b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.HudViewport.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a5dd8ee9ad37499c9b12765ee3402d6b diff --git a/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.cs b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.cs index da90aa02..e0230317 100644 --- a/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.cs +++ b/Assets/Scripts/Editor/ResourceBrowser/ResourceModelPreview.cs @@ -18,8 +18,10 @@ namespace Pal3.ResourceBrowser using Engine.Core.Abstraction; using Engine.Core.Implementation; using Engine.Extensions; + using Engine.Utilities; using Game.Data; using Game.Rendering.Material; + using Game.Rendering.Native; using Game.Rendering.Renderer; using UnityEditor; using UnityEditor.SceneManagement; @@ -29,18 +31,30 @@ namespace Pal3.ResourceBrowser using UnityEngine.SceneManagement; using Object = UnityEngine.Object; - public sealed class ResourceModelPreview : IDisposable + public sealed partial class ResourceModelPreview : IDisposable { private readonly ResourceCatalog _catalog; private readonly Scene _scene; private readonly Camera _camera; private readonly GameMaterialManager _materials; + private readonly Light _toonKey; private readonly Dictionary _textures = new(StringComparer.OrdinalIgnoreCase); private readonly List _renderers = new(); private readonly List> _samplers = new(); private RenderTexture _target; + private RenderTexture _presented; + private Vector2Int _presentedSize; + private readonly DisplayFramePacer _drawPacer = new(); + + public bool LimitToDisplayRefreshRate + { + get; set; + } + private Vector2 _orbit = new(145, 20); private Vector3 _center; + private Quaternion? _cameraOrientation; + private float? _horizontalFieldOfView; private float _distance = 5; private Bounds? _fallbackBounds; @@ -61,25 +75,64 @@ namespace Pal3.ResourceBrowser public Dictionary Dependencies { get; } = new(StringComparer.OrdinalIgnoreCase); - public ResourceModelPreview(ResourceCatalog catalog, bool toon) + public event Action Rendering; + + // Effects which the original renderer submits after its screen-space + // composite draw into the final target without replaying the scene. + public event Action PostComposite; + + public GameBoxNativeLighting NativeLighting => _materials.NativeLighting; + + public bool UsesToonRendering => _materials.UsesToonRendering; + + public IResourcePreviewFrameEffect FrameEffect + { + get; set; + } + + public ResourceModelPreview(ResourceCatalog catalog, bool toon, GameBoxNativeLighting nativeLighting = null) { _catalog = catalog; _scene = EditorSceneManager.NewPreviewScene(); - Root = NewObject("Resource preview"); - var cameraObject = NewObject("Preview camera"); - _camera = cameraObject.AddComponent(); - _camera.enabled = false; - _camera.scene = _scene; - _camera.clearFlags = CameraClearFlags.SolidColor; - _camera.backgroundColor = new Color(0.12f, 0.13f, 0.15f); - _camera.fieldOfView = 40; - _camera.nearClipPlane = 0.01f; - _camera.farClipPlane = 10000; - var light = NewObject("Preview light").AddComponent(); - light.type = LightType.Directional; - light.intensity = 1.2f; - light.transform.rotation = Quaternion.Euler(45, -35, 0); - _materials = new GameMaterialManager(new UnityMaterialFactory(), toon); + try + { + Root = NewObject("Resource preview"); + var cameraObject = NewObject("Preview camera"); + _camera = cameraObject.AddComponent(); + _camera.enabled = false; + _camera.scene = _scene; + _camera.clearFlags = CameraClearFlags.SolidColor; + _camera.backgroundColor = new Color(0.12f, 0.13f, 0.15f); + _camera.fieldOfView = 40; + _camera.aspect = 4f / 3; + _camera.nearClipPlane = 0.01f; + _camera.farClipPlane = 10000; + if (toon) + { + _toonKey = Pal3.Game.Rendering.Toon.ToonLighting.CreateKey(Root.transform, Quaternion.Euler(58, -30, 0), + new Color(1, .94f, .86f), 1, .95f); + Pal3.Game.Rendering.Toon.ToonCameraLighting.AttachPreview(_camera); + } + _materials = new GameMaterialManager(new UnityMaterialFactory(), toon, nativeLighting); + } + catch + { + Dispose(); + throw; + } + } + + public void ConfigureToonLighting(Pal3.Game.Rendering.Toon.ToonLightingProfile profile) + { + profile.Validate(); + if (_toonKey == null) + throw new InvalidOperationException("This preview does not own a Toon key light."); + _toonKey.transform.rotation = profile.Rotation; + _toonKey.color = profile.LightColor; + _toonKey.intensity = profile.Intensity; + _toonKey.shadowStrength = profile.ShadowStrength; + _toonKey.shadows = profile.ShadowStrength > 0 ? LightShadows.Soft : LightShadows.None; + Pal3.Game.Rendering.Toon.ToonCameraLighting.AttachPreview(_camera, profile); } private GameObject NewObject(string name, Transform parent = null) @@ -91,6 +144,80 @@ namespace Pal3.ResourceBrowser return go; } + // Composite previews share the same isolated scene, material pool and texture cache. + public GameObject CreateObject(string name) => NewObject(name, Root.transform); + + public Texture2D GetTexture(string resourcePath) => (Texture2D)new ModelTextures(this, DirectoryOf(resourcePath)).GetTexture(FileName(resourcePath)).NativeObject; + + public Mv3ModelRenderer SetVertexModel(GameObject target, string resourcePath, Mv3File model, + string weaponPath = null, PolFile weapon = null, bool preserveWeaponPresentation = false, string weaponTexture = null) + { + if (target == null || !target.transform.IsChildOf(Root.transform)) + throw new ArgumentException("The model must belong to this preview.", nameof(target)); + var previous = target.GetComponentInChildren(); + GameObject geometry = NewObject("Vertex geometry", target.transform); + var renderer = geometry.AddComponent(); + try + { + renderer.Init(model, _materials, new ModelTextures(this, DirectoryOf(resourcePath)), + tagNodePolFile: weapon, tagNodeTextureProvider: weaponPath == null ? null : new ModelTextures(this, DirectoryOf(weaponPath), weaponTexture), + textureFactory: new UnityTextureFactory(), animateTagWater: false); + renderer.SampleAnimation(0); + if (preserveWeaponPresentation && previous != null) + renderer.MoveWeaponPresentationFrom(previous); + } + catch + { + renderer.Dispose(); + Object.DestroyImmediate(geometry); + throw; + } + if (previous != null) + { + _renderers.Remove(previous); + previous.Dispose(); + Object.DestroyImmediate(previous.gameObject); + } + _renderers.Add(renderer); + foreach (Transform child in target.GetComponentsInChildren(true)) + child.gameObject.hideFlags = HideFlags.HideAndDontSave; + return renderer; + } + + public void SetCamera(Vector3 position, Vector3 target, float fieldOfView) + { + _cameraOrientation = null; + _horizontalFieldOfView = null; + _center = target; + _distance = Mathf.Max(0.05f, Vector3.Distance(position, target)); + Vector3 angles = Quaternion.LookRotation(target - position).eulerAngles; + _orbit = new Vector2(angles.y, angles.x); + _camera.fieldOfView = fieldOfView; + } + + public void SetCameraOrientation(Vector3 position, Vector3 forward, Vector3 up, float fieldOfView) + { + SetCamera(position, position + forward.normalized * _distance, fieldOfView); + _cameraOrientation = Quaternion.LookRotation(forward, up); + } + + // GameBox describes the horizontal frustum angle, whereas Unity stores + // its vertical angle. Keep the original angle until the viewport is known. + public void SetHorizontalCameraOrientation(Vector3 position, Vector3 forward, Vector3 up, float fieldOfView) + { + SetCameraOrientation(position, forward, up, Camera.HorizontalToVerticalFieldOfView(fieldOfView, _camera.aspect)); + _horizontalFieldOfView = fieldOfView; + } + + public float HorizontalFieldOfView => _horizontalFieldOfView ?? Camera.VerticalToHorizontalFieldOfView(_camera.fieldOfView, _camera.aspect); + + public void GetCamera(out Vector3 position, out Vector3 target, out float fieldOfView) + { + target = _center; + position = _center + (_cameraOrientation ?? Quaternion.Euler(_orbit.y, _orbit.x, 0)) * new Vector3(0, 0, -_distance); + fieldOfView = _camera.fieldOfView; + } + public void Load(ResourceEntry entry, object decoded) { GameObject go = NewObject(entry.Name, Root.transform); @@ -174,19 +301,22 @@ namespace Pal3.ResourceBrowser { private readonly ResourceModelPreview _owner; private readonly string _directory; + private readonly string _replacement; - public ModelTextures(ResourceModelPreview owner, string directory) + public ModelTextures(ResourceModelPreview owner, string directory, string replacement = null) { _owner = owner; _directory = directory; + _replacement = replacement; } - public string GetTexturePath(string name) => CombinePath(_directory, name); + public string GetTexturePath(string name) => CombinePath(_directory, _replacement ?? name); public ITexture2D GetTexture(string name) => GetTexture(name, out _); public ITexture2D GetTexture(string name, out bool hasAlphaChannel) { + name = _replacement ?? name; if (string.IsNullOrEmpty(name)) { hasAlphaChannel = false; @@ -242,6 +372,7 @@ namespace Pal3.ResourceBrowser public void Frame() { + _cameraOrientation = null; Renderer[] renderers = Root.GetComponentsInChildren(); Bounds bounds = renderers.Length > 0 ? renderers[0].bounds : (_fallbackBounds ?? new Bounds(Vector3.zero, Vector3.one)); foreach (Renderer renderer in renderers) @@ -260,6 +391,12 @@ namespace Pal3.ResourceBrowser Frame(); } + public Ray ScreenRay(Vector2 point, Rect viewport) + { + return _camera.ViewportPointToRay(new Vector3((point.x - viewport.x) / viewport.width, + 1 - (point.y - viewport.y) / viewport.height, 0)); + } + public bool Project(Vector3 world, Rect view, out Vector2 screen) { Vector3 point = _camera.WorldToViewportPoint(world); @@ -267,17 +404,28 @@ namespace Pal3.ResourceBrowser return point.z > 0; } - public void Draw(Rect rect) + // Combat UI coordinates use a fixed reference canvas. Configure the + // current pose here as captures can occur before the next editor repaint. + public Vector2 ProjectReference(Vector3 world, int width, int height) { - Event e = Event.current; - if (rect.Contains(e.mousePosition)) + ConfigureCamera(width, height, new Rect(0, 0, 1, 1)); + Vector3 point = _camera.WorldToViewportPoint(world); + return new Vector2(point.x * width, (1 - point.y) * height); + } + + private void HandleCameraInput(Event e, Rect rect, bool allowCameraInput) + { + if (allowCameraInput && rect.Contains(e.mousePosition)) { if (e.type == EventType.MouseDrag) { if (e.button == 2 || e.shift) _center += (_camera.transform.right * -e.delta.x + _camera.transform.up * e.delta.y) * (_distance / 600); else if (e.button == 0) + { + _cameraOrientation = null; _orbit += e.delta * new Vector2(0.5f, -0.5f); + } e.Use(); } if (e.type == EventType.ScrollWheel) @@ -285,25 +433,62 @@ namespace Pal3.ResourceBrowser _distance = Mathf.Clamp(_distance * Mathf.Exp(e.delta.y * 0.06f), 0.05f, 5000); e.Use(); } - if (e.type == EventType.KeyDown && e.keyCode == KeyCode.F) + if (e.type == EventType.KeyDown && e.keyCode == KeyCode.F && (e.modifiers & (EventModifiers.Command | EventModifiers.Control | EventModifiers.Alt)) == 0) { Frame(); e.Use(); } } + } + + public void Draw(Rect rect, bool allowCameraInput = true) + { + Event e = Event.current; + HandleCameraInput(e, rect, allowCameraInput); if (e.type != EventType.Repaint || rect.width < 2 || rect.height < 2) return; - GUI.DrawTexture(rect, Render(Mathf.CeilToInt(rect.width), Mathf.CeilToInt(rect.height)), ScaleMode.StretchToFill, false); + float pixels = EditorGUIUtility.pixelsPerPoint; + var size = new Vector2Int(Mathf.CeilToInt(rect.width * pixels), Mathf.CeilToInt(rect.height * pixels)); + bool due = _drawPacer.TryAdvance(EditorApplication.timeSinceStartup, DisplayFrameRate.RefreshRate); + if (!LimitToDisplayRefreshRate || due || _presented == null || _presentedSize != size) + { + _presented = Render(size.x, size.y); + _presentedSize = size; + } + GUI.DrawTexture(rect, _presented, ScaleMode.StretchToFill, false); } public RenderTexture Render(int width, int height) { - EnsureTarget(width, height); - _camera.transform.position = _center + Quaternion.Euler(_orbit.y, _orbit.x, 0) * new Vector3(0, 0, -_distance); - _camera.transform.LookAt(_center); - _camera.aspect = (float)width / height; - RenderPipeline.SubmitRenderRequest(_camera, new UniversalRenderPipeline.SingleCameraRequest { destination = _target }); - return _target; + Vector2Int size = FrameEffect?.TargetSize(width, height) ?? new Vector2Int(width, height); + EnsureTarget(size.x, size.y); + // Projection belongs to the presented image; the history viewport + // only packs that image into its fixed native render texture. + ConfigureCamera(width, height, FrameEffect?.Viewport ?? new Rect(0, 0, 1, 1)); + RenderTexture output; + try + { + Rendering?.Invoke(_camera); + NativeLighting?.Apply(_camera); + RenderPipeline.SubmitRenderRequest(_camera, new UniversalRenderPipeline.SingleCameraRequest { destination = _target }); + output = FrameEffect?.Composite(_target, width, height) ?? _target; + } + finally + { + _camera.rect = new Rect(0, 0, 1, 1); + } + PostComposite?.Invoke(_camera, output); + return output; + } + + private void ConfigureCamera(int width, int height, Rect viewport) + { + Quaternion orientation = _cameraOrientation ?? Quaternion.Euler(_orbit.y, _orbit.x, 0); + _camera.transform.SetPositionAndRotation(_center + orientation * new Vector3(0, 0, -_distance), orientation); + _camera.rect = viewport; + _camera.aspect = width / (float)height; + if (_horizontalFieldOfView.HasValue) + _camera.fieldOfView = PreviewVerticalFieldOfView(_horizontalFieldOfView.Value, _camera.aspect, ExpandReferenceFraming); } private void EnsureTarget(int width, int height) @@ -321,6 +506,8 @@ namespace Pal3.ResourceBrowser public void Dispose() { + if (Root != null) + DisposeEffects(Root); // Capture partially initialized resources too: runtime renderers may not yet be IsInitialized. Mesh[] meshes = Root != null ? Root.GetComponentsInChildren().Select(m => m.sharedMesh).Where(m => m != null).Distinct().ToArray() : Array.Empty(); Material[] materials = Root != null ? Root.GetComponentsInChildren().SelectMany(r => r.sharedMaterials).Where(m => m != null).Distinct().ToArray() : Array.Empty(); @@ -328,9 +515,12 @@ namespace Pal3.ResourceBrowser renderer.Dispose(); _renderers.Clear(); _samplers.Clear(); + Rendering = null; + PostComposite = null; + FrameEffect = null; if (Root != null) Object.DestroyImmediate(Root); - _materials.Dispose(); + _materials?.Dispose(); foreach (Mesh mesh in meshes) if (mesh != null) Object.DestroyImmediate(mesh); diff --git a/Assets/Scripts/Engine/Core/Implementation/UnityTextureFactory.cs b/Assets/Scripts/Engine/Core/Implementation/UnityTextureFactory.cs index 5fcab665..325abd04 100644 --- a/Assets/Scripts/Engine/Core/Implementation/UnityTextureFactory.cs +++ b/Assets/Scripts/Engine/Core/Implementation/UnityTextureFactory.cs @@ -8,6 +8,7 @@ namespace Engine.Core.Implementation using System; using System.Buffers; using Abstraction; + using Engine.Extensions; using UnityEngine; using UnityEngine.Experimental.Rendering; @@ -84,7 +85,8 @@ namespace Engine.Core.Implementation } catch { - if (texture != null) UnityEngine.Object.Destroy(texture); + if (texture != null) + texture.Destroy(); throw; } } diff --git a/Assets/Scripts/Engine/Utilities/DisplayFrameRate.cs b/Assets/Scripts/Engine/Utilities/DisplayFrameRate.cs new file mode 100644 index 00000000..f7277eaa --- /dev/null +++ b/Assets/Scripts/Engine/Utilities/DisplayFrameRate.cs @@ -0,0 +1,49 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Engine.Utilities +{ + using System; + using UnityEngine; + + public static class DisplayFrameRate + { + public static double RefreshRate => ValidRefreshRate(Screen.currentResolution.refreshRateRatio.value); + + public static double ValidRefreshRate(double refreshRate) => + double.IsFinite(refreshRate) && refreshRate >= 1 && refreshRate <= int.MaxValue ? refreshRate : 60; + + // Desktop and Web ignore the software target while v-sync is active. + public static int VSyncForLimit(int configured, int requested, double refreshRate) => + configured > 0 && requested > 0 && ValidRefreshRate(refreshRate) / configured > requested ? 0 : configured; + + // Unity's target is integral; flooring keeps it at or below fractional + // display rates too. Lower user limits remain valid. + public static int Limit(int requested, double refreshRate) + { + int maximum = (int)ValidRefreshRate(refreshRate); + return requested > 0 ? Math.Min(requested, maximum) : maximum; + } + } + + // A presentation clock only: simulation and audio must advance separately. + public sealed class DisplayFramePacer + { + private double _lastFrame = double.NegativeInfinity; + + public bool TryAdvance(double now, double refreshRate) + { + if (!double.IsFinite(now)) + return false; + // Floating-point rounding must not defer a callback that arrives + // exactly one display period after the previous frame. + const double timestampTolerance = 1e-9; + if (now >= _lastFrame && now - _lastFrame + timestampTolerance < 1 / DisplayFrameRate.ValidRefreshRate(refreshRate)) + return false; + _lastFrame = now; + return true; + } + } +} diff --git a/Assets/Scripts/Engine/Utilities/DisplayFrameRate.cs.meta b/Assets/Scripts/Engine/Utilities/DisplayFrameRate.cs.meta new file mode 100644 index 00000000..01d242ea --- /dev/null +++ b/Assets/Scripts/Engine/Utilities/DisplayFrameRate.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cf4d83ab05194fb28fcc15382b65fd8d diff --git a/Assets/Scripts/Pal3.Battle.meta b/Assets/Scripts/Pal3.Battle.meta new file mode 100644 index 00000000..a0e3e0dd --- /dev/null +++ b/Assets/Scripts/Pal3.Battle.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 70a274ed56df146169013ad19c8a3ac5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Battle/Configuration.meta b/Assets/Scripts/Pal3.Battle/Configuration.meta new file mode 100644 index 00000000..2f5196fc --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Configuration.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c110567d20604a4c930e7cacad9dfe80 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Battle/Configuration/BattleScenario.cs b/Assets/Scripts/Pal3.Battle/Configuration/BattleScenario.cs new file mode 100644 index 00000000..6c12b4a2 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Configuration/BattleScenario.cs @@ -0,0 +1,352 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public enum BattleSide + { + Ally, + Enemy, + } + + public enum BattleSlot + { + Water, + Fire, + Wind, + Thunder, + Earth, + Center, + } + + public enum BattleEncounter + { + Normal, + AllyAmbush, + EnemyAmbush, + } + + public enum BattleAttributeSource + { + ExplicitEffective, + BaseWithEquipment, + LevelGrowth, + } + + // Authoring contracts contain resource IDs and explicit values, never engine objects. + // Level and loadout are inputs; generating their derived values belongs to a verified ruleset. + [Serializable] + public sealed class BattleScenario + { + public const int CurrentVersion = 1; + + public int Version = CurrentVersion; + public string Variant = "PAL3"; + public string DataFingerprint = ""; + public string Scene = ""; + public int SceneElement; + public int FiveSpiritElement; + public int FiveSpiritForce; + public string EnemyAiIgnoredActor = ""; + public string Music = ""; + public int Seed = 1; + public int RoundLimit = -1; + public bool ScriptBattle; + public bool MustFail; + public bool GameOverOnDefeat = true; + public int Money; + public BattleEncounter Encounter; + public bool ToonRendering = true; + public bool MotionBlur = true; + public BattlePal3AState Pal3A = new(); + public BattleCamera Camera = new(); + public List Participants = new(); + public List Items = new(); + public List TreasureUses = new(); + + public BattleScenario Copy() + { + var copy = (BattleScenario)MemberwiseClone(); + copy.Participants = Participants?.Select(actor => actor?.Copy()).ToList(); + copy.Items = Items?.Select(item => item?.Copy()).ToList(); + copy.TreasureUses = TreasureUses?.Select(item => item?.Copy()).ToList(); + copy.Camera = Camera?.Copy(); + copy.Pal3A = Pal3A?.Copy(); + return copy; + } + + public List Validate() + { + var errors = new List(); + if (Version != CurrentVersion) + errors.Add($"Unsupported scenario version {Version}; expected {CurrentVersion}."); + if (Variant is not ("PAL3" or "PAL3A")) + errors.Add("Select PAL3 or PAL3A."); + if (string.IsNullOrWhiteSpace(Scene)) + errors.Add("Select a combat scene."); + if (SceneElement < 0 || SceneElement > 5 || !Enum.IsDefined(typeof(BattleEncounter), Encounter)) + errors.Add("Invalid scene element or encounter type."); + if (FiveSpiritElement < 0 || FiveSpiritElement > 5 || FiveSpiritForce < 0 || FiveSpiritForce > 2) + errors.Add("Invalid original five-spirit field element or force."); + if (Variant == "PAL3A") + { + try + { + (Pal3A ?? throw new ArgumentException("PAL3A needs its original resource snapshot.")).Validate(); + } + catch (ArgumentException exception) + { + errors.Add(exception.Message); + } + } + if (Money < 0 || RoundLimit < -1) + errors.Add("Money must be nonnegative; round limit must be -1 or nonnegative."); + if (Camera == null || !Camera.Position.IsFinite || !Camera.Target.IsFinite || + !float.IsFinite(Camera.FieldOfView) || Camera.FieldOfView < 1 || Camera.FieldOfView > 120) + errors.Add("Camera needs finite positions and a field of view between 1 and 120."); + else if (Camera.Override && Camera.Position.X == Camera.Target.X && Camera.Position.Y == Camera.Target.Y && Camera.Position.Z == Camera.Target.Z) + errors.Add("Camera position and target must differ."); + if (Participants == null || Items == null || TreasureUses == null) + { + errors.Add("Participant and item collections must be present."); + return errors; + } + var ids = new HashSet(StringComparer.Ordinal); + var slots = new HashSet<(BattleSide, BattleSlot)>(); + foreach (BattleParticipant actor in Participants) + { + if (actor == null) + { + errors.Add("A participant is missing."); + continue; + } + string label = $"Actor {actor.ActorId} ({actor.InstanceId})"; + if (string.IsNullOrWhiteSpace(actor.InstanceId) || !ids.Add(actor.InstanceId)) + errors.Add(label + ": instance ID must be present and unique."); + if (actor.ActorId <= 0 || actor.Level < 1 || actor.Level > 100 || actor.Experience < 0 || actor.Love < 0 || actor.Love > 999) + errors.Add(label + ": invalid actor ID, level or experience."); + if (!Enum.IsDefined(typeof(BattleAttributeSource), actor.AttributeSource)) + errors.Add(label + ": invalid attribute source."); + if (!Enum.IsDefined(typeof(BattleSide), actor.Side) || !Enum.IsDefined(typeof(BattleSlot), actor.Slot)) + errors.Add(label + ": invalid side or slot."); + else if (!slots.Add((actor.Side, actor.Slot))) + errors.Add(label + ": another participant occupies this slot."); + if (actor.Attributes == null || actor.Attributes.Length != 12 || actor.Attributes.Any(value => value < 0)) + errors.Add(label + ": provide 12 nonnegative explicit attributes."); + if (actor.Vitals == null || actor.Vitals.Length != 3 || actor.Vitals.Any(value => value < 0) || + actor.AttributeSource == BattleAttributeSource.ExplicitEffective && actor.Attributes is { Length: 12 } && actor.Vitals is { Length: 3 } && + Enumerable.Range(0, 3).Any(index => actor.Vitals[index] > actor.Attributes[index])) + errors.Add(label + ": current vitals must be between zero and their explicit maxima."); + var skillIds = new HashSet(); + var stateIds = new HashSet(); + foreach (BattleStatus state in actor.Statuses ?? new List()) + { + if (state == null) + { + errors.Add(label + ": a configured initial status is missing."); + continue; + } + if (!stateIds.Add(state.Id)) + errors.Add(label + ": initial status IDs must be unique."); + if (!BattleStatusRules.SupportsInitialState((BattleState)state.Id)) + errors.Add(label + $": status {state.Id} is not supported as an initial status."); + } + var magicSlots = new HashSet<(int Group, int Slot)>(); + foreach (BattleSkill skill in actor.Skills ?? new List()) + { + if (skill == null) + { + errors.Add(label + ": a configured initial skill is missing."); + continue; + } + if (!skillIds.Add(skill.Id)) + errors.Add(label + ": skill IDs must be unique."); + bool specified = skill.NativeMagicGroup != -1 || skill.NativeMagicSlot != -1; + if (specified && (skill.NativeMagicGroup < 0 || skill.NativeMagicGroup >= 6 || skill.NativeMagicSlot < 0 || + skill.NativeMagicSlot >= (Variant == "PAL3A" ? 9 : 8))) + errors.Add(label + ": native magic group and slot must both be specified within the original six-group layout."); + else if (specified && !magicSlots.Add((skill.NativeMagicGroup, skill.NativeMagicSlot))) + errors.Add(label + ": multiple skills occupy the same native magic slot."); + } + if (actor.MagicSword != null) + { + if (Variant != "PAL3" || actor.Equipment is not { Length: > 0 } || actor.Equipment[0] != BattleMagicSwordRules.WeaponId) + errors.Add(label + ": a magic sword snapshot requires PAL3 weapon 6603."); + try + { + _ = actor.MagicSword.Capture(); + } + catch (ArgumentException) + { + errors.Add(label + ": invalid magic sword cultivation or energy snapshot."); + } + } + else if (actor.Equipment is { Length: > 0 } && actor.Equipment[0] == BattleMagicSwordRules.WeaponId && + !(BattleLoadoutRules.IsNativeDefaultWeapon(Variant, actor) && BattleLoadoutRules.PlayerIdentity(Variant, actor.ActorId) != 0)) + errors.Add(label + ": weapon 6603 requires its captured cultivation and energy."); + if (actor.UsesNativeDefaultWeapon && !BattleLoadoutRules.IsNativeDefaultWeapon(Variant, actor)) + errors.Add(label + ": the native default weapon provenance does not match this actor or item."); + if (!actor.Position.IsFinite) + errors.Add(label + ": position must be finite."); + int maximumSkillUses = Variant == "PAL3A" ? ushort.MaxValue : byte.MaxValue; + if (actor.Skills?.Any(skill => skill != null && skill.Uses > maximumSkillUses) == true) + errors.Add(label + $": initial skill use counts must not exceed {maximumSkillUses} for {Variant}."); + if (actor.Skills == null || actor.Statuses == null || actor.Equipment == null || + actor.Equipment.Any(id => id < 0) || + actor.Skills?.Any(skill => skill == null || skill.Id <= 0 || skill.Level < 1 || skill.Level > 10 || skill.Uses < 0) == true || + actor.Statuses?.Any(state => state == null || state.Id < 0 || state.Rounds < 1) == true) + errors.Add(label + ": invalid skills, statuses or equipment."); + } + if (!string.IsNullOrEmpty(EnemyAiIgnoredActor) && !Participants.Any(actor => actor != null && actor.InstanceId == EnemyAiIgnoredActor && actor.Side == BattleSide.Ally)) + errors.Add("The actor ignored by enemy AI must be an allied participant."); + foreach (BattleSide side in Enum.GetValues(typeof(BattleSide))) + { + int count = Participants.Count(actor => actor != null && actor.Side == side); + if (count == 0 || count > (side == BattleSide.Ally ? 4 : 6)) + errors.Add(side + ": configure 1–" + (side == BattleSide.Ally ? 4 : 6) + " participants."); + } + if (Items.Any(item => item == null || item.Id <= 0 || item.Count < 1) || + Items.Where(item => item != null).GroupBy(item => item.Id).Any(group => group.Count() > 1)) + errors.Add("Items need unique positive IDs and positive quantities."); + if (TreasureUses.Any(item => item == null || Variant is not ("PAL3" or "PAL3A") || !BattleSpecialRules.IsTreasure(Variant, item.Id) || item.Count < 0 || item.Count > byte.MaxValue) || + TreasureUses.Where(item => item != null).GroupBy(item => item.Id).Any(group => group.Count() > 1)) + errors.Add("Treasure use counters need unique valid treasure IDs and quantities between 0 and 255."); + return errors; + } + } + + [Serializable] + public sealed class BattleCamera + { + public bool Override; + public BattlePoint Position; + public BattlePoint Target; + public float FieldOfView = 39; + + public BattleCamera Copy() => (BattleCamera)MemberwiseClone(); + } + + [Serializable] + public struct BattlePoint + { + public float X; + public float Y; + public float Z; + + public bool IsFinite => !float.IsNaN(X) && !float.IsInfinity(X) && + !float.IsNaN(Y) && !float.IsInfinity(Y) && !float.IsNaN(Z) && !float.IsInfinity(Z); + } + + [Serializable] + public sealed class BattleParticipant + { + // Allocate once for a new participant. Copies keep this ID, even after a + // slot swap, so inputs and replays can keep addressing the same actor. + public string InstanceId = Guid.NewGuid().ToString("N"); + public int ActorId; + public BattleSide Side; + public BattleSlot Slot; + public string Model = ""; + public int Level = 1; + public int Experience; + public int Love; + public BattleAttributeSource AttributeSource; + public int[] Attributes = new int[12]; + public int[] Vitals = new int[3]; + public int[] Equipment = new int[6]; + public bool UsesNativeDefaultWeapon; + public BattleMagicSword MagicSword; + public List Skills = new(); + public List Statuses = new(); + public bool OverridePosition; + public BattlePoint Position; + + public BattleParticipant Copy() + { + var copy = (BattleParticipant)MemberwiseClone(); + copy.Attributes = Attributes?.ToArray(); + copy.Vitals = Vitals?.ToArray(); + copy.Equipment = Equipment?.ToArray(); + copy.MagicSword = MagicSword?.Copy(); + copy.Skills = Skills?.Select(skill => skill?.Copy()).ToList(); + copy.Statuses = Statuses?.Select(state => state?.Copy()).ToList(); + return copy; + } + } + + // Per-instance authoring input. The released game has one sword; test actors never share its mutable gauge. + [Serializable] + public sealed class BattleMagicSword + { + public int AttackBonus = 35; + public BattleSwordPurificationElement SelectedElement = BattleSwordPurificationElement.Wind; + public int PurificationCount; + public int SkillId = 2224; + public uint ChargeCoefficient = 10; + public float Energy; + + public BattleMagicSwordSnapshot Capture() + { + if (SkillId != 0 && !BattleMagicSwordRules.IsSupportedSkill(SkillId)) + throw new ArgumentOutOfRangeException(nameof(SkillId)); + return new BattleMagicSwordSnapshot(AttackBonus, SelectedElement, PurificationCount, SkillId, ChargeCoefficient, Energy); + } + + public BattleMagicSword Copy() => (BattleMagicSword)MemberwiseClone(); + } + + [Serializable] + public sealed class BattleSkill + { + public int Id; + public int Level = 1; + public int Uses; + public bool Mastered; + public int NativeMagicGroup = -1; + public int NativeMagicSlot = -1; + + public BattleSkill Copy() => (BattleSkill)MemberwiseClone(); + } + + [Serializable] + public sealed class BattleStatus + { + public int Id; + public int Rounds = 1; + + public BattleStatus Copy() => (BattleStatus)MemberwiseClone(); + } + + [Serializable] + public sealed class BattleItem + { + public int Id; + public int Count = 1; + + public BattleItem Copy() => (BattleItem)MemberwiseClone(); + } + + // Each start/reset gets its own deep copy. Nothing writable escapes the captured initial state. + public sealed class BattleSetup + { + private readonly BattleScenario _initial; + + public BattleSetup(BattleScenario scenario) + { + if (scenario == null) + throw new ArgumentNullException(nameof(scenario)); + List errors = scenario.Validate(); + if (errors.Count > 0) + throw new ArgumentException(string.Join("\n", errors), nameof(scenario)); + _initial = scenario.Copy(); + } + + public BattleScenario CreateInstance() => _initial.Copy(); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Configuration/BattleScenario.cs.meta b/Assets/Scripts/Pal3.Battle/Configuration/BattleScenario.cs.meta new file mode 100644 index 00000000..4d29e504 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Configuration/BattleScenario.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2df050c07caf643d7837b69df8cd8421 \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Battle/Contracts.meta b/Assets/Scripts/Pal3.Battle/Contracts.meta new file mode 100644 index 00000000..75fc2116 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 9e27a17dfa6d4f3c86bdf2a77e04a048 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleAbilityDefinition.cs b/Assets/Scripts/Pal3.Battle/Contracts/BattleAbilityDefinition.cs new file mode 100644 index 00000000..5cde5443 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleAbilityDefinition.cs @@ -0,0 +1,243 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + // Mutable assembly inputs are consumed once; definitions capture their own immutable collections. + public sealed class BattleAbilityData + { + public int Id; + public string Name = ""; + public bool IsMagic; + public int SkillTypeId = -1; + public int AiNullCureOperation; + public bool IsItem; + public bool IsTreasure; + public bool BattleUsable = true; + public BattleTargetRange Range; + public int ElementMask; + public int SuccessRate = 100; + public int SpellRank = 1; + public int LearningLevel = 1; + public int NextSkillId; + public int NextSkillRequiredProficiency; + public int[] UsesBeforeLevelUp = Array.Empty(); + public BattleAttributeEffect[] Attributes = Array.Empty(); + public BattleStatusEffect[] States = Array.Empty(); + public BattleCost[] Costs = Array.Empty(); + public int[] ApplicableIdentities = Array.Empty(); + public string UnsupportedReason = ""; + public int SpecialEffect; + public BattleSpecialHandler Handler; + public int ItemType; + public BattleSkillUnlock[] Unlocks = Array.Empty(); + } + + public sealed class BattleAbilityDefinition + { + public int Id + { + get; + } + + public string Name + { + get; + } + + public bool IsMagic + { + get; + } + + public int SkillTypeId + { + get; + } + + public int AiNullCureOperation + { + get; + } + + public bool IsItem + { + get; + } + + public bool IsTreasure + { + get; + } + + public bool BattleUsable + { + get; + } + + public BattleTargetRange Range + { + get; + } + + public int ElementMask + { + get; + } + + public int SuccessRate + { + get; + } + + public int SpellRank + { + get; + } + + public int LearningLevel + { + get; + } + + public int NextSkillId + { + get; + } + + public int NextSkillRequiredProficiency + { + get; + } + + public IReadOnlyList UsesBeforeLevelUp + { + get; + } + + public IReadOnlyList Attributes + { + get; + } + + public IReadOnlyList States + { + get; + } + + public IReadOnlyList Costs + { + get; + } + + public IReadOnlyList ApplicableIdentities + { + get; + } + + public string UnsupportedReason + { + get; + } + + public int SpecialEffect + { + get; + } + + public BattleSpecialHandler Handler + { + get; + } + + public int ItemType + { + get; + } + + public IReadOnlyList Unlocks + { + get; + } + + public bool Revives => States.Any(state => state.State == BattleState.Death && state.Remove); + + public bool Supported => string.IsNullOrEmpty(UnsupportedReason); + + public BattleAbilityDefinition(BattleAbilityData data) + { + if (data == null || data.Id <= 0) + throw new ArgumentException("An ability needs a positive resource ID."); + Id = data.Id; + Name = data.Name ?? ""; + IsMagic = data.IsMagic; + SkillTypeId = data.SkillTypeId; + AiNullCureOperation = data.AiNullCureOperation; + IsItem = data.IsItem; + IsTreasure = data.IsTreasure; + BattleUsable = data.BattleUsable; + Range = data.Range; + ElementMask = data.ElementMask; + SuccessRate = data.SuccessRate; + SpellRank = data.SpellRank; + LearningLevel = data.LearningLevel; + NextSkillId = data.NextSkillId; + NextSkillRequiredProficiency = data.NextSkillRequiredProficiency; + UsesBeforeLevelUp = Capture(data.UsesBeforeLevelUp); + Attributes = Capture(data.Attributes); + States = Capture(data.States); + Costs = Capture(data.Costs); + ApplicableIdentities = Capture(data.ApplicableIdentities); + UnsupportedReason = data.UnsupportedReason ?? ""; + SpecialEffect = data.SpecialEffect; + Handler = data.Handler; + ItemType = data.ItemType; + Unlocks = Capture(data.Unlocks); + } + + internal static IReadOnlyList Capture(IEnumerable values) => Array.AsReadOnly(values?.ToArray() ?? Array.Empty()); + } + + public readonly struct BattleSkillUnlock + { + public int SkillId + { + get; + } + + public int OtherSkillId + { + get; + } + + public int OtherTier + { + get; + } + + public int SelfTier + { + get; + } + + public int ActorLevel + { + get; + } + + public BattleSkillUnlock(int skillId, int otherSkillId, int otherTier, int selfTier, int actorLevel) + { + SkillId = skillId; + OtherSkillId = otherSkillId; + OtherTier = otherTier; + SelfTier = selfTier; + ActorLevel = actorLevel; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleAbilityDefinition.cs.meta b/Assets/Scripts/Pal3.Battle/Contracts/BattleAbilityDefinition.cs.meta new file mode 100644 index 00000000..182053f6 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleAbilityDefinition.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 280d001801b8449dbb6a5a7c51807663 diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleActorDefinition.cs b/Assets/Scripts/Pal3.Battle/Contracts/BattleActorDefinition.cs new file mode 100644 index 00000000..76f6028a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleActorDefinition.cs @@ -0,0 +1,236 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleActorData + { + public string InstanceId; + public int Identity = -1; + public BattleMagicSwordSnapshot MagicSword; + public bool Boss; + public BattleEquipmentDefinition[] Equipment = Array.Empty(); + public BattleState[] ImmuneStates = Array.Empty(); + public BattleState[] PermanentStates = Array.Empty(); + public BattleState[] InitialStates = Array.Empty(); + public int PhysicalAttackElements; + public int PhysicalDefenseElements; + public int[] PhysicalAttackElementValues = new int[5]; + public int[] PhysicalDefenseElementValues = new int[5]; + public int NormalAttackMode; + public BattleTargetRange NormalAttackRange = BattleTargetRange.OpponentSingle; + public int ExperienceReward; + public int MoneyReward; + public int LootItem; + public int LootCount; + public int CorpseItem; + public int CorpseSkill; + public int CorpsePercent; + public int EscapePercent; + public int StealableMoney; + public int StealableItemId; + public int StealableItemCount; + public bool MoneyShield; + public int[] ExperienceThresholds = Array.Empty(); + public int[][] AttributesByLevel = Array.Empty(); + public string GrowthUnsupportedReason = ""; + public string UnsupportedReason = ""; + } + + public sealed class BattleActorDefinition + { + public string InstanceId + { + get; + } + + public int Identity + { + get; + } + + public bool Boss + { + get; + } + + public BattleMagicSwordSnapshot MagicSword + { + get; + } + + public IReadOnlyList Equipment + { + get; + } + + public IReadOnlyList ImmuneStates + { + get; + } + + public IReadOnlyList PermanentStates + { + get; + } + + public IReadOnlyList InitialStates + { + get; + } + + public int PhysicalAttackElements + { + get; + } + + public int PhysicalDefenseElements + { + get; + } + + public IReadOnlyList PhysicalAttackElementValues + { + get; + } + + public IReadOnlyList PhysicalDefenseElementValues + { + get; + } + + public int NormalAttackMode + { + get; + } + + public BattleTargetRange NormalAttackRange + { + get; + } + + public int ExperienceReward + { + get; + } + + public int MoneyReward + { + get; + } + + public int LootItem + { + get; + } + + public int LootCount + { + get; + } + + public int CorpseItem + { + get; + } + + public int CorpseSkill + { + get; + } + + public int CorpsePercent + { + get; + } + + public int EscapePercent + { + get; + } + + public int StealableMoney + { + get; + } + + public int StealableItemId + { + get; + } + + public int StealableItemCount + { + get; + } + + public bool MoneyShield + { + get; + } + + public IReadOnlyList ExperienceThresholds + { + get; + } + + public IReadOnlyList> AttributesByLevel + { + get; + } + + public string GrowthUnsupportedReason + { + get; + } + + public string UnsupportedReason + { + get; + } + + public BattleActorDefinition(BattleActorData data) + { + if (data == null || string.IsNullOrWhiteSpace(data.InstanceId)) + throw new ArgumentException("Missing actor instance ID."); + if (data.StealableMoney < 0 || data.StealableItemId < 0 || data.StealableItemCount < 0) + throw new ArgumentException("Invalid initial stealable pool."); + InstanceId = data.InstanceId; + Identity = data.Identity; + MagicSword = data.MagicSword; + Boss = data.Boss; + Equipment = BattleAbilityDefinition.Capture(data.Equipment); + ImmuneStates = BattleAbilityDefinition.Capture(data.ImmuneStates); + PermanentStates = BattleAbilityDefinition.Capture(data.PermanentStates); + InitialStates = BattleAbilityDefinition.Capture(data.InitialStates); + PhysicalAttackElements = data.PhysicalAttackElements; + PhysicalDefenseElements = data.PhysicalDefenseElements; + PhysicalAttackElementValues = BattleAbilityDefinition.Capture(data.PhysicalAttackElementValues); + PhysicalDefenseElementValues = BattleAbilityDefinition.Capture(data.PhysicalDefenseElementValues); + NormalAttackMode = data.NormalAttackMode; + NormalAttackRange = data.NormalAttackRange; + ExperienceReward = data.ExperienceReward; + MoneyReward = data.MoneyReward; + LootItem = data.LootItem; + LootCount = data.LootCount; + CorpseItem = data.CorpseItem; + CorpseSkill = data.CorpseSkill; + CorpsePercent = data.CorpsePercent; + EscapePercent = data.EscapePercent; + StealableMoney = data.StealableMoney; + StealableItemId = data.StealableItemId; + StealableItemCount = data.StealableItemCount; + MoneyShield = data.MoneyShield; + ExperienceThresholds = BattleAbilityDefinition.Capture(data.ExperienceThresholds); + AttributesByLevel = Array.AsReadOnly((data.AttributesByLevel ?? Array.Empty()).Select(values => BattleAbilityDefinition.Capture(values)).ToArray()); + GrowthUnsupportedReason = data.GrowthUnsupportedReason ?? ""; + UnsupportedReason = data.UnsupportedReason ?? ""; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleActorDefinition.cs.meta b/Assets/Scripts/Pal3.Battle/Contracts/BattleActorDefinition.cs.meta new file mode 100644 index 00000000..ecac884a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleActorDefinition.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e0a47667938649428336cab1a68cbb4e diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleActorSnapshot.cs b/Assets/Scripts/Pal3.Battle/Contracts/BattleActorSnapshot.cs new file mode 100644 index 00000000..99f6d1e8 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleActorSnapshot.cs @@ -0,0 +1,246 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleActorSnapshot + { + public int ActorId + { + get; internal set; + } + + public int NativeIndex + { + get; internal set; + } + + public int CorpseItem + { + get; internal set; + } + + public int Love + { + get; internal set; + } + + public long NativePresentationTick + { + get; internal set; + } + + public float NativePlaybackRate + { + get; internal set; + } + + public float WeaponTrailSeconds + { + get; internal set; + } + + public float? NativeAnimationHalfDepth + { + get; internal set; + } + + public string NativeAnimationClip + { + get; internal set; + } + + public double NativeAnimationSeconds + { + get; internal set; + } + + public string Id + { + get; internal set; + } + + public BattleSide Side + { + get; internal set; + } + + public BattleSlot Slot + { + get; internal set; + } + + public BattleMovementPoint Home + { + get; internal set; + } + + public BattleMovementPoint Position + { + get; internal set; + } + + public BattleMovementSnapshot Movement + { + get; internal set; + } + + public BattleAttackPlan AttackPlan + { + get; internal set; + } + + public int Hp + { + get; internal set; + } + + public int MaxHp + { + get; internal set; + } + + public int Sp + { + get; internal set; + } + + public int Mp + { + get; internal set; + } + + public int Gauge + { + get; internal set; + } + + public int CastGauge + { + get; internal set; + } + + public int MaxSp + { + get; internal set; + } + + public int MaxMp + { + get; internal set; + } + + public int Level + { + get; internal set; + } + + public int Experience + { + get; internal set; + } + + public IReadOnlyList Attributes + { + get; internal set; + } + + public IReadOnlyList States + { + get; internal set; + } + + public float FacingDegrees + { + get; internal set; + } + + public BattleMagicSwordSnapshot MagicSword + { + get; internal set; + } + + public IReadOnlyList Skills + { + get; internal set; + } + + public BattleAction? CurrentAction + { + get; internal set; + } + + public int AbilityId + { + get; internal set; + } + + public int Rounds + { + get; internal set; + } + + public bool Ready + { + get; internal set; + } + + public bool Guarding + { + get; internal set; + } + + public bool Fleeing + { + get; internal set; + } + + public bool Escaped + { + get; internal set; + } + + public bool AliveFlag + { + get; internal set; + } + + public bool ModelAliveFlag + { + get; internal set; + } + + public bool Alive => AliveFlag && !Escaped; + + public BattlePose Pose + { + get; internal set; + } + + public string Target + { + get; internal set; + } + + public long ActionId + { + get; internal set; + } + + public int ActionTick + { + get; internal set; + } + + public int PoseTick + { + get; internal set; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleActorSnapshot.cs.meta b/Assets/Scripts/Pal3.Battle/Contracts/BattleActorSnapshot.cs.meta new file mode 100644 index 00000000..5d6f647c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleActorSnapshot.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: db988bbaf82c4587801816b5e73f898a diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleComboDefinition.cs b/Assets/Scripts/Pal3.Battle/Contracts/BattleComboDefinition.cs new file mode 100644 index 00000000..1c93e4f6 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleComboDefinition.cs @@ -0,0 +1,61 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleComboDefinition + { + public int Id => Requirement.Id; + + public string Name + { + get; + } + + public BattleComboRequirement Requirement + { + get; + } + + public int NativeRange + { + get; + } + + public IReadOnlyList ResourceValues + { + get; + } + + public int PowerMultiplierPercentage + { + get; + } + + public BattleComboDefinition(string name, BattleComboRequirement requirement, int originalRange, + IEnumerable originalResourceValues, int powerMultiplierPercentage = 0) + { + Requirement = requirement ?? throw new ArgumentNullException(nameof(requirement)); + Name = name ?? ""; + NativeRange = originalRange; + int[] values = originalResourceValues?.ToArray() ?? throw new ArgumentNullException(nameof(originalResourceValues)); + if (values.Length != 12 || originalRange < 0 || originalRange > 3) + throw new ArgumentException("An original combo requires twelve raw resource slots and a verified range."); + ResourceValues = Array.AsReadOnly(values); + PowerMultiplierPercentage = powerMultiplierPercentage; + } + } + + public interface IBattleCoAttackTimings + { + BattleComboStageProfile CoAttack(string actor, BattleComboDefinition combo); + + BattleMovementPoint CoAttackHome(string actor, BattleSlot slot); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleComboDefinition.cs.meta b/Assets/Scripts/Pal3.Battle/Contracts/BattleComboDefinition.cs.meta new file mode 100644 index 00000000..eafa3f7f --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleComboDefinition.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b09ae210cdb44d9099430a3a66df389b diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleDefinitions.cs b/Assets/Scripts/Pal3.Battle/Contracts/BattleDefinitions.cs new file mode 100644 index 00000000..f833a639 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleDefinitions.cs @@ -0,0 +1,69 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + + // A session captures definitions, not a GDB cache, Unity object or mutable editor service. + public sealed class BattleDefinitions + { + public string Variant + { + get; + } + + public string Fingerprint + { + get; + } + + public IReadOnlyDictionary Skills + { + get; + } + + public IReadOnlyDictionary Items + { + get; + } + + public IReadOnlyDictionary Actors + { + get; + } + + // Stream order is observable: the original picks the first eligible combination. + public IReadOnlyList Combos + { + get; + } + + public IReadOnlyList SkillsInOriginalOrder + { + get; + } + + public BattleDefinitions(string variant, string fingerprint, IEnumerable skills, + IEnumerable items, IEnumerable actors, IEnumerable combos = null) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant."); + Variant = variant; + Fingerprint = fingerprint ?? ""; + SkillsInOriginalOrder = BattleAbilityDefinition.Capture(skills); + Skills = new ReadOnlyDictionary(SkillsInOriginalOrder.ToDictionary(value => value.Id)); + Items = new ReadOnlyDictionary(items.ToDictionary(value => value.Id)); + Actors = new ReadOnlyDictionary(actors.ToDictionary(value => value.InstanceId, StringComparer.Ordinal)); + BattleComboDefinition[] ordered = combos?.ToArray() ?? Array.Empty(); + if (ordered.Any(combo => combo == null) || ordered.GroupBy(combo => combo.Id).Any(group => group.Count() > 1)) + throw new ArgumentException("Combo definitions need unique non-null IDs.", nameof(combos)); + Combos = Array.AsReadOnly(ordered); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleDefinitions.cs.meta b/Assets/Scripts/Pal3.Battle/Contracts/BattleDefinitions.cs.meta new file mode 100644 index 00000000..6e49657c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleDefinitions.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0913416c190c43a68598176ece9fbe9c diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleEffects.cs b/Assets/Scripts/Pal3.Battle/Contracts/BattleEffects.cs new file mode 100644 index 00000000..6f9ec552 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleEffects.cs @@ -0,0 +1,140 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public enum BattleValueMode + { + Absolute, Percentage, RecoverToMax, IncreaseMax + } + + public enum BattleTargetRange + { + None, OwnSingle, OwnAll, OpponentSingle, OpponentAll, OpponentRow, OpponentColumn + } + + public enum BattleState + { + PoisonWind, PoisonThunder, PoisonWater, PoisonFire, PoisonEarth, + AttackIncrease, AttackDecrease, DefenseIncrease, DefenseDecrease, LuckIncrease, LuckDecrease, SpeedIncrease, SpeedDecrease, + Paralysis, Seal, Forbidden, Sleep, Chaos, Madness, Reflection, Evade, Barrier, Invisible, Dying, Death, + PoisonResist, PoisonAny, EvilResist, DemonResist, GodsEye, ExpIncrease, + } + + public readonly struct BattleAttributeEffect + { + public int Attribute + { + get; + } + + public BattleValueMode Mode + { + get; + } + + public int Value + { + get; + } + + public BattleAttributeEffect(int attribute, BattleValueMode mode, int value) + { + if (attribute < 0 || attribute > 11 || !Enum.IsDefined(typeof(BattleValueMode), mode)) + throw new ArgumentException("Invalid attribute effect."); + Attribute = attribute; + Mode = mode; + Value = value; + } + } + + public readonly struct BattleStatusEffect + { + public BattleState State + { + get; + } + + public bool Remove + { + get; + } + + public int Value + { + get; + } + + public BattleStatusEffect(BattleState state, bool remove, int value = 0) + { + if (!Enum.IsDefined(typeof(BattleState), state)) + throw new ArgumentOutOfRangeException(nameof(state)); + State = state; + Remove = remove; + Value = value; + } + } + + public readonly struct BattleCost + { + // 0 HP, 1 SP, 2 MP, 10 money, 16 inventory Gu item 6113: original resource numbers are preserved at this boundary. + public int Resource + { + get; + } + + public BattleValueMode Mode + { + get; + } + + public int Value + { + get; + } + + public BattleCost(int resource, BattleValueMode mode, int value) + { + Resource = resource; + Mode = mode; + Value = value; + } + } + + public readonly struct BattleCostEstimate + { + public int Resource + { + get; + } + + public int Required + { + get; + } + + public int Payable + { + get; + } + + public int Available + { + get; + } + + public BattleCostEstimate(int resource, int required, int payable, int available) + { + Resource = resource; + Required = required; + Payable = payable; + Available = available; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleEffects.cs.meta b/Assets/Scripts/Pal3.Battle/Contracts/BattleEffects.cs.meta new file mode 100644 index 00000000..3a748f49 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleEffects.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e723765770af41299b2a74ec25ddf3cc diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleEquipmentDefinition.cs b/Assets/Scripts/Pal3.Battle/Contracts/BattleEquipmentDefinition.cs new file mode 100644 index 00000000..3595511b --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleEquipmentDefinition.cs @@ -0,0 +1,151 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleEquipmentData + { + public int Id; + public int Slot; + public int WeaponType; + public BattleMagicSwordSnapshot MagicSwordCultivation; + public bool StartupInvisibility; + public int AttackStealPercent; + public string Name = ""; + public BattleAttributeEffect[] Attributes = Array.Empty(); + public BattleStatusEffect[] States = Array.Empty(); + public int ElementMask; + public int SpSaving; + public int MpSaving; + public int CriticalBonus; + public bool PhysicalReflectionPassive; + public int TechniqueSuccessBonus; + public int SpecialEffect; + public string UnsupportedReason = ""; + public int[] RecoveryPerRound = new int[3]; + } + + public sealed class BattleEquipmentDefinition + { + // Attribute input for a native fallback; this does not grant energy or skills. + public BattleMagicSwordSnapshot MagicSwordCultivation + { + get; + } + + public int Id + { + get; + } + + public int Slot + { + get; + } + + public int WeaponType + { + get; + } + + public bool StartupInvisibility + { + get; + } + + public int AttackStealPercent + { + get; + } + + public string Name + { + get; + } + + public IReadOnlyList Attributes + { + get; + } + + public IReadOnlyList States + { + get; + } + + public int ElementMask + { + get; + } + + public int SpSaving + { + get; + } + + public int MpSaving + { + get; + } + + public int CriticalBonus + { + get; + } + + public bool PhysicalReflectionPassive + { + get; + } + + public int TechniqueSuccessBonus + { + get; + } + + public int SpecialEffect + { + get; + } + + public string UnsupportedReason + { + get; + } + + public IReadOnlyList RecoveryPerRound + { + get; + } + + public BattleEquipmentDefinition(BattleEquipmentData data) + { + if (data == null || data.Id <= 0 || data.Slot < 0 || data.Slot > 5) + throw new ArgumentException("Invalid equipped item."); + Id = data.Id; + Slot = data.Slot; + WeaponType = data.WeaponType; + MagicSwordCultivation = data.MagicSwordCultivation; + StartupInvisibility = data.StartupInvisibility; + AttackStealPercent = data.AttackStealPercent; + Name = data.Name ?? ""; + Attributes = BattleAbilityDefinition.Capture(data.Attributes); + States = BattleAbilityDefinition.Capture(data.States); + ElementMask = data.ElementMask; + SpSaving = data.SpSaving; + MpSaving = data.MpSaving; + CriticalBonus = data.CriticalBonus; + PhysicalReflectionPassive = data.PhysicalReflectionPassive; + TechniqueSuccessBonus = data.TechniqueSuccessBonus; + SpecialEffect = data.SpecialEffect; + UnsupportedReason = data.UnsupportedReason ?? ""; + RecoveryPerRound = BattleAbilityDefinition.Capture(data.RecoveryPerRound); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleEquipmentDefinition.cs.meta b/Assets/Scripts/Pal3.Battle/Contracts/BattleEquipmentDefinition.cs.meta new file mode 100644 index 00000000..ee952bf5 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleEquipmentDefinition.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c8527aef0dde4476b807de8e86946aaa diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleItemSnapshot.cs b/Assets/Scripts/Pal3.Battle/Contracts/BattleItemSnapshot.cs new file mode 100644 index 00000000..5c16af2d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleItemSnapshot.cs @@ -0,0 +1,37 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + // Inventory results carry values, never the mutable scenario authoring object. + public sealed class BattleItemSnapshot + { + public int Id + { + get; + } + + public int Count + { + get; + } + + public BattleItemSnapshot(int id, int count) + { + Id = id; + Count = count; + } + + public BattleItemSnapshot(BattleItem item) + { + if (item == null) + throw new ArgumentNullException(nameof(item)); + Id = item.Id; + Count = item.Count; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleItemSnapshot.cs.meta b/Assets/Scripts/Pal3.Battle/Contracts/BattleItemSnapshot.cs.meta new file mode 100644 index 00000000..db9f41fc --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleItemSnapshot.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4331321ec74a46f58ca34d68a6d1b1db diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleSkillSnapshot.cs b/Assets/Scripts/Pal3.Battle/Contracts/BattleSkillSnapshot.cs new file mode 100644 index 00000000..fb8a35d8 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleSkillSnapshot.cs @@ -0,0 +1,55 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + // Preserve the full learned-skill/save layout without exposing a state writer. + public sealed class BattleSkillSnapshot + { + public int Id + { + get; + } + + public int Level + { + get; + } + + public int Uses + { + get; + } + + public bool Mastered + { + get; + } + + public int NativeMagicGroup + { + get; + } + + public int NativeMagicSlot + { + get; + } + + public BattleSkillSnapshot(BattleSkill skill) + { + if (skill == null) + throw new ArgumentNullException(nameof(skill)); + Id = skill.Id; + Level = skill.Level; + Uses = skill.Uses; + Mastered = skill.Mastered; + NativeMagicGroup = skill.NativeMagicGroup; + NativeMagicSlot = skill.NativeMagicSlot; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleSkillSnapshot.cs.meta b/Assets/Scripts/Pal3.Battle/Contracts/BattleSkillSnapshot.cs.meta new file mode 100644 index 00000000..9b90d38d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleSkillSnapshot.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b40dbf3a375a45c0a163d1c52a933d6b diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleStatusSnapshot.cs b/Assets/Scripts/Pal3.Battle/Contracts/BattleStatusSnapshot.cs new file mode 100644 index 00000000..ed41fa82 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleStatusSnapshot.cs @@ -0,0 +1,34 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleStatusSnapshot + { + public BattleState State + { + get; internal set; + } + + public int LatentRounds + { + get; internal set; + } + + public int RemainingRounds + { + get; internal set; + } + + public bool Permanent + { + get; internal set; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Contracts/BattleStatusSnapshot.cs.meta b/Assets/Scripts/Pal3.Battle/Contracts/BattleStatusSnapshot.cs.meta new file mode 100644 index 00000000..69d8de8a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Contracts/BattleStatusSnapshot.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d7f9161e995d4794ac6094c7eff81c15 diff --git a/Assets/Scripts/Pal3.Battle/Pal3.Battle.asmdef b/Assets/Scripts/Pal3.Battle/Pal3.Battle.asmdef new file mode 100644 index 00000000..06b85a87 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Pal3.Battle.asmdef @@ -0,0 +1,5 @@ +{ + "name": "Pal3.Battle", + "references": [], + "noEngineReferences": true +} diff --git a/Assets/Scripts/Pal3.Battle/Pal3.Battle.asmdef.meta b/Assets/Scripts/Pal3.Battle/Pal3.Battle.asmdef.meta new file mode 100644 index 00000000..bd6ac369 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Pal3.Battle.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 76f9486c1ba8145c5990c97019280090 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Battle/Presentation.meta b/Assets/Scripts/Pal3.Battle/Presentation.meta new file mode 100644 index 00000000..fa83cb99 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: f5d8be820d7644cbb6ebc5a622ae0029 +folderAsset: yes diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleHudInput.cs b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudInput.cs new file mode 100644 index 00000000..3cf0b6e2 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudInput.cs @@ -0,0 +1,482 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle.Presentation +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public enum BattleHudIntentKind + { + Navigate, Confirm, Back, Normal, Repeat, PointerDown, PointerMove, PointerUp, PointerCancel, CyclePrevious, CycleNext, Primary + } + + public enum BattleHudDirection + { + Up, Down, Left, Right, UpRight, DownRight, DownLeft, UpLeft, Neutral + } + + public readonly struct BattleHudIntent + { + public BattleHudIntentKind Kind + { + get; + } + + public BattleHudDirection Direction + { + get; + } + + public int PointerId + { + get; + } + + public string ControlId + { + get; + } + + public BattleHudIntent(BattleHudIntentKind kind, string controlId = null, int pointerId = 0, BattleHudDirection direction = BattleHudDirection.Down) + { + Kind = kind; + ControlId = controlId; + PointerId = pointerId; + Direction = direction; + } + } + + public readonly struct BattleHudFocus + { + public string Id + { + get; + } + + public string Label + { + get; + } + + public bool Enabled + { + get; + } + + public int Column + { + get; + } + + public int Row + { + get; + } + + public BattleHudFocus(string id, string label, bool enabled = true, int column = 0, int row = 0) + { + Id = id; + Label = label; + Enabled = enabled; + Column = column; + Row = row; + } + } + + public sealed partial class BattleHudPresenter + { + private string _focusId; + private int? _pointerId; + private string _pressedControl; + private int? _pressedTargetGeneration; + + private bool PressedTargetReplaced => _pressedTargetGeneration.HasValue && + _session.MonsterGeneration(_pressedControl[7..]) != _pressedTargetGeneration.Value; + + public string FormationActor + { + get; private set; + } + + public string AiActor + { + get; private set; + } + + public string FocusedId + { + get + { + IReadOnlyList items = FocusItems(); + if (items.Any(item => item.Id == _focusId)) + return _focusId; + string first = items.FirstOrDefault(item => item.Enabled).Id; + return first?.StartsWith("category:", StringComparison.Ordinal) == true ? "category:" + Category : first; + } + } + + public int? CapturedPointerId => _pointerId; + + // The control actually activated by the latest input. A cancelled or + // stray release never produces activation feedback. + public string ActivatedControl + { + get; private set; + } + + public IReadOnlyList FocusItems() + { + if (_session == null || Controller == null) + return Array.Empty(); + BattleActorSnapshot actor = _session.Actors.First(value => value.Id == Controller); + if (Page == BattleHudPage.Commands) + { + BattleDefinitions definitions = _session.Definitions; + // Offer the same entries as the lists below. PAL3 FillSkillList + // (cbrolestate.cpp) skips ally skills that have not been mastered. + var learned = actor.Skills.Where(skill => actor.Side == BattleSide.Enemy || skill.Mastered); + bool seal = _session.HasActiveState(Controller, BattleState.Seal); + bool forbidden = _session.HasActiveState(Controller, BattleState.Forbidden); + var items = new List + { + new("attack", "击", Reason(BattleAction.Attack) == null, 1, 1), + new("skills", "技", _session.FormActionDenial(Controller, BattleAction.Skill) == null && definitions != null && learned.Any(skill => definitions.Skills.TryGetValue(skill.Id, out var ability) && !IsMagicMenu(ability)), 1, 0), + new("magic", "术", !seal && _session.FormActionDenial(Controller, BattleAction.Skill, magic: true) == null && definitions != null && learned.Any(skill => definitions.Skills.TryGetValue(skill.Id, out var ability) && IsMagicMenu(ability)), 0, 1), + new("items", "物", definitions != null && actor.Side == BattleSide.Ally && !forbidden && _session.FormActionDenial(Controller, BattleAction.Item) == null, 1, 2), + new("defend", "防", Reason(BattleAction.Defend) == null, 2, 1), + new("formation", "阵", _session.CanBeginFormation(Controller) == null, 0, 2), + new("flee", "逃", Reason(BattleAction.Flee) == null, 2, 2), + new("ai", "AI", definitions != null && !_session.IsPal3ATransformed(Controller), 0, 0), + new("protection", "护", _session.CanSetProtection(Controller, null) == null, 2, 0) + }; + if (actor.MagicSword is { SkillId: > 0 } sword && sword.Energy > 199.9f) + items.Add(new BattleHudFocus("sword", "魔剑技", Reason(BattleAction.Skill, sword.SkillId) == null, 0, 3)); + if (definitions?.Variant == "PAL3A" && actor.NativeIndex == 0) + { + if (actor.ActorId == 101) + items.Add(new BattleHudFocus("transform", "炎兽变身", Reason(BattleAction.Transform) == null, 6, 0)); + items.AddRange(Enumerable.Range(264, 5).Select(id => new BattleHudFocus("wheel:" + id, definitions.Skills.TryGetValue(id, out BattleAbilityDefinition ability) ? ability.Name : "五灵轮" + id, WheelReason(id) == null, id is 264 or 265 ? 5 : 6, id switch { 265 => 0, 264 or 266 => 1, 267 => 2, _ => 3 }))); + } + return items; + } + if (Page is BattleHudPage.Skills or BattleHudPage.Magic or BattleHudPage.Items) + { + IEnumerable rows = Abilities().Select(row => new BattleHudFocus("ability:" + row.Definition.Id, row.Definition.Name, row.Denied == null)); + if (Page is BattleHudPage.Magic or BattleHudPage.Items) + { + string[] categories = Page == BattleHudPage.Magic ? new[] { "水", "火", "雷", "风", "土", "双系" } : new[] { "恢复", "攻击", "仙宝" }; + rows = rows.Concat(categories.Select((name, index) => new BattleHudFocus("category:" + index, name, CategoryEnabled(index)))); + } + return rows.ToArray(); + } + if (Page == BattleHudPage.Targets) + return Targets.Select(target => new BattleHudFocus("target:" + target.Id, target.Id)).ToArray(); + if (Page == BattleHudPage.Formation) + { + var items = _session.Actors.Where(value => value.Side == BattleSide.Ally).Select(value => + new BattleHudFocus("actor:" + value.Id, value.Id, _session.CanSwapFormation(value.Id, value.Slot) == null && FormationActor == null)).ToList(); + items.AddRange(Enum.GetValues(typeof(BattleSlot)).Cast().Select(slot => + new BattleHudFocus("slot:" + (int)slot, slot switch + { + BattleSlot.Water => "水", + BattleSlot.Fire => "火", + BattleSlot.Wind => "风", + BattleSlot.Thunder => "雷", + BattleSlot.Earth => "土", + _ => "中" + }, FormationActor != null && _session.CanSwapFormation(FormationActor, slot) == null))); + items.Add(new BattleHudFocus("end", "确认阵型")); + return items; + } + if (Page == BattleHudPage.Protection) + return _session.Actors.Where(value => value.Side == BattleSide.Ally && _session.CanSetProtection(Controller, value.Id) == null) + .Select(value => new BattleHudFocus("protect:" + value.Id, value.Id)).ToArray(); + if (Page == BattleHudPage.Ai) + return _session.Actors.Select(value => new BattleHudFocus("ai-actor:" + value.Id, value.Id + (value.Id == Controller && value.Side == BattleSide.Ally ? "(操作者)" : "(工具/免费)"))) + .Concat(Enumerable.Range(0, 6).Select(bit => new BattleHudFocus("flag:" + bit, new[] { "普攻", "仙术", "特技", "物品", "全力/万全", "自动" }[bit]))) + .Append(new BattleHudFocus("end", "确认AI")).ToArray(); + return Array.Empty(); + } + + public bool SetFocus(string id) + { + if (!FocusItems().Any(item => item.Id == id && item.Enabled)) + return false; + _focusId = id; + if (Page == BattleHudPage.Targets && id.StartsWith("target:", StringComparison.Ordinal)) + HoverTarget(id[7..]); + return true; + } + + public bool Handle(BattleHudIntent input) + { + ActivatedControl = null; + if (PressedTargetReplaced) + CancelPointer(); + if (Controller == null || _session.WaitingActor != Controller) + return false; + if (input.Kind == BattleHudIntentKind.PointerCancel) + { + if (_pointerId != input.PointerId) + return false; + CancelPointer(); + return true; + } + if (input.Kind == BattleHudIntentKind.PointerDown) + { + if (_pointerId.HasValue || !SetFocus(input.ControlId)) + return false; + _pointerId = input.PointerId; + _pressedControl = input.ControlId; + if (Page == BattleHudPage.Targets) + _pressedTargetGeneration = _session.MonsterGeneration(input.ControlId[7..]); + if (Page == BattleHudPage.Formation && input.ControlId.StartsWith("actor:", StringComparison.Ordinal)) + FormationActor = input.ControlId[6..]; + return true; + } + if (input.Kind is BattleHudIntentKind.PointerMove or BattleHudIntentKind.PointerUp) + { + if (_pointerId != input.PointerId) + return false; + if (input.ControlId != null) + SetFocus(input.ControlId); + if (input.Kind == BattleHudIntentKind.PointerMove) + return true; + string pressed = _pressedControl; + CancelPointer(); + if (Page == BattleHudPage.Formation && pressed?.StartsWith("actor:", StringComparison.Ordinal) == true) + return input.ControlId?.StartsWith("slot:", StringComparison.Ordinal) == true && + int.TryParse(input.ControlId[5..], out int slot) && MoveFormation(pressed[6..], (BattleSlot)slot); + return pressed == input.ControlId && ExecuteFocus(input.ControlId); + } + CancelPointer(); + switch (input.Kind) + { + case BattleHudIntentKind.Navigate: + return Navigate(input.Direction); + case BattleHudIntentKind.Confirm: + return ExecuteFocus(input.ControlId ?? FocusedId); + case BattleHudIntentKind.CyclePrevious: + return CycleSection(-1); + case BattleHudIntentKind.CycleNext: + return CycleSection(1); + case BattleHudIntentKind.Primary: + return Page == BattleHudPage.Protection ? SetProtection(null) && CommitProtection() : Page == BattleHudPage.Commands && SetFocus("attack"); + case BattleHudIntentKind.Back: + Back(); + return true; + case BattleHudIntentKind.Normal: + return RequestAi(false); + case BattleHudIntentKind.Repeat: + return RequestAi(true); + default: + return false; + } + } + + private readonly Dictionary _focusLayout = new(StringComparer.Ordinal); + + public void SetFocusLayout(IEnumerable<(string Id, float X, float Y)> positions) + { + _focusLayout.Clear(); + foreach (var position in positions) + _focusLayout[position.Id] = (position.X, position.Y); + } + + public static (int X, int Y) DirectionVector(BattleHudDirection direction) => direction switch + { + BattleHudDirection.Up => (0, -1), + BattleHudDirection.Down => (0, 1), + BattleHudDirection.Left => (-1, 0), + BattleHudDirection.Right => (1, 0), + BattleHudDirection.UpRight => (1, -1), + BattleHudDirection.DownRight => (1, 1), + BattleHudDirection.DownLeft => (-1, 1), + BattleHudDirection.UpLeft => (-1, -1), + _ => (0, 0) + }; + + private bool FocusNavigation(string id) + { + // Disabled list entries remain inspectable, but ExecuteFocus still + // checks their enabled state before any command can be issued. + if (!FocusItems().Any(item => item.Id == id)) + return false; + _focusId = id; + if (Page == BattleHudPage.Targets && id.StartsWith("target:", StringComparison.Ordinal)) + HoverTarget(id[7..]); + InspectAbilityRow(id); + return true; + } + + private bool CycleSection(int step) + { + if (Page is BattleHudPage.Magic or BattleHudPage.Items) + { + int count = Page == BattleHudPage.Magic ? 6 : 3; + int next = (Category + count + step) % count; + if (!CategoryEnabled(next)) + next = (next + count + step) % count; + SetCategory(next); + return true; + } + if (Page == BattleHudPage.Ai) + { + var actors = _session.Actors.ToArray(); + int index = Math.Max(0, Array.FindIndex(actors, actor => actor.Id == AiActor)); + AiActor = actors[(index + step + actors.Length) % actors.Length].Id; + _focusId = "flag:0"; + return true; + } + var items = FocusItems().Where(item => item.Enabled).ToArray(); + if (items.Length == 0) + return false; + int at = Math.Max(0, Array.FindIndex(items, item => item.Id == FocusedId)); + return SetFocus(items[(at + step + items.Length) % items.Length].Id); + } + + private bool Navigate(BattleHudDirection direction) + { + if (direction == BattleHudDirection.Neutral) + return Page == BattleHudPage.Commands && FocusNavigation("attack"); + var (dx, dy) = DirectionVector(direction); + if (Page is BattleHudPage.Magic or BattleHudPage.Items && dy == 0) + return CycleSection(dx); + var items = FocusItems().Where(item => Page is BattleHudPage.Skills or BattleHudPage.Magic or BattleHudPage.Items || item.Enabled).ToArray(); + if (Page is BattleHudPage.Magic or BattleHudPage.Items) + items = items.Where(item => item.Id.StartsWith("ability:", StringComparison.Ordinal)).ToArray(); + if (Page == BattleHudPage.Ai) + items = items.Where(item => !item.Id.StartsWith("ai-actor:", StringComparison.Ordinal)).ToArray(); + if (items.Length == 0) + return false; + if (Page == BattleHudPage.Commands) + { + var radial = FocusItems().FirstOrDefault(item => item.Column == 1 + dx && item.Row == 1 + dy); + return radial.Id != null && FocusNavigation(radial.Id); + } + int index = Array.FindIndex(items, item => item.Id == FocusedId); + if (index < 0) + return FocusNavigation(items[dy < 0 || dy == 0 && dx < 0 ? items.Length - 1 : 0].Id); + if (Page is BattleHudPage.Targets or BattleHudPage.Formation or BattleHudPage.Ai or BattleHudPage.Protection && + _focusLayout.TryGetValue(items[index].Id, out var origin)) + { + var next = items.Where(item => item.Id != items[index].Id && _focusLayout.ContainsKey(item.Id)) + .Select(item => (Item: item, X: _focusLayout[item.Id].X - origin.X, Y: _focusLayout[item.Id].Y - origin.Y)) + .Where(item => item.X * dx + item.Y * dy > .001f) + .OrderBy(item => (Math.Abs(item.X * dy - item.Y * dx) * 2 + Math.Sqrt(item.X * item.X + item.Y * item.Y))) + .FirstOrDefault(); + if (next.Item.Id != null) + return FocusNavigation(next.Item.Id); + } + int step = dy < 0 || dy == 0 && dx < 0 ? -1 : 1; + return FocusNavigation(items[(index + step + items.Length) % items.Length].Id); + } + + private bool ExecuteFocus(string id) + { + if (!SetFocus(id)) + return false; + ActivatedControl = id; + Message = null; + if (id.StartsWith("category:", StringComparison.Ordinal)) + { + SetCategory(int.Parse(id[9..])); + return true; + } + if (id.StartsWith("ability:", StringComparison.Ordinal)) + return ChooseAbility(int.Parse(id[8..])); + if (id.StartsWith("target:", StringComparison.Ordinal)) + return SelectTarget(id[7..]); + if (id.StartsWith("actor:", StringComparison.Ordinal)) + { + FormationActor = id[6..]; + _focusId = FocusItems().FirstOrDefault(item => item.Id.StartsWith("slot:", StringComparison.Ordinal) && item.Enabled).Id; + return true; + } + if (id.StartsWith("slot:", StringComparison.Ordinal)) + return FormationActor != null && MoveFormation(FormationActor, (BattleSlot)int.Parse(id[5..])); + if (id.StartsWith("protect:", StringComparison.Ordinal)) + return SetProtection(id[8..]) && CommitProtection(); + if (id.StartsWith("wheel:", StringComparison.Ordinal)) + return ChooseWheel(int.Parse(id[6..])); + if (id.StartsWith("ai-actor:", StringComparison.Ordinal)) + { + AiActor = id[9..]; + _focusId = "flag:0"; + return true; + } + if (id.StartsWith("flag:", StringComparison.Ordinal)) + { + return ToggleAiDraft(int.Parse(id[5..])); + } + switch (id) + { + case "attack": + return ChooseAction(BattleAction.Attack); + case "skills": + Open(BattleHudPage.Skills); + return true; + case "magic": + Open(BattleHudPage.Magic); + return true; + case "items": + Open(BattleHudPage.Items); + return true; + case "defend": + return ChooseAction(BattleAction.Defend); + case "flee": + return ChooseAction(BattleAction.Flee); + case "formation": + return BeginFormation(); + case "ai": + AiActor = Controller; + Open(BattleHudPage.Ai); + return true; + case "protection": + Open(BattleHudPage.Protection); + return true; + case "transform": + return ChooseAction(BattleAction.Transform); + case "end" when Page == BattleHudPage.Ai: + return CommitAiDraft(); + case "end" when Page == BattleHudPage.Formation: + return CommitFormation(); + case "sword": + return ChooseAction(BattleAction.Skill, _session.MagicSwordAbilityId(Controller)); + default: + return false; + } + } + + private void ResetFocus() + { + _focusId = null; + CancelPointer(); + } + + private void CancelPointer() + { + // PointerDown selects an actor only for this drag. Keyboard actor + // selection has no pressed control and keeps its two-stage Back. + if (_pressedControl?.StartsWith("actor:", StringComparison.Ordinal) == true) + { + FormationActor = null; + _focusId = null; + } + _pointerId = null; + _pressedControl = null; + _pressedTargetGeneration = null; + } + + private void ClearInput() + { + ResetFocus(); + FormationActor = AiActor = ProtectionSelection = null; + _aiDraft.Clear(); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleHudInput.cs.meta b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudInput.cs.meta new file mode 100644 index 00000000..218f3b9a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudInput.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d4e9d372ec10465dbbdeb1893cfb3b14 diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.Ai.cs b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.Ai.cs new file mode 100644 index 00000000..fcd8d7f1 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.Ai.cs @@ -0,0 +1,98 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle.Presentation +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleHudPresenter + { + private readonly Dictionary _aiDraft = new(StringComparer.Ordinal); + + private void BeginAiDraft() + { + _aiDraft.Clear(); + AiActor = Controller; + } + + public bool AiControlConsumesGauges => Controller != null && _session.Actors.First(actor => actor.Id == Controller).Side == BattleSide.Ally && + BattleAiControlRules.ConsumesGauges(_session.GetAiProfile(Controller), AiFlags(Controller)); + + public int AiFlags(string actor) + { + int live = _session.GetAiProfile(actor); + return _aiDraft.TryGetValue(actor, out var edit) && edit.Generation == _session.MonsterGeneration(actor) + ? (live & ~edit.Mask) | (edit.Flags & edit.Mask) + : live; + } + + public static int ToggleAiFlag(int flags, int bit) + { + if (flags < 0 || flags > 63 || bit < 0 || bit > 5) + throw new ArgumentOutOfRangeException(nameof(flags)); + int changed = flags ^ 1 << bit; + if (bit == 5) + return (changed & 32) != 0 ? changed | 1 : changed & ~15; + if (bit == 0) + return (changed & 1) == 0 ? changed & ~47 : (flags & 32) != 0 ? changed : flags & ~1; + if ((flags & 32) == 0) + return bit == 4 ? flags : flags & ~(1 << bit); + return changed; + } + + public bool ToggleAiDraft(int bit) + { + if (Page != BattleHudPage.Ai || Controller == null) + return false; + string actor = AiActor ?? Controller; + int before = AiFlags(actor); + int next = ToggleAiFlag(before, bit); + int generation = _session.MonsterGeneration(actor); + int previousMask = _aiDraft.TryGetValue(actor, out var edit) && edit.Generation == generation ? edit.Mask : 0; + int live = _session.GetAiProfile(actor); + // Preserve changes made outside this panel to flags the draft leaves alone. + int mask = (previousMask | (before ^ next)) & (live ^ next); + if (mask != 0) + _aiDraft[actor] = (generation, mask, next); + else + _aiDraft.Remove(actor); + bool denied = (before & 32) == 0 && (bit is >= 1 and <= 4 || bit == 0 && (before & 1) == 0); + Message = denied ? "先启用 AI,再设置此项。" : null; + return next != before; + } + + public bool CommitAiDraft() + { + if (Page != BattleHudPage.Ai || Controller == null || _session.WaitingActor != Controller || _session.IsPal3ATransformed(Controller)) + return false; + string controller = Controller; + int flags = AiFlags(controller); + // The original controller pays its original menu cost atomically. + if (_session.GetAiProfile(controller) != flags) + { + bool playerController = _session.Actors.First(actor => actor.Id == controller).Side == BattleSide.Ally; + if (playerController) + { + if (!_session.CommitAiControl(controller, flags)) + return false; + } + else + _session.SetAiProfile(controller, flags); + } + // Editing a different participant is an explicit tool extension. + // It retains the existing recorded debug profile command. + foreach (BattleActorSnapshot actor in _session.Actors) + if (actor.Id != controller && _aiDraft.ContainsKey(actor.Id)) + _session.SetAiProfile(actor.Id, AiFlags(actor.Id)); + _aiDraft.Clear(); + Page = BattleHudPage.Commands; + ResetFocus(); + Synchronize(_session); + return true; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.Ai.cs.meta b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.Ai.cs.meta new file mode 100644 index 00000000..5b5f9fe0 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.Ai.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6fc531fb95b8405fa03523abc0595c62 diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.cs b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.cs new file mode 100644 index 00000000..91d74d32 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.cs @@ -0,0 +1,430 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle.Presentation +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + + public enum BattleHudPage + { + Commands, Skills, Magic, Items, Targets, Formation, Protection, Ai + } + + public sealed class BattleHudAbility + { + public BattleAbilityDefinition Definition + { + get; internal set; + } + + public string Denied + { + get; internal set; + } + + public int Count + { + get; internal set; + } + + public int Uses + { + get; internal set; + } + + public int Level + { + get; internal set; + } + } + + // Selection is local to the view. Reading this presenter never submits a + // command, advances time, pays a resource, or chooses a random recipient. + public sealed partial class BattleHudPresenter + { + private readonly Dictionary _magicCategories = new(StringComparer.Ordinal); + private BattleSession _session; + private BattleHudPage _returnPage; + private BattleAction _action; + private int _ability; + + public string Controller + { + get; private set; + } + + public BattleHudPage Page + { + get; private set; + } + + public int Category + { + get; private set; + } + + public string Target + { + get; private set; + } + + public string ProtectionSelection + { + get; private set; + } + + public string Message + { + get; private set; + } + + public BattleCommand Command => new(Controller, _action, Target, _ability); + + public BattleTargetRange Range => _session?.GetActionTargetRange(Command) ?? BattleTargetRange.None; + + public IReadOnlyList Targets => _session?.GetTargetCandidates(Command) ?? Array.Empty(); + + public IReadOnlyList Affected => _session?.GetPotentialAffectedTargets(Command) ?? Array.Empty(); + + public IReadOnlyList Costs => _session?.GetCostEstimate(Command) ?? Array.Empty(); + + public void Synchronize(BattleSession session) + { + string waiting = session?.Status == BattleSessionStatus.Running ? session.WaitingActor : null; + if (_session != session || Controller != waiting) + { + if (_session != session) + _magicCategories.Clear(); + _session = session; + Controller = waiting; + Reset(); + } + if (session?.ActiveFormationController != null) + { + if (Page != BattleHudPage.Formation) + { + Reset(); + Page = BattleHudPage.Formation; + } + } + else if (Page == BattleHudPage.Formation) + Reset(); + if (AbilityMenuBlocked()) + Reset(); + if (Page == BattleHudPage.Targets) + { + if (PressedTargetReplaced) + CancelPointer(); + IReadOnlyList targets = Targets; + if (targets.Count == 0) + Back(); + else if (!targets.Any(actor => actor.Id == Target)) + { + FocusDefaultTarget(); + } + } + } + + private bool AbilityMenuBlocked() + { + BattleState state; + if (Page == BattleHudPage.Items || Page == BattleHudPage.Targets && _action == BattleAction.Item) + state = BattleState.Forbidden; + else if (Page == BattleHudPage.Magic || Page == BattleHudPage.Targets && _action == BattleAction.Skill && + _session?.Definitions?.Skills.TryGetValue(_ability, out var ability) == true && IsMagicMenu(ability)) + state = BattleState.Seal; + else + return false; + return _session?.HasActiveState(Controller, state) == true; + } + + private int _blockedMagicCategory = -1; + + public void Reset() + { + _blockedMagicCategory = -1; + Page = BattleHudPage.Commands; + Category = 0; + Target = null; + Message = null; + _action = BattleAction.Attack; + _ability = 0; + ClearInput(); + } + + public void Open(BattleHudPage page) + { + if (Controller == null) + return; + if (page == BattleHudPage.Protection) + ProtectionSelection = _session.ProtectionTarget; + if (page == BattleHudPage.Ai) + BeginAiDraft(); + else if (Page == BattleHudPage.Ai) + _aiDraft.Clear(); + Page = page; + Category = page == BattleHudPage.Magic ? _magicCategories.GetValueOrDefault(Controller) : 0; + Target = null; + Message = null; + ResetFocus(); + if (page == BattleHudPage.Ai) + _focusId = "flag:0"; + RefreshMagicCategoryGate(); + } + + public void SetCategory(int category) + { + if (!CategoryEnabled(category)) + return; + Category = Math.Max(0, category); + RememberMagicCategory(); + Message = null; + ResetFocus(); + } + + private bool CategoryEnabled(int category) => Page != BattleHudPage.Magic || category != _blockedMagicCategory; + + private bool IsPal3AMagicPage => Page == BattleHudPage.Magic && _session?.Definitions?.Variant == "PAL3A"; + + private void RememberMagicCategory() + { + if (Page == BattleHudPage.Magic && Controller != null) + _magicCategories[Controller] = Category; + } + + // PAL3A configures tab availability when entering the magic menu + // (0x4D09AA–0x4D0A5E). Individual spells use the live field when checked. + private void RefreshMagicCategoryGate() + { + _blockedMagicCategory = -1; + if (IsPal3AMagicPage && _session.FiveSpiritForce == 2 && _session.FiveSpiritElement != 0 && + _session.Actors.Any(actor => actor.Id == Controller && actor.Side == BattleSide.Ally)) + { + _blockedMagicCategory = BattleMagicSlots.Group(1 << (_session.FiveSpiritElement - 1)); + if (Category == _blockedMagicCategory) + Category = (_blockedMagicCategory + 1) % 5; + } + RememberMagicCategory(); + } + + public bool InspectAbilityRow(string id) => IsPal3AMagicPage && Controller != null && _session.FiveSpiritElement != 0 && + id?.StartsWith("ability:", StringComparison.Ordinal) == true && int.TryParse(id[8..], out int abilityId) && + AbilityDefinitions(_session.Actors.First(actor => actor.Id == Controller), Array.Empty()) + .Any(ability => ability.Id == abilityId) && + _session.InspectMagicMenuAbility(Controller, abilityId); + + public IReadOnlyList Abilities() + { + if (_session?.Definitions == null || Controller == null) + return Array.Empty(); + BattleActorSnapshot actor = _session.Actors.First(value => value.Id == Controller); + bool item = Page == BattleHudPage.Items; + IReadOnlyList inventory = item ? _session.InventoryEntries : Array.Empty(); + var counts = item ? inventory.ToDictionary(entry => entry.Id, entry => entry.Count) : null; + return AbilityDefinitions(actor, inventory).Select(ability => new BattleHudAbility + { + Definition = ability, + Denied = Reason(item ? BattleAction.Item : BattleAction.Skill, ability.Id), + Count = item ? counts[ability.Id] : 0, + Uses = actor.Skills.FirstOrDefault(skill => skill.Id == ability.Id)?.Uses ?? 0, + Level = actor.Skills.FirstOrDefault(skill => skill.Id == ability.Id)?.Level ?? 0 + }).ToArray(); + } + + private IEnumerable AbilityDefinitions(BattleActorSnapshot actor, IReadOnlyList inventory) + { + bool item = Page == BattleHudPage.Items; + IEnumerable ids = item ? inventory.Where(entry => entry.Count > 0).Select(entry => entry.Id) : + actor.Skills.Where(skill => actor.Side == BattleSide.Enemy || skill.Mastered).Select(skill => skill.Id); + if (!item && Page == BattleHudPage.Magic && actor.Side == BattleSide.Ally) + ids = BattleMagicSlots.Capture(_session.Definitions.Variant, _session.Definitions, + _session.Definitions.Actors[Controller].Identity, actor.Skills) + .Where(slot => slot.Group == Category && actor.Skills.Any(skill => skill.Id == slot.SkillId && skill.Mastered)) + .Select(slot => slot.SkillId); + IReadOnlyDictionary table = item ? _session.Definitions.Items : _session.Definitions.Skills; + return ids.Distinct().Where(table.ContainsKey).Select(id => table[id]).Where(ability => + item ? ability.ItemType == Category + 1 : Page == BattleHudPage.Skills ? !IsMagicMenu(ability) : IsMagicMenu(ability) && + (actor.Side == BattleSide.Ally || MagicCategory(ability.ElementMask) == Category)); + } + + public static bool IsMagicMenu(BattleAbilityDefinition ability) => ability.SkillTypeId is 1 or 2 or 3 || + ability.SkillTypeId == -1 && ability.IsMagic; + + public static int MagicCategory(int mask) => Math.Min(5, BattleMagicSlots.Group(mask)); + + public string Reason(BattleAction action, int ability = 0) + { + if (_session == null || Controller == null) + return "等待角色就绪"; + var query = new BattleCommand(Controller, action, abilityId: ability); + string target = _session.GetTargetCandidates(query).FirstOrDefault()?.Id; + return _session.CanSubmit(new BattleCommand(Controller, action, target, ability)); + } + + public bool ChooseAbility(int ability) + { + if (Page is not (BattleHudPage.Skills or BattleHudPage.Magic or BattleHudPage.Items)) + return false; + return ChooseAction(Page == BattleHudPage.Items ? BattleAction.Item : BattleAction.Skill, ability); + } + + public bool ChooseAction(BattleAction action, int ability = 0) + { + Message = Reason(action, ability); + if (Message != null) + return false; + _returnPage = Page; + _action = action; + _ability = ability; + Target = null; + if (action is BattleAction.Defend or BattleAction.Flee or BattleAction.Transform || + action == BattleAction.Skill && ability != 0 && ability == _session.MagicSwordAbilityId(Controller)) + return Submit(); + Page = BattleHudPage.Targets; + FocusDefaultTarget(); + return true; + } + + private void FocusDefaultTarget() + { + ResetFocus(); + Target = _session.GetDefaultTarget(Command); + _focusId = Target == null ? null : "target:" + Target; + } + + public bool HoverTarget(string target) + { + if (Page != BattleHudPage.Targets || !Targets.Any(actor => actor.Id == target)) + return false; + Target = target; + _focusId = "target:" + target; + return true; + } + + public bool SelectTarget(string target) + { + if (!HoverTarget(target)) + return false; + return Submit(); + } + + public bool Submit() + { + if (_session == null || Controller == null || _session.WaitingActor != Controller) + return false; + if (Page == BattleHudPage.Targets && Target == null) + return false; + BattleTargetRange range = Range; + BattleCommand command = (_action is BattleAction.Skill or BattleAction.Item) && (range is BattleTargetRange.OwnAll or BattleTargetRange.OpponentAll) ? + new BattleCommand(Controller, _action, abilityId: _ability) : Command; + Message = _session.CanSubmit(command); + if (Message != null) + return false; + _session.Submit(command); + Synchronize(_session); + return true; + } + + public bool BeginFormation() + { + if (Controller == null || !_session.BeginFormation(Controller)) + return false; + Synchronize(_session); + return true; + } + + public bool CommitFormation() + { + if (Page != BattleHudPage.Formation || Controller == null || _session.WaitingActor != Controller) + return false; + bool ended = _session.EndFormation(Controller); + Reset(); + Synchronize(_session); + return ended; + } + + public bool MoveFormation(string actor, BattleSlot slot) + { + Message = _session?.CanSwapFormation(actor, slot); + bool moved = Message == null && _session?.SwapFormation(actor, slot) == true; + if (moved) + { + FormationActor = null; + ResetFocus(); + } + return moved; + } + + public bool SetProtection(string target) + { + if (Page != BattleHudPage.Protection || Controller == null) + return false; + Message = _session.CanSetProtection(Controller, target); + if (Message != null) + return false; + ProtectionSelection = ProtectionSelection == target ? null : target; + return true; + } + + public bool CommitProtection() + { + if (Controller == null || Page != BattleHudPage.Protection || _session.WaitingActor != Controller) + return false; + Message = _session.CanSetProtection(Controller, ProtectionSelection); + if (Message != null) + return false; + if (_session.ProtectionTarget != ProtectionSelection && !_session.SetProtection(Controller, ProtectionSelection)) + return false; + Page = BattleHudPage.Commands; + ResetFocus(); + Synchronize(_session); + return true; + } + + public string WheelReason(int skillId) => Controller == null ? "等待角色就绪" : _session.CanSubmitElementWheel(Controller, skillId); + + public bool ChooseWheel(int skillId) + { + Message = WheelReason(skillId); + if (Message != null || !_session.SubmitElementWheel(Controller, skillId)) + return false; + Synchronize(_session); + return true; + } + + public bool RequestAi(bool repeat) + { + if (Controller == null || Page == BattleHudPage.Formation) + return false; + bool submitted = repeat ? _session.RequestAiRepeat(Controller) : _session.RequestAiNormal(Controller); + Synchronize(_session); + return submitted; + } + + public bool Back() + { + if (Page == BattleHudPage.Formation && FormationActor != null) + { + FormationActor = null; + ResetFocus(); + return false; + } + _aiDraft.Clear(); + if (Page == BattleHudPage.Formation) + return CommitFormation(); + Page = Page == BattleHudPage.Targets ? _returnPage : BattleHudPage.Commands; + Target = null; + Message = null; + ResetFocus(); + if (Page is BattleHudPage.Magic or BattleHudPage.Skills or BattleHudPage.Items) + _focusId = "ability:" + _ability; + RefreshMagicCategoryGate(); + return false; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.cs.meta b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.cs.meta new file mode 100644 index 00000000..ede9f734 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleHudPresenter.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 04f3f1e366054d2ab6d28226c68a5cbb diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleLineupProjection.cs b/Assets/Scripts/Pal3.Battle/Presentation/BattleLineupProjection.cs new file mode 100644 index 00000000..8ae73964 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleLineupProjection.cs @@ -0,0 +1,103 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle.Presentation +{ + using System; + using System.Collections.Generic; + + public readonly struct BattleLineupFrame + { + public BattleSide Side + { + get; + } + + public byte Alpha + { + get; + } + + public BattleLineupFrame(BattleSide side, byte alpha) + { + Side = side; + Alpha = alpha; + } + } + + public static class BattleLineupProjection + { + public static IReadOnlyList Capture(BattleSession battle) + { + if (battle == null) + throw new ArgumentNullException(nameof(battle)); + var frames = new List(); + if (battle.Status != BattleSessionStatus.Running || battle.IsModalPresentation) + return frames; + double elapsed = BattleStageScheduler.TimeAt(battle.SimulationTick); + // ProcDialog starts this non-blocking task alongside ProcControl. + if (battle.Encounter != BattleEncounter.EnemyAmbush && elapsed <= 4) + { + byte alpha = Alpha(elapsed, 4); + frames.Add(new BattleLineupFrame(BattleSide.Ally, alpha)); + frames.Add(new BattleLineupFrame(BattleSide.Enemy, alpha)); + } + foreach (BattleAbilityPresentationSnapshot ability in battle.AbilityPresentations) + if (ability.LineupVisible) + frames.Add(new BattleLineupFrame(ability.Side, Alpha(ability.LineupElapsedSeconds, ability.LineupDurationSeconds))); + return frames; + } + + public static byte Alpha(double elapsed, double duration) + { + if (duration <= 0 || elapsed < 0 || elapsed > duration) + return 0; + // ProcShowFiveLineup submits the previous pass's alpha before + // calculating the next value. Repainting must not age this value. + float previous = (float)Math.Max(0, elapsed - BattleSession.StepSeconds); + float fadeIn = (float)duration / 4 * 3; + float fadeOut = (float)duration / 4; + float value = previous < fadeIn ? 255 * (previous / fadeIn) : 255 * (1 - (previous - fadeIn) / fadeOut); + return (byte)Math.Clamp((int)Math.Round(value, MidpointRounding.ToEven), 0, 255); + } + + public static float AllyRoll(float initial, int sceneElement) + { + int greater = BattleEffectRules.GreaterElement(sceneElement); + int turns = greater switch + { + 1 => 1, + 2 => 2, + 3 => 4, + 4 => 3, + _ => 0 + }; + return initial + turns * ((360f / 5) * 3.14159f / 180f); + } + + public static uint CenterColor(int sceneElement) => sceneElement switch + { + 1 => 0x399aadu, + 2 => 0xde7531u, + 3 => 0x52b66bu, + 4 => 0xde75bdu, + 5 => 0xd6ae5au, + _ => 0u + }; + + public static BattleMovementPoint Corner(BattleMovementPoint center, float radius, float roll, int index, bool centerTile) + { + if (index is < 0 or > 3) + throw new ArgumentOutOfRangeException(nameof(index)); + float half = centerTile ? radius / 2 : radius; + float x = index is 0 or 3 ? -half : half; + float z = index < 2 ? -half : half; + float sine = centerTile ? 0 : MathF.Sin(roll); + float cosine = centerTile ? 1 : MathF.Cos(roll); + return new BattleMovementPoint(center.X + x * cosine + z * sine, + centerTile ? 0 : .5f, center.Z - x * sine + z * cosine); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleLineupProjection.cs.meta b/Assets/Scripts/Pal3.Battle/Presentation/BattleLineupProjection.cs.meta new file mode 100644 index 00000000..36e25c7c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleLineupProjection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 982344fa55624589809517b2d144a1e1 diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberFont.cs b/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberFont.cs new file mode 100644 index 00000000..4e232133 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberFont.cs @@ -0,0 +1,51 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle.Presentation +{ + using System; + using System.IO; + + // GB_FONT_UNICODE20 is a one-bit BMP-indexed font, including the centered + // half-width ASCII used by ShowDamage and ShowMiss in both released games. + public sealed class BattleNumberFont + { + public const int Size = 20; + private const int BytesPerGlyph = Size * Size / 8; + private readonly byte[] _glyphs; + private readonly int _count; + + public BattleNumberFont(byte[] source) + { + if (source == null) + throw new ArgumentNullException(nameof(source)); + using var reader = new BinaryReader(new MemoryStream(source, false)); + if (source.Length < 20) + throw new InvalidDataException("The native battle font header is truncated."); + reader.ReadUInt32(); // Engine does not interpret the file's magic. + uint version = reader.ReadUInt32(); + uint size = reader.ReadUInt32(); + uint bits = reader.ReadUInt32(); + _count = reader.ReadInt32(); + if (version != 1 || size != Size || bits != 1 || _count <= 0 || _count > 65536 || + source.Length != 20 + _count * BytesPerGlyph) + throw new InvalidDataException("Expected an original unicode20.tft one-bit font."); + _glyphs = reader.ReadBytes(_count * BytesPerGlyph); + } + + public static int Advance(char character) => character is >= ' ' and <= '~' ? Size / 2 : Size; + + public byte[] GlyphAlpha(char character) + { + if (character >= _count) + throw new InvalidDataException("The native battle font has no glyph for " + (int)character + "."); + var alpha = new byte[Size * Size]; + int start = character * BytesPerGlyph; + for (int pixel = 0; pixel < alpha.Length; pixel++) + alpha[pixel] = (_glyphs[start + pixel / 8] & (1 << (pixel % 8))) != 0 ? byte.MaxValue : (byte)0; + return alpha; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberFont.cs.meta b/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberFont.cs.meta new file mode 100644 index 00000000..22406e7e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberFont.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c0d26360b4c04e6d8b9c7bd37f414b18 diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberProjection.cs b/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberProjection.cs new file mode 100644 index 00000000..a995cca5 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberProjection.cs @@ -0,0 +1,146 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle.Presentation +{ + using System; + using System.Collections.Generic; + using System.Globalization; + + public readonly struct BattleNumberFrame + { + public string Text + { + get; + } + + public BattleMovementPoint Position + { + get; + } + + public int OffsetX + { + get; + } + + public int OffsetY + { + get; + } + + public uint Color + { + get; + } + + public byte Alpha + { + get; + } + + public BattleNumberFrame(string text, BattleMovementPoint position, int offsetX, int offsetY, uint color, byte alpha) + { + Text = text; + Position = position; + OffsetX = offsetX; + OffsetY = offsetY; + Color = color; + Alpha = alpha; + } + } + + // A read-only projection of published number activations. It owns neither + // battle tasks nor random draws, and survives batched stepping and replay. + public sealed class BattleNumberProjection + { + private sealed class Number + { + public BattleEvent Event; + public int Stack; + } + + private sealed class Stack + { + public long Tick; + public float Height; + } + + private readonly List _numbers = new(); + private readonly Dictionary _stacks = new(StringComparer.Ordinal); + private readonly string _guName; + private int _eventCursor; + private long _tick; + + public BattleNumberProjection(string guName = "蛊") => _guName = guName; + + public void Synchronize(IReadOnlyList events, long simulationTick) + { + if (events == null) + throw new ArgumentNullException(nameof(events)); + if (simulationTick < _tick || events.Count < _eventCursor) + Clear(); + _tick = simulationTick; + for (; _eventCursor < events.Count; _eventCursor++) + { + BattleEvent entry = events[_eventCursor]; + if (entry.Kind != BattleEventKind.NumberShown) + continue; + int stack = 16; + if (!entry.NumberIsMiss) + { + if (!_stacks.TryGetValue(entry.Target, out Stack state)) + _stacks.Add(entry.Target, state = new Stack { Tick = entry.NumberActivationTick }); + // The native stage decays once before each simulation pass. + // The loop is bounded by the 160-pixel reset and zero floor. + for (long tick = state.Tick; tick < entry.NumberActivationTick && state.Height > 0; tick++) + state.Height = state.Height > 160 ? 160 : Math.Max(0, state.Height - .6f); + state.Tick = entry.NumberActivationTick; + state.Height += 10; + stack = Round(state.Height); + } + _numbers.Add(new Number { Event = entry, Stack = stack }); + } + float now = BattleStageScheduler.TimeAt(simulationTick); + _numbers.RemoveAll(number => (double)now - number.Event.NumberStartedTime > number.Event.DurationSeconds); + } + + public IReadOnlyList Sample() + { + var result = new List(_numbers.Count); + float now = BattleStageScheduler.TimeAt(_tick); + foreach (Number number in _numbers) + { + BattleEvent entry = number.Event; + double elapsed = Math.Max(0, (double)now - entry.NumberStartedTime); + double ratio = entry.DurationSeconds > 0 ? Math.Min(1, elapsed / entry.DurationSeconds) : 1; + byte alpha = (byte)Math.Clamp(Round((float)((1 - ratio) * 255)), 0, 255); + int rise = Round((float)(entry.NumberIsMiss ? ratio * 32 : elapsed * 30)); + bool cost = entry.Resource == 16; + string text = entry.NumberIsMiss ? "MISS" : (cost ? _guName + " " : string.Empty) + + entry.RequestedDelta.ToString(CultureInfo.InvariantCulture); + uint color = entry.NumberIsMiss || cost ? 0x32ffffu : entry.Resource switch + { + 1 => 0xfbe0a2u, + 2 => 0xfaa8d5u, + _ => entry.NumberIsRecovery ? 0x00ff00u : 0x3232ffu + }; + result.Add(new BattleNumberFrame(text, entry.NumberPosition, + entry.NumberOffset - (cost ? 32 : 16), number.Stack - rise, color, alpha)); + } + return result; + } + + private static int Round(float value) => (int)Math.Round(value, MidpointRounding.ToEven); + + public void Clear() + { + _numbers.Clear(); + _stacks.Clear(); + _eventCursor = 0; + _tick = 0; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberProjection.cs.meta b/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberProjection.cs.meta new file mode 100644 index 00000000..25b7fd43 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleNumberProjection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1369bc4f24a345d3a30dfd3becbcdaeb diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleStageMessageProjection.cs b/Assets/Scripts/Pal3.Battle/Presentation/BattleStageMessageProjection.cs new file mode 100644 index 00000000..009c5f23 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleStageMessageProjection.cs @@ -0,0 +1,51 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle.Presentation +{ + using System; + using System.Collections.Generic; + using System.Linq; + + // UIStaticCB's reference count belongs to presentation. A native Trail + // suppresses Name/Flee/ambush callers permanently, while items keep showing. + // This projection cannot shorten a domain wait or consume a random number. + public sealed class BattleStageMessageProjection + { + private readonly HashSet _seen = new(); + private readonly Dictionary _visible = new(); + private readonly BattleStageMessageSnapshot[] _last = new BattleStageMessageSnapshot[2]; + + public IReadOnlyList Messages => Array.AsReadOnly(_last + .Where(message => message != null && _visible.Values.Any(reference => reference.Side == message.Side)).ToArray()); + + public int VisibleReferenceCount(BattleSide side) => _visible.Values.Count(message => message.Side == side); + + public void Synchronize(IReadOnlyList references, bool trail) + { + if (references == null) + throw new ArgumentNullException(nameof(references)); + var active = new HashSet(references.Select(message => message.ReferenceId)); + _seen.RemoveWhere(reference => !active.Contains(reference)); + foreach (long reference in _visible.Keys.ToArray()) + if (!active.Contains(reference) || trail && !_visible[reference].AllowTrail) + _visible.Remove(reference); + foreach (BattleStageMessageSnapshot message in references) + { + if (!_seen.Add(message.ReferenceId) || trail && !message.AllowTrail) + continue; + _visible.Add(message.ReferenceId, message); + _last[(int)message.Side] = message; + } + } + + public void Clear() + { + _seen.Clear(); + _visible.Clear(); + Array.Clear(_last, 0, _last.Length); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleStageMessageProjection.cs.meta b/Assets/Scripts/Pal3.Battle/Presentation/BattleStageMessageProjection.cs.meta new file mode 100644 index 00000000..7dd8f003 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleStageMessageProjection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1857f5a6e6b34da39e038ac386e7a093 diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleSwordSparkProjection.cs b/Assets/Scripts/Pal3.Battle/Presentation/BattleSwordSparkProjection.cs new file mode 100644 index 00000000..4e9db97d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleSwordSparkProjection.cs @@ -0,0 +1,128 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle.Presentation +{ + using System; + using System.Collections.Generic; + + public readonly struct BattleSwordSparkFrame + { + public float X + { + get; + } + + public float Y + { + get; + } + + public float Size + { + get; + } + + public byte Alpha + { + get; + } + + public BattleSwordSparkFrame(float x, float y, float size, byte alpha) + { + X = x; + Y = y; + Size = size; + Alpha = alpha; + } + } + + // PAL3 C2DSpark::CreateStars/Update. The clock and C-runtime random stream + // belong to this decoration, separately from battle and effect randomness. + public sealed class BattleSwordSparkProjection + { + private sealed class Spark + { + public float X, Y, VelocityY, AccelerationY, Luminosity, Size; + + public bool Alive => X < 800 && X > -Size && Y < 600 && Y > -Size && + Luminosity > 1 && Luminosity <= 255 && Size >= .01f; + + public void Advance(float seconds) + { + VelocityY += seconds * AccelerationY; + Y += seconds * VelocityY; + Luminosity -= seconds * 100; + } + } + + private readonly List _sparks = new(); + private readonly BattleRandom _random; + private float _lastEmission; + + public double Time + { + get; private set; + } + + public IReadOnlyList Frames + { + get + { + var frames = new BattleSwordSparkFrame[_sparks.Count]; + for (int index = 0; index < frames.Length; index++) + { + Spark spark = _sparks[index]; + byte alpha = (byte)Math.Clamp((int)Math.Round(spark.Luminosity, MidpointRounding.ToEven), 0, 255); + frames[index] = new BattleSwordSparkFrame(spark.X, spark.Y, spark.Size, alpha); + } + return Array.AsReadOnly(frames); + } + } + + public BattleSwordSparkProjection(int seed) => _random = new BattleRandom(seed); + + public void Advance(double seconds, bool emit, float energy) + { + if (!double.IsFinite(seconds) || seconds < 0 || !float.IsFinite(energy) || energy < 0) + throw new ArgumentOutOfRangeException(nameof(seconds)); + if (seconds == 0) + return; + Time += seconds; + float now = (float)Time; + // CCBRoleState stores GetTime() as float, uses a strict boundary, + // and emits once per pass rather than catching up a stalled frame. + if (emit && now - _lastEmission > .1f) + { + Emit(energy); + if (energy > 199.9f) + Emit(energy); + _lastEmission = now; + } + // RoleState creates the stars before CCBSystem updates C2DSpark. + foreach (Spark spark in _sparks) + spark.Advance((float)seconds); + _sparks.RemoveAll(spark => !spark.Alive); + } + + private void Emit(float energy) + { + float size = energy / 10; + var spark = new Spark + { + Size = size, + VelocityY = -10, + Luminosity = 250 - _random.Next() % 50, + X = 25 - size / 2 - 10 + _random.Next() % 20, + Y = 570 - size / 2 - 20 + _random.Next() % 40, + AccelerationY = -(_random.Next() % (size < 19 ? 50 : 100)) + }; + if (_sparks.Count < 512) + _sparks.Add(spark); + } + + public void Clear() => _sparks.Clear(); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Presentation/BattleSwordSparkProjection.cs.meta b/Assets/Scripts/Pal3.Battle/Presentation/BattleSwordSparkProjection.cs.meta new file mode 100644 index 00000000..4e2fc91b --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/BattleSwordSparkProjection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6559b6e6826346a29a37c9901fff5f3e diff --git a/Assets/Scripts/Pal3.Battle/Presentation/Pal3.Battle.Presentation.asmdef b/Assets/Scripts/Pal3.Battle/Presentation/Pal3.Battle.Presentation.asmdef new file mode 100644 index 00000000..e511b356 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/Pal3.Battle.Presentation.asmdef @@ -0,0 +1,7 @@ +{ + "name": "Pal3.Battle.Presentation", + "references": [ + "Pal3.Battle" + ], + "noEngineReferences": true +} diff --git a/Assets/Scripts/Pal3.Battle/Presentation/Pal3.Battle.Presentation.asmdef.meta b/Assets/Scripts/Pal3.Battle/Presentation/Pal3.Battle.Presentation.asmdef.meta new file mode 100644 index 00000000..9b2c1c0f --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Presentation/Pal3.Battle.Presentation.asmdef.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f13a3757cf3343b6800baa424e20ec47 diff --git a/Assets/Scripts/Pal3.Battle/README.md b/Assets/Scripts/Pal3.Battle/README.md new file mode 100644 index 00000000..66e97f6b --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/README.md @@ -0,0 +1,21 @@ +# Battle core + +This assembly is independent of Unity and original binary readers. It owns captured battle definitions, deterministic rules, authoritative state, fixed-clock execution, commands and replay. + +| Directory | Responsibility | +| --- | --- | +| `Configuration` | Mutable authoring DTOs and deep-copied initial setup. | +| `Contracts` | Immutable actor/ability/equipment definitions and state snapshots. | +| `Runtime` | Commands, ordered inputs/events, replay and variant state. `Session` contains the one authoritative state writer, split by mechanism. | +| `Rules` | Verified original calculations and policy; AI selection is grouped under `AI`. | +| `Stage` | Logical body/movement/camera/effect protocols and scheduling. These timings determine Work callbacks and rule execution, so they stay in the core. | +| `Presentation` | Separate engine-independent assembly for semantic HUD intent, focus, selection and visual projections; references the battle kernel. | +| `Results` | Immutable results and the result/body presentation protocol. | + +The resource adapter compiles metadata before play. The core never searches resources, polls devices or derives simulation time from rendering. UI queries must not advance state or consume RNG. Snapshots and replay inputs must preserve ownership and ordering. + +`IBattleRules` currently customizes the small basic battle ruleset. Full original battles compose the verified mechanic rules; this is not yet an arbitrary rule-plugin interface. Extend an actual mechanic through definitions/commands and its explicit execution boundary, then update deterministic replay coverage. Replay always uses the current implementation with captured setup, definitions and inputs; it has no rules-version negotiation or legacy execution paths. Resource fingerprints identify the captured data. + +`Pal3.Battle.Presentation` owns semantic HUD intent, focus, selection and menu state. Unity resource/rendering and editor interaction live in `Editor/BattleEditor`. The existing story-side `Pal3.Game/GameSystems/Battle` remains a separate placeholder until inventory, story outcome and save adapters are connected to this kernel. + +`Presentation/` is physically nested here but owns its own asmdef, so Unity excludes it from the kernel assembly. A standalone SDK project must likewise exclude `Presentation/**/*.cs` from the kernel and build that folder as a separate project referencing the kernel. diff --git a/Assets/Scripts/Pal3.Battle/README.md.meta b/Assets/Scripts/Pal3.Battle/README.md.meta new file mode 100644 index 00000000..452fd310 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/README.md.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b22194c5b35041f48f4be1d807371dc4 diff --git a/Assets/Scripts/Pal3.Battle/Results.meta b/Assets/Scripts/Pal3.Battle/Results.meta new file mode 100644 index 00000000..494e122b --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8a10da2b9c414bdaa7e0601e9668e7e0 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleActorReward.cs b/Assets/Scripts/Pal3.Battle/Results/BattleActorReward.cs new file mode 100644 index 00000000..e36dcc32 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleActorReward.cs @@ -0,0 +1,54 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleActorReward + { + public string Actor + { + get; internal set; + } + + public int ExperienceGained + { + get; internal set; + } + + public int LevelBefore + { + get; internal set; + } + + public int LevelAfter + { + get; internal set; + } + + public int ExperienceBefore + { + get; internal set; + } + + public int ExperienceAfter + { + get; internal set; + } + + public IReadOnlyList AttributesBefore + { + get; internal set; + } + + public IReadOnlyList AttributesAfter + { + get; internal set; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleActorReward.cs.meta b/Assets/Scripts/Pal3.Battle/Results/BattleActorReward.cs.meta new file mode 100644 index 00000000..7b892772 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleActorReward.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ba456509be134273b8e6996ff7a94053 diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleResult.cs b/Assets/Scripts/Pal3.Battle/Results/BattleResult.cs new file mode 100644 index 00000000..c197cc65 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleResult.cs @@ -0,0 +1,105 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + + public sealed class BattleResult + { + public int SettlementEventStart + { + get; internal set; + } + + public IReadOnlyList PreSettlementActors + { + get; internal set; + } + + public bool GameOver + { + get; internal set; + } + + public BattleSessionStatus Status + { + get; internal set; + } + + public BattleSide? Winner + { + get; internal set; + } + + public string Reason + { + get; internal set; + } + + public long Tick + { + get; internal set; + } + + public IReadOnlyList Actors + { + get; internal set; + } + + public IReadOnlyList TreasureUses + { + get; internal set; + } + + public IReadOnlyList StealPools + { + get; internal set; + } + + public IReadOnlyDictionary MagicSwords + { + get; internal set; + } + + public int MoneyBefore + { + get; internal set; + } + + public int MoneyAfter + { + get; internal set; + } + + public BattlePal3AStateSnapshot Pal3A + { + get; internal set; + } + + public bool Escaped + { + get; internal set; + } + + public IReadOnlyList Rewards + { + get; internal set; + } + + public IReadOnlyList Items + { + get; internal set; + } + + public IReadOnlyList Loot + { + get; internal set; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleResult.cs.meta b/Assets/Scripts/Pal3.Battle/Results/BattleResult.cs.meta new file mode 100644 index 00000000..d1874197 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleResult.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b041a029c9654643afa42da7cdd782bf diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleResultPresentation.cs b/Assets/Scripts/Pal3.Battle/Results/BattleResultPresentation.cs new file mode 100644 index 00000000..6220431b --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleResultPresentation.cs @@ -0,0 +1,283 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public enum BattleResultStepKind + { + MusicFadeOut, WinBanner, LoseBanner, Statistics, LevelUpBody, LevelUp, SkillLearned, SkillImproved, Money, Item, Wait, MusicFadeIn, ScreenFadeOut + } + + // A captured presentation command contains no mutable inventory or actor state. + public sealed class BattleResultStep + { + public BattleResultStepKind Kind + { + get; + } + + public float Duration + { + get; + } + + public string Actor + { + get; + } + + public int Id + { + get; + } + + public int Value + { + get; + } + + public bool CanSkip => Kind is not (BattleResultStepKind.MusicFadeOut or BattleResultStepKind.MusicFadeIn or BattleResultStepKind.LevelUpBody); + + public BattleResultStep(BattleResultStepKind kind, float duration, string actor = null, int id = 0, int value = 0) + { + if (!float.IsFinite(duration) || duration < 0) + throw new ArgumentOutOfRangeException(nameof(duration)); + Kind = kind; + Duration = duration; + Actor = actor; + Id = id; + Value = value; + } + } + + public interface IBattleResultBodyPort + { + bool TryStartLevelUp(string actor); + } + + // Result commit stays in BattleSession. This independent 50Hz clock only + // presents its captured report and can be replayed without settling again. + public sealed class BattleResultPresentation + { + private readonly IReadOnlyList _sequence; + private readonly IReadOnlyList _presentationActors, _finalActors; + private readonly IBattleResultBodyPort _bodies; + private bool _executed; + private float _startTime, _time; + private double _accumulator; + + public IReadOnlyList Sequence => _sequence; + + // A escape recovers HP only after its result tasks. The authoritative + // final commit stays unchanged while the show retains pre-recovery HP. + public IReadOnlyList Actors => Completed ? _finalActors : _presentationActors; + + public int Index + { + get; private set; + } + + public long Tick + { + get; private set; + } + + public BattleResultStep Current => Completed ? null : _sequence[Index]; + + public bool Completed => Index >= _sequence.Count; + + public bool HasExecuted => _executed; + + public bool CanSkip => _executed && Current?.CanSkip == true; + + public int CameraList + { + get; + } + + public bool StatisticsVisible + { + get; private set; + } + + public double StatisticsSeconds + { + get; private set; + } + + public float Elapsed => Math.Max(0, _time - _startTime); + + public float ScreenOpacity + { + get; private set; + } + + public float MusicGain { get; private set; } = 1; + + public int MusicStopCount + { + get; private set; + } + + public BattleResultPresentation(string variant, BattleResult result, IReadOnlyList events, IBattleResultBodyPort bodies = null) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown game variant.", nameof(variant)); + if (result == null || events == null || result.Status != BattleSessionStatus.Completed) + throw new ArgumentException("A committed completed result and its full event stream are required."); + if (result.SettlementEventStart < 0 || result.SettlementEventStart > events.Count) + throw new ArgumentException("Settlement event range is outside the supplied stream."); + _bodies = bodies; + _finalActors = Array.AsReadOnly(result.Actors.ToArray()); + _presentationActors = Array.AsReadOnly(result.Actors.Select(actor => + variant == "PAL3A" && result.Escaped && actor.Side == BattleSide.Ally && + result.PreSettlementActors.First(before => before.Id == actor.Id).Hp == 0 + ? result.PreSettlementActors.First(before => before.Id == actor.Id) : actor).ToArray()); + CameraList = result.Escaped ? 8 : result.Winner == BattleSide.Ally ? 3 : 10; + var steps = new List(); + void Add(BattleResultStepKind kind, float duration) => steps.Add(new BattleResultStep(kind, duration)); + bool win = result.Winner == BattleSide.Ally && !result.Escaped; + if (!result.Escaped) + { + Add(BattleResultStepKind.MusicFadeOut, .5f); + Add(win ? BattleResultStepKind.WinBanner : BattleResultStepKind.LoseBanner, win ? 3 : 5); + } + if (win || result.Escaped) + { + Add(BattleResultStepKind.Statistics, 2); + foreach (BattleEvent entry in events.Skip(result.SettlementEventStart)) + { + BattleResultStep step = entry.Kind switch + { + BattleEventKind.LevelUp => new BattleResultStep(BattleResultStepKind.LevelUp, 5, entry.Source, + value: result.Rewards.First(reward => reward.Actor == entry.Source).LevelAfter), + BattleEventKind.SkillLearned => new BattleResultStep(BattleResultStepKind.SkillLearned, 5, entry.Source, entry.AbilityId), + BattleEventKind.SkillImproved => new BattleResultStep(BattleResultStepKind.SkillImproved, 5, entry.Source, entry.AbilityId, entry.ValueAfter), + BattleEventKind.ResourceChanged when entry.Resource == 10 && entry.RequestedDelta > 0 => + new BattleResultStep(BattleResultStepKind.Money, 5, value: entry.RequestedDelta), + BattleEventKind.ItemChanged when entry.RequestedDelta > 0 => + new BattleResultStep(BattleResultStepKind.Item, 4, id: entry.AbilityId, value: entry.RequestedDelta), + _ => null + }; + if (step != null) + { + if (variant == "PAL3A" && step.Kind == BattleResultStepKind.LevelUp) + steps.Add(new BattleResultStep(BattleResultStepKind.LevelUpBody, 0, step.Actor, value: step.Value)); + steps.Add(step); + } + } + Add(BattleResultStepKind.Wait, result.Escaped ? variant == "PAL3A" ? 3 : 15 : 5); + } + if (!result.Escaped) + { + if (!win) + Add(BattleResultStepKind.ScreenFadeOut, 1); + Add(BattleResultStepKind.MusicFadeIn, .2f); + if (win) + Add(BattleResultStepKind.ScreenFadeOut, 1); + } + _sequence = steps.AsReadOnly(); + } + + public void Advance(double seconds) + { + if (!double.IsFinite(seconds) || seconds < 0 || seconds > 60) + throw new ArgumentOutOfRangeException(nameof(seconds)); + _accumulator += seconds; + while (_accumulator + 1e-12 >= BattleSession.StepSeconds && !Completed) + { + _accumulator -= BattleSession.StepSeconds; + Step(); + } + } + + public void CloseStatistics() + { + StatisticsVisible = false; + if (Current?.Kind == BattleResultStepKind.Statistics && _executed) + FinishCurrent(); + } + + public bool SkipCurrent() + { + if (!CanSkip) + return false; + FinishCurrent(); + return true; + } + + public void Step() + { + if (Completed) + return; + Tick++; + _time = (float)(Tick * BattleSession.StepSeconds); + if (StatisticsVisible) + StatisticsSeconds += BattleSession.StepSeconds; + if (!_executed) + { + if (Current.Kind == BattleResultStepKind.LevelUpBody) + { + if (_bodies != null && !_bodies.TryStartLevelUp(Current.Actor)) + return; + FinishCurrent(); + if (Completed) + return; + } + _executed = true; + if (Current.Kind == BattleResultStepKind.Statistics) + { + StatisticsVisible = true; + StatisticsSeconds = 0; + } + if (Current.Kind is not (BattleResultStepKind.MusicFadeOut or BattleResultStepKind.MusicFadeIn)) + return; + } + float elapsed = Elapsed; + switch (Current.Kind) + { + case BattleResultStepKind.MusicFadeOut: + MusicGain = Math.Clamp(1 - elapsed / Current.Duration, 0, 1); + break; + case BattleResultStepKind.MusicFadeIn: + // Both shipped callbacks use this reversed ramp, then restore + // the saved volume only when the strict end boundary passes. + MusicGain = Math.Clamp(1 - elapsed / Current.Duration, 0, 1); + break; + case BattleResultStepKind.ScreenFadeOut: + ScreenOpacity = Math.Clamp(elapsed / Current.Duration, 0, 1); + break; + } + if (Current.Kind == BattleResultStepKind.Wait ? elapsed >= Current.Duration : elapsed > Current.Duration) + FinishCurrent(); + } + + private void FinishCurrent() + { + if (Current.Kind == BattleResultStepKind.MusicFadeOut) + { + MusicGain = 0; + MusicStopCount++; + } + if (Current.Kind == BattleResultStepKind.MusicFadeIn) + MusicGain = 1; + if (Current.Kind == BattleResultStepKind.ScreenFadeOut) + ScreenOpacity = 1; + Index++; + _executed = false; + _startTime = _time; + if (Completed) + { + // The standalone editor retains a useful inspection viewport. + ScreenOpacity = 0; + StatisticsVisible = false; + } + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleResultPresentation.cs.meta b/Assets/Scripts/Pal3.Battle/Results/BattleResultPresentation.cs.meta new file mode 100644 index 00000000..f2348fe0 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleResultPresentation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c21af581ca28443fb11e6257c93730ff diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleResultRoleBody.cs b/Assets/Scripts/Pal3.Battle/Results/BattleResultRoleBody.cs new file mode 100644 index 00000000..66656afd --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleResultRoleBody.cs @@ -0,0 +1,194 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + + public readonly struct BattleResultBodyState + { + public int Hp + { + get; + } + + public int MaxHp + { + get; + } + + public bool Guarding + { + get; + } + + public bool Sleeping + { + get; + } + + public bool Paralyzed + { + get; + } + + public BattleResultBodyState(int hp, int maxHp, bool guarding = false, bool sleeping = false, bool paralyzed = false) + { + if (hp < 0 || maxHp < 1) + throw new ArgumentOutOfRangeException(nameof(hp)); + Hp = hp; + MaxHp = maxHp; + Guarding = guarding; + Sleeping = sleeping; + Paralyzed = paralyzed; + } + + // Both published GetProperCurAction routines inspect HP rather than + // the separate life/model flags. Guard precedes sleep and low HP. + public int ProperAction => Hp == 0 && MaxHp / 4 > 0 ? 47 : Guarding ? 42 : Sleeping || Paralyzed ? 45 : Hp < MaxHp / 4 ? 46 : 32; + } + + public enum BattleResultBodyOwner + { + None, Victory, LevelUp, External + } + + // A role owns its task/FIFO independently of the result text timeline. + // Stage ownership is released before role Update on the following pass. + public sealed class BattleResultRoleBody + { + private readonly IReadOnlyDictionary _animations; + private readonly BattleResultBodyState _state; + private readonly float _activeRate; + private int? _task; + private bool _executed; + + private readonly BattleBodyAnimationBinding _binding; + + public BattleBodyAnimationBinding Binding => _binding.Clone(); + + public float PlaybackRate + { + get; private set; + } + + public float BladeSeconds { get; private set; } = .01f; + + public bool HasTask => _task.HasValue; + + public bool VictoryCompleted + { + get; private set; + } + + public BattleResultBodyOwner Owner + { + get; private set; + } + + public bool NormalGrab + { + get; private set; + } + + public BattleResultRoleBody(string variant, BattleBodyAnimationBinding initial, + IReadOnlyDictionary animations, BattleResultBodyState state, bool victory = false) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown game variant.", nameof(variant)); + _binding = initial?.Clone() ?? throw new ArgumentNullException(nameof(initial)); + _animations = animations ?? throw new ArgumentNullException(nameof(animations)); + _state = state; + _activeRate = variant == "PAL3" ? 1.3f : 1; + PlaybackRate = _binding.RequestedNativeActionIndex == 32 ? .65f : _activeRate; + if (victory) + { + Owner = BattleResultBodyOwner.Victory; + NormalGrab = true; + if (state.Sleeping || state.Paralyzed) + VictoryCompleted = true; + else + _task = 49; + } + } + + public void PrepareStagePass() + { + if (Owner == BattleResultBodyOwner.Victory && VictoryCompleted) + Release(); + } + + public bool TryGrab(BattleResultBodyOwner owner, bool normalGrab) + { + if (owner == BattleResultBodyOwner.None || Owner != BattleResultBodyOwner.None) + return false; + Owner = owner; + NormalGrab = normalGrab; + return true; + } + + public void Release() + { + _task = null; + _executed = false; + Owner = BattleResultBodyOwner.None; + NormalGrab = false; + } + + public bool TryStartLevelUp() + { + if (Owner != BattleResultBodyOwner.None) + { + if (NormalGrab) + return false; + Release(); + } + TryGrab(BattleResultBodyOwner.LevelUp, true); + _task = 59; + _executed = false; + return true; + } + + public void Step() + { + // Actor.Update captures this rate before DoTask can change action. + PlaybackRate = _binding.RequestedNativeActionIndex == 32 ? .65f : _activeRate; + _binding.PopMessage(); + if (!_task.HasValue) + { + int action = _state.ProperAction; + BladeSeconds = action == 42 ? .25f : .01f; + if (_binding.RequestedNativeActionIndex != action) + { + _binding.SetRequestedNativeAction(action); + _binding.TryPlay(_animations.GetValueOrDefault(action), true); + } + } + else if (!_executed) + { + BladeSeconds = .25f; + _binding.SetRequestedNativeAction(_task.Value); + _binding.TryPlay(_animations.GetValueOrDefault(_task.Value), false); + _binding.ClearMessages(); + _executed = true; + } + else if (_binding.LastPoppedMarker == BattlePhysicalMarkerKind.Over) + { + if (_task == 49) + { + BladeSeconds = .01f; + VictoryCompleted = true; + } + // ClearFinishedTask removes the task but does not change this + // pass's action/clip. Proper action is chosen on the next pass. + _task = null; + _executed = false; + } + _binding.Advance(PlaybackRate); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleResultRoleBody.cs.meta b/Assets/Scripts/Pal3.Battle/Results/BattleResultRoleBody.cs.meta new file mode 100644 index 00000000..4df3aea4 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleResultRoleBody.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d0618fbbaca6b4fd8a29153ce4424154 diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleResultStatistics.cs b/Assets/Scripts/Pal3.Battle/Results/BattleResultStatistics.cs new file mode 100644 index 00000000..4a979621 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleResultStatistics.cs @@ -0,0 +1,45 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public static class BattleResultStatistics + { + // Both shipped UI callbacks publish float task time, retain the + // gravity product through x87 and truncate the final MoveWindow pixel. + public static int CardY(int column, double seconds) + { + if (column < 0 || column > 4 || !double.IsFinite(seconds) || seconds < 0) + throw new ArgumentOutOfRangeException(nameof(seconds)); + float now = (float)seconds; + float start = column * .08f; + if (now <= start) + return -256; + double elapsed = (double)now - start; + return (int)Math.Min(0, elapsed * elapsed * 1500d - 256d); + } + + public static IReadOnlyList MagicUseCounts(string variant, BattleDefinitions definitions, int identity, IReadOnlyList skills) + { + IReadOnlyList slots = BattleMagicSlots.Capture(variant, definitions, identity, skills); + return Array.AsReadOnly(Enumerable.Range(0, 6).Select(group => slots.Where(slot => slot.Group == group) + .Sum(slot => skills.FirstOrDefault(skill => skill.Id == slot.SkillId)?.Uses ?? 0)).ToArray()); + } + + // Native reward accumulation can wrap to a negative signed int32 gain. + // Animate that committed value without changing the settlement result. + public static int Experience(int gained, double seconds) + { + if (!double.IsFinite(seconds) || seconds < 0) + throw new ArgumentOutOfRangeException(nameof(seconds)); + float ratio = Math.Clamp((float)seconds / 2f, 0, 1); + return BattleBasicRules.Round(gained * ratio); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleResultStatistics.cs.meta b/Assets/Scripts/Pal3.Battle/Results/BattleResultStatistics.cs.meta new file mode 100644 index 00000000..fb646923 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleResultStatistics.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 933edc626c21488c93021ccd6512ac90 diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleVictoryBody.cs b/Assets/Scripts/Pal3.Battle/Results/BattleVictoryBody.cs new file mode 100644 index 00000000..e4976c28 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleVictoryBody.cs @@ -0,0 +1,33 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System.Collections.Generic; + + // A single Win task uses the same result role controller as character + // level-up tasks. Completion leaves action49 until the next free pass. + public sealed class BattleVictoryBody + { + private readonly BattleResultRoleBody _role; + + public BattleBodyAnimationBinding Binding => _role.Binding; + + public bool Completed => _role.VictoryCompleted; + + public float PlaybackRate => _role.PlaybackRate; + + public float BladeSeconds => _role.BladeSeconds; + + public BattleVictoryBody(string variant, BattleBodyAnimationBinding initial, + BattlePhysicalAnimation win, BattlePhysicalAnimation idle) + { + _role = new BattleResultRoleBody(variant, initial, new Dictionary { [49] = win, [32] = idle }, + new BattleResultBodyState(100, 100), true); + } + + public void Step() => _role.Step(); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Results/BattleVictoryBody.cs.meta b/Assets/Scripts/Pal3.Battle/Results/BattleVictoryBody.cs.meta new file mode 100644 index 00000000..85613eb3 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Results/BattleVictoryBody.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b7a750c01dd14885a0696b27b5cd2e2e diff --git a/Assets/Scripts/Pal3.Battle/Rules.meta b/Assets/Scripts/Pal3.Battle/Rules.meta new file mode 100644 index 00000000..ea796817 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8c87af2958784982afbada1038648faa +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI.meta b/Assets/Scripts/Pal3.Battle/Rules/AI.meta new file mode 100644 index 00000000..cd24be2e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f33a05f216934fa1a9010f6ba6255dca +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAi.cs b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAi.cs new file mode 100644 index 00000000..1de086a3 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAi.cs @@ -0,0 +1,500 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using static BattleAiAttemptKind; + using D = BattleAiDemandKind; + + public sealed partial class BattleAi + { + private readonly bool _pal3A; + private readonly BattleRandom _random; + private readonly BattleAiPort _port; + + public BattleAiRole[] Roles { get; } = new BattleAiRole[11]; + public BattleAiDemand[,] Demand { get; } = new BattleAiDemand[11, 10]; + public BattleAiDemand[] FriendDemand { get; } = new BattleAiDemand[10]; + public BattleAiDemand[] EnemyDemand { get; } = new BattleAiDemand[10]; + public bool[] NewRole { get; } = new bool[11]; + public IReadOnlyList Items { get; set; } = Array.Empty(); + + public bool Automatic + { + get; private set; + } + + public BattleAi(bool pal3A, BattleRandom random, BattleAiPort port) + { + _pal3A = pal3A; + _random = random ?? throw new ArgumentNullException(nameof(random)); + if (random.Variant != (pal3A ? "PAL3A" : "PAL3")) + throw new ArgumentException("The AI and random stream variants differ.", nameof(random)); + _port = port ?? throw new ArgumentNullException(nameof(port)); + for (int role = 0; role < 11; role++) + { + Roles[role] = new BattleAiRole(); + NewRole[role] = true; + for (int kind = 0; kind < 10; kind++) + Demand[role, kind] = new BattleAiDemand(); + } + for (int kind = 0; kind < 10; kind++) + { + FriendDemand[kind] = new BattleAiDemand(); + EnemyDemand[kind] = new BattleAiDemand(); + } + } + + public static int HpState(int current, int maximum) + { + if (current == maximum) + return 1; + if (current >= maximum / 2 && current < maximum) + return 2; + if (current >= maximum / 4) + return 3; + return current > 0 ? 4 : 5; + } + + public void SetAutomatic(bool enabled, bool only = false) + { + Automatic = enabled; + if (!only) + { + for (int role = 0; role < 5; role++) + Roles[role].Profile.SetEnabled(enabled); + } + } + + public void UpdateDemands() + { + CheckDemands(); + TraceDemands(); + } + + public void CheckDemands() + { + for (int role = 0; role < 11; role++) + { + BattleAiRole actor = Roles[role]; + if (!actor.Valid) + continue; + SetDemand(role, D.Revive, actor.Alive ? 100 : 0, actor.Alive); + int state = HpState(actor.Hp, actor.MaxHp); + SetDemand(role, D.Recover, state >= 3 ? 40 : 100, state < 3); + SetDemand(role, D.BeAttack, state >= 3 ? 40 : 80, state < 3); + if (state == 4) + { + SetDemand(role, D.Recover, 10); + SetDemand(role, D.BeAttack, 10); + } + BattleAiDemand bad = Demand[role, (int)D.BadSpecStateRecover]; + if (!actor.BadState) + bad.Satisfy = 100; + else if (!bad.Handled) + { + bad.State = actor.WorstBadState; + bad.Satisfy = 50; + } + } + CheckGroupDemand(false); + CheckGroupDemand(true); + } + + public void TraceDemands() + { + for (int role = 0; role < 11; role++) + { + if (!Roles[role].Valid) + continue; + for (int kind = 1; kind < 10; kind++) + TraceDemand(Demand[role, kind]); + } + for (int kind = 1; kind < 10; kind++) + { + TraceDemand(FriendDemand[kind]); + TraceDemand(EnemyDemand[kind]); + } + } + + private void TraceDemand(BattleAiDemand demand) + { + if (demand.ActionId < 0) + return; + if (_port.IsActionActive(demand.ActionId)) + { + demand.Handled = true; + demand.Satisfy = 100; + } + else + { + demand.ActionId = -1; + demand.Handled = false; + } + } + + private void SetDemand(int role, D kind, int satisfy, bool force = false) + { + BattleAiDemand demand = Demand[role, (int)kind]; + if (force || !demand.Handled) + demand.Satisfy = satisfy; + } + + private void CheckGroupDemand(bool enemy) + { + int count = 0; + for (int role = enemy ? 5 : 0; role < (enemy ? 11 : 5); role++) + { + if (Roles[role].Valid && HpState(Roles[role].Hp, Roles[role].MaxHp) >= 3) + count++; + } + int satisfy = count < 2 ? 100 : count == 2 ? 60 : count == 3 ? 40 : 20; + BattleAiDemand[] group = enemy ? EnemyDemand : FriendDemand; + if (!group[(int)D.Recover].Handled) + group[(int)D.Recover].Satisfy = satisfy + 10; + if (!group[(int)D.BeAttack].Handled) + group[(int)D.BeAttack].Satisfy = enemy ? 100 - satisfy : satisfy; + } + + private bool Try(BattleAiAttemptKind kind, int source, int target = -1, BattleAiDemand demand = null, int ability = 0) + { + long action = _port.TryAttempt(new BattleAiAttempt(kind, source, target, demand, ability)); + // The original BossPhysical entry always returns false, even if a future adapter is permissive. + if (kind == BossPhysical || action < 0) + return false; + if (demand != null && kind is not (AttackBigMagic or FiveSpiritMagic or FiveSpiritBigMagic)) + demand.ActionId = action; + return true; + } + + private BattleAiDemand At(int target, D kind) => Demand[target, (int)kind]; + + private static bool Needs(BattleAiDemand demand) => demand.Satisfy < 100; + + private bool MadTarget(int source) => Roles[source].Madness && _random.Next() % 10 > 7; + + private bool ChaosTarget(int source) => Roles[source].Chaos && _random.Next() % 10 > 7; + + public static bool IsSpecialBossReady(BattleAiRole role) + => role.Identity == 739 && role.Mp == role.MaxMp; + + public bool HandleSpecialBoss(int source) + => IsSpecialBossReady(Roles[source]) && Try(SpecAI, source, ability: 7709); + + // Use this inside the real CastNormalAttack adapter, after observing the attempt. + // Formation and initial-position predicates come from the same session snapshot as commands. + public bool CanNormalAttack(int source, int target, bool invisible, bool wall, bool mirror, bool atInitialPosition) + { + BattleAiRole actor = Roles[source]; + BattleAiRole destination = Roles[target]; + if (source == target || !actor.Profile.Attack && !actor.Chaos && !actor.Madness) + return false; + if (!actor.Valid || !destination.Valid || !actor.Alive || !destination.Alive || !_pal3A && invisible) + return false; + if (wall && mirror && (source < 5 || _random.Probability(70))) + return false; + return atInitialPosition && _port.CanAttackBack(source, target); + } + + public bool CapabilityEnabled(int source, BattleAiAttemptKind kind) + { + BattleAiRole actor = Roles[source]; + if (kind == Normal) + return actor.Profile.Attack || actor.Chaos || actor.Madness; + if (kind == BossPhysical) + return false; + if (kind == SpecAI) + return IsSpecialBossReady(actor); + if (_pal3A && kind is SelectedMiscMagic or FiveSpiritMagic or FiveSpiritBigMagic) + return !actor.Madness; + bool enabled = kind is RecoverSkill or RecoverBigSkill or AttackSkill or AttackBigSkill or ReviveSkill or CureSkill ? actor.Profile.Skill + : kind is RecoverItem or RecoverBigItem or AttackItem or AttackBigItem or ReviveItem or CureItem ? actor.Profile.Item : actor.Profile.Magic; + return (enabled || actor.Chaos) && !actor.Madness; + } + + public bool HandleEnemy(int source) + { + if (!Roles[source].Valid || !Roles[source].Alive) + return false; + int state = HpState(Roles[source].Hp, Roles[source].MaxHp); + if (state == 5) + return false; + return Roles[source].Chaos ? HandleEnemyChaos(source) : HandleEnemyState(source, state <= 2 ? 0 : state == 3 ? 1 : 2); + } + + // Exposed for native-function oracle tests, which invoke these three entry points directly. + public bool HandleEnemyState(int source, int condition) + { + if (condition < 0 || condition > 2) + throw new ArgumentOutOfRangeException(nameof(condition)); + if (condition == 0 && Try(SpecAI, source, ability: IsSpecialBossReady(Roles[source]) ? 7709 : 0)) + return true; + int start = 0; + for (; start < 11; start++) + { + if (_random.Next() % 3 == 1 && Roles[start].Valid) + break; + } + if (start == 10) + start = 0; + for (int target = start; target < 11; target++) + { + BattleAiRole actor = Roles[target]; + if (!actor.Valid || !actor.Alive || actor.EnemyFriend) + continue; + if (_pal3A && condition == 2 && Roles[source].Identity == 7325) + { + if (Try(RecoverMagic, source, source, At(target, D.Recover)) || Try(RecoverBigMagic, source, demand: At(target, D.Recover))) + return true; + } + bool firstAttack = condition == 2 + ? target < 5 || MadTarget(source) && Needs(At(target, D.OneHit)) + : (target < 5 || MadTarget(source) || ChaosTarget(source)) && Needs(At(target, D.OneHit)); + if (firstAttack && Try(Normal, source, target, At(target, D.OneHit))) + return true; + if (Needs(EnemyDemand[(int)D.Recover]) && Try(RecoverBigMagic, source, demand: EnemyDemand[(int)D.Recover])) + return true; + if (condition > 0 && target == source && Needs(At(target, D.Recover))) + { + if (Try(RecoverMagic, source, target, At(target, D.Recover))) + return true; + if (condition == 2 && Try(RecoverBigMagic, source, demand: At(target, D.Recover))) + return true; + } + if (target >= 5 && Needs(At(target, D.Recover)) && Try(RecoverMagic, source, target, At(target, D.Recover))) + return true; + if (target >= 5 && Needs(At(target, D.BadSpecStateRecover)) && _random.Probability(50) && Try(CureMagic, source, target, At(target, D.BadSpecStateRecover))) + return true; + if (_pal3A ? HandlePal3AAdditional(source, target, condition) : HandlePal3Remainder(source, target, condition)) + return true; + } + return false; + } + + private bool HandlePal3Remainder(int source, int target, int condition) + { + BattleAiDemand group = FriendDemand[(int)D.BeAttack]; + if (Needs(group)) + { + if (_random.Probability(condition == 0 ? 37 : 25) && Try(AttackBigMagic, source, demand: group)) + return true; + if (Roles[source].Boss && _random.Probability(30) && Try(BossPhysical, source, demand: group)) + return true; + } + if (condition > 0 && HandleElementDemands(source, target, 70, -1, 25)) + return true; + if (target < 5 && _random.Probability(condition == 0 ? 15 : 10)) + { + if (Try(AttackBigMagic, source) || Try(AttackMagic, source, target)) + return true; + } + if (condition == 0 && target >= 5 && _random.Probability(30)) + { + if (Needs(At(target, D.Recover)) && Try(RecoverMagic, source, target)) + return true; + if (_random.Probability(30) && Try(RandomMiscMagic, source, target)) + return true; + } + return (target < 5 || MadTarget(source) || condition == 0 && ChaosTarget(source)) && Try(Normal, source, target); + } + + private bool HandleElementDemands(int source, int target, int wallProbability, int bossPhysicalProbability, int fiveProbability) + { + if (target >= 5) + return false; + if (Needs(At(target, D.WallMirrorAttack))) + { + if (_random.Probability(wallProbability) && Try(AttackMagic, source, target, At(target, D.WallMirrorAttack))) + return true; + if (bossPhysicalProbability >= 0 && _random.Probability(bossPhysicalProbability) && Try(BossPhysical, source, demand: At(target, D.WallMirrorAttack))) + return true; + } + if (Needs(At(target, D.BoundAttack)) && _random.Probability(70) && Try(Normal, source, target, At(target, D.BoundAttack))) + return true; + if (Needs(At(target, D.FiveMagicAttack))) + { + if (Try(AttackMagic, source, target, At(target, D.FiveMagicAttack))) + return true; + if (_random.Probability(fiveProbability) && Try(AttackMagic, source, target, At(target, D.FiveMagicAttack))) + return true; + } + return false; + } + + private bool HandlePal3AAdditional(int source, int target, int condition) + { + BattleAiRole actor = Roles[source]; + bool boss = actor.Boss; + if (actor.Seal && target < 5 && Try(Normal, source, target)) + return true; + if (source >= 5) + { + int skill = QueryStatusMagic(source, BattleAiStatusQuery.Debuff); + if (skill > 0 && target < 5 && _random.Probability(30 + condition * 10) && HealthyFriendCount() > (boss ? 1 : 2) + && Try(SelectedMiscMagic, source, target, ability: skill)) + return true; + if (condition == 1 || condition == 0 && !boss || condition == 2 && boss) + { + skill = QueryStatusMagic(source, BattleAiStatusQuery.Buff); + if (skill > 0 && target >= 5 && _random.Probability(condition == 1 && boss ? 30 : 50) && Try(SelectedMiscMagic, source, target, ability: skill)) + return true; + } + skill = QueryStatusMagic(source, BattleAiStatusQuery.Poison); + if (skill > 0 && target < 5 && _random.Probability(50) && Try(SelectedMiscMagic, source, target, ability: skill)) + return true; + } + BattleAiDemand group = FriendDemand[(int)D.BeAttack]; + if (Needs(group) && _random.Probability(boss ? 60 - condition * 10 : 50) && Try(boss ? BossPhysical : AttackBigMagic, source, demand: group)) + return true; + if (HasSkillBetween(source, 264, 268)) + { + bool single = _port.SceneFiveSpiritMode == 0 && source >= 5; + int chance = single ? (boss ? 70 : 90) - condition * 10 : boss ? 60 - condition * 10 : 50; + if (_random.Probability(chance) && Try(single ? FiveSpiritMagic : FiveSpiritBigMagic, source, single ? target : -1, At(target, D.WallMirrorAttack))) + return true; + } + if (boss && HasSkillBetween(source, 274, 274) && AliveEnemyCount() == 1 && _random.Probability(60 - condition * 10) + && Try(SelectedMiscMagic, source, target, ability: 274)) + return true; + int wall = condition == 0 || boss ? 80 : condition == 1 ? 60 : 40; + int physical = condition == 0 ? 50 : condition == 1 ? (boss ? 50 : 40) : boss ? 40 : 30; + if (HandleElementDemands(source, target, wall, physical, boss ? 80 : 70 - condition * 10)) + return true; + if (target < 5 && _random.Probability(condition == 2 ? 50 : boss ? 80 - condition * 20 : 40)) + { + if (Try(AttackBigMagic, source) || Try(AttackMagic, source, target)) + return true; + } + if (target >= 5 && _random.Probability(10 + condition * 10) && Needs(At(target, D.Recover)) && Try(RecoverMagic, source, target)) + return true; + return (target < 5 || MadTarget(source) || condition == 0 && ChaosTarget(source)) && Try(Normal, source, target); + } + + private int HealthyFriendCount() + { + int count = 0; + for (int role = 0; role < 5; role++) + { + if (Roles[role].Valid && !Roles[role].Fled && !Roles[role].BadState) + count++; + } + return count; + } + + private int AliveEnemyCount() + { + int count = 0; + for (int role = 5; role < 11; role++) + { + if (Roles[role].Valid && Roles[role].Alive && !Roles[role].Fled) + count++; + } + return count; + } + + private bool HasSkillBetween(int source, int first, int last) + { + foreach (BattleAiSkill skill in Roles[source].Skills) + { + if (skill.Id >= first && skill.Id <= last) + return true; + } + return false; + } + + public bool HandleEnemyChaos(int source) + { + int target = 0; + for (int count = 0; count < 512; count++) + { + target = _random.Next() % 11; + if (Roles[target].Valid && target != source && (!_pal3A || !Roles[target].Fled && !Roles[target].Fleeing)) + break; + } + if (!Roles[target].Valid || _pal3A && (Roles[target].Fled || Roles[target].Fleeing)) + return false; + int choice = _random.Next() % 8; + BattleAiAttemptKind kind = choice == 1 ? RecoverBigMagic : choice == 2 ? RecoverMagic : choice == 4 ? AttackBigMagic : choice == 5 ? AttackMagic : Normal; + return Try(kind, source, choice == 1 || choice == 4 ? -1 : target); + } + + public bool HandleFriend(int source) + { + BattleAiRole actor = Roles[source]; + if (!actor.Valid || !actor.Alive || actor.Hp == 0) + return false; + return actor.Profile.Negative && HandleFriendNegative(source) || HandleFriendAffirmative(source); + } + + public bool HandleFriendNegative(int source) + { + BattleAiAttemptKind[] chaos = { ReviveSkill, ReviveMagic, ReviveItem, RecoverBigMagic, RecoverBigSkill, RecoverBigItem, RecoverMagic, RecoverSkill, RecoverItem }; + for (int target = 0; target < 11; target++) + { + BattleAiRole actor = Roles[target]; + if (!actor.Valid) + continue; + if (Roles[source].Chaos) + { + int choice = _random.Next() % 64; + if (choice < chaos.Length && Try(chaos[choice], source, choice >= 3 && choice <= 5 ? -1 : target)) + return true; + continue; + } + if (target < 5 && Needs(At(target, D.Revive)) && TryThree(source, target, At(target, D.Revive), ReviveSkill, ReviveMagic, ReviveItem)) + return true; + if (!actor.Alive || actor.Fled) + continue; + if (Needs(FriendDemand[(int)D.Recover]) && TryThree(source, -1, FriendDemand[(int)D.Recover], RecoverBigMagic, RecoverBigSkill, RecoverBigItem)) + return true; + if (target < 5 && At(target, D.Recover).Satisfy < 50 && TryThree(source, target, At(target, D.Recover), RecoverMagic, RecoverSkill, RecoverItem)) + return true; + if (target < 5 && Needs(At(target, D.BadSpecStateRecover)) && _random.Probability(50) && TryThree(source, target, At(target, D.BadSpecStateRecover), CureMagic, CureSkill, CureItem)) + return true; + } + return false; + } + + public bool HandleFriendAffirmative(int source) + { + if (Roles[source].Chaos) + { + int target = 0; + for (int count = 0; count < 1024; count++) + { + target = _random.Next() % 11; + if (Roles[target].Valid && Roles[target].Fled && target != source) + break; + } + if (!Roles[target].Valid || Roles[target].Fled) + return false; + BattleAiAttemptKind[] choices = { AttackBigMagic, AttackBigSkill, AttackBigItem, Normal, AttackMagic, AttackSkill, AttackItem, AttackMagic, AttackSkill, AttackItem, Normal }; + int choice = _random.Next() % 11; + return Try(choices[choice], source, choice < 3 ? -1 : target); + } + for (int target = 0; target < 11; target++) + { + BattleAiRole actor = Roles[target]; + if (!actor.Valid || !actor.Alive || actor.Fled) + continue; + if (Needs(EnemyDemand[(int)D.BeAttack]) && TryThree(source, -1, EnemyDemand[(int)D.BeAttack], AttackBigMagic, AttackBigSkill, AttackBigItem)) + return true; + if ((target >= 5 && Needs(At(target, D.OneHit)) || MadTarget(source)) && TryAttackSet(source, target, At(target, D.OneHit))) + return true; + if ((target >= 5 || MadTarget(source)) && TryAttackSet(source, target, null)) + return true; + } + return false; + } + + private bool TryThree(int source, int target, BattleAiDemand demand, BattleAiAttemptKind first, BattleAiAttemptKind second, BattleAiAttemptKind third) + => Try(first, source, target, demand) || Try(second, source, target, demand) || Try(third, source, target, demand); + + private bool TryAttackSet(int source, int target, BattleAiDemand demand) + => Try(Normal, source, target, demand) || TryThree(source, target, demand, AttackMagic, AttackSkill, AttackItem); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAi.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAi.cs.meta new file mode 100644 index 00000000..ae524a1c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAi.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3f061128a8e64557ad7adc6bd55f6485 diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiControlRules.cs b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiControlRules.cs new file mode 100644 index 00000000..0a067224 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiControlRules.cs @@ -0,0 +1,22 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public static class BattleAiControlRules + { + public static bool ConsumesGauges(int before, int after) + { + if (before is < 0 or > 63 || after is < 0 or > 63) + throw new ArgumentOutOfRangeException(before is < 0 or > 63 ? nameof(before) : nameof(after)); + int difference = before ^ after; + // Published ProcAIList: Attack is not part of the cost comparison. + // Disabled child settings still commit, without generating ProcAI. + return (difference & 32) != 0 || (after & 32) != 0 && (difference & 30) != 0; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiControlRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiControlRules.cs.meta new file mode 100644 index 00000000..dc4698e0 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiControlRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 39d41d645d71435f9c9e51ce9d68ee5d diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiModel.cs b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiModel.cs new file mode 100644 index 00000000..57ad8f92 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiModel.cs @@ -0,0 +1,149 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + public enum BattleAiDemandKind + { + Null, Recover, Revive, Detoxification, BadSpecStateRecover, BeAttack, OneHit, FiveMagicAttack, WallMirrorAttack, BoundAttack + } + + public enum BattleAiAttemptKind + { + Normal, RecoverMagic, RecoverBigMagic, AttackMagic, AttackBigMagic, RandomMiscMagic, SelectedMiscMagic, + RecoverSkill, RecoverBigSkill, AttackSkill, AttackBigSkill, RecoverItem, RecoverBigItem, AttackItem, AttackBigItem, + ReviveMagic, ReviveSkill, ReviveItem, CureMagic, CureSkill, CureItem, BossPhysical, FiveSpiritMagic, FiveSpiritBigMagic, SpecAI + } + + public enum BattleAiStatusQuery + { + Debuff, Buff, Poison + } + + public sealed class BattleAiProfile + { + public bool Attack, Magic, Skill, Item, Negative, Enabled; + + public void SetEnabled(bool enabled) + { + Attack = Magic = Skill = Item = Enabled = enabled; + } + } + + // A captured entry in original directory order: monster slot order or player magic-grid order. + public sealed class BattleAiSkill + { + public int Id, Type, Range, Power, PowerMode, ElementMask, NullCureOperation, Level = 1, Count = 1; + public bool Mastered = true; + public bool IsMagic = true; + public bool IsItem; + public int[] StateOperations = Array.Empty(); + } + + // Index is implicit in Roles[0..10]; never compact the original identity/formation positions. + public sealed class BattleAiRole + { + public bool Valid, Alive, Fled, Fleeing, EnemyFriend, Boss; + public bool Chaos, Madness, Seal, BadState; + public int Identity, Hp, MaxHp, Mp, MaxMp, WorstBadState; + public BattleAiProfile Profile = new(); + public IReadOnlyList Skills = Array.Empty(); + } + + public sealed class BattleAiDemand + { + public int Satisfy = 100; + public long ActionId = -1; + public bool Handled; + public int State; + } + + public readonly struct BattleAiAttempt + { + public BattleAiAttemptKind Kind + { + get; + } + + public int Source + { + get; + } + + public int Target + { + get; + } + + public int AbilityId + { + get; + } + + public BattleAiDemand Demand + { + get; + } + + public BattleAiAttempt(BattleAiAttemptKind kind, int source, int target = -1, BattleAiDemand demand = null, int abilityId = 0) + { + Kind = kind; + Source = source; + Target = target; + Demand = demand; + AbilityId = abilityId; + } + } + + // Attempts are synchronous, sequential Cast... boundaries. A failed attempt may consume the + // shared random stream. The adapter owns cost, status, formation, range and command submission. + public abstract class BattleAiPort + { + public abstract long TryAttempt(BattleAiAttempt attempt); + + public virtual bool CanCast(int source, int skillId) => false; + + public virtual bool CanAttackBack(int source, int target) => true; + + public virtual bool IsActionActive(long actionId) => false; + + public virtual int SceneFiveSpiritMode => 0; + + // Original force numbers: 0 unset, 1 player side, 2 enemy side. + public virtual int SceneFiveSpiritOwner => 0; + + public virtual void RecordPlayerNormal(int source, int target) + { + } + + public virtual bool CanRepeat(int source, BattleAiCommand command) => false; + + public virtual bool AllRepeatTargetsDead(BattleAiCommand command) => true; + + public virtual bool IsRepeatAttack(BattleAiCommand command) => true; + + public virtual int PickRepeatTarget(int source, bool enemy) => -1; + + public virtual int PickRepeatTarget(int source, bool enemy, bool filterBackRole) => PickRepeatTarget(source, enemy); + + public virtual void ExpandRepeatRange(BattleAiCommand command) + { + } + + public virtual long SubmitRepeat(BattleAiCommand command) => -1; + } + + public sealed class BattleAiCommand + { + // Original command constants: 0x103 attack, 0x104 skill, 0x105 magic, + // 0x106 item, 0x109 defend, 0x10b flee; PAL3A additionally handles 0x10f. + public int Kind, AbilityId, Source, Target; + public bool MultipleTargets; + public bool[] TargetMask = new bool[11]; + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiModel.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiModel.cs.meta new file mode 100644 index 00000000..b4a38073 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiModel.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 81f8eb1b590c4ad3a922fb551ceee3c5 diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiRepeat.cs b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiRepeat.cs new file mode 100644 index 00000000..01260b8c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiRepeat.cs @@ -0,0 +1,76 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public sealed partial class BattleAi + { + public int SelectRepeatTarget(int source, bool enemy, bool filterBackRole) + { + int best = -1; + int minimum = int.MaxValue; + for (int target = enemy ? 5 : 0; target < (enemy ? 11 : 5); target++) + { + BattleAiRole actor = Roles[target]; + if (!actor.Valid || !actor.Alive || actor.Fled || actor.Fleeing) + continue; + if (filterBackRole && target == 6 && !_port.CanAttackBack(source, target)) + continue; + if (actor.Hp < minimum) + { + minimum = actor.Hp; + best = target; + } + } + return best; + } + + public bool RepeatTargetsDead(BattleAiCommand command) + { + if (command == null) + throw new ArgumentNullException(nameof(command)); + if (command.Target >= 0 && command.Target < 11) + { + BattleAiRole target = Roles[command.Target]; + return target.Hp <= 0 || target.Fled || _pal3A && target.Fleeing; + } + for (int target = 0; target < 11; target++) + { + BattleAiRole actor = Roles[target]; + if (command.TargetMask[target] && actor.Valid && actor.Hp > 0 && !actor.Fled && (!_pal3A || !actor.Fleeing)) + return false; + } + return true; + } + + public bool Repeat(int source, BattleAiCommand command) + { + if (command == null) + throw new ArgumentNullException(nameof(command)); + if (command.Kind is 0x109 or 0x10b) + return _port.SubmitRepeat(command) >= 0; + bool normal = command.Kind == 0x103; + bool extra = _pal3A && command.Kind == 0x10f; + bool ability = command.Kind is 0x104 or 0x105 or 0x106 || extra; + if (!normal && (!ability || !_port.CanRepeat(source, command))) + return PlayerNormal(source, false); + // Preserve the call before the NewRole check: the native function evaluates both this way. + if (_port.AllRepeatTargetsDead(command) || NewRole[source]) + { + Array.Clear(command.TargetMask, 0, command.TargetMask.Length); + bool enemy = normal || extra || _port.IsRepeatAttack(command); + command.Target = _port.PickRepeatTarget(source, enemy, _pal3A && enemy && command.Kind != 0x105); + if (_pal3A && command.Target < 0) + return false; + command.MultipleTargets = false; + if (!extra) + _port.ExpandRepeatRange(command); + } + return _port.SubmitRepeat(command) >= 0; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiRepeat.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiRepeat.cs.meta new file mode 100644 index 00000000..86888c09 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiRepeat.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5f42c38ed8c04a36829cdff18d038f0c diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiSelection.cs b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiSelection.cs new file mode 100644 index 00000000..9e054177 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiSelection.cs @@ -0,0 +1,266 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + public sealed partial class BattleAi + { + public int SelectMagic(int source, bool attack, bool group, int weight) + { + if (!Roles[source].Alive) + return 0; + var candidates = new List(); + int type = attack ? 2 : 3; + int range = (attack ? 3 : 1) + (group ? 1 : 0); + foreach (BattleAiSkill skill in Roles[source].Skills) + { + if (skill.Id != 0 && skill.Mastered && skill.IsMagic && skill.Type == type && skill.Range == range && _port.CanCast(source, skill.Id)) + candidates.Add(skill); + } + int best = 0; + int leastDistance = int.MaxValue; + foreach (BattleAiSkill skill in candidates) + { + // The recovery comparator intentionally differs from the distance stored afterward. + int distance = attack ? BattleBasicRules.SignedAbs(BattleBasicRules.SignedAbs(skill.Power) - BattleBasicRules.SignedAbs(weight)) : BattleBasicRules.SignedAbs(skill.Power - weight); + if (distance < leastDistance) + { + leastDistance = BattleBasicRules.SignedAbs(BattleBasicRules.SignedAbs(skill.Power) - BattleBasicRules.SignedAbs(weight)); + best = skill.Id; + } + } + return best; + } + + // These are the original GetBestRole... support selectors. The caller supplies the + // weight from the Cast boundary, including its native RNG draw for attack skills/items. + public int SelectSupport(int source, BattleAiAttemptKind kind, bool group, int weight, int nativeState = 1) + { + if (!Roles[source].Alive) + return 0; + bool item = kind is BattleAiAttemptKind.RecoverItem or BattleAiAttemptKind.AttackItem or BattleAiAttemptKind.ReviveItem or BattleAiAttemptKind.CureItem; + bool magic = kind is BattleAiAttemptKind.ReviveMagic or BattleAiAttemptKind.CureMagic; + bool recover = kind is BattleAiAttemptKind.RecoverItem or BattleAiAttemptKind.RecoverSkill; + bool attack = kind is BattleAiAttemptKind.AttackItem or BattleAiAttemptKind.AttackSkill; + bool revive = kind is BattleAiAttemptKind.ReviveItem or BattleAiAttemptKind.ReviveSkill or BattleAiAttemptKind.ReviveMagic; + bool cure = kind is BattleAiAttemptKind.CureItem or BattleAiAttemptKind.CureSkill or BattleAiAttemptKind.CureMagic; + if (!recover && !attack && !revive && !cure) + throw new ArgumentException("This attempt has no support selector.", nameof(kind)); + int best = 0; + int minimum = int.MaxValue; + foreach (BattleAiSkill skill in item ? Items : Roles[source].Skills) + { + if (skill.Id == 0 || item && skill.Count <= 0 || !item && (!skill.Mastered || skill.IsMagic != magic || skill.IsItem)) + continue; + // Ordinary item selectors check usability before reading the range/category. + if (item && !revive && !cure && !_port.CanCast(source, skill.Id)) + continue; + bool rangeMatches = item ? group ? skill.Range is not (1 or 3) : skill.Range is not (2 or 4) + : skill.Range == (attack ? 3 : 1) + (group ? 1 : 0); + if (!rangeMatches) + continue; + if (!item && !magic && skill.Type != 0 || magic && source >= 5 && skill.Type == 0) + continue; + bool category = recover ? item ? skill.Type == 1 && (skill.PowerMode == 2 || skill.PowerMode <= 1 && skill.Power > 0) : skill.Power > 0 + : attack ? item ? skill.Type == 2 && skill.PowerMode <= 1 && skill.Power < 0 : skill.Power < 0 + : Operation(skill, revive ? 25 : nativeState) == 2; + if (!category) + continue; + if ((!item || revive || cure) && !_port.CanCast(source, skill.Id)) + continue; + int power = item ? ItemPower(source, skill, recover) : skill.Power; + if (item && recover && Operation(skill, 25) == 2) + power += 100000; + int comparison = item ? BattleBasicRules.SignedAbs(BattleBasicRules.SignedAbs(power) - (cure ? 0 : weight)) + : magic && revive ? BattleBasicRules.SignedAbs(BattleBasicRules.SignedAbs(power) - BattleBasicRules.SignedAbs(weight)) : BattleBasicRules.SignedAbs(power - (cure ? 0 : weight)); + if (comparison < minimum) + { + minimum = BattleBasicRules.SignedAbs(BattleBasicRules.SignedAbs(power) - BattleBasicRules.SignedAbs(cure ? 0 : weight)); + best = skill.Id; + } + } + return best; + } + + private static int Operation(BattleAiSkill skill, int nativeState) + => nativeState == 0 ? skill.NullCureOperation : nativeState > 0 && nativeState <= skill.StateOperations.Length ? skill.StateOperations[nativeState - 1] : 0; + + private int ItemPower(int source, BattleAiSkill item, bool recover) + { + return item.PowerMode switch + { + 0 => item.Power, + 1 => item.Power * Roles[source].MaxHp / 100, + 2 when recover => Roles[source].MaxHp - Roles[source].Hp, + _ => 0 + }; + } + + public int ConvertSingleAttackMagic(int skillId) + { + if (skillId != (_pal3A ? 7714 : 7711)) + return skillId; + int[] converted = { 207, 215, 232, 224, 240 }; + return converted[_random.Next() % converted.Length]; + } + + public bool IsSceneMagicForbidden(int source, int skillId, int elementMask) + { + int scene = _port.SceneFiveSpiritMode; + return _pal3A && skillId != 0 && scene >= 1 && scene <= 5 && elementMask == 1 << (scene - 1) + && _port.SceneFiveSpiritOwner != (Roles[source].Valid ? source < 5 ? 1 : 2 : 0); + } + + public int SelectFiveSpiritMagic(int source, bool group, int weight = 0) + { + if (!Roles[source].Alive) + return 0; + int best = 0; + int minimum = int.MaxValue; + foreach (BattleAiSkill skill in Roles[source].Skills) + { + if (source < 5 && (!skill.Mastered || !skill.IsMagic)) + continue; + if (!group) + { + if (skill.Id >= 264 && skill.Id <= 268) + return skill.Id; + continue; + } + int scene = _port.SceneFiveSpiritMode; + if (skill.Id == 0 || skill.Type != 2 || skill.Range != 4 || scene < 1 || scene > 5 || skill.ElementMask != 1 << (scene - 1)) + continue; + if (!_port.CanCast(source, skill.Id)) + continue; + int distance = BattleBasicRules.SignedAbs(BattleBasicRules.SignedAbs(skill.Power) - BattleBasicRules.SignedAbs(weight)); + if (distance < minimum) + { + minimum = distance; + best = skill.Id; + } + } + return best; + } + + public int SelectMiscMagic(int source, bool group) + { + if (!Roles[source].Alive) + return 0; + var candidates = new List(); + foreach (BattleAiSkill skill in Roles[source].Skills) + { + if (skill.Id != 0 && skill.Mastered && skill.IsMagic && skill.Type == 1 && skill.Range == (group ? 2 : 1) && _port.CanCast(source, skill.Id)) + candidates.Add(skill.Id); + } + return candidates.Count == 0 ? 0 : candidates[_random.Next() % candidates.Count]; + } + + public int QueryStatusMagic(int source, BattleAiStatusQuery query) + { + if (!Roles[source].Alive) + return 0; + var candidates = new List(); + foreach (BattleAiSkill skill in Roles[source].Skills) + { + if (skill.Id == 0 || !MatchesStatusQuery(skill, query)) + continue; + if (_port.CanCast(source, skill.Id)) + candidates.Add(skill.Id); + } + return candidates.Count == 0 ? 0 : candidates[_random.Next() % candidates.Count]; + } + + private static bool MatchesStatusQuery(BattleAiSkill skill, BattleAiStatusQuery query) + { + for (int state = 0; state < skill.StateOperations.Length; state++) + { + int operation = skill.StateOperations[state]; + bool matches = query switch + { + BattleAiStatusQuery.Debuff => state is 6 or 8 or 10 or 12 or 13 or 14 or 15 or 16 or 17 or 18, + BattleAiStatusQuery.Buff => state is 5 or 7 or 9 or 11 or 19 or 20 or 21 or 22, + _ => state is >= 0 and <= 4 or 26 + }; + if (matches && (query == BattleAiStatusQuery.Poison ? operation != 0 : operation == 1)) + return true; + } + return false; + } + + public int MonsterSkillLevel(int source, int skillId) + { + int count = Math.Min(4, Roles[source].Skills.Count); + for (int slot = 0; slot < count; slot++) + { + if (Roles[source].Skills[slot].Id == skillId) + return slot == 3 ? 4 : Roles[source].Skills[slot].Level; + } + return skillId is 207 or 215 or 224 or 232 or 240 ? 1 : 0; + } + + public bool PlayerNormal(int source, bool playerCommand) + { + int target = SelectPlayerNormalTarget(source); + if (target < 0) + return false; + Roles[source].Profile.Attack = true; + bool accepted; + try + { + accepted = Try(BattleAiAttemptKind.Normal, source, target); + } + finally + { + // Native F clears this bit even when it was previously enabled. + Roles[source].Profile.Attack = false; + } + if (playerCommand) + { + _port.RecordPlayerNormal(source, target); + NewRole[source] = false; + } + return accepted; + } + + public int SelectPlayerNormalTarget(int source) + { + int best = -1; + int count = 0; + float minimum = 1.1f; + for (int target = 5; target < 11; target++) + { + BattleAiRole actor = Roles[target]; + if (!PlayerNormalCandidate(source, target)) + continue; + count++; + double ratio = (double)(float)actor.Hp / actor.MaxHp; + if (_pal3A) + ratio = (float)ratio; + if (ratio < minimum) + { + minimum = (float)ratio; + best = target; + } + } + if (count == 0 || best >= 0) + return best; + for (int target = 5; target < 11; target++) + { + if (PlayerNormalCandidate(source, target) && _random.Probability(100 / count)) + return target; + } + return -1; + } + + private bool PlayerNormalCandidate(int source, int target) + { + BattleAiRole actor = Roles[target]; + return actor.Valid && actor.Alive && (!_pal3A || !actor.Fled && !actor.Fleeing && (target != 6 || _port.CanAttackBack(source, target))); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiSelection.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiSelection.cs.meta new file mode 100644 index 00000000..1ed0def4 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/AI/BattleAiSelection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 13363e19043b462fa479f222088bb358 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleAttributeCalculator.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleAttributeCalculator.cs new file mode 100644 index 00000000..ff96f4cb --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleAttributeCalculator.cs @@ -0,0 +1,70 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Linq; + + public static class BattleAttributeCalculator + { + public static int[] Calculate(BattleParticipant initial, BattleActorDefinition definition, string variant) + { + if (initial == null || definition == null) + throw new ArgumentNullException(initial == null ? nameof(initial) : nameof(definition)); + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + if (initial.Attributes == null || initial.Attributes.Length != 12) + throw new ArgumentException("An actor needs twelve attributes.", nameof(initial)); + if (initial.AttributeSource == BattleAttributeSource.ExplicitEffective) + return initial.Attributes.ToArray(); + int[] values; + if (initial.AttributeSource == BattleAttributeSource.BaseWithEquipment) + values = initial.Attributes.ToArray(); + else if (initial.AttributeSource == BattleAttributeSource.LevelGrowth) + { + if (!string.IsNullOrEmpty(definition.GrowthUnsupportedReason)) + throw new NotSupportedException(definition.GrowthUnsupportedReason); + if (initial.Level < 1 || initial.Level >= definition.AttributesByLevel.Count || + definition.AttributesByLevel[initial.Level].Count != 12) + throw new NotSupportedException("Original level attributes are unavailable for this actor."); + values = definition.AttributesByLevel[initial.Level].ToArray(); + } + else + throw new ArgumentException("Unknown attribute source.", nameof(initial)); + + // Native CalMaxRV: weapon, cloth, hat, shoes, two ornaments. Percentage + // vital effects belong to per-round recovery and do not change maxima. + foreach (BattleEquipmentDefinition item in definition.Equipment.OrderBy(item => EquipmentOrder(item.Slot))) + { + if (item.Slot == 0 && item.Id == BattleMagicSwordRules.WeaponId) + { + bool nativeDefault = BattleLoadoutRules.IsNativeDefaultWeapon(variant, initial); + BattleMagicSwordSnapshot cultivation = definition.Identity == 0 ? definition.MagicSword : item.MagicSwordCultivation; + if (variant != "PAL3" || (definition.Identity != 0 && !nativeDefault) || cultivation == null) + throw new NotSupportedException("Weapon 6603 requires captured PAL3 cultivation attributes and a valid owner or native fallback."); + // CalMaxRV keys cultivation attributes by item ID, whereas + // combat energy and weapon skills belong only to Jingtian. + for (int attribute = 0; attribute < 12; attribute++) + values[attribute] = checked(values[attribute] + BattleMagicSwordRules.EquipmentAttributeBonus(cultivation, attribute)); + } + foreach (BattleAttributeEffect effect in item.Attributes) + { + if (effect.Mode != BattleValueMode.Absolute || effect.Attribute >= 7 && (variant == "PAL3A" || item.Slot == 0)) + continue; + values[effect.Attribute] = checked(values[effect.Attribute] + effect.Value); + } + for (int element = 0; element < 5; element++) + { + if ((item.ElementMask & (1 << element)) != 0) + values[element + 7] = checked(values[element + 7] + 1); + } + } + return values; + } + + private static int EquipmentOrder(int slot) => slot switch { 0 => 0, 2 => 1, 1 => 2, _ => slot }; + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleAttributeCalculator.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleAttributeCalculator.cs.meta new file mode 100644 index 00000000..019ba10c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleAttributeCalculator.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d91fe5ac356c4f72a27518cd05236f0e diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleBasicRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleBasicRules.cs new file mode 100644 index 00000000..1cabdc85 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleBasicRules.cs @@ -0,0 +1,151 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public sealed class BattleRandom + { + public string Variant + { + get; + } + + public uint State + { + get; private set; + } + + public BattleRandom(int seed, string variant = "PAL3") + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + Variant = variant; + State = unchecked((uint)seed); + } + + public int Next() + { + State = unchecked(State * 214013 + 2531011); + return (int)(State >> 16) & 0x7fff; + } + + // PAL3 inlines every positive roll. PAL3A's shared helper returns + // immediately for certain success; preserving the stream affects later actions. + public bool Probability(int percent) => percent > 0 && (Variant == "PAL3A" && percent >= 100 || + Next() % 1024 < BattleBasicRules.Round(1024f / 100 * percent)); + + public int Warp(int value, float fraction) + { + int width = BattleBasicRules.SignedAbs(BattleBasicRules.Round(value * fraction)); + if (width == 0) + return value; + int offset = Next() % width; + return Next() % 1024 >= 512 ? value + offset : value - offset; + } + } + + public readonly struct PhysicalHit + { + public int Delta + { + get; + } + + public bool Critical + { + get; + } + + public bool Dodged + { + get; + } + + public PhysicalHit(int delta, bool critical, bool dodged) + { + Delta = delta; + Critical = critical; + Dodged = dodged; + } + } + + public interface IBattleRules + { + int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random); + + int GaugePerStep(BattleParticipant actor); + + PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1); + } + + // Verified common PAL3/PAL3A neutral-element physical rules. Equipment/abnormal states are stage 3. + public sealed class BattleBasicRules : IBattleRules + { + // Native int32 abs keeps INT_MIN negative; widening it changes both + // the signed capture comparison and Warp's division/RNG behavior. + internal static int SignedAbs(int value) => value < 0 ? unchecked(-value) : value; + + public static int Round(float value) + { + // Native util::f2i uses x87 FISTP with masked invalid exceptions. + // Its integer-indefinite result is INT_MIN for NaN, infinity and + // finite values whose rounded result is outside signed int32. + double rounded = Math.Round(value, MidpointRounding.ToEven); + return rounded >= int.MinValue && rounded <= int.MaxValue ? (int)rounded : int.MinValue; + } + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) + { + if (encounter != BattleEncounter.Normal) + return (encounter == BattleEncounter.AllyAmbush) == (actor.Side == BattleSide.Ally) ? BattleSession.FullGauge : 0; + // The native expression divides two integers before multiplying by speed. + return Math.Min(BattleSession.FullGauge, 638 * actor.Attributes[5] + random.Next() % 638); + } + + public int GaugePerStep(BattleParticipant actor) + { + // Native storage is BYTE; int += float truncates at every update. Our reference update is 20ms. + return unchecked((byte)DefaultGaugeSpeed(actor)); + } + + private static int DefaultGaugeSpeed(BattleParticipant actor) => 20 + 5 * actor.Attributes[5]; + + // Published MagicWait multiplies CallDefaultSpeed's full int result + // before clamping and storing the second-slot byte. + internal int MagicCastGaugePerStep(BattleParticipant actor, int proficiency) => + Math.Min(byte.MaxValue, DefaultGaugeSpeed(actor) * proficiency * 2); + + public int NormalDamage(BattleParticipant source, BattleParticipant target, BattleRandom random, int damageDivisor = 1) + { + if (damageDivisor < 1) + throw new ArgumentOutOfRangeException(nameof(damageDivisor)); + int delta = -Round((1 + source.Level / 200f) * (source.Attributes[3] - target.Attributes[4])); + delta = random.Warp(delta, 0.1f); + if (source.Side == BattleSide.Ally) + delta /= damageDivisor; + // Native fallback is positive, so AttackDamage treats it as a miss, not minimum HP damage. + return delta >= 0 ? 1 + random.Next() % 5 : delta; + } + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) + { + int criticalPercent = (int)(Math.Sqrt(source.Attributes[6] / 2) * 10); + bool critical = random.Probability(criticalPercent); + if (!targetAtHome) + return new PhysicalHit(0, critical, false); + bool dodge = target.Side == BattleSide.Ally && random.Probability(Math.Max(0, (target.Attributes[5] - source.Attributes[5]) * 5)); + int delta = NormalDamage(source, target, random, damageDivisor); + if (dodge || delta >= 0) + return new PhysicalHit(0, critical, dodge); + if (critical) + delta = Round(delta * 1.3f); + if (guarding && delta < -1) + delta /= 2; + return new PhysicalHit(delta, critical, false); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleBasicRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleBasicRules.cs.meta new file mode 100644 index 00000000..50a5403a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleBasicRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: bb001218ff3a440faff36273e45c3775 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleBodyAudioRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleBodyAudioRules.cs new file mode 100644 index 00000000..74f14993 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleBodyAudioRules.cs @@ -0,0 +1,138 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Globalization; + + public readonly struct BattleMovementSound + { + public string Sound + { + get; + } + + public bool Loop + { + get; + } + + public BattleMovementSound(string sound, bool loop) + { + Sound = sound; + Loop = loop; + } + } + + public readonly struct BattleBodySoundProfile + { + public int Attack + { + get; + } + + public int Hurt + { + get; + } + + public BattleBodySoundProfile(int attack, int hurt) + { + Attack = attack; + Hurt = hurt; + } + } + + public interface IBattleBodyAudioCatalog + { + BattleBodySoundProfile BodySounds(string actor); + } + + public interface IBattleMovementAudio + { + void PlayMovementSound(string actor, string sound, bool loop); + + void StopMovementSound(string actor); + + void StopBodySounds(); + } + + // Published ProcAttack / ProcBlock / movement bodies. Sound selection never + // draws from the combat RNG and never manufactures a damage callback. + public static class BattleBodyAudioRules + { + public static string Attack(string variant, int identity, int weapon, BattlePhysicalMarkerKind marker, + int monsterSound = 0, bool magicSword = false, bool transformed = false) + { + Validate(variant, identity); + if (marker > (variant == "PAL3" ? BattlePhysicalMarkerKind.Work1 : BattlePhysicalMarkerKind.Work3)) + return null; + if (identity < 0) + return Numbered("wd", monsterSound); + if (variant == "PAL3") + return identity switch + { + 0 => magicSword ? "wd023" : "wd025", + 1 => "wd028", + 2 => weapon == 7 ? "wd030" : marker == BattlePhysicalMarkerKind.Work1 ? "wd024" : null, + 3 => weapon == 4 ? "wd027" : "wd026", + 4 => weapon == 2 ? "wd025" : "wd029", + _ => null + }; + return identity switch + { + 0 when weapon == 2 && !transformed => null, + 0 => "wd025", + 1 => weapon == 3 ? "wd026" : "wd023", + 2 => weapon == 5 ? "wd027" : "wd028", + 3 when weapon == 10 => null, + 3 => "wd028", + 4 => weapon == 9 ? "wd031" : "wd030", + _ => null + }; + } + + public static string Hurt(string variant, int identity, bool guarded, int monsterSound = 0) + { + Validate(variant, identity); + if (identity < 0) + return Numbered("we", monsterSound); + return guarded ? "we020" : Numbered("we", (variant == "PAL3" ? 15 : 2) + identity); + } + + public static BattleMovementSound Movement(string variant, int identity, BattleMovementPlan plan) + { + Validate(variant, identity); + if (plan == null) + throw new ArgumentNullException(nameof(plan)); + // Native early arrival does not activate a movement sound. + if (BattleMovement.Distance(plan.From, plan.To) < (plan.Kind == BattleMovementKind.FastRun ? 4f : 2f)) + return default; + bool fleeing = plan.To.X < -700f && plan.To.Z < -700f; + if (plan.Kind == BattleMovementKind.Teleport) + return new BattleMovementSound("we014", false); + if (variant == "PAL3A") + return identity < 0 || plan.Kind is not (BattleMovementKind.Run or BattleMovementKind.NpcFly) ? default : + new BattleMovementSound(identity is 1 or 2 ? "we001" : "we011", !fleeing); + return plan.Kind switch + { + BattleMovementKind.Run or BattleMovementKind.NpcFly when identity == 0 => new BattleMovementSound("we011", !fleeing), + BattleMovementKind.Run or BattleMovementKind.NpcFly when identity == 4 => new BattleMovementSound("we011b", !fleeing), + BattleMovementKind.Fly when identity == 1 => new BattleMovementSound("we012", false), + BattleMovementKind.Fly or BattleMovementKind.FlyRotate when identity == 3 => new BattleMovementSound("we013", false), + _ => default + }; + } + + private static string Numbered(string prefix, int number) => number == 0 ? null : prefix + number.ToString("D3", CultureInfo.InvariantCulture); + + private static void Validate(string variant, int identity) + { + if (variant is not ("PAL3" or "PAL3A") || identity is < -1 or > 4) + throw new ArgumentException("Invalid original combat body sound identity."); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleBodyAudioRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleBodyAudioRules.cs.meta new file mode 100644 index 00000000..00010986 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleBodyAudioRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: db9b44d6ff124e92ba9c4f2473d191c8 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleBossRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleBossRules.cs new file mode 100644 index 00000000..2886f7aa --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleBossRules.cs @@ -0,0 +1,127 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + public readonly struct BattleNativeEnemySlot + { + public bool Valid + { + get; + } + + public bool Alive + { + get; + } + + public bool Escaped + { + get; + } + + public BattleNativeEnemySlot(bool valid, bool alive, bool escaped = false) + { + Valid = valid; + Alive = alive; + Escaped = escaped; + } + } + + public readonly struct BattleMonsterRequest + { + public int NativeIndex + { + get; + } + + public int ActorId + { + get; + } + + public BattleMonsterRequest(int nativeIndex, int actorId) + { + if (nativeIndex < 5 || nativeIndex > 10 || actorId <= 0) + throw new ArgumentOutOfRangeException(nameof(nativeIndex)); + NativeIndex = nativeIndex; + ActorId = actorId; + } + } + + public sealed class BattleBossRules + { + private readonly bool _pal3A; + + public BattleBossRules(string variant) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + _pal3A = variant == "PAL3A"; + } + + public bool SelfDestructsAfterMagic(int actorId, int magicId) => actorId == 7312 && magicId == (_pal3A ? 308 : 210); + + public bool SkipsMagicCost(int actorId) => _pal3A && actorId == 7345; + + public int DeathReplacement(int actorId) => !_pal3A && actorId == 738 ? 739 : 0; + + public IReadOnlyList RoundStates(int actorId, int processedRound) => actorId == 7372 && processedRound == 3 + ? _pal3A ? Array.AsReadOnly(new[] { BattleState.AttackIncrease, BattleState.SpeedIncrease, BattleState.DefenseIncrease }) + : Array.AsReadOnly(new[] { BattleState.AttackIncrease }) + : Array.Empty(); + + public int SplitSlot(int actorId, int processedRound, IReadOnlyList slots, BattleRandom random) + { + if (slots == null || slots.Count != 6 || random == null) + throw new ArgumentException("Six original enemy slots and a random stream are required."); + int probability = actorId == 7378 && processedRound >= 3 ? 5 : actorId == 7395 && processedRound == 2 ? 20 : 0; + if (!random.Probability(probability)) + return -1; + for (int offset = 0; offset < slots.Count; offset++) + if (!slots[offset].Valid || actorId == 7378 && !slots[offset].Alive) + return offset + 5; + return -1; + } + + public IReadOnlyList Summon(int sourceIndex, int aliveEnemies, IReadOnlyList slots, BattleRandom random) + { + if (slots == null || slots.Count != 6 || random == null) + throw new ArgumentException("Six original enemy slots and a random stream are required."); + if (aliveEnemies != 1) + return Array.Empty(); + if (_pal3A) + { + int first = 5; + int second = 7; + for (int attempt = 0; attempt < 256; attempt++) + { + int candidateFirst = random.Next() % 5 + 6; + int candidateSecond = random.Next() % 5 + 6; + if (candidateFirst == sourceIndex || candidateSecond == sourceIndex || candidateFirst == candidateSecond) + continue; + first = candidateFirst; + second = candidateSecond; + break; + } + return Array.AsReadOnly(new[] { new BattleMonsterRequest(first, 7364), new BattleMonsterRequest(second, 7365) }); + } + if (slots[0].Alive && !slots[0].Escaped || slots[2].Alive && !slots[2].Escaped) + return Array.Empty(); + int[] identities = { 7369, 7368, 7370 }; + for (int attempt = 0; attempt < 16; attempt++) + { + int first = random.Next() % 3; + int second = random.Next() % 3; + if (first != second) + (identities[first], identities[second]) = (identities[second], identities[first]); + } + return Array.AsReadOnly(new[] { new BattleMonsterRequest(5, identities[0]), new BattleMonsterRequest(7, identities[1]) }); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleBossRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleBossRules.cs.meta new file mode 100644 index 00000000..eee197f0 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleBossRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fb9e83a6c6c843c8a0091069e9c180a3 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackRules.cs new file mode 100644 index 00000000..3f35be9c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackRules.cs @@ -0,0 +1,76 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + // Arithmetic only. Eligibility, achievement registration, resource writes and + // stage/thread lifecycle remain with their respective domain policies. + public sealed class BattleCoAttackRules + { + private readonly bool _isPal3A; + + public BattleCoAttackRules(string variant) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + _isPal3A = variant == "PAL3A"; + } + + // The callback runs once per nonzero man[] in stored order. It must execute + // original NormalAttackDamage with range=0, including that call's RNG. + public int Power(IReadOnlyList participantIds, Func normalDamage, + int multiplierPercentage, BattleRandom random) + { + if (participantIds == null || normalDamage == null || random == null) + throw new ArgumentNullException(participantIds == null ? nameof(participantIds) + : normalDamage == null ? nameof(normalDamage) : nameof(random)); + if (participantIds.Count != 4) + throw new ArgumentException("Original combo man[] contains four entries.", nameof(participantIds)); + int sum = 0; + for (int member = 0; member < 4; member++) + { + if (participantIds[member] != 0) + sum = unchecked(sum + normalDamage(participantIds[member])); + } + if (!_isPal3A) + sum = unchecked(sum * 2); + else if (multiplierPercentage > 0) + { + float multiplier = (float)(multiplierPercentage * (double)0.01f); + int integerMultiplier = (int)Math.Round(multiplier, MidpointRounding.ToEven); + sum = unchecked(sum * integerMultiplier); + } + return random.Warp(sum, 0.1f); + } + + // PAL3A evaluates even the nine discarded non-resource entries, preserving + // their NormalAttackDamage/Warp RNG calls. Only indices 0..2 write resources. + public IReadOnlyList EvaluationIndices(IReadOnlyList rawRoleValues) + { + if (rawRoleValues == null) + throw new ArgumentNullException(nameof(rawRoleValues)); + if (rawRoleValues.Count != 12) + throw new ArgumentException("Original RoleValue contains twelve entries.", nameof(rawRoleValues)); + var result = new List(); + for (int index = 0; index < 12; index++) + { + if (_isPal3A || rawRoleValues[index] != 0) + result.Add(index); + } + return result.AsReadOnly(); + } + + public static bool WritesResource(int index) => index >= 0 && index < 3; + + public static int SignedPower(int power, int rawRoleValue) + { + int magnitude = power < 0 ? unchecked(-power) : power; + return rawRoleValue > 0 ? magnitude : unchecked(-magnitude); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackRules.cs.meta new file mode 100644 index 00000000..f9d417fa --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 820de350c9b44c89a25277e6d43c5829 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackTargets.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackTargets.cs new file mode 100644 index 00000000..5d1ffbb5 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackTargets.cs @@ -0,0 +1,185 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleCoAttackTargetActorSnapshot + { + public bool Valid + { + get; + } + + public bool Alive + { + get; + } + + public bool Fled + { + get; + } + + public bool Boss + { + get; + } + + public int CurrentHp + { + get; + } + + public BattleCoAttackTargetActorSnapshot(bool valid, bool alive, bool fled, bool boss, int currentHp) + { + Valid = valid; + Alive = alive; + Fled = fled; + Boss = boss; + CurrentHp = currentHp; + } + } + + // Collection positions are original native actor indices 0..10, not lineup positions. + public sealed class BattleCoAttackTargetInput + { + public int NativeTargetIndex + { + get; + } + + public IReadOnlyList PreviousTargetMask + { + get; + } + + public int RawRange + { + get; + } + + public IReadOnlyList Actors + { + get; + } + + public BattleCoAttackTargetInput(int nativeTargetIndex, IEnumerable previousTargetMask, + int rawRange, IEnumerable actors) + { + if (nativeTargetIndex < -1 || nativeTargetIndex > 10) + throw new ArgumentOutOfRangeException(nameof(nativeTargetIndex)); + if (rawRange < 0 || rawRange > 3) + throw new ArgumentOutOfRangeException(nameof(rawRange)); + bool[] mask = previousTargetMask?.ToArray() ?? throw new ArgumentNullException(nameof(previousTargetMask)); + BattleCoAttackTargetActorSnapshot[] capturedActors = actors?.ToArray() ?? throw new ArgumentNullException(nameof(actors)); + if (mask.Length != 11 || capturedActors.Length != 11 || capturedActors.Any(actor => actor == null)) + throw new ArgumentException("Original combo targeting requires eleven actor slots and mask entries."); + NativeTargetIndex = nativeTargetIndex; + PreviousTargetMask = Array.AsReadOnly(mask); + RawRange = rawRange; + Actors = Array.AsReadOnly(capturedActors); + } + } + + public sealed class BattleCoAttackTargetSelection + { + public int NativeTargetIndex + { + get; + } + + public bool Multi + { + get; + } + + // Single-target expansion retains the old native mask, even though only + // NativeTargetIndex is effective. Keeping it is necessary for exact replay. + public IReadOnlyList TargetMask + { + get; + } + + public IReadOnlyList TargetIndices + { + get; + } + + internal BattleCoAttackTargetSelection(int nativeTargetIndex, bool multi, bool[] mask) + { + NativeTargetIndex = nativeTargetIndex; + Multi = multi; + TargetMask = Array.AsReadOnly(mask); + int[] indices = multi ? Enumerable.Range(0, 11).Where(index => mask[index]).ToArray() + : nativeTargetIndex < 0 ? Array.Empty() : new[] { nativeTargetIndex }; + TargetIndices = Array.AsReadOnly(indices); + } + } + + // Original GetCoAttackRange: both published variants use the same policy. + // Eligibility and the native-index-to-session-identity mapping belong to the caller. + public sealed class BattleCoAttackTargets + { + public BattleCoAttackTargets(string variant) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + } + + public BattleCoAttackTargetSelection Resolve(BattleCoAttackTargetInput input) + { + if (input == null) + throw new ArgumentNullException(nameof(input)); + int target = input.NativeTargetIndex; + bool[] mask = input.PreviousTargetMask.ToArray(); + if (input.RawRange is 1 or 3) + { + Array.Clear(mask, 0, mask.Length); + int first = input.RawRange == 1 ? 0 : 5; + int end = input.RawRange == 1 ? 5 : 11; + for (int index = first; index < end; index++) + { + BattleCoAttackTargetActorSnapshot actor = input.Actors[index]; + mask[index] = actor.Valid && !actor.Fled; + } + return new BattleCoAttackTargetSelection(-1, true, mask); + } + if (input.RawRange == 2) + { + if (target >= 0 && target < 5) + target = SelectEnemy(input.Actors); + if (target == -1) + target = Array.FindIndex(mask, selected => selected); + } + return new BattleCoAttackTargetSelection(target, false, mask); + } + + private static int SelectEnemy(IReadOnlyList actors) + { + // Original locals initialize both HP and best index to zero. With no + // eligible positive-HP enemy, the result is native player slot 0. + int best = 0; + int highestHp = 0; + for (int index = 5; index < 11; index++) + { + BattleCoAttackTargetActorSnapshot actor = actors[index]; + if (!actor.Valid || !actor.Alive || actor.Fled) + continue; + if (actor.Boss) + return index; + if (actor.CurrentHp > highestHp) + { + highestHp = actor.CurrentHp; + best = index; + } + } + return best; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackTargets.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackTargets.cs.meta new file mode 100644 index 00000000..736de0a6 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleCoAttackTargets.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f0eb4a7a7f334b3e96b79ae93de1c18b diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleEffectAudioRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleEffectAudioRules.cs new file mode 100644 index 00000000..6cfcabae --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleEffectAudioRules.cs @@ -0,0 +1,56 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System.Collections.Generic; + using System.Linq; + + // SetSpecState, ChangeSpecState and ChangeRoleValue share these cues in both games. + public static class BattleEffectAudioRules + { + public static string Recovery(bool hp, bool mp) => hp ? mp ? "wd003" : "wd001" : mp ? "wd002" : null; + + public static string State(BattleState state, bool remove) + { + if (remove) + return state switch + { + >= BattleState.PoisonWind and <= BattleState.PoisonEarth => "wd006", + BattleState.Reflection or BattleState.Evade or BattleState.Barrier or BattleState.Invisible => "wd020", + _ => null + }; + return state switch + { + >= BattleState.PoisonWind and <= BattleState.PoisonEarth => "wd005", + BattleState.AttackIncrease or BattleState.DefenseIncrease or BattleState.LuckIncrease or BattleState.SpeedIncrease => "wd021", + BattleState.AttackDecrease or BattleState.DefenseDecrease or BattleState.LuckDecrease or BattleState.SpeedDecrease => "wd022", + BattleState.Paralysis => "wd007", + BattleState.Seal => "wd008", + BattleState.Forbidden => "wd009", + BattleState.Sleep => "wd010", + BattleState.Madness => "wd011", + BattleState.Chaos => "wd012", + BattleState.Evade => "wd013", + BattleState.Barrier => "wd014", + BattleState.Invisible => "wd015", + BattleState.Reflection => "wd016", + _ => null + }; + } + + public static IEnumerable ClearedAilments(IEnumerable effects) + { + var removed = new HashSet(effects.Where(effect => effect.Remove).Select(effect => effect.State)); + BattleState[] ailments = { BattleState.Paralysis, BattleState.Seal, BattleState.Forbidden, BattleState.Sleep, BattleState.Madness, BattleState.Chaos }; + if (ailments.All(removed.Contains)) + yield return "wd019"; + else + foreach (BattleState state in ailments) + if (removed.Contains(state)) + yield return state is BattleState.Paralysis or BattleState.Seal or BattleState.Forbidden ? "wd017" : "wd018"; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleEffectAudioRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleEffectAudioRules.cs.meta new file mode 100644 index 00000000..fb0e126a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleEffectAudioRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4470432e59734f959c959c012bdee566 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleEffectRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleEffectRules.cs new file mode 100644 index 00000000..0af92c69 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleEffectRules.cs @@ -0,0 +1,216 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + // Signed original powers. Target eligibility, critical hits, guarding and HP writes belong to the session. + public sealed class BattleEffectRules + { + private readonly bool _isPal3A; + + public BattleEffectRules(string variant) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + _isPal3A = variant == "PAL3A"; + } + + public int MagicPower(int raw, BattleParticipant source, BattleParticipant target, int elementMask, + BattleRandom random, int enhancementMask = 0, int weatherElement = 0) + { + RequireParticipants(source, target, random); + if ((elementMask & ~31) != 0 || (enhancementMask & ~31) != 0 || weatherElement < 0 || weatherElement > 5) + throw new ArgumentOutOfRangeException(nameof(elementMask)); + if (raw == 0) + return 0; + // Both coefficient floats are exact multiples of 2^-28. Keep the + // product exact until the native truncation, since double can round + // across an integer boundary before _ftol retains the low 32 bits. + const long denominator = 1L << 28; + long factor = source.Level * (long)(0.05f * denominator) + + (source.Side == BattleSide.Ally ? denominator : (long)(0.1f * denominator)); + long integralPower = raw * (factor / denominator) + raw * (factor % denominator) / denominator; + int power = random.Warp(BattleBasicRules.SignedAbs(unchecked((int)integralPower)), 0.1f); + if (raw < 0) + power = -power; + + GetElements(elementMask, out int first, out int second); + if (source.Side == BattleSide.Ally) + { + int position = (int)source.Slot + 1; + int divisor = _isPal3A ? 4 : 2; + if (Matches(first, position) || Matches(second, position)) + power += power / divisor; + if (Matches(GreaterElement(first), position)) + power -= power / divisor; + if (Matches(GreaterElement(second), position)) + power -= power / divisor; + } + // PAL3A Magic Formula (0x4EAB42) queries enhancement at 0x504471 + // and the current weather element at 0x504440 after position adjustment. + if (_isPal3A) + { + if (HasElement(enhancementMask, first) || HasElement(enhancementMask, second)) + power += BattleBasicRules.Round(power * 0.3f); + if (Matches(first, weatherElement)) + power += power / -2; + if (Matches(second, weatherElement)) + power += power / -2; + } + return power; + } + + public int TechniquePower(int raw, BattleParticipant source, BattleParticipant target, bool multi, + int abilityId, int primaryActorLevel, BattleRandom random, out BattleValueMode mode) + { + RequireParticipants(source, target, random); + mode = !multi && target.Side == BattleSide.Ally ? BattleValueMode.Percentage : BattleValueMode.Absolute; + if (raw == 0) + return 0; + int power = target.Side == BattleSide.Enemy ? random.Warp(raw, 0.1f) : raw; + // The discarded original power still consumes its Warp calls before this ID override. + if (abilityId == (_isPal3A ? 4106 : 4102)) + power = 40 + 2 * primaryActorLevel; + return power; + } + + public int TechniqueSuccessPercent(int sourceLuck, int targetLuck, int equipmentBonus, BattleRandom random) + { + if (random == null) + throw new ArgumentNullException(nameof(random)); + int result = 80 + (sourceLuck - targetLuck) * 10; + result += BattleBasicRules.Round(Percent(result, equipmentBonus)); + return random.Warp(result, 0.2f); + } + + public int PhysicalPower(BattleParticipant source, BattleParticipant target, + BattleActorDefinition sourceDefinition, BattleActorDefinition targetDefinition, + BattleTargetRange range, int damageDivisor, bool madness, BattleRandom random) + { + RequireParticipants(source, target, random); + if (damageDivisor < 1) + throw new ArgumentOutOfRangeException(nameof(damageDivisor)); + // The native expression spills to float immediately before f2i. + float raw = (float)((1.0 + source.Level * (double)0.005f) * (source.Attributes[3] - target.Attributes[4])); + int power = random.Warp(-BattleBasicRules.Round(raw), 0.1f); + if (range is BattleTargetRange.OpponentRow or BattleTargetRange.OpponentColumn) + power = power * (random.Warp(100, 0.05f) - 45) / 100; + + int elementDifference = PhysicalElementDifference(sourceDefinition, targetDefinition); + power = BattleBasicRules.Round((float)(power * (1.0 - elementDifference * (double)0.05f))); + if (source.Side == BattleSide.Ally && damageDivisor > 1) + power /= damageDivisor; + if (madness) + power *= 2; + return power >= 0 ? 1 + random.Next() % 5 : power; + } + + public int CriticalPower(int signedPower, int equipmentBonus) + { + // PAL3A adds round(power * .5f); PAL3 multiplies by 1.3f. + int power = _isPal3A ? signedPower + BattleBasicRules.Round(signedPower * 0.5f) : BattleBasicRules.Round(signedPower * 1.3f); + return power + BattleBasicRules.Round(power * (float)equipmentBonus / 100); + } + + public static int ReduceResourceLoss(int signedDelta, int savingPercentage) + => signedDelta < 0 ? signedDelta - BattleBasicRules.Round(Percent(signedDelta, savingPercentage)) : signedDelta; + + // ProcFleeWait in both released executables writes BYTE(20 + 8 * speed). + // The older PAL3 source computes a different value through CallDefaultSpeed. + public int FleeGaugePerStep(int effectiveSpeed) => unchecked((byte)(20 + 8 * effectiveSpeed)); + + public int FleeSuccessPercent(int level, int luck, IReadOnlyList opponentLevels, IReadOnlyList opponentLuck) + { + if (opponentLevels == null || opponentLuck == null) + throw new ArgumentNullException(opponentLevels == null ? nameof(opponentLevels) : nameof(opponentLuck)); + if (opponentLevels.Count == 0 || opponentLevels.Count != opponentLuck.Count) + throw new ArgumentException("Flee requires matching nonempty opponent attribute lists."); + int totalLevel = 0; + int lowestLuck = 0xffffff; + for (int index = 0; index < opponentLevels.Count; index++) + { + totalLevel = unchecked(totalLevel + opponentLevels[index]); + lowestLuck = Math.Min(lowestLuck, opponentLuck[index]); + } + int averageLevel = totalLevel / opponentLevels.Count; + return unchecked(30 + (level - averageLevel) * (luck - lowestLuck) * 10); + } + + // Original element order is water, fire, wind, thunder, earth. + public static int GreaterElement(int element) => element switch + { + 1 => 5, + 2 => 1, + 3 => 4, + 4 => 2, + 5 => 3, + _ => 0, + }; + + public static int PunyElement(int element) => element switch + { + 1 => 2, + 2 => 4, + 3 => 5, + 4 => 3, + 5 => 1, + _ => 0, + }; + + public static int PhysicalElementDifference(BattleActorDefinition source, BattleActorDefinition target) + { + if (source == null || target == null) + return 0; + bool targetHasElement = false; + int attackElement = 0; + for (int element = 1; element <= 5; element++) + { + targetHasElement |= PackedElement(target, element) != 0; + if (attackElement == 0 && ValueAt(source.PhysicalAttackElementValues, element) != 0) + attackElement = element; + } + if (!targetHasElement || attackElement == 0) + return 0; + // Both native EXEs preserve the logical-AND bug: compare whole packed DWORDs to zero. + return (PackedElement(target, GreaterElement(attackElement)) != 0 ? 1 : 0) + - (PackedElement(target, PunyElement(attackElement)) != 0 ? 1 : 0); + } + + private static uint PackedElement(BattleActorDefinition actor, int element) + => (uint)ValueAt(actor.PhysicalAttackElementValues, element) << 16 | ValueAt(actor.PhysicalDefenseElementValues, element); + + private static ushort ValueAt(IReadOnlyList values, int element) + => values != null && element >= 1 && element <= values.Count ? unchecked((ushort)values[element - 1]) : (ushort)0; + + private static float Percent(int value, int percent) => (float)(value * (double)percent * (double)0.01f); + + private static bool HasElement(int mask, int element) => element > 0 && element <= 5 && (mask & (1 << (element - 1))) != 0; + + private static bool Matches(int element, int position) => element > 0 && element <= 5 && element == position; + + private static void GetElements(int mask, out int first, out int second) + { + first = second = 0; + for (int element = 1; element <= 5; element++) + { + if (!HasElement(mask, element)) + continue; + if (first == 0) + first = element; + else + second = element; + } + } + + private static void RequireParticipants(BattleParticipant source, BattleParticipant target, BattleRandom random) + { + if (source == null || target == null || random == null) + throw new ArgumentNullException(source == null ? nameof(source) : target == null ? nameof(target) : nameof(random)); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleEffectRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleEffectRules.cs.meta new file mode 100644 index 00000000..32809a53 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleEffectRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 331c6329efb64594a995942dfd497650 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleEncounterRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleEncounterRules.cs new file mode 100644 index 00000000..8e115478 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleEncounterRules.cs @@ -0,0 +1,72 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + + public enum BattleEncounterOutcome + { + None, + Win, + Lose, + } + + // Released CheckPerRound and CheckState use the enemy center's counter, + // independently of every actor's individual gauge-round counter. + public sealed class BattleEncounterRules + { + private readonly bool _pal3A; + + public BattleEncounterRules(string variant) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + _pal3A = variant == "PAL3A"; + } + + public static int NativeMaximumRounds(int roundLimit) => roundLimit == -1 ? int.MaxValue : roundLimit; + + public static bool RoundLimitReached(int bossRounds, int roundLimit) => bossRounds >= NativeMaximumRounds(roundLimit); + + public static bool BeginRound(int nativeIndex, int sequenceRound, int roundLimit, ref int processedRounds, ref int bossRounds) + { + if (RoundLimitReached(bossRounds, roundLimit) || processedRounds >= sequenceRound) + return false; + processedRounds++; + if (nativeIndex == 10) + bossRounds++; + return true; + } + + public static int HpAfterMustFail(bool mustFail, int nativeIndex, int hpAfterChange, int maximumHp) => + mustFail && nativeIndex == 10 ? maximumHp : hpAfterChange; + + // Native task numbers remain at this boundary because the released + // variants have different task tables and different outcome gates. + public BattleEncounterOutcome CheckOutcome(bool allyAlive, bool enemyAlive, int bossRounds, int roundLimit, + bool mustFail, IReadOnlyCollection unfinishedTasks) + { + bool HasTask(int id) => unfinishedTasks != null && Contains(unfinishedTasks, id); + bool coAttack = HasTask(_pal3A ? 13 : 12); + if (!allyAlive && !coAttack && (!_pal3A || !HasTask(17) && !HasTask(11))) + return BattleEncounterOutcome.Lose; + if ((!enemyAlive || RoundLimitReached(bossRounds, roundLimit) && !mustFail) && !coAttack && + (!_pal3A || !HasTask(31) && !HasTask(17))) + return BattleEncounterOutcome.Win; + return BattleEncounterOutcome.None; + } + + private static bool Contains(IReadOnlyCollection values, int value) + { + foreach (int entry in values) + if (entry == value) + return true; + return false; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleEncounterRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleEncounterRules.cs.meta new file mode 100644 index 00000000..fa490561 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleEncounterRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1f9bce2df08e4f098a5034d0f3e4cfc2 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleFacingRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleFacingRules.cs new file mode 100644 index 00000000..c300b30e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleFacingRules.cs @@ -0,0 +1,26 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public static class BattleFacingRules + { + public static float Initial(BattleSide side) => side switch + { + BattleSide.Ally => 45f, + BattleSide.Enemy => -135f, + _ => throw new ArgumentOutOfRangeException(nameof(side)), + }; + + public static float Starting(BattleSide side, BattleEncounter encounter) + { + bool reversed = side == BattleSide.Ally && encounter == BattleEncounter.EnemyAmbush || + side == BattleSide.Enemy && encounter == BattleEncounter.AllyAmbush; + return Initial(side) + (reversed ? 180f : 0f); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleFacingRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleFacingRules.cs.meta new file mode 100644 index 00000000..b26ec68a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleFacingRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a886c47fcd7f4c1b8b709a39df619a41 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleFormationRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleFormationRules.cs new file mode 100644 index 00000000..7759f66e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleFormationRules.cs @@ -0,0 +1,339 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleFormationActor + { + public int Index + { + get; + } + + public int ResourceId + { + get; + } + + public BattleSlot Slot + { + get; + } + + public int WeaponType + { + get; + } + + public bool Valid + { + get; + } + + public bool Alive + { + get; + } + + public int Hp + { + get; + } + + public int MaxHp + { + get; + } + + public IReadOnlyList States + { + get; + } + + public int TaskCount + { + get; + } + + public bool AtHome + { + get; + } + + public bool Idle + { + get; + } + + public bool Transformed + { + get; + } + + public bool Fled + { + get; + } + + public BattleFormationActor(int index, int resourceId, BattleSlot slot, int weaponType, + bool valid = true, bool alive = true, int hp = 1, int maxHp = 1, + IEnumerable states = null, int taskCount = 0, bool atHome = true, + bool idle = true, bool transformed = false, bool fled = false) + { + if (index < 0 || index > 10 || !Enum.IsDefined(typeof(BattleSlot), slot) || + weaponType < 0 || weaponType > byte.MaxValue || hp < 0 || maxHp < 0 || taskCount < 0) + throw new ArgumentException("Invalid formation actor snapshot."); + Index = index; + ResourceId = resourceId; + Slot = slot; + WeaponType = weaponType; + Valid = valid; + Alive = alive; + Hp = hp; + MaxHp = maxHp; + States = Array.AsReadOnly(states?.ToArray() ?? Array.Empty()); + TaskCount = taskCount; + AtHome = atHome; + Idle = idle; + Transformed = transformed; + Fled = fled; + } + } + + public sealed class BattleComboRequirement + { + public int Id + { + get; + } + + public int TriggerSkillId + { + get; + } + + public IReadOnlyList Members + { + get; + } + + public IReadOnlyList Positions + { + get; + } + + public IReadOnlyList WeaponTypes + { + get; + } + + // Original FS indices: -1 ignores, 0..25 tests CBRSS(index+1), 26 means any poison. + public IReadOnlyList AuxiliaryStates + { + get; + } + + public BattleComboRequirement(int id, int triggerSkillId, IEnumerable members, + IEnumerable positions, IEnumerable weaponTypes, IEnumerable auxiliaryStates) + { + Id = id; + TriggerSkillId = triggerSkillId; + Members = Capture(members, 4); + Positions = Capture(positions, 4); + WeaponTypes = Capture(weaponTypes, 4); + AuxiliaryStates = Capture(auxiliaryStates, 3); + } + + private static IReadOnlyList Capture(IEnumerable values, int count) + { + int[] result = values?.ToArray() ?? throw new ArgumentNullException(nameof(values)); + if (result.Length != count) + throw new ArgumentException($"Expected {count} combo conditions.", nameof(values)); + return Array.AsReadOnly(result); + } + } + + public sealed class BattleFormationDecision + { + public bool Allowed => FailureReason == null; + + public string FailureReason + { + get; + } + + public int? ActorIndex + { + get; + } + + internal BattleFormationDecision(string failureReason = null, int? actorIndex = null) + { + FailureReason = failureReason; + ActorIndex = actorIndex; + } + } + + // Eligibility only. The session owns gauge costs, damage routing, action lifecycle and presentation. + public sealed class BattleFormationRules + { + private static readonly BattleFormationDecision Allowed = new(); + private readonly bool _isPal3A; + + public BattleFormationRules(string variant) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + _isPal3A = variant == "PAL3A"; + } + + public BattleFormationDecision CanMove(BattleFormationActor actor) + { + RequireActor(actor); + if (!actor.Valid) + return Denied("角色未出场。", actor.Index); + if (!actor.Alive) + return Denied("死亡角色不能换位。", actor.Index); + foreach (BattleState state in new[] { BattleState.Paralysis, BattleState.Chaos, BattleState.Madness, BattleState.Sleep }) + { + if (actor.States.Contains(state)) + return Denied($"角色处于{state},不能换位。", actor.Index); + } + return Allowed; + } + + public BattleFormationDecision CanChangeLineup(IReadOnlyList actors) + { + if (actors == null) + throw new ArgumentNullException(nameof(actors)); + foreach (BattleFormationActor actor in actors) + { + RequireActor(actor); + if (actor.Index < 5 && actor.Valid && actor.TaskCount > 0) + return Denied("我方角色仍有未结束的舞台任务。", actor.Index); + } + return Allowed; + } + + internal bool IsProtectionTargetSlot(int index) => index >= 1 && index <= (_isPal3A ? 2 : 3); + + public BattleFormationDecision CanSetProtect(BattleFormationActor guardian, BattleFormationActor target) + { + RequireActor(guardian); + RequireActor(target); + if (guardian.Index != 0 || !guardian.Valid || !guardian.Alive) + return Denied("只有出场且存活的原版角色槽0可以设置援护。", guardian.Index); + if (guardian.Slot != BattleSlot.Center) + return Denied("援护者必须位于中位才能设置援护。", guardian.Index); + if (!IsProtectionTargetSlot(target.Index)) + return Denied("原版援护面板不提供该角色。", target.Index); + if (!target.Valid || !target.Alive) + return Denied("援护对象必须出场且存活。", target.Index); + return Allowed; + } + + public BattleFormationDecision CanProtect(int selectedTarget, BattleFormationActor guardian, BattleFormationActor target) + { + RequireActor(guardian); + RequireActor(target); + if (guardian.Index != 0) + return Denied("只有原版角色槽0执行援护。", guardian.Index); + if (selectedTarget == 0 || selectedTarget != target.Index) + return Denied("目标不是当前设定的援护对象。", target.Index); + if (!guardian.Valid || !guardian.Alive) + return Denied("援护者未出场或已经死亡。", guardian.Index); + if (guardian.Hp < guardian.MaxHp / 2) + return Denied("援护者的精不足最大精的一半。", guardian.Index); + if (target.Hp > target.MaxHp / 10) + return Denied("援护对象的精高于最大精的十分之一。", target.Index); + if (guardian.Slot != BattleSlot.Center) + return Denied("援护者必须位于中央。", guardian.Index); + if (!guardian.Idle) + return Denied("援护者尚未空闲。", guardian.Index); + if (!guardian.AtHome) + return Denied("援护者尚未回到阵位。", guardian.Index); + if (!target.AtHome) + return Denied("援护对象尚未回到阵位。", target.Index); + return Allowed; + } + + public BattleFormationDecision CanCoAttack(int initiator, int triggerSkillId, BattleComboRequirement requirement, + IReadOnlyList actors) + { + if (requirement == null || actors == null) + throw new ArgumentNullException(requirement == null ? nameof(requirement) : nameof(actors)); + if (initiator < 0 || initiator >= 5) + return Denied("合击只能由我方角色发起。", initiator); + if (triggerSkillId != requirement.TriggerSkillId) + return Denied($"需要触发技能{requirement.TriggerSkillId}。"); + var byIndex = actors.ToDictionary(actor => actor.Index); + if (!byIndex.TryGetValue(initiator, out BattleFormationActor source) || source.ResourceId != requirement.Members[0]) + return Denied($"需要资源角色{requirement.Members[0]}发起合击。", initiator); + for (int member = 0; member < 4; member++) + { + if (requirement.Members[member] == 0) + continue; + int index = MemberIndex(requirement.Members[member]); + if (index < 0) + return Denied($"未核实成员资源{requirement.Members[member]}的原版身份映射。"); + if (!byIndex.TryGetValue(index, out BattleFormationActor actor) || !actor.Valid) + return Denied($"合击成员{requirement.Members[member]}未出场。", index); + if (_isPal3A && actor.Transformed) + return Denied("变身中的成员不能参与外传合击。", index); + int position = requirement.Positions[member]; + int actual = (int)actor.Slot + 1; + if (position >= 1 && position <= 6 && position != actual) + return Denied($"合击成员必须位于原版阵位{position}。", index); + if (position == 7 && actual is not (2 or 3 or 4)) + return Denied("合击成员必须位于火、风或雷阵位。", index); + if (position == 8 && actual is not (1 or 2 or 5)) + return Denied("合击成员必须位于水、火或土阵位。", index); + int weapon = requirement.WeaponTypes[member]; + if ((!_isPal3A || weapon > 0) && actor.WeaponType != weapon) + return Denied($"合击成员需要武器类型{weapon}。", index); + } + for (int auxiliary = 0; auxiliary < 3; auxiliary++) + { + int index = MemberIndex(requirement.Members[auxiliary + 1]); + if (index < 0) + continue; + BattleFormationActor actor = byIndex[index]; + int condition = requirement.AuxiliaryStates[auxiliary]; + if (condition >= 0 && condition < 26 && !actor.States.Contains((BattleState)condition)) + return Denied($"合击成员需要状态{(BattleState)condition}。", index); + if (condition == 26 && !actor.States.Any(state => state >= BattleState.PoisonWind && state <= BattleState.PoisonEarth)) + return Denied("合击成员需要任一五毒状态。", index); + } + return Allowed; + } + + internal int MemberIndex(int resourceId) + { + if (_isPal3A) + return resourceId >= 101 && resourceId <= 105 ? resourceId - 101 : -1; + return resourceId switch + { + 101 => 0, + 104 => 1, + 105 or 106 => 2, + 107 => 3, + 102 => 4, + _ => -1, + }; + } + + private static BattleFormationDecision Denied(string reason, int? actor = null) => new(reason, actor); + + private static void RequireActor(BattleFormationActor actor) + { + if (actor == null) + throw new ArgumentNullException(nameof(actor)); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleFormationRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleFormationRules.cs.meta new file mode 100644 index 00000000..dfb09ca8 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleFormationRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4d07730c230b4826b55d0c58eeecc7c6 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleLoadoutRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleLoadoutRules.cs new file mode 100644 index 00000000..76c6e174 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleLoadoutRules.cs @@ -0,0 +1,60 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public static class BattleLoadoutRules + { + public static int DefaultWeapon(string variant, int identity) + { + if (identity is < 0 or > 4) + throw new ArgumentOutOfRangeException(nameof(identity)); + return variant switch + { + "PAL3" => BattleMagicSwordRules.WeaponId, + "PAL3A" => identity switch { 0 => 82110, 1 => 82209, 2 => 82310, 3 => 82402, _ => 82508 }, + _ => throw new ArgumentException("Unknown original game variant.", nameof(variant)) + }; + } + + public static int PlayerIdentity(string variant, int actorId) => variant switch + { + "PAL3" => actorId switch { 101 => 0, 104 => 1, 106 => 2, 107 => 3, 102 => 4, _ => -1 }, + "PAL3A" => actorId is >= 101 and <= 105 ? actorId - 101 : -1, + _ => throw new ArgumentException("Unknown original game variant.", nameof(variant)) + }; + + public static bool IsNativeDefaultWeapon(string variant, BattleParticipant actor) + { + if (variant is not ("PAL3" or "PAL3A") || actor == null || !actor.UsesNativeDefaultWeapon) + return false; + int identity = PlayerIdentity(variant, actor.ActorId); + return actor.Side == BattleSide.Ally && identity >= 0 && + actor.Equipment is { Length: > 0 } && actor.Equipment[0] == DefaultWeapon(variant, identity); + } + + // Preparation is deterministic and returns a copy. The authoring draft + // and the original database remain untouched, including across replay. + public static BattleParticipant Prepare(string variant, BattleParticipant actor) + { + if (actor == null) + throw new ArgumentNullException(nameof(actor)); + BattleParticipant copy = actor.Copy(); + int identity = PlayerIdentity(variant, actor.ActorId); + if (copy.Side != BattleSide.Ally || identity < 0 || copy.Equipment == null || + copy.Equipment.Length > 0 && copy.Equipment[0] != 0) + return copy; + if (copy.Equipment.Length == 0) + copy.Equipment = new int[6]; + copy.Equipment[0] = DefaultWeapon(variant, identity); + copy.UsesNativeDefaultWeapon = true; + if (variant == "PAL3" && identity == 0) + copy.MagicSword ??= new BattleMagicSword(); + return copy; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleLoadoutRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleLoadoutRules.cs.meta new file mode 100644 index 00000000..4dc1516c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleLoadoutRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a6e5be9a0a63465facdb8219a58b92b3 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSlots.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSlots.cs new file mode 100644 index 00000000..eb8e5a13 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSlots.cs @@ -0,0 +1,107 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public readonly struct BattleMagicSlot + { + public int Group + { + get; + } + + public int Slot + { + get; + } + + public BattleAbilityDefinition Definition + { + get; + } + + public int SkillId => Definition.Id; + + public BattleMagicSlot(int group, int slot, BattleAbilityDefinition definition) + { + Group = group; + Slot = slot; + Definition = definition ?? throw new ArgumentNullException(nameof(definition)); + } + } + + // Native magic groups are water, fire, thunder, wind, earth, composite. + // Explicit save/authoring slots override LoadUseableMagic's group/ID ordering. + // Group 6 retains old synthetic definitions without an element attribute. + public static class BattleMagicSlots + { + public static int Group(int elementMask) => elementMask switch + { + 1 => 0, + 2 => 1, + 8 => 2, + 4 => 3, + 16 => 4, + > 0 when (elementMask & (elementMask - 1)) != 0 => 5, + _ => 6 + }; + + public static bool IsCatalogueMagic(BattleAbilityDefinition ability) => ability.SkillTypeId is >= 1 and <= 3 || + ability.SkillTypeId == -1 && ability.IsMagic; + + public static IReadOnlyList Capture(string variant, BattleDefinitions definitions, int identity, + IReadOnlyList skills) => CaptureSlots(variant, definitions, identity, + skills?.Select(skill => skill == null ? throw new ArgumentException("Missing magic skill.") : + (skill.Id, skill.NativeMagicGroup, skill.NativeMagicSlot))); + + public static IReadOnlyList Capture(string variant, BattleDefinitions definitions, int identity, + IReadOnlyList skills) => CaptureSlots(variant, definitions, identity, + skills?.Select(skill => skill == null ? throw new ArgumentException("Missing magic skill.") : + (skill.Id, skill.NativeMagicGroup, skill.NativeMagicSlot))); + + private static IReadOnlyList CaptureSlots(string variant, BattleDefinitions definitions, int identity, + IEnumerable<(int Id, int Group, int Slot)> skills) + { + if (variant is not ("PAL3" or "PAL3A") || definitions == null || skills == null) + throw new ArgumentException("Magic slots require a variant, captured definitions and actor skills."); + if (definitions.Variant != variant) + throw new ArgumentException("Invalid native magic group and slot."); + var explicitSlots = new Dictionary(); + foreach (var skill in skills) + { + bool specified = skill.Group != -1 || skill.Slot != -1; + if (specified && (skill.Group < 0 || skill.Group >= 6 || skill.Slot < 0 || skill.Slot >= (variant == "PAL3A" ? 9 : 8))) + throw new ArgumentException("Invalid native magic group and slot."); + if (specified) + explicitSlots.Add(skill.Id, (skill.Group, skill.Slot)); + } + var occupied = new HashSet<(int Group, int Slot)>(); + var result = new List(); + BattleAbilityDefinition[] legal = definitions.SkillsInOriginalOrder.Where(ability => IsCatalogueMagic(ability) && + ability.ApplicableIdentities.Contains(identity)).ToArray(); + foreach (BattleAbilityDefinition ability in legal.Where(ability => explicitSlots.ContainsKey(ability.Id))) + { + var position = explicitSlots[ability.Id]; + if (position.Group < 0 || position.Group >= 6 || position.Slot < 0 || position.Slot >= (variant == "PAL3A" ? 9 : 8) || !occupied.Add(position)) + throw new ArgumentException("Conflicting native magic slots."); + result.Add(new BattleMagicSlot(position.Group, position.Slot, ability)); + } + foreach (BattleAbilityDefinition ability in legal.Where(ability => !explicitSlots.ContainsKey(ability.Id)).OrderBy(ability => Group(ability.ElementMask)).ThenBy(ability => ability.Id)) + { + int group = Group(ability.ElementMask); + int slot = 0; + while (occupied.Contains((group, slot))) + slot++; + occupied.Add((group, slot)); + result.Add(new BattleMagicSlot(group, slot, ability)); + } + return Array.AsReadOnly(result.OrderBy(slot => slot.Group).ThenBy(slot => slot.Slot).ToArray()); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSlots.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSlots.cs.meta new file mode 100644 index 00000000..e7a72a0d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSlots.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 549cb521cee44482488594ee37b49562 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSwordRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSwordRules.cs new file mode 100644 index 00000000..a85b9d6f --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSwordRules.cs @@ -0,0 +1,150 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + // Original purification UI order differs from the GDB elemental attribute order. + public enum BattleSwordPurificationElement + { + Water, Fire, Thunder, Wind, Earth, None + } + + // Captured cultivation data and battle energy. The editor supplies these values; + // battle rules neither consult PlayerMgr nor reconstruct cultivation history. + public sealed class BattleMagicSwordSnapshot + { + public int AttackBonus + { + get; + } + + public BattleSwordPurificationElement SelectedElement + { + get; + } + + public int PurificationCount + { + get; + } + + public int SkillId + { + get; + } + + public uint ChargeCoefficient + { + get; + } + + public float Energy + { + get; + } + + public BattleMagicSwordSnapshot(int attackBonus, BattleSwordPurificationElement selectedElement, + int purificationCount, int skillId, uint chargeCoefficient, float energy) + { + if (attackBonus < 0) + throw new ArgumentOutOfRangeException(nameof(attackBonus)); + if (selectedElement < BattleSwordPurificationElement.Water || selectedElement > BattleSwordPurificationElement.None) + throw new ArgumentOutOfRangeException(nameof(selectedElement)); + if (purificationCount < 0) + throw new ArgumentOutOfRangeException(nameof(purificationCount)); + if (skillId < 0) + throw new ArgumentOutOfRangeException(nameof(skillId)); + if (float.IsNaN(energy) || float.IsInfinity(energy) || energy < 0 || energy > 200) + throw new ArgumentOutOfRangeException(nameof(energy)); + AttackBonus = attackBonus; + SelectedElement = selectedElement; + PurificationCount = purificationCount; + SkillId = skillId; + ChargeCoefficient = chargeCoefficient; + Energy = energy; + } + + public BattleMagicSwordSnapshot WithEnergy(float energy, uint? chargeCoefficient = null) => + new(AttackBonus, SelectedElement, PurificationCount, SkillId, chargeCoefficient ?? ChargeCoefficient, energy); + } + + // PAL3 released EXE rules. Session code owns energy writes, action validation, + // target/status order and events; cultivation menus are outside battle scope. + public static class BattleMagicSwordRules + { + public const int WeaponId = 6603; + public const float MaximumEnergy = 200; + public const float ReadyThreshold = 199.9f; + + public static bool IsSupportedSkill(int id) => id >= 2201 && id <= 2224; + + public static int SelectedAttribute(BattleSwordPurificationElement element) => element switch + { + BattleSwordPurificationElement.Water => 7, + BattleSwordPurificationElement.Fire => 8, + BattleSwordPurificationElement.Thunder => 10, + BattleSwordPurificationElement.Wind => 9, + BattleSwordPurificationElement.Earth => 11, + BattleSwordPurificationElement.None => -1, + _ => throw new ArgumentOutOfRangeException(nameof(element)) + }; + + public static int EquipmentAttributeBonus(BattleMagicSwordSnapshot snapshot, int attribute) + { + RequireSnapshot(snapshot); + if (attribute < 0 || attribute > 11) + throw new ArgumentOutOfRangeException(nameof(attribute)); + if (attribute == 3) + return snapshot.AttackBonus; + return attribute == SelectedAttribute(snapshot.SelectedElement) ? 1 : 0; + } + + public static bool IsReady(BattleMagicSwordSnapshot snapshot, int identity, bool equipped) + { + RequireSnapshot(snapshot); + return identity == 0 && equipped && snapshot.SkillId != 0 && snapshot.Energy > ReadyThreshold; + } + + // Invoke for every ordinary physical work/work1 marker before hit resolution, + // including markers that subsequently miss. A zero coefficient is repaired there. + public static BattleMagicSwordSnapshot GainOnPhysicalWork(BattleMagicSwordSnapshot snapshot, int identity, bool equipped) + { + RequireSnapshot(snapshot); + if (identity != 0 || !equipped || snapshot.SkillId == 0) + return snapshot; + uint coefficient = snapshot.ChargeCoefficient == 0 ? 1 : snapshot.ChargeCoefficient; + float energy = Math.Min(MaximumEnergy, (float)(snapshot.Energy + (double)coefficient)); + return snapshot.WithEnergy(energy, coefficient); + } + + // Native action start consumes the entire gauge before any target is affected. + public static BattleMagicSwordSnapshot ConsumeEnergy(BattleMagicSwordSnapshot snapshot) + { + RequireSnapshot(snapshot); + return snapshot.WithEnergy(0); + } + + public static int SkillPower(BattleMagicSwordSnapshot snapshot, int skillId, short rawPower, + BattleSide targetSide, out BattleValueMode mode) + { + RequireSnapshot(snapshot); + if (!IsSupportedSkill(skillId)) + throw new NotSupportedException("Unknown PAL3 magic sword skill."); + if (targetSide is not (BattleSide.Ally or BattleSide.Enemy)) + throw new ArgumentOutOfRangeException(nameof(targetSide)); + mode = targetSide == BattleSide.Ally ? BattleValueMode.Percentage : BattleValueMode.Absolute; + // No magic-level, elemental, Warp or technique success calculation belongs here. + return skillId == 2224 ? BattleNativeArithmetic.TruncateToLowInt32(rawPower * (1.0 + 0.5 * snapshot.PurificationCount)) : rawPower; + } + + private static void RequireSnapshot(BattleMagicSwordSnapshot snapshot) + { + if (snapshot == null) + throw new ArgumentNullException(nameof(snapshot)); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSwordRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSwordRules.cs.meta new file mode 100644 index 00000000..646bba9c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleMagicSwordRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a9fa6cbb7304429cb7549a396644ed61 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleNativeArithmetic.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleNativeArithmetic.cs new file mode 100644 index 00000000..1e46e042 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleNativeArithmetic.cs @@ -0,0 +1,22 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + internal static class BattleNativeArithmetic + { + // Released CRT _ftol truncates to signed int64; callers retain EAX. + // Invalid conversion returns int64 indefinite, whose low int32 is zero. + // This differs from util::f2i's rounded int32 FISTP conversion. + internal static int TruncateToLowInt32(double value) + { + double truncated = Math.Truncate(value); + long converted = truncated >= long.MinValue && truncated < (double)long.MaxValue ? (long)truncated : long.MinValue; + return unchecked((int)converted); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleNativeArithmetic.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleNativeArithmetic.cs.meta new file mode 100644 index 00000000..a1ab4e69 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleNativeArithmetic.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cdf05faa4c7442548ac5cd55187eb249 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattlePal3ARules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattlePal3ARules.cs new file mode 100644 index 00000000..cd25f217 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattlePal3ARules.cs @@ -0,0 +1,62 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public static class BattlePal3ARules + { + public const int SpiritCaptureSkill = 4102; + public const int PengxuTransformSkill = 4308; + public const int GuInventoryItem = 6113; + public const int LiaoRiCarryActor = 722; + + public static bool IsDedicatedAbility(int id) => id is SpiritCaptureSkill or PengxuTransformSkill; + + public static BattleSpiritWheelSnapshot Gain(BattleSpiritWheelSnapshot wheel, int element, int count) + { + if (wheel == null || element < 0 || element >= 5) + throw new ArgumentException("Invalid spirit wheel operation."); + int[] charges = wheel.Charges.ToArray(); + charges[element] = Math.Clamp(unchecked(charges[element] + count), 0, 9); + return new BattleSpiritWheelSnapshot(charges); + } + + public static int CaptureForecast(int level, int effectiveAttack, int effectiveDefense, + int physicalElementDifference, bool rowOrColumn, BattleRandom random) + { + if (random == null) + throw new ArgumentNullException(nameof(random)); + // ForecastDamage(type=7), not a real attack: no minimum damage roll, + // madness multiplier, critical check, guarding or weapon divisor. + float raw = (float)((effectiveAttack - effectiveDefense) * (1.0 + level * (double)0.005f)); + int value = random.Warp(-BattleBasicRules.Round(raw), .1f); + if (rowOrColumn) + value = value * (random.Warp(100, .05f) - 45) / 100; + float scaled = (float)(value * (1.0 - physicalElementDifference * (double).05f)); + return BattleBasicRules.Round(scaled); + } + + public static bool CanCapture(int hp, bool valid, bool alive, bool boss, int forecast) + => valid && alive && !boss && hp <= BattleBasicRules.SignedAbs(forecast); + + public static int CaptureCount(IEnumerable originalElementValues) => checked(originalElementValues.Sum()); + + public static int AddLoss(int accumulated, int negativeRequest) => negativeRequest < 0 + ? unchecked(accumulated - negativeRequest) : accumulated; + + public static int CarryAttribute(int ordinary, int accumulated) => unchecked(ordinary + accumulated); + + public static int NangongAttribute(int ordinary, bool transformed) => transformed ? unchecked(ordinary * 2) : ordinary; + + public static bool ExpiresOnRound(int completedRounds, int roundLimit) => completedRounds >= roundLimit - 1; + + public static int PengxuSpellPower(int originalPower, bool transformed) => transformed + ? BattleBasicRules.Round((float)(originalPower * 1.5f)) : originalPower; + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattlePal3ARules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattlePal3ARules.cs.meta new file mode 100644 index 00000000..25ac1db0 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattlePal3ARules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 67aa7bab280846c4b83216b58b3203ae diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattlePhysicalAttackModes.cs b/Assets/Scripts/Pal3.Battle/Rules/BattlePhysicalAttackModes.cs new file mode 100644 index 00000000..d523817e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattlePhysicalAttackModes.cs @@ -0,0 +1,104 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + // Published InitRoleState/AttackSpecAffect switches, not the GDB skill range + // or state descriptions. Modes 930-934 belong to PAL3A. + public static class BattlePhysicalAttackModes + { + public static BattleTargetRange Range(int modeId) + { + ValidateMode(modeId); + return modeId switch + { + 916 or 917 or 921 or 922 or 926 or 927 or 933 => BattleTargetRange.OpponentRow, + 918 or 919 or 920 or 923 or 928 or 930 or 931 or 932 => BattleTargetRange.OpponentColumn, + _ => BattleTargetRange.OpponentSingle + }; + } + + public static BattleState? AddedState(int modeId) + { + ValidateMode(modeId); + return modeId switch + { + 901 or 933 => BattleState.PoisonWater, + 902 or 918 or 926 => BattleState.PoisonFire, + 903 or 932 => BattleState.PoisonWind, + 904 => BattleState.PoisonThunder, + 905 or 920 or 927 => BattleState.PoisonEarth, + 906 => BattleState.Paralysis, + 907 or 919 or 921 => BattleState.Seal, + 908 or 928 => BattleState.Forbidden, + 909 => BattleState.Sleep, + 910 or 916 => BattleState.Chaos, + 911 or 917 => BattleState.Madness, + // PAL3A's 930/931/934 do not add the states written in the GDB. + _ => null + }; + } + + public static BattleTargetRange WeaponRange(string variant, int weaponType, int identity) + { + ValidateVariant(variant); + if (identity < 0 || identity > 4) + throw new ArgumentOutOfRangeException(nameof(identity), "A weapon range needs the original player identity."); + if (weaponType == 0) + throw new NotSupportedException("Weapon type 0 consumes original random initialization and needs a session-owned range snapshot."); + if (variant == "PAL3") + { + if (weaponType < 1 || weaponType > 7) + throw new NotSupportedException("Unknown PAL3 weapon type " + weaponType + "."); + // The published game overrides Jingtian's range after the type switch. + if (identity == 0) + return BattleTargetRange.OpponentColumn; + return weaponType switch + { + 1 or 3 => BattleTargetRange.OpponentColumn, + 4 or 7 => BattleTargetRange.OpponentRow, + _ => BattleTargetRange.OpponentSingle + }; + } + if (weaponType < 1 || weaponType > 10) + throw new NotSupportedException("Unknown PAL3A weapon type " + weaponType + "."); + return weaponType switch + { + 2 or 10 => BattleTargetRange.OpponentRow, + 4 or 9 => BattleTargetRange.OpponentColumn, + _ => BattleTargetRange.OpponentSingle + }; + } + + public static string UnsupportedReason(string variant, int modeId) + { + ValidateVariant(variant); + // Stock non-combat spirits use 0; PAL3A actor 7398 uses 7714. + // InitRoleState leaves all range flags clear and AttackSpecAffect + // takes its default branch. The latter is not an AI spell alias + // when stored in the actor's normal-attack field. + if (modeId == 0 || variant == "PAL3A" && modeId == 7714) + return ""; + if (modeId < 901 || modeId > (variant == "PAL3" ? 929 : 934)) + return "Unknown original physical attack mode " + modeId + "."; + // Published special handler 30 succeeds without changing state. + return ""; + } + + private static void ValidateMode(int modeId) + { + if (modeId != 0 && modeId != 7714 && (modeId < 901 || modeId > 934)) + throw new NotSupportedException("Unknown original physical attack mode " + modeId + "."); + } + + private static void ValidateVariant(string variant) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattlePhysicalAttackModes.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattlePhysicalAttackModes.cs.meta new file mode 100644 index 00000000..295a9a4e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattlePhysicalAttackModes.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8b0c354e7d3d46cda93bc9e348668c93 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleRelationRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleRelationRules.cs new file mode 100644 index 00000000..e0205074 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleRelationRules.cs @@ -0,0 +1,47 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public readonly struct BattleRelationChange + { + public bool Applied + { + get; + } + + public int Value + { + get; + } + + public string Sound + { + get; + } + + internal BattleRelationChange(bool applied, int value, string sound) + { + Applied = applied; + Value = value; + Sound = sound; + } + } + + public static class BattleRelationRules + { + public static BattleRelationChange Change(string variant, int nativeIndex, int current, int requested, bool heroValid) + { + if (variant is not ("PAL3" or "PAL3A") || nativeIndex is < 0 or > 10) + throw new ArgumentException("Invalid original relationship writer context."); + if (!heroValid || nativeIndex == 4 || variant == "PAL3A" && nativeIndex == 3) + return new BattleRelationChange(false, current, null); + int value = Math.Clamp(unchecked(current + requested), 0, 999); + return new BattleRelationChange(true, value, requested > 0 ? "wa010" : requested < 0 ? "wa048" : null); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleRelationRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleRelationRules.cs.meta new file mode 100644 index 00000000..0cbc44e1 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleRelationRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7fd40a31b8564e75aeecdfc31b1016e1 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleSpecialRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleSpecialRules.cs new file mode 100644 index 00000000..b12f669d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleSpecialRules.cs @@ -0,0 +1,199 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + public enum BattleSpecialHandler + { + None, HalfActualHpAbsorb, ReturnedMpAbsorb, Steal, MoneyRecovery, MoneyThrow, RandomPoison, PoisonDragonGall, Summon, + GenericOnly, RandomFormation, AbsorbHpWorm, ForceFlee + } + + public sealed class BattleStealPoolSnapshot + { + public string Actor + { + get; + } + + public int Money + { + get; + } + + public int ItemId + { + get; + } + + public int ItemCount + { + get; + } + + internal BattleStealPoolSnapshot(string actor, int money, int itemId, int itemCount) + { + Actor = actor; + Money = money; + ItemId = itemId; + ItemCount = itemCount; + } + } + + // Published dispatch and arithmetic only. The session owns every resource and state write. + public static class BattleSpecialRules + { + public static BattleSpecialHandler AbilityHandler(string variant, int id, bool item, bool magic, int rawSpecial) + { + ValidateVariant(variant); + if (item) + return id == 6230 ? BattleSpecialHandler.PoisonDragonGall : rawSpecial switch + { + 1 => BattleSpecialHandler.RandomPoison, + 2 => BattleSpecialHandler.ForceFlee, + 29 => BattleSpecialHandler.Summon, + _ => BattleSpecialHandler.None + }; + if (magic) + return rawSpecial switch + { + 1 => BattleSpecialHandler.RandomPoison, + 25 => BattleSpecialHandler.RandomFormation, + 29 => BattleSpecialHandler.Summon, + 18 when id == 258 => BattleSpecialHandler.GenericOnly, + 0 when variant == "PAL3A" && id == 205 => BattleSpecialHandler.GenericOnly, + 35 when variant == "PAL3A" && id == 273 => BattleSpecialHandler.GenericOnly, + _ => BattleSpecialHandler.None + }; + if (id == 4101) + return BattleSpecialHandler.Steal; + if (id == (variant == "PAL3" ? 4201 : 4301)) + return BattleSpecialHandler.HalfActualHpAbsorb; + if (id == (variant == "PAL3" ? 4304 : 4504)) + return BattleSpecialHandler.ReturnedMpAbsorb; + if (id == (variant == "PAL3" ? 4102 : 4106)) + return BattleSpecialHandler.MoneyRecovery; + if (id == (variant == "PAL3" ? 4305 : 4206)) + return BattleSpecialHandler.MoneyThrow; + if (variant == "PAL3" && id == 4402) + return BattleSpecialHandler.AbsorbHpWorm; + if (variant == "PAL3A" && id == 4505 && rawSpecial == 37) + return BattleSpecialHandler.GenericOnly; + return BattleSpecialHandler.None; + } + + public static bool SupportsSuccessRate(string variant, int id, int rate) + { + ValidateVariant(variant); + return rate is 0 or 1 or 100 || variant == "PAL3A" && id is 4503 or 4505 && rate == 50; + } + + public static bool UsesLiteralSuccessRate(string variant, int id, int rate) + { + ValidateVariant(variant); + return variant == "PAL3A" && id is 4503 or 4505 && rate == 50; + } + + public static bool RejectsBossBeforeSuccessRoll(string variant, int id) + { + ValidateVariant(variant); + return variant == "PAL3A" && id == 4505; + } + + public static bool UsesAbsoluteHpCost(string variant, int id) + { + ValidateVariant(variant); + return variant == "PAL3A" && id == 4507; + } + + public static bool SupportsEquipmentSpecial(string variant, int id, int slot, int rawSpecial) + { + ValidateVariant(variant); + if (rawSpecial is 0 or 20 or 21 or 22 or 23 or 24) + return true; + // Released non-weapon initialization ignores these markers. Their + // ordinary GDB attributes still apply; no named passive is inferred. + return slot != 0 && (variant == "PAL3" && id == 84006 && rawSpecial == 32 || + variant == "PAL3A" && (id == 8148 && rawSpecial == 33 || id == 8151 && rawSpecial == 34)); + } + + public static IReadOnlyList RandomFormation(BattleRandom random) + { + if (random == null) + throw new ArgumentNullException(nameof(random)); + var lineup = new[] { BattleSlot.Water, BattleSlot.Fire, BattleSlot.Wind, BattleSlot.Thunder, BattleSlot.Earth, BattleSlot.Center }; + for (int swap = 0; swap < 32; swap++) + { + int first = random.Next() % 6; + int second = random.Next() % 6; + (lineup[first], lineup[second]) = (lineup[second], lineup[first]); + } + return Array.AsReadOnly(lineup); + } + + public static int AbsorbHpWormRequest(int maximumHp, int round) + { + if (maximumHp < 0 || round < 1 || round > byte.MaxValue) + throw new ArgumentOutOfRangeException(maximumHp < 0 ? nameof(maximumHp) : nameof(round)); + // Released x87 multiplies the integer by the stored float constant + // before truncation; keep that precision instead of a float product. + float fraction = round switch + { + 1 => .05f, + 2 => .1f, + 3 => .15f, + _ => 0f + }; + return (int)(-maximumHp * (double)fraction); + } + + public static bool IsTreasure(string variant, int id) + { + ValidateVariant(variant); + return id >= 6119 && id <= (variant == "PAL3" ? 6125 : 6124); + } + + public static int HalfActualHp(int before, int after) => Math.Abs((before - after) / 2); + + public static int AbsorbedMp(int nativeReturnedValue) => BattleBasicRules.SignedAbs(nativeReturnedValue); + + public static int RequiredMoney(string variant, BattleSpecialHandler handler, int rawCost, int livingAllies, int primaryLevel) + { + ValidateVariant(variant); + return handler switch + { + BattleSpecialHandler.MoneyRecovery => Math.Max(rawCost, checked(livingAllies * (40 + 2 * primaryLevel))), + BattleSpecialHandler.MoneyThrow => Math.Max(rawCost, variant == "PAL3" ? 1000 : 3000), + _ => rawCost + }; + } + + public static int StealAmount(int remaining, BattleRandom random) + { + if (remaining < 0) + throw new ArgumentOutOfRangeException(nameof(remaining)); + if (random == null) + throw new ArgumentNullException(nameof(random)); + return remaining == 0 ? 0 : random.Next() % remaining + 1; + } + + public static int ShieldedHpRequest(int signedRequest, int money, out int payment) + { + if (money < 0) + throw new ArgumentOutOfRangeException(nameof(money)); + payment = signedRequest >= 0 ? 0 : (int)Math.Min(money, -(long)signedRequest); + return signedRequest + payment; + } + + private static void ValidateVariant(string variant) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleSpecialRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleSpecialRules.cs.meta new file mode 100644 index 00000000..312db385 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleSpecialRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2392bfe58fc34211835615742133e356 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleStatusRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleStatusRules.cs new file mode 100644 index 00000000..844a584b --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleStatusRules.cs @@ -0,0 +1,248 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleStatusInstance + { + public BattleState State + { + get; + } + + public int LatentRounds + { + get; internal set; + } + + public int RemainingRounds + { + get; internal set; + } + + public bool Permanent + { + get; + } + + public float EarthDamage + { + get; internal set; + } + + internal bool EarthDamageInitialized + { + get; set; + } + + internal BattleStatusInstance(BattleState state, int latentRounds, int remainingRounds, bool permanent) + { + State = state; + LatentRounds = latentRounds; + RemainingRounds = remainingRounds; + Permanent = permanent; + } + } + + // Native SetSpecState / HandleSpecStateBout. The session owns HP writes and cancellation. + public sealed class BattleStatusRules + { + public static bool SupportsInitialState(BattleState state) => state is >= BattleState.PoisonWind and <= BattleState.PoisonResist; + + private readonly bool _isPal3A; + + public BattleStatusRules(string variant) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + _isPal3A = variant == "PAL3A"; + } + + public BattleStatusInstance Create(BattleState state, int maxHp, int? durationOverride = null, + bool permanent = false, BattleRandom random = null, bool isPlayer = true) + { + if (maxHp < 0) + throw new ArgumentOutOfRangeException(nameof(maxHp)); + if (durationOverride < 1) + throw new ArgumentOutOfRangeException(nameof(durationOverride)); + int latent = 0; + int duration; + switch (state) + { + case BattleState.PoisonWind: + latent = 3; + duration = 5; + break; + case BattleState.PoisonThunder: + latent = 3; + duration = 2; + break; + case BattleState.PoisonWater: + case BattleState.AttackIncrease: + case BattleState.AttackDecrease: + case BattleState.DefenseIncrease: + case BattleState.DefenseDecrease: + case BattleState.LuckIncrease: + case BattleState.LuckDecrease: + case BattleState.SpeedIncrease: + case BattleState.SpeedDecrease: + case BattleState.Invisible: + duration = 5; + break; + case BattleState.PoisonFire: + case BattleState.PoisonEarth: + case BattleState.Seal: + case BattleState.Forbidden: + case BattleState.Chaos: + case BattleState.Madness: + duration = short.MaxValue; + break; + case BattleState.Paralysis: + case BattleState.Evade: + case BattleState.Barrier: + duration = 4; + break; + case BattleState.Sleep: + if (!durationOverride.HasValue && random == null) + throw new ArgumentException("Sleep duration requires the session random source.", nameof(random)); + duration = durationOverride ?? random.Next() % 7 + 2; + break; + case BattleState.Reflection: + duration = isPlayer ? 3 : 5; + break; + case BattleState.Dying: + case BattleState.Death: + case BattleState.PoisonResist: + duration = short.MaxValue; + permanent = true; + break; + default: + throw new NotSupportedException($"State {state} has no verified ordinary combat rule."); + } + return new BattleStatusInstance(state, latent, durationOverride ?? duration, permanent); + } + + public int ModifyAttribute(int index, int value, IEnumerable states) + { + if (states == null) + throw new ArgumentNullException(nameof(states)); + BattleState increase; + BattleState decrease; + switch (index) + { + case 3: + increase = BattleState.AttackIncrease; + decrease = BattleState.AttackDecrease; + break; + case 4: + increase = BattleState.DefenseIncrease; + decrease = BattleState.DefenseDecrease; + break; + case 5: + increase = BattleState.SpeedIncrease; + decrease = BattleState.SpeedDecrease; + break; + case 6: + increase = BattleState.LuckIncrease; + decrease = BattleState.LuckDecrease; + break; + default: + return value; + } + float fraction = _isPal3A && index is 3 or 4 ? 0.08f : 0.25f; + var active = states as ICollection ?? states.ToArray(); + if (active.Contains(increase)) + return value + BattleBasicRules.Round(value * fraction); + if (active.Contains(decrease)) + return value + BattleBasicRules.Round(value * -fraction); + return value; + } + + public int TickRound(BattleStatusInstance instance, int maxHp, int currentHp) + { + if (instance == null) + throw new ArgumentNullException(nameof(instance)); + if (maxHp < 0 || currentHp < 0) + throw new ArgumentOutOfRangeException(nameof(maxHp)); + if (!instance.Permanent && instance.RemainingRounds <= 0) + return 0; + if (instance.LatentRounds > 0) + { + instance.LatentRounds--; + return 0; + } + int delta = 0; + switch (instance.State) + { + case BattleState.PoisonWind: + delta = maxHp * 3 / -4; + break; + case BattleState.PoisonThunder: + delta = maxHp / -2; + break; + case BattleState.PoisonWater: + delta = currentHp / -2; + break; + case BattleState.PoisonFire: + delta = maxHp * 5 / -100; + break; + case BattleState.PoisonEarth: + if (!instance.EarthDamageInitialized) + { + instance.EarthDamage = maxHp * -0.02f; + instance.EarthDamageInitialized = true; + } + delta = BattleBasicRules.Round(instance.EarthDamage); + instance.EarthDamage *= 1.5f; + break; + } + if (!instance.Permanent) + instance.RemainingRounds = Math.Max(0, instance.RemainingRounds - 1); + return delta; + } + + public IEnumerable ReplacedBy(BattleState state) + { + if (state >= BattleState.Paralysis && state <= BattleState.Invisible) + { + for (var conflict = BattleState.Paralysis; conflict <= BattleState.Invisible; conflict++) + yield return conflict; + } + else if (state >= BattleState.AttackIncrease && state <= BattleState.SpeedDecrease) + { + int pair = ((int)state - (int)BattleState.AttackIncrease) / 2; + yield return BattleState.AttackIncrease + pair * 2; + yield return BattleState.AttackIncrease + pair * 2 + 1; + } + else + { + yield return state; + } + } + + public string CanAdd(BattleState state, IEnumerable existing, IEnumerable immune) + { + if (existing == null || immune == null) + throw new ArgumentNullException(existing == null ? nameof(existing) : nameof(immune)); + var active = existing as ICollection ?? existing.ToArray(); + if (state != BattleState.Invisible && active.Contains(BattleState.Invisible)) + return "隐状态阻止其他状态变化。"; + if (IsPoison(state)) + { + if (active.Any(IsPoison)) + return "已有五毒,不能叠加或覆盖。"; + if (active.Contains(BattleState.PoisonResist) || immune.Contains(BattleState.PoisonResist)) + return "辟毒免疫五毒。"; + } + return immune.Contains(state) ? "目标免疫此状态。" : null; + } + + private static bool IsPoison(BattleState state) => state >= BattleState.PoisonWind && state <= BattleState.PoisonEarth; + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleStatusRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleStatusRules.cs.meta new file mode 100644 index 00000000..7ce31643 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleStatusRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2c1819bc8b814ab1a658a96c9a4d4462 diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleTargetRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleTargetRules.cs new file mode 100644 index 00000000..6f8eba10 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleTargetRules.cs @@ -0,0 +1,76 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Linq; + + public static class BattleTargetRules + { + // Original GetBestRoleForAttackRowOrCol visits these groups and slots in order. + private static readonly int[][] EnemyRows = { new[] { 8, 9 }, new[] { 5, 10, 7 }, new[] { 6 } }; + private static readonly int[][] EnemyColumns = { new[] { 5, 8 }, new[] { 6, 10 }, new[] { 7, 9 } }; + + private static readonly int[] AllyElementChain = { 1, 2, 4, 3, 5 }; + + private static int AllyFormationStart(int sceneElement) + { + if (sceneElement is < 0 or > 5) + throw new ArgumentOutOfRangeException(nameof(sceneElement)); + // FillFiveMagicMatrix leaves its starting index at Water for an unset element. + return sceneElement == 0 ? 0 : Array.IndexOf(AllyElementChain, BattleEffectRules.GreaterElement(sceneElement)); + } + + public static BattleSlot InitialAllySlot(BattleSlot slot, int sceneElement) + { + if (slot == BattleSlot.Center || sceneElement == 0) + return slot; + int original = Array.IndexOf(AllyElementChain, (int)slot + 1); + int offset = AllyFormationStart(sceneElement) + 1; + return (BattleSlot)(AllyElementChain[(original - offset + 5) % 5] - 1); + } + + internal static bool IsFrontAllySlot(BattleSlot slot, int sceneElement) + { + int start = AllyFormationStart(sceneElement); + int element = (int)slot + 1; + return element == AllyElementChain[(start + 2) % 5] || element == AllyElementChain[(start + 3) % 5]; + } + + internal static int BestEnemyLine(bool row, Func available) + { + int best = -1, bestCount = 0; + foreach (int[] line in row ? EnemyRows : EnemyColumns) + { + int count = line.Count(available); + if (count > 0 && count >= bestCount) + { + bestCount = count; + best = line.First(available); + } + } + return best; + } + + public static bool Aligned(BattleSide side, BattleSlot first, BattleSlot second, bool row, int sceneElement) + { + if (first == second) + return true; + if (side == BattleSide.Enemy) + return (row ? EnemyRows : EnemyColumns).Any(line => line.Contains(5 + (int)first) && line.Contains(5 + (int)second)); + int start = AllyFormationStart(sceneElement); + int[] groupsByOffset = row ? new[] { 0, 1, 2, 2, 1 } : new[] { 1, 0, 0, 2, 2 }; + int Group(BattleSlot slot) + { + if (slot == BattleSlot.Center) + return 1; + int offset = (Array.IndexOf(AllyElementChain, (int)slot + 1) - start + 5) % 5; + return groupsByOffset[offset]; + } + return Group(first) == Group(second); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleTargetRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleTargetRules.cs.meta new file mode 100644 index 00000000..4eaa5fcb --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleTargetRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 76acf46add81446b9fb4c9580aa0378f diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleWeaponPresentationRules.cs b/Assets/Scripts/Pal3.Battle/Rules/BattleWeaponPresentationRules.cs new file mode 100644 index 00000000..44510a19 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleWeaponPresentationRules.cs @@ -0,0 +1,152 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public readonly struct BattleWeaponVisibility + { + public bool Left + { + get; + } + + public bool Right + { + get; + } + + public BattleWeaponVisibility(bool left, bool right) + { + Left = left; + Right = right; + } + } + + public static class BattleWeaponPresentationRules + { + // Native logical action indices, not the currently retained MV3 name. + // The published combat tables and additional A actions are independent + // of the scene actor enum's NpcRun alias. + public static BattleWeaponVisibility Visible(string variant, int identity, int action, int weaponType, + bool hiddenForm = false, bool hasWeapon = true, bool external = false, float leftFlag = 0, float rightFlag = 0) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown original combat variant.", nameof(variant)); + bool left = action == 46; + bool right = action is >= 29 and <= 49 && action is not (38 or 46 or 48) || variant == "PAL3A" && action is 60 or 61; + if (variant == "PAL3") + { + if (identity == 0 && action is 39 or 49) + left = right = false; + if (identity is 1 or 3) + left = right = true; + if (identity is 2 or 4 && action == 46) + { + left = false; + right = true; + } + if (external) + { + left = leftFlag >= 0; + right = rightFlag >= 0; + } + } + else + { + if (identity == 0) + { + ApplyAHelper(identity, action, weaponType, ref left, ref right); + if (hiddenForm) + left = right = false; + } + if (identity == 1) + { + if (weaponType == 3) + left = right = true; + else if (weaponType == 4) + { + left = false; + right = true; + } + } + if (identity == 2) + { + if (hiddenForm) + left = right = false; + else if (weaponType == 6) + left = right = true; + else if (weaponType == 5) + { + left = true; + right = false; + } + } + if (identity == 3) + { + if (weaponType == 7) + { + left = false; + right = true; + } + if (weaponType == 10) + { + left = true; + right = false; + } + ApplyAHelper(identity, action, weaponType, ref left, ref right); + } + if (identity == 4) + ApplyAHelper(identity, action, weaponType, ref left, ref right); + if (external) + { + // A: positive forces on, zero forces off, negative retains + // the table/weapon result. PAL3's zero instead forces on. + if (leftFlag >= 0) + left = leftFlag > 0; + if (rightFlag >= 0) + right = rightFlag > 0; + } + } + return hasWeapon ? new BattleWeaponVisibility(left, right) : default; + } + + private static void ApplyAHelper(int identity, int action, int weapon, ref bool left, ref bool right) + { + if (identity == 0) + { + if (action == 46) + { + left = false; + right = true; + } + else if (action == 59 || action == 62 && weapon == 2) + { + left = false; + right = true; + } + else if (action == 62) + left = false; + } + if (identity == 3) + { + if (action == 59 && weapon == 10) + left = right = false; + if (action == 62) + { + if (weapon == 2) + right = false; + left = true; + } + } + if (identity == 4 && action is 46 or 59) + { + left = false; + right = true; + } + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Rules/BattleWeaponPresentationRules.cs.meta b/Assets/Scripts/Pal3.Battle/Rules/BattleWeaponPresentationRules.cs.meta new file mode 100644 index 00000000..5e5c5003 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Rules/BattleWeaponPresentationRules.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: bea171244d8944a89d7f577d15f0d5b3 diff --git a/Assets/Scripts/Pal3.Battle/Runtime.meta b/Assets/Scripts/Pal3.Battle/Runtime.meta new file mode 100644 index 00000000..5941df7a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 8601eb17b6f74fcf9e6c710273bb8b40 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattleCommand.cs b/Assets/Scripts/Pal3.Battle/Runtime/BattleCommand.cs new file mode 100644 index 00000000..e6be5d9b --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattleCommand.cs @@ -0,0 +1,47 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public enum BattleAction + { + Attack, Defend, Skill, Item, Flee, Transform + } + + public readonly struct BattleCommand + { + public string Actor + { + get; + } + + public BattleAction Action + { + get; + } + + public string Target + { + get; + } + + public int AbilityId + { + get; + } + + public BattleCommand(string actor, BattleAction action, string target = null, int abilityId = 0) + { + Actor = actor; + Action = action; + Target = target; + AbilityId = abilityId; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattleCommand.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/BattleCommand.cs.meta new file mode 100644 index 00000000..9fcaaf11 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattleCommand.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5b78e7d94f3c4242a695f75595327d27 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattleEvent.cs b/Assets/Scripts/Pal3.Battle/Runtime/BattleEvent.cs new file mode 100644 index 00000000..cc1af28d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattleEvent.cs @@ -0,0 +1,141 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public enum BattleEventKind + { + Started, Ready, Command, Hit, Miss, Death, ActionEnded, Cancelled, Interrupted, ControlChanged, Ended, + ResourceChanged, StatusAdded, StatusRemoved, SkillImproved, SkillLearned, ItemChanged, LevelUp, Escaped, + FormationOpened, FormationChanged, FormationClosed, ProtectionChanged, MovementStarted, MovementEnded, + TreasureUseChanged, StealPoolChanged, NumberShown, RelationChanged, CorpseObtained, PresentationCleanupFailed + } + + public sealed class BattleEvent + { + public long Tick + { + get; internal set; + } + + public BattleEventKind Kind + { + get; internal set; + } + + public string Source + { + get; internal set; + } + + public string Target + { + get; internal set; + } + + public long ActionId + { + get; internal set; + } + + public int RequestedDelta + { + get; internal set; + } + + public int ActualDelta + { + get; internal set; + } + + public int HpBefore + { + get; internal set; + } + + public int HpAfter + { + get; internal set; + } + + public bool Critical + { + get; internal set; + } + + public bool Dodged + { + get; internal set; + } + + public uint RandomState + { + get; internal set; + } + + public string Detail + { + get; internal set; + } + + public int Resource { get; internal set; } = -1; + + public int ValueBefore + { + get; internal set; + } + + public int ValueAfter + { + get; internal set; + } + + public int NumberOffset + { + get; internal set; + } + + public float DurationSeconds + { + get; internal set; + } + + public long NumberActivationTick + { + get; internal set; + } + + public float NumberStartedTime + { + get; internal set; + } + + public BattleMovementPoint NumberPosition + { + get; internal set; + } + + public bool NumberIsMiss + { + get; internal set; + } + + public bool NumberIsRecovery + { + get; internal set; + } + + public int AbilityId + { + get; internal set; + } + + public override string ToString() => FormattableString.Invariant($"{Tick * BattleSession.StepSeconds:F2}s {Kind} {Source} → {Target} Δ{ActualDelta} {Detail}"); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattleEvent.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/BattleEvent.cs.meta new file mode 100644 index 00000000..51bb1b6d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattleEvent.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 04cc04e4aff948238652e37035858ae8 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattleInput.cs b/Assets/Scripts/Pal3.Battle/Runtime/BattleInput.cs new file mode 100644 index 00000000..0c4f6a2c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattleInput.cs @@ -0,0 +1,43 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public enum BattleInputKind + { + Command, ControlChange, CancelAction, Abort, Fault, + BeginFormation, SwapFormation, EndFormation, SetProtection, + AiNormal, AiRepeat, AiProfile, AiAutoOnly, CoAttackPresentationSkip, AiControl, ElementWheel, ModalPresentationSkip, MagicMenuFieldDenial + } + + // Every external input, including a controller change, is recorded at the exact logical boundary. + [Serializable] + public sealed class BattleInput + { + public long Tick; + public string Actor; + public string Target; + public BattleAction Action; + public int AbilityId; + public int AiFlags; + public BattleInputKind Kind; + public BattleSlot FormationSlot; + public BattleSide Side; + public bool Automatic; + public bool FromTestAi; + public string Reason; + + internal bool Matches(BattleInput other) => other != null && + Tick == other.Tick && Kind == other.Kind && Actor == other.Actor && Target == other.Target && + Action == other.Action && AbilityId == other.AbilityId && AiFlags == other.AiFlags && FormationSlot == other.FormationSlot && + Side == other.Side && Automatic == other.Automatic && FromTestAi == other.FromTestAi && Reason == other.Reason; + + internal BattleInput Copy() => (BattleInput)MemberwiseClone(); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattleInput.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/BattleInput.cs.meta new file mode 100644 index 00000000..581e28c8 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattleInput.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 715da27bea084696873ca83d2756aaba diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattlePal3AState.cs b/Assets/Scripts/Pal3.Battle/Runtime/BattlePal3AState.cs new file mode 100644 index 00000000..07fe81a5 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattlePal3AState.cs @@ -0,0 +1,179 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + // Core element order is water, fire, wind, thunder, earth. The native wheel + // UI swaps wind/thunder; that presentation detail never changes this contract. + [Serializable] + public sealed class BattleSpiritWheel + { + public int[] Charges = new int[5]; + + public BattleSpiritWheel Copy() => new() { Charges = Charges?.ToArray() }; + + public BattleSpiritWheelSnapshot Capture() => new(Charges); + } + + [Serializable] + public sealed class BattlePal3AState + { + public BattleSpiritWheel SpiritWheel = new(); + public int SpiritVisualSeed = 1; + public bool NangongStartsTransformed; + public bool PengxuStartsTransformed; + public bool PreserveLiaoRiLosses; + public int HpLoss; + public int MpLoss; + + public BattlePal3AState Copy() => new() + { + SpiritWheel = SpiritWheel?.Copy(), + SpiritVisualSeed = SpiritVisualSeed, + NangongStartsTransformed = NangongStartsTransformed, + PengxuStartsTransformed = PengxuStartsTransformed, + PreserveLiaoRiLosses = PreserveLiaoRiLosses, + HpLoss = HpLoss, + MpLoss = MpLoss + }; + + public void Validate() + { + if (SpiritWheel == null) + throw new ArgumentException("PAL3A needs an explicit spirit wheel snapshot."); + _ = SpiritWheel.Capture(); + if (PreserveLiaoRiLosses && (HpLoss < 0 || MpLoss < 0)) + throw new ArgumentException("Captured PAL3A HP and MP losses must be nonnegative signed int32 values."); + } + } + + public sealed class BattleSpiritWheelSnapshot + { + public IReadOnlyList Charges + { + get; + } + + public int Tier => Charges.Min() / 3; + + public int NangongRounds => Tier * 3; + + public BattleSpiritWheelSnapshot(IEnumerable charges) + { + int[] values = charges?.ToArray(); + if (values is not { Length: 5 } || values.Any(value => value < 0 || value > 9)) + throw new ArgumentException("The original spirit wheel has five int32 charges between zero and nine.", nameof(charges)); + Charges = Array.AsReadOnly(values); + } + } + + public enum BattlePal3AFormKind + { + Human, + NangongFireBeast, + PengxuFairyBeast, + } + + public sealed class BattlePal3AFormSnapshot + { + public BattlePal3AFormKind Kind + { + get; + } + + public int Generation + { + get; + } + + public int Rounds + { + get; + } + + public int RoundLimit + { + get; + } + + public bool Pending + { + get; + } + + public bool LethalReturnPending + { + get; + } + + public string Model => Kind switch + { + BattlePal3AFormKind.NangongFireBeast => "107", + BattlePal3AFormKind.PengxuFairyBeast => "106", + _ => "" + }; + + internal BattlePal3AFormSnapshot(BattlePal3AFormKind kind, int generation, int rounds, int roundLimit, + bool pending, bool lethalReturnPending) + { + Kind = kind; + Generation = generation; + Rounds = rounds; + RoundLimit = roundLimit; + Pending = pending; + LethalReturnPending = lethalReturnPending; + } + } + + public sealed class BattlePal3AStateSnapshot + { + public BattleSpiritWheelSnapshot SpiritWheel + { + get; + } + + public uint SpiritVisualRandomState + { + get; + } + + public bool PreserveLiaoRiLosses + { + get; + } + + public int HpLoss + { + get; + } + + public int MpLoss + { + get; + } + + internal BattlePal3AStateSnapshot(BattleSpiritWheelSnapshot spiritWheel, bool preserveLiaoRiLosses, int hpLoss, int mpLoss, uint spiritVisualRandomState) + { + SpiritWheel = spiritWheel; + SpiritVisualRandomState = spiritVisualRandomState; + PreserveLiaoRiLosses = preserveLiaoRiLosses; + HpLoss = hpLoss; + MpLoss = mpLoss; + } + } + + // Captured immutable resource profiles are selected by the adapter at the + // native model swap, while actor identity, native slot and AI remain intact. + public interface IBattlePal3AFormCatalog + { + BattlePhysicalAnimation FormChangeAnimation(string actorId, bool transformed); + + void ActivatePal3AForm(string actorId, BattlePal3AFormKind kind); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattlePal3AState.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/BattlePal3AState.cs.meta new file mode 100644 index 00000000..d8ca9f5e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattlePal3AState.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2d5430e17c604c06b0f22d4bd456409d diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattleReplay.cs b/Assets/Scripts/Pal3.Battle/Runtime/BattleReplay.cs new file mode 100644 index 00000000..befd6215 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattleReplay.cs @@ -0,0 +1,157 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public static class BattleReplay + { + public static BattleSession Recreate(BattleSetup setup, IBattleCatalog catalog, BattleSession original, + IBattleEffectDirector effects = null, Action onCreated = null) + { + return RecreateFrames(setup, catalog, original, effects, onCreated).Last(); + } + + // Every element is the same session advanced to the next replay boundary. + // Enumeration must finish to verify the final timeline. + public static IEnumerable RecreateFrames(BattleSetup setup, IBattleCatalog catalog, BattleSession original, + IBattleEffectDirector effects = null, Action onCreated = null) + { + if (original == null) + throw new ArgumentNullException(nameof(original)); + BattleSession replay = null; + foreach (BattleSession frame in PlayFrames(setup, catalog, original.Inputs, original.Tick, + original.ReplayRules, original.Definitions, effects, onCreated)) + { + replay = frame; + yield return frame; + } + if (!original.MatchesModalTimeline(replay) || original.SimulationTick != replay.SimulationTick || + original.Status != replay.Status || original.Result?.Reason != replay.Result?.Reason) + throw new InvalidOperationException("Replay diverged from the original battle. Check that the same battle movies are available."); + } + + public static BattleSession Play(BattleSetup setup, IBattleCatalog catalog, IEnumerable inputs, long endTick, IBattleRules rules = null, BattleDefinitions definitions = null, IBattleEffectDirector effects = null, Action onCreated = null) + => PlayFrames(setup, catalog, inputs, endTick, rules, definitions, effects, onCreated).Last(); + + private static IEnumerable PlayFrames(BattleSetup setup, IBattleCatalog catalog, IEnumerable inputs, long endTick, + IBattleRules rules, BattleDefinitions definitions, IBattleEffectDirector effects, Action onCreated) + { + if (endTick < 0 || endTick > 10000000) + throw new ArgumentOutOfRangeException(nameof(endTick)); + BattleInput[] recorded = inputs?.Select(input => input?.Copy() ?? throw new ArgumentException("Missing replay input.")).ToArray() + ?? throw new ArgumentNullException(nameof(inputs)); + if (recorded.Any(input => input.Tick < 0 || input.Tick > endTick) || !recorded.Select(input => input.Tick).SequenceEqual(recorded.Select(input => input.Tick).OrderBy(tick => tick))) + throw new ArgumentException("Replay inputs must be in their recorded order and within the requested tick range."); + var session = new BattleSession(setup, catalog, rules, definitions, effects); + onCreated?.Invoke(session); + int cursor = 0; + while (true) + { + while (cursor < recorded.Length && recorded[cursor].Tick == session.Tick) + { + BattleInput input = recorded[cursor++]; + if (!Enum.IsDefined(typeof(BattleInputKind), input.Kind)) + throw new ArgumentException("Unknown replay input kind."); + if (input.FromTestAi) + { + // Automatic commands are regenerated; they must still agree with their recorded payload. + if (!session.MatchesRecordedInput(cursor - 1, input)) + throw new InvalidOperationException("Replay automatic input diverged at " + session.Tick); + continue; + } + switch (input.Kind) + { + case BattleInputKind.ControlChange: + session.SetAutomatic(input.Side, input.Automatic); + break; + case BattleInputKind.Abort: + session.Abort(input.Reason); + break; + case BattleInputKind.Fault: + session.Fault(input.Reason); + break; + case BattleInputKind.CancelAction: + if (!session.CancelAction(input.Actor)) + throw new InvalidOperationException("Replay cancellation rejected at " + session.Tick); + break; + case BattleInputKind.Command: + if (!session.Submit(new BattleCommand(input.Actor, input.Action, input.Target, input.AbilityId))) + throw new InvalidOperationException("Replay command rejected at " + session.Tick); + break; + case BattleInputKind.ElementWheel: + if (!session.SubmitElementWheel(input.Actor, input.AbilityId)) + throw new InvalidOperationException("Replay spirit wheel command rejected at " + session.Tick); + break; + case BattleInputKind.SetProtection: + if (!session.SetProtection(input.Actor, input.Target)) + throw new InvalidOperationException("Replay protection change rejected at " + session.Tick); + break; + case BattleInputKind.BeginFormation: + if (!session.BeginFormation(input.Actor)) + throw new InvalidOperationException("Replay formation opening rejected at " + session.Tick); + break; + case BattleInputKind.SwapFormation: + if (!session.SwapFormation(input.Actor, input.FormationSlot)) + throw new InvalidOperationException("Replay formation swap rejected at " + session.Tick); + break; + case BattleInputKind.AiNormal: + session.RequestAiNormal(input.Actor); + break; + case BattleInputKind.AiRepeat: + session.RequestAiRepeat(input.Actor); + break; + case BattleInputKind.MagicMenuFieldDenial: + if (!session.InspectMagicMenuAbility(input.Actor, input.AbilityId)) + throw new InvalidOperationException("Replay could not invalidate a forbidden magic menu command at " + session.Tick); + break; + case BattleInputKind.AiProfile: + session.SetAiProfile(input.Actor, input.AiFlags); + break; + case BattleInputKind.AiControl: + if (!session.CommitAiControl(input.Actor, input.AiFlags)) + throw new InvalidOperationException("Replay AI control rejected at " + session.Tick); + break; + case BattleInputKind.AiAutoOnly: + session.SetAiAutoOnly(input.Automatic); + break; + case BattleInputKind.CoAttackPresentationSkip: + session.SkipCoAttackPresentation(); + break; + case BattleInputKind.ModalPresentationSkip: + if (!session.SkipModalPresentation()) + throw new InvalidOperationException("Replay cannot skip a missing battle movie at " + session.Tick); + break; + case BattleInputKind.EndFormation: + if (!session.EndFormation(input.Actor)) + throw new InvalidOperationException("Replay formation closing rejected at " + session.Tick); + break; + default: + throw new ArgumentException("Unsupported replay input kind: " + input.Kind); + } + if (!session.MatchesRecordedInput(cursor - 1, input)) + throw new InvalidOperationException("Replay input diverged at " + session.Tick); + } + if (session.Tick == endTick) + { + if (session.RecordedInputCount != recorded.Length) + throw new InvalidOperationException("Replay generated a different number of inputs."); + yield return session; + yield break; + } + if (session.Status != BattleSessionStatus.Running) + throw new InvalidOperationException("Replay ended before its recorded final tick."); + long before = session.Tick; + session.Step(); + if (session.Tick == before) + throw new InvalidOperationException("Replay needs a battle movie that has not finished preparing."); + yield return session; + } + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattleReplay.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/BattleReplay.cs.meta new file mode 100644 index 00000000..df0f78dc --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattleReplay.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: dc0c06f5bfd440c098102a1e4c4adb6c diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattleSessionStatus.cs b/Assets/Scripts/Pal3.Battle/Runtime/BattleSessionStatus.cs new file mode 100644 index 00000000..5ecfdef2 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattleSessionStatus.cs @@ -0,0 +1,16 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public enum BattleSessionStatus + { + Running, Completed, Aborted, Faulted + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/BattleSessionStatus.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/BattleSessionStatus.cs.meta new file mode 100644 index 00000000..ec05876c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/BattleSessionStatus.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1de0600fd8e64369af0ec71cdf46f160 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session.meta new file mode 100644 index 00000000..65b9265a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e84ee91c42b543cca45c20c39fe721cc +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.AbilityPresentation.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.AbilityPresentation.cs new file mode 100644 index 00000000..b0655fce --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.AbilityPresentation.cs @@ -0,0 +1,384 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private sealed class AbilityPresentationSubtask + { + public int Status; + public float Started; + public bool Executed; + } + + private sealed class AbilityPresentationRun + { + public BattleAbilityStageProfile Profile; + public Actor Owner; + public bool OwnsMovement; + public bool ReturnTurnQueued; + public readonly AbilityPresentationSubtask[] Steps = Enumerable.Range(0, 7).Select(_ => new AbilityPresentationSubtask()).ToArray(); + public bool Worked, FirstStarted, SecondStarted; + public long FirstHandle, SecondHandle; + public long BodyQueuedAt; + public bool UsesBodyBinding, BodyExecuted, BodyFinished; + public BattlePhysicalAnimation BodyRequested; + public int? BodyNativeAction; + } + + private readonly Dictionary _abilityPresentations = new(); + private readonly Dictionary _pendingAbilityMovementBodies = new(StringComparer.Ordinal); + + private string ValidateAbilityPresentation(Actor actor, BattleAbilityDefinition ability, bool elementWheel = false) + { + if (IsMagicSwordAbility(ability) || _catalog is not IBattleAbilityEffects catalog) + return null; + BattleAbilityStageProfile profile = elementWheel ? ((IBattleElementWheelTimings)_catalog).ElementWheelStage(actor.Initial.InstanceId, ability) : + catalog.AbilityStage(actor.Initial.InstanceId, ability); + if (_effects == null && (profile.First.GroupId >= 0 || profile.Second.GroupId >= 0 || + profile.WorkBoundary == BattleAbilityWorkBoundary.WorkTimeAndFirstGroupFinished)) + return "This ability requires its original effect completion director."; + return null; + } + + // Catalogs without presentation profiles preserve the independent pure + // mechanics fixtures. Resource-backed catalogs always use this director. + private bool TryAdvanceAbilityPresentation(Actor actor, ActionRun run, BattleStageContext context, out bool finished) + { + finished = false; + if (IsMagicSwordAbility(run.Ability) || _catalog is not IBattleAbilityEffects catalog) + return false; + if (!_abilityPresentations.TryGetValue(run.Id, out AbilityPresentationRun stage)) + { + stage = new AbilityPresentationRun + { + Profile = run.ElementWheel ? ((IBattleElementWheelTimings)_catalog).ElementWheelStage(actor.Initial.InstanceId, run.Ability) : + catalog.AbilityStage(actor.Initial.InstanceId, run.Ability), + Owner = actor + }; + stage.Steps[0].Status = 1; + stage.Steps[0].Started = context.CreatedTime; + _abilityPresentations.Add(run.Id, stage); + } + run.Elapsed = checked((int)(context.Tick - run.TimelineOriginTick)); + for (int index = 0; index < stage.Steps.Length; index++) + { + if (index > 0 && stage.Steps[(int)BattleAbilityStageStep.Grab].Status != 2) + break; + AbilityPresentationSubtask sub = stage.Steps[index]; + if (index > 0 && stage.Steps[index - 1].Status == 0) + break; + if (sub.Status == 2) + continue; + if (run.ElementWheel && index is >= (int)BattleAbilityStageStep.Name and <= (int)BattleAbilityStageStep.PrepareBody) + { + sub.Status = 2; + sub.Started = stage.Steps[(int)BattleAbilityStageStep.Grab].Started; + continue; + } + if (index == (int)BattleAbilityStageStep.Lineup && stage.Profile.Kind != BattleAbilityStageKind.Magic) + { + sub.Status = 2; + sub.Started = stage.Steps[(int)BattleAbilityStageStep.Name].Started; + continue; + } + if (sub.Status == 0) + { + AbilityPresentationSubtask previous = stage.Steps[index - 1]; + bool parallel = index == (int)BattleAbilityStageStep.Lineup && stage.Profile.Kind == BattleAbilityStageKind.Magic || + index == (int)BattleAbilityStageStep.PrepareBody; + if (parallel) + { + // Skill has no separate lineup task. Its prepare wait is relative to Name. + if (stage.Profile.Kind != BattleAbilityStageKind.Magic && index == (int)BattleAbilityStageStep.PrepareBody) + previous = stage.Steps[(int)BattleAbilityStageStep.Name]; + float wait = index == (int)BattleAbilityStageStep.PrepareBody ? stage.Profile.PrepareWaitSeconds : 0; + if ((double)context.Time - previous.Started <= wait) + continue; + } + else if (previous.Status != 2) + continue; + sub.Status = 1; + sub.Started = context.Time; + } + if (AdvanceAbilityPresentationStep(actor, run, stage, (BattleAbilityStageStep)index, sub, context)) + sub.Status = 2; + if (actor.Run != run || Status != BattleSessionStatus.Running) + { + finished = true; + return true; + } + } + finished = stage.Steps.All(sub => sub.Status == 2); + if (finished) + _abilityPresentations.Remove(run.Id); + return true; + } + + private bool AbilityRoleIdle(Actor actor, ActionRun run, AbilityPresentationRun stage) => + !IsActorExternallyControlled(actor.Initial.InstanceId) && !PhysicalBodyBusy(actor) && !HasFormationMovement(actor) && SimulationTick >= actor.HurtUntil && + (!run.StageStarted || (stage.UsesBodyBinding ? stage.BodyFinished : SimulationTick > stage.BodyQueuedAt && run.BodyElapsed >= stage.Profile.BodyAnimationTicks)); + + private bool AdvanceAbilityPresentationStep(Actor actor, ActionRun run, AbilityPresentationRun stage, + BattleAbilityStageStep step, AbilityPresentationSubtask sub, BattleStageContext context) + { + switch (step) + { + case BattleAbilityStageStep.Grab: + return !HasFormationMovement(actor) && context.Tick >= actor.HurtUntil && TryGrabStageBody(actor, context.Handle); + case BattleAbilityStageStep.Name: + if (!sub.Executed) + { + sub.Executed = true; + ShowStageMessage(stage, actor.Initial.Side, run.Ability.Name, allowTrail: run.Ability.IsItem, handle: context.Handle); + } + bool nameDone = run.EndRequested || (double)context.Time - sub.Started > stage.Profile.NameSeconds; + if (nameDone) + HideStageMessage(stage); + return nameDone; + case BattleAbilityStageStep.Lineup: + return stage.Profile.Kind != BattleAbilityStageKind.Magic || run.EndRequested || + (double)context.Time - sub.Started > stage.Profile.LineupSeconds; + case BattleAbilityStageStep.PrepareBody: + if (!sub.Executed) + { + if (!AbilityRoleIdle(actor, run, stage)) + return stage.Profile.Kind == BattleAbilityStageKind.Magic && run.EndRequested; + sub.Executed = true; + if (stage.Profile.Kind == BattleAbilityStageKind.Magic) + ResetActorFacing(actor); + if (stage.Profile.ApproachKind.HasValue) + { + stage.OwnsMovement = true; + QueueAbilityMovement(actor, run, false); + } + } + return run.EndRequested || !HasFormationMovement(actor) && context.Tick >= actor.HurtUntil; + case BattleAbilityStageStep.Act: + if (!sub.Executed) + { + // Native MagicAct rechecks both common and special costs before body/effects. + if (stage.Profile.Kind == BattleAbilityStageKind.Magic && + GetCostEstimate(new BattleCommand(actor.Initial.InstanceId, run.Kind, run.Target, run.Ability.Id)).Any(cost => cost.Required > cost.Available)) + { + stage.Worked = run.AbilityResolved = true; + return true; + } + if (HasFormationMovement(actor) || PhysicalBodyBusy(actor) || IsActorExternallyControlled(actor.Initial.InstanceId) || context.Tick < actor.HurtUntil) + return false; + sub.Executed = true; + if (stage.Profile.Kind == BattleAbilityStageKind.Item) + ResetActorFacing(actor); + run.StageStarted = true; + if (_catalog is IBattleAbilityBodyAnimations bodies) + { + stage.UsesBodyBinding = true; + stage.BodyRequested = run.ElementWheel ? ((IBattleElementWheelTimings)_catalog).ElementWheelBody(actor.Initial.InstanceId, run.Ability) : + bodies.AbilityBody(actor.Initial.InstanceId, run.Ability); + stage.BodyNativeAction = run.ElementWheel ? null : bodies.AbilityNativeAction(actor.Initial.InstanceId, run.Ability); + } + run.BodyElapsed = 0; + run.BodyRestartPending = true; + stage.BodyQueuedAt = context.Tick; + } + double elapsed = (double)context.Time - sub.Started; + if (!stage.FirstStarted && elapsed >= stage.Profile.First.WaitSeconds) + { + stage.FirstStarted = true; + stage.FirstHandle = StartAbilityEffect(actor, run, stage.Profile, stage.Profile.First); + } + if (!stage.SecondStarted && elapsed >= stage.Profile.Second.WaitSeconds) + { + stage.SecondStarted = true; + stage.SecondHandle = StartAbilityEffect(actor, run, stage.Profile, stage.Profile.Second); + } + if (!stage.Worked && elapsed >= stage.Profile.WorkSeconds && + (stage.Profile.Kind != BattleAbilityStageKind.Item || stage.FirstStarted) && + (stage.Profile.WorkBoundary != BattleAbilityWorkBoundary.WorkTimeAndFirstGroupFinished || + stage.FirstStarted && (stage.FirstHandle == 0 || !_effects.IsRunning(stage.FirstHandle)))) + { + stage.Worked = true; + if (stage.Profile.WorkBoundary != BattleAbilityWorkBoundary.WorkTimeAndBodyIdle && actor.Alive && !actor.Escaped) + ResolveActionMarker(actor, run); + } + if (stage.Worked && AbilityRoleIdle(actor, run, stage)) + { + if (stage.Profile.WorkBoundary == BattleAbilityWorkBoundary.WorkTimeAndBodyIdle && actor.Alive && !actor.Escaped) + ResolveActionMarker(actor, run); + return true; + } + return run.EndRequested; + case BattleAbilityStageStep.ReturnHome: + if (run.EndRequested) + return true; + if (!sub.Executed) + { + if (!AbilityRoleIdle(actor, run, stage)) + return false; + sub.Executed = true; + if (stage.Profile.ReturnKind.HasValue) + { + stage.OwnsMovement = true; + QueueAbilityMovement(actor, run, true); + } + } + if (HasFormationMovement(actor) || context.Tick < actor.HurtUntil) + return false; + if (stage.Profile.Kind == BattleAbilityStageKind.Skill && !stage.ReturnTurnQueued) + { + stage.ReturnTurnQueued = true; + // ProcSkillEnd queues ProcTurn after the return movement. + // Keep the body lease until that final body task has run. + if (_catalog is IBattlePhysicalTimings) + { + QueuePhysicalTask(actor, new PhysicalBodyTask + { + Kind = BattlePhysicalBodyKind.Turn, + Destination = new BattleMovementPoint(BattleFacingRules.Initial(actor.Initial.Side), 0, 0) + }); + return false; + } + ResetActorFacing(actor); + } + return !PhysicalBodyBusy(actor); + case BattleAbilityStageStep.Release: + ReleaseStageBody(actor, context.Handle); + return true; + default: + throw new InvalidOperationException("Unknown original ability stage step."); + } + } + + private bool HasActiveOrdinaryAbilityBody(Actor actor) => actor.Run != null && actor.Run.StageStarted && + (_abilityPresentations.TryGetValue(actor.Run.Id, out AbilityPresentationRun stage) && stage.UsesBodyBinding && !stage.BodyFinished || + _magicSwordStages.TryGetValue(actor.Run.Id, out MagicSwordStageRun sword) && sword.UsesBodyBinding && !sword.BodyFinished); + + private void RestartOrdinaryAbilityBodyAfterPush(Actor actor) + { + if (actor.Run != null && _abilityPresentations.TryGetValue(actor.Run.Id, out AbilityPresentationRun stage) && + stage.UsesBodyBinding && !stage.BodyFinished) + { + stage.BodyExecuted = false; + actor.Run.BodyElapsed = 0; + } + if (actor.Run != null && _magicSwordStages.TryGetValue(actor.Run.Id, out MagicSwordStageRun sword) && + sword.UsesBodyBinding && !sword.BodyFinished) + { + sword.BodyExecuted = false; + actor.Run.BodyElapsed = 0; + } + } + + private bool TryAdvanceOrdinaryAbilityBody(Actor actor, ActionRun run) + { + if (TryAdvanceMagicSwordBody(actor, run)) + return true; + if (!_abilityPresentations.TryGetValue(run.Id, out AbilityPresentationRun stage) || !stage.UsesBodyBinding || !run.StageStarted) + return false; + if (stage.BodyFinished) + { + EnsureProperBodyAnimation(actor); + return true; + } + if (!stage.BodyExecuted) + { + stage.BodyExecuted = true; + run.BodyRestartPending = false; + if (stage.Profile.NpcItemIdle) + { + SetBodyBladeSeconds(actor, .01f); + if (GetBodyBinding(actor).LogicalPose != BattlePose.Idle) + TryPlayBodyAnimation(actor, stage.BodyRequested, true, BattlePose.Idle, 32); + stage.BodyFinished = true; + run.BodyElapsed = run.Timing.BodyAnimationTicks; + return true; + } + if (stage.Profile.RetainsBody || stage.Profile.BodyAnimationTicks > 0) + { + SetBodyBladeSeconds(actor, 0.25f); + if (stage.Profile.Kind != BattleAbilityStageKind.Magic) + ResetActorFacing(actor); + TryPlayBodyAnimation(actor, stage.BodyRequested, false, run.Kind == BattleAction.Item ? BattlePose.UsingItem : BattlePose.UsingSkill, stage.BodyNativeAction); + if (stage.BodyNativeAction == 39) + PlaySound("we033"); + } + else + stage.BodyFinished = true; + return true; + } + if (!actor.Alive || GetBodyBinding(actor).LastPoppedMarker == BattlePhysicalMarkerKind.Over) + { + stage.BodyFinished = true; + SetBodyBladeSeconds(actor, 0.01f); + run.BodyElapsed = run.Timing.BodyAnimationTicks; + } + return true; + } + + private void QueueAbilityMovement(Actor actor, ActionRun run, bool returning) + { + var catalog = (IBattleAbilityEffects)_catalog; + Actor target = run.Target != null && _byId.TryGetValue(run.Target, out Actor chosen) ? chosen : null; + IReadOnlyList plans = catalog.AbilityMovement(Snapshot(actor), target == null ? null : Snapshot(target), run.Ability, Definitions, returning); + if (plans == null || plans.Count == 0 || plans.Any(plan => plan == null)) + throw new InvalidOperationException("An original ability movement requires a complete captured plan."); + QueueFormationMoves(actor, plans); + if (_catalog is IBattleAbilityBodyAnimations bodies) + _pendingAbilityMovementBodies[actor.Initial.InstanceId] = (bodies.AbilityMovementBody(actor.Initial.InstanceId, run.Ability, plans[0].Kind, returning), + plans[0].Kind != BattleMovementKind.Fly, plans[0].Kind == BattleMovementKind.Teleport ? BattlePose.Idle : BattlePose.Moving); + } + + private bool TryStartAbilityMovementBody(Actor actor) + { + if (!_pendingAbilityMovementBodies.Remove(actor.Initial.InstanceId, out var pending)) + return false; + TryPlayBodyAnimation(actor, pending.Animation, pending.Loop, pending.Pose, pending.Pose == BattlePose.Idle ? 32 : 31); + return true; + } + + private long StartAbilityEffect(Actor source, ActionRun run, BattleAbilityStageProfile profile, BattleAbilityEffectBinding binding) + { + if (binding.GroupId < 0) + return 0; + var geometry = _catalog as IBattleStageGeometry; + if (geometry == null && binding.PlacementFlags != 0) + throw new InvalidOperationException("An actor-relative effect requires original formation geometry."); + bool singleTarget = run.Ability.Range is not (BattleTargetRange.OwnAll or BattleTargetRange.OpponentAll); + Actor target = run.Target != null && _byId.TryGetValue(run.Target, out Actor chosen) ? chosen : null; + Actor centerActor = singleTarget ? target : _actors.FirstOrDefault(actor => + (actor.Initial.Side != source.Initial.Side) == profile.TargetCenterIsOpposing); + BattleMovementPoint Center(Actor reference) => reference?.Initial.Side == BattleSide.Enemy && + _actors.FirstOrDefault(actor => actor.Initial.Side == BattleSide.Enemy && actor.Slot == BattleSlot.Center) is { } center + ? center.Home : reference == null ? default : geometry?.FormationHome(reference.Initial.InstanceId, BattleSlot.Center) ?? default; + BattleMovementPoint sourceCenter = Center(source); + BattleMovementPoint targetCenter = centerActor == null ? sourceCenter : Center(centerActor); + BattleMovementPoint origin = binding.Resolve(sourceCenter, targetCenter, source.Home, target?.Home ?? targetCenter, singleTarget && target != null); + return StartEffect(new BattleEffectRequest(binding.GroupId, source.Initial.InstanceId, run.Targets, origin, unchecked((uint)_scenario.Seed))); + } + + private void CancelAbilityPresentation(ActionRun run) + { + if (run == null || !_abilityPresentations.Remove(run.Id, out AbilityPresentationRun stage)) + return; + HideStageMessage(stage); + _pendingAbilityMovementBodies.Remove(stage.Owner.Initial.InstanceId); + if (stage.OwnsMovement && run.StageHandle is { } handle && OwnsStageBody(stage.Owner, handle)) + { + stage.Owner.Movement?.Stop(); + stage.Owner.Movement = null; + stage.Owner.MovementQueue.Clear(); + } + if (stage.FirstHandle != 0) + StopEffect(stage.FirstHandle); + if (stage.SecondHandle != 0) + StopEffect(stage.SecondHandle); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.AbilityPresentation.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.AbilityPresentation.cs.meta new file mode 100644 index 00000000..eafe4a62 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.AbilityPresentation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e29df421aefc43c79477c44c8e37db61 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Ai.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Ai.cs new file mode 100644 index 00000000..ce824bbb --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Ai.cs @@ -0,0 +1,748 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + using K = BattleAiAttemptKind; + + public sealed partial class BattleSession + { + private BattleAi _ai; + private SessionAiPort _aiPort; + private readonly Dictionary _aiLastCommands = new(); + private readonly Dictionary<(string Actor, int Ability), BattleSkill> _aiSkillAliases = new(); + private BattleCommand? _aiSubmitting; + private BattleAiCommand _aiRepeating; + private bool _aiPrevalidated; + private int _fiveSpiritElement, _fiveSpiritForce, _fiveSpiritRoundActor, _fiveSpiritRounds; + + public int FiveSpiritElement => _fiveSpiritElement; + + public int FiveSpiritForce => _fiveSpiritForce; + + private void InitializeAi() + { + if (Definitions == null || _ai != null) + return; + _aiPort = new SessionAiPort(this); + _ai = new BattleAi(Definitions.Variant == "PAL3A", _random, _aiPort); + for (int index = 5; index < 11; index++) + { + _ai.Roles[index].Profile.SetEnabled(true); + _ai.Roles[index].Profile.Negative = true; + } + _automatic[(int)BattleSide.Enemy] = true; + _fiveSpiritElement = _scenario.FiveSpiritElement; + _fiveSpiritForce = _scenario.FiveSpiritForce; + ResetAiSceneAnchor(true); + RefreshAiSnapshot(); + } + + private void SetOriginalAutomatic(BattleSide side, bool enabled) + { + if (Definitions == null) + return; + InitializeAi(); + if (side == BattleSide.Ally) + _ai.SetAutomatic(enabled); + else + { + for (int index = 5; index < 11; index++) + _ai.Roles[index].Profile.SetEnabled(enabled); + } + _automatic[(int)side] = enabled; + } + + private bool IsAiEnabled(Actor actor) + { + if (Definitions == null) + return _automatic[(int)actor.Initial.Side]; + InitializeAi(); + return _ai.Roles[NativeActorIndex(actor)].Profile.Enabled; + } + + public int GetAiProfile(string actorId) + { + InitializeAi(); + if (_ai == null || actorId == null || !_byId.TryGetValue(actorId, out Actor actor)) + throw new ArgumentException("A captured battle actor is required.", nameof(actorId)); + BattleAiProfile profile = _ai.Roles[NativeActorIndex(actor)].Profile; + return (profile.Attack ? 1 : 0) | (profile.Magic ? 2 : 0) | (profile.Skill ? 4 : 0) | (profile.Item ? 8 : 0) | + (profile.Negative ? 16 : 0) | (profile.Enabled ? 32 : 0); + } + + public void SetAiProfile(string actorId, int flags) + { + if (flags < 0 || flags > 63) + throw new ArgumentOutOfRangeException(nameof(flags)); + int current = GetAiProfile(actorId); + if (Status != BattleSessionStatus.Running || current == flags) + return; + ApplyAiProfile(_byId[actorId], flags); + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.AiProfile, Actor = actorId, AiFlags = flags }); + Add(BattleEventKind.ControlChanged, actorId, detail: "original AI flags " + flags); + } + + private void ApplyAiProfile(Actor actor, int flags) + { + BattleAiProfile profile = _ai.Roles[NativeActorIndex(actor)].Profile; + profile.Attack = (flags & 1) != 0; + profile.Magic = (flags & 2) != 0; + profile.Skill = (flags & 4) != 0; + profile.Item = (flags & 8) != 0; + profile.Negative = (flags & 16) != 0; + profile.Enabled = (flags & 32) != 0; + } + + public void SetAiAutoOnly(bool enabled) + { + InitializeAi(); + if (_ai == null || Status != BattleSessionStatus.Running || _ai.Automatic == enabled) + return; + _ai.SetAutomatic(enabled, true); + _automatic[(int)BattleSide.Ally] = enabled; + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.AiAutoOnly, Automatic = enabled }); + Add(BattleEventKind.ControlChanged, detail: "original system auto only " + enabled); + } + + public bool RequestAiNormal(string actorId) + { + if (!CanRequestAiInput(actorId, out Actor actor)) + return false; + int index = NativeActorIndex(actor); + if (index == 2 && _pal3AForms.TryGetValue(actorId, out Pal3AFormState form) && + (form.Pending || form.Kind == BattlePal3AFormKind.PengxuFairyBeast)) + return false; + RefreshAiSnapshot(); + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.AiNormal, Actor = actorId }); + return _ai.PlayerNormal(index, true); + } + + public bool RequestAiRepeat(string actorId) + { + if (!CanRequestAiInput(actorId, out Actor actor)) + return false; + // PAL3A checks Pengxu and then Nangong before repeating for the active controller. + if (Definitions.Variant == "PAL3A" && (!CanRepeatWithTransformedRole(2, actorId) || !CanRepeatWithTransformedRole(0, actorId))) + return false; + int index = NativeActorIndex(actor); + _aiLastCommands.TryGetValue(index, out BattleAiCommand command); + RefreshAiSnapshot(); + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.AiRepeat, Actor = actorId }); + return _ai.Repeat(index, command ?? new BattleAiCommand { Source = index, Target = -1 }); + } + + private bool CanRepeatWithTransformedRole(int index, string controller) + { + if (!IsPal3ATransformed(ActorAtNativeIndex(index)?.Initial.InstanceId)) + return true; + bool fairyBeast = index == 2; + if (!_aiLastCommands.TryGetValue(index, out BattleAiCommand command)) + return !fairyBeast; + bool forbidden = fairyBeast ? command.Kind is 0x103 or 0x104 or 0x106 : command.Kind is 0x104 or 0x105 or 0x106; + if (!forbidden) + return true; + _aiLastCommands.Remove(index); + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.AiRepeat, Actor = controller }); + return false; + } + + public bool InspectMagicMenuAbility(string actorId, int abilityId) + { + if (Definitions?.Variant != "PAL3A" || _fiveSpiritElement == 0 || + !CanRequestAiInput(actorId, out Actor actor) || !_aiLastCommands.ContainsKey(NativeActorIndex(actor)) || + !Definitions.Skills.TryGetValue(abilityId, out BattleAbilityDefinition ability)) + return false; + var spell = new BattleCommand(actorId, BattleAction.Skill, abilityId: abilityId); + ValidateAbility(actor, spell, ability, out bool forbiddenByField); + if (!forbiddenByField || !_aiLastCommands.Remove(NativeActorIndex(actor))) + return false; + // The original spell list invokes the same ability check as the AI. + // Record the state change without making menu rendering mutate battle state. + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.MagicMenuFieldDenial, Actor = actorId, AbilityId = abilityId }); + return true; + } + + private bool CanRequestAiInput(string actorId, out Actor actor) + { + InitializeAi(); + actor = null; + return _ai != null && actorId != null && WaitingActor == actorId && _byId.TryGetValue(actorId, out actor) && + Status == BattleSessionStatus.Running && !_resolvingOutcome && ActiveFormationController == null && + actor.Initial.Side == BattleSide.Ally && actor.Alive && !actor.Escaped && actor.Ready && actor.Run == null && + ActionBodyIdle(actor) && !IsUncontrollable(actor); + } + + private void PrepareAiActions() + { + foreach (Actor actor in _actors) + { + ActionRun run = actor.Run; + if (run?.Ability?.IsMagic != true || run.ElementWheel || run.CreatedTick >= SimulationTick || !Has(actor, BattleState.Seal) || + run.SystemStarted && !run.Casting || IsCoAttackRun(run)) + continue; + // Native MagicWait substitutes a combination before testing the seal state. + if (!run.SystemStarted && TryReplaceWithCoAttack(actor, run)) + continue; + Cancel(actor, "封 interrupted original magic wait"); + actor.Gauge = actor.CastGauge = 0; + actor.Ready = false; + } + } + + private void RunAi() + { + InitializeAi(); + if (_ai == null || _resolvingOutcome || ActiveFormationController != null) + return; + RefreshAiSnapshot(); + _ai.UpdateDemands(); + for (int index = 0; index < 11; index++) + { + Actor actor = ActorAtNativeIndex(index); + if (actor == null || !actor.Alive || actor.Escaped || !actor.Ready || actor.Run != null || + !ActionBodyIdle(actor)) + continue; + if (Has(actor, BattleState.Paralysis) || Has(actor, BattleState.Sleep)) + { + AdvanceFiveSpiritFieldTurn(actor); + actor.Gauge = 0; + actor.Ready = false; + continue; + } + if (!_ai.Roles[index].Profile.Enabled && !Has(actor, BattleState.Chaos) && !Has(actor, BattleState.Madness)) + { + if (index < 5) + return; // ProcControl activates the first manual player before scanning later roles. + continue; + } + if (index >= 5) + _ai.HandleEnemy(index); + else + _ai.HandleFriend(index); + } + } + + private void RefreshAiSnapshot() + { + for (int index = 0; index < 11; index++) + { + Actor actor = ActorAtNativeIndex(index); + BattleAiProfile profile = _ai.Roles[index].Profile; + if (actor == null) + { + _ai.Roles[index] = new BattleAiRole { Profile = profile }; + continue; + } + int[] bad = actor.States.Keys.Where(AiBadState).Select(state => (int)state + 1).OrderBy(state => state).ToArray(); + _ai.Roles[index] = new BattleAiRole + { + Valid = true, + Alive = actor.Alive, + Fled = actor.Escaped, + Fleeing = IsFleeing(actor), + Boss = actor.Initial.Side == BattleSide.Enemy && actor.Definition.Boss, + EnemyFriend = actor.Initial.InstanceId == _scenario.EnemyAiIgnoredActor || Definitions.Variant == "PAL3" && index == 3 && + _actors.Any(enemy => enemy.Initial.Side == BattleSide.Enemy && enemy.Initial.ActorId == 708), + Identity = actor.Initial.ActorId, + Hp = actor.Hp, + MaxHp = actor.Attributes[0], + Mp = actor.Mp, + MaxMp = actor.Attributes[2], + Chaos = Has(actor, BattleState.Chaos), + Madness = Has(actor, BattleState.Madness), + Seal = Has(actor, BattleState.Seal), + BadState = bad.Length > 0, + // The released getter checks role zero's alive flag before scanning any target. + WorstBadState = ActorAtNativeIndex(0)?.Alive == true ? bad.FirstOrDefault() : 0, + Profile = profile, + Skills = CaptureAiSkills(actor) + }; + } + _ai.Items = _inventoryOrder.Where(Definitions.Items.ContainsKey).Select(id => + CaptureAiSkill(Definitions.Items[id], null, _inventory[id])).ToArray(); + } + + private static bool AiBadState(BattleState state) => state <= BattleState.PoisonResist && state is not + (BattleState.AttackIncrease or BattleState.DefenseIncrease or BattleState.LuckIncrease or BattleState.SpeedIncrease or + BattleState.Reflection or BattleState.Evade or BattleState.Barrier or BattleState.Invisible or BattleState.PoisonResist); + + private BattleAiSkill[] CaptureAiSkills(Actor actor) + { + if (actor.Initial.Side == BattleSide.Enemy) + return actor.Skills.Take(4).Select(skill => Definitions.Skills.TryGetValue(skill.Id, out BattleAbilityDefinition ability) + ? CaptureAiSkill(ability, skill) : new BattleAiSkill { Id = skill.Id, Level = skill.Level }).ToArray(); + var learned = actor.Skills.ToDictionary(skill => skill.Id); + BattleAbilityDefinition[] magic = Definitions.SkillsInOriginalOrder.Where(ability => ability.IsMagic && learned.ContainsKey(ability.Id) && AiMagicGroup(ability.ElementMask) >= 0) + .OrderBy(ability => AiMagicGroup(ability.ElementMask)).ThenBy(ability => ability.Id).ToArray(); + var magicIds = new HashSet(magic.Select(ability => ability.Id)); + BattleAbilityDefinition[] nativeMagic = BattleMagicSlots.Capture(Definitions.Variant, Definitions, actor.Definition.Identity, actor.Skills) + .Where(slot => magicIds.Contains(slot.SkillId)).Select(slot => slot.Definition).ToArray(); + var nativeIds = new HashSet(nativeMagic.Select(ability => ability.Id)); + int nativeIndex = 0; + // Native selectors scan captured group/slot order. Keep combat-only + // and synthetic abilities in their existing positions outside that catalogue. + for (int index = 0; index < magic.Length; index++) + if (nativeIds.Contains(magic[index].Id)) + magic[index] = nativeMagic[nativeIndex++]; + IEnumerable techniques = Definitions.SkillsInOriginalOrder.Where(ability => !ability.IsMagic && !ability.IsItem && + (ability.SkillTypeId == 0 || ability.SkillTypeId < 0) && learned.ContainsKey(ability.Id)); + return magic.Concat(techniques).Select(ability => CaptureAiSkill(ability, learned[ability.Id])).ToArray(); + } + + private static int AiMagicGroup(int mask) + { + if (mask == 0) + return -1; + if ((mask & (mask - 1)) != 0) + return 5; + return mask switch + { + 1 => 0, + 2 => 1, + 8 => 2, + 4 => 3, + 16 => 4, + _ => -1 + }; + } + + private static BattleAiSkill CaptureAiSkill(BattleAbilityDefinition ability, BattleSkill learned, int count = 1) + { + BattleAttributeEffect hp = ability.Attributes.FirstOrDefault(effect => effect.Attribute == 0); + var states = new int[32]; + foreach (BattleStatusEffect effect in ability.States) + states[(int)effect.State] = effect.Remove ? 2 : 1; + return new BattleAiSkill + { + Id = ability.Id, + Type = ability.IsItem ? ability.ItemType : ability.SkillTypeId >= 0 ? ability.SkillTypeId : ability.IsMagic ? hp.Value < 0 ? 2 : hp.Value > 0 ? 3 : 1 : 0, + Range = (int)ability.Range, + Power = hp.Value, + PowerMode = (int)hp.Mode, + ElementMask = ability.ElementMask, + Level = learned?.Level ?? 1, + Count = count, + Mastered = learned?.Mastered ?? true, + IsMagic = ability.IsMagic, + IsItem = ability.IsItem, + NullCureOperation = ability.IsItem ? ability.AiNullCureOperation : ability.SuccessRate, + StateOperations = states + }; + } + + private int AiAverage(BattleSide side, bool maximum = false, bool missing = false) + { + Actor[] members = _actors.Where(actor => actor.Initial.Side == side && actor.Alive).ToArray(); + if (members.Length == 0) + return missing ? 99999 : 0; + return members.Sum(actor => missing ? actor.Attributes[0] - actor.Hp : maximum ? actor.Attributes[0] : actor.Hp) / members.Length; + } + + private bool AiPrevalidatedAbility(Actor actor, BattleAbilityDefinition ability) => _aiPrevalidated && + _aiSubmitting is BattleCommand command && command.Actor == actor.Initial.InstanceId && command.AbilityId == ability.Id; + + private BattleSkill AiSkill(Actor actor, int abilityId) => actor.Skills.FirstOrDefault(skill => skill.Id == abilityId) ?? + (_aiSkillAliases.TryGetValue((actor.Initial.InstanceId, abilityId), out BattleSkill alias) ? alias : null); + + private bool TryAiTargetCandidates(BattleCommand command, out IReadOnlyList candidates) + { + candidates = null; + if (_aiSubmitting is not BattleCommand active || active.Actor != command.Actor || active.Action != command.Action || + active.AbilityId != command.AbilityId || active.Target != command.Target) + return false; + BattleAbilityDefinition ability = Ability(command); + Actor source = _byId[command.Actor]; + BattleTargetRange range = ActionRange(source, ability); + if (range == BattleTargetRange.None && Definitions.Variant == "PAL3A" && command.AbilityId is >= 264 and <= 268) + { + candidates = Array.AsReadOnly(new[] { Snapshot(_byId[command.Actor]) }); + return true; + } + if (range == BattleTargetRange.None) + return false; + if (ability != null && range is BattleTargetRange.OwnAll or BattleTargetRange.OpponentAll) + { + candidates = Array.AsReadOnly(FightSkillRange(source, range).Select(Snapshot).ToArray()); + return true; + } + if (command.Target == null || !_byId.TryGetValue(command.Target, out Actor anchor)) + return false; + // AI has already chosen its primary role, including same-side targets under chaos. + // GetNormalAttackRange expands around that role without the manual selection filters. + candidates = range is BattleTargetRange.OwnSingle or BattleTargetRange.OpponentSingle + ? Array.AsReadOnly(new[] { Snapshot(anchor) }) + : Array.AsReadOnly(_actors.OrderBy(NativeActorIndex).Where(actor => actor.Initial.Side == anchor.Initial.Side && + actor.Alive && !actor.Escaped && !IsFleeing(actor)).Select(Snapshot).ToArray()); + return true; + } + + private bool TryAiCapturedTargets(BattleCommand command, out string[] targets) + { + targets = null; + if (_aiRepeating == null || _aiSubmitting is not BattleCommand active || active.Actor != command.Actor || + active.Action != command.Action || active.AbilityId != command.AbilityId || active.Target != command.Target) + return false; + if (_aiRepeating.MultipleTargets) + targets = Enumerable.Range(0, 11).Where(index => _aiRepeating.TargetMask[index]).Select(ActorAtNativeIndex) + .Where(actor => actor != null).Select(actor => actor.Initial.InstanceId).ToArray(); + else + targets = command.Target == null ? Array.Empty() : new[] { command.Target }; + return true; + } + + private long SubmitAiCommand(BattleCommand command, bool prevalidated) + { + BattleCommand? previous = _aiSubmitting; + bool oldPrevalidated = _aiPrevalidated; + _aiSubmitting = command; + _aiPrevalidated = prevalidated; + if (prevalidated && command.Action == BattleAction.Skill && !_byId[command.Actor].Skills.Any(skill => skill.Id == command.AbilityId)) + _aiSkillAliases[(command.Actor, command.AbilityId)] = new BattleSkill + { + Id = command.AbilityId, + Mastered = true, + Level = command.AbilityId is 207 or 215 or 224 or 232 or 240 ? 1 : 4 + }; + try + { + if (!SubmitCommand(command, true)) + return -1; + AdvanceFiveSpiritFieldTurn(_byId[command.Actor]); + return _byId[command.Actor].Run.Id; + } + finally + { + _aiSubmitting = previous; + _aiPrevalidated = oldPrevalidated; + } + } + + private void RememberAiCommand(BattleCommand command) + { + if (Definitions == null || !_byId.TryGetValue(command.Actor, out Actor actor) || actor.Initial.Side != BattleSide.Ally) + return; + InitializeAi(); + int index = NativeActorIndex(actor); + _ai.NewRole[index] = false; + // ProcControl dispatches the sword thread without replacing LastRoleCmd. + if (IsMagicSwordAbility(Ability(command))) + return; + int kind = command.Action switch + { + BattleAction.Attack => 0x103, + BattleAction.Skill => Ability(command)?.IsMagic == true ? 0x105 : 0x104, + BattleAction.Item => 0x106, + BattleAction.Defend => 0x109, + BattleAction.Flee => 0x10b, + _ => 0 + }; + var stored = new BattleAiCommand + { + Source = index, + Kind = kind, + AbilityId = command.AbilityId, + Target = command.Target != null && _byId.TryGetValue(command.Target, out Actor target) ? NativeActorIndex(target) : -1 + }; + if (command.Action is BattleAction.Attack or BattleAction.Skill or BattleAction.Item) + { + BattleTargetRange range = ActionRange(actor, Ability(command)); + stored.MultipleTargets = range is not (BattleTargetRange.OwnSingle or BattleTargetRange.OpponentSingle); + foreach (string targetId in actor.Run.Targets) + stored.TargetMask[NativeActorIndex(_byId[targetId])] = true; + if (stored.MultipleTargets) + stored.Target = -1; + } + _aiLastCommands[index] = stored; + } + + private void ResolveAiSceneMagic(Actor source, BattleAbilityDefinition ability) + { + if (Definitions.Variant != "PAL3A" || ability.Id < 264 || ability.Id > 268) + return; + int group = AiMagicGroup(ability.ElementMask); + if (group < 0 || group >= 5) + throw new NotSupportedException("A five-spirit field spell needs one original element."); + _fiveSpiritElement = ability.ElementMask switch + { + 1 => 1, + 2 => 2, + 4 => 3, + 8 => 4, + 16 => 5, + _ => 0 + }; + _fiveSpiritForce = source.Initial.Side == BattleSide.Ally ? 1 : 2; + ResetAiSceneAnchor(true); + Add(BattleEventKind.ControlChanged, source.Initial.InstanceId, source.Run?.Target, source.Run?.Id ?? 0, + "five-spirit field " + _fiveSpiritElement + ":" + _fiveSpiritForce); + } + + private void ResetAiSceneAnchor(bool resetRounds) + { + _fiveSpiritRoundActor = Enumerable.Range(0, 5).FirstOrDefault(index => ActorAtNativeIndex(index)?.Alive == true); + if (resetRounds) + _fiveSpiritRounds = 0; + } + + private void AdvanceFiveSpiritFieldTurn(Actor actor) + { + if (Definitions?.Variant != "PAL3A" || _fiveSpiritElement == 0 || actor.Initial.Side != BattleSide.Ally) + return; + if (ActorAtNativeIndex(_fiveSpiritRoundActor)?.Alive != true) + ResetAiSceneAnchor(false); + if (NativeActorIndex(actor) != _fiveSpiritRoundActor || ++_fiveSpiritRounds < 5) + return; + _fiveSpiritElement = _fiveSpiritForce = 0; + Add(BattleEventKind.ControlChanged, actor.Initial.InstanceId, detail: "five-spirit field expired"); + } + + private sealed class SessionAiPort : BattleAiPort + { + private readonly BattleSession _session; + + public SessionAiPort(BattleSession session) => _session = session; + + public override int SceneFiveSpiritMode => _session._fiveSpiritElement; + + public override int SceneFiveSpiritOwner => _session._fiveSpiritForce; + + public override bool CanAttackBack(int source, int target) => _session.CanAttackBack(_session.ActorAtNativeIndex(source), _session.ActorAtNativeIndex(target)); + + public override bool IsActionActive(long actionId) => _session._actors.Any(actor => actor.Run?.Id == actionId); + + public override bool CanCast(int source, int skillId) + { + Actor actor = _session.ActorAtNativeIndex(source); + if (actor == null) + return false; + bool item = _session.Definitions.Items.TryGetValue(skillId, out BattleAbilityDefinition ability); + if (!item && !_session.Definitions.Skills.TryGetValue(skillId, out ability)) + return false; + var command = new BattleCommand(actor.Initial.InstanceId, item ? BattleAction.Item : BattleAction.Skill, abilityId: skillId); + string denial = _session.ValidateAbility(actor, command, ability, out bool forbiddenByField); + if (forbiddenByField) + _session._aiLastCommands.Remove(source); + return denial == null; + } + + public override long TryAttempt(BattleAiAttempt attempt) + { + BattleAi ai = _session._ai; + Actor source = _session.ActorAtNativeIndex(attempt.Source); + Actor target = attempt.Target >= 0 ? _session.ActorAtNativeIndex(attempt.Target) : null; + if (source == null || !ai.CapabilityEnabled(attempt.Source, attempt.Kind)) + return -1; + K kind = attempt.Kind; + if (kind == K.SpecAI) + { + if (attempt.AbilityId != 7709 || !BattleAi.IsSpecialBossReady(ai.Roles[attempt.Source]) || _session._effects == null) + return -1; + long special = Submit(source, null, 7709, false, true); + if (special >= 0) + _session.StartEffect(new BattleEffectRequest(559, source.Initial.InstanceId, source.Run.Targets, source.Position, unchecked((uint)_session._scenario.Seed))); + return special; + } + if (!source.Alive) + return -1; + if (kind == K.Normal) + { + if (target == null || !ai.CanNormalAttack(attempt.Source, attempt.Target, Has(target, BattleState.Invisible), Has(target, BattleState.Evade), Has(target, BattleState.Reflection), _session.IsAtHome(target))) + return -1; + return _session.SubmitAiCommand(new BattleCommand(source.Initial.InstanceId, BattleAction.Attack, target.Initial.InstanceId), false); + } + if (kind == K.BossPhysical) + return -1; + bool group = kind is K.RecoverBigMagic or K.AttackBigMagic or K.RecoverBigSkill or K.AttackBigSkill or K.RecoverBigItem or K.AttackBigItem or K.FiveSpiritBigMagic; + bool item = kind is K.RecoverItem or K.RecoverBigItem or K.AttackItem or K.AttackBigItem or K.ReviveItem or K.CureItem; + bool revive = kind is K.ReviveMagic or K.ReviveSkill or K.ReviveItem; + bool selected = kind is K.SelectedMiscMagic or K.FiveSpiritMagic or K.FiveSpiritBigMagic; + if (!group && !selected && (target == null || (revive ? target.Alive : !target.Alive))) + return -1; + bool pal3A = _session.Definitions.Variant == "PAL3A"; + if (pal3A && kind is K.RecoverMagic or K.AttackMagic or K.CureMagic && (target.Escaped || _session.IsFleeing(target))) + return -1; + BattleSide opposite = source.Initial.Side == BattleSide.Ally ? BattleSide.Enemy : BattleSide.Ally; + int weight = 0; + int abilityId; + if (kind == K.SelectedMiscMagic) + { + if (_session.AiAverage(opposite) == 0) + return -1; + abilityId = attempt.AbilityId; + } + else if (kind is K.FiveSpiritMagic or K.FiveSpiritBigMagic) + { + weight = group ? _session.AiAverage(opposite) : 0; + if (group && weight == 0) + return -1; + abilityId = ai.SelectFiveSpiritMagic(attempt.Source, group, weight); + } + else if (kind == K.RandomMiscMagic) + { + if (target.Hp <= 0) + return -1; + abilityId = ai.SelectMiscMagic(attempt.Source, false); + } + else + { + if (kind is K.RecoverMagic or K.RecoverSkill or K.RecoverItem) + weight = target.Attributes[0] - target.Hp; + else if (kind is K.RecoverBigMagic or K.RecoverBigSkill or K.RecoverBigItem) + weight = _session.AiAverage(source.Initial.Side, missing: true); + else if (revive) + weight = source.Attributes[0]; + else if (kind is K.AttackMagic or K.AttackSkill or K.AttackItem) + { + if (target.Hp <= 0) + return -1; + weight = kind == K.AttackMagic ? target.Hp : _session._random.Next() % target.Hp; + } + else if (kind == K.AttackBigSkill) + { + int maximum = _session.AiAverage(opposite, maximum: true); + if (maximum <= 0) + return -1; + weight = _session._random.Next() % maximum; + } + else if (kind is K.AttackBigMagic or K.AttackBigItem) + { + weight = _session.AiAverage(opposite); + if (kind == K.AttackBigMagic && weight == 0) + return -1; + } + abilityId = kind is K.RecoverMagic or K.RecoverBigMagic or K.AttackMagic or K.AttackBigMagic + ? ai.SelectMagic(attempt.Source, kind is K.AttackMagic or K.AttackBigMagic, group, weight) + : ai.SelectSupport(attempt.Source, NormalizeSupportKind(kind), group, weight, attempt.Demand?.State ?? 0); + } + if (abilityId == 0) + return -1; + if (kind == K.AttackMagic) + abilityId = ai.ConvertSingleAttackMagic(abilityId); + if (pal3A && kind is K.AttackSkill or K.AttackBigSkill) + _session.ResumeOriginalAtb(); + return Submit(source, target, abilityId, item, true); + } + + private static K NormalizeSupportKind(K kind) => kind switch + { + K.RecoverBigSkill => K.RecoverSkill, + K.AttackBigSkill => K.AttackSkill, + K.RecoverBigItem => K.RecoverItem, + K.AttackBigItem => K.AttackItem, + _ => kind + }; + + private long Submit(Actor source, Actor target, int abilityId, bool item, bool prevalidated) + => _session.SubmitAiCommand(new BattleCommand(source.Initial.InstanceId, item ? BattleAction.Item : BattleAction.Skill, target?.Initial.InstanceId, abilityId), prevalidated); + + public override void RecordPlayerNormal(int source, int target) + => _session._aiLastCommands[source] = new BattleAiCommand { Kind = 0x103, Source = source, Target = target }; + + public override bool CanRepeat(int source, BattleAiCommand command) + { + if (command.Kind == 0x10f || !TryCommand(command, out BattleCommand translated)) + return false; + string denial = _session.ValidateAbility(_session.ActorAtNativeIndex(source), translated, _session.Ability(translated), + out bool forbiddenByField); + if (forbiddenByField) + _session._aiLastCommands.Remove(source); + return denial == null; + } + + public override bool AllRepeatTargetsDead(BattleAiCommand command) => _session._ai.RepeatTargetsDead(command); + + public override bool IsRepeatAttack(BattleAiCommand command) + { + bool item = command.Kind == 0x106; + var definitions = item ? _session.Definitions.Items : _session.Definitions.Skills; + if (!definitions.TryGetValue(command.AbilityId, out BattleAbilityDefinition ability)) + return false; + if (_session.Definitions.Variant == "PAL3A") + return item ? ability.ItemType == 2 : ability.Range > BattleTargetRange.OwnAll; + BattleAttributeEffect hp = ability.Attributes.FirstOrDefault(effect => effect.Attribute == 0); + return item ? ability.ItemType == 2 && hp.Mode is BattleValueMode.Absolute or BattleValueMode.Percentage && hp.Value < 0 + : command.Kind == 0x105 ? ability.SkillTypeId == 2 : hp.Value < 0; + } + + public override int PickRepeatTarget(int source, bool enemy, bool filterBackRole) + => _session._ai.SelectRepeatTarget(source, enemy, filterBackRole); + + public override void ExpandRepeatRange(BattleAiCommand command) + { + if (!TryCommand(command, out BattleCommand translated) || !_session._byId.TryGetValue(translated.Actor, out Actor source)) + return; + BattleAbilityDefinition ability = _session.Ability(translated); + BattleTargetRange range = _session.ActionRange(source, ability); + command.MultipleTargets = range is not (BattleTargetRange.OwnSingle or BattleTargetRange.OpponentSingle); + if (!command.MultipleTargets) + return; + Actor anchor = _session.ActorAtNativeIndex(command.Target); + IEnumerable targets = command.Kind is 0x104 or 0x105 or 0x106 + ? _session.FightSkillRange(source, range) + : _session._actors.Where(actor => actor.Initial.Side == anchor?.Initial.Side && + actor.Alive && !actor.Escaped && !_session.IsFleeing(actor)); + if (range is BattleTargetRange.OpponentRow or BattleTargetRange.OpponentColumn) + { + if (anchor == null) + return; + targets = targets.Where(actor => BattleTargetRules.Aligned(anchor.Initial.Side, anchor.Slot, actor.Slot, + range == BattleTargetRange.OpponentRow, _session._scenario.SceneElement)); + } + foreach (Actor target in targets) + command.TargetMask[NativeActorIndex(target)] = true; + command.Target = -1; + } + + public override long SubmitRepeat(BattleAiCommand command) + { + if (!TryCommand(command, out BattleCommand translated)) + return -1; + BattleAiCommand previous = _session._aiRepeating; + _session._aiRepeating = command; + try + { + return _session.SubmitAiCommand(translated, command.Kind is 0x104 or 0x105 or 0x106); + } + finally + { + _session._aiRepeating = previous; + } + } + + private bool TryCommand(BattleAiCommand command, out BattleCommand translated) + { + translated = default; + Actor source = _session.ActorAtNativeIndex(command.Source); + if (source == null || command.Kind is not (0x103 or 0x104 or 0x105 or 0x106 or 0x109 or 0x10b)) + return false; + BattleAction action = command.Kind switch + { + 0x103 => BattleAction.Attack, + 0x106 => BattleAction.Item, + 0x109 => BattleAction.Defend, + 0x10b => BattleAction.Flee, + _ => BattleAction.Skill + }; + Actor target = _session.ActorAtNativeIndex(command.Target); + int abilityId = action is BattleAction.Skill or BattleAction.Item ? command.AbilityId : 0; + translated = new BattleCommand(source.Initial.InstanceId, action, target?.Initial.InstanceId, abilityId); + if (command.MultipleTargets && target == null && + (action == BattleAction.Attack || _session.GetActionTargetRange(translated) is BattleTargetRange.OpponentRow or BattleTargetRange.OpponentColumn)) + { + // Native group repeats store only a mask. Supply a legal anchor to the + // command API; the physical stage and damage both use the recorded mask. + target = _session._actors.OrderBy(NativeActorIndex).FirstOrDefault(actor => command.TargetMask[NativeActorIndex(actor)] && + actor.Alive && !actor.Escaped && !_session.IsFleeing(actor)); + translated = new BattleCommand(source.Initial.InstanceId, action, target?.Initial.InstanceId, abilityId); + } + return true; + } + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Ai.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Ai.cs.meta new file mode 100644 index 00000000..87c9595b --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Ai.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8e060ec0b58647e3871b736427d4ed31 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Audio.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Audio.cs new file mode 100644 index 00000000..a00d80ee --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Audio.cs @@ -0,0 +1,73 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + public sealed partial class BattleSession + { + private readonly Dictionary _soundingMovements = new(StringComparer.Ordinal); + + private void PlaySound(string sound) + { + if (sound != null) + (_effects as IBattleAudio)?.PlaySound(sound); + } + + private void PlayAttackBodySound(Actor actor, PhysicalBodyState body, BattlePhysicalMarkerKind marker) + { + BattleBodySoundProfile sounds = (_catalog as IBattleBodyAudioCatalog)?.BodySounds(actor.Initial.InstanceId) ?? default; + string sound = BattleBodyAudioRules.Attack(_scenario.Variant, body.Profile.Identity, body.Profile.WeaponType, + marker, sounds.Attack, actor.Definition?.MagicSword != null, IsPal3ATransformed(actor.Initial.InstanceId)); + PlaySound(sound); + } + + private void PlayHurtBodySound(Actor actor, PhysicalBodyState body) + { + BattleBodySoundProfile sounds = (_catalog as IBattleBodyAudioCatalog)?.BodySounds(actor.Initial.InstanceId) ?? default; + string sound = BattleBodyAudioRules.Hurt(_scenario.Variant, body.Profile.Identity, actor.Guard, sounds.Hurt); + PlaySound(sound); + } + + private void AdvanceBodyMovement(Actor actor, bool alive, BattleMovementMessage? message = null) + { + BattleMovement movement = actor.Movement; + if (!_soundingMovements.TryGetValue(actor.Initial.InstanceId, out BattleMovement previous) || previous != movement) + { + StopMovementBodySound(actor); + _soundingMovements[actor.Initial.InstanceId] = movement; + int identity = actor.Initial.Side == BattleSide.Enemy ? -1 : (_catalog as IBattlePhysicalTimings)?.Physical(actor.Initial.InstanceId).Identity ?? actor.Definition?.Identity ?? -1; + BattleMovementSound sound = BattleBodyAudioRules.Movement(_scenario.Variant, identity, movement.Plan); + if (sound.Sound != null) + (_effects as IBattleMovementAudio)?.PlayMovementSound(actor.Initial.InstanceId, sound.Sound, sound.Loop); + } + movement.Step(alive, message); + if (movement.Finished) + StopMovementBodySound(actor); + } + + private void StopMovementBodySound(Actor actor) + { + if (!_soundingMovements.Remove(actor.Initial.InstanceId)) + return; + try + { + (_effects as IBattleMovementAudio)?.StopMovementSound(actor.Initial.InstanceId); + } + catch (Exception exception) when (_ending) + { + Add(BattleEventKind.PresentationCleanupFailed, actor.Initial.InstanceId, detail: exception.Message); + } + } + + private void SyncBodyMovementSound(Actor actor) + { + if (_soundingMovements.TryGetValue(actor.Initial.InstanceId, out BattleMovement movement) && actor.Movement != movement) + StopMovementBodySound(actor); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Audio.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Audio.cs.meta new file mode 100644 index 00000000..060cd754 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Audio.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 81af12d97866471e9a84744145efafb4 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyAnimation.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyAnimation.cs new file mode 100644 index 00000000..424d8b72 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyAnimation.cs @@ -0,0 +1,120 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + public sealed partial class BattleSession + { + private readonly Dictionary _bodyAnimations = new(StringComparer.Ordinal); + private readonly Dictionary _bodyPassRates = new(StringComparer.Ordinal); + + public BattlePhysicalAnimation CurrentBodyAnimation(string actorId) => _byId.TryGetValue(actorId, out Actor actor) ? GetBodyBinding(actor).CurrentAnimation : null; + + public BattleBodyAnimationBinding CaptureBodyAnimation(string actorId) => _byId.TryGetValue(actorId, out Actor actor) ? GetBodyBinding(actor).Clone() : null; + + private BattleBodyAnimationBinding GetBodyBinding(Actor actor) + { + if (_bodyAnimations.TryGetValue(actor.Initial.InstanceId, out BattleBodyAnimationBinding binding)) + return binding; + BattlePhysicalStageProfile profile = (_catalog as IBattlePhysicalTimings)?.Physical(actor.Initial.InstanceId); + BattlePose pose = !actor.ModelAlive && actor.Initial.Side == BattleSide.Ally ? BattlePose.Dead : BattlePose.Idle; + BattlePhysicalAnimation initial = profile?.Animation(pose); + binding = new BattleBodyAnimationBinding(initial); + binding.SetLogicalPose(pose); + binding.SetRequestedNativeAction(actor.Initial.Side == BattleSide.Enemy ? 50 : pose == BattlePose.Dead ? 47 : 32); + _bodyAnimations.Add(actor.Initial.InstanceId, binding); + return binding; + } + + private void SetBodyAnimationPose(Actor actor, BattlePose pose) => GetBodyBinding(actor).SetLogicalPose(pose); + + private bool TryPlayBodyAnimation(Actor actor, BattlePhysicalAnimation animation, bool loop, BattlePose? requestedPose = null, int? requestedNativeActionIndex = null) + { + BattleBodyAnimationBinding binding = GetBodyBinding(actor); + bool sameRequest = requestedNativeActionIndex.HasValue ? requestedNativeActionIndex.Value == binding.RequestedNativeActionIndex : requestedPose == binding.LogicalPose; + bool unchanged = animation != null && loop && sameRequest && string.Equals(animation.Clip, binding.CurrentAnimation?.Clip, StringComparison.Ordinal); + if (requestedPose.HasValue) + binding.SetLogicalPose(requestedPose.Value); + if (requestedNativeActionIndex.HasValue) + binding.SetRequestedNativeAction(requestedNativeActionIndex.Value); + return unchanged || binding.TryPlay(animation, loop); + } + + private BattleMovementMessage CurrentBodyMovementMessage(Actor actor) => GetBodyBinding(actor).LastPoppedMarker switch + { + BattlePhysicalMarkerKind.FlyUp => BattleMovementMessage.FlyUp, + BattlePhysicalMarkerKind.FlyDown => BattleMovementMessage.FlyDown, + BattlePhysicalMarkerKind.Over => BattleMovementMessage.Over, + _ => BattleMovementMessage.None + }; + + private void EnsureMovementBodyAnimation(Actor actor) + { + if (_catalog is not IBattlePhysicalTimings || actor.Movement == null || actor.Movement.ElapsedTicks != 0) + return; + BattlePose pose = actor.Movement.Plan.Kind == BattleMovementKind.Teleport ? BattlePose.Idle : BattlePose.Moving; + TryPlayBodyAnimation(actor, PhysicalBody(actor).Profile.Animation(pose), true, pose, PhysicalBody(actor).Profile.NativeAction(pose)); + } + + private void SetBodyBladeSeconds(Actor actor, float seconds) + { + PhysicalBodyState body = PhysicalBody(actor); + if (body != null) + body.BladeSeconds = seconds; + } + + public float CurrentBladeSeconds(string actorId) => _byId.TryGetValue(actorId, out Actor actor) ? PhysicalBody(actor)?.BladeSeconds ?? .01f : .01f; + + private void EnsureProperBodyAnimation(Actor actor) + { + if (_catalog is not IBattlePhysicalTimings || PhysicalBodyBusy(actor) || HasFormationMovement(actor) || + IsActorExternallyControlled(actor.Initial.InstanceId) || HasActiveOrdinaryAbilityBody(actor) || HasActivePal3AFormBody(actor)) + return; + PhysicalBodyState body = PhysicalBody(actor); + BattlePose pose = BattlePose.Idle; + if (actor.Initial.Side == BattleSide.Ally) + { + if (actor.Hp == 0) + pose = BattlePose.Dead; + else if (actor.Run?.Casting == true) + pose = BattlePose.Casting; + else if (actor.Guard) + pose = BattlePose.Guard; + else if (Has(actor, BattleState.Sleep) || Has(actor, BattleState.Paralysis)) + pose = BattlePose.Sleeping; + else if (actor.Hp < actor.Attributes[0] / 4) + pose = BattlePose.Dying; + } + body.Pose = pose; + body.BladeSeconds = pose == BattlePose.Guard ? .25f : .01f; + TryPlayBodyAnimation(actor, body.Profile.Animation(pose), true, pose, body.Profile.NativeAction(pose)); + } + + private void SetNativeBodyAction(Actor actor, int action) => GetBodyBinding(actor).SetRequestedNativeAction(action); + + private void ResetBodyAnimation(Actor actor) => GetBodyBinding(actor).Reset(); + + private void BeginBodyAnimationPass(Actor actor) + { + BattleBodyAnimationBinding binding = GetBodyBinding(actor); + float rate = _scenario.Variant == "PAL3" ? 1.3f : 1f; + if (!IsActorExternallyControlled(actor.Initial.InstanceId) && binding.RequestedNativeActionIndex is 32 or 50) + rate = .65f; + _bodyPassRates[actor.Initial.InstanceId] = rate; + binding.PopMessage(); + if (!IsActorExternallyControlled(actor.Initial.InstanceId)) + AdvanceThrownWeapon(actor); + } + + private void EndBodyAnimationPass(Actor actor) + { + SyncBodyMovementSound(actor); + GetBodyBinding(actor).Advance(_bodyPassRates.GetValueOrDefault(actor.Initial.InstanceId, 1f)); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyAnimation.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyAnimation.cs.meta new file mode 100644 index 00000000..a5f89fb8 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyAnimation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a44c3bb507074f7bba03be335a726b5f diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyOwnership.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyOwnership.cs new file mode 100644 index 00000000..02345dfd --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyOwnership.cs @@ -0,0 +1,36 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + public sealed partial class BattleSession + { + // IsIdle describes the role's task queue. Normal Grab separately reserves + // that queue until Release, even after an ability's body has finished. + private readonly Dictionary _bodyStageOwners = new(StringComparer.Ordinal); + + private bool OwnsStageBody(Actor actor, BattleStageHandle handle) => + _bodyStageOwners.TryGetValue(actor.Initial.InstanceId, out long owner) && owner == handle.Id; + + private bool TryGrabStageBody(Actor actor, BattleStageHandle handle) + { + if (_bodyStageOwners.TryGetValue(actor.Initial.InstanceId, out long owner) && owner != handle.Id) + return false; + _bodyStageOwners[actor.Initial.InstanceId] = handle.Id; + return true; + } + + private void ReleaseStageBody(Actor actor, BattleStageHandle handle) + { + if (!OwnsStageBody(actor, handle)) + return; + ClearPhysicalBody(actor); + _bodyStageOwners.Remove(actor.Initial.InstanceId); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyOwnership.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyOwnership.cs.meta new file mode 100644 index 00000000..eb75717f --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.BodyOwnership.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9f9c4b79f2724c978e5b635bbf638797 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.CoAttack.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.CoAttack.cs new file mode 100644 index 00000000..4ddf73c2 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.CoAttack.cs @@ -0,0 +1,448 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private sealed class CoAttackSubtask + { + internal BattleCoAttackStepStatus Status; + internal float Started; + internal bool Executed, SkipRequested; + } + + private sealed class CoAttackStageRun : IBattleStageJob + { + internal readonly BattleSession Session; + internal readonly Actor Source; + internal readonly ActionRun Run; + internal readonly BattleComboDefinition Combo; + internal readonly BattleComboStageProfile Profile; + internal readonly BattleCoAttackTargetSelection Selection; + internal readonly string[] Targets; + internal readonly CoAttackSubtask[] Subtasks; + internal readonly HashSet HiddenActors = new(StringComparer.Ordinal); + internal BattleStageHandle Handle; + internal bool NameVisible, Worked, FirstStarted, SecondStarted, Finished; + internal long FirstHandle, SecondHandle; + + internal CoAttackStageRun(BattleSession session, Actor source, ActionRun run, + BattleComboDefinition combo, BattleComboStageProfile profile, BattleCoAttackTargetSelection selection, + string[] targets, float createdTime) + { + Session = session; + Source = source; + Run = run; + Combo = combo; + Profile = profile; + Selection = selection; + Targets = targets; + Subtasks = Enumerable.Range(0, 13).Select(_ => new CoAttackSubtask()).ToArray(); + Subtasks[0].Status = BattleCoAttackStepStatus.Running; + Subtasks[0].Started = createdTime; + } + + internal IEnumerable SkippableSubtasks => Subtasks.Where((sub, index) => + sub.Status == BattleCoAttackStepStatus.Running && (BattleCoAttackStep)index is + BattleCoAttackStep.FadeOutToCombo or BattleCoAttackStep.FadeInToCombo or + BattleCoAttackStep.FadeOutToHome or BattleCoAttackStep.FadeInToHome); + + internal bool HasComboPositions => + Subtasks[(int)BattleCoAttackStep.SetComboPositions].Status == BattleCoAttackStepStatus.Finished && + Subtasks[(int)BattleCoAttackStep.RestorePositions].Status != BattleCoAttackStepStatus.Finished; + + public bool Advance(BattleStageContext context) => Session.AdvanceCoAttack(this, context); + + internal BattleCoAttackSnapshot Capture() => new(Run.Id, Combo, Source.Initial.InstanceId, + NameVisible, Worked, Finished, Targets, Subtasks.Select((sub, index) => + new BattleCoAttackStepSnapshot((BattleCoAttackStep)index, sub.Status, sub.Started))); + } + + private readonly Dictionary _coAttackStages = new(); + private readonly HashSet _coAttackChecked = new(); + private bool _coAttackAtbPaused; + private CoAttackStageRun _coAttackFadeOwner; + + public bool IsCoAttackAtbPaused => _coAttackAtbPaused; + + public float CoAttackScreenOpacity + { + get; private set; + } + + public uint CoAttackScreenColor + { + get; private set; + } + + public IReadOnlyList CoAttacks => Array.AsReadOnly(_coAttackStages.Values + .OrderBy(stage => stage.Handle.Slot).Select(stage => stage.Capture()).ToArray()); + + public bool CoAttackActorVisible(string actor) => !_coAttackStages.Values.Any(stage => stage.HiddenActors.Contains(actor)); + + public bool IsCoAttackPresentationBlockingInput => Status == BattleSessionStatus.Running && + (CoAttackScreenOpacity > 0 || _coAttackStages.Values.Any(stage => stage.SkippableSubtasks.Any())); + + public bool SkipCoAttackPresentation() + { + if (Status != BattleSessionStatus.Running || IsBattleInputSuspended) + return false; + bool requested = false; + foreach (CoAttackSubtask sub in _coAttackStages.Values.SelectMany(stage => stage.SkippableSubtasks)) + { + if (sub.SkipRequested) + continue; + sub.SkipRequested = requested = true; + } + if (requested) + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.CoAttackPresentationSkip }); + return requested; + } + + private bool IsCoAttackRun(ActionRun run) => run != null && _coAttackStages.ContainsKey(run.Id); + + private int CoAttackId(ActionRun run) => run != null && _coAttackStages.TryGetValue(run.Id, out CoAttackStageRun stage) ? stage.Combo.Id : 0; + + // Call once on an original Attack/Skill system thread's first pass, before + // ordinary casting/stage setup. A matching combo replaces that command. + private bool TryReplaceWithCoAttack(Actor source, ActionRun run) + { + if (IsCoAttackRun(run)) + return true; + if (Definitions == null || run == null || run.ElementWheel || !_coAttackChecked.Add(run.Id) || source.Initial.Side != BattleSide.Ally || + run.Kind is not (BattleAction.Attack or BattleAction.Skill) || + run.Kind == BattleAction.Skill && (run.Ability == null || run.Ability.IsItem || run.Ability.SkillTypeId == 4)) + return false; + int trigger = run.Kind == BattleAction.Attack ? 0 : run.Ability.Id; + BattleComboDefinition combo = Definitions.Combos.FirstOrDefault(candidate => + FormationRules().CanCoAttack(source.Definition.Identity, trigger, candidate.Requirement, FormationActors()).Allowed); + if (combo == null) + return false; + if (_catalog is not IBattleCoAttackTimings timings || _effects == null) + throw new NotSupportedException($"Combo {combo.Id} requires its original effect linker and effect completion director."); + BattleComboStageProfile profile = timings.CoAttack(source.Initial.InstanceId, combo) ?? + throw new InvalidOperationException("The original combo profile is missing."); + BattleCoAttackTargetSelection selection = SelectCoAttackTargets(run, combo); + string[] targets = selection.TargetIndices.Select(ActorAtNativeIndex).Where(actor => actor != null) + .Select(actor => actor.Initial.InstanceId).ToArray(); + float now = BattleStageScheduler.TimeAt(SimulationTick); + var stage = new CoAttackStageRun(this, source, run, combo, profile, selection, targets, now); + // The successful command substitution clears source slot 1 before the + // new CoAttack thread allocates its stage. Helpers retain their bars. + if (run.StageHandle is { } previous) + _stage.Cancel(previous); + run.StageHandle = null; + run.Casting = false; + run.AttackPlan = null; + source.Gauge = source.CastGauge = 0; + source.Ready = source.Guard = false; + _coAttackAtbPaused = true; + if (!_stage.TryAdd(source.Initial.InstanceId, "coattack", stage, now, out BattleStageHandle handle, autoDelete: false)) + { + _coAttackAtbPaused = false; + Cancel(source, "original combo stage allocation failed"); + return true; + } + stage.Handle = handle; + run.StageHandle = handle; + _coAttackStages.Add(run.Id, stage); + return true; + } + + private BattleCoAttackTargetSelection SelectCoAttackTargets(ActionRun run, BattleComboDefinition combo) + { + var mask = new bool[11]; + foreach (string id in run.Targets ?? Array.Empty()) + if (_byId.TryGetValue(id, out Actor actor)) + mask[NativeActorIndex(actor)] = true; + int target = run.Target != null && _byId.TryGetValue(run.Target, out Actor selected) ? NativeActorIndex(selected) : -1; + BattleCoAttackTargetActorSnapshot[] actors = Enumerable.Range(0, 11).Select(index => + { + Actor actor = ActorAtNativeIndex(index); + return actor == null ? new BattleCoAttackTargetActorSnapshot(false, false, false, false, 0) : + new BattleCoAttackTargetActorSnapshot(true, actor.Alive, actor.Escaped, actor.Definition.Boss, actor.Hp); + }).ToArray(); + return new BattleCoAttackTargets(Definitions.Variant).Resolve(new BattleCoAttackTargetInput(target, mask, combo.NativeRange, actors)); + } + + private static int NativeActorIndex(Actor actor) => actor.NativeIndex; + + private Actor ActorAtNativeIndex(int index) => _actors.FirstOrDefault(actor => NativeActorIndex(actor) == index); + + // This runs in System.Proceed before ATB/state/stage. Native non-auto + // CoAttack stages are deleted by their thread after the stage is Finished. + private void PrepareCoAttackThreads() + { + foreach (CoAttackStageRun stage in _coAttackStages.Values.Where(stage => stage.Finished).ToArray()) + { + _coAttackStages.Remove(stage.Run.Id); + _coAttackChecked.Remove(stage.Run.Id); + _stage.Cancel(stage.Handle); + // Both native system threads release the global ATB pause on completion. + _coAttackAtbPaused = false; + if (_coAttackFadeOwner == stage) + _coAttackFadeOwner = null; + if (stage.Source.Run == stage.Run) + Finish(stage.Source); + } + } + + private bool AdvanceCoAttack(CoAttackStageRun stage, BattleStageContext context) + { + for (int index = 0; index < stage.Subtasks.Length; index++) + { + CoAttackSubtask sub = stage.Subtasks[index]; + if (index > 0 && stage.Subtasks[index - 1].Status == BattleCoAttackStepStatus.Ready) + break; + if (sub.Status == BattleCoAttackStepStatus.Finished) + { + if (stage.Subtasks.All(value => value.Status == BattleCoAttackStepStatus.Finished)) + return stage.Finished = true; + continue; + } + if (sub.Status == BattleCoAttackStepStatus.Ready) + { + CoAttackSubtask previous = stage.Subtasks[index - 1]; + bool ready = index == (int)BattleCoAttackStep.WaitForSource + ? (double)context.Time - previous.Started > 0f + : previous.Status == BattleCoAttackStepStatus.Finished; + if (!ready) + continue; + sub.Status = BattleCoAttackStepStatus.Running; + sub.Started = context.Time; + } + if (AdvanceCoAttackSubtask(stage, (BattleCoAttackStep)index, sub, context)) + sub.Status = BattleCoAttackStepStatus.Finished; + } + return false; + } + + private bool AdvanceCoAttackSubtask(CoAttackStageRun stage, BattleCoAttackStep step, CoAttackSubtask sub, BattleStageContext context) + { + bool requireEnd = stage.Run.EndRequested; + bool presentationSkip = sub.SkipRequested; + switch (step) + { + case BattleCoAttackStep.GrabSource: + return TryGrabStageBody(stage.Source, stage.Handle); + case BattleCoAttackStep.Preload: + if (_effects is IBattleEffectPreloader preloader) + { + if (stage.Profile.FirstGroupId >= 0) + preloader.Preload(stage.Profile.FirstGroupId); + if (stage.Profile.SecondGroupId >= 0) + preloader.Preload(stage.Profile.SecondGroupId); + } + return true; + case BattleCoAttackStep.FadeOutToCombo: + case BattleCoAttackStep.FadeInToCombo: + case BattleCoAttackStep.FadeOutToHome: + case BattleCoAttackStep.FadeInToHome: + if (!sub.Executed) + { + sub.Executed = true; + return false; + } + bool fadeOut = step is BattleCoAttackStep.FadeOutToCombo or BattleCoAttackStep.FadeOutToHome; + double fadeElapsed = (double)context.Time - sub.Started; + bool done = requireEnd || presentationSkip || fadeElapsed > BattleComboStageProfile.FadeSeconds; + _coAttackFadeOwner = stage; + CoAttackScreenColor = step is BattleCoAttackStep.FadeOutToCombo or BattleCoAttackStep.FadeInToCombo ? uint.MaxValue : 0; + CoAttackScreenOpacity = done ? fadeOut ? 1f : 0f : (float)Math.Clamp(fadeOut ? fadeElapsed : 1 - fadeElapsed, 0, 1); + return done; + case BattleCoAttackStep.SetComboPositions: + SetCoAttackPositions(stage); + return true; + case BattleCoAttackStep.ShowName: + if (!sub.Executed) + { + sub.Executed = true; + ShowStageMessage(stage, stage.Source.Initial.Side, stage.Combo.Name, handle: context.Handle); + } + stage.NameVisible = true; + bool nameDone = requireEnd || (double)context.Time - sub.Started > BattleComboStageProfile.NameSeconds; + if (nameDone) + { + stage.NameVisible = false; + HideStageMessage(stage); + } + return nameDone; + case BattleCoAttackStep.WaitForSource: + case BattleCoAttackStep.WaitForSourceAfterAct: + return requireEnd || CoAttackSourceIdle(stage.Source); + case BattleCoAttackStep.Act: + if (!sub.Executed) + { + sub.Executed = true; + ResetActorFacing(stage.Source); + } + double elapsed = (double)context.Time - sub.Started; + if (!stage.FirstStarted && elapsed >= stage.Profile.FirstWaitSeconds) + { + stage.FirstStarted = true; + stage.FirstHandle = StartCoAttackEffect(stage, stage.Profile.FirstGroupId, stage.Profile.FirstOrigin); + } + if (!stage.SecondStarted && elapsed >= stage.Profile.SecondWaitSeconds) + { + stage.SecondStarted = true; + stage.SecondHandle = StartCoAttackEffect(stage, stage.Profile.SecondGroupId, stage.Profile.SecondOrigin); + } + if (!stage.Worked && elapsed >= stage.Profile.WorkSeconds) + { + stage.Worked = true; + ResolveCoAttackValues(stage); + } + // Both games ignore RequireToEnd and source data life here. + // PAL3A writes Finish before checking the two running groups. + return stage.Worked && CoAttackSourceIdle(stage.Source) && (Definitions.Variant == "PAL3A" || + !CoAttackEffectRunning(stage.FirstHandle) && !CoAttackEffectRunning(stage.SecondHandle)); + case BattleCoAttackStep.RestorePositions: + RestoreCoAttackPositions(stage); + return true; + case BattleCoAttackStep.ReleaseSource: + ReleaseStageBody(stage.Source, stage.Handle); + ReleaseCoAttackSourceBody(stage.Source); + return true; + default: + throw new InvalidOperationException("Unknown original combo stage."); + } + } + + private bool CoAttackSourceIdle(Actor source) => PhysicalBodyIdle(source); + + private long StartCoAttackEffect(CoAttackStageRun stage, int group, BattleMovementPoint origin) => group < 0 ? 0 : + StartEffect(new BattleEffectRequest(group, stage.Source.Initial.InstanceId, stage.Targets, origin, unchecked((uint)_scenario.Seed))); + + private bool CoAttackEffectRunning(long handle) => handle != 0 && _effects.IsRunning(handle); + + private void SetCoAttackPositions(CoAttackStageRun stage) + { + if (_catalog is not IBattleCoAttackTimings positions) + throw new NotSupportedException("Original combo positions require the scene formation geometry."); + foreach (Actor actor in _actors.Where(actor => actor.Initial.Side == BattleSide.Ally && actor.Alive)) + { + SetActorPosition(actor, positions.CoAttackHome(actor.Initial.InstanceId, actor.Slot)); + ResetActorFacing(actor); + } + int targetIndex = stage.Selection.NativeTargetIndex; + if (stage.Combo.NativeRange != 2 || targetIndex == -1) + return; + Actor center = ActorAtNativeIndex(10); + if (targetIndex != 10) + { + if (center != null && !center.Escaped && center.ModelAlive) + { + SetActorPosition(center, center.Home); + stage.HiddenActors.Add(center.Initial.InstanceId); + } + Actor target = ActorAtNativeIndex(targetIndex); + if (target != null) + SetActorPosition(target, center?.Home ?? stage.Profile.EnemyCenter); + } + if (Definitions.Variant == "PAL3A") + foreach (Actor actor in _actors.Where(actor => actor.Initial.Side == BattleSide.Ally && !actor.Escaped && + actor.Slot == BattleSlot.Center && actor.Initial.ActorId != stage.Combo.Requirement.Members[0])) + stage.HiddenActors.Add(actor.Initial.InstanceId); + } + + private void RestoreCoAttackPositions(CoAttackStageRun stage) + { + foreach (Actor actor in _actors.Where(actor => !actor.Escaped)) + { + SetActorPosition(actor, actor.Home); + ResetActorFacing(actor); + } + // Visibility due to death or escape is handled separately by the preview. + stage.HiddenActors.Clear(); + } + + private void ResolveCoAttackValues(CoAttackStageRun stage) + { + var rules = new BattleCoAttackRules(Definitions.Variant); + BattleFormationRules formation = FormationRules(); + foreach (string id in stage.Targets) + { + Actor target = _byId[id]; + int returned = 0; + bool hpRecovered = false, mpRecovered = false; + foreach (int resource in rules.EvaluationIndices(stage.Combo.ResourceValues)) + { + int power = rules.Power(stage.Combo.Requirement.Members, memberId => + { + Actor member = ActorAtNativeIndex(formation.MemberIndex(memberId)) ?? + throw new InvalidOperationException("An original combo participant disappeared."); + if (Has(target, BattleState.Barrier) || Has(target, BattleState.Invisible)) + return 0; + return _effectRules.PhysicalPower(RuleParticipant(member), RuleParticipant(target), member.Definition, + target.Definition, BattleTargetRange.OpponentSingle, _catalog.DamageDivisor(member.Initial.InstanceId), + Has(member, BattleState.Madness), _random); + }, stage.Combo.PowerMultiplierPercentage, _random); + if (BattleCoAttackRules.WritesResource(resource)) + { + returned = ChangeResource(target, resource, + BattleCoAttackRules.SignedPower(power, stage.Combo.ResourceValues[resource]), + stage.Source, stage.Run.Id, stage.Combo.Name, showNumber: Definitions.Variant == "PAL3A" && resource == 2); + hpRecovered |= resource == 0 && returned > 0; + mpRecovered |= resource == 2 && returned > 0; + } + } + PlaySound(BattleEffectAudioRules.Recovery(hpRecovered, mpRecovered)); + if (returned < 0 && target.Run?.Casting == true) + { + Cancel(target, "original combo value interrupted the second gauge slot"); + target.Gauge = target.CastGauge = 0; + target.Ready = false; + } + } + // No trigger cost, proficiency gain, auxiliary gauge reset, or status write. + CheckResult(); + } + + private void ReleaseCoAttackSourceBody(Actor source) + { + source.Movement?.Stop(); + source.Movement = null; + source.MovementQueue.Clear(); + source.HurtUntil = checked((int)SimulationTick); + source.Dodging = false; + } + + // Explicit session/editor cancellation may destroy the stage. Native role + // death instead sets EndRequested and must leave Act running. + private void CancelCoAttackStage(ActionRun run) + { + if (run == null) + return; + _coAttackChecked.Remove(run.Id); + if (!_coAttackStages.Remove(run.Id, out CoAttackStageRun stage)) + return; + HideStageMessage(stage); + if (stage.FirstHandle != 0) + StopEffect(stage.FirstHandle); + if (stage.SecondHandle != 0) + StopEffect(stage.SecondHandle); + // Editor cancellation releases this combo's presentation only. + if (_coAttackStages.Count == 0) + _coAttackAtbPaused = false; + if (_coAttackFadeOwner == stage) + { + _coAttackFadeOwner = null; + CoAttackScreenOpacity = 0; + } + if (stage.HasComboPositions && !_coAttackStages.Values.Any(other => other.HasComboPositions)) + RestoreCoAttackPositions(stage); + if (OwnsStageBody(stage.Source, stage.Handle)) + { + ReleaseStageBody(stage.Source, stage.Handle); + ReleaseCoAttackSourceBody(stage.Source); + } + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.CoAttack.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.CoAttack.cs.meta new file mode 100644 index 00000000..f9ff9411 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.CoAttack.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c16e9b85eae94b8b9896a070fe6343be diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Corpses.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Corpses.cs new file mode 100644 index 00000000..59fc185a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Corpses.cs @@ -0,0 +1,41 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System.Linq; + + public sealed partial class BattleSession + { + private void TryObtainOriginalCorpse(Actor source, Actor target, ActionRun run) + { + BattleAbilityDefinition ability = run.Ability; + BattleActorDefinition definition = target.Definition; + if (ability.IsItem || NativeActorIndex(target) is < 5 or >= 11 || target.Hp > 0 || + definition.CorpseItem == 0 || definition.CorpseSkill != ability.Id || + _actors.Any(actor => NativeActorIndex(actor) < 5 && actor.Slot == BattleSlot.Center)) + return; + // The lineup test considers every valid ally, including dead or + // fled allies. The roll occurs here, before payment and proficiency. + if (!_random.Probability(definition.CorpsePercent)) + return; + int before = target.CorpseItem; + target.CorpseItem = definition.CorpseItem; + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.CorpseObtained, + Source = source.Initial.InstanceId, + Target = target.Initial.InstanceId, + ActionId = run.Id, + AbilityId = definition.CorpseItem, + ValueBefore = before, + ValueAfter = target.CorpseItem, + RandomState = _random.State, + Detail = "original corpse recorded on the native enemy slot" + }); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Corpses.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Corpses.cs.meta new file mode 100644 index 00000000..ac16b74f --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Corpses.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: bf2a40c5395f48ac93c6c1201258bff2 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.EffectPresentation.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.EffectPresentation.cs new file mode 100644 index 00000000..6e7e9056 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.EffectPresentation.cs @@ -0,0 +1,225 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public interface IBattleEffectActorAnimations + { + BattlePhysicalAnimation ExternalBody(BattleActorSnapshot actor, string requested, BattleDefinitions definitions); + + string EffectActor(uint modelCrc); + } + + public interface IBattleModalEffects + { + bool BlocksBattleTime + { + get; + } + + bool SkipModalPresentation(); + } + + public interface IBattlePresentationPreparation + { + bool IsPreparingPlayback + { + get; + } + } + + public sealed class BattleEffectActorSnapshot + { + public bool HasBlend + { + get; internal set; + } + + public string Id + { + get; internal set; + } + + public BattleMovementPoint Position + { + get; internal set; + } + + public float FacingDegrees + { + get; internal set; + } + + public float Blend + { + get; internal set; + } + + public bool Controlled + { + get; internal set; + } + + public string Clip + { + get; internal set; + } + + public int AnimationTick + { + get; internal set; + } + + public bool ActionOver + { + get; internal set; + } + + public bool LongBlade + { + get; internal set; + } + + public float LeftWeapon + { + get; internal set; + } + + public float RightWeapon + { + get; internal set; + } + } + + public sealed partial class BattleSession + { + private sealed class ExternalEffectActor + { + public readonly HashSet Controllers = new(); + public bool LongBlade; + + public bool Controlled => Controllers.Count != 0; + + public float? Blend; + public float LeftWeapon, RightWeapon; + } + + private readonly List _modalTransitions = new(); + + // Consecutive entries mark the beginning and resumption of blocked battle frames. + internal bool MatchesModalTimeline(BattleSession other) => + IsModalPresentation == other.IsModalPresentation && _modalTransitions.SequenceEqual(other._modalTransitions); + + public bool SkipModalPresentation() + { + if (Status != BattleSessionStatus.Running || _effects is not IBattleModalEffects modal || + !modal.BlocksBattleTime || !modal.SkipModalPresentation()) + return false; + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.ModalPresentationSkip }); + return true; + } + + private readonly Dictionary _externalEffectActors = new(StringComparer.Ordinal); + + public string EffectActorId(int nativeIndex, uint modelCrc = 0) => modelCrc > 0 ? + (_catalog as IBattleEffectActorAnimations)?.EffectActor(modelCrc) : ActorAtNativeIndex(nativeIndex)?.Initial.InstanceId; + + public bool IsActorExternallyControlled(string actor) => _externalEffectActors.TryGetValue(actor, out ExternalEffectActor state) && state.Controlled; + + public BattleEffectActorSnapshot EffectActor(string actorId) + { + if (!_byId.TryGetValue(actorId ?? "", out Actor actor)) + return null; + _externalEffectActors.TryGetValue(actorId, out ExternalEffectActor state); + BattleBodyAnimationBinding body = GetBodyBinding(actor); + return new BattleEffectActorSnapshot + { + Id = actorId, + Position = actor.Position, + FacingDegrees = actor.FacingDegrees, + Blend = state?.Blend ?? actor.Movement?.Blend ?? (actor.States.ContainsKey(BattleState.Invisible) ? 0.44f : 1), + HasBlend = state?.Blend.HasValue == true, + Controlled = state?.Controlled == true, + Clip = state?.Controlled == true ? body.CurrentAnimation?.Clip : null, + AnimationTick = body.LocalTick, + ActionOver = body.LastPoppedMarker == BattlePhysicalMarkerKind.Over, + LongBlade = state?.LongBlade == true, + LeftWeapon = state?.LeftWeapon ?? 0, + RightWeapon = state?.RightWeapon ?? 0 + }; + } + + private ExternalEffectActor ExternalActor(string actorId) + { + if (!_byId.ContainsKey(actorId ?? "")) + throw new ArgumentException("Unknown effect-controlled actor.", nameof(actorId)); + if (!_externalEffectActors.TryGetValue(actorId, out ExternalEffectActor state)) + _externalEffectActors.Add(actorId, state = new ExternalEffectActor()); + return state; + } + + public void SetEffectActorControlled(string actorId, bool controlled) => SetEffectActorControlled(actorId, controlled, null); + + public void SetEffectActorControlled(string actorId, bool controlled, object owner) + { + // An explicit stage flag and each running action node release independently. + var controllers = ExternalActor(actorId).Controllers; + if (controlled) + { + controllers.Add(owner); + } + else + { + controllers.Remove(owner); + } + } + + public void SetEffectActorAction(string actorId, string requested) + { + if (requested == null) + return; + Actor actor = _byId[actorId]; + if (_catalog is not IBattleEffectActorAnimations catalog) + throw new InvalidOperationException("External actor control requires original animation resources."); + ExternalActor(actorId); + TryPlayBodyAnimation(actor, catalog.ExternalBody(Snapshot(actor), requested, Definitions), false); + ResetBodyAnimation(actor); + } + + public void SetEffectActorPosition(string actorId, BattleMovementPoint position) => SetActorPosition(_byId[actorId], position); + + public void SetEffectActorFacing(string actorId, float facing) + { + if (!float.IsFinite(facing)) + throw new ArgumentException("An original facing must be finite.", nameof(facing)); + Actor actor = _byId[actorId]; + actor.FacingDegrees = facing; + actor.Movement?.SetHeading(facing); + } + + public void SetEffectActorBlend(string actorId, float blend) => ExternalActor(actorId).Blend = Math.Clamp(blend, 0, 1); + + public void SetEffectActorBlade(string actorId, bool longBlade) + { + ExternalActor(actorId).LongBlade = longBlade; + SetBodyBladeSeconds(_byId[actorId], longBlade ? 0.25f : 0.01f); + } + + public void SetEffectActorWeapons(string actorId, float left, float right) + { + ExternalEffectActor actor = ExternalActor(actorId); + actor.LeftWeapon = left; + actor.RightWeapon = right; + } + + // CCBStageRole keeps its body task while external control suppresses + // Proceed. After release that task observes the external clip's over. + private bool TryAdvanceExternalEffectBody(Actor actor, ActionRun run) => IsActorExternallyControlled(actor.Initial.InstanceId); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.EffectPresentation.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.EffectPresentation.cs.meta new file mode 100644 index 00000000..f2b7862d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.EffectPresentation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3bb49cfb33124559830d9415a58a9a16 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Effects.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Effects.cs new file mode 100644 index 00000000..17111560 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Effects.cs @@ -0,0 +1,568 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + public IReadOnlyList GetCostEstimate(BattleCommand command) + { + if (command.Actor == null || !_byId.TryGetValue(command.Actor, out Actor actor)) + return Array.Empty(); + BattleAbilityDefinition ability = Ability(command); + if (ability == null || ability.IsItem) + return Array.Empty(); + return Array.AsReadOnly(ability.Costs.Select(cost => + { + int amount = CostAmount(actor, ability, cost); + int required = cost.Resource is 1 or 2 ? (cost.Resource == (ability.IsMagic ? 2 : 1) ? amount : 0) : amount; + required = SpecialRequiredCost(ability, cost, required); + int saving = cost.Resource == 1 ? EquipmentBonus(actor, item => item.SpSaving) : cost.Resource == 2 ? EquipmentBonus(actor, item => item.MpSaving) : 0; + int payable = -BattleEffectRules.ReduceResourceLoss(-amount, saving); + return new BattleCostEstimate(cost.Resource, required, payable, ResourceValue(actor, cost.Resource)); + }).ToArray()); + } + + private int CostAmount(Actor actor, BattleAbilityDefinition ability, BattleCost cost) + { + if (cost.Resource == 0 && BattleSpecialRules.UsesAbsoluteHpCost(Definitions.Variant, ability.Id)) + return Math.Max(0, cost.Value); + if (cost.Resource == 1 && Definitions.Variant == "PAL3A" && ability.Id == 4308) + return actor.Attributes[1]; + // GP/MP consume mode bytes are metadata; original FightSkillCost reads their absolute integers. + if (cost.Resource is 1 or 2) + return Math.Max(0, cost.Value); + if (cost.Resource == 16) + return 1; + if (cost.Mode == BattleValueMode.Percentage) + return (int)((long)ResourceValue(actor, cost.Resource) * cost.Value / 100); + return Math.Max(0, cost.Value); + } + + private int ResourceValue(Actor actor, int resource) => resource switch + { + 0 => actor.Hp, + 1 => actor.Sp, + 2 => actor.Mp, + 6 => actor.Experience, + 7 => actor.Attributes[5], + 8 => actor.Attributes[6], + 10 => _money, + 16 => _inventory.GetValueOrDefault(BattlePal3ARules.GuInventoryItem), + _ => 0, + }; + + private static int EquipmentBonus(Actor actor, Func select) => + actor.Definition?.Equipment.Where(item => item.Slot != 0).Sum(select) ?? 0; + + private int ItemRecoveryBonus(Actor actor) => actor.Definition?.Equipment.Where(item => item.Slot != 0) + .Sum(item => item.SpecialEffect is 21 or 22 ? 10 : 0) ?? 0; + + private void PaySkillCost(Actor actor, BattleAbilityDefinition ability, long actionId, int lastTargetReturn) + { + foreach (BattleCost cost in ability.Costs.OrderBy(value => value.Resource is 1 or 2 ? value.Resource : 100 + value.Resource)) + { + int amount = cost.Resource == 10 && ability.Handler == BattleSpecialHandler.MoneyRecovery ? lastTargetReturn : CostAmount(actor, ability, cost); + if (cost.Resource == 0 && Definitions.Variant == "PAL3") + continue; // Released PAL3 leaves special HP costs unimplemented; PAL3A actually charges them. + if (cost.Resource == 16) + { + if (_inventory.GetValueOrDefault(BattlePal3ARules.GuInventoryItem) > 0) + { + ChangeItem(BattlePal3ARules.GuInventoryItem, -1, actor.Initial.InstanceId, "fixed original Gu skill cost " + ability.Id); + QueueNumber(actor, 16, -1, 3.5f, false); + } + } + else if (cost.Resource == 0 && BattleSpecialRules.UsesAbsoluteHpCost(Definitions.Variant, ability.Id)) + ChangeHp(actor, -amount, null, actionId, "skill cost " + ability.Id, showAction: false); + else + ChangeResource(actor, cost.Resource, -amount, actor, actionId, "skill cost " + ability.Id); + } + if (ability.IsMagic && actor.Initial.Side == BattleSide.Ally) + { + BattleSkill skill = AiSkill(actor, ability.Id); + int maximum = Definitions.Variant == "PAL3A" ? ushort.MaxValue : byte.MaxValue; + skill.Uses = Math.Min(maximum, skill.Uses + 1); + } + } + + private void ResolveActionMarker(Actor source, ActionRun run) + { + if (ResolveElementWheelMarker(source, run)) + return; + if (ResolvePal3AAbilityMarker(source, run)) + return; + if (ResolveMagicSwordMarker(source, run)) + return; + if (run.Ability == null) + { + ResolvePhysicalMarker(source, run); + CheckResult(); + return; + } + if (run.AbilityResolved) + return; + run.AbilityResolved = true; + BattleAbilityDefinition ability = run.Ability; + ResolveAiSceneMagic(source, ability); + int lastTargetReturn = 0; + foreach (string targetId in run.Targets) + { + Actor target = _byId[targetId]; + if (target.Escaped) + continue; + bool multi = ability.Range is not (BattleTargetRange.OwnSingle or BattleTargetRange.OpponentSingle); + if (!TechniqueSucceeds(source, target, run)) + continue; + if (!IsAtHome(target) && !ability.Revives && (ability.IsMagic || !multi)) + { + Add(BattleEventKind.Miss, source.Initial.InstanceId, targetId, run.Id, "target away from home"); + QueueNumber(target, 0, 0, 1f, false, miss: true); + continue; + } + if (ability.IsMagic && Has(target, BattleState.Barrier)) + { + Add(BattleEventKind.Miss, source.Initial.InstanceId, targetId, run.Id, "界 rejects all magic effects"); + continue; + } + if (ResolveSpecialBeforeStates(source, target, run)) + { + lastTargetReturn = 0; + continue; + } + // Ordinary spells and techniques change statuses before resource values. Resurrection depends on this order. + ApplyAbilityStates(source, target, run); + int oldHp = target.Hp; + int lastReturnedDelta = 0; + bool hpRecovered = false, mpRecovered = false; + foreach (BattleAttributeEffect effect in ability.Attributes.OrderBy(value => value.Attribute)) + { + if (effect.Value == 0) + continue; + int power = effect.Value; + BattleValueMode mode = effect.Mode; + if (ability.IsMagic) + power = _effectRules.MagicPower(power, RuleParticipant(source), RuleParticipant(target), ability.ElementMask, _random, + enhancementMask: Definitions.Variant == "PAL3A" && FiveSpiritElement > 0 ? 1 << (FiveSpiritElement - 1) : 0, + weatherElement: Definitions.Variant == "PAL3A" ? BattleEffectRules.GreaterElement(FiveSpiritElement) : 0); + if (ability.IsMagic) + power = AdjustPal3AMagicPower(source, power); + else if (!ability.IsItem) + power = _effectRules.TechniquePower(power, RuleParticipant(source), RuleParticipant(target), multi, ability.Id, + _actors.FirstOrDefault(actor => actor.Definition?.Identity == 0)?.Level ?? source.Level, _random, out mode); + else if (power > 0 && source.Initial.Side == BattleSide.Ally) + power += BattleBasicRules.Round(power * (float)ItemRecoveryBonus(source) / 100); + if (effect.Attribute > 2) + throw new NotSupportedException("Combat attributes outside HP/SP/MP need an explicit effect handler."); + int resource = effect.Attribute; + if (mode == BattleValueMode.IncreaseMax) + { + if (resource != 1) + { + int before = target.Attributes[resource]; + target.Attributes[resource] = Math.Max(0, unchecked(before + power)); + AddResource(source, target, run.Id, resource, before, target.Attributes[resource], power, "maximum increased"); + } + lastReturnedDelta = 0; + continue; + } + int requested = mode == BattleValueMode.RecoverToMax ? target.Attributes[resource] - ResourceValue(target, resource) : + mode == BattleValueMode.Percentage ? (int)((long)target.Attributes[resource] * power / 100) : power; + lastReturnedDelta = ChangeResource(target, resource, requested, source, run.Id, ability.Name, + showNumber: Definitions.Variant == "PAL3A" && resource == 2); + hpRecovered |= resource == 0 && lastReturnedDelta > 0; + mpRecovered |= resource == 2 && lastReturnedDelta > 0; + } + PlaySound(BattleEffectAudioRules.Recovery(hpRecovered, mpRecovered)); + lastTargetReturn = lastReturnedDelta; + ResolveSpecialAfterValues(source, target, run, oldHp, lastReturnedDelta); + if (lastReturnedDelta < 0 && target.Run?.Casting == true) + { + Cancel(target, "ability hit interrupted casting"); + target.Ready = false; + target.Gauge = ability.IsMagic ? FullGauge - FullGauge * ability.SpellRank / 8 : 0; + } + ResolveSpecialAfterTarget(source, target, run); + TryObtainOriginalCorpse(source, target, run); + } + // All targets resolve before costs and the single proficiency use; a last lethal hit must not skip payment. + if (!ability.IsItem && (!ability.IsMagic || !_bossRules.SkipsMagicCost(source.Initial.ActorId))) + PaySkillCost(source, ability, run.Id, lastTargetReturn); + HandleOriginalPostMagic(source, run); + CheckResult(); + } + + private void ResolvePhysicalMarker(Actor source, ActionRun run) + { + GainMagicSwordOnPhysicalWork(source, run.Id); + int sourceLuck = EffectiveAttributes(source)[6]; + bool critical = _random.Probability((int)(Math.Sqrt(sourceLuck / 2) * 10)); + BattleTargetRange range = ActionRange(source, null); + foreach (string targetId in run.Targets) + { + Actor target = _byId[targetId]; + if (!target.Alive || target.Escaped) + continue; + if (!IsAtHome(target) || Has(target, BattleState.Evade)) + { + Add(BattleEventKind.Miss, source.Initial.InstanceId, targetId, run.Id, "away target or 避"); + QueueNumber(target, 0, 0, 1f, false, miss: !Has(target, BattleState.Evade)); + continue; + } + bool dodged = target.Initial.Side == BattleSide.Ally && _random.Probability(Math.Max(0, (EffectiveAttributes(target)[5] - EffectiveAttributes(source)[5]) * 5)); + if (Has(target, BattleState.Reflection) || Has(target, BattleState.Paralysis) || Has(target, BattleState.Sleep)) + dodged = false; + int damage = Has(target, BattleState.Invisible) ? 0 : _effectRules.PhysicalPower(RuleParticipant(source), RuleParticipant(target), source.Definition, + target.Definition, range, _catalog.DamageDivisor(source.Initial.InstanceId), Has(source, BattleState.Madness), _random); + if (dodged || damage >= 0) + { + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.Miss, + Source = source.Initial.InstanceId, + Target = targetId, + ActionId = run.Id, + Critical = critical, + Dodged = dodged, + RandomState = _random.State, + Detail = dodged ? "dodged" : "nonnegative native damage" + }); + QueueNumber(target, 0, 0, 1f, false, miss: true, dodgeBody: true); + continue; + } + if (critical) + damage = _effectRules.CriticalPower(damage, EquipmentBonus(source, item => item.CriticalBonus)); + bool reflected = Has(target, BattleState.Reflection) || + _random.Probability(4) && target.Definition.Equipment.Any(item => item.PhysicalReflectionPassive); + if (reflected) + ChangeHp(source, damage, target, run.Id, "physical reflection", false, critical); + else + { + bool protectedHit = TryGetPhysicalProtector(source, target, out Actor guardian); + Actor receiver = protectedHit ? guardian : target; + bool fleeing = IsFleeWaiting(receiver); + if (!protectedHit && target.Run?.Casting == true) + { + if (IsFleeWaiting(target)) + InterruptFleeWaiting(target, "physical request interrupted the second slot before HP payment", FullGauge / 2); + else + { + Cancel(target, "physical request interrupted the second slot before HP payment"); + target.Gauge = FullGauge / 2; + target.Ready = false; + } + } + if (critical && !protectedHit && _effects != null) + StartEffect(new BattleEffectRequest(470, target.Initial.InstanceId, new[] { target.Initial.InstanceId }, target.Position, unchecked((uint)_scenario.Seed))); + int actualHp = ChangeHp(receiver, damage, source, run.Id, "physical", true, critical); + if (protectedHit) + { + ChangeLove(target, 1); + if (critical && _effects != null) + StartEffect(new BattleEffectRequest(470, receiver.Initial.InstanceId, new[] { receiver.Initial.InstanceId }, receiver.Position, unchecked((uint)_scenario.Seed))); + } + if (fleeing && actualHp < 0) + receiver.Gauge = 0; + if (target.Initial.Side == BattleSide.Ally) + ChangeResource(target, 1, _catalog.SpImpact(source.Initial.InstanceId), source, run.Id, "physical SP impact"); + if (source.Initial.Side == BattleSide.Enemy) + { + int probability = 5 + EffectiveAttributes(source)[6] - EffectiveAttributes(receiver)[6]; + if (_random.Probability(probability)) + { + int mode = source.Definition.NormalAttackMode; + BattleState? state = BattlePhysicalAttackModes.AddedState(mode); + if (state.HasValue) + ApplyState(receiver, state.Value, false, source: source, actionId: run.Id); + else if (mode == 912) + { + foreach (int resource in new[] { 2, 1 }) + { + int transfer = Math.Min(10, ResourceValue(receiver, resource)); + ChangeResource(receiver, resource, -transfer, source, run.Id, "normal attack resource transfer", showNumber: true); + ChangeResource(source, resource, transfer, source, run.Id, "normal attack resource transfer", showNumber: true); + } + } + else if (mode == 915) + ApplyRandomPoison(source, receiver, run.Id); + else + ResolvePhysicalSpecial(source, receiver, run, mode); + } + } + foreach (BattleEquipmentDefinition weapon in source.Definition.Equipment.Where(item => item.Slot == 0)) + foreach (BattleStatusEffect state in weapon.States.OrderBy(value => value.State)) + if (state.State < BattleState.Dying && _random.Probability(state.Value)) + { + ApplyState(receiver, state.State, false, source: source, actionId: run.Id); + break; + } + ResolveAttackSteal(source, receiver, run); + } + } + } + + private int ChangeResource(Actor actor, int resource, int requested, Actor source, long actionId, string reason, bool showNumber = false) + { + if (resource == 0) + return ChangeHp(actor, requested, source, actionId, reason); + int before = ResourceValue(actor, resource); + int delta = requested; + if (resource is 1 or 2) + { + if (!actor.Alive || resource == 2 && Pal3AIgnoresMpChange(actor)) + return 0; + int saving = resource == 1 ? EquipmentBonus(actor, item => item.SpSaving) : EquipmentBonus(actor, item => item.MpSaving); + delta = BattleEffectRules.ReduceResourceLoss(delta, saving); + if (resource == 2) + TrackPal3AMpLoss(actor, delta); + int after = (int)Math.Clamp((long)before + delta, 0, actor.Attributes[resource]); + if (resource == 1) + actor.Sp = after; + else + actor.Mp = after; + } + else if (resource == 10) + _money = (int)Math.Clamp((long)_money + delta, 0, int.MaxValue); + else if (resource == 7 || resource == 8) + { + actor.Attributes[resource == 7 ? 5 : 6] = (int)Math.Clamp((long)before + delta, 0, 1000000); + if (resource == 7 && actor.Run?.Casting == true) + actor.CastSpeed = _rules.GaugePerStep(RuleParticipant(actor)); + } + else + throw new NotSupportedException("Unsupported resource " + resource); + int actual = ResourceValue(actor, resource) - before; + AddResource(source, actor, actionId, resource, before, ResourceValue(actor, resource), requested, reason); + // Only a successfully registered displayed GP/MP number clamps the native return value. + bool displayed = resource is 1 or 2 && requested != 0 && showNumber && QueueNumber(actor, resource, actual, 2.5f, false); + return resource is 1 or 2 ? displayed ? actual : delta : actual; + } + + private int ChangeHp(Actor target, int requested, Actor source, long actionId, string reason, bool showAction = true, bool critical = false, bool ignoreInvisible = false) + { + int before = target.Hp; + if (target.Escaped || !target.Alive || !ignoreInvisible && Has(target, BattleState.Invisible)) + return 0; + int delta = requested; + if (delta < -1 && target.Guard) + delta /= 2; + if (delta < 0 && Definitions?.Variant == "PAL3" && target.Definition.MoneyShield) + { + delta = ApplyMoneyShield(target, delta, source, actionId); + if (delta == 0) + return 0; + } + TrackPal3AHpLoss(target, delta); + target.Hp = (int)Math.Clamp((long)target.Hp + delta, 0, target.Attributes[0]); + if (requested < 0 && Has(target, BattleState.Sleep)) + ApplyState(target, BattleState.Sleep, true, source: source, actionId: actionId); + ApplyOriginalMustFailHp(target); + HandlePal3AFormHpFloor(target, actionId); + if (HandleOriginalBossLethal(target, actionId)) + return -before; + int actual = target.Hp - before; + if (target.Hp > 0) + target.Reviving = false; + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = actual < 0 ? BattleEventKind.Hit : BattleEventKind.ResourceChanged, + Source = source?.Initial.InstanceId, + Target = target.Initial.InstanceId, + ActionId = actionId, + HpBefore = before, + HpAfter = target.Hp, + RequestedDelta = requested, + ActualDelta = actual, + Critical = critical, + Resource = 0, + ValueBefore = before, + ValueAfter = target.Hp, + RandomState = _random.State, + Detail = reason + }); + if (requested < 0 && IsFleeWaiting(target)) + InterruptFleeWaiting(target, "negative HP request interrupted escape waiting"); + bool displayed = target.ModelAlive && QueueNumber(target, 0, delta > 0 ? actual : delta, + delta > 0 ? 2.5f : 2f, delta < 0 && showAction, recovery: delta > 0); + if (target.Hp == 0) + { + target.Reviving = false; + target.Killer = source?.Initial.InstanceId; + target.DeathTick = SimulationTick; + RequestRoleEnd(target); + target.PoseStarted = (int)SimulationTick; + Add(BattleEventKind.Death, source?.Initial.InstanceId, target.Initial.InstanceId, actionId); + } + return delta > 0 && !displayed ? delta : delta <= 0 ? -Math.Abs(actual) : actual; + } + + private void ApplyAbilityStates(Actor source, Actor target, ActionRun run) + { + foreach (BattleStatusEffect state in run.Ability.States) + ApplyState(target, state.State, state.Remove, source: source, actionId: run.Id); + // Native cure cues describe the requested operation, even when the + // recipient had none of these ailments. Expiry and waking are silent. + foreach (string sound in BattleEffectAudioRules.ClearedAilments(run.Ability.States)) + PlaySound(sound); + } + + // The second gauge can fill during ATB advancement before the next + // system pass transfers MagicWait to the spell's stage. + private static bool CanInterruptCast(Actor actor) => actor.Run?.Casting == true || + actor.CastGauge == FullCastGauge && actor.Run is + { Kind: BattleAction.Skill, SystemStarted: true, StageHandle: null, Ability: { IsMagic: true }, ElementWheel: false }; + + private bool ApplyState(Actor target, BattleState state, bool remove, int? duration = null, bool permanent = false, Actor source = null, long actionId = 0, bool sound = true) + { + if (Has(target, BattleState.Invisible) && state != BattleState.Invisible) + return false; + if (state == BattleState.Death) + { + if (remove && !target.Alive) + { + // Native resurrection restores life without deleting the + // stage thread or its body queue. Existing end requests stay. + target.States.Clear(); + target.Reviving = true; + target.Alive = true; + target.ModelAlive = true; + target.Ready = false; + target.Gauge = FullGauge * 2 / 3; + target.CastGauge = 0; + target.PoseStarted = (int)SimulationTick; + QueuePhysicalRevivalReturn(target); + Add(BattleEventKind.StatusRemoved, source?.Initial.InstanceId, target.Initial.InstanceId, actionId, "Death; resurrection enabled before HP recovery"); + if (sound) + PlaySound("wd004"); + return true; + } + if (!remove && target.Alive) + ChangeHp(target, -target.Hp * (target.Guard ? 2 : 1), source, actionId, "death status"); + return false; + } + if (!target.Alive && !permanent) + { + // Native removal cues still play for dead roles (including the + // victory cleanup); their stage-only undo animation is skipped. + if (remove && sound) + PlaySound(BattleEffectAudioRules.State(state, true)); + return false; + } + if (remove) + { + if (sound) + PlaySound(BattleEffectAudioRules.State(state, true)); + if (!target.States.Remove(state)) + return false; + Add(BattleEventKind.StatusRemoved, source?.Initial.InstanceId, target.Initial.InstanceId, actionId, state.ToString()); + } + else + { + string denied = _statusRules.CanAdd(state, target.States.Keys, target.Definition.ImmuneStates); + if (denied != null) + { + Add(BattleEventKind.Miss, source?.Initial.InstanceId, target.Initial.InstanceId, actionId, denied); + return false; + } + BattleStatusInstance instance = _statusRules.Create(state, target.Attributes[0], duration, permanent, _random, target.Initial.Side == BattleSide.Ally); + foreach (BattleState conflict in _statusRules.ReplacedBy(state)) + if (target.States.Remove(conflict)) + Add(BattleEventKind.StatusRemoved, source?.Initial.InstanceId, target.Initial.InstanceId, actionId, conflict + " replaced"); + target.States.Add(state, instance); + Add(BattleEventKind.StatusAdded, source?.Initial.InstanceId, target.Initial.InstanceId, actionId, state + (permanent ? " permanent" : " " + instance.RemainingRounds)); + if (sound) + PlaySound(BattleEffectAudioRules.State(state, false)); + } + if (state is BattleState.SpeedIncrease or BattleState.SpeedDecrease && target.Run?.Casting == true) + target.CastSpeed = _rules.GaugePerStep(RuleParticipant(target)); + bool losesControl = !remove && state is BattleState.Paralysis or BattleState.Sleep or BattleState.Chaos or BattleState.Madness; + if (losesControl && (IsFleeWaiting(target) || IsFleeStageRun(target.Run))) + { + if (!_fleeAlwaysSucceeds) + { + if (IsFleeWaiting(target)) + InterruptFleeWaiting(target, state + " interrupted escape waiting"); + else + { + target.Gauge = target.CastGauge = 0; + target.Ready = false; + } + } + return true; + } + // HandleUncontrolableState resets only the second gauge. ProcControl + // handles sleep and paralysis when the first gauge reaches its command mark. + if (!remove && CanInterruptCast(target) && (losesControl && !_fleeAlwaysSucceeds || + state == BattleState.Seal && target.Run.Kind == BattleAction.Skill || + state == BattleState.Forbidden && target.Run.Kind == BattleAction.Flee && !_fleeAlwaysSucceeds)) + { + if (IsFleeWaiting(target)) + InterruptFleeWaiting(target, state + " interrupted escape waiting"); + else + { + Cancel(target, state + " interrupted action"); + target.Gauge = target.CastGauge = 0; + target.Ready = false; + } + } + return true; + } + + private int ChangeItem(int itemId, int amount, string actor, string detail) + { + int before = _inventory.GetValueOrDefault(itemId); + long sum = (long)before + amount; + // Existing entries cap additions at 99. A larger authored stack keeps its current quantity. + int after = Definitions != null && before > 0 && amount > 0 + ? (int)Math.Min(Math.Max(99, before), sum) : checked((int)sum); + if (after < 0) + throw new InvalidOperationException("Inventory cannot become negative."); + _inventory[itemId] = after; + if (before <= 0 && after > 0) + _inventoryOrder.Add(itemId); + else if (before > 0 && after == 0) + _inventoryOrder.Remove(itemId); + int actual = after - before; + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.ItemChanged, + Source = actor, + AbilityId = itemId, + ValueBefore = before, + ValueAfter = after, + RequestedDelta = amount, + ActualDelta = actual, + RandomState = _random.State, + Detail = detail + }); + return actual; + } + + private void AddResource(Actor source, Actor target, long actionId, int resource, int before, int after, int requested, string detail) + => _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.ResourceChanged, + Source = source?.Initial.InstanceId, + Target = target.Initial.InstanceId, + ActionId = actionId, + Resource = resource, + ValueBefore = before, + ValueAfter = after, + RequestedDelta = requested, + ActualDelta = after - before, + RandomState = _random.State, + Detail = detail + }); + + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Effects.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Effects.cs.meta new file mode 100644 index 00000000..02b815ef --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Effects.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b127a4da8cd74810a66915de278140a2 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ElementWheel.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ElementWheel.cs new file mode 100644 index 00000000..57b6c854 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ElementWheel.cs @@ -0,0 +1,66 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public sealed partial class BattleSession + { + // MainPanel 0x220 is a separate released command, not ordinary magic. + // Its GDB record still supplies the element and effect linker. + public string CanSubmitElementWheel(string controller, int skillId) => + ValidateCommand(new BattleCommand(controller, BattleAction.Skill, null, skillId), false, true); + + public bool SubmitElementWheel(string controller, int skillId) => + SubmitCommand(new BattleCommand(controller, BattleAction.Skill, null, skillId), false, true); + + private string ValidateElementWheelController(Actor actor, BattleCommand command, BattleAbilityDefinition ability) + { + if (Definitions?.Variant != "PAL3A" || command.Action != BattleAction.Skill || command.Target != null || + command.AbilityId is < 264 or > 268 || ability == null || ability.Range != BattleTargetRange.None) + return "Choose a PAL3A five-spirit wheel element."; + if (actor.Initial.Side != BattleSide.Ally || NativeActorIndex(actor) != 0 || WaitingActor != command.Actor) + return "The spirit wheel needs Nangong Huang as the current ready controller."; + if (_pal3AForms.TryGetValue(command.Actor, out Pal3AFormState form) && form.Pending) + return "The original form transition is still running."; + if (_spiritWheel.Charges[ElementWheelCoreElement(command.AbilityId)] != 9) + return "This spirit wheel element needs nine charges."; + if (_catalog is IBattleAbilityEffects && _catalog is not IBattleElementWheelTimings) + return "The original spirit wheel presentation is missing."; + return null; + } + + private static int ElementWheelCoreElement(int skillId) => skillId switch + { + 264 => 0, + 265 => 1, + 266 => 3, + 267 => 2, + 268 => 4, + _ => throw new ArgumentOutOfRangeException(nameof(skillId)) + }; + + private AttackTiming ElementWheelTiming(string actor, BattleAbilityDefinition ability) => + _catalog is IBattleElementWheelTimings wheel ? wheel.ElementWheel(actor, ability) : + (_catalog as IBattleAbilityTimings)?.Ability(actor, ability); + + private bool ResolveElementWheelMarker(Actor source, ActionRun run) + { + if (!run.ElementWheel) + return false; + if (!run.AbilityResolved) + { + run.AbilityResolved = true; + ResolveAiSceneMagic(source, run.Ability); + int element = ElementWheelCoreElement(run.Ability.Id); + _spiritWheel = BattlePal3ARules.Gain(_spiritWheel, element, -9); + Add(BattleEventKind.ControlChanged, source.Initial.InstanceId, actionId: run.Id, + detail: "spirit wheel element " + element + " consumed"); + } + return true; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ElementWheel.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ElementWheel.cs.meta new file mode 100644 index 00000000..bdd7957e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ElementWheel.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c144c90c429e452489779b72d17585bc diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Encounter.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Encounter.cs new file mode 100644 index 00000000..1a06e7d6 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Encounter.cs @@ -0,0 +1,202 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + + public sealed partial class BattleSession + { + private BattleEncounterRules _encounterRules; + private BattleBossRules _bossRules; + private IBattleMonsterFactory _monsterFactory; + private int _bossRounds; + private string _activeEncounterScene; + private readonly Dictionary _monsterGenerations = new(StringComparer.Ordinal); + + public int BossRounds => _bossRounds; + + public string ActiveScene => _activeEncounterScene ?? _scenario.Scene; + + public int MonsterGeneration(string instanceId) => _monsterGenerations.GetValueOrDefault(instanceId); + + public BattleParticipant CaptureParticipant(string instanceId) => _byId.TryGetValue(instanceId, out Actor actor) + ? actor.Initial.Copy() : throw new ArgumentException("Unknown battle actor.", nameof(instanceId)); + + private void InitializeOriginalEncounter() + { + _encounterRules = new BattleEncounterRules(_scenario.Variant); + _bossRules = new BattleBossRules(_scenario.Variant); + _monsterFactory = _catalog as IBattleMonsterFactory; + } + + private bool BeginOriginalRound(Actor actor) => BattleEncounterRules.BeginRound(NativeActorIndex(actor), actor.Rounds, + _scenario.RoundLimit, ref actor.ProcessedRounds, ref _bossRounds); + + private bool RoundLimitReached => BattleEncounterRules.RoundLimitReached(_bossRounds, _scenario.RoundLimit); + + private BattleEncounterOutcome EncounterOutcome(IReadOnlyCollection unfinishedNativeTasks) => _encounterRules.CheckOutcome( + _actors.Any(actor => actor.Initial.Side == BattleSide.Ally && actor.Alive), + _actors.Any(actor => actor.Initial.Side == BattleSide.Enemy && actor.Alive && !actor.Escaped), + _bossRounds, _scenario.RoundLimit, _scenario.MustFail, unfinishedNativeTasks); + + private void ApplyOriginalMustFailHp(Actor actor) => actor.Hp = BattleEncounterRules.HpAfterMustFail( + _scenario.MustFail, NativeActorIndex(actor), actor.Hp, actor.Attributes[0]); + + private void HandleOriginalBossRound(Actor actor) + { + if (Definitions == null) + return; + foreach (BattleState state in _bossRules.RoundStates(actor.Initial.ActorId, actor.ProcessedRounds)) + ApplyState(actor, state, false); + int slot = _bossRules.SplitSlot(actor.Initial.ActorId, actor.ProcessedRounds, CaptureEnemySlots(), _random); + if (slot >= 0) + CreateOriginalMonster(slot, actor.Initial.ActorId, 0); + } + + private bool HandleOriginalBossLethal(Actor actor, long actionId) + { + if (Definitions == null || actor.Hp > 0) + return false; + int replacement = _bossRules.DeathReplacement(actor.Initial.ActorId); + if (replacement == 0) + return false; + RequestRoleEnd(actor); + CreateOriginalMonster(NativeActorIndex(actor), replacement, actionId); + _activeEncounterScene = "z39"; + return true; + } + + private void HandleOriginalPostMagic(Actor actor, ActionRun run) + { + if (Definitions == null || run.Ability?.IsMagic != true || run.Ability.IsItem || + !_bossRules.SelfDestructsAfterMagic(actor.Initial.ActorId, run.Ability.Id) || actor.Escaped || + actor.Run?.Kind == BattleAction.Flee) + return; + if (_effects != null) + { + StartEffect(new BattleEffectRequest(324, actor.Initial.InstanceId, new[] { actor.Initial.InstanceId }, actor.Position, unchecked((uint)_scenario.Seed))); + StartEffect(new BattleEffectRequest(325, actor.Initial.InstanceId, new[] { actor.Initial.InstanceId }, actor.Position, unchecked((uint)_scenario.Seed))); + } + ChangeHp(actor, -actor.Hp, null, run.Id, "original fireball self-destruction after magic cost", false); + } + + private void ResolveOriginalSummon(Actor source, long actionId) + { + int alive = _actors.Count(actor => actor.Initial.Side == BattleSide.Enemy && actor.Alive && !actor.Escaped); + foreach (BattleMonsterRequest request in _bossRules.Summon(NativeActorIndex(source), alive, CaptureEnemySlots(), _random)) + CreateOriginalMonster(request.NativeIndex, request.ActorId, actionId); + } + + private BattleNativeEnemySlot[] CaptureEnemySlots() => Enumerable.Range(5, 6).Select(index => + { + Actor actor = ActorAtNativeIndex(index); + return actor == null ? default : new BattleNativeEnemySlot(true, actor.Alive, actor.Escaped); + }).ToArray(); + + private void CreateOriginalMonster(int nativeIndex, int actorId, long actionId) + { + if (_monsterFactory == null) + throw new NotSupportedException("This encounter needs a captured native-slot monster factory."); + Actor actor = ActorAtNativeIndex(nativeIndex); + string instanceId = actor?.Initial.InstanceId ?? "__native_enemy_" + nativeIndex; + if (actor == null) + { + string prefix = instanceId; + int suffix = 0; + while (_byId.ContainsKey(instanceId)) + instanceId = prefix + "_" + ++suffix; + } + BattleMonsterCreation creation = _monsterFactory.Prepare(nativeIndex, actorId, instanceId) + ?? throw new InvalidOperationException("The monster factory did not prepare a candidate."); + BattleParticipant participant = creation.Participant; + if (creation.NativeIndex != nativeIndex || participant.ActorId != actorId || participant.InstanceId != instanceId || + participant.Attributes.Length != 12 || participant.Vitals.Length != 3 || participant.Attributes.Any(value => value < 0 || value > 1000000) || + participant.Vitals.Where((value, resource) => value != participant.Attributes[resource]).Any()) + throw new InvalidOperationException("The prepared monster does not match the native creation request."); + _monsterFactory.Commit(creation); + if (actor == null) + { + actor = new Actor { NativeIndex = nativeIndex }; + _actors.Add(actor); + _byId.Add(instanceId, actor); + } + else + { + Cancel(actor, "native monster slot replaced"); + ClearPhysicalBody(actor); + _physicalBodies.Remove(instanceId); + // Native StageRole.Init resets the role's grab as well as its + // body queue. Independent stages retain their slot reference, + // but cannot keep a lease on the replacement role's body. + _bodyStageOwners.Remove(instanceId); + _fallbackFleeBodies.Remove(instanceId); + } + // Native CreateMonster zeroes this slot's role state. Stage jobs + // referring to the slot remain; stable IDs make queued targets bind + // to its new occupant just as original native-index commands do. + actor.Initial = participant; + ClearOriginalAbsorbHpWorm(actor); + actor.Definition = creation.Definition; + actor.Slot = participant.Slot; + actor.Home = (_catalog as IBattleStageGeometry)?.InitialHome(instanceId) ?? default; + actor.Position = actor.Home; + actor.FacingDegrees = BattleFacingRules.Starting(BattleSide.Enemy, _scenario.Encounter); + actor.Movement = null; + actor.MovementQueue.Clear(); + actor.Hp = participant.Vitals[0]; + actor.Sp = participant.Vitals[1]; + actor.Mp = participant.Vitals[2]; + actor.Gauge = actor.CastGauge = actor.CastSpeed = actor.Rounds = actor.ProcessedRounds = actor.HurtUntil = 0; + actor.PoseStarted = checked((int)SimulationTick); + actor.Level = participant.Level; + actor.Experience = participant.Experience; + actor.Love = participant.Love; + actor.PresentationTick = 0; + actor.Attributes = participant.Attributes.ToArray(); + ApplyPal3ALiaoRiCarry(actor); + actor.EnemyFleeing = false; + actor.Escaped = actor.Dodging = actor.Reviving = actor.Ready = actor.Guard = false; + actor.Alive = actor.ModelAlive = true; + actor.Killer = null; + actor.DeathTick = -1; + actor.CorpseItem = 0; + actor.Skills.Clear(); + actor.Skills.AddRange(participant.Skills.Select(skill => skill.Copy())); + actor.States.Clear(); + foreach (BattleState state in actor.Definition.PermanentStates.OrderBy(state => state)) + ApplyState(actor, state, false, null, true, sound: false); + _stealPools[instanceId] = new StealPool + { + Money = actor.Definition.StealableMoney, + ItemId = actor.Definition.StealableItemId, + ItemCount = actor.Definition.StealableItemCount + }; + _bodyAnimations.Remove(instanceId); + _bodyPassRates.Remove(instanceId); + _externalEffectActors.Remove(instanceId); + foreach (CoAttackStageRun stage in _coAttackStages.Values) + stage.HiddenActors.Remove(instanceId); + _spiritCapturedActors.Remove(instanceId); + foreach (var key in _aiSkillAliases.Keys.Where(key => key.Actor == instanceId).ToArray()) + _aiSkillAliases.Remove(key); + _monsterGenerations[instanceId] = _monsterGenerations.GetValueOrDefault(instanceId) + 1; + if (_ai != null) + { + _ai.Roles[nativeIndex].Profile.SetEnabled(true); + _ai.Roles[nativeIndex].Profile.Negative = true; + for (int index = 0; index < _ai.NewRole.Length; index++) + _ai.NewRole[index] = true; + } + Add(BattleEventKind.ResourceChanged, target: instanceId, actionId: actionId, + detail: "native enemy slot " + nativeIndex + " created actor " + actorId); + if (_effects != null) + StartEffect(new BattleEffectRequest(321, instanceId, new[] { instanceId }, actor.Home, unchecked((uint)_scenario.Seed))); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Encounter.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Encounter.cs.meta new file mode 100644 index 00000000..8847e282 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Encounter.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: bb0cc4fd914444fbb057e84200ae8001 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Flee.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Flee.cs new file mode 100644 index 00000000..75910d96 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Flee.cs @@ -0,0 +1,475 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleFleeResultSnapshot + { + public string Actor + { + get; + } + + public bool Success + { + get; + } + + public float StartedAtSeconds + { + get; + } + + internal BattleFleeResultSnapshot(string actor, bool success, float started) + { + Actor = actor; + Success = success; + StartedAtSeconds = started; + } + } + + public sealed partial class BattleSession + { + private sealed class FleeStage : IBattleStageJob + { + internal BattleSession Session; + internal Actor Actor; + internal ActionRun Run; + internal BattleStageHandle Handle; + internal bool Attempt, Grabbed, BodyQueued, BodyFinished, Finished, Interrupted, Running; + internal bool FallbackBodyStarted, WaitInitialized; + + public bool Advance(BattleStageContext context) => Session.AdvanceFleeStage(this, context); + } + + private sealed class EnemyFleeStage : IBattleStageJob + { + internal BattleSession Session; + internal Actor Actor; + internal bool Grabbed, BodyQueued; + + public bool Advance(BattleStageContext context) + { + if (Grabbed && !Session.OwnsStageBody(Actor, context.Handle)) + return true; + if (!Grabbed) + { + if (!Session.TryGrabStageBody(Actor, context.Handle)) + return false; + Grabbed = true; + } + if (!BodyQueued && Session.PhysicalBodyIdle(Actor)) + { + Session.QueueFleeBody(Actor, BattlePhysicalBodyKind.EnemyFlee, null); + BodyQueued = true; + } + if (!Actor.Escaped && (Actor.Alive || !Session.PhysicalBodyIdle(Actor))) + return false; + Session.ReleaseStageBody(Actor, context.Handle); + return true; + } + } + + private sealed class FleeResultStage : IBattleStageJob + { + internal BattleSession Session; + internal string Actor; + internal bool Success; + private BattleFleeResultSnapshot _message; + + public bool Advance(BattleStageContext context) + { + if (_message == null) + { + _message = new BattleFleeResultSnapshot(Actor, Success, context.CreatedTime); + Session.FleeResult = _message; + Session.ShowStageMessage(this, BattleSide.Ally, languageKey: Success ? "FleeSuccess" : "FleeFail", handle: context.Handle); + } + // Native ProcShowFleeResult uses strict > against the float clock. + if (context.Time - context.CreatedTime <= 3f) + return false; + Session.FleeResult = null; + Session.HideStageMessage(this); + return true; + } + } + + private readonly Dictionary _fleeStages = new(); + private readonly Dictionary _fallbackFleeBodies = new(StringComparer.Ordinal); + private bool _fleeAlwaysSucceeds, _fleeAtbPaused; + + public bool FleeAlwaysSucceeds => _fleeAlwaysSucceeds; + + public BattleFleeResultSnapshot FleeResult + { + get; private set; + } + + private bool IsFleeWaiting(Actor actor) => _fleeStages.Values.Any(stage => stage.Actor == actor && !stage.Attempt); + + private bool IsFleeStageRun(ActionRun run) => run != null && _fleeStages.ContainsKey(run.Id); + + private bool IsInterruptedFleeRun(ActionRun run) => run != null && _fleeStages.TryGetValue(run.Id, out FleeStage stage) && stage.Interrupted; + + private bool IsFleeing(Actor actor) => actor.EnemyFleeing; + + private bool AllFleeOpponentsGone => !_actors.Any(actor => actor.Initial.Side == BattleSide.Enemy && actor.Alive && !actor.Escaped); + + private void StartFleeAction(Actor actor, ActionRun run) + { + var stage = new FleeStage { Session = this, Actor = actor, Run = run }; + if (!ScheduleFleeStage(stage)) + Cancel(actor, "original escape stage allocation failed"); + } + + private bool ScheduleFleeStage(FleeStage stage) + { + if (!_stage.TryAdd(stage.Actor.Initial.InstanceId, stage.Attempt ? "party flee" : "flee wait", stage, + BattleStageScheduler.TimeAt(SimulationTick), out BattleStageHandle handle, autoDelete: false)) + return false; + stage.Handle = handle; + stage.Run.StageHandle = handle; + _fleeStages[stage.Run.Id] = stage; + return true; + } + + private void PrepareFleeThreads() + { + foreach (FleeStage stage in _fleeStages.Values.ToArray()) + { + Actor actor = stage.Actor; + if (!stage.Attempt && !stage.WaitInitialized) + { + stage.WaitInitialized = true; + if (_fleeAlwaysSucceeds) + { + actor.Gauge = 0; + actor.CastGauge = FullCastGauge; + stage.Run.Casting = false; + } + } + if (!stage.Finished) + { + if (!stage.Attempt && Has(actor, BattleState.Forbidden) && !_fleeAlwaysSucceeds) + InterruptFleeWaiting(actor, "forbidden ended escape waiting"); + continue; + } + _stage.Cancel(stage.Handle); + _fleeStages.Remove(stage.Run.Id); + stage.Run.StageHandle = null; + if (stage.Attempt) + { + actor.Gauge = actor.CastGauge = 0; + if (stage.Running) + { + if (!_actors.Any(member => member.Initial.Side == actor.Initial.Side && member.Hp > 0)) + { + ReleaseRunningFleeBodies(stage); + CompleteFleeThread(stage); + continue; + } + _partyEscaped = true; + Add(BattleEventKind.Escaped, actor.Initial.InstanceId, actionId: stage.Run.Id, detail: "party escape run completed"); + End(BattleSessionStatus.Completed, null, "party escaped"); + return; + } + CompleteFleeThread(stage); + } + else if (AllFleeOpponentsGone) + CompleteFleeThread(stage); + else if (actor.CastGauge >= FullCastGauge || _fleeAlwaysSucceeds) + { + var attempt = new FleeStage { Session = this, Actor = actor, Run = stage.Run, Attempt = true }; + if (!ScheduleFleeStage(attempt)) + CompleteFleeThread(stage); + } + else + { + ShowFleeResult(actor, false); + CompleteFleeThread(stage); + } + } + } + + private void CompleteFleeThread(FleeStage stage) + { + if (stage.Actor.Run == stage.Run) + Finish(stage.Actor); + else + Add(BattleEventKind.ActionEnded, stage.Actor.Initial.InstanceId, actionId: stage.Run.Id); + } + + private bool AdvanceFleeStage(FleeStage stage, BattleStageContext context) + { + Actor actor = stage.Actor; + if (!stage.Grabbed) + { + if (!TryGrabStageBody(actor, context.Handle)) + return false; + stage.Grabbed = true; + } + if (!stage.Attempt) + { + if (!stage.BodyQueued && PhysicalBodyIdle(actor)) + { + QueueFleeBody(actor, BattlePhysicalBodyKind.FleeWait, stage.Run); + stage.BodyQueued = true; + } + if (!stage.BodyFinished) + return false; + } + else + { + if (!stage.Running) + { + if (AllFleeOpponentsGone) + { + // Native victory replaces the stage without rolling escape. + // Our outcome drain must first release this pending attempt. + ReleaseStageBody(actor, context.Handle); + return stage.Finished = true; + } + Actor[] opponents = _actors.Where(target => target.Initial.Side != actor.Initial.Side).ToArray(); + int chance = _effectRules.FleeSuccessPercent(actor.Level, EffectiveAttributes(actor)[6], + opponents.Select(target => target.Level).ToArray(), opponents.Select(target => EffectiveAttributes(target)[6]).ToArray()); + // Both published executables roll and show the result before checking for an idle + // body. A successful roll while busy leaves the attempt pending for the next pass. + bool success = _random.Probability(chance); + if (_fleeAlwaysSucceeds) + success = true; + if (_scenario.ScriptBattle) + success = false; + ShowFleeResult(actor, success); + if (!success) + { + ReleaseStageBody(actor, context.Handle); + return stage.Finished = true; + } + if (!PhysicalBodyIdle(actor)) + return false; + foreach (Actor ally in _actors.Where(value => value.Initial.Side == actor.Initial.Side && value.Alive).ToArray()) + { + if (ally != actor) + { + Cancel(ally, "successful party escape replaced the actor's system threads"); + foreach (FleeStage other in _fleeStages.Values.Where(value => value.Actor == ally).ToArray()) + _fleeStages.Remove(other.Run.Id); + foreach (BattleStageTaskSnapshot task in _stage.Snapshot().Where(task => task.Owner == ally.Initial.InstanceId)) + _stage.Cancel(task.Handle); + _bodyStageOwners.Remove(ally.Initial.InstanceId); + TryGrabStageBody(ally, context.Handle); + ally.Gauge = ally.CastGauge = 0; + } + ClearPhysicalBody(ally); + ally.Movement?.Stop(); + ally.Movement = null; + ally.MovementQueue.Clear(); + ally.HurtUntil = (int)SimulationTick; + ally.Ready = false; + if (_formationController == ally.Initial.InstanceId) + { + _formationController = null; + _formationInitialSlots = null; + } + QueueFleeBody(ally, BattlePhysicalBodyKind.Run, stage.Run); + } + stage.Running = true; + _fleeAtbPaused = true; + } + if (!PhysicalBodyIdle(actor)) + return false; + } + ReleaseStageBody(actor, context.Handle); + return stage.Finished = true; + } + + private void ShowFleeResult(Actor actor, bool success) + { + _stage.TryAdd(success ? "__party_flee_result" : actor.Initial.InstanceId, "flee result", + new FleeResultStage { Session = this, Actor = actor.Initial.InstanceId, Success = success }, + BattleStageScheduler.TimeAt(SimulationTick), out _); + Add(success ? BattleEventKind.Escaped : BattleEventKind.Miss, actor.Initial.InstanceId, + detail: success ? "party escape succeeded; run begins after the body becomes idle" : "escape failed"); + } + + private void InterruptFleeWaiting(Actor actor, string reason, int firstGauge = 0) + { + foreach (FleeStage stage in _fleeStages.Values.Where(value => value.Actor == actor && !value.Attempt)) + { + if (stage.Interrupted) + continue; + stage.Interrupted = true; + stage.Run.Casting = false; + Add(BattleEventKind.Interrupted, actor.Initial.InstanceId, actionId: stage.Run.Id, detail: reason); + } + actor.Gauge = firstGauge; + actor.CastGauge = 0; + actor.Ready = false; + } + + private void ResolveForceFlee(Actor source, Actor target) + { + if (_scenario.ScriptBattle) + { + ShowFleeResult(source, false); + return; + } + _fleeAlwaysSucceeds = true; + var run = new ActionRun + { + Id = ++_nextAction, + Kind = BattleAction.Flee, + Target = target.Initial.InstanceId, + SystemStarted = true, + CreatedTick = SimulationTick, + TimelineOriginTick = SimulationTick + }; + StartFleeAction(source, run); + } + + private void StartEnemyFlee(Actor actor) + { + actor.EnemyFleeing = true; + actor.Ready = false; + _stage.TryAdd(actor.Initial.InstanceId, "enemy flee", new EnemyFleeStage { Session = this, Actor = actor }, + BattleStageScheduler.TimeAt(SimulationTick), out _); + } + + private void QueueFleeBody(Actor actor, BattlePhysicalBodyKind kind, ActionRun run) + { + if (_catalog is IBattlePhysicalTimings) + QueuePhysicalTask(actor, new PhysicalBodyTask + { + Kind = kind, + Run = run, + Destination = kind == BattlePhysicalBodyKind.EnemyFlee ? new BattleMovementPoint(800, 0, 800) : new BattleMovementPoint(-800, 0, -800) + }); + else + _fallbackFleeBodies[actor.Initial.InstanceId] = kind; + } + + private void AdvanceFleeBody(Actor actor, PhysicalBodyState body, PhysicalBodyTask task) + { + if (task.Kind == BattlePhysicalBodyKind.FleeWait) + { + if (!task.Executed) + { + body.BladeSeconds = .01f; + body.Pose = BattlePose.Fleeing; + TryPlayBodyAnimation(actor, body.Profile.Animation(body.Pose), true, body.Pose, 48); + task.Executed = true; + return; + } + if (!actor.Alive || actor.CastGauge >= FullCastGauge || !task.Run.Casting || AllFleeOpponentsGone) + { + task.Finished = true; + if (_fleeStages.TryGetValue(task.Run.Id, out FleeStage stage)) + stage.BodyFinished = true; + } + return; + } + if (!task.Executed) + { + actor.Movement = new BattleMovement(_scenario.Variant, new BattleMovementPlan(BattleMovementKind.EnemyFlee, actor.Position, task.Destination)); + body.Pose = BattlePose.Moving; + TryPlayBodyAnimation(actor, body.Profile.Animation(body.Pose), true, body.Pose, 52); + task.Executed = true; + Add(BattleEventKind.MovementStarted, actor.Initial.InstanceId, detail: "enemy escape walk"); + } + AdvanceBodyMovement(actor, actor.Alive); + actor.Position = actor.Movement.Position; + if (actor.Movement.FacingDegrees is { } facing) + actor.FacingDegrees = facing; + if (task.Finished = actor.Movement.Finished) + CompleteEnemyFlee(actor); + } + + private bool AdvanceFallbackFleeBody(Actor actor) + { + if (!_fallbackFleeBodies.TryGetValue(actor.Initial.InstanceId, out BattlePhysicalBodyKind kind)) + return false; + FleeStage stage = _fleeStages.Values.FirstOrDefault(value => value.Actor == actor); + if (kind == BattlePhysicalBodyKind.FleeWait) + { + if (stage == null) + _fallbackFleeBodies.Remove(actor.Initial.InstanceId); + else if (!stage.FallbackBodyStarted) + stage.FallbackBodyStarted = true; + else if (!actor.Alive || actor.CastGauge >= FullCastGauge || !stage.Run.Casting || AllFleeOpponentsGone) + { + stage.BodyFinished = true; + _fallbackFleeBodies.Remove(actor.Initial.InstanceId); + } + return true; + } + actor.Movement ??= new BattleMovement(_scenario.Variant, new BattleMovementPlan( + kind == BattlePhysicalBodyKind.EnemyFlee ? BattleMovementKind.EnemyFlee : BattleMovementKind.Run, + actor.Position, kind == BattlePhysicalBodyKind.EnemyFlee ? new BattleMovementPoint(800, 0, 800) : new BattleMovementPoint(-800, 0, -800))); + AdvanceBodyMovement(actor, actor.Alive); + actor.Position = actor.Movement.Position; + actor.FacingDegrees = actor.Movement.FacingDegrees ?? actor.FacingDegrees; + if (actor.Movement.Finished) + { + actor.Movement = null; + _fallbackFleeBodies.Remove(actor.Initial.InstanceId); + if (kind == BattlePhysicalBodyKind.EnemyFlee) + CompleteEnemyFlee(actor); + } + return true; + } + + private void CompleteEnemyFlee(Actor actor) + { + if (!actor.Alive) + return; + actor.Escaped = true; + actor.Gauge = actor.CastGauge = 0; + actor.Ready = false; + if (_scenario.Variant == "PAL3A") + { + RequestRoleEnd(actor); + actor.ModelAlive = false; + } + Add(BattleEventKind.Escaped, actor.Initial.InstanceId, detail: "original enemy escape walk reached its destination"); + Add(BattleEventKind.MovementEnded, actor.Initial.InstanceId); + } + + private void CancelFleeStage(ActionRun run) + { + if (run == null || !_fleeStages.Remove(run.Id, out FleeStage stage)) + return; + _fallbackFleeBodies.Remove(stage.Actor.Initial.InstanceId); + if (stage.Running) + ReleaseRunningFleeBodies(stage); + } + + private void ReleaseRunningFleeBodies(FleeStage stage) + { + foreach (Actor actor in _actors.Where(actor => OwnsStageBody(actor, stage.Handle))) + { + _fallbackFleeBodies.Remove(actor.Initial.InstanceId); + ReleaseStageBody(actor, stage.Handle); + actor.Movement?.Stop(); + actor.Movement = null; + actor.MovementQueue.Clear(); + } + _fleeAtbPaused = _fleeStages.Values.Any(other => other.Running && _stage.IsActive(other.Handle)); + } + + private void StopFleeStages() + { + foreach (FleeStage stage in _fleeStages.Values.ToArray()) + CancelFleeStage(stage.Run); + _fleeStages.Clear(); + _fallbackFleeBodies.Clear(); + _fleeAtbPaused = false; + FleeResult = null; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Flee.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Flee.cs.meta new file mode 100644 index 00000000..9a8d7d7a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Flee.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a640d3bcc3194d0b84a1cacd7aae2923 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Formation.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Formation.cs new file mode 100644 index 00000000..38067c6e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Formation.cs @@ -0,0 +1,311 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private string _formationController; + private Dictionary _formationInitialSlots; + + public string ActiveFormationController => _formationController; + + public string CanBeginFormation(string controller) + { + if (Status != BattleSessionStatus.Running) + return "The battle has ended."; + if (Definitions == null || _catalog is not IBattleStageGeometry) + return "This combat catalog has no verified formation movement plans."; + if (_formationController != null) + return "A formation panel is already open."; + if (WaitingActor != controller || !_byId.TryGetValue(controller ?? "", out Actor actor) || actor.Initial.Side != BattleSide.Ally) + return "Choose the current ready allied controller."; + Actor[] allies = _actors.Where(value => value.Initial.Side == BattleSide.Ally).ToArray(); + if (allies.Any(value => value.Definition.Identity is < 0 or > 4) || allies.GroupBy(value => value.Definition.Identity).Any(group => group.Count() > 1)) + return "Original formations require distinct original player identities."; + return FormationRules().CanChangeLineup(FormationActors()).FailureReason; + } + + public bool BeginFormation(string controller) + { + if (CanBeginFormation(controller) != null) + return false; + _formationController = controller; + _formationInitialSlots = _actors.Where(actor => actor.Initial.Side == BattleSide.Ally) + .ToDictionary(actor => actor.Initial.InstanceId, actor => actor.Slot, StringComparer.Ordinal); + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.BeginFormation, Actor = controller }); + Add(BattleEventKind.FormationOpened, controller); + return true; + } + + public string CanSwapFormation(string actorId, BattleSlot destination) + { + if (Status != BattleSessionStatus.Running || _formationController == null) + return "Open the formation panel first."; + if (IsBattleInputSuspended) + return "The battle movie is playing or its frame is resuming."; + if (!Enum.IsDefined(typeof(BattleSlot), destination)) + return "Unknown formation slot."; + if (!_byId.TryGetValue(actorId ?? "", out Actor actor) || actor.Initial.Side != BattleSide.Ally) + return "Only an allied participant can change formation."; + string denied = FormationRules().CanMove(FormationActor(actor)).FailureReason; + if (denied != null) + return denied; + Actor other = _actors.FirstOrDefault(value => value.Initial.Side == BattleSide.Ally && value.Slot == destination && value != actor); + if (other != null) + return FormationRules().CanMove(FormationActor(other)).FailureReason; + return null; + } + + public bool SwapFormation(string actorId, BattleSlot destination) + { + if (CanSwapFormation(actorId, destination) != null) + return false; + Actor actor = _byId[actorId]; + if (actor.Slot == destination) + return false; + Actor other = _actors.FirstOrDefault(value => value.Initial.Side == BattleSide.Ally && value.Slot == destination && value != actor); + var geometry = (IBattleStageGeometry)_catalog; + bool crossing = _scenario.Variant == "PAL3" && other != null && + (actor.Definition.Identity == 0 && other.Definition.Identity == 4 || actor.Definition.Identity == 4 && other.Definition.Identity == 0); + BattleMovementPoint sourceHome = actor.Home; + BattleMovementPoint destinationHome = other?.Home ?? geometry.FormationHome(actorId, destination); + // Compile both sides before changing slots, queues, logs or resource values. + BattleMovementPlan[] first = ValidateMovementPlans(geometry.PlanFormationMove(actorId, sourceHome, destinationHome, crossing), sourceHome, destinationHome); + BattleMovementPlan[] second = other == null ? null : ValidateMovementPlans(geometry.PlanFormationMove(other.Initial.InstanceId, other.Home, sourceHome, crossing), other.Home, sourceHome); + BattleSlot previous = actor.Slot; + actor.Slot = destination; + actor.Home = destinationHome; + QueueFormationMoves(actor, first); + if (other != null) + { + other.Slot = previous; + other.Home = sourceHome; + QueueFormationMoves(other, second); + } + _inputs.Add(new BattleInput + { + Tick = Tick, + Kind = BattleInputKind.SwapFormation, + Actor = actorId, + Target = _formationController, + FormationSlot = destination + }); + Add(BattleEventKind.FormationChanged, actorId, other?.Initial.InstanceId, + detail: previous + " -> " + destination + "; slot/home changed immediately; gauges unchanged"); + return true; + } + + public bool EndFormation(string controller) + { + if (_formationController == null || controller != _formationController || Status != BattleSessionStatus.Running || IsBattleInputSuspended) + return false; + bool changed = _actors.Any(actor => actor.Initial.Side == BattleSide.Ally && + _formationInitialSlots.TryGetValue(actor.Initial.InstanceId, out BattleSlot original) && original != actor.Slot); + ReleaseFormationBodies(); + if (changed) + { + Actor actor = _byId[controller]; + AdvanceFiveSpiritFieldTurn(actor); + actor.Gauge = actor.CastGauge = 0; + actor.Ready = false; + } + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.EndFormation, Actor = controller }); + _formationController = null; + _formationInitialSlots = null; + Add(BattleEventKind.FormationClosed, controller, + detail: changed ? "changed lineup: controller gauges cleared" : "original lineup restored: no gauge cost"); + return true; + } + + private BattleFormationRules FormationRules() => new(_scenario.Variant); + + private BattleFormationActor FormationActor(Actor actor) + { + int index = NativeActorIndex(actor); + int weapon = actor.Definition.Equipment.FirstOrDefault(item => item.Slot == 0)?.WeaponType ?? 0; + return new BattleFormationActor(index, actor.Initial.ActorId, actor.Slot, weapon, + alive: actor.Alive, hp: actor.Hp, maxHp: actor.Attributes[0], states: actor.States.Keys, + taskCount: StageTaskCount(actor), + atHome: IsAtHome(actor), idle: actor.Run == null && ActionBodyIdle(actor), + fled: actor.Escaped, transformed: IsPal3ATransformed(actor.Initial.InstanceId)); + } + + private IReadOnlyList FormationActors() => + Array.AsReadOnly(_actors.Select(FormationActor).ToArray()); + + private BattleMovementPlan[] ValidateMovementPlans(IReadOnlyList plans, BattleMovementPoint from, BattleMovementPoint to) + { + if (plans == null || plans.Count == 0 || plans.Any(plan => plan == null)) + throw new InvalidOperationException("The formation has no complete verified movement plan."); + BattleMovementPoint previous = from; + foreach (BattleMovementPlan plan in plans) + { + if (!SamePoint(plan.From, previous)) + throw new InvalidOperationException("Formation movement segments must form a continuous path."); + _ = new BattleMovement(_scenario.Variant, plan); + previous = plan.To; + } + if (!SamePoint(previous, to)) + throw new InvalidOperationException("The movement plan does not finish at the new home."); + return plans.ToArray(); + } + + private static bool HasFormationMovement(Actor actor) => actor.Movement?.Finished == false || actor.MovementQueue.Count > 0; + + private void QueueFormationMoves(Actor actor, IEnumerable plans) + { + foreach (BattleMovementPlan plan in plans) + actor.MovementQueue.Enqueue(plan); + if (actor.Movement == null || actor.Movement.Finished) + StartNextFormationMovement(actor); + } + + private void StartNextFormationMovement(Actor actor) + { + BattleMovementPlan queued = actor.MovementQueue.Dequeue(); + float opacity = Has(actor, BattleState.Invisible) ? 0.44f : 1f; + var plan = new BattleMovementPlan(queued.Kind, queued.From, queued.To, + queued.FlyUpTick, queued.FlyDownTick, queued.OverTick, + targetBlend: opacity, initialBlend: actor.Movement?.Blend ?? opacity); + actor.Movement = new BattleMovement(_scenario.Variant, plan); + Add(BattleEventKind.MovementStarted, actor.Initial.InstanceId, detail: actor.Movement.Plan.Kind.ToString()); + } + + private void AdvanceFormationMovements() + { + foreach (Actor actor in _actors) + AdvanceFormationMovement(actor); + } + + private void AdvanceFormationMovement(Actor actor) + { + if (actor.Movement == null || _fallbackFleeBodies.ContainsKey(actor.Initial.InstanceId) || PhysicalBodyBusy(actor) || IsActorExternallyControlled(actor.Initial.InstanceId) || SimulationTick < actor.HurtUntil) + return; + bool wasFinished = actor.Movement.Finished; + if (_catalog is IBattlePhysicalTimings) + { + if (!TryStartAbilityMovementBody(actor)) + EnsureMovementBodyAnimation(actor); + AdvanceBodyMovement(actor, actor.Alive && !actor.Escaped, CurrentBodyMovementMessage(actor)); + } + else + AdvanceBodyMovement(actor, actor.Alive && !actor.Escaped); + actor.Position = actor.Movement.Position; + if (actor.Movement.FacingDegrees is { } facing) + actor.FacingDegrees = facing; + if (!wasFinished && actor.Movement.Finished) + Add(BattleEventKind.MovementEnded, actor.Initial.InstanceId); + if (!actor.Movement.Finished) + return; + if (actor.MovementQueue.Count > 0) + StartNextFormationMovement(actor); + else + actor.Movement = null; + } + + private static bool SamePoint(BattleMovementPoint first, BattleMovementPoint second) => + first.X == second.X && first.Y == second.Y && first.Z == second.Z; + + private void ReleaseUnavailableFormationController() + { + if (_formationController == null) + return; + Actor controller = _byId[_formationController]; + if (controller.Hp > 0 && !controller.Escaped && !IsUncontrollable(controller)) + return; + string owner = _formationController; + ReleaseFormationBodies(); + _formationController = null; + _formationInitialSlots = null; + Add(BattleEventKind.FormationClosed, owner, detail: "controller unavailable; existing lineup changes retained"); + } + + private static bool IsWithinHome(BattleMovementPoint position, BattleMovementPoint home) + { + double x = position.X - home.X, y = position.Y - home.Y, z = position.Z - home.Z; + return x * x + y * y + z * z <= 13d * 13d; + } + + private void ReleaseFormationBodies() + { + var geometry = (IBattleStageGeometry)_catalog; + // Validate every return before releasing any body ownership. + var returns = _actors.Where(actor => actor.Initial.Side == BattleSide.Ally) + .OrderBy(NativeActorIndex).Select(actor => (Actor: actor, + Moves: IsWithinHome(actor.Position, actor.Home) ? null : + ValidateMovementPlans(geometry.PlanFormationMove(actor.Initial.InstanceId, actor.Position, actor.Home, false), actor.Position, actor.Home))) + .ToArray(); + foreach (var (actor, moves) in returns) + { + ClearPhysicalBody(actor); + actor.Movement?.Stop(); + actor.Movement = null; + actor.MovementQueue.Clear(); + actor.HurtUntil = (int)SimulationTick; + if (moves != null && QueueReturnHomeStage(actor)) + QueueFormationMoves(actor, moves); + } + } + + private static BattleMovementPoint Interpolate(BattleMovementPoint from, BattleMovementPoint to, float amount) => + new(from.X + (to.X - from.X) * amount, from.Y + (to.Y - from.Y) * amount, from.Z + (to.Z - from.Z) * amount); + + private static void ResetActorFacing(Actor actor) + { + actor.FacingDegrees = BattleFacingRules.Initial(actor.Initial.Side); + actor.Movement?.SetHeading(actor.FacingDegrees); + } + + private static void SetActorPosition(Actor actor, BattleMovementPoint position) + { + actor.Position = position; + actor.Movement?.Relocate(position); + } + + private void UpdateAttackPosition(Actor actor, ActionRun run) + { + if (run.Kind != BattleAction.Attack || run.AttackPlan == null) + return; + BattleAttackPlan plan = run.AttackPlan; + int elapsed = run.Elapsed - run.Timing.PreparationTicks; + int travel = run.Timing.TravelTicks; + if (elapsed == 1 && travel > 0) + actor.FacingDegrees = BattleMovement.FacingBetween(plan.Origin, plan.Approach); + if (elapsed == travel + run.Timing.AnimationTicks && !IsWithinHome(actor.Position, actor.Home)) + actor.FacingDegrees = BattleMovement.FacingBetween(actor.Position, actor.Home); + BattleMovementPoint sample; + if (elapsed <= travel) + sample = Interpolate(plan.Origin, plan.Approach, travel == 0 ? 1f : Math.Clamp(elapsed / (float)travel, 0f, 1f)); + else if (elapsed >= travel + run.Timing.AnimationTicks) + sample = Interpolate(plan.Approach, actor.Home, travel == 0 ? 1f : Math.Clamp((elapsed - travel - run.Timing.AnimationTicks) / (float)travel, 0f, 1f)); + else + return; + SetActorPosition(actor, new BattleMovementPoint(actor.Position.X + sample.X - run.LastAttackSample.X, + actor.Position.Y + sample.Y - run.LastAttackSample.Y, actor.Position.Z + sample.Z - run.LastAttackSample.Z)); + run.LastAttackSample = sample; + } + + private void StopFormationMovements() + { + _formationController = null; + _formationInitialSlots = null; + foreach (Actor actor in _actors) + { + actor.MovementQueue.Clear(); + // Preserve the final visual position; no queued task runs after termination. + actor.Movement?.Stop(); + } + } + + private BattleAttackPlan PlanAttack(Actor source, Actor target) => _catalog is IBattleStageGeometry geometry + ? geometry.PlanAttack(source.Initial.InstanceId, target.Initial.InstanceId, source.Home, target.Home) + : new BattleAttackPlan(_catalog.Attack(source.Initial.InstanceId, target.Initial.InstanceId), source.Home, source.Home, target.Home); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Formation.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Formation.cs.meta new file mode 100644 index 00000000..3d743dc5 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Formation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fdf773faed704db38b1ccca4aefb0d6b diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HitFeedback.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HitFeedback.cs new file mode 100644 index 00000000..0e7622bf --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HitFeedback.cs @@ -0,0 +1,35 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private readonly List<(long Id, string Actor, BattleMovementPoint Position, long Tick)> _hitFlashes = new(); + private long _nextHitFlash; + + public IReadOnlyList HitFlashes => Array.AsReadOnly(_hitFlashes + .Select(flash => new BattleHitFlashSnapshot(flash.Id, flash.Actor, flash.Position, + BattleHitFlashSnapshot.FrameAt(SimulationTick - flash.Tick))) + .Where(flash => flash.Frame is >= 0 and < BattleHitFlashSnapshot.FrameCount).ToArray()); + + private void ShowOriginalHitFlash(Actor actor) + { + // ProcBlock emits on enemy roles even when Stable retains the old + // animation. ProcDodge and party blocks never create this quad. + if (actor.Initial.Side != BattleSide.Enemy) + return; + _hitFlashes.RemoveAll(flash => BattleHitFlashSnapshot.FrameAt(SimulationTick - flash.Tick) >= BattleHitFlashSnapshot.FrameCount); + if (_hitFlashes.Count >= 2047) + return; // CEffect::CreateOnePartical reserves the final quad slot. + _hitFlashes.Add((++_nextHitFlash, actor.Initial.InstanceId, + new BattleMovementPoint(actor.Position.X, 20, actor.Position.Z), SimulationTick)); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HitFeedback.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HitFeedback.cs.meta new file mode 100644 index 00000000..d4d1a83e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HitFeedback.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: db72c854e5cf4fd5817baf618b0000ae diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudControl.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudControl.cs new file mode 100644 index 00000000..1ea43c11 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudControl.cs @@ -0,0 +1,39 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public sealed partial class BattleSession + { + // Native panel confirmation is distinct from the free debugger setter. + // One recorded input owns both the profile write and its gauge cost. + public bool CommitAiControl(string controller, int flags) + { + if (flags is < 0 or > 63) + throw new ArgumentOutOfRangeException(nameof(flags)); + if (!CanRequestAiInput(controller, out Actor actor) || IsPal3ATransformed(controller)) + return false; + int before = GetAiProfile(controller); + if (before == flags) + return true; + ApplyAiProfile(actor, flags); + bool consumes = BattleAiControlRules.ConsumesGauges(before, flags); + if (consumes) + { + // Native SetToStart writes these slots and second-running only; + // it does not change the role's guard, pose, rounds or resources. + AdvanceFiveSpiritFieldTurn(actor); + actor.Gauge = actor.CastGauge = 0; + actor.Ready = false; + } + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.AiControl, Actor = controller, AiFlags = flags }); + Add(BattleEventKind.ControlChanged, controller, detail: "original AI control flags " + flags + + (consumes ? "; controller gauges cleared" : "; gauges retained")); + return true; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudControl.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudControl.cs.meta new file mode 100644 index 00000000..35c5f140 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudControl.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fa831935671640358005956291d4fc85 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudQueries.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudQueries.cs new file mode 100644 index 00000000..69136517 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudQueries.cs @@ -0,0 +1,134 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + public bool HasActiveState(string actorId, BattleState state) => actorId != null && _byId.TryGetValue(actorId, out Actor actor) && + actor.States.TryGetValue(state, out BattleStatusInstance status) && status.LatentRounds == 0; + + public BattleTargetRange GetActionTargetRange(BattleCommand command) + { + if (command.Actor == null || !_byId.TryGetValue(command.Actor, out Actor source) || + command.Action is not (BattleAction.Attack or BattleAction.Skill or BattleAction.Item)) + return BattleTargetRange.None; + BattleAbilityDefinition ability = Ability(command); + if (command.Action is BattleAction.Skill or BattleAction.Item && ability == null) + return BattleTargetRange.None; + return ActionRange(source, ability); + } + + public string GetDefaultTarget(BattleCommand command) + { + var candidates = GetTargetCandidates(command); + if (candidates.Count == 0) + return null; + BattleTargetRange range = GetActionTargetRange(command); + if (range is BattleTargetRange.OwnSingle or BattleTargetRange.OwnAll) + { + BattleAbilityDefinition ability = Ability(command); + if (ability != null) + { + var cure = candidates.FirstOrDefault(actor => ability.States.Any(effect => effect.Remove && AiBadState(effect.State) && + (effect.State == BattleState.Death ? !actor.Alive : Has(_byId[actor.Id], effect.State)))); + if (cure != null) + return cure.Id; + if (ability.IsItem && ability.ItemType == 1 && RecoversResource(ability, 2) && !RecoversResource(ability, 0)) + { + string lowestMp = LowestResourceTarget(candidates, mp: true); + if (lowestMp != null) + return lowestMp; + } + } + } + else if (candidates[0].Side == BattleSide.Enemy) + { + int preferred = -1; + if (range == BattleTargetRange.OpponentSingle) + preferred = FirstEnemyToReachCommand(); + else if (range is BattleTargetRange.OpponentRow or BattleTargetRange.OpponentColumn) + preferred = BattleTargetRules.BestEnemyLine(range == BattleTargetRange.OpponentRow, index => + { + Actor actor = ActorAtNativeIndex(index); + return actor != null && actor.Hp > 0 && !actor.Escaped && !IsFleeing(actor) && + (_scenario.Variant == "PAL3A" || !Has(actor, BattleState.Invisible)); + }); + var selected = candidates.FirstOrDefault(actor => actor.NativeIndex == preferred); + if (selected != null) + return selected.Id; + } + return LowestResourceTarget(candidates, mp: false) ?? candidates[0].Id; + } + + private static bool RecoversResource(BattleAbilityDefinition ability, int resource) => ability.Attributes.Any(effect => + effect.Attribute == resource && (effect.Mode == BattleValueMode.RecoverToMax || + effect.Mode is BattleValueMode.Absolute or BattleValueMode.Percentage && effect.Value > 0)); + + private static string LowestResourceTarget(IReadOnlyList candidates, bool mp) + { + float lowest = 1f; + string best = null; + foreach (BattleActorSnapshot actor in candidates) + { + if (!actor.Alive) + continue; + // The original compares its x87 division to the previous single-precision minimum. + double ratio = mp ? actor.Mp / (double)actor.MaxMp : actor.Hp / (double)actor.MaxHp; + if (!(mp ? ratio >= lowest : ratio > lowest)) + { + lowest = (float)ratio; + best = actor.Id; + } + } + return best; + } + + private int FirstEnemyToReachCommand() + { + float shortest = 100000000f; + int best = -1; + foreach (Actor actor in _actors.Where(actor => actor.Initial.Side == BattleSide.Enemy).OrderBy(NativeActorIndex)) + { + if (actor.Hp <= 0 || actor.Escaped || IsFleeing(actor)) + continue; + bool casting = actor.Run?.SystemStarted == true && CanInterruptCast(actor); + int speed = casting ? actor.CastSpeed : _rules.GaugePerStep(RuleParticipant(actor)); + int firstGauge = actor.Run is { SystemStarted: false } ? FullGauge : actor.Gauge; + double time = casting ? (FullCastGauge - actor.CastGauge) / (50.0 * speed) : + (FullGauge - firstGauge) / (50.0 * speed) + 10000.0; + if (!(time >= shortest)) + { + shortest = (float)time; + best = NativeActorIndex(actor); + } + } + return best; + } + + // This is a potential area preview. Protection, random hit routing, and + // original AI repetition are resolved only when the command executes. + public IReadOnlyList GetPotentialAffectedTargets(BattleCommand command) + { + BattleTargetRange range = GetActionTargetRange(command); + if (range == BattleTargetRange.None) + return Array.Empty(); + IReadOnlyList candidates = GetTargetCandidates(command); + if (range is BattleTargetRange.OwnAll or BattleTargetRange.OpponentAll) + return candidates; + BattleActorSnapshot anchor = candidates.FirstOrDefault(actor => actor.Id == command.Target); + if (anchor == null) + return Array.Empty(); + if (range is BattleTargetRange.OpponentRow or BattleTargetRange.OpponentColumn) + return Array.AsReadOnly(candidates.Where(actor => BattleTargetRules.Aligned(anchor.Side, + anchor.Slot, actor.Slot, range == BattleTargetRange.OpponentRow, _scenario.SceneElement)).ToArray()); + return Array.AsReadOnly(new[] { anchor }); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudQueries.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudQueries.cs.meta new file mode 100644 index 00000000..e9a51d44 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.HudQueries.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 891c29c991124299868c2fbd267e5035 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Identity.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Identity.cs new file mode 100644 index 00000000..97cf58da --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Identity.cs @@ -0,0 +1,51 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private bool AutomaticMatches(BattleSide side, bool enabled) + { + if (Definitions == null) + return true; + InitializeAi(); + int first = side == BattleSide.Ally ? 0 : 5; + int count = side == BattleSide.Ally ? 5 : 6; + return Enumerable.Range(first, count).All(index => + { + BattleAiProfile profile = _ai.Roles[index].Profile; + return profile.Enabled == enabled && profile.Attack == enabled && profile.Magic == enabled && + profile.Skill == enabled && profile.Item == enabled; + }); + } + + private void AssignNativeActorIndices() + { + Actor[] allies = _actors.Where(actor => actor.Initial.Side == BattleSide.Ally).ToArray(); + var reserved = new HashSet(); + // Known original identities keep their exact native slots. Custom + // fixtures may use other actors; assign them only the unreserved + // player slots, independently of resource identity and formation. + foreach (var group in allies.Where(actor => actor.Definition?.Identity is >= 0 and < 5) + .GroupBy(actor => actor.Definition.Identity).Where(group => group.Count() == 1)) + { + group.Single().NativeIndex = group.Key; + reserved.Add(group.Key); + } + foreach (Actor actor in allies.Where(actor => actor.NativeIndex < 0)) + { + actor.NativeIndex = Enumerable.Range(0, 5).First(index => !reserved.Contains(index)); + reserved.Add(actor.NativeIndex); + } + foreach (Actor actor in _actors.Where(actor => actor.Initial.Side == BattleSide.Enemy)) + actor.NativeIndex = 5 + (int)actor.Initial.Slot; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Identity.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Identity.cs.meta new file mode 100644 index 00000000..29c97e8a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Identity.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 34060715e56a4e2fb0e303e2c8143424 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.MagicSword.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.MagicSword.cs new file mode 100644 index 00000000..646342e4 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.MagicSword.cs @@ -0,0 +1,264 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + + public sealed partial class BattleSession + { + private readonly Dictionary _magicSwords = new(StringComparer.Ordinal); + + public IReadOnlyDictionary MagicSwords => + new ReadOnlyDictionary(_magicSwords.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.Ordinal)); + + public int MagicSwordAbilityId(string actor) => actor != null && _magicSwords.TryGetValue(actor, out BattleMagicSwordSnapshot snapshot) ? snapshot.SkillId : 0; + + private static bool IsMagicSwordAbility(BattleAbilityDefinition ability) => ability is { IsItem: false, SkillTypeId: 4 }; + + private void InitializeActorMagicSword(Actor actor) + { + BattleMagicSwordSnapshot captured = actor.Definition?.MagicSword; + BattleMagicSword authored = actor.Initial.MagicSword; + if (captured == null && authored == null) + return; + if (Definitions?.Variant != "PAL3" || actor.Initial.Side != BattleSide.Ally || actor.Definition?.Identity != 0 || + !actor.Definition.Equipment.Any(item => item.Slot == 0 && item.Id == BattleMagicSwordRules.WeaponId) || + captured == null || authored == null) + throw new ArgumentException("A magic sword needs PAL3 Jingtian, weapon 6603 and matching captured cultivation."); + BattleMagicSwordSnapshot initial = authored.Capture(); + if (captured.AttackBonus != initial.AttackBonus || captured.SelectedElement != initial.SelectedElement || + captured.PurificationCount != initial.PurificationCount || captured.SkillId != initial.SkillId || + captured.ChargeCoefficient != initial.ChargeCoefficient || captured.Energy != initial.Energy) + throw new ArgumentException("Magic sword definitions do not match the captured scenario."); + if (captured.SkillId != 0 && (!Definitions.Skills.TryGetValue(captured.SkillId, out BattleAbilityDefinition ability) || + !IsMagicSwordAbility(ability) || !BattleMagicSwordRules.IsSupportedSkill(ability.Id) || !ability.Supported)) + throw new NotSupportedException("The captured magic sword has no verified original weapon skill record."); + _magicSwords.Add(actor.Initial.InstanceId, initial); + } + + private BattleMagicSwordSnapshot CaptureMagicSword(Actor actor) => _magicSwords.GetValueOrDefault(actor.Initial.InstanceId); + + private string ValidateMagicSwordCommand(Actor actor, BattleAbilityDefinition ability) + { + BattleMagicSwordSnapshot snapshot = CaptureMagicSword(actor); + if (Definitions?.Variant != "PAL3" || snapshot == null || !BattleMagicSwordRules.IsSupportedSkill(ability.Id) || + snapshot.SkillId != ability.Id || actor.Definition?.Identity != 0) + return "This actor has no captured magic sword with the selected weapon skill."; + if (!BattleMagicSwordRules.IsReady(snapshot, actor.Definition.Identity, true)) + return "The magic sword energy must be greater than 199.9."; + return null; + } + + private void GainMagicSwordOnPhysicalWork(Actor actor, long actionId) + { + BattleMagicSwordSnapshot snapshot = CaptureMagicSword(actor); + if (snapshot == null) + return; + _magicSwords[actor.Initial.InstanceId] = BattleMagicSwordRules.GainOnPhysicalWork(snapshot, actor.Definition.Identity, true); + } + + // Called on the native system-thread first pass, before stage waits or target effects. + private void StartMagicSwordAction(Actor actor, ActionRun run) + { + if (!IsMagicSwordAbility(run.Ability)) + return; + BattleMagicSwordSnapshot snapshot = CaptureMagicSword(actor) ?? throw new InvalidOperationException("Missing magic sword state."); + run.Targets = FightSkillRange(actor, run.Ability.Range).Select(target => target.Initial.InstanceId).ToArray(); + _magicSwords[actor.Initial.InstanceId] = BattleMagicSwordRules.ConsumeEnergy(snapshot); + } + + private sealed class MagicSwordStageRun + { + public BattleMagicSwordStageProfile Profile; + public string Actor; + public float NameStarted, ActStarted; + public bool NameShown, FirstStarted, SecondStarted, Worked; + public bool UsesBodyBinding, BodyExecuted, BodyFinished; + public BattlePhysicalAnimation BodyRequested; + public long FirstHandle, SecondHandle; + } + + private readonly Dictionary _magicSwordStages = new(); + + private bool AdvanceMagicSwordStage(Actor actor, ActionRun run, BattleStageContext context) + { + if (!_magicSwordStages.TryGetValue(run.Id, out MagicSwordStageRun stage)) + { + if (_catalog is not IBattleMagicSwordTimings timings || _effects == null) + throw new NotSupportedException("The magic sword needs its original effect completion director."); + stage = new MagicSwordStageRun { Actor = actor.Initial.InstanceId, Profile = timings.MagicSword(actor.Initial.InstanceId, run.Ability) }; + if (_catalog is IBattleAbilityBodyAnimations bodies) + { + stage.UsesBodyBinding = true; + stage.BodyRequested = bodies.AbilityBody(actor.Initial.InstanceId, run.Ability); + } + _magicSwordStages.Add(run.Id, stage); + } + if (run.EndRequested || actor.Escaped || !actor.Alive) + { + ReleaseStageBody(actor, context.Handle); + CancelMagicSwordStage(run); + return true; + } + if (!stage.NameShown) + { + if (HasFormationMovement(actor) || PhysicalBodyBusy(actor) || IsActorExternallyControlled(actor.Initial.InstanceId) || context.Tick < actor.HurtUntil || + !TryGrabStageBody(actor, context.Handle)) + return false; + stage.NameShown = true; + stage.NameStarted = context.Time; + ShowStageMessage(stage, actor.Initial.Side, run.Ability.Name, handle: context.Handle); + return false; + } + if ((double)context.Time - stage.NameStarted > BattleMagicSwordStageProfile.NameDelaySeconds) + HideStageMessage(stage); + if (!run.StageStarted) + { + if (context.Time <= stage.NameStarted || + HasFormationMovement(actor) || PhysicalBodyBusy(actor) || IsActorExternallyControlled(actor.Initial.InstanceId) || context.Tick < actor.HurtUntil) + return false; + run.StageStarted = true; + run.BodyElapsed = 0; + run.BodyRestartPending = true; + stage.ActStarted = context.Time; + } + double elapsed = (double)context.Time - stage.ActStarted; + if (!stage.FirstStarted && elapsed >= stage.Profile.FirstWaitSeconds) + { + if (_absoluteTimeActor != null && _absoluteTimeActor != actor.Initial.InstanceId) + return false; + stage.FirstHandle = StartMagicSwordGroup(stage.Profile.FirstGroupId, stage.Profile.FirstOrigin, actor, run); + stage.FirstStarted = true; + _absoluteTimeActor = actor.Initial.InstanceId; + } + if (!stage.SecondStarted && elapsed >= stage.Profile.SecondWaitSeconds) + { + stage.SecondHandle = StartMagicSwordGroup(stage.Profile.SecondGroupId, stage.Profile.SecondOrigin, actor, run); + stage.SecondStarted = true; + } + if (!stage.Worked && stage.FirstStarted && (stage.FirstHandle == 0 || !_effects.IsRunning(stage.FirstHandle))) + { + _absoluteTimeActor = null; + stage.Worked = true; + ResolveActionMarker(actor, run); + if (actor.Run != run || Status != BattleSessionStatus.Running) + return true; + } + if (!stage.Worked || (stage.UsesBodyBinding ? !stage.BodyFinished : run.BodyElapsed < stage.Profile.BodyAnimationTicks) || + PhysicalBodyBusy(actor) || IsActorExternallyControlled(actor.Initial.InstanceId) || context.Tick < actor.HurtUntil || HasFormationMovement(actor)) + return false; + // ShowName is parallel: Act starts one tick later, while the whole + // stage keeps its name subtask until the strict one-second boundary. + if ((double)context.Time - stage.NameStarted <= BattleMagicSwordStageProfile.NameDelaySeconds) + return false; + // Group 2 belongs to the ATS effect manager and may outlive the role/stage task. + _magicSwordStages.Remove(run.Id); + HideStageMessage(stage); + ReleaseStageBody(actor, context.Handle); + return true; + } + + private bool TryAdvanceMagicSwordBody(Actor actor, ActionRun run) + { + if (!_magicSwordStages.TryGetValue(run.Id, out MagicSwordStageRun stage) || !stage.UsesBodyBinding || !run.StageStarted) + return false; + if (stage.BodyFinished) + { + EnsureProperBodyAnimation(actor); + return true; + } + if (!stage.BodyExecuted) + { + stage.BodyExecuted = true; + run.BodyRestartPending = false; + SetBodyBladeSeconds(actor, 0.25f); + ResetActorFacing(actor); + TryPlayBodyAnimation(actor, stage.BodyRequested, false, BattlePose.UsingSkill, 40); + return true; + } + if (!actor.Alive || GetBodyBinding(actor).LastPoppedMarker == BattlePhysicalMarkerKind.Over) + { + stage.BodyFinished = true; + SetBodyBladeSeconds(actor, 0.01f); + run.BodyElapsed = run.Timing.BodyAnimationTicks; + } + return true; + } + + private long StartMagicSwordGroup(int group, BattleMovementPoint origin, Actor actor, ActionRun run) => group < 0 ? 0 : + StartEffect(new BattleEffectRequest(group, actor.Initial.InstanceId, run.Targets, origin, unchecked((uint)_scenario.Seed), absoluteTime: true)); + + private void CancelMagicSwordStage(ActionRun run) + { + if (run == null || !_magicSwordStages.Remove(run.Id, out MagicSwordStageRun stage)) + return; + HideStageMessage(stage); + if (_absoluteTimeActor == stage.Actor) + _absoluteTimeActor = null; + if (stage.FirstHandle != 0) + StopEffect(stage.FirstHandle); + if (stage.SecondHandle != 0) + StopEffect(stage.SecondHandle); + } + + // This marker is the effect-group-1 completion callback, never the linker work time. + private bool ResolveMagicSwordMarker(Actor source, ActionRun run) + { + if (!IsMagicSwordAbility(run.Ability)) + return false; + if (run.AbilityResolved) + return true; + run.AbilityResolved = true; + BattleMagicSwordSnapshot snapshot = CaptureMagicSword(source) ?? throw new InvalidOperationException("Missing magic sword state."); + BattleAbilityDefinition ability = run.Ability; + int lastTargetReturn = 0; + foreach (string targetId in run.Targets) + { + Actor target = _byId[targetId]; + if (target.Escaped) + continue; + bool group = ability.Range is not (BattleTargetRange.OwnSingle or BattleTargetRange.OpponentSingle); + if (!group && !IsAtHome(target)) + { + Add(BattleEventKind.Miss, source.Initial.InstanceId, targetId, run.Id, "weapon skill target away from home"); + continue; + } + int returned = 0; + bool hpRecovered = false, mpRecovered = false; + foreach (BattleAttributeEffect effect in ability.Attributes.OrderBy(value => value.Attribute)) + { + if (effect.Value == 0) + continue; + if (effect.Attribute > 2) + throw new NotSupportedException("An original weapon skill cannot change this combat resource."); + int power = BattleMagicSwordRules.SkillPower(snapshot, ability.Id, checked((short)effect.Value), target.Initial.Side, out BattleValueMode mode); + int requested = mode == BattleValueMode.Percentage ? (int)((long)target.Attributes[effect.Attribute] * power / 100) : power; + returned = ChangeResource(target, effect.Attribute, requested, source, run.Id, ability.Name); + hpRecovered |= effect.Attribute == 0 && returned > 0; + mpRecovered |= effect.Attribute == 2 && returned > 0; + } + PlaySound(BattleEffectAudioRules.Recovery(hpRecovered, mpRecovered)); + // Released WeaponSkillAffect changes values first, including on dead targets. + ApplyAbilityStates(source, target, run); + lastTargetReturn = returned; + if (returned < 0 && target.Run?.Casting == true) + { + Cancel(target, "weapon skill hit interrupted casting"); + target.Ready = false; + target.Gauge = 0; + } + } + PaySkillCost(source, ability, run.Id, lastTargetReturn); + // Native WeaponSkillDamage clears again after every target and FightSkillCost. + _magicSwords[source.Initial.InstanceId] = BattleMagicSwordRules.ConsumeEnergy(CaptureMagicSword(source)); + CheckResult(); + return true; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.MagicSword.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.MagicSword.cs.meta new file mode 100644 index 00000000..dc7abfaf --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.MagicSword.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fbe315cf108244a0aa52caeaff51956e diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Mechanics.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Mechanics.cs new file mode 100644 index 00000000..eb84ceb2 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Mechanics.cs @@ -0,0 +1,518 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private BattleScenario _scenario; + private BattleStatusRules _statusRules; + private BattleEffectRules _effectRules; + private int _money; + private bool _partyEscaped; + private readonly Dictionary _inventory = new(); + + public BattleDefinitions Definitions + { + get; private set; + } + + public int Money => _money; + + public IReadOnlyList Inventory => Array.AsReadOnly(_inventory.OrderBy(pair => pair.Key) + .Where(pair => pair.Value > 0).Select(pair => new BattleItemSnapshot(pair.Key, pair.Value)).ToArray()); + + private void InitializeMechanics(BattleScenario scenario, BattleDefinitions definitions) + { + _scenario = scenario; + Definitions = definitions; + _money = scenario.Money; + InitializePal3AState(scenario); + InitializeSpecialResources(scenario); + foreach (BattleItem item in scenario.Items) + _inventory.Add(item.Id, item.Count); + if (definitions == null) + return; + if (definitions.Variant != scenario.Variant || definitions.Fingerprint != scenario.DataFingerprint) + throw new ArgumentException("Combat definitions do not match the captured scenario variant/data."); + _statusRules = new BattleStatusRules(definitions.Variant); + _effectRules = new BattleEffectRules(definitions.Variant); + } + + private void InitializeActorMechanics(Actor actor) + { + actor.Skills.AddRange(actor.Initial.Skills.Select(skill => skill.Copy())); + if (Definitions == null) + { + InitializeActorMagicSword(actor); + return; + } + if (!Definitions.Actors.TryGetValue(actor.Initial.InstanceId, out BattleActorDefinition definition)) + throw new ArgumentException("Missing combat actor definition: " + actor.Initial.InstanceId); + actor.Definition = definition; + InitializeActorMagicSword(actor); + InitializeActorSpecials(actor); + if (!string.IsNullOrEmpty(definition.UnsupportedReason)) + throw new NotSupportedException($"Actor {actor.Initial.ActorId}: {definition.UnsupportedReason}"); + foreach (BattleEquipmentDefinition item in definition.Equipment) + if (!string.IsNullOrEmpty(item.UnsupportedReason)) + throw new NotSupportedException($"Equipment {item.Id}: {item.UnsupportedReason}"); + actor.Attributes = BattleAttributeCalculator.Calculate(actor.Initial, definition, Definitions.Variant); + if (actor.Attributes.Length != 12 || actor.Attributes.Take(3).Any(value => value < 0) || actor.Attributes.Any(value => value > 1000000)) + throw new ArgumentException("Invalid derived attributes on " + actor.Initial.InstanceId); + if (actor.Hp > actor.Attributes[0] || actor.Sp > actor.Attributes[1] || actor.Mp > actor.Attributes[2]) + throw new ArgumentException("Initial vitals exceed the derived maxima on " + actor.Initial.InstanceId); + foreach (BattleState state in definition.PermanentStates.OrderBy(state => state)) + ApplyState(actor, state, false, null, true, sound: false); + foreach (BattleState state in definition.InitialStates.OrderBy(state => state)) + ApplyState(actor, state, false, sound: false); + foreach (BattleStatus initial in actor.Initial.Statuses.OrderBy(state => state.Id)) + { + if (Enum.IsDefined(typeof(BattleState), initial.Id)) + { + actor.States.Remove((BattleState)initial.Id); + ApplyState(actor, (BattleState)initial.Id, false, initial.Rounds, sound: false); + } + else + throw new NotSupportedException("Unknown initial combat state " + initial.Id); + } + } + + private static bool Has(Actor actor, BattleState state) => actor.States.ContainsKey(state); + + private static bool IsUncontrollable(Actor actor) => Has(actor, BattleState.Paralysis) || Has(actor, BattleState.Sleep) || + Has(actor, BattleState.Chaos) || Has(actor, BattleState.Madness); + + private int[] EffectiveAttributes(Actor actor) + { + int[] attributes = actor.Attributes.ToArray(); + if (_statusRules != null) + for (int index = 3; index <= 6; index++) + attributes[index] = _statusRules.ModifyAttribute(index, attributes[index], actor.States.Keys); + AdjustPal3AEffectiveAttributes(actor, attributes); + return attributes; + } + + private BattleParticipant RuleParticipant(Actor actor) + { + if (Definitions == null) + return actor.Initial; + return new BattleParticipant + { + InstanceId = actor.Initial.InstanceId, + ActorId = actor.Initial.ActorId, + Side = actor.Initial.Side, + Slot = actor.Slot, + Level = actor.Level, + Attributes = EffectiveAttributes(actor) + }; + } + + private IReadOnlyList StatusSnapshots(Actor actor) => Array.AsReadOnly(actor.States.Values.OrderBy(value => value.State) + .Select(value => new BattleStatusSnapshot + { + State = value.State, + LatentRounds = value.LatentRounds, + RemainingRounds = value.RemainingRounds, + Permanent = value.Permanent + }).ToArray()); + + public string CanSubmit(BattleCommand command) => ValidateCommand(command, false); + + private string ValidateCommand(BattleCommand command, bool fromController, bool elementWheel = false) + { + if (Status != BattleSessionStatus.Running) + return "The battle has ended."; + if (IsBattleInputSuspended) + return "The battle movie is playing or its frame is resuming."; + if (_resolvingOutcome) + return "The encounter outcome is resolving."; + if (ActiveFormationController != null) + return "Finish formation control before submitting an action."; + if (!Enum.IsDefined(typeof(BattleAction), command.Action)) + return "Unsupported command."; + if (command.Action is not (BattleAction.Skill or BattleAction.Item) && command.AbilityId != 0) + return "This action cannot carry a skill or item ID."; + if (command.Actor == null || !_byId.TryGetValue(command.Actor, out Actor actor) || !actor.Alive || actor.Escaped || actor.EnemyFleeing || + !actor.Ready || Definitions != null && actor.ProcessedRounds < actor.Rounds || actor.Run != null || !ActionBodyIdle(actor)) + return "Actor is not ready."; + if (Has(actor, BattleState.Paralysis) || Has(actor, BattleState.Sleep)) + return "定/眠期间不能行动。"; + if (!fromController && (Has(actor, BattleState.Chaos) || Has(actor, BattleState.Madness))) + return "乱/狂期间由原版异常状态 AI 接管。"; + if (!fromController && !IsAiEnabled(actor) && WaitingActor != command.Actor) + return "An earlier actor is waiting for input."; + BattleAbilityDefinition ability = Ability(command); + string formDenied = elementWheel ? ValidateElementWheelController(actor, command, ability) : + ValidatePal3AFormCommand(actor, command, ability, fromController); + if (formDenied != null) + return formDenied; + if (command.Action is BattleAction.Defend or BattleAction.Transform) + return null; + if (command.Action == BattleAction.Flee) + return Definitions == null ? "The basic fixture has no escape rules." : actor.Initial.Side != BattleSide.Ally ? "Only the player party can request escape." : Has(actor, BattleState.Forbidden) ? "禁期间不能等待逃跑。" : null; + if (command.Action is BattleAction.Skill or BattleAction.Item) + { + string denied = ValidateAbility(actor, command, ability, out _, elementWheel); + if (denied != null) + return denied; + } + else if (command.Action != BattleAction.Attack) + return "Unsupported command."; + if (elementWheel) + return null; + IReadOnlyList candidates = CommandTargetCandidates(command, fromController); + BattleTargetRange range = ActionRange(actor, ability); + bool manualGroup = !fromController && !IsMagicSwordAbility(ability) && + range is BattleTargetRange.OwnAll or BattleTargetRange.OpponentAll; + if (candidates.Count == 0 || manualGroup && !candidates.Any(target => target.Alive)) + return "There is no legal target."; + if (manualGroup && command.Target != null && !candidates.Any(target => target.Id == command.Target)) + return "Choose a legal target for this action."; + if (command.Action == BattleAction.Attack || range is BattleTargetRange.OwnSingle or BattleTargetRange.OpponentSingle or BattleTargetRange.OpponentRow or BattleTargetRange.OpponentColumn) + { + if (command.Target == null || !candidates.Any(target => target.Id == command.Target)) + return "Choose a legal target for this action."; + } + return null; + } + + private string ValidateAbility(Actor actor, BattleCommand command, BattleAbilityDefinition ability, + out bool forbiddenByField, bool elementWheel = false) + { + forbiddenByField = false; + if (Definitions == null || ability == null) + return "Unknown skill or item."; + if (!ability.Supported) + return ability.UnsupportedReason; + if (_scenario.Variant == "PAL3A" && ability.Id == BattlePal3ARules.SpiritCaptureSkill && _effects is not IBattleSpiritCaptureLayout) + return "Spirit capture needs the original screen-space wheel layout."; + if (ability.Attributes.Any(effect => effect.Attribute > 2 && effect.Value != 0)) + return "This attribute effect needs its original dedicated battle handler."; + if (!Enum.IsDefined(typeof(BattleTargetRange), ability.Range) || ability.States.Any(effect => effect.State == BattleState.Dying && !effect.Remove || effect.State > BattleState.Death)) + return "This ability contains an unverified target range or derived/passive state operation."; + if (ability.Costs.Any(cost => cost.Value < 0 || !Enum.IsDefined(typeof(BattleValueMode), cost.Mode) || cost.Resource is not (0 or 1 or 2 or 7 or 8 or 10 or 16))) + return "This ability has an unsupported resource cost."; + string specialDenied = ValidateSpecialCommand(ability); + if (specialDenied != null) + return specialDenied; + if (!ability.BattleUsable) + return "This item cannot be used in combat."; + if (command.Action == BattleAction.Item) + { + if (actor.Initial.Side != BattleSide.Ally) + return "Original enemies cannot use inventory items."; + if (Has(actor, BattleState.Forbidden)) + return "禁期间不能使用物品。"; + int reserved = ability.IsTreasure ? 0 : _actors.Count(other => other.Run is { Kind: BattleAction.Item, ItemConsumed: false } && + other.Run.Ability.Id == ability.Id); + if (!_inventory.TryGetValue(ability.Id, out int count) || count <= reserved) + return "No item remains in this battle inventory."; + } + else if (IsMagicSwordAbility(ability)) + { + string denied = ValidateMagicSwordCommand(actor, ability); + if (denied != null) + return denied; + if (_effects == null || _catalog is not IBattleMagicSwordTimings) + return "The magic sword needs its original effect completion director."; + } + else if (!elementWheel && !AiPrevalidatedAbility(actor, ability)) + { + BattleSkill learned = actor.Skills.FirstOrDefault(skill => skill.Id == ability.Id); + if (learned == null || actor.Initial.Side == BattleSide.Ally && !learned.Mastered) + return "This actor has not mastered the skill."; + if (ability.ApplicableIdentities.Count > 0 && actor.Initial.Side == BattleSide.Ally && !ability.ApplicableIdentities.Contains(actor.Definition.Identity)) + return "This skill belongs to another character."; + if (learned.Level < 1 || learned.Level > 4) + return "The original skill proficiency must be 1–4."; + if (ability.IsMagic && Has(actor, BattleState.Seal)) + return "封期间不能施放仙术。"; + } + foreach (BattleCostEstimate cost in elementWheel || AiPrevalidatedAbility(actor, ability) + ? Array.Empty() : GetCostEstimate(command)) + if (cost.Required > cost.Available) + return $"Resource {cost.Resource}: need {cost.Required}, available {cost.Available}."; + if (!elementWheel && command.Action == BattleAction.Skill && ability.IsMagic && + _ai?.IsSceneMagicForbidden(NativeActorIndex(actor), ability.Id, ability.ElementMask) == true) + { + forbiddenByField = true; + return "敌方五灵阵法封禁了此系仙术。"; + } + try + { + string presentationDenied = ValidateAbilityPresentation(actor, ability, elementWheel); + if (presentationDenied != null) + return presentationDenied; + AttackTiming timing = elementWheel ? ElementWheelTiming(command.Actor, ability) : + (_catalog as IBattleAbilityTimings)?.Ability(command.Actor, ability); + if (timing == null) + return "The ability has no verified action timeline."; + if (timing.HitTicks.Count != 1) + return "This ability requires a dedicated repeated-effect timeline."; + } + catch (Exception exception) when (exception is ArgumentException or InvalidOperationException or NotSupportedException or System.IO.IOException) + { + return exception.Message; + } + return null; + } + + private BattleAbilityDefinition Ability(BattleCommand command) + { + if (Definitions == null || command.Action is not (BattleAction.Skill or BattleAction.Item)) + return null; + var table = command.Action == BattleAction.Item ? Definitions.Items : Definitions.Skills; + return table.TryGetValue(command.AbilityId, out BattleAbilityDefinition ability) ? ability : null; + } + + private BattleTargetRange RuntimeNormalAttackRange(Actor source) + { + // The original fire beast swap clears all three weapon range flags. + if (_scenario.Variant == "PAL3A" && NativeActorIndex(source) == 0 && IsPal3ATransformed(source.Initial.InstanceId)) + return BattleTargetRange.OpponentSingle; + return source.Definition?.NormalAttackRange ?? BattleTargetRange.OpponentSingle; + } + + private bool CanAttackBack(Actor source, Actor target) + { + if (source == null || target == null) + return false; + if (RuntimeNormalAttackRange(source) is BattleTargetRange.OpponentColumn or BattleTargetRange.OpponentAll) + return true; + if (source.Initial.Side == BattleSide.Enemy && target.Initial.Side == BattleSide.Ally && (int)target.Slot + 1 == BattleEffectRules.GreaterElement(_scenario.SceneElement)) + return !_actors.Any(actor => actor.Initial.Side == BattleSide.Ally && actor.Slot == BattleSlot.Center && actor.Hp > 0 && + !actor.Escaped && !IsFleeing(actor)); + if (source.Initial.Side == BattleSide.Ally && NativeActorIndex(target) == 6) + { + Actor center = ActorAtNativeIndex(10); + return center == null || center.Hp <= 0 || center.Escaped || IsFleeing(center); + } + return true; + } + + private BattleTargetRange ActionRange(Actor source, BattleAbilityDefinition ability) + { + if (ability != null) + return ability.Range; + return RuntimeNormalAttackRange(source); + } + + public IReadOnlyList GetTargetCandidates(BattleCommand command) + { + if (command.Actor == null || !_byId.TryGetValue(command.Actor, out Actor source)) + return Array.Empty(); + BattleTargetRange range = GetActionTargetRange(command); + if (range == BattleTargetRange.None) + return Array.Empty(); + BattleAbilityDefinition ability = Ability(command); + bool own = range is BattleTargetRange.OwnSingle or BattleTargetRange.OwnAll; + if (IsMagicSwordAbility(ability)) + return Array.AsReadOnly(FightSkillRange(source, range).Select(Snapshot).ToArray()); + + // ProcSelectRole copies these selected slots into the command at confirmation. + return Array.AsReadOnly(_actors.OrderBy(NativeActorIndex).Where(target => + (target.Initial.Side == source.Initial.Side) == own && !target.Escaped && !IsFleeing(target) && + (target.Alive || own && ability?.Revives == true) && + CanManuallySelectTarget(target, own, ability) && + (Definitions == null || command.Action != BattleAction.Attack || CanAttackBack(source, target)) && + (_scenario.Variant != "PAL3A" || ability?.Id != BattlePal3ARules.PengxuTransformSkill || target == source)) + .Select(Snapshot).ToArray()); + } + + // GetFightSkillRange constructs group masks for AI spells, items and PAL3 weapon skills. + private IEnumerable FightSkillRange(Actor source, BattleTargetRange range) => + _actors.OrderBy(NativeActorIndex).Where(target => !target.Escaped && + (target.Initial.Side == source.Initial.Side) == (range == BattleTargetRange.OwnAll) && + (_scenario.Variant == "PAL3" || target.Hp > 0)); + + private IReadOnlyList CommandTargetCandidates(BattleCommand command, bool fromController) => + fromController && TryAiTargetCandidates(command, out IReadOnlyList targets) + ? targets : GetTargetCandidates(command); + + private string[] CaptureTargets(Actor source, BattleCommand command, BattleAbilityDefinition ability, bool fromController) + { + if (IsMagicSwordAbility(ability)) + return Array.Empty(); // ProcWeaponSkill builds its own mask on the first system pass. + if (fromController && TryAiCapturedTargets(command, out string[] recorded)) + return recorded; + BattleTargetRange range = ActionRange(source, ability); + var candidates = CommandTargetCandidates(command, fromController); + if (range is BattleTargetRange.OwnSingle or BattleTargetRange.OpponentSingle) + return new[] { command.Target }; + if (range is BattleTargetRange.OpponentRow or BattleTargetRange.OpponentColumn) + { + Actor anchor = _byId[command.Target]; + return candidates.Where(target => BattleTargetRules.Aligned(anchor.Initial.Side, anchor.Slot, + _byId[target.Id].Slot, range == BattleTargetRange.OpponentRow, _scenario.SceneElement)).Select(target => target.Id).ToArray(); + } + return candidates.Select(target => target.Id).ToArray(); + } + + private bool SubmitCommand(BattleCommand command, bool fromController, bool elementWheel = false) + { + if (ValidateCommand(command, fromController, elementWheel) != null) + return false; + Actor actor = _byId[command.Actor]; + BattleAbilityDefinition ability = Ability(command); + BattleAttackPlan attackPlan = command.Action == BattleAction.Attack ? PlanAttack(actor, _byId[command.Target]) : null; + AttackTiming timing = elementWheel ? ElementWheelTiming(command.Actor, ability) : + attackPlan?.Timing ?? (ability != null ? ((IBattleAbilityTimings)_catalog).Ability(command.Actor, ability) : null); + int guardTicks = _catalog.GuardEntry(command.Actor); + string[] targets = !elementWheel && command.Action is BattleAction.Attack or BattleAction.Skill or BattleAction.Item ? CaptureTargets(actor, command, ability, fromController) : Array.Empty(); + bool casting = !elementWheel && ability?.IsMagic == true || command.Action == BattleAction.Flee; + actor.Ready = false; + actor.Guard = false; + actor.Gauge = casting ? FullGauge : 0; + actor.CastGauge = 0; + actor.CastSpeed = 0; + if (command.Action == BattleAction.Flee) + actor.CastSpeed = _effectRules.FleeGaugePerStep(EffectiveAttributes(actor)[5]); + else if (casting) + { + int proficiency = AiSkill(actor, ability.Id).Level; + if (proficiency >= 4) + casting = false; + else + { + BattleParticipant current = RuleParticipant(actor); + actor.CastSpeed = _rules is BattleBasicRules native ? + native.MagicCastGaugePerStep(current, proficiency) : + Math.Min(byte.MaxValue, _rules.GaugePerStep(current) * proficiency * 2); + } + if (!casting) + { + actor.Gauge = 0; + actor.CastGauge = FullCastGauge; + } + } + actor.Run = new ActionRun + { + Id = ++_nextAction, + CreatedTick = SimulationTick, + TimelineOriginTick = SimulationTick, + Kind = command.Action, + Target = command.Target, + Targets = targets, + Ability = ability, + Timing = timing, + AttackPlan = attackPlan, + LastAttackSample = attackPlan?.Origin ?? actor.Position, + GuardTicks = guardTicks, + Casting = casting, + ElementWheel = elementWheel + }; + _inputs.Add(new BattleInput + { + Tick = Tick, + Kind = elementWheel ? BattleInputKind.ElementWheel : BattleInputKind.Command, + Actor = command.Actor, + Action = command.Action, + Target = command.Target, + AbilityId = command.AbilityId, + FromTestAi = fromController + }); + Add(BattleEventKind.Command, command.Actor, actor.Run.Target, actor.Run.Id, detail: command.Action + (ability == null ? "" : " " + ability.Id)); + if (!fromController) + { + AdvanceFiveSpiritFieldTurn(actor); + if (!elementWheel && command.Action != BattleAction.Transform) + RememberAiCommand(command); + } + return true; + } + + private void AdvanceGauges() + { + if (IsCoAttackAtbPaused || _fleeAtbPaused) + return; + foreach (Actor actor in _actors.Where(actor => actor.Alive && !actor.Escaped && !actor.EnemyFleeing)) + { + if (actor.Run?.Casting == true) + { + actor.CastGauge = Math.Min(FullCastGauge, actor.CastGauge + actor.CastSpeed); + if (actor.CastGauge >= FullCastGauge) + { + actor.Run.Casting = false; + actor.Gauge = 0; + actor.Run.Elapsed = 0; + actor.Run.TimelineOriginTick = SimulationTick; + + } + } + else if (!actor.Ready && (actor.Run == null || actor.Run.Kind == BattleAction.Defend || IsInterruptedFleeRun(actor.Run))) + { + actor.Gauge = Math.Min(FullGauge, actor.Gauge + _rules.GaugePerStep(RuleParticipant(actor))); + MakeReady(actor); + } + } + } + + private Actor ChooseTestTarget(Actor actor) => _actors.FirstOrDefault(target => target.Alive && !target.Escaped && target.Initial.Side != actor.Initial.Side && IsAtHome(target) && + (target.Run?.Kind != BattleAction.Attack || target.Run.Timing.TravelTicks == 0)); + + private void ProcessRounds() + { + if (Definitions != null && (_resolvingOutcome || !_actors.Any(actor => actor.Initial.Side == BattleSide.Enemy && actor.Alive && !actor.Escaped))) + { + CheckResult(); + return; + } + foreach (Actor actor in _actors.OrderBy(NativeActorIndex).Where(actor => actor.Run == null && ActionBodyIdle(actor)).ToArray()) + { + if (RoundLimitReached) + break; + if (BeginOriginalRound(actor)) + { + if (Definitions != null) + { + foreach (BattleStatusInstance state in actor.States.Values.OrderBy(value => value.State).ToArray()) + { + int delta = _statusRules.TickRound(state, actor.Attributes[0], actor.Hp); + if (delta != 0) + ChangeHp(actor, delta, null, 0, "poison " + state.State, false); + if (!state.Permanent && state.RemainingRounds == 0) + ApplyState(actor, state.State, true); + if (actor.Hp <= 0) + break; + } + AdvanceOriginalAbsorbHpWormOnRound(actor); + AdvancePal3AFormsOnRound(actor); + if (actor.Hp > 0) + { + for (int resource = 0; resource < 3; resource++) + { + int rate = actor.Definition.Equipment.Where(item => item.Slot != 0).Sum(item => item.RecoveryPerRound.Count > resource ? item.RecoveryPerRound[resource] : 0); + if (rate > 0 && ResourceValue(actor, resource) < actor.Attributes[resource]) + ChangeResource(actor, resource, (int)(actor.Attributes[resource] * (float)rate / 100), null, 0, "equipment per-round recovery"); + } + if (actor.Initial.Side == BattleSide.Enemy && _random.Probability(actor.Definition.EscapePercent)) + { + StartEnemyFlee(actor); + } + } + HandleOriginalBossRound(actor); + } + } + if (!actor.Alive || actor.Escaped || actor.EnemyFleeing) + continue; + if (actor.Ready && (Has(actor, BattleState.Paralysis) || Has(actor, BattleState.Sleep))) + { + AdvanceFiveSpiritFieldTurn(actor); + actor.Ready = false; + actor.Gauge = 0; + Add(BattleEventKind.Cancelled, actor.Initial.InstanceId, detail: "定/眠 skips a ready turn"); + } + if (actor.Ready && !IsUncontrollable(actor) && !IsAiEnabled(actor)) + break; + } + CheckResult(); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Mechanics.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Mechanics.cs.meta new file mode 100644 index 00000000..35b6c199 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Mechanics.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d32b3b0a9de446339b7a3d7414d59663 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Pal3AForms.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Pal3AForms.cs new file mode 100644 index 00000000..66a16987 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Pal3AForms.cs @@ -0,0 +1,433 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private sealed class Pal3AFormState + { + internal BattlePal3AFormKind Kind; + internal int Generation, Rounds, RoundLimit; + internal int SavedHp, SavedMaxHp, SavedDefense; + internal bool Pending, LethalReturnPending, PengxuStatsPrepared; + } + + private readonly Dictionary _pal3AForms = new(StringComparer.Ordinal); + private BattleSpiritWheelSnapshot _spiritWheel = new(new int[5]); + private BattleRandom _spiritVisualRandom = new(1); + private bool _preserveLiaoRiLosses; + private int _pal3AHpLoss, _pal3AMpLoss; + + public BattlePal3AStateSnapshot Pal3AState => new(_spiritWheel, _preserveLiaoRiLosses, _pal3AHpLoss, _pal3AMpLoss, _spiritVisualRandom.State); + + public bool IsPal3ATransformed(string actorId) => actorId != null && _pal3AForms.TryGetValue(actorId, out Pal3AFormState state) && + state.Kind != BattlePal3AFormKind.Human; + + public BattlePal3AFormSnapshot Pal3AForm(string actorId) => actorId != null && _pal3AForms.TryGetValue(actorId, out Pal3AFormState state) + ? new BattlePal3AFormSnapshot(state.Kind, state.Generation, state.Rounds, state.RoundLimit, state.Pending, state.LethalReturnPending) + : new BattlePal3AFormSnapshot(BattlePal3AFormKind.Human, 0, 0, 0, false, false); + + private void InitializePal3AState(BattleScenario scenario) + { + if (scenario.Variant != "PAL3A") + return; + BattlePal3AState captured = scenario.Pal3A ?? throw new ArgumentException("PAL3A state is missing."); + captured.Validate(); + _spiritWheel = captured.SpiritWheel.Capture(); + _spiritVisualRandom = new BattleRandom(captured.SpiritVisualSeed); + _preserveLiaoRiLosses = captured.PreserveLiaoRiLosses; + if (_preserveLiaoRiLosses) + { + _pal3AHpLoss = captured.HpLoss; + _pal3AMpLoss = captured.MpLoss; + } + } + + private void InitializePal3AForms() + { + if (_scenario.Variant != "PAL3A" || Definitions == null) + return; + foreach (Actor actor in _actors) + { + if (_preserveLiaoRiLosses && actor.Initial.ActorId == BattlePal3ARules.LiaoRiCarryActor && + ((long)actor.Attributes[0] + _pal3AHpLoss > int.MaxValue || (long)actor.Attributes[2] + _pal3AMpLoss > int.MaxValue)) + throw new ArgumentException("Captured PAL3A losses exceed Liao Ri's signed int32 attribute capacity."); + ApplyPal3ALiaoRiCarry(actor); + } + foreach (Actor actor in _actors.Where(actor => actor.Initial.Side == BattleSide.Ally && NativeActorIndex(actor) is 0 or 2)) + _pal3AForms.Add(actor.Initial.InstanceId, new Pal3AFormState()); + Actor nangong = ActorAtNativeIndex(0); + if (_scenario.Pal3A.NangongStartsTransformed) + { + if (nangong == null) + throw new ArgumentException("Opening fire beast form needs Nangong Huang in native slot zero."); + _spiritWheel = new BattleSpiritWheelSnapshot(Enumerable.Repeat(9, 5)); + SwapPal3AForm(nangong, true); + } + Actor pengxu = ActorAtNativeIndex(2); + if (_scenario.Pal3A.PengxuStartsTransformed) + { + if (pengxu == null) + throw new ArgumentException("Opening fairy beast form needs Wang Pengxu in native slot two."); + PreparePal3APengxuStats(pengxu); + SwapPal3AForm(pengxu, true); + } + } + + private string ValidatePal3AFormCommand(Actor actor, BattleCommand command, BattleAbilityDefinition ability, bool fromController) + { + if (_scenario.Variant != "PAL3A") + return command.Action == BattleAction.Transform ? "Transformation is exclusive to PAL3A." : null; + Pal3AFormState state = _pal3AForms.GetValueOrDefault(actor.Initial.InstanceId); + if (state?.Pending == true) + return "The original form transition is still running."; + if (command.Action == BattleAction.Transform) + { + if (NativeActorIndex(actor) != 0 || actor.Initial.ActorId != 101 || state == null || state.Kind != BattlePal3AFormKind.Human) + return "Only Nangong Huang's human form can request the fire beast transformation."; + if (_spiritWheel.Tier == 0) + return "All five spirit wheel charges must reach three."; + return _catalog is IBattlePal3AFormCatalog ? null : "The original form animation catalog is missing."; + } + if (ability?.Id == BattlePal3ARules.PengxuTransformSkill) + { + if (NativeActorIndex(actor) != 2 || actor.Initial.ActorId != 103 || state == null || state.Kind != BattlePal3AFormKind.Human) + return "朱仙变 requires Wang Pengxu's human form."; + if (actor.Sp < actor.Attributes[1]) + return "朱仙变 requires full SP before equipment savings."; + return _catalog is IBattlePal3AFormCatalog ? null : "The original form animation catalog is missing."; + } + if (ability?.Id == BattlePal3ARules.SpiritCaptureSkill && NativeActorIndex(actor) != 0) + return "摄灵法阵 requires Nangong Huang in native slot zero."; + return fromController ? null : FormActionDenial(actor.Initial.InstanceId, command.Action, ability?.IsMagic == true); + } + + public string FormActionDenial(string actorId, BattleAction action, bool magic = false) + { + if (action == BattleAction.Flee || actorId == null || !_pal3AForms.TryGetValue(actorId, out Pal3AFormState state)) + return null; + if (state.Kind == BattlePal3AFormKind.NangongFireBeast && action is not (BattleAction.Attack or BattleAction.Defend)) + return "The original fire beast form permits only physical attack, defense, or escape."; + if (state.Kind == BattlePal3AFormKind.PengxuFairyBeast && action != BattleAction.Defend && !(action == BattleAction.Skill && magic)) + return "The original fairy beast form permits only magic, defense, or escape."; + return null; + } + + private void AdjustPal3AEffectiveAttributes(Actor actor, int[] attributes) + { + if (_scenario.Variant != "PAL3A" || NativeActorIndex(actor) != 0 || !IsPal3ATransformed(actor.Initial.InstanceId)) + return; + // Native GetAttack/GetDefend return before ordinary status modifiers. + attributes[3] = unchecked(actor.Attributes[3] * 2); + attributes[4] = unchecked(actor.Attributes[4] * 2); + } + + private int AdjustPal3AMagicPower(Actor source, int originalPower) => BattlePal3ARules.PengxuSpellPower(originalPower, + _scenario.Variant == "PAL3A" && NativeActorIndex(source) == 2 && IsPal3ATransformed(source.Initial.InstanceId)); + + private bool Pal3AIgnoresMpChange(Actor actor) => _scenario.Variant == "PAL3A" && NativeActorIndex(actor) == 2 && + IsPal3ATransformed(actor.Initial.InstanceId); + + private void TrackPal3AHpLoss(Actor target, int negativeDelta) + { + if (_scenario.Variant == "PAL3A" && NativeActorIndex(target) is >= 0 and < 5) + _pal3AHpLoss = BattlePal3ARules.AddLoss(_pal3AHpLoss, negativeDelta); + } + + private void TrackPal3AMpLoss(Actor target, int negativeDelta) + { + if (_scenario.Variant == "PAL3A" && NativeActorIndex(target) is >= 0 and < 5) + _pal3AMpLoss = BattlePal3ARules.AddLoss(_pal3AMpLoss, negativeDelta); + } + + private void ApplyPal3ALiaoRiCarry(Actor actor) + { + if (_scenario.Variant != "PAL3A" || !_preserveLiaoRiLosses || actor.Initial.ActorId != BattlePal3ARules.LiaoRiCarryActor) + return; + actor.Hp = actor.Attributes[0] = BattlePal3ARules.CarryAttribute(actor.Attributes[0], _pal3AHpLoss); + actor.Mp = actor.Attributes[2] = BattlePal3ARules.CarryAttribute(actor.Attributes[2], _pal3AMpLoss); + _preserveLiaoRiLosses = false; + } + + private void AdvancePal3AFormsOnRound(Actor actor) + { + if (!_pal3AForms.TryGetValue(actor.Initial.InstanceId, out Pal3AFormState state) || state.Kind == BattlePal3AFormKind.Human || state.Pending || !actor.Alive) + return; + if (BattlePal3ARules.ExpiresOnRound(state.Rounds, state.RoundLimit)) + QueuePal3AFormChange(actor, false, false); + else + state.Rounds++; + } + + private void HandlePal3AFormHpFloor(Actor actor, long actionId) + { + if (actor.Hp > 0 || !_pal3AForms.TryGetValue(actor.Initial.InstanceId, out Pal3AFormState state) || state.Kind == BattlePal3AFormKind.Human) + return; + if (NativeActorIndex(actor) == 0) + { + actor.Hp = 1; + if (!state.LethalReturnPending) + { + state.LethalReturnPending = true; + QueuePal3AFormChange(actor, false, true); + } + } + else if (!state.Pending) + QueuePal3AFormChange(actor, false, true); + } + + private void PreparePal3APengxuStats(Actor actor) + { + Pal3AFormState state = _pal3AForms[actor.Initial.InstanceId]; + state.PengxuStatsPrepared = true; + state.SavedHp = actor.Hp; + state.SavedMaxHp = actor.Attributes[0]; + state.SavedDefense = actor.Attributes[4]; + actor.Hp = actor.Attributes[0] = 400; + actor.Attributes[4] = unchecked(actor.Attributes[4] * 2); + } + + private void RestorePal3APengxuStats(Actor actor, bool lethal) + { + Pal3AFormState state = _pal3AForms[actor.Initial.InstanceId]; + if (!state.PengxuStatsPrepared) + return; + state.PengxuStatsPrepared = false; + actor.Attributes[0] = state.SavedMaxHp; + actor.Attributes[4] = state.SavedDefense; + actor.Hp = lethal ? 0 : state.SavedHp; + } + + private void SwapPal3AForm(Actor actor, bool entering) + { + Pal3AFormState state = _pal3AForms[actor.Initial.InstanceId]; + int identity = NativeActorIndex(actor); + BattlePal3AFormKind kind = entering ? identity == 0 ? BattlePal3AFormKind.NangongFireBeast : BattlePal3AFormKind.PengxuFairyBeast : BattlePal3AFormKind.Human; + if (identity == 0) + { + int luck = EffectiveAttributes(actor)[6]; + state.RoundLimit = entering ? _spiritWheel.NangongRounds : 0; + if (entering) + _spiritWheel = new BattleSpiritWheelSnapshot(new int[5]); + actor.Attributes[6] = Math.Max(0, unchecked(actor.Attributes[6] + (entering ? luck : luck / -2))); + } + else + { + state.RoundLimit = entering ? 5 : 0; + if (entering) + ApplyState(actor, BattleState.Barrier, false, 5); + else + ApplyState(actor, BattleState.Invisible, true, sound: !_ending); + actor.Attributes[6] = Math.Max(0, actor.Attributes[6] + (entering ? 3 : -3)); + } + state.Rounds = 0; + state.Kind = kind; + state.Generation++; + if (!entering) + state.LethalReturnPending = false; + try + { + (_catalog as IBattlePal3AFormCatalog)?.ActivatePal3AForm(actor.Initial.InstanceId, kind); + } + catch (Exception exception) when (_ending) + { + Add(BattleEventKind.PresentationCleanupFailed, actor.Initial.InstanceId, detail: exception.Message); + } + ClearActorThrownWeapon(actor.Initial.InstanceId); + _physicalBodies.Remove(actor.Initial.InstanceId); + _bodyAnimations.Remove(actor.Initial.InstanceId); + Add(BattleEventKind.ResourceChanged, target: actor.Initial.InstanceId, detail: "native PAL3A form swapped to " + kind); + } + + private bool _pal3AWinReturnQueued; + + private void QueuePal3AVictoryReturns() + { + if (_scenario.Variant != "PAL3A" || _pal3AWinReturnQueued) + return; + Actor[] transformed = _actors.Where(actor => IsPal3ATransformed(actor.Initial.InstanceId)).ToArray(); + if (transformed.Length == 0) + return; + _pal3AWinReturnQueued = true; + foreach (Actor actor in transformed) + QueuePal3AFormChange(actor, false, false); + } + + private void RestorePal3AFormsAfterStageStop() + { + foreach (Actor actor in _actors) + { + if (!_pal3AForms.TryGetValue(actor.Initial.InstanceId, out Pal3AFormState state)) + continue; + // Pengxu's native stats change when the task is queued, before + // the model swap. A stopped task can therefore still be human. + if (state.PengxuStatsPrepared) + RestorePal3APengxuStats(actor, actor.Hp <= 0); + if (state.Kind != BattlePal3AFormKind.Human) + SwapPal3AForm(actor, false); + state.Pending = false; + state.LethalReturnPending = false; + } + foreach (Pal3AFormStage stage in _pal3AFormStages) + stage.Finished = true; + _absoluteTimeActor = null; + } + + private sealed class Pal3AFormStage : IBattleStageCancellableJob + { + internal BattleSession Session; + internal Actor Actor; + internal bool Entering, Lethal; + internal int Phase; + internal bool AnimationStarted; + internal bool Finished; + internal BattleStageHandle Handle; + internal long EffectHandle; + + public bool Advance(BattleStageContext context) => Session.AdvancePal3AFormStage(this); + + public void Cancel() + { + try + { + if (Entering && Phase < 3 && NativeActorIndex(Actor) == 2) + Session.RestorePal3APengxuStats(Actor, Actor.Hp <= 0); + Session.StopEffect(EffectHandle); + } + finally + { + Session.CompletePal3AFormStage(this); + } + } + } + + private readonly List _pal3AFormStages = new(); + + private IEnumerable ActivePal3AFormTasks => _pal3AFormStages.Where(stage => !stage.Finished).Select(_ => 31); + + private bool HasActivePal3AFormBody(Actor actor) => _pal3AFormStages.Any(stage => stage.Actor == actor && !stage.Finished && stage.Phase > 0); + + private BattleStageHandle QueuePal3AFormChange(Actor actor, bool entering, bool lethal) + { + Pal3AFormState state = _pal3AForms[actor.Initial.InstanceId]; + if (state.Pending) + return _pal3AFormStages.Last(stage => stage.Actor == actor && !stage.Finished).Handle; + if (NativeActorIndex(actor) == 2) + { + if (entering) + PreparePal3APengxuStats(actor); + else + RestorePal3APengxuStats(actor, lethal); + } + var stage = new Pal3AFormStage { Session = this, Actor = actor, Entering = entering, Lethal = lethal }; + if (!_stage.TryAdd(actor.Initial.InstanceId, "PAL3A form", stage, BattleStageScheduler.TimeAt(SimulationTick), out BattleStageHandle handle)) + throw new InvalidOperationException("The original form transition task could not be allocated."); + stage.Handle = handle; + state.Pending = true; + _pal3AFormStages.Add(stage); + return handle; + } + + private void StartPal3ATransformAction(Actor actor, ActionRun run) + { + if (run.Kind == BattleAction.Transform) + run.StageHandle = QueuePal3AFormChange(actor, true, false); + } + + private void StartPal3APengxuAction(Actor actor, ActionRun run) + { + if (_scenario.Variant == "PAL3A" && run.Ability?.Id == BattlePal3ARules.PengxuTransformSkill && !_pal3AForms[actor.Initial.InstanceId].Pending) + run.FormStageHandle = QueuePal3AFormChange(actor, true, false); + } + + private bool AdvancePal3APengxuStage(Actor actor, ActionRun run, BattleStageContext context) + { + if (run.AbilityResolved) + return true; + if (context.Tick - run.TimelineOriginTick < run.Timing.PreparationTicks || !PhysicalBodyIdle(actor)) + return false; + StartPal3APengxuAction(actor, run); + run.StageStarted = run.AbilityResolved = true; + PaySkillCost(actor, run.Ability, run.Id, 0); + return true; + } + + private bool AdvancePal3AFormStage(Pal3AFormStage stage) + { + Actor actor = stage.Actor; + Pal3AFormState state = _pal3AForms[actor.Initial.InstanceId]; + if (_catalog is not IBattlePal3AFormCatalog catalog) + throw new NotSupportedException("The original form animation catalog is missing."); + if (stage.Phase == 0) + { + if (!PhysicalBodyIdle(actor) || IsActorExternallyControlled(actor.Initial.InstanceId) || + _absoluteTimeActor != null && _absoluteTimeActor != actor.Initial.InstanceId || !TryGrabStageBody(actor, stage.Handle)) + return false; + _absoluteTimeActor = actor.Initial.InstanceId; + stage.Phase = NativeActorIndex(actor) == 0 ? 1 : 2; + } + if (stage.Phase == 1) + { + if (!AdvancePal3AFormAnimation(stage, catalog, 164)) + return false; + stage.Phase = 2; + stage.AnimationStarted = false; + } + if (stage.Phase == 2) + { + SwapPal3AForm(actor, stage.Entering); + stage.Phase = 3; + if (!stage.Entering) + { + if (NativeActorIndex(actor) == 2 && _effects != null) + StartEffect(new BattleEffectRequest(605, actor.Initial.InstanceId, new[] { actor.Initial.InstanceId }, actor.Position, + unchecked((uint)_scenario.Seed), true)); + CompletePal3AFormStage(stage); + return true; + } + return false; + } + if (!AdvancePal3AFormAnimation(stage, catalog, NativeActorIndex(actor) == 2 && stage.Entering ? 605 : 0)) + return false; + CompletePal3AFormStage(stage); + return true; + } + + private void CompletePal3AFormStage(Pal3AFormStage stage) + { + if (stage.Finished) + return; + _pal3AForms[stage.Actor.Initial.InstanceId].Pending = false; + ReleaseStageBody(stage.Actor, stage.Handle); + stage.Finished = true; + if (stage.Phase > 0 && _absoluteTimeActor == stage.Actor.Initial.InstanceId) + _absoluteTimeActor = null; + } + + private bool AdvancePal3AFormAnimation(Pal3AFormStage stage, IBattlePal3AFormCatalog catalog, int effect) + { + Actor actor = stage.Actor; + if (!stage.AnimationStarted) + { + // Native Actor::GotoAction keeps the selected model's clock and + // message FIFO when z20 is absent, as it is for model 106. The + // form body still waits for that model's next Over message. + BattlePhysicalAnimation animation = catalog.FormChangeAnimation(actor.Initial.InstanceId, IsPal3ATransformed(actor.Initial.InstanceId)); + TryPlayBodyAnimation(actor, animation, false, BattlePose.UsingSkill, 60); + if (effect > 0 && _effects != null) + stage.EffectHandle = StartEffect(new BattleEffectRequest(effect, actor.Initial.InstanceId, new[] { actor.Initial.InstanceId }, actor.Position, + unchecked((uint)_scenario.Seed), true)); + stage.AnimationStarted = true; + return false; + } + return GetBodyBinding(actor).LastPoppedMarker == BattlePhysicalMarkerKind.Over; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Pal3AForms.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Pal3AForms.cs.meta new file mode 100644 index 00000000..7a8d3416 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Pal3AForms.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a2ed9209de84446fb3bd63a56932906a diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.PhysicalPresentation.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.PhysicalPresentation.cs new file mode 100644 index 00000000..1c07a656 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.PhysicalPresentation.cs @@ -0,0 +1,523 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private sealed class PhysicalBodyTask + { + internal BattlePhysicalBodyKind Kind; + internal BattleMovementPoint Destination; + internal Actor Target; + internal ActionRun Run; + internal BattlePhysicalAnimation Animation; + internal bool Executed, Finished, DiscardOnPush; + } + + private sealed class PhysicalBodyState + { + internal readonly List Tasks = new(); + internal BattlePhysicalStageProfile Profile; + internal long Owner; + internal bool Pushed, PushExecuted, PushDodge; + internal BattleMovementPlan PausedMovement; + internal BattlePhysicalAnimation PausedAnimation; + internal BattlePose PausedPose; + internal int PausedNativeAction; + internal float PausedBlend; + internal BattlePose Pose = BattlePose.Idle; + internal int LocalTick; + internal float BladeSeconds = .01f; + } + + private sealed class PhysicalStageRun : IBattleStageJob + { + internal BattleSession Session; + internal Actor Source, Protected, Attacker; + internal ActionRun Run; + internal BattlePhysicalStageProfile Profile; + internal BattleStageHandle Handle; + internal readonly int[] Status = new int[5]; + internal readonly bool[] Executed = new bool[5]; + internal bool Protection, RevivalReturn, EndRequested, Finished, CanStartProtection = true; + + public bool Advance(BattleStageContext context) => Session.AdvancePhysicalStage(this); + } + + private readonly Dictionary _physicalStages = new(); + private readonly List _protectionStages = new(); + private readonly Dictionary _physicalBodies = new(StringComparer.Ordinal); + private int _physicalProtectionTarget = -1; + + public string ProtectionTarget => ActorAtNativeIndex(_physicalProtectionTarget)?.Initial.InstanceId; + + private bool IsPhysicalRun(ActionRun run) => run != null && _physicalStages.ContainsKey(run.Id); + + private bool PhysicalBodyBusy(Actor actor) => _physicalBodies.TryGetValue(actor.Initial.InstanceId, out PhysicalBodyState body) && (body.Pushed || body.PausedMovement != null || body.Tasks.Count > 0); + + private PhysicalBodyState PhysicalBody(Actor actor) + { + if (_physicalBodies.TryGetValue(actor.Initial.InstanceId, out PhysicalBodyState body)) + return body; + if (_catalog is not IBattlePhysicalTimings catalog) + return null; + body = new PhysicalBodyState { Profile = catalog.Physical(actor.Initial.InstanceId) }; + _physicalBodies.Add(actor.Initial.InstanceId, body); + return body; + } + + // Native IsIdle counts every queued role task, including ability and + // form bodies. PhysicalBodyBusy stays limited to the physical queue so + // an ability can advance its own body without waiting on itself. + private bool PhysicalBodyIdle(Actor actor) => !PhysicalBodyBusy(actor) && !_fallbackFleeBodies.ContainsKey(actor.Initial.InstanceId) && !HasFormationMovement(actor) && + !HasActiveOrdinaryAbilityBody(actor) && !HasActivePal3AFormBody(actor) && SimulationTick >= actor.HurtUntil; + + private bool ActionBodyIdle(Actor actor) => PhysicalBodyIdle(actor) && + _pal3AForms.GetValueOrDefault(actor.Initial.InstanceId)?.Pending != true; + + private bool TryStartPhysicalStage(Actor actor, ActionRun run) + { + if (run == null || run.Kind is not (BattleAction.Attack or BattleAction.Defend) || _catalog is not IBattlePhysicalTimings || IsCoAttackRun(run)) + return false; + PhysicalBodyState body = PhysicalBody(actor); + var stage = new PhysicalStageRun { Session = this, Source = actor, Run = run, Profile = body.Profile }; + float now = BattleStageScheduler.TimeAt(SimulationTick); + if (!_stage.TryAdd(actor.Initial.InstanceId, "physical attack", stage, now, out BattleStageHandle handle, autoDelete: false)) + { + Cancel(actor, "original physical stage allocation failed"); + return true; + } + stage.Handle = handle; + run.StageHandle = handle; + run.AttackPlan = null; + actor.Gauge = actor.CastGauge = 0; + actor.Ready = false; + _physicalStages.Add(run.Id, stage); + return true; + } + + private void PreparePhysicalThreads() + { + foreach (PhysicalStageRun stage in _physicalStages.Values.Where(stage => stage.Finished).ToArray()) + { + _physicalStages.Remove(stage.Run.Id); + _stage.Cancel(stage.Handle); + if (stage.Source.Run == stage.Run) + Finish(stage.Source); + } + _protectionStages.RemoveAll(stage => !_stage.IsActive(stage.Handle)); + } + + private bool AdvancePhysicalStage(PhysicalStageRun stage) + { + for (int index = 0; index < stage.Status.Length; index++) + { + if (index > 0 && stage.Status[index - 1] == 0) + break; + if (stage.Status[index] == 4) + { + if (stage.Status.All(status => status == 4)) + return stage.Finished = true; + continue; + } + if (stage.Status[index] == 0) + { + if (index > 0 && stage.Status[index - 1] != 4) + continue; + stage.Status[index] = 2; + } + if (AdvancePhysicalSubtask(stage, index)) + stage.Status[index] = 4; + } + return false; + } + + private bool AdvancePhysicalSubtask(PhysicalStageRun stage, int index) + { + Actor actor = stage.Source; + PhysicalBodyState body = PhysicalBody(actor); + bool require = stage.EndRequested || stage.Run?.EndRequested == true; + if (index == 0) + { + if (!TryGrabStageBody(actor, stage.Handle)) + return false; + body.Owner = stage.Handle.Id; + return true; + } + if (index == 4) + { + ReleaseStageBody(actor, stage.Handle); + return true; + } + if (body.Owner != stage.Handle.Id) + return true; + if (stage.RevivalReturn) + return AdvanceRevivalReturn(stage, index); + if (stage.Protection) + return AdvanceProtectionSubtask(stage, index, require); + if (stage.Run.Kind == BattleAction.Defend) + { + if (index != 1) + return true; + if (!stage.Executed[index] && PhysicalBodyIdle(actor)) + { + QueuePhysicalTask(actor, new PhysicalBodyTask { Kind = BattlePhysicalBodyKind.StartGuard }); + stage.Executed[index] = true; + } + return require || PhysicalBodyIdle(actor); + } + if (!stage.Executed[index] && PhysicalBodyIdle(actor)) + { + if (index == 1) + QueuePhysicalApproach(stage); + else if (index == 2) + QueuePhysicalTask(actor, new PhysicalBodyTask { Kind = BattlePhysicalBodyKind.Attack, Run = stage.Run, Target = TargetForPhysicalTurn(actor, stage.Run), Animation = stage.Profile.Animation(BattlePose.Attacking) }); + else + QueuePhysicalReturn(stage, stage.Profile.Return(IsPal3ATransformed(actor.Initial.InstanceId))); + stage.Executed[index] = true; + } + if (index == 1) + { + if (actor.Initial.Side == BattleSide.Ally && !PhysicalTargetsAlive(stage.Run)) + return true; + TryStartProtection(stage); + } + return PhysicalBodyIdle(actor) || require && (index != 3 || actor.Hp == 0); + } + + private bool PhysicalTargetsAlive(ActionRun run) => run.Targets.Any(id => _byId[id].Alive); + + private Actor TargetForPhysicalTurn(Actor actor, ActionRun run) => ActionRange(actor, null) == BattleTargetRange.OpponentSingle && + run.Target != null && _byId.TryGetValue(run.Target, out Actor target) ? target : null; + + private BattleMovementPoint PhysicalHome(int index) + { + Actor actor = ActorAtNativeIndex(index); + if (actor != null) + return actor.Home; + BattleSide side = index < 5 ? BattleSide.Ally : BattleSide.Enemy; + Actor representative = _actors.First(candidate => candidate.Initial.Side == side); + return ((IBattleStageGeometry)_catalog).FormationHome(representative.Initial.InstanceId, (BattleSlot)(index < 5 ? index : index - 5)); + } + + private float PhysicalRadius(Actor actor) + { + PhysicalBodyState body = PhysicalBody(actor); + return (GetBodyBinding(actor).CurrentAnimation?.HalfDepth ?? 0f) - + (body.Profile.Identity == (body.Profile.Variant == "PAL3" ? 1 : 3) ? 10f : 0f); + } + + private void QueuePhysicalApproach(PhysicalStageRun stage) + { + Actor actor = stage.Source; + BattleTargetRange range = ActionRange(actor, null); + bool multi = range is BattleTargetRange.OpponentAll or BattleTargetRange.OpponentRow or BattleTargetRange.OpponentColumn; + int[] targets = stage.Run.Targets.Select(id => NativeActorIndex(_byId[id])).OrderBy(index => index).ToArray(); + var slots = _actors.Where(candidate => candidate.Initial.Side == BattleSide.Ally).ToDictionary(NativeActorIndex, candidate => candidate.Slot); + BattlePhysicalAnchor anchor = multi ? BattlePhysicalGeometry.Anchor(targets, slots, _scenario.SceneElement) : new BattlePhysicalAnchor(NativeActorIndex(_byId[stage.Run.Target])); + Actor target = ActorAtNativeIndex(anchor.First); + float radius = target != null ? PhysicalRadius(target) : 0; + BattleMovementPoint destination = BattlePhysicalGeometry.Approach(actor.Position, PhysicalRadius(actor), PhysicalHome(anchor.First), radius, + anchor.Second.HasValue ? PhysicalHome(anchor.Second.Value) : null, + spear: multi && stage.Profile.Identity == 4 && stage.Profile.Variant == "PAL3" && stage.Profile.WeaponType == 1, + doubleRadius: !multi && stage.Profile.ResourceId is 7364 or 7381); + float heading = BattleMovement.FacingBetween(actor.Position, destination); + foreach (BattlePhysicalBodyKind kind in stage.Profile.Approach(IsPal3ATransformed(actor.Initial.InstanceId))) + QueuePhysicalTask(actor, new PhysicalBodyTask + { + Kind = kind, + Destination = kind == BattlePhysicalBodyKind.Turn ? new BattleMovementPoint(heading, 0, 0) : destination, + Target = multi ? null : _byId[stage.Run.Target], + Run = stage.Run, + Animation = stage.Profile.Animation(BattlePose.Moving) + }); + } + + private void QueuePhysicalReturn(PhysicalStageRun stage, IReadOnlyList kinds) + { + foreach (BattlePhysicalBodyKind kind in kinds) + QueuePhysicalTask(stage.Source, new PhysicalBodyTask + { + Kind = kind, + Destination = kind == BattlePhysicalBodyKind.Turn ? new BattleMovementPoint(BattleFacingRules.Initial(stage.Source.Initial.Side), 0, 0) : stage.Source.Home, + Animation = stage.Profile.Animation(BattlePose.Moving) + }); + } + + private void QueuePhysicalTask(Actor actor, PhysicalBodyTask task) + { + PhysicalBodyState body = PhysicalBody(actor); + if (body.Tasks.Count >= 63) + throw new InvalidOperationException("The original body task pool is full."); + body.Tasks.Add(task); + } + + // One role pass executes one task, removes at most one finished task, + // and then clears pushed tasks that have already performed their work. + private bool AdvancePhysicalBody(Actor actor) + { + PhysicalBodyState body = PhysicalBody(actor); + if (body == null) + return false; + body.LocalTick = GetBodyBinding(actor).LocalTick; + if (body.Pushed) + { + if (!body.PushExecuted) + { + body.PushExecuted = true; + if (!body.PushDodge) + { + PlayHurtBodySound(actor, body); + ShowOriginalHitFlash(actor); + } + body.BladeSeconds = .25f; + BattlePose pose = body.PushDodge ? BattlePose.Dodging : actor.Guard ? BattlePose.GuardHurt : BattlePose.Hurt; + if (!Has(actor, BattleState.Paralysis) || body.PushDodge) + { + if (body.PushDodge ? GetBodyBinding(actor).RequestedNativeActionIndex == 44 : GetBodyBinding(actor).RequestedNativeActionIndex is 33 or 43 or 54) + { + ResetBodyAnimation(actor); + pose = GetBodyBinding(actor).LogicalPose; + } + else if (!body.PushDodge || actor.Initial.Side == BattleSide.Ally) + TryPlayBodyAnimation(actor, body.Profile.Animation(pose), false, pose, body.Profile.NativeAction(pose)); + } + body.Pose = pose; + return true; + } + if (GetBodyBinding(actor).LastPoppedMarker == BattlePhysicalMarkerKind.Over || + (body.PushDodge ? !actor.Alive : Has(actor, BattleState.Paralysis))) + { + body.Pushed = body.PushExecuted = false; + body.BladeSeconds = .01f; + actor.HurtUntil = checked((int)SimulationTick); + actor.Dodging = false; + if (!actor.Alive) + actor.ModelAlive = false; + } + return true; + } + if (body.Tasks.Count == 0 && body.PausedMovement is { } paused) + { + body.PausedMovement = null; + actor.Movement = new BattleMovement(_scenario.Variant, new BattleMovementPlan(paused.Kind, actor.Position, paused.To, + paused.FlyUpTick, paused.FlyDownTick, paused.OverTick, paused.TargetBlend, body.PausedBlend)); + actor.Movement.SetHeading(actor.FacingDegrees); + body.Pose = body.PausedPose; + TryPlayBodyAnimation(actor, body.PausedAnimation, true, body.Pose, body.PausedNativeAction); + AdvanceBodyMovement(actor, actor.Alive, BattleMovementMessage.None); + actor.Position = actor.Movement.Position; + if (actor.Movement.FacingDegrees is { } facing) + actor.FacingDegrees = facing; + return true; + } + if (body.Tasks.Count == 0) + { + EnsureProperBodyAnimation(actor); + return body.Owner != 0; + } + PhysicalBodyTask task = body.Tasks[0]; + AdvancePhysicalTask(actor, body, task); + body.LocalTick = GetBodyBinding(actor).LocalTick; + if (task.Finished) + { + body.Tasks.RemoveAt(0); + actor.Movement = null; + } + return true; + } + + private void AdvancePhysicalTask(Actor actor, PhysicalBodyState body, PhysicalBodyTask task) + { + if (task.Kind is BattlePhysicalBodyKind.FleeWait or BattlePhysicalBodyKind.EnemyFlee) + { + AdvanceFleeBody(actor, body, task); + return; + } + if (task.Kind is BattlePhysicalBodyKind.Turn or BattlePhysicalBodyKind.TurnToPosition or BattlePhysicalBodyKind.TurnToRole) + { + actor.FacingDegrees = task.Kind == BattlePhysicalBodyKind.Turn ? task.Destination.X : + BattleMovement.FacingBetween(actor.Position, task.Kind == BattlePhysicalBodyKind.TurnToRole && task.Target != null ? task.Target.Position : task.Destination); + if (task.Kind == BattlePhysicalBodyKind.Turn) + { + body.Pose = BattlePose.Idle; + TryPlayBodyAnimation(actor, body.Profile.Animation(BattlePose.Idle), true, BattlePose.Idle, body.Profile.NativeAction(BattlePose.Idle)); + } + task.Finished = true; + return; + } + if (task.Kind == BattlePhysicalBodyKind.StartGuard) + { + if (!task.Executed) + { + body.BladeSeconds = .01f; + actor.FacingDegrees = BattleFacingRules.Initial(actor.Initial.Side); + if (actor.Initial.Side == BattleSide.Ally) + { + body.Pose = BattlePose.GuardEntry; + TryPlayBodyAnimation(actor, body.Profile.Animation(body.Pose), false, body.Pose, body.Profile.NativeAction(body.Pose)); + } + task.Executed = true; + return; + } + if (!actor.Alive || GetBodyBinding(actor).LastPoppedMarker == BattlePhysicalMarkerKind.Over) + { + task.Finished = true; + body.BladeSeconds = .01f; + actor.Guard = true; + } + return; + } + if (task.Kind == BattlePhysicalBodyKind.Attack) + { + AdvancePhysicalAttackBody(actor, body, task); + return; + } + if (task.Kind == BattlePhysicalBodyKind.Protect) + { + AdvancePhysicalGuardBody(actor, body, task); + return; + } + if (task.Kind is BattlePhysicalBodyKind.ThrownWeapon or BattlePhysicalBodyKind.RestoreThrownWeapon) + { + AdvanceThrownWeaponBody(actor, body, task); + return; + } + if (!task.Executed) + { + BattleMovementKind kind = task.Kind switch + { + BattlePhysicalBodyKind.Fly => BattleMovementKind.Fly, + BattlePhysicalBodyKind.FlyRotate => BattleMovementKind.FlyRotate, + BattlePhysicalBodyKind.NpcFly => BattleMovementKind.NpcFly, + BattlePhysicalBodyKind.Teleport => BattleMovementKind.Teleport, + BattlePhysicalBodyKind.FastRun => BattleMovementKind.FastRun, + _ => BattleMovementKind.Run + }; + actor.Movement = new BattleMovement(_scenario.Variant, new BattleMovementPlan(kind, actor.Position, task.Destination, + targetBlend: Has(actor, BattleState.Invisible) ? .44f : 1f)); + actor.Movement.SetHeading(actor.FacingDegrees); + body.Pose = kind == BattleMovementKind.Teleport ? BattlePose.Idle : BattlePose.Moving; + bool nearAtStart = BattleMovement.Distance(actor.Position, task.Destination) < (kind == BattleMovementKind.FastRun ? 4f : 2f) && + !(body.Profile.Variant == "PAL3A" && kind == BattleMovementKind.Fly); + if (!nearAtStart) + TryPlayBodyAnimation(actor, body.Profile.Animation(body.Pose), true, body.Pose, body.Profile.NativeAction(body.Pose)); + body.BladeSeconds = kind == BattleMovementKind.FlyRotate ? .4f : .01f; + task.Executed = true; + Add(BattleEventKind.MovementStarted, actor.Initial.InstanceId, detail: kind.ToString()); + } + actor.Movement.SetTargetBlend(Has(actor, BattleState.Invisible) ? .44f : 1f); + AdvanceBodyMovement(actor, actor.Alive, CurrentBodyMovementMessage(actor)); + actor.Position = actor.Movement.Position; + if (actor.Movement.FacingDegrees is { } facing) + actor.FacingDegrees = facing; + if (task.Finished = actor.Movement.Finished) + Add(BattleEventKind.MovementEnded, actor.Initial.InstanceId); + } + + private void AdvancePhysicalAttackBody(Actor actor, PhysicalBodyState body, PhysicalBodyTask task) + { + if (!task.Executed) + { + body.BladeSeconds = .25f; + task.Finished = !PhysicalTargetsAlive(task.Run) || body.Profile.UsesThrownWeaponFor(IsPal3ATransformed(actor.Initial.InstanceId)); + if (!body.Profile.UsesThrownWeaponFor(IsPal3ATransformed(actor.Initial.InstanceId))) + { + body.Pose = BattlePose.Attacking; + TryPlayBodyAnimation(actor, task.Animation, false, BattlePose.Attacking, body.Profile.NativeAction(BattlePose.Attacking)); + if (body.Profile.TurnsAtAttack && task.Target != null) + actor.FacingDegrees = BattleMovement.FacingBetween(actor.Position, task.Target.Position); + } + task.Executed = true; + return; + } + BattlePhysicalMarkerKind? marker = GetBodyBinding(actor).LastPoppedMarker; + if (marker is >= BattlePhysicalMarkerKind.Work and <= BattlePhysicalMarkerKind.Work3) + { + task.DiscardOnPush = true; + PlayAttackBodySound(actor, body, marker.Value); + int count = body.Profile.DamageCount(marker.Value, IsPal3ATransformed(actor.Initial.InstanceId)); + // Both native bodies dispatch all repeats of this marker before checking source life. + for (int hit = 0; hit < count; hit++) + { + task.Run.NextHit++; + ResolveActionMarker(actor, task.Run); + } + } + if (!actor.Alive || marker == BattlePhysicalMarkerKind.Over) + task.Finished = true; + } + + private bool PushPhysicalBody(Actor actor, bool dodge) + { + PhysicalBodyState body = PhysicalBody(actor); + if (body == null) + return false; + body.Pushed = true; + body.PushExecuted = false; + body.PushDodge = dodge; + RestartOrdinaryAbilityBodyAfterPush(actor); + if (body.Tasks.Count == 0 && actor.Movement != null) + { + body.PausedMovement = actor.Movement.Plan; + body.PausedBlend = actor.Movement.Blend; + body.PausedAnimation = GetBodyBinding(actor).CurrentAnimation; + body.PausedPose = GetBodyBinding(actor).LogicalPose; + body.PausedNativeAction = GetBodyBinding(actor).RequestedNativeActionIndex; + } + if (body.Tasks.Count > 0 && body.Tasks[0].DiscardOnPush) + body.Tasks.RemoveAt(0); + if (body.Tasks.Count > 0) + body.Tasks[0].Executed = false; + actor.Movement = null; + return true; + } + + private void ClearPhysicalBody(Actor actor) + { + StopMovementBodySound(actor); + if (!_physicalBodies.TryGetValue(actor.Initial.InstanceId, out PhysicalBodyState body)) + return; + body.Tasks.Clear(); + body.Owner = 0; + body.Pushed = false; + body.PausedMovement = null; + actor.Movement?.Stop(); + actor.Movement = null; + actor.MovementQueue.Clear(); + actor.HurtUntil = checked((int)SimulationTick); + actor.Dodging = false; + } + + private void CancelPhysicalStage(ActionRun run) + { + if (run == null || !_physicalStages.Remove(run.Id, out PhysicalStageRun stage)) + return; + _stage.Cancel(stage.Handle); + ReleaseStageBody(stage.Source, stage.Handle); + } + + private void RequestPhysicalRoleEnd(Actor actor) + { + foreach (PhysicalStageRun stage in _protectionStages.Where(stage => stage.Source == actor)) + stage.EndRequested = true; + if (NativeActorIndex(actor) == _physicalProtectionTarget) + _physicalProtectionTarget = -1; + } + + private void CapturePhysicalPose(Actor actor, ref BattlePose pose, ref int localTick) + { + if (!_physicalBodies.TryGetValue(actor.Initial.InstanceId, out PhysicalBodyState body) || body.Owner == 0 && body.Tasks.Count == 0 && !body.Pushed) + return; + pose = body.Pose; + localTick = body.LocalTick; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.PhysicalPresentation.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.PhysicalPresentation.cs.meta new file mode 100644 index 00000000..055a428c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.PhysicalPresentation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e9a8aa269aff40d38ded18285d4466bb diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Presentation.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Presentation.cs new file mode 100644 index 00000000..882f89d9 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Presentation.cs @@ -0,0 +1,62 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private readonly HashSet _effectHandles = new(); + + private long StartEffect(BattleEffectRequest request) + { + if (_effects == null) + throw new InvalidOperationException("This battle has no effect director."); + long handle = _effects.Start(request); + if (handle <= 0 || !_effectHandles.Add(handle)) + throw new InvalidOperationException("An effect director must return a unique positive handle."); + return handle; + } + + private void PruneEffects() + { + if (_effects != null) + _effectHandles.RemoveWhere(handle => !_effects.IsRunning(handle)); + } + + private void StopEffect(long handle) + { + if (!_effectHandles.Remove(handle)) + return; + try + { + _effects.Stop(handle); + } + catch (Exception exception) when (_ending) + { + Add(BattleEventKind.PresentationCleanupFailed, detail: $"Effect {handle}: {exception.Message}"); + } + } + + private void StopEffects() + { + _soundingMovements.Clear(); + try + { + (_effects as IBattleMovementAudio)?.StopBodySounds(); + } + catch (Exception exception) + { + Add(BattleEventKind.PresentationCleanupFailed, detail: "Body sounds: " + exception.Message); + } + foreach (long handle in _effectHandles.ToArray()) + StopEffect(handle); + _absoluteTimeActor = null; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Presentation.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Presentation.cs.meta new file mode 100644 index 00000000..e55479a4 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Presentation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d4a9e803721b4da9baeb41583f1505e8 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Protection.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Protection.cs new file mode 100644 index 00000000..570af5bf --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Protection.cs @@ -0,0 +1,155 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Linq; + + public sealed partial class BattleSession + { + private string ValidatePhysicalProtection(string controller, string target) + { + if (Status != BattleSessionStatus.Running || _resolvingOutcome || controller == null || !_byId.TryGetValue(controller, out Actor guardian) || + !guardian.Ready || guardian.Run != null || !PhysicalBodyIdle(guardian) || IsUncontrollable(guardian)) + return "The protection controller is not ready."; + if (NativeActorIndex(guardian) != 0 || guardian.Initial.Side != BattleSide.Ally || !guardian.Alive || guardian.Slot != BattleSlot.Center) + return "Original protection requires the living player in native slot 0 at the center."; + BattleFormationRules rules = FormationRules(); + if (target == null) + { + // The command wheel checks occupied party slots, including fallen allies. + return _actors.Any(actor => rules.IsProtectionTargetSlot(NativeActorIndex(actor))) ? null : "队伍中没有可设置援护的角色。"; + } + if (!_byId.TryGetValue(target, out Actor protectedActor)) + return "The protection target is missing."; + BattleFormationDecision decision = rules.CanSetProtect(FormationActor(guardian), FormationActor(protectedActor)); + return decision.FailureReason; + } + + // The caller records a SetProtection input only when this changes the + // selection. Native confirmation of an unchanged selection returns to UI. + private bool ApplyPhysicalProtection(string controller, string target) + { + if (ValidatePhysicalProtection(controller, target) != null) + return false; + int selection = target == null ? -1 : NativeActorIndex(_byId[target]); + if (selection == _physicalProtectionTarget) + return false; + _physicalProtectionTarget = selection; + Actor actor = _byId[controller]; + AdvanceFiveSpiritFieldTurn(actor); + actor.Gauge = actor.CastGauge = 0; + actor.Ready = false; + return true; + } + + private void TryStartProtection(PhysicalStageRun attack) + { + if (!attack.CanStartProtection || attack.Source.Initial.Side != BattleSide.Enemy || _physicalProtectionTarget < 0) + return; + Actor guardian = ActorAtNativeIndex(0); + Actor target = ActorAtNativeIndex(_physicalProtectionTarget); + if (guardian == null || target == null || !attack.Run.Targets.Contains(target.Initial.InstanceId) || _catalog is not IBattlePhysicalTimings) + return; + double distance = BattleMovement.Distance(target.Position, attack.Source.Position); + if (distance >= 120f || distance <= 50f) + return; + BattleFormationActor guardianSnapshot = FormationActor(guardian); + var idleGuardian = new BattleFormationActor(guardianSnapshot.Index, guardianSnapshot.ResourceId, guardianSnapshot.Slot, + guardianSnapshot.WeaponType, valid: guardianSnapshot.Valid, alive: guardianSnapshot.Alive, + hp: guardianSnapshot.Hp, maxHp: guardianSnapshot.MaxHp, states: guardian.States.Keys, + idle: PhysicalBodyIdle(guardian), atHome: IsAtHome(guardian), fled: guardian.Escaped); + if (!FormationRules().CanProtect(_physicalProtectionTarget, idleGuardian, FormationActor(target)).Allowed) + return; + var stage = new PhysicalStageRun + { + Session = this, + Source = guardian, + Protected = target, + Attacker = attack.Source, + Profile = PhysicalBody(guardian).Profile, + Protection = true + }; + if (!_stage.TryAdd(guardian.Initial.InstanceId, "protection", stage, + BattleStageScheduler.TimeAt(SimulationTick), out BattleStageHandle handle)) + return; + stage.Handle = handle; + _protectionStages.Add(stage); + attack.CanStartProtection = false; + } + + private bool AdvanceProtectionSubtask(PhysicalStageRun stage, int index, bool require) + { + Actor guardian = stage.Source; + if (!stage.Executed[index]) + { + if (PhysicalBodyIdle(guardian)) + { + if (index == 1) + { + BattleMovementPoint destination = BattlePhysicalGeometry.ProtectRunTarget(guardian.Position, stage.Protected.Home, stage.Attacker.Home); + QueuePhysicalTask(guardian, new PhysicalBodyTask + { + Kind = BattlePhysicalBodyKind.FastRun, + Destination = destination, + Animation = stage.Profile.Animation(BattlePose.Moving) + }); + QueuePhysicalTask(guardian, new PhysicalBodyTask + { + Kind = BattlePhysicalBodyKind.Turn, + Destination = new BattleMovementPoint(BattleFacingRules.Initial(guardian.Initial.Side), 0, 0) + }); + } + else if (index == 2) + QueuePhysicalTask(guardian, new PhysicalBodyTask + { + Kind = BattlePhysicalBodyKind.Protect, + Target = stage.Protected, + Animation = stage.Profile.Animation(BattlePose.Guard) + }); + else + QueuePhysicalReturn(stage, new[] { BattlePhysicalBodyKind.Run, BattlePhysicalBodyKind.Turn }); + stage.Executed[index] = true; + } + else if (index == 1) + return true; + } + return require || PhysicalBodyIdle(guardian); + } + + private bool HasEnemyPhysicalAttack(Actor target) => _physicalStages.Values.Any(stage => !stage.Finished && + stage.Source.Initial.Side == BattleSide.Enemy && stage.Run.Targets.Contains(target.Initial.InstanceId)); + + private void AdvancePhysicalGuardBody(Actor actor, PhysicalBodyState body, PhysicalBodyTask task) + { + if (!task.Executed) + { + task.Executed = true; + body.Pose = BattlePose.Guard; + TryPlayBodyAnimation(actor, task.Animation, true, BattlePose.Guard, body.Profile.NativeAction(BattlePose.Guard)); + body.BladeSeconds = .25f; + return; + } + BattlePhysicalMarkerKind? marker = GetBodyBinding(actor).LastPoppedMarker; + if ((!actor.Alive || marker == BattlePhysicalMarkerKind.Over) && + (!HasEnemyPhysicalAttack(task.Target) || !IsAtHome(task.Target) || !task.Target.Alive)) + { + task.Finished = true; + body.BladeSeconds = .01f; + } + } + + private bool TryGetPhysicalProtector(Actor attacker, Actor target, out Actor guardian) + { + guardian = ActorAtNativeIndex(0); + return target.Initial.Side == BattleSide.Ally && guardian != null && _physicalProtectionTarget != 0 && + NativeActorIndex(target) == _physicalProtectionTarget && guardian.Alive && guardian.Slot == BattleSlot.Center && + !Has(guardian, BattleState.Paralysis) && IsAtHome(target) && + BattlePhysicalGeometry.AtProtectPosition(NativeActorIndex(guardian), guardian.Position, target.Home, attacker.Home) && + _protectionStages.Any(stage => !stage.Finished && _stage.IsActive(stage.Handle)); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Protection.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Protection.cs.meta new file mode 100644 index 00000000..9b0794f9 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Protection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 866ca523f31c429eb8bbdb242091ff7f diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ProtectionControl.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ProtectionControl.cs new file mode 100644 index 00000000..6363d2d1 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ProtectionControl.cs @@ -0,0 +1,28 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + public sealed partial class BattleSession + { + public string CanSetProtection(string controller, string target) + { + if (_catalog is not IBattlePhysicalTimings) + return "This catalog has no original protection body tasks."; + if (WaitingActor != controller || ActiveFormationController != null) + return "Choose the current ready controller."; + return ValidatePhysicalProtection(controller, target); + } + + public bool SetProtection(string controller, string target) + { + if (CanSetProtection(controller, target) != null || !ApplyPhysicalProtection(controller, target)) + return false; + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.SetProtection, Actor = controller, Target = target }); + Add(BattleEventKind.ProtectionChanged, controller, target, detail: target == null ? "protection cleared" : "protection selected"); + return true; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ProtectionControl.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ProtectionControl.cs.meta new file mode 100644 index 00000000..83e0d9da --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ProtectionControl.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2d94d4b1110d40c8a821ee0bb806f49c diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Relations.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Relations.cs new file mode 100644 index 00000000..32fc3b37 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Relations.cs @@ -0,0 +1,33 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + public sealed partial class BattleSession + { + private void ChangeLove(Actor actor, int requested) + { + int before = actor.Love; + BattleRelationChange change = BattleRelationRules.Change(_scenario.Variant, NativeActorIndex(actor), before, requested, + ActorAtNativeIndex(0) != null); + if (!change.Applied) + return; + actor.Love = change.Value; + if (change.Sound != null) + PlaySound(change.Sound); + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.RelationChanged, + Target = actor.Initial.InstanceId, + RequestedDelta = requested, + ActualDelta = unchecked(change.Value - before), + ValueBefore = before, + ValueAfter = change.Value, + Detail = change.Sound + }); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Relations.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Relations.cs.meta new file mode 100644 index 00000000..32f2becb --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Relations.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 93cd7512006b436599dfb21ba8ea96f6 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.RemainingSpecials.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.RemainingSpecials.cs new file mode 100644 index 00000000..31a68b81 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.RemainingSpecials.cs @@ -0,0 +1,65 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private readonly Dictionary _absorbHpWormRounds = new(StringComparer.Ordinal); + + public int? AbsorbHpWormRound(string actor) => actor != null && _absorbHpWormRounds.TryGetValue(actor, out int round) ? round : null; + + private void RandomizeOriginalFormation(Actor source, long actionId) + { + Actor[] allies = _actors.Where(actor => actor.Initial.Side == BattleSide.Ally).OrderBy(NativeActorIndex).ToArray(); + // Valid roles include dead and fled participants. The published gate + // tests scene position and stage tasks, without a living-role filter. + if (allies.Any(actor => !IsAtHome(actor) || _stage.CountOwner(actor.Initial.InstanceId) > 0)) + return; + var geometry = (IBattleStageGeometry)_catalog; + string controller = _formationController; + _formationController = null; + _formationInitialSlots = null; + if (controller != null) + Add(BattleEventKind.FormationClosed, controller, actionId: actionId, detail: "random formation forced control release; no gauge cost"); + IReadOnlyList lineup = BattleSpecialRules.RandomFormation(_random); + foreach (Actor actor in allies) + { + BattleSlot before = actor.Slot; + actor.Slot = lineup[NativeActorIndex(actor)]; + actor.Home = geometry.FormationHome(actor.Initial.InstanceId, actor.Slot); + SetActorPosition(actor, actor.Home); + Add(BattleEventKind.FormationChanged, source.Initial.InstanceId, actor.Initial.InstanceId, actionId, + before + " -> " + actor.Slot + "; original random lineup changed position/home immediately"); + } + } + + private void ApplyOriginalAbsorbHpWorm(Actor target) => _absorbHpWormRounds[target.Initial.InstanceId] = 0; + + private void ClearOriginalAbsorbHpWorm(Actor target) => _absorbHpWormRounds.Remove(target.Initial.InstanceId); + + private void AdvanceOriginalAbsorbHpWormOnRound(Actor target) + { + if (_scenario.Variant != "PAL3" || !_absorbHpWormRounds.TryGetValue(target.Initial.InstanceId, out int before)) + return; + int round = before + 1; + if (round >= 4) + ClearOriginalAbsorbHpWorm(target); + else + _absorbHpWormRounds[target.Initial.InstanceId] = round; + int request = BattleSpecialRules.AbsorbHpWormRequest(target.Attributes[0], round); + Actor recipient = ActorAtNativeIndex(3); + ChangeHp(target, request, recipient, 0, "original absorb HP worm round " + round); + // Native always asks identity 3 for the full opposite request, + // independently of the actual target loss or the casting identity. + if (recipient != null) + ChangeHp(recipient, -request, null, 0, "original absorb HP worm recovery"); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.RemainingSpecials.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.RemainingSpecials.cs.meta new file mode 100644 index 00000000..6db0176c --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.RemainingSpecials.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 33345222771445568d7937be61319ad7 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Resurrection.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Resurrection.cs new file mode 100644 index 00000000..9b25cc41 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Resurrection.cs @@ -0,0 +1,47 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + public sealed partial class BattleSession + { + private void QueuePhysicalRevivalReturn(Actor actor) + { + if (_catalog is not IBattlePhysicalTimings || IsAtHome(actor)) + return; + var stage = new PhysicalStageRun + { + Session = this, + Source = actor, + Profile = PhysicalBody(actor).Profile, + RevivalReturn = true + }; + if (_stage.TryAdd(actor.Initial.InstanceId, "revival return", stage, BattleStageScheduler.TimeAt(SimulationTick), out BattleStageHandle handle)) + stage.Handle = handle; + } + + // CBST_GotoInitPos differs from the ordinary attack's return routing: + // PAL3 Zixuan flies without rotation, and PAL3A ignores weapon/form. + private BattlePhysicalBodyKind RevivalReturnKind(Actor actor) => NativeActorIndex(actor) switch + { + 2 => BattlePhysicalBodyKind.Teleport, + 1 or 3 when _scenario.Variant == "PAL3" => BattlePhysicalBodyKind.Fly, + _ => BattlePhysicalBodyKind.Run + }; + + private bool AdvanceRevivalReturn(PhysicalStageRun stage, int index) + { + if (index != 1) + return true; + if (!stage.Executed[index] && PhysicalBodyIdle(stage.Source)) + { + QueuePhysicalReturn(stage, new[] { RevivalReturnKind(stage.Source), BattlePhysicalBodyKind.Turn }); + stage.Executed[index] = true; + } + // The native return callback deliberately ignores RequireToEnd. + return PhysicalBodyIdle(stage.Source); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Resurrection.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Resurrection.cs.meta new file mode 100644 index 00000000..f652e9cf --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Resurrection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e9cd368c163345779ca0ba327f290d64 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ScenePresentation.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ScenePresentation.cs new file mode 100644 index 00000000..fc59aa19 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ScenePresentation.cs @@ -0,0 +1,14 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + public sealed partial class BattleSession + { + public BattleEncounter Encounter => _scenario.Encounter; + + public int SceneElement => _scenario.SceneElement; + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ScenePresentation.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ScenePresentation.cs.meta new file mode 100644 index 00000000..1339ecc3 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ScenePresentation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 14828d4512554fd896e87fd8dbfa05a6 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Settlement.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Settlement.cs new file mode 100644 index 00000000..f5d93434 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Settlement.cs @@ -0,0 +1,259 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private BattleResult BuildResult(BattleSessionStatus status, BattleSide? winner, string reason) + { + int settlementEventStart = _events.Count; + IReadOnlyList preSettlementActors = Actors; + FlushPal3ASpiritOrbs(); + IReadOnlyList rewards = Array.Empty(); + IReadOnlyList loot = Array.Empty(); + if (Definitions != null && status == BattleSessionStatus.Completed && (winner == BattleSide.Ally || _partyEscaped)) + { + if (!_partyEscaped) + foreach (Actor actor in _actors.Where(actor => actor.Initial.Side == BattleSide.Ally)) + foreach (BattleState state in new[] { BattleState.Paralysis, BattleState.Sleep, BattleState.Invisible }) + ApplyState(actor, state, true); + rewards = SettleExperienceAndSkills(); + loot = SettleLootAndMoney(); + foreach (Actor actor in _actors.Where(actor => actor.Initial.Side == BattleSide.Ally && actor.Hp == 0 && + (!_partyEscaped || _scenario.Variant == "PAL3A"))) + { + actor.Hp = Math.Min(1, actor.Attributes[0]); + ChangeLove(actor, -2); + } + } + return new BattleResult + { + SettlementEventStart = settlementEventStart, + PreSettlementActors = preSettlementActors, + Status = status, + GameOver = status == BattleSessionStatus.Completed && winner == BattleSide.Enemy && _scenario.GameOverOnDefeat, + Winner = winner, + Reason = reason, + Tick = Tick, + Actors = Actors, + MoneyBefore = _scenario.Money, + MoneyAfter = _money, + Pal3A = _scenario.Variant == "PAL3A" ? Pal3AState : null, + Escaped = _partyEscaped, + Rewards = rewards, + Items = Inventory, + TreasureUses = TreasureUses, + MagicSwords = MagicSwords, + StealPools = StealPools, + Loot = loot + }; + } + + private IReadOnlyList SettleExperienceAndSkills() + { + Actor[] dead = _actors.Where(actor => actor.Initial.Side == BattleSide.Enemy && actor.Hp <= 0 && !actor.Escaped).OrderBy(NativeActorIndex).ToArray(); + Actor[] survivors = _actors.Where(actor => actor.Initial.Side == BattleSide.Ally && actor.Hp > 0 && !actor.Escaped).ToArray(); + var gains = _actors.Where(actor => actor.Initial.Side == BattleSide.Ally).ToDictionary(actor => actor.Initial.InstanceId, actor => 0); + // PAL3A's flee path runs only the commit pass. Unlike PAL3, it + // never allocates new experience from enemies killed this battle. + if (survivors.Length > 0 && (!_partyEscaped || Definitions.Variant == "PAL3")) + { + int shared = dead.Aggregate(0, (sum, actor) => unchecked(sum + Math.Max(0, actor.Definition.ExperienceReward))) / survivors.Length; + foreach (Actor actor in survivors) + gains[actor.Initial.InstanceId] = shared; + } + if (!_partyEscaped) + { + Actor last = dead.Where(actor => actor.DeathTick > 0).OrderByDescending(actor => actor.DeathTick).FirstOrDefault(); + if (last?.Killer != null && gains.ContainsKey(last.Killer)) + { + int finishingExperience = dead.Where(actor => actor.DeathTick >= last.DeathTick && actor.Killer == last.Killer) + .Aggregate(0, (sum, actor) => unchecked(sum + Math.Max(0, actor.Definition.ExperienceReward))); + gains[last.Killer] += finishingExperience * 3 / 10; + } + } + var reports = new List(); + foreach (Actor actor in _actors.Where(actor => actor.Initial.Side == BattleSide.Ally).OrderBy(NativeActorIndex)) + { + int beforeLevel = actor.Level, beforeExperience = actor.Experience; + int[] beforeAttributes = actor.Attributes.ToArray(); + int gained = 0; + if (actor.Hp > 0 && !actor.Escaped) + { + int bonus = actor.Definition.Equipment.Where(item => item.Slot != 0).Sum(item => item.SpecialEffect switch { 20 => 5, 21 => 15, 24 => 20, _ => 0 }); + gained = BattleBasicRules.Round(gains[actor.Initial.InstanceId] * (float)(100 + bonus) / 100); + // The released commit adds signed int32 values before CalLevel. + // A wrapped runtime result is distinct from validated initial EXP. + actor.Experience = unchecked(actor.Experience + gained); + // CalLevel compares its DWORD table with unsigned JA, including + // wrapped negative EXP. Only a higher resulting level commits growth. + if (actor.Definition.ExperienceThresholds.Count == 101) + while (actor.Level < 100 && unchecked((uint)actor.Experience) >= unchecked((uint)actor.Definition.ExperienceThresholds[actor.Level + 1])) + actor.Level++; + if (actor.Level > beforeLevel) + { + if (!string.IsNullOrEmpty(actor.Definition.GrowthUnsupportedReason) || actor.Definition.AttributesByLevel.Count <= actor.Level) + throw new NotSupportedException("Level-up has no verified original growth definition for " + actor.Initial.InstanceId); + for (int attribute = 0; attribute <= 4; attribute++) + actor.Attributes[attribute] = unchecked(actor.Attributes[attribute] + actor.Definition.AttributesByLevel[actor.Level][attribute] - actor.Definition.AttributesByLevel[beforeLevel][attribute]); + actor.Hp = Math.Max(0, actor.Attributes[0]); + actor.Sp = Math.Max(0, actor.Attributes[1]); + actor.Mp = Math.Max(0, actor.Attributes[2]); + Add(BattleEventKind.LevelUp, actor.Initial.InstanceId, detail: beforeLevel + " → " + actor.Level); + foreach (BattleAbilityDefinition technique in Definitions.Skills.Values.Where(ability => !ability.IsMagic && ability.SkillTypeId == 0 && + ability.ApplicableIdentities.Contains(actor.Definition.Identity) && ability.LearningLevel > 0 && ability.LearningLevel <= actor.Level).OrderBy(ability => ability.Id)) + LearnSkill(actor, technique.Id); + } + SettleSkillGrowth(actor); + } + reports.Add(new BattleActorReward + { + Actor = actor.Initial.InstanceId, + ExperienceGained = gained, + LevelBefore = beforeLevel, + LevelAfter = actor.Level, + ExperienceBefore = beforeExperience, + ExperienceAfter = actor.Experience, + AttributesBefore = Array.AsReadOnly(beforeAttributes), + AttributesAfter = Array.AsReadOnly(actor.Attributes.ToArray()) + }); + } + return reports.AsReadOnly(); + } + + private bool LearnSkill(Actor actor, int id) + { + if (!Definitions.Skills.TryGetValue(id, out BattleAbilityDefinition definition) || !definition.ApplicableIdentities.Contains(actor.Definition.Identity)) + return false; + BattleSkill existing = actor.Skills.FirstOrDefault(skill => skill.Id == id); + if (existing?.Mastered == true) + return false; + if (existing == null) + { + existing = new BattleSkill { Id = id }; + actor.Skills.Add(existing); + } + existing.Mastered = true; + existing.Level = 1; + existing.Uses = 0; + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.SkillLearned, + Source = actor.Initial.InstanceId, + AbilityId = id, + RandomState = _random.State, + Detail = definition.Name + }); + return true; + } + + private void SettleSkillGrowth(Actor actor) + { + IReadOnlyList slots = BattleMagicSlots.Capture(Definitions.Variant, Definitions, actor.Definition.Identity, actor.Skills); + // Only newly learned next-chain magic restarts the published pass. + // Composite learning alone does not rescan a previously visited slot. + int limit = Definitions.Skills.Count + 1; + for (int pass = 0; pass < limit; pass++) + { + foreach (BattleMagicSlot slot in slots) + { + BattleSkill skill = actor.Skills.FirstOrDefault(candidate => candidate.Id == slot.SkillId && candidate.Mastered); + if (skill == null) + continue; + BattleAbilityDefinition definition = slot.Definition; + int before = skill.Level; + for (int tier = Math.Min(4, definition.UsesBeforeLevelUp.Count); tier > skill.Level; tier--) + if (skill.Uses >= definition.UsesBeforeLevelUp[tier - 1]) + { + skill.Level = tier; + break; + } + if (skill.Level != before) + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.SkillImproved, + Source = actor.Initial.InstanceId, + AbilityId = skill.Id, + ValueBefore = before, + ValueAfter = skill.Level, + RandomState = _random.State, + Detail = definition.Name + }); + } + foreach (BattleMagicSlot slot in slots) + { + BattleSkill skill = actor.Skills.FirstOrDefault(candidate => candidate.Id == slot.SkillId && candidate.Mastered); + if (skill == null) + continue; + foreach (BattleSkillUnlock unlock in slot.Definition.Unlocks) + { + BattleSkill other = actor.Skills.FirstOrDefault(candidate => candidate.Id == unlock.OtherSkillId && candidate.Mastered); + if (skill.Level >= unlock.SelfTier && actor.Level >= unlock.ActorLevel && other != null && other.Level >= unlock.OtherTier && + slots.Any(candidate => candidate.SkillId == unlock.OtherSkillId) && slots.Any(candidate => candidate.SkillId == unlock.SkillId)) + LearnSkill(actor, unlock.SkillId); + } + } + bool nextLearned = false; + foreach (BattleMagicSlot slot in slots) + { + BattleSkill skill = actor.Skills.FirstOrDefault(candidate => candidate.Id == slot.SkillId && candidate.Mastered); + BattleAbilityDefinition definition = slot.Definition; + if (skill != null && definition.NextSkillId > 0 && skill.Level >= definition.NextSkillRequiredProficiency && + actor.Level >= definition.LearningLevel && slots.Any(candidate => candidate.SkillId == definition.NextSkillId)) + nextLearned |= LearnSkill(actor, definition.NextSkillId); + } + if (!nextLearned) + return; + } + throw new InvalidOperationException("Skill growth graph did not converge."); + } + + private IReadOnlyList SettleLootAndMoney() + { + Actor[] dead = _actors.Where(actor => actor.Initial.Side == BattleSide.Enemy && actor.Hp <= 0 && !actor.Escaped).OrderBy(NativeActorIndex).ToArray(); + int baseMoney = dead.Aggregate(0, (sum, actor) => unchecked(sum + Math.Max(0, actor.Definition.MoneyReward))); + int bonus = _actors.Where(actor => actor.Initial.Side == BattleSide.Ally).Sum(actor => + actor.Definition.Equipment.Count(item => item.Slot != 0 && item.SpecialEffect == 21) * 5); + // Published reward accumulators and arithmetic use signed int32 wrap. + int reward = unchecked(baseMoney + (int)(baseMoney * (float)bonus / 100)); + int before = _money; + _money = (int)Math.Clamp((long)_money + reward, 0, int.MaxValue); + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.ResourceChanged, + Resource = 10, + ValueBefore = before, + ValueAfter = _money, + RequestedDelta = reward, + ActualDelta = _money - before, + RandomState = _random.State, + Detail = "ordinary combat money reward" + }); + var drops = new Dictionary(); + void Receive(int item, int count, string reason) + { + if (item <= 0 || count <= 0) + return; + int received = ChangeItem(item, count, null, reason); + if (received > 0) + drops[item] = drops.GetValueOrDefault(item) + received; + } + foreach (Actor actor in dead) + { + Receive(actor.Definition.LootItem, actor.Definition.LootCount, "ordinary combat loot; no drop probability roll"); + Receive(actor.CorpseItem, 1, "original corpse loot; success was rolled at the ability marker"); + } + return Array.AsReadOnly(drops.OrderBy(pair => pair.Key).Select(pair => new BattleItemSnapshot(pair.Key, pair.Value)).ToArray()); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Settlement.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Settlement.cs.meta new file mode 100644 index 00000000..735e8982 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Settlement.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9ec9bb4c85dc48409f597f060886f0ce diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Specials.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Specials.cs new file mode 100644 index 00000000..2035fa1e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Specials.cs @@ -0,0 +1,251 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private sealed class StealPool + { + public int Money, ItemId, ItemCount; + } + + private readonly Dictionary _stealPools = new(StringComparer.Ordinal); + private readonly Dictionary _treasureUses = new(); + private readonly List _inventoryOrder = new(); + + public IReadOnlyList TreasureUses => Array.AsReadOnly(_treasureUses.OrderBy(pair => pair.Key) + .Select(pair => new BattleItemSnapshot(pair.Key, pair.Value)).ToArray()); + + public IReadOnlyList StealPools => Array.AsReadOnly(_stealPools.OrderBy(pair => pair.Key, StringComparer.Ordinal) + .Select(pair => new BattleStealPoolSnapshot(pair.Key, pair.Value.Money, pair.Value.ItemId, pair.Value.ItemCount)).ToArray()); + + public IReadOnlyList InventoryEntries => Array.AsReadOnly(_inventoryOrder + .Select(id => new BattleItemSnapshot(id, _inventory[id])).ToArray()); + + private void InitializeSpecialResources(BattleScenario scenario) + { + _inventoryOrder.AddRange(scenario.Items.Select(item => item.Id)); + foreach (BattleItem item in scenario.TreasureUses) + _treasureUses.Add(item.Id, item.Count); + } + + private void InitializeActorSpecials(Actor actor) + { + _stealPools.Add(actor.Initial.InstanceId, new StealPool + { + Money = actor.Definition.StealableMoney, + ItemId = actor.Definition.StealableItemId, + ItemCount = actor.Definition.StealableItemCount + }); + } + + private void InitializeStartupSpecials() + { + if (Definitions == null || Definitions.Variant != "PAL3") + return; + // Native InitAllObj initializes every gauge before this identity-ordered equipment roll. + foreach (Actor actor in _actors.Where(actor => actor.Initial.Side == BattleSide.Ally) + .OrderBy(actor => actor.Definition.Identity).ThenBy(actor => actor.Initial.InstanceId, StringComparer.Ordinal)) + if (actor.Definition.Equipment.Any(item => item.StartupInvisibility) && _random.Probability(10)) + ApplyState(actor, BattleState.Invisible, false); + } + + private bool CanManuallySelectTarget(Actor target, bool own, BattleAbilityDefinition ability) + { + if (own) + return !IsPal3ATransformed(target.Initial.InstanceId); + // PAL3 CanBeSelect exempts Wan Yi Gu (4401) from the Hermit check. + return _scenario.Variant != "PAL3" || ability?.Id == 4401 || !Has(target, BattleState.Invisible); + } + + private string ValidateSpecialCommand(BattleAbilityDefinition ability) + { + if (ability.Handler == BattleSpecialHandler.RandomFormation && _catalog is not IBattleStageGeometry) + return "Random formation needs the original scene's formation positions."; + if (!ability.IsTreasure) + return null; + if (!BattleSpecialRules.IsTreasure(Definitions.Variant, ability.Id)) + return "This treasure has no original usage counter in the selected variant."; + int reserved = _actors.Count(actor => actor.Run is { Kind: BattleAction.Item, ItemConsumed: false } && + actor.Run.Ability.Id == ability.Id); + return _treasureUses.GetValueOrDefault(ability.Id) > reserved ? null : "No independent treasure use remains."; + } + + private int PrimaryActorLevel() => _actors.FirstOrDefault(actor => actor.Definition?.Identity == 0)?.Level ?? 0; + + private int SpecialRequiredCost(BattleAbilityDefinition ability, BattleCost cost, int ordinaryRequired) + { + return cost.Resource != 10 ? ordinaryRequired : BattleSpecialRules.RequiredMoney(Definitions.Variant, ability.Handler, ordinaryRequired, + _actors.Count(actor => actor.Initial.Side == BattleSide.Ally && actor.Hp > 0 && !actor.Escaped), PrimaryActorLevel()); + } + + private void ConsumeItemAtStart(Actor actor, BattleAbilityDefinition ability) + { + if (!ability.IsTreasure) + { + ChangeItem(ability.Id, -1, actor.Initial.InstanceId, "item consumed when its action starts"); + return; + } + int before = _treasureUses.GetValueOrDefault(ability.Id); + if (before <= 0) + throw new InvalidOperationException("A treasure counter cannot become negative."); + _treasureUses[ability.Id] = before - 1; + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.TreasureUseChanged, + Source = actor.Initial.InstanceId, + AbilityId = ability.Id, + ValueBefore = before, + ValueAfter = before - 1, + RequestedDelta = -1, + ActualDelta = -1, + RandomState = _random.State, + Detail = "independent treasure use consumed at action start; inventory retained" + }); + } + + private bool ResolveSpecialBeforeStates(Actor source, Actor target, ActionRun run) + { + switch (run.Ability.Handler) + { + case BattleSpecialHandler.ForceFlee: + ResolveForceFlee(source, target); + break; + case BattleSpecialHandler.RandomPoison: + ApplyRandomPoison(source, target, run.Id); + break; + case BattleSpecialHandler.Summon: + ResolveOriginalSummon(source, run.Id); + break; + case BattleSpecialHandler.RandomFormation: + RandomizeOriginalFormation(source, run.Id); + break; + case BattleSpecialHandler.PoisonDragonGall: + if (!target.States.Keys.Any(IsPoisonState)) + { + ChangeHp(target, -99999999, source, run.Id, "poison dragon gall used on an unpoisoned target"); + return true; // Native ItemAffect returns zero before ordinary states, values and interrupt handling. + } + break; + } + return false; + } + + private void ResolveSpecialAfterValues(Actor source, Actor target, ActionRun run, int oldHp, int returned) + { + switch (run.Ability.Handler) + { + case BattleSpecialHandler.HalfActualHpAbsorb: + ChangeHp(source, BattleSpecialRules.HalfActualHp(oldHp, target.Hp), source, run.Id, "half actual HP absorption"); + break; + case BattleSpecialHandler.ReturnedMpAbsorb: + ChangeResource(source, 2, BattleSpecialRules.AbsorbedMp(returned), source, run.Id, "native returned MP absorption"); + break; + case BattleSpecialHandler.AbsorbHpWorm: + ApplyOriginalAbsorbHpWorm(target); + break; + } + } + + private void ResolveSpecialAfterTarget(Actor source, Actor target, ActionRun run) + { + if (run.Ability.Handler == BattleSpecialHandler.Steal) + StealFrom(source, target, run.Id); + } + + private static bool IsPoisonState(BattleState state) => state >= BattleState.PoisonWind && state <= BattleState.PoisonEarth; + + private void ApplyRandomPoison(Actor source, Actor target, long actionId) + { + if (Has(target, BattleState.PoisonResist) || target.Definition.ImmuneStates.Contains(BattleState.PoisonResist) || target.States.Keys.Any(IsPoisonState)) + return; + ApplyState(target, (BattleState)(_random.Next() % 5), false, source: source, actionId: actionId); + } + + private void StealFrom(Actor source, Actor target, long actionId) + { + StealPool pool = _stealPools[target.Initial.InstanceId]; + int money = BattleSpecialRules.StealAmount(pool.Money, _random); + if (money > 0) + { + ChangeStealPool(source, target, actionId, pool, true, money); + ChangeResource(source, 10, money, source, actionId, "stolen money"); + } + // Original dispatch draws money first, then independently draws an item quantity. + int count = pool.ItemId > 0 ? BattleSpecialRules.StealAmount(pool.ItemCount, _random) : 0; + if (count > 0) + { + ChangeStealPool(source, target, actionId, pool, false, count); + PlaySound("wa006"); + ChangeItem(pool.ItemId, count, source.Initial.InstanceId, "stolen item"); + } + if (money == 0 && count == 0) + Add(BattleEventKind.Miss, source.Initial.InstanceId, target.Initial.InstanceId, actionId, "nothing remains in the independent stealable pool"); + } + + private void ChangeStealPool(Actor source, Actor target, long actionId, StealPool pool, bool money, int amount) + { + int before = money ? pool.Money : pool.ItemCount; + if (amount < 0 || amount > before) + throw new InvalidOperationException("Invalid stealable-pool change."); + if (money) + pool.Money -= amount; + else + pool.ItemCount -= amount; + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.StealPoolChanged, + Source = source.Initial.InstanceId, + Target = target.Initial.InstanceId, + ActionId = actionId, + Resource = money ? 10 : -1, + AbilityId = money ? 0 : pool.ItemId, + ValueBefore = before, + ValueAfter = before - amount, + RequestedDelta = -amount, + ActualDelta = -amount, + RandomState = _random.State, + Detail = money ? "stealable money" : "stealable item quantity" + }); + } + + private void ResolvePhysicalSpecial(Actor source, Actor target, ActionRun run, int mode) + { + if (mode == 929) + return; // Published Special30 succeeds without effects, service calls or RNG. + if (mode == 913) + return; // Published Special27 is a verified no-op for legal nonnegative money, without RNG. + if (mode != 914 || target.Initial.Side != BattleSide.Ally) + return; + int[] eligible = _inventoryOrder.Where(id => Definitions.Items.TryGetValue(id, out BattleAbilityDefinition item) && item.ItemType == 1 && + (Definitions.Variant == "PAL3" || item.Revives || item.Attributes.Any(effect => effect.Attribute < 3 && + (effect.Mode == BattleValueMode.RecoverToMax || effect.Value > 0)))).ToArray(); + if (eligible.Length == 0) + return; + int chosen = eligible[_random.Next() % eligible.Length]; + ChangeItem(chosen, Definitions.Variant == "PAL3" ? -_inventory[chosen] : -1, source.Initial.InstanceId, "enemy recovery-item theft"); + } + + private void ResolveAttackSteal(Actor source, Actor target, ActionRun run) + { + if (_random.Probability(EquipmentBonus(source, item => item.AttackStealPercent))) + StealFrom(source, target, run.Id); + } + + private int ApplyMoneyShield(Actor target, int signedRequest, Actor source, long actionId) + { + int remaining = BattleSpecialRules.ShieldedHpRequest(signedRequest, _money, out int payment); + ChangeResource(target, 10, -payment, source, actionId, "money shield paid HP request"); + return remaining; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Specials.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Specials.cs.meta new file mode 100644 index 00000000..9507485d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Specials.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 456cf8c1dcc1445d86fc69f02be9ebc4 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.SpiritCapture.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.SpiritCapture.cs new file mode 100644 index 00000000..70d42168 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.SpiritCapture.cs @@ -0,0 +1,119 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private sealed class SpiritOrbRun + { + internal long Id; + internal string Actor; + internal int Element; + internal float Acceleration; + internal BattleSpiritRect Destination; + internal BattleSpiritOrb Orb; + } + + private long _nextSpiritOrb; + private readonly List _spiritOrbs = new(); + private readonly HashSet _spiritCapturedActors = new(StringComparer.Ordinal); + + public IReadOnlyList SpiritOrbs => Array.AsReadOnly(_spiritOrbs.Select(orb => + new BattleSpiritOrbSnapshot(orb.Id, orb.Actor, orb.Element, orb.Orb.Position, orb.Destination, orb.Acceleration, orb.Orb.Origin)).ToArray()); + + public bool WasSpiritCaptured(string actorId) => actorId != null && _spiritCapturedActors.Contains(actorId); + + private bool ResolvePal3AAbilityMarker(Actor source, ActionRun run) + { + if (_scenario.Variant != "PAL3A" || run.Ability?.Id != BattlePal3ARules.SpiritCaptureSkill) + return false; + if (run.AbilityResolved) + return true; + if (_effects is not IBattleSpiritCaptureLayout layout) + throw new NotSupportedException("Spirit capture needs the original screen-space wheel layout."); + run.AbilityResolved = true; + Actor primary = ActorAtNativeIndex(0) ?? throw new InvalidOperationException("Spirit capture requires native slot zero."); + foreach (Actor enemy in _actors.Where(actor => NativeActorIndex(actor) is >= 5 and < 11).OrderBy(NativeActorIndex)) + { + if (enemy.Escaped || enemy.EnemyFleeing || !enemy.Alive) + continue; + // GetSpiritCount calls CanCapture a second time. Both forecasts + // consume their own original RNG even when the second gate fails. + bool eligible = CanPal3ASpiritCapture(enemy, primary); + int count = eligible && CanPal3ASpiritCapture(enemy, primary) + ? BattlePal3ARules.CaptureCount(enemy.Definition.PhysicalAttackElementValues) : 0; + if (!eligible) + continue; + if (!IsAtHome(enemy) || count <= 0) + { + QueueNumber(enemy, 0, 0, 1f, false, miss: true); + continue; + } + int emitted = 0; + for (int element = 0; element < 5; element++) + for (int unit = 0; unit < enemy.Definition.PhysicalAttackElementValues.ElementAtOrDefault(element); unit++) + { + float acceleration = 3.06f; + if (emitted++ > 0) + acceleration = (float)(3.06f + (_spiritVisualRandom.Next() % 20 - 10) * (double).1f); + BattleSpiritRect target = layout.SpiritWheelTarget(element); + BattleSpiritPoint origin = layout.CaptureSpiritOrigin(enemy.Initial.InstanceId, + new BattleMovementPoint(enemy.Position.X, enemy.Position.Y + 80f, enemy.Position.Z)); + _spiritOrbs.Add(new SpiritOrbRun + { + Id = ++_nextSpiritOrb, + Actor = enemy.Initial.InstanceId, + Element = element, + Acceleration = acceleration, + Destination = target, + Orb = new BattleSpiritOrb(origin, target, acceleration) + }); + if (emitted == 1) + { + // PAL3A requests the current HP through ChangeHP. Guard can halve + // that request without suppressing the native flag or spirit orbs. + ChangeHp(enemy, -enemy.Hp, source, run.Id, "original spirit capture", ignoreInvisible: true); + _spiritCapturedActors.Add(enemy.Initial.InstanceId); + } + } + } + PaySkillCost(source, run.Ability, run.Id, 0); + CheckResult(); + return true; + } + + private bool CanPal3ASpiritCapture(Actor enemy, Actor primary) + { + if (!enemy.Alive || enemy.Escaped || enemy.Definition.Boss) + return false; + int forecast = BattlePal3ARules.CaptureForecast(primary.Level, EffectiveAttributes(primary)[3], EffectiveAttributes(enemy)[4], + BattleEffectRules.PhysicalElementDifference(primary.Definition, enemy.Definition), + RuntimeNormalAttackRange(primary) is BattleTargetRange.OpponentRow or BattleTargetRange.OpponentColumn, _random); + return BattlePal3ARules.CanCapture(enemy.Hp, true, true, false, forecast); + } + + private void AdvancePal3ASpiritOrbs() + { + foreach (SpiritOrbRun orb in _spiritOrbs.ToArray()) + if (orb.Orb.Advance((float)StepSeconds)) + { + _spiritWheel = BattlePal3ARules.Gain(_spiritWheel, orb.Element, 1); + _spiritOrbs.Remove(orb); + } + } + + private void FlushPal3ASpiritOrbs() + { + foreach (SpiritOrbRun orb in _spiritOrbs) + _spiritWheel = BattlePal3ARules.Gain(_spiritWheel, orb.Element, 1); + _spiritOrbs.Clear(); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.SpiritCapture.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.SpiritCapture.cs.meta new file mode 100644 index 00000000..01733b6a --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.SpiritCapture.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a3e4241e3c5244f8b55f682ca021e7a0 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Stage.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Stage.cs new file mode 100644 index 00000000..8c224547 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Stage.cs @@ -0,0 +1,333 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private readonly BattleStageScheduler _stage = new(); + + public IReadOnlyList StageTasks => _stage.Snapshot(); + + private sealed class AbilityStageJob : IBattleStageJob + { + private readonly BattleSession _session; + private readonly Actor _actor; + private readonly ActionRun _run; + + internal AbilityStageJob(BattleSession session, Actor actor, ActionRun run) + { + _session = session; + _actor = actor; + _run = run; + } + + public bool Advance(BattleStageContext context) => _session.AdvanceAbilityStage(_actor, _run, context); + } + + private sealed class ReturnHomeStageJob : IBattleStageJob + { + private readonly BattleSession _session; + private readonly Actor _actor; + + internal ReturnHomeStageJob(BattleSession session, Actor actor) + { + _session = session; + _actor = actor; + } + + public bool Advance(BattleStageContext context) => + !HasFormationMovement(_actor) && context.Tick >= _actor.HurtUntil; + } + + private void ResumeOriginalAtb() => _coAttackAtbPaused = false; + + private int StageTaskCount(Actor actor) => _stage.CountOwner(actor.Initial.InstanceId) + + (actor.Run != null && !actor.Run.StageHandle.HasValue ? 1 : 0); + + // System threads prepare a stage action before ATB/state/AI and stage traversal. + private void PrepareStageActions() + { + PrepareFleeThreads(); + if (Status != BattleSessionStatus.Running) + return; + PrepareAiActions(); + PreparePhysicalThreads(); + PrepareCoAttackThreads(); + foreach (Actor actor in _actors.Where(actor => actor.Run is { SystemStarted: false }).OrderBy(actor => actor.Run.Id)) + { + actor.Run.SystemStarted = true; + if (actor.Run.Kind == BattleAction.Flee) + StartFleeAction(actor, actor.Run); + else if (actor.Run.Kind == BattleAction.Transform) + StartPal3ATransformAction(actor, actor.Run); + else if (!TryReplaceWithCoAttack(actor, actor.Run) && !TryStartPhysicalStage(actor, actor.Run)) + StartMagicSwordAction(actor, actor.Run); + } + foreach (Actor actor in _actors.Where(actor => actor.Run?.EndRequested == true && actor.Run.Ability == null && !IsFleeStageRun(actor.Run) && !IsCoAttackRun(actor.Run) && !IsPhysicalRun(actor.Run)).ToArray()) + Cancel(actor, "physical stage received an end request"); + foreach (Actor actor in _actors.Where(actor => actor.Run?.Ability != null && !IsCoAttackRun(actor.Run)).OrderBy(actor => actor.Run.Id).ToArray()) + { + ActionRun run = actor.Run; + if (run == null) + continue; + if (run.Casting) + { + if (run.EndRequested || actor.Gauge < FullGauge) + Cancel(actor, "casting lost its first gauge"); + continue; + } + if (run.StageHandle is { } handle) + { + if ((_stage.IsFinished(handle) || !_stage.IsActive(handle)) && (run.EndRequested || SimulationTick - run.TimelineOriginTick >= run.Timing.MinimumEndTick)) + Finish(actor); + continue; + } + ScheduleAbilityStage(actor, run); + } + } + + private void ScheduleAbilityStage(Actor actor, ActionRun run) + { + if (run.Ability == null || run.Casting || run.StageHandle.HasValue || IsCoAttackRun(run)) + return; + if (_stage.TryAdd(actor.Initial.InstanceId, "ability", new AbilityStageJob(this, actor, run), + BattleStageScheduler.TimeAt(SimulationTick), out BattleStageHandle handle, autoDelete: false)) + { + run.StageHandle = handle; + if (run.Kind == BattleAction.Item && !run.ItemConsumed) + { + ConsumeItemAtStart(actor, run.Ability); + run.ItemConsumed = true; + } + } + else + Cancel(actor, "stage action allocation failed"); + } + + private bool AdvanceAbilityStage(Actor actor, ActionRun run, BattleStageContext context) + { + if (actor.Run != run || Status != BattleSessionStatus.Running) + return true; + if (IsMagicSwordAbility(run.Ability)) + return AdvanceMagicSwordStage(actor, run, context); + if (_scenario.Variant == "PAL3A" && run.Ability?.Id == BattlePal3ARules.PengxuTransformSkill) + return AdvancePal3APengxuStage(actor, run, context); + if (TryAdvanceAbilityPresentation(actor, run, context, out bool presentationFinished)) + return presentationFinished; + long stageStart = run.TimelineOriginTick + run.Timing.PreparationTicks; + int elapsed = checked((int)(context.Tick - stageStart)); + if (elapsed < 0) + return false; + run.Elapsed = checked((int)(context.Tick - run.TimelineOriginTick)); + if (!run.StageStarted) + { + if (!run.ElementWheel && run.Ability.IsMagic && GetCostEstimate(new BattleCommand(actor.Initial.InstanceId, BattleAction.Skill, + run.Target, run.Ability.Id)).Any(cost => cost.Required > cost.Available)) + { + run.AbilityResolved = true; + return true; + } + if (HasFormationMovement(actor) || context.Tick < actor.HurtUntil || !TryGrabStageBody(actor, context.Handle)) + return false; + run.StageStarted = true; + run.BodyElapsed = 0; + run.BodyRestartPending = true; + } + while (run.NextHit < run.Timing.HitTicks.Count) + { + bool reached = run.Timing.NativeWorkTimeSeconds is { } seconds + ? (double)context.Time - BattleStageScheduler.TimeAt(stageStart) >= seconds + : elapsed >= run.Timing.HitTicks[run.NextHit]; + if (!reached) + break; + run.NextHit++; + if (actor.Alive && !actor.Escaped) + ResolveActionMarker(actor, run); + if (actor.Run != run || Status != BattleSessionStatus.Running) + return true; + } + bool finished = run.EndRequested || run.NextHit >= run.Timing.HitTicks.Count && elapsed >= run.Timing.AnimationTicks && + run.BodyElapsed >= run.Timing.BodyAnimationTicks && context.Tick >= actor.HurtUntil && + context.Tick - run.TimelineOriginTick >= run.Timing.MinimumEndTick - 1; + if (finished) + ReleaseStageBody(actor, context.Handle); + return finished; + } + + private void AdvanceAbilityBody(Actor actor, ActionRun run) + { + if (HasActivePal3AFormBody(actor) || _scenario.Variant == "PAL3A" && run.Ability?.Id == BattlePal3ARules.PengxuTransformSkill) + return; + if (TryAdvanceExternalEffectBody(actor, run)) + return; + if (TryAdvanceOrdinaryAbilityBody(actor, run)) + return; + if (!run.StageStarted || SimulationTick < actor.HurtUntil || !actor.ModelAlive) + return; + if (run.BodyRestartPending) + run.BodyRestartPending = false; + else + run.BodyElapsed++; + } + + private void FixNativeState() + { + foreach (Actor actor in _actors) + { + if (actor.Hp <= 0) + { + actor.Alive = false; + actor.States.Remove(BattleState.Dying); + actor.States[BattleState.Death] = new BattleStatusInstance(BattleState.Death, 0, short.MaxValue, true); + } + else if (actor.Hp < actor.Attributes[0] / 10) + actor.States[BattleState.Dying] = new BattleStatusInstance(BattleState.Dying, 0, short.MaxValue, true); + } + } + + private void UpdateModelLife(Actor actor) + { + if (actor.Escaped) + return; + if (actor.Alive) + { + if (!actor.ModelAlive && actor.Hp > 0) + actor.ModelAlive = true; + return; + } + // FixState changes data life first. A lethal hit still plays the + // queued block; the body becomes dead only when that work ends. + if (actor.ModelAlive && SimulationTick >= actor.HurtUntil && !HasFormationMovement(actor) && !PhysicalBodyBusy(actor) && + (actor.Run == null || _catalog is IBattlePhysicalTimings && actor.Run.Ability == null || actor.Run.EndRequested || actor.Run.Ability != null && + actor.Run.BodyElapsed >= actor.Run.Timing.BodyAnimationTicks)) + { + actor.ModelAlive = false; + actor.PoseStarted = checked((int)SimulationTick); + } + } + + private void RequestRoleEnd(Actor actor) + { + RequestPhysicalRoleEnd(actor); + if (actor.Run != null) + actor.Run.EndRequested = true; + actor.States.Clear(); + actor.Guard = actor.Ready = false; + actor.Gauge = actor.CastGauge = 0; + } + + private bool QueueReturnHomeStage(Actor actor) + { + return _stage.TryAdd(actor.Initial.InstanceId, "return home", new ReturnHomeStageJob(this, actor), + BattleStageScheduler.TimeAt(SimulationTick), out _); + } + + private bool QueueNumber(Actor actor, int resource, int signedValue, float duration, + bool blockBody, bool miss = false, bool dodgeBody = false, bool recovery = false) + { + if (Definitions == null) + return false; + var number = new BattleStageNumber(duration, context => + { + int offset = _random.Next() % 32; + // Freeze the native anchor at activation. Repainting and replay + // must not resample an actor which has since moved or vanished. + BattleMovementPoint anchor = miss || resource == 16 ? actor.Home : actor.Position; + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = BattleEventKind.NumberShown, + Target = actor.Initial.InstanceId, + Resource = resource, + RequestedDelta = signedValue, + RandomState = _random.State, + NumberOffset = offset, + DurationSeconds = duration, + NumberActivationTick = context.Tick, + NumberStartedTime = blockBody || dodgeBody ? context.Time : context.CreatedTime, + NumberPosition = new BattleMovementPoint(anchor.X, miss ? anchor.Y + 80 : 50, anchor.Z), + NumberIsMiss = miss, + NumberIsRecovery = recovery, + Detail = miss ? "native miss" : "native resource number" + }); + }, blockBody || dodgeBody ? _ => PushBodyBlock(actor, dodgeBody) : null); + return _stage.TryAdd(actor.Initial.InstanceId, miss ? "miss number" : "resource number", number, BattleStageScheduler.TimeAt(SimulationTick), out _); + } + + private void PushBodyBlock(Actor actor, bool dodge = false) + { + if (!actor.ModelAlive || Has(actor, BattleState.Paralysis) || Has(actor, BattleState.Sleep)) + { + if (actor.ModelAlive && !dodge) + ShowOriginalHitFlash(actor); + return; + } + actor.PoseStarted = (int)SimulationTick; + actor.Dodging = dodge; + int duration = dodge ? (_catalog as IBattleDodgeTimings)?.Dodge(actor.Initial.InstanceId) ?? 1 : _catalog.Hurt(actor.Initial.InstanceId); + actor.HurtUntil = checked((int)SimulationTick + Math.Max(1, duration)); + if (PushPhysicalBody(actor, dodge)) + return; + ActionRun run = actor.Run; + if (run != null && !run.Casting) + { + if (run.Ability != null) + { + if (run.BodyElapsed < run.Timing.BodyAnimationTicks) + { + run.BodyElapsed = 0; + run.BodyRestartPending = true; + } + } + else if (run.Kind is BattleAction.Attack or BattleAction.Defend) + { + bool afterHit = run.Kind == BattleAction.Attack && run.NextHit > 0; + run.DiscardRemainingHits = afterHit; + if (!afterHit) + run.Elapsed = 0; + Add(BattleEventKind.Interrupted, actor.Initial.InstanceId, run.Target, run.Id, + afterHit ? "body hurt after work: discard remaining physical work" : "body task restarts after hurt"); + } + } + if (actor.Movement?.Finished == false) + { + BattleMovementPlan old = actor.Movement.Plan; + actor.Movement = new BattleMovement(_scenario.Variant, new BattleMovementPlan(old.Kind, actor.Position, old.To, + old.FlyUpTick, old.FlyDownTick, old.OverTick, old.TargetBlend, actor.Movement.Blend)); + } + } + + private void CancelStageAction(ActionRun run) + { + CancelFleeStage(run); + CancelPhysicalStage(run); + CancelAbilityPresentation(run); + CancelMagicSwordStage(run); + CancelCoAttackStage(run); + if (run?.StageHandle is { } handle && run.Kind != BattleAction.Transform) + { + Actor owner = _actors.Find(actor => actor.Run == run); + if (owner != null) + ReleaseStageBody(owner, handle); + _stage.Cancel(handle); + } + } + + private void StopStage() + { + ClearStageFeedback(); + foreach (BattleStageTaskSnapshot task in _stage.Snapshot()) + _stage.Cancel(task.Handle); + _bodyStageOwners.Clear(); + StopFleeStages(); + ClearThrownWeapons(); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Stage.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Stage.cs.meta new file mode 100644 index 00000000..af7cd177 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.Stage.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c2718ac05b4f4e69aec4945408027afa diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.StageFeedback.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.StageFeedback.cs new file mode 100644 index 00000000..4a509a15 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.StageFeedback.cs @@ -0,0 +1,275 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleAbilityPresentationSnapshot + { + public long ActionId + { + get; + } + + public string Actor + { + get; + } + + public BattleSide Side + { + get; + } + + public int NativeIndex + { + get; + } + + public BattleSlot Slot + { + get; + } + + public int StageSlot + { + get; + } + + public int AbilityId + { + get; + } + + public string Name + { + get; + } + + public bool IsItem + { + get; + } + + public int ElementMask + { + get; + } + + public bool NameVisible + { + get; + } + + public double NameElapsedSeconds + { + get; + } + + public bool LineupVisible + { + get; + } + + public double LineupElapsedSeconds + { + get; + } + + public double LineupDurationSeconds + { + get; + } + + internal BattleAbilityPresentationSnapshot(long actionId, string actor, BattleSide side, int nativeIndex, + BattleSlot slot, int stageSlot, BattleAbilityDefinition ability, bool nameVisible, double nameElapsed, + bool lineupVisible = false, double lineupElapsed = 0, double lineupDuration = 0) + { + ActionId = actionId; + Actor = actor; + Side = side; + NativeIndex = nativeIndex; + Slot = slot; + StageSlot = stageSlot; + AbilityId = ability.Id; + Name = ability.Name; + IsItem = ability.IsItem; + ElementMask = ability.ElementMask; + NameVisible = nameVisible; + NameElapsedSeconds = nameElapsed; + LineupVisible = lineupVisible; + LineupElapsedSeconds = lineupElapsed; + LineupDurationSeconds = lineupDuration; + } + } + + public sealed partial class BattleSession + { + private sealed class StageMessage + { + public BattleSide Side; + public string Text, LanguageKey; + public bool AllowTrail; + public BattleStageHandle? Handle; + public long ReferenceId; + } + + private readonly Dictionary _stageMessageOwners = new(); + private readonly StageMessage[] _stageMessages = new StageMessage[2]; + private readonly object _encounterStageMessage = new(); + private bool _encounterStageMessageStarted, _encounterStageMessageFinished; + private long _nextStageMessage; + + public IReadOnlyList StageMessageReferences => Status == BattleSessionStatus.Running + ? Array.AsReadOnly(_stageMessageOwners.Values.Where(message => !message.Handle.HasValue || _stage.IsActive(message.Handle.Value)) + .OrderBy(message => message.ReferenceId) + .Select(message => new BattleStageMessageSnapshot(message.Side, message.Text, message.LanguageKey, + message.AllowTrail, 1, message.ReferenceId)).ToArray()) + : Array.Empty(); + + // UIStaticCB keeps the last SetText even when that particular caller + // hides: its window remains visible until all ShowWindow references end. + public IReadOnlyList StageMessages => Status == BattleSessionStatus.Running + ? Array.AsReadOnly(_stageMessages.Where(message => message != null) + .Select(message => new BattleStageMessageSnapshot(message.Side, message.Text, message.LanguageKey, + message.AllowTrail, _stageMessageOwners.Values.Count(owner => owner.Side == message.Side && + (!owner.Handle.HasValue || _stage.IsActive(owner.Handle.Value))))) + .Where(message => message.ReferenceCount > 0).ToArray()) + : Array.Empty(); + + private void ShowStageMessage(object owner, BattleSide side, string text = null, string languageKey = null, + bool allowTrail = false, BattleStageHandle? handle = null) + { + if (_stageMessageOwners.ContainsKey(owner)) + return; + var message = new StageMessage + { + Side = side, + Text = text, + LanguageKey = languageKey, + AllowTrail = allowTrail, + Handle = handle, + ReferenceId = checked(++_nextStageMessage) + }; + _stageMessageOwners.Add(owner, message); + _stageMessages[(int)side] = message; + } + + private void HideStageMessage(object owner) => _stageMessageOwners.Remove(owner); + + private void UpdateEncounterStageFeedback() + { + foreach (object owner in _stageMessageOwners.Where(pair => pair.Value.Handle.HasValue && + !_stage.IsActive(pair.Value.Handle.Value)).Select(pair => pair.Key).ToArray()) + HideStageMessage(owner); + if (_encounterStageMessageFinished || _scenario.Encounter == BattleEncounter.Normal) + return; + if (!_encounterStageMessageStarted) + { + _encounterStageMessageStarted = true; + bool ally = _scenario.Encounter == BattleEncounter.AllyAmbush; + ShowStageMessage(_encounterStageMessage, ally ? BattleSide.Ally : BattleSide.Enemy, + languageKey: ally ? "WeSneakAttackEnemy" : "EnemySneakAttackUs"); + } + if (BattleStageScheduler.TimeAt(SimulationTick) > 3f) + { + HideStageMessage(_encounterStageMessage); + _encounterStageMessageFinished = true; + } + } + + private void ClearStageFeedback() + { + _stageMessageOwners.Clear(); + Array.Clear(_stageMessages, 0, _stageMessages.Length); + } + + // These are captured views of already-advanced tasks. Inspection never + // starts a task, samples a random stream, or moves either battle clock. + public IReadOnlyList AbilityPresentations => + Array.AsReadOnly(CaptureAbilityPresentations().OrderBy(value => value.StageSlot).ToArray()); + + private IEnumerable CaptureAbilityPresentations() + { + if (Status != BattleSessionStatus.Running) + yield break; + double time = BattleStageScheduler.TimeAt(SimulationTick); + foreach (var pair in _abilityPresentations) + { + AbilityPresentationRun stage = pair.Value; + Actor actor = stage.Owner; + ActionRun run = actor.Run; + if (run?.Id != pair.Key) + continue; + AbilityPresentationSubtask name = stage.Steps[(int)BattleAbilityStageStep.Name]; + AbilityPresentationSubtask lineup = stage.Steps[(int)BattleAbilityStageStep.Lineup]; + yield return new BattleAbilityPresentationSnapshot(run.Id, actor.Initial.InstanceId, + actor.Initial.Side, NativeActorIndex(actor), actor.Slot, run.StageHandle?.Slot ?? int.MaxValue, + run.Ability, name.Status == 1, Math.Max(0, time - name.Started), + stage.Profile.Kind == BattleAbilityStageKind.Magic && lineup.Status == 1, + Math.Max(0, time - lineup.Started), stage.Profile.LineupSeconds); + } + foreach (var pair in _magicSwordStages) + { + MagicSwordStageRun stage = pair.Value; + Actor actor = _byId[stage.Actor]; + ActionRun run = actor.Run; + if (run?.Id != pair.Key) + continue; + double elapsed = Math.Max(0, time - stage.NameStarted); + yield return new BattleAbilityPresentationSnapshot(run.Id, actor.Initial.InstanceId, + actor.Initial.Side, NativeActorIndex(actor), actor.Slot, run.StageHandle?.Slot ?? int.MaxValue, + run.Ability, stage.NameShown && elapsed <= BattleMagicSwordStageProfile.NameDelaySeconds, + elapsed); + } + } + } + + public sealed class BattleStageMessageSnapshot + { + public BattleSide Side + { + get; + } + + public string Text + { + get; + } + + public string LanguageKey + { + get; + } + + public bool AllowTrail + { + get; + } + + public int ReferenceCount + { + get; + } + + public long ReferenceId + { + get; + } + + internal BattleStageMessageSnapshot(BattleSide side, string text, string languageKey, bool allowTrail, int references, long referenceId = 0) + { + Side = side; + Text = text; + LanguageKey = languageKey; + AllowTrail = allowTrail; + ReferenceCount = references; + ReferenceId = referenceId; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.StageFeedback.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.StageFeedback.cs.meta new file mode 100644 index 00000000..f5c0dfc8 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.StageFeedback.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b2fe56aaee2346b0995535501e19423c diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.TechniqueSuccess.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.TechniqueSuccess.cs new file mode 100644 index 00000000..fe95129b --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.TechniqueSuccess.cs @@ -0,0 +1,34 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + public sealed partial class BattleSession + { + private bool TechniqueSucceeds(Actor source, Actor target, ActionRun run) + { + BattleAbilityDefinition ability = run.Ability; + if (ability.IsItem || ability.IsMagic) + return true; + bool rejectedBoss = target.Initial.Side == BattleSide.Enemy && target.Definition.Boss && + BattleSpecialRules.RejectsBossBeforeSuccessRoll(Definitions.Variant, ability.Id); + if (!rejectedBoss) + { + if (ability.SuccessRate == 100) + return true; + int chance = BattleSpecialRules.UsesLiteralSuccessRate(Definitions.Variant, ability.Id, ability.SuccessRate) + ? ability.SuccessRate + : _effectRules.TechniqueSuccessPercent(EffectiveAttributes(source)[6], EffectiveAttributes(target)[6], + EquipmentBonus(source, item => item.TechniqueSuccessBonus), _random); + if (_random.Probability(chance)) + return true; + } + Add(BattleEventKind.Miss, source.Initial.InstanceId, target.Initial.InstanceId, run.Id, + rejectedBoss ? "original boss restriction rejected the technique before its success roll" : "technique success roll failed"); + QueueNumber(target, 0, 0, 1f, false, miss: true); + return false; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.TechniqueSuccess.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.TechniqueSuccess.cs.meta new file mode 100644 index 00000000..2a73b1a4 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.TechniqueSuccess.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cee3397a7133454a80c5314d1cf4eeeb diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ThrownWeapon.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ThrownWeapon.cs new file mode 100644 index 00000000..b95515bb --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ThrownWeapon.cs @@ -0,0 +1,160 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleThrownWeaponSnapshot + { + public string Actor + { + get; + } + + public BattleMovementPoint Position + { + get; + } + + public BattleMovementPoint RotationDegrees + { + get; + } + + public bool Active + { + get; + } + + internal BattleThrownWeaponSnapshot(string actor, BattleThrownWeapon projectile) + { + Actor = actor; + Position = projectile.Position; + RotationDegrees = projectile.Rotation; + Active = projectile.Active; + } + } + + public sealed partial class BattleSession + { + private sealed class ThrownWeaponRun + { + internal Actor Source; + internal ActionRun Command; + internal BattleThrownWeapon Projectile; + internal bool RestoreQueued; + } + + private readonly Dictionary _thrownWeapons = new(StringComparer.Ordinal); + + public IReadOnlyList ThrownWeapons => Array.AsReadOnly(_thrownWeapons.Values + .OrderBy(run => NativeActorIndex(run.Source)).Select(run => new BattleThrownWeaponSnapshot(run.Source.Initial.InstanceId, run.Projectile)).ToArray()); + + private void AdvanceThrownWeapon(Actor actor) + { + if (!_thrownWeapons.TryGetValue(actor.Initial.InstanceId, out ThrownWeaponRun run)) + return; + run.Projectile.Advance(actor.Alive); + SetWeaponDrawingEnabled(actor.Initial.InstanceId, run.Projectile.WeaponVisible); + if (run.Projectile.HitThisPass) + { + run.Command.NextHit++; + ResolveActionMarker(actor, run.Command); + } + if (run.Projectile.RestoreRequested && !run.RestoreQueued) + { + run.RestoreQueued = true; + PushThrownWeaponRestore(actor); + } + } + + private void AdvanceThrownWeaponBody(Actor actor, PhysicalBodyState body, PhysicalBodyTask task) + { + if (task.Kind == BattlePhysicalBodyKind.ThrownWeapon) + { + if (!task.Executed) + { + var projectile = new BattleThrownWeapon(actor.Position, task.Destination); + _thrownWeapons[actor.Initial.InstanceId] = new ThrownWeaponRun { Source = actor, Command = task.Run, Projectile = projectile }; + body.Pose = BattlePose.Attacking; + body.BladeSeconds = .25f; + TryPlayBodyAnimation(actor, body.Profile.ThrownStart, true, body.Pose, 61); + task.Executed = true; + } + BattleThrownWeapon projectileState = _thrownWeapons[actor.Initial.InstanceId].Projectile; + projectileState.AdvanceBody(GetBodyBinding(actor).LastPoppedMarker, actor.Alive); + SetWeaponDrawingEnabled(actor.Initial.InstanceId, projectileState.WeaponVisible); + task.Finished = projectileState.BodyFinished; + return; + } + if (!task.Executed) + { + body.Pose = BattlePose.Attacking; + TryPlayBodyAnimation(actor, body.Profile.ThrownReturn, true, body.Pose, 62); + task.Executed = true; + } + BattlePhysicalMarkerKind? marker = GetBodyBinding(actor).LastPoppedMarker; + if (marker is BattlePhysicalMarkerKind.Catched or BattlePhysicalMarkerKind.Over || !actor.Alive) + { + if (_thrownWeapons.TryGetValue(actor.Initial.InstanceId, out ThrownWeaponRun run)) + run.Projectile.FinishRestore(); + SetWeaponDrawingEnabled(actor.Initial.InstanceId, true); + if (marker == BattlePhysicalMarkerKind.Catched) + { + body.Pose = BattlePose.Idle; + TryPlayBodyAnimation(actor, body.Profile.Animation(BattlePose.Idle), true, body.Pose, 32); + } + task.Finished = true; + } + } + + private void PushThrownWeaponRestore(Actor actor) + { + PhysicalBodyState body = PhysicalBody(actor); + body.Pushed = body.PushExecuted = false; + actor.HurtUntil = checked((int)SimulationTick); + actor.Dodging = false; + RestartOrdinaryAbilityBodyAfterPush(actor); + if (body.Tasks.Count > 0 && body.Tasks[0].DiscardOnPush) + body.Tasks.RemoveAt(0); + if (body.Tasks.Count > 0) + body.Tasks[0].Executed = false; + else if (actor.Movement != null) + { + body.PausedMovement = actor.Movement.Plan; + body.PausedBlend = actor.Movement.Blend; + body.PausedAnimation = GetBodyBinding(actor).CurrentAnimation; + body.PausedPose = GetBodyBinding(actor).LogicalPose; + body.PausedNativeAction = GetBodyBinding(actor).RequestedNativeActionIndex; + } + actor.Movement = null; + body.Tasks.Insert(0, new PhysicalBodyTask { Kind = BattlePhysicalBodyKind.RestoreThrownWeapon, DiscardOnPush = true }); + } + + private void CancelOwnedThrownWeapon(Actor actor, ActionRun run) + { + // Natural command completion leaves the projectile independent. + // An explicit cancellation must not destroy an older command's flight. + if (_thrownWeapons.TryGetValue(actor.Initial.InstanceId, out ThrownWeaponRun thrown) && ReferenceEquals(thrown.Command, run)) + ClearActorThrownWeapon(actor.Initial.InstanceId); + } + + private void ClearActorThrownWeapon(string actorId) + { + if (_thrownWeapons.Remove(actorId)) + SetWeaponDrawingEnabled(actorId, true); + } + + private void ClearThrownWeapons() + { + foreach (ThrownWeaponRun run in _thrownWeapons.Values) + SetWeaponDrawingEnabled(run.Source.Initial.InstanceId, true); + _thrownWeapons.Clear(); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ThrownWeapon.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ThrownWeapon.cs.meta new file mode 100644 index 00000000..8d93834e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.ThrownWeapon.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 40d9bb1985cb431ea7d130094f945ce0 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.WeaponPresentation.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.WeaponPresentation.cs new file mode 100644 index 00000000..6fb6e227 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.WeaponPresentation.cs @@ -0,0 +1,38 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed partial class BattleSession + { + private readonly Dictionary _weaponDrawingEnabled = new(StringComparer.Ordinal); + + public bool WeaponDrawingEnabled(string actorId) => _weaponDrawingEnabled.GetValueOrDefault(actorId, true); + + public void SetWeaponDrawingEnabled(string actorId, bool enabled) + { + if (!_byId.ContainsKey(actorId ?? "")) + throw new ArgumentException("Unknown original weapon owner.", nameof(actorId)); + _weaponDrawingEnabled[actorId] = enabled; + } + + public BattleWeaponVisibility WeaponVisibility(string actorId) + { + Actor actor = _byId[actorId]; + var weapon = actor.Definition?.Equipment.FirstOrDefault(item => item.Slot == 0); + BattleBodyAnimationBinding body = GetBodyBinding(actor); + int action = body.RequestedNativeActionIndex; + BattleEffectActorSnapshot effect = EffectActor(actorId); + return BattleWeaponPresentationRules.Visible(_scenario.Variant, actor.Definition?.Identity ?? -1, + action, weapon?.WeaponType ?? 0, IsPal3ATransformed(actorId), weapon != null && actor.Initial.Side == BattleSide.Ally && WeaponDrawingEnabled(actorId), + effect.Controlled, effect.LeftWeapon, effect.RightWeapon); + } + + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.WeaponPresentation.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.WeaponPresentation.cs.meta new file mode 100644 index 00000000..8af55d42 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.WeaponPresentation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b50842da072047ffb20ac443cd9f29c5 diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.cs b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.cs new file mode 100644 index 00000000..715ac7f1 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.cs @@ -0,0 +1,771 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + + // Single writer. Fixed reference steps decouple rule rounding and marker order from render frames. + public sealed partial class BattleSession + { + public const double StepSeconds = 0.02; + public const int FullGauge = 11500; + public const int FullCastGauge = 11500; + + private sealed class Actor + { + public BattleParticipant Initial; + public int NativeIndex = -1; + public BattleSlot Slot; + public BattleMovementPoint Home; + public BattleMovementPoint Position; + public float FacingDegrees; + public BattleMovement Movement; + public readonly Queue MovementQueue = new(); + public int Hp, Sp, Mp, Gauge, CastGauge, CastSpeed, Rounds, ProcessedRounds, HurtUntil, PoseStarted; + public int Level, Experience, Love; + public long PresentationTick; + public int[] Attributes; + public bool Escaped, EnemyFleeing; + public bool Alive, ModelAlive, Dodging; + public bool Reviving; + public int CorpseItem; + public string Killer; + public long DeathTick = -1; + public BattleActorDefinition Definition; + public readonly List Skills = new(); + public readonly Dictionary States = new(); + public bool Ready, Guard; + public ActionRun Run; + } + + private sealed class ActionRun + { + public long Id; + public int Elapsed; + public long CreatedTick, TimelineOriginTick; + public BattleStageHandle? StageHandle; + public BattleStageHandle? FormStageHandle; + public bool SystemStarted, StageStarted, BodyRestartPending, EndRequested, ItemConsumed; + public int BodyElapsed; + public BattleAction Kind; + public string Target; + public AttackTiming Timing; + public BattleAttackPlan AttackPlan; + public BattleMovementPoint LastAttackSample; + public int NextHit, GuardTicks; + public bool DiscardRemainingHits; + public bool Casting; + public bool ElementWheel; + public int CastingPoseTick; + public bool AbilityResolved; + public BattleAbilityDefinition Ability; + public string[] Targets; + } + + private readonly List _actors; + private readonly Dictionary _byId; + private readonly IBattleCatalog _catalog; + private readonly IBattleRules _rules; + private readonly BattleRandom _random; + private readonly bool[] _automatic = new bool[2]; + private readonly List _events = new(); + private readonly List _inputs = new(); + private double _remainder; + private long _nextAction; + + public long Tick + { + get; private set; + } + + public long SimulationTick + { + get; private set; + } + + private readonly IBattleEffectDirector _effects; + private string _absoluteTimeActor; + private bool _pendingEffectFrame, _pendingEffectFrameFrozen; + private double _pendingTimeScale, _simulationStepCredit; + + internal IBattleRules ReplayRules => _rules; + + public bool IsModalPresentation => (_effects as IBattleModalEffects)?.BlocksBattleTime == true; + + public bool IsPreparingPresentation => (_effects as IBattlePresentationPreparation)?.IsPreparingPlayback == true; + + private bool IsBattleInputSuspended => _pendingEffectFrame || IsModalPresentation; + + public BattleSessionStatus Status { get; private set; } = BattleSessionStatus.Running; + + public BattleResult Result + { + get; private set; + } + + public IReadOnlyList Events => _events.AsReadOnly(); + + public IReadOnlyList Inputs => Array.AsReadOnly(_inputs.Select(input => input.Copy()).ToArray()); + + public int RecordedInputCount => _inputs.Count; + + internal bool MatchesRecordedInput(int index, BattleInput expected) => + index >= 0 && index < _inputs.Count && _inputs[index].Matches(expected); + + public string Variant => _scenario.Variant; + + public IReadOnlyList Actors => Array.AsReadOnly(_actors.OrderBy(NativeActorIndex).Select(Snapshot).ToArray()); + + public string WaitingActor => Status != BattleSessionStatus.Running || _ending || _resolvingOutcome || IsBattleInputSuspended ? null : _formationController ?? _actors.FirstOrDefault(actor => actor.Ready && actor.Alive && !actor.Escaped && (Definitions == null || actor.ProcessedRounds >= actor.Rounds) && actor.Run == null && ActionBodyIdle(actor) && !IsUncontrollable(actor) && !IsAiEnabled(actor))?.Initial.InstanceId; + + public BattleSession(BattleSetup setup, IBattleCatalog catalog, IBattleRules rules = null, BattleDefinitions definitions = null, IBattleEffectDirector effects = null) + { + BattleScenario scenario = setup?.CreateInstance() ?? throw new ArgumentNullException(nameof(setup)); + _effects = effects; + _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); + _rules = rules ?? new BattleBasicRules(); + _random = new BattleRandom(scenario.Seed, scenario.Variant); + InitializeMechanics(scenario, definitions); + InitializeOriginalEncounter(); + if (definitions == null && (scenario.RoundLimit != -1 || scenario.Participants.Any(actor => actor.Statuses.Count > 0))) + throw new NotSupportedException("Basic combat does not yet support round limits or initial abnormal states."); + if (scenario.Participants.Any(actor => actor.Attributes.Any(value => value > 1000000))) + throw new ArgumentOutOfRangeException(nameof(setup), "Basic combat attributes must not exceed 1,000,000."); + // Original internal priority: allied character identity, then enemy formation slot. + _actors = scenario.Participants.OrderBy(actor => actor.Side).ThenBy(actor => _catalog.Priority(actor.InstanceId)) + .ThenBy(actor => actor.InstanceId, StringComparer.Ordinal) + .Select(actor => new Actor { Initial = actor, Slot = actor.Slot, Alive = actor.Vitals[0] > 0, ModelAlive = actor.Vitals[0] > 0, Hp = actor.Vitals[0], Sp = actor.Vitals[1], Mp = actor.Vitals[2], Level = actor.Level, Experience = actor.Experience, Love = actor.Love, Attributes = actor.Attributes.ToArray() }).ToList(); + _byId = _actors.ToDictionary(actor => actor.Initial.InstanceId, StringComparer.Ordinal); + foreach (Actor actor in _actors) + { + actor.Home = (_catalog as IBattleStageGeometry)?.InitialHome(actor.Initial.InstanceId) ?? default; + actor.Position = actor.Home; + actor.FacingDegrees = BattleFacingRules.Starting(actor.Initial.Side, scenario.Encounter); + InitializeActorMechanics(actor); + } + foreach (Actor actor in _actors) + { + if (_catalog.GuardEntry(actor.Initial.InstanceId) < 1 || _catalog.Hurt(actor.Initial.InstanceId) < 0 || _catalog.SpImpact(actor.Initial.InstanceId) < 0 || _catalog.DamageDivisor(actor.Initial.InstanceId) < 1) + throw new ArgumentException("Invalid actor combat definition."); + foreach (Actor target in _actors.Where(target => target.Initial.Side != actor.Initial.Side)) + _ = _catalog.Attack(actor.Initial.InstanceId, target.Initial.InstanceId) ?? throw new ArgumentException("Missing attack timeline."); + // InitSequen visits valid slots, including dead party members. + actor.Gauge = _rules.InitialGauge(RuleParticipant(actor), scenario.Encounter, _random); + if (actor.Alive) + MakeReady(actor, false); + } + if (definitions != null) + FixNativeState(); + AssignNativeActorIndices(); + InitializePal3AForms(); + InitializeAi(); + InitializeStartupSpecials(); + Add(BattleEventKind.Started, detail: scenario.Variant + (Definitions == null ? "; explicit attributes; neutral elements" : "; captured definitions, equipment and ordinary statuses") + "; encounter is already resolved."); + CheckResult(); + } + + public bool IsAutomatic(BattleSide side) => _automatic[(int)side]; + + public void SetAutomatic(BattleSide side, bool enabled) + { + if (!Enum.IsDefined(typeof(BattleSide), side)) + throw new ArgumentOutOfRangeException(nameof(side)); + if (Status != BattleSessionStatus.Running || _automatic[(int)side] == enabled && AutomaticMatches(side, enabled)) + return; + _automatic[(int)side] = enabled; + SetOriginalAutomatic(side, enabled); + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.ControlChange, Side = side, Automatic = enabled }); + Add(BattleEventKind.ControlChanged, detail: side + ": " + (enabled ? Definitions == null ? "basic test AI" : "original AI" : "manual")); + } + + public string CanSubmit(string actorId, BattleAction action, string targetId = null) + => CanSubmit(new BattleCommand(actorId, action, targetId)); + + public bool Submit(string actorId, BattleAction action, string targetId = null) + => Submit(new BattleCommand(actorId, action, targetId)); + + public bool Submit(BattleCommand command) => SubmitCommand(command, false); + + public void Advance(double seconds) + { + if (double.IsNaN(seconds) || double.IsInfinity(seconds) || seconds < 0 || seconds > 60) + throw new ArgumentOutOfRangeException(nameof(seconds), "Advance between 0 and 60 seconds per call."); + _remainder += seconds; + while (_remainder + 1e-10 >= StepSeconds && Status == BattleSessionStatus.Running) + { + if (IsPreparingPresentation) + { + // Preparing files is outside the battle and the movie's native clock. + _remainder = 0; + break; + } + _remainder -= StepSeconds; + Step(); + } + } + + public void Step() + { + if (Status != BattleSessionStatus.Running || IsPreparingPresentation) + return; + try + { + Tick++; + bool frozen = _pendingEffectFrame ? _pendingEffectFrameFrozen : _absoluteTimeActor != null; + double scale = _pendingEffectFrame ? _pendingTimeScale : (_effects as IBattleTimeScale)?.TimeScale ?? 1d; + if (!double.IsFinite(scale) || scale is < 0d or > 1d) + throw new InvalidOperationException("Battle clock scale must be between zero and one."); + double scaledSeconds = frozen ? 0d : StepSeconds * scale; + _effects?.Advance(Tick, _pendingEffectFrame ? 0f : (float)scaledSeconds, (float)StepSeconds); + // The original movie player returns synchronously and excludes its + // wall time. Keep this frame's domain continuation until that return. + if (IsModalPresentation) + { + if (!_pendingEffectFrame) + _modalTransitions.Add(Tick); + _pendingEffectFrame = true; + _pendingEffectFrameFrozen = frozen; + _pendingTimeScale = scale; + return; + } + if (_pendingEffectFrame) + _modalTransitions.Add(Tick); + _pendingEffectFrame = false; + PruneEffects(); + AdvancePal3ASpiritOrbs(); + if (!frozen) + { + _simulationStepCredit += scale; + if (_simulationStepCredit < 1d) + { + (_effects as IBattleStagePresentation)?.AdvanceStage(scaledSeconds, StepSeconds); + return; + } + _simulationStepCredit -= 1d; + SimulationTick++; + } + foreach (Actor actor in _actors) + if (!frozen || _absoluteTimeActor == actor.Initial.InstanceId) + actor.PresentationTick++; + UpdateEncounterStageFeedback(); + if (Definitions != null) + { + PrepareStageActions(); + if (Status != BattleSessionStatus.Running) + return; + if (!frozen && !_resolvingOutcome && WaitingActor == null) + AdvanceGauges(); + FixNativeState(); + CheckResult(); + if (Status != BattleSessionStatus.Running) + return; + ProcessRounds(); + if (Status != BattleSessionStatus.Running) + return; + if (!frozen && !_resolvingOutcome) + RunTestAi(); + _stage.Advance(SimulationTick); + if (Status != BattleSessionStatus.Running) + return; + for (int nativeIndex = 0; nativeIndex < 11; nativeIndex++) + { + Actor actor = ActorAtNativeIndex(nativeIndex); + if (actor == null) + continue; + if (!frozen || _absoluteTimeActor == actor.Initial.InstanceId) + { + BeginBodyAnimationPass(actor); + if (!IsActorExternallyControlled(actor.Initial.InstanceId)) + { + if (_catalog is IBattlePhysicalTimings) + UpdateModelLife(actor); + AdvanceFormationMovement(actor); + AdvanceAction(actor); + } + EndBodyAnimationPass(actor); + } + if (_catalog is not IBattlePhysicalTimings) + UpdateModelLife(actor); + if (Status != BattleSessionStatus.Running) + return; + } + (_effects as IBattleStagePresentation)?.AdvanceStage(scaledSeconds, StepSeconds); + ReleaseUnavailableFormationController(); + CheckResult(); + return; + } + AdvanceFormationMovements(); + foreach (Actor actor in _actors) + { + AdvanceAction(actor); + if (Status != BattleSessionStatus.Running) + return; + } + ReleaseUnavailableFormationController(); + ProcessRounds(); + if (Status != BattleSessionStatus.Running) + return; + RunTestAi(); + if (WaitingActor != null) + return; // Input pauses gauges, not already-running animations/hits. + AdvanceGauges(); + ProcessRounds(); + if (Status != BattleSessionStatus.Running) + return; + RunTestAi(); + } + catch (Exception exception) + { + Fault(exception.GetType().Name + ": " + exception.Message); + } + } + + private void MakeReady(Actor actor, bool countRound = true) + { + if (actor.Gauge < FullGauge || actor.Ready || actor.Hp <= 0 || actor.Escaped) + return; + actor.Ready = true; + if (countRound) + actor.Rounds++; + actor.Guard = false; + Add(BattleEventKind.Ready, actor.Initial.InstanceId); + } + + private void RunTestAi() + { + if (Definitions != null) + { + RunAi(); + return; + } + foreach (Actor actor in _actors.Where(actor => actor.Ready && actor.Alive && !actor.Escaped && actor.Run == null && ActionBodyIdle(actor) && !Has(actor, BattleState.Paralysis) && !Has(actor, BattleState.Sleep) && (_automatic[(int)actor.Initial.Side] || IsUncontrollable(actor)))) + { + Actor target = ChooseTestTarget(actor); + if (target == null) + { + CheckResult(); + continue; + } + // Do not send both sides chasing one another forever. Native AI also rejects away targets. + SubmitCommand(new BattleCommand(actor.Initial.InstanceId, BattleAction.Attack, target.Initial.InstanceId), true); + } + } + + private void AdvanceAction(Actor actor) + { + ActionRun run = actor.Run; + if (HasActivePal3AFormBody(actor)) + return; + if (run?.Kind == BattleAction.Transform) + { + if (run.StageHandle is { } formHandle && (_stage.IsFinished(formHandle) || !_stage.IsActive(formHandle))) + Finish(actor); + return; + } + if (IsActorExternallyControlled(actor.Initial.InstanceId) || AdvancePhysicalBody(actor) || IsPhysicalRun(run) || IsCoAttackRun(run)) + return; + if (AdvanceFallbackFleeBody(actor) || run?.Kind == BattleAction.Flee) + return; + if (run == null || !actor.ModelAlive || actor.Escaped || SimulationTick < actor.HurtUntil || SimulationTick <= run.CreatedTick || !run.Casting && SimulationTick <= run.TimelineOriginTick) + return; + if (run.Casting) + { + run.CastingPoseTick++; + return; + } + if (Definitions != null && run.Ability != null) + { + AdvanceAbilityBody(actor, run); + return; + } + if (run.EndRequested && run.Ability == null) + { + Finish(actor); + return; + } + if (run.DiscardRemainingHits) + { + Finish(actor); + return; + } + int elapsed = ++run.Elapsed; + UpdateAttackPosition(actor, run); + if (run.Kind == BattleAction.Defend) + { + if (elapsed >= run.GuardTicks) + { + actor.Guard = !actor.Ready; + Finish(actor); + } + return; + } + while (run.NextHit < run.Timing.HitTicks.Count && elapsed >= run.Timing.PreparationTicks + run.Timing.TravelTicks + run.Timing.HitTicks[run.NextHit]) + { + run.NextHit++; + if (Definitions != null) + ResolveActionMarker(actor, run); + else + ResolveHit(actor, _byId[run.Target], run); + if (Status != BattleSessionStatus.Running || actor.Run != run || actor.Hp <= 0) + return; + } + if (elapsed >= run.Timing.EndTick) + Finish(actor); + } + + // Lightweight definition-free scenarios run the supplied IBattleRules per + // hit and clamp HP directly. Authored game-data sessions use native stage + // markers, one power roll per attack, and the full death/corpse lifecycle. + private void ResolveHit(Actor source, Actor target, ActionRun run) + { + if (target.Hp <= 0) + { + Add(BattleEventKind.Miss, source.Initial.InstanceId, target.Initial.InstanceId, run.Id, detail: "target died; no retarget"); + return; + } + bool atHome = IsAtHome(target); + PhysicalHit hit = _rules.Hit(source.Initial, target.Initial, target.Guard, _random, atHome, _catalog.DamageDivisor(source.Initial.InstanceId)); + int before = target.Hp; + target.Hp = Math.Clamp(target.Hp + hit.Delta, 0, target.Attributes[0]); + int actual = target.Hp - before; + if (actual < 0) + { + target.HurtUntil = checked((int)SimulationTick + _catalog.Hurt(target.Initial.InstanceId)); + target.PoseStarted = (int)SimulationTick; + if (target.Run != null) + { + bool afterHit = target.Run.Kind == BattleAction.Attack && target.Run.NextHit > 0; + target.Run.DiscardRemainingHits = afterHit; + if (!afterHit) + target.Run.Elapsed = 0; + Add(BattleEventKind.Interrupted, target.Initial.InstanceId, target.Run.Target, target.Run.Id, + detail: afterHit ? "hurt after work: discard remaining hits, recover then finish" : "hurt before work: restart animation after recovery"); + } + if (target.Initial.Side == BattleSide.Ally) + target.Sp = (int)Math.Min(target.Attributes[1], (long)target.Sp + _catalog.SpImpact(source.Initial.InstanceId)); + } + _events.Add(new BattleEvent + { + Tick = Tick, + Kind = actual < 0 ? BattleEventKind.Hit : BattleEventKind.Miss, + Source = source.Initial.InstanceId, + Target = target.Initial.InstanceId, + ActionId = run.Id, + HpBefore = before, + HpAfter = target.Hp, + RequestedDelta = hit.Delta, + ActualDelta = actual, + Critical = hit.Critical, + Dodged = hit.Dodged, + RandomState = _random.State, + Detail = !atHome ? "target away from home" : hit.Dodged ? "dodged" : actual == 0 ? "nonnegative native damage" : target.Guard ? "guard" : "physical" + }); + if (target.Hp == 0) + { + // This fallback has no native body/state pass to synchronize death. + target.Alive = target.ModelAlive = false; + Cancel(target, "death"); + target.Gauge = 0; + target.Ready = target.Guard = false; + target.PoseStarted = (int)SimulationTick; + Add(BattleEventKind.Death, source.Initial.InstanceId, target.Initial.InstanceId, run.Id); + } + CheckResult(); + } + + private void Finish(Actor actor) + { + CancelStageAction(actor.Run); + if (actor.Run.Kind == BattleAction.Attack && actor.Run.AttackPlan != null) + actor.Position = actor.Home; + Add(BattleEventKind.ActionEnded, actor.Initial.InstanceId, actor.Run.Target, actor.Run.Id); + actor.Run = null; + actor.CastGauge = 0; + } + + private void Cancel(Actor actor, string reason) + { + CancelStageAction(actor.Run); + if (actor.Run != null) + Add(BattleEventKind.Cancelled, actor.Initial.InstanceId, actor.Run.Target, actor.Run.Id, detail: reason); + actor.Run = null; + actor.CastGauge = 0; + } + + public bool CancelAction(string actorId) + { + if (Status != BattleSessionStatus.Running || actorId == null || !_byId.TryGetValue(actorId, out Actor actor) || actor.Run == null) + return false; + ActionRun run = actor.Run; + Actor[] ownedBodies = run.StageHandle is { } handle + ? _actors.Where(candidate => OwnsStageBody(candidate, handle)).ToArray() + : run.AttackPlan is { } plan && !SamePoint(run.LastAttackSample, plan.Origin) ? new[] { actor } : Array.Empty(); + _inputs.Add(new BattleInput { Tick = Tick, Actor = actorId, Kind = BattleInputKind.CancelAction }); + CancelOwnedThrownWeapon(actor, run); + BattleStageHandle? form = run.Kind == BattleAction.Transform ? run.StageHandle : run.FormStageHandle; + bool cancelledTransition; + try + { + cancelledTransition = form is { } transition && _stage.Cancel(transition); + } + finally + { + Cancel(actor, "editor cancellation; gauge cost retained"); + } + if (cancelledTransition) + EnsureProperBodyAnimation(actor); + // Explicit cancellation removes the action's normal return movement. + // A still-owned body continues under its own stage or effect. + foreach (Actor body in ownedBodies) + { + if (!body.Alive || body.Escaped || SamePoint(body.Position, body.Home) || body.Run != null || + _bodyStageOwners.ContainsKey(body.Initial.InstanceId) || PhysicalBodyBusy(body) || + HasFormationMovement(body) || IsActorExternallyControlled(body.Initial.InstanceId)) + continue; + SetActorPosition(body, body.Home); + ResetActorFacing(body); + } + return true; + } + + public void Abort(string reason = "editor stop") + { + if (Status == BattleSessionStatus.Running) + { + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.Abort, Reason = reason ?? "editor stop" }); + End(BattleSessionStatus.Aborted, null, reason ?? "editor stop"); + } + } + + public void Fault(string reason) + { + if (Status == BattleSessionStatus.Running) + { + reason ??= "external fault"; + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.Fault, Reason = reason }); + End(BattleSessionStatus.Faulted, null, reason); + } + } + + private bool IsAtHome(Actor actor) => _catalog is IBattleStageGeometry + ? IsWithinHome(actor.Position, actor.Home) + : actor.Run?.Kind != BattleAction.Attack || actor.Run.Timing.TravelTicks == 0; + + private bool _resolvingOutcome; + private bool _ending; + private (BattleSide? Winner, string Reason) _pendingOutcome; + + public bool IsResolvingOutcome => _resolvingOutcome; + + private IReadOnlyCollection UnfinishedNativeTasks() + { + var tasks = new HashSet(ActivePal3AFormTasks); + if (_coAttackStages.Values.Any(stage => !stage.Finished && _stage.IsActive(stage.Handle))) + tasks.Add(Definitions.Variant == "PAL3A" ? 13 : 12); + if (Definitions.Variant == "PAL3A") + foreach (Actor actor in _actors) + { + ActionRun run = actor.Run; + if (run?.SystemStarted != true || IsCoAttackRun(run)) + continue; + bool finished = run.StageHandle is { } handle && _stage.IsFinished(handle); + if (finished) + continue; + if (run.Kind == BattleAction.Attack) + tasks.Add(11); + else if (run.Kind == BattleAction.Skill && run.Ability != null && !run.Casting && + (_catalog is IBattleAbilityEffects catalog ? catalog.AbilityStage(actor.Initial.InstanceId, run.Ability).Kind == BattleAbilityStageKind.Skill : !run.Ability.IsMagic)) + tasks.Add(17); + } + return tasks; + } + + private void CheckResult() + { + BattleSide? winner; + string reason; + if (Definitions != null) + { + BattleEncounterOutcome outcome = EncounterOutcome(UnfinishedNativeTasks()); + if (outcome == BattleEncounterOutcome.None && !_pal3AWinReturnQueued) + { + _resolvingOutcome = false; + return; + } + winner = outcome == BattleEncounterOutcome.Win || _pal3AWinReturnQueued ? BattleSide.Ally : BattleSide.Enemy; + reason = RoundLimitReached && outcome == BattleEncounterOutcome.Win ? "original boss round limit reached" : "opposing team defeated"; + } + else + { + bool ally = _actors.Any(actor => actor.Hp > 0 && !actor.Escaped && actor.Initial.Side == BattleSide.Ally); + bool enemy = _actors.Any(actor => actor.Hp > 0 && !actor.Escaped && actor.Initial.Side == BattleSide.Enemy); + if (ally && enemy) + { + _resolvingOutcome = false; + return; + } + winner = ally ? BattleSide.Ally : enemy ? BattleSide.Enemy : null; + reason = ally || enemy ? "opposing team defeated" : "both teams defeated"; + } + if (winner == BattleSide.Ally) + QueuePal3AVictoryReturns(); + if (Definitions == null || SimulationTick == 0 && !_pal3AWinReturnQueued) + { + End(BattleSessionStatus.Completed, winner, reason); + return; + } + if (!_resolvingOutcome) + { + _resolvingOutcome = true; + _pendingOutcome = (winner, reason); + foreach (Actor actor in _actors.Where(actor => actor.Run?.Casting == true)) + Cancel(actor, "encounter outcome is resolving"); + } + if (_stage.Count == 0 && _actors.All(actor => actor.Run == null && !PhysicalBodyBusy(actor) && !HasFormationMovement(actor))) + End(BattleSessionStatus.Completed, _pendingOutcome.Winner, _pendingOutcome.Reason); + } + + private void End(BattleSessionStatus status, BattleSide? winner, string reason) + { + _ending = true; + try + { + StopFormationMovements(); + StopStage(); + RestorePal3AFormsAfterStageStop(); + StopEffects(); + foreach (Actor actor in _actors) + { + Cancel(actor, "session ended"); + ClearPhysicalBody(actor); + } + } + finally + { + _ending = false; + } + try + { + Result = BuildResult(status, winner, reason); + Status = status; + } + catch (Exception exception) + { + string fault = "settlement: " + exception.GetType().Name + ": " + exception.Message; + _inputs.Add(new BattleInput { Tick = Tick, Kind = BattleInputKind.Fault, Reason = fault }); + Status = BattleSessionStatus.Faulted; + Result = BuildResult(BattleSessionStatus.Faulted, null, fault); + } + Add(BattleEventKind.Ended, detail: Result.Status + ": " + Result.Winner + " " + Result.Reason); + } + + private BattleActorSnapshot Snapshot(Actor actor) + { + ActionRun run = actor.Run; + int elapsed = run?.Elapsed ?? 0; + BattlePose pose = !actor.ModelAlive ? BattlePose.Dead : actor.Guard ? BattlePose.Guard : BattlePose.Idle; + int local = !actor.ModelAlive ? (int)SimulationTick - actor.PoseStarted : (int)actor.PresentationTick; + if (run != null) + { + if (IsCoAttackRun(run) || run.Kind == BattleAction.Transform) + pose = actor.ModelAlive ? BattlePose.Idle : BattlePose.Dead; + else if (run.Casting) + pose = run.Kind == BattleAction.Flee ? BattlePose.Fleeing : BattlePose.Casting; + else if (elapsed < (run.Timing?.PreparationTicks ?? 0)) + pose = BattlePose.Idle; + else if (run.Ability != null && !run.StageStarted) + pose = BattlePose.Idle; + else if (run.Kind == BattleAction.Skill) + pose = run.BodyElapsed >= run.Timing.BodyAnimationTicks ? BattlePose.Idle : BattlePose.UsingSkill; + else if (run.Kind == BattleAction.Item) + pose = run.BodyElapsed >= run.Timing.BodyAnimationTicks ? BattlePose.Idle : BattlePose.UsingItem; + else if (run.Kind == BattleAction.Flee) + pose = BattlePose.Fleeing; + else if (run.Kind == BattleAction.Defend) + pose = BattlePose.GuardEntry; + else if (elapsed < run.Timing.TravelTicks) + pose = BattlePose.Moving; + else if (elapsed < run.Timing.TravelTicks + run.Timing.AnimationTicks) + pose = BattlePose.Attacking; + else + pose = BattlePose.Returning; + local = pose == BattlePose.Attacking ? elapsed - run.Timing.PreparationTicks - run.Timing.TravelTicks : + pose == BattlePose.Returning ? elapsed - run.Timing.PreparationTicks - run.Timing.TravelTicks - run.Timing.AnimationTicks : + pose is BattlePose.UsingSkill or BattlePose.UsingItem ? run.BodyElapsed : elapsed; + } + if (run?.Ability != null && pose == BattlePose.Idle) + local = (int)actor.PresentationTick; + CapturePhysicalPose(actor, ref pose, ref local); + if (actor.ModelAlive && HasFormationMovement(actor) && !PhysicalBodyBusy(actor)) + { + pose = BattlePose.Repositioning; + local = Math.Max(0, actor.Movement.ElapsedTicks - 1); + } + if (_catalog is not IBattlePhysicalTimings && actor.ModelAlive && SimulationTick < actor.HurtUntil) + { + pose = actor.Dodging ? BattlePose.Dodging : BattlePose.Hurt; + local = (int)SimulationTick - actor.PoseStarted; + } + else if (run?.Casting == true) + local = run.CastingPoseTick; + return new BattleActorSnapshot + { + Id = actor.Initial.InstanceId, + ActorId = actor.Initial.ActorId, + NativeIndex = NativeActorIndex(actor), + NativeAnimationClip = GetBodyBinding(actor).CurrentAnimation?.Clip, + NativePresentationTick = actor.PresentationTick, + NativePlaybackRate = _bodyPassRates.GetValueOrDefault(actor.Initial.InstanceId, 1f), + WeaponTrailSeconds = CurrentBladeSeconds(actor.Initial.InstanceId), + NativeAnimationHalfDepth = GetBodyBinding(actor).CurrentAnimation?.HalfDepth, + NativeAnimationSeconds = GetBodyBinding(actor).CurrentAnimationTimeSeconds, + MagicSword = CaptureMagicSword(actor), + Side = actor.Initial.Side, + Slot = actor.Slot, + Home = actor.Home, + Position = actor.Position, + FacingDegrees = actor.FacingDegrees, + Movement = actor.Movement?.Capture(), + AttackPlan = run?.AttackPlan, + Hp = actor.Hp, + MaxHp = actor.Attributes[0], + Sp = actor.Sp, + Mp = actor.Mp, + MaxSp = actor.Attributes[1], + MaxMp = actor.Attributes[2], + Level = actor.Level, + Experience = actor.Experience, + Love = actor.Love, + CorpseItem = actor.CorpseItem, + Attributes = Array.AsReadOnly(EffectiveAttributes(actor)), + States = StatusSnapshots(actor), + Skills = Array.AsReadOnly(actor.Skills.Select(skill => new BattleSkillSnapshot(skill)).ToArray()), + CurrentAction = run?.Kind, + AbilityId = IsCoAttackRun(run) ? CoAttackId(run) : run?.Ability?.Id ?? 0, + Escaped = actor.Escaped, + Fleeing = IsFleeing(actor), + AliveFlag = actor.Alive, + ModelAliveFlag = actor.ModelAlive, + Gauge = actor.Gauge, + CastGauge = actor.CastGauge, + Rounds = actor.Rounds, + Ready = actor.Ready, + Guarding = actor.Guard, + Pose = pose, + PoseTick = local, + Target = run?.Target, + ActionId = run?.Id ?? 0, + ActionTick = elapsed + }; + } + + private void Add(BattleEventKind kind, string source = null, string target = null, long actionId = 0, string detail = "") => + _events.Add(new BattleEvent { Tick = Tick, Kind = kind, Source = source, Target = target, ActionId = actionId, Detail = detail, RandomState = _random.State }); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.cs.meta b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.cs.meta new file mode 100644 index 00000000..29ef428f --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Runtime/Session/BattleSession.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b953a650d498470fa3f3fa0520363ca8 diff --git a/Assets/Scripts/Pal3.Battle/Stage.meta b/Assets/Scripts/Pal3.Battle/Stage.meta new file mode 100644 index 00000000..01e0cbd1 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 34f78a8395c6420cb680c9bcceaf5c51 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Battle/Stage/AttackTiming.cs b/Assets/Scripts/Pal3.Battle/Stage/AttackTiming.cs new file mode 100644 index 00000000..efb4ec1e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/AttackTiming.cs @@ -0,0 +1,91 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + // Durations and markers are in logical ticks, compiled from the resource adapter before play. + public sealed class AttackTiming + { + public int TravelTicks + { + get; + } + + public int AnimationTicks + { + get; + } + + public IReadOnlyList HitTicks + { + get; + } + + public int PreparationTicks + { + get; + } + + public int MinimumEndTick + { + get; + } + + public int BodyAnimationTicks + { + get; + } + + public float? NativeWorkTimeSeconds + { + get; + } + + public int EndTick => Math.Max(PreparationTicks + TravelTicks * 2 + AnimationTicks, MinimumEndTick); + + public AttackTiming(int travelTicks, int animationTicks, IEnumerable hitTicks, int preparationTicks = 0, int minimumEndTick = 0, int? bodyAnimationTicks = null, float? nativeWorkTimeSeconds = null, bool allowEmptyHits = false) + { + int[] hits = hitTicks?.ToArray() ?? throw new ArgumentNullException(nameof(hitTicks)); + if (bodyAnimationTicks < 0 || bodyAnimationTicks > 30000 || nativeWorkTimeSeconds < 0 || nativeWorkTimeSeconds > 600 || + nativeWorkTimeSeconds.HasValue && !float.IsFinite(nativeWorkTimeSeconds.Value)) + throw new ArgumentException("Invalid body or native work time."); + if (travelTicks < 0 || animationTicks < 1 || travelTicks > 30000 || animationTicks > 30000 || preparationTicks < 0 || preparationTicks > 30000 || minimumEndTick < 0 || minimumEndTick > 90000 || + !allowEmptyHits && hits.Length == 0 || hits.Length > 32 || hits.Any(tick => tick < 0 || tick > animationTicks) || !hits.SequenceEqual(hits.OrderBy(tick => tick))) + throw new ArgumentException("Invalid normal attack timeline."); + TravelTicks = travelTicks; + AnimationTicks = animationTicks; + PreparationTicks = preparationTicks; + MinimumEndTick = minimumEndTick; + BodyAnimationTicks = bodyAnimationTicks ?? animationTicks; + NativeWorkTimeSeconds = nativeWorkTimeSeconds; + HitTicks = Array.AsReadOnly(hits); + } + } + + // Presentation/resource knowledge is supplied at the composition boundary, never looked up by the loop. + public interface IBattleCatalog + { + AttackTiming Attack(string source, string target); + + int GuardEntry(string actor); + + int Hurt(string actor); + + int SpImpact(string actor); + + int Priority(string actor); + + int DamageDivisor(string actor); + } + + public interface IBattleAbilityTimings + { + AttackTiming Ability(string actor, BattleAbilityDefinition ability); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/AttackTiming.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/AttackTiming.cs.meta new file mode 100644 index 00000000..562fb2f9 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/AttackTiming.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f22c4528947e43f0ae7fd4efa352a848 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleAbilityStageProfile.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleAbilityStageProfile.cs new file mode 100644 index 00000000..daa650d2 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleAbilityStageProfile.cs @@ -0,0 +1,179 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + public enum BattleAbilityStageKind + { + Skill, Magic, Item, ElementWheel + } + + public enum BattleAbilityWorkBoundary + { + WorkTime, WorkTimeAndBodyIdle, WorkTimeAndFirstGroupFinished + } + + public enum BattleAbilityStageStep + { + Grab, Name, Lineup, PrepareBody, Act, ReturnHome, Release + } + + // The four original booleans are applied in file order. Later enabled + // coordinates replace earlier ones; an empty flag set uses the explicit vector. + public sealed class BattleAbilityEffectBinding + { + public int GroupId + { + get; + } + + public float WaitSeconds + { + get; + } + + public int PlacementFlags + { + get; + } + + public BattleMovementPoint ExplicitOrigin + { + get; + } + + public BattleAbilityEffectBinding(int groupId, float waitSeconds, int placementFlags = 0, BattleMovementPoint explicitOrigin = default) + { + if (groupId < -1 || !float.IsFinite(waitSeconds) || waitSeconds < 0 || waitSeconds > 600 || placementFlags < 0 || placementFlags > 15) + throw new ArgumentException("Invalid original ability effect binding."); + GroupId = groupId; + WaitSeconds = waitSeconds; + PlacementFlags = placementFlags; + ExplicitOrigin = explicitOrigin; + } + + public BattleMovementPoint Resolve(BattleMovementPoint sourceCenter, BattleMovementPoint targetCenter, + BattleMovementPoint sourceHome, BattleMovementPoint targetHome, bool hasSingleTarget) + { + BattleMovementPoint origin = ExplicitOrigin; + if ((PlacementFlags & 1) != 0) + origin = sourceCenter; + if ((PlacementFlags & 2) != 0) + origin = targetCenter; + if ((PlacementFlags & 4) != 0) + origin = sourceHome; + if ((PlacementFlags & 8) != 0) + origin = hasSingleTarget ? targetHome : targetCenter; + return origin; + } + } + + public sealed class BattleAbilityStageProfile + { + public BattleAbilityStageKind Kind + { + get; + } + + public BattleAbilityEffectBinding First + { + get; + } + + public BattleAbilityEffectBinding Second + { + get; + } + + public float WorkSeconds + { + get; + } + + public BattleAbilityWorkBoundary WorkBoundary + { + get; + } + + public int BodyAnimationTicks + { + get; + } + + public BattleMovementKind? ApproachKind + { + get; + } + + public BattleMovementKind? ReturnKind + { + get; + } + + public bool TargetCenterIsOpposing + { + get; + } + + public bool RetainsBody + { + get; + } + + public bool NpcItemIdle + { + get; + } + + public float NameSeconds => Kind == BattleAbilityStageKind.Item ? 1.5f : 1f; + + public float LineupSeconds => Kind == BattleAbilityStageKind.Magic ? 2f : 0f; + + public float PrepareWaitSeconds => Kind == BattleAbilityStageKind.Skill ? 0.05f : 0f; + + public BattleAbilityStageProfile(BattleAbilityStageKind kind, BattleAbilityEffectBinding first, BattleAbilityEffectBinding second, + float workSeconds, BattleAbilityWorkBoundary workBoundary, int bodyAnimationTicks, bool targetCenterIsOpposing, + BattleMovementKind? approachKind = null, BattleMovementKind? returnKind = null, bool retainsBody = false, bool npcItemIdle = false) + { + if (!Enum.IsDefined(typeof(BattleAbilityStageKind), kind) || first == null || second == null || + !float.IsFinite(workSeconds) || workSeconds < 0 || workSeconds > 600 || + !Enum.IsDefined(typeof(BattleAbilityWorkBoundary), workBoundary) || bodyAnimationTicks < 0 || bodyAnimationTicks > 30000 || + approachKind.HasValue && !Enum.IsDefined(typeof(BattleMovementKind), approachKind.Value) || + returnKind.HasValue && !Enum.IsDefined(typeof(BattleMovementKind), returnKind.Value)) + throw new ArgumentException("Invalid original ability stage profile."); + Kind = kind; + First = first; + Second = second; + WorkSeconds = workSeconds; + WorkBoundary = workBoundary; + BodyAnimationTicks = bodyAnimationTicks; + TargetCenterIsOpposing = targetCenterIsOpposing; + ApproachKind = approachKind; + ReturnKind = returnKind; + RetainsBody = retainsBody; + NpcItemIdle = npcItemIdle; + } + } + + public interface IBattleAbilityBodyAnimations + { + BattlePhysicalAnimation AbilityBody(string actor, BattleAbilityDefinition ability); + + int? AbilityNativeAction(string actor, BattleAbilityDefinition ability); + + BattlePhysicalAnimation AbilityMovementBody(string actor, BattleAbilityDefinition ability, BattleMovementKind kind, bool returning); + } + + public interface IBattleAbilityEffects + { + BattleAbilityStageProfile AbilityStage(string actor, BattleAbilityDefinition ability); + + IReadOnlyList AbilityMovement(BattleActorSnapshot source, BattleActorSnapshot target, + BattleAbilityDefinition ability, BattleDefinitions definitions, bool returning); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleAbilityStageProfile.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleAbilityStageProfile.cs.meta new file mode 100644 index 00000000..dc46256d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleAbilityStageProfile.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d252dc247c254cd68c0efc99d22f8eb2 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleAudio.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleAudio.cs new file mode 100644 index 00000000..82823ad6 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleAudio.cs @@ -0,0 +1,13 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + // Optional output port for one-shot battle cues; timing belongs to the caller. + public interface IBattleAudio + { + void PlaySound(string sound); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleAudio.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleAudio.cs.meta new file mode 100644 index 00000000..e07e2281 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleAudio.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a59ee0d3a39243b2b0ba0ea285bc0f1b diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleBodyAnimationBinding.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleBodyAnimationBinding.cs new file mode 100644 index 00000000..c547a474 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleBodyAnimationBinding.cs @@ -0,0 +1,161 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + // The actor owns its raw 4800-tick animation clock and message FIFO. Body + // tasks consume one message before proceeding; actor Update runs afterward. + public sealed class BattleBodyAnimationBinding + { + private readonly Queue _pending = new(); + private bool _loop; + + public BattlePhysicalAnimation CurrentAnimation + { + get; private set; + } + + public int LocalTick + { + get; private set; + } + + public uint GameBoxTime + { + get; private set; + } + + public BattlePose LogicalPose { get; private set; } = BattlePose.Idle; + + public int RequestedNativeActionIndex { get; private set; } = 32; + + public BattlePhysicalMarkerKind? LastPoppedMarker + { + get; private set; + } + + public string LastPoppedName + { + get; private set; + } + + public int PendingMessageCount => _pending.Count; + + public double CurrentAnimationTimeSeconds => CurrentAnimation == null ? 0 : + (_loop ? GameBoxTime % CurrentAnimation.GameBoxDuration : GameBoxTime) / 4800d; + + public BattleBodyAnimationBinding(BattlePhysicalAnimation initial = null, bool loop = true) + { + CurrentAnimation = initial; + _loop = loop; + } + + public BattleBodyAnimationBinding Clone() + { + var copy = new BattleBodyAnimationBinding(CurrentAnimation, _loop) + { + LocalTick = LocalTick, + GameBoxTime = GameBoxTime, + LogicalPose = LogicalPose, + RequestedNativeActionIndex = RequestedNativeActionIndex, + LastPoppedMarker = LastPoppedMarker, + LastPoppedName = LastPoppedName + }; + foreach (BattlePhysicalMarker marker in _pending) + copy._pending.Enqueue(marker); + return copy; + } + + public void ClearMessages() + { + _pending.Clear(); + LastPoppedMarker = null; + LastPoppedName = null; + } + + public void SetLogicalPose(BattlePose pose) => LogicalPose = pose; + + public void SetRequestedNativeAction(int action) + { + if (action < 0 || action > 63) + throw new ArgumentOutOfRangeException(nameof(action)); + RequestedNativeActionIndex = action; + } + + public bool TryPlay(BattlePhysicalAnimation animation, bool loop) + { + if (animation == null) + return false; + CurrentAnimation = animation; + _loop = loop; + _pending.Clear(); + Reset(); + return true; + } + + public void Reset() + { + LocalTick = 0; + GameBoxTime = 0; + } + + public void PopMessage() + { + if (_pending.Count == 0) + { + LastPoppedMarker = null; + LastPoppedName = null; + return; + } + BattlePhysicalMarker marker = _pending.Dequeue(); + LastPoppedMarker = marker.Kind; + LastPoppedName = marker.NativeName; + } + + public void Advance(float playbackRate = 1f) + { + if (!float.IsFinite(playbackRate) || playbackRate < 0) + throw new ArgumentOutOfRangeException(nameof(playbackRate)); + if (CurrentAnimation == null) + return; + LocalTick++; + // Installed PAL3 gbActor.Update retains dt*FPS in x87 through the + // 4800 conversion despite spilling a copy of dtime to float. + uint delta = checked((uint)(BattleSession.StepSeconds * playbackRate * 4800d)); + uint oldTime = GameBoxTime; + GameBoxTime = unchecked(GameBoxTime + delta); + uint duration = CurrentAnimation.GameBoxDuration; + if (!_loop && GameBoxTime >= duration) + { + // Native gbTick/start/end are unsigned, including max(start, end - 4). + GameBoxTime = unchecked(duration - 4); + EnqueueOver(); + return; + } + if (GameBoxTime == oldTime) + return; + uint first = oldTime % duration; + ulong last = first + (ulong)delta; + if (last >= duration) + EnqueueOver(); + // GetTriggeredEvent emits the automatic Over first, then the file's + // triggers in stored order, including loop-boundary tick-zero events. + for (ulong cycle = 0; cycle * duration <= last; cycle++) + foreach (BattlePhysicalMarker marker in CurrentAnimation.Markers) + { + ulong tick = marker.GameBoxTick + cycle * duration; + if (tick > last) + break; + if (tick > first) + _pending.Enqueue(marker); + } + } + + private void EnqueueOver() => _pending.Enqueue(new BattlePhysicalMarker(0, BattlePhysicalMarkerKind.Over, 0, "over")); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleBodyAnimationBinding.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleBodyAnimationBinding.cs.meta new file mode 100644 index 00000000..f10d50eb --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleBodyAnimationBinding.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4a36f656e0344b9a8807e82b9d827436 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleBodyTimings.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleBodyTimings.cs new file mode 100644 index 00000000..2f8dbdb7 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleBodyTimings.cs @@ -0,0 +1,12 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + public interface IBattleDodgeTimings + { + int Dodge(string actor); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleBodyTimings.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleBodyTimings.cs.meta new file mode 100644 index 00000000..f0e636f1 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleBodyTimings.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e007fe473346405c8e9a84502f0ac9e7 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleCamera.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleCamera.cs new file mode 100644 index 00000000..31357519 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleCamera.cs @@ -0,0 +1,575 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + [Flags] + public enum BattleCameraFlags + { + None = 0, + StartCamera = 1, + EndCamera = 2, + Time = 4, + Speed = 8, + Line = 16, + Circle = 32, + Mechanics = 64, + TimeRevise = 128, + AbsoluteTime = 256, + CounterYaw = 512, + CounterPitch = 1024, + CounterRoll = 2048, + RandomSwing = 4096, + SightTrace = 8192, + PositionTrace = 16384 + } + + // Position is in original GameBox units; all three angles are radians. + public readonly struct BattleCameraPose + { + public BattleMovementPoint Position + { + get; + } + + public float Yaw + { + get; + } + + public float Pitch + { + get; + } + + public float Roll + { + get; + } + + public BattleCameraPose(BattleMovementPoint position, float yaw, float pitch, float roll) + { + Position = position; + Yaw = yaw; + Pitch = pitch; + Roll = roll; + } + + public BattleMovementPoint Forward => new((float)(Math.Sin(Yaw) * Math.Cos(Pitch)), (float)Math.Sin(Pitch), (float)(-Math.Cos(Pitch) * Math.Cos(Yaw))); + + public BattleMovementPoint Up => new( + (float)(-Math.Cos(Yaw) * Math.Sin(Roll) - Math.Sin(Yaw) * Math.Sin(Pitch) * Math.Cos(Roll)), + (float)(Math.Cos(Pitch) * Math.Cos(Roll)), + (float)(-Math.Sin(Yaw) * Math.Sin(Roll) + Math.Sin(Pitch) * Math.Cos(Roll) * Math.Cos(Yaw))); + + public BattleCameraPose WithPosition(BattleMovementPoint position) => new(position, Yaw, Pitch, Roll); + + internal BattleCameraPose WithAngles(float yaw, float pitch) => new(Position, yaw, pitch, Roll); + + internal static BattleCameraPose Interpolate(BattleCameraPose start, BattleCameraPose end, float ratio) + => new(start.Position, start.Yaw + (end.Yaw - start.Yaw) * ratio, start.Pitch + (end.Pitch - start.Pitch) * ratio, start.Roll + (end.Roll - start.Roll) * ratio); + } + + // This deliberately retains fields that the published controller does not + // consume. Splice, inertia, counter-pitch/roll, swing and FOV are not extra + // algorithms: assigning invented behavior to them changes original playback. + public sealed class BattleCameraTask + { + public BattleCameraFlags Flags + { + get; set; + } + + public BattleCameraPose Start + { + get; set; + } + + public BattleCameraPose End + { + get; set; + } + + public float ExpectedSeconds + { + get; set; + } + + public bool Splice + { + get; set; + } + + public int TraceActor { get; set; } = -1; + + public float StartSpeed + { + get; set; + } + + public float Inertia + { + get; set; + } + + public float FirstAccelerationStart + { + get; set; + } + + public float SecondAccelerationStart + { + get; set; + } + + public float FirstAcceleration + { + get; set; + } + + public float SecondAcceleration + { + get; set; + } + + public float CircleAngle + { + get; set; + } + + public float AngularSpeed + { + get; set; + } + + public BattleMovementPoint CircleCenter + { + get; set; + } + + public BattleMovementPoint CircleEnd + { + get; set; + } + + public float SwingFrequency + { + get; set; + } + + public float SwingAmplitude + { + get; set; + } + + public float TimeCompensation + { + get; set; + } + + public float StartFieldOfView + { + get; set; + } + + public float EndFieldOfView + { + get; set; + } + + public BattleMovementPoint SavedTraceStart + { + get; set; + } + } + + // CCBCamControl, shared by both games. The owner calls Advance exactly once + // per stage update, including the native one-update gap between list tasks. + // No engine objects, original pointers or wall-clock services are involved. + public sealed class BattleCameraController + { + private sealed class Runtime + { + public BattleCameraTask Definition; + public BattleCameraPose Start; + public BattleMovementPoint TraceStart; + public float Expected, StartTime; + public bool Executed, Finished; + } + + private readonly Runtime[][] _lists; + private readonly Func _tracePosition; + private BattleCameraPose _start, _current; + private BattleMovementPoint _position, _speed, _nextSpeed; + private float _distance, _startSpeed, _time, _absoluteTime; + private double _timeFund, _absoluteTimeFund; + private float _quake, _quakeFrequency = 80, _quakeDecay = 1; + + public BattleCameraPose Pose + { + get; private set; + } + + public float FieldOfView + { + get; private set; + } + + public bool TrailEnabled + { + get; private set; + } + + public bool IsRunning => CurrentList >= 0; + + public int CurrentList { get; private set; } = -1; + + public int CurrentTask { get; private set; } = -1; + + public float CurrentExpectedSeconds => IsRunning ? Active.Expected : 0; + + public bool CurrentTaskFinished => IsRunning && Active.Finished; + + public float ScaledTime => _time; + + public float AbsoluteTime => _absoluteTime; + + public BattleCameraController(IReadOnlyList> lists, BattleCameraPose initialPose, + Func tracePosition = null, float fieldOfView = 50) + { + if (lists == null) + throw new ArgumentNullException(nameof(lists)); + var pool = new Dictionary(); + _lists = lists.Select(list => list.Select(task => + { + if (task == null) + throw new ArgumentException("Camera lists cannot contain null tasks.", nameof(lists)); + if (!pool.TryGetValue(task, out Runtime runtime)) + { + runtime = new Runtime { Definition = task, Start = task.Start, Expected = task.ExpectedSeconds, TraceStart = task.SavedTraceStart }; + pool.Add(task, runtime); + } + return runtime; + }).ToArray()).ToArray(); + _tracePosition = tracePosition ?? (_ => default); + SetPose(initialPose, fieldOfView); + } + + public void SetPose(BattleCameraPose pose, float fieldOfView = 50) + { + Pose = _current = pose; + FieldOfView = fieldOfView; + } + + public bool StartList(int index, int task = 0) + { + if (index < 0 || index >= _lists.Length || task < 0 || task >= _lists[index].Length) + return false; + foreach (Runtime runtime in _lists[index]) + { + runtime.Executed = false; + runtime.Finished = false; + } + CurrentList = index; + CurrentTask = task; + return true; + } + + public void StopList() + { + CurrentList = CurrentTask = -1; + } + + public void SetQuake(float amplitude, float frequency, float decay) + { + if (!Finite(amplitude) || !Finite(frequency) || !Finite(decay)) + throw new ArgumentException("Camera quake parameters must be finite."); + _quake = amplitude; + _quakeFrequency = frequency; + _quakeDecay = decay; + } + + public void Advance(double scaledSeconds, double absoluteSeconds) + { + if (!Finite(scaledSeconds) || !Finite(absoluteSeconds) || scaledSeconds < 0 || absoluteSeconds < 0) + throw new ArgumentException("Camera time deltas must be nonnegative and finite."); + AdvanceAt(_timeFund + scaledSeconds, _absoluteTimeFund + absoluteSeconds, scaledSeconds, absoluteSeconds); + } + + // The original system accumulates gbLongTime (double), then publishes + // float task times. An owner with an authoritative stage clock can + // supply it directly, without accumulating a second independent clock. + public void AdvanceAt(double scaledTime, double absoluteTime, double scaledSeconds, double absoluteSeconds) + { + if (!Finite(scaledTime) || !Finite(absoluteTime) || !Finite(scaledSeconds) || !Finite(absoluteSeconds) || + scaledTime < _timeFund || absoluteTime < _absoluteTimeFund || scaledSeconds < 0 || absoluteSeconds < 0) + throw new ArgumentException("Camera clocks must be ordered and time deltas must be nonnegative and finite."); + _timeFund = scaledTime; + _absoluteTimeFund = absoluteTime; + _time = (float)scaledTime; + _absoluteTime = (float)absoluteTime; + float scaledDelta = (float)scaledSeconds, absoluteDelta = (float)absoluteSeconds; + if (IsRunning) + DoList(scaledDelta, absoluteDelta); + // Quake always uses the ordinary combat clock, even when the active + // camera task uses absolute time. Decay precedes the sine sample. + if (_quake > 0) + { + _quake -= scaledDelta * _quakeDecay; + BattleMovementPoint p = _current.Position; + Pose = _current.WithPosition(new BattleMovementPoint(p.X, p.Y + _quake * (float)Math.Sin(_time * _quakeFrequency), p.Z)); + } + else + _quake = 0; + } + + private Runtime Active => _lists[CurrentList][CurrentTask]; + + private static bool Finite(float value) => !float.IsNaN(value) && !float.IsInfinity(value); + + private static bool Finite(double value) => !double.IsNaN(value) && !double.IsInfinity(value); + + private static bool Has(BattleCameraTask task, BattleCameraFlags flag) => (task.Flags & flag) != 0; + + private float Now(BattleCameraTask task) => Has(task, BattleCameraFlags.AbsoluteTime) ? _absoluteTime : _time; + + private void DoList(float scaledSeconds, float absoluteSeconds) + { + Runtime runtime = Active; + if (runtime.Finished) + { + CurrentTask++; + if (CurrentTask >= _lists[CurrentList].Length) + StopList(); + return; + } + BattleCameraTask task = runtime.Definition; + // bRandSwing toggles CTrail; it never perturbs the camera pose. + TrailEnabled = Has(task, BattleCameraFlags.RandomSwing); + if (Has(task, BattleCameraFlags.Line)) + Line(runtime); + if (Has(task, BattleCameraFlags.Circle)) + Circle(runtime); + if (Has(task, BattleCameraFlags.Mechanics)) + Mechanics(runtime, Has(task, BattleCameraFlags.AbsoluteTime) ? absoluteSeconds : scaledSeconds); + } + + private void Begin(Runtime runtime, bool captureTrace) + { + BattleCameraTask task = runtime.Definition; + if (!Has(task, BattleCameraFlags.StartCamera)) + runtime.Start = Pose; + _start = runtime.Start; + if (Has(task, BattleCameraFlags.CounterYaw)) + { + float difference = task.End.Yaw - _start.Yaw; + float yaw = _start.Yaw + (difference > 0 ? 2 * (float)Math.PI : difference < 0 ? -2 * (float)Math.PI : 0); + _start = _start.WithAngles(yaw, _start.Pitch); + } + runtime.StartTime = Now(task); + if (captureTrace && Has(task, BattleCameraFlags.PositionTrace)) + runtime.TraceStart = _tracePosition(task.TraceActor); + runtime.Executed = true; + } + + private static float AcceleratedDistance(BattleCameraTask task, float speed, float elapsed) + { + float distance = speed * elapsed; + if (elapsed >= task.FirstAccelerationStart) + { + float delta = elapsed - task.FirstAccelerationStart; + distance += task.FirstAcceleration * delta * delta / 2; + } + if (elapsed >= task.SecondAccelerationStart) + { + float delta = elapsed - task.SecondAccelerationStart; + distance += (task.FirstAcceleration + task.SecondAcceleration) * delta * delta / 2; + } + return distance; + } + + private void Line(Runtime runtime) + { + BattleCameraTask task = runtime.Definition; + bool targetUnknown = !Has(task, BattleCameraFlags.EndCamera); + bool speedUnknown = !targetUnknown && !Has(task, BattleCameraFlags.Speed); + bool timeUnknown = !targetUnknown && !speedUnknown && !Has(task, BattleCameraFlags.Time); + if (!targetUnknown && !speedUnknown && !timeUnknown) + return; // The published dispatch also leaves this overspecified task idle. + if (!runtime.Executed) + { + Begin(runtime, true); + _distance = (float)BattleMovement.Distance(runtime.Start.Position, task.End.Position); + _startSpeed = task.StartSpeed; + if (speedUnknown) + { + float t1 = runtime.Expected - task.FirstAccelerationStart; + float t2 = runtime.Expected - task.SecondAccelerationStart; + _startSpeed = runtime.Expected != 0 ? (_distance - (task.FirstAcceleration * t1 * t1 / 2 + + (task.FirstAcceleration + task.SecondAcceleration) * t2 * t2 / 2)) / runtime.Expected : 0; + if (_startSpeed < 0) + _startSpeed = 0; + } + } + float elapsed = Now(task) - runtime.StartTime; + float ratio = runtime.Expected <= 0 ? 1 : elapsed / runtime.Expected; + if (speedUnknown && ratio >= 1) + ratio = 1; + float distance = AcceleratedDistance(task, _startSpeed, elapsed); + if (!targetUnknown && distance > _distance) + distance = _distance; + if (timeUnknown) + ratio = _distance == 0 ? 1 : distance / _distance; + BattleMovementPoint offset = Scale(BattleMovement.NormalizeDirection(Subtract(task.End.Position, runtime.Start.Position)), distance); + BattleMovementPoint trace = Trace(runtime, ref offset); + BattleMovementPoint position = Add(runtime.Start.Position, offset); + if (Has(task, BattleCameraFlags.SightTrace)) + { + _current = _current.WithPosition(position); + // The two speed-specified native branches pass displacement, + // whereas the time-specified branch passes world position. + LookAt(speedUnknown ? position : offset, trace); + } + else + { + BattleCameraPose from = timeUnknown ? runtime.Start : _start; + _current = BattleCameraPose.Interpolate(from, task.End, ratio).WithPosition(position); + } + if (timeUnknown) + { + if (distance >= _distance) + { + runtime.Expected = elapsed; + runtime.Finished = true; + } + } + else + { + if (speedUnknown && runtime.Expected == 0 && _distance > 0) + _current = task.End; + if (ratio >= 1) + runtime.Finished = true; + if (speedUnknown && distance == _distance && Has(task, BattleCameraFlags.TimeRevise)) + { + if (ratio < 1) + runtime.Expected = elapsed; + runtime.Finished = true; + } + } + Pose = _current; + } + + private void Circle(Runtime runtime) + { + BattleCameraTask task = runtime.Definition; + // The other two circle branches in both published executables are + // empty functions, including lists shipped as editor experiments. + if (!Has(task, BattleCameraFlags.EndCamera) || !Has(task, BattleCameraFlags.Speed) || Has(task, BattleCameraFlags.Time)) + return; + if (!runtime.Executed) + { + Begin(runtime, false); + _distance = task.CircleAngle; + _startSpeed = task.AngularSpeed; + } + float elapsed = Now(task) - runtime.StartTime; + float distance = AcceleratedDistance(task, _startSpeed, elapsed); + if (_distance > 0 ? distance > _distance : distance < _distance) + distance = _distance; + float ratio = distance / _distance; + BattleMovementPoint relative = Subtract(runtime.Start.Position, task.CircleCenter); + // gbQuaternion::SetYawPitchRoll + GetMatrix + RotateIn. Retaining + // the half-angle construction also retains its float rounding. + // gbSin/gbCos take degrees even though tagCam's Euler angles are + // radians. Published flexcam circles contain values such as 250 + // and -180; interpreting these as radians reverses their framing. + double radians = (double)(distance * 0.5f) * 0.01745329238474369f; + float sine = (float)Math.Sin(radians), cosine = (float)Math.Cos(radians); + float xx = 1 - 2 * sine * sine, xz = -2 * sine * cosine; + BattleMovementPoint position = new(relative.X * xx - relative.Z * xz + task.CircleCenter.X, + relative.Y + task.CircleCenter.Y + (task.CircleEnd.Y - task.CircleCenter.Y) * ratio, + relative.X * xz + relative.Z * xx + task.CircleCenter.Z); + BattleMovementPoint trace = Trace(runtime, ref position); + if (Has(task, BattleCameraFlags.SightTrace)) + { + _current = _current.WithPosition(position); + LookAt(position, trace); + } + else + _current = _start.WithPosition(position); + Pose = _current; + if (_distance > 0 ? distance >= _distance : distance <= _distance) + { + runtime.Expected = elapsed; + runtime.Finished = true; + } + } + + private void Mechanics(Runtime runtime, float delta) + { + BattleCameraTask task = runtime.Definition; + if (!runtime.Executed) + { + Begin(runtime, false); + _position = runtime.Start.Position; + BattleMovementPoint direction = Subtract(task.End.Position, runtime.Start.Position); + if (runtime.Expected > 0) + direction = Scale(direction, 1 / runtime.Expected); + if (CurrentTask == 0 || !Has(_lists[CurrentList][CurrentTask - 1].Definition, BattleCameraFlags.Mechanics)) + _speed = direction; + _nextSpeed = direction; + _current = runtime.Start; + } + float elapsed = Now(task) - runtime.StartTime; + float ratio = runtime.Expected <= 0 ? 1 : elapsed / (runtime.Expected + task.TimeCompensation); + float speed = (float)BattleMovement.Distance(default, _speed); + _speed = Scale(BattleMovement.NormalizeDirection(Add(_speed, Scale(_nextSpeed, delta))), speed); + _position = Add(_position, Scale(_speed, delta)); + BattleMovementPoint position = _position; + BattleMovementPoint trace = Trace(runtime, ref position); + if (Has(task, BattleCameraFlags.SightTrace)) + { + _current = _current.WithPosition(position); + LookAt(position, trace); + } + else + _current = BattleCameraPose.Interpolate(_start, task.End, ratio).WithPosition(position); + Pose = _current; + if (ratio >= 1) + runtime.Finished = true; + } + + private BattleMovementPoint Trace(Runtime runtime, ref BattleMovementPoint position) + { + BattleCameraTask task = runtime.Definition; + BattleMovementPoint trace = default; + if (Has(task, BattleCameraFlags.PositionTrace | BattleCameraFlags.SightTrace)) + trace = _tracePosition(task.TraceActor); + if (Has(task, BattleCameraFlags.PositionTrace)) + position = Subtract(Add(position, trace), runtime.TraceStart); + return trace; + } + + private void LookAt(BattleMovementPoint from, BattleMovementPoint target) + { + BattleMovementPoint direction = Subtract(target, from); + float yaw = (float)Math.Atan(-direction.X / direction.Z); + if (target.Z > from.Z) + yaw += (float)Math.PI; + float pitch = (float)Math.Asin(direction.Y / (float)BattleMovement.Distance(from, target)); + _current = _current.WithAngles(yaw, pitch); + } + + private static BattleMovementPoint Add(BattleMovementPoint a, BattleMovementPoint b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z); + + private static BattleMovementPoint Subtract(BattleMovementPoint a, BattleMovementPoint b) => new(a.X - b.X, a.Y - b.Y, a.Z - b.Z); + + private static BattleMovementPoint Scale(BattleMovementPoint point, float factor) => new(point.X * factor, point.Y * factor, point.Z * factor); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleCamera.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleCamera.cs.meta new file mode 100644 index 00000000..5821f69e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleCamera.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 78daa390992f48bc85c7cae9d9fa1e53 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleComboStageProfile.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleComboStageProfile.cs new file mode 100644 index 00000000..567c693e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleComboStageProfile.cs @@ -0,0 +1,185 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + // Resource work occurs while the original screen is faded out, before the + // actor positions or effect playback change. + public interface IBattleEffectPreloader + { + void Preload(int groupId); + } + + public enum BattleCoAttackStep + { + GrabSource, FadeOutToCombo, Preload, SetComboPositions, FadeInToCombo, + ShowName, WaitForSource, Act, WaitForSourceAfterAct, FadeOutToHome, + RestorePositions, FadeInToHome, ReleaseSource + } + + public enum BattleCoAttackStepStatus + { + Ready, Running, Finished + } + + // Original linker metadata is captured before a command changes session state. + // CoAttack creates no ordinary role animation; the effect group owns its visuals. + public sealed class BattleComboStageProfile + { + public const float FadeSeconds = 1f; + public const float NameSeconds = 1f; + + public int FirstGroupId + { + get; + } + + public int SecondGroupId + { + get; + } + + public float FirstWaitSeconds + { + get; + } + + public float SecondWaitSeconds + { + get; + } + + public float WorkSeconds + { + get; + } + + public BattleMovementPoint FirstOrigin + { + get; + } + + public BattleMovementPoint SecondOrigin + { + get; + } + + public BattleMovementPoint EnemyCenter + { + get; + } + + public BattleComboStageProfile(int firstGroupId, int secondGroupId, + float firstWaitSeconds, float secondWaitSeconds, float workSeconds, + BattleMovementPoint firstOrigin = default, BattleMovementPoint secondOrigin = default, + BattleMovementPoint enemyCenter = default) + { + if (firstGroupId < -1 || secondGroupId < -1 || !ValidTime(firstWaitSeconds) || + !ValidTime(secondWaitSeconds) || !ValidTime(workSeconds)) + throw new ArgumentException("Invalid original combo effect linker."); + FirstGroupId = firstGroupId; + SecondGroupId = secondGroupId; + FirstWaitSeconds = firstWaitSeconds; + SecondWaitSeconds = secondWaitSeconds; + WorkSeconds = workSeconds; + FirstOrigin = firstOrigin; + SecondOrigin = secondOrigin; + EnemyCenter = enemyCenter; + } + + private static bool ValidTime(float value) => float.IsFinite(value) && value >= 0 && value <= 600; + } + + public sealed class BattleCoAttackStepSnapshot + { + public BattleCoAttackStep Step + { + get; + } + + public BattleCoAttackStepStatus Status + { + get; + } + + public float StartTime + { + get; + } + + internal BattleCoAttackStepSnapshot(BattleCoAttackStep step, BattleCoAttackStepStatus status, float startTime) + { + Step = step; + Status = status; + StartTime = startTime; + } + } + + public sealed class BattleCoAttackSnapshot + { + public long ActionId + { + get; + } + + public int ComboId + { + get; + } + + public string Source + { + get; + } + + public string Name + { + get; + } + + public bool NameVisible + { + get; + } + + public bool Worked + { + get; + } + + public bool Finished + { + get; + } + + public IReadOnlyList Targets + { + get; + } + + public IReadOnlyList Steps + { + get; + } + + internal BattleCoAttackSnapshot(long actionId, BattleComboDefinition combo, string source, + bool nameVisible, bool worked, bool finished, IEnumerable targets, IEnumerable steps) + { + ActionId = actionId; + ComboId = combo.Id; + Source = source; + Name = combo.Name; + NameVisible = nameVisible; + Worked = worked; + Finished = finished; + Targets = Array.AsReadOnly(targets.ToArray()); + Steps = Array.AsReadOnly(steps.ToArray()); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleComboStageProfile.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleComboStageProfile.cs.meta new file mode 100644 index 00000000..1d796c28 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleComboStageProfile.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7708d2a79cd347ec9c3b8bc9f54b96b9 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleEffectDirector.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleEffectDirector.cs new file mode 100644 index 00000000..dc51edaf --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleEffectDirector.cs @@ -0,0 +1,86 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public sealed class BattleEffectRequest + { + public int GroupId + { + get; + } + + public string Source + { + get; + } + + public IReadOnlyList Targets + { + get; + } + + public BattleMovementPoint Origin + { + get; + } + + public uint Seed + { + get; + } + + public bool AbsoluteTime + { + get; + } + + public BattleEffectRequest(int groupId, string source, IEnumerable targets, BattleMovementPoint origin, uint seed, + bool absoluteTime = false) + { + if (groupId < 0 || string.IsNullOrWhiteSpace(source)) + throw new ArgumentException("An effect needs a group and its owning combat actor."); + GroupId = groupId; + Source = source; + Targets = Array.AsReadOnly(targets?.ToArray() ?? Array.Empty()); + Origin = origin; + Seed = seed; + AbsoluteTime = absoluteTime; + } + } + + // Role bodies update before the original camera controller. An optional + // stage presentation owner receives only completed (including resumed) frames. + public interface IBattleStagePresentation + { + void AdvanceStage(double scaledSeconds, double absoluteSeconds); + } + + public interface IBattleTimeScale + { + // Native slow-motion effects temporarily run the stage at a fraction of normal speed (0–1). + float TimeScale + { + get; + } + } + + // The composition root supplies the original resource player. Advancing it + // belongs to the fixed battle loop; rendering never determines work timing. + public interface IBattleEffectDirector + { + long Start(BattleEffectRequest request); + + bool IsRunning(long handle); + + void Advance(long frame, float scaledSeconds, float unscaledSeconds); + + void Stop(long handle); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleEffectDirector.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleEffectDirector.cs.meta new file mode 100644 index 00000000..cb33bbf1 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleEffectDirector.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f35ce1f500554374998f66f9d3464dfc diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleElementWheelTimings.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleElementWheelTimings.cs new file mode 100644 index 00000000..0fa7efd8 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleElementWheelTimings.cs @@ -0,0 +1,18 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + // The wheel has no spell name, lineup, casting bar, MP cost or proficiency. + // Its dedicated body task plays Nangong Huang's z24 and the two linker groups. + public interface IBattleElementWheelTimings + { + AttackTiming ElementWheel(string actor, BattleAbilityDefinition ability); + + BattleAbilityStageProfile ElementWheelStage(string actor, BattleAbilityDefinition ability); + + BattlePhysicalAnimation ElementWheelBody(string actor, BattleAbilityDefinition ability); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleElementWheelTimings.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleElementWheelTimings.cs.meta new file mode 100644 index 00000000..0d32ace4 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleElementWheelTimings.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 808cf717dcf04ed69249623f7d26c02e diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleHitFlash.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleHitFlash.cs new file mode 100644 index 00000000..6305e75d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleHitFlash.cs @@ -0,0 +1,50 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + // CEffectSimple: one fixed XZ quad, sixteen 64x64 cells, one 50 fps loop. + public sealed class BattleHitFlashSnapshot + { + public long Id + { + get; + } + + public string Actor + { + get; + } + + public BattleMovementPoint Position + { + get; + } + + public int Frame + { + get; + } + + public const float HalfSize = 100; + + public const int FrameCount = 16; + + internal BattleHitFlashSnapshot(long id, string actor, BattleMovementPoint position, int frame) + { + Id = id; + Actor = actor; + Position = position; + Frame = frame; + } + + // PAL3::GAME_COMBAT updates the global simple particles after the role + // pass that creates them. The creation pass already advances one cell. + public static int FrameAt(long elapsedTicks) => elapsedTicks < 0 ? -1 : + checked((int)Math.Round((elapsedTicks + 1) * BattleSession.StepSeconds * 50, MidpointRounding.ToEven)); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleHitFlash.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleHitFlash.cs.meta new file mode 100644 index 00000000..acbaa481 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleHitFlash.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 96e35fe97a574c6292790e89e453edf0 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleMagicSwordStageProfile.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleMagicSwordStageProfile.cs new file mode 100644 index 00000000..0b371d9d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleMagicSwordStageProfile.cs @@ -0,0 +1,70 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public interface IBattleMagicSwordTimings + { + BattleMagicSwordStageProfile MagicSword(string actor, BattleAbilityDefinition ability); + } + + // ProcWeaponSkillAct waits for group 1 to finish. WorkTime is deliberately absent. + public sealed class BattleMagicSwordStageProfile + { + public const float NameDelaySeconds = 1; + + public int FirstGroupId + { + get; + } + + public int SecondGroupId + { + get; + } + + public float FirstWaitSeconds + { + get; + } + + public float SecondWaitSeconds + { + get; + } + + public int BodyAnimationTicks + { + get; + } + + public BattleMovementPoint FirstOrigin + { + get; + } + + public BattleMovementPoint SecondOrigin + { + get; + } + + public BattleMagicSwordStageProfile(int firstGroupId, int secondGroupId, float firstWaitSeconds, float secondWaitSeconds, int bodyAnimationTicks, + BattleMovementPoint firstOrigin = default, BattleMovementPoint secondOrigin = default) + { + if (firstGroupId < -1 || secondGroupId < -1 || !float.IsFinite(firstWaitSeconds) || !float.IsFinite(secondWaitSeconds) || + firstWaitSeconds < 0 || secondWaitSeconds < 0 || firstWaitSeconds > 600 || secondWaitSeconds > 600 || bodyAnimationTicks < 1 || bodyAnimationTicks > 30000) + throw new ArgumentException("Invalid original magic sword stage profile."); + FirstGroupId = firstGroupId; + SecondGroupId = secondGroupId; + FirstWaitSeconds = firstWaitSeconds; + SecondWaitSeconds = secondWaitSeconds; + BodyAnimationTicks = bodyAnimationTicks; + FirstOrigin = firstOrigin; + SecondOrigin = secondOrigin; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleMagicSwordStageProfile.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleMagicSwordStageProfile.cs.meta new file mode 100644 index 00000000..cdb9fbf1 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleMagicSwordStageProfile.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 282c0ef9b45d40aab1dddbe02522df68 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleMonsterFactory.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleMonsterFactory.cs new file mode 100644 index 00000000..b2f35614 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleMonsterFactory.cs @@ -0,0 +1,47 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public sealed class BattleMonsterCreation + { + private readonly BattleParticipant _participant; + + public int NativeIndex + { + get; + } + + public BattleParticipant Participant => _participant.Copy(); + + public BattleActorDefinition Definition + { + get; + } + + public BattleMonsterCreation(int nativeIndex, BattleParticipant participant, BattleActorDefinition definition) + { + if (nativeIndex < 5 || nativeIndex > 10 || participant == null || definition == null || + participant.Side != BattleSide.Enemy || (int)participant.Slot != nativeIndex - 5 || + participant.InstanceId != definition.InstanceId || !string.IsNullOrEmpty(definition.UnsupportedReason)) + throw new ArgumentException("A supported captured monster in its original enemy slot is required."); + NativeIndex = nativeIndex; + _participant = participant.Copy(); + Definition = definition; + } + } + + // Prepare can load and validate resources without changing a live catalog. + // Commit publishes those prepared bindings only after the session validates + // the candidate. Native slots keep stable instance IDs across replacement. + public interface IBattleMonsterFactory + { + BattleMonsterCreation Prepare(int nativeIndex, int actorId, string instanceId); + + void Commit(BattleMonsterCreation creation); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleMonsterFactory.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleMonsterFactory.cs.meta new file mode 100644 index 00000000..fef16eb7 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleMonsterFactory.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ea10d0e34a2141978a48ca24d7b9508a diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleMovement.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleMovement.cs new file mode 100644 index 00000000..79bfd253 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleMovement.cs @@ -0,0 +1,487 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + // Raw GameBox scene/model units. Presentation owns conversion to Unity coordinates. + public readonly struct BattleMovementPoint + { + public float X + { + get; + } + + public float Y + { + get; + } + + public float Z + { + get; + } + + public BattleMovementPoint(float x, float y, float z) + { + if (float.IsNaN(x) || float.IsInfinity(x) || float.IsNaN(y) || float.IsInfinity(y) || + float.IsNaN(z) || float.IsInfinity(z)) + throw new ArgumentException("Movement coordinates must be finite."); + X = x; + Y = y; + Z = z; + } + } + + public enum BattleMovementMessage + { + None, FlyUp, FlyDown, Over + } + + public enum BattleMovementKind + { + Run, + Fly, + Teleport, + FlyRotate, + NpcFly, + FastRun, + EnemyFlee + } + + // One native role task, without assumptions about the gap to the next queued task. + // Animation ticks are zero-based task calls: the first Step consumes call 0. + public sealed class BattleMovementPlan + { + public BattleMovementKind Kind + { + get; + } + + public BattleMovementPoint From + { + get; + } + + public BattleMovementPoint To + { + get; + } + + public int? FlyUpTick + { + get; + } + + public int? FlyDownTick + { + get; + } + + public int? OverTick + { + get; + } + + public float TargetBlend + { + get; + } + + public float InitialBlend + { + get; + } + + public BattleMovementPlan(BattleMovementKind kind, BattleMovementPoint from, BattleMovementPoint to, + int? flyUpTick = null, int? flyDownTick = null, int? overTick = null, + float targetBlend = 1f, float initialBlend = 1f) + { + if (!Enum.IsDefined(typeof(BattleMovementKind), kind) || flyUpTick < 0 || flyDownTick < 0 || overTick < 0 || + float.IsNaN(targetBlend) || targetBlend < 0f || targetBlend > 1f || + float.IsNaN(initialBlend) || initialBlend < 0f || initialBlend > 1f) + throw new ArgumentException("Invalid native movement plan."); + Kind = kind; + From = from; + To = to; + FlyUpTick = flyUpTick; + FlyDownTick = flyDownTick; + OverTick = overTick; + TargetBlend = targetBlend; + InitialBlend = initialBlend; + } + } + + public sealed class BattleMovementSnapshot + { + public BattleMovementPlan Plan + { + get; + } + + public int ElapsedTicks + { + get; + } + + public double ElapsedSeconds => ElapsedTicks * BattleMovement.StepSeconds; + + public BattleMovementPoint Position + { + get; + } + + public float Blend + { + get; + } + + public bool Finished + { + get; + } + + internal BattleMovementSnapshot(BattleMovement movement) + { + Plan = movement.Plan; + ElapsedTicks = movement.ElapsedTicks; + Position = movement.Position; + Blend = movement.Blend; + Finished = movement.Finished; + } + } + + public sealed class BattleMovement + { + public const double StepSeconds = 0.02d; + private const double DegreesPerRadian = 57.295780181884766d; + private const double TwoPi = 6.2831854820251465d; + private const double DirectionThreshold = 1.5707963705062866d; + private readonly bool _isPal3A; + private bool _initialized; + private bool _flying; + private bool _fadingOut; + private BattleMovementPoint _velocity; + private float _initialDirection; + private bool _headingAssigned; + private float _travelDirection; + private BattleMovementMessage? _message; + private float _targetBlend; + + public BattleMovementPlan Plan + { + get; + } + + public int ElapsedTicks + { + get; private set; + } + + public double ElapsedSeconds => ElapsedTicks * StepSeconds; + + public BattleMovementPoint Position + { + get; private set; + } + + public float Blend + { + get; private set; + } + + public bool Finished + { + get; private set; + } + + public BattleMovement(string variant, BattleMovementPlan plan) + { + if (variant is not ("PAL3" or "PAL3A")) + throw new ArgumentException("Unknown combat variant.", nameof(variant)); + Plan = plan ?? throw new ArgumentNullException(nameof(plan)); + _isPal3A = variant == "PAL3A"; + Position = plan.From; + Blend = plan.InitialBlend; + _targetBlend = plan.TargetBlend; + } + + public float? FacingDegrees => _headingAssigned ? _initialDirection : null; + + public static float FacingBetween(BattleMovementPoint from, BattleMovementPoint to) => InitialHeading(Normalize(new BattleMovementPoint(to.X - from.X, to.Y - from.Y, to.Z - from.Z))); + + public static double Distance(BattleMovementPoint first, BattleMovementPoint second) => Length(Difference(first, second)); + + public static BattleMovementPoint NormalizeDirection(BattleMovementPoint vector) => Normalize(vector); + + public void SetHeading(float degrees) + { + if (!float.IsFinite(degrees)) + throw new ArgumentOutOfRangeException(nameof(degrees)); + _initialDirection = degrees; + _headingAssigned = true; + } + + public BattleMovementSnapshot Capture() => new(this); + + // Original SetPos writes the shared body position without replacing the + // currently executing task, its destination, velocity or marker state. + public void Relocate(BattleMovementPoint position) => Position = position; + + // Session cancellation is not another original task update. + public void Stop() => Finished = true; + + public void Step(bool alive = true) => Step(alive, null); + + public void Step(bool alive, BattleMovementMessage? message) + { + _message = message; + if (Finished) + return; + int call = ElapsedTicks++; + bool first = !_initialized; + BattleMovementPoint difference = Difference(Plan.To, Position); + if (first) + { + _initialized = true; + double length = Length(difference); + if (Plan.Kind != BattleMovementKind.EnemyFlee && length < (Plan.Kind == BattleMovementKind.FastRun ? 4f : 2f) && !(_isPal3A && Plan.Kind == BattleMovementKind.Fly)) + { + Position = Plan.To; + if (Plan.Kind == BattleMovementKind.Teleport) + Blend = 1f; + Finished = true; + return; + } + BattleMovementPoint direction = Normalize(difference); + _travelDirection = InitialHeading(direction); + if (Plan.Kind != BattleMovementKind.FlyRotate) + SetHeading(_travelDirection); + float speed = Plan.Kind switch + { + BattleMovementKind.Fly or BattleMovementKind.FlyRotate => (float)length * 2f, + BattleMovementKind.NpcFly => 570f, + BattleMovementKind.FastRun => 480f, + _ => 380f + }; + if (_isPal3A && Plan.Kind == BattleMovementKind.Fly) + { + // PAL3A keeps length * (1/30 float) * 50 in x87 until each component store. + double flightSpeed = (float)length * (double)(1f / 30f) * 50f; + _velocity = new BattleMovementPoint((float)(direction.X * flightSpeed), (float)(direction.Y * flightSpeed), (float)(direction.Z * flightSpeed)); + } + else + _velocity = Scale(direction, speed); + _fadingOut = true; + } + switch (Plan.Kind) + { + case BattleMovementKind.Run: + case BattleMovementKind.EnemyFlee: + case BattleMovementKind.NpcFly: + case BattleMovementKind.FastRun: + StepRun(alive); + break; + case BattleMovementKind.FlyRotate: + StepFlyRotate(difference, call, first, alive); + break; + case BattleMovementKind.Fly: + if (_isPal3A) + StepPal3AFlight(call, first, alive); + else + StepFly(difference, call, first, alive); + break; + case BattleMovementKind.Teleport: + StepTeleport(alive); + break; + default: + throw new InvalidOperationException("Unknown movement kind."); + } + } + + public void SetTargetBlend(float blend) + { + if (!float.IsFinite(blend) || blend is < 0f or > 1f) + throw new ArgumentOutOfRangeException(nameof(blend)); + _targetBlend = blend; + } + + private bool HasMessage(BattleMovementMessage message, int? scheduled, int call) => + _message.HasValue ? _message.Value == message : scheduled == call; + + private void StepRun(bool alive) + { + Integrate(); + BattleMovementPoint remaining = Difference(Plan.To, Position); + if (Plan.Kind != BattleMovementKind.EnemyFlee && Length(remaining) < (Plan.Kind == BattleMovementKind.FastRun ? 4f : 2f) || PassedTarget(remaining)) + { + Position = Plan.To; + Finished = true; + } + if (!alive) + Finished = true; + } + + private void StepFly(BattleMovementPoint difference, int call, bool first, bool alive) + { + // Original activation resets dwMsg=0 even when an animation marker arrived. + bool up = !first && HasMessage(BattleMovementMessage.FlyUp, Plan.FlyUpTick, call); + bool down = !first && HasMessage(BattleMovementMessage.FlyDown, Plan.FlyDownTick, call) && !up; + bool over = !first && HasMessage(BattleMovementMessage.Over, Plan.OverTick, call) && !up && !down; + if (up) + _flying = true; + double distanceBeforeStep = Length(difference); + if (_flying && distanceBeforeStep > 2f) + Integrate(); + if (down && distanceBeforeStep <= 2f) + _flying = false; + // The direction test deliberately uses the pre-integration vector too. + if (PassedTarget(difference)) + { + Position = Plan.To; + _flying = false; + } + if (over) + { + Position = Plan.To; + Finished = true; + } + if (!alive) + Finished = true; + } + + private void StepPal3AFlight(int call, bool first, bool alive) + { + bool up = !first && HasMessage(BattleMovementMessage.FlyUp, Plan.FlyUpTick, call); + bool down = !first && HasMessage(BattleMovementMessage.FlyDown, Plan.FlyDownTick, call) && !up; + bool over = !first && HasMessage(BattleMovementMessage.Over, Plan.OverTick, call) && !up && !down; + if (up) + _flying = true; + if (down) + _flying = false; + if (_flying) + { + Integrate(); + if (Length(Difference(Plan.To, Position)) < 8f) + { + Position = Plan.To; + _flying = false; + } + } + if (over) + { + Position = Plan.To; + Finished = true; + } + if (!alive) + Finished = true; + } + + private void StepFlyRotate(BattleMovementPoint difference, int call, bool first, bool alive) + { + if (_isPal3A) + throw new NotSupportedException("PAL3A's thrown weapon is a separate actor, not body movement."); + bool up = !first && HasMessage(BattleMovementMessage.FlyUp, Plan.FlyUpTick, call); + bool down = !first && HasMessage(BattleMovementMessage.FlyDown, Plan.FlyDownTick, call) && !up; + bool over = !first && HasMessage(BattleMovementMessage.Over, Plan.OverTick, call) && !up && !down; + if (up) + _flying = true; + double distance = Length(difference); + if (_flying && distance > 2f) + { + Integrate(); + SetHeading((float)(_initialDirection + StepSeconds * 720f)); + } + if (down && distance <= 2f) + _flying = false; + if (PassedTarget(difference, _travelDirection)) + { + Position = Plan.To; + _flying = false; + } + if (over) + { + Position = Plan.To; + Finished = true; + } + if (!alive) + Finished = true; + } + + private void StepTeleport(bool alive) + { + double next = Blend + (_fadingOut ? -1d : 1d) * StepSeconds * 2.5d; + float stored = (float)next; + if (_fadingOut) + { + if (next < 0d) + { + _fadingOut = false; + Position = Plan.To; + if (_isPal3A) + stored = 0f; + } + } + else if ((_isPal3A ? stored : next) >= _targetBlend) + { + stored = _targetBlend; + Finished = true; + } + if (!alive) + { + stored = _targetBlend; + Finished = true; + } + Blend = stored >= 1f ? 1f : stored; + } + + private void Integrate() + { + // PAL3 retains Z*dt in x87 through the addition. X/Y and all PAL3A + // components are stored as float before adding the previous position. + float x = (float)(Position.X + (float)(_velocity.X * StepSeconds)); + float y = (float)(Position.Y + (float)(_velocity.Y * StepSeconds)); + float z = _isPal3A ? (float)(Position.Z + (float)(_velocity.Z * StepSeconds)) + : (float)(Position.Z + _velocity.Z * StepSeconds); + Position = new BattleMovementPoint(x, y, z); + } + + private bool PassedTarget(BattleMovementPoint difference) => PassedTarget(difference, _initialDirection); + + private static bool PassedTarget(BattleMovementPoint difference, float originalDirection) + { + BattleMovementPoint direction = Normalize(difference); + float angle = (float)Math.Acos(Math.Max(-1d, Math.Min(1d, direction.Z))); + double radians = direction.X < 0f ? TwoPi - angle : angle; + // The original compares a degree difference with the radian constant PI/2. + return Math.Abs(radians * DegreesPerRadian - originalDirection) >= DirectionThreshold; + } + + private static float InitialHeading(BattleMovementPoint direction) + { + float angle = (float)Math.Acos(Math.Max(-1d, Math.Min(1d, direction.Z))); + if (direction.X < 0f) + angle = (float)(TwoPi - angle); + return (float)(angle * DegreesPerRadian); + } + + private static BattleMovementPoint Difference(BattleMovementPoint left, BattleMovementPoint right) + => new(left.X - right.X, left.Y - right.Y, left.Z - right.Z); + + private static BattleMovementPoint Scale(BattleMovementPoint point, float scale) + => new(point.X * scale, point.Y * scale, point.Z * scale); + + private static double Length(BattleMovementPoint point) + => Math.Sqrt((double)point.X * point.X + (double)point.Y * point.Y + (double)point.Z * point.Z); + + private static BattleMovementPoint Normalize(BattleMovementPoint point) + { + double length = Math.Sqrt((double)point.X * point.X + (double)point.Y * point.Y + (double)point.Z * point.Z); + return length < (double)0.005f ? new BattleMovementPoint(0f, 1f, 0f) + : new BattleMovementPoint((float)(point.X / length), (float)(point.Y / length), (float)(point.Z / length)); + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleMovement.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleMovement.cs.meta new file mode 100644 index 00000000..a2e0fa43 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleMovement.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f62b8643fed44c8fb9fb1b1f9393a7a1 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalGeometry.cs b/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalGeometry.cs new file mode 100644 index 00000000..310e99e3 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalGeometry.cs @@ -0,0 +1,113 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + + public readonly struct BattlePhysicalAnchor + { + public int First + { + get; + } + + public int? Second + { + get; + } + + public BattlePhysicalAnchor(int first, int? second = null) + { + if (first is < 0 or > 10 || second is < 0 or > 10) + throw new ArgumentException("Invalid original attack anchor."); + First = first; + Second = second; + } + } + + public static class BattlePhysicalGeometry + { + public static BattlePhysicalAnchor Anchor(IReadOnlyList selected, IReadOnlyDictionary slots, int sceneElement) + { + if (selected == null || slots == null) + throw new ArgumentNullException(selected == null ? nameof(selected) : nameof(slots)); + int[] indices = selected.OrderBy(index => index).ToArray(); + if (indices.Length == 0 || indices.Any(index => index is < 0 or > 10)) + throw new ArgumentException("The original normal attack requires a target mask."); + if (indices.Length == 1) + return new BattlePhysicalAnchor(indices[0]); + bool Has(int index) => Array.IndexOf(indices, index) >= 0; + if (indices[0] >= 5) + { + if (Has(8) && Has(9)) + return new BattlePhysicalAnchor(8, 9); + if (Has(5) && Has(7)) + return new BattlePhysicalAnchor(10); + if (Has(6) && !Has(10)) + return new BattlePhysicalAnchor(6); + if (Has(5) && Has(10) && !Has(7)) + return new BattlePhysicalAnchor(5, 10); + if (!Has(5) && Has(10) && Has(7)) + return new BattlePhysicalAnchor(10, 7); + if (Has(8) && Has(5)) + return new BattlePhysicalAnchor(8); + if (Has(9) && Has(7)) + return new BattlePhysicalAnchor(9); + if (Has(10) && Has(6)) + return new BattlePhysicalAnchor(10); + return new BattlePhysicalAnchor(indices[0]); + } + int first = indices[0], second = indices[1]; + if (second < 5 && BattleTargetRules.Aligned(BattleSide.Ally, slots[first], slots[second], true, sceneElement)) + { + if (indices.Length == 2) + return new BattlePhysicalAnchor(first, second); + foreach (int index in indices.Take(3)) + if (slots[index] == BattleSlot.Center) + return new BattlePhysicalAnchor(index); + } + return new BattlePhysicalAnchor(slots[first] == BattleSlot.Center || BattleTargetRules.IsFrontAllySlot(slots[first], sceneElement) ? first : second); + } + + public static BattleMovementPoint Approach(BattleMovementPoint source, float sourceRadius, BattleMovementPoint firstHome, + float targetRadius, BattleMovementPoint? secondHome = null, bool spear = false, bool doubleRadius = false) + { + BattleMovementPoint destination = secondHome.HasValue + ? new BattleMovementPoint((firstHome.X + secondHome.Value.X) / 2f, (firstHome.Y + secondHome.Value.Y) / 2f, (firstHome.Z + secondHome.Value.Z) / 2f) + : firstHome; + BattleMovementPoint direction = BattleMovement.NormalizeDirection(new BattleMovementPoint(source.X - destination.X, + source.Y - destination.Y, source.Z - destination.Z)); + float distance = secondHome.HasValue ? 40f : sourceRadius + targetRadius + (spear ? 80f : 0f); + var offset = new BattleMovementPoint(direction.X * distance, direction.Y * distance, direction.Z * distance); + if (doubleRadius && !secondHome.HasValue) + offset = new BattleMovementPoint(offset.X * 2f, offset.Y * 2f, offset.Z * 2f); + return new BattleMovementPoint(destination.X + offset.X, destination.Y + offset.Y, destination.Z + offset.Z); + } + + public static BattleMovementPoint ProtectPosition(BattleMovementPoint targetHome, BattleMovementPoint attackerHome, float distance = 40f) + { + BattleMovementPoint direction = BattleMovement.NormalizeDirection(new BattleMovementPoint(attackerHome.X - targetHome.X, + attackerHome.Y - targetHome.Y, attackerHome.Z - targetHome.Z)); + return new BattleMovementPoint(targetHome.X + direction.X * distance, targetHome.Y + direction.Y * distance, targetHome.Z + direction.Z * distance); + } + + public static BattleMovementPoint ProtectRunTarget(BattleMovementPoint source, BattleMovementPoint targetHome, BattleMovementPoint attackerHome) + { + BattleMovementPoint destination = ProtectPosition(targetHome, attackerHome, 32f); + if (BattleMovement.Distance(source, destination) < 4f) + return destination; + BattleMovementPoint direction = BattleMovement.NormalizeDirection(new BattleMovementPoint(source.X - destination.X, + source.Y - destination.Y, source.Z - destination.Z)); + return new BattleMovementPoint(destination.X + direction.X * 10f, destination.Y + direction.Y * 10f, destination.Z + direction.Z * 10f); + } + + public static bool AtProtectPosition(int guardianIndex, BattleMovementPoint source, BattleMovementPoint targetHome, BattleMovementPoint attackerHome) + => guardianIndex == 0 && BattleMovement.Distance(source, ProtectPosition(targetHome, attackerHome)) <= 20f; + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalGeometry.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalGeometry.cs.meta new file mode 100644 index 00000000..7afbe3a7 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalGeometry.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b1666eec37694caf853a13a2a5b0d8a5 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalStageProfile.cs b/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalStageProfile.cs new file mode 100644 index 00000000..a2086702 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalStageProfile.cs @@ -0,0 +1,280 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + + public enum BattlePhysicalBodyKind + { + Run, Fly, FlyRotate, NpcFly, Teleport, Turn, TurnToPosition, TurnToRole, + Attack, Protect, FastRun, ThrownWeapon, StartGuard, RestoreThrownWeapon, FleeWait, EnemyFlee + } + + public enum BattlePhysicalMarkerKind + { + Work, Work1, Work2, Work3, Over, FlyUp, FlyDown, Start, Other, Catched, Throwed + } + + public readonly struct BattlePhysicalMarker + { + public int Tick + { + get; + } + + public BattlePhysicalMarkerKind Kind + { + get; + } + + public uint GameBoxTick + { + get; + } + + public string NativeName + { + get; + } + + public BattlePhysicalMarker(int tick, BattlePhysicalMarkerKind kind, uint? gameBoxTick = null, string nativeName = null) + { + if (tick < 0 || !Enum.IsDefined(typeof(BattlePhysicalMarkerKind), kind)) + throw new ArgumentException("Invalid physical animation marker."); + Tick = tick; + Kind = kind; + GameBoxTick = gameBoxTick ?? checked((uint)tick * 96); + NativeName = nativeName; + } + } + + public sealed class BattlePhysicalAnimation + { + public string Clip + { + get; + } + + public int DurationTicks + { + get; + } + + public float HalfDepth + { + get; + } + + public IReadOnlyList Markers + { + get; + } + + public uint GameBoxDuration + { + get; + } + + public BattlePhysicalAnimation(string clip, int durationTicks, float halfDepth, IEnumerable markers = null, uint? gameBoxDuration = null) + { + if (string.IsNullOrWhiteSpace(clip) || durationTicks < 1 || !float.IsFinite(halfDepth) || halfDepth < 0) + throw new ArgumentException("Invalid original physical animation."); + Clip = clip; + DurationTicks = durationTicks; + HalfDepth = halfDepth; + GameBoxDuration = gameBoxDuration ?? checked((uint)durationTicks * 96); + if (GameBoxDuration == 0) + throw new ArgumentException("The original actor animation duration must be nonzero."); + Markers = Array.AsReadOnly((markers ?? Array.Empty()).OrderBy(marker => marker.GameBoxTick).ToArray()); + } + } + + // The current clip's merged original AABB supplies the native OBB depth. + // Actor identity, weapon/lian and animation metadata are captured together. + public sealed class BattlePhysicalStageProfile + { + public string Variant + { + get; + } + + public int ResourceId + { + get; + } + + public int Identity + { + get; + } + + public int WeaponType + { + get; + } + + public int AttackCount + { + get; + } + + public bool Transformed + { + get; + } + + public BattlePhysicalAnimation ThrownStart + { + get; + } + + public BattlePhysicalAnimation ThrownReturn + { + get; + } + + public bool IsAlly => Identity >= 0; + + public IReadOnlyDictionary Animations + { + get; + } + + public BattlePhysicalStageProfile(string variant, int resourceId, int identity, int weaponType, int attackCount, + IReadOnlyDictionary animations, bool transformed = false, BattlePhysicalAnimation thrownStart = null, BattlePhysicalAnimation thrownReturn = null) + { + if (variant is not ("PAL3" or "PAL3A") || identity is < -1 or > 4 || weaponType < 0 || attackCount < 0 || animations == null || + !animations.TryGetValue(BattlePose.Idle, out BattlePhysicalAnimation idle) || idle == null) + throw new ArgumentException("Incomplete original physical profile."); + Variant = variant; + ResourceId = resourceId; + Identity = identity; + WeaponType = weaponType; + AttackCount = attackCount; + Transformed = transformed; + ThrownStart = thrownStart; + ThrownReturn = thrownReturn; + Animations = new ReadOnlyDictionary(animations.ToDictionary(pair => pair.Key, pair => pair.Value)); + } + + public BattlePhysicalAnimation Animation(BattlePose pose) => Animations.GetValueOrDefault(pose); + + public int NativeAction(BattlePose pose) => pose switch + { + BattlePose.Idle => IsAlly ? 32 : 50, + BattlePose.Moving or BattlePose.Returning or BattlePose.Repositioning => IsAlly ? 31 : 52, + BattlePose.Attacking => !IsAlly ? 53 : + (Variant == "PAL3" ? Identity == 2 && WeaponType == 7 || Identity == 3 && WeaponType == 4 || Identity == 4 && WeaponType == 2 + : Identity == 1 && WeaponType == 4 || Identity == 2 && WeaponType == 6 || Identity == 4 && WeaponType == 9) ? 30 : 29, + BattlePose.Hurt => IsAlly ? 33 : 54, + BattlePose.GuardHurt => 43, + BattlePose.Dodging => 44, + BattlePose.GuardEntry => 41, + BattlePose.Guard => 42, + BattlePose.Dead => 47, + BattlePose.Dying => 46, + BattlePose.Sleeping => 45, + BattlePose.Casting => IsAlly ? 34 : 55, + BattlePose.Fleeing => 48, + _ => throw new ArgumentException("This body pose requires its command's native action index.", nameof(pose)) + }; + + public float Radius(BattlePose pose) => (Animation(pose) ?? Animations[BattlePose.Idle]).HalfDepth - (Identity == (Variant == "PAL3" ? 1 : 3) ? 10f : 0f); + + public bool UsesThrownWeapon => UsesThrownWeaponFor(Transformed); + + public bool UsesThrownWeaponFor(bool transformed) => Variant == "PAL3A" && (Identity == 0 && WeaponType == 2 && !transformed || Identity == 3 && WeaponType == 10); + + public int DamageCount(BattlePhysicalMarkerKind marker, bool? transformed = null) + { + if (UsesThrownWeaponFor(transformed ?? Transformed) || marker > (Variant == "PAL3A" ? BattlePhysicalMarkerKind.Work3 : BattlePhysicalMarkerKind.Work1)) + return 0; + if (!IsAlly) + return Variant == "PAL3A" || marker == BattlePhysicalMarkerKind.Work ? 1 : 0; + int repeatedIdentity = Variant == "PAL3" ? 2 : 4; + if (Identity != repeatedIdentity) + return 1; + if (WeaponType == 5 && marker == BattlePhysicalMarkerKind.Work) + return 0; + return Math.Max(1, AttackCount); + } + + public bool TurnsAtAttack => IsAlly && Identity == (Variant == "PAL3" ? 2 : 4) && WeaponType != (Variant == "PAL3" ? 7 : 9); + + public IReadOnlyList Approach(bool? transformed = null) + { + bool shape = transformed ?? Transformed; + if (IsAlly && (WeaponType == 5 || Variant == "PAL3A" && WeaponType == 8) || Variant == "PAL3" && ResourceId == 7366) + return Array.AsReadOnly(new[] { BattlePhysicalBodyKind.TurnToRole }); + if (Variant == "PAL3") + return Identity switch + { + 1 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Fly }), + 2 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Teleport, BattlePhysicalBodyKind.Run }), + 3 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.TurnToPosition, BattlePhysicalBodyKind.FlyRotate, BattlePhysicalBodyKind.Turn }), + -1 when ResourceId == 720 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Teleport }), + -1 when ResourceId is 738 or 739 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.NpcFly }), + _ => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Run }) + }; + if (UsesThrownWeaponFor(shape)) + return Array.AsReadOnly(new[] { BattlePhysicalBodyKind.TurnToPosition, BattlePhysicalBodyKind.ThrownWeapon }); + return Identity switch + { + 0 when shape => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Teleport }), + 2 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Teleport }), + 4 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Run, BattlePhysicalBodyKind.Run }), + -1 when ResourceId == 719 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Fly, BattlePhysicalBodyKind.Run }), + -1 when ResourceId == 713 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Teleport, BattlePhysicalBodyKind.Run }), + -1 when ResourceId == 720 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Teleport }), + -1 when ResourceId is 738 or 739 => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.NpcFly }), + _ => Array.AsReadOnly(new[] { BattlePhysicalBodyKind.Run }) + }; + } + + public IReadOnlyList Return(bool? transformed = null) + { + bool shape = transformed ?? Transformed; + var result = new List(); + if (Variant == "PAL3") + result.Add(Identity switch + { + 1 => BattlePhysicalBodyKind.Fly, + 2 => BattlePhysicalBodyKind.Teleport, + 3 => BattlePhysicalBodyKind.FlyRotate, + -1 when ResourceId == 720 => BattlePhysicalBodyKind.Teleport, + -1 when ResourceId is 738 or 739 => BattlePhysicalBodyKind.NpcFly, + _ => BattlePhysicalBodyKind.Run + }); + else if (!IsAlly) + { + if (ResourceId == 719) + result.Add(BattlePhysicalBodyKind.Fly); + else if (ResourceId == 713) + result.Add(BattlePhysicalBodyKind.Teleport); + result.Add(ResourceId switch + { + 720 => BattlePhysicalBodyKind.Teleport, + 738 or 739 => BattlePhysicalBodyKind.NpcFly, + _ => BattlePhysicalBodyKind.Run + }); + } + else if (Identity == 2 && WeaponType == 6 || Identity == 0 && shape) + result.Add(BattlePhysicalBodyKind.Teleport); + else if (Identity == 0 && WeaponType != 2 || Identity == 1 && WeaponType is not (2 or 10) || Identity == 3 && WeaponType != 10 || Identity == 4 && WeaponType == 9) + result.Add(BattlePhysicalBodyKind.Run); + result.Add(BattlePhysicalBodyKind.Turn); + return result.AsReadOnly(); + } + } + + public interface IBattlePhysicalTimings + { + BattlePhysicalStageProfile Physical(string actor); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalStageProfile.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalStageProfile.cs.meta new file mode 100644 index 00000000..ac300335 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattlePhysicalStageProfile.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8c43b1c577974732afbb27f473bd07d0 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattlePose.cs b/Assets/Scripts/Pal3.Battle/Stage/BattlePose.cs new file mode 100644 index 00000000..d0c8c655 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattlePose.cs @@ -0,0 +1,16 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public enum BattlePose + { + Idle, Moving, Attacking, Returning, GuardEntry, Guard, Hurt, Dead, Casting, UsingSkill, UsingItem, Fleeing, Repositioning, Dodging, Dying, Sleeping, GuardHurt + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattlePose.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattlePose.cs.meta new file mode 100644 index 00000000..bc965e60 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattlePose.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 35580b140773483bb2ac0b6828ce11e2 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleSpiritOrb.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleSpiritOrb.cs new file mode 100644 index 00000000..3d9e5143 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleSpiritOrb.cs @@ -0,0 +1,177 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + public readonly struct BattleSpiritPoint + { + public float X + { + get; + } + + public float Y + { + get; + } + + public BattleSpiritPoint(float x, float y) + { + if (!float.IsFinite(x) || !float.IsFinite(y)) + throw new ArgumentException("Spirit UI coordinates must be finite."); + X = x; + Y = y; + } + } + + public readonly struct BattleSpiritRect + { + public int Left + { + get; + } + + public int Top + { + get; + } + + public int Right + { + get; + } + + public int Bottom + { + get; + } + + public BattleSpiritPoint Center => new(Left + (Right - Left) / 2, Top + (Bottom - Top) / 2); + + public BattleSpiritRect(int left, int top, int right, int bottom) + { + if (right <= left || bottom <= top) + throw new ArgumentException("Spirit UI rectangles must have positive dimensions."); + Left = left; + Top = top; + Right = right; + Bottom = bottom; + } + + public bool Reached(int x, int y) => x > Right || x >= Left && x < Right && y >= Top && y < Bottom; + } + + public interface IBattleSpiritCaptureLayout + { + BattleSpiritPoint CaptureSpiritOrigin(string actorId, BattleMovementPoint world); + + BattleSpiritRect SpiritWheelTarget(int coreElement); + } + + public sealed class BattleSpiritOrbSnapshot + { + public long Id + { + get; + } + + public string Source + { + get; + } + + public int Element + { + get; + } + + public BattleSpiritPoint Position + { + get; + } + + public BattleSpiritPoint Origin + { + get; + } + + public BattleSpiritRect Destination + { + get; + } + + public float Acceleration + { + get; + } + + internal BattleSpiritOrbSnapshot(long id, string source, int element, BattleSpiritPoint position, BattleSpiritRect destination, float acceleration, BattleSpiritPoint origin) + { + Id = id; + Source = source; + Element = element; + Position = position; + Origin = origin; + Destination = destination; + Acceleration = acceleration; + } + } + + public sealed class BattleSpiritOrb + { + private float _velocityX, _velocityY; + private int _x, _y; + private readonly BattleSpiritRect _target; + private readonly float _acceleration; + + public BattleSpiritPoint Position => new(_x, _y); + + public BattleSpiritPoint Origin + { + get; + } + + public bool Arrived + { + get; private set; + } + + public BattleSpiritOrb(BattleSpiritPoint origin, BattleSpiritRect target, float acceleration) + { + if (!float.IsFinite(acceleration) || acceleration <= 0) + throw new ArgumentOutOfRangeException(nameof(acceleration)); + _x = BattleNativeArithmetic.TruncateToLowInt32(origin.X); + _y = BattleNativeArithmetic.TruncateToLowInt32(origin.Y); + Origin = new BattleSpiritPoint(_x, _y); + _target = target; + _acceleration = acceleration; + float dx = target.Center.X - _x; + float dy = target.Center.Y - _y; + float length = MathF.Sqrt(dx * dx + dy * dy); + _velocityX = length > 0 ? dx / length : 0; + _velocityY = length > 0 ? dy / length : 0; + } + + public bool Advance(float seconds) + { + if (!float.IsFinite(seconds) || seconds < 0) + throw new ArgumentOutOfRangeException(nameof(seconds)); + if (Arrived) + return false; + // Released UI integrates from the last integer coordinate before + // accelerating the unit vector; dt scales acceleration, not position. + _x = BattleNativeArithmetic.TruncateToLowInt32((float)(_x + (double)_velocityX)); + _y = BattleNativeArithmetic.TruncateToLowInt32((float)(_y + (double)_velocityY)); + _velocityX = (float)(_velocityX + (double)_acceleration * _velocityX * seconds); + _velocityY = (float)(_velocityY + (double)_acceleration * _velocityY * seconds); + // The published UI adds the target half-size again here. Keep its + // half-open right-edge hole and immediate arrival from the right. + Arrived = _target.Reached(_x + (_target.Right - _target.Left) / 2, _y + (_target.Bottom - _target.Top) / 2); + return Arrived; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleSpiritOrb.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleSpiritOrb.cs.meta new file mode 100644 index 00000000..87866343 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleSpiritOrb.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 50505c36cc3c4f038d42b078328bffff diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleStageNumber.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleStageNumber.cs new file mode 100644 index 00000000..1a729751 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleStageNumber.cs @@ -0,0 +1,70 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + // ShowDamage and ShowMiss have the same lifetime and one activation callback. + // The caller owns the original RNG draw, numeric offset, and displayed value. + public sealed class BattleStageNumber : IBattleStageJob + { + private readonly Action _onStart; + private readonly Action _onBodyBlock; + + public float Duration + { + get; + } + + public bool Started + { + get; private set; + } + + public float StartTime + { + get; private set; + } + + public bool Finished + { + get; private set; + } + + public BattleStageNumber(float duration, Action onStart, + Action onBodyBlock = null) + { + if (float.IsNaN(duration) || float.IsInfinity(duration) || duration < 0f) + throw new ArgumentOutOfRangeException(nameof(duration)); + Duration = duration; + _onStart = onStart ?? throw new ArgumentNullException(nameof(onStart)); + _onBodyBlock = onBodyBlock; + } + + public bool Advance(BattleStageContext context) + { + if (Finished) + return true; + if (!Started) + { + Started = true; + StartTime = context.CreatedTime; + if (_onBodyBlock != null) + { + _onBodyBlock(context); + // A blocking body subtask finishes immediately; native DoTask + // starts ShowDamage later in this same pass, resetting its time. + StartTime = context.Time; + } + _onStart(context); + } + // Both operands are stored floats, but x87 retains the subtraction + // through the strict comparison. A float subtraction loses a tick. + Finished = (double)context.Time - StartTime > Duration; + return Finished; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleStageNumber.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleStageNumber.cs.meta new file mode 100644 index 00000000..ef60195f --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleStageNumber.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5849b4dbb05349af9f9250a4fa545c36 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleStagePlans.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleStagePlans.cs new file mode 100644 index 00000000..1a64fce7 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleStagePlans.cs @@ -0,0 +1,56 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + public sealed class BattleAttackPlan + { + public AttackTiming Timing + { + get; + } + + public BattleMovementPoint Origin + { + get; + } + + public BattleMovementPoint Approach + { + get; + } + + public BattleMovementPoint TargetHome + { + get; + } + + public BattleAttackPlan(AttackTiming timing, BattleMovementPoint origin, + BattleMovementPoint approach, BattleMovementPoint targetHome) + { + Timing = timing ?? throw new ArgumentNullException(nameof(timing)); + Origin = origin; + Approach = approach; + TargetHome = targetHome; + } + } + + // All coordinates use original GameBox units. Implementations compile immutable + // resource plans; a running session never changes the shared catalog. + public interface IBattleStageGeometry + { + BattleMovementPoint InitialHome(string actor); + + BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint sourceHome, BattleMovementPoint targetHome); + + BattleMovementPoint FormationHome(string actor, BattleSlot slot); + + IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint currentHome, + BattleMovementPoint destination, bool passThroughMidpoint); + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleStagePlans.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleStagePlans.cs.meta new file mode 100644 index 00000000..8828b2af --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleStagePlans.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 28f333caeb7241c78eec3a66e9359548 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleStageScheduler.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleStageScheduler.cs new file mode 100644 index 00000000..cd89fa7e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleStageScheduler.cs @@ -0,0 +1,299 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + using System.Collections.Generic; + + public interface IBattleStageJob + { + // A finished subtask remains in the stage until the following pass. + bool Advance(BattleStageContext context); + } + + // Jobs that hold resources beyond their scheduler slot release those + // resources when an unfinished task is removed from any cancellation path. + public interface IBattleStageCancellableJob : IBattleStageJob + { + void Cancel(); + } + + public readonly struct BattleStageHandle : IEquatable + { + internal BattleStageScheduler Scheduler + { + get; + } + + public int Slot + { + get; + } + + public long Id + { + get; + } + + internal BattleStageHandle(BattleStageScheduler scheduler, int slot, long id) + { + Scheduler = scheduler; + Slot = slot; + Id = id; + } + + public bool Equals(BattleStageHandle other) + => ReferenceEquals(Scheduler, other.Scheduler) && Slot == other.Slot && Id == other.Id; + + public override bool Equals(object obj) => obj is BattleStageHandle other && Equals(other); + + public override int GetHashCode() => HashCode.Combine(Scheduler, Slot, Id); + + public static bool operator ==(BattleStageHandle left, BattleStageHandle right) => left.Equals(right); + + public static bool operator !=(BattleStageHandle left, BattleStageHandle right) => !left.Equals(right); + } + + public readonly struct BattleStageContext + { + public BattleStageScheduler Scheduler + { + get; + } + + public BattleStageHandle Handle + { + get; + } + + public long Tick + { + get; + } + + public float Time + { + get; + } + + public float CreatedTime + { + get; + } + + internal BattleStageContext(BattleStageScheduler scheduler, BattleStageHandle handle, + long tick, float time, float createdTime) + { + Scheduler = scheduler; + Handle = handle; + Tick = tick; + Time = time; + CreatedTime = createdTime; + } + } + + public sealed class BattleStageTaskSnapshot + { + public BattleStageHandle Handle + { + get; + } + + public string Owner + { + get; + } + + public string Kind + { + get; + } + + public float CreatedTime + { + get; + } + + public bool Finished + { + get; + } + + internal BattleStageTaskSnapshot(BattleStageHandle handle, string owner, string kind, + float createdTime, bool finished) + { + Handle = handle; + Owner = owner; + Kind = kind; + CreatedTime = createdTime; + Finished = finished; + } + } + + // CCBStage allocates the first empty slot and scans the live array in order. + // A task created above the current slot can therefore run in the same pass. + public sealed class BattleStageScheduler + { + public const int DefaultCapacity = 256; + public const double StepSeconds = 0.02d; + private readonly Task[] _tasks; + private long _nextId; + private bool _advancing; + + public int Capacity => _tasks.Length; + + public int Count + { + get; private set; + } + + public BattleStageScheduler(int capacity = DefaultCapacity) + { + if (capacity <= 0) + throw new ArgumentOutOfRangeException(nameof(capacity)); + _tasks = new Task[capacity]; + } + + // This combines native AddTask/StartTask: it stores the float start time + // and marks the task running without executing its first callback. + public BattleStageHandle Add(string owner, string kind, IBattleStageJob job, float createdTime, bool autoDelete = true) + { + if (owner == null) + throw new ArgumentNullException(nameof(owner)); + if (kind == null) + throw new ArgumentNullException(nameof(kind)); + if (job == null) + throw new ArgumentNullException(nameof(job)); + if (float.IsNaN(createdTime) || float.IsInfinity(createdTime)) + throw new ArgumentOutOfRangeException(nameof(createdTime)); + for (int slot = 0; slot < _tasks.Length; slot++) + { + if (_tasks[slot] != null) + continue; + var handle = new BattleStageHandle(this, slot, checked(++_nextId)); + _tasks[slot] = new Task(handle, owner, kind, job, createdTime, autoDelete); + Count++; + return handle; + } + throw new InvalidOperationException("The combat stage task pool is full."); + } + + public bool TryAdd(string owner, string kind, IBattleStageJob job, float createdTime, out BattleStageHandle handle, bool autoDelete = true) + { + if (Count >= Capacity) + { + handle = default; + return false; + } + handle = Add(owner, kind, job, createdTime, autoDelete); + return true; + } + + public bool IsActive(BattleStageHandle handle) + => ReferenceEquals(handle.Scheduler, this) && handle.Slot >= 0 && handle.Slot < _tasks.Length && + _tasks[handle.Slot]?.Handle == handle; + + public bool IsFinished(BattleStageHandle handle) => IsActive(handle) && _tasks[handle.Slot].Finished; + + public bool Cancel(BattleStageHandle handle) + { + if (!IsActive(handle)) + return false; + Task task = _tasks[handle.Slot]; + _tasks[handle.Slot] = null; + Count--; + // Detach first so cancellation is idempotent and may reuse the slot. + if (!task.Finished && task.Job is IBattleStageCancellableJob cancellable) + cancellable.Cancel(); + return true; + } + + public int CountOwner(string owner) + { + int count = 0; + foreach (Task task in _tasks) + { + if (task != null && string.Equals(task.Owner, owner, StringComparison.Ordinal)) + count++; + } + return count; + } + + public IReadOnlyList Snapshot() + { + var result = new List(Count); + foreach (Task task in _tasks) + { + if (task != null) + result.Add(new BattleStageTaskSnapshot(task.Handle, task.Owner, task.Kind, + task.CreatedTime, task.Finished)); + } + return result.AsReadOnly(); + } + + public static float TimeAt(long tick) + { + if (tick < 0) + throw new ArgumentOutOfRangeException(nameof(tick)); + return (float)(tick * StepSeconds); + } + + public void Advance(long tick) + { + float time = TimeAt(tick); + if (_advancing) + throw new InvalidOperationException("A combat stage pass cannot run recursively."); + _advancing = true; + try + { + for (int slot = 0; slot < _tasks.Length; slot++) + { + Task task = _tasks[slot]; + if (task == null) + continue; + if (task.Finished) + { + if (task.AutoDelete) + Cancel(task.Handle); + continue; + } + bool finished = task.Job.Advance(new BattleStageContext(this, task.Handle, + tick, time, task.CreatedTime)); + // A callback may cancel itself and reuse this slot. Its return + // value must never finish or delete the replacement task. + if (ReferenceEquals(_tasks[slot], task)) + task.Finished = finished; + } + } + finally + { + _advancing = false; + } + } + + private sealed class Task + { + internal readonly BattleStageHandle Handle; + internal readonly string Owner; + internal readonly string Kind; + internal readonly IBattleStageJob Job; + internal readonly float CreatedTime; + internal bool Finished; + internal readonly bool AutoDelete; + + internal Task(BattleStageHandle handle, string owner, string kind, IBattleStageJob job, + float createdTime, bool autoDelete) + { + Handle = handle; + Owner = owner; + Kind = kind; + Job = job; + CreatedTime = createdTime; + AutoDelete = autoDelete; + } + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleStageScheduler.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleStageScheduler.cs.meta new file mode 100644 index 00000000..347af90e --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleStageScheduler.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 717863f1aad04b7a82a4e7218df033be diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleThrownWeapon.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleThrownWeapon.cs new file mode 100644 index 00000000..85abe1ab --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleThrownWeapon.cs @@ -0,0 +1,146 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + // PAL3A's second actor travels independently of its owner's body queue. + public sealed class BattleThrownWeapon + { + private const float Delta = .02f; + private BattleMovementPoint _segmentOrigin; + private float _distance; + private float _speed = 680f; + private bool _initialized; + + public BattleMovementPoint Position + { + get; private set; + } + + public BattleMovementPoint Direction + { + get; private set; + } + + public BattleMovementPoint Rotation + { + get; private set; + } + + public int State + { + get; private set; + } + + public bool Active + { + get; private set; + } + + public bool WeaponVisible { get; private set; } = true; + + public bool BodyFinished + { + get; private set; + } + + public bool RestoreRequested + { + get; private set; + } + + public bool HitThisPass + { + get; private set; + } + + public float Speed => _speed; + + public float Distance => _distance; + + public BattleThrownWeapon(BattleMovementPoint source, BattleMovementPoint destination) + { + BattleMovementPoint direction = BattleMovement.NormalizeDirection(new BattleMovementPoint(destination.X - source.X, 36f - source.Y, destination.Z - source.Z)); + Position = new BattleMovementPoint((float)(source.X + direction.X * 68d), 36f, source.Z + direction.Z * 68f); + _segmentOrigin = Position; + BattleMovementPoint difference = new(destination.X - Position.X, 36f - Position.Y, destination.Z - Position.Z); + _distance = (float)BattleMovement.Distance(default, difference); + Direction = BattleMovement.NormalizeDirection(difference); + } + + public void AdvanceBody(BattlePhysicalMarkerKind? marker, bool alive) + { + if (BodyFinished) + return; + _initialized = true; + if (marker == BattlePhysicalMarkerKind.Throwed && !Active) + { + Active = true; + WeaponVisible = false; + double angle = Math.Acos(Math.Clamp(Direction.Z, -1f, 1f)); + if (Direction.X < 0) + angle = 6.2831854820251465d - angle; + Rotation = new BattleMovementPoint(0, (float)(angle * 57.295780181884766d), 0); + BodyFinished = true; + } + else if (marker == BattlePhysicalMarkerKind.Over && Active || !alive) + { + BodyFinished = true; + if (!alive) + WeaponVisible = true; + } + } + + public void Advance(bool alive) + { + HitThisPass = false; + if (!_initialized || !Active) + return; + if (!alive) + { + Active = false; + WeaponVisible = true; + return; + } + if (State == 2) + { + Active = false; + RestoreRequested = true; + return; + } + float vx = Direction.X * _speed; + float vy = Direction.Y * _speed; + if (State == 0) + Position = new BattleMovementPoint(Position.X + vx * Delta, Position.Y + vy * Delta, + (float)(Position.Z + Direction.Z * (double)_speed * Delta)); + else + Position = new BattleMovementPoint((float)(Position.X - vx * (double)Delta), Position.Y - vy * Delta, + Position.Z - (float)(Direction.Z * (double)_speed * Delta)); + double distance = BattleMovement.Distance(Position, _segmentOrigin); + if (_distance <= 0) + _distance = 1f; + double acceleration = 680d / _distance * Delta * 200d; + _speed = (float)(_speed + (State == 0 ? -acceleration : acceleration)); + double spin = Rotation.X + (State == 0 ? 1d : -1d) * Delta * 3600d; + if (State == 0 ? spin > 360d : spin < 0d) + spin += State == 0 ? -360d : 360d; + Rotation = new BattleMovementPoint((float)spin, Rotation.Y, Rotation.Z); + if (distance < _distance) + return; + _segmentOrigin = Position; + State++; + HitThisPass = State == 1; + } + + public void FinishRestore() + { + WeaponVisible = true; + Active = false; + RestoreRequested = false; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleThrownWeapon.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleThrownWeapon.cs.meta new file mode 100644 index 00000000..98f51359 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleThrownWeapon.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 327ecf195f6249b4ae6a14d8d36c09d5 diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleTrailState.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleTrailState.cs new file mode 100644 index 00000000..d94ef720 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleTrailState.cs @@ -0,0 +1,56 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + // CTrail's ring advances once per Update, independently of render calls or + // enablement. The published trail.gbf uses diffuse alpha and additive blend. + public sealed class BattleTrailState + { + public const int Capacity = 8; + private float _remainder; + + public uint Frame + { + get; private set; + } + + public int CurrentTexture => (int)(Frame % Capacity); + + public void Advance(double scaledSeconds) + { + if (!double.IsFinite(scaledSeconds) || scaledSeconds < 0) + throw new ArgumentOutOfRangeException(nameof(scaledSeconds)); + _remainder += (float)scaledSeconds; + if (_remainder >= .02f) + { + Frame = unchecked(Frame + 1); + _remainder -= .02f; + } + } + + public int TextureAt(int drawOrder) + { + if (drawOrder < 0 || drawOrder >= Capacity) + throw new ArgumentOutOfRangeException(nameof(drawOrder)); + return (CurrentTexture + 1 + drawOrder) % Capacity; + } + + public static byte AlphaAt(int drawOrder) + { + if (drawOrder < 0 || drawOrder >= Capacity) + throw new ArgumentOutOfRangeException(nameof(drawOrder)); + return (byte)(158 - (Capacity - 1 - drawOrder) * 8); + } + + public static float ContributionAt(int drawOrder) + { + int alpha = AlphaAt(drawOrder); + return alpha / 255f * (alpha / 2) / 255f; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleTrailState.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleTrailState.cs.meta new file mode 100644 index 00000000..bcf0d601 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleTrailState.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: dda3d7d70a074a5bb6a4bfa64f549d3e diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleWeaponSpark.cs b/Assets/Scripts/Pal3.Battle/Stage/BattleWeaponSpark.cs new file mode 100644 index 00000000..3d573c5d --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleWeaponSpark.cs @@ -0,0 +1,52 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Battle +{ + using System; + + // PAL3 C3DSpark::CreateOne/Update. Its C-runtime random stream belongs to + // presentation and must never consume combat CUtil random draws. + public sealed class BattleWeaponSpark + { + public BattleMovementPoint Position + { + get; private set; + } + + public BattleMovementPoint Velocity + { + get; private set; + } + + public float Luminosity { get; private set; } = 200; + + public const float Size = 8; + + public bool Alive => Position.Y > -Size && Luminosity > 1 && Luminosity <= 255; + + public byte Alpha => (byte)Math.Clamp((int)Math.Round(Luminosity, MidpointRounding.ToEven), 0, 255); + + public BattleWeaponSpark(BattleMovementPoint position, BattleRandom visualRandom) + { + if (visualRandom == null) + throw new ArgumentNullException(nameof(visualRandom)); + Position = position; + int power = visualRandom.Next() % 10; + int degrees = visualRandom.Next() % 5760 / 16; + double angle = degrees * Math.PI / 180; + Velocity = new BattleMovementPoint(power * (float)Math.Sin(angle), -10, power * (float)Math.Cos(angle)); + } + + public void Advance(float delta) + { + if (!float.IsFinite(delta) || delta < 0) + throw new ArgumentOutOfRangeException(nameof(delta)); + Velocity = new BattleMovementPoint(Velocity.X, Velocity.Y - delta * 20, Velocity.Z); + Position = new BattleMovementPoint(Position.X + delta * Velocity.X, Position.Y + delta * Velocity.Y, Position.Z + delta * Velocity.Z); + Luminosity -= delta * 250; + } + } +} diff --git a/Assets/Scripts/Pal3.Battle/Stage/BattleWeaponSpark.cs.meta b/Assets/Scripts/Pal3.Battle/Stage/BattleWeaponSpark.cs.meta new file mode 100644 index 00000000..b1680285 --- /dev/null +++ b/Assets/Scripts/Pal3.Battle/Stage/BattleWeaponSpark.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 456bc5acb7de4b739bca447a85b08b87 diff --git a/Assets/Scripts/Pal3.Core/Contract/Enums/CombatEnums.cs b/Assets/Scripts/Pal3.Core/Contract/Enums/CombatEnums.cs index 7c65bf5a..48f2e500 100644 --- a/Assets/Scripts/Pal3.Core/Contract/Enums/CombatEnums.cs +++ b/Assets/Scripts/Pal3.Core/Contract/Enums/CombatEnums.cs @@ -30,6 +30,15 @@ namespace Pal3.Core.Contract.Enums WaterFireEarth = 8, // 水火土[任意] } + [System.Serializable] + public enum ComboTargetRangeType + { + PreserveSingleTarget = 0, + OwnAll = 1, + OpponentSingle = 2, + OpponentAll = 3, + } + [System.Serializable] public enum TargetRangeType { @@ -124,7 +133,7 @@ namespace Pal3.Core.Contract.Enums [System.Serializable] public enum SkillType { - StandardMagic = 0, // 标准技能 + Technique = 0, // 特技(原版 type 0;不是仙术) AssistMagic, // 辅助技能 DamageMagic, // 伤害法术 RecoverMagic, // 恢复法术 @@ -147,4 +156,4 @@ namespace Pal3.Core.Contract.Enums RecoverToMax, // 恢复到上限 IncreaseMax, // 增加上限值 } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Core/DataReader/Dat/EffectLinkerFile.cs b/Assets/Scripts/Pal3.Core/DataReader/Dat/EffectLinkerFile.cs index e5039853..18c88b84 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Dat/EffectLinkerFile.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Dat/EffectLinkerFile.cs @@ -18,7 +18,7 @@ namespace Pal3.Core.DataReader.Dat public bool IsReceiverActor; // 接收方是人物 public GameBoxVector3 EffectGameBoxPosition; // 特效位置 public float WaitDurationInSeconds; // 等待时间 - public float EffectDurationInSeconds; // 特效时间 + public float WorkTimeInSeconds; // 从任务启动起的语义作用时刻(原 fWorkTime),不是特效持续时间 } public struct EffectLinker diff --git a/Assets/Scripts/Pal3.Core/DataReader/Dat/EffectLinkerFileReader.cs b/Assets/Scripts/Pal3.Core/DataReader/Dat/EffectLinkerFileReader.cs index d575a1fb..53fcef7e 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Dat/EffectLinkerFileReader.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Dat/EffectLinkerFileReader.cs @@ -50,7 +50,7 @@ namespace Pal3.Core.DataReader.Dat IsReceiverActor = reader.ReadBoolean(), EffectGameBoxPosition = reader.ReadGameBoxVector3(), WaitDurationInSeconds = reader.ReadSingle(), - EffectDurationInSeconds = reader.ReadSingle(), + WorkTimeInSeconds = reader.ReadSingle(), }; } } diff --git a/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFile.cs b/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFile.cs new file mode 100644 index 00000000..af57ec4c --- /dev/null +++ b/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFile.cs @@ -0,0 +1,288 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Core.DataReader.Dat +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Primitives; + + // Original tagCam stores its angles in radians and position in GameBox units. + public readonly struct FlexCameraPose + { + public GameBoxVector3 Position + { + get; + } + + public float Yaw + { + get; + } + + public float Pitch + { + get; + } + + public float Roll + { + get; + } + + public FlexCameraPose(GameBoxVector3 position, float yaw, float pitch, float roll) + { + Position = position; + Yaw = yaw; + Pitch = pitch; + Roll = roll; + } + } + + [Flags] + public enum FlexCameraFlags + { + None = 0, + StartCamera = 1, + EndCamera = 2, + Time = 4, + Speed = 8, + Line = 16, + Circle = 32, + Mechanics = 64, + TimeRevise = 128, + AbsoluteTime = 256, + CounterYaw = 512, + CounterPitch = 1024, + CounterRoll = 2048, + RandomSwing = 4096, + SightTrace = 8192, + PositionTrace = 16384, + } + + // Saved runtime fields are retained for inspection. Playback resets them; + // serialized member-function pointers are data and are never executed. + public sealed class FlexCameraTask + { + public IReadOnlyList SerializedDispatchWords + { + get; + } + + public uint Id + { + get; + } + + public bool SavedValid + { + get; + } + + public bool SavedExecuted + { + get; + } + + public bool SavedFinished + { + get; + } + + public bool Splice + { + get; + } + + public float SavedStartTime + { + get; + } + + public float ExpectedSeconds + { + get; + } + + public FlexCameraPose Start + { + get; + } + + public FlexCameraPose End + { + get; + } + + public int StartCameraIndex + { + get; + } + + public int EndCameraIndex + { + get; + } + + public FlexCameraFlags Flags + { + get; + } + + public int TraceActor + { + get; + } + + public float StartSpeed + { + get; + } + + public float Inertia + { + get; + } + + public float FirstAccelerationStart + { + get; + } + + public float SecondAccelerationStart + { + get; + } + + public float FirstAcceleration + { + get; + } + + public float SecondAcceleration + { + get; + } + + public float CircleAngle + { + get; + } + + public float AngularSpeed + { + get; + } + + public GameBoxVector3 CircleCenter + { + get; + } + + public GameBoxVector3 CircleEnd + { + get; + } + + public float SwingFrequency + { + get; + } + + public float SwingAmplitude + { + get; + } + + public float TimeCompensation + { + get; + } + + public float StartFieldOfView + { + get; + } + + public float EndFieldOfView + { + get; + } + + public GameBoxVector3 SavedTraceStart + { + get; + } + + public IReadOnlyList ExtensionWords + { + get; + } + + internal FlexCameraTask(uint[] dispatchWords, uint id, bool valid, bool executed, bool finished, bool splice, + float startTime, float expected, FlexCameraPose start, FlexCameraPose end, int startCamera, int endCamera, + FlexCameraFlags flags, int traceActor, float[] parameters, GameBoxVector3 center, GameBoxVector3 circleEnd, + float[] tail, GameBoxVector3 traceStart, uint[] extensionWords) + { + SerializedDispatchWords = Array.AsReadOnly(dispatchWords); + Id = id; + SavedValid = valid; + SavedExecuted = executed; + SavedFinished = finished; + Splice = splice; + SavedStartTime = startTime; + ExpectedSeconds = expected; + Start = start; + End = end; + StartCameraIndex = startCamera; + EndCameraIndex = endCamera; + Flags = flags; + TraceActor = traceActor; + StartSpeed = parameters[0]; + Inertia = parameters[1]; + FirstAccelerationStart = parameters[2]; + SecondAccelerationStart = parameters[3]; + FirstAcceleration = parameters[4]; + SecondAcceleration = parameters[5]; + CircleAngle = parameters[6]; + AngularSpeed = parameters[7]; + CircleCenter = center; + CircleEnd = circleEnd; + SwingFrequency = tail[0]; + SwingAmplitude = tail[1]; + TimeCompensation = tail[2]; + StartFieldOfView = tail[3]; + EndFieldOfView = tail[4]; + SavedTraceStart = traceStart; + ExtensionWords = Array.AsReadOnly(extensionWords); + } + } + + public sealed class FlexCameraFile + { + public IReadOnlyList Pool + { + get; + } + + public IReadOnlyList InUse + { + get; + } + + public IReadOnlyList> Lists + { + get; + } + + internal FlexCameraFile(FlexCameraTask[] pool, bool[] inUse, int[][] lists) + { + Pool = Array.AsReadOnly(pool); + InUse = Array.AsReadOnly(inUse); + Lists = Array.AsReadOnly(lists.Select(list => (IReadOnlyList)Array.AsReadOnly(list)).ToArray()); + } + } +} diff --git a/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFile.cs.meta b/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFile.cs.meta new file mode 100644 index 00000000..ce88a989 --- /dev/null +++ b/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFile.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a376c019f6eb460cab3f08818e75275d diff --git a/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFileReader.cs b/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFileReader.cs new file mode 100644 index 00000000..da283439 --- /dev/null +++ b/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFileReader.cs @@ -0,0 +1,71 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Core.DataReader.Dat +{ + using System.IO; + + public sealed class FlexCameraFileReader : IFileReader + { + public const int RecordBytes = 204; + public const int PoolCount = 2000; + public const int ListCount = 100; + public const int ListCapacity = 50; + public const int FileBytes = RecordBytes * PoolCount + PoolCount + ListCount * ListCapacity * sizeof(int); + + public FlexCameraFile Read(IBinaryReader reader, int codepage) + { + if (reader.Length - reader.Position != FileBytes) + throw new InvalidDataException("Original flexcam.dat must contain the complete 430000-byte pool, use flags and index lists."); + var pool = new FlexCameraTask[PoolCount]; + for (int index = 0; index < pool.Length; index++) + pool[index] = ReadTask(reader); + var inUse = new bool[PoolCount]; + for (int index = 0; index < inUse.Length; index++) + inUse[index] = reader.ReadBoolean(); + var lists = new int[ListCount][]; + for (int list = 0; list < lists.Length; list++) + { + lists[list] = reader.ReadInt32s(ListCapacity); + foreach (int index in lists[list]) + if (index < -1 || index >= PoolCount) + throw new InvalidDataException("A flexcam list references an invalid pool entry."); + } + return new FlexCameraFile(pool, inUse, lists); + } + + private static FlexCameraPose ReadPose(IBinaryReader reader) => + new(reader.ReadGameBoxVector3(), reader.ReadSingle(), reader.ReadSingle(), reader.ReadSingle()); + + private static FlexCameraTask ReadTask(IBinaryReader reader) + { + long startOffset = reader.Position; + // The saved MSVC member-function-pointer representation occupies + // sixteen bytes in both published files, not a single x86 pointer. + uint[] dispatch = reader.ReadUInt32s(4); + uint id = reader.ReadUInt32(); + bool valid = reader.ReadBoolean(), executed = reader.ReadBoolean(), finished = reader.ReadBoolean(), splice = reader.ReadBoolean(); + float start = reader.ReadSingle(), expected = reader.ReadSingle(); + FlexCameraPose from = ReadPose(reader), to = ReadPose(reader); + int startCamera = reader.ReadInt32(), endCamera = reader.ReadInt32(); + FlexCameraFlags flags = FlexCameraFlags.None; + for (int bit = 0; bit < 15; bit++) + if (reader.ReadBoolean()) + flags |= (FlexCameraFlags)(1 << bit); + _ = reader.ReadByte(); // tagCCT alignment before nTraceRole. + int trace = reader.ReadInt32(); + float[] parameters = reader.ReadSingles(8); + var center = reader.ReadGameBoxVector3(); + var circleEnd = reader.ReadGameBoxVector3(); + float[] tail = reader.ReadSingles(5); + var traceStart = reader.ReadGameBoxVector3(); + uint[] extension = reader.ReadUInt32s(2); + if (reader.Position - startOffset != RecordBytes) + throw new InvalidDataException("The flexcam record layout does not match tagCCT."); + return new FlexCameraTask(dispatch, id, valid, executed, finished, splice, start, expected, from, to, + startCamera, endCamera, flags, trace, parameters, center, circleEnd, tail, traceStart, extension); + } + } +} diff --git a/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFileReader.cs.meta b/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFileReader.cs.meta new file mode 100644 index 00000000..8f5e9e0f --- /dev/null +++ b/Assets/Scripts/Pal3.Core/DataReader/Dat/FlexCameraFileReader.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 442f431828b84c90aae3eb77bd826f14 diff --git a/Assets/Scripts/Pal3.Core/DataReader/Data/EffectDefinitionFileReader.cs b/Assets/Scripts/Pal3.Core/DataReader/Data/EffectDefinitionFileReader.cs index a955264d..3fd2a058 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Data/EffectDefinitionFileReader.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Data/EffectDefinitionFileReader.cs @@ -1,4 +1,4 @@ -// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ // Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved. // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ @@ -133,7 +133,8 @@ namespace Pal3.Core.DataReader.Data task.ModifyLast = reader.ReadBoolean(); reader.ReadByte(); // native 4-byte alignment task.YStretchSpeed = reader.ReadSingle(); - reader.Seek(28, System.IO.SeekOrigin.Current); // reserved, not active parameters + for (int index = 0; index < task.ReservedWords.Length; index++) + task.ReservedWords[index] = reader.ReadUInt32(); // PAL3A action prefix CRC and actor ID use words 0 and 1. if (task.IsValid && (!Finite(task.StartTime) || !Finite(task.Duration) || task.Duration < 0)) throw new System.IO.InvalidDataException("Invalid effect task timing"); return task; diff --git a/Assets/Scripts/Pal3.Core/DataReader/Data/EffectGroup.cs b/Assets/Scripts/Pal3.Core/DataReader/Data/EffectGroup.cs index 56b69739..4e1750ec 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Data/EffectGroup.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Data/EffectGroup.cs @@ -23,6 +23,7 @@ namespace Pal3.Core.DataReader.Data public float CreateTimeSlot; public bool IsValid, CreateNew, ModifyLast; public float YStretchSpeed; + public uint[] ReservedWords = new uint[7]; public GameBoxVector3 Speed => new(SpeedX, SpeedY, SpeedZ); public GameBoxVector3 CircleAxis => new(CircleAxisX, CircleAxisY, CircleAxisZ); diff --git a/Assets/Scripts/Pal3.Core/DataReader/Gdb/GdbFile.cs b/Assets/Scripts/Pal3.Core/DataReader/Gdb/GdbFile.cs index 2ea44962..921118ed 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Gdb/GdbFile.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Gdb/GdbFile.cs @@ -1,4 +1,4 @@ -// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ // Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved. // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ @@ -14,24 +14,24 @@ namespace Pal3.Core.DataReader.Gdb public short Value; // 属性影响值 } - public struct CombatStateImpact + public struct ItemCombatStateValue { - public CombatStateImpactType Type; // 战斗状态影响类型 - public short Value; // 战斗状态影响值 + public byte Flags; // 原 fstype:武器附加状态使能标记,不能当作药物增加/解除操作 + public short Value; // 战斗状态影响值 } public struct GameItemInfo { - public uint Id; // 物品ID + public uint Id; // 物品ID - public string Name; // 物品名称 - public string ModelName; // 物品模型名称 - public string IconName; // 物品图标名称 - public string Description; // 物品描述 - public int Price; // 物品价格 + public string Name; // 物品名称 + public string ModelName; // 物品模型名称 + public string ImageId; // 原 ImageID:图标和武器模型贴图共用的图像后缀 + public string Description; // 物品描述 + public int Price; // 物品价格 - public ItemType Type; // 物品类型 - public WeaponType WeaponType; // 武器类型(只有物品为武器的时候有意义) + public ItemType Type; // 物品类型 + public WeaponType WeaponType; // 武器类型(只有物品为武器的时候有意义) // 主角可使用信息 public HashSet ApplicableActors; @@ -39,51 +39,52 @@ namespace Pal3.Core.DataReader.Gdb // 五灵属性 public HashSet ElementAttributes; - public int AncientValue; // 古董价值 + public int AncientValue; // 古董价值 - public ItemSpecialType ItemSpecialType; // 特殊类型 - public TargetRangeType TargetRangeType; // 目标范围类型 - public PlaceOfUseType PlaceOfUseType; // 使用地点类型 + public ItemSpecialType ItemSpecialType; // 特殊类型 + public TargetRangeType TargetRangeType; // 目标范围类型 + public PlaceOfUseType PlaceOfUseType; // 使用地点类型 // 角色属性影响类型和影响值 public Dictionary AttributeImpacts; // 战斗状态影响类型和值 - public Dictionary CombatStateImpacts; + public Dictionary CombatStates; - #if PAL3 - public int ComboCount; // 连击次数 + // 原 lian,PAL3 offset 0x2fc,PAL3A 0x300;有符号比较,0/1按单次处理。 + public int AttackHitCount; - // 装备属性 - public short SpSavingPercentage; // 气消耗减少百分比 - public short MpSavingPercentage; // 神消耗减少百分比 - public short CriticalAttackAmplifyPercentage; // 暴击伤害增加百分比 - public short SpecialSkillSuccessRate; // 特技成功率增加百分比 +#if PAL3 - // 尸块属性 - public uint OreId; // 矿石ID - public uint ProductId; // 炼制出的物品ID - public int ProductPrice; // 炼制出的物品价格 + // 装备属性 + public short SpSavingPercentage; // 气消耗减少百分比 + public short MpSavingPercentage; // 神消耗减少百分比 + public short CriticalAttackAmplifyPercentage; // 暴击伤害增加百分比 + public short SpecialSkillSuccessRate; // 特技成功率增加百分比 - // 合成属性 - public uint[] SynthesisMaterialIds; // 两种合成材料的ID - public uint SynthesisProductId; // 合成出的物品ID - #elif PAL3A - public int Unknown1; - public uint Unknown2; + // 尸块属性 + public uint OreId; // 矿石ID + public uint ProductId; // 炼制出的物品ID + public int ProductPrice; // 炼制出的物品价格 - public short SpSavingPercentage; // 气消耗减少百分比 - public short MpSavingPercentage; // 神消耗减少百分比 - public short CriticalAttackAmplifyPercentage; // 暴击伤害增加百分比 - public short SpecialSkillSuccessRate; // 特技成功率增加百分比 + // 合成属性 + public uint[] SynthesisMaterialIds; // 两种合成材料的ID + public uint SynthesisProductId; // 合成出的物品ID +#elif PAL3A + public int UnresolvedValue2FC; // 有符号原值,尚未确认完整语义;不是连击除数。 - public PlayerActorId CreatorActorId; // 制作角色ID - public uint MaterialId; // 制作所需材料的ID + public short SpSavingPercentage; // 气消耗减少百分比 + public short MpSavingPercentage; // 神消耗减少百分比 + public short CriticalAttackAmplifyPercentage; // 暴击伤害增加百分比 + public short SpecialSkillSuccessRate; // 特技成功率增加百分比 - public int ProductType; // 制作出的物品类型(0美食方,梦溪杂录,1装备图谱,花种,2武器图谱) - public uint ProductId; // 制作出的物品ID - public uint RequiredFavorValue; // 制作所需的最低好感度 - #endif + public PlayerActorId CreatorActorId; // 制作角色ID + public uint MaterialId; // 制作所需材料的ID + + public int ProductType; // 制作出的物品类型(0美食方,梦溪杂录,1装备图谱,花种,2武器图谱) + public uint ProductId; // 制作出的物品ID + public uint RequiredFavorValue; // 制作所需的最低好感度 +#endif } [System.Serializable] @@ -98,18 +99,27 @@ namespace Pal3.Core.DataReader.Gdb // 角色基础五灵属性值(由 GDB 文件读取) [field: System.NonSerialized] - public Dictionary ElementAttributeValues { get; set; } + public Dictionary ElementAttributeValues + { + get; set; + } public string Name; // 战斗角色名称 public int Level; // 战斗角色等级 // 角色基础属性值 [field: System.NonSerialized] - public Dictionary AttributeValues { get; set; } + public Dictionary AttributeValues + { + get; set; + } // 战斗状态影响类型 [field: System.NonSerialized] - public Dictionary CombatStateImpactTypes { get; set; } + public Dictionary CombatStateImpactTypes + { + get; set; + } public int MaxRound; // 指定最大回合数 (保存或者初始化的时候用,数据库文件里均为-1,主角为0) public int SpecialActionId; // 特殊动作ID @@ -163,7 +173,7 @@ namespace Pal3.Core.DataReader.Gdb public byte SuccessRateLevel; // 施法成功率 0~10对应不约定的计算方式 其他为百分比 // 战斗状态影响类型 - public Dictionary CombatStateImpactTypes; + public Dictionary CombatStateImpactTypes; // 消耗属性类型 public AttributeImpactType SpConsumeImpactType; @@ -178,10 +188,10 @@ namespace Pal3.Core.DataReader.Gdb public int SpecialConsumeValue; // 特殊消耗数值 public byte Level; // 技能等级 - public byte[] TimesBeforeLevelUp; // 升级前需使用次数 - public byte RequiredActorLevel; // 使用所需角色等级 - public byte MagicLevel; // 本级法术等级 - public uint NextLevelSkillId; // 下一级法术ID + public byte[] CumulativeUseThresholds; // 累计使用次数阈值(不在升级时扣除) + public byte LearningActorLevel; // 特技学习/当前仙术解锁next所需角色等级(不是通用施法门槛) + public byte NextSkillRequiredProficiency; // 解锁next所需的当前仙术显示熟练等级 + public uint NextSkillId; // 下一级法术ID public byte IsUsableOutsideCombat; // 是否可以在战斗外使用 public uint[] CompositeSkillIds; // 可以合成的法术ID @@ -203,35 +213,62 @@ namespace Pal3.Core.DataReader.Gdb public uint SkillId; // 发动技能ID public WeaponType[] WeaponTypeRequirements; // 对应每个参战者的武器类型 - public ActorCombatStateType[] CombatStateRequirements; // 对应每个参战者的战斗状态要求 + public int[] AuxiliaryStateConditions; // 三名辅助者的原始FS索引:-1忽略,0..25状态,26任一毒 public string Description; // 合击技描述 - public TargetRangeType TargetRangeType; // 使用范围类型 + public ComboTargetRangeType TargetRangeType; // 使用范围类型 // 角色属性影响类型和影响值 public Dictionary AttributeImpacts; - #if PAL3A - public int Unknown; // 三外新增数据 暂时未知 - #endif +#if PAL3A + public int PowerMultiplierPercentage; // 外传合击倍率输入;发布版先除100并取整,再乘普通攻击总和 +#endif } // Pal3 Game Database file public sealed class GdbFile { - public IDictionary CombatActorInfos { get; } - public IDictionary SkillInfos { get; } - public IDictionary GameItemInfos { get; } - public IDictionary ComboSkillInfos { get; } + public IDictionary CombatActorInfos + { + get; + } + + public IDictionary SkillInfos + { + get; + } + + public IDictionary GameItemInfos + { + get; + } + + public IDictionary ComboSkillInfos + { + get; + } + + public IReadOnlyList ComboSkillOrder + { + get; + } + + public IReadOnlyList SkillOrder + { + get; + } public GdbFile(IDictionary combatActorInfos, IDictionary skillInfos, IDictionary gameItemInfos, - IDictionary comboSkillInfos) + IDictionary comboSkillInfos, IEnumerable comboSkillOrder = null, IEnumerable skillOrder = null) { CombatActorInfos = combatActorInfos; SkillInfos = skillInfos; + SkillOrder = new List(skillOrder ?? skillInfos.Keys).AsReadOnly(); GameItemInfos = gameItemInfos; ComboSkillInfos = comboSkillInfos; + ComboSkillOrder = new List(comboSkillOrder ?? comboSkillInfos.Keys).AsReadOnly(); } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Core/DataReader/Gdb/GdbFileReader.cs b/Assets/Scripts/Pal3.Core/DataReader/Gdb/GdbFileReader.cs index 763d65bc..7a41f13d 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Gdb/GdbFileReader.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Gdb/GdbFileReader.cs @@ -1,4 +1,4 @@ -// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ // Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved. // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ @@ -34,15 +34,17 @@ namespace Pal3.Core.DataReader.Gdb for (int i = 0; i < numOfActors; i++) { CombatActorInfo actor = ReadCombatActorInfo(reader, codepage); - combatActorInfos[(int) actor.Id] = actor; + combatActorInfos[(int)actor.Id] = actor; } reader.Seek(skillDataOffset, SeekOrigin.Begin); Dictionary skillInfos = new(); + List skillOrder = new(); for (int i = 0; i < numOfSkills; i++) { SkillInfo skill = ReadSkillInfo(reader, codepage); - skillInfos[(int) skill.Id] = skill; + skillInfos[(int)skill.Id] = skill; + skillOrder.Add((int)skill.Id); } reader.Seek(itemDataOffset, SeekOrigin.Begin); @@ -50,27 +52,29 @@ namespace Pal3.Core.DataReader.Gdb for (int i = 0; i < numOfItems; i++) { GameItemInfo item = ReadGameItemInfo(reader, codepage); - gameItems[(int) item.Id] = item; + gameItems[(int)item.Id] = item; } reader.Seek(comboSkillDataOffset, SeekOrigin.Begin); Dictionary comboSkillInfos = new(); + List comboSkillOrder = new(); for (int i = 0; i < numOfComboSkills; i++) { ComboSkillInfo comboSkill = ReadComboSkillInfo(reader, codepage); - comboSkillInfos[(int) comboSkill.Id] = comboSkill; + comboSkillInfos[(int)comboSkill.Id] = comboSkill; + comboSkillOrder.Add((int)comboSkill.Id); } return new GdbFile(combatActorInfos, skillInfos, gameItems, - comboSkillInfos); + comboSkillInfos, comboSkillOrder, skillOrder); } private static CombatActorInfo ReadCombatActorInfo(IBinaryReader reader, int codepage) { uint id = reader.ReadUInt32(); - CombatActorType type = (CombatActorType) reader.ReadUInt16(); + CombatActorType type = (CombatActorType)reader.ReadUInt16(); string description = reader.ReadString(512, codepage); string modelId = reader.ReadString(30, codepage); string iconId = reader.ReadString(32, codepage); @@ -95,7 +99,8 @@ namespace Pal3.Core.DataReader.Gdb byte chaseSpeed = reader.ReadByte(); _ = reader.ReadBytes(3); // padding uint[] skillIds = reader.ReadUInt32s(4); - byte[] skillLevels = reader.ReadBytes(4); + byte[] skillLevels = reader.ReadBytes(3); + _ = reader.ReadByte(); // padding; the fourth monster skill always has proficiency 4 int spImpactValue = reader.ReadInt32(); float[] properties = reader.ReadSingles(10); uint normalLoot = reader.ReadUInt32(); @@ -120,7 +125,7 @@ namespace Pal3.Core.DataReader.Gdb Name = name, Level = level, AttributeValues = GetActorAttributeValues(attributeValues), - CombatStateImpactTypes = GetCombatStateImpactTypes(combatStateImpactTypes), + CombatStateImpactTypes = GetCombatStateImpactTypes(combatStateImpactTypes.Select(value => (int)value).ToArray()), MaxRound = maxRound, SpecialActionId = specialActionId, EscapeRate = escapeRate, @@ -166,7 +171,7 @@ namespace Pal3.Core.DataReader.Gdb short[] attributeImpactValue = reader.ReadInt16s(12); byte successRateLevel = reader.ReadByte(); _ = reader.ReadByte(); // padding - byte[] combatStateImpactTypes = reader.ReadInt16s(31).Select(_ => (byte)_).ToArray(); + short[] combatStateImpactTypes = reader.ReadInt16s(31); AttributeImpactType spConsumeImpactType = (AttributeImpactType)reader.ReadInt32(); AttributeImpactType mpConsumeImpactType = (AttributeImpactType)reader.ReadInt32(); @@ -208,7 +213,7 @@ namespace Pal3.Core.DataReader.Gdb SpecialSkillId = specialSkillId, AttributeImpacts = GetActorAttributeImpacts(attributeImpactType, attributeImpactValue), SuccessRateLevel = successRateLevel, - CombatStateImpactTypes = GetCombatStateImpactTypes(combatStateImpactTypes), + CombatStateImpactTypes = GetCombatStateImpactTypes(combatStateImpactTypes.Select(value => (int)value).ToArray()), SpConsumeImpactType = spConsumeImpactType, MpConsumeImpactType = mpConsumeImpactType, SpConsumeValue = spConsumeValue, @@ -217,10 +222,10 @@ namespace Pal3.Core.DataReader.Gdb SpecialConsumeImpactType = specialConsumeImpactType, SpecialConsumeValue = specialConsumeValue, Level = level, - TimesBeforeLevelUp = timesBeforeLevelUp, - RequiredActorLevel = requiredActorLevel, - MagicLevel = magicLevel, - NextLevelSkillId = nextLevelSkillId, + CumulativeUseThresholds = timesBeforeLevelUp, + LearningActorLevel = requiredActorLevel, + NextSkillRequiredProficiency = magicLevel, + NextSkillId = nextLevelSkillId, IsUsableOutsideCombat = isUsableOutsideCombat, CompositeSkillIds = compositeSkillIds, CompositeRequiredSkillIds = compositeRequiredSkillIds, @@ -236,17 +241,17 @@ namespace Pal3.Core.DataReader.Gdb uint id = reader.ReadUInt32(); string name = reader.ReadString(32, codepage); string modelName = reader.ReadString(30, codepage); - string iconName = reader.ReadString(30, codepage); + string imageId = reader.ReadString(30, codepage); string description = reader.ReadString(512, codepage); int price = reader.ReadInt32(); - ItemType type = (ItemType) reader.ReadByte(); - WeaponType weaponType = (WeaponType) reader.ReadByte(); + ItemType type = (ItemType)reader.ReadByte(); + WeaponType weaponType = (WeaponType)reader.ReadByte(); byte[] mainActorCanUse = reader.ReadBytes(5); byte[] elementAttributes = reader.ReadBytes(5); int ancientValue = reader.ReadInt32(); - ItemSpecialType itemSpecialType = (ItemSpecialType) reader.ReadByte(); - TargetRangeType targetRangeType = (TargetRangeType) reader.ReadByte(); - PlaceOfUseType placeOfUseType = (PlaceOfUseType) reader.ReadByte(); + ItemSpecialType itemSpecialType = (ItemSpecialType)reader.ReadByte(); + TargetRangeType targetRangeType = (TargetRangeType)reader.ReadByte(); + PlaceOfUseType placeOfUseType = (PlaceOfUseType)reader.ReadByte(); byte[] attributeImpactType = reader.ReadBytes(12); _ = reader.ReadByte(); // padding short[] attributeImpactValue = reader.ReadInt16s(12); @@ -255,8 +260,8 @@ namespace Pal3.Core.DataReader.Gdb short[] combatStateImpactValue = reader.ReadInt16s(31); _ = reader.ReadBytes(2); // padding - #if PAL3 - int comboCount = reader.ReadInt32(); +#if PAL3 + int attackHitCount = reader.ReadInt32(); short spSavingPercentage = reader.ReadInt16(); short mpSavingPercentage = reader.ReadInt16(); short criticalAttackAmplifyPercentage = reader.ReadInt16(); @@ -266,9 +271,9 @@ namespace Pal3.Core.DataReader.Gdb int productPrice = reader.ReadInt32(); uint[] synthesisMaterialIds = reader.ReadUInt32s(2); uint synthesisProductId = reader.ReadUInt32(); - #elif PAL3A - int unknown1 = reader.ReadInt32(); - uint unknown2 = reader.ReadUInt32(); +#elif PAL3A + int unresolvedValue2FC = reader.ReadInt32(); + int attackHitCount = reader.ReadInt32(); short spSavingPercentage = reader.ReadInt16(); short mpSavingPercentage = reader.ReadInt16(); @@ -280,14 +285,14 @@ namespace Pal3.Core.DataReader.Gdb int productType = reader.ReadInt32(); uint productId = reader.ReadUInt32(); uint requiredFavorValue = reader.ReadUInt32(); - #endif +#endif return new GameItemInfo() { Id = id, Name = name, ModelName = modelName, - IconName = iconName, + ImageId = imageId, Description = description, Price = price, Type = type, @@ -298,12 +303,11 @@ namespace Pal3.Core.DataReader.Gdb ItemSpecialType = itemSpecialType, TargetRangeType = targetRangeType, PlaceOfUseType = placeOfUseType, - AttributeImpacts = GetActorAttributeImpacts(attributeImpactType, attributeImpactValue), - CombatStateImpacts = GetCombatStateImpacts( - GetCombatStateImpactTypes(combatStateImpactTypes), combatStateImpactValue), + AttributeImpacts = GetActorAttributeImpacts(attributeImpactType, attributeImpactValue, includeZero: true), + CombatStates = GetItemCombatStates(combatStateImpactTypes, combatStateImpactValue), + AttackHitCount = attackHitCount, - #if PAL3 - ComboCount = comboCount, +#if PAL3 SpSavingPercentage = spSavingPercentage, MpSavingPercentage = mpSavingPercentage, CriticalAttackAmplifyPercentage = criticalAttackAmplifyPercentage, @@ -313,9 +317,8 @@ namespace Pal3.Core.DataReader.Gdb ProductPrice = productPrice, SynthesisMaterialIds = synthesisMaterialIds, SynthesisProductId = synthesisProductId, - #elif PAL3A - Unknown1 = unknown1, - Unknown2 = unknown2, +#elif PAL3A + UnresolvedValue2FC = unresolvedValue2FC, SpSavingPercentage = spSavingPercentage, MpSavingPercentage = mpSavingPercentage, CriticalAttackAmplifyPercentage = criticalAttackAmplifyPercentage, @@ -325,7 +328,7 @@ namespace Pal3.Core.DataReader.Gdb ProductType = productType, ProductId = productId, RequiredFavorValue = requiredFavorValue, - #endif +#endif }; } @@ -339,18 +342,18 @@ namespace Pal3.Core.DataReader.Gdb uint skillId = reader.ReadUInt32(); WeaponType[] weaponTypeRequirements = reader.ReadBytes(4).Select(_ => (WeaponType)_).ToArray(); _ = reader.ReadBytes(4); // not used - ActorCombatStateType[] combatStateRequirements = reader.ReadInt32s(3) - .Select(_ => (ActorCombatStateType)_).ToArray(); + int[] auxiliaryStateConditions = reader.ReadInt32s(3); string description = reader.ReadString(512, codepage); - TargetRangeType targetRangeType = (TargetRangeType)reader.ReadByte(); + ComboTargetRangeType targetRangeType = (ComboTargetRangeType)reader.ReadByte(); byte[] attributeImpactType = reader.ReadBytes(12); - _ = reader.ReadBytes(3); // padding + _ = reader.ReadByte(); // align the signed short array at +0x25e short[] attributeImpactValue = reader.ReadInt16s(12); + _ = reader.ReadBytes(2); // align the record tail at +0x278 - #if PAL3A - int unknown = reader.ReadInt32(); - #endif +#if PAL3A + int powerMultiplierPercentage = reader.ReadInt32(); +#endif return new ComboSkillInfo() { @@ -360,23 +363,24 @@ namespace Pal3.Core.DataReader.Gdb ElementPositionRequirements = elementPositionRequirements, SkillId = skillId, WeaponTypeRequirements = weaponTypeRequirements, - CombatStateRequirements = combatStateRequirements, + AuxiliaryStateConditions = auxiliaryStateConditions, Description = description, TargetRangeType = targetRangeType, - AttributeImpacts = GetActorAttributeImpacts(attributeImpactType, attributeImpactValue), - #if PAL3A - Unknown = unknown, - #endif + AttributeImpacts = GetActorAttributeImpacts(attributeImpactType, attributeImpactValue, includeZero: true), +#if PAL3A + PowerMultiplierPercentage = powerMultiplierPercentage, +#endif }; } private static Dictionary GetElementAttributeValues(int[] elementAttributeValues) { - Dictionary elementAttributeValueMap = new (); + Dictionary elementAttributeValueMap = new(); foreach (ElementType elementType in Enum.GetValues(typeof(ElementType))) { - if (elementType == ElementType.None) continue; + if (elementType == ElementType.None) + continue; elementAttributeValueMap[elementType] = elementAttributeValues[(int)elementType - 1]; } @@ -385,7 +389,7 @@ namespace Pal3.Core.DataReader.Gdb private static Dictionary GetActorAttributeValues(int[] attributeValues) { - Dictionary attributeValueMap = new (); + Dictionary attributeValueMap = new(); foreach (ActorAttributeType attributeType in Enum.GetValues(typeof(ActorAttributeType))) { @@ -397,7 +401,7 @@ namespace Pal3.Core.DataReader.Gdb private static HashSet GetPlayerActorIds(byte[] mainActorCanUse) { - HashSet playerActorIds = new (); + HashSet playerActorIds = new(); for (int i = 0; i < 5; i++) { @@ -412,7 +416,7 @@ namespace Pal3.Core.DataReader.Gdb private static HashSet GetElementAttributes(byte[] elementAttributes) { - HashSet elementAttributeSet = new (); + HashSet elementAttributeSet = new(); for (int i = 0; i < 5; i++) { @@ -426,13 +430,13 @@ namespace Pal3.Core.DataReader.Gdb } private static Dictionary GetCombatStateImpactTypes( - byte[] combatStateImpactTypes) + int[] combatStateImpactTypes) { - Dictionary combatStateImpacts = new (); + Dictionary combatStateImpacts = new(); foreach (ActorCombatStateType combatState in Enum.GetValues(typeof(ActorCombatStateType))) { - CombatStateImpactType impactType = (CombatStateImpactType)combatStateImpactTypes[(int) combatState]; + CombatStateImpactType impactType = (CombatStateImpactType)combatStateImpactTypes[(int)combatState]; if (impactType != CombatStateImpactType.None) { combatStateImpacts[combatState] = impactType; @@ -442,20 +446,20 @@ namespace Pal3.Core.DataReader.Gdb return combatStateImpacts; } - private static Dictionary GetCombatStateImpacts( - Dictionary combatStateImpactTypes, + private static Dictionary GetItemCombatStates( + byte[] combatStateFlags, short[] combatStateImpactValues) { - Dictionary combatStateImpacts = new (); + Dictionary combatStateImpacts = new(); foreach (ActorCombatStateType combatState in Enum.GetValues(typeof(ActorCombatStateType))) { - short impactValue = combatStateImpactValues[(int) combatState]; - if (impactValue != 0) + short impactValue = combatStateImpactValues[(int)combatState]; + if (impactValue != 0 || combatStateFlags[(int)combatState] != 0) { - combatStateImpacts[combatState] = new CombatStateImpact + combatStateImpacts[combatState] = new ItemCombatStateValue { - Type = combatStateImpactTypes.GetValueOrDefault(combatState, CombatStateImpactType.None), + Flags = combatStateFlags[(int)combatState], Value = impactValue }; } @@ -465,14 +469,14 @@ namespace Pal3.Core.DataReader.Gdb } private static Dictionary GetActorAttributeImpacts( - byte[] attributeImpactType, short[] attributeImpactValue) + byte[] attributeImpactType, short[] attributeImpactValue, bool includeZero = false) { - Dictionary attributeImpacts = new (); + Dictionary attributeImpacts = new(); foreach (ActorAttributeType attributeType in Enum.GetValues(typeof(ActorAttributeType))) { - short impactValue = attributeImpactValue[(int) attributeType]; - if (impactValue != 0) + short impactValue = attributeImpactValue[(int)attributeType]; + if (includeZero || impactValue != 0) { attributeImpacts[attributeType] = new AttributeImpact() { @@ -485,4 +489,4 @@ namespace Pal3.Core.DataReader.Gdb return attributeImpacts; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatCameraConfigFileReader.cs b/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatCameraConfigFileReader.cs index 69fe4657..70503664 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatCameraConfigFileReader.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatCameraConfigFileReader.cs @@ -7,6 +7,7 @@ namespace Pal3.Core.DataReader.Ini { using System; using System.Collections.Generic; + using System.Globalization; using System.IO; using System.Text; using IniParser; @@ -37,17 +38,26 @@ namespace Pal3.Core.DataReader.Ini { defaultCamConfigs.Add(new CombatCameraConfig() { - GameBoxPositionX = float.Parse(iniData[section.SectionName]["x"]), - GameBoxPositionY = float.Parse(iniData[section.SectionName]["y"]), - GameBoxPositionZ = float.Parse(iniData[section.SectionName]["z"]), - Yaw = float.Parse(iniData[section.SectionName]["yaw"]), - Pitch = float.Parse(iniData[section.SectionName]["pitch"]), - Roll = float.Parse(iniData[section.SectionName]["roll"]), + GameBoxPositionX = ParseFloat(section, "x"), + GameBoxPositionY = ParseFloat(section, "y"), + GameBoxPositionZ = ParseFloat(section, "z"), + Yaw = ParseFloat(section, "yaw"), + Pitch = ParseFloat(section, "pitch"), + Roll = ParseFloat(section, "roll"), }); } } return new CombatCameraConfigFile(defaultCamConfigs.ToArray()); } + + private static float ParseFloat(SectionData section, string key) + { + string value = section.Keys[key] ?? throw new FormatException($"[{section.SectionName}] is missing {key}."); + int comment = value.IndexOf(';'); + if (comment >= 0) + value = value[..comment]; + return float.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture); + } } } \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatConfigFile.cs b/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatConfigFile.cs index 278ec0e4..2de3b043 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatConfigFile.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatConfigFile.cs @@ -11,6 +11,7 @@ namespace Pal3.Core.DataReader.Ini { public GameBoxVector3 CenterGameBoxPosition; public float GameBoxRadius; + public float RollRadians; } public sealed class CombatConfigFile @@ -34,4 +35,4 @@ namespace Pal3.Core.DataReader.Ini LevelExperienceTable = levelExperienceTable; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatConfigFileReader.cs b/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatConfigFileReader.cs index d99d0043..41e2a8d4 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatConfigFileReader.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Ini/CombatConfigFileReader.cs @@ -6,6 +6,7 @@ namespace Pal3.Core.DataReader.Ini { using System; + using System.Globalization; using System.IO; using System.Text; using IniParser; @@ -31,25 +32,31 @@ namespace Pal3.Core.DataReader.Ini IniData iniData = parser.ReadData(reader); - GameBoxVector3[] actorGameBoxPositions = new GameBoxVector3[10]; + GameBoxVector3[] actorGameBoxPositions = new GameBoxVector3[11]; FiveElementsFormationConfig allyFormationConfig = default; FiveElementsFormationConfig enemyFormationConfig = default; int[] levelExperienceTable = new int[100]; + bool hasEnemyCenterRole = false; foreach (SectionData section in iniData.Sections) { if (section.SectionName.Equals(ROLE_POSITION_SECTION_HEADER_PREFIX, StringComparison.OrdinalIgnoreCase)) { - for (int i = 0; i < 10; i++) + for (int i = 0; i < actorGameBoxPositions.Length; i++) { string x = iniData[section.SectionName][$"Role{i}-x"]; string z = iniData[section.SectionName][$"Role{i}-z"]; - if (x.Contains(";")) x = x[..x.IndexOf(';')].Trim(); - if (z.Contains(";")) z = z[..z.IndexOf(';')].Trim(); - - actorGameBoxPositions[i] = new GameBoxVector3(float.Parse(x), 0f, float.Parse(z)); + if (i == 10) + { + // Older user-provided layouts may only supply roles 0–9. + hasEnemyCenterRole = x != null || z != null; + if (!hasEnemyCenterRole) + continue; + } + actorGameBoxPositions[i] = new GameBoxVector3(ParseFloat(x, section, $"Role{i}-x"), 0f, + ParseFloat(z, section, $"Role{i}-z")); } } @@ -59,13 +66,13 @@ namespace Pal3.Core.DataReader.Ini string y = iniData[section.SectionName]["y"]; string z = iniData[section.SectionName]["z"]; string radius = iniData[section.SectionName]["radius"]; - - if (radius.Contains(";")) radius = radius[..radius.IndexOf(';')].Trim(); + string roll = iniData[section.SectionName]["roll"]; FiveElementsFormationConfig config = new() { - CenterGameBoxPosition = new GameBoxVector3(float.Parse(x), float.Parse(y), float.Parse(z)), - GameBoxRadius = float.Parse(radius), + CenterGameBoxPosition = new GameBoxVector3(ParseFloat(x, section, "x"), ParseFloat(y, section, "y"), ParseFloat(z, section, "z")), + GameBoxRadius = ParseFloat(radius, section, "radius"), + RollRadians = roll == null ? 0f : ParseFloat(roll, section, "roll"), }; if (section.SectionName.StartsWith("Enemy")) @@ -82,16 +89,33 @@ namespace Pal3.Core.DataReader.Ini { for (int i = 1; i <= 99; i++) { - string exp = iniData[section.SectionName][i.ToString()]; - levelExperienceTable[i] = int.Parse(exp); + string exp = iniData[section.SectionName][i.ToString(CultureInfo.InvariantCulture)]; + if (exp == null) + throw new FormatException($"[{section.SectionName}] is missing level {i}."); + levelExperienceTable[i] = int.Parse(exp, CultureInfo.InvariantCulture); } } } + if (!hasEnemyCenterRole) + { + GameBoxVector3 center = enemyFormationConfig.CenterGameBoxPosition; + actorGameBoxPositions[10] = new GameBoxVector3(center.X, 0f, center.Z); + } return new CombatConfigFile(actorGameBoxPositions, allyFormationConfig, enemyFormationConfig, levelExperienceTable); } + + private static float ParseFloat(string value, SectionData section, string key) + { + if (value == null) + throw new FormatException($"[{section.SectionName}] is missing {key}."); + int comment = value.IndexOf(';'); + if (comment >= 0) + value = value[..comment]; + return float.Parse(value, NumberStyles.Float, CultureInfo.InvariantCulture); + } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Core/DataReader/Lgt/LgtFileReader.cs b/Assets/Scripts/Pal3.Core/DataReader/Lgt/LgtFileReader.cs index c87c4681..cb5847bd 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Lgt/LgtFileReader.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Lgt/LgtFileReader.cs @@ -7,6 +7,7 @@ namespace Pal3.Core.DataReader.Lgt { using System; using System.Collections.Generic; + using System.IO; using Primitives; using Utilities; @@ -15,6 +16,9 @@ namespace Pal3.Core.DataReader.Lgt public LgtFile Read(IBinaryReader reader, int codepage) { int numOfLightNodes = reader.ReadInt32(); + const int recordBytes = 148; + if (numOfLightNodes < 0 || numOfLightNodes > (reader.Length - reader.Position) / recordBytes) + throw new InvalidDataException("The LGT light count exceeds its 148-byte native records."); List lightNodes = new(); for (int i = 0; i < numOfLightNodes; i++) @@ -35,10 +39,22 @@ namespace Pal3.Core.DataReader.Lgt { GameBoxMatrix4x4 transformMatrix = new() { - Xx = reader.ReadSingle(), Xy = reader.ReadSingle(), Xz = reader.ReadSingle(), Xw = reader.ReadSingle(), - Yx = reader.ReadSingle(), Yy = reader.ReadSingle(), Yz = reader.ReadSingle(), Yw = reader.ReadSingle(), - Zx = reader.ReadSingle(), Zy = reader.ReadSingle(), Zz = reader.ReadSingle(), Zw = reader.ReadSingle(), - Tx = reader.ReadSingle(), Ty = reader.ReadSingle(), Tz = reader.ReadSingle(), Tw = reader.ReadSingle() + Xx = reader.ReadSingle(), + Xy = reader.ReadSingle(), + Xz = reader.ReadSingle(), + Xw = reader.ReadSingle(), + Yx = reader.ReadSingle(), + Yy = reader.ReadSingle(), + Yz = reader.ReadSingle(), + Yw = reader.ReadSingle(), + Zx = reader.ReadSingle(), + Zy = reader.ReadSingle(), + Zz = reader.ReadSingle(), + Zw = reader.ReadSingle(), + Tx = reader.ReadSingle(), + Ty = reader.ReadSingle(), + Tz = reader.ReadSingle(), + Tw = reader.ReadSingle() }; transformMatrix.Tw = 1f; @@ -48,8 +64,9 @@ namespace Pal3.Core.DataReader.Lgt LightType = (GameBoxLightType)reader.ReadInt32(), LightColor = reader.ReadColor(), AmbientColor = reader.ReadColor(), - UseDiffuse = reader.ReadBoolean(), - UseSpecular = reader.ReadBoolean(), + // gbBOOL is signed int32 in both shipped engine ABIs. + UseDiffuse = reader.ReadInt32() != 0, + UseSpecular = reader.ReadInt32() != 0, NearStart = reader.ReadSingle(), NearEnd = reader.ReadSingle(), FarStart = reader.ReadSingle(), @@ -65,4 +82,4 @@ namespace Pal3.Core.DataReader.Lgt return lightNode; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3File.cs b/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3File.cs index 020091ad..ac6307b8 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3File.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3File.cs @@ -30,8 +30,8 @@ namespace Pal3.Core.DataReader.Mv3 public struct Mv3IndexBuffer { - public ushort[] TriangleIndex; // 3 - public ushort[] TexCoordIndex; // 3 + public ushort[] TriangleIndex; // 3 + public ushort[] TexCoordIndex; // 3 } public struct Mv3Attribute @@ -72,6 +72,7 @@ namespace Pal3.Core.DataReader.Mv3 { public uint GameBoxTick; public GameBoxVector3[] GameBoxVertices; + public ushort[] NativeNormals; } /// @@ -79,11 +80,30 @@ namespace Pal3.Core.DataReader.Mv3 /// public sealed class Mv3File { - public uint TotalGameBoxTicks { get; } - public Mv3AnimationEvent[] AnimationEvents { get; } - public Mv3TagNode[] TagNodes { get; } - public Mv3Mesh[] Meshes { get; } - public GameBoxMaterial[] Materials { get; } + public uint TotalGameBoxTicks + { + get; + } + + public Mv3AnimationEvent[] AnimationEvents + { + get; + } + + public Mv3TagNode[] TagNodes + { + get; + } + + public Mv3Mesh[] Meshes + { + get; + } + + public GameBoxMaterial[] Materials + { + get; + } public Mv3File(uint totalGameBoxTicks, Mv3AnimationEvent[] animationEvents, diff --git a/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3FileReader.cs b/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3FileReader.cs index 71190378..7662c376 100644 --- a/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3FileReader.cs +++ b/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3FileReader.cs @@ -1,4 +1,4 @@ -// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ // Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved. // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ @@ -13,6 +13,17 @@ namespace Pal3.Core.DataReader.Mv3 public sealed class Mv3FileReader : IFileReader { + private readonly bool _includeNativeNormals; + + public Mv3FileReader() : this(false) + { + } + + public Mv3FileReader(bool includeNativeNormals) + { + _includeNativeNormals = includeNativeNormals; + } + public Mv3File Read(IBinaryReader reader, int codepage) { char[] header = reader.ReadChars(4); @@ -40,46 +51,52 @@ namespace Pal3.Core.DataReader.Mv3 throw new InvalidDataException("Invalid MV3(.mv3) file: missing mesh or material info"); } + ValidateCount(reader, numberOfAnimationEvents, 20, "animation event"); Mv3AnimationEvent[] animationEvents = new Mv3AnimationEvent[numberOfAnimationEvents]; for (int i = 0; i < numberOfAnimationEvents; i++) { animationEvents[i] = ReadAnimationEvent(reader, codepage); } + ValidateCount(reader, numberOfTagNodes, 72, "tag node"); Mv3TagNode[] tagNodes = new Mv3TagNode[numberOfTagNodes]; for (int i = 0; i < numberOfTagNodes; i++) { tagNodes[i] = ReadTagNode(reader, codepage); } + ValidateCount(reader, numberOfMaterials, 84, "material"); GameBoxMaterial[] materials = new GameBoxMaterial[numberOfMaterials]; for (int i = 0; i < numberOfMaterials; i++) { materials[i] = ReadMaterial(reader, codepage); } - Mv3Mesh[] meshes = new Mv3Mesh[numberOfMeshes]; + ValidateCount(reader, numberOfMeshes, 104, "mesh"); + var meshes = new List(); for (int i = 0; i < numberOfMeshes; i++) { - meshes[i] = ReadMesh(reader, codepage); + meshes.AddRange(ReadMesh(reader, codepage)); } return new Mv3File(duration, animationEvents, tagNodes, - meshes, + meshes.ToArray(), materials); } - private static Mv3Mesh ReadMesh(IBinaryReader reader, int codepage) + private IEnumerable ReadMesh(IBinaryReader reader, int codepage) { string name = reader.ReadString(64, codepage); int numberOfVertices = reader.ReadInt32(); + ValidateCount(reader, numberOfVertices, 1, "vertex"); GameBoxVector3 gameBoxBoundsMin = reader.ReadGameBoxVector3(); GameBoxVector3 gameBoxBoundsMax = reader.ReadGameBoxVector3(); int numberOfFrames = reader.ReadInt32(); + ValidateCount(reader, numberOfFrames, 4 + 8L * numberOfVertices, "vertex frame"); Mv3VertFrame[] frames = new Mv3VertFrame[numberOfFrames]; for (int i = 0; i < numberOfFrames; i++) { @@ -103,28 +120,32 @@ namespace Pal3.Core.DataReader.Mv3 } int numberOfTexCoords = reader.ReadInt32(); + ValidateCount(reader, numberOfTexCoords, 8, "texture coordinate"); GameBoxVector2[] texCoords = numberOfTexCoords == 0 ? - new GameBoxVector2[] { new (0f, 0f) } : + new GameBoxVector2[] { new(0f, 0f) } : reader.ReadGameBoxVector2s(numberOfTexCoords); int numberOfAttributes = reader.ReadInt32(); + ValidateCount(reader, numberOfAttributes, 12, "mesh attribute"); + if (numberOfFrames == 0 && numberOfAttributes > 0) + throw new InvalidDataException("Invalid MV3 mesh: attributes require at least one vertex frame."); Mv3Attribute[] attributes = new Mv3Attribute[numberOfAttributes]; for (int i = 0; i < numberOfAttributes; i++) { int materialId = reader.ReadInt32(); int numberOfTriangles = reader.ReadInt32(); + ValidateCount(reader, numberOfTriangles, 12, "triangle"); Mv3IndexBuffer[] triangles = new Mv3IndexBuffer[numberOfTriangles]; for (int j = 0; j < numberOfTriangles; j++) { - triangles[j] = new Mv3IndexBuffer() - { - TriangleIndex = new []{ reader.ReadUInt16(), reader.ReadUInt16(), reader.ReadUInt16()}, - TexCoordIndex = new []{ reader.ReadUInt16(), reader.ReadUInt16(), reader.ReadUInt16()} - }; + ushort[] positions = ReadTriangleIndices(reader, numberOfVertices, "vertex"); + ushort[] coordinates = ReadTriangleIndices(reader, texCoords.Length, "texture coordinate"); + triangles[j] = new Mv3IndexBuffer { TriangleIndex = positions, TexCoordIndex = coordinates }; } int numberOfCommands = reader.ReadInt32(); + ValidateCount(reader, numberOfCommands, 4, "command"); int[] commands = new int[numberOfCommands]; for (int j = 0; j < numberOfCommands; j++) { @@ -139,7 +160,31 @@ namespace Pal3.Core.DataReader.Mv3 }; } - return GetMv3Mesh(name, gameBoxBoundsMin, gameBoxBoundsMax, attributes, frames, texCoords); + ushort[][] nativeNormals = _includeNativeNormals ? Mv3NativeNormals.Calculate(frames, attributes) : null; + for (int i = 0; i < attributes.Length; i++) + { + yield return GetMv3Mesh(attributes.Length == 1 ? name : name + " / " + i, gameBoxBoundsMin, + gameBoxBoundsMax, new[] { attributes[i] }, frames, texCoords, nativeNormals); + } + } + + private static void ValidateCount(IBinaryReader reader, int count, long recordBytes, string field) + { + if (count < 0 || count > (reader.Length - reader.Position) / recordBytes) + throw new InvalidDataException($"Invalid MV3 {field} count {count} for the remaining file data."); + } + + private static ushort[] ReadTriangleIndices(IBinaryReader reader, int count, string field) + { + var indices = new ushort[3]; + for (int corner = 0; corner < indices.Length; corner++) + { + ushort index = reader.ReadUInt16(); + if (index >= count) + throw new InvalidDataException($"Invalid MV3 triangle {field} index {index} with {count} entries."); + indices[corner] = index; + } + return indices; } private static Mv3Mesh GetMv3Mesh(string name, @@ -147,7 +192,8 @@ namespace Pal3.Core.DataReader.Mv3 GameBoxVector3 gameBoxBoundsMax, Mv3Attribute[] attributes, Mv3VertFrame[] vertFrames, - GameBoxVector2[] texCoords) + GameBoxVector2[] texCoords, + ushort[][] nativeNormals) { Mv3IndexBuffer[] faces = attributes[0].IndexBuffers; int[] triangles = new int[faces.Length * 3]; @@ -163,7 +209,7 @@ namespace Pal3.Core.DataReader.Mv3 int[] vertexRepresentatives = GetVertexRepresentatives(vertFrames, positionCount); var (normalCorners, normalCount) = CoreUtility.GetNormalIndices(sourceCorners, positionCount, vertexRepresentatives); - var renderVertexByCorner = new Dictionary<(int normalIndex, ushort uv), int>(); + var renderVertexByCorner = new Dictionary<(int normalIndex, ushort uv, ushort source), int>(); var normalIndices = new List(); var positionIndices = new List(); var uvs = new List(); @@ -175,7 +221,7 @@ namespace Pal3.Core.DataReader.Mv3 for (int j = 0; j < 3; j++) { int normalIndex = normalCorners[corner]; - var key = (normalIndex, uv: face.TexCoordIndex[j]); + var key = (normalIndex, uv: face.TexCoordIndex[j], source: face.TriangleIndex[j]); if (!renderVertexByCorner.TryGetValue(key, out int renderVertex)) { renderVertex = normalIndices.Count; @@ -194,16 +240,20 @@ namespace Pal3.Core.DataReader.Mv3 { Mv3VertFrame frame = vertFrames[i]; var vertices = new GameBoxVector3[normalIndices.Count]; + ushort[] packedNormals = nativeNormals == null ? null : new ushort[vertices.Length]; for (int j = 0; j < vertices.Length; j++) { Mv3Vert vertex = frame.Vertices[positionIndices[j]]; vertices[j] = new GameBoxVector3(vertex.X, vertex.Y, vertex.Z); + if (packedNormals != null) + packedNormals[j] = nativeNormals[i][positionIndices[j]]; } animationKeyFrames[i] = new Mv3AnimationKeyFrame { GameBoxTick = frame.GameBoxTick, GameBoxVertices = vertices, + NativeNormals = packedNormals, }; } @@ -246,7 +296,8 @@ namespace Pal3.Core.DataReader.Mv3 { Mv3Vert first = frame.Vertices[a]; Mv3Vert second = frame.Vertices[b]; - if (first.X != second.X || first.Y != second.Y || first.Z != second.Z) return false; + if (first.X != second.X || first.Y != second.Y || first.Z != second.Z) + return false; } return true; } @@ -271,6 +322,7 @@ namespace Pal3.Core.DataReader.Mv3 float flipScale = reader.ReadSingle(); int numberOfFrames = reader.ReadInt32(); + ValidateCount(reader, numberOfFrames, 56, "tag frame"); Mv3TagFrame[] tagFrames = new Mv3TagFrame[numberOfFrames]; for (int i = 0; i < numberOfFrames; i++) { @@ -325,7 +377,7 @@ namespace Pal3.Core.DataReader.Mv3 private static GameBoxMaterial ReadMaterial(IBinaryReader reader, int codepage) { - GameBoxMaterial material = new () + GameBoxMaterial material = new() { Diffuse = reader.ReadColor(), Ambient = reader.ReadColor(), @@ -334,15 +386,17 @@ namespace Pal3.Core.DataReader.Mv3 SpecularPower = reader.ReadSingle() }; - List textureNames = new (); + List textureNames = new(); for (int i = 0; i < 4; i++) { string textureName; int length = reader.ReadInt32(); + ValidateCount(reader, length, 1, "texture name byte"); if (length == 0) { - if (i > 0) continue; + if (i > 0) + continue; textureName = string.Empty; // Use default white texture } else @@ -358,4 +412,4 @@ namespace Pal3.Core.DataReader.Mv3 return material; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3NativeNormals.cs b/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3NativeNormals.cs new file mode 100644 index 00000000..6b1fabfe --- /dev/null +++ b/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3NativeNormals.cs @@ -0,0 +1,88 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Core.DataReader.Mv3 +{ + using System; + using Primitives; + + /// The original morph renderer repairs exported normals at each keyframe. + public static class Mv3NativeNormals + { + private const double LatitudeScale = 81.16901871813289; + private const double LongitudeScale = 40.584509359066445; + private const float Pi = 3.1415926535f; + + public static ushort[][] Calculate(Mv3VertFrame[] frames, Mv3Attribute[] attributes) + { + var result = new ushort[frames.Length][]; + for (int frame = 0; frame < frames.Length; frame++) + { + Mv3Vert[] vertices = frames[frame].Vertices; + var sums = new GameBoxVector3[vertices.Length]; + foreach (Mv3Attribute attribute in attributes) + { + foreach (Mv3IndexBuffer face in attribute.IndexBuffers) + { + ushort[] indices = face.TriangleIndex; + GameBoxVector3 a = Position(vertices[indices[0]]); + GameBoxVector3 b = Position(vertices[indices[1]]) - a; + GameBoxVector3 c = Position(vertices[indices[2]]) - a; + var cross = new GameBoxVector3( + (float)((double)b.Y * c.Z - (double)b.Z * c.Y), + (float)((double)b.Z * c.X - (double)b.X * c.Z), + (float)((double)b.X * c.Y - (double)b.Y * c.X)); + GameBoxVector3 normal = Normalize(cross); + foreach (ushort index in indices) + sums[index] += normal; + } + } + var packed = new ushort[vertices.Length]; + for (int vertex = 0; vertex < vertices.Length; vertex++) + packed[vertex] = Encode(Normalize(sums[vertex])); + result[frame] = packed; + } + return result; + } + + private static GameBoxVector3 Position(Mv3Vert vertex) => new(vertex.X / 64f, vertex.Y / 64f, vertex.Z / 64f); + + private static GameBoxVector3 Normalize(GameBoxVector3 value) + { + double length = Math.Sqrt((double)value.X * value.X + (double)value.Y * value.Y + (double)value.Z * value.Z); + return length < .005f ? new GameBoxVector3(0, 1, 0) : + new GameBoxVector3((float)(value.X / length), (float)(value.Y / length), (float)(value.Z / length)); + } + + private static ushort Encode(GameBoxVector3 value) + { + if (Math.Abs(value.X) + Math.Abs(value.Y) < 1f / 500f) + return value.Z > 0 ? (ushort)0 : (ushort)255; + int longitude = Math.Clamp((int)(Math.Atan2(value.Y, value.X) * LongitudeScale), -127, 127); + int latitude = Math.Min(255, (int)(Math.Acos(Math.Clamp(value.Z, -1f, 1f)) * LatitudeScale)); + return (ushort)(((longitude << 8) | latitude) & 65535); + } + + private static readonly Lazy Decoded = new(CreateDecodedTable); + + public static GameBoxVector3 Decode(ushort value) => Decoded.Value[value]; + + private static GameBoxVector3[] CreateDecodedTable() + { + var values = new GameBoxVector3[65536]; + for (int value = 0; value < values.Length; value++) + values[value] = DecodeValue((ushort)value); + return values; + } + + private static GameBoxVector3 DecodeValue(ushort value) + { + float longitude = (sbyte)(value >> 8) * 2 * Pi / 255; + float latitude = (value & 255) * Pi / 255; + return new GameBoxVector3((float)(Math.Cos(longitude) * Math.Sin(latitude)), + (float)(Math.Sin(longitude) * Math.Sin(latitude)), (float)Math.Cos(latitude)); + } + } +} diff --git a/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3NativeNormals.cs.meta b/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3NativeNormals.cs.meta new file mode 100644 index 00000000..a37ff3f3 --- /dev/null +++ b/Assets/Scripts/Pal3.Core/DataReader/Mv3/Mv3NativeNormals.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f7346833e4df411fa4670215e95ed629 diff --git a/Assets/Scripts/Pal3.Core/Primitives/GameBoxVector3.cs b/Assets/Scripts/Pal3.Core/Primitives/GameBoxVector3.cs index 3437b073..2ffbf9f0 100644 --- a/Assets/Scripts/Pal3.Core/Primitives/GameBoxVector3.cs +++ b/Assets/Scripts/Pal3.Core/Primitives/GameBoxVector3.cs @@ -107,7 +107,7 @@ namespace Pal3.Core.Primitives { float dx = a.X - b.X; float dy = a.Y - b.Y; - float dz = a.Z - b.X; + float dz = a.Z - b.Z; return (double) dx * (double) dx + @@ -129,7 +129,7 @@ namespace Pal3.Core.Primitives { float dx = X - other.X; float dy = Y - other.Y; - float dz = Z - other.X; + float dz = Z - other.Z; return (double) dx * (double) dx + diff --git a/Assets/Scripts/Pal3.Core/Utilities/GameBoxLightOrder.cs b/Assets/Scripts/Pal3.Core/Utilities/GameBoxLightOrder.cs new file mode 100644 index 00000000..11173591 --- /dev/null +++ b/Assets/Scripts/Pal3.Core/Utilities/GameBoxLightOrder.cs @@ -0,0 +1,72 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Core.Utilities +{ + using System; + + /// Released light sorting also determines which equally strong lights survive. + public static class GameBoxLightOrder + { + public static void Sort(Span order, ReadOnlySpan weights) + { + if (order.Length != weights.Length) + throw new ArgumentException("Light ordering requires one weight per index."); + for (int index = 0; index < order.Length; index++) + order[index] = index; + SortRange(order, weights, 0, order.Length - 1); + } + + private static int Compare(float a, float b) => a > b ? -1 : a < b ? 1 : 0; + + private static void SortRange(Span order, ReadOnlySpan weights, int low, int high) + { + if (high <= low) + return; + if (high - low < 8) + { + for (int end = high; end > low; end--) + { + int weakest = low; + for (int index = low + 1; index <= end; index++) + if (Compare(weights[order[index]], weights[order[weakest]]) > 0) + weakest = index; + Swap(order, weakest, end); + } + return; + } + Swap(order, low, low + (high - low + 1) / 2); + float pivot = weights[order[low]]; + int left = low; + int right = high + 1; + while (true) + { + do + { + left++; + } + while (left <= high && Compare(weights[order[left]], pivot) <= 0); + do + { + right--; + } + while (right > low && Compare(weights[order[right]], pivot) >= 0); + if (right < left) + break; + Swap(order, left, right); + } + Swap(order, low, right); + SortRange(order, weights, low, right - 1); + SortRange(order, weights, left, high); + } + + private static void Swap(Span order, int a, int b) + { + int value = order[a]; + order[a] = order[b]; + order[b] = value; + } + } +} diff --git a/Assets/Scripts/Pal3.Core/Utilities/GameBoxLightOrder.cs.meta b/Assets/Scripts/Pal3.Core/Utilities/GameBoxLightOrder.cs.meta new file mode 100644 index 00000000..6d771918 --- /dev/null +++ b/Assets/Scripts/Pal3.Core/Utilities/GameBoxLightOrder.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d4dbf7201166446ab51eb657f2f59266 diff --git a/Assets/Scripts/Pal3.Game/Actor/Controllers/ActorController.cs b/Assets/Scripts/Pal3.Game/Actor/Controllers/ActorController.cs index 6324bcd7..530b8159 100644 --- a/Assets/Scripts/Pal3.Game/Actor/Controllers/ActorController.cs +++ b/Assets/Scripts/Pal3.Game/Actor/Controllers/ActorController.cs @@ -178,7 +178,7 @@ namespace Pal3.Game.Actor.Controllers ServiceLocator.Instance.Get() .GetPlayerActorId() == actorController.GetActor().Id) { - Pal3.Instance.Execute(new CombatActorCollideWithPlayerActorNotification( + Pal3.Instance.Execute(new BattleActorCollideWithPlayerActorNotification( _actor.Id, actorController.GetActor().Id)); } } diff --git a/Assets/Scripts/Pal3.Game/Command/Extensions/CombatActorCollideWithPlayerActorNotification.cs b/Assets/Scripts/Pal3.Game/Command/Extensions/BattleActorCollideWithPlayerActorNotification.cs similarity index 67% rename from Assets/Scripts/Pal3.Game/Command/Extensions/CombatActorCollideWithPlayerActorNotification.cs rename to Assets/Scripts/Pal3.Game/Command/Extensions/BattleActorCollideWithPlayerActorNotification.cs index b84a5ea5..54a98948 100644 --- a/Assets/Scripts/Pal3.Game/Command/Extensions/CombatActorCollideWithPlayerActorNotification.cs +++ b/Assets/Scripts/Pal3.Game/Command/Extensions/BattleActorCollideWithPlayerActorNotification.cs @@ -7,9 +7,9 @@ namespace Pal3.Game.Command.Extensions { using Core.Command; - public sealed class CombatActorCollideWithPlayerActorNotification : ICommand + public sealed class BattleActorCollideWithPlayerActorNotification : ICommand { - public CombatActorCollideWithPlayerActorNotification( + public BattleActorCollideWithPlayerActorNotification( int combatActorId, int playerActorId) { @@ -17,7 +17,14 @@ namespace Pal3.Game.Command.Extensions PlayerActorId = playerActorId; } - public int CombatActorId { get; } - public int PlayerActorId { get; } + public int CombatActorId + { + get; + } + + public int PlayerActorId + { + get; + } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/Command/Extensions/CombatActorCollideWithPlayerActorNotification.cs.meta b/Assets/Scripts/Pal3.Game/Command/Extensions/BattleActorCollideWithPlayerActorNotification.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/Command/Extensions/CombatActorCollideWithPlayerActorNotification.cs.meta rename to Assets/Scripts/Pal3.Game/Command/Extensions/BattleActorCollideWithPlayerActorNotification.cs.meta diff --git a/Assets/Scripts/Pal3.Game/Data/GameResourceProvider.cs b/Assets/Scripts/Pal3.Game/Data/GameResourceProvider.cs index cf9bb33d..9e6ef322 100644 --- a/Assets/Scripts/Pal3.Game/Data/GameResourceProvider.cs +++ b/Assets/Scripts/Pal3.Game/Data/GameResourceProvider.cs @@ -148,7 +148,7 @@ namespace Pal3.Game.Data return _shadowSprite; } - public Effect.Original.OriginalEffectResources OriginalEffects => Effects.Original; + public Effect.Runtime.EffectResources EffectResources => Effects.Resources; public IMaterialManager GetMaterialManager() => _materialManager; diff --git a/Assets/Scripts/Pal3.Game/Dev/Presenters/CombatActorInfoPresenter.cs b/Assets/Scripts/Pal3.Game/Dev/Presenters/BattleActorInfoPresenter.cs similarity index 90% rename from Assets/Scripts/Pal3.Game/Dev/Presenters/CombatActorInfoPresenter.cs rename to Assets/Scripts/Pal3.Game/Dev/Presenters/BattleActorInfoPresenter.cs index 89fe1489..32d5ddf8 100644 --- a/Assets/Scripts/Pal3.Game/Dev/Presenters/CombatActorInfoPresenter.cs +++ b/Assets/Scripts/Pal3.Game/Dev/Presenters/BattleActorInfoPresenter.cs @@ -11,8 +11,8 @@ namespace Pal3.Game.Dev.Presenters /// /// CombatActorInfo holder component to present ScnObjectInfo in the Unity inspector. /// - public sealed class CombatActorInfoPresenter : GameEntityScript + public sealed class BattleActorInfoPresenter : GameEntityScript { [UnityEngine.SerializeField] public CombatActorInfo combatActorInfo; } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/Dev/Presenters/CombatActorInfoPresenter.cs.meta b/Assets/Scripts/Pal3.Game/Dev/Presenters/BattleActorInfoPresenter.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/Dev/Presenters/CombatActorInfoPresenter.cs.meta rename to Assets/Scripts/Pal3.Game/Dev/Presenters/BattleActorInfoPresenter.cs.meta diff --git a/Assets/Scripts/Pal3.Game/Effect/CombatEffect.cs b/Assets/Scripts/Pal3.Game/Effect/BattleEffect.cs similarity index 93% rename from Assets/Scripts/Pal3.Game/Effect/CombatEffect.cs rename to Assets/Scripts/Pal3.Game/Effect/BattleEffect.cs index 8afac298..9f08db13 100644 --- a/Assets/Scripts/Pal3.Game/Effect/CombatEffect.cs +++ b/Assets/Scripts/Pal3.Game/Effect/BattleEffect.cs @@ -9,7 +9,7 @@ namespace Pal3.Game.Effect using Data; using Engine.Core.Implementation; - public sealed class CombatEffect : GameEntityScript, IEffect + public sealed class BattleEffect : GameEntityScript, IEffect { private IDisposable _effect; diff --git a/Assets/Scripts/Pal3.Game/Effect/CombatEffect.cs.meta b/Assets/Scripts/Pal3.Game/Effect/BattleEffect.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/Effect/CombatEffect.cs.meta rename to Assets/Scripts/Pal3.Game/Effect/BattleEffect.cs.meta diff --git a/Assets/Scripts/Pal3.Game/Effect/EffectRuntime.cs b/Assets/Scripts/Pal3.Game/Effect/EffectRuntime.cs index c90faace..6c7788c8 100644 --- a/Assets/Scripts/Pal3.Game/Effect/EffectRuntime.cs +++ b/Assets/Scripts/Pal3.Game/Effect/EffectRuntime.cs @@ -8,7 +8,7 @@ namespace Pal3.Game.Effect using System; using System.Collections; using System.Collections.Generic; - using Original; + using Runtime; using Core.FileSystem; using Core.Command.SceCommands; using Engine.Core.Abstraction; @@ -19,18 +19,18 @@ namespace Pal3.Game.Effect internal sealed class EffectRuntime : IDisposable { - private readonly OriginalEffectResources _original; + private readonly EffectResources _resources; private readonly HashSet _failures = new(); private readonly List _playedEffects = new(); private readonly List _persistentEffects = new(); private int _preloadGeneration; private bool _disposed; - internal OriginalEffectResources Original => _original; + internal EffectResources Resources => _resources; internal EffectRuntime(ICpkFileSystem fileSystem, int codepage) { - _original = new OriginalEffectResources(fileSystem, codepage); + _resources = new EffectResources(fileSystem, codepage); } internal IEnumerator PreloadAsync(int groupId) @@ -38,11 +38,11 @@ namespace Pal3.Game.Effect if (_disposed) yield break; int generation = _preloadGeneration; - OriginalEffectOverrides edits; + EffectOverrides edits; try { - edits = Resources.Load(_original.OverridesPath); - string[] issues = _original.Diagnose(groupId, edits); + edits = UnityEngine.Resources.Load(_resources.OverridesPath); + string[] issues = _resources.Diagnose(groupId, edits); if (issues.Length != 0) { Report(groupId, string.Join("\n", issues)); @@ -54,7 +54,7 @@ namespace Pal3.Game.Effect Report(groupId, ex.Message); yield break; } - using var preload = _original.Preload(groupId, edits).GetEnumerator(); + using var preload = _resources.Preload(groupId, edits).GetEnumerator(); while (!_disposed && generation == _preloadGeneration) { bool next; @@ -86,21 +86,21 @@ namespace Pal3.Game.Effect GameObject root = null; try { - var edits = Resources.Load(_original.OverridesPath); - string[] issues = groupId == -1 ? Array.Empty() : _original.Diagnose(groupId, edits); + var edits = UnityEngine.Resources.Load(_resources.OverridesPath); + string[] issues = groupId == -1 ? Array.Empty() : _resources.Diagnose(groupId, edits); if (issues.Length != 0) { Report(groupId, string.Join("\n", issues)); return null; } - root = new GameObject(groupId == -1 ? "Original transport" : $"Original effect {groupId}"); + root = new GameObject(groupId == -1 ? "Effect transport" : $"Effect {groupId}"); root.transform.SetParent((Transform)parent.Transform.NativeObject, false); if (groupId == -1) - root.AddComponent().Initialize(_original, portalType); + root.AddComponent().Initialize(_resources, portalType); else { - var player = root.AddComponent(); - player.Initialize(_original, groupId, (uint)UnityEngine.Random.Range(1, int.MaxValue), overrides: edits, + var player = root.AddComponent(); + player.Initialize(_resources, groupId, (uint)UnityEngine.Random.Range(1, int.MaxValue), overrides: edits, sound: name => Pal3.Instance.Execute(new PlaySfxCommand(name, 1))); player.DestroyOnComplete = true; if (player.Error != null) @@ -112,8 +112,7 @@ namespace Pal3.Game.Effect { if (root != null) { - root.SetActive(false); - OriginalEffectResources.Destroy(root); + Stop(new GameEntity(root)); } Report(groupId, ex.Message); return null; @@ -154,7 +153,7 @@ namespace Pal3.Game.Effect if (Application.isPlaying && Pal3.Instance != null) Pal3.Instance.StartCoroutine(TrimSceneRenderAssetsAfterFrame()); else - _original.TrimUnusedRenderAssets(LiveRoots()); + _resources.TrimUnusedRenderAssets(LiveRoots()); } private IEnumerator TrimSceneRenderAssetsAfterFrame() @@ -164,7 +163,7 @@ namespace Pal3.Game.Effect if (_disposed) yield break; PruneDeadAttachments(); - _original.TrimUnusedRenderAssets(LiveRoots()); + _resources.TrimUnusedRenderAssets(LiveRoots()); } private IEnumerable LiveRoots() @@ -181,7 +180,10 @@ namespace Pal3.Game.Effect { if (effect.IsNullOrDisposed()) return; - ((GameObject)effect.NativeObject).SetActive(false); + var root = (GameObject)effect.NativeObject; + root.GetComponent()?.Dispose(); + root.GetComponent()?.Dispose(); + root.SetActive(false); effect.Destroy(); } @@ -206,7 +208,7 @@ namespace Pal3.Game.Effect ClearPlayedEffects(); foreach (PersistentEffect effect in _persistentEffects.ToArray()) effect.Dispose(); - _original.Dispose(); + _resources.Dispose(); } private sealed class PersistentEffect : IDisposable @@ -224,11 +226,11 @@ namespace Pal3.Game.Effect _owner = owner; _parent = parent; _instance = owner.Create(groupId, parent, portalType); - if (Root != null && Root.GetComponent() is { } player) + if (Root != null && Root.GetComponent() is { } player) { player.DestroyOnComplete = false; player.Loop = true; - player.RepeatInterval = owner._original.GameVariant == "PAL3" && groupId == 275 ? 9.5f : 0; + player.RepeatInterval = owner._resources.GameVariant == "PAL3" && groupId == 275 ? 9.5f : 0; } } diff --git a/Assets/Scripts/Pal3.Game/Effect/EffectTypeResolver.cs b/Assets/Scripts/Pal3.Game/Effect/EffectTypeResolver.cs index dfe53690..6188b330 100644 --- a/Assets/Scripts/Pal3.Game/Effect/EffectTypeResolver.cs +++ b/Assets/Scripts/Pal3.Game/Effect/EffectTypeResolver.cs @@ -17,7 +17,7 @@ namespace Pal3.Game.Effect { GraphicsEffectType.Fire => typeof(FireEffect), GraphicsEffectType.Portal => typeof(PortalEffect), - GraphicsEffectType.Combat => typeof(CombatEffect), + GraphicsEffectType.Combat => typeof(BattleEffect), _ => null }; } diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/EffectMeshBuffer.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/EffectMeshBuffer.cs.meta deleted file mode 100644 index 3ce77447..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/EffectMeshBuffer.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 4daa7814a3fa8493293fc2ad9eb6fecc \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectNode.cs.meta deleted file mode 100644 index 76be86ca..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectNode.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 03437bbaa78854faca572e1b314a630a \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectOverrides.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectOverrides.cs.meta deleted file mode 100644 index 9410eb8c..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectOverrides.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 3a0f5edeb37f04ad28e5e2ed9000e2c5 \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectPlayer.cs b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectPlayer.cs deleted file mode 100644 index a60a27df..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectPlayer.cs +++ /dev/null @@ -1,296 +0,0 @@ -// ------------------------------------------------------------------------ -// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. -// See LICENSE file in the project root for license information. -// ------------------------------------------------------------------------ - -namespace Pal3.Game.Effect.Original -{ - using System; - using System.Collections.Generic; - using Core.DataReader.Data; - using UnityEngine; - - // One simulation serves both clocks: real frame time in game, and fixed - // steps for editor playback/seeking. Rendering never advances the clock. - public sealed class OriginalEffectPlayer : MonoBehaviour - { - public const float FixedStep = 0.02f; - private readonly List _nodes = new(); - private OriginalEffectResources _resources; - private OriginalEffectOverrides _overrides; - private int _groupId; - private double _time; - private uint _seed; - private uint _spawnSequence; - private float _accumulator; - private Action _sound; - private bool _disposed, _suppressEvents; - private float _lastRepeat; - - public float Time => (float)_time; - public bool AutoAdvance { get; set; } = true; - - public bool Paused - { - get; set; - } - - public float Speed { get; set; } = 1; - - public bool Loop - { - get; set; - } - - public bool DestroyOnComplete - { - get; set; - } - - public float RepeatInterval - { - get; set; - } - - public int NodeCount => _nodes.Count; - - public int QuadCount - { - get; private set; - } - - public bool IsAlive - { - get; private set; - } - - public string Error - { - get; private set; - } - - public void Initialize(OriginalEffectResources resources, int groupId, uint seed = 1, - OriginalEffectOverrides overrides = null, Action sound = null) - { - if (overrides != null && overrides.Version != 1) - throw new NotSupportedException($"Unknown original effect override version {overrides.Version}"); - _resources = resources; - _groupId = groupId; - _seed = seed == 0 ? 1 : seed; - _overrides = overrides; - _sound = sound; - ResetSimulation(); - } - - private void ResetSimulation(bool resetRandom = true) - { - ClearNodes(); - _time = 0; - _accumulator = 0; - _lastRepeat = 0; - Error = null; - if (resetRandom) - _spawnSequence = 0; - try - { - AddGroup(_groupId, Vector3.zero); - IsAlive = _nodes.Count > 0; - } - catch (Exception ex) - { - Error = ex.Message; - ClearNodes(); - IsAlive = false; - } - } - - internal void AddGroup(int groupId, Vector3 position) - { - if (groupId < 0 || groupId >= _resources.Definitions.Groups.Length) - throw new ArgumentOutOfRangeException(nameof(groupId)); - EffectGroup group = _resources.Definitions.Groups[groupId]; - for (int i = 0; i < group.Objects.Length; i++) - { - EffectGroupObject obj = group.Objects[i]; - _resources.Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d); - EffectTask[] tasks = obj.Tasks; - if (!OriginalEffectOverrides.Resolve(_overrides, groupId, i, ref d, ref tasks)) - continue; - if (_nodes.Count >= 2048) - throw new InvalidOperationException("Original effect object limit (2048) reached"); - obj = new EffectGroupObject { TypeCrc = obj.TypeCrc, Tasks = tasks }; - var root = new GameObject($"{groupId}:{i} {d.TypeName}") { hideFlags = HideFlags.DontSave, layer = gameObject.layer }; - root.transform.SetParent(transform, false); - OriginalEffectNode node = null; - try - { - string kind = EffectClass.Name(d.ClassNameCrc); - uint seed = _seed + _spawnSequence++ * 7919 + (uint)(groupId * 104729 + i); - node = kind switch - { - "callback" or "audio" => new OriginalControlNode(root, d, obj.Tasks, position, Time, this, kind), - "quad" => new OriginalQuadNode(root, d, obj.Tasks, position, Time, _resources), - "S-Particle" => new OriginalSparNode(root, d, obj.Tasks, position, Time, _resources, seed), - "particle" => new OriginalParticleNode(root, d, obj.Tasks, position, Time, _resources, seed, _overrides), - "cylinder" or "grid" => new OriginalGeometryNode(root, d, obj.Tasks, position, Time, _resources, kind), - "meteor" or "shock" => new OriginalTrailNode(root, d, obj.Tasks, position, Time, _resources, kind, seed), - "model" => new OriginalModelNode(root, d, obj.Tasks, position, Time, _resources), - "explosive" => new OriginalExplosiveNode(root, d, obj.Tasks, position, Time, _resources, seed), - _ => throw new NotSupportedException($"Original effect class {kind}: {d.TypeName}"), - }; - _nodes.Add(node); - } - catch - { - node?.Dispose(); - OriginalEffectResources.Destroy(root); - throw; - } - } - } - - internal void Sound(string name) - { - if (!_suppressEvents) - _sound?.Invoke(name); - } - - public void Advance(float delta) - { - float elapsed = ScaledDelta(delta); - if (elapsed <= 0) - return; - _accumulator += elapsed; - while (_accumulator + 0.000001f >= FixedStep) - { - _accumulator -= FixedStep; - if (!SimulateStep(FixedStep)) - break; - } - } - - public void AdvanceFrame(float delta) - { - float elapsed = ScaledDelta(delta); - if (elapsed <= 0) - return; - elapsed += _accumulator; - _accumulator = 0; - SimulateStep(elapsed); - } - - private float ScaledDelta(float delta) - { - if (_disposed || Paused || Error != null || delta <= 0 || !float.IsFinite(delta)) - return 0; - float elapsed = delta * (float.IsFinite(Speed) ? Mathf.Clamp(Speed, 0, 16) : 1); - return float.IsFinite(elapsed) ? elapsed : 0; - } - - private bool SimulateStep(float delta) - { - _time += delta; - try - { - int count = _nodes.Count; - bool alive = false; - for (int i = 0; i < count; i++) - { - _nodes[i].Step(Time, delta); - alive |= _nodes[i].Alive; - } - IsAlive = alive || _nodes.Count > count; - for (int i = _nodes.Count - 1; i >= 0; i--) - if (!_nodes[i].Alive) - { - _nodes[i].Dispose(); - _nodes.RemoveAt(i); - } - if (Loop && RepeatInterval > 0 && Time - _lastRepeat >= RepeatInterval) - { - AddGroup(_groupId, Vector3.zero); - _lastRepeat = Time; - IsAlive = true; - } - if (Loop && !IsAlive && RepeatInterval <= 0) - { - ResetSimulation(false); - return false; - } - return true; - } - catch (Exception ex) - { - Error = ex.ToString(); - ClearNodes(); - IsAlive = false; - Debug.LogException(ex); - return false; - } - } - - public void Seek(float time) - { - if (_disposed) - return; - time = Mathf.Clamp(float.IsFinite(time) ? time : 0, 0, 600); - bool paused = Paused, loop = Loop; - float speed = Speed; - ResetSimulation(); - Paused = false; - Loop = false; - Speed = 1; - _suppressEvents = true; - try - { - Advance(time); - } - finally - { - _suppressEvents = false; - Paused = paused; - Loop = loop; - Speed = speed; - } - } - - public void Render(Camera camera) - { - QuadCount = 0; - foreach (OriginalEffectNode node in _nodes) - { - node.Render(camera); - QuadCount += node.QuadCount; - } - } - - private void Update() - { - if (!AutoAdvance) - return; - AdvanceFrame(UnityEngine.Time.deltaTime); - if (DestroyOnComplete && !Loop && !IsAlive && Time > 0) - OriginalEffectResources.Destroy(gameObject); - } - - private void LateUpdate() - { - if (AutoAdvance) - Render(Camera.main); - } - - private void ClearNodes() - { - foreach (OriginalEffectNode node in _nodes) - node.Dispose(); - _nodes.Clear(); - QuadCount = 0; - } - - private void OnDestroy() - { - _disposed = true; - ClearNodes(); - } - } -} diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectPlayer.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectPlayer.cs.meta deleted file mode 100644 index 88f1fdd2..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectPlayer.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 7b4e14dc881ee4e348d1125f142c9dc4 \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectResources.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectResources.cs.meta deleted file mode 100644 index 0bce0cfe..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectResources.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 6df74732b3a2d44b69e9ed674b10f621 \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalGeometryNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalGeometryNode.cs.meta deleted file mode 100644 index c1f67557..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalGeometryNode.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: b4096b3ce200a447ba269be4a95c0f5a \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalModelNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalModelNode.cs.meta deleted file mode 100644 index 657d3eb8..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalModelNode.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 931441919a39d495fa8277a0dca473d0 \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalParticleNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalParticleNode.cs.meta deleted file mode 100644 index ef38c243..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalParticleNode.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 13f42c5931db146b8a60320470832551 \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalPortalEffect.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalPortalEffect.cs.meta deleted file mode 100644 index 736451fe..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalPortalEffect.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 279668a7de3554dc9b94b925ca64ee9d \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalQuadNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalQuadNode.cs.meta deleted file mode 100644 index 0aee159a..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalQuadNode.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 81978aa3bb0d146e1ba874a04516b592 \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalTrailNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Original/OriginalTrailNode.cs.meta deleted file mode 100644 index 52b0240c..00000000 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalTrailNode.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 5b9bae354ece74ad9a9def2a773f3f6e \ No newline at end of file diff --git a/Assets/Scripts/Pal3.Game/Effect/Original.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/Effect/Original.meta rename to Assets/Scripts/Pal3.Game/Effect/Runtime.meta diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleControlNode.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleControlNode.cs new file mode 100644 index 00000000..3693fa9a --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleControlNode.cs @@ -0,0 +1,261 @@ +// ------------------------------------------------------------------------ +// 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 Core.DataReader.Data; + using Core.DataReader.Cpk; + using UnityEngine; + + internal sealed class BattleControlNode : EffectNode + { + private readonly IBattleEffectContext _context; + private readonly string _kind; + private readonly bool _externalNames; + private readonly Vector3[] _starts; + private readonly bool[] _silentActions; + private readonly IEffectMovie[] _movies; + private readonly IEffectTimeControl _timeControl; + private readonly double[] _timeStarts; + private readonly Dictionary<(int Slot, uint Model), IEffectActor> _controlledActors = new(); + private EffectTaskClock _cameraTask; + private int _pendingMovieTask = -1; + private float _pendingDelta; + private bool _aliveBeforeMovie; + + public BattleControlNode(GameObject root, EffectDefinition definition, EffectTask[] tasks, + Vector3 origin, float birth, IBattleEffectContext context, string kind, bool externalNames) + : base(root, definition, tasks, origin, birth) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + _kind = kind; + _externalNames = externalNames; + _starts = new Vector3[Tasks.Length]; + if (kind == "action") + _silentActions = new bool[Tasks.Length]; + _movies = new IEffectMovie[Tasks.Length]; + if (kind == "time") + { + if (Array.Exists(Tasks, task => !SupportsTimeTask(task))) + throw new NotSupportedException("Unsupported original time task parameters."); + _timeControl = context as IEffectTimeControl ?? + throw new NotSupportedException("The battle context does not control its clock."); + _timeStarts = new double[Tasks.Length]; + } + } + + internal bool ControlsTime => _timeControl != null; + + internal static bool SupportsTimeTask(EffectTask task) => + task.CreateNew && task.ModifyLast && float.IsFinite(task.XStretchSpeed) && task.XStretchSpeed is >= 0f and <= 1f && + float.IsFinite(task.StartTime) && float.IsFinite(task.Duration) && task.Duration >= 0f && task.SpeedY == 0f && task.CircleRadius == 0f; + + internal void StepTimeControl(float time, float delta, double absoluteTime) + { + float localTime = time - Birth; + bool alive = false; + for (int index = 0; index < Tasks.Length; index++) + { + EffectTask task = Tasks[index]; + EffectTaskClock clock = Clocks[index]; + if (delta > 0 && clock.StartedAt < 0 && clock.Tick(localTime, delta, task, out _)) + { + _timeStarts[index] = absoluteTime; + _timeControl.SetTimeScale(clock, task.XStretchSpeed); + clock.KeepRunning(); + } + // Start waits follow the effect clock. An active slowdown expires in real time. + if (clock.StartedAt >= 0 && !clock.Finished && absoluteTime - _timeStarts[index] >= task.Duration) + { + _timeControl.ClearTimeScale(clock); + clock.Complete(); + } + alive |= !clock.Finished; + } + Alive = alive; + } + + protected override void Apply(EffectTask task, EffectTaskClock clock, float delta) + { + int index = Array.IndexOf(Tasks, task); + if (_kind == "action") + { + if (_silentActions[index]) + return; + uint roleId = _externalNames ? task.ReservedWords[1] : 0; + int slot = (int)MathF.Round(task.CreateTimeSlot); + bool owned = _controlledActors.TryGetValue((slot, roleId), out IEffectActor actor); + actor ??= _context.Actor(slot, roleId); + if (actor == null) + return; // Original invalid/missing role identifiers do not control a role. + Vector3 previous = actor.Position; + if (clock.StartedNow) + { + if (!owned) + { + _controlledActors.Add((slot, roleId), actor); + actor.SetExternalTask(true, this); + } + actor.SetAction(ActionName((int)MathF.Round(task.XStretchSpeed), _externalNames ? task.ReservedWords[0] : 0)); + actor.SetLongBlade(task.RequireLoops > 0); + if (task.SpeedBlue > 0) + _starts[index] = previous; + } + Vector3 current; + if (task.SpeedBlue <= 0) + current = previous + new Vector3(task.SpeedX, task.SpeedY, task.SpeedZ) * delta; + else + { + Vector3 target = new(task.RotAxisX, task.RotAxisY, task.RotAxisZ); + float elapsed = LocalTime - clock.StartedAt; + current = task.Duration - elapsed <= 0 ? target : _starts[index] + (target - _starts[index]) * (elapsed / task.Duration); + } + actor.Position = current; + if (task.CreateNew && (current.x != previous.x || current.y != previous.y || current.z != previous.z)) + { + Vector3 direction = current - previous; + double length = Math.Sqrt((double)direction.x * direction.x + (double)direction.y * direction.y + (double)direction.z * direction.z); + direction = length < (double)0.005f ? new Vector3(0, 1, 0) : + new Vector3((float)(direction.x / length), (float)(direction.y / length), (float)(direction.z / length)); + double angle = Math.Acos(Math.Clamp(direction.z, -1f, 1f)); + if (direction.x < 0) + angle = -angle + (double)(MathF.PI * 2); + actor.FacingDegrees = (float)(angle * (double)Mathf.Rad2Deg); + } + if (task.SpeedAlpha != 0) + actor.Blend = Mathf.Clamp01(actor.Blend + task.SpeedAlpha * delta); + actor.SetWeapons(task.SpeedRed, task.SpeedGreen); + if (clock.Finished || task.ModifyLast && actor.ActionOver) + { + if (task.YStretchSpeed > 0) + actor.FacingDegrees = task.YStretchSpeed; + actor.SetLongBlade(false); + clock.Complete(); + } + } + else if (_kind == "camera") + { + if (clock.StartedNow && _context.Camera is { } camera) + { + camera.StopList(); + _cameraTask = null; + if (task.XStretchSpeed > 0 && camera.StartList((int)MathF.Round(task.XStretchSpeed))) + _cameraTask = clock; + } + // Ordinary duration expiry leaves the camera list running. Only + // an explicit task end request stops it in CEffCamera. + } + else if (_kind == "quake") + { + if (clock.StartedNow) + _context.Camera?.SetQuake(task.XStretchSpeed, task.SpeedY, task.SpeedX); + } + else if (_kind == "bink" && task.XStretchSpeed != 0 && LocalTime - clock.StartedAt >= task.SpeedX) + { + _movies[index] ??= _context.PlayMovie(Definition.VideoFileNamePrefix + ((int)MathF.Round(task.XStretchSpeed)).ToString("000") + ".bik"); + if (_movies[index]?.Finished != false) + clock.Complete(); + else + clock.KeepRunning(); + } + } + + internal static string ActionName(int index, uint prefix) + { + if (index <= 0) + return null; + if (prefix == 0) + return "z" + index.ToString("00"); + var hash = new Crc32Hash(); + hash.Init(); + foreach (string candidate in new[] { "z", "z0", "th", "th0", "tw", "tw0", "tp", "tp0", "tx", "tx0", "tl", "tl0", "hj", "hj0", "x", "t" }) + if (hash.Compute(candidate, 936) == prefix) + return candidate + index.ToString(); + throw new NotSupportedException($"Unknown original external action prefix {prefix:X8}."); + } + + public override void Step(float time, float delta) + { + LocalTime = time - Birth; + AdvanceTasks(0, delta, false); + } + + internal void StepSilently(float time, float delta) + { + LocalTime = time - Birth; + AdvanceTasks(0, delta, false, silent: true); + } + + private void AdvanceTasks(int first, float delta, bool alive, bool silent = false) + { + for (int index = first; index < Tasks.Length; index++) + { + EffectTaskClock clock = Clocks[index]; + if (clock.Tick(LocalTime, delta, Tasks[index], out float activeDelta)) + { + if (!silent) + Apply(Tasks[index], clock, activeDelta); + // A seek cannot capture the external actor's original position or action. + else if (_silentActions != null && clock.StartedNow) + _silentActions[index] = true; + } + if (!silent && _context.IsModalPresentationRunning) + { + _pendingMovieTask = index; + _pendingDelta = delta; + _aliveBeforeMovie = alive; + Alive = true; + return; + } + alive |= !Clocks[index].Finished; + } + Alive = alive; + if (!Alive) + ReleaseControl(); + } + + internal bool ResumeModal() + { + if (_pendingMovieTask < 0) + return true; + if (_context.IsModalPresentationRunning) + return false; + int index = _pendingMovieTask; + if (_movies[index]?.Finished == true) + Clocks[index].Complete(); + _pendingMovieTask = -1; + AdvanceTasks(index + 1, _pendingDelta, _aliveBeforeMovie || !Clocks[index].Finished); + return _pendingMovieTask < 0; + } + + private void ReleaseControl() + { + foreach (IEffectActor actor in _controlledActors.Values) + { + actor.SetExternalTask(false, this); + } + _controlledActors.Clear(); + } + + public override void Dispose() + { + ReleaseControl(); + if (_timeControl != null) + foreach (EffectTaskClock clock in Clocks) + _timeControl.ClearTimeScale(clock); + if (_cameraTask is { Finished: false }) + _context.Camera?.StopList(); + foreach (IEffectMovie movie in _movies) + movie?.Dispose(); + base.Dispose(); + } + + public override void Render(Camera camera) + { + } + } +} diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleControlNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleControlNode.cs.meta new file mode 100644 index 00000000..46386043 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleControlNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e2803935aba14506a94c659bc5571e9b diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleEffectContext.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleEffectContext.cs new file mode 100644 index 00000000..103e0d1e --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleEffectContext.cs @@ -0,0 +1,87 @@ +// ------------------------------------------------------------------------ +// 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 UnityEngine; + + public interface IEffectActor + { + Vector3 Position + { + get; set; + } + + float FacingDegrees + { + get; set; + } + + float Blend + { + get; set; + } + + bool ActionOver + { + get; + } + + void SetExternalTask(bool controlled, object owner); + + void SetAction(string action); + + void SetLongBlade(bool enabled); + + void SetWeapons(float left, float right); + } + + public interface IEffectCamera + { + void StopList(); + + bool StartList(int index); + + void SetQuake(float amplitude, float frequency, float decay); + } + + public interface IEffectMovie : System.IDisposable + { + bool Finished + { + get; + } + } + + public interface IEffectTimeControl + { + void SetTimeScale(object owner, float scale); + + void ClearTimeScale(object owner); + } + + // A scene viewer has no combat role pool, camera controller or modal movie + // loop. These capabilities must be supplied explicitly by the battle owner. + public interface IBattleEffectContext + { + // GT util::Rand belongs to the effect manager. It is independent of + // CUtil::Rand used by combat rules and of the engine particle streams. + int NextEffectRandom(); + + IEffectActor Actor(int nativeIndex, uint modelCrc = 0); + + IEffectCamera Camera + { + get; + } + + bool IsModalPresentationRunning + { + get; + } + + IEffectMovie PlayMovie(string originalPath); + } +} diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleEffectContext.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleEffectContext.cs.meta new file mode 100644 index 00000000..c6e45ce9 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/BattleEffectContext.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 36a80e309c344157bc7d5fd066b3d238 diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/EffectMeshBuffer.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectMeshBuffer.cs similarity index 96% rename from Assets/Scripts/Pal3.Game/Effect/Original/EffectMeshBuffer.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/EffectMeshBuffer.cs index 2cbf7e11..c9150642 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/EffectMeshBuffer.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectMeshBuffer.cs @@ -3,7 +3,7 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using System; using System.Collections.Generic; @@ -81,6 +81,6 @@ namespace Pal3.Game.Effect.Original _mesh.SetTriangles(_indices, 0, true); } - public void Dispose() => OriginalEffectResources.Destroy(_mesh); + public void Dispose() => EffectResources.Destroy(_mesh); } } diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectMeshBuffer.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectMeshBuffer.cs.meta new file mode 100644 index 00000000..869445f3 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectMeshBuffer.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4daa7814a3fa8493293fc2ad9eb6fecc diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectNode.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectNode.cs similarity index 80% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectNode.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/EffectNode.cs index 8ba1bf25..3e8a5c05 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectNode.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectNode.cs @@ -3,14 +3,15 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using System; using Core.DataReader.Data; + using Rendering.Native; using UnityEngine; using Color = UnityEngine.Color; - internal sealed class OriginalTaskClock + internal sealed class EffectTaskClock { private bool _initialized, _finished; private float _initAt; @@ -24,6 +25,12 @@ namespace Pal3.Game.Effect.Original public bool Finished => _finished; + public bool NativeComparison; + + public void Complete() => _finished = true; + + public void KeepRunning() => _finished = false; + public bool Tick(float time, float dt, EffectTask task, out float elapsed) { StartedNow = false; @@ -49,17 +56,17 @@ namespace Pal3.Game.Effect.Original StartedNow = true; } elapsed = dt - Mathf.Max(0, time - StartedAt - task.Duration); - _finished = time - StartedAt + 0.000001f >= task.Duration; + _finished = NativeComparison ? (double)time - StartedAt >= task.Duration : time - StartedAt + 0.000001f >= task.Duration; return true; } } - internal abstract class OriginalEffectNode : IDisposable + internal abstract class EffectNode : IDisposable { protected readonly GameObject Root; protected readonly EffectDefinition Definition; protected readonly EffectTask[] Tasks; - protected readonly OriginalTaskClock[] Clocks; + protected readonly EffectTaskClock[] Clocks; protected readonly float Birth; protected Vector3 Position, Rotation, Orbit, Scale; protected Color Tint; @@ -69,7 +76,27 @@ namespace Pal3.Game.Effect.Original public virtual bool Alive { get; protected set; } = true; public virtual int QuadCount => 0; - protected OriginalEffectNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth) + internal void UseNativeClockComparisons() + { + foreach (EffectTaskClock clock in Clocks) + clock.NativeComparison = true; + } + + private int? _renderOrder; + + internal void SetRenderOrder(int order) + { + _renderOrder = order; + ApplyRenderOrder(); + } + + internal void ApplyRenderOrder() + { + if (_renderOrder.HasValue) + GameBoxBattleRenderPhase.Apply(Root, _renderOrder.Value); + } + + protected EffectNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth) { Root = root; Definition = d; @@ -79,9 +106,9 @@ namespace Pal3.Game.Effect.Original Rotation = new Vector3(d.InitXRotation, d.InitYRotation, d.InitZRotation); Scale = Vector3.one * d.InitSize; Tint = PackedColor(d.InitColor); - Clocks = new OriginalTaskClock[Tasks.Length]; + Clocks = new EffectTaskClock[Tasks.Length]; for (int i = 0; i < Clocks.Length; i++) - Clocks[i] = new OriginalTaskClock(); + Clocks[i] = new EffectTaskClock(); } public virtual void Step(float time, float dt) @@ -100,7 +127,7 @@ namespace Pal3.Game.Effect.Original Alive = alive; } - protected virtual void Apply(EffectTask t, OriginalTaskClock clock, float dt) + protected virtual void Apply(EffectTask t, EffectTaskClock clock, float dt) { Position += new Vector3(t.SpeedX, t.SpeedY, t.SpeedZ) * dt; ApplyRotationAndStretch(t, dt); @@ -122,7 +149,7 @@ namespace Pal3.Game.Effect.Original { if (Root != null) Root.SetActive(false); - OriginalEffectResources.Destroy(Root); + EffectResources.Destroy(Root); } internal static Vector3 UnityPosition(Vector3 v) => new(-v.x / 20, v.y / 20, v.z / 20); @@ -150,13 +177,13 @@ namespace Pal3.Game.Effect.Original } } - internal sealed class OriginalControlNode : OriginalEffectNode + internal sealed class ControlEffectNode : EffectNode { - private readonly OriginalEffectPlayer _player; + private readonly EffectPlayer _player; private readonly string _kind; private readonly byte[] _played; - public OriginalControlNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectPlayer player, string kind) + public ControlEffectNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, EffectPlayer player, string kind) : base(root, d, tasks, origin, birth) { _player = player; @@ -164,7 +191,7 @@ namespace Pal3.Game.Effect.Original _played = new byte[Tasks.Length]; } - protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt) + protected override void Apply(EffectTask t, EffectTaskClock clock, float dt) { if (_kind == "callback") { diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectNode.cs.meta new file mode 100644 index 00000000..d1d5bd99 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 03437bbaa78854faca572e1b314a630a diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectOverrides.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectOverrides.cs similarity index 83% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectOverrides.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/EffectOverrides.cs index 543546b8..8e4c0d9d 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectOverrides.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectOverrides.cs @@ -3,7 +3,7 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using System; using System.Collections.Generic; @@ -13,7 +13,7 @@ namespace Pal3.Game.Effect.Original using UnityEngine; [Serializable] - public sealed class OriginalEffectObjectOverride + public sealed class EffectObjectOverride { public int GroupId, ObjectIndex; public EffectDefinition Definition; @@ -22,7 +22,7 @@ namespace Pal3.Game.Effect.Original } [Serializable] - public sealed class OriginalParticleCurveOverride + public sealed class ParticleCurveOverride { public string File, Parameter; public bool Emitter; @@ -30,22 +30,23 @@ namespace Pal3.Game.Effect.Original public AnimationCurve[] Channels; } - [CreateAssetMenu(menuName = "PAL3/Original effect overrides")] - public sealed class OriginalEffectOverrides : ScriptableObject + [CreateAssetMenu(menuName = "PAL3/Effect Overrides")] + [UnityEngine.Scripting.APIUpdating.MovedFrom(true, "Pal3.Game.Effect.Original", "Pal3.Game", "OriginalEffectOverrides")] + public sealed class EffectOverrides : ScriptableObject { public int Version = 1; - public List Objects = new(); - public List ParticleCurves = new(); + public List Objects = new(); + public List ParticleCurves = new(); - public OriginalEffectObjectOverride Find(int group, int index) => + public EffectObjectOverride Find(int group, int index) => Objects.Find(o => o.GroupId == group && o.ObjectIndex == index); - internal static bool Resolve(OriginalEffectOverrides edits, int group, int index, + internal static bool Resolve(EffectOverrides edits, int group, int index, ref EffectDefinition definition, ref EffectTask[] tasks) { if (edits != null && edits.Version != 1) throw new NotSupportedException($"Unknown original effect override version {edits.Version}"); - OriginalEffectObjectOverride edit = edits?.Find(group, index); + EffectObjectOverride edit = edits?.Find(group, index); if (edit?.Hidden == true) return false; if (edit != null) @@ -81,13 +82,13 @@ namespace Pal3.Game.Effect.Original } public bool HasParticleEdits(string file) => ParticleCurves.Exists(c => - string.Equals(OriginalEffectResources.Normalize(c.File), OriginalEffectResources.Normalize(file), StringComparison.OrdinalIgnoreCase)); + string.Equals(EffectResources.Normalize(c.File), EffectResources.Normalize(file), StringComparison.OrdinalIgnoreCase)); public void ApplyParticle(string path, ParticleFile file) { - foreach (OriginalParticleCurveOverride edit in ParticleCurves) + foreach (ParticleCurveOverride edit in ParticleCurves) { - if (!string.Equals(OriginalEffectResources.Normalize(edit.File), OriginalEffectResources.Normalize(path), StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(EffectResources.Normalize(edit.File), EffectResources.Normalize(path), StringComparison.OrdinalIgnoreCase)) continue; ParticleCurve curve = FindCurve(file, edit.Emitter, edit.Index, edit.Parameter); if (edit.Channels == null || edit.Channels.Length != curve.Channels || edit.Channels.Any(c => c == null)) diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectOverrides.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectOverrides.cs.meta new file mode 100644 index 00000000..2175a270 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectOverrides.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3a0f5edeb37f04ad28e5e2ed9000e2c5 diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectPlayer.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectPlayer.cs new file mode 100644 index 00000000..36ca0104 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectPlayer.cs @@ -0,0 +1,426 @@ +// ------------------------------------------------------------------------ +// 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 Core.DataReader.Data; + using Rendering.Native; + using UnityEngine; + + // One simulation serves both clocks: real frame time in game, and fixed + // steps for editor playback/seeking. Rendering never advances the clock. + [UnityEngine.Scripting.APIUpdating.MovedFrom(true, "Pal3.Game.Effect.Original", "Pal3.Game", "OriginalEffectPlayer")] + public sealed class EffectPlayer : MonoBehaviour, IDisposable + { + public const float FixedStep = 0.02f; + private readonly List _nodes = new(); + private EffectResources _resources; + private EffectOverrides _overrides; + private int _groupId; + private double _time; + private uint _seed; + private uint _spawnSequence; + private float _accumulator; + private Action _sound; + private IBattleEffectContext _battleContext; + private GameBoxNativeLighting _nativeLighting; + private bool _disposed, _suppressEvents; + private float _lastRepeat; + private double _clockOrigin, _timeControlElapsed, _fallbackElapsed, _battleAbsoluteTime = double.NaN; + private int _pendingNode = -1, _pendingNodeCount; + private float _pendingDelta; + private bool _pendingAlive; + + public float Time => (float)_time; + public bool AutoAdvance { get; set; } = true; + + public bool Paused + { + get; set; + } + + public float Speed { get; set; } = 1; + + public bool Loop + { + get; set; + } + + public bool DestroyOnComplete + { + get; set; + } + + public float RepeatInterval + { + get; set; + } + + public int NodeCount => _nodes.Count; + + public int QuadCount + { + get; private set; + } + + public bool IsAlive + { + get; private set; + } + + public string Error + { + get; private set; + } + + public void Initialize(EffectResources resources, int groupId, uint seed = 1, + EffectOverrides overrides = null, Action sound = null, IBattleEffectContext battleContext = null, double clockOrigin = 0, + GameBoxNativeLighting nativeLighting = null) + { + if (_disposed) + throw new ObjectDisposedException(nameof(EffectPlayer)); + if (overrides != null && overrides.Version != 1) + throw new NotSupportedException($"Unknown original effect override version {overrides.Version}"); + _resources = resources; + _groupId = groupId; + _seed = seed == 0 ? 1 : seed; + _overrides = overrides; + _sound = sound; + _battleContext = battleContext; + _nativeLighting = nativeLighting; + _clockOrigin = clockOrigin; + ResetSimulation(); + } + + private void ResetSimulation(bool resetRandom = true) + { + ClearNodes(); + _pendingNode = -1; + _time = _clockOrigin; + _battleAbsoluteTime = double.NaN; + _timeControlElapsed = _fallbackElapsed = 0; + _accumulator = 0; + _lastRepeat = 0; + Error = null; + if (resetRandom) + _spawnSequence = 0; + try + { + AddGroup(_groupId, Vector3.zero); + IsAlive = _nodes.Count > 0; + } + catch (Exception ex) + { + Error = ex.Message; + ClearNodes(); + IsAlive = false; + } + } + + internal void AddGroup(int groupId, Vector3 position) + { + if (groupId < 0 || groupId >= _resources.Definitions.Groups.Length) + throw new ArgumentOutOfRangeException(nameof(groupId)); + EffectGroup group = _resources.Definitions.Groups[groupId]; + for (int i = 0; i < group.Objects.Length; i++) + { + EffectGroupObject obj = group.Objects[i]; + _resources.Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d); + EffectTask[] tasks = obj.Tasks; + if (!EffectOverrides.Resolve(_overrides, groupId, i, ref d, ref tasks)) + continue; + if (_nodes.Count >= 2048) + throw new InvalidOperationException("Original effect object limit (2048) reached"); + obj = new EffectGroupObject { TypeCrc = obj.TypeCrc, Tasks = tasks }; + var root = new GameObject($"{groupId}:{i} {d.TypeName}") { hideFlags = HideFlags.DontSave, layer = gameObject.layer }; + root.transform.SetParent(transform, false); + EffectNode node = null; + try + { + string kind = EffectClass.Name(d.ClassNameCrc); + uint seed = _seed + _spawnSequence++ * 7919 + (uint)(groupId * 104729 + i); + node = kind switch + { + "action" or "camera" or "quake" or "bink" or "time" when _battleContext != null => new BattleControlNode(root, d, obj.Tasks, position, Time, _battleContext, kind, _resources.GameVariant == "PAL3A"), + "callback" or "audio" => new ControlEffectNode(root, d, obj.Tasks, position, Time, this, kind), + "quad" => new QuadNode(root, d, obj.Tasks, position, Time, _resources, _battleContext != null), + "S-Particle" => new SparNode(root, d, obj.Tasks, position, Time, _resources, seed), + "particle" => new ParticleNode(root, d, obj.Tasks, position, Time, _resources, seed, _overrides), + "cylinder" or "grid" => new GeometryNode(root, d, obj.Tasks, position, Time, _resources, kind, _battleContext != null), + "meteor" or "shock" => new TrailNode(root, d, obj.Tasks, position, Time, _resources, kind, seed, _battleContext != null, _battleContext == null ? null : _battleContext.NextEffectRandom), + "model" => new ModelNode(root, d, obj.Tasks, position, Time, _resources, _nativeLighting), + "explosive" => new ExplosiveNode(root, d, obj.Tasks, position, Time, _resources, seed, _battleContext != null, _battleContext == null ? null : _battleContext.NextEffectRandom), + _ => throw new NotSupportedException($"Original effect class {kind}: {d.TypeName}"), + }; + if (_battleContext != null) + { + node.UseNativeClockComparisons(); + node.SetRenderOrder(GameBoxBattleRenderOrder.Effect(_resources.GameVariant == "PAL3A", kind == "model")); + } + _nodes.Add(node); + } + catch + { + node?.Dispose(); + EffectResources.Destroy(root); + throw; + } + } + } + + internal void Sound(string name) + { + if (!_suppressEvents) + _sound?.Invoke(name); + } + + public void Advance(float delta) + { + float elapsed = ScaledDelta(delta); + if (elapsed <= 0) + return; + _accumulator += elapsed; + while (_accumulator + 0.000001f >= FixedStep) + { + _accumulator -= FixedStep; + if (!SimulateStep(FixedStep)) + break; + } + } + + // Battle managers receive the float projection of the system's double + // clock. Keep the scene viewer's delta-driven API independent. + public void AdvanceTo(double managerTime, double absoluteTime = double.NaN) + { + if (_disposed || Paused || Error != null || _pendingNode >= 0 || !float.IsFinite((float)managerTime)) + return; + float projected = (float)managerTime; + float delta = projected - (float)_time; + bool absoluteAdvanced = double.IsFinite(absoluteTime) && + (!double.IsFinite(_battleAbsoluteTime) || absoluteTime > _battleAbsoluteTime); + if (delta < 0 || delta == 0 && !absoluteAdvanced) + return; + _time = projected; + if (absoluteAdvanced) + { + // Account for fallback frames already counted since the last real sample, + // then anchor the next external frame to this actual timestamp. + double elapsed = double.IsFinite(_battleAbsoluteTime) ? absoluteTime - _battleAbsoluteTime : delta; + double remaining = elapsed - _fallbackElapsed; + _timeControlElapsed += remaining < -0.000001 ? delta : Math.Max(0, remaining); + _battleAbsoluteTime = absoluteTime; + _fallbackElapsed = 0; + } + else if (!double.IsFinite(absoluteTime)) + AdvanceFallbackClock(delta); + try + { + AdvanceNodes(0, _nodes.Count, delta, false); + } + catch (Exception error) + { + Error = error.ToString(); + ClearNodes(); + IsAlive = false; + Debug.LogException(error); + } + } + + public void AdvanceFrame(float delta) + { + float elapsed = ScaledDelta(delta); + if (elapsed <= 0) + return; + elapsed += _accumulator; + _accumulator = 0; + SimulateStep(elapsed); + } + + private float ScaledDelta(float delta) + { + if (_disposed || Paused || Error != null || _pendingNode >= 0 || delta <= 0 || !float.IsFinite(delta)) + return 0; + float elapsed = delta * (float.IsFinite(Speed) ? Mathf.Clamp(Speed, 0, 16) : 1); + return float.IsFinite(elapsed) ? elapsed : 0; + } + + private bool SimulateStep(float delta) + { + _time += delta; + AdvanceFallbackClock(delta); + try + { + return AdvanceNodes(0, _nodes.Count, delta, false); + } + catch (Exception ex) + { + Error = ex.ToString(); + ClearNodes(); + IsAlive = false; + Debug.LogException(ex); + return false; + } + } + + private void AdvanceFallbackClock(float delta) + { + _timeControlElapsed += delta; + if (double.IsFinite(_battleAbsoluteTime)) + _fallbackElapsed += delta; + } + + private bool AdvanceNodes(int first, int count, float delta, bool alive) + { + for (int index = first; index < count; index++) + { + EffectNode node = _nodes[index]; + if (_suppressEvents && node is BattleControlNode silentControl) + { + if (delta > 0) + silentControl.StepSilently(Time, delta); + } + else if (node is BattleControlNode { ControlsTime: true } timeControl) + timeControl.StepTimeControl(Time, delta, _timeControlElapsed); + else if (delta > 0) + node.Step(Time, delta); + if (!_suppressEvents && _battleContext?.IsModalPresentationRunning == true) + { + _pendingNode = index; + _pendingNodeCount = count; + _pendingDelta = delta; + _pendingAlive = alive; + IsAlive = true; + return false; + } + alive |= _nodes[index].Alive; + } + IsAlive = alive || _nodes.Count > count; + for (int index = _nodes.Count - 1; index >= 0; index--) + if (!_nodes[index].Alive) + { + _nodes[index].Dispose(); + _nodes.RemoveAt(index); + } + if (Loop && RepeatInterval > 0 && Time - _lastRepeat >= RepeatInterval) + { + AddGroup(_groupId, Vector3.zero); + _lastRepeat = Time; + IsAlive = true; + } + if (Loop && !IsAlive && RepeatInterval <= 0) + { + ResetSimulation(false); + return false; + } + return true; + } + + public bool ResumeBattleStep() + { + if (_pendingNode < 0) + return true; + if (_battleContext?.IsModalPresentationRunning == true) + return false; + try + { + int index = _pendingNode; + if (_nodes[index] is BattleControlNode control && !control.ResumeModal()) + return false; + _pendingNode = -1; + return AdvanceNodes(index + 1, _pendingNodeCount, _pendingDelta, _pendingAlive || _nodes[index].Alive); + } + catch (Exception ex) + { + Error = ex.ToString(); + ClearNodes(); + IsAlive = false; + return false; + } + } + + public void Seek(float time) + { + if (_disposed) + return; + time = Mathf.Clamp(float.IsFinite(time) ? time : 0, 0, 600); + bool paused = Paused, loop = Loop; + float speed = Speed; + ResetSimulation(); + Paused = false; + Loop = false; + Speed = 1; + _suppressEvents = true; + try + { + Advance(time); + } + finally + { + _suppressEvents = false; + Paused = paused; + Loop = loop; + Speed = speed; + } + } + + public void Render(Camera camera) + { + QuadCount = 0; + foreach (EffectNode node in _nodes) + { + node.Render(camera); + node.ApplyRenderOrder(); + QuadCount += node.QuadCount; + } + } + + private void Update() + { + if (!AutoAdvance) + return; + AdvanceFrame(UnityEngine.Time.deltaTime); + if (DestroyOnComplete && !Loop && !IsAlive && Time > 0) + EffectResources.Destroy(gameObject); + } + + private void LateUpdate() + { + if (AutoAdvance) + Render(Camera.main); + } + + private void ClearNodes() + { + _pendingNode = -1; + foreach (EffectNode node in _nodes) + node.Dispose(); + _nodes.Clear(); + QuadCount = 0; + } + + // Editor owners must dispose explicitly: ordinary MonoBehaviour destroy + // callbacks are not guaranteed for objects used outside Play Mode. + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + AutoAdvance = false; + IsAlive = false; + _pendingNode = -1; + _accumulator = 0; + ClearNodes(); + _resources = null; + _overrides = null; + _sound = null; + _battleContext = null; + _nativeLighting = null; + } + + private void OnDestroy() => Dispose(); + } +} diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectPlayer.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectPlayer.cs.meta new file mode 100644 index 00000000..46603b55 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectPlayer.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7b4e14dc881ee4e348d1125f142c9dc4 diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectResources.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectResources.cs similarity index 74% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectResources.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/EffectResources.cs index 26f6340b..f89dfca9 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalEffectResources.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectResources.cs @@ -3,7 +3,7 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using System; using System.Collections.Generic; @@ -19,9 +19,10 @@ namespace Pal3.Game.Effect.Original using Engine.Core.Implementation; using Engine.Core.Abstraction; using UnityEngine; + using Rendering.Native; using UnityEngine.Rendering; - public sealed class OriginalEffectResources : IDisposable + public sealed class EffectResources : IDisposable { private readonly ICpkFileSystem _fileSystem; private readonly int _codepage; @@ -35,8 +36,14 @@ namespace Pal3.Game.Effect.Original private readonly Dictionary _models = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<(string, int, int, bool, int, int), Material> _materials = new(); private readonly Dictionary _diagnostics = new(); + private readonly HashSet _missingBattleTextures = new(StringComparer.OrdinalIgnoreCase); + + public IReadOnlyCollection MissingBattleTextures => _missingBattleTextures; + + private readonly Dictionary _battleDiagnostics = new(); + private readonly Dictionary _battleOverrideDiagnostics = new(); private readonly Dictionary _overrideDiagnostics = new(); - private OriginalEffectOverrides _cachedOverrides; + private EffectOverrides _cachedOverrides; private string _cachedOverridesJson; private EffectDefinitionFile _definitions; @@ -46,7 +53,7 @@ namespace Pal3.Game.Effect.Original public string OverridesPath => $"Effects/{GameVariant}Overrides"; - public OriginalEffectResources(ICpkFileSystem fileSystem, int codepage = 936) + public EffectResources(ICpkFileSystem fileSystem, int codepage = 936) { _fileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem)); _codepage = codepage; @@ -66,10 +73,10 @@ namespace Pal3.Game.Effect.Original private sealed class ModelTextures : ITextureResourceProvider { - private readonly OriginalEffectResources _owner; + private readonly EffectResources _owner; private readonly string _file; - public ModelTextures(OriginalEffectResources owner, string file) + public ModelTextures(EffectResources owner, string file) { _owner = owner; _file = file; @@ -86,7 +93,7 @@ namespace Pal3.Game.Effect.Original } } - public ParticleFile Particle(string path, OriginalEffectOverrides edits = null) + public ParticleFile Particle(string path, EffectOverrides edits = null) { path = Normalize(path); if (!_particles.TryGetValue(path, out ParticleFile file)) @@ -109,7 +116,7 @@ namespace Pal3.Game.Effect.Original return file; } - private void RefreshOverrideCache(OriginalEffectOverrides edits) + 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 @@ -120,10 +127,23 @@ namespace Pal3.Game.Effect.Original _cachedOverrides = edits; _cachedOverridesJson = json; _overrideDiagnostics.Clear(); + _battleOverrideDiagnostics.Clear(); _overrideParticles.Clear(); } - public ParticleShapeFile Shape(string path) + 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())); @@ -203,6 +223,22 @@ namespace Pal3.Game.Effect.Original 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 { @@ -217,9 +253,9 @@ namespace Pal3.Game.Effect.Original 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/OriginalEffect"); + Shader shader = Shader.Find("Pal3/Effect"); if (shader == null || !shader.isSupported) - throw new InvalidOperationException("OriginalEffect URP shader is unavailable"); + throw new InvalidOperationException("Effect URP shader is unavailable"); var material = new Material(shader) { name = $"Original {texture}", hideFlags = HideFlags.DontSave }; try { @@ -240,11 +276,11 @@ namespace Pal3.Game.Effect.Original } // Validate the complete callback closure before choosing this backend. - public string[] Diagnose(int groupId, OriginalEffectOverrides edits = null) + public string[] Diagnose(int groupId, EffectOverrides edits = null, bool battleContext = false) { if (edits != null) RefreshOverrideCache(edits); - Dictionary cache = edits == null ? _diagnostics : _overrideDiagnostics; + Dictionary cache = battleContext ? edits == null ? _battleDiagnostics : _battleOverrideDiagnostics : edits == null ? _diagnostics : _overrideDiagnostics; if (cache.TryGetValue(groupId, out string[] cached)) return cached; var errors = new List(); @@ -285,7 +321,7 @@ namespace Pal3.Game.Effect.Original try { EffectTask[] tasks = obj.Tasks; - if (!OriginalEffectOverrides.Resolve(edits, id, index, ref d, ref tasks)) + if (!EffectOverrides.Resolve(edits, id, index, ref d, ref tasks)) continue; string kind = EffectClass.Name(d.ClassNameCrc); switch (kind) @@ -297,11 +333,24 @@ namespace Pal3.Game.Effect.Original 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) { - OriginalSparEmitter.Validate(sg); + SparEmitter.Validate(sg); ResolveTexture(RelativeTo(d.ParticleFileName, sg.Texture)); } break; @@ -311,7 +360,7 @@ namespace Pal3.Game.Effect.Original ResolveTexture(RelativeTo(d.ParticleFileName, pd.Texture)); foreach (ParticleEmitter e in p.Emitters) if (e.Shape == 2) - Shape(RelativeTo(d.ParticleFileName, e.ShapePath)); + ParticleShape(d.ParticleFileName, e.ShapePath); break; case "quad": case "cylinder": @@ -319,7 +368,11 @@ namespace Pal3.Game.Effect.Original case "shock": case "grid": case "explosive": - ResolveTexture(d.TextureName); + try + { + ResolveTexture(d.TextureName); + } + catch (FileNotFoundException) when (battleContext) { _missingBattleTextures.Add(Normalize(d.TextureName)); } break; case "model": if (d.TextureName.EndsWith(".pol", StringComparison.OrdinalIgnoreCase)) @@ -357,7 +410,22 @@ namespace Pal3.Game.Effect.Original return result; } - public IEnumerable Preload(int groupId, OriginalEffectOverrides edits = null) + public IEnumerable 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 Preload(int groupId, EffectOverrides edits = null, bool battleContext = false) { var seen = new HashSet(); var pending = new Stack(); @@ -373,7 +441,7 @@ namespace Pal3.Game.Effect.Original EffectGroupObject obj = objects[index]; Definitions.TryGetType(obj.TypeCrc, out EffectDefinition d); EffectTask[] tasks = obj.Tasks; - if (!OriginalEffectOverrides.Resolve(edits, id, index, ref d, ref tasks)) + if (!EffectOverrides.Resolve(edits, id, index, ref d, ref tasks)) continue; string kind = EffectClass.Name(d.ClassNameCrc); if (kind == "callback") @@ -386,7 +454,9 @@ namespace Pal3.Game.Effect.Original else if (kind == "S-Particle") foreach (SparGroup group in Spar(d.ParticleFileName).Groups) Texture(RelativeTo(d.ParticleFileName, group.Texture)); - else if (kind != "audio" && kind != "model") + 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; } @@ -403,20 +473,27 @@ namespace Pal3.Game.Effect.Original continue; foreach (Renderer renderer in root.GetComponentsInChildren(true)) foreach (Material material in renderer.sharedMaterials) - { - if (material == null) - continue; - materials.Add(material); - // POL materials can also hold a baked lightmap. Every - // referenced texture must survive a scene-cache trim. - foreach (int property in material.GetTexturePropertyNameIDs()) - { - Texture texture = material.GetTexture(property); - if (texture != null) - textures.Add(texture); - } - } + 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(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]); @@ -446,6 +523,9 @@ namespace Pal3.Game.Effect.Original _sparFiles.Clear(); _diagnostics.Clear(); _overrideDiagnostics.Clear(); + _battleOverrideDiagnostics.Clear(); + _battleDiagnostics.Clear(); + _missingBattleTextures.Clear(); _cachedOverrides = null; _cachedOverridesJson = null; } diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectResources.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectResources.cs.meta new file mode 100644 index 00000000..beecf30d --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/EffectResources.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6df74732b3a2d44b69e9ed674b10f621 diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalExplosiveNode.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/ExplosiveNode.cs similarity index 86% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalExplosiveNode.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/ExplosiveNode.cs index 75d69518..a109649e 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalExplosiveNode.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/ExplosiveNode.cs @@ -3,33 +3,35 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using System; using Core.DataReader.Data; using UnityEngine; // CEffExplosive: subdivided plane, per-fragment velocity and spin. - internal sealed class OriginalExplosiveNode : OriginalEffectNode + internal sealed class ExplosiveNode : EffectNode { private readonly EffectMeshBuffer _mesh; private readonly Vector3[][] _corners; private readonly Vector3[] _velocity, _spin; private readonly bool[] _exploded; private readonly System.Random _random; + private readonly Func _effectRandom; private readonly int _columns, _rows; public override int QuadCount => _mesh.QuadCount; - public OriginalExplosiveNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectResources resources, uint seed) + public ExplosiveNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, EffectResources resources, uint seed, bool battleContext = false, Func effectRandom = null) : base(root, d, tasks, origin, birth) { _columns = (int)d.RotationAngle; _rows = (int)d.DivisionCount; if (_columns < 1 || _rows < 1 || (long)_columns * _rows >= 2501) throw new InvalidOperationException("Invalid original explosive subdivisions"); - _mesh = new EffectMeshBuffer(root, resources.Material(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored)); + _mesh = new EffectMeshBuffer(root, resources.EffectTextureMaterial(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored, battleContext)); _random = new System.Random(unchecked((int)seed)); + _effectRandom = effectRandom; _corners = new Vector3[_columns * _rows][]; _velocity = new Vector3[_corners.Length]; _spin = new Vector3[_corners.Length]; @@ -60,17 +62,17 @@ namespace Pal3.Game.Effect.Original { int power = Mathf.Max(1, Mathf.RoundToInt(Mathf.Max(minimum, maximum - Mathf.Abs(row - _columns / 2) * Mathf.Abs(column - _rows / 2) * Mathf.Max(0, Definition.TopRiseSpeed)))); - float Component() => _random.Next(power) - power / 2; + float Component() => (_effectRandom == null ? _random.Next(power) : _effectRandom() % power) - power / 2; Vector3 velocity = new(Component(), Component(), Component()); if (velocity.magnitude < minimum) velocity = velocity.normalized * minimum; _velocity[count] = velocity + new Vector3(Definition.TopRadiusIncreaseSpeed, Definition.BottomRadiusIncreaseSpeed, Definition.TextureRepeat); - float Spin() => (_random.Next(160) - 80) * 16f; + float Spin() => ((_effectRandom == null ? _random.Next(160) : _effectRandom() % 160) - 80) * 16f; _spin[count] = new Vector3(Spin(), Spin(), Spin()); } } - protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt) + protected override void Apply(EffectTask t, EffectTaskClock clock, float dt) { Position += new Vector3(t.SpeedX, t.SpeedY, t.SpeedZ) * dt; Rotation += new Vector3(t.RotAxisX, t.RotAxisY, t.RotAxisZ) * dt; diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalExplosiveNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/ExplosiveNode.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalExplosiveNode.cs.meta rename to Assets/Scripts/Pal3.Game/Effect/Runtime/ExplosiveNode.cs.meta diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalGeometryNode.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/GeometryNode.cs similarity index 91% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalGeometryNode.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/GeometryNode.cs index 84dc1942..c17e5af5 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalGeometryNode.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/GeometryNode.cs @@ -3,12 +3,12 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using Core.DataReader.Data; using UnityEngine; - internal sealed class OriginalGeometryNode : OriginalEffectNode + internal sealed class GeometryNode : EffectNode { private readonly EffectMeshBuffer _mesh; private readonly string _kind; @@ -17,12 +17,12 @@ namespace Pal3.Game.Effect.Original public override int QuadCount => _mesh.QuadCount; - public OriginalGeometryNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectResources resources, string kind) + public GeometryNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, EffectResources resources, string kind, bool battleContext = false) : base(root, d, tasks, origin, birth) { _kind = kind; Scale = new Vector3(d.InitSize, 1, d.InitSize); - _mesh = new EffectMeshBuffer(root, resources.Material(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored)); + _mesh = new EffectMeshBuffer(root, resources.EffectTextureMaterial(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored, battleContext)); if (kind == "cylinder") { _columns = Mathf.Clamp(Mathf.RoundToInt(d.DivisionCount), 1, 4096); @@ -49,7 +49,7 @@ namespace Pal3.Game.Effect.Original } } - protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt) + protected override void Apply(EffectTask t, EffectTaskClock clock, float dt) { base.Apply(t, clock, dt); if (_kind == "cylinder") diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/GeometryNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/GeometryNode.cs.meta new file mode 100644 index 00000000..99c009c5 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/GeometryNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b4096b3ce200a447ba269be4a95c0f5a diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalModelNode.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/ModelNode.cs similarity index 58% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalModelNode.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/ModelNode.cs index cfa8f1d4..af4690ed 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalModelNode.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/ModelNode.cs @@ -3,40 +3,37 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using System; using System.Collections.Generic; - using System.Linq; - using Core.DataReader.Pol; - using Engine.Core.Abstraction; - using Engine.Extensions; using UnityEngine.Rendering; using Core.DataReader.Data; using Engine.Core.Implementation; using Rendering.Material; using Rendering.Renderer; + using Rendering.Native; using UnityEngine; - internal sealed class OriginalModelNode : OriginalEffectNode + internal sealed class ModelNode : EffectNode { private const float ReferenceFramesPerSecond = 60f; private readonly CvdModelRenderer _model; + private readonly PolyModelRenderer _poly; private readonly GameMaterialManager _materials; private readonly Renderer[] _renderers; private float _animationStart; private float _opacity = 1; - private readonly List _polMaterials = new(); - private readonly List _meshes = new(); private readonly List _opacityMaterials = new(); private readonly MaterialPropertyBlock _properties = new(); - public OriginalModelNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectResources resources) + public ModelNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, EffectResources resources, + GameBoxNativeLighting nativeLighting = null) : base(root, d, tasks, origin, birth) { // CEffModel ignores the flexeff tint/additive/depth flags: the model // owns those settings. SetBlend(ALPHA) overrides them only for fades. - _materials = new GameMaterialManager(new UnityMaterialFactory(), false); + _materials = new GameMaterialManager(new UnityMaterialFactory(), false, nativeLighting); try { if (d.TextureName.EndsWith(".cvd", StringComparison.OrdinalIgnoreCase)) @@ -45,72 +42,47 @@ namespace Pal3.Game.Effect.Original _model.Init(resources.Model(d.TextureName), resources.ModelTextureProvider(d.TextureName), _materials); } else if (d.TextureName.EndsWith(".pol", StringComparison.OrdinalIgnoreCase)) - RenderPol(root, d.TextureName, resources); + { + _poly = root.AddComponent(); + _poly.Render(resources.PolModel(d.TextureName), resources.ModelTextureProvider(d.TextureName), _materials, + isStaticObject: false, textureFactory: new UnityTextureFactory(), animateWater: false, + modelMode: PolModelMode.Authored); + } else throw new NotSupportedException($"Unsupported original model {d.TextureName}"); } catch { _model?.Dispose(); - foreach (Mesh mesh in _meshes) - OriginalEffectResources.Destroy(mesh); - foreach (IMaterial[] materials in _polMaterials) - _materials.ReturnToPool(materials); + _poly?.Dispose(); _materials.Dispose(); throw; } _renderers = root.GetComponentsInChildren(); - foreach (Transform child in root.GetComponentsInChildren()) - child.gameObject.layer = root.layer; - } - - private void RenderPol(GameObject root, string path, OriginalEffectResources resources) - { - ITextureResourceProvider provider = resources.ModelTextureProvider(path); - foreach (PolMesh source in resources.PolModel(path).Meshes) - { - Vector3[] positions = source.VertexInfo.GameBoxPositions.ToUnityPositions(); - foreach (PolTexture texture in source.Textures) + if (_poly != null) + foreach (Renderer renderer in _renderers) { - if (texture.GameBoxTriangles.Length == 0) - continue; - string[] names = texture.Material.TextureFileNames; - int main = names.Length > 1 && !string.IsNullOrEmpty(names[1]) ? 1 : 0; - ITexture2D Texture(int index) => string.IsNullOrEmpty(names[index]) - ? new UnityTexture2D(Texture2D.whiteTexture) : provider.GetTexture(names[index]); - IMaterial[] materials = _materials.CreateStandardMaterials(Rendering.RendererType.Pol, - (names[main], Texture(main)), main == 1 ? (names[0], Texture(0)) : default, - Core.Primitives.Color.White, texture.BlendFlag); - _polMaterials.Add(materials); - var mesh = new Mesh { name = "Original effect POL", indexFormat = IndexFormat.UInt32, hideFlags = HideFlags.DontSave }; - _meshes.Add(mesh); - mesh.vertices = positions; - mesh.uv = source.VertexInfo.Uvs[main].ToUnityVector2s(); - mesh.uv2 = source.VertexInfo.Uvs[0].ToUnityVector2s(); - mesh.triangles = texture.GameBoxTriangles.Reverse().ToArray(); - mesh.RecalculateBounds(); - var child = new GameObject("Original POL section") { hideFlags = HideFlags.DontSave, layer = root.layer }; - child.transform.SetParent(root.transform, false); - child.AddComponent().sharedMesh = mesh; - MeshRenderer renderer = child.AddComponent(); - renderer.sharedMaterials = materials.Select(m => (Material)m.NativeObject).ToArray(); renderer.shadowCastingMode = ShadowCastingMode.Off; renderer.receiveShadows = false; } - } + foreach (Transform child in root.GetComponentsInChildren()) + child.gameObject.layer = root.layer; } private void EnableOpacityOverride() { if (_opacityMaterials.Count > 0) return; + Shader shader = Shader.Find("Pal3/Transparent"); + if (shader == null) + throw new System.InvalidOperationException("The effect opacity shader is missing."); foreach (Renderer renderer in _renderers) { if (renderer.sharedMaterial == null) continue; var material = new Material(renderer.sharedMaterial) { - shader = Shader.Find("Pal3/Transparent"), + shader = shader, hideFlags = HideFlags.DontSave }; material.SetInt("_BlendSrcFactor", (int)BlendMode.SrcAlpha); @@ -123,7 +95,7 @@ namespace Pal3.Game.Effect.Original } } - protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt) + protected override void Apply(EffectTask t, EffectTaskClock clock, float dt) { if (clock.StartedNow) _animationStart = LocalTime; @@ -148,12 +120,15 @@ namespace Pal3.Game.Effect.Original Root.transform.localPosition = UnityPosition(Position + Orbit); Root.transform.localRotation = UnityRotation(Rotation); Root.transform.localScale = Scale; - _properties.SetColor("_TintColor", new Color(1, 1, 1, _opacity)); foreach (Renderer renderer in _renderers) { renderer.enabled = Alive && Visible; if (_opacityMaterials.Count > 0) + { + renderer.GetPropertyBlock(_properties); + _properties.SetColor("_TintColor", new Color(1, 1, 1, _opacity)); renderer.SetPropertyBlock(_properties); + } } if (Alive && Visible) _model?.SetCurrentTime(Mathf.Max(0, LocalTime - _animationStart)); @@ -162,12 +137,9 @@ namespace Pal3.Game.Effect.Original public override void Dispose() { _model?.Dispose(); - foreach (Mesh mesh in _meshes) - OriginalEffectResources.Destroy(mesh); + _poly?.Dispose(); foreach (Material material in _opacityMaterials) - OriginalEffectResources.Destroy(material); - foreach (IMaterial[] materials in _polMaterials) - _materials.ReturnToPool(materials); + EffectResources.Destroy(material); _materials.Dispose(); base.Dispose(); } diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/ModelNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/ModelNode.cs.meta new file mode 100644 index 00000000..d7dcab12 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/ModelNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 931441919a39d495fa8277a0dca473d0 diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalParticleNode.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/ParticleNode.cs similarity index 94% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalParticleNode.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/ParticleNode.cs index a6fd2259..1fcd987f 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalParticleNode.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/ParticleNode.cs @@ -3,7 +3,7 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using System; using Core.DataReader.Data; @@ -17,7 +17,7 @@ namespace Pal3.Game.Effect.Original // This is PAL3's CEffgbParticle -> ParticleEffect/particle.cpp path, not // gbengine9/physics/gbparteffect.cpp: the combat implementation scales both // scope and displacement and forces ONE/ONE blending regardless of BlendMode. - internal sealed class OriginalParticleNode : OriginalEffectNode + internal sealed class ParticleNode : EffectNode { private struct Unit { @@ -57,8 +57,8 @@ namespace Pal3.Game.Effect.Original } } - public OriginalParticleNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, - OriginalEffectResources resources, uint seed, OriginalEffectOverrides edits) : base(root, d, tasks, origin, birth) + public ParticleNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, + EffectResources resources, uint seed, EffectOverrides edits) : base(root, d, tasks, origin, birth) { _random = new System.Random(unchecked((int)seed)); _file = resources.Particle(d.ParticleFileName, edits); @@ -91,7 +91,7 @@ namespace Pal3.Game.Effect.Original var shape = c.System.shape; shape.enabled = false; var renderer = c.System.GetComponent(); - renderer.sharedMaterial = resources.Material(OriginalEffectResources.RelativeTo(d.ParticleFileName, c.Particle.Texture), true, false, 1); + renderer.sharedMaterial = resources.Material(EffectResources.RelativeTo(d.ParticleFileName, c.Particle.Texture), true, false, 1); renderer.renderMode = ParticleSystemRenderMode.Billboard; renderer.alignment = ParticleSystemRenderSpace.View; renderer.minParticleSize = 0; @@ -111,12 +111,12 @@ namespace Pal3.Game.Effect.Original c.System.Play(false); c.System.Pause(false); if (c.Emitter.Shape == 2) - c.Shape = resources.Shape(OriginalEffectResources.RelativeTo(d.ParticleFileName, c.Emitter.ShapePath)); + c.Shape = resources.ParticleShape(d.ParticleFileName, c.Emitter.ShapePath); _controllers[i] = c; } } - protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt) + protected override void Apply(EffectTask t, EffectTaskClock clock, float dt) { if (clock.StartedNow) _loopEmission = true; diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/ParticleNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/ParticleNode.cs.meta new file mode 100644 index 00000000..c65eba1d --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/ParticleNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 13f42c5931db146b8a60320470832551 diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalPortalEffect.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/PortalEffectPlayer.cs similarity index 76% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalPortalEffect.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/PortalEffectPlayer.cs index 249d0c93..fd7daf48 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalPortalEffect.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/PortalEffectPlayer.cs @@ -3,25 +3,33 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { + using System; + using System.Collections.Generic; using UnityEngine; // MXTransport is a scene effect, not flexeff group zero. - public sealed class OriginalPortalEffect : MonoBehaviour + [UnityEngine.Scripting.APIUpdating.MovedFrom(true, "Pal3.Game.Effect.Original", "Pal3.Game", "OriginalPortalEffect")] + public sealed class PortalEffectPlayer : MonoBehaviour, IDisposable { + private readonly List _parts = new(); private EffectMeshBuffer _base, _outer, _inner; private float _time; + private bool _disposed; private Color32 _outerColor = new(245, 188, 28, 255), _innerColor = new(10, 67, 227, 255); public bool AutoAdvance { get; set; } = true; - public void Initialize(OriginalEffectResources resources, uint type = 0) + public void Initialize(EffectResources resources, uint type = 0) { + if (_disposed) + throw new ObjectDisposedException(nameof(PortalEffectPlayer)); GameObject Child(string name) { var go = new GameObject(name) { hideFlags = HideFlags.DontSave, layer = gameObject.layer }; go.transform.SetParent(transform, false); + _parts.Add(go); return go; } string texture = "effect\\trans.tga"; @@ -57,7 +65,7 @@ namespace Pal3.Game.Effect.Original return; _base.Clear(); Quaternion rotation = Quaternion.AngleAxis(-time * 32 * 0.2f, Vector3.up); - Vector3 P(float x, float z) => OriginalEffectNode.UnityPosition(rotation * new Vector3(x, 0, z)); + Vector3 P(float x, float z) => EffectNode.UnityPosition(rotation * new Vector3(x, 0, z)); _base.Quad(P(-36, -36), P(-36, 36), P(36, 36), P(36, -36), Vector2.zero, Vector2.one, Color.white); _base.Upload(); Cone(_outer, 41, 28, 50, rotation, _outerColor); @@ -70,7 +78,7 @@ namespace Pal3.Game.Effect.Original Vector3 P(int i, float radius, float y) { float a = i * 2 * Mathf.PI / 6; - return OriginalEffectNode.UnityPosition(rotation * new Vector3(Mathf.Cos(a) * radius, y, Mathf.Sin(a) * radius)); + return EffectNode.UnityPosition(rotation * new Vector3(Mathf.Cos(a) * radius, y, Mathf.Sin(a) * radius)); } for (int i = 0; i < 6; i++) mesh.Quad(P(i, bottom, 0), P(i + 1, bottom, 0), P(i + 1, top, height), P(i, top, height), @@ -84,11 +92,21 @@ namespace Pal3.Game.Effect.Original Sample(_time + Time.deltaTime); } - private void OnDestroy() + public void Dispose() { + if (_disposed) + return; + _disposed = true; + AutoAdvance = false; _base?.Dispose(); _outer?.Dispose(); _inner?.Dispose(); + _base = _outer = _inner = null; + foreach (GameObject part in _parts) + EffectResources.Destroy(part); + _parts.Clear(); } + + private void OnDestroy() => Dispose(); } } diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/PortalEffectPlayer.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/PortalEffectPlayer.cs.meta new file mode 100644 index 00000000..ef1065b6 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/PortalEffectPlayer.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 279668a7de3554dc9b94b925ca64ee9d diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalQuadNode.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/QuadNode.cs similarity index 91% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalQuadNode.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/QuadNode.cs index 22fe4c7f..5d51cdbe 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalQuadNode.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/QuadNode.cs @@ -3,13 +3,13 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using System.Collections.Generic; using Core.DataReader.Data; using UnityEngine; - internal sealed class OriginalQuadNode : OriginalEffectNode + internal sealed class QuadNode : EffectNode { private sealed class Quad { @@ -28,10 +28,10 @@ namespace Pal3.Game.Effect.Original public override int QuadCount => _mesh.QuadCount; - public OriginalQuadNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, OriginalEffectResources resources) + public QuadNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, EffectResources resources, bool battleContext = false) : base(root, d, tasks, origin, birth) { - _mesh = new EffectMeshBuffer(root, resources.Material(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored)); + _mesh = new EffectMeshBuffer(root, resources.EffectTextureMaterial(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored, battleContext)); _spawnAt = new float[Tasks.Length]; _lastSpawn = new float[Tasks.Length]; for (int i = 0; i < Tasks.Length; i++) @@ -95,7 +95,7 @@ namespace Pal3.Game.Effect.Original }); } - protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt) + protected override void Apply(EffectTask t, EffectTaskClock clock, float dt) { int start = t.ModifyLast ? Mathf.Max(0, _quads.Count - 1) : 0; Vector3 axis = new(t.CircleAxisX, t.CircleAxisY, t.CircleAxisZ); diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/QuadNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/QuadNode.cs.meta new file mode 100644 index 00000000..f5faf118 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/QuadNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 81978aa3bb0d146e1ba874a04516b592 diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalSparEmitter.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/SparEmitter.cs similarity index 98% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalSparEmitter.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/SparEmitter.cs index ec7d6c77..50a1c02b 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalSparEmitter.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/SparEmitter.cs @@ -3,7 +3,7 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using System; using System.IO; @@ -13,7 +13,7 @@ namespace Pal3.Game.Effect.Original // PAL3A 0x4c8509 / 0x4c8446 / 0x4c8bfc. Keep the native update order, // including newly emitted units receiving a full update in their birth frame. - internal sealed class OriginalSparEmitter + internal sealed class SparEmitter { internal struct Unit { @@ -43,7 +43,7 @@ namespace Pal3.Game.Effect.Original public float Time => _time; - public OriginalSparEmitter(SparGroup group, uint seed) + public SparEmitter(SparGroup group, uint seed) { Validate(group); _group = group; diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalSparEmitter.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/SparEmitter.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalSparEmitter.cs.meta rename to Assets/Scripts/Pal3.Game/Effect/Runtime/SparEmitter.cs.meta diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalSparNode.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/SparNode.cs similarity index 80% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalSparNode.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/SparNode.cs index 8f945825..00b6cb9e 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalSparNode.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/SparNode.cs @@ -3,35 +3,35 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using Core.DataReader.Data; using Core.DataReader.Par; using UnityEngine; - internal sealed class OriginalSparNode : OriginalEffectNode + internal sealed class SparNode : EffectNode { private readonly SparFile _file; - private readonly OriginalSparEmitter[] _emitters; + private readonly SparEmitter[] _emitters; private readonly EffectMeshBuffer[] _meshes; private bool _running; private float _dt; - public OriginalSparNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, - OriginalEffectResources resources, uint seed) : base(root, d, tasks, origin, birth) + public SparNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, + EffectResources resources, uint seed) : base(root, d, tasks, origin, birth) { _file = resources.Spar(d.ParticleFileName); - _emitters = new OriginalSparEmitter[_file.Groups.Length]; + _emitters = new SparEmitter[_file.Groups.Length]; _meshes = new EffectMeshBuffer[_emitters.Length]; try { for (int i = 0; i < _emitters.Length; i++) { SparGroup group = _file.Groups[i]; - _emitters[i] = new OriginalSparEmitter(group, seed + (uint)i); + _emitters[i] = new SparEmitter(group, seed + (uint)i); var child = new GameObject(group.Name) { hideFlags = HideFlags.DontSave, layer = root.layer }; child.transform.SetParent(root.transform, false); - _meshes[i] = new EffectMeshBuffer(child, resources.SparMaterial(OriginalEffectResources.RelativeTo(d.ParticleFileName, group.Texture), _file.Shader), reverseWinding: true); + _meshes[i] = new EffectMeshBuffer(child, resources.SparMaterial(EffectResources.RelativeTo(d.ParticleFileName, group.Texture), _file.Shader), reverseWinding: true); } } catch @@ -58,16 +58,16 @@ namespace Pal3.Game.Effect.Original // CEffSParticle updates the system before processing effect tasks. _dt = dt; if (_running) - foreach (OriginalSparEmitter emitter in _emitters) + foreach (SparEmitter emitter in _emitters) emitter.Step(dt); base.Step(time, dt); } - protected override void Apply(EffectTask task, OriginalTaskClock clock, float dt) + protected override void Apply(EffectTask task, EffectTaskClock clock, float dt) { if (clock.StartedNow) { - foreach (OriginalSparEmitter emitter in _emitters) + foreach (SparEmitter emitter in _emitters) emitter.Start(); _running = true; } @@ -79,7 +79,7 @@ namespace Pal3.Game.Effect.Original if (clock.Finished) { _running = false; // native Stop clears the pool immediately - foreach (OriginalSparEmitter emitter in _emitters) + foreach (SparEmitter emitter in _emitters) emitter.Stop(); } } @@ -95,10 +95,10 @@ namespace Pal3.Game.Effect.Original mesh.Clear(); if (Visible && _running) { - OriginalSparEmitter emitter = _emitters[i]; + SparEmitter emitter = _emitters[i]; for (int j = 0; j < emitter.Count; j++) { - OriginalSparEmitter.Unit u = emitter.Units[j]; + SparEmitter.Unit u = emitter.Units[j]; Vector3 center = UnityPosition(Position + Orbit + rotation * u.Position); float sin = Mathf.Sin(u.Rotation), cos = Mathf.Cos(u.Rotation); // Native SPar builds the quad directly in view space: diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalSparNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/SparNode.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalSparNode.cs.meta rename to Assets/Scripts/Pal3.Game/Effect/Runtime/SparNode.cs.meta diff --git a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalTrailNode.cs b/Assets/Scripts/Pal3.Game/Effect/Runtime/TrailNode.cs similarity index 90% rename from Assets/Scripts/Pal3.Game/Effect/Original/OriginalTrailNode.cs rename to Assets/Scripts/Pal3.Game/Effect/Runtime/TrailNode.cs index 3ad84abd..a0609928 100644 --- a/Assets/Scripts/Pal3.Game/Effect/Original/OriginalTrailNode.cs +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/TrailNode.cs @@ -3,18 +3,19 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.Effect.Original +namespace Pal3.Game.Effect.Runtime { using System; using System.Collections.Generic; using Core.DataReader.Data; using UnityEngine; - internal sealed class OriginalTrailNode : OriginalEffectNode + internal sealed class TrailNode : EffectNode { private readonly EffectMeshBuffer _mesh, _trailMesh; private readonly string _kind; private readonly System.Random _random; + private readonly Func _effectRandom; private readonly Vector3 _origin; private readonly List[] _trails; private readonly Vector3[] _positions, _velocities; @@ -25,13 +26,14 @@ namespace Pal3.Game.Effect.Original public override int QuadCount => _mesh.QuadCount + (_trailMesh?.QuadCount ?? 0); - public OriginalTrailNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, - OriginalEffectResources resources, string kind, uint seed) : base(root, d, tasks, origin, birth) + public TrailNode(GameObject root, EffectDefinition d, EffectTask[] tasks, Vector3 origin, float birth, + EffectResources resources, string kind, uint seed, bool battleContext = false, Func effectRandom = null) : base(root, d, tasks, origin, birth) { _kind = kind; _origin = origin; _random = new System.Random(unchecked((int)seed)); - _mesh = new EffectMeshBuffer(root, resources.Material(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored)); + _effectRandom = effectRandom; + _mesh = new EffectMeshBuffer(root, resources.EffectTextureMaterial(d.TextureName, d.IsAdditiveBlend, d.IsZTestIgnored, battleContext)); _launched = new bool[Tasks.Length]; if (kind == "meteor") { @@ -39,7 +41,7 @@ namespace Pal3.Game.Effect.Original child.transform.SetParent(root.transform, false); // CMeteorChain always uses depth-tested additive blending. When // the meteor has a textured head, its ribbon is untextured. - _trailMesh = new EffectMeshBuffer(child, resources.Material(d.RotationAngle > 0 ? null : d.TextureName, true, false)); + _trailMesh = new EffectMeshBuffer(child, resources.EffectTextureMaterial(d.RotationAngle > 0 ? null : d.TextureName, true, false, battleContext)); _lum = d.TextureRepeat; int count = Mathf.Clamp(Mathf.Abs(Mathf.RoundToInt(d.RotationAngle)), 1, 512); _trails = new List[count]; @@ -57,7 +59,7 @@ namespace Pal3.Game.Effect.Original } } - protected override void Apply(EffectTask t, OriginalTaskClock clock, float dt) + protected override void Apply(EffectTask t, EffectTaskClock clock, float dt) { int task = Array.IndexOf(Tasks, t); if (_kind == "shock") @@ -65,7 +67,8 @@ namespace Pal3.Game.Effect.Original if (clock.StartedNow) for (int i = 0; i < _shockFrame.Length; i++) { - _shockFrame[i] = (float)_random.NextDouble() * Mathf.Max(1, Definition.FrameCount); + _shockFrame[i] = _effectRandom == null ? (float)_random.NextDouble() * Mathf.Max(1, Definition.FrameCount) : + (_effectRandom() % (Math.Max(1, Definition.FrameCount) * 100)) * .01f; _shockLimit[i] = t.RequireLoops + _shockFrame[i] + (i % _cascades) * Definition.BottomRadius; } return; // Original shock tasks only trigger the animated plane stack. diff --git a/Assets/Scripts/Pal3.Game/Effect/Runtime/TrailNode.cs.meta b/Assets/Scripts/Pal3.Game/Effect/Runtime/TrailNode.cs.meta new file mode 100644 index 00000000..2f93d110 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Effect/Runtime/TrailNode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5b9bae354ece74ad9a9def2a773f3f6e diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle.meta similarity index 67% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle.meta index 51df26d6..5ec30d0d 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat.meta +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle.meta @@ -3,6 +3,6 @@ guid: c1c42f68e5e1964449b5a0d73b35bcfc folderAsset: yes DefaultImporter: externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor.meta diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/CombatActor.cs b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/BattleActor.cs similarity index 88% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/CombatActor.cs rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/BattleActor.cs index d3470e57..fe349db8 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/CombatActor.cs +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/BattleActor.cs @@ -3,7 +3,7 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.GameSystems.Combat.Actor +namespace Pal3.Game.GameSystems.Battle.Actor { using System; using Core.Contract.Constants; @@ -12,11 +12,14 @@ namespace Pal3.Game.GameSystems.Combat.Actor using Data; using Game.Actor; - public sealed class CombatActor : ActorBase + public sealed class BattleActor : ActorBase { - public CombatActorInfo Info { get; } + public CombatActorInfo Info + { + get; + } - public CombatActor(GameResourceProvider resourceProvider, CombatActorInfo actorInfo) : + public BattleActor(GameResourceProvider resourceProvider, CombatActorInfo actorInfo) : base(resourceProvider, (int)actorInfo.Id, string.IsNullOrEmpty(actorInfo.ModelId) || actorInfo.Type == CombatActorType.MainActor && string.Equals(actorInfo.ModelId, "Null", StringComparison.OrdinalIgnoreCase) @@ -51,4 +54,4 @@ namespace Pal3.Game.GameSystems.Combat.Actor return 12f; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/CombatActor.cs.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/BattleActor.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/CombatActor.cs.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/BattleActor.cs.meta diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/CombatActorFactory.cs b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/BattleActorFactory.cs similarity index 83% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/CombatActorFactory.cs rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/BattleActorFactory.cs index 76a940a3..6613f018 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/CombatActorFactory.cs +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/BattleActorFactory.cs @@ -3,10 +3,10 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.GameSystems.Combat.Actor +namespace Pal3.Game.GameSystems.Battle.Actor { using System; - using Combat; + using Battle; using Controllers; using Data; using Dev.Presenters; @@ -18,10 +18,10 @@ namespace Pal3.Game.GameSystems.Combat.Actor using Color = Core.Primitives.Color; using Vector2Int = UnityEngine.Vector2Int; - public static class CombatActorFactory + public static class BattleActorFactory { - public static IGameEntity CreateCombatActorGameEntity(GameResourceProvider resourceProvider, - CombatActor actor, + public static IGameEntity CreateBattleActorGameEntity(GameResourceProvider resourceProvider, + BattleActor actor, ElementPosition elementPosition, bool isDropShadowEnabled) { @@ -30,10 +30,10 @@ namespace Pal3.Game.GameSystems.Combat.Actor try { // Attach CombatActorInfo to the GameEntity for better debuggability - #if UNITY_EDITOR - CombatActorInfoPresenter combatActorInfoPresent = actorGameEntity.AddComponent(); +#if UNITY_EDITOR + BattleActorInfoPresenter combatActorInfoPresent = actorGameEntity.AddComponent(); combatActorInfoPresent.combatActorInfo = actor.Info; - #endif +#endif ActorActionController actionController; switch (actor.AnimationType) @@ -56,7 +56,7 @@ namespace Pal3.Game.GameSystems.Combat.Actor throw new NotSupportedException($"Unsupported actor animation type: {actor.AnimationType}"); } - CombatActorController actorController = actorGameEntity.AddComponent(); + BattleActorController actorController = actorGameEntity.AddComponent(); actorController.Init(actor, actionController, elementPosition); actorController.IsActive = true; // combat actor is always active @@ -69,4 +69,4 @@ namespace Pal3.Game.GameSystems.Combat.Actor } } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/CombatActorFactory.cs.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/BattleActorFactory.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/CombatActorFactory.cs.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/BattleActorFactory.cs.meta diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/Controllers.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/Controllers.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/Controllers.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/Controllers.meta diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/Controllers/CombatActorController.cs b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/Controllers/BattleActorController.cs similarity index 81% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/Controllers/CombatActorController.cs rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/Controllers/BattleActorController.cs index ebf4df41..fd84d28c 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/Controllers/CombatActorController.cs +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/Controllers/BattleActorController.cs @@ -3,11 +3,11 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.GameSystems.Combat.Actor.Controllers +namespace Pal3.Game.GameSystems.Battle.Actor.Controllers { using System; using System.Collections; - using Combat; + using Battle; using Engine.Animation; using Engine.Core.Implementation; using Game.Actor.Controllers; @@ -16,12 +16,12 @@ namespace Pal3.Game.GameSystems.Combat.Actor.Controllers using Quaternion = UnityEngine.Quaternion; using Vector3 = UnityEngine.Vector3; - public sealed class CombatActorController : GameEntityScript + public sealed class BattleActorController : GameEntityScript { private const string COMBAT_ANIMATION_NORMAL_ATTACK_EVENT_NAME_PREFIX = "work"; private const string COMBAT_ANIMATION_JUMP_ATTACK_EVENT_NAME_PREFIX = "flydown"; - - private CombatActor _actor; + + private BattleActor _actor; private ActorActionController _actionController; private ElementPosition _elementPosition; @@ -30,14 +30,16 @@ namespace Pal3.Game.GameSystems.Combat.Actor.Controllers get => _actor.IsActive; set { - if (value) Activate(); - else DeActivate(); + if (value) + Activate(); + else + DeActivate(); _actor.IsActive = value; } } - public void Init(CombatActor actor, + public void Init(BattleActor actor, ActorActionController actionController, ElementPosition elementPosition) { @@ -63,15 +65,15 @@ namespace Pal3.Game.GameSystems.Combat.Actor.Controllers { var values = _actor.Info.AttributeValues; values[attribute] = (int)Math.Clamp((long)values[attribute] + delta, 0, int.MaxValue); - #if PAL3A +#if PAL3A if (_elementPosition <= ElementPosition.AllyCenter) { foreach (var mapping in Core.Contract.Constants.ActorConstants.MainActorCombatActorIdMap) if (mapping.Value == _actor.Id) - Engine.Services.ServiceLocator.Instance.Get().ScriptState + Engine.Services.ServiceLocator.Instance.Get().ScriptState .RecordAttributeChange((int)mapping.Key, attribute, delta); } - #endif +#endif } public ElementPosition GetElementPosition() @@ -89,32 +91,45 @@ namespace Pal3.Game.GameSystems.Combat.Actor.Controllers return _actionController; } + protected override void OnEnableGameEntity() + { + if (_actor?.IsActive == true) + SetAnimationEvents(true); + } + + protected override void OnDisableGameEntity() + { + SetAnimationEvents(false); + } + private void Activate() { - if (_actionController is VertexAnimationActorActionController vertexActionController) - { - vertexActionController.AnimationEventTriggered -= AnimationEventTriggered; - vertexActionController.AnimationEventTriggered += AnimationEventTriggered; - } - + SetAnimationEvents(isActiveAndEnabled); _actionController.PerformAction(_actor.GetPreAttackAction()); } private void DeActivate() { - if (_actionController is VertexAnimationActorActionController vertexActionController) - { - vertexActionController.AnimationEventTriggered -= AnimationEventTriggered; - } - + SetAnimationEvents(false); _actionController.DeActivate(); } - public IEnumerator StartNormalAttackAsync(CombatActorController enemyActorController, - CombatScene combatScene) + private void SetAnimationEvents(bool enabled) + { + if (_actionController is VertexAnimationActorActionController vertexActionController) + { + vertexActionController.AnimationEventTriggered -= AnimationEventTriggered; + if (enabled) + vertexActionController.AnimationEventTriggered += AnimationEventTriggered; + } + } + + public IEnumerator StartNormalAttackAsync(BattleActorController enemyActorController, + BattleScene combatScene) { // Some scripted forms (e.g. WangPengXu's beast form) have no normal attack. - if (!_actor.HasAction(_actor.GetAttackAction())) yield break; + if (!_actor.HasAction(_actor.GetAttackAction())) + yield break; Quaternion currentRotation = _actionController.Transform.Rotation; @@ -136,7 +151,7 @@ namespace Pal3.Game.GameSystems.Combat.Actor.Controllers _actionController.Transform.LookAt(targetElementPosition); yield return Transform.MoveAsync(targetElementPosition, duration); - + yield return _actionController.PerformActionAsync(_actor.GetAttackAction()); _actionController.PerformAction(_actor.GetMovementAction()); @@ -148,4 +163,4 @@ namespace Pal3.Game.GameSystems.Combat.Actor.Controllers _actionController.Transform.Rotation = currentRotation; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/Controllers/CombatActorController.cs.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/Controllers/BattleActorController.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Actor/Controllers/CombatActorController.cs.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Actor/Controllers/BattleActorController.cs.meta diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContext.cs b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContext.cs similarity index 54% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContext.cs rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContext.cs index 0ec83fe8..4d1bae19 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContext.cs +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContext.cs @@ -3,7 +3,7 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.GameSystems.Combat +namespace Pal3.Game.GameSystems.Battle { using Core.Contract.Enums; using Script.Waiter; @@ -18,35 +18,58 @@ namespace Pal3.Game.GameSystems.Combat /// /// Data contract for combat context. /// - public sealed class CombatContext + public sealed class BattleContext { public WaitUntilCanceled ScriptWaiter { get; set; } = null; // null means no script waiter - public string CombatSceneName { get; set; } = string.Empty; - public ElementType CombatSceneElementType { get; set; } = ElementType.None; - public bool IsScriptTriggeredCombat { get; set; } = false; + public string BattleSceneName { get; set; } = string.Empty; + public ElementType BattleSceneElementType { get; set; } = ElementType.None; + public bool IsScriptTriggeredBattle { get; set; } = false; public MeetType MeetType { get; set; } = MeetType.RunningIntoEachOther; - public string CombatMusicName { get; set; } = string.Empty; + public string BattleMusicName { get; set; } = string.Empty; public int MaxRound { get; set; } = -1; // -1 means no limit public bool IsUnbeatable { get; set; } = false; public bool IsNoGameOverWhenLose { get; set; } = false; public uint[] EnemyIds { get; set; } = new uint[6]; - #if PAL3A - public bool NanGongHuangAbilitiesEnabled { get; set; } - public bool WangPengXuTransformEnabled { get; set; } - public bool NanGongHuangStartsTransformed { get; set; } - public bool WangPengXuStartsTransformed { get; set; } - public int LiaoRiHpBonus { get; set; } - public int LiaoRiMpBonus { get; set; } - #endif +#if PAL3A + public bool NanGongHuangAbilitiesEnabled + { + get; set; + } + + public bool WangPengXuTransformEnabled + { + get; set; + } + + public bool NanGongHuangStartsTransformed + { + get; set; + } + + public bool WangPengXuStartsTransformed + { + get; set; + } + + public int LiaoRiHpBonus + { + get; set; + } + + public int LiaoRiMpBonus + { + get; set; + } +#endif public override string ToString() { - return $"CombatContext: " + - $"CombatScene: {CombatSceneName} " + - $"ElementType: {CombatSceneElementType} " + - $"CombatMusic: {CombatMusicName} " + - $"IsScriptTriggeredCombat: {IsScriptTriggeredCombat} " + + return $"BattleContext: " + + $"BattleScene: {BattleSceneName} " + + $"ElementType: {BattleSceneElementType} " + + $"BattleMusic: {BattleMusicName} " + + $"IsScriptTriggeredBattle: {IsScriptTriggeredBattle} " + $"MeetType: {MeetType} " + $"MaxRound: {MaxRound} " + $"IsUnbeatable: {IsUnbeatable} " + @@ -54,4 +77,4 @@ namespace Pal3.Game.GameSystems.Combat $"Enemies: {string.Join(" ", EnemyIds)}"; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContext.cs.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContext.cs.meta similarity index 76% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContext.cs.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContext.cs.meta index 23134352..bb153e19 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContext.cs.meta +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContext.cs.meta @@ -6,6 +6,6 @@ MonoImporter: defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContextBuilder.cs b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContextBuilder.cs similarity index 57% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContextBuilder.cs rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContextBuilder.cs index 47edd830..8458b07e 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContextBuilder.cs +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContextBuilder.cs @@ -3,70 +3,70 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.GameSystems.Combat +namespace Pal3.Game.GameSystems.Battle { using Core.Contract.Enums; using Script.Waiter; - public sealed class CombatContextBuilder + public sealed class BattleContextBuilder { - private CombatContext _context = new(); + private BattleContext _context = new(); - public CombatContextBuilder WithScriptWaiter(WaitUntilCanceled scriptWaiter) + public BattleContextBuilder WithScriptWaiter(WaitUntilCanceled scriptWaiter) { _context.ScriptWaiter = scriptWaiter; return this; } - public CombatContextBuilder WithCombatSceneName(string combatSceneName) + public BattleContextBuilder WithBattleSceneName(string combatSceneName) { - _context.CombatSceneName = combatSceneName; + _context.BattleSceneName = combatSceneName; return this; } - public CombatContextBuilder WithCombatSceneElementType(ElementType combatSceneElementType) + public BattleContextBuilder WithBattleSceneElementType(ElementType combatSceneElementType) { - _context.CombatSceneElementType = combatSceneElementType; + _context.BattleSceneElementType = combatSceneElementType; return this; } - public CombatContextBuilder WithIsScriptTriggeredCombat(bool isScriptTriggeredCombat) + public BattleContextBuilder WithIsScriptTriggeredBattle(bool isScriptTriggeredCombat) { - _context.IsScriptTriggeredCombat = isScriptTriggeredCombat; + _context.IsScriptTriggeredBattle = isScriptTriggeredCombat; return this; } - public CombatContextBuilder WithMeetType(MeetType meetType) + public BattleContextBuilder WithMeetType(MeetType meetType) { _context.MeetType = meetType; return this; } - public CombatContextBuilder WithCombatMusicName(string combatMusicName) + public BattleContextBuilder WithBattleMusicName(string combatMusicName) { - _context.CombatMusicName = combatMusicName; + _context.BattleMusicName = combatMusicName; return this; } - public CombatContextBuilder WithMaxRound(int maxRound) + public BattleContextBuilder WithMaxRound(int maxRound) { _context.MaxRound = maxRound; return this; } - public CombatContextBuilder WithUnbeatable(bool isUnbeatable) + public BattleContextBuilder WithUnbeatable(bool isUnbeatable) { _context.IsUnbeatable = isUnbeatable; return this; } - public CombatContextBuilder WithNoGameOverWhenLose(bool isNoGameOverWhenLose) + public BattleContextBuilder WithNoGameOverWhenLose(bool isNoGameOverWhenLose) { _context.IsNoGameOverWhenLose = isNoGameOverWhenLose; return this; } - public CombatContextBuilder WithEnemyIds( + public BattleContextBuilder WithEnemyIds( uint enemy1Id, uint enemy2Id, uint enemy3Id, @@ -74,7 +74,7 @@ namespace Pal3.Game.GameSystems.Combat uint enemy5Id, uint enemy6Id) { - _context.EnemyIds = new [] + _context.EnemyIds = new[] { enemy1Id, enemy2Id, @@ -88,11 +88,11 @@ namespace Pal3.Game.GameSystems.Combat public void ResetContext() { - _context = new CombatContext(); + _context = new BattleContext(); } - public CombatContext CurrentContext => _context; + public BattleContext CurrentContext => _context; - public CombatContext Build() => _context; + public BattleContext Build() => _context; } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContextBuilder.cs.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContextBuilder.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatContextBuilder.cs.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleContextBuilder.cs.meta diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatCoordinator.cs b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleCoordinator.cs similarity index 81% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatCoordinator.cs rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleCoordinator.cs index c5691645..7ffe85bd 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatCoordinator.cs +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleCoordinator.cs @@ -3,7 +3,7 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.GameSystems.Combat +namespace Pal3.Game.GameSystems.Battle { using System; using System.Collections.Generic; @@ -37,11 +37,11 @@ namespace Pal3.Game.GameSystems.Combat /// /// Receive events and gather context to start a combat. /// - public sealed class CombatCoordinator : IDisposable, - ICommandExecutor, + public sealed class BattleCoordinator : IDisposable, + ICommandExecutor, ICommandExecutor, ICommandExecutor, - #if PAL3A +#if PAL3A ICommandExecutor, ICommandExecutor, ICommandExecutor, @@ -49,7 +49,7 @@ namespace Pal3.Game.GameSystems.Combat ICommandExecutor, ICommandExecutor, ICommandExecutor, - #endif +#endif ICommandExecutor, ICommandExecutor, ICommandExecutor, @@ -57,22 +57,23 @@ namespace Pal3.Game.GameSystems.Combat { private const string COMBAT_SCN_FILE_NAME = "combatScn.txt"; - #if PAL3A +#if PAL3A public Core.Contract.Pal3ACombatScriptState ScriptState { get; } = new(); - #endif + +#endif private readonly GameSettings _gameSettings; - private readonly CombatManager _combatManager; + private readonly BattleManager _battleManager; private readonly PlayerActorManager _playerActorManager; private readonly AudioManager _audioManager; private readonly SceneManager _sceneManager; private readonly GameStateManager _gameStateManager; - private readonly CombatScnFile _combatScnFile; - private readonly CombatContextBuilder _combatContextBuilder = new(); + private readonly CombatScnFile _battleScnFile; + private readonly BattleContextBuilder _battleContextBuilder = new(); - public CombatCoordinator(GameResourceProvider resourceProvider, + public BattleCoordinator(GameResourceProvider resourceProvider, GameSettings gameSettings, - CombatManager combatManager, + BattleManager combatManager, PlayerActorManager playerActorManager, AudioManager audioManager, SceneManager sceneManager, @@ -80,58 +81,58 @@ namespace Pal3.Game.GameSystems.Combat { Requires.IsNotNull(resourceProvider, nameof(resourceProvider)); _gameSettings = Requires.IsNotNull(gameSettings, nameof(gameSettings)); - _combatManager = Requires.IsNotNull(combatManager, nameof(combatManager)); + _battleManager = Requires.IsNotNull(combatManager, nameof(combatManager)); _playerActorManager = Requires.IsNotNull(playerActorManager, nameof(playerActorManager)); _audioManager = Requires.IsNotNull(audioManager, nameof(audioManager)); _sceneManager = Requires.IsNotNull(sceneManager, nameof(sceneManager)); _gameStateManager = Requires.IsNotNull(gameStateManager, nameof(gameStateManager)); - _combatScnFile = resourceProvider.GetGameResourceFile( + _battleScnFile = resourceProvider.GetGameResourceFile( FileConstants.DataScriptFolderVirtualPath + COMBAT_SCN_FILE_NAME); - _combatManager.OnCombatFinished += OnCombatFinished; + _battleManager.OnBattleFinished += OnBattleFinished; CommandExecutorRegistry.Instance.Register(this); } public void Dispose() { - _combatManager.OnCombatFinished -= OnCombatFinished; + _battleManager.OnBattleFinished -= OnBattleFinished; CommandExecutorRegistry.Instance.UnRegister(this); } - private void StartCombat() + private void StartBattle() { if (!_gameSettings.IsTurnBasedCombatEnabled) { // A skipped encounter must not leave its one-shot flags on an unrelated later fight. - #if PAL3A - ScriptState.BeginBattle(Array.IndexOf(_combatContextBuilder.CurrentContext.EnemyIds, 722u) >= 0); - #endif - _combatContextBuilder.ResetContext(); +#if PAL3A + ScriptState.BeginBattle(Array.IndexOf(_battleContextBuilder.CurrentContext.EnemyIds, 722u) >= 0); +#endif + _battleContextBuilder.ResetContext(); return; } GameState previousState = _gameStateManager.GetCurrentState(); - #if PAL3A +#if PAL3A int flags = ScriptState.Flags, lostHp = ScriptState.LostHp, lostMp = ScriptState.LostMp; - #endif +#endif try { GameScene currentScene = _sceneManager.GetCurrentScene(); // Figure out which combat scene to use - string combatSceneName = GetCombatSceneName(currentScene); - _combatContextBuilder.WithCombatSceneName(combatSceneName); + string combatSceneName = GetBattleSceneName(currentScene); + _battleContextBuilder.WithBattleSceneName(combatSceneName); // Figure out element property of the combat scene - if (_combatScnFile.CombatSceneElementTypeInfo.TryGetValue(combatSceneName, + if (_battleScnFile.CombatSceneElementTypeInfo.TryGetValue(combatSceneName, out ElementType combatSceneElementType)) { - _combatContextBuilder.WithCombatSceneElementType(combatSceneElementType); + _battleContextBuilder.WithBattleSceneElementType(combatSceneElementType); } // Figure out which combat music to play - if (string.IsNullOrEmpty(_combatContextBuilder.CurrentContext.CombatMusicName)) + if (string.IsNullOrEmpty(_battleContextBuilder.CurrentContext.BattleMusicName)) { if (MusicConstants.CombatMusicInfo.TryGetValue( currentScene.GetSceneInfo().CityName.ToLower(), @@ -139,9 +140,9 @@ namespace Pal3.Game.GameSystems.Combat { // Set music only if it's not set yet or it's not a script triggered combat if (string.IsNullOrEmpty(_audioManager.GetCurrentScriptMusic()) || - !_combatContextBuilder.CurrentContext.IsScriptTriggeredCombat) + !_battleContextBuilder.CurrentContext.IsScriptTriggeredBattle) { - _combatContextBuilder.WithCombatMusicName(combatMusic); + _battleContextBuilder.WithBattleMusicName(combatMusic); } } } @@ -152,12 +153,12 @@ namespace Pal3.Game.GameSystems.Combat { WaitUntilCanceled combatWaiter = new(); Pal3.Instance.Execute(new ScriptRunnerAddWaiterRequest(combatWaiter)); - _combatContextBuilder.WithScriptWaiter(combatWaiter); + _battleContextBuilder.WithScriptWaiter(combatWaiter); } - CombatContext combatContext = _combatContextBuilder.Build(); + BattleContext combatContext = _battleContextBuilder.Build(); - #if PAL3A +#if PAL3A var options = ScriptState.BeginBattle(Array.IndexOf(combatContext.EnemyIds, 722u) >= 0); combatContext.NanGongHuangAbilitiesEnabled = ScriptState.NanGongHuangAbilitiesEnabled; combatContext.WangPengXuTransformEnabled = ScriptState.WangPengXuTransformEnabled; @@ -165,30 +166,31 @@ namespace Pal3.Game.GameSystems.Combat combatContext.WangPengXuStartsTransformed = options.pengXu; combatContext.LiaoRiHpBonus = options.hpBonus; combatContext.LiaoRiMpBonus = options.mpBonus; - #endif +#endif // Start combat EngineLogger.LogWarning($"Starting combat with context: {combatContext}"); _gameStateManager.TryGoToState(GameState.Combat); - _combatManager.EnterCombat(combatContext); + _battleManager.EnterBattle(combatContext); } catch { - #if PAL3A +#if PAL3A ScriptState.Restore(flags, lostHp, lostMp); - #endif - _combatContextBuilder.CurrentContext.ScriptWaiter?.CancelWait(); - _combatContextBuilder.ResetContext(); - if (!_gameStateManager.TryGoToState(previousState)) _gameStateManager.TryGoToState(GameState.Cutscene); +#endif + _battleContextBuilder.CurrentContext.ScriptWaiter?.CancelWait(); + _battleContextBuilder.ResetContext(); + if (!_gameStateManager.TryGoToState(previousState)) + _gameStateManager.TryGoToState(GameState.Cutscene); throw; } } - private void OnCombatFinished(object sender, CombatResult combatResult) + private void OnBattleFinished(object sender, BattleResult combatResult) { - _combatManager.ExitCombat(); - combatResult.CombatContext.ScriptWaiter?.CancelWait(); - _combatContextBuilder.ResetContext(); + _battleManager.ExitBattle(); + combatResult.BattleContext.ScriptWaiter?.CancelWait(); + _battleContextBuilder.ResetContext(); if (combatResult.IsPlayerWin) { @@ -200,11 +202,11 @@ namespace Pal3.Game.GameSystems.Combat } } - private string GetCombatSceneName(GameScene currentScene) + private string GetBattleSceneName(GameScene currentScene) { ScnSceneInfo sceneInfo = currentScene.GetSceneInfo(); - if (!_combatScnFile.CombatSceneMapInfo.TryGetValue($"{sceneInfo.CityName}_{sceneInfo.SceneName}", + if (!_battleScnFile.CombatSceneMapInfo.TryGetValue($"{sceneInfo.CityName}_{sceneInfo.SceneName}", out Dictionary combatSceneFloorKindToMapInfo)) { throw new DataException($"Combat scene not found for {sceneInfo.CityName}_{sceneInfo.SceneName}!"); @@ -229,9 +231,9 @@ namespace Pal3.Game.GameSystems.Combat combatSceneName = combatSceneFloorKindToMapInfo[FloorType.Default]; } - #if PAL3 +#if PAL3 combatSceneName = combatSceneName.ToUpper(); - #endif +#endif return combatSceneName; } @@ -272,7 +274,7 @@ namespace Pal3.Game.GameSystems.Combat (monsterIds[i], monsterIds[randomIndex]) = (monsterIds[randomIndex], monsterIds[i]); } - _combatContextBuilder + _battleContextBuilder .WithEnemyIds( monsterIds[0], monsterIds[1], @@ -280,15 +282,15 @@ namespace Pal3.Game.GameSystems.Combat monsterIds[3], monsterIds[4], monsterIds[5]) - .WithIsScriptTriggeredCombat(false); // CombatEnterNormalFightCommand is used for + .WithIsScriptTriggeredBattle(false); // CombatEnterNormalFightCommand is used for // normal combat only (player collide with monster) - StartCombat(); + StartBattle(); } public void Execute(CombatEnterBossFightCommand command) { - _combatContextBuilder + _battleContextBuilder .WithEnemyIds( command.Monster1Id, command.Monster2Id, @@ -296,14 +298,14 @@ namespace Pal3.Game.GameSystems.Combat command.Monster4Id, command.Monster5Id, command.Monster6Id) - .WithIsScriptTriggeredCombat(true); - StartCombat(); + .WithIsScriptTriggeredBattle(true); + StartBattle(); } - #if PAL3A +#if PAL3A public void Execute(CombatEnterBossFightUsingMusicCommand command) { - _combatContextBuilder + _battleContextBuilder .WithEnemyIds( command.Monster1Id, command.Monster2Id, @@ -311,44 +313,49 @@ namespace Pal3.Game.GameSystems.Combat command.Monster4Id, command.Monster5Id, command.Monster6Id) - .WithIsScriptTriggeredCombat(true) - .WithCombatMusicName(command.CombatMusicName); - StartCombat(); + .WithIsScriptTriggeredBattle(true) + .WithBattleMusicName(command.CombatMusicName); + StartBattle(); } public void Execute(CombatPrepareNanGongHuangTransformCommand command) => ScriptState.NextNanGongHuangTransform = true; + public void Execute(CombatPrepareWangPengXuTransformCommand command) => ScriptState.NextWangPengXuTransform = true; + public void Execute(NanGongHuangEnableCombatAbilitiesCommand command) => ScriptState.NanGongHuangAbilitiesEnabled = command.Enable > 0; + public void Execute(WangPengXuEnableCombatTransformCommand command) => ScriptState.WangPengXuTransformEnabled = command.Enabled > 0; + public void Execute(CombatPreserveDamageForLiaoRiCommand command) => ScriptState.PreserveLosses = true; + public void Execute(Pal3ARestoreCombatScriptStateCommand command) => ScriptState.Restore(command.Flags, command.LostHp, command.LostMp); - #endif +#endif public void Execute(CombatSetUnbeatableCommand command) { - _combatContextBuilder.WithUnbeatable(true); + _battleContextBuilder.WithUnbeatable(true); } public void Execute(CombatSetMaxRoundCommand command) { - _combatContextBuilder.WithMaxRound(command.MaxRound); + _battleContextBuilder.WithMaxRound(command.MaxRound); } public void Execute(CombatSetNoGameOverWhenLoseCommand command) { - _combatContextBuilder.WithNoGameOverWhenLose(true); + _battleContextBuilder.WithNoGameOverWhenLose(true); } public void Execute(ResetGameStateCommand command) { - _combatContextBuilder.ResetContext(); - #if PAL3A + _battleContextBuilder.ResetContext(); +#if PAL3A ScriptState.Reset(); - #endif +#endif } // Player actor collides with combat NPC in maze - public void Execute(CombatActorCollideWithPlayerActorNotification command) + public void Execute(BattleActorCollideWithPlayerActorNotification command) { Pal3.Instance.Execute(new ActorActivateCommand(command.CombatActorId, 0)); @@ -361,7 +368,7 @@ namespace Pal3.Game.GameSystems.Combat ITransform playerTransform = currentScene.GetActorGameEntity(command.PlayerActorId).Transform; ITransform enemyTransform = currentScene.GetActorGameEntity(command.CombatActorId).Transform; - _combatContextBuilder.WithMeetType(CalculateMeetType(playerTransform, enemyTransform)); + _battleContextBuilder.WithMeetType(CalculateMeetType(playerTransform, enemyTransform)); Execute(new CombatEnterNormalFightCommand( gameActor.Info.NumberOfMonsters, @@ -398,4 +405,4 @@ namespace Pal3.Game.GameSystems.Combat return MeetType.RunningIntoEachOther; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatCoordinator.cs.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleCoordinator.cs.meta similarity index 76% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatCoordinator.cs.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleCoordinator.cs.meta index 833ec9ee..3d6e125b 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatCoordinator.cs.meta +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleCoordinator.cs.meta @@ -6,6 +6,6 @@ MonoImporter: defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatManager.cs b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleManager.cs similarity index 56% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatManager.cs rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleManager.cs index 07013022..e0936371 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatManager.cs +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleManager.cs @@ -3,11 +3,10 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.GameSystems.Combat +namespace Pal3.Game.GameSystems.Battle { using System; using System.Collections.Generic; - using Actor.Controllers; using Camera; using Command; using Command.Extensions; @@ -25,22 +24,28 @@ namespace Pal3.Game.GameSystems.Combat using Engine.Services; using Game.Scene; using Scene; - using State; using Team; using UnityEngine.InputSystem; using Quaternion = UnityEngine.Quaternion; using Vector3 = UnityEngine.Vector3; - public sealed class CombatResult + public sealed class BattleResult { - public bool IsPlayerWin { get; set; } - public CombatContext CombatContext { get; set; } + public bool IsPlayerWin + { + get; set; + } + + public BattleContext BattleContext + { + get; set; + } } - public sealed class CombatManager + public sealed class BattleManager { - public event EventHandler OnCombatFinished; + public event EventHandler OnBattleFinished; private const string COMBAT_CAMERA_CONFIG_FILE_NAME = "cbCam.ini"; private const float COMBAT_CAMERA_DEFAULT_FOV = 39f; @@ -48,19 +53,18 @@ namespace Pal3.Game.GameSystems.Combat private readonly TeamManager _teamManager; private readonly SceneManager _sceneManager; private readonly CameraManager _cameraManager; - private readonly GameStateManager _gameStateManager; - private readonly IDictionary _combatActorInfos; - private readonly CombatCameraConfigFile _combatCameraConfigFile; + private readonly IDictionary _battleActorInfos; + private readonly CombatCameraConfigFile _battleCameraConfigFile; - private Vector3 _cameraPositionBeforeCombat; - private Quaternion _cameraRotationBeforeCombat; - private float _cameraFovBeforeCombat; + private Vector3 _cameraPositionBeforeBattle; + private Quaternion _cameraRotationBeforeBattle; + private float _cameraFovBeforeBattle; - private CombatScene _combatScene; - private CombatContext _currentCombatContext; + private BattleScene _battleScene; + private BattleContext _currentBattleContext; - public CombatManager(GameResourceProvider resourceProvider, + public BattleManager(GameResourceProvider resourceProvider, TeamManager teamManager, CameraManager cameraManager, SceneManager sceneManager) @@ -70,39 +74,39 @@ namespace Pal3.Game.GameSystems.Combat _cameraManager = Requires.IsNotNull(cameraManager, nameof(cameraManager)); _sceneManager = Requires.IsNotNull(sceneManager, nameof(sceneManager)); - _combatActorInfos = resourceProvider.GetCombatActorInfos(); - _combatCameraConfigFile = resourceProvider.GetGameResourceFile( + _battleActorInfos = resourceProvider.GetCombatActorInfos(); + _battleCameraConfigFile = resourceProvider.GetGameResourceFile( FileConstants.DataScriptFolderVirtualPath + COMBAT_CAMERA_CONFIG_FILE_NAME); } - public void EnterCombat(CombatContext combatContext) + public void EnterBattle(BattleContext combatContext) { - _currentCombatContext = combatContext; + _currentBattleContext = combatContext; - _cameraManager.GetCameraTransform().GetPositionAndRotation(out _cameraPositionBeforeCombat, - out _cameraRotationBeforeCombat); + _cameraManager.GetCameraTransform().GetPositionAndRotation(out _cameraPositionBeforeBattle, + out _cameraRotationBeforeBattle); - _cameraFovBeforeCombat = _cameraManager.GetFieldOfView(); + _cameraFovBeforeBattle = _cameraManager.GetFieldOfView(); string previousMusic = Engine.Services.ServiceLocator.Instance.Get().GetCurrentScriptMusic(); try { - if (!string.IsNullOrEmpty(combatContext.CombatMusicName)) + if (!string.IsNullOrEmpty(combatContext.BattleMusicName)) { - Pal3.Instance.Execute(new PlayScriptMusicCommand(combatContext.CombatMusicName, -1)); + Pal3.Instance.Execute(new PlayScriptMusicCommand(combatContext.BattleMusicName, -1)); } - _combatScene = _sceneManager.LoadCombatScene(combatContext.CombatSceneName); + _battleScene = _sceneManager.LoadBattleScene(combatContext.BattleSceneName); - Dictionary combatActors = new (); + Dictionary combatActors = new(); int positionIndex = 0; foreach (PlayerActorId playerActorId in _teamManager.GetActorsInTeam()) { int combatActorId = ActorConstants.MainActorCombatActorIdMap[playerActorId]; - CombatActorInfo info = CopyActorInfo(_combatActorInfos[combatActorId]); + CombatActorInfo info = CopyActorInfo(_battleActorInfos[combatActorId]); info.Level = ServiceLocator.Instance.Get().GetLevel((int)playerActorId); - #if PAL3A +#if PAL3A if (playerActorId == PlayerActorId.NanGongHuang && combatContext.NanGongHuangStartsTransformed) info.ModelId = ActorConstants.NanGongHuangWolfModeActorName; if (playerActorId == PlayerActorId.WangPengXu && combatContext.WangPengXuStartsTransformed) @@ -111,16 +115,17 @@ namespace Pal3.Game.GameSystems.Combat info.AttributeValues[ActorAttributeType.Hp] = 400; info.AttributeValues[ActorAttributeType.Defense] *= 2; } - #endif +#endif combatActors[(ElementPosition)positionIndex++] = info; } for (int i = 0; i < combatContext.EnemyIds.Length; i++) { uint enemyActorId = combatContext.EnemyIds[i]; - if (enemyActorId == 0) continue; - CombatActorInfo info = CopyActorInfo(_combatActorInfos[(int)enemyActorId]); - #if PAL3A + if (enemyActorId == 0) + continue; + CombatActorInfo info = CopyActorInfo(_battleActorInfos[(int)enemyActorId]); +#if PAL3A if (enemyActorId == 722) { info.AttributeValues[ActorAttributeType.Hp] = AddAttributeBonus( @@ -128,13 +133,13 @@ namespace Pal3.Game.GameSystems.Combat info.AttributeValues[ActorAttributeType.Mp] = AddAttributeBonus( info.AttributeValues[ActorAttributeType.Mp], combatContext.LiaoRiMpBonus); } - #endif +#endif combatActors[(ElementPosition)((int)ElementPosition.EnemyWater + i)] = info; } - _combatScene.LoadActors(combatActors, combatContext.MeetType); + _battleScene.LoadActors(combatActors, combatContext.MeetType); - SetCameraPosition(_combatCameraConfigFile.DefaultCamConfigs[0]); + SetCameraPosition(_battleCameraConfigFile.DefaultCamConfigs[0]); Pal3.Instance.Execute(new CameraFadeInCommand()); @@ -148,15 +153,17 @@ namespace Pal3.Game.GameSystems.Combat } catch { - _sceneManager.UnloadCombatScene(); + _sceneManager.UnloadBattleScene(); ResetCameraPosition(); - if (!string.IsNullOrEmpty(combatContext.CombatMusicName)) + if (!string.IsNullOrEmpty(combatContext.BattleMusicName)) { - if (string.IsNullOrEmpty(previousMusic)) Pal3.Instance.Execute(new StopScriptMusicCommand()); - else Pal3.Instance.Execute(new PlayScriptMusicCommand(previousMusic, -1)); + if (string.IsNullOrEmpty(previousMusic)) + Pal3.Instance.Execute(new StopScriptMusicCommand()); + else + Pal3.Instance.Execute(new PlayScriptMusicCommand(previousMusic, -1)); } - _combatScene = null; - _currentCombatContext = null; + _battleScene = null; + _currentBattleContext = null; throw; } } @@ -164,24 +171,27 @@ namespace Pal3.Game.GameSystems.Combat private static CombatActorInfo CopyActorInfo(CombatActorInfo info) { info.AttributeValues = new Dictionary(info.AttributeValues); - if (info.Type == CombatActorType.MainActor) info.ModelId = info.Id.ToString(); + if (info.Type == CombatActorType.MainActor) + info.ModelId = info.Id.ToString(); return info; } - #if PAL3A +#if PAL3A private static int AddAttributeBonus(int value, int bonus) { return (int)Math.Clamp((long)value + bonus, 0, int.MaxValue); } - #endif +#endif - public void ExitCombat() + public void ExitBattle() { // Stop combat music Pal3.Instance.Execute(new StopScriptMusicCommand()); Pal3.Instance.Execute(new CameraFadeInCommand()); - _sceneManager.UnloadCombatScene(); + _sceneManager.UnloadBattleScene(); ResetCameraPosition(); + _battleScene = null; + _currentBattleContext = null; } private void SetCameraPosition(CombatCameraConfig config) @@ -202,76 +212,40 @@ namespace Pal3.Game.GameSystems.Combat private void ResetCameraPosition() { - _cameraManager.GetCameraTransform().SetPositionAndRotation(_cameraPositionBeforeCombat, - _cameraRotationBeforeCombat); + _cameraManager.GetCameraTransform().SetPositionAndRotation(_cameraPositionBeforeBattle, + _cameraRotationBeforeBattle); - Pal3.Instance.Execute(new CameraSetFieldOfViewCommand(_cameraFovBeforeCombat)); + Pal3.Instance.Execute(new CameraSetFieldOfViewCommand(_cameraFovBeforeBattle)); } public void Update(float deltaTime) { - if (Keyboard.current.escapeKey.wasPressedThisFrame) + var keyboard = Keyboard.current; + if (keyboard == null || _battleScene == null) + return; + + if (keyboard.escapeKey.wasPressedThisFrame) { - OnCombatFinished?.Invoke(this, new CombatResult + OnBattleFinished?.Invoke(this, new BattleResult { IsPlayerWin = true, - CombatContext = _currentCombatContext, + BattleContext = _currentBattleContext, }); + return; } - CombatActorController fromController = null; - int fromPosition = (int)ElementPosition.AllyWater; + ElementPosition first = keyboard.ctrlKey.isPressed ? ElementPosition.EnemyWater : ElementPosition.AllyWater; + for (var key = Key.F1; key <= Key.F6; key++) + { + if (!keyboard[key].wasPressedThisFrame) + continue; - if (Keyboard.current.ctrlKey.isPressed) - { - fromPosition = (int)ElementPosition.EnemyWater; - } - - if (Keyboard.current.f1Key.wasPressedThisFrame) - { - fromController = _combatScene.GetCombatActorController((ElementPosition)fromPosition); - } - else if (Keyboard.current.f2Key.wasPressedThisFrame) - { - fromController = _combatScene.GetCombatActorController((ElementPosition)(fromPosition + 1)); - } - else if (Keyboard.current.f3Key.wasPressedThisFrame) - { - fromController = _combatScene.GetCombatActorController((ElementPosition)(fromPosition + 2)); - } - else if (Keyboard.current.f4Key.wasPressedThisFrame) - { - fromController = _combatScene.GetCombatActorController((ElementPosition)(fromPosition + 3)); - } - else if (Keyboard.current.f5Key.wasPressedThisFrame) - { - fromController = _combatScene.GetCombatActorController((ElementPosition)(fromPosition + 4)); - } - else if (Keyboard.current.f6Key.wasPressedThisFrame) - { - fromController = _combatScene.GetCombatActorController((ElementPosition)(fromPosition + 5)); - } - - if (fromController != null) - { - CombatActorController toController = null; - - while (true) - { - int min = (int) (fromPosition == 0 ? ElementPosition.EnemyWater : ElementPosition.AllyWater); - int max = (int) (fromPosition == 0 ? ElementPosition.EnemyCenter : ElementPosition.AllyCenter); - - ElementPosition toPosition = (ElementPosition)RandomGenerator.Range(min, max + 1); - - if (_combatScene.GetCombatActorController(toPosition) is {} controller) - { - toController = controller; - break; - } - } - - Pal3.Instance.StartCoroutine(fromController.StartNormalAttackAsync(toController, _combatScene)); + var slot = (ElementPosition)((int)first + (int)key - (int)Key.F1); + var attacker = _battleScene.GetBattleActorController(slot); + if (attacker != null && _battleScene.GetRandomOpponent(slot) is { } target) + attacker.StartCoroutine(attacker.StartNormalAttackAsync(target, _battleScene)); + return; } } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatManager.cs.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleManager.cs.meta similarity index 76% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatManager.cs.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleManager.cs.meta index 8661532e..77434ae1 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/CombatManager.cs.meta +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/BattleManager.cs.meta @@ -6,6 +6,6 @@ MonoImporter: defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/ElementPosition.cs b/Assets/Scripts/Pal3.Game/GameSystems/Battle/ElementPosition.cs similarity index 52% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/ElementPosition.cs rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/ElementPosition.cs index b4769230..70a65304 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/ElementPosition.cs +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/ElementPosition.cs @@ -3,22 +3,22 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.GameSystems.Combat +namespace Pal3.Game.GameSystems.Battle { public enum ElementPosition { - AllyWater = 0, - AllyFire = 1, - AllyWind = 2, + AllyWater = 0, + AllyFire = 1, + AllyWind = 2, AllyThunder = 3, - AllyEarth = 4, - AllyCenter = 5, + AllyEarth = 4, + AllyCenter = 5, - EnemyWater = 6, - EnemyFire = 7, - EnemyWind = 8, - EnemyThunder = 9, - EnemyEarth = 10, - EnemyCenter = 11, + EnemyWater = 6, + EnemyFire = 7, + EnemyWind = 8, + EnemyThunder = 9, + EnemyEarth = 10, + EnemyCenter = 11, } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/ElementPosition.cs.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/ElementPosition.cs.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/ElementPosition.cs.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/ElementPosition.cs.meta diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Scene.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Scene.meta similarity index 100% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Scene.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Scene.meta diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Scene/CombatScene.cs b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Scene/BattleScene.cs similarity index 75% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Scene/CombatScene.cs rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Scene/BattleScene.cs index 14c902c8..e982689e 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Scene/CombatScene.cs +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Scene/BattleScene.cs @@ -3,9 +3,10 @@ // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ -namespace Pal3.Game.GameSystems.Combat.Scene +namespace Pal3.Game.GameSystems.Battle.Scene { using System.Collections.Generic; + using System.Linq; using Actor; using Actor.Controllers; using Core.Contract.Constants; @@ -14,6 +15,7 @@ namespace Pal3.Game.GameSystems.Combat.Scene using Core.DataReader.Gdb; using Core.DataReader.Ini; using Core.DataReader.Pol; + using Core.Utilities; using Data; using Engine.Core.Abstraction; using Engine.Core.Implementation; @@ -27,7 +29,7 @@ namespace Pal3.Game.GameSystems.Combat.Scene using Vector3 = UnityEngine.Vector3; using Quaternion = UnityEngine.Quaternion; - public sealed class CombatScene : GameEntityScript + public sealed class BattleScene : GameEntityScript { private const string COMBAT_CONFIG_FILE_NAME = "combat.ini"; @@ -36,25 +38,25 @@ namespace Pal3.Game.GameSystems.Combat.Scene private UnityEngine.Light _keyLight; private IMaterialManager _materialManager; - private string _combatSceneName; + private string _battleSceneName; private bool _usesToonRendering; private IGameEntity _parent; private IGameEntity _mesh; - private CombatConfigFile _combatConfigFile; + private CombatConfigFile _battleConfigFile; private static readonly Quaternion EnemyFormationRotation = Quaternion.Euler(0, 145, 0); private static readonly Quaternion PlayerFormationRotation = Quaternion.Euler(0, -45, 0); - private Dictionary _combatActorControllers; + private readonly Dictionary _battleActorControllers = new(); public void Init(GameResourceProvider resourceProvider) { _resourceProvider = resourceProvider; _materialManager = resourceProvider.GetMaterialManager(); - _combatConfigFile = _resourceProvider.GetGameResourceFile( + _battleConfigFile = _resourceProvider.GetGameResourceFile( FileConstants.DataScriptFolderVirtualPath + COMBAT_CONFIG_FILE_NAME); } @@ -63,7 +65,7 @@ namespace Pal3.Game.GameSystems.Combat.Scene bool usesToonRendering) { _parent = parent; - _combatSceneName = combatSceneName; + _battleSceneName = combatSceneName; _usesToonRendering = usesToonRendering; if (usesToonRendering) { @@ -87,18 +89,20 @@ namespace Pal3.Game.GameSystems.Combat.Scene private void OnLightingSettingsChanged(string propertyName) { - if (_keyLight != null) ToonLighting.ConfigureKeyShadows(_keyLight, _lightingSettings); + if (_keyLight != null) + ToonLighting.ConfigureKeyShadows(_keyLight, _lightingSettings); } protected override void OnDisableGameEntity() { - if (_lightingSettings != null) _lightingSettings.OnGameSettingsChanged -= OnLightingSettingsChanged; + if (_lightingSettings != null) + _lightingSettings.OnGameSettingsChanged -= OnLightingSettingsChanged; } private void RenderMesh(PolFile polFile, ITextureResourceProvider textureProvider) { // Render mesh - _mesh = GameEntityFactory.Create($"Mesh_{_combatSceneName}", + _mesh = GameEntityFactory.Create($"Mesh_{_battleSceneName}", _parent, worldPositionStays: false); _mesh.IsStatic = true; // Combat Scene mesh is static @@ -111,7 +115,7 @@ namespace Pal3.Game.GameSystems.Combat.Scene public Vector3 GetWorldPosition(ElementPosition position) { - int positionIndex = (int) position; + int positionIndex = (int)position; if (position >= ElementPosition.EnemyWater) { @@ -120,21 +124,31 @@ namespace Pal3.Game.GameSystems.Combat.Scene return position switch { - ElementPosition.AllyCenter => _combatConfigFile.AllyFormationConfig.CenterGameBoxPosition.ToUnityPosition(), - ElementPosition.EnemyCenter => _combatConfigFile.EnemyFormationConfig.CenterGameBoxPosition.ToUnityPosition(), - _ => _combatConfigFile.ActorGameBoxPositions[positionIndex].ToUnityPosition() + ElementPosition.AllyCenter => _battleConfigFile.AllyFormationConfig.CenterGameBoxPosition.ToUnityPosition(), + ElementPosition.EnemyCenter => _battleConfigFile.EnemyFormationConfig.CenterGameBoxPosition.ToUnityPosition(), + _ => _battleConfigFile.ActorGameBoxPositions[positionIndex].ToUnityPosition() }; } - public CombatActorController GetCombatActorController(ElementPosition elementPosition) + public BattleActorController GetBattleActorController(ElementPosition elementPosition) { - return _combatActorControllers.GetValueOrDefault(elementPosition); + return _battleActorControllers.GetValueOrDefault(elementPosition); + } + + internal BattleActorController GetRandomOpponent(ElementPosition attacker) + { + bool enemyAttacks = attacker >= ElementPosition.EnemyWater; + var opponents = _battleActorControllers + .Where(pair => (pair.Key >= ElementPosition.EnemyWater) != enemyAttacks && pair.Value != null) + .Select(pair => pair.Value) + .ToArray(); + return opponents.Length == 0 ? null : opponents[RandomGenerator.Range(0, opponents.Length)]; } public void LoadActors(Dictionary combatActors, MeetType meetType) { - _combatActorControllers = new Dictionary(); + _battleActorControllers.Clear(); foreach ((ElementPosition elementPosition, CombatActorInfo actorInfo) in combatActors) { @@ -148,8 +162,8 @@ namespace Pal3.Game.GameSystems.Combat.Scene combatActorInfo.ModelId = combatActorInfo.Id.ToString(); } - CombatActor combatActor = new(_resourceProvider, combatActorInfo); - IGameEntity combatActorGameEntity = CombatActorFactory.CreateCombatActorGameEntity( + BattleActor combatActor = new(_resourceProvider, combatActorInfo); + IGameEntity combatActorGameEntity = BattleActorFactory.CreateBattleActorGameEntity( _resourceProvider, combatActor, elementPosition, @@ -173,8 +187,8 @@ namespace Pal3.Game.GameSystems.Combat.Scene combatActorGameEntity.Transform.SetPositionAndRotation(GetWorldPosition(elementPosition), rotation); - _combatActorControllers[elementPosition] = combatActorGameEntity.GetComponent(); + _battleActorControllers[elementPosition] = combatActorGameEntity.GetComponent(); } } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Scene/CombatScene.cs.meta b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Scene/BattleScene.cs.meta similarity index 76% rename from Assets/Scripts/Pal3.Game/GameSystems/Combat/Scene/CombatScene.cs.meta rename to Assets/Scripts/Pal3.Game/GameSystems/Battle/Scene/BattleScene.cs.meta index 7897e8f0..93aec275 100644 --- a/Assets/Scripts/Pal3.Game/GameSystems/Combat/Scene/CombatScene.cs.meta +++ b/Assets/Scripts/Pal3.Game/GameSystems/Battle/Scene/BattleScene.cs.meta @@ -6,6 +6,6 @@ MonoImporter: defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Game/Pal3.cs b/Assets/Scripts/Pal3.Game/Pal3.cs index b3368338..0add87a1 100644 --- a/Assets/Scripts/Pal3.Game/Pal3.cs +++ b/Assets/Scripts/Pal3.Game/Pal3.cs @@ -33,7 +33,7 @@ namespace Pal3.Game using Engine.Utilities; using GamePlay; using GameSystems.Caption; - using GameSystems.Combat; + using GameSystems.Battle; using GameSystems.Dialogue; using GameSystems.Favor; using GameSystems.Inventory; @@ -178,10 +178,10 @@ namespace Pal3.Game private CursorManager _cursorManager; private SaveManager _saveManager; private RenderingSettingsManager _renderingSettingsManager; - private CombatManager _combatManager; - private CombatCoordinator _combatCoordinator; + private BattleManager _battleManager; + private BattleCoordinator _battleCoordinator; - #if PAL3 // PAL3 specific components +#if PAL3 // PAL3 specific components private AppraisalsMiniGame _appraisalsMiniGame; private SailingMiniGame _sailingMiniGame; private HideFightMiniGame _hideFightMiniGame; @@ -467,17 +467,17 @@ namespace Pal3.Game dialogueSelectionButtonPrefab) ); - ServiceLocator.Instance.Register(_combatManager = - new CombatManager(_gameResourceProvider, + ServiceLocator.Instance.Register(_battleManager = + new BattleManager(_gameResourceProvider, _teamManager, _cameraManager, _sceneManager) ); - ServiceLocator.Instance.Register(_combatCoordinator = - new CombatCoordinator(_gameResourceProvider, + ServiceLocator.Instance.Register(_battleCoordinator = + new BattleCoordinator(_gameResourceProvider, _gameSettings, - _combatManager, + _battleManager, _playerActorManager, _audioManager, _sceneManager, @@ -645,7 +645,7 @@ namespace Pal3.Game if (currentState == GameState.Combat) { - _combatManager.Update(deltaTime); + _battleManager.Update(deltaTime); } _playerGamePlayManager.Update(deltaTime); diff --git a/Assets/Scripts/Pal3.Game/Rendering/Material/GameMaterialManager.cs b/Assets/Scripts/Pal3.Game/Rendering/Material/GameMaterialManager.cs index 19588df8..b5c8de4b 100644 --- a/Assets/Scripts/Pal3.Game/Rendering/Material/GameMaterialManager.cs +++ b/Assets/Scripts/Pal3.Game/Rendering/Material/GameMaterialManager.cs @@ -1,4 +1,4 @@ -// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ // Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ @@ -46,9 +46,19 @@ namespace Pal3.Game.Rendering.Material private const float PolAlphaCutoff = 245f / 255f; private const float DisabledAlphaCutoff = 2f; private const float DefaultLightmapScale = 1f / 0.6f; - private const float PolLightmapScale = 2f; + internal const float PolLightmapScale = 2f; - public bool UsesToonRendering { get; } + public bool UsesToonRendering + { + get; + } + + public bool RequiresNormals => UsesToonRendering || NativeLighting != null; + + public Native.GameBoxNativeLighting NativeLighting + { + get; + } private readonly IMaterial _waterMaterial; private readonly IMaterial _transparentMaterial; @@ -67,9 +77,10 @@ namespace Pal3.Game.Rendering.Material private bool _disposed; - public GameMaterialManager(IMaterialFactory materialFactory, bool usesToonRendering) : base(materialFactory) + public GameMaterialManager(IMaterialFactory materialFactory, bool usesToonRendering, Native.GameBoxNativeLighting nativeLighting = null) : base(materialFactory) { UsesToonRendering = usesToonRendering; + NativeLighting = usesToonRendering ? null : nativeLighting; _waterMaterial = MaterialFactory.CreateMaterial(usesToonRendering ? ToonWaterShaderName : WaterShaderName); _transparentMaterial = MaterialFactory.CreateMaterial(usesToonRendering ? ToonTransparentShaderName : TransparentShaderName); _alphaCutoutMaterial = MaterialFactory.CreateMaterial(usesToonRendering ? ToonCutoutShaderName : AlphaCutoutShaderName); @@ -78,7 +89,8 @@ namespace Pal3.Game.Rendering.Material public void Dispose() { - if (_disposed) return; + if (_disposed) + return; _disposed = true; DisposePool(_waterMaterialPool); DisposePool(_transparentMaterialPool); @@ -104,7 +116,8 @@ namespace Pal3.Game.Rendering.Material (string name, ITexture2D texture) mainTexture, (string name, ITexture2D texture) bakedLightmap, Color tintColor, - GameBoxBlendFlag blendFlag) + GameBoxBlendFlag blendFlag, + GameBoxMaterial? sourceMaterial = null) { float lightmapScale = rendererType == RendererType.Pol ? PolLightmapScale : DefaultLightmapScale; switch (blendFlag) @@ -132,10 +145,17 @@ namespace Pal3.Game.Rendering.Material IMaterial material = RentMaterial(pool, template); material.SetMainTexture(mainTexture.texture); material.SetColor(TintColorPropertyId, tintColor); + if (NativeLighting != null) + { + material.SetFloat(ShaderUtility.GetPropertyIdByName("_GbNativeLighting"), 1); + material.SetColor(ShaderUtility.GetPropertyIdByName("_GbMaterialDiffuse"), sourceMaterial?.Diffuse ?? Color.White); + material.SetColor(ShaderUtility.GetPropertyIdByName("_GbMaterialAmbient"), sourceMaterial?.Ambient ?? Color.White); + } material.SetFloat(LightmapScalePropertyId, lightmapScale); SetBakedLightmap(material, bakedLightmap.texture); if (UsesToonRendering) { + material.SetFloat(ShaderUtility.GetPropertyIdByName("_SourceDiffuseAlpha"), sourceMaterial?.Diffuse.A ?? 1f); material.SetFloat(ReceiveShadowsPropertyId, 1f); material.SetFloat(CharacterPropertyId, rendererType is RendererType.Mv3 or RendererType.Msh ? 1f : 0f); } @@ -166,7 +186,8 @@ namespace Pal3.Game.Rendering.Material IMaterial material = RentMaterial(_waterMaterialPool, _waterMaterial); material.SetMainTexture(mainTexture.texture); material.SetFloat(WaterAlphaPropId, opacity); - if (UsesToonRendering) material.SetFloat(ReceiveShadowsPropertyId, 1f); + if (UsesToonRendering) + material.SetFloat(ReceiveShadowsPropertyId, 1f); SetBakedLightmap(material, bakedLightmap.texture); return material; } @@ -184,7 +205,8 @@ namespace Pal3.Game.Rendering.Material protected override void ReturnToPool(IMaterial material) { - if (material == null || material.IsNativeObjectDisposed) return; + if (material == null || material.IsNativeObjectDisposed) + return; (Stack pool, int capacity) = material.ShaderName switch { @@ -196,7 +218,8 @@ namespace Pal3.Game.Rendering.Material _ => (null, 0), }; - if (pool == null) return; + if (pool == null) + return; if (_disposed || pool.Count >= capacity) { material.Destroy(); diff --git a/Assets/Scripts/Pal3.Game/Rendering/Material/IMaterialManager.cs b/Assets/Scripts/Pal3.Game/Rendering/Material/IMaterialManager.cs index 968b24b8..0cdaebec 100644 --- a/Assets/Scripts/Pal3.Game/Rendering/Material/IMaterialManager.cs +++ b/Assets/Scripts/Pal3.Game/Rendering/Material/IMaterialManager.cs @@ -1,4 +1,4 @@ -// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ // Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved. // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ @@ -12,7 +12,20 @@ namespace Pal3.Game.Rendering.Material public interface IMaterialManager : IDisposable { - public bool UsesToonRendering { get; } + public bool UsesToonRendering + { + get; + } + + public bool RequiresNormals + { + get; + } + + public Native.GameBoxNativeLighting NativeLighting + { + get; + } /// /// Create a material for effect sprite without alpha channel. @@ -41,7 +54,8 @@ namespace Pal3.Game.Rendering.Material (string name, ITexture2D texture) mainTexture, (string name, ITexture2D texture) bakedLightmap, Color tintColor, - GameBoxBlendFlag blendFlag); + GameBoxBlendFlag blendFlag, + GameBoxMaterial? sourceMaterial = null); /// /// Create material for water surface @@ -79,4 +93,4 @@ namespace Pal3.Game.Rendering.Material /// Materials to return public void ReturnToPool(IMaterial[] materials); } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native.meta b/Assets/Scripts/Pal3.Game/Rendering/Native.meta new file mode 100644 index 00000000..f2cb7594 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 296a877b824a4097b30c18f42e6c2471 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderOrder.cs b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderOrder.cs new file mode 100644 index 00000000..5722e2b3 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderOrder.cs @@ -0,0 +1,21 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Native +{ + /// Published scene-graph flush boundaries around combat shadows. + public static class GameBoxBattleRenderOrder + { + public const int BeforeShadows = -1; + public const int AfterShadows = 1; + public const int DirectEffects = 2; + + public static int Actor(bool pal3A, bool ally, int actorId) => + pal3A && (ally || actorId == 7310) ? AfterShadows : BeforeShadows; + + public static int Effect(bool pal3A, bool model) => + model ? pal3A ? AfterShadows : BeforeShadows : DirectEffects; + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderOrder.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderOrder.cs.meta new file mode 100644 index 00000000..d2a4596c --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderOrder.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1a422b569c2d40819f95ac4c5108eac6 diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderPhase.cs b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderPhase.cs new file mode 100644 index 00000000..00062ca6 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderPhase.cs @@ -0,0 +1,118 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Native +{ + using System.Collections.Generic; + using System.Linq; + using Engine.Extensions; + using UnityEngine; + + // A native post-shadow scene graph must execute in URP's transparent pass, + // including its opaque draws. Copies retain the original blend/depth state. + [ExecuteAlways] + [DisallowMultipleComponent] + public sealed class GameBoxBattleRenderPhase : MonoBehaviour + { + private sealed class Binding + { + public Renderer Renderer; + public Material[] Sources; + public Material[] Copies; + + public void Release() + { + if (Renderer != null) + { + Material[] current = Renderer.sharedMaterials; + for (int i = 0; i < current.Length && i < Copies.Length; i++) + if (current[i] == Copies[i]) + current[i] = Sources[i]; + Renderer.sharedMaterials = current; + } + foreach (Material copy in Copies) + if (copy != null) + copy.Destroy(); + } + } + + private readonly Dictionary _bindings = new(); + + public IEnumerable SourceMaterials => _bindings.Values.SelectMany(binding => binding.Sources).Where(material => material != null); + + public static void Apply(GameObject root, int order) + { + var phase = root.GetComponent(); + if (phase == null && order > 0) + phase = root.AddComponent(); + if (phase != null) + phase.ApplyOrder(order); + else + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + renderer.sortingOrder = order; + } + + private void ApplyOrder(int order) + { + foreach (Renderer renderer in _bindings.Keys.Where(renderer => renderer == null || !renderer.transform.IsChildOf(transform)).ToArray()) + { + _bindings[renderer].Release(); + _bindings.Remove(renderer); + } + if (order <= 0) + { + Release(); + foreach (Renderer renderer in GetComponentsInChildren(true)) + renderer.sortingOrder = order; + return; + } + foreach (Renderer renderer in GetComponentsInChildren(true)) + { + renderer.sortingOrder = order; + Material[] current = renderer.sharedMaterials; + if (!_bindings.TryGetValue(renderer, out Binding binding) || binding.Copies.Length != current.Length) + { + binding?.Release(); + current = renderer.sharedMaterials; + binding = new Binding { Renderer = renderer, Sources = new Material[current.Length], Copies = new Material[current.Length] }; + _bindings[renderer] = binding; + } + for (int i = 0; i < current.Length; i++) + { + Material source = current[i] == binding.Copies[i] ? binding.Sources[i] : current[i]; + if (!ReferenceEquals(source, binding.Sources[i]) || binding.Copies[i] == null && source != null) + { + if (binding.Copies[i] != null) + binding.Copies[i].Destroy(); + binding.Sources[i] = source; + binding.Copies[i] = source == null ? null : new Material(source) + { + name = source.name + " (combat phase)", + hideFlags = HideFlags.HideAndDontSave + }; + } + if (source != null) + { + Material copy = binding.Copies[i]; + copy.shader = source.shader; + copy.CopyPropertiesFromMaterial(source); + copy.renderQueue = source.renderQueue <= 2500 ? 3002 : 3003; + } + current[i] = binding.Copies[i]; + } + renderer.sharedMaterials = current; + } + } + + private void Release() + { + foreach (Binding binding in _bindings.Values) + binding.Release(); + _bindings.Clear(); + } + + private void OnDestroy() => Release(); + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderPhase.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderPhase.cs.meta new file mode 100644 index 00000000..d866917c --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleRenderPhase.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ad7d1f11d27e496989c1031a9962a7c8 diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadow.cs b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadow.cs new file mode 100644 index 00000000..05d5d895 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadow.cs @@ -0,0 +1,69 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Native +{ + using System; + using Core.DataReader.Mv3; + using Engine.Extensions; + using UnityEngine; + + /// A captured native shadow radius and the current role position. + public readonly struct GameBoxBattleShadow + { + public Vector3 Position + { + get; + } + + public float NativeRadius + { + get; + } + + public GameBoxBattleShadow(Vector3 position, float nativeRadius) + { + Position = position; + NativeRadius = nativeRadius; + } + + public Vector3 Corner(int index) + { + float radius = NativeRadius / UnityPrimitivesConvertor.GameBoxUnitToUnityUnit; + float height = .5f / UnityPrimitivesConvertor.GameBoxUnitToUnityUnit; + return Position + (index switch + { + 0 => new Vector3(radius, height, radius), + 1 => new Vector3(-radius, height, radius), + 2 => new Vector3(-radius, height, -radius), + 3 => new Vector3(radius, height, -radius), + _ => throw new ArgumentOutOfRangeException(nameof(index)) + }); + } + + // GetCollideOBB takes the union of the action's authored mesh bounds. + // The combat shadow uses the complete X/Z width as its radius. + public static float CaptureRadius(Mv3File model) + { + if (model == null) + throw new ArgumentNullException(nameof(model)); + if (model.Meshes.Length == 0) + throw new ArgumentException("A shadow model must contain meshes.", nameof(model)); + float minX = float.MaxValue, minZ = float.MaxValue; + float maxX = float.MinValue, maxZ = float.MinValue; + foreach (Mv3Mesh mesh in model.Meshes) + { + minX = Math.Min(minX, mesh.GameBoxBoundsMin.X); + minZ = Math.Min(minZ, mesh.GameBoxBoundsMin.Z); + maxX = Math.Max(maxX, mesh.GameBoxBoundsMax.X); + maxZ = Math.Max(maxZ, mesh.GameBoxBoundsMax.Z); + } + return Math.Min(maxX - minX, maxZ - minZ); + } + + public static bool IsVisible(bool pal3A, bool valid, bool modelAlive, bool ally, int hp, float blend) => + valid && (!pal3A || blend >= .5f) && (modelAlive || ally && hp > 0); + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadow.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadow.cs.meta new file mode 100644 index 00000000..c05f35fc --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadow.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e15d28a4b8884ee5a05611b9f380c200 diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadowRenderer.cs b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadowRenderer.cs new file mode 100644 index 00000000..9ef5ac9d --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadowRenderer.cs @@ -0,0 +1,89 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Native +{ + using System; + using System.Collections.Generic; + using Engine.Extensions; + using UnityEngine; + using UnityEngine.Rendering; + + /// Original combat texture quads, independent of Unity light shadows. + public sealed class GameBoxBattleShadowRenderer : IDisposable + { + private readonly Mesh _mesh; + private readonly Material _material; + private readonly List _vertices = new(); + private readonly List _uv = new(); + private readonly List _indices = new(); + + public int Count => _vertices.Count / 4; + + public GameBoxBattleShadowRenderer(string variant, Texture texture) + { + bool pal3A = string.Equals(variant, "PAL3A", StringComparison.OrdinalIgnoreCase); + if (!pal3A && !string.Equals(variant, "PAL3", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Unknown GameBox shadow variant.", nameof(variant)); + if (texture == null) + throw new ArgumentNullException(nameof(texture)); + Shader shader = Shader.Find("Pal3/BattleShadow"); + if (shader == null) + throw new InvalidOperationException("The battle shadow shader is missing."); + _material = new Material(shader) { name = "Original battle shadow", hideFlags = HideFlags.DontSave, mainTexture = texture }; + // The two shipped shadow.gbf resources deliberately differ. + _material.SetInt("_SrcBlend", (int)(pal3A ? BlendMode.OneMinusSrcAlpha : BlendMode.DstColor)); + _material.SetInt("_DstBlend", (int)(pal3A ? BlendMode.SrcAlpha : BlendMode.Zero)); + _mesh = new Mesh { name = "Original battle shadow quads", hideFlags = HideFlags.DontSave }; + _mesh.MarkDynamic(); + } + + public void Begin() + { + _vertices.Clear(); + _uv.Clear(); + _indices.Clear(); + } + + public void Add(GameBoxBattleShadow shadow) + { + int start = _vertices.Count; + for (int index = 0; index < 4; index++) + _vertices.Add(shadow.Corner(index)); + _uv.Add(new Vector2(0, 0)); + _uv.Add(new Vector2(1, 0)); + _uv.Add(new Vector2(1, 1)); + _uv.Add(new Vector2(0, 1)); + // GameBox splits the quad along 1--3. X mirroring reverses winding. + _indices.Add(start); + _indices.Add(start + 3); + _indices.Add(start + 1); + _indices.Add(start + 3); + _indices.Add(start + 2); + _indices.Add(start + 1); + } + + public void End() + { + _mesh.Clear(); + _mesh.SetVertices(_vertices); + _mesh.SetUVs(0, _uv); + _mesh.SetTriangles(_indices, 0, true); + } + + public void Render(Camera camera, int layer) + { + if (Count > 0) + Graphics.DrawMesh(_mesh, Matrix4x4.identity, _material, layer, camera, 0, null, + ShadowCastingMode.Off, false, null, LightProbeUsage.Off); + } + + public void Dispose() + { + _mesh.Destroy(); + _material.Destroy(); + } + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadowRenderer.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadowRenderer.cs.meta new file mode 100644 index 00000000..ebf4f3b4 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxBattleShadowRenderer.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 021b6304d44641a2ae78a2bdea8ba31b diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxNativeLighting.cs b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxNativeLighting.cs new file mode 100644 index 00000000..a8bf7ef1 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxNativeLighting.cs @@ -0,0 +1,212 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Native +{ + using System; + using System.Collections.Generic; + using Core.DataReader.Lgt; + using Core.Primitives; + using Core.Utilities; + using Engine.Extensions; + using UnityEngine; + + /// Original per-object, two-light selection. Each preview owns its context. + public sealed class GameBoxNativeLighting : IDisposable + { + private readonly bool _pal3A; + private LightNode[] _lights = Array.Empty(); + private readonly List _bindings = new(); + private readonly MaterialPropertyBlock _properties = new(); + private bool _disposed; + private bool _hasLightFile; + private RuntimeLight[] _candidates = new RuntimeLight[1]; + private float[] _weights = new float[1]; + private int[] _order = new int[1]; + + private static readonly int CountId = Shader.PropertyToID("_GbLightCount"); + private static readonly int UnitsId = Shader.PropertyToID("_GbVertexUnits"); + private static readonly int VertexColorId = Shader.PropertyToID("_GbVertexColor"); + private static readonly int SourceFromRendererId = Shader.PropertyToID("_GbSourceFromRenderer"); + private static readonly int[] PositionIds = { Shader.PropertyToID("_GbLightPosition0"), Shader.PropertyToID("_GbLightPosition1") }; + private static readonly int[] DiffuseIds = { Shader.PropertyToID("_GbLightDiffuse0"), Shader.PropertyToID("_GbLightDiffuse1") }; + private static readonly int[] AmbientIds = { Shader.PropertyToID("_GbLightAmbient0"), Shader.PropertyToID("_GbLightAmbient1") }; + private static readonly int[] AttenuationIds = { Shader.PropertyToID("_GbLightAttenuation0"), Shader.PropertyToID("_GbLightAttenuation1") }; + + public GameBoxNativeLighting(string variant) + { + _pal3A = string.Equals(variant, "PAL3A", StringComparison.OrdinalIgnoreCase); + if (!_pal3A && !string.Equals(variant, "PAL3", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Unknown GameBox lighting variant.", nameof(variant)); + } + + public void SetLights(LgtFile lights) + { + if (_disposed) + throw new ObjectDisposedException(nameof(GameBoxNativeLighting)); + _hasLightFile = lights != null; + _lights = lights == null ? Array.Empty() : (LightNode[])lights.LightNodes.Clone(); + _candidates = new RuntimeLight[_lights.Length + 1]; + _weights = new float[_candidates.Length]; + _order = new int[_candidates.Length]; + } + + public IDisposable Bind(MeshRenderer renderer, Vector3 anchor, bool lightmapped, + bool vertexColors, bool environment, float vertexUnits, Func sourceToRenderer = null) + { + if (_disposed) + throw new ObjectDisposedException(nameof(GameBoxNativeLighting)); + if (renderer == null) + throw new ArgumentNullException(nameof(renderer)); + var binding = new Binding(this, renderer, anchor, lightmapped, vertexColors, environment, vertexUnits, sourceToRenderer); + _bindings.Add(binding); + return binding; + } + + public void Apply(Camera camera) + { + if (_disposed) + throw new ObjectDisposedException(nameof(GameBoxNativeLighting)); + if (camera == null) + throw new ArgumentNullException(nameof(camera)); + foreach (Binding binding in _bindings) + { + MeshRenderer renderer = binding.Renderer; + if (renderer == null) + continue; + renderer.GetPropertyBlock(_properties); + _properties.SetFloat(UnitsId, binding.VertexUnits); + _properties.SetFloat(VertexColorId, binding.VertexColors ? 1 : 0); + Matrix4x4 sourceToRenderer = binding.SourceToRenderer?.Invoke() ?? Matrix4x4.identity; + Matrix4x4 sourceFromRenderer = binding.SourceToRenderer == null ? Matrix4x4.identity : sourceToRenderer.inverse; + _properties.SetMatrix(SourceFromRendererId, sourceFromRenderer); + int count = 0; + if (!binding.Lightmapped && !binding.VertexColors) + { + Vector3 anchor = renderer.transform.TransformPoint(sourceToRenderer.MultiplyPoint3x4(binding.Anchor)); + // PAL3 attaches its default before POL, then attaches LGT before actors. + // PAL3A attaches LGT before both, using the default only when LGT is absent. + if (!_pal3A || !_hasLightFile) + Consider(DefaultLight()); + if (_pal3A || !binding.Environment) + foreach (LightNode light in _lights) + if (light.LightDecayType == GameBoxLightDecayType.None || ValidDecayRadius(light.DecayRadius)) + Consider(Convert(light, camera.transform.position)); + + void Consider(RuntimeLight light) + { + float weight = Influence(light, anchor); + if (weight == 0 || !float.IsFinite(weight)) + return; + _candidates[count] = light; + _weights[count] = weight; + count++; + } + } + GameBoxLightOrder.Sort(_order.AsSpan(0, count), _weights.AsSpan(0, count)); + int selected = Math.Min(2, count); + for (int index = 0; index < selected; index++) + Upload(_candidates[_order[index]], index); + _properties.SetFloat(CountId, selected); + renderer.SetPropertyBlock(_properties); + + void Upload(RuntimeLight light, int index) + { + // Source shaders transform lights into object coordinates. Preserve + // that space instead of normalizing inverse-transpose world normals. + Vector3 local = sourceFromRenderer.MultiplyPoint3x4(renderer.transform.InverseTransformPoint(light.Position)) * UnityPrimitivesConvertor.GameBoxUnitToUnityUnit; + _properties.SetVector(PositionIds[index], local); + _properties.SetVector(DiffuseIds[index], light.Diffuse); + _properties.SetVector(AmbientIds[index], light.Ambient); + _properties.SetVector(AttenuationIds[index], light.Attenuation); + } + } + } + + private static RuntimeLight Convert(LightNode light, Vector3 camera) + { + GameBoxMatrix4x4 matrix = light.GameBoxWorldMatrix; + Vector3 position = new(-matrix.Tx, matrix.Ty, matrix.Tz); + if (light.LightType == GameBoxLightType.Directional) + position = camera * UnityPrimitivesConvertor.GameBoxUnitToUnityUnit - + new Vector3(matrix.Yx, -matrix.Yy, -matrix.Yz) * 100000; + return new RuntimeLight + { + Position = position / UnityPrimitivesConvertor.GameBoxUnitToUnityUnit, + Diffuse = light.UseDiffuse ? new Vector4(light.LightColor.R, light.LightColor.G, light.LightColor.B, 0) : Vector4.zero, + Ambient = new Vector4(light.AmbientColor.R, light.AmbientColor.G, light.AmbientColor.B, 0), + Attenuation = Attenuation(light.LightDecayType, light.DecayRadius), + }; + } + + private static RuntimeLight DefaultLight() => new() + { + Diffuse = new Vector4(.01f, .01f, .01f, 0), + Ambient = new Vector4(-.25f, -.25f, -.25f, 0), + Attenuation = Attenuation(GameBoxLightDecayType.Distance, 300), + }; + + private static bool ValidDecayRadius(float radius) => float.IsFinite(radius) && radius >= 1e-10f; + + public static Vector4 Attenuation(GameBoxLightDecayType type, float radius) => type switch + { + GameBoxLightDecayType.None => new Vector4(1, 0, 0, 0), + GameBoxLightDecayType.Distance when ValidDecayRadius(radius) => new Vector4(.01f, 1 / radius, 0, 0), + GameBoxLightDecayType.Square when ValidDecayRadius(radius) => new Vector4(.01f, 0, 1 / (radius * radius), 0), + GameBoxLightDecayType.Distance or GameBoxLightDecayType.Square => Vector4.zero, + _ => throw new ArgumentOutOfRangeException(nameof(type)), + }; + + private static float Influence(RuntimeLight light, Vector3 point) + { + float distance = Vector3.Distance(light.Position, point) * UnityPrimitivesConvertor.GameBoxUnitToUnityUnit; + Vector4 attenuation = light.Attenuation; + float effect = Mathf.Min(1, 1 / (attenuation.x + attenuation.y * distance + attenuation.z * distance * distance)); + return effect * (light.Diffuse.x + light.Diffuse.y + light.Diffuse.z) / 3; + } + + public void Dispose() + { + _disposed = true; + _bindings.Clear(); + _lights = Array.Empty(); + } + + private struct RuntimeLight + { + public Vector3 Position; + public Vector4 Diffuse; + public Vector4 Ambient; + public Vector4 Attenuation; + } + + private sealed class Binding : IDisposable + { + private readonly GameBoxNativeLighting _owner; + internal readonly MeshRenderer Renderer; + internal readonly Vector3 Anchor; + internal readonly bool Lightmapped; + internal readonly bool VertexColors; + internal readonly bool Environment; + internal readonly float VertexUnits; + internal readonly Func SourceToRenderer; + + internal Binding(GameBoxNativeLighting owner, MeshRenderer renderer, Vector3 anchor, + bool lightmapped, bool vertexColors, bool environment, float vertexUnits, Func sourceToRenderer) + { + _owner = owner; + Renderer = renderer; + Anchor = anchor; + Lightmapped = lightmapped; + VertexColors = vertexColors; + Environment = environment; + VertexUnits = vertexUnits; + SourceToRenderer = sourceToRenderer; + } + + public void Dispose() => _owner._bindings.Remove(this); + } + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxNativeLighting.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxNativeLighting.cs.meta new file mode 100644 index 00000000..30ce0d03 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Native/GameBoxNativeLighting.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 78ff948091a44addb08dc7cc87eac3bb diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/CvdModelRenderer.cs b/Assets/Scripts/Pal3.Game/Rendering/Renderer/CvdModelRenderer.cs index a2becb84..983dfaf3 100644 --- a/Assets/Scripts/Pal3.Game/Rendering/Renderer/CvdModelRenderer.cs +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/CvdModelRenderer.cs @@ -27,8 +27,9 @@ namespace Pal3.Game.Rendering.Renderer /// public sealed class CvdModelRenderer : GameEntityScript, IDisposable { - private readonly Dictionary _textureCache = new (); + private readonly Dictionary _textureCache = new(); private readonly List _renderers = new(); + private readonly List _nativeLightingBindings = new(); private sealed class CvdNodeRenderState { @@ -47,7 +48,8 @@ namespace Pal3.Game.Rendering.Renderer private float _currentAnimationTime; private float _animationDuration; - private CancellationTokenSource _animationCts = new (); + private CancellationTokenSource _animationCts; + private IGameEntity _meshRoot; private IMaterialManager _materialManager; @@ -66,6 +68,7 @@ namespace Pal3.Game.Rendering.Renderer Color? tintColor = default, float initTime = 0f) { + Dispose(); _materialManager = materialManager; _animationDuration = cvdFile.AnimationDuration; _tintColor = tintColor ?? Color.White; @@ -76,7 +79,7 @@ namespace Pal3.Game.Rendering.Renderer BuildTextureCache(node, textureProvider, _textureCache); } - IGameEntity root = GameEntityFactory.Create("Cvd Mesh", + _meshRoot = GameEntityFactory.Create("Cvd Mesh", GameEntity, worldPositionStays: false); for (int i = 0; i < cvdFile.RootNodes.Length; i++) @@ -87,7 +90,7 @@ namespace Pal3.Game.Rendering.Renderer hashKey, cvdFile.RootNodes[i], _textureCache, - root); + _meshRoot); } } @@ -103,14 +106,15 @@ namespace Pal3.Game.Rendering.Renderer public float GetDefaultAnimationDuration(float timeScale = 1f) { - if (timeScale == 0f) return 0f; + if (timeScale == 0f) + return 0f; return _animationDuration / MathF.Abs(timeScale); } public Bounds GetRendererBounds() { bool boundsInitialized = false; - Bounds bounds = new (Transform.Position, Vector3.one); + Bounds bounds = new(Transform.Position, Vector3.one); foreach (CvdNodeRenderState node in _renderers) { @@ -135,7 +139,7 @@ namespace Pal3.Game.Rendering.Renderer public Bounds GetMeshBounds() { bool boundsInitialized = false; - Bounds bounds = new (Vector3.zero, Vector3.one); + Bounds bounds = new(Vector3.zero, Vector3.one); foreach (CvdNodeRenderState node in _renderers) { @@ -166,10 +170,13 @@ namespace Pal3.Game.Rendering.Renderer foreach (CvdMeshSection meshSection in node.Mesh.MeshSections) { string textureName = meshSection.Material.TextureFileNames[0]; - if (string.IsNullOrEmpty(textureName)) continue; - if (textureCache.ContainsKey(textureName)) continue; + if (string.IsNullOrEmpty(textureName)) + continue; + if (textureCache.ContainsKey(textureName)) + continue; ITexture2D texture2D = textureProvider.GetTexture(textureName); - if (texture2D != null) textureCache[textureName] = texture2D; + if (texture2D != null) + textureCache[textureName] = texture2D; } } @@ -239,7 +246,8 @@ namespace Pal3.Game.Rendering.Renderer continue; int vertexCount = meshSection.FrameVertices[frameIndex].Length; - MeshDataBuffer meshDataBuffer = new(vertexCount, 0, vertexCount, meshSection.GameBoxTriangles.Length); + MeshDataBuffer meshDataBuffer = new(vertexCount, _materialManager.NativeLighting != null ? vertexCount : 0, + vertexCount, meshSection.GameBoxTriangles.Length); meshSection.GameBoxTriangles.ToUnityTriangles(meshDataBuffer.TriangleBuffer); UpdateMeshDataBuffer(meshDataBuffer, meshSection, frameIndex, influence, frameMatrix); @@ -247,30 +255,42 @@ namespace Pal3.Game.Rendering.Renderer meshEntity, worldPositionStays: false); // Attach BlendFlag and GameBoxMaterial to the GameEntity for better debuggability. - #if UNITY_EDITOR +#if UNITY_EDITOR MaterialInfoPresenter materialInfoPresenter = meshEntity.AddComponent(); materialInfoPresenter.blendFlag = meshSection.BlendFlag; materialInfoPresenter.material = meshSection.Material; - #endif +#endif IMaterial[] materials = _materialManager.CreateStandardMaterials( RendererType.Cvd, mainTexture: (textureName, texture), bakedLightmap: default, // CVD models don't have shadow textures tintColor: _tintColor, - blendFlag: meshSection.BlendFlag); + blendFlag: meshSection.BlendFlag, + sourceMaterial: meshSection.Material); StaticMeshRenderer meshRenderer = meshSectionEntity.AddComponent(); Mesh renderMesh = meshRenderer.Render( vertices: meshDataBuffer.VertexBuffer, triangles: meshDataBuffer.TriangleBuffer, - normals: null, + normals: _materialManager.NativeLighting != null ? meshDataBuffer.NormalBuffer : null, mainTextureUvs: (channel: 0, uvs: meshDataBuffer.UvBuffer), secondaryTextureUvs: default, // CVD models don't have secondary texture materials: materials, isDynamic: true); - if (usesToon) renderMesh.RecalculateNormals(); + if (usesToon) + renderMesh.RecalculateNormals(); + + if (_materialManager.NativeLighting != null) + { + // The IPOL loader retains VertStart from its last loaded + // frame as the section's light-selection point. + Vector3 anchor = meshSection.FrameVertices[^1][0].GameBoxPosition.CvdPositionToUnityPosition(); + _nativeLightingBindings.Add(_materialManager.NativeLighting.Bind( + meshRenderer.GetComponent(), anchor, false, false, false, + UnityPrimitivesConvertor.GameBoxUnitToUnityUnit, () => nodeMeshes.Pose.matrix)); + } nodeMeshes.Sections.Add((i, new RenderMeshComponent { @@ -313,6 +333,15 @@ namespace Pal3.Game.Rendering.Renderer bool updateUvs = true) { CvdVertex[] frameVertices = meshSection.FrameVertices[frameIndex]; + if (meshDataBuffer.NormalBuffer?.Length > 0) + { + // gbIpolMesh::DrawSubSet copies the current frame's authored + // normals while interpolating only positions and UVs. Keep + // normals in source space; the lighting binding undoes the + // node matrix baked into positions, including nonuniform scale. + for (int i = 0; i < frameVertices.Length; i++) + meshDataBuffer.NormalBuffer[i] = frameVertices[i].GameBoxNormal.CvdPositionToUnityPosition(1); + } if (influence < float.Epsilon) { @@ -320,7 +349,8 @@ namespace Pal3.Game.Rendering.Renderer { meshDataBuffer.VertexBuffer[i] = matrix.MultiplyPoint3x4( frameVertices[i].GameBoxPosition.CvdPositionToUnityPosition()); - if (updateUvs) meshDataBuffer.UvBuffer[i] = frameVertices[i].Uv.ToUnityVector2(); + if (updateUvs) + meshDataBuffer.UvBuffer[i] = frameVertices[i].Uv.ToUnityVector2(); } } else @@ -344,7 +374,8 @@ namespace Pal3.Game.Rendering.Renderer private void UpdateMesh(float time) { _currentAnimationTime = time; - if (_renderers.Count == 0) return; + if (_renderers.Count == 0) + return; bool usesToon = _materialManager.UsesToonRendering; foreach (CvdNodeRenderState node in _renderers) @@ -353,7 +384,8 @@ namespace Pal3.Game.Rendering.Renderer var previous = node.Pose; bool matrixChanged = !pose.matrix.Equals(previous.matrix); bool vertexFrameChanged = pose.frameIndex != previous.frameIndex || pose.influence != previous.influence; - if (!matrixChanged && !vertexFrameChanged) continue; + if (!matrixChanged && !vertexFrameChanged) + continue; node.Pose = pose; bool normalTransformChanged = usesToon && @@ -368,8 +400,12 @@ namespace Pal3.Game.Rendering.Renderer CvdMeshSection source = node.Node.Mesh.MeshSections[sectionIndex]; UpdateMeshDataBuffer(buffer, source, pose.frameIndex, pose.influence, pose.matrix, vertexFrameChanged); mesh.SetVertices(buffer.VertexBuffer); - if (usesToon && (vertexFrameChanged || normalTransformChanged)) mesh.RecalculateNormals(); - if (vertexFrameChanged) mesh.SetUVs(0, buffer.UvBuffer); + if (_materialManager.NativeLighting != null) + mesh.SetNormals(buffer.NormalBuffer); + if (usesToon && (vertexFrameChanged || normalTransformChanged)) + mesh.RecalculateNormals(); + if (vertexFrameChanged) + mesh.SetUVs(0, buffer.UvBuffer); mesh.RecalculateBounds(); } } @@ -415,8 +451,7 @@ namespace Pal3.Game.Rendering.Renderer StopCurrentAnimation(); - if (!_animationCts.IsCancellationRequested) _animationCts.Cancel(); - + _animationCts?.Dispose(); _animationCts = new CancellationTokenSource(); yield return PlayAnimationInternalAsync(timeScale, @@ -480,7 +515,8 @@ namespace Pal3.Game.Rendering.Renderer private Vector3 GetPosition(float time, CvdAnimationPositionKeyFrame[] nodePositionInfo) { - if (nodePositionInfo.Length == 1) return nodePositionInfo[0].GameBoxPosition.CvdPositionToUnityPosition(); + if (nodePositionInfo.Length == 1) + return nodePositionInfo[0].GameBoxPosition.CvdPositionToUnityPosition(); // Find the two keyframes that the current time lies between // using binary search @@ -550,7 +586,8 @@ namespace Pal3.Game.Rendering.Renderer private Quaternion GetRotation(float time, CvdAnimationRotationKeyFrame[] nodeRotationInfo) { - if (nodeRotationInfo.Length == 1) return nodeRotationInfo[0].GameBoxRotation.CvdQuaternionToUnityQuaternion(); + if (nodeRotationInfo.Length == 1) + return nodeRotationInfo[0].GameBoxRotation.CvdQuaternionToUnityQuaternion(); // Find the two keyframes that the current time lies between int startIndex = 0; @@ -579,7 +616,7 @@ namespace Pal3.Game.Rendering.Renderer public void StopCurrentAnimation() { - if (!_animationCts.IsCancellationRequested) + if (_animationCts != null && !_animationCts.IsCancellationRequested) { _animationCts.Cancel(); } @@ -588,6 +625,11 @@ namespace Pal3.Game.Rendering.Renderer public void Dispose() { StopCurrentAnimation(); + _animationCts?.Dispose(); + _animationCts = null; + foreach (IDisposable binding in _nativeLightingBindings) + binding.Dispose(); + _nativeLightingBindings.Clear(); foreach (CvdNodeRenderState node in _renderers) { @@ -602,6 +644,11 @@ namespace Pal3.Game.Rendering.Renderer } } _renderers.Clear(); + _meshRoot?.Destroy(); + _meshRoot = null; + // Textures are borrowed from the provider; release only our references. + _textureCache.Clear(); + _materialManager = null; } } } diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.Selection.cs b/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.Selection.cs new file mode 100644 index 00000000..319921d6 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.Selection.cs @@ -0,0 +1,51 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Renderer +{ + using System.Collections.Generic; + using UnityEngine; + + public sealed partial class Mv3ModelRenderer + { + private static readonly int SelectionProperty = Shader.PropertyToID("_BattleSelection"); + private MaterialPropertyBlock _selectionProperties; + private readonly Dictionary _selectionBlocks = new(); + + // Native selection replaces body RGB only. Tag-node weapons keep their + // own lighting; invisibility/fade and native-light MPB values survive. + public void SetSelectionLuminance(float luminance) + { + if (_meshEntities == null) + return; + _selectionProperties ??= new MaterialPropertyBlock(); + foreach (var entity in _meshEntities) + { + var renderer = entity?.GetComponent(); + if (renderer == null) + continue; + if (luminance < 0 && !_selectionBlocks.ContainsKey(renderer)) + continue; + renderer.GetPropertyBlock(_selectionProperties); + if (luminance >= 0) + { + if (!_selectionBlocks.ContainsKey(renderer)) + _selectionBlocks.Add(renderer, _selectionProperties.isEmpty && _materialManager.NativeLighting == null); + _selectionProperties.SetFloat(SelectionProperty, luminance); + renderer.SetPropertyBlock(_selectionProperties); + } + else + { + // An otherwise empty Toon body must rejoin the SRP Batcher. + // Native lighting owns an existing block and keeps its values. + bool owned = _selectionBlocks[renderer]; + _selectionBlocks.Remove(renderer); + _selectionProperties.SetFloat(SelectionProperty, -1); + renderer.SetPropertyBlock(owned ? null : _selectionProperties); + } + } + } + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.Selection.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.Selection.cs.meta new file mode 100644 index 00000000..ec2abee9 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.Selection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e408b0b5299e4efd98d8a1a6487ab01c diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.WeaponPresentation.cs b/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.WeaponPresentation.cs new file mode 100644 index 00000000..c3159c06 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.WeaponPresentation.cs @@ -0,0 +1,199 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Renderer +{ + using System; + using System.Collections.Generic; + using Core.DataReader.Pol; + using Engine.Extensions; + using UnityEngine; + using UnityEngine.Rendering; + + public sealed partial class Mv3ModelRenderer + { + private readonly Dictionary _weaponBlades = new(StringComparer.OrdinalIgnoreCase); + private Material _weaponBladeMaterial; + private bool _leftWeaponVisible = true, _rightWeaponVisible = true; + private double? _lastWeaponClock; + private bool _preparedSinceFlush, _preparedBodyAdvanced; + private float _bladeRate = 1, _bladeSeconds = .12f; + private bool _hasNativeFlush; + + public bool UseRenderBladeClock + { + get; set; + } + + public bool RightWeaponVisible => _rightWeaponVisible; + + public void ResetWeaponPresentation() => DisposeWeaponPresentation(); + + public bool TryGetRightWeaponBladeTip(out Vector3 position) + { + position = default; + return _weaponBlades.TryGetValue("tag_weapon1", out WeaponBlade blade) && blade.TryGetLastPosition(out position); + } + + public void SetWeaponVisibility(bool left, bool right) + { + _leftWeaponVisible = left; + _rightWeaponVisible = right; + if (_tagNodesInfo == null || _tagNodes == null) + return; + for (int index = 0; index < _tagNodesInfo.Length; index++) + { + if (_tagNodes[index]?.NativeObject is not GameObject weapon) + continue; + string tag = _tagNodesInfo[index].Name; + if (tag.Equals("tag_weapon1", StringComparison.OrdinalIgnoreCase)) + SetWeaponRendering(weapon, right); + else if (tag.Equals("tag_weapon2", StringComparison.OrdinalIgnoreCase)) + SetWeaponRendering(weapon, left); + } + } + + private static void SetWeaponRendering(GameObject weapon, bool visible) + { + // Disabling the object invokes PolyModelRenderer.Dispose. Weapon + // attachment flags only control drawing and must retain geometry. + foreach (UnityEngine.Renderer renderer in weapon.GetComponentsInChildren(true)) + renderer.enabled = visible; + } + + // Stage the current body/weapon state after sampling transforms. PAL3 + // consumes it once per displayed frame; compatibility mode samples here. + public void SampleWeaponBlades(double actorClock, float playbackRate, float trailSeconds) + { + if ((_tagNodePolFile?.TagNodes == null || _tagNodePolFile.TagNodes.Length < 2 || _tagNodes == null) && _weaponBlades.Count == 0) + return; + if (!double.IsFinite(actorClock) || !float.IsFinite(playbackRate) || playbackRate < 0 || !float.IsFinite(trailSeconds) || trailSeconds <= 0) + throw new ArgumentException("Invalid original weapon blade clock."); + if (_lastWeaponClock.HasValue && actorClock < _lastWeaponClock.Value) + DisposeWeaponPresentation(); + float delta = (float)(actorClock - (_lastWeaponClock ?? actorClock)); + // Idempotent synchronization must not revoke an advance that this + // displayed frame has prepared but has not flushed yet. + _preparedBodyAdvanced = _preparedSinceFlush && _preparedBodyAdvanced || + !_lastWeaponClock.HasValue || actorClock > _lastWeaponClock.Value; + _preparedSinceFlush = true; + _lastWeaponClock = actorClock; + _bladeRate = playbackRate; + _bladeSeconds = trailSeconds; + if (!UseRenderBladeClock) + SampleBladePoses(delta, false, true); + } + + private void SampleBladePoses(float delta, bool poseOnly, bool bodyVisible) + { + var sampled = new HashSet(StringComparer.OrdinalIgnoreCase); + for (int index = 0; index < (_tagNodesInfo?.Length ?? 0); index++) + { + if (_tagNodes?[index]?.NativeObject is not GameObject weapon) + continue; + string tag = _tagNodesInfo[index].Name; + bool right = tag.Equals("tag_weapon1", StringComparison.OrdinalIgnoreCase); + bool left = tag.Equals("tag_weapon2", StringComparison.OrdinalIgnoreCase); + if (!left && !right) + continue; + if (!_weaponBlades.TryGetValue(tag, out WeaponBlade blade)) + _weaponBlades.Add(tag, blade = new WeaponBlade(_tagNodePolFile.TagNodes)); + bool visible = bodyVisible && (right ? _rightWeaponVisible : _leftWeaponVisible); + if (poseOnly) + blade.SamplePose(weapon.transform, visible, _bladeSeconds, rebuildMesh: false); + else + blade.Sample(weapon.transform, visible, delta, _bladeRate, _bladeSeconds); + sampled.Add(tag); + } + foreach (var pair in _weaponBlades) + if (!sampled.Contains(pair.Key)) + { + if (poseOnly) + pair.Value.SamplePose(null, false, _bladeSeconds, rebuildMesh: false); + else + pair.Value.Sample(null, false, delta, _bladeRate, _bladeSeconds); + } + } + + // Transfer only when the caller has verified the same equipped POL. + // Keys are semantic hand tags, so reordering or absent tags in a new + // actor clip cannot remap a right-hand trail onto the left hand. + public void MoveWeaponPresentationFrom(Mv3ModelRenderer previous) + { + if (previous == null || ReferenceEquals(previous, this)) + return; + DisposeWeaponPresentation(); + foreach (var pair in previous._weaponBlades) + _weaponBlades.Add(pair.Key, pair.Value); + previous._weaponBlades.Clear(); + _weaponBladeMaterial = previous._weaponBladeMaterial; + previous._weaponBladeMaterial = null; + _lastWeaponClock = previous._lastWeaponClock; + previous._lastWeaponClock = null; + _preparedSinceFlush = previous._preparedSinceFlush; + _preparedBodyAdvanced = previous._preparedBodyAdvanced; + _bladeRate = previous._bladeRate; + _bladeSeconds = previous._bladeSeconds; + _hasNativeFlush = previous._hasNativeFlush; + _leftWeaponVisible = previous._leftWeaponVisible; + _rightWeaponVisible = previous._rightWeaponVisible; + } + + public void RenderWeaponBlades(Camera camera) + { + if (_weaponBlades.Count == 0 || camera == null) + return; + if (_weaponBladeMaterial == null) + { + _weaponBladeMaterial = WeaponBlade.CreateMaterial(); + } + foreach (WeaponBlade blade in _weaponBlades.Values) + blade.Render(camera, _weaponBladeMaterial, GameEntity.Layer); + } + + // PAL3's two Scene.End calls each Update then Flush all retained records. + // The owner supplies one stable presentation-frame delta for both calls. + public void RenderPublishedWeaponBlades(Camera camera, float frameDelta, bool newFrame, bool bodyVisible) + { + bool update = newFrame || !_hasNativeFlush; + if (update) + { + // The frozen body pool stops while the absolute-time actor + // continues. A retained record with no body update (for example + // a defeated role during results) still uses the frame delta. + if (_preparedSinceFlush && !_preparedBodyAdvanced) + frameDelta = 0; + SampleBladePoses(0, true, bodyVisible); + _preparedSinceFlush = false; + _preparedBodyAdvanced = false; + } + if (_weaponBlades.Count == 0 || camera == null) + return; + _weaponBladeMaterial ??= WeaponBlade.CreateMaterial(); + for (int flush = 0; flush < 2; flush++) + foreach (WeaponBlade blade in _weaponBlades.Values) + { + if (update) + blade.Advance(frameDelta, _bladeRate, rebuildMesh: false); + blade.RenderFlush(camera, _weaponBladeMaterial, GameEntity.Layer, flush, update); + } + _hasNativeFlush = true; + } + + private void DisposeWeaponPresentation() + { + foreach (WeaponBlade blade in _weaponBlades.Values) + blade.Dispose(); + _weaponBlades.Clear(); + _lastWeaponClock = null; + _preparedSinceFlush = false; + _preparedBodyAdvanced = false; + _hasNativeFlush = false; + if (_weaponBladeMaterial != null) + _weaponBladeMaterial.Destroy(); + _weaponBladeMaterial = null; + } + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.WeaponPresentation.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.WeaponPresentation.cs.meta new file mode 100644 index 00000000..d0806441 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.WeaponPresentation.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ff39f9fcfd51477d97d3bd5b8b1ebba7 diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.cs b/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.cs index 1eb5e90d..0c4a948f 100644 --- a/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.cs +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/Mv3ModelRenderer.cs @@ -1,4 +1,4 @@ -// ------------------------------------------------------------------------ +// ------------------------------------------------------------------------ // Copyright (c) 2021-2026, Jiaqi (0x7c13) Liu. All rights reserved. // See LICENSE file in the project root for license information. // ------------------------------------------------------------------------ @@ -26,9 +26,10 @@ namespace Pal3.Game.Rendering.Renderer /// /// MV3(.mv3) model renderer /// - public sealed class Mv3ModelRenderer : GameEntityScript, IDisposable + public sealed partial class Mv3ModelRenderer : GameEntityScript, IDisposable { public event EventHandler AnimationLoopPointReached; + public event EventHandler AnimationEventTriggered; private const string MV3_ANIMATION_HOLD_EVENT_NAME = "hold"; @@ -48,8 +49,10 @@ namespace Pal3.Game.Rendering.Renderer private GameBoxMaterial[] _gbMaterials; private ITexture2D[] _textures; private bool[] _textureHasAlphaChannel; - private IMaterial[][] _materials; + private RenderModelOpacity[] _materials; + private float _opacity = 1f; private Vector3[][] _sourceNormals; + private Vector3 _nativeLightAnchor; private string[] _animationName; private uint[][] _frameTicks; private IGameEntity[] _meshEntities; @@ -59,9 +62,15 @@ namespace Pal3.Game.Rendering.Renderer private Mv3TagNode[] _tagNodesInfo; private uint[][] _tagNodeFrameTicks; private IGameEntity[] _tagNodes; + private PolyModelRenderer[] _tagNodeRenderers; // State - public bool IsInitialized { get; private set; } + public bool IsInitialized + { + get; private set; + } + + private bool _hasResources; private bool _isActionInHoldState; private uint _actionHoldingTick; private int _lastCheckedTick = -1; // Track the last checked tick @@ -82,107 +91,130 @@ namespace Pal3.Game.Rendering.Renderer Color? tintColor = default, PolFile tagNodePolFile = default, ITextureResourceProvider tagNodeTextureProvider = default, - Color? tagNodeTintColor = default) + Color? tagNodeTintColor = default, + ITextureFactory textureFactory = null, + bool animateTagWater = true) { Dispose(); - _materialManager = materialManager; - _textureProvider = textureProvider; - _tintColor = tintColor ?? Color.White; - _tagNodePolFile = tagNodePolFile; - - _events = mv3File.AnimationEvents; - _totalGameBoxTicks = mv3File.TotalGameBoxTicks; - _meshes = mv3File.Meshes; - _meshCount = mv3File.Meshes.Length; - _tagNodesInfo = mv3File.TagNodes; - - // Only allocate memory when needed, reuse memory when possible - if (_renderMeshComponents == null || _renderMeshComponents.Length != _meshCount) + _hasResources = true; + try { - _renderMeshComponents = new RenderMeshComponent[_meshCount]; - _gbMaterials = new GameBoxMaterial[_meshCount]; - _textures = new ITexture2D[_meshCount]; - _textureHasAlphaChannel = new bool[_meshCount]; - _materials = new IMaterial[_meshCount][]; - _animationName = new string[_meshCount]; - _frameTicks = new uint[_meshCount][]; - _meshEntities = new IGameEntity[_meshCount]; - } + _materialManager = materialManager; + _textureProvider = textureProvider; + _tintColor = tintColor ?? Color.White; + _tagNodePolFile = tagNodePolFile; - if (_materialManager.UsesToonRendering && (_sourceNormals == null || _sourceNormals.Length != _meshCount)) - { - _sourceNormals = new Vector3[_meshCount][]; - } - - // Same for tag nodes - if (_tagNodesInfo.Length > 0) - { - if (_tagNodeFrameTicks == null || _tagNodeFrameTicks.Length != _tagNodesInfo.Length) + _events = mv3File.AnimationEvents; + _totalGameBoxTicks = mv3File.TotalGameBoxTicks; + _meshes = mv3File.Meshes; + _meshCount = mv3File.Meshes.Length; + var nativeBounds = new Bounds(_meshes[0].GameBoxBoundsMin.ToUnityPosition(), Vector3.zero); + foreach (Mv3Mesh mesh in _meshes) { - _tagNodeFrameTicks = new uint[_tagNodesInfo.Length][]; + nativeBounds.Encapsulate(mesh.GameBoxBoundsMin.ToUnityPosition()); + nativeBounds.Encapsulate(mesh.GameBoxBoundsMax.ToUnityPosition()); + } + _nativeLightAnchor = nativeBounds.center; + _tagNodesInfo = mv3File.TagNodes; + + // Only allocate memory when needed, reuse memory when possible + if (_renderMeshComponents == null || _renderMeshComponents.Length != _meshCount) + { + _renderMeshComponents = new RenderMeshComponent[_meshCount]; + _gbMaterials = new GameBoxMaterial[_meshCount]; + _textures = new ITexture2D[_meshCount]; + _textureHasAlphaChannel = new bool[_meshCount]; + _materials = new RenderModelOpacity[_meshCount]; + _animationName = new string[_meshCount]; + _frameTicks = new uint[_meshCount][]; + _meshEntities = new IGameEntity[_meshCount]; } - if (_tagNodes == null || _tagNodes.Length != _tagNodesInfo.Length) + if (_materialManager.UsesToonRendering && (_sourceNormals == null || _sourceNormals.Length != _meshCount)) { - _tagNodes = new IGameEntity[_tagNodesInfo.Length]; - } - } - - for (int i = 0; i < _tagNodesInfo.Length; i++) - { - Mv3TagFrame[] tagFrames = _tagNodesInfo[i].TagFrames; - int tagFramesCount = tagFrames.Length; - - if (_tagNodeFrameTicks[i] == null || _tagNodeFrameTicks[i].Length != tagFramesCount) - { - _tagNodeFrameTicks[i] = new uint[tagFramesCount]; + _sourceNormals = new Vector3[_meshCount][]; } - for (int j = 0; j < tagFramesCount; j++) + // Same for tag nodes + if (_tagNodesInfo.Length > 0) { - _tagNodeFrameTicks[i][j] = tagFrames[j].GameBoxTick; - } - } - - for (int i = 0; i < _meshCount; i++) - { - Mv3Mesh mesh = mv3File.Meshes[i]; - int materialId = mesh.Attributes[0].MaterialId; - GameBoxMaterial material = mv3File.Materials[materialId]; - - InitSubMeshes(i, ref mesh, ref material); - } - - if (_tagNodePolFile != null) - { - for (int i = 0; i < _tagNodesInfo.Length; i++) - { - if (_tagNodesInfo[i].Name.Equals("tag_weapon3", StringComparison.OrdinalIgnoreCase)) + if (_tagNodeFrameTicks == null || _tagNodeFrameTicks.Length != _tagNodesInfo.Length) { - _tagNodes[i] = null; - continue; + _tagNodeFrameTicks = new uint[_tagNodesInfo.Length][]; } - _tagNodes[i] = GameEntityFactory.Create(_tagNodePolFile.NodeDescriptions[0].Name, - GameEntity, worldPositionStays: true); - - PolyModelRenderer tagNodeRenderer = _tagNodes[i].AddComponent(); - tagNodeRenderer.Render(_tagNodePolFile, - tagNodeTextureProvider, - _materialManager, - isStaticObject: false, - tagNodeTintColor); - - _tagNodes[i].Transform.SetLocalPositionAndRotation( - mv3File.TagNodes[i].TagFrames[0].GameBoxPosition - .ToUnityPosition(UnityPrimitivesConvertor.GameBoxMv3UnitToUnityUnit), - mv3File.TagNodes[i].TagFrames[0].GameBoxRotation - .Mv3QuaternionToUnityQuaternion()); + if (_tagNodes == null || _tagNodes.Length != _tagNodesInfo.Length) + { + _tagNodes = new IGameEntity[_tagNodesInfo.Length]; + _tagNodeRenderers = new PolyModelRenderer[_tagNodesInfo.Length]; + } } - } - IsInitialized = true; + for (int i = 0; i < _tagNodesInfo.Length; i++) + { + Mv3TagFrame[] tagFrames = _tagNodesInfo[i].TagFrames; + int tagFramesCount = tagFrames.Length; + + if (_tagNodeFrameTicks[i] == null || _tagNodeFrameTicks[i].Length != tagFramesCount) + { + _tagNodeFrameTicks[i] = new uint[tagFramesCount]; + } + + for (int j = 0; j < tagFramesCount; j++) + { + _tagNodeFrameTicks[i][j] = tagFrames[j].GameBoxTick; + } + } + + for (int i = 0; i < _meshCount; i++) + { + Mv3Mesh mesh = mv3File.Meshes[i]; + int materialId = mesh.Attributes[0].MaterialId; + GameBoxMaterial material = mv3File.Materials[materialId]; + + InitSubMeshes(i, ref mesh, ref material); + } + + if (_tagNodePolFile != null) + { + for (int i = 0; i < _tagNodesInfo.Length; i++) + { + if (_tagNodesInfo[i].Name.Equals("tag_weapon3", StringComparison.OrdinalIgnoreCase)) + { + _tagNodes[i] = null; + continue; + } + + _tagNodes[i] = GameEntityFactory.Create(_tagNodePolFile.NodeDescriptions[0].Name, + GameEntity, worldPositionStays: true); + + PolyModelRenderer tagNodeRenderer = _tagNodes[i].AddComponent(); + _tagNodeRenderers[i] = tagNodeRenderer; + tagNodeRenderer.SetOpacity(_opacity); + tagNodeRenderer.Render(_tagNodePolFile, + tagNodeTextureProvider, + _materialManager, + isStaticObject: false, + tagNodeTintColor, + textureFactory: textureFactory, + animateWater: animateTagWater); + + _tagNodes[i].Transform.SetLocalPositionAndRotation( + mv3File.TagNodes[i].TagFrames[0].GameBoxPosition + .ToUnityPosition(UnityPrimitivesConvertor.GameBoxMv3UnitToUnityUnit), + mv3File.TagNodes[i].TagFrames[0].GameBoxRotation + .Mv3QuaternionToUnityQuaternion()); + } + } + + IsInitialized = true; + } + catch + { + Dispose(); + throw; + } } private void InitSubMeshes(int index, @@ -213,17 +245,18 @@ namespace Pal3.Game.Rendering.Renderer GameEntity, worldPositionStays: false); // Attach BlendFlag and GameBoxMaterial to the GameEntity for better debuggability - #if UNITY_EDITOR +#if UNITY_EDITOR MaterialInfoPresenter materialInfoPresenter = _meshEntities[index].AddComponent(); materialInfoPresenter.blendFlag = _textureHasAlphaChannel[index] ? GameBoxBlendFlag.AlphaBlend : GameBoxBlendFlag.Opaque; materialInfoPresenter.material = _gbMaterials[index]; - #endif +#endif StaticMeshRenderer meshRenderer = _meshEntities[index].AddComponent(); - _materials[index] = CreateMaterials(textureName, _textures[index], hasAlphaChannel); + _materials[index] = CreateMaterials(textureName, _textures[index], hasAlphaChannel, _gbMaterials[index]); + _materials[index].SetOpacity(_opacity); _renderMeshComponents[index] ??= new RenderMeshComponent(); _renderMeshComponents[index].MeshDataBuffer ??= new MeshDataBuffer(); @@ -232,7 +265,7 @@ namespace Pal3.Game.Rendering.Renderer bool usesToon = _materialManager.UsesToonRendering; int vertexCount = mv3Mesh.KeyFrames[0].GameBoxVertices.Length; buffer.AllocateOrResizeBuffers(vertexBufferSize: vertexCount, - normalBufferSize: usesToon ? vertexCount : 0, + normalBufferSize: _materialManager.RequiresNormals ? vertexCount : 0, uvBufferSize: mv3Mesh.Uvs.Length, triangleBufferSize: mv3Mesh.GameBoxTriangles.Length); @@ -250,15 +283,20 @@ namespace Pal3.Game.Rendering.Renderer buffer.RebuildNormalsBySourceVertex(mv3Mesh.NormalIndices, _sourceNormals[index]); } + if (_materialManager.NativeLighting != null) + FillNativeNormals(mv3Mesh, buffer.NormalBuffer, 0, 0, 0); + Mesh renderMesh = meshRenderer.Render( vertices: buffer.VertexBuffer, triangles: buffer.TriangleBuffer, - normals: usesToon ? buffer.NormalBuffer : null, + normals: _materialManager.RequiresNormals ? buffer.NormalBuffer : null, mainTextureUvs: (channel: 0, uvs: buffer.UvBuffer), secondaryTextureUvs: default, // MV3 models don't have secondary texture - materials: _materials[index], + materials: _materials[index].Materials, isDynamic: true); + _materials[index].Bind(meshRenderer, apply: false, anchor: _nativeLightAnchor, + vertexUnits: UnityPrimitivesConvertor.GameBoxMv3UnitToUnityUnit / 64f); _renderMeshComponents[index].Mesh = renderMesh; _renderMeshComponents[index].MeshRenderer = meshRenderer; } @@ -276,55 +314,61 @@ namespace Pal3.Game.Rendering.Renderer StartCoroutine(PlayAnimationInternalAsync(loopCount, _animationCts.Token)); } - private IMaterial[] CreateMaterials(string textureName, ITexture2D texture, bool hasAlphaChannel) + private RenderModelOpacity CreateMaterials(string textureName, ITexture2D texture, bool hasAlphaChannel, GameBoxMaterial sourceMaterial) { - IMaterial[] materials = _materialManager.CreateStandardMaterials( - RendererType.Mv3, - mainTexture: (textureName, texture), - bakedLightmap: default, - tintColor: _tintColor, - blendFlag: hasAlphaChannel ? GameBoxBlendFlag.AlphaBlend : GameBoxBlendFlag.Opaque); - ApplyTextureScale(materials, textureName); - return materials; + return new RenderModelOpacity(_materialManager, RendererType.Mv3, (textureName, texture), default, + _tintColor, hasAlphaChannel ? GameBoxBlendFlag.AlphaBlend : GameBoxBlendFlag.Opaque, + configure: ApplyTextureScale, returnMaterials: ReturnMaterials, sourceMaterial: sourceMaterial); + } + + public void SetOpacity(float opacity) + { + _opacity = RenderModelOpacity.Normalize(opacity); + if (!IsInitialized) + return; + foreach (RenderModelOpacity materials in _materials) + materials?.SetOpacity(_opacity); + if (_tagNodeRenderers != null) + foreach (PolyModelRenderer renderer in _tagNodeRenderers) + renderer?.SetOpacity(_opacity); } private void ApplyTextureScale(IMaterial[] materials, string textureName) { - #if PAL3A +#if PAL3A string texturePath = _textureProvider.GetTexturePath(textureName); float scaleY = Dev.TexturePatcher.TextureFileHasWrongTiling(texturePath) ? -1f : 1f; foreach (IMaterial material in materials) { material.SetMainTextureScale(1f, scaleY); } - #endif +#endif } public void ChangeTexture(string textureName) { - if (!IsInitialized || _meshCount == 0) return; - if (!textureName.Contains(".")) textureName += MV3_MODEL_DEFAULT_TEXTURE_EXTENSION; + if (!IsInitialized || _meshCount == 0) + return; + if (!textureName.Contains(".")) + textureName += MV3_MODEL_DEFAULT_TEXTURE_EXTENSION; ITexture2D texture = _textureProvider.GetTexture(textureName, out bool hasAlphaChannel); - if (texture == null) return; + if (texture == null) + return; // ActorChangeTexture targets the first sub-mesh and all of its material passes. - IMaterial[] materials = _materials[0]; + RenderModelOpacity materials = _materials[0]; if (_textureHasAlphaChannel[0] != hasAlphaChannel) { - IMaterial[] replacement = CreateMaterials(textureName, texture, hasAlphaChannel); - _renderMeshComponents[0].MeshRenderer.SetMaterials(replacement); + RenderModelOpacity replacement = CreateMaterials(textureName, texture, hasAlphaChannel, _gbMaterials[0]); + replacement.SetOpacity(_opacity); + replacement.Bind(_renderMeshComponents[0].MeshRenderer, anchor: _nativeLightAnchor, + vertexUnits: UnityPrimitivesConvertor.GameBoxMv3UnitToUnityUnit / 64f); _materials[0] = replacement; - ReturnMaterials(materials); + materials.Dispose(); } else - { - foreach (IMaterial material in materials) - { - material.SetMainTexture(texture); - } - ApplyTextureScale(materials, textureName); - } + materials.ChangeTexture(textureName, texture); _textures[0] = texture; _textureHasAlphaChannel[0] = hasAlphaChannel; @@ -332,19 +376,19 @@ namespace Pal3.Game.Rendering.Renderer private void ReturnMaterials(IMaterial[] materials) { - #if PAL3A +#if PAL3A foreach (IMaterial material in materials) { material.SetMainTextureScale(1f, 1f); } - #endif +#endif _materialManager.ReturnToPool(materials); } public void PauseAnimation() { - if (_animationCts is {IsCancellationRequested: false}) + if (_animationCts is { IsCancellationRequested: false }) { _animationCts.Cancel(); } @@ -390,7 +434,8 @@ namespace Pal3.Game.Rendering.Renderer private IEnumerator ResumeActionInternalAsync() { - if (!_isActionInHoldState) yield break; + if (!_isActionInHoldState) + yield break; _animationCts = new CancellationTokenSource(); CancellationToken cancellationToken = _animationCts.Token; yield return PlayOneTimeAnimationInternalAsync(_actionHoldingTick, @@ -489,7 +534,7 @@ namespace Pal3.Game.Rendering.Renderer break; } } - + _lastCheckedTick = (int)currentTick; } @@ -508,7 +553,7 @@ namespace Pal3.Game.Rendering.Renderer // Trigger animation events CheckForAnimationEvents(tick); - + if (tick >= endTick) { yield break; @@ -520,7 +565,8 @@ namespace Pal3.Game.Rendering.Renderer continue; } - if (cancellationToken.IsCancellationRequested) yield break; + if (cancellationToken.IsCancellationRequested) + yield break; SampleGeometry(tick, endTick); @@ -539,6 +585,20 @@ namespace Pal3.Game.Rendering.Renderer SampleGeometry(tick, _totalGameBoxTicks); } + private static void FillNativeNormals(Mv3Mesh mesh, Vector3[] destination, int current, int next, float influence) + { + ushort[] first = mesh.KeyFrames[current].NativeNormals; + ushort[] second = mesh.KeyFrames[next].NativeNormals; + if (first == null || second == null || first.Length != destination.Length || second.Length != destination.Length) + throw new InvalidOperationException("The MV3 has no original per-keyframe normals."); + for (int vertex = 0; vertex < destination.Length; vertex++) + { + Vector3 a = Mv3NativeNormals.Decode(first[vertex]).ToUnityNormal(); + Vector3 b = Mv3NativeNormals.Decode(second[vertex]).ToUnityNormal(); + destination[vertex] = a * (1 - influence) + b * influence; + } + } + private void SampleGeometry(uint tick, uint endTick) { // Animates the mesh @@ -572,6 +632,11 @@ namespace Pal3.Game.Rendering.Renderer meshComponent.MeshDataBuffer.RebuildNormalsBySourceVertex(_meshes[i].NormalIndices, _sourceNormals[i]); meshComponent.Mesh.SetNormals(meshComponent.MeshDataBuffer.NormalBuffer); } + else if (_materialManager.NativeLighting != null) + { + FillNativeNormals(_meshes[i], meshComponent.MeshDataBuffer.NormalBuffer, currentFrameIndex, nextFrameIndex, influence); + meshComponent.Mesh.SetNormals(meshComponent.MeshDataBuffer.NormalBuffer); + } meshComponent.Mesh.RecalculateBounds(); } @@ -607,11 +672,13 @@ namespace Pal3.Game.Rendering.Renderer public bool IsVisibleToCamera() { - if (!IsInitialized) return false; + if (!IsInitialized) + return false; foreach (RenderMeshComponent renderMeshComponent in _renderMeshComponents) { - if (renderMeshComponent.MeshRenderer.IsVisible) return true; + if (renderMeshComponent.MeshRenderer.IsVisible) + return true; } return false; @@ -619,28 +686,37 @@ namespace Pal3.Game.Rendering.Renderer public void Dispose() { - if (!IsInitialized) return; + if (!_hasResources) + return; + _hasResources = false; + DisposeWeaponPresentation(); + _selectionBlocks.Clear(); IsInitialized = false; PauseAnimation(); + _animationCts?.Dispose(); + _animationCts = null; + if (_renderMeshComponents != null) { foreach (RenderMeshComponent renderMeshComponent in _renderMeshComponents) { - if (renderMeshComponent?.MeshRenderer == null) continue; + if (renderMeshComponent?.MeshRenderer == null) + continue; renderMeshComponent.MeshRenderer.Dispose(); renderMeshComponent.MeshRenderer.Destroy(); } } - for (int i = 0; i < _materials.Length; i++) + for (int i = 0; i < (_materials?.Length ?? 0); i++) { - IMaterial[] materials = _materials[i]; - if (materials == null) continue; + RenderModelOpacity materials = _materials[i]; + if (materials == null) + continue; - ReturnMaterials(materials); + materials.Dispose(); _materials[i] = null; } @@ -652,16 +728,24 @@ namespace Pal3.Game.Rendering.Renderer } } + if (_tagNodeRenderers != null) + { + foreach (PolyModelRenderer renderer in _tagNodeRenderers) + renderer?.Dispose(); + Array.Clear(_tagNodeRenderers, 0, _tagNodeRenderers.Length); + } + if (_tagNodes != null) { foreach (IGameEntity tagNode in _tagNodes) { tagNode?.Destroy(); // tagNode can be null } + Array.Clear(_tagNodes, 0, _tagNodes.Length); } _isActionInHoldState = false; _actionHoldingTick = 0; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolMeshBatch.cs b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolMeshBatch.cs index de38a149..eec24743 100644 --- a/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolMeshBatch.cs +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolMeshBatch.cs @@ -16,21 +16,30 @@ namespace Pal3.Game.Rendering.Renderer internal const int MaximumVertices = 65535; internal readonly List Positions = new(); internal readonly List Normals = new(); + internal readonly List Colors = new(); internal readonly List MainUvs = new(); internal readonly List LightmapUvs = new(); internal readonly List Triangles = new(); - #if UNITY_EDITOR +#if UNITY_EDITOR internal readonly List Sources = new(); - #endif +#endif internal void Add(PolMeshIndexMap map, Vector3[] positions, Vector3[] normals, - Vector2[] mainUvs, Vector2[] lightmapUvs) + Vector2[] mainUvs, Vector2[] lightmapUvs, Color32[] colors = null, bool geometricNormals = false) { int offset = Positions.Count; + Vector3[] generatedNormals = geometricNormals ? CaptureGroupNormals(map, positions) : null; + int local = 0; foreach (int source in map.SourceIndices) { Positions.Add(positions[source]); - if (normals != null) Normals.Add(normals[source]); + if (generatedNormals != null) + Normals.Add(generatedNormals[local]); + else if (normals != null) + Normals.Add(normals[source]); + local++; + if (colors != null) + Colors.Add(colors[source]); MainUvs.Add(mainUvs[source]); LightmapUvs.Add(lightmapUvs[source]); } @@ -39,10 +48,32 @@ namespace Pal3.Game.Rendering.Renderer Triangles.Add(offset + map.Triangles[i]); } + // Reconstruct only within the selected material group. Original exports + // can smooth a level floor into an adjoining painted vertical backdrop. + internal static Vector3[] CaptureGroupNormals(PolMeshIndexMap map, Vector3[] positions) + { + var normals = new Vector3[map.SourceIndices.Length]; + for (int index = 0; index < map.Triangles.Length; index += 3) + { + int a = map.Triangles[index + 2]; + int b = map.Triangles[index + 1]; + int c = map.Triangles[index]; + Vector3 face = Vector3.Cross(positions[map.SourceIndices[b]] - positions[map.SourceIndices[a]], + positions[map.SourceIndices[c]] - positions[map.SourceIndices[a]]); + normals[a] += face; + normals[b] += face; + normals[c] += face; + } + for (int index = 0; index < normals.Length; index++) + normals[index] = normals[index].normalized; + return normals; + } + internal static bool TryGetCell(PolMeshIndexMap map, Vector3[] positions, out Vector3Int cell) { var bounds = new Bounds(positions[map.SourceIndices[0]], Vector3.zero); - foreach (int source in map.SourceIndices) bounds.Encapsulate(positions[source]); + foreach (int source in map.SourceIndices) + bounds.Encapsulate(positions[source]); cell = Vector3Int.FloorToInt(bounds.center / CellSize); // Large sections stay separate so batching cannot turn a whole scene into one bound. return bounds.size.x <= CellSize && bounds.size.y <= CellSize && bounds.size.z <= CellSize; diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolModelMode.cs b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolModelMode.cs new file mode 100644 index 00000000..0e7a53a3 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolModelMode.cs @@ -0,0 +1,18 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Renderer +{ + public enum PolModelMode + { + // Apply the game's animated-water convention where requested by texture name. + Game, + + // Retain file blend flags and vertex colors without substituting water + // materials, and preserve the full source mesh bounds. Scene lighting + // remains the material manager's responsibility. + Authored, + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolModelMode.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolModelMode.cs.meta new file mode 100644 index 00000000..2c2a1e80 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolModelMode.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 224dd1a6f12f46ab94fd35dd915fa405 diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolSurfaceAppearance.cs b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolSurfaceAppearance.cs new file mode 100644 index 00000000..6243f313 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolSurfaceAppearance.cs @@ -0,0 +1,52 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Renderer +{ + using System; + + /// An explicit material-group appearance override, independent of gameplay and resource naming. + public readonly struct PolSurfaceAppearance : IEquatable + { + public bool UnlitBackground + { + get; + } + + public bool GeometricNormals + { + get; + } + + public static PolSurfaceAppearance Painted(float brightness = 1) => new(true, false, brightness); + + public static PolSurfaceAppearance RecalculateNormals => new(false, true, 1); + + public float Brightness + { + get; + } + + private PolSurfaceAppearance(bool unlitBackground, bool geometricNormals, float brightness) + { + UnlitBackground = unlitBackground; + GeometricNormals = geometricNormals; + Brightness = brightness; + Validate(); + } + + public void Validate() + { + if (!float.IsFinite(Brightness) || Brightness < 0 || Brightness > 2) + throw new ArgumentOutOfRangeException(nameof(Brightness), "Background brightness must be finite and between zero and two."); + } + + public bool Equals(PolSurfaceAppearance other) => UnlitBackground == other.UnlitBackground && GeometricNormals == other.GeometricNormals && Brightness.Equals(other.Brightness); + + public override bool Equals(object other) => other is PolSurfaceAppearance appearance && Equals(appearance); + + public override int GetHashCode() => HashCode.Combine(UnlitBackground, GeometricNormals, Brightness); + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolSurfaceAppearance.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolSurfaceAppearance.cs.meta new file mode 100644 index 00000000..bfa8a2e1 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolSurfaceAppearance.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0d2eb8c043864cd995e3c1d427d1666b diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolyModelRenderer.cs b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolyModelRenderer.cs index 266d8eee..c765de68 100644 --- a/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolyModelRenderer.cs +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/PolyModelRenderer.cs @@ -39,13 +39,17 @@ namespace Pal3.Game.Rendering.Renderer private Dictionary _textureCache; private ITexture2D _whiteTexture; private readonly List _meshRenderers = new(); + private readonly List _meshEntities = new(); + private float _opacity = 1f; // Materials share one tint and texture provider within this POL instance. - private readonly Dictionary<(string main, string lightmap, GameBoxBlendFlag blend), IMaterial[]> _meshMaterials = new(); + private readonly Dictionary<(string main, string lightmap, GameBoxBlendFlag blend, int nativeMaterial), RenderModelOpacity> _meshMaterials = new(); + private readonly Dictionary<(Color diffuse, Color ambient, bool vertexColors), int> _nativeMaterialIds = new(); private bool _isStaticObject; private Color _tintColor; private bool _forceOpaqueWater; - private List<(IMaterial[] materials, ITexture2D firstFrame)> _waterSurfaces; + private PolModelMode _modelMode; + private List<(RenderModelOpacity materials, ITexture2D firstFrame)> _waterSurfaces; private UnityEngine.Coroutine _waterAnimation; protected override void OnDisableGameEntity() @@ -60,23 +64,27 @@ namespace Pal3.Game.Rendering.Renderer Color? tintColor = default, bool forceOpaqueWater = false, ITextureFactory textureFactory = null, - bool animateWater = true) + bool animateWater = true, + PolModelMode modelMode = PolModelMode.Game, + Func surfaceAppearance = null) { + Dispose(); _textureFactory = textureFactory ?? ServiceLocator.Instance.Get(); _textureProvider = textureProvider; _materialManager = materialManager; _isStaticObject = isStaticObject; _tintColor = tintColor ?? Color.White; _forceOpaqueWater = forceOpaqueWater; + _modelMode = modelMode; _textureCache = BuildTextureCache(polFile, textureProvider); - var batches = new Dictionary<(IMaterial[] materials, Vector3Int cell), PolMeshBatch>(); + var batches = new Dictionary<(RenderModelOpacity materials, Vector3Int cell, PolSurfaceAppearance? appearance), PolMeshBatch>(); for (int i = 0; i < polFile.Meshes.Length; i++) { - RenderMeshInternal(polFile.NodeDescriptions[i], polFile.Meshes[i], batches); + RenderMeshInternal(polFile.NodeDescriptions[i], polFile.Meshes[i], batches, i, surfaceAppearance); } foreach (var entry in batches) - RenderGeometry("POL " + entry.Key.cell, entry.Value, entry.Key.materials); + RenderGeometry("POL " + entry.Key.cell, entry.Value, entry.Key.materials, appearance: entry.Key.appearance); if (animateWater && _waterSurfaces != null) { @@ -84,6 +92,16 @@ namespace Pal3.Game.Rendering.Renderer } } + public void SetOpacity(float opacity) + { + _opacity = RenderModelOpacity.Normalize(opacity); + foreach (RenderModelOpacity materials in _meshMaterials.Values) + materials.SetOpacity(_opacity); + if (_waterSurfaces != null) + foreach (var (materials, _) in _waterSurfaces) + materials.SetOpacity(_opacity); + } + public Bounds GetRendererBounds() { StaticMeshRenderer[] renderers = GameEntity.GetComponentsInChildren(); @@ -124,8 +142,10 @@ namespace Pal3.Game.Rendering.Renderer { foreach (string textureName in texture.Material.TextureFileNames) { - if (string.IsNullOrEmpty(textureName)) continue; - if (textureCache.ContainsKey(textureName)) continue; + if (string.IsNullOrEmpty(textureName)) + continue; + if (textureCache.ContainsKey(textureName)) + continue; textureCache[textureName] = textureProvider.GetTexture(textureName); } @@ -135,10 +155,21 @@ namespace Pal3.Game.Rendering.Renderer } private void RenderMeshInternal(PolGeometryNode meshNode, PolMesh mesh, - Dictionary<(IMaterial[] materials, Vector3Int cell), PolMeshBatch> batches) + Dictionary<(RenderModelOpacity materials, Vector3Int cell, PolSurfaceAppearance? appearance), PolMeshBatch> batches, + int nodeIndex, Func surfaceAppearance) { Vector3[] positions = mesh.VertexInfo.GameBoxPositions.ToUnityPositions(); - Vector3[] normals = _materialManager.UsesToonRendering ? mesh.VertexInfo.GameBoxNormals.ToUnityNormals() : null; + Vector3[] normals = _materialManager.RequiresNormals ? mesh.VertexInfo.GameBoxNormals.ToUnityNormals() : null; + UnityEngine.Color32[] colors = (_modelMode == PolModelMode.Authored || _materialManager.NativeLighting != null || surfaceAppearance != null) && (mesh.VertexFvfFlag & GameBoxVertexType.Diffuse) != 0 + ? mesh.VertexInfo.DiffuseColors.ToUnityColor32s() : null; + Bounds? sourceBounds = null; + if (_modelMode == PolModelMode.Authored && positions.Length > 0) + { + var bounds = new Bounds(positions[0], Vector3.zero); + foreach (Vector3 position in positions) + bounds.Encapsulate(position); + sourceBounds = bounds; + } var uvs = new Vector2[mesh.VertexInfo.Uvs.Length][]; Vector2[] GetUvs(int index) => uvs[index] ??= mesh.VertexInfo.Uvs[index].ToUnityVector2s(); @@ -166,59 +197,65 @@ namespace Pal3.Game.Rendering.Renderer return; } + PolSurfaceAppearance? appearance = surfaceAppearance?.Invoke(nodeIndex, i); + appearance?.Validate(); GameBoxBlendFlag blendFlag = mesh.Textures[i].BlendFlag; int mainTextureIndex = textures.Count == 1 ? 0 : 1; - int lightmapIndex = textures.Count == 1 ? -1 : 0; + if (_modelMode == PolModelMode.Authored && mainTextureIndex == 1 && string.IsNullOrEmpty(textures[1].name)) + mainTextureIndex = 0; + int lightmapIndex = mainTextureIndex == 0 ? -1 : 0; var mainTexture = textures[mainTextureIndex]; var bakedLightmap = lightmapIndex >= 0 ? textures[lightmapIndex] : default; - IMaterial[] materials; - if (mainTexture.name.StartsWith(ANIMATED_WATER_TEXTURE_DEFAULT_NAME, StringComparison.OrdinalIgnoreCase)) + RenderModelOpacity materials; + if (_modelMode == PolModelMode.Game && _materialManager.NativeLighting == null && appearance?.UnlitBackground != true && + mainTexture.name.StartsWith(ANIMATED_WATER_TEXTURE_DEFAULT_NAME, StringComparison.OrdinalIgnoreCase)) { // Water mutates its main texture, so it owns a separate material. - materials = _forceOpaqueWater - ? _materialManager.CreateStandardMaterials( - RendererType.Pol, mainTexture, bakedLightmap, _tintColor, GameBoxBlendFlag.Opaque) - : new[] - { - _materialManager.CreateWaterMaterial( - mainTexture, bakedLightmap, mainTexture.texture.GetPixel(0, 0).a), - }; + materials = new RenderModelOpacity(_materialManager, RendererType.Pol, mainTexture, bakedLightmap, + _tintColor, GameBoxBlendFlag.Opaque, + waterAlpha: _forceOpaqueWater ? null : mainTexture.texture.GetPixel(0, 0).a); + materials.SetOpacity(_opacity); (_waterSurfaces ??= new()).Add((materials, mainTexture.texture)); } else { - var key = (mainTexture.name, bakedLightmap.name, blendFlag); + var key = (mainTexture.name, bakedLightmap.name, blendFlag, NativeMaterialId(mesh.Textures[i].Material, colors != null, appearance?.UnlitBackground == true)); if (!_meshMaterials.TryGetValue(key, out materials)) { - materials = _materialManager.CreateStandardMaterials( - RendererType.Pol, mainTexture, bakedLightmap, _tintColor, blendFlag); + materials = new RenderModelOpacity(_materialManager, RendererType.Pol, mainTexture, bakedLightmap, _tintColor, blendFlag, + sourceMaterial: mesh.Textures[i].Material); + materials.SetOpacity(_opacity); _meshMaterials.Add(key, materials); } } var map = new PolMeshIndexMap(positions.Length, mesh.Textures[i].GameBoxTriangles); - if (map.SourceIndices.Length == 0) continue; - bool batchable = _isStaticObject && blendFlag == GameBoxBlendFlag.Opaque && + if (map.SourceIndices.Length == 0) + continue; + bool sharedLighting = _materialManager.NativeLighting == null || bakedLightmap.texture != null || colors != null; + bool batchable = _modelMode == PolModelMode.Game && sharedLighting && _isStaticObject && blendFlag == GameBoxBlendFlag.Opaque && !mainTexture.name.StartsWith(ANIMATED_WATER_TEXTURE_DEFAULT_NAME, StringComparison.OrdinalIgnoreCase); Vector3Int cell = default; batchable &= PolMeshBatch.TryGetCell(map, positions, out cell); PolMeshBatch geometry; if (batchable) { - var key = (materials, cell); + var key = (materials, cell, appearance); if (batches.TryGetValue(key, out geometry) && geometry.Positions.Count + map.SourceIndices.Length > PolMeshBatch.MaximumVertices) { - RenderGeometry("POL " + cell, geometry, materials); + RenderGeometry("POL " + cell, geometry, materials, appearance: appearance); batches.Remove(key); geometry = null; } - if (geometry == null) batches.Add(key, geometry = new PolMeshBatch()); + if (geometry == null) + batches.Add(key, geometry = new PolMeshBatch()); } - else geometry = new PolMeshBatch(); + else + geometry = new PolMeshBatch(); - #if UNITY_EDITOR +#if UNITY_EDITOR geometry.Sources.Add(new PolMeshBatchInfoPresenter.SourceGroup { nodeName = meshNode.Name, @@ -228,33 +265,65 @@ namespace Pal3.Game.Rendering.Renderer vertexStart = geometry.Positions.Count, vertexCount = map.SourceIndices.Length, }); - #endif - geometry.Add(map, positions, normals, GetUvs(mainTextureIndex), GetUvs(Math.Max(lightmapIndex, 0))); +#endif + geometry.Add(map, positions, normals, GetUvs(mainTextureIndex), GetUvs(Math.Max(lightmapIndex, 0)), colors, geometricNormals: appearance?.GeometricNormals == true); if (!batchable) { - IGameEntity entity = RenderGeometry(meshNode.Name, geometry, materials); - #if UNITY_EDITOR + IGameEntity entity = RenderGeometry(meshNode.Name, geometry, materials, sourceBounds, appearance); +#if UNITY_EDITOR MaterialInfoPresenter presenter = entity.AddComponent(); presenter.blendFlag = blendFlag; presenter.material = mesh.Textures[i].Material; - #endif +#endif } } } - private IGameEntity RenderGeometry(string name, PolMeshBatch geometry, IMaterial[] materials) + private int NativeMaterialId(GameBoxMaterial material, bool vertexColors, bool painted) + { + if (_materialManager.NativeLighting == null && !painted) + return vertexColors ? -1 : 0; + var key = (material.Diffuse, material.Ambient, vertexColors); + if (!_nativeMaterialIds.TryGetValue(key, out int id)) + _nativeMaterialIds.Add(key, id = _nativeMaterialIds.Count + 1); + return id; + } + + private IGameEntity RenderGeometry(string name, PolMeshBatch geometry, RenderModelOpacity materials, Bounds? sourceBounds = null, PolSurfaceAppearance? appearance = null) { IGameEntity entity = GameEntityFactory.Create(name, GameEntity, worldPositionStays: false); entity.IsStatic = _isStaticObject; StaticMeshRenderer renderer = entity.AddComponent(); _meshRenderers.Add(renderer); - renderer.Render(geometry.Positions.ToArray(), geometry.Triangles.ToArray(), + _meshEntities.Add(entity); + Mesh mesh = renderer.Render(geometry.Positions.ToArray(), geometry.Triangles.ToArray(), geometry.Normals.Count > 0 ? geometry.Normals.ToArray() : null, - (0, geometry.MainUvs.ToArray()), (1, geometry.LightmapUvs.ToArray()), materials, isDynamic: false); - #if UNITY_EDITOR + (0, geometry.MainUvs.ToArray()), (1, geometry.LightmapUvs.ToArray()), materials.Materials, isDynamic: false); + if (geometry.Colors.Count > 0) + mesh.SetColors(geometry.Colors); + if (sourceBounds.HasValue) + mesh.bounds = sourceBounds.Value; + materials.Bind(renderer, apply: false, vertexColors: geometry.Colors.Count > 0, environment: _isStaticObject); + if (appearance?.UnlitBackground == true) + { + // Authored painted backgrounds remain independent of scene lights. + // A property block keeps this choice local even when materials are pooled. + var meshRenderer = renderer.GetComponent(); + var properties = new MaterialPropertyBlock(); + meshRenderer.GetPropertyBlock(properties); + properties.SetFloat(Shader.PropertyToID("_UnlitBackground"), 1); + properties.SetFloat(Shader.PropertyToID("_BackgroundBrightness"), appearance.Value.Brightness); + // Painted POL layers use the original texture-stage gain even + // when a water texture selected a different material template. + properties.SetFloat(Shader.PropertyToID("_LightmapScale"), GameMaterialManager.PolLightmapScale); + meshRenderer.SetPropertyBlock(properties); + meshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + meshRenderer.receiveShadows = false; + } +#if UNITY_EDITOR PolMeshBatchInfoPresenter presenter = entity.AddComponent(); presenter.sources = geometry.Sources.ToArray(); - #endif +#endif return entity; } @@ -275,7 +344,7 @@ namespace Pal3.Game.Rendering.Renderer { foreach (var (materials, firstFrame) in _waterSurfaces) { - materials[0].SetMainTexture(firstFrame); + materials.ChangeTexture(ANIMATED_WATER_TEXTURE_DEFAULT_NAME, firstFrame); } yield return delay; @@ -286,7 +355,7 @@ namespace Pal3.Game.Rendering.Renderer { foreach (var (materials, _) in _waterSurfaces) { - materials[0].SetMainTexture(frame); + materials.ChangeTexture(ANIMATED_WATER_TEXTURE_DEFAULT_NAME, frame); } } @@ -305,26 +374,34 @@ namespace Pal3.Game.Rendering.Renderer foreach (StaticMeshRenderer meshRenderer in _meshRenderers) { - if (meshRenderer == null) continue; + if (meshRenderer == null) + continue; meshRenderer.Dispose(); meshRenderer.Destroy(); } _meshRenderers.Clear(); + foreach (IGameEntity entity in _meshEntities) + entity.Destroy(); + _meshEntities.Clear(); - foreach (IMaterial[] materials in _meshMaterials.Values) + foreach (RenderModelOpacity materials in _meshMaterials.Values) { - _materialManager.ReturnToPool(materials); + materials.Dispose(); } _meshMaterials.Clear(); + _nativeMaterialIds.Clear(); if (_waterSurfaces != null) { foreach (var (materials, _) in _waterSurfaces) { - _materialManager.ReturnToPool(materials); + materials.Dispose(); } _waterSurfaces = null; } + // The texture factory exposes Unity's shared built-in white texture. + _whiteTexture = null; + _textureCache = null; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/RenderModelOpacity.cs b/Assets/Scripts/Pal3.Game/Rendering/Renderer/RenderModelOpacity.cs new file mode 100644 index 00000000..b26b109a --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/RenderModelOpacity.cs @@ -0,0 +1,177 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Renderer +{ + using System; + using System.Collections.Generic; + using Core.Primitives; + using Engine.Core.Abstraction; + using Engine.Renderer; + using Engine.Services; + using Material; + using Color = Core.Primitives.Color; + + // Each model owns these rented materials. A fade changes uniforms; only the + // first opaque-to-transparent transition rents an additional material pair. + internal sealed class RenderModelOpacity : IDisposable + { + private static readonly int TintId = ShaderUtility.GetPropertyIdByName("_TintColor"); + private static readonly int ThresholdId = ShaderUtility.GetPropertyIdByName("_Threshold"); + private static readonly int WaterAlphaId = ShaderUtility.GetPropertyIdByName("_Alpha"); + private static readonly int VertexColorId = ShaderUtility.GetPropertyIdByName("_GbVertexColor"); + + private readonly IMaterialManager _manager; + private readonly GameBoxMaterial? _sourceMaterial; + private readonly List _lightingBindings = new(); + private readonly RendererType _rendererType; + private readonly (string name, ITexture2D texture) _lightmap; + private readonly Color _tint; + private readonly GameBoxBlendFlag _blend; + private readonly float? _waterAlpha; + private readonly Action _configure; + private readonly Action _returnMaterials; + private readonly List _renderers = new(); + private readonly float[] _thresholds; + private (string name, ITexture2D texture) _texture; + private IMaterial[] _normal; + private IMaterial[] _faded; + + public IMaterial[] Materials + { + get; private set; + } + + public RenderModelOpacity(IMaterialManager manager, RendererType rendererType, + (string name, ITexture2D texture) texture, (string name, ITexture2D texture) lightmap, + Color tint, GameBoxBlendFlag blend, float? waterAlpha = null, + Action configure = null, Action returnMaterials = null, + GameBoxMaterial? sourceMaterial = null) + { + _manager = manager; + _sourceMaterial = sourceMaterial; + _rendererType = rendererType; + _texture = texture; + _lightmap = lightmap; + _tint = tint; + _blend = blend; + _waterAlpha = waterAlpha; + _configure = configure; + _returnMaterials = returnMaterials ?? manager.ReturnToPool; + _normal = waterAlpha.HasValue + ? new[] { manager.CreateWaterMaterial(texture, lightmap, waterAlpha.Value) } + : manager.CreateStandardMaterials(rendererType, texture, lightmap, tint, blend, sourceMaterial); + Materials = _normal; + _configure?.Invoke(_normal, texture.name); + if (!waterAlpha.HasValue && blend != GameBoxBlendFlag.Opaque) + { + _thresholds = new float[_normal.Length]; + for (int i = 0; i < _normal.Length; i++) + _thresholds[i] = _normal[i].GetFloat(ThresholdId); + } + } + + public static float Normalize(float value) + { + if (!float.IsFinite(value)) + throw new ArgumentOutOfRangeException(nameof(value), "Model opacity must be finite."); + return Math.Clamp(value, 0f, 1f); + } + + public void Bind(StaticMeshRenderer renderer, bool apply = true, UnityEngine.Vector3 anchor = default, + bool vertexColors = false, bool environment = false, float vertexUnits = 20f) + { + _renderers.Add(renderer); + if (_manager.NativeLighting != null) + _lightingBindings.Add(_manager.NativeLighting.Bind(renderer.GetComponent(), + anchor, _lightmap.texture != null, vertexColors, environment, vertexUnits)); + else if (vertexColors) + { + var meshRenderer = renderer.GetComponent(); + var properties = new UnityEngine.MaterialPropertyBlock(); + meshRenderer.GetPropertyBlock(properties); + properties.SetFloat(VertexColorId, 1); + meshRenderer.SetPropertyBlock(properties); + } + if (apply) + renderer.SetMaterials(Materials); + } + + public void SetOpacity(float opacity) + { + IMaterial[] previous = Materials; + if (!_waterAlpha.HasValue && _blend == GameBoxBlendFlag.Opaque && opacity < 1f) + { + if (_faded == null) + { + _faded = _manager.CreateStandardMaterials(_rendererType, _texture, _lightmap, _tint, GameBoxBlendFlag.AlphaBlend, _sourceMaterial); + _configure?.Invoke(_faded, _texture.name); + } + Materials = _faded; + } + else + Materials = _normal; + + if (_waterAlpha.HasValue) + Materials[0].SetFloat(WaterAlphaId, _waterAlpha.Value * opacity); + else + { + Color tint = _tint; + tint.A *= opacity; + if (_blend is GameBoxBlendFlag.AdditiveBlend or GameBoxBlendFlag.InvertColorBlend) + { + tint.R *= opacity; + tint.G *= opacity; + tint.B *= opacity; + } + for (int i = 0; i < Materials.Length; i++) + { + Materials[i].SetColor(TintId, tint); + if (Materials == _faded || _blend == GameBoxBlendFlag.AlphaBlend) + { + // Both shaders classify raw texture alpha before tinting. + // Disable the opaque part and let the blended part draw all + // pixels during a fade, including originally opaque texels. + Materials[i].SetFloat(ThresholdId, opacity < 1f ? 2f : _thresholds[i]); + } + else if (_thresholds != null) + Materials[i].SetFloat(ThresholdId, opacity == 0f ? 0f : _thresholds[i]); + } + } + + if (previous != Materials) + foreach (StaticMeshRenderer renderer in _renderers) + renderer.SetMaterials(Materials); + } + + public void ChangeTexture(string name, ITexture2D texture) + { + _texture = (name, texture); + UpdateTexture(_normal); + if (_faded != null) + UpdateTexture(_faded); + } + + private void UpdateTexture(IMaterial[] materials) + { + foreach (IMaterial material in materials) + material.SetMainTexture(_texture.texture); + _configure?.Invoke(materials, _texture.name); + } + + public void Dispose() + { + foreach (IDisposable binding in _lightingBindings) + binding.Dispose(); + _lightingBindings.Clear(); + _renderers.Clear(); + if (_normal != null) + _returnMaterials(_normal); + if (_faded != null) + _returnMaterials(_faded); + _normal = _faded = Materials = null; + } + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/RenderModelOpacity.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Renderer/RenderModelOpacity.cs.meta new file mode 100644 index 00000000..02f60a83 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/RenderModelOpacity.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e387756413584d4c91cea17d13173397 diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/WeaponBlade.cs b/Assets/Scripts/Pal3.Game/Rendering/Renderer/WeaponBlade.cs new file mode 100644 index 00000000..04ed0ab6 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/WeaponBlade.cs @@ -0,0 +1,206 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Renderer +{ + using System; + using Core.DataReader.Pol; + using Engine.Extensions; + using UnityEngine; + using UnityEngine.Rendering; + using UnityEngine.SceneManagement; + + // gbBladeMgr/BladeRecord: 40 samples, duplicate the newest frame in + // slots 0/1, and replace slot 0 between sample insertions. + public sealed class WeaponBlade : IDisposable + { + private const int MaximumFrames = 40; + private readonly Vector3[][] _frames = new Vector3[MaximumFrames][]; + private readonly float[] _times = new float[MaximumFrames]; + private readonly bool[] _fresh = new bool[MaximumFrames]; + private readonly TagNode[] _tags; + private readonly Vector3[] _vertices; + private readonly Color32[] _colors; + private readonly int[] _triangles; + private int _count; + private bool _created; + private float _time, _lifetime = 0.1f; + private readonly Mesh _mesh; + private readonly Mesh[] _flushMeshes = new Mesh[2]; + private readonly MeshRenderer[] _flushRenderers = new MeshRenderer[2]; + + public WeaponBlade(TagNode[] tags) + { + _tags = tags ?? throw new ArgumentNullException(nameof(tags)); + _vertices = new Vector3[MaximumFrames * tags.Length]; + _colors = new Color32[_vertices.Length]; + _triangles = new int[(MaximumFrames - 1) * Math.Max(0, tags.Length - 1) * 6]; + int cursor = 0; + for (int frame = 0; frame < MaximumFrames - 1; frame++) + for (int index = 0; index < tags.Length - 1; index++) + { + int first = frame * tags.Length + index, next = first + tags.Length; + _triangles[cursor++] = first; + _triangles[cursor++] = next + 1; + _triangles[cursor++] = next; + _triangles[cursor++] = first; + _triangles[cursor++] = first + 1; + _triangles[cursor++] = next + 1; + } + _mesh = new Mesh { name = "Original weapon blade", hideFlags = HideFlags.DontSave }; + _mesh.MarkDynamic(); + } + + public int TriangleCount => Math.Max(0, _count - 1) * Math.Max(0, _tags.Length - 1) * 2; + + public bool TryGetLastPosition(out Vector3 position) + { + position = _count > 0 && _frames[0] is { Length: > 0 } ? _frames[0][0] : default; + return _count > 0 && _frames[0] is { Length: > 0 }; + } + + public static Material CreateMaterial() + { + // Both games' blade.gbf use SRCALPHA/ONE, no culling or depth writes. + Shader shader = Shader.Find("Pal3/Effect"); + if (shader == null) + throw new InvalidOperationException("The weapon blade shader is missing."); + var material = new Material(shader) { hideFlags = HideFlags.DontSave }; + material.mainTexture = Texture2D.whiteTexture; + material.SetInt("_SrcBlend", (int)BlendMode.SrcAlpha); + material.SetInt("_DstBlend", (int)BlendMode.One); + material.SetInt("_Cull", (int)CullMode.Off); + return material; + } + + // Compatibility sampling path for the PAL3A engine boundary and direct + // single-update oracles. PAL3 combat calls SamplePose and Advance apart. + public void Sample(Transform weapon, bool visible, float delta, float rate, float trailSeconds) + { + if (_count > 0) + _lifetime = trailSeconds; + Advance(delta, rate); + SamplePose(weapon, visible, trailSeconds); + } + + // Published draws use separate flush snapshots and can skip the + // compatibility mesh without changing either update's native clock. + public void Advance(float delta, float rate, bool rebuildMesh = true) + { + if (_created) + _time = (float)(_time + (double)delta * rate); + if (_count > 0 && (double)_time - _times[0] > (double)_lifetime * 100) + _count = 0; + Array.Clear(_fresh, 0, _fresh.Length); + if (rebuildMesh) + Rebuild(_mesh); + } + + public void SamplePose(Transform weapon, bool visible, float trailSeconds, bool rebuildMesh = true) + { + if (_count > 0) + _lifetime = trailSeconds; + Array.Clear(_fresh, 0, _fresh.Length); + if (visible) + { + _created = true; + var current = new Vector3[_tags.Length]; + for (int index = 0; index < current.Length; index++) + { + var matrix = _tags[index].GameBoxTransformMatrix; + current[index] = weapon.TransformPoint(new Core.Primitives.GameBoxVector3(matrix.Tx, matrix.Ty, matrix.Tz).ToUnityPosition()); + } + if (_count == 0 || (double)_time - _times[1] >= (double)_lifetime * (double)0.025f) + { + for (int index = Math.Min(_count, MaximumFrames - 1); index > 1; index--) + { + _frames[index] = _frames[index - 1]; + _times[index] = _times[index - 1]; + } + _frames[1] = current; + _times[1] = _time; + _fresh[1] = true; + _count = Math.Clamp(_count + 1, 2, MaximumFrames); + } + _frames[0] = current; + _times[0] = _time; + _fresh[0] = true; + } + if (rebuildMesh) + Rebuild(_mesh); + } + + private void Rebuild(Mesh target) + { + target.Clear(); + if (_count < 3 || _tags.Length < 2) + return; + int vertexCount = _count * _tags.Length; + int indexCount = (_count - 1) * (_tags.Length - 1) * 6; + for (int frame = 0; frame < _count; frame++) + { + // The published DLL uses _ftol (truncate toward zero), + // retaining the x87 intermediate until the integer store. + int alpha = Math.Clamp(100 - (int)(100 * ((double)_time - _times[frame]) / _lifetime), 0, 100); + for (int index = 0; index < _tags.Length; index++) + { + _vertices[frame * _tags.Length + index] = _frames[frame][index]; + uint tint = _tags[index].TintColor; + _colors[frame * _tags.Length + index] = new Color32((byte)(tint >> 16), (byte)(tint >> 8), (byte)tint, _fresh[frame] ? (byte)(tint >> 24) : (byte)alpha); + } + } + target.SetVertices(_vertices, 0, vertexCount); + target.SetColors(_colors, 0, vertexCount); + target.SetTriangles(_triangles, 0, indexCount, 0, false); + target.RecalculateBounds(); + } + + public void Render(Camera camera, Material material, int layer) + { + if (_mesh.vertexCount > 0) + Graphics.DrawMesh(_mesh, Matrix4x4.identity, material, layer, camera); + } + + // These two snapshots cannot alias: deferred rendering would otherwise + // see the second Update's alpha in both queued draws. + public void RenderFlush(Camera camera, Material material, int layer, int flush, bool rebuild) + { + if (_flushMeshes[flush] == null) + { + _flushMeshes[flush] = new Mesh { name = "Original blade flush " + flush, hideFlags = HideFlags.HideAndDontSave }; + _flushMeshes[flush].MarkDynamic(); + var root = new GameObject("Original blade flush " + flush) { hideFlags = HideFlags.HideAndDontSave, layer = layer }; + Scene scene = camera.scene.IsValid() ? camera.scene : camera.gameObject.scene; + SceneManager.MoveGameObjectToScene(root, scene); + root.AddComponent().sharedMesh = _flushMeshes[flush]; + var renderer = root.AddComponent(); + renderer.sharedMaterial = material; + renderer.sortingOrder = flush == 0 ? 0 : 3; + renderer.shadowCastingMode = ShadowCastingMode.Off; + renderer.receiveShadows = false; + renderer.lightProbeUsage = LightProbeUsage.Off; + renderer.reflectionProbeUsage = ReflectionProbeUsage.Off; + _flushRenderers[flush] = renderer; + rebuild = true; + } + if (rebuild) + Rebuild(_flushMeshes[flush]); + _flushRenderers[flush].enabled = _flushMeshes[flush].vertexCount > 0; + } + + public void Dispose() + { + _mesh.Destroy(); + for (int i = 0; i < _flushMeshes.Length; i++) + { + if (_flushRenderers[i] != null) + _flushRenderers[i].gameObject.Destroy(); + if (_flushMeshes[i] != null) + _flushMeshes[i].Destroy(); + } + } + } + +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Renderer/WeaponBlade.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Renderer/WeaponBlade.cs.meta new file mode 100644 index 00000000..5c1d67cb --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Renderer/WeaponBlade.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a852f22bc26242eb9f9e0606d3917290 diff --git a/Assets/Scripts/Pal3.Game/Rendering/Toon/ToonCameraLighting.cs b/Assets/Scripts/Pal3.Game/Rendering/Toon/ToonCameraLighting.cs index f70e5782..1f93ae4f 100644 --- a/Assets/Scripts/Pal3.Game/Rendering/Toon/ToonCameraLighting.cs +++ b/Assets/Scripts/Pal3.Game/Rendering/Toon/ToonCameraLighting.cs @@ -10,6 +10,7 @@ namespace Pal3.Game.Rendering.Toon using UnityEngine.Rendering; using Camera = UnityEngine.Camera; + [ExecuteAlways] [DisallowMultipleComponent] [RequireComponent(typeof(Camera))] public sealed class ToonCameraLighting : MonoBehaviour @@ -26,8 +27,10 @@ namespace Pal3.Game.Rendering.Toon private Object _scene; private bool _night; private bool _indoors; + private ToonLightingProfile? _preview; - internal bool ContactShadowsEnabled => _settings?.ToonContactShadows == true && _settings.ToonContactShadowStrength > 0f; + internal bool ContactShadowsEnabled => _preview.HasValue ? _preview.Value.ContactStrength > 0 : + _settings?.ToonContactShadows == true && _settings.ToonContactShadowStrength > 0f; public static ToonCameraLighting Attach(Camera camera, GameSettings settings) { @@ -37,10 +40,24 @@ namespace Pal3.Game.Rendering.Toon } lighting._settings = settings; + lighting._preview = null; lighting.enabled = true; return lighting; } + public static ToonCameraLighting AttachPreview(Camera camera) => AttachPreview(camera, ToonLightingProfile.Default); + + public static ToonCameraLighting AttachPreview(Camera camera, ToonLightingProfile profile) + { + profile.Validate(); + // An editor preview owns its lighting independently of saved game + // preferences and of other cameras rendered by the Editor. + ToonCameraLighting lighting = Attach(camera, null); + lighting._preview = profile; + lighting.SetScene(camera, profile.Night, profile.Indoors); + return lighting; + } + internal void SetScene(Object scene, bool night, bool indoors) { _scene = scene; @@ -57,6 +74,7 @@ namespace Pal3.Game.Rendering.Toon { _settings = null; _scene = null; + _preview = null; enabled = false; } @@ -86,19 +104,20 @@ namespace Pal3.Game.Rendering.Toon { if (camera == _camera) { - Shader.SetGlobalFloat(CharacterLightingId, _settings?.ToonCharacterLighting == true - ? _settings.ToonCharacterLightingStrength : 0f); + float character = _preview?.CharacterFill ?? (_settings?.ToonCharacterLighting == true ? _settings.ToonCharacterLightingStrength : 0f); + float contrast = _preview?.Contrast ?? (_settings?.ToonEnvironmentContrast == true ? _settings.ToonEnvironmentContrastStrength : 0f); + float contact = _preview?.ContactStrength ?? (ContactShadowsEnabled ? _settings.ToonContactShadowStrength : 0f); + float baked = _preview?.BakedStrength ?? (_settings?.ToonBakedShadows == true ? _settings.ToonBakedShadowStrength : 0f); + Shader.SetGlobalFloat(CharacterLightingId, character); Shader.SetGlobalFloat(NightFireBoostId, _scene != null && _night && _settings?.ToonNightFireBoost == true ? 1f : 0f); Shader.SetGlobalVector(SceneLightingId, new Vector4( _scene != null && _night ? 1f : 0f, _scene != null && _indoors ? 1f : 0f, - _scene != null && _settings?.ToonEnvironmentContrast == true - ? _settings.ToonEnvironmentContrastStrength : 0f, + _scene != null ? contrast : 0f, 0f)); Shader.SetGlobalVector(EffectStrengthsId, new Vector4( - ContactShadowsEnabled ? _settings.ToonContactShadowStrength : 0f, - _settings?.ToonBakedShadows == true ? _settings.ToonBakedShadowStrength : 0f, 0f, 0f)); + contact, baked, 0f, 0f)); } } } diff --git a/Assets/Scripts/Pal3.Game/Rendering/Toon/ToonLightingProfile.cs b/Assets/Scripts/Pal3.Game/Rendering/Toon/ToonLightingProfile.cs new file mode 100644 index 00000000..8c5d6554 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Toon/ToonLightingProfile.cs @@ -0,0 +1,106 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Rendering.Toon +{ + using System; + using UnityEngine; + + /// A captured view-local light and camera appearance, independent of saved preferences. + public readonly struct ToonLightingProfile + { + public Quaternion Rotation + { + get; + } + + public Color LightColor + { + get; + } + + public float Intensity + { + get; + } + + public float ShadowStrength + { + get; + } + + public float CharacterFill + { + get; + } + + public float Contrast + { + get; + } + + public float BakedStrength + { + get; + } + + public float ContactStrength + { + get; + } + + public bool Night + { + get; + } + + public bool Indoors + { + get; + } + + public static ToonLightingProfile Default => new(Quaternion.Euler(58, -30, 0), new Color(1, .94f, .86f), + 1, .95f, .9f, 1, .65f, 1.25f, false, false); + + public ToonLightingProfile(Quaternion rotation, Color lightColor, float intensity, float shadowStrength, + float characterFill, float contrast, float bakedStrength, float contactStrength, bool night, bool indoors) + { + Rotation = rotation; + LightColor = lightColor; + Intensity = intensity; + ShadowStrength = shadowStrength; + CharacterFill = characterFill; + Contrast = contrast; + BakedStrength = bakedStrength; + ContactStrength = contactStrength; + Night = night; + Indoors = indoors; + Validate(); + } + + public void Validate() + { + Range(Intensity, 0, 4, nameof(Intensity)); + Range(ShadowStrength, 0, 1, nameof(ShadowStrength)); + Range(CharacterFill, 0, 1, nameof(CharacterFill)); + Range(Contrast, 0, 1, nameof(Contrast)); + Range(BakedStrength, 0, 1, nameof(BakedStrength)); + Range(ContactStrength, 0, 2, nameof(ContactStrength)); + Range(LightColor.r, 0, 1, nameof(LightColor)); + Range(LightColor.g, 0, 1, nameof(LightColor)); + Range(LightColor.b, 0, 1, nameof(LightColor)); + Range(LightColor.a, 0, 1, nameof(LightColor)); + float norm = Rotation.x * Rotation.x + Rotation.y * Rotation.y + Rotation.z * Rotation.z + Rotation.w * Rotation.w; + if (!float.IsFinite(norm) || Math.Abs(norm - 1) > .001f) + throw new ArgumentException("The lighting rotation must be a finite unit quaternion.", nameof(Rotation)); + } + + private static void Range(float value, float minimum, float maximum, string name) + { + if (!float.IsFinite(value) || value < minimum || value > maximum) + throw new ArgumentOutOfRangeException(name, "The lighting value is outside its supported range."); + } + } +} diff --git a/Assets/Scripts/Pal3.Game/Rendering/Toon/ToonLightingProfile.cs.meta b/Assets/Scripts/Pal3.Game/Rendering/Toon/ToonLightingProfile.cs.meta new file mode 100644 index 00000000..96ac44b3 --- /dev/null +++ b/Assets/Scripts/Pal3.Game/Rendering/Toon/ToonLightingProfile.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fd6dce8a8cbb4aad8dde607057730d10 diff --git a/Assets/Scripts/Pal3.Game/Scene/SceneManager.cs b/Assets/Scripts/Pal3.Game/Scene/SceneManager.cs index d4263fa7..d00112ba 100644 --- a/Assets/Scripts/Pal3.Game/Scene/SceneManager.cs +++ b/Assets/Scripts/Pal3.Game/Scene/SceneManager.cs @@ -22,7 +22,7 @@ namespace Pal3.Game.Scene using Engine.Core.Implementation; using Engine.Extensions; using Engine.Logging; - using GameSystems.Combat.Scene; + using GameSystems.Battle.Scene; using Newtonsoft.Json; using Script; using State; @@ -40,10 +40,10 @@ namespace Pal3.Game.Scene private readonly IGameEntity _cameraEntity; private IGameEntity _currentSceneRoot; - private IGameEntity _currentCombatSceneRoot; + private IGameEntity _currentBattleSceneRoot; private GameScene _currentGameScene; - private CombatScene _currentCombatScene; + private BattleScene _currentBattleScene; private readonly HashSet _sceneObjectIdsToNotLoadFromSaveState = new (); @@ -72,16 +72,16 @@ namespace Pal3.Game.Scene return _currentGameScene; } - public CombatScene GetCurrentCombatScene() + public BattleScene GetCurrentBattleScene() { - return _currentCombatScene; + return _currentBattleScene; } public IGameEntity GetSceneRootGameEntity() { - if (_currentCombatSceneRoot != null) + if (_currentBattleSceneRoot != null) { - return _currentCombatSceneRoot; + return _currentBattleSceneRoot; } else if (_currentSceneRoot != null) { @@ -135,53 +135,54 @@ namespace Pal3.Game.Scene return _currentGameScene; } - public CombatScene LoadCombatScene(string combatSceneName) + public BattleScene LoadBattleScene(string combatSceneName) { Stopwatch timer = Stopwatch.StartNew(); - if (_currentCombatSceneRoot != null) UnloadCombatScene(); + if (_currentBattleSceneRoot != null) + UnloadBattleScene(); try { HideCurrentScene(); - _currentCombatSceneRoot = GameEntityFactory.Create($"CombatScene_{combatSceneName}", + _currentBattleSceneRoot = GameEntityFactory.Create($"CombatScene_{combatSceneName}", null, worldPositionStays: false); - _currentCombatScene = _currentCombatSceneRoot.AddComponent(); - _currentCombatScene.Init(_resourceProvider); - _currentCombatScene.Load(_currentCombatSceneRoot, + _currentBattleScene = _currentBattleSceneRoot.AddComponent(); + _currentBattleScene.Init(_resourceProvider); + _currentBattleScene.Load(_currentBattleSceneRoot, combatSceneName, _resourceProvider.GetMaterialManager().UsesToonRendering); } catch { - UnloadCombatScene(); + UnloadBattleScene(); throw; } - EngineLogger.Log($"CombatScene loaded in {timer.ElapsedMilliseconds} ms"); + EngineLogger.Log($"BattleScene loaded in {timer.ElapsedMilliseconds} ms"); // Also a good time to collect garbage System.GC.Collect(); - return _currentCombatScene; + return _currentBattleScene; } - public void UnloadCombatScene() + public void UnloadBattleScene() { - DisposeCombatScene(); + DisposeBattleScene(); ShowCurrentScene(); } - private void DisposeCombatScene() + private void DisposeBattleScene() { - if (_currentCombatSceneRoot?.NativeObject is GameObject root && root != null) + if (_currentBattleSceneRoot?.NativeObject is GameObject root && root != null) { root.SetActive(false); - _currentCombatSceneRoot.Destroy(); + _currentBattleSceneRoot.Destroy(); } - _currentCombatSceneRoot = null; - _currentCombatScene = null; + _currentBattleSceneRoot = null; + _currentBattleScene = null; } private readonly IList _temporarilyDisabledRenderers = new List(); @@ -259,7 +260,7 @@ namespace Pal3.Game.Scene _currentGameScene = null; } - DisposeCombatScene(); + DisposeBattleScene(); if (_currentSceneRoot != null) { diff --git a/Assets/Scripts/Pal3.Game/Settings/GameSettings.cs b/Assets/Scripts/Pal3.Game/Settings/GameSettings.cs index 286b1d94..e7511b6e 100644 --- a/Assets/Scripts/Pal3.Game/Settings/GameSettings.cs +++ b/Assets/Scripts/Pal3.Game/Settings/GameSettings.cs @@ -33,7 +33,7 @@ namespace Pal3.Game.Settings DebugLogConsole.AddCommand("Settings.AntiAliasing", "设置抗锯齿设定(0:关闭,2:2倍抗锯齿,4:4倍抗锯齿,8:8倍抗锯齿)", _ => AntiAliasing = _); DebugLogConsole.AddCommand("Settings.TargetFrameRate", - "设置目标帧率设定(-1:不限制,30:30帧,60:60帧)", _ => TargetFrameRate = _); + "设置目标帧率(-1:屏幕刷新率,正数:不高于刷新率的上限)", _ => TargetFrameRate = _); DebugLogConsole.AddCommand("Settings.ResolutionScale", "设置分辨率缩放设定(0.1:10%分辨率,0.5:50%分辨率,1.0:100%分辨率)", _ => ResolutionScale = _); DebugLogConsole.AddCommand("Settings.MusicVolume", @@ -178,32 +178,10 @@ namespace Pal3.Game.Settings AntiAliasing = UnityEngineUtility.IsDesktopDevice() ? 2 : 0; } - #if UNITY_2022_1_OR_NEWER - int screenRefreshRate = (int) Screen.currentResolution.refreshRateRatio.value; - #else - int screenRefreshRate = Screen.currentResolution.refreshRate; - #endif - - // Only respect the target frame rate if it is higher than the screen refresh rate - if (SettingsStore.TryGet(nameof(TargetFrameRate), out int targetFrameRate) && - targetFrameRate >= screenRefreshRate) - { - TargetFrameRate = targetFrameRate; - } - else - { - #if UNITY_STANDALONE - const int minimumTargetFrameRate = 120; - #elif UNITY_ANDROID || UNITY_IOS - const int minimumTargetFrameRate = 90; - #else - const int minimumTargetFrameRate = 60; - #endif - - // Set target frame rate to screen refresh rate by default - // unless it is lower than the minimum target frame rate - TargetFrameRate = Math.Max(screenRefreshRate, minimumTargetFrameRate); - } + // -1 follows the display. The rendering owner caps explicit saved + // limits too, and follows refresh-rate changes without rewriting preferences. + TargetFrameRate = SettingsStore.TryGet(nameof(TargetFrameRate), out int targetFrameRate) && targetFrameRate > 0 + ? targetFrameRate : -1; if (SettingsStore.TryGet(nameof(ResolutionScale), out float resolutionScale)) { @@ -249,7 +227,7 @@ namespace Pal3.Game.Settings SfxVolume = 0.5f; } - ToonRendering = SettingsStore.TryGet(nameof(ToonRendering), out bool toonRendering) && toonRendering; + ToonRendering = !SettingsStore.TryGet(nameof(ToonRendering), out bool toonRendering) || toonRendering; bool desktop = UnityEngineUtility.IsDesktopDevice(); ToonContactShadows = SettingsStore.TryGet(nameof(ToonContactShadows), out bool contactShadows) ? contactShadows : desktop; @@ -387,4 +365,4 @@ namespace Pal3.Game.Settings return sb.Length == 0 ? string.Empty : sb.ToString()[2..]; } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/Settings/RenderingSettingsManager.cs b/Assets/Scripts/Pal3.Game/Settings/RenderingSettingsManager.cs index b3acdf45..4853d983 100644 --- a/Assets/Scripts/Pal3.Game/Settings/RenderingSettingsManager.cs +++ b/Assets/Scripts/Pal3.Game/Settings/RenderingSettingsManager.cs @@ -10,6 +10,7 @@ namespace Pal3.Game.Settings using Command.Extensions; using Core.Command; using Core.Utilities; + using Engine.Utilities; using UnityEngine; using UnityEngine.Rendering.Universal; @@ -43,8 +44,7 @@ namespace Pal3.Game.Settings private void ApplyCurrentSettings(GameSettings settings) { - QualitySettings.vSyncCount = settings.VSyncCount; - Application.targetFrameRate = settings.TargetFrameRate; + ApplyFrameRateLimit(); ApplyResolutionScale(settings.ResolutionScale); } @@ -67,6 +67,7 @@ namespace Pal3.Game.Settings public void Update(float deltaTime) { + ApplyFrameRateLimit(); // This could happen on Android foldable devices if (_mainDisplayWidth != Display.main.systemWidth || _mainDisplayHeight != Display.main.systemHeight) @@ -77,6 +78,18 @@ namespace Pal3.Game.Settings } } + private void ApplyFrameRateLimit() + { + double refresh = DisplayFrameRate.RefreshRate; + int requested = _gameSettings.TargetFrameRate; + int vSync = DisplayFrameRate.VSyncForLimit(_gameSettings.VSyncCount, requested, refresh); + if (QualitySettings.vSyncCount != vSync) + QualitySettings.vSyncCount = vSync; + int limit = DisplayFrameRate.Limit(requested, refresh); + if (Application.targetFrameRate != limit) + Application.targetFrameRate = limit; + } + private void OnResolutionChanged() { ApplyResolutionScale(_gameSettings.ResolutionScale); @@ -98,17 +111,13 @@ namespace Pal3.Game.Settings { ApplyShadowAtlasBudget(); } - else if (command.SettingName == nameof(_gameSettings.VSyncCount)) - { - QualitySettings.vSyncCount = _gameSettings.VSyncCount; - } else if (command.SettingName == nameof(_gameSettings.AntiAliasing)) { _antiAliasing.Apply(_gameSettings.AntiAliasing); } - else if (command.SettingName == nameof(_gameSettings.TargetFrameRate)) + else if (command.SettingName is nameof(_gameSettings.TargetFrameRate) or nameof(_gameSettings.VSyncCount)) { - Application.targetFrameRate = _gameSettings.TargetFrameRate; + ApplyFrameRateLimit(); } else if (command.SettingName == nameof(_gameSettings.ResolutionScale)) { @@ -116,4 +125,4 @@ namespace Pal3.Game.Settings } } } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/Settings/SettingsBase.cs b/Assets/Scripts/Pal3.Game/Settings/SettingsBase.cs index b001e637..9ced3212 100644 --- a/Assets/Scripts/Pal3.Game/Settings/SettingsBase.cs +++ b/Assets/Scripts/Pal3.Game/Settings/SettingsBase.cs @@ -77,7 +77,8 @@ namespace Pal3.Game.Settings } } - private int _targetFrameRate = -1; // Default to -1 for unlimited frame rate + private int _targetFrameRate = -1; // -1 follows the display refresh rate + public int TargetFrameRate { get => _targetFrameRate; @@ -355,15 +356,16 @@ namespace Pal3.Game.Settings } } - private bool _isTurnBasedCombatEnabled = false; + private bool _isTurnBasedBattleEnabled = false; + public bool IsTurnBasedCombatEnabled { - get => _isTurnBasedCombatEnabled; + get => _isTurnBasedBattleEnabled; internal set { - if (_isTurnBasedCombatEnabled != value) + if (_isTurnBasedBattleEnabled != value) { - _isTurnBasedCombatEnabled = value; + _isTurnBasedBattleEnabled = value; SettingsStore.Set(nameof(IsTurnBasedCombatEnabled), value); NotifyPropertyChanged(); } @@ -372,4 +374,4 @@ namespace Pal3.Game.Settings #endregion } -} \ No newline at end of file +} diff --git a/Assets/Scripts/Pal3.Game/State/SaveManager.cs b/Assets/Scripts/Pal3.Game/State/SaveManager.cs index 4bb73b07..0ce3e4c4 100644 --- a/Assets/Scripts/Pal3.Game/State/SaveManager.cs +++ b/Assets/Scripts/Pal3.Game/State/SaveManager.cs @@ -336,7 +336,7 @@ namespace Pal3.Game.State (int)huaYingGameEntity.Transform.EulerAngles.y)); } #elif PAL3A - var combatState = ServiceLocator.Instance.Get().ScriptState; + var combatState = ServiceLocator.Instance.Get().ScriptState; commands.Add(new Pal3ARestoreCombatScriptStateCommand(combatState.Flags, combatState.LostHp, combatState.LostMp)); // Save Task state commands.AddRange(_taskManager.GetOpenedTasks(). diff --git a/Assets/Tests/Battle.meta b/Assets/Tests/Battle.meta new file mode 100644 index 00000000..686e2912 --- /dev/null +++ b/Assets/Tests/Battle.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 3ab0d1aa7ed8471faf47b6d7eb4e4899 +folderAsset: yes +DefaultImporter: + externalObjects: {} diff --git a/Assets/Tests/Battle/Editor.meta b/Assets/Tests/Battle/Editor.meta new file mode 100644 index 00000000..032b3eab --- /dev/null +++ b/Assets/Tests/Battle/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f93a6a2caf39475aa1ddf562120d303b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/Battle/Editor/BattleAbilityPresentationTests.cs b/Assets/Tests/Battle/Editor/BattleAbilityPresentationTests.cs new file mode 100644 index 00000000..fe04e83d --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAbilityPresentationTests.cs @@ -0,0 +1,323 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleAbilityPresentationTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattleAbilityEffects, IBattleStageGeometry + { + public BattleAbilityStageProfile Profile; + + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 1 }); + + public AttackTiming Ability(string source, BattleAbilityDefinition ability) => new(0, Math.Max(1, Profile.BodyAnimationTicks), new[] { 0 }, bodyAnimationTicks: Profile.BodyAnimationTicks); + + public BattleAbilityStageProfile AbilityStage(string actor, BattleAbilityDefinition ability) => Profile; + + public IReadOnlyList AbilityMovement(BattleActorSnapshot source, BattleActorSnapshot target, BattleAbilityDefinition ability, BattleDefinitions definitions, bool returning) => + new[] { new BattleMovementPlan(BattleMovementKind.Run, source.Position, returning ? source.Home : new BattleMovementPoint(0, 0, 20)) }; + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 1; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "A" ? 0 : 1; + + public int DamageDivisor(string actor) => 1; + + public BattleMovementPoint InitialHome(string actor) => new(0, 0, actor == "A" ? 100 : 0); + + public BattleMovementPoint FormationHome(string actor, BattleSlot slot) => actor == "A" ? new(10, 20, 30) : new(-10, -20, -30); + + public BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint sourceHome, BattleMovementPoint targetHome) => new(Attack(source, target), sourceHome, sourceHome, targetHome); + + public IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint currentHome, BattleMovementPoint destination, bool passThroughMidpoint) => new[] { new BattleMovementPlan(BattleMovementKind.Run, currentHome, destination) }; + } + + private sealed class Rules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => actor.Side == BattleSide.Ally ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => 1; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => new(-1, false, false); + } + + private sealed class Director : IBattleEffectDirector, IBattleMovementAudio + { + public readonly List<(long Frame, long Handle, BattleEffectRequest Request)> Started = new(); + public readonly List Stopped = new(); + private readonly Dictionary _active = new(); + private long _frame, _next; + public int FirstFrames = 5, SecondFrames = 5; + public bool FailDuringAdvance, FailDuringCleanup; + + public long Start(BattleEffectRequest request) + { + long handle = ++_next; + _active.Add(handle, (request.GroupId == 10 ? FirstFrames : SecondFrames, request.AbsoluteTime)); + Started.Add((_frame, handle, request)); + return handle; + } + + public bool IsRunning(long handle) => _active.TryGetValue(handle, out var state) && state.Frames > 0; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + if (FailDuringAdvance) + throw new InvalidOperationException("effect update failed"); + _frame = frame; + foreach (long handle in _active.Keys.ToArray()) + { + var state = _active[handle]; + if ((state.Absolute ? unscaledSeconds : scaledSeconds) > 0) + _active[handle] = (state.Frames - 1, state.Absolute); + } + } + + public void Stop(long handle) + { + Stopped.Add(handle); + _active.Remove(handle); + if (FailDuringCleanup && handle == 1) + throw new InvalidOperationException("effect release failed"); + } + + public void PlayMovementSound(string actor, string sound, bool loop) + { + } + + public void StopMovementSound(string actor) + { + } + + public void StopBodySounds() + { + if (FailDuringCleanup) + throw new InvalidOperationException("audio release failed"); + } + } + + private static BattleAbilityStageProfile Profile(BattleAbilityStageKind kind = BattleAbilityStageKind.Skill, float work = 0, + int body = 5, BattleAbilityWorkBoundary boundary = BattleAbilityWorkBoundary.WorkTime, + float wait1 = 0, float wait2 = 0.04f, bool move = false, int firstFlags = 4, int secondFlags = 8) => + new(kind, new BattleAbilityEffectBinding(10, wait1, firstFlags), new BattleAbilityEffectBinding(11, wait2, secondFlags), work, boundary, body, true, + move ? BattleMovementKind.Run : null, move ? BattleMovementKind.Run : null); + + private static BattleScenario Scenario(int id = 4201, bool item = false, bool treasure = false) + { + var scenario = new BattleScenario { Scene = "fixture", DataFingerprint = "ability-presentation" }; + foreach (string instance in new[] { "A", "E" }) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = instance, + ActorId = instance == "A" ? 101 : 701, + Side = instance == "A" ? BattleSide.Ally : BattleSide.Enemy, + Attributes = new[] { 500, 100, 100, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 100, 100 } + }); + if (item) + scenario.Items.Add(new BattleItem { Id = id, Count = 2 }); + else + scenario.Participants[0].Skills.Add(new BattleSkill { Id = id, Mastered = true, Level = 4 }); + if (treasure) + scenario.TreasureUses.Add(new BattleItem { Id = id, Count = 2 }); + return scenario; + } + + private static BattleDefinitions Definitions(BattleScenario scenario, int id, bool magic = false, bool item = false, bool treasure = false, BattleTargetRange range = BattleTargetRange.OpponentSingle) => + new(scenario.Variant, scenario.DataFingerprint, + item ? Array.Empty() : new[] { Ability(id, magic, item, treasure, range) }, + item ? new[] { Ability(id, magic, item, treasure, range) } : Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData { InstanceId = actor.InstanceId, Identity = actor.InstanceId == "A" ? 0 : -1 }))); + + private static BattleAbilityDefinition Ability(int id, bool magic, bool item, bool treasure, BattleTargetRange range) => new(new BattleAbilityData + { + Id = id, + Name = "native ordinary ability", + IsMagic = magic, + SkillTypeId = magic ? 2 : 0, + IsItem = item, + IsTreasure = treasure, + ItemType = item ? 2 : 0, + SuccessRate = 100, + Range = range, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -20) } + }); + + private static void Until(BattleSession session, Func done) + { + for (int step = 0; step < 500 && !done() && session.Status == BattleSessionStatus.Running; step++) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + Assert.That(done(), Is.True); + } + + private static BattleSession Session(BattleScenario scenario, Catalog catalog, Director director, int id = 4201, + bool magic = false, bool item = false, bool treasure = false, BattleTargetRange range = BattleTargetRange.OpponentSingle) => + new(new BattleSetup(scenario), catalog, new Rules(), Definitions(scenario, id, magic, item, treasure, range), director); + + [Test] + public void OrdinaryGroupsUseBothWaitsAndCurrentHomesWithoutFreezingCombat() + { + var catalog = new Catalog { Profile = Profile(work: 0.1f) }; + var director = new Director(); + BattleSession session = Session(Scenario(), catalog, director); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + Until(session, () => director.Started.Count == 2); + Assert.That(director.Started[0].Request.GroupId, Is.EqualTo(10)); + Assert.That(director.Started[1].Frame, Is.GreaterThan(director.Started[0].Frame)); + Assert.That(director.Started.All(entry => !entry.Request.AbsoluteTime), Is.True); + Assert.That(director.Started[0].Request.Origin.Z, Is.EqualTo(100)); + Assert.That(director.Started[1].Request.Origin.Z, Is.Zero); + Assert.That(session.SimulationTick, Is.EqualTo(session.Tick)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit), Is.False); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.Hit)); + } + + [Test] + public void GroupTargetsUseTheOriginalFormationCenterInsteadOfAnArbitraryFirstActor() + { + var catalog = new Catalog { Profile = Profile(firstFlags: 2) }; + var director = new Director(); + BattleSession session = Session(Scenario(), catalog, director, range: BattleTargetRange.OpponentAll); + session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 4201)); + Until(session, () => director.Started.Count > 0); + BattleMovementPoint origin = director.Started[0].Request.Origin; + Assert.That((origin.X, origin.Y, origin.Z), Is.EqualTo((-10f, -20f, -30f))); + } + + [Test] + public void ParallelNameAndLineupTasksKeepTheMagicActionOwnedAfterDamage() + { + var catalog = new Catalog { Profile = Profile(BattleAbilityStageKind.Magic, body: 1) }; + var director = new Director(); + BattleSession session = Session(Scenario(301), catalog, director, 301, magic: true); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.Hit)); + long workTick = session.Tick; + Assert.That(session.Actors.Single(actor => actor.Id == "A").ActionId, Is.Not.Zero); + Assert.That(workTick, Is.LessThan(50)); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded)); + Assert.That(session.Events.Single(entry => entry.Kind == BattleEventKind.ActionEnded).Tick, Is.GreaterThan(100)); + } + + [Test] + public void StealWaitsForTheRoleBodyAfterItsWorkTime() + { + var catalog = new Catalog { Profile = Profile(body: 12, boundary: BattleAbilityWorkBoundary.WorkTimeAndBodyIdle) }; + var director = new Director(); + BattleSession session = Session(Scenario(4101), catalog, director, 4101); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4101)); + Until(session, () => director.Started.Count > 0); + long started = session.Tick; + for (int step = 0; step < 5; step++) + session.Step(); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit), Is.False); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.Hit)); + Assert.That(session.Events.Single(entry => entry.Kind == BattleEventKind.Hit).Tick, Is.GreaterThanOrEqualTo(started + 12)); + } + + [Test] + public void TreasureWaitsForGroupOneAndKeepsTheRoleIdle() + { + var catalog = new Catalog { Profile = Profile(BattleAbilityStageKind.Item, body: 0, boundary: BattleAbilityWorkBoundary.WorkTimeAndFirstGroupFinished) }; + var director = new Director { FirstFrames = 20 }; + BattleSession session = Session(Scenario(6119, item: true, treasure: true), catalog, director, 6119, item: true, treasure: true); + session.Submit(new BattleCommand("A", BattleAction.Item, "E", 6119)); + Until(session, () => director.Started.Count > 0); + long started = session.Tick; + for (int step = 0; step < 10; step++) + { + session.Step(); + Assert.That(session.Actors.Single(actor => actor.Id == "A").Pose, Is.EqualTo(BattlePose.Idle)); + } + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit), Is.False); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.Hit)); + Assert.That(session.Events.Single(entry => entry.Kind == BattleEventKind.Hit).Tick, Is.EqualTo(started + 20)); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(2)); + Assert.That(session.TreasureUses.Single().Count, Is.EqualTo(1)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ApproachAndReturnRestoreFacingBeforeTheRoleActionIsReleased(string variant) + { + var catalog = new Catalog { Profile = Profile(move: true) }; + var director = new Director(); + BattleScenario scenario = Scenario(); + scenario.Variant = variant; + BattleSession session = Session(scenario, catalog, director); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)); + Until(session, () => director.Started.Count > 0); + Assert.That(session.Actors.Single(actor => actor.Id == "A").Position.Z, Is.EqualTo(20)); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded)); + Assert.That(session.Actors.Single(actor => actor.Id == "A").Position.Z, Is.EqualTo(100)); + Assert.That(session.Actors.Single(actor => actor.Id == "A").FacingDegrees, Is.EqualTo(BattleFacingRules.Initial(BattleSide.Ally))); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.MovementStarted), Is.EqualTo(2)); + } + + [Test] + public void RetiredAbilityTailEffectsStillBelongToTheSession() + { + var catalog = new Catalog { Profile = Profile(body: 1) }; + var director = new Director { SecondFrames = 400 }; + BattleSession session = Session(Scenario(), catalog, director); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded)); + long tail = director.Started.Single(entry => entry.Request.GroupId == 11).Handle; + Assert.That(director.IsRunning(tail), Is.True); + session.Abort(); + Assert.That(director.Stopped, Does.Contain(tail)); + } + + [Test] + public void FaultRetainsItsOriginalReasonAndReleasesRemainingEffectsAfterCleanupErrors() + { + var catalog = new Catalog { Profile = Profile(work: 0.1f) }; + var director = new Director { FirstFrames = 400, SecondFrames = 400 }; + BattleSession session = Session(Scenario(), catalog, director); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + Until(session, () => director.Started.Count == 2); + director.FailDuringAdvance = director.FailDuringCleanup = true; + + Assert.DoesNotThrow(session.Step); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Faulted)); + Assert.That(session.Result.Reason, Is.EqualTo("InvalidOperationException: effect update failed")); + Assert.That(session.Result.Winner, Is.Null); + Assert.That(director.Stopped, Is.EquivalentTo(director.Started.Select(entry => entry.Handle))); + Assert.That(session.StageTasks, Is.Empty); + Assert.That(session.Actors.All(actor => actor.ActionId == 0), Is.True); + Assert.That(session.Events.Where(entry => entry.Kind == BattleEventKind.PresentationCleanupFailed) + .Select(entry => entry.Detail), Is.EquivalentTo(new[] { "Body sounds: audio release failed", "Effect 1: effect release failed" })); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Ended), Is.EqualTo(1)); + } + + [Test] + public void CancellingAnAbilityStopsItsPendingMovementAndEffects() + { + var catalog = new Catalog { Profile = Profile(move: true) }; + var director = new Director(); + BattleSession session = Session(Scenario(), catalog, director); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.MovementStarted)); + session.CancelAction("A"); + float stopped = session.Actors.Single(actor => actor.Id == "A").Position.Z; + for (int step = 0; step < 10; step++) + session.Step(); + Assert.That(session.Actors.Single(actor => actor.Id == "A").Position.Z, Is.EqualTo(stopped)); + Assert.That(director.Started, Is.Empty); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleAbilityPresentationTests.cs.meta b/Assets/Tests/Battle/Editor/BattleAbilityPresentationTests.cs.meta new file mode 100644 index 00000000..35f1ed83 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAbilityPresentationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3674fdf5f4784b519c2ba8aeea4e8f7f diff --git a/Assets/Tests/Battle/Editor/BattleAiControlTests.cs b/Assets/Tests/Battle/Editor/BattleAiControlTests.cs new file mode 100644 index 00000000..6ab4f770 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAiControlTests.cs @@ -0,0 +1,198 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleAiControlTests + { + // The 64 rows of 64 outcomes came from exhaustive execution of both + // published ProcAIList comparison branches; the two matrices match. + private const string NativeCosts = + "AAAAAP////8AAAAA/////wAAAAD/////AAAAAP////8AAAAA/////wAAAAD/////AAAAAP////8AAAAA/////wAAAAD/////AAAAAP////8AAAAA" + + "/////wAAAAD/////AAAAAP////8AAAAA/////wAAAAD/////AAAAAP////8AAAAA/////wAAAAD/////AAAAAP////8AAAAA/////wAAAAD/////" + + "AAAAAP////8AAAAA/////wAAAAD/////AAAAAP////8AAAAA/////wAAAAD/////AAAAAP////8AAAAA/////wAAAAD/////AAAAAP////8AAAAA" + + "///////////8//////////z/////////8//////////z/////////8//////////z/////////8//////////z////////////z//////////P//" + + "///////z//////////P/////////z//////////P/////////z//////////P////////////P/////////8//////////P/////////8///////" + + "///P/////////8//////////P/////////8////////////8//////////z/////////8//////////z/////////8//////////z/////////8/" + + "/////////z8="; + + private sealed class Catalog : IBattleCatalog + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "A" ? 0 : actor == "B" ? 1 : 2; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class Effects : IBattleEffectDirector, IBattleModalEffects + { + public bool BlocksBattleTime + { + get; set; + } + + public bool SkipModalPresentation() => false; + + public long Start(BattleEffectRequest request) => 1; + + public bool IsRunning(long handle) => false; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + } + } + + private static (BattleSession Session, BattleSetup Setup, Catalog Catalog, BattleDefinitions Definitions) Create(string variant, Effects effects = null) + { + var scenario = new BattleScenario { Variant = variant, Scene = "portable", DataFingerprint = "ai-control", Encounter = BattleEncounter.AllyAmbush }; + foreach (var entry in new[] { ("A", BattleSide.Ally, BattleSlot.Water), ("B", BattleSide.Ally, BattleSlot.Fire), ("E", BattleSide.Enemy, BattleSlot.Water) }) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = entry.Item1, + ActorId = entry.Item1 == "A" ? 101 : entry.Item1 == "B" ? variant == "PAL3" ? 104 : 102 : 701, + Side = entry.Item2, + Slot = entry.Item3, + Attributes = new[] { 100, 100, 100, 60, 20, 3, 2, 0, 0, 0, 0, 0 }, + Vitals = new[] { 100, 100, 100 } + }); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, Array.Empty(), Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId == "A" ? 0 : actor.InstanceId == "B" ? 1 : -1 + }))); + var setup = new BattleSetup(scenario); + var catalog = new Catalog(); + var session = new BattleSession(setup, catalog, definitions: definitions, effects: effects); + session.SetAutomatic(BattleSide.Enemy, false); + return (session, setup, catalog, definitions); + } + + private static BattleActorSnapshot Actor(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + [Test] + public void EveryProfileComparisonMatchesBothPublishedPrograms() + { + byte[] matrix = Convert.FromBase64String(NativeCosts); + for (int before = 0; before < 64; before++) + for (int after = 0; after < 64; after++) + Assert.That(BattleAiControlRules.ConsumesGauges(before, after), + Is.EqualTo((matrix[before * 8 + after / 8] & (1 << (after % 8))) != 0), $"before={before}, after={after}"); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ConfirmingEnabledAiConsumesOnlyTheControllersGaugesAndRecordsOneInput(string variant) + { + var fixture = Create(variant); + BattleSession session = fixture.Session; + BattleActorSnapshot before = Actor(session, "A"), companion = Actor(session, "B"); + uint random = session.Events.Last().RandomState; + int count = session.Inputs.Count; + int flags = session.GetAiProfile("A") | 33; + Assert.That(session.CommitAiControl("A", flags), Is.True); + Assert.That(session.Inputs.Skip(count).Select(input => input.Kind), Is.EqualTo(new[] { BattleInputKind.AiControl })); + Assert.That(session.GetAiProfile("A"), Is.EqualTo(flags)); + BattleActorSnapshot after = Actor(session, "A"); + Assert.That((after.Gauge, after.CastGauge, after.Ready), Is.EqualTo((0, 0, false))); + Assert.That((after.Hp, after.Sp, after.Mp, after.Rounds, after.Guarding, after.Pose), + Is.EqualTo((before.Hp, before.Sp, before.Mp, before.Rounds, before.Guarding, before.Pose))); + Assert.That(Actor(session, "B").Gauge, Is.EqualTo(companion.Gauge)); + Assert.That(session.WaitingActor, Is.EqualTo("B")); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(random)); + } + + [TestCase("PAL3", 2)] + [TestCase("PAL3A", 2)] + [TestCase("PAL3", 1)] + [TestCase("PAL3A", 1)] + public void DisabledChildrenAndAttackOnlyDifferencesStillCommitWithoutGaugeCost(string variant, int flags) + { + BattleSession session = Create(variant).Session; + session.SetAiProfile("A", 0); + int count = session.Inputs.Count; + uint random = session.Events.Last().RandomState; + Assert.That(session.CommitAiControl("A", flags), Is.True); + Assert.That(session.GetAiProfile("A"), Is.EqualTo(flags)); + Assert.That((Actor(session, "A").Gauge, Actor(session, "A").Ready), Is.EqualTo((BattleSession.FullGauge, true))); + Assert.That(session.WaitingActor, Is.EqualTo("A")); + Assert.That(session.Inputs.Count, Is.EqualTo(count + 1)); + Assert.That(session.Inputs.Last().Kind, Is.EqualTo(BattleInputKind.AiControl)); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(random)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void IdenticalConfirmationIsAcceptedWithoutAnInputOrMutation(string variant) + { + BattleSession session = Create(variant).Session; + int inputs = session.Inputs.Count, events = session.Events.Count; + Assert.That(session.CommitAiControl("A", session.GetAiProfile("A")), Is.True); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs)); + Assert.That(session.Events.Count, Is.EqualTo(events)); + Assert.That(Actor(session, "A").Gauge, Is.EqualTo(BattleSession.FullGauge)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void DebugSetterRemainsFreeAndAtomicConfirmReplaysWithTheSameGaugeCost(string variant) + { + var fixture = Create(variant); + BattleSession session = fixture.Session; + session.SetAiProfile("A", 0); + Assert.That(Actor(session, "A").Gauge, Is.EqualTo(BattleSession.FullGauge)); + Assert.That(session.CommitAiControl("A", 2), Is.True); + Assert.That(session.CommitAiControl("A", 35), Is.True); + Assert.That(session.Submit("B", BattleAction.Defend), Is.True); + for (int tick = 0; tick < 4; tick++) + session.Step(); + BattleSession replay = BattleReplay.Play(fixture.Setup, fixture.Catalog, session.Inputs, session.Tick, definitions: fixture.Definitions); + Assert.That(replay.GetAiProfile("A"), Is.EqualTo(session.GetAiProfile("A"))); + Assert.That(replay.Actors.Select(actor => (actor.Id, actor.Gauge, actor.CastGauge, actor.Ready, actor.Guarding, actor.Hp, actor.Rounds)), + Is.EqualTo(session.Actors.Select(actor => (actor.Id, actor.Gauge, actor.CastGauge, actor.Ready, actor.Guarding, actor.Hp, actor.Rounds)))); + Assert.That(replay.Events.Select(entry => (entry.Tick, entry.Kind, entry.Source, entry.RandomState, entry.Detail)), + Is.EqualTo(session.Events.Select(entry => (entry.Tick, entry.Kind, entry.Source, entry.RandomState, entry.Detail)))); + Assert.That(replay.Events.Last().RandomState, Is.EqualTo(session.Events.Last().RandomState)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void StaleEnemyModalAndCompletedControllersCannotChangeProfiles(string variant) + { + var effects = new Effects(); + BattleSession session = Create(variant, effects).Session; + int count = session.Inputs.Count; + uint random = session.Events.Last().RandomState; + foreach (string controller in new[] { "B", "E", "missing", null }) + Assert.That(session.CommitAiControl(controller, 33), Is.False); + effects.BlocksBattleTime = true; + Assert.That(session.CommitAiControl("A", 33), Is.False); + effects.BlocksBattleTime = false; + Assert.That(session.Inputs.Count, Is.EqualTo(count)); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(random)); + session.Abort(); + count = session.Inputs.Count; + Assert.That(session.CommitAiControl("A", 33), Is.False); + Assert.That(session.Inputs.Count, Is.EqualTo(count)); + Assert.Throws(() => session.CommitAiControl("A", 64)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleAiControlTests.cs.meta b/Assets/Tests/Battle/Editor/BattleAiControlTests.cs.meta new file mode 100644 index 00000000..196259fd --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAiControlTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3e1c776f879c46e2a37717d6f20e2173 diff --git a/Assets/Tests/Battle/Editor/BattleAiFieldTests.cs b/Assets/Tests/Battle/Editor/BattleAiFieldTests.cs new file mode 100644 index 00000000..26c0609b --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAiFieldTests.cs @@ -0,0 +1,330 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using Battle; + using NUnit.Framework; + + public sealed class BattleAiFieldTests + { + // Published PAL3A MagicPower plus real scene field accessors; metadata lookup is an explicit port. + private static readonly string[] NativeVectors = + { + "0,0,1,-101,1,-201,3357800067", + "0,0,1,-101,12345,-206,1255958651", + "0,0,1,101,1,201,3357800067", + "0,0,1,101,12345,206,1255958651", + "0,0,2,-101,1,-201,3357800067", + "0,0,2,-101,12345,-206,1255958651", + "0,0,2,101,1,201,3357800067", + "0,0,2,101,12345,206,1255958651", + "0,0,4,-101,1,-201,3357800067", + "0,0,4,-101,12345,-206,1255958651", + "0,0,4,101,1,201,3357800067", + "0,0,4,101,12345,206,1255958651", + "0,0,8,-101,1,-201,3357800067", + "0,0,8,-101,12345,-206,1255958651", + "0,0,8,101,1,201,3357800067", + "0,0,8,101,12345,206,1255958651", + "0,0,16,-101,1,-201,3357800067", + "0,0,16,-101,12345,-206,1255958651", + "0,0,16,101,1,201,3357800067", + "0,0,16,101,12345,206,1255958651", + "0,0,9,-101,1,-201,3357800067", + "0,0,9,-101,12345,-206,1255958651", + "0,0,9,101,1,201,3357800067", + "0,0,9,101,12345,206,1255958651", + "0,5,1,-101,1,-103,3357800067", + "0,5,1,-101,12345,-116,1255958651", + "0,5,1,101,1,103,3357800067", + "0,5,1,101,12345,116,1255958651", + "0,5,2,-101,1,-103,3357800067", + "0,5,2,-101,12345,-116,1255958651", + "0,5,2,101,1,103,3357800067", + "0,5,2,101,12345,116,1255958651", + "0,5,4,-101,1,-103,3357800067", + "0,5,4,-101,12345,-116,1255958651", + "0,5,4,101,1,103,3357800067", + "0,5,4,101,12345,116,1255958651", + "0,5,8,-101,1,-103,3357800067", + "0,5,8,-101,12345,-116,1255958651", + "0,5,8,101,1,103,3357800067", + "0,5,8,101,12345,116,1255958651", + "0,5,16,-101,1,-103,3357800067", + "0,5,16,-101,12345,-116,1255958651", + "0,5,16,101,1,103,3357800067", + "0,5,16,101,12345,116,1255958651", + "0,5,9,-101,1,-103,3357800067", + "0,5,9,-101,12345,-116,1255958651", + "0,5,9,101,1,103,3357800067", + "0,5,9,101,12345,116,1255958651", + "1,0,1,-101,1,-261,3357800067", + "1,0,1,-101,12345,-268,1255958651", + "1,0,1,101,1,261,3357800067", + "1,0,1,101,12345,268,1255958651", + "1,0,2,-101,1,-201,3357800067", + "1,0,2,-101,12345,-206,1255958651", + "1,0,2,101,1,201,3357800067", + "1,0,2,101,12345,206,1255958651", + "1,0,4,-101,1,-201,3357800067", + "1,0,4,-101,12345,-206,1255958651", + "1,0,4,101,1,201,3357800067", + "1,0,4,101,12345,206,1255958651", + "1,0,8,-101,1,-201,3357800067", + "1,0,8,-101,12345,-206,1255958651", + "1,0,8,101,1,201,3357800067", + "1,0,8,101,12345,206,1255958651", + "1,0,16,-101,1,-101,3357800067", + "1,0,16,-101,12345,-103,1255958651", + "1,0,16,101,1,101,3357800067", + "1,0,16,101,12345,103,1255958651", + "1,0,9,-101,1,-261,3357800067", + "1,0,9,-101,12345,-268,1255958651", + "1,0,9,101,1,261,3357800067", + "1,0,9,101,12345,268,1255958651", + "1,5,1,-101,1,-134,3357800067", + "1,5,1,-101,12345,-151,1255958651", + "1,5,1,101,1,134,3357800067", + "1,5,1,101,12345,151,1255958651", + "1,5,2,-101,1,-103,3357800067", + "1,5,2,-101,12345,-116,1255958651", + "1,5,2,101,1,103,3357800067", + "1,5,2,101,12345,116,1255958651", + "1,5,4,-101,1,-103,3357800067", + "1,5,4,-101,12345,-116,1255958651", + "1,5,4,101,1,103,3357800067", + "1,5,4,101,12345,116,1255958651", + "1,5,8,-101,1,-103,3357800067", + "1,5,8,-101,12345,-116,1255958651", + "1,5,8,101,1,103,3357800067", + "1,5,8,101,12345,116,1255958651", + "1,5,16,-101,1,-52,3357800067", + "1,5,16,-101,12345,-58,1255958651", + "1,5,16,101,1,52,3357800067", + "1,5,16,101,12345,58,1255958651", + "1,5,9,-101,1,-134,3357800067", + "1,5,9,-101,12345,-151,1255958651", + "1,5,9,101,1,134,3357800067", + "1,5,9,101,12345,151,1255958651", + "2,0,1,-101,1,-101,3357800067", + "2,0,1,-101,12345,-103,1255958651", + "2,0,1,101,1,101,3357800067", + "2,0,1,101,12345,103,1255958651", + "2,0,2,-101,1,-261,3357800067", + "2,0,2,-101,12345,-268,1255958651", + "2,0,2,101,1,261,3357800067", + "2,0,2,101,12345,268,1255958651", + "2,0,4,-101,1,-201,3357800067", + "2,0,4,-101,12345,-206,1255958651", + "2,0,4,101,1,201,3357800067", + "2,0,4,101,12345,206,1255958651", + "2,0,8,-101,1,-201,3357800067", + "2,0,8,-101,12345,-206,1255958651", + "2,0,8,101,1,201,3357800067", + "2,0,8,101,12345,206,1255958651", + "2,0,16,-101,1,-201,3357800067", + "2,0,16,-101,12345,-206,1255958651", + "2,0,16,101,1,201,3357800067", + "2,0,16,101,12345,206,1255958651", + "2,0,9,-101,1,-101,3357800067", + "2,0,9,-101,12345,-103,1255958651", + "2,0,9,101,1,101,3357800067", + "2,0,9,101,12345,103,1255958651", + "2,5,1,-101,1,-52,3357800067", + "2,5,1,-101,12345,-58,1255958651", + "2,5,1,101,1,52,3357800067", + "2,5,1,101,12345,58,1255958651", + "2,5,2,-101,1,-134,3357800067", + "2,5,2,-101,12345,-151,1255958651", + "2,5,2,101,1,134,3357800067", + "2,5,2,101,12345,151,1255958651", + "2,5,4,-101,1,-103,3357800067", + "2,5,4,-101,12345,-116,1255958651", + "2,5,4,101,1,103,3357800067", + "2,5,4,101,12345,116,1255958651", + "2,5,8,-101,1,-103,3357800067", + "2,5,8,-101,12345,-116,1255958651", + "2,5,8,101,1,103,3357800067", + "2,5,8,101,12345,116,1255958651", + "2,5,16,-101,1,-103,3357800067", + "2,5,16,-101,12345,-116,1255958651", + "2,5,16,101,1,103,3357800067", + "2,5,16,101,12345,116,1255958651", + "2,5,9,-101,1,-52,3357800067", + "2,5,9,-101,12345,-58,1255958651", + "2,5,9,101,1,52,3357800067", + "2,5,9,101,12345,58,1255958651", + "3,0,1,-101,1,-201,3357800067", + "3,0,1,-101,12345,-206,1255958651", + "3,0,1,101,1,201,3357800067", + "3,0,1,101,12345,206,1255958651", + "3,0,2,-101,1,-201,3357800067", + "3,0,2,-101,12345,-206,1255958651", + "3,0,2,101,1,201,3357800067", + "3,0,2,101,12345,206,1255958651", + "3,0,4,-101,1,-261,3357800067", + "3,0,4,-101,12345,-268,1255958651", + "3,0,4,101,1,261,3357800067", + "3,0,4,101,12345,268,1255958651", + "3,0,8,-101,1,-101,3357800067", + "3,0,8,-101,12345,-103,1255958651", + "3,0,8,101,1,101,3357800067", + "3,0,8,101,12345,103,1255958651", + "3,0,16,-101,1,-201,3357800067", + "3,0,16,-101,12345,-206,1255958651", + "3,0,16,101,1,201,3357800067", + "3,0,16,101,12345,206,1255958651", + "3,0,9,-101,1,-101,3357800067", + "3,0,9,-101,12345,-103,1255958651", + "3,0,9,101,1,101,3357800067", + "3,0,9,101,12345,103,1255958651", + "3,5,1,-101,1,-103,3357800067", + "3,5,1,-101,12345,-116,1255958651", + "3,5,1,101,1,103,3357800067", + "3,5,1,101,12345,116,1255958651", + "3,5,2,-101,1,-103,3357800067", + "3,5,2,-101,12345,-116,1255958651", + "3,5,2,101,1,103,3357800067", + "3,5,2,101,12345,116,1255958651", + "3,5,4,-101,1,-134,3357800067", + "3,5,4,-101,12345,-151,1255958651", + "3,5,4,101,1,134,3357800067", + "3,5,4,101,12345,151,1255958651", + "3,5,8,-101,1,-52,3357800067", + "3,5,8,-101,12345,-58,1255958651", + "3,5,8,101,1,52,3357800067", + "3,5,8,101,12345,58,1255958651", + "3,5,16,-101,1,-103,3357800067", + "3,5,16,-101,12345,-116,1255958651", + "3,5,16,101,1,103,3357800067", + "3,5,16,101,12345,116,1255958651", + "3,5,9,-101,1,-52,3357800067", + "3,5,9,-101,12345,-58,1255958651", + "3,5,9,101,1,52,3357800067", + "3,5,9,101,12345,58,1255958651", + "4,0,1,-101,1,-201,3357800067", + "4,0,1,-101,12345,-206,1255958651", + "4,0,1,101,1,201,3357800067", + "4,0,1,101,12345,206,1255958651", + "4,0,2,-101,1,-101,3357800067", + "4,0,2,-101,12345,-103,1255958651", + "4,0,2,101,1,101,3357800067", + "4,0,2,101,12345,103,1255958651", + "4,0,4,-101,1,-201,3357800067", + "4,0,4,-101,12345,-206,1255958651", + "4,0,4,101,1,201,3357800067", + "4,0,4,101,12345,206,1255958651", + "4,0,8,-101,1,-261,3357800067", + "4,0,8,-101,12345,-268,1255958651", + "4,0,8,101,1,261,3357800067", + "4,0,8,101,12345,268,1255958651", + "4,0,16,-101,1,-201,3357800067", + "4,0,16,-101,12345,-206,1255958651", + "4,0,16,101,1,201,3357800067", + "4,0,16,101,12345,206,1255958651", + "4,0,9,-101,1,-261,3357800067", + "4,0,9,-101,12345,-268,1255958651", + "4,0,9,101,1,261,3357800067", + "4,0,9,101,12345,268,1255958651", + "4,5,1,-101,1,-103,3357800067", + "4,5,1,-101,12345,-116,1255958651", + "4,5,1,101,1,103,3357800067", + "4,5,1,101,12345,116,1255958651", + "4,5,2,-101,1,-52,3357800067", + "4,5,2,-101,12345,-58,1255958651", + "4,5,2,101,1,52,3357800067", + "4,5,2,101,12345,58,1255958651", + "4,5,4,-101,1,-103,3357800067", + "4,5,4,-101,12345,-116,1255958651", + "4,5,4,101,1,103,3357800067", + "4,5,4,101,12345,116,1255958651", + "4,5,8,-101,1,-134,3357800067", + "4,5,8,-101,12345,-151,1255958651", + "4,5,8,101,1,134,3357800067", + "4,5,8,101,12345,151,1255958651", + "4,5,16,-101,1,-103,3357800067", + "4,5,16,-101,12345,-116,1255958651", + "4,5,16,101,1,103,3357800067", + "4,5,16,101,12345,116,1255958651", + "4,5,9,-101,1,-134,3357800067", + "4,5,9,-101,12345,-151,1255958651", + "4,5,9,101,1,134,3357800067", + "4,5,9,101,12345,151,1255958651", + "5,0,1,-101,1,-201,3357800067", + "5,0,1,-101,12345,-206,1255958651", + "5,0,1,101,1,201,3357800067", + "5,0,1,101,12345,206,1255958651", + "5,0,2,-101,1,-201,3357800067", + "5,0,2,-101,12345,-206,1255958651", + "5,0,2,101,1,201,3357800067", + "5,0,2,101,12345,206,1255958651", + "5,0,4,-101,1,-101,3357800067", + "5,0,4,-101,12345,-103,1255958651", + "5,0,4,101,1,101,3357800067", + "5,0,4,101,12345,103,1255958651", + "5,0,8,-101,1,-201,3357800067", + "5,0,8,-101,12345,-206,1255958651", + "5,0,8,101,1,201,3357800067", + "5,0,8,101,12345,206,1255958651", + "5,0,16,-101,1,-261,3357800067", + "5,0,16,-101,12345,-268,1255958651", + "5,0,16,101,1,261,3357800067", + "5,0,16,101,12345,268,1255958651", + "5,0,9,-101,1,-201,3357800067", + "5,0,9,-101,12345,-206,1255958651", + "5,0,9,101,1,201,3357800067", + "5,0,9,101,12345,206,1255958651", + "5,5,1,-101,1,-103,3357800067", + "5,5,1,-101,12345,-116,1255958651", + "5,5,1,101,1,103,3357800067", + "5,5,1,101,12345,116,1255958651", + "5,5,2,-101,1,-103,3357800067", + "5,5,2,-101,12345,-116,1255958651", + "5,5,2,101,1,103,3357800067", + "5,5,2,101,12345,116,1255958651", + "5,5,4,-101,1,-52,3357800067", + "5,5,4,-101,12345,-58,1255958651", + "5,5,4,101,1,52,3357800067", + "5,5,4,101,12345,58,1255958651", + "5,5,8,-101,1,-103,3357800067", + "5,5,8,-101,12345,-116,1255958651", + "5,5,8,101,1,103,3357800067", + "5,5,8,101,12345,116,1255958651", + "5,5,16,-101,1,-134,3357800067", + "5,5,16,-101,12345,-151,1255958651", + "5,5,16,101,1,134,3357800067", + "5,5,16,101,12345,151,1255958651", + "5,5,9,-101,1,-103,3357800067", + "5,5,9,-101,12345,-116,1255958651", + "5,5,9,101,1,103,3357800067", + "5,5,9,101,12345,116,1255958651", + }; + + private static IEnumerable NativeCases() + { + foreach (string vector in NativeVectors) + yield return new TestCaseData(vector); + } + + [TestCaseSource(nameof(NativeCases))] + public void DynamicFiveSpiritPowerMatchesPublishedImage(string vector) + { + string[] values = vector.Split(','); + int Read(int index) => int.Parse(values[index], CultureInfo.InvariantCulture); + int field = Read(0); + var source = new BattleParticipant { Level = 20, Side = Read(1) == 0 ? BattleSide.Ally : BattleSide.Enemy, Slot = BattleSlot.Center }; + var target = new BattleParticipant { Side = source.Side == BattleSide.Ally ? BattleSide.Enemy : BattleSide.Ally }; + var random = new BattleRandom(Read(4)); + int power = new BattleEffectRules("PAL3A").MagicPower(Read(3), source, target, Read(2), random, + field > 0 ? 1 << (field - 1) : 0, BattleEffectRules.GreaterElement(field)); + Assert.That(power, Is.EqualTo(Read(5)), vector); + Assert.That(random.State, Is.EqualTo(uint.Parse(values[6], CultureInfo.InvariantCulture)), vector); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleAiFieldTests.cs.meta b/Assets/Tests/Battle/Editor/BattleAiFieldTests.cs.meta new file mode 100644 index 00000000..0420b1a2 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAiFieldTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f397ab319b9e4ceea751a36148239957 diff --git a/Assets/Tests/Battle/Editor/BattleAiSessionTests.cs b/Assets/Tests/Battle/Editor/BattleAiSessionTests.cs new file mode 100644 index 00000000..509d3e3a --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAiSessionTests.cs @@ -0,0 +1,797 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Battle; + using NUnit.Framework; + + public sealed class BattleAiSessionTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings + { + public readonly Dictionary Timings = new(); + + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string source, BattleAbilityDefinition ability) => Timings.TryGetValue(ability.Id, out AttackTiming timing) ? timing : new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class Effects : IBattleEffectDirector + { + private long _next; + public readonly List Requests = new(); + + public long Start(BattleEffectRequest request) + { + Requests.Add(request); + return ++_next; + } + + public bool IsRunning(long handle) => false; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + } + } + + private sealed class Rules : IBattleRules + { + private readonly bool _allyReady, _enemyReady; + private readonly int _speed; + private readonly BattleBasicRules _original = new(); + + public Rules(bool allyReady, bool enemyReady, int speed = 1) + { + _allyReady = allyReady; + _enemyReady = enemyReady; + _speed = speed; + } + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + (actor.Side == BattleSide.Ally ? _allyReady : _enemyReady) ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => actor.Side == BattleSide.Enemy && !_enemyReady ? 0 : _speed; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => _original.Hit(source, target, guarding, random, targetAtHome, damageDivisor); + } + + private static BattleParticipant Actor(string id, BattleSide side, BattleSlot slot, int hp = 1000, int maximum = 1000) => new() + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = slot, + Attributes = new[] { maximum, 100, 100, 60, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { hp, 100, 100 } + }; + + private static BattleScenario Scenario(string variant = "PAL3", int seed = 1) + { + var scenario = new BattleScenario { Variant = variant, Scene = "portable", DataFingerprint = "ai-port", Seed = seed }; + scenario.Participants.Add(Actor("A", BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(Actor("E", BattleSide.Enemy, BattleSlot.Water)); + return scenario; + } + + private static BattleAbilityDefinition Ability(int id, int power, bool magic, BattleTargetRange range, int cost = 0, + bool revive = false, bool item = false, int element = 1) => new(new BattleAbilityData + { + Id = id, + Name = "native AI port fixture", + IsMagic = magic, + IsItem = item, + ItemType = item ? power < 0 ? 2 : 1 : 0, + SkillTypeId = magic ? power < 0 ? 2 : 3 : 0, + Range = range, + ElementMask = element, + Attributes = power == 0 ? Array.Empty() : new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, power) }, + States = revive ? new[] { new BattleStatusEffect(BattleState.Death, true) } : Array.Empty(), + Costs = cost == 0 ? Array.Empty() : new[] { new BattleCost(magic ? 2 : 1, BattleValueMode.Absolute, cost) } + }); + + private static (BattleSession Session, BattleSetup Setup, BattleDefinitions Definitions, Catalog Catalog, Rules Rules) Create( + BattleScenario scenario, IEnumerable abilities, bool allyReady, bool enemyReady, int speed = 1, IBattleEffectDirector effects = null) + { + BattleAbilityDefinition[] all = abilities.ToArray(); + var definitions = new BattleDefinitions(scenario.Variant, scenario.DataFingerprint, all.Where(ability => !ability.IsItem), all.Where(ability => ability.IsItem), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? actor.InstanceId == "A" ? 0 : 1 : -1 + }))); + var setup = new BattleSetup(scenario); + var catalog = new Catalog(); + var rules = new Rules(allyReady, enemyReady, speed); + return (new BattleSession(setup, catalog, rules, definitions, effects), setup, definitions, catalog, rules); + } + + private static BattleActorSnapshot Snapshot(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + private static void AdvanceUntil(BattleSession session, Func condition, int maximum = 1000) + { + for (int step = 0; step < maximum && !condition() && session.Status == BattleSessionStatus.Running; step++) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + Assert.That(condition(), Is.True); + } + + private static string Trace(BattleSession session) => string.Join("\n", session.Events.Select(entry => + $"{entry.Tick}|{entry.Kind}|{entry.Source}|{entry.Target}|{entry.ActionId}|{entry.AbilityId}|{entry.RequestedDelta}|{entry.ActualDelta}|{entry.RandomState}|{entry.Detail}")); + + private static void Replay((BattleSession Session, BattleSetup Setup, BattleDefinitions Definitions, Catalog Catalog, Rules Rules) fixture, IBattleEffectDirector effects = null) + { + BattleSession replay = BattleReplay.Play(fixture.Setup, fixture.Catalog, fixture.Session.Inputs, fixture.Session.Tick, fixture.Rules, fixture.Definitions, effects); + Assert.That(Trace(replay), Is.EqualTo(Trace(fixture.Session))); + Assert.That(replay.Inventory.Select(item => item.Id + ":" + item.Count), Is.EqualTo(fixture.Session.Inventory.Select(item => item.Id + ":" + item.Count))); + Assert.That(replay.FiveSpiritElement, Is.EqualTo(fixture.Session.FiveSpiritElement)); + Assert.That(replay.FiveSpiritForce, Is.EqualTo(fixture.Session.FiveSpiritForce)); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void MagicSelectorsPreserveExplicitNativeSlotsWithoutDroppingOtherMagic(string variant, bool miscellaneous) + { + BattleScenario scenario = Scenario(variant); + foreach (int id in new[] { 264, 312, 316, 9001 }) + scenario.Participants[0].Skills.Add(new BattleSkill + { + Id = id, + Level = 4, + Mastered = true, + NativeMagicGroup = id is 312 or 316 ? 0 : -1, + NativeMagicSlot = id == 316 ? 0 : id == 312 ? 1 : -1 + }); + BattleAbilityDefinition Magic(int id) => new(new BattleAbilityData + { + Id = id, + IsMagic = true, + SkillTypeId = id == 264 ? 0 : miscellaneous ? 1 : 2, + ApplicableIdentities = id is 312 or 316 ? new[] { 0 } : Array.Empty(), + ElementMask = 1, + Range = id is 264 or 9001 ? BattleTargetRange.OpponentAll : + miscellaneous ? BattleTargetRange.OwnSingle : BattleTargetRange.OpponentSingle, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -50) } + }); + var fixture = Create(scenario, new[] { 264, 312, 316, 9001 }.Select(Magic), true, false); + var ai = (BattleAi)typeof(BattleSession).GetField("_ai", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(fixture.Session); + Assert.That(ai.Roles[0].Skills.Select(skill => skill.Id), Is.EqualTo(new[] { 264, 316, 312, 9001 })); + if (miscellaneous) + { + var expectedRandom = new BattleRandom(unchecked((int)fixture.Session.Events.Last().RandomState), variant); + int expected = new[] { 316, 312 }[expectedRandom.Next() % 2]; + Assert.That(ai.SelectMiscMagic(0, false), Is.EqualTo(expected)); + } + else + Assert.That(ai.SelectMagic(0, true, false, 50), Is.EqualTo(316), "Equal power retains the first captured native slot."); + } + + // Released GetFightSkillRange: PAL3 4f0830, PAL3A 4e1efe. + // A tests signed HP, independently of the later FixState alive flag. + [TestCase("PAL3", 0, false, true)] + [TestCase("PAL3", 0, true, true)] + [TestCase("PAL3", 1, false, true)] + [TestCase("PAL3A", 0, false, false)] + [TestCase("PAL3A", 0, true, false)] + [TestCase("PAL3A", 1, false, true)] + public void RepeatGroupRangeRetainsTheReleasedCorpseAndHpBoundaries(string variant, int hp, bool alive, bool included) + { + var fixture = Create(Scenario(variant), new[] { Ability(9001, -10, true, BattleTargetRange.OpponentAll) }, true, false); + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + var actors = (IDictionary)typeof(BattleSession).GetField("_byId", fields).GetValue(fixture.Session); + object enemy = actors["E"]; + enemy.GetType().GetField("Hp").SetValue(enemy, hp); + enemy.GetType().GetField("Alive").SetValue(enemy, alive); + var port = (BattleAiPort)typeof(BattleSession).GetField("_aiPort", fields).GetValue(fixture.Session); + var command = new BattleAiCommand { Kind = 0x105, AbilityId = 9001, Source = 0, Target = 5 }; + port.ExpandRepeatRange(command); + Assert.That(command.MultipleTargets, Is.True); + Assert.That(command.TargetMask[5], Is.EqualTo(included)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void EnemyUsesItsFourthRecoverySlotAndSharesTheRecordedRandomStream(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Vitals[0] = 400; + for (int slot = 0; slot < 4; slot++) + scenario.Participants[1].Skills.Add(new BattleSkill { Id = 9001 + slot, Level = slot == 3 ? 4 : slot + 1, Mastered = true }); + BattleAbilityDefinition[] spells = new[] { 10, 40, 100, 400 }.Select((power, slot) => Ability(9001 + slot, power, true, BattleTargetRange.OwnSingle, cost: 5)).ToArray(); + var fixture = Create(scenario, spells, false, true); + fixture.Session.Step(); + BattleEvent command = fixture.Session.Events.First(entry => entry.Kind == BattleEventKind.Command); + Assert.That(command.Source, Is.EqualTo("E")); + Assert.That(command.Target, Is.EqualTo("E")); + Assert.That(fixture.Session.Inputs.First(input => input.Kind == BattleInputKind.Command).AbilityId, Is.EqualTo(9004)); + Assert.That(command.RandomState, Is.EqualTo(1030492215u)); + AdvanceUntil(fixture.Session, () => Snapshot(fixture.Session, "E").Hp > 400); + Assert.That(Snapshot(fixture.Session, "E").Mp, Is.EqualTo(95)); + Replay(fixture); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NegativeProfileUsesAnEnabledRecoveryTechniqueBeforeAttacking(string variant) + { + BattleScenario scenario = Scenario(variant, 107); + scenario.Participants[0].Vitals[0] = 100; + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 9001, Level = 4, Mastered = true }); + var fixture = Create(scenario, new[] { Ability(9001, 20, false, BattleTargetRange.OwnSingle, cost: 10) }, true, false); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + fixture.Session.SetAiProfile("A", 1 | 4 | 16 | 32); + fixture.Session.Step(); + BattleEvent command = fixture.Session.Events.First(entry => entry.Kind == BattleEventKind.Command); + Assert.That(fixture.Session.Inputs.First(input => input.Kind == BattleInputKind.Command).AbilityId, Is.EqualTo(9001)); + Assert.That(command.Target, Is.EqualTo("A")); + AdvanceUntil(fixture.Session, () => Snapshot(fixture.Session, "A").Hp > 100); + Assert.That(Snapshot(fixture.Session, "A").Sp, Is.EqualTo(90)); + Replay(fixture); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RepeatKeepsTheManualGroupMaskAfterAnUnselectedEnemyRevives(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.Add(Actor("E2", BattleSide.Enemy, BattleSlot.Fire, 0)); + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 9001, Level = 4, Mastered = true }); + scenario.Participants[1].Skills.Add(new BattleSkill { Id = 9002, Level = 4, Mastered = true }); + var fixture = Create(scenario, new[] + { + Ability(9001, -30, true, BattleTargetRange.OpponentAll), + Ability(9002, 50, true, BattleTargetRange.OwnSingle, revive: true) + }, true, true, BattleSession.FullGauge); + fixture.Catalog.Timings[9002] = new AttackTiming(0, 5, new[] { 1 }); + BattleSession session = fixture.Session; + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 9001)), Is.True); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "E2", 9002)), Is.True); + for (int step = 0; step < 100 && session.WaitingActor != "A"; step++) + { + if (session.WaitingActor is { } waiting) + Assert.That(session.Submit(waiting, BattleAction.Defend), Is.True); + session.Step(); + } + Assert.That(session.WaitingActor, Is.EqualTo("A")); + Assert.That(Snapshot(session, "E2").Hp, Is.Positive); + int revivedHp = Snapshot(session, "E2").Hp; + int originalEnemyHp = Snapshot(session, "E").Hp; + Assert.That(session.RequestAiRepeat("A"), Is.True); + AdvanceUntil(session, () => Snapshot(session, "E").Hp < originalEnemyHp); + Assert.That(Snapshot(session, "E2").Hp, Is.EqualTo(revivedHp)); + Replay(fixture); + } + + [TestCase("PAL3", "E2")] + [TestCase("PAL3A", "E")] + public void FUsesTheReleasedRatioPrecisionAndReplaysItsInput(string variant, string target) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Attributes[0] = 100; + scenario.Participants[1].Vitals[0] = 20; + scenario.Participants.Add(Actor("E2", BattleSide.Enemy, BattleSlot.Fire, 20, 100)); + var fixture = Create(scenario, Array.Empty(), true, false); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(fixture.Session.RequestAiNormal("A"), Is.True); + Assert.That(fixture.Session.Events.Last(entry => entry.Kind == BattleEventKind.Command).Target, Is.EqualTo(target)); + Assert.That(fixture.Session.Inputs.Any(input => input.Kind == BattleInputKind.AiNormal), Is.True); + Assert.That((fixture.Session.GetAiProfile("A") & 1), Is.EqualTo(0)); + Replay(fixture); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RRepeatsTheRememberedDefenseWithoutRunningOrdinaryAi(string variant) + { + var fixture = Create(Scenario(variant), Array.Empty(), true, false, BattleSession.FullGauge); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(fixture.Session.Submit("A", BattleAction.Defend), Is.True); + AdvanceUntil(fixture.Session, () => fixture.Session.WaitingActor == "A"); + Assert.That(fixture.Session.RequestAiRepeat("A"), Is.True); + Assert.That(fixture.Session.Events.Last(entry => entry.Kind == BattleEventKind.Command).Detail, Does.StartWith("Defend")); + Replay(fixture); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NegativeProfileRevivesFromInventoryBeforeSpendingAnAttack(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.Add(Actor("B", BattleSide.Ally, BattleSlot.Fire, 0)); + scenario.Items.Add(new BattleItem { Id = 6201, Count = 1 }); + var fixture = Create(scenario, new[] { Ability(6201, 100, false, BattleTargetRange.OwnSingle, revive: true, item: true) }, true, false); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + fixture.Session.SetAiProfile("A", 1 | 8 | 16 | 32); + fixture.Session.Step(); + BattleEvent command = fixture.Session.Events.First(entry => entry.Kind == BattleEventKind.Command); + Assert.That(command.Target, Is.EqualTo("B")); + Assert.That(fixture.Session.Inputs.First(input => input.Kind == BattleInputKind.Command).AbilityId, Is.EqualTo(6201)); + AdvanceUntil(fixture.Session, () => Snapshot(fixture.Session, "B").Hp > 0); + Assert.That(fixture.Session.Inventory, Is.Empty); + Replay(fixture); + } + + [TestCase("PAL3", 7711)] + [TestCase("PAL3A", 7714)] + public void SingleAttackConversionCanSubmitAnOriginalSpecialIdOutsideTheFourSlots(string variant, int original) + { + BattleScenario scenario = Scenario(variant, 107); + scenario.Participants[1].Skills.Add(new BattleSkill { Id = original, Level = 4, Mastered = true }); + BattleAbilityDefinition[] spells = new[] { Ability(original, -20, true, BattleTargetRange.OpponentSingle, cost: 5) } + .Concat(new[] { 207, 215, 232, 224, 240 }.Select(id => Ability(id, -20, true, BattleTargetRange.OpponentSingle))).ToArray(); + var fixture = Create(scenario, spells, false, true, 100); + fixture.Session.SetAiProfile("E", 2 | 32); + AdvanceUntil(fixture.Session, () => fixture.Session.Events.Any(entry => entry.Kind == BattleEventKind.Command), 100); + int chosen = fixture.Session.Inputs.First(input => input.Kind == BattleInputKind.Command).AbilityId; + Assert.That(new[] { 207, 215, 232, 224, 240 }, Does.Contain(chosen)); + Assert.That(scenario.Participants[1].Skills.Any(skill => skill.Id == chosen), Is.False); + AdvanceUntil(fixture.Session, () => fixture.Session.Events.Any(entry => entry.Kind is BattleEventKind.Hit or BattleEventKind.Miss), 1000); + Replay(fixture); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ChaosRunsWithoutTheEnabledFlagAndRetainsTheOriginalSamplingFailure(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Statuses.Add(new BattleStatus { Id = (int)BattleState.Chaos, Rounds = 10 }); + var fixture = Create(scenario, Array.Empty(), true, false); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + fixture.Session.Step(); + Assert.That(fixture.Session.Events.Any(entry => entry.Kind == BattleEventKind.Command), Is.False); + fixture.Session.SetAiProfile("A", 1); + Assert.That(fixture.Session.Events.Last().RandomState, Is.EqualTo(1957819393u)); + Replay(fixture); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void MadnessCanSubmitARealFriendlyPhysicalAttackWithAttackDisabled(string variant) + { + BattleScenario scenario = Scenario(variant, 2); + scenario.Participants[0].Statuses.Add(new BattleStatus { Id = (int)BattleState.Madness, Rounds = 10 }); + scenario.Participants.Add(Actor("B", BattleSide.Ally, BattleSlot.Fire)); + var fixture = Create(scenario, Array.Empty(), true, false); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + fixture.Session.Step(); + BattleInput command = fixture.Session.Inputs.First(input => input.Kind == BattleInputKind.Command); + Assert.That(command.Action, Is.EqualTo(BattleAction.Attack)); + Assert.That(command.Actor, Is.EqualTo("A")); + Assert.That(command.Target, Is.EqualTo("B")); + Replay(fixture); + } + + [Test] + public void FiveSpiritDedicatedMagicWaitAcceptsItsOriginalNoneRangeAndSetsTheFieldAtWork() + { + BattleScenario scenario = Scenario("PAL3A", 107); + scenario.Participants[1].Skills.Add(new BattleSkill { Id = 264, Level = 4, Mastered = true }); + var field = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 264, + IsMagic = true, + SkillTypeId = 0, + Range = BattleTargetRange.None, + ElementMask = 1, + Costs = new[] { new BattleCost(2, BattleValueMode.Absolute, 5) } + }); + var fixture = Create(scenario, new[] { field }, false, true); + fixture.Session.Step(); + Assert.That(fixture.Session.Inputs.Last(input => input.Kind == BattleInputKind.Command).AbilityId, Is.EqualTo(264)); + Assert.That(fixture.Session.FiveSpiritElement, Is.EqualTo(0)); + AdvanceUntil(fixture.Session, () => fixture.Session.FiveSpiritElement == 1); + Assert.That(fixture.Session.FiveSpiritForce, Is.EqualTo(2)); + Assert.That(Snapshot(fixture.Session, "E").Mp, Is.EqualTo(95)); + Replay(fixture); + } + + [Test] + public void FullMpBossUsesItsDedicatedMagicAndStartsEffect559() + { + BattleScenario scenario = Scenario("PAL3", 107); + scenario.Participants.Add(Actor("B", BattleSide.Ally, BattleSlot.Fire, 0)); + scenario.Participants[1].ActorId = 739; + scenario.Participants[1].Skills.Add(new BattleSkill { Id = 7709, Level = 4, Mastered = true }); + var effects = new Effects(); + var fixture = Create(scenario, new[] { Ability(7709, -360, true, BattleTargetRange.OpponentAll, cost: 80) }, false, true, effects: effects); + fixture.Session.SetAiProfile("E", 32); + fixture.Session.Step(); + Assert.That(fixture.Session.Inputs.Last(input => input.Kind == BattleInputKind.Command).AbilityId, Is.EqualTo(7709)); + Assert.That(effects.Requests.Single(request => request.GroupId == 559).Targets, Is.EqualTo(new[] { "A", "B" })); + AdvanceUntil(fixture.Session, () => Snapshot(fixture.Session, "E").Mp == 20); + Replay(fixture, new Effects()); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", true)] + public void FRetainsTheNativeInvisibleTargetDifferenceIncludingRejectedInputReplay(string variant, bool accepted) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Statuses.Add(new BattleStatus { Id = (int)BattleState.Invisible, Rounds = 5 }); + var fixture = Create(scenario, Array.Empty(), true, false); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(fixture.Session.RequestAiNormal("A"), Is.EqualTo(accepted)); + Assert.That(fixture.Session.Inputs.Count(input => input.Kind == BattleInputKind.Command), Is.EqualTo(accepted ? 1 : 0)); + Assert.That(fixture.Session.Inputs.Last(input => input.Kind == BattleInputKind.AiNormal).Actor, Is.EqualTo("A")); + Replay(fixture); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AReadyManualPlayerBlocksLaterEnemyDispatchEvenWhenSystemAutoOnlyIsSet(string variant) + { + var fixture = Create(Scenario(variant, 107), Array.Empty(), true, true); + fixture.Session.Step(); + Assert.That(fixture.Session.Inputs.Any(input => input.Kind == BattleInputKind.Command), Is.False); + fixture.Session.SetAiAutoOnly(true); + fixture.Session.Step(); + Assert.That(fixture.Session.Inputs.Any(input => input.Kind == BattleInputKind.Command), Is.False); + Assert.That(fixture.Session.Submit("A", BattleAction.Defend), Is.True); + fixture.Session.Step(); + Assert.That(fixture.Session.Inputs.Any(input => input.Kind == BattleInputKind.Command && input.Actor == "E"), Is.True); + Replay(fixture); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void WorstStatePreservesTheReleasedRoleZeroLifeGateAndNullCureField(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Vitals[0] = 0; + scenario.Participants.Add(Actor("B", BattleSide.Ally, BattleSlot.Fire)); + scenario.Participants.Add(Actor("C", BattleSide.Ally, BattleSlot.Wind)); + scenario.Participants[2].Skills.Add(new BattleSkill { Id = 9001, Level = 4, Mastered = true }); + scenario.Participants[3].Statuses.Add(new BattleStatus { Id = (int)BattleState.Paralysis, Rounds = 10 }); + var spell = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 9001, + IsMagic = true, + SkillTypeId = 1, + ElementMask = 1, + Range = BattleTargetRange.OwnSingle, + SuccessRate = 2, + Costs = new[] { new BattleCost(2, BattleValueMode.Absolute, 5) } + }); + var fixture = Create(scenario, new[] { spell }, true, false); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + fixture.Session.SetAiProfile("B", 2 | 16 | 32); + fixture.Session.Step(); + BattleInput command = fixture.Session.Inputs.First(input => input.Kind == BattleInputKind.Command); + Assert.That(command.Actor, Is.EqualTo("B")); + Assert.That(command.Target, Is.EqualTo("C")); + Assert.That(command.AbilityId, Is.EqualTo(9001)); + AdvanceUntil(fixture.Session, () => Snapshot(fixture.Session, "B").Mp == 95); + Assert.That(Snapshot(fixture.Session, "C").States.Any(state => state.State == BattleState.Paralysis), Is.True); + Replay(fixture); + } + + [Test] + public void ASealedFiveSpiritAttemptQueuesThenCancelsAtItsFirstMagicWaitPass() + { + BattleScenario scenario = Scenario("PAL3A", 107); + scenario.Participants[1].Skills.Add(new BattleSkill { Id = 264, Level = 4, Mastered = true }); + scenario.Participants[1].Statuses.Add(new BattleStatus { Id = (int)BattleState.Seal, Rounds = 10 }); + var field = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 264, + IsMagic = true, + SkillTypeId = 0, + Range = BattleTargetRange.None, + ElementMask = 1, + Costs = new[] { new BattleCost(2, BattleValueMode.Absolute, 5) } + }); + var fixture = Create(scenario, new[] { field }, false, true); + fixture.Session.SetAiProfile("E", 32); + fixture.Session.Step(); + Assert.That(fixture.Session.Inputs.Last(input => input.Kind == BattleInputKind.Command).AbilityId, Is.EqualTo(264)); + fixture.Session.Step(); + Assert.That(fixture.Session.Events.Any(entry => entry.Kind == BattleEventKind.Cancelled && entry.Source == "E"), Is.True); + Assert.That(fixture.Session.FiveSpiritElement, Is.EqualTo(0)); + Assert.That(Snapshot(fixture.Session, "E").Mp, Is.EqualTo(100)); + Assert.That(Snapshot(fixture.Session, "E").Ready, Is.False); + Replay(fixture); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void SealAppliedAfterMagicActStartsDoesNotCancelTheAct(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 9001, Level = 4, Mastered = true }); + scenario.Participants[1].Skills.Add(new BattleSkill { Id = 9002, Level = 4, Mastered = true }); + var seal = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 9002, + SkillTypeId = 0, + Range = BattleTargetRange.OpponentSingle, + States = new[] { new BattleStatusEffect(BattleState.Seal, false) } + }); + var fixture = Create(scenario, new[] { Ability(9001, -20, true, BattleTargetRange.OpponentSingle), seal }, true, true); + fixture.Catalog.Timings[9001] = new AttackTiming(0, 30, new[] { 20 }); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(fixture.Session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 9001)), Is.True); + fixture.Session.Step(); + Assert.That(fixture.Session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 9002)), Is.True); + AdvanceUntil(fixture.Session, () => Snapshot(fixture.Session, "A").States.Any(state => state.State == BattleState.Seal)); + Assert.That(fixture.Session.Events.Any(entry => entry.Kind == BattleEventKind.Cancelled && entry.Source == "A"), Is.False); + AdvanceUntil(fixture.Session, () => fixture.Session.Events.Any(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "A")); + Assert.That(fixture.Session.Events.Any(entry => entry.Kind == BattleEventKind.Cancelled && entry.Source == "A"), Is.False); + Replay(fixture); + } + + [Test] + public void AFieldForbiddenMagicIsExcludedBeforeRankingTheLegalSpells() + { + BattleScenario scenario = Scenario("PAL3A"); + scenario.FiveSpiritElement = 1; + scenario.FiveSpiritForce = 2; + scenario.Participants[0].Vitals[0] = 100; + foreach (int id in new[] { 9001, 9010, 9011 }) + scenario.Participants[0].Skills.Add(new BattleSkill { Id = id, Level = 4, Mastered = true }); + var fixture = Create(scenario, new[] + { + Ability(9001, 20, false, BattleTargetRange.OwnSingle, cost: 10), + Ability(9010, 400, true, BattleTargetRange.OwnSingle, cost: 5), + Ability(9011, 10, true, BattleTargetRange.OwnSingle, cost: 5, element: 2) + }, true, false); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + fixture.Session.SetAiProfile("A", 63); + fixture.Session.Step(); + Assert.That(fixture.Session.Inputs.Last(input => input.Kind == BattleInputKind.Command).AbilityId, Is.EqualTo(9011)); + AdvanceUntil(fixture.Session, () => Snapshot(fixture.Session, "A").Hp > 100); + Assert.That(Snapshot(fixture.Session, "A").Mp, Is.EqualTo(95)); + Assert.That(Snapshot(fixture.Session, "A").Sp, Is.EqualTo(100)); + Replay(fixture); + } + + [Test] + public void NativeFieldDenialDuringRankingInvalidatesDifferentSavedCommand() + { + BattleScenario scenario = Scenario("PAL3A"); + scenario.FiveSpiritElement = 1; + scenario.FiveSpiritForce = 2; + scenario.Participants[0].InstanceId = "B"; + scenario.Participants[0].ActorId = 102; + scenario.Participants[0].Vitals[0] = 100; + foreach (int id in new[] { 318, 302 }) + scenario.Participants[0].Skills.Add(new BattleSkill { Id = id, Level = 4, Mastered = true }); + var fixture = Create(scenario, new[] + { + Ability(318, 100, true, BattleTargetRange.OwnSingle, cost: 5), + Ability(302, 40, true, BattleTargetRange.OwnSingle, cost: 5, element: 4) + }, true, false, BattleSession.FullGauge); + var session = fixture.Session; + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(session.Submit("B", BattleAction.Defend), Is.True); + session.SetAiProfile("B", 63); + AdvanceUntil(session, () => session.Inputs.Any(input => input.Kind == BattleInputKind.Command && input.AbilityId == 302)); + session.SetAiProfile("B", 31); + AdvanceUntil(session, () => session.WaitingActor == "B"); + Assert.That(session.RequestAiRepeat("B"), Is.True); + Replay(fixture); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Attack)); + } + + [Test] + public void VisitingAForbiddenMagicRowRecordsTheRepeatInvalidation() + { + BattleScenario scenario = Scenario("PAL3A"); + scenario.FiveSpiritElement = 1; + scenario.FiveSpiritForce = 2; + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 318, Level = 4, Mastered = true }); + var magic = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 318, + ApplicableIdentities = new[] { 0 }, + SkillTypeId = 3, + IsMagic = true, + Range = BattleTargetRange.OwnSingle, + ElementMask = 1 + }); + var fixture = Create(scenario, new[] { magic }, true, false, BattleSession.FullGauge); + var session = fixture.Session; + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(session.Submit("A", BattleAction.Defend), Is.True); + AdvanceUntil(session, () => session.WaitingActor == "A"); + int before = session.RecordedInputCount; + Assert.That(session.CanSubmit(new BattleCommand("A", BattleAction.Skill, "A", 318)), Is.Not.Null); + Assert.That(session.RecordedInputCount, Is.EqualTo(before)); + Assert.That(session.InspectMagicMenuAbility("A", 318), Is.True); + Assert.That(session.Inputs.Last().Kind, Is.EqualTo(BattleInputKind.MagicMenuFieldDenial)); + Assert.That(session.InspectMagicMenuAbility("A", 318), Is.False); + Assert.That(session.RecordedInputCount, Is.EqualTo(before + 1)); + Assert.That(session.RequestAiRepeat("A"), Is.True); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Attack)); + Replay(fixture); + } + + [Test] + public void EnemyFieldDeniesManualMagicAndInvalidatesARepeatBeforeFallingBack() + { + BattleScenario scenario = Scenario("PAL3A"); + scenario.FiveSpiritElement = 1; + scenario.FiveSpiritForce = 2; + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 9001, Level = 4, Mastered = true }); + var fixture = Create(scenario, new[] { Ability(9001, -10, true, BattleTargetRange.OpponentSingle) }, true, false); + var session = fixture.Session; + var command = new BattleCommand("A", BattleAction.Skill, "E", 9001); + Assert.That(session.CanSubmit(command), Does.Contain("五灵阵法")); + Assert.That(session.Submit(command), Is.False); + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + var saved = (IDictionary)typeof(BattleSession).GetField("_aiLastCommands", fields).GetValue(session); + saved[0] = new BattleAiCommand { Source = 0, Kind = 0x105, AbilityId = 9001, Target = 5 }; + Assert.That(session.RequestAiRepeat("A"), Is.True); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Attack)); + Assert.That(saved.Contains(0), Is.False); + } + + [TestCase("PAL3", false, "E2")] + [TestCase("PAL3A", false, "E3")] + [TestCase("PAL3", true, "E2")] + [TestCase("PAL3A", true, "E2")] + public void RRetargetsAbsoluteHpAndAppliesTheOriginalMagicVersusNormalBackFilter(string variant, bool magic, string expected) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Vitals[0] = 1; + scenario.Participants.Add(Actor("E2", BattleSide.Enemy, BattleSlot.Fire, 10)); + scenario.Participants.Add(Actor("E3", BattleSide.Enemy, BattleSlot.Center, 500)); + if (magic) + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 9001, Level = 4, Mastered = true }); + var fixture = Create(scenario, magic ? new[] { Ability(9001, -20, true, BattleTargetRange.OpponentSingle) } : Array.Empty(), + true, false, BattleSession.FullGauge); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(fixture.Session.Submit(new BattleCommand("A", magic ? BattleAction.Skill : BattleAction.Attack, "E", magic ? 9001 : 0)), Is.True); + AdvanceUntil(fixture.Session, () => Snapshot(fixture.Session, "E").Hp == 0 && fixture.Session.WaitingActor == "A"); + Assert.That(fixture.Session.RequestAiRepeat("A"), Is.True); + Assert.That(fixture.Session.Inputs.Last(input => input.Kind == BattleInputKind.Command).Target, Is.EqualTo(expected)); + Replay(fixture); + } + + [TestCase(0, false)] + [TestCase(1, false)] + [TestCase(0, true)] + public void Pal3ARepeatRetargetsEnemyDebuffsAndThrowablesAfterTheOriginalTargetDies(int skillType, bool item) + { + const int id = 9001; + BattleScenario scenario = Scenario("PAL3A"); + scenario.Participants[1].Vitals[0] = 1; + scenario.Participants.Add(Actor("B", BattleSide.Ally, BattleSlot.Fire)); + scenario.Participants.Add(Actor("E2", BattleSide.Enemy, BattleSlot.Fire)); + if (item) + scenario.Items.Add(new BattleItem { Id = id, Count = 2 }); + else + scenario.Participants[0].Skills.Add(new BattleSkill { Id = id, Level = 4, Mastered = true }); + var ability = new BattleAbilityDefinition(new BattleAbilityData + { + Id = id, + IsItem = item, + ItemType = item ? 2 : 0, + IsMagic = skillType != 0, + SkillTypeId = skillType, + Range = BattleTargetRange.OpponentSingle, + SuccessRate = 100, + States = new[] { new BattleStatusEffect(BattleState.DefenseDecrease, false) } + }); + var fixture = Create(scenario, new[] { ability }, true, false, BattleSession.FullGauge); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(fixture.Session.Submit(new BattleCommand("A", item ? BattleAction.Item : BattleAction.Skill, "E", id)), Is.True); + Assert.That(fixture.Session.Submit("B", BattleAction.Attack, "E"), Is.True); + fixture.Session.SetAiProfile("B", 32); + for (int step = 0; step < 80 && (Snapshot(fixture.Session, "E").Hp > 0 || fixture.Session.WaitingActor != "A"); step++) + fixture.Session.Step(); + Assert.That((Snapshot(fixture.Session, "E").Hp, fixture.Session.WaitingActor), Is.EqualTo((0, "A")), Trace(fixture.Session)); + + Assert.That(fixture.Session.RequestAiRepeat("A"), Is.True); + Assert.That(fixture.Session.Inputs.Last(input => input.Kind == BattleInputKind.Command).Target, Is.EqualTo("E2")); + Replay(fixture); + } + + [Test] + public void AutoOnlyChangesTheSystemFlagAndKeepsEveryActorCapability() + { + var fixture = Create(Scenario(), Array.Empty(), false, false); + int before = fixture.Session.GetAiProfile("A"); + fixture.Session.SetAiAutoOnly(true); + Assert.That(fixture.Session.IsAutomatic(BattleSide.Ally), Is.True); + Assert.That(fixture.Session.GetAiProfile("A"), Is.EqualTo(before)); + Replay(fixture); + } + + [TestCase(false)] + [TestCase(true)] + public void FiveSpiritFieldExpiresAfterFiveSuccessfulActionsOfItsAlivePlayerAnchor(bool endWithAiControl) + { + BattleScenario scenario = Scenario("PAL3A"); + scenario.FiveSpiritElement = 1; + scenario.FiveSpiritForce = 2; + var fixture = Create(scenario, Array.Empty(), true, false, BattleSession.FullGauge); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + for (int action = 1; action <= 5; action++) + { + if (action == 5 && endWithAiControl) + { + int profile = fixture.Session.GetAiProfile("A"); + Assert.That(fixture.Session.CommitAiControl("A", profile ^ 1), Is.True, "Editing attack preference keeps the turn."); + Assert.That(fixture.Session.FiveSpiritElement, Is.EqualTo(1)); + Assert.That(fixture.Session.CommitAiControl("A", profile ^ 32), Is.True); + } + else + Assert.That(fixture.Session.Submit("A", BattleAction.Defend), Is.True); + Assert.That(fixture.Session.FiveSpiritElement, Is.EqualTo(action < 5 ? 1 : 0)); + if (action < 5) + AdvanceUntil(fixture.Session, () => fixture.Session.WaitingActor == "A"); + } + Assert.That(fixture.Session.FiveSpiritForce, Is.EqualTo(0)); + Replay(fixture); + } + + [TestCase("A", 0, 1, -201)] + [TestCase("A", 1, 1, -261)] + [TestCase("A", 1, 16, -101)] + [TestCase("E", 0, 1, -103)] + [TestCase("E", 1, 1, -134)] + [TestCase("E", 1, 16, -52)] + public void DynamicFieldChangesRealMagicPowerForEitherForceAndReplays(string source, int field, int mask, int expectedPower) + { + BattleScenario scenario = Scenario("PAL3A"); + scenario.SceneElement = 2; + scenario.FiveSpiritElement = field; + scenario.FiveSpiritForce = source == "A" ? 1 : 2; + BattleParticipant caster = scenario.Participants.Single(actor => actor.InstanceId == source); + caster.Level = 20; + caster.Slot = BattleSlot.Center; + caster.Skills.Add(new BattleSkill { Id = 9001, Level = 4, Mastered = true }); + var fixture = Create(scenario, new[] { Ability(9001, -101, true, BattleTargetRange.OpponentSingle, element: mask) }, source == "A", source == "E"); + fixture.Session.SetAutomatic(BattleSide.Enemy, false); + string target = source == "A" ? "E" : "A"; + Assert.That(fixture.Session.Submit(new BattleCommand(source, BattleAction.Skill, target, 9001)), Is.True); + AdvanceUntil(fixture.Session, () => Snapshot(fixture.Session, target).Hp < 1000); + Assert.That(Snapshot(fixture.Session, target).Hp, Is.EqualTo(1000 + expectedPower)); + BattleEvent damage = fixture.Session.Events.Last(entry => entry.Kind == BattleEventKind.Hit && entry.Source == source); + Assert.That(damage.RandomState, Is.EqualTo(3357800067u)); + Replay(fixture); + } + + [TestCase("PAL3", 1766988168u)] + [TestCase("PAL3A", 1924036713u)] + public void FailedReadyEnemyAttemptsOnlyOneNativeDecisionPerControlFrame(string variant, uint expectedState) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.Add(Actor("B", BattleSide.Ally, BattleSlot.Fire)); + scenario.Participants.Add(Actor("E2", BattleSide.Enemy, BattleSlot.Fire)); + var fixture = Create(scenario, Array.Empty(), false, true); + fixture.Session.SetAiProfile("E", 32); + fixture.Session.SetAiProfile("E2", 0); + fixture.Session.Step(); + Assert.That(fixture.Session.Inputs.Any(input => input.Kind == BattleInputKind.Command), Is.False); + fixture.Session.SetAiProfile("E", 0); + Assert.That(fixture.Session.Events.Last().RandomState, Is.EqualTo(expectedState)); + Replay(fixture); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleAiSessionTests.cs.meta b/Assets/Tests/Battle/Editor/BattleAiSessionTests.cs.meta new file mode 100644 index 00000000..d2fba822 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAiSessionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f3d89088fd604233a10f4337b1f2c6e8 diff --git a/Assets/Tests/Battle/Editor/BattleAiSupportTests.cs b/Assets/Tests/Battle/Editor/BattleAiSupportTests.cs new file mode 100644 index 00000000..2676fde5 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAiSupportTests.cs @@ -0,0 +1,2458 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using Battle; + using NUnit.Framework; + + // Released-EXE selectors executed with synthetic records; GDB/inventory lookup and + // CanCastTrick are explicit ports. Original range, category, power and ranking execute. + public sealed class BattleAiSupportTests + { + private static readonly string[] NativeVectors = + { + "S|PAL3|Skill|recover|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|-25|negative|9002|9002:1,9004:1", + "S|PAL3|Skill|recover|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|0|negative|9002|9002:1,9004:1", + "S|PAL3|Skill|recover|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|25|negative|9002|9002:1,9004:1", + "S|PAL3|Skill|recover|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|80|negative|9004|9002:1,9004:1", + "S|PAL3|Skill|recover|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|0|250|negative|9004|9002:1,9004:1", + "S|PAL3|Skill|recover|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|-25|negative|9002|9002:1,9004:1", + "S|PAL3|Skill|recover|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|0|negative|9002|9002:1,9004:1", + "S|PAL3|Skill|recover|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|25|negative|9002|9002:1,9004:1", + "S|PAL3|Skill|recover|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|80|negative|9004|9002:1,9004:1", + "S|PAL3|Skill|recover|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|recover|1|250|negative|9004|9002:1,9004:1", + "S|PAL3|Skill|recover|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|-25|negative|9001|9001:1,9003:1", + "S|PAL3|Skill|attack|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|0|negative|9001|9001:1,9003:1", + "S|PAL3|Skill|attack|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|25|negative|9001|9001:1,9003:1", + "S|PAL3|Skill|attack|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|80|negative|9001|9001:1,9003:1", + "S|PAL3|Skill|attack|0|80|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|0|250|negative|9001|9001:1,9003:1", + "S|PAL3|Skill|attack|0|250|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|-25|negative|9001|9001:1,9003:1", + "S|PAL3|Skill|attack|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|0|negative|9001|9001:1,9003:1", + "S|PAL3|Skill|attack|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|25|negative|9001|9001:1,9003:1", + "S|PAL3|Skill|attack|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|80|negative|9001|9001:1,9003:1", + "S|PAL3|Skill|attack|1|80|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|attack|1|250|negative|9001|9001:1,9003:1", + "S|PAL3|Skill|attack|1|250|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|80|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|250|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|80|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|250|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|revive|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|0|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Skill|cure|1|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|revive|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|0|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Magic|cure|1|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|-25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|-25|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|-25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|0|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|0|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|0|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|25|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|80|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|80|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|250|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|250|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|250|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|0|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|-25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|-25|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|-25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|0|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|0|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|0|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|25|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|80|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|80|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|250|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|250|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|250|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|recover|1|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|-25|wrongRange|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|-25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|0|wrongRange|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|0|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|0|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|25|wrongRange|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|80|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|250|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|250|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|0|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|-25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|-25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|0|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|0|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|0|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|80|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|250|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|250|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|attack|1|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|-25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|0|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|250|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|0|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|-25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|0|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|250|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|revive|1|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|-25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|0|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|80|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|80|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|80|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|250|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|250|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|0|250|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|-25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|0|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|80|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|80|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|80|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|250|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|250|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|Item|cure|1|250|zeroCount|9002|9002:1,9003:1,9004:1", + "C|PAL3|7711|0|224|2531011", + "C|PAL3|7711|1|215|2745024", + "C|PAL3|7711|2|207|2959037", + "C|PAL3|7711|107|224|25430402", + "C|PAL3|7711|12345|240|2644521496", + "C|PAL3|7714|0|7714|0", + "C|PAL3|7714|1|7714|1", + "C|PAL3|7714|2|7714|2", + "C|PAL3|7714|107|7714|107", + "C|PAL3|7714|12345|7714|12345", + "C|PAL3|9001|0|9001|0", + "C|PAL3|9001|1|9001|1", + "C|PAL3|9001|2|9001|2", + "C|PAL3|9001|107|9001|107", + "C|PAL3|9001|12345|9001|12345", + "U|PAL3|Skill|0,2,1,2||9002|9002:1,9004:1", + "U|PAL3|Skill|0,2,1,2|9002|9004|9002:0,9004:1", + "U|PAL3|Skill|2,0,0,0||9001|9001:1", + "U|PAL3|Skill|2,0,0,0|9002|9001|9001:1", + "U|PAL3|Skill|0,0,0,0||0|", + "U|PAL3|Skill|0,0,0,0|9002|0|", + "U|PAL3|Magic|0,2,1,2||9002|9002:1,9004:1", + "U|PAL3|Magic|0,2,1,2|9002|9004|9002:0,9004:1", + "U|PAL3|Magic|2,0,0,0||9001|9001:1", + "U|PAL3|Magic|2,0,0,0|9002|9001|9001:1", + "U|PAL3|Magic|0,0,0,0||0|", + "U|PAL3|Magic|0,0,0,0|9002|0|", + "U|PAL3|Item|0,2,1,2||9002|9002:1,9004:1", + "U|PAL3|Item|0,2,1,2|9002|9004|9002:0,9004:1", + "U|PAL3|Item|2,0,0,0||9001|9001:1", + "U|PAL3|Item|2,0,0,0|9002|9001|9001:1", + "U|PAL3|Item|0,0,0,0||0|", + "U|PAL3|Item|0,0,0,0|9002|0|", + "S|PAL3A|Skill|recover|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|-25|negative|9002|9002:1,9004:1", + "S|PAL3A|Skill|recover|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|0|negative|9002|9002:1,9004:1", + "S|PAL3A|Skill|recover|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|25|negative|9002|9002:1,9004:1", + "S|PAL3A|Skill|recover|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|80|negative|9004|9002:1,9004:1", + "S|PAL3A|Skill|recover|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|0|250|negative|9004|9002:1,9004:1", + "S|PAL3A|Skill|recover|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|-25|negative|9002|9002:1,9004:1", + "S|PAL3A|Skill|recover|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|0|negative|9002|9002:1,9004:1", + "S|PAL3A|Skill|recover|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|25|negative|9002|9002:1,9004:1", + "S|PAL3A|Skill|recover|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|80|negative|9004|9002:1,9004:1", + "S|PAL3A|Skill|recover|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|recover|1|250|negative|9004|9002:1,9004:1", + "S|PAL3A|Skill|recover|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|-25|negative|9001|9001:1,9003:1", + "S|PAL3A|Skill|attack|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|0|negative|9001|9001:1,9003:1", + "S|PAL3A|Skill|attack|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|25|negative|9001|9001:1,9003:1", + "S|PAL3A|Skill|attack|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|80|negative|9001|9001:1,9003:1", + "S|PAL3A|Skill|attack|0|80|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|0|250|negative|9001|9001:1,9003:1", + "S|PAL3A|Skill|attack|0|250|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|-25|negative|9001|9001:1,9003:1", + "S|PAL3A|Skill|attack|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|0|negative|9001|9001:1,9003:1", + "S|PAL3A|Skill|attack|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|25|negative|9001|9001:1,9003:1", + "S|PAL3A|Skill|attack|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|80|negative|9001|9001:1,9003:1", + "S|PAL3A|Skill|attack|1|80|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|attack|1|250|negative|9001|9001:1,9003:1", + "S|PAL3A|Skill|attack|1|250|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|80|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|250|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|80|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|250|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|revive|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|0|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Skill|cure|1|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|80|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|250|unmastered|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|revive|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|0|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|-25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|0|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|25|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|80|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|250|unmastered|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Magic|cure|1|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|-25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|-25|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|-25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|0|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|0|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|0|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|25|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|80|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|80|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|250|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|250|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|250|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|0|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|-25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|-25|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|-25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|0|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|0|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|0|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|25|reviveFirst|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|80|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|80|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|250|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|250|negative|9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|250|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|recover|1|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|-25|wrongRange|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|-25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|0|wrongRange|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|0|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|0|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|25|wrongRange|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|80|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|250|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|250|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|0|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|-25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|-25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|0|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|0|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|0|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|25|wrongRange|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|80|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|250|wrongRange|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|250|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|attack|1|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|-25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|0|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|250|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|0|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|-25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|-25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|-25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|0|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|0|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|25|negative|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|25|reviveFirst|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|25|full|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|80|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|80|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|80|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|80|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|80|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|80|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|80|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|80|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|250|base|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|250|denied|9003|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|250|wrongRange|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|250|negative|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|250|reviveFirst|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|250|percentage|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|250|full|9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|revive|1|250|zeroCount|9003|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|-25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|0|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|80|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|80|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|80|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|250|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|250|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|0|250|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|-25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|-25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|-25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|-25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|-25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|-25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|-25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|-25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|0|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|0|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|0|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|0|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|0|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|0|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|0|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|0|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|25|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|25|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|25|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|25|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|25|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|25|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|25|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|25|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|80|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|80|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|80|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|80|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|80|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|80|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|80|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|80|zeroCount|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|250|base|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|250|denied|9002|9001:0,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|250|wrongRange|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|250|negative|9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|250|reviveFirst|9002|9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|250|percentage|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|250|full|9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|Item|cure|1|250|zeroCount|9002|9002:1,9003:1,9004:1", + "F|PAL3A|0|0|0|0|base|265|", + "F|PAL3A|0|0|0|0|denied|265|", + "F|PAL3A|0|0|0|0|unmastered|264|", + "F|PAL3A|0|0|0|25|base|265|", + "F|PAL3A|0|0|0|25|denied|265|", + "F|PAL3A|0|0|0|25|unmastered|264|", + "F|PAL3A|0|0|0|80|base|265|", + "F|PAL3A|0|0|0|80|denied|265|", + "F|PAL3A|0|0|0|80|unmastered|264|", + "F|PAL3A|0|0|0|250|base|265|", + "F|PAL3A|0|0|0|250|denied|265|", + "F|PAL3A|0|0|0|250|unmastered|264|", + "F|PAL3A|0|0|1|0|base|265|", + "F|PAL3A|0|0|1|0|denied|265|", + "F|PAL3A|0|0|1|0|unmastered|264|", + "F|PAL3A|0|0|1|25|base|265|", + "F|PAL3A|0|0|1|25|denied|265|", + "F|PAL3A|0|0|1|25|unmastered|264|", + "F|PAL3A|0|0|1|80|base|265|", + "F|PAL3A|0|0|1|80|denied|265|", + "F|PAL3A|0|0|1|80|unmastered|264|", + "F|PAL3A|0|0|1|250|base|265|", + "F|PAL3A|0|0|1|250|denied|265|", + "F|PAL3A|0|0|1|250|unmastered|264|", + "F|PAL3A|0|0|2|0|base|265|", + "F|PAL3A|0|0|2|0|denied|265|", + "F|PAL3A|0|0|2|0|unmastered|264|", + "F|PAL3A|0|0|2|25|base|265|", + "F|PAL3A|0|0|2|25|denied|265|", + "F|PAL3A|0|0|2|25|unmastered|264|", + "F|PAL3A|0|0|2|80|base|265|", + "F|PAL3A|0|0|2|80|denied|265|", + "F|PAL3A|0|0|2|80|unmastered|264|", + "F|PAL3A|0|0|2|250|base|265|", + "F|PAL3A|0|0|2|250|denied|265|", + "F|PAL3A|0|0|2|250|unmastered|264|", + "F|PAL3A|0|0|3|0|base|265|", + "F|PAL3A|0|0|3|0|denied|265|", + "F|PAL3A|0|0|3|0|unmastered|264|", + "F|PAL3A|0|0|3|25|base|265|", + "F|PAL3A|0|0|3|25|denied|265|", + "F|PAL3A|0|0|3|25|unmastered|264|", + "F|PAL3A|0|0|3|80|base|265|", + "F|PAL3A|0|0|3|80|denied|265|", + "F|PAL3A|0|0|3|80|unmastered|264|", + "F|PAL3A|0|0|3|250|base|265|", + "F|PAL3A|0|0|3|250|denied|265|", + "F|PAL3A|0|0|3|250|unmastered|264|", + "F|PAL3A|0|0|4|0|base|265|", + "F|PAL3A|0|0|4|0|denied|265|", + "F|PAL3A|0|0|4|0|unmastered|264|", + "F|PAL3A|0|0|4|25|base|265|", + "F|PAL3A|0|0|4|25|denied|265|", + "F|PAL3A|0|0|4|25|unmastered|264|", + "F|PAL3A|0|0|4|80|base|265|", + "F|PAL3A|0|0|4|80|denied|265|", + "F|PAL3A|0|0|4|80|unmastered|264|", + "F|PAL3A|0|0|4|250|base|265|", + "F|PAL3A|0|0|4|250|denied|265|", + "F|PAL3A|0|0|4|250|unmastered|264|", + "F|PAL3A|0|0|5|0|base|265|", + "F|PAL3A|0|0|5|0|denied|265|", + "F|PAL3A|0|0|5|0|unmastered|264|", + "F|PAL3A|0|0|5|25|base|265|", + "F|PAL3A|0|0|5|25|denied|265|", + "F|PAL3A|0|0|5|25|unmastered|264|", + "F|PAL3A|0|0|5|80|base|265|", + "F|PAL3A|0|0|5|80|denied|265|", + "F|PAL3A|0|0|5|80|unmastered|264|", + "F|PAL3A|0|0|5|250|base|265|", + "F|PAL3A|0|0|5|250|denied|265|", + "F|PAL3A|0|0|5|250|unmastered|264|", + "F|PAL3A|0|1|0|0|base|0|", + "F|PAL3A|0|1|0|0|denied|0|", + "F|PAL3A|0|1|0|0|unmastered|0|", + "F|PAL3A|0|1|0|25|base|0|", + "F|PAL3A|0|1|0|25|denied|0|", + "F|PAL3A|0|1|0|25|unmastered|0|", + "F|PAL3A|0|1|0|80|base|0|", + "F|PAL3A|0|1|0|80|denied|0|", + "F|PAL3A|0|1|0|80|unmastered|0|", + "F|PAL3A|0|1|0|250|base|0|", + "F|PAL3A|0|1|0|250|denied|0|", + "F|PAL3A|0|1|0|250|unmastered|0|", + "F|PAL3A|0|1|1|0|base|9001|9001:1", + "F|PAL3A|0|1|1|0|denied|9001|9001:1", + "F|PAL3A|0|1|1|0|unmastered|9001|9001:1", + "F|PAL3A|0|1|1|25|base|9001|9001:1", + "F|PAL3A|0|1|1|25|denied|9001|9001:1", + "F|PAL3A|0|1|1|25|unmastered|9001|9001:1", + "F|PAL3A|0|1|1|80|base|9001|9001:1", + "F|PAL3A|0|1|1|80|denied|9001|9001:1", + "F|PAL3A|0|1|1|80|unmastered|9001|9001:1", + "F|PAL3A|0|1|1|250|base|9001|9001:1", + "F|PAL3A|0|1|1|250|denied|9001|9001:1", + "F|PAL3A|0|1|1|250|unmastered|9001|9001:1", + "F|PAL3A|0|1|2|0|base|265|265:1", + "F|PAL3A|0|1|2|0|denied|0|265:0", + "F|PAL3A|0|1|2|0|unmastered|0|", + "F|PAL3A|0|1|2|25|base|265|265:1", + "F|PAL3A|0|1|2|25|denied|0|265:0", + "F|PAL3A|0|1|2|25|unmastered|0|", + "F|PAL3A|0|1|2|80|base|265|265:1", + "F|PAL3A|0|1|2|80|denied|0|265:0", + "F|PAL3A|0|1|2|80|unmastered|0|", + "F|PAL3A|0|1|2|250|base|265|265:1", + "F|PAL3A|0|1|2|250|denied|0|265:0", + "F|PAL3A|0|1|2|250|unmastered|0|", + "F|PAL3A|0|1|3|0|base|264|264:1", + "F|PAL3A|0|1|3|0|denied|264|264:1", + "F|PAL3A|0|1|3|0|unmastered|264|264:1", + "F|PAL3A|0|1|3|25|base|264|264:1", + "F|PAL3A|0|1|3|25|denied|264|264:1", + "F|PAL3A|0|1|3|25|unmastered|264|264:1", + "F|PAL3A|0|1|3|80|base|264|264:1", + "F|PAL3A|0|1|3|80|denied|264|264:1", + "F|PAL3A|0|1|3|80|unmastered|264|264:1", + "F|PAL3A|0|1|3|250|base|264|264:1", + "F|PAL3A|0|1|3|250|denied|264|264:1", + "F|PAL3A|0|1|3|250|unmastered|264|264:1", + "F|PAL3A|0|1|4|0|base|9004|9004:1", + "F|PAL3A|0|1|4|0|denied|9004|9004:1", + "F|PAL3A|0|1|4|0|unmastered|9004|9004:1", + "F|PAL3A|0|1|4|25|base|9004|9004:1", + "F|PAL3A|0|1|4|25|denied|9004|9004:1", + "F|PAL3A|0|1|4|25|unmastered|9004|9004:1", + "F|PAL3A|0|1|4|80|base|9004|9004:1", + "F|PAL3A|0|1|4|80|denied|9004|9004:1", + "F|PAL3A|0|1|4|80|unmastered|9004|9004:1", + "F|PAL3A|0|1|4|250|base|9004|9004:1", + "F|PAL3A|0|1|4|250|denied|9004|9004:1", + "F|PAL3A|0|1|4|250|unmastered|9004|9004:1", + "F|PAL3A|0|1|5|0|base|0|", + "F|PAL3A|0|1|5|0|denied|0|", + "F|PAL3A|0|1|5|0|unmastered|0|", + "F|PAL3A|0|1|5|25|base|0|", + "F|PAL3A|0|1|5|25|denied|0|", + "F|PAL3A|0|1|5|25|unmastered|0|", + "F|PAL3A|0|1|5|80|base|0|", + "F|PAL3A|0|1|5|80|denied|0|", + "F|PAL3A|0|1|5|80|unmastered|0|", + "F|PAL3A|0|1|5|250|base|0|", + "F|PAL3A|0|1|5|250|denied|0|", + "F|PAL3A|0|1|5|250|unmastered|0|", + "F|PAL3A|5|0|0|0|base|265|", + "F|PAL3A|5|0|0|0|denied|265|", + "F|PAL3A|5|0|0|0|unmastered|265|", + "F|PAL3A|5|0|0|25|base|265|", + "F|PAL3A|5|0|0|25|denied|265|", + "F|PAL3A|5|0|0|25|unmastered|265|", + "F|PAL3A|5|0|0|80|base|265|", + "F|PAL3A|5|0|0|80|denied|265|", + "F|PAL3A|5|0|0|80|unmastered|265|", + "F|PAL3A|5|0|0|250|base|265|", + "F|PAL3A|5|0|0|250|denied|265|", + "F|PAL3A|5|0|0|250|unmastered|265|", + "F|PAL3A|5|0|1|0|base|265|", + "F|PAL3A|5|0|1|0|denied|265|", + "F|PAL3A|5|0|1|0|unmastered|265|", + "F|PAL3A|5|0|1|25|base|265|", + "F|PAL3A|5|0|1|25|denied|265|", + "F|PAL3A|5|0|1|25|unmastered|265|", + "F|PAL3A|5|0|1|80|base|265|", + "F|PAL3A|5|0|1|80|denied|265|", + "F|PAL3A|5|0|1|80|unmastered|265|", + "F|PAL3A|5|0|1|250|base|265|", + "F|PAL3A|5|0|1|250|denied|265|", + "F|PAL3A|5|0|1|250|unmastered|265|", + "F|PAL3A|5|0|2|0|base|265|", + "F|PAL3A|5|0|2|0|denied|265|", + "F|PAL3A|5|0|2|0|unmastered|265|", + "F|PAL3A|5|0|2|25|base|265|", + "F|PAL3A|5|0|2|25|denied|265|", + "F|PAL3A|5|0|2|25|unmastered|265|", + "F|PAL3A|5|0|2|80|base|265|", + "F|PAL3A|5|0|2|80|denied|265|", + "F|PAL3A|5|0|2|80|unmastered|265|", + "F|PAL3A|5|0|2|250|base|265|", + "F|PAL3A|5|0|2|250|denied|265|", + "F|PAL3A|5|0|2|250|unmastered|265|", + "F|PAL3A|5|0|3|0|base|265|", + "F|PAL3A|5|0|3|0|denied|265|", + "F|PAL3A|5|0|3|0|unmastered|265|", + "F|PAL3A|5|0|3|25|base|265|", + "F|PAL3A|5|0|3|25|denied|265|", + "F|PAL3A|5|0|3|25|unmastered|265|", + "F|PAL3A|5|0|3|80|base|265|", + "F|PAL3A|5|0|3|80|denied|265|", + "F|PAL3A|5|0|3|80|unmastered|265|", + "F|PAL3A|5|0|3|250|base|265|", + "F|PAL3A|5|0|3|250|denied|265|", + "F|PAL3A|5|0|3|250|unmastered|265|", + "F|PAL3A|5|0|4|0|base|265|", + "F|PAL3A|5|0|4|0|denied|265|", + "F|PAL3A|5|0|4|0|unmastered|265|", + "F|PAL3A|5|0|4|25|base|265|", + "F|PAL3A|5|0|4|25|denied|265|", + "F|PAL3A|5|0|4|25|unmastered|265|", + "F|PAL3A|5|0|4|80|base|265|", + "F|PAL3A|5|0|4|80|denied|265|", + "F|PAL3A|5|0|4|80|unmastered|265|", + "F|PAL3A|5|0|4|250|base|265|", + "F|PAL3A|5|0|4|250|denied|265|", + "F|PAL3A|5|0|4|250|unmastered|265|", + "F|PAL3A|5|0|5|0|base|265|", + "F|PAL3A|5|0|5|0|denied|265|", + "F|PAL3A|5|0|5|0|unmastered|265|", + "F|PAL3A|5|0|5|25|base|265|", + "F|PAL3A|5|0|5|25|denied|265|", + "F|PAL3A|5|0|5|25|unmastered|265|", + "F|PAL3A|5|0|5|80|base|265|", + "F|PAL3A|5|0|5|80|denied|265|", + "F|PAL3A|5|0|5|80|unmastered|265|", + "F|PAL3A|5|0|5|250|base|265|", + "F|PAL3A|5|0|5|250|denied|265|", + "F|PAL3A|5|0|5|250|unmastered|265|", + "F|PAL3A|5|1|0|0|base|0|", + "F|PAL3A|5|1|0|0|denied|0|", + "F|PAL3A|5|1|0|0|unmastered|0|", + "F|PAL3A|5|1|0|25|base|0|", + "F|PAL3A|5|1|0|25|denied|0|", + "F|PAL3A|5|1|0|25|unmastered|0|", + "F|PAL3A|5|1|0|80|base|0|", + "F|PAL3A|5|1|0|80|denied|0|", + "F|PAL3A|5|1|0|80|unmastered|0|", + "F|PAL3A|5|1|0|250|base|0|", + "F|PAL3A|5|1|0|250|denied|0|", + "F|PAL3A|5|1|0|250|unmastered|0|", + "F|PAL3A|5|1|1|0|base|9001|9001:1", + "F|PAL3A|5|1|1|0|denied|9001|9001:1", + "F|PAL3A|5|1|1|0|unmastered|9001|9001:1", + "F|PAL3A|5|1|1|25|base|9001|9001:1", + "F|PAL3A|5|1|1|25|denied|9001|9001:1", + "F|PAL3A|5|1|1|25|unmastered|9001|9001:1", + "F|PAL3A|5|1|1|80|base|9001|9001:1", + "F|PAL3A|5|1|1|80|denied|9001|9001:1", + "F|PAL3A|5|1|1|80|unmastered|9001|9001:1", + "F|PAL3A|5|1|1|250|base|9001|9001:1", + "F|PAL3A|5|1|1|250|denied|9001|9001:1", + "F|PAL3A|5|1|1|250|unmastered|9001|9001:1", + "F|PAL3A|5|1|2|0|base|265|265:1", + "F|PAL3A|5|1|2|0|denied|0|265:0", + "F|PAL3A|5|1|2|0|unmastered|265|265:1", + "F|PAL3A|5|1|2|25|base|265|265:1", + "F|PAL3A|5|1|2|25|denied|0|265:0", + "F|PAL3A|5|1|2|25|unmastered|265|265:1", + "F|PAL3A|5|1|2|80|base|265|265:1", + "F|PAL3A|5|1|2|80|denied|0|265:0", + "F|PAL3A|5|1|2|80|unmastered|265|265:1", + "F|PAL3A|5|1|2|250|base|265|265:1", + "F|PAL3A|5|1|2|250|denied|0|265:0", + "F|PAL3A|5|1|2|250|unmastered|265|265:1", + "F|PAL3A|5|1|3|0|base|264|264:1", + "F|PAL3A|5|1|3|0|denied|264|264:1", + "F|PAL3A|5|1|3|0|unmastered|264|264:1", + "F|PAL3A|5|1|3|25|base|264|264:1", + "F|PAL3A|5|1|3|25|denied|264|264:1", + "F|PAL3A|5|1|3|25|unmastered|264|264:1", + "F|PAL3A|5|1|3|80|base|264|264:1", + "F|PAL3A|5|1|3|80|denied|264|264:1", + "F|PAL3A|5|1|3|80|unmastered|264|264:1", + "F|PAL3A|5|1|3|250|base|264|264:1", + "F|PAL3A|5|1|3|250|denied|264|264:1", + "F|PAL3A|5|1|3|250|unmastered|264|264:1", + "F|PAL3A|5|1|4|0|base|9004|9004:1", + "F|PAL3A|5|1|4|0|denied|9004|9004:1", + "F|PAL3A|5|1|4|0|unmastered|9004|9004:1", + "F|PAL3A|5|1|4|25|base|9004|9004:1", + "F|PAL3A|5|1|4|25|denied|9004|9004:1", + "F|PAL3A|5|1|4|25|unmastered|9004|9004:1", + "F|PAL3A|5|1|4|80|base|9004|9004:1", + "F|PAL3A|5|1|4|80|denied|9004|9004:1", + "F|PAL3A|5|1|4|80|unmastered|9004|9004:1", + "F|PAL3A|5|1|4|250|base|9004|9004:1", + "F|PAL3A|5|1|4|250|denied|9004|9004:1", + "F|PAL3A|5|1|4|250|unmastered|9004|9004:1", + "F|PAL3A|5|1|5|0|base|0|", + "F|PAL3A|5|1|5|0|denied|0|", + "F|PAL3A|5|1|5|0|unmastered|0|", + "F|PAL3A|5|1|5|25|base|0|", + "F|PAL3A|5|1|5|25|denied|0|", + "F|PAL3A|5|1|5|25|unmastered|0|", + "F|PAL3A|5|1|5|80|base|0|", + "F|PAL3A|5|1|5|80|denied|0|", + "F|PAL3A|5|1|5|80|unmastered|0|", + "F|PAL3A|5|1|5|250|base|0|", + "F|PAL3A|5|1|5|250|denied|0|", + "F|PAL3A|5|1|5|250|unmastered|0|", + "W|PAL3A|0|0|0|0|0", + "W|PAL3A|0|0|0|1|0", + "W|PAL3A|0|0|0|2|0", + "W|PAL3A|0|0|0|4|0", + "W|PAL3A|0|0|0|8|0", + "W|PAL3A|0|0|0|16|0", + "W|PAL3A|0|0|0|3|0", + "W|PAL3A|0|0|0|31|0", + "W|PAL3A|0|0|1|0|0", + "W|PAL3A|0|0|1|1|0", + "W|PAL3A|0|0|1|2|0", + "W|PAL3A|0|0|1|4|0", + "W|PAL3A|0|0|1|8|0", + "W|PAL3A|0|0|1|16|0", + "W|PAL3A|0|0|1|3|0", + "W|PAL3A|0|0|1|31|0", + "W|PAL3A|0|0|2|0|0", + "W|PAL3A|0|0|2|1|0", + "W|PAL3A|0|0|2|2|0", + "W|PAL3A|0|0|2|4|0", + "W|PAL3A|0|0|2|8|0", + "W|PAL3A|0|0|2|16|0", + "W|PAL3A|0|0|2|3|0", + "W|PAL3A|0|0|2|31|0", + "W|PAL3A|0|1|0|0|0", + "W|PAL3A|0|1|0|1|1", + "W|PAL3A|0|1|0|2|0", + "W|PAL3A|0|1|0|4|0", + "W|PAL3A|0|1|0|8|0", + "W|PAL3A|0|1|0|16|0", + "W|PAL3A|0|1|0|3|0", + "W|PAL3A|0|1|0|31|0", + "W|PAL3A|0|1|1|0|0", + "W|PAL3A|0|1|1|1|0", + "W|PAL3A|0|1|1|2|0", + "W|PAL3A|0|1|1|4|0", + "W|PAL3A|0|1|1|8|0", + "W|PAL3A|0|1|1|16|0", + "W|PAL3A|0|1|1|3|0", + "W|PAL3A|0|1|1|31|0", + "W|PAL3A|0|1|2|0|0", + "W|PAL3A|0|1|2|1|1", + "W|PAL3A|0|1|2|2|0", + "W|PAL3A|0|1|2|4|0", + "W|PAL3A|0|1|2|8|0", + "W|PAL3A|0|1|2|16|0", + "W|PAL3A|0|1|2|3|0", + "W|PAL3A|0|1|2|31|0", + "W|PAL3A|0|2|0|0|0", + "W|PAL3A|0|2|0|1|0", + "W|PAL3A|0|2|0|2|1", + "W|PAL3A|0|2|0|4|0", + "W|PAL3A|0|2|0|8|0", + "W|PAL3A|0|2|0|16|0", + "W|PAL3A|0|2|0|3|0", + "W|PAL3A|0|2|0|31|0", + "W|PAL3A|0|2|1|0|0", + "W|PAL3A|0|2|1|1|0", + "W|PAL3A|0|2|1|2|0", + "W|PAL3A|0|2|1|4|0", + "W|PAL3A|0|2|1|8|0", + "W|PAL3A|0|2|1|16|0", + "W|PAL3A|0|2|1|3|0", + "W|PAL3A|0|2|1|31|0", + "W|PAL3A|0|2|2|0|0", + "W|PAL3A|0|2|2|1|0", + "W|PAL3A|0|2|2|2|1", + "W|PAL3A|0|2|2|4|0", + "W|PAL3A|0|2|2|8|0", + "W|PAL3A|0|2|2|16|0", + "W|PAL3A|0|2|2|3|0", + "W|PAL3A|0|2|2|31|0", + "W|PAL3A|0|3|0|0|0", + "W|PAL3A|0|3|0|1|0", + "W|PAL3A|0|3|0|2|0", + "W|PAL3A|0|3|0|4|1", + "W|PAL3A|0|3|0|8|0", + "W|PAL3A|0|3|0|16|0", + "W|PAL3A|0|3|0|3|0", + "W|PAL3A|0|3|0|31|0", + "W|PAL3A|0|3|1|0|0", + "W|PAL3A|0|3|1|1|0", + "W|PAL3A|0|3|1|2|0", + "W|PAL3A|0|3|1|4|0", + "W|PAL3A|0|3|1|8|0", + "W|PAL3A|0|3|1|16|0", + "W|PAL3A|0|3|1|3|0", + "W|PAL3A|0|3|1|31|0", + "W|PAL3A|0|3|2|0|0", + "W|PAL3A|0|3|2|1|0", + "W|PAL3A|0|3|2|2|0", + "W|PAL3A|0|3|2|4|1", + "W|PAL3A|0|3|2|8|0", + "W|PAL3A|0|3|2|16|0", + "W|PAL3A|0|3|2|3|0", + "W|PAL3A|0|3|2|31|0", + "W|PAL3A|0|4|0|0|0", + "W|PAL3A|0|4|0|1|0", + "W|PAL3A|0|4|0|2|0", + "W|PAL3A|0|4|0|4|0", + "W|PAL3A|0|4|0|8|1", + "W|PAL3A|0|4|0|16|0", + "W|PAL3A|0|4|0|3|0", + "W|PAL3A|0|4|0|31|0", + "W|PAL3A|0|4|1|0|0", + "W|PAL3A|0|4|1|1|0", + "W|PAL3A|0|4|1|2|0", + "W|PAL3A|0|4|1|4|0", + "W|PAL3A|0|4|1|8|0", + "W|PAL3A|0|4|1|16|0", + "W|PAL3A|0|4|1|3|0", + "W|PAL3A|0|4|1|31|0", + "W|PAL3A|0|4|2|0|0", + "W|PAL3A|0|4|2|1|0", + "W|PAL3A|0|4|2|2|0", + "W|PAL3A|0|4|2|4|0", + "W|PAL3A|0|4|2|8|1", + "W|PAL3A|0|4|2|16|0", + "W|PAL3A|0|4|2|3|0", + "W|PAL3A|0|4|2|31|0", + "W|PAL3A|0|5|0|0|0", + "W|PAL3A|0|5|0|1|0", + "W|PAL3A|0|5|0|2|0", + "W|PAL3A|0|5|0|4|0", + "W|PAL3A|0|5|0|8|0", + "W|PAL3A|0|5|0|16|1", + "W|PAL3A|0|5|0|3|0", + "W|PAL3A|0|5|0|31|0", + "W|PAL3A|0|5|1|0|0", + "W|PAL3A|0|5|1|1|0", + "W|PAL3A|0|5|1|2|0", + "W|PAL3A|0|5|1|4|0", + "W|PAL3A|0|5|1|8|0", + "W|PAL3A|0|5|1|16|0", + "W|PAL3A|0|5|1|3|0", + "W|PAL3A|0|5|1|31|0", + "W|PAL3A|0|5|2|0|0", + "W|PAL3A|0|5|2|1|0", + "W|PAL3A|0|5|2|2|0", + "W|PAL3A|0|5|2|4|0", + "W|PAL3A|0|5|2|8|0", + "W|PAL3A|0|5|2|16|1", + "W|PAL3A|0|5|2|3|0", + "W|PAL3A|0|5|2|31|0", + "W|PAL3A|5|0|0|0|0", + "W|PAL3A|5|0|0|1|0", + "W|PAL3A|5|0|0|2|0", + "W|PAL3A|5|0|0|4|0", + "W|PAL3A|5|0|0|8|0", + "W|PAL3A|5|0|0|16|0", + "W|PAL3A|5|0|0|3|0", + "W|PAL3A|5|0|0|31|0", + "W|PAL3A|5|0|1|0|0", + "W|PAL3A|5|0|1|1|0", + "W|PAL3A|5|0|1|2|0", + "W|PAL3A|5|0|1|4|0", + "W|PAL3A|5|0|1|8|0", + "W|PAL3A|5|0|1|16|0", + "W|PAL3A|5|0|1|3|0", + "W|PAL3A|5|0|1|31|0", + "W|PAL3A|5|0|2|0|0", + "W|PAL3A|5|0|2|1|0", + "W|PAL3A|5|0|2|2|0", + "W|PAL3A|5|0|2|4|0", + "W|PAL3A|5|0|2|8|0", + "W|PAL3A|5|0|2|16|0", + "W|PAL3A|5|0|2|3|0", + "W|PAL3A|5|0|2|31|0", + "W|PAL3A|5|1|0|0|0", + "W|PAL3A|5|1|0|1|1", + "W|PAL3A|5|1|0|2|0", + "W|PAL3A|5|1|0|4|0", + "W|PAL3A|5|1|0|8|0", + "W|PAL3A|5|1|0|16|0", + "W|PAL3A|5|1|0|3|0", + "W|PAL3A|5|1|0|31|0", + "W|PAL3A|5|1|1|0|0", + "W|PAL3A|5|1|1|1|1", + "W|PAL3A|5|1|1|2|0", + "W|PAL3A|5|1|1|4|0", + "W|PAL3A|5|1|1|8|0", + "W|PAL3A|5|1|1|16|0", + "W|PAL3A|5|1|1|3|0", + "W|PAL3A|5|1|1|31|0", + "W|PAL3A|5|1|2|0|0", + "W|PAL3A|5|1|2|1|0", + "W|PAL3A|5|1|2|2|0", + "W|PAL3A|5|1|2|4|0", + "W|PAL3A|5|1|2|8|0", + "W|PAL3A|5|1|2|16|0", + "W|PAL3A|5|1|2|3|0", + "W|PAL3A|5|1|2|31|0", + "W|PAL3A|5|2|0|0|0", + "W|PAL3A|5|2|0|1|0", + "W|PAL3A|5|2|0|2|1", + "W|PAL3A|5|2|0|4|0", + "W|PAL3A|5|2|0|8|0", + "W|PAL3A|5|2|0|16|0", + "W|PAL3A|5|2|0|3|0", + "W|PAL3A|5|2|0|31|0", + "W|PAL3A|5|2|1|0|0", + "W|PAL3A|5|2|1|1|0", + "W|PAL3A|5|2|1|2|1", + "W|PAL3A|5|2|1|4|0", + "W|PAL3A|5|2|1|8|0", + "W|PAL3A|5|2|1|16|0", + "W|PAL3A|5|2|1|3|0", + "W|PAL3A|5|2|1|31|0", + "W|PAL3A|5|2|2|0|0", + "W|PAL3A|5|2|2|1|0", + "W|PAL3A|5|2|2|2|0", + "W|PAL3A|5|2|2|4|0", + "W|PAL3A|5|2|2|8|0", + "W|PAL3A|5|2|2|16|0", + "W|PAL3A|5|2|2|3|0", + "W|PAL3A|5|2|2|31|0", + "W|PAL3A|5|3|0|0|0", + "W|PAL3A|5|3|0|1|0", + "W|PAL3A|5|3|0|2|0", + "W|PAL3A|5|3|0|4|1", + "W|PAL3A|5|3|0|8|0", + "W|PAL3A|5|3|0|16|0", + "W|PAL3A|5|3|0|3|0", + "W|PAL3A|5|3|0|31|0", + "W|PAL3A|5|3|1|0|0", + "W|PAL3A|5|3|1|1|0", + "W|PAL3A|5|3|1|2|0", + "W|PAL3A|5|3|1|4|1", + "W|PAL3A|5|3|1|8|0", + "W|PAL3A|5|3|1|16|0", + "W|PAL3A|5|3|1|3|0", + "W|PAL3A|5|3|1|31|0", + "W|PAL3A|5|3|2|0|0", + "W|PAL3A|5|3|2|1|0", + "W|PAL3A|5|3|2|2|0", + "W|PAL3A|5|3|2|4|0", + "W|PAL3A|5|3|2|8|0", + "W|PAL3A|5|3|2|16|0", + "W|PAL3A|5|3|2|3|0", + "W|PAL3A|5|3|2|31|0", + "W|PAL3A|5|4|0|0|0", + "W|PAL3A|5|4|0|1|0", + "W|PAL3A|5|4|0|2|0", + "W|PAL3A|5|4|0|4|0", + "W|PAL3A|5|4|0|8|1", + "W|PAL3A|5|4|0|16|0", + "W|PAL3A|5|4|0|3|0", + "W|PAL3A|5|4|0|31|0", + "W|PAL3A|5|4|1|0|0", + "W|PAL3A|5|4|1|1|0", + "W|PAL3A|5|4|1|2|0", + "W|PAL3A|5|4|1|4|0", + "W|PAL3A|5|4|1|8|1", + "W|PAL3A|5|4|1|16|0", + "W|PAL3A|5|4|1|3|0", + "W|PAL3A|5|4|1|31|0", + "W|PAL3A|5|4|2|0|0", + "W|PAL3A|5|4|2|1|0", + "W|PAL3A|5|4|2|2|0", + "W|PAL3A|5|4|2|4|0", + "W|PAL3A|5|4|2|8|0", + "W|PAL3A|5|4|2|16|0", + "W|PAL3A|5|4|2|3|0", + "W|PAL3A|5|4|2|31|0", + "W|PAL3A|5|5|0|0|0", + "W|PAL3A|5|5|0|1|0", + "W|PAL3A|5|5|0|2|0", + "W|PAL3A|5|5|0|4|0", + "W|PAL3A|5|5|0|8|0", + "W|PAL3A|5|5|0|16|1", + "W|PAL3A|5|5|0|3|0", + "W|PAL3A|5|5|0|31|0", + "W|PAL3A|5|5|1|0|0", + "W|PAL3A|5|5|1|1|0", + "W|PAL3A|5|5|1|2|0", + "W|PAL3A|5|5|1|4|0", + "W|PAL3A|5|5|1|8|0", + "W|PAL3A|5|5|1|16|1", + "W|PAL3A|5|5|1|3|0", + "W|PAL3A|5|5|1|31|0", + "W|PAL3A|5|5|2|0|0", + "W|PAL3A|5|5|2|1|0", + "W|PAL3A|5|5|2|2|0", + "W|PAL3A|5|5|2|4|0", + "W|PAL3A|5|5|2|8|0", + "W|PAL3A|5|5|2|16|0", + "W|PAL3A|5|5|2|3|0", + "W|PAL3A|5|5|2|31|0", + "C|PAL3A|7711|0|7711|0", + "C|PAL3A|7711|1|7711|1", + "C|PAL3A|7711|2|7711|2", + "C|PAL3A|7711|107|7711|107", + "C|PAL3A|7711|12345|7711|12345", + "C|PAL3A|7714|0|224|2531011", + "C|PAL3A|7714|1|215|2745024", + "C|PAL3A|7714|2|207|2959037", + "C|PAL3A|7714|107|224|25430402", + "C|PAL3A|7714|12345|240|2644521496", + "C|PAL3A|9001|0|9001|0", + "C|PAL3A|9001|1|9001|1", + "C|PAL3A|9001|2|9001|2", + "C|PAL3A|9001|107|9001|107", + "C|PAL3A|9001|12345|9001|12345", + "U|PAL3A|Skill|0,2,1,2||9002|9002:1,9004:1", + "U|PAL3A|Skill|0,2,1,2|9002|9004|9002:0,9004:1", + "U|PAL3A|Skill|2,0,0,0||9001|9001:1", + "U|PAL3A|Skill|2,0,0,0|9002|9001|9001:1", + "U|PAL3A|Skill|0,0,0,0||0|", + "U|PAL3A|Skill|0,0,0,0|9002|0|", + "U|PAL3A|Magic|0,2,1,2||9002|9002:1,9004:1", + "U|PAL3A|Magic|0,2,1,2|9002|9004|9002:0,9004:1", + "U|PAL3A|Magic|2,0,0,0||9001|9001:1", + "U|PAL3A|Magic|2,0,0,0|9002|9001|9001:1", + "U|PAL3A|Magic|0,0,0,0||0|", + "U|PAL3A|Magic|0,0,0,0|9002|0|", + "U|PAL3A|Item|0,2,1,2||9002|9002:1,9004:1", + "U|PAL3A|Item|0,2,1,2|9002|9004|9002:0,9004:1", + "U|PAL3A|Item|2,0,0,0||9001|9001:1", + "U|PAL3A|Item|2,0,0,0|9002|9001|9001:1", + "U|PAL3A|Item|0,0,0,0||0|", + "U|PAL3A|Item|0,0,0,0|9002|0|", + "N|PAL3|0|5|base|1|1|1", + "N|PAL3|0|5|base|107|1|107", + "N|PAL3|0|5|invisible|1|0|1", + "N|PAL3|0|5|invisible|107|0|107", + "N|PAL3|0|5|wall|1|1|1", + "N|PAL3|0|5|wall|107|1|107", + "N|PAL3|0|5|mirror|1|1|1", + "N|PAL3|0|5|mirror|107|1|107", + "N|PAL3|0|5|both|1|0|1", + "N|PAL3|0|5|both|107|0|107", + "N|PAL3|0|5|targetDead|1|0|1", + "N|PAL3|0|5|targetDead|107|0|107", + "N|PAL3|0|5|sourceDead|1|0|1", + "N|PAL3|0|5|sourceDead|107|0|107", + "N|PAL3|0|0|self|1|0|1", + "N|PAL3|0|0|self|107|0|107", + "N|PAL3|0|5|noAttack|1|0|1", + "N|PAL3|0|5|noAttack|107|0|107", + "N|PAL3|0|5|chaosNoAttack|1|1|1", + "N|PAL3|0|5|chaosNoAttack|107|1|107", + "N|PAL3|0|5|madNoAttack|1|1|1", + "N|PAL3|0|5|madNoAttack|107|1|107", + "N|PAL3|0|5|away|1|0|1", + "N|PAL3|0|5|away|107|0|107", + "N|PAL3|0|5|backBlocked|1|0|1", + "N|PAL3|0|5|backBlocked|107|0|107", + "N|PAL3|0|5|targetFled|1|1|1", + "N|PAL3|0|5|targetFled|107|1|107", + "N|PAL3|0|5|sourceFled|1|1|1", + "N|PAL3|0|5|sourceFled|107|1|107", + "N|PAL3|5|0|base|1|1|1", + "N|PAL3|5|0|base|107|1|107", + "N|PAL3|5|0|invisible|1|0|1", + "N|PAL3|5|0|invisible|107|0|107", + "N|PAL3|5|0|wall|1|1|1", + "N|PAL3|5|0|wall|107|1|107", + "N|PAL3|5|0|mirror|1|1|1", + "N|PAL3|5|0|mirror|107|1|107", + "N|PAL3|5|0|both|1|0|2745024", + "N|PAL3|5|0|both|107|0|25430402", + "N|PAL3|5|0|targetDead|1|0|1", + "N|PAL3|5|0|targetDead|107|0|107", + "N|PAL3|5|0|sourceDead|1|0|1", + "N|PAL3|5|0|sourceDead|107|0|107", + "N|PAL3|5|5|self|1|0|1", + "N|PAL3|5|5|self|107|0|107", + "N|PAL3|5|0|noAttack|1|0|1", + "N|PAL3|5|0|noAttack|107|0|107", + "N|PAL3|5|0|chaosNoAttack|1|1|1", + "N|PAL3|5|0|chaosNoAttack|107|1|107", + "N|PAL3|5|0|madNoAttack|1|1|1", + "N|PAL3|5|0|madNoAttack|107|1|107", + "N|PAL3|5|0|away|1|0|1", + "N|PAL3|5|0|away|107|0|107", + "N|PAL3|5|0|backBlocked|1|0|1", + "N|PAL3|5|0|backBlocked|107|0|107", + "N|PAL3|5|0|targetFled|1|1|1", + "N|PAL3|5|0|targetFled|107|1|107", + "N|PAL3|5|0|sourceFled|1|1|1", + "N|PAL3|5|0|sourceFled|107|1|107", + "N|PAL3A|0|5|base|1|1|1", + "N|PAL3A|0|5|base|107|1|107", + "N|PAL3A|0|5|invisible|1|1|1", + "N|PAL3A|0|5|invisible|107|1|107", + "N|PAL3A|0|5|wall|1|1|1", + "N|PAL3A|0|5|wall|107|1|107", + "N|PAL3A|0|5|mirror|1|1|1", + "N|PAL3A|0|5|mirror|107|1|107", + "N|PAL3A|0|5|both|1|0|1", + "N|PAL3A|0|5|both|107|0|107", + "N|PAL3A|0|5|targetDead|1|0|1", + "N|PAL3A|0|5|targetDead|107|0|107", + "N|PAL3A|0|5|sourceDead|1|0|1", + "N|PAL3A|0|5|sourceDead|107|0|107", + "N|PAL3A|0|0|self|1|0|1", + "N|PAL3A|0|0|self|107|0|107", + "N|PAL3A|0|5|noAttack|1|0|1", + "N|PAL3A|0|5|noAttack|107|0|107", + "N|PAL3A|0|5|chaosNoAttack|1|1|1", + "N|PAL3A|0|5|chaosNoAttack|107|1|107", + "N|PAL3A|0|5|madNoAttack|1|1|1", + "N|PAL3A|0|5|madNoAttack|107|1|107", + "N|PAL3A|0|5|away|1|0|1", + "N|PAL3A|0|5|away|107|0|107", + "N|PAL3A|0|5|backBlocked|1|0|1", + "N|PAL3A|0|5|backBlocked|107|0|107", + "N|PAL3A|0|5|targetFled|1|1|1", + "N|PAL3A|0|5|targetFled|107|1|107", + "N|PAL3A|0|5|sourceFled|1|1|1", + "N|PAL3A|0|5|sourceFled|107|1|107", + "N|PAL3A|5|0|base|1|1|1", + "N|PAL3A|5|0|base|107|1|107", + "N|PAL3A|5|0|invisible|1|1|1", + "N|PAL3A|5|0|invisible|107|1|107", + "N|PAL3A|5|0|wall|1|1|1", + "N|PAL3A|5|0|wall|107|1|107", + "N|PAL3A|5|0|mirror|1|1|1", + "N|PAL3A|5|0|mirror|107|1|107", + "N|PAL3A|5|0|both|1|0|2745024", + "N|PAL3A|5|0|both|107|0|25430402", + "N|PAL3A|5|0|targetDead|1|0|1", + "N|PAL3A|5|0|targetDead|107|0|107", + "N|PAL3A|5|0|sourceDead|1|0|1", + "N|PAL3A|5|0|sourceDead|107|0|107", + "N|PAL3A|5|5|self|1|0|1", + "N|PAL3A|5|5|self|107|0|107", + "N|PAL3A|5|0|noAttack|1|0|1", + "N|PAL3A|5|0|noAttack|107|0|107", + "N|PAL3A|5|0|chaosNoAttack|1|1|1", + "N|PAL3A|5|0|chaosNoAttack|107|1|107", + "N|PAL3A|5|0|madNoAttack|1|1|1", + "N|PAL3A|5|0|madNoAttack|107|1|107", + "N|PAL3A|5|0|away|1|0|1", + "N|PAL3A|5|0|away|107|0|107", + "N|PAL3A|5|0|backBlocked|1|0|1", + "N|PAL3A|5|0|backBlocked|107|0|107", + "N|PAL3A|5|0|targetFled|1|1|1", + "N|PAL3A|5|0|targetFled|107|1|107", + "N|PAL3A|5|0|sourceFled|1|1|1", + "N|PAL3A|5|0|sourceFled|107|1|107", + "L|PAL3|1|0|base|1|", + "L|PAL3|1|0|invalid|0|", + "L|PAL3|1|0|deadFlag|0|", + "L|PAL3|1|0|zeroHp|1|", + "L|PAL3|1|0|fled|0|", + "L|PAL3|1|0|fleeing|0|", + "L|PAL3|1|0|backBlocked|1|", + "L|PAL3|2|0|base|6|", + "L|PAL3|2|0|invalid|10|", + "L|PAL3|2|0|deadFlag|10|", + "L|PAL3|2|0|zeroHp|6|", + "L|PAL3|2|0|fled|10|", + "L|PAL3|2|0|fleeing|10|", + "L|PAL3|2|0|backBlocked|6|", + "J|PAL3|6|base|6|0", + "J|PAL3|6|invalid|6|0", + "J|PAL3|6|deadFlag|6|0", + "J|PAL3|6|zeroHp|6|1", + "J|PAL3|6|fled|6|1", + "J|PAL3|6|fleeing|6|0", + "J|PAL3|6|backBlocked|6|0", + "J|PAL3|6|emptyMask||0", + "J|PAL3|-1|base|6|0", + "J|PAL3|-1|invalid|6|1", + "J|PAL3|-1|deadFlag|6|0", + "J|PAL3|-1|zeroHp|6|1", + "J|PAL3|-1|fled|6|1", + "J|PAL3|-1|fleeing|6|0", + "J|PAL3|-1|backBlocked|6|0", + "J|PAL3|-1|emptyMask||1", + "L|PAL3A|1|0|base|1|", + "L|PAL3A|1|0|invalid|0|", + "L|PAL3A|1|0|deadFlag|0|", + "L|PAL3A|1|0|zeroHp|1|", + "L|PAL3A|1|0|fled|0|", + "L|PAL3A|1|0|fleeing|0|", + "L|PAL3A|1|0|backBlocked|1|", + "L|PAL3A|1|1|base|1|", + "L|PAL3A|1|1|invalid|0|", + "L|PAL3A|1|1|deadFlag|0|", + "L|PAL3A|1|1|zeroHp|1|", + "L|PAL3A|1|1|fled|0|", + "L|PAL3A|1|1|fleeing|0|", + "L|PAL3A|1|1|backBlocked|1|", + "L|PAL3A|2|0|base|6|", + "L|PAL3A|2|0|invalid|10|", + "L|PAL3A|2|0|deadFlag|10|", + "L|PAL3A|2|0|zeroHp|6|", + "L|PAL3A|2|0|fled|10|", + "L|PAL3A|2|0|fleeing|10|", + "L|PAL3A|2|0|backBlocked|6|", + "L|PAL3A|2|1|base|6|6", + "L|PAL3A|2|1|invalid|10|", + "L|PAL3A|2|1|deadFlag|10|", + "L|PAL3A|2|1|zeroHp|6|6", + "L|PAL3A|2|1|fled|10|", + "L|PAL3A|2|1|fleeing|10|", + "L|PAL3A|2|1|backBlocked|10|6", + "J|PAL3A|6|base|6|0", + "J|PAL3A|6|invalid|6|0", + "J|PAL3A|6|deadFlag|6|0", + "J|PAL3A|6|zeroHp|6|1", + "J|PAL3A|6|fled|6|1", + "J|PAL3A|6|fleeing|6|1", + "J|PAL3A|6|backBlocked|6|0", + "J|PAL3A|6|emptyMask||0", + "J|PAL3A|-1|base|6|0", + "J|PAL3A|-1|invalid|6|1", + "J|PAL3A|-1|deadFlag|6|0", + "J|PAL3A|-1|zeroHp|6|1", + "J|PAL3A|-1|fled|6|1", + "J|PAL3A|-1|fleeing|6|1", + "J|PAL3A|-1|backBlocked|6|0", + "J|PAL3A|-1|emptyMask||1", + }; + + public static IEnumerable NativeCases() + { + for (int index = 0; index < NativeVectors.Length; index++) + yield return new TestCaseData(NativeVectors[index]).SetName("OriginalAiSupportNative_" + index.ToString(CultureInfo.InvariantCulture)); + } + + private static int Number(string text) => int.Parse(text, CultureInfo.InvariantCulture); + + [TestCaseSource(nameof(NativeCases))] + public void MatchesReleasedSupportSelector(string encoded) + { + string[] data = encoded.Split('|'); + if (data[0] is "L" or "J") + { + string leafCase = data[data[0] == "L" ? 4 : 3]; + var leafPort = new Port { Back = leafCase != "backBlocked" }; + var leafAi = new BattleAi(data[1] == "PAL3A", new BattleRandom(1, data[1]), leafPort); + int[] indices = { 0, 1, 5, 6, 10 }; + int[] hpValues = { 100, 60, 30, 5, 5 }; + for (int index = 0; index < indices.Length; index++) + { + int role = indices[index]; + bool changed = role is 1 or 6; + leafAi.Roles[role] = new BattleAiRole + { + Valid = !changed || leafCase != "invalid", + Alive = !changed || leafCase != "deadFlag", + Hp = changed && leafCase == "zeroHp" ? 0 : hpValues[index], + Fled = changed && leafCase == "fled", + Fleeing = changed && leafCase == "fleeing" + }; + } + if (data[0] == "L") + { + Assert.That(unchecked((uint)leafAi.SelectRepeatTarget(0, data[2] == "2", data[3] == "1")).ToString(CultureInfo.InvariantCulture), Is.EqualTo(data[5])); + Assert.That(string.Join(",", leafPort.BackQueries), Is.EqualTo(data[6])); + } + else + { + var leafCommand = new BattleAiCommand { Target = Number(data[2]) }; + if (data[4].Length > 0) + leafCommand.TargetMask[6] = true; + Assert.That(leafAi.RepeatTargetsDead(leafCommand), Is.EqualTo(data[5] == "1")); + } + return; + } + if (data[0] == "U") + { + int[] nullOperations = data[3].Split(',').Select(Number).ToArray(); + var nullPort = new Port { DenyFirst = data[4].Length > 0, Denied = data[4].Length > 0 ? Number(data[4]) : 0 }; + var nullAi = new BattleAi(data[1] == "PAL3A", new BattleRandom(1, data[1]), nullPort); + nullAi.Roles[0].Alive = true; + nullAi.Roles[0].Hp = 40; + nullAi.Roles[0].MaxHp = 200; + BattleAiSkill[] nullRecords = Enumerable.Range(0, 4).Select(index => new BattleAiSkill + { + Id = 9001 + index, + IsItem = data[2] == "Item", + IsMagic = data[2] == "Magic", + Type = data[2] == "Skill" ? 0 : data[2] == "Magic" ? 3 : 1, + Range = 1, + Power = new[] { 10, 40, 100, 400 }[index], + NullCureOperation = nullOperations[index] + }).ToArray(); + nullAi.Roles[0].Skills = nullRecords; + nullAi.Items = nullRecords; + var nullKind = (BattleAiAttemptKind)Enum.Parse(typeof(BattleAiAttemptKind), "Cure" + data[2]); + Assert.That(nullAi.SelectSupport(0, nullKind, false, 0, 0), Is.EqualTo(Number(data[5]))); + Assert.That(string.Join(",", nullPort.Eligibility), Is.EqualTo(data[6])); + return; + } + if (data[0] == "N") + { + int normalSource = Number(data[2]); + int normalTarget = Number(data[3]); + string normalCase = data[4]; + var normalRandom = new BattleRandom(Number(data[5]), data[1]); + var normalPort = new Port { Back = normalCase != "backBlocked" }; + var normalAi = new BattleAi(data[1] == "PAL3A", normalRandom, normalPort); + foreach (int role in new[] { 0, 5 }) + { + normalAi.Roles[role].Valid = normalAi.Roles[role].Alive = true; + normalAi.Roles[role].Hp = normalAi.Roles[role].MaxHp = 100; + normalAi.Roles[role].Profile.Attack = true; + } + if (normalCase is "noAttack" or "chaosNoAttack" or "madNoAttack") + normalAi.Roles[normalSource].Profile.Attack = false; + normalAi.Roles[normalSource].Chaos = normalCase == "chaosNoAttack"; + normalAi.Roles[normalSource].Madness = normalCase == "madNoAttack"; + if (normalCase == "targetDead") + normalAi.Roles[normalTarget].Alive = false; + if (normalCase == "sourceDead") + normalAi.Roles[normalSource].Alive = false; + normalAi.Roles[normalTarget].Fled = normalCase == "targetFled"; + normalAi.Roles[normalSource].Fled = normalCase == "sourceFled"; + bool normalResult = normalAi.CanNormalAttack(normalSource, normalTarget, normalCase == "invisible", normalCase is "wall" or "both", normalCase is "mirror" or "both", normalCase != "away"); + Assert.That(normalResult, Is.EqualTo(data[6] == "1")); + Assert.That(normalRandom.State.ToString(CultureInfo.InvariantCulture), Is.EqualTo(data[7])); + return; + } + if (data[0] == "C") + { + var conversionRandom = new BattleRandom(Number(data[3]), data[1]); + var converter = new BattleAi(data[1] == "PAL3A", conversionRandom, new Port()); + Assert.That(converter.ConvertSingleAttackMagic(Number(data[2])), Is.EqualTo(Number(data[4]))); + Assert.That(conversionRandom.State.ToString(CultureInfo.InvariantCulture), Is.EqualTo(data[5])); + return; + } + if (data[0] == "W") + { + var scenePort = new Port { Scene = Number(data[3]), Owner = Number(data[4]) }; + var sceneAi = new BattleAi(true, new BattleRandom(1, "PAL3A"), scenePort); + sceneAi.Roles[Number(data[2])].Valid = true; + Assert.That(sceneAi.IsSceneMagicForbidden(Number(data[2]), 9001, Number(data[5])), Is.EqualTo(data[6] == "1")); + return; + } + bool five = data[0] == "F"; + string scenario = data[6]; + int source = five ? Number(data[2]) : 0; + bool group = data[five ? 3 : 4] == "1"; + int weight = Number(data[5]); + var port = new Port { Scene = five ? Number(data[4]) : 0, DenyFirst = scenario == "denied", Denied = five ? 265 : 9001 }; + var random = new BattleRandom(1, data[1]); + var ai = new BattleAi(data[1] == "PAL3A", random, port); + ai.Roles[source].Alive = ai.Roles[source].Valid = true; + ai.Roles[source].Hp = 40; + ai.Roles[source].MaxHp = 200; + var records = new List(); + for (int index = 0; index < 4; index++) + { + int power = new[] { 10, 40, 100, 400 }[index]; + if (five) + { + records.Add(new BattleAiSkill + { + Id = new[] { 9001, 265, 264, 9004 }[index], + Type = 2, + Range = 4, + Power = -power, + ElementMask = 1 << index, + Mastered = scenario != "unmastered" || index != 1 + }); + continue; + } + bool item = data[2] == "Item"; + bool attack = data[3] == "attack"; + int range = (attack ? 3 : 1) + (group ? 1 : 0); + if (attack) + power = -power; + if (scenario == "negative") + power = new[] { -20, 10, -40, 40 }[index]; + var operations = new int[32]; + if (data[3] == "revive" || scenario == "reviveFirst" && index == 0) + operations[24] = 2; + else if (data[3] == "cure") + operations[0] = 2; + records.Add(new BattleAiSkill + { + Id = 9001 + index, + Type = item ? attack ? 2 : 1 : data[2] == "Skill" ? 0 : 3, + Range = scenario == "wrongRange" && index == 0 ? range == 1 ? 2 : 1 : range, + Power = power, + PowerMode = index == 0 ? scenario == "percentage" ? 1 : scenario == "full" ? 2 : 0 : 0, + Count = scenario == "zeroCount" && index == 0 ? 0 : 1, + IsItem = item, + IsMagic = data[2] == "Magic", + Mastered = scenario != "unmastered" || index != 0, + StateOperations = operations + }); + } + ai.Roles[source].Skills = records; + ai.Items = records; + int actual; + if (five) + actual = ai.SelectFiveSpiritMagic(source, group, weight); + else + { + string name = char.ToUpperInvariant(data[3][0]) + data[3].Substring(1) + data[2]; + var kind = (BattleAiAttemptKind)Enum.Parse(typeof(BattleAiAttemptKind), name); + actual = ai.SelectSupport(source, kind, group, weight); + } + Assert.That(actual, Is.EqualTo(Number(data[7]))); + Assert.That(string.Join(",", port.Eligibility), Is.EqualTo(data[8])); + Assert.That(random.State, Is.EqualTo(1u)); + } + + [Test] + public void AcceptedGroupMagicDoesNotBindItsIgnoredDemand() + { + var port = new Port { Accept = true }; + var ai = new BattleAi(false, new BattleRandom(107), port); + ai.Roles[0].Valid = ai.Roles[0].Alive = true; + ai.Roles[0].Hp = ai.Roles[0].MaxHp = 100; + ai.Roles[5].Valid = ai.Roles[5].Alive = true; + ai.Roles[5].Hp = ai.Roles[5].MaxHp = 100; + ai.EnemyDemand[5].Satisfy = 40; + Assert.That(ai.HandleFriendAffirmative(0), Is.True); + Assert.That(ai.EnemyDemand[5].ActionId, Is.EqualTo(-1)); + } + + [Test] + public void Pal3ASelectedAndFiveSpiritAttemptsIgnoreMagicToggle() + { + var ai = new BattleAi(true, new BattleRandom(1, "PAL3A"), new Port()); + Assert.That(ai.CapabilityEnabled(5, BattleAiAttemptKind.SelectedMiscMagic), Is.True); + Assert.That(ai.CapabilityEnabled(5, BattleAiAttemptKind.FiveSpiritMagic), Is.True); + Assert.That(ai.CapabilityEnabled(5, BattleAiAttemptKind.FiveSpiritBigMagic), Is.True); + ai.Roles[5].Madness = true; + Assert.That(ai.CapabilityEnabled(5, BattleAiAttemptKind.SelectedMiscMagic), Is.False); + } + + private sealed class Port : BattleAiPort + { + public int Scene, Owner, Denied; + public bool DenyFirst, Accept; + public bool Back = true; + public readonly List Eligibility = new(); + public readonly List BackQueries = new(); + + public override int SceneFiveSpiritMode => Scene; + + public override int SceneFiveSpiritOwner => Owner; + + public override bool CanCast(int source, int skillId) + { + bool allowed = !DenyFirst || skillId != Denied; + Eligibility.Add(skillId + ":" + (allowed ? 1 : 0)); + return allowed; + } + + public override bool CanAttackBack(int source, int target) + { + BackQueries.Add(target); + return Back; + } + + public override long TryAttempt(BattleAiAttempt attempt) => Accept ? 7 : -1; + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleAiSupportTests.cs.meta b/Assets/Tests/Battle/Editor/BattleAiSupportTests.cs.meta new file mode 100644 index 00000000..5c563feb --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAiSupportTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 35c62a902da145e9a3fdd6b4002b617d diff --git a/Assets/Tests/Battle/Editor/BattleAiTests.cs b/Assets/Tests/Battle/Editor/BattleAiTests.cs new file mode 100644 index 00000000..5cc965f7 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAiTests.cs @@ -0,0 +1,1223 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using Battle; + using NUnit.Framework; + + // 874 independent original-EXE outcomes. Inputs and the unabridged RNG/call traces + // are retained under workspace/Analysis/Battle-Stage6-AI. Cast/eligibility/range ports + // have the same explicit stub boundaries as those probes; these are not full battle tests. + public sealed class BattleAiTests + { + private static readonly string[] NativeVectors = + { + "H|PAL3|0|100|5", + "H|PAL3|1|100|4", + "H|PAL3|24|100|4", + "H|PAL3|25|100|3", + "H|PAL3|49|100|3", + "H|PAL3|50|100|2", + "H|PAL3|100|100|1", + "H|PAL3|0|101|5", + "H|PAL3|1|101|4", + "H|PAL3|24|101|4", + "H|PAL3|25|101|3", + "H|PAL3|49|101|3", + "H|PAL3|50|101|2", + "H|PAL3|101|101|1", + "H|PAL3|0|1|2", + "H|PAL3|1|1|1", + "H|PAL3|0|3|3", + "H|PAL3|1|3|2", + "H|PAL3|3|3|1", + "E|PAL3|well|1|0,1,5,6||5|0||0||0|0||0|SpecAI:5:0|1766988168", + "E|PAL3|well|1|0,1,5,6||5|0||0||0|0|Normal|0|SpecAI:5:0|1766988168", + "E|PAL3|well|1|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|1766988168", + "E|PAL3|well|1|0,1,5,6||5|0||0||0|0|AttackMagic|0|SpecAI:5:0|1766988168", + "E|PAL3|well|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1766988168", + "E|PAL3|well|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1766988168", + "E|PAL3|well|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3|well|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1766988168", + "E|PAL3|well|1|0,1,5,6|3584:40|5|0||0||0|0||0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3|well|1|0,1,5,6|3584:40|5|0||0||0|0|Normal|0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3|well|1|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3|well|1|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3|well|1|0,1,5,6|1680:10|5|0||0||0|0||0|SpecAI:5:0|1766988168", + "E|PAL3|well|1|0,1,5,6|1680:10|5|0||0||0|0|Normal|0|SpecAI:5:0|1766988168", + "E|PAL3|well|1|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|1766988168", + "E|PAL3|well|1|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0|1766988168", + "E|PAL3|well|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3|well|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3|well|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3|well|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3|well|12345|0,1,5,6||5|0||0||0|0||0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6||5|0||0||0|0|Normal|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6||5|0||0||0|0|AttackMagic|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3584:40|5|0||0||0|0||0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3584:40|5|0||0||0|0|Normal|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|1680:10|5|0||0||0|0||0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|1680:10|5|0||0||0|0|Normal|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|980411738", + "E|PAL3|well|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0|SpecAI:5:0|980411738", + "E|PAL3|well|107|0,1,5,6||5|0||0||0|0||0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3|well|107|0,1,5,6||5|0||0||0|0|Normal|1|SpecAI:5:0;Normal:5:0:-1:0:1|715590205", + "E|PAL3|well|107|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3|well|107|0,1,5,6||5|0||0||0|0|AttackMagic|0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3|well|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|2042807014", + "E|PAL3|well|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|1|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:1|715590205", + "E|PAL3|well|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3|well|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|2042807014", + "E|PAL3|well|107|0,1,5,6|3584:40|5|0||0||0|0||0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3|well|107|0,1,5,6|3584:40|5|0||0||0|0|Normal|1|SpecAI:5:0;Normal:5:0:-1:0:1|4255167500", + "E|PAL3|well|107|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3|well|107|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3|well|107|0,1,5,6|1680:10|5|0||0||0|0||0|SpecAI:5:0;Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3|well|107|0,1,5,6|1680:10|5|0||0||0|0|Normal|1|SpecAI:5:0;Normal:5:0:1680:0:1|25430402", + "E|PAL3|well|107|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0;Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3|well|107|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3|well|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|SpecAI:5:0;Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0|3990963237", + "E|PAL3|well|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|1|SpecAI:5:0;Normal:5:0:1680:0:1|25430402", + "E|PAL3|well|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|SpecAI:5:0;Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3|well|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0|3990963237", + "E|PAL3|weak|1|0,1,5,6||5|0||0||0|0||0||1030492215", + "E|PAL3|weak|1|0,1,5,6||5|0||0||0|0|Normal|0||1030492215", + "E|PAL3|weak|1|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0||1030492215", + "E|PAL3|weak|1|0,1,5,6||5|0||0||0|0|AttackMagic|0||1030492215", + "E|PAL3|weak|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1030492215", + "E|PAL3|weak|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1030492215", + "E|PAL3|weak|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3|weak|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1030492215", + "E|PAL3|weak|1|0,1,5,6|3584:40|5|0||0||0|0||0|AttackBigMagic:5:-1:3584:0:0|1924036713", + "E|PAL3|weak|1|0,1,5,6|3584:40|5|0||0||0|0|Normal|0|AttackBigMagic:5:-1:3584:0:0|1924036713", + "E|PAL3|weak|1|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|AttackBigMagic:5:-1:3584:0:0|1924036713", + "E|PAL3|weak|1|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|AttackBigMagic:5:-1:3584:0:0|1924036713", + "E|PAL3|weak|1|0,1,5,6|1680:10|5|0||0||0|0||0||1030492215", + "E|PAL3|weak|1|0,1,5,6|1680:10|5|0||0||0|0|Normal|0||1030492215", + "E|PAL3|weak|1|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0||1030492215", + "E|PAL3|weak|1|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0||1030492215", + "E|PAL3|weak|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|1766988168", + "E|PAL3|weak|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|1766988168", + "E|PAL3|weak|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3|weak|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|1766988168", + "E|PAL3|weak|12345|0,1,5,6||5|0||0||0|0||0||980411738", + "E|PAL3|weak|12345|0,1,5,6||5|0||0||0|0|Normal|0||980411738", + "E|PAL3|weak|12345|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3|weak|12345|0,1,5,6||5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3584:40|5|0||0||0|0||0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3584:40|5|0||0||0|0|Normal|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|1680:10|5|0||0||0|0||0||980411738", + "E|PAL3|weak|12345|0,1,5,6|1680:10|5|0||0||0|0|Normal|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3|weak|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3|weak|107|0,1,5,6||5|0||0||0|0||0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|weak|107|0,1,5,6||5|0||0||0|0|Normal|1|Normal:5:0:-1:0:1|715590205", + "E|PAL3|weak|107|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|weak|107|0,1,5,6||5|0||0||0|0|AttackMagic|0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|weak|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|4255167500", + "E|PAL3|weak|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|1|RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:1|715590205", + "E|PAL3|weak|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3|weak|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|4255167500", + "E|PAL3|weak|107|0,1,5,6|3584:40|5|0||0||0|0||0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|899012752", + "E|PAL3|weak|107|0,1,5,6|3584:40|5|0||0||0|0|Normal|1|Normal:5:0:-1:0:1|4255167500", + "E|PAL3|weak|107|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|899012752", + "E|PAL3|weak|107|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|899012752", + "E|PAL3|weak|107|0,1,5,6|1680:10|5|0||0||0|0||0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|weak|107|0,1,5,6|1680:10|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3|weak|107|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|weak|107|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|weak|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackMagic:5:0:1712:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0|3990963237", + "E|PAL3|weak|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3|weak|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3|weak|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|1|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackMagic:5:0:1712:0:1|4255167500", + "E|PAL3|low|1|0,1,5,6||5|0||0||0|0||0||1030492215", + "E|PAL3|low|1|0,1,5,6||5|0||0||0|0|Normal|0||1030492215", + "E|PAL3|low|1|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0||1030492215", + "E|PAL3|low|1|0,1,5,6||5|0||0||0|0|AttackMagic|0||1030492215", + "E|PAL3|low|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1030492215", + "E|PAL3|low|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1030492215", + "E|PAL3|low|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3|low|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1030492215", + "E|PAL3|low|1|0,1,5,6|3584:40|5|0||0||0|0||0|AttackBigMagic:5:-1:3584:0:0|1924036713", + "E|PAL3|low|1|0,1,5,6|3584:40|5|0||0||0|0|Normal|0|AttackBigMagic:5:-1:3584:0:0|1924036713", + "E|PAL3|low|1|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|AttackBigMagic:5:-1:3584:0:0|1924036713", + "E|PAL3|low|1|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|AttackBigMagic:5:-1:3584:0:0|1924036713", + "E|PAL3|low|1|0,1,5,6|1680:10|5|0||0||0|0||0||1030492215", + "E|PAL3|low|1|0,1,5,6|1680:10|5|0||0||0|0|Normal|0||1030492215", + "E|PAL3|low|1|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0||1030492215", + "E|PAL3|low|1|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0||1030492215", + "E|PAL3|low|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|1766988168", + "E|PAL3|low|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|1766988168", + "E|PAL3|low|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3|low|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|1766988168", + "E|PAL3|low|12345|0,1,5,6||5|0||0||0|0||0||980411738", + "E|PAL3|low|12345|0,1,5,6||5|0||0||0|0|Normal|0||980411738", + "E|PAL3|low|12345|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3|low|12345|0,1,5,6||5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3|low|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0||980411738", + "E|PAL3|low|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0||980411738", + "E|PAL3|low|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3|low|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3|low|12345|0,1,5,6|3584:40|5|0||0||0|0||0||980411738", + "E|PAL3|low|12345|0,1,5,6|3584:40|5|0||0||0|0|Normal|0||980411738", + "E|PAL3|low|12345|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3|low|12345|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3|low|12345|0,1,5,6|1680:10|5|0||0||0|0||0||980411738", + "E|PAL3|low|12345|0,1,5,6|1680:10|5|0||0||0|0|Normal|0||980411738", + "E|PAL3|low|12345|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3|low|12345|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3|low|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0||980411738", + "E|PAL3|low|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0||980411738", + "E|PAL3|low|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3|low|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3|low|107|0,1,5,6||5|0||0||0|0||0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|low|107|0,1,5,6||5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3|low|107|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|low|107|0,1,5,6||5|0||0||0|0|AttackMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|low|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|4255167500", + "E|PAL3|low|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3|low|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3|low|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|4255167500", + "E|PAL3|low|107|0,1,5,6|3584:40|5|0||0||0|0||0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;Normal:5:1:-1:0:0|899012752", + "E|PAL3|low|107|0,1,5,6|3584:40|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3|low|107|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;Normal:5:1:-1:0:0|899012752", + "E|PAL3|low|107|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;Normal:5:1:-1:0:0|899012752", + "E|PAL3|low|107|0,1,5,6|1680:10|5|0||0||0|0||0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|low|107|0,1,5,6|1680:10|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3|low|107|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|low|107|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;Normal:5:1:-1:0:0|4255167500", + "E|PAL3|low|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackMagic:5:0:1712:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0|3990963237", + "E|PAL3|low|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3|low|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3|low|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|1|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackMagic:5:0:1712:0:1|4255167500", + "E|PAL3|chaos|1|0,1,5,6||5|18||0||0|0||0|RecoverBigMagic:5:-1:-1:0:0|3403800452", + "E|PAL3|chaos|1|0,1,5,6||5|18|1|0||0|0||0|RecoverBigMagic:5:-1:-1:0:0|3403800452", + "E|PAL3|chaos|12345|0,1,5,6||5|18||0||0|0||0|AttackMagic:5:0:-1:0:0|1449997005", + "E|PAL3|chaos|12345|0,1,5,6||5|18|1|0||0|0||0|AttackMagic:5:0:-1:0:0|1449997005", + "E|PAL3|chaos|107|0,1,5,6||5|18||0||0|0||0|RecoverMagic:5:0:-1:0:0|2042807014", + "E|PAL3|chaos|107|0,1,5,6||5|18|1|0||0|0||0|RecoverMagic:5:0:-1:0:0|2042807014", + "E|PAL3|affirmative|1|0,1,5,6||0|18||0||0|0||0||1957819393", + "E|PAL3|affirmative|1|0,1,5,6||0|18|1|0||0|0||0||3884216597", + "E|PAL3|affirmative|12345|0,1,5,6||0|18||0||0|0||0||352822329", + "E|PAL3|affirmative|12345|0,1,5,6||0|18|1|0||0|0||0||354763681", + "E|PAL3|affirmative|107|0,1,5,6||0|18||0||0|0||0|AttackBigMagic:0:-1:-1:0:0|417451394", + "E|PAL3|affirmative|107|0,1,5,6||0|18|1|0||0|0||0||2150497223", + "E|PAL3|affirmative|1|0,1,5,6||0|19||0||0|0||0|Normal:0:5:2480:0:0;AttackMagic:0:5:2480:0:0;AttackSkill:0:5:2480:0:0;AttackItem:0:5:2480:0:0;Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|1030492215", + "E|PAL3|affirmative|1|0,1,5,6||0|19|1|0||0|0||0|Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|3884216597", + "E|PAL3|affirmative|12345|0,1,5,6||0|19||0||0|0||0|Normal:0:5:2480:0:0;AttackMagic:0:5:2480:0:0;AttackSkill:0:5:2480:0:0;AttackItem:0:5:2480:0:0;Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|3681394607", + "E|PAL3|affirmative|12345|0,1,5,6||0|19|1|0||0|0||0|Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|1449997005", + "E|PAL3|affirmative|107|0,1,5,6||0|19||0||0|0||0|Normal:0:0:1680:0:0;AttackMagic:0:0:1680:0:0;AttackSkill:0:0:1680:0:0;AttackItem:0:0:1680:0:0;Normal:0:0:-1:0:0;AttackMagic:0:0:-1:0:0;AttackSkill:0:0:-1:0:0;AttackItem:0:0:-1:0:0;Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|2538958353", + "E|PAL3|affirmative|107|0,1,5,6||0|19|1|0||0|0||0|Normal:0:0:1680:0:0;AttackMagic:0:0:1680:0:0;AttackSkill:0:0:1680:0:0;AttackItem:0:0:1680:0:0;Normal:0:0:-1:0:0;AttackMagic:0:0:-1:0:0;AttackSkill:0:0:-1:0:0;AttackItem:0:0:-1:0:0;Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|3543904927", + "E|PAL3|negative|1|0,1,5,6||0|18||0||0|0||0|RecoverBigSkill:0:-1:-1:0:0|3884216597", + "E|PAL3|negative|1|0,1,5,6||0|18|1|0||0|0||0|RecoverBigSkill:0:-1:-1:0:0|3884216597", + "E|PAL3|negative|12345|0,1,5,6||0|18||0||0|0||0|RecoverBigMagic:0:-1:-1:0:0|1449997005", + "E|PAL3|negative|12345|0,1,5,6||0|18|1|0||0|0||0|RecoverBigMagic:0:-1:-1:0:0|1449997005", + "E|PAL3|negative|107|0,1,5,6||0|18||0||0|0||0|RecoverBigSkill:0:-1:-1:0:0|3543904927", + "E|PAL3|negative|107|0,1,5,6||0|18|1|0||0|0||0|RecoverBigSkill:0:-1:-1:0:0|3543904927", + "D|PAL3|0,1,2,3,5,6,7,8|100,100,100,100,100,100,100,100|0:100,100,100,100,100,80,100,100,100,100;1:100,100,100,100,100,80,100,100,100,100;2:100,100,100,100,100,80,100,100,100,100;3:100,100,100,100,100,80,100,100,100,100;5:100,100,100,100,100,80,100,100,100,100;6:100,100,100,100,100,80,100,100,100,100;7:100,100,100,100,100,80,100,100,100,100;8:100,100,100,100,100,80,100,100,100,100|100,110,100,100,100,0,100,100,100,100|100,110,100,100,100,100,100,100,100,100", + "D|PAL3|0,1,2,3,5,6,7,8|50,49,25,24,50,49,25,24|0:100,100,100,100,100,80,100,100,100,100;1:100,40,100,100,100,40,100,100,100,100;2:100,40,100,100,100,40,100,100,100,100;3:100,10,100,100,100,10,100,100,100,100;5:100,100,100,100,100,80,100,100,100,100;6:100,40,100,100,100,40,100,100,100,100;7:100,40,100,100,100,40,100,100,100,100;8:100,10,100,100,100,10,100,100,100,100|100,50,100,100,100,60,100,100,100,100|100,50,100,100,100,40,100,100,100,100", + "D|PAL3|0,1,2,3,5,6,7,8|0,0,100,100,0,0,100,100|0:100,40,0,100,100,40,100,100,100,100;1:100,40,0,100,100,40,100,100,100,100;2:100,100,100,100,100,80,100,100,100,100;3:100,100,100,100,100,80,100,100,100,100;5:100,40,0,100,100,40,100,100,100,100;6:100,40,0,100,100,40,100,100,100,100;7:100,100,100,100,100,80,100,100,100,100;8:100,100,100,100,100,80,100,100,100,100|100,70,100,100,100,40,100,100,100,100|100,70,100,100,100,60,100,100,100,100", + "D|PAL3|0,1,2,3,5,6,7,8|25,25,25,25,25,25,25,25|0:100,40,100,100,100,40,100,100,100,100;1:100,40,100,100,100,40,100,100,100,100;2:100,40,100,100,100,40,100,100,100,100;3:100,40,100,100,100,40,100,100,100,100;5:100,40,100,100,100,40,100,100,100,100;6:100,40,100,100,100,40,100,100,100,100;7:100,40,100,100,100,40,100,100,100,100;8:100,40,100,100,100,40,100,100,100,100|100,30,100,100,100,80,100,100,100,100|100,30,100,100,100,20,100,100,100,100", + "B|PAL3|738|100|100|0", + "B|PAL3|739|99|100|0", + "B|PAL3|739|100|100|1", + "B|PAL3|739|0|100|0", + "F|PAL3|20,30|100,1000||1|Normal:0:6:-1:0:1|1", + "F|PAL3|20,20|100,100||1|Normal:0:6:-1:0:1|1", + "F|PAL3|50,50|100,100||1|Normal:0:5:-1:0:1|1", + "F|PAL3|10,10|100,100||1|Normal:0:6:-1:0:1|1", + "F|PAL3|70,70|100,100||1|Normal:0:5:-1:0:1|1", + "F|PAL3|20,10|100,100|6|1|Normal:0:6:-1:0:1|1", + "F|PAL3|20,10|100,100||1|Normal:0:6:-1:0:1|1", + "F|PAL3|0,0|100,100||0||1", + "F|PAL3|200,300|100,100||1|Normal:0:5:-1:0:1|2745024", + "A|PAL3|0|0|0|0,0,0,0,0,0;0,0,0,0,0,0;0,0,0,0,0,0;0,0,0,0,0,0;0,0,0,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0|0", + "A|PAL3|0|0|1|0,0,0,0,1,0;0,0,0,0,1,0;0,0,0,0,1,0;0,0,0,0,1,0;0,0,0,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0|0", + "A|PAL3|0|1|0|1,1,1,1,0,1;1,1,1,1,0,1;1,1,1,1,0,1;1,1,1,1,0,1;1,1,1,1,0,1;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0|1", + "A|PAL3|0|1|1|1,1,1,1,1,1;1,1,1,1,1,1;1,1,1,1,1,1;1,1,1,1,1,1;1,1,1,1,1,1;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0|1", + "A|PAL3|1|0|1|1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0|0", + "A|PAL3|1|1|0|1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0|1", + "S|PAL3|attack|0|-25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|0|-25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|0|-25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|0|0|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|0|0|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|0|0|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|0|25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|0|25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|0|25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|0|26|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|0|26|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9002|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|0|26|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|0|80|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|0|80|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|0|80|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|0|250|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|0|250|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|0|250|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|0|1000|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|0|1000|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|0|1000|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|1|-25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|1|-25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|1|-25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|1|0|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|1|0|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|1|0|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|1|25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|1|25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|1|25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|1|26|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|1|26|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9002|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|1|26|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|1|80|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|1|80|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|1|80|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|1|250|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|1|250|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|1|250|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|attack|1|1000|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|attack|1|1000|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|attack|1|1000|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|0|-25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|0|-25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|0|-25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|0|0|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|0|0|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|0|0|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|0|25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|0|25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|0|25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|0|26|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|0|26|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9002|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|0|26|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|0|80|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|0|80|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|0|80|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|0|250|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|0|250|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|0|250|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|0|1000|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|0|1000|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|0|1000|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|1|-25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|1|-25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|1|-25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|1|0|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|1|0|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|1|0|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|1|25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|1|25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|1|25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|1|26|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|1|26|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9002|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|1|26|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|1|80|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|1|80|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|1|80|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|1|250|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|1|250|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|1|250|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover|1|1000|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3|recover|1|1000|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3|recover|1|1000|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3|recover-mixed|0|25|9001,3,1,10;9002,3,1,-20;9003,3,3,40;9004,3,1,0||9001|9001:1,9002:1,9004:1", + "S|PAL3|recover-mixed|0|25|9001,3,1,40;9002,3,1,10;9003,3,3,100;9004,3,1,400||9001|9001:1,9002:1,9004:1", + "S|PAL3|recover-mixed|0|25|9001,3,1,10;9002,3,1,40;9003,3,3,100;9004,3,1,400||9001|9001:1,9002:1,9004:1", + "T|PAL3|1,2,3|9001|1", + "T|PAL3|1,2,3|9002|2", + "T|PAL3|1,2,3|9003|3", + "T|PAL3|1,2,3|9004|4", + "T|PAL3|1,2,3|9999|0", + "T|PAL3|1,2,3|207|1", + "T|PAL3|1,2,3|215|1", + "T|PAL3|1,2,3|224|1", + "T|PAL3|1,2,3|232|1", + "T|PAL3|1,2,3|240|1", + "T|PAL3|0,0,0|9001|0", + "T|PAL3|0,0,0|9002|0", + "T|PAL3|0,0,0|9003|0", + "T|PAL3|0,0,0|9004|4", + "T|PAL3|0,0,0|9999|0", + "T|PAL3|0,0,0|207|1", + "T|PAL3|0,0,0|215|1", + "T|PAL3|0,0,0|224|1", + "T|PAL3|0,0,0|232|1", + "T|PAL3|0,0,0|240|1", + "T|PAL3|4,4,4|9001|4", + "T|PAL3|4,4,4|9002|4", + "T|PAL3|4,4,4|9003|4", + "T|PAL3|4,4,4|9004|4", + "T|PAL3|4,4,4|9999|0", + "T|PAL3|4,4,4|207|1", + "T|PAL3|4,4,4|215|1", + "T|PAL3|4,4,4|224|1", + "T|PAL3|4,4,4|232|1", + "T|PAL3|4,4,4|240|1", + "T|PAL3|255,128,17|9001|255", + "T|PAL3|255,128,17|9002|128", + "T|PAL3|255,128,17|9003|17", + "T|PAL3|255,128,17|9004|4", + "T|PAL3|255,128,17|9999|0", + "T|PAL3|255,128,17|207|1", + "T|PAL3|255,128,17|215|1", + "T|PAL3|255,128,17|224|1", + "T|PAL3|255,128,17|232|1", + "T|PAL3|255,128,17|240|1", + "R|PAL3|259|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|AllTargetsDead;Submit:259:8", + "R|PAL3|259|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|AllTargetsDead;Submit:259:8", + "R|PAL3|259|1|1|0|1|6|1|6|0,0,0,0,0,0,0,0,0,0,0|AllTargetsDead;Pick:2:;ExpandRange;Submit:259:6", + "R|PAL3|259|1|0|1|0|1|1|1|0,0,0,0,0,0,0,0,0,0,0|AllTargetsDead;Pick:2:;ExpandRange;Submit:259:1", + "R|PAL3|259|1|1|0|1|-1|1|4294967295|0,0,0,0,0,0,0,0,0,0,0|AllTargetsDead;Pick:2:;ExpandRange;Submit:259:4294967295", + "R|PAL3|260|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;AllTargetsDead;Submit:260:8", + "R|PAL3|260|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;FallbackPlayerNormal", + "R|PAL3|260|1|1|0|1|6|1|6|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:;ExpandRange;Submit:260:6", + "R|PAL3|260|1|0|1|0|1|1|1|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:1:;ExpandRange;Submit:260:1", + "R|PAL3|260|1|1|0|1|-1|1|4294967295|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:;ExpandRange;Submit:260:4294967295", + "R|PAL3|261|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;AllTargetsDead;Submit:261:8", + "R|PAL3|261|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;FallbackPlayerNormal", + "R|PAL3|261|1|1|0|1|6|1|6|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:;ExpandRange;Submit:261:6", + "R|PAL3|261|1|0|1|0|1|1|1|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:1:;ExpandRange;Submit:261:1", + "R|PAL3|261|1|1|0|1|-1|1|4294967295|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:;ExpandRange;Submit:261:4294967295", + "R|PAL3|262|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;AllTargetsDead;Submit:262:8", + "R|PAL3|262|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;FallbackPlayerNormal", + "R|PAL3|262|1|1|0|1|6|1|6|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:;ExpandRange;Submit:262:6", + "R|PAL3|262|1|0|1|0|1|1|1|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:1:;ExpandRange;Submit:262:1", + "R|PAL3|262|1|1|0|1|-1|1|4294967295|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:;ExpandRange;Submit:262:4294967295", + "R|PAL3|265|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:265:8", + "R|PAL3|265|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:265:8", + "R|PAL3|265|1|1|0|1|6|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:265:8", + "R|PAL3|265|1|0|1|0|1|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:265:8", + "R|PAL3|265|1|1|0|1|-1|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:265:8", + "R|PAL3|267|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:267:8", + "R|PAL3|267|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:267:8", + "R|PAL3|267|1|1|0|1|6|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:267:8", + "R|PAL3|267|1|0|1|0|1|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:267:8", + "R|PAL3|267|1|1|0|1|-1|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:267:8", + "R|PAL3|271|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|FallbackPlayerNormal", + "R|PAL3|271|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|FallbackPlayerNormal", + "R|PAL3|271|1|1|0|1|6|1|8|1,1,1,1,1,1,1,1,1,1,1|FallbackPlayerNormal", + "R|PAL3|271|1|0|1|0|1|1|8|1,1,1,1,1,1,1,1,1,1,1|FallbackPlayerNormal", + "R|PAL3|271|1|1|0|1|-1|1|8|1,1,1,1,1,1,1,1,1,1,1|FallbackPlayerNormal", + "H|PAL3A|0|100|5", + "H|PAL3A|1|100|4", + "H|PAL3A|24|100|4", + "H|PAL3A|25|100|3", + "H|PAL3A|49|100|3", + "H|PAL3A|50|100|2", + "H|PAL3A|100|100|1", + "H|PAL3A|0|101|5", + "H|PAL3A|1|101|4", + "H|PAL3A|24|101|4", + "H|PAL3A|25|101|3", + "H|PAL3A|49|101|3", + "H|PAL3A|50|101|2", + "H|PAL3A|101|101|1", + "H|PAL3A|0|1|2", + "H|PAL3A|1|1|1", + "H|PAL3A|0|3|3", + "H|PAL3A|1|3|2", + "H|PAL3A|3|3|1", + "E|PAL3A|well|1|0,1,5,6||5|0||0||0|0||0|SpecAI:5:0|1924036713", + "E|PAL3A|well|1|0,1,5,6||5|0||0||0|0|Normal|0|SpecAI:5:0|1924036713", + "E|PAL3A|well|1|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|1924036713", + "E|PAL3A|well|1|0,1,5,6||5|0||0||0|0|AttackMagic|0|SpecAI:5:0|1924036713", + "E|PAL3A|well|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1924036713", + "E|PAL3A|well|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1924036713", + "E|PAL3A|well|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3A|well|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1924036713", + "E|PAL3A|well|1|0,1,5,6|3584:40|5|0||0||0|0||0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|well|1|0,1,5,6|3584:40|5|0||0||0|0|Normal|0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|well|1|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|well|1|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|well|1|0,1,5,6|1680:10|5|0||0||0|0||0|SpecAI:5:0|1924036713", + "E|PAL3A|well|1|0,1,5,6|1680:10|5|0||0||0|0|Normal|0|SpecAI:5:0|1924036713", + "E|PAL3A|well|1|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|1924036713", + "E|PAL3A|well|1|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0|1924036713", + "E|PAL3A|well|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3A|well|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3A|well|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3A|well|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3A|well|12345|0,1,5,6||5|0||0||0|0||0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6||5|0||0||0|0|Normal|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6||5|0||0||0|0|AttackMagic|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3584:40|5|0||0||0|0||0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3584:40|5|0||0||0|0|Normal|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|1680:10|5|0||0||0|0||0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|1680:10|5|0||0||0|0|Normal|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0|980411738", + "E|PAL3A|well|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0|SpecAI:5:0|980411738", + "E|PAL3A|well|107|0,1,5,6||5|0||0||0|0||0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|well|107|0,1,5,6||5|0||0||0|0|Normal|1|SpecAI:5:0;Normal:5:0:-1:0:1|715590205", + "E|PAL3A|well|107|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|well|107|0,1,5,6||5|0||0||0|0|AttackMagic|0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|well|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|2042807014", + "E|PAL3A|well|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|1|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:1|715590205", + "E|PAL3A|well|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3A|well|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|2042807014", + "E|PAL3A|well|107|0,1,5,6|3584:40|5|0||0||0|0||0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3A|well|107|0,1,5,6|3584:40|5|0||0||0|0|Normal|1|SpecAI:5:0;Normal:5:0:-1:0:1|4255167500", + "E|PAL3A|well|107|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3A|well|107|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3A|well|107|0,1,5,6|1680:10|5|0||0||0|0||0|SpecAI:5:0;Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|well|107|0,1,5,6|1680:10|5|0||0||0|0|Normal|1|SpecAI:5:0;Normal:5:0:1680:0:1|25430402", + "E|PAL3A|well|107|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0|SpecAI:5:0;Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|well|107|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0|SpecAI:5:0;Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|well|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|SpecAI:5:0;Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackMagic:5:0:1712:0:0;Normal:5:0:1728:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackBigMagic:5:-1:3584:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;AttackBigMagic:5:-1:3584:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackBigMagic:5:-1:3584:0:0|2849146734", + "E|PAL3A|well|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|1|SpecAI:5:0;Normal:5:0:1680:0:1|25430402", + "E|PAL3A|well|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|SpecAI:5:0;Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3A|well|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|1|SpecAI:5:0;Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackMagic:5:0:1712:0:1|4255167500", + "E|PAL3A|weak|1|0,1,5,6||5|0||0||0|0||0||1924036713", + "E|PAL3A|weak|1|0,1,5,6||5|0||0||0|0|Normal|0||1924036713", + "E|PAL3A|weak|1|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0||1924036713", + "E|PAL3A|weak|1|0,1,5,6||5|0||0||0|0|AttackMagic|0||1924036713", + "E|PAL3A|weak|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1924036713", + "E|PAL3A|weak|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1924036713", + "E|PAL3A|weak|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3A|weak|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1924036713", + "E|PAL3A|weak|1|0,1,5,6|3584:40|5|0||0||0|0||0|AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|weak|1|0,1,5,6|3584:40|5|0||0||0|0|Normal|0|AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|weak|1|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|weak|1|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|weak|1|0,1,5,6|1680:10|5|0||0||0|0||0||1924036713", + "E|PAL3A|weak|1|0,1,5,6|1680:10|5|0||0||0|0|Normal|0||1924036713", + "E|PAL3A|weak|1|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0||1924036713", + "E|PAL3A|weak|1|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0||1924036713", + "E|PAL3A|weak|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3A|weak|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3A|weak|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3A|weak|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3A|weak|12345|0,1,5,6||5|0||0||0|0||0||980411738", + "E|PAL3A|weak|12345|0,1,5,6||5|0||0||0|0|Normal|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6||5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3584:40|5|0||0||0|0||0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3584:40|5|0||0||0|0|Normal|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|1680:10|5|0||0||0|0||0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|1680:10|5|0||0||0|0|Normal|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3A|weak|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3A|weak|107|0,1,5,6||5|0||0||0|0||0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|weak|107|0,1,5,6||5|0||0||0|0|Normal|1|Normal:5:0:-1:0:1|715590205", + "E|PAL3A|weak|107|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|weak|107|0,1,5,6||5|0||0||0|0|AttackMagic|0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|weak|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|2042807014", + "E|PAL3A|weak|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|1|RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:1|715590205", + "E|PAL3A|weak|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3A|weak|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|2042807014", + "E|PAL3A|weak|107|0,1,5,6|3584:40|5|0||0||0|0||0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3A|weak|107|0,1,5,6|3584:40|5|0||0||0|0|Normal|1|Normal:5:0:-1:0:1|4255167500", + "E|PAL3A|weak|107|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3A|weak|107|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3A|weak|107|0,1,5,6|1680:10|5|0||0||0|0||0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|weak|107|0,1,5,6|1680:10|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3A|weak|107|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|weak|107|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|weak|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackMagic:5:0:1712:0:0;Normal:5:0:1728:0:0;Normal:5:0:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackBigMagic:5:-1:3584:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:2400:0:0;AttackBigMagic:5:-1:3584:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackBigMagic:5:-1:3584:0:0|2849146734", + "E|PAL3A|weak|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3A|weak|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3A|weak|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|1|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackMagic:5:0:1712:0:1|4255167500", + "E|PAL3A|low|1|0,1,5,6||5|0||0||0|0||0||1924036713", + "E|PAL3A|low|1|0,1,5,6||5|0||0||0|0|Normal|0||1924036713", + "E|PAL3A|low|1|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0||1924036713", + "E|PAL3A|low|1|0,1,5,6||5|0||0||0|0|AttackMagic|0||1924036713", + "E|PAL3A|low|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1924036713", + "E|PAL3A|low|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1924036713", + "E|PAL3A|low|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3A|low|1|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverMagic:5:5:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|1924036713", + "E|PAL3A|low|1|0,1,5,6|3584:40|5|0||0||0|0||0|AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|low|1|0,1,5,6|3584:40|5|0||0||0|0|Normal|0|AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|low|1|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|low|1|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0|AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|low|1|0,1,5,6|1680:10|5|0||0||0|0||0||1924036713", + "E|PAL3A|low|1|0,1,5,6|1680:10|5|0||0||0|0|Normal|0||1924036713", + "E|PAL3A|low|1|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0||1924036713", + "E|PAL3A|low|1|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0||1924036713", + "E|PAL3A|low|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3A|low|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3A|low|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|RecoverBigMagic:5:-1:3360:0:1|1030492215", + "E|PAL3A|low|1|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0|RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;CureMagic:5:5:2448:0:0;RecoverBigMagic:5:-1:3360:0:0|373929026", + "E|PAL3A|low|12345|0,1,5,6||5|0||0||0|0||0||980411738", + "E|PAL3A|low|12345|0,1,5,6||5|0||0||0|0|Normal|0||980411738", + "E|PAL3A|low|12345|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3A|low|12345|0,1,5,6||5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3584:40|5|0||0||0|0||0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3584:40|5|0||0||0|0|Normal|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|1680:10|5|0||0||0|0||0||980411738", + "E|PAL3A|low|12345|0,1,5,6|1680:10|5|0||0||0|0|Normal|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|0||980411738", + "E|PAL3A|low|12345|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0||980411738", + "E|PAL3A|low|107|0,1,5,6||5|0||0||0|0||0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|low|107|0,1,5,6||5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3A|low|107|0,1,5,6||5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|low|107|0,1,5,6||5|0||0||0|0|AttackMagic|1|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:1|4255167500", + "E|PAL3A|low|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0||0|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:6:2560:0:0|2042807014", + "E|PAL3A|low|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3A|low|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|RecoverBigMagic|1|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3A|low|107|0,1,5,6|3360:60,2400:40,2560:10|5|0||0||0|0|AttackMagic|1|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:1|4255167500", + "E|PAL3A|low|107|0,1,5,6|3584:40|5|0||0||0|0||0|Normal:5:0:1680:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:0:-1:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3A|low|107|0,1,5,6|3584:40|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3A|low|107|0,1,5,6|3584:40|5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:1680:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:0:-1:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0|505850762", + "E|PAL3A|low|107|0,1,5,6|3584:40|5|0||0||0|0|AttackMagic|1|Normal:5:0:1680:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:0:-1:0:1|4255167500", + "E|PAL3A|low|107|0,1,5,6|1680:10|5|0||0||0|0||0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|low|107|0,1,5,6|1680:10|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3A|low|107|0,1,5,6|1680:10|5|0||0||0|0|RecoverBigMagic|0|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0|2042807014", + "E|PAL3A|low|107|0,1,5,6|1680:10|5|0||0||0|0|AttackMagic|1|Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:1|4255167500", + "E|PAL3A|low|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0||0|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:1728:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackBigMagic:5:-1:3584:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;AttackBigMagic:5:-1:3584:0:0;RecoverMagic:5:5:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackBigMagic:5:-1:3584:0:0|2849146734", + "E|PAL3A|low|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|Normal|1|Normal:5:0:1680:0:1|25430402", + "E|PAL3A|low|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|RecoverBigMagic|1|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:1|25430402", + "E|PAL3A|low|107|0,1,5,6|3360:60,3584:40,1680:10,2400:40,2448:50,1712:50,1728:50|5|0||0||0|0|AttackMagic|0|Normal:5:0:1680:0:0;RecoverBigMagic:5:-1:3360:0:0;Normal:5:0:1728:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackBigMagic:5:-1:3584:0:0;Normal:5:1:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2400:0:0;AttackBigMagic:5:-1:3584:0:0;RecoverMagic:5:5:-1:0:0;RecoverBigMagic:5:-1:3360:0:0;AttackBigMagic:5:-1:3584:0:0|2849146734", + "E|PAL3A|chaos|1|0,1,5,6||5|18||0||0|0||0|RecoverBigMagic:5:-1:-1:0:0|3403800452", + "E|PAL3A|chaos|1|0,1,5,6||5|18|1|0||0|0||0|RecoverBigMagic:5:-1:-1:0:0|373929026", + "E|PAL3A|chaos|12345|0,1,5,6||5|18||0||0|0||0|AttackMagic:5:0:-1:0:0|1449997005", + "E|PAL3A|chaos|12345|0,1,5,6||5|18|1|0||0|0||0|AttackMagic:5:0:-1:0:0|1449997005", + "E|PAL3A|chaos|107|0,1,5,6||5|18||0||0|0||0|RecoverMagic:5:0:-1:0:0|2042807014", + "E|PAL3A|chaos|107|0,1,5,6||5|18|1|0||0|0||0|RecoverMagic:5:0:-1:0:0|2042807014", + "E|PAL3A|affirmative|1|0,1,5,6||0|18||0||0|0||0||1957819393", + "E|PAL3A|affirmative|1|0,1,5,6||0|18|1|0||0|0||0||3884216597", + "E|PAL3A|affirmative|12345|0,1,5,6||0|18||0||0|0||0||352822329", + "E|PAL3A|affirmative|12345|0,1,5,6||0|18|1|0||0|0||0||354763681", + "E|PAL3A|affirmative|107|0,1,5,6||0|18||0||0|0||0|AttackBigMagic:0:-1:-1:0:0|417451394", + "E|PAL3A|affirmative|107|0,1,5,6||0|18|1|0||0|0||0||2150497223", + "E|PAL3A|affirmative|1|0,1,5,6||0|19||0||0|0||0|Normal:0:5:2480:0:0;AttackMagic:0:5:2480:0:0;AttackSkill:0:5:2480:0:0;AttackItem:0:5:2480:0:0;Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|1030492215", + "E|PAL3A|affirmative|1|0,1,5,6||0|19|1|0||0|0||0|Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|3884216597", + "E|PAL3A|affirmative|12345|0,1,5,6||0|19||0||0|0||0|Normal:0:5:2480:0:0;AttackMagic:0:5:2480:0:0;AttackSkill:0:5:2480:0:0;AttackItem:0:5:2480:0:0;Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|3681394607", + "E|PAL3A|affirmative|12345|0,1,5,6||0|19|1|0||0|0||0|Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|1449997005", + "E|PAL3A|affirmative|107|0,1,5,6||0|19||0||0|0||0|Normal:0:0:1680:0:0;AttackMagic:0:0:1680:0:0;AttackSkill:0:0:1680:0:0;AttackItem:0:0:1680:0:0;Normal:0:0:-1:0:0;AttackMagic:0:0:-1:0:0;AttackSkill:0:0:-1:0:0;AttackItem:0:0:-1:0:0;Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|2538958353", + "E|PAL3A|affirmative|107|0,1,5,6||0|19|1|0||0|0||0|Normal:0:0:1680:0:0;AttackMagic:0:0:1680:0:0;AttackSkill:0:0:1680:0:0;AttackItem:0:0:1680:0:0;Normal:0:0:-1:0:0;AttackMagic:0:0:-1:0:0;AttackSkill:0:0:-1:0:0;AttackItem:0:0:-1:0:0;Normal:0:5:-1:0:0;AttackMagic:0:5:-1:0:0;AttackSkill:0:5:-1:0:0;AttackItem:0:5:-1:0:0;Normal:0:6:-1:0:0;AttackMagic:0:6:-1:0:0;AttackSkill:0:6:-1:0:0;AttackItem:0:6:-1:0:0|3543904927", + "E|PAL3A|negative|1|0,1,5,6||0|18||0||0|0||0|RecoverBigSkill:0:-1:-1:0:0|3884216597", + "E|PAL3A|negative|1|0,1,5,6||0|18|1|0||0|0||0|RecoverBigSkill:0:-1:-1:0:0|3884216597", + "E|PAL3A|negative|12345|0,1,5,6||0|18||0||0|0||0|RecoverBigMagic:0:-1:-1:0:0|1449997005", + "E|PAL3A|negative|12345|0,1,5,6||0|18|1|0||0|0||0|RecoverBigMagic:0:-1:-1:0:0|1449997005", + "E|PAL3A|negative|107|0,1,5,6||0|18||0||0|0||0|RecoverBigSkill:0:-1:-1:0:0|3543904927", + "E|PAL3A|negative|107|0,1,5,6||0|18|1|0||0|0||0|RecoverBigSkill:0:-1:-1:0:0|3543904927", + "E|PAL3A|well|1|0,1,5,6||5|0||0|9001,9002,9003,264|0|0||0|SpecAI:5:0;SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritMagic:5:5:2512:0:0;SelectedMiscMagic:5:6:-1:9002:0;FiveSpiritMagic:5:6:2672:0:0|2503793637", + "E|PAL3A|well|1|0,1,5,6||5|0||0|9001,9002,9003,264|1|0||0|SpecAI:5:0;SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritBigMagic:5:-1:2512:0:0;SelectedMiscMagic:5:6:-1:9002:0|2503793637", + "E|PAL3A|well|1|0,1,5||5|0||0|9001,9002,9003,274|0|0||0|SpecAI:5:0;SelectedMiscMagic:5:5:-1:9002:0|1844513277", + "E|PAL3A|well|1|0,1,5,6||5|0||1|9001,9002,9003,264|0|0||0|SpecAI:5:0;BossPhysical:5:-1:3584:0:0;BossPhysical:5:-1:3584:0:0|2179684817", + "E|PAL3A|well|1|0,1,5,6||5|0||1|9001,9002,9003,264|1|0||0|SpecAI:5:0;BossPhysical:5:-1:3584:0:0;BossPhysical:5:-1:3584:0:0|2179684817", + "E|PAL3A|well|1|0,1,5||5|0||1|9001,9002,9003,274|0|0||0|SpecAI:5:0;BossPhysical:5:-1:3584:0:0|373929026", + "E|PAL3A|well|107|0,1,5,6||5|0||0|9001,9002,9003,264|0|0||0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;FiveSpiritMagic:5:0:1712:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9003:0;FiveSpiritMagic:5:1:1872:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritMagic:5:5:2512:0:0;FiveSpiritMagic:5:6:2672:0:0|1876656616", + "E|PAL3A|well|107|0,1,5,6||5|0||0|9001,9002,9003,264|1|0||0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9003:0;FiveSpiritBigMagic:5:-1:1872:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritBigMagic:5:-1:2512:0:0|1876656616", + "E|PAL3A|well|107|0,1,5||5|0||0|9001,9002,9003,274|0|0||0|SpecAI:5:0;AttackBigMagic:5:-1:3584:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9003:0;AttackBigMagic:5:-1:3584:0:0;Normal:5:1:-1:0:0;AttackBigMagic:5:-1:3584:0:0|1967352054", + "E|PAL3A|well|107|0,1,5,6||5|0||1|9001,9002,9003,264|0|0||0|SpecAI:5:0;SelectedMiscMagic:5:0:-1:9003:0;FiveSpiritMagic:5:0:1712:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:0:-1:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9003:0;BossPhysical:5:-1:3584:0:0;FiveSpiritMagic:5:1:1872:0:0;Normal:5:1:-1:0:0;FiveSpiritMagic:5:5:2512:0:0;BossPhysical:5:-1:3584:0:0;FiveSpiritMagic:5:6:2672:0:0|531642010", + "E|PAL3A|well|107|0,1,5,6||5|0||1|9001,9002,9003,264|1|0||0|SpecAI:5:0;SelectedMiscMagic:5:0:-1:9003:0;FiveSpiritBigMagic:5:-1:1712:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:0:-1:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9003:0;BossPhysical:5:-1:3584:0:0;FiveSpiritBigMagic:5:-1:1872:0:0;Normal:5:1:-1:0:0;FiveSpiritBigMagic:5:-1:2512:0:0;BossPhysical:5:-1:3584:0:0;FiveSpiritBigMagic:5:-1:2672:0:0|531642010", + "E|PAL3A|well|107|0,1,5||5|0||1|9001,9002,9003,274|0|0||0|SpecAI:5:0;SelectedMiscMagic:5:0:-1:9003:0;SelectedMiscMagic:5:0:-1:274:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:0:-1:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9003:0;BossPhysical:5:-1:3584:0:0;SelectedMiscMagic:5:1:-1:274:0;Normal:5:1:-1:0:0;SelectedMiscMagic:5:5:-1:274:0|2716591599", + "E|PAL3A|weak|1|0,1,5,6||5|0||0|9001,9002,9003,264|0|0||0|SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritMagic:5:5:2512:0:0;SelectedMiscMagic:5:6:-1:9002:0;FiveSpiritMagic:5:6:2672:0:0|2503793637", + "E|PAL3A|weak|1|0,1,5,6||5|0||0|9001,9002,9003,264|1|0||0|SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritBigMagic:5:-1:2512:0:0;SelectedMiscMagic:5:6:-1:9002:0|2503793637", + "E|PAL3A|weak|1|0,1,5||5|0||0|9001,9002,9003,274|0|0||0|SelectedMiscMagic:5:5:-1:9002:0|1844513277", + "E|PAL3A|weak|1|0,1,5,6||5|0||1|9001,9002,9003,264|0|0||0|FiveSpiritMagic:5:5:2512:0:0|2503793637", + "E|PAL3A|weak|1|0,1,5,6||5|0||1|9001,9002,9003,264|1|0||0|FiveSpiritBigMagic:5:-1:2512:0:0|2503793637", + "E|PAL3A|weak|1|0,1,5||5|0||1|9001,9002,9003,274|0|0||0|SelectedMiscMagic:5:5:-1:274:0|3673273548", + "E|PAL3A|weak|107|0,1,5,6||5|0||0|9001,9002,9003,264|0|0||0|AttackBigMagic:5:-1:3584:0:0;FiveSpiritMagic:5:0:1712:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9003:0;FiveSpiritMagic:5:1:1872:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritMagic:5:5:2512:0:0;FiveSpiritMagic:5:6:2672:0:0|1876656616", + "E|PAL3A|weak|107|0,1,5,6||5|0||0|9001,9002,9003,264|1|0||0|AttackBigMagic:5:-1:3584:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9003:0;FiveSpiritBigMagic:5:-1:1872:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritBigMagic:5:-1:2512:0:0|1876656616", + "E|PAL3A|weak|107|0,1,5||5|0||0|9001,9002,9003,274|0|0||0|AttackBigMagic:5:-1:3584:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9003:0;AttackBigMagic:5:-1:3584:0:0;Normal:5:1:-1:0:0;AttackBigMagic:5:-1:3584:0:0|1967352054", + "E|PAL3A|weak|107|0,1,5,6||5|0||1|9001,9002,9003,264|0|0||0|BossPhysical:5:-1:3584:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:0:-1:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9001:0;SelectedMiscMagic:5:1:-1:9003:0;FiveSpiritMagic:5:1:1872:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;FiveSpiritMagic:5:5:2512:0:0|1876656616", + "E|PAL3A|weak|107|0,1,5,6||5|0||1|9001,9002,9003,264|1|0||0|BossPhysical:5:-1:3584:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:0:-1:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9001:0;SelectedMiscMagic:5:1:-1:9003:0;FiveSpiritBigMagic:5:-1:1872:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;FiveSpiritBigMagic:5:-1:2512:0:0|1876656616", + "E|PAL3A|weak|107|0,1,5||5|0||1|9001,9002,9003,274|0|0||0|BossPhysical:5:-1:3584:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:0:-1:0:0;Normal:5:0:-1:0:0;SelectedMiscMagic:5:1:-1:9001:0;SelectedMiscMagic:5:1:-1:9003:0;SelectedMiscMagic:5:1:-1:274:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;SelectedMiscMagic:5:5:-1:274:0|1494520163", + "E|PAL3A|low|1|0,1,5,6||5|0||0|9001,9002,9003,264|0|0||0|AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|2179684817", + "E|PAL3A|low|1|0,1,5,6||5|0||0|9001,9002,9003,264|1|0||0|AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:3584:0:0|2179684817", + "E|PAL3A|low|1|0,1,5||5|0||0|9001,9002,9003,274|0|0||0|AttackBigMagic:5:-1:3584:0:0|3750785579", + "E|PAL3A|low|1|0,1,5,6||5|0||1|9001,9002,9003,264|0|0||0|SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritMagic:5:5:2512:0:0;SelectedMiscMagic:5:6:-1:9002:0|2503793637", + "E|PAL3A|low|1|0,1,5,6||5|0||1|9001,9002,9003,264|1|0||0|SelectedMiscMagic:5:5:-1:9002:0;SelectedMiscMagic:5:6:-1:9002:0|2503793637", + "E|PAL3A|low|1|0,1,5||5|0||1|9001,9002,9003,274|0|0||0|SelectedMiscMagic:5:5:-1:9002:0|3673273548", + "E|PAL3A|low|107|0,1,5,6||5|0||0|9001,9002,9003,264|0|0||0|Normal:5:0:1680:0:0;SelectedMiscMagic:5:0:-1:9003:0;FiveSpiritMagic:5:0:1712:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;SelectedMiscMagic:5:1:-1:9003:0;AttackBigMagic:5:-1:3584:0:0;FiveSpiritMagic:5:1:1872:0:0;Normal:5:1:-1:0:0;FiveSpiritMagic:5:5:2512:0:0;AttackBigMagic:5:-1:3584:0:0;FiveSpiritMagic:5:6:2672:0:0|531642010", + "E|PAL3A|low|107|0,1,5,6||5|0||0|9001,9002,9003,264|1|0||0|Normal:5:0:1680:0:0;SelectedMiscMagic:5:0:-1:9003:0;FiveSpiritBigMagic:5:-1:1712:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;SelectedMiscMagic:5:1:-1:9003:0;AttackBigMagic:5:-1:3584:0:0;FiveSpiritBigMagic:5:-1:1872:0:0;Normal:5:1:-1:0:0;FiveSpiritBigMagic:5:-1:2512:0:0;AttackBigMagic:5:-1:3584:0:0;FiveSpiritBigMagic:5:-1:2672:0:0|531642010", + "E|PAL3A|low|107|0,1,5||5|0||0|9001,9002,9003,274|0|0||0|Normal:5:0:1680:0:0;SelectedMiscMagic:5:0:-1:9003:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:0:-1:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;SelectedMiscMagic:5:1:-1:9003:0;AttackBigMagic:5:-1:3584:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;AttackBigMagic:5:-1:3584:0:0|1812355730", + "E|PAL3A|low|107|0,1,5,6||5|0||1|9001,9002,9003,264|0|0||0|Normal:5:0:1680:0:0;SelectedMiscMagic:5:0:-1:9001:0;BossPhysical:5:-1:3584:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;SelectedMiscMagic:5:1:-1:9001:0;SelectedMiscMagic:5:1:-1:9003:0;FiveSpiritMagic:5:1:1872:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritMagic:5:5:2512:0:0|1876656616", + "E|PAL3A|low|107|0,1,5,6||5|0||1|9001,9002,9003,264|1|0||0|Normal:5:0:1680:0:0;SelectedMiscMagic:5:0:-1:9001:0;BossPhysical:5:-1:3584:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;SelectedMiscMagic:5:1:-1:9001:0;SelectedMiscMagic:5:1:-1:9003:0;FiveSpiritBigMagic:5:-1:1872:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;SelectedMiscMagic:5:5:-1:9002:0;FiveSpiritBigMagic:5:-1:2512:0:0|1876656616", + "E|PAL3A|low|107|0,1,5||5|0||1|9001,9002,9003,274|0|0||0|Normal:5:0:1680:0:0;SelectedMiscMagic:5:0:-1:9001:0;BossPhysical:5:-1:3584:0:0;Normal:5:0:-1:0:0;Normal:5:1:1840:0:0;SelectedMiscMagic:5:1:-1:9001:0;SelectedMiscMagic:5:1:-1:9003:0;SelectedMiscMagic:5:1:-1:274:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;SelectedMiscMagic:5:5:-1:9002:0;SelectedMiscMagic:5:5:-1:274:0|1494520163", + "E|PAL3A|low-7325|1|0,1,5,6||5|0||0||0|7325||0|RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2560:0:0;RecoverBigMagic:5:-1:2560:0:0|1924036713", + "E|PAL3A|low-7325|1|0,1,5,6||5|0||0||0|7325|RecoverMagic|1|RecoverMagic:5:5:2400:0:1|1030492215", + "E|PAL3A|low-7325|107|0,1,5,6||5|0||0||0|7325||0|RecoverMagic:5:5:1600:0:0;RecoverBigMagic:5:-1:1600:0:0;Normal:5:0:1680:0:0;Normal:5:0:-1:0:0;RecoverMagic:5:5:1760:0:0;RecoverBigMagic:5:-1:1760:0:0;Normal:5:1:1840:0:0;AttackBigMagic:5:-1:-1:0:0;AttackMagic:5:1:-1:0:0;Normal:5:1:-1:0:0;RecoverMagic:5:5:2400:0:0;RecoverBigMagic:5:-1:2400:0:0;RecoverMagic:5:5:2560:0:0;RecoverBigMagic:5:-1:2560:0:0|2042807014", + "E|PAL3A|low-7325|107|0,1,5,6||5|0||0||0|7325|RecoverMagic|1|RecoverMagic:5:5:1600:0:1|25430402", + "D|PAL3A|0,1,2,3,5,6,7,8|100,100,100,100,100,100,100,100|0:100,100,100,100,100,80,100,100,100,100;1:100,100,100,100,100,80,100,100,100,100;2:100,100,100,100,100,80,100,100,100,100;3:100,100,100,100,100,80,100,100,100,100;5:100,100,100,100,100,80,100,100,100,100;6:100,100,100,100,100,80,100,100,100,100;7:100,100,100,100,100,80,100,100,100,100;8:100,100,100,100,100,80,100,100,100,100|100,110,100,100,100,0,100,100,100,100|100,110,100,100,100,100,100,100,100,100", + "D|PAL3A|0,1,2,3,5,6,7,8|50,49,25,24,50,49,25,24|0:100,100,100,100,100,80,100,100,100,100;1:100,40,100,100,100,40,100,100,100,100;2:100,40,100,100,100,40,100,100,100,100;3:100,10,100,100,100,10,100,100,100,100;5:100,100,100,100,100,80,100,100,100,100;6:100,40,100,100,100,40,100,100,100,100;7:100,40,100,100,100,40,100,100,100,100;8:100,10,100,100,100,10,100,100,100,100|100,50,100,100,100,60,100,100,100,100|100,50,100,100,100,40,100,100,100,100", + "D|PAL3A|0,1,2,3,5,6,7,8|0,0,100,100,0,0,100,100|0:100,40,0,100,100,40,100,100,100,100;1:100,40,0,100,100,40,100,100,100,100;2:100,100,100,100,100,80,100,100,100,100;3:100,100,100,100,100,80,100,100,100,100;5:100,40,0,100,100,40,100,100,100,100;6:100,40,0,100,100,40,100,100,100,100;7:100,100,100,100,100,80,100,100,100,100;8:100,100,100,100,100,80,100,100,100,100|100,70,100,100,100,40,100,100,100,100|100,70,100,100,100,60,100,100,100,100", + "D|PAL3A|0,1,2,3,5,6,7,8|25,25,25,25,25,25,25,25|0:100,40,100,100,100,40,100,100,100,100;1:100,40,100,100,100,40,100,100,100,100;2:100,40,100,100,100,40,100,100,100,100;3:100,40,100,100,100,40,100,100,100,100;5:100,40,100,100,100,40,100,100,100,100;6:100,40,100,100,100,40,100,100,100,100;7:100,40,100,100,100,40,100,100,100,100;8:100,40,100,100,100,40,100,100,100,100|100,30,100,100,100,80,100,100,100,100|100,30,100,100,100,20,100,100,100,100", + "B|PAL3A|738|100|100|0", + "B|PAL3A|739|99|100|0", + "B|PAL3A|739|100|100|1", + "B|PAL3A|739|0|100|0", + "F|PAL3A|20,30|100,1000||1|Normal:0:6:-1:0:1|1", + "F|PAL3A|20,20|100,100||1|Normal:0:5:-1:0:1|1", + "F|PAL3A|50,50|100,100||1|Normal:0:5:-1:0:1|1", + "F|PAL3A|10,10|100,100||1|Normal:0:5:-1:0:1|1", + "F|PAL3A|70,70|100,100||1|Normal:0:5:-1:0:1|1", + "F|PAL3A|20,10|100,100|6|1|Normal:0:5:-1:0:1|1", + "F|PAL3A|20,10|100,100||1|Normal:0:6:-1:0:1|1", + "F|PAL3A|0,0|100,100||0||1", + "F|PAL3A|200,300|100,100||1|Normal:0:5:-1:0:1|2745024", + "A|PAL3A|0|0|0|0,0,0,0,0,0;0,0,0,0,0,0;0,0,0,0,0,0;0,0,0,0,0,0;0,0,0,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0|0", + "A|PAL3A|0|0|1|0,0,0,0,1,0;0,0,0,0,1,0;0,0,0,0,1,0;0,0,0,0,1,0;0,0,0,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0|0", + "A|PAL3A|0|1|0|1,1,1,1,0,1;1,1,1,1,0,1;1,1,1,1,0,1;1,1,1,1,0,1;1,1,1,1,0,1;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0|1", + "A|PAL3A|0|1|1|1,1,1,1,1,1;1,1,1,1,1,1;1,1,1,1,1,1;1,1,1,1,1,1;1,1,1,1,1,1;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0|1", + "A|PAL3A|1|0|1|1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0;1,0,1,0,1,0|0", + "A|PAL3A|1|1|0|1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0;1,0,1,0,0,0|1", + "S|PAL3A|attack|0|-25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|0|-25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|0|-25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|0|0|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|0|0|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|0|0|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|0|25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|0|25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|0|25|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|0|26|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|0|26|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9002|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|0|26|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|0|80|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|0|80|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|0|80|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|0|250|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|0|250|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|0|250|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|0|1000|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400||9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|0|1000|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|0|1000|9001,2,3,-10;9002,2,3,-40;9003,2,3,-100;9004,2,3,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|1|-25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|1|-25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|1|-25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|1|0|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|1|0|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|1|0|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|1|25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|1|25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|1|25|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|1|26|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|1|26|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9002|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|1|26|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|1|80|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|1|80|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|1|80|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|1|250|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|1|250|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|1|250|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|attack|1|1000|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400||9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|attack|1|1000|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|attack|1|1000|9001,2,4,-10;9002,2,4,-40;9003,2,4,-100;9004,2,4,-400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|0|-25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|0|-25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|0|-25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|0|0|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|0|0|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|0|0|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|0|25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|0|25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|0|25|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|0|26|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|0|26|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9002|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|0|26|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|0|80|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|0|80|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|0|80|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|0|250|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|0|250|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|0|250|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|0|1000|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400||9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|0|1000|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|0|1000|9001,3,1,10;9002,3,1,40;9003,3,1,100;9004,3,1,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|1|-25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|1|-25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|1|-25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|1|0|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|1|0|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|1|0|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|1|25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9001|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|1|25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9001|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|1|25|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|1|26|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9002|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|1|26|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9002|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|1|26|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|1|80|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|1|80|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|1|80|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|1|250|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9003|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|1|250|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|1|250|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover|1|1000|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400||9004|9001:1,9002:1,9003:1,9004:1", + "S|PAL3A|recover|1|1000|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9004|9003|9001:1,9002:1,9003:1,9004:0", + "S|PAL3A|recover|1|1000|9001,3,2,10;9002,3,2,40;9003,3,2,100;9004,3,2,400|9001,9002,9003|9004|9001:0,9002:0,9003:0,9004:1", + "S|PAL3A|recover-mixed|0|25|9001,3,1,10;9002,3,1,-20;9003,3,3,40;9004,3,1,0||9001|9001:1,9002:1,9004:1", + "S|PAL3A|recover-mixed|0|25|9001,3,1,40;9002,3,1,10;9003,3,3,100;9004,3,1,400||9001|9001:1,9002:1,9004:1", + "S|PAL3A|recover-mixed|0|25|9001,3,1,10;9002,3,1,40;9003,3,3,100;9004,3,1,400||9001|9001:1,9002:1,9004:1", + "T|PAL3A|1,2,3|9001|1", + "T|PAL3A|1,2,3|9002|2", + "T|PAL3A|1,2,3|9003|3", + "T|PAL3A|1,2,3|9004|4", + "T|PAL3A|1,2,3|9999|0", + "T|PAL3A|1,2,3|207|1", + "T|PAL3A|1,2,3|215|1", + "T|PAL3A|1,2,3|224|1", + "T|PAL3A|1,2,3|232|1", + "T|PAL3A|1,2,3|240|1", + "T|PAL3A|0,0,0|9001|0", + "T|PAL3A|0,0,0|9002|0", + "T|PAL3A|0,0,0|9003|0", + "T|PAL3A|0,0,0|9004|4", + "T|PAL3A|0,0,0|9999|0", + "T|PAL3A|0,0,0|207|1", + "T|PAL3A|0,0,0|215|1", + "T|PAL3A|0,0,0|224|1", + "T|PAL3A|0,0,0|232|1", + "T|PAL3A|0,0,0|240|1", + "T|PAL3A|4,4,4|9001|4", + "T|PAL3A|4,4,4|9002|4", + "T|PAL3A|4,4,4|9003|4", + "T|PAL3A|4,4,4|9004|4", + "T|PAL3A|4,4,4|9999|0", + "T|PAL3A|4,4,4|207|1", + "T|PAL3A|4,4,4|215|1", + "T|PAL3A|4,4,4|224|1", + "T|PAL3A|4,4,4|232|1", + "T|PAL3A|4,4,4|240|1", + "T|PAL3A|255,128,17|9001|255", + "T|PAL3A|255,128,17|9002|128", + "T|PAL3A|255,128,17|9003|17", + "T|PAL3A|255,128,17|9004|4", + "T|PAL3A|255,128,17|9999|0", + "T|PAL3A|255,128,17|207|1", + "T|PAL3A|255,128,17|215|1", + "T|PAL3A|255,128,17|224|1", + "T|PAL3A|255,128,17|232|1", + "T|PAL3A|255,128,17|240|1", + "Q|PAL3A|debuff|1,2,0,1|1|9004|2745024|9001:1,9004:1", + "Q|PAL3A|debuff|1,2,0,1|12345|9001|2644521496|9001:1,9004:1", + "Q|PAL3A|debuff|0,0,0,1|1|9004|2745024|9004:1", + "Q|PAL3A|debuff|0,0,0,1|12345|9004|2644521496|9004:1", + "Q|PAL3A|debuff|2,2,0,0|1|0|1|", + "Q|PAL3A|debuff|2,2,0,0|12345|0|12345|", + "Q|PAL3A|buff|1,2,0,1|1|9004|2745024|9001:1,9004:1", + "Q|PAL3A|buff|1,2,0,1|12345|9001|2644521496|9001:1,9004:1", + "Q|PAL3A|buff|0,0,0,1|1|9004|2745024|9004:1", + "Q|PAL3A|buff|0,0,0,1|12345|9004|2644521496|9004:1", + "Q|PAL3A|buff|2,2,0,0|1|0|1|", + "Q|PAL3A|buff|2,2,0,0|12345|0|12345|", + "Q|PAL3A|poison|1,2,0,1|1|9004|2745024|9001:1,9002:1,9004:1", + "Q|PAL3A|poison|1,2,0,1|12345|9001|2644521496|9001:1,9002:1,9004:1", + "Q|PAL3A|poison|0,0,0,1|1|9004|2745024|9004:1", + "Q|PAL3A|poison|0,0,0,1|12345|9004|2644521496|9004:1", + "Q|PAL3A|poison|2,2,0,0|1|9002|2745024|9001:1,9002:1", + "Q|PAL3A|poison|2,2,0,0|12345|9001|2644521496|9001:1,9002:1", + "R|PAL3A|259|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|AllTargetsDead;Submit:259:8", + "R|PAL3A|259|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|AllTargetsDead;Submit:259:8", + "R|PAL3A|259|1|1|0|1|6|1|6|0,0,0,0,0,0,0,0,0,0,0|AllTargetsDead;Pick:2:0;ExpandRange;Submit:259:6", + "R|PAL3A|259|1|0|1|0|1|1|1|0,0,0,0,0,0,0,0,0,0,0|AllTargetsDead;Pick:2:0;ExpandRange;Submit:259:1", + "R|PAL3A|259|1|1|0|1|-1|0|4294967295|0,0,0,0,0,0,0,0,0,0,0|AllTargetsDead;Pick:2:0", + "R|PAL3A|260|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;AllTargetsDead;Submit:260:8", + "R|PAL3A|260|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;FallbackPlayerNormal", + "R|PAL3A|260|1|1|0|1|6|1|6|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:0;ExpandRange;Submit:260:6", + "R|PAL3A|260|1|0|1|0|1|1|1|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:1:;ExpandRange;Submit:260:1", + "R|PAL3A|260|1|1|0|1|-1|0|4294967295|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:0", + "R|PAL3A|261|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;AllTargetsDead;Submit:261:8", + "R|PAL3A|261|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;FallbackPlayerNormal", + "R|PAL3A|261|1|1|0|1|6|1|6|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:;ExpandRange;Submit:261:6", + "R|PAL3A|261|1|0|1|0|1|1|1|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:1:;ExpandRange;Submit:261:1", + "R|PAL3A|261|1|1|0|1|-1|0|4294967295|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:", + "R|PAL3A|262|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;AllTargetsDead;Submit:262:8", + "R|PAL3A|262|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;FallbackPlayerNormal", + "R|PAL3A|262|1|1|0|1|6|1|6|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:0;ExpandRange;Submit:262:6", + "R|PAL3A|262|1|0|1|0|1|1|1|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:1:;ExpandRange;Submit:262:1", + "R|PAL3A|262|1|1|0|1|-1|0|4294967295|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;IsAttack;Pick:2:0", + "R|PAL3A|265|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:265:8", + "R|PAL3A|265|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:265:8", + "R|PAL3A|265|1|1|0|1|6|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:265:8", + "R|PAL3A|265|1|0|1|0|1|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:265:8", + "R|PAL3A|265|1|1|0|1|-1|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:265:8", + "R|PAL3A|267|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:267:8", + "R|PAL3A|267|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:267:8", + "R|PAL3A|267|1|1|0|1|6|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:267:8", + "R|PAL3A|267|1|0|1|0|1|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:267:8", + "R|PAL3A|267|1|1|0|1|-1|1|8|1,1,1,1,1,1,1,1,1,1,1|Submit:267:8", + "R|PAL3A|271|1|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;AllTargetsDead;Submit:271:8", + "R|PAL3A|271|0|0|0|1|5|1|8|1,1,1,1,1,1,1,1,1,1,1|CanCast;FallbackPlayerNormal", + "R|PAL3A|271|1|1|0|1|6|1|6|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;Pick:2:0;Submit:271:6", + "R|PAL3A|271|1|0|1|0|1|1|1|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;Pick:2:0;Submit:271:1", + "R|PAL3A|271|1|1|0|1|-1|0|4294967295|0,0,0,0,0,0,0,0,0,0,0|CanCast;AllTargetsDead;Pick:2:0", + }; + + public static IEnumerable NativeCases() + { + for (int index = 0; index < NativeVectors.Length; index++) + yield return new TestCaseData(NativeVectors[index]).SetName("OriginalAiNative_" + index.ToString(CultureInfo.InvariantCulture)); + } + + private static int Number(string value) => int.Parse(value, CultureInfo.InvariantCulture); + + private static int[] Numbers(string value) => value.Length == 0 ? Array.Empty() : value.Split(',').Select(Number).ToArray(); + + private static string Join(IEnumerable values) => string.Join(",", values); + + private static (BattleAi Ai, Port Port, BattleRandom Random) Create(string variant, int seed = 1) + { + var random = new BattleRandom(seed, variant); + var port = new Port(); + var ai = new BattleAi(variant == "PAL3A", random, port); + port.Ai = ai; + return (ai, port, random); + } + + private static void SetRoles(BattleAi ai, int[] valid, int[] hp = null) + { + for (int index = 0; index < valid.Length; index++) + { + int value = hp == null ? 100 : hp[index]; + ai.Roles[valid[index]] = new BattleAiRole { Valid = true, Alive = value > 0, Hp = value, MaxHp = 100 }; + } + } + + [TestCaseSource(nameof(NativeCases))] + public void MatchesReleasedExecutable(string encoded) + { + string[] data = encoded.Split('|'); + string variant = data[1]; + if (data[0] == "H") + { + Assert.That(BattleAi.HpState(Number(data[2]), Number(data[3])), Is.EqualTo(Number(data[4]))); + return; + } + if (data[0] == "E") + { + var (ai, port, random) = Create(variant, Number(data[3])); + SetRoles(ai, Numbers(data[4])); + foreach (string pair in data[5].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) + { + int[] parts = pair.Split(':').Select(Number).ToArray(); + int offset = parts[0]; + if (offset < 0xd10) + { + int value = offset - 0x630; + ai.Demand[value / 160, value % 160 / 16].Satisfy = parts[1]; + } + else if (offset < 0xdb0) + ai.EnemyDemand[(offset - 0xd10) / 16].Satisfy = parts[1]; + else + ai.FriendDemand[(offset - 0xdb0) / 16].Satisfy = parts[1]; + } + int source = Number(data[6]); + ai.Roles[source].Chaos = data[7] == "18"; + ai.Roles[source].Madness = data[7] == "19"; + foreach (int fled in Numbers(data[8])) + ai.Roles[fled].Fled = true; + ai.Roles[source].Boss = data[9] == "1"; + if (data[10].Length > 0) + { + ai.FriendDemand[5].Satisfy = 40; + port.Scene = Number(data[11]); + ai.Roles[source].Skills = Numbers(data[10]).Select((id, index) => + { + var operations = new int[32]; + if (index < 3) + operations[index == 0 ? 6 : index == 1 ? 5 : 0] = 1; + return new BattleAiSkill { Id = id, Type = 1, Range = 3, StateOperations = operations }; + }).ToArray(); + } + ai.Roles[source].Identity = Number(data[12]); + port.Success = data[13]; + bool actual = data[2] switch + { + "well" => ai.HandleEnemyState(source, 0), + "weak" => ai.HandleEnemyState(source, 1), + "low" or "low-7325" => ai.HandleEnemyState(source, 2), + "chaos" => ai.HandleEnemyChaos(source), + "negative" => ai.HandleFriendNegative(source), + "affirmative" => ai.HandleFriendAffirmative(source), + _ => throw new ArgumentException(data[2]) + }; + Assert.That(actual, Is.EqualTo(data[14] == "1")); + Assert.That(string.Join(";", port.Attempts), Is.EqualTo(data[15])); + Assert.That(random.State.ToString(CultureInfo.InvariantCulture), Is.EqualTo(data[16])); + return; + } + if (data[0] == "D") + { + var (ai, _, _) = Create(variant); + SetRoles(ai, Numbers(data[2]), Numbers(data[3])); + ai.CheckDemands(); + foreach (string row in data[4].Split(';')) + { + string[] parts = row.Split(':'); + int role = Number(parts[0]); + Assert.That(Enumerable.Range(0, 10).Select(kind => ai.Demand[role, kind].Satisfy), Is.EqualTo(Numbers(parts[1]))); + } + Assert.That(ai.EnemyDemand.Select(demand => demand.Satisfy), Is.EqualTo(Numbers(data[5]))); + Assert.That(ai.FriendDemand.Select(demand => demand.Satisfy), Is.EqualTo(Numbers(data[6]))); + return; + } + if (data[0] == "B") + { + var (ai, port, _) = Create(variant); + ai.Roles[5].Identity = Number(data[2]); + ai.Roles[5].Mp = Number(data[3]); + ai.Roles[5].MaxMp = Number(data[4]); + port.Success = "SpecAI"; + Assert.That(ai.HandleSpecialBoss(5), Is.EqualTo(data[5] == "1")); + Assert.That(port.LastAbility, Is.EqualTo(data[5] == "1" ? 7709 : 0)); + return; + } + if (data[0] == "F") + { + var (ai, port, random) = Create(variant); + SetRoles(ai, new[] { 0, 5, 6 }, new[] { 100 }.Concat(Numbers(data[2])).ToArray()); + int[] maxima = Numbers(data[3]); + ai.Roles[5].MaxHp = maxima[0]; + ai.Roles[6].MaxHp = maxima[1]; + foreach (int fled in Numbers(data[4])) + ai.Roles[fled].Fled = true; + port.Success = "Normal"; + Assert.That(ai.PlayerNormal(0, false), Is.EqualTo(data[5] == "1")); + Assert.That(string.Join(";", port.Attempts), Is.EqualTo(data[6])); + Assert.That(random.State.ToString(CultureInfo.InvariantCulture), Is.EqualTo(data[7])); + return; + } + if (data[0] == "A") + { + var (ai, _, _) = Create(variant); + foreach (BattleAiRole role in ai.Roles) + role.Profile = new BattleAiProfile { Attack = true, Skill = true, Negative = data[4] == "1" }; + ai.SetAutomatic(data[3] == "1", data[2] == "1"); + Assert.That(ai.Automatic, Is.EqualTo(data[6] == "1")); + Assert.That(string.Join(";", ai.Roles.Select(role => Join(new[] { role.Profile.Attack, role.Profile.Magic, role.Profile.Skill, role.Profile.Item, role.Profile.Negative, role.Profile.Enabled }.Select(value => value ? 1 : 0)))), Is.EqualTo(data[5])); + return; + } + if (data[0] == "S") + { + var (ai, port, _) = Create(variant); + SetRoles(ai, new[] { 5 }); + ai.Roles[5].Skills = data[5].Split(';').Select(row => + { + int[] fields = Numbers(row); + return new BattleAiSkill { Id = fields[0], Type = fields[1], Range = fields[2], Power = fields[3] }; + }).ToArray(); + port.Denied = new HashSet(Numbers(data[6])); + Assert.That(ai.SelectMagic(5, data[2] == "attack", data[3] == "1", Number(data[4])), Is.EqualTo(Number(data[7]))); + Assert.That(string.Join(",", port.Eligibility), Is.EqualTo(data[8])); + return; + } + if (data[0] == "T") + { + var (ai, _, _) = Create(variant); + int[] levels = Numbers(data[2]); + ai.Roles[5].Skills = Enumerable.Range(0, 4).Select(index => new BattleAiSkill { Id = 9001 + index, Level = index < 3 ? levels[index] : 1 }).ToArray(); + Assert.That(ai.MonsterSkillLevel(5, Number(data[3])), Is.EqualTo(Number(data[4]))); + return; + } + if (data[0] == "Q") + { + var (ai, port, random) = Create(variant, Number(data[4])); + SetRoles(ai, new[] { 5 }); + int[] operations = Numbers(data[3]); + int state = data[2] == "debuff" ? 6 : data[2] == "buff" ? 5 : 0; + ai.Roles[5].Skills = Enumerable.Range(0, 4).Select(index => + { + var values = new int[32]; + values[state] = operations[index]; + return new BattleAiSkill { Id = 9001 + index, StateOperations = values }; + }).ToArray(); + Assert.That(ai.QueryStatusMagic(5, (BattleAiStatusQuery)Enum.Parse(typeof(BattleAiStatusQuery), data[2], true)), Is.EqualTo(Number(data[5]))); + Assert.That(random.State.ToString(CultureInfo.InvariantCulture), Is.EqualTo(data[6])); + Assert.That(string.Join(",", port.Eligibility), Is.EqualTo(data[7])); + return; + } + if (data[0] == "R") + { + var (ai, port, _) = Create(variant); + SetRoles(ai, new[] { 0, 5 }); + port.RepeatCan = data[3] == "1"; + port.RepeatDead = data[4] == "1"; + ai.NewRole[0] = data[5] == "1"; + port.RepeatAttack = data[6] == "1"; + port.RepeatTarget = Number(data[7]); + int kind = Number(data[2]); + port.Fallback = !port.RepeatCan && kind is 0x104 or 0x105 or 0x106 or 0x10f || variant == "PAL3" && kind == 0x10f; + var command = new BattleAiCommand { Kind = kind, AbilityId = 301, Source = 0, Target = 8, TargetMask = Enumerable.Repeat(true, 11).ToArray() }; + Assert.That(ai.Repeat(0, command), Is.EqualTo(data[8] == "1")); + Assert.That(unchecked((uint)command.Target).ToString(CultureInfo.InvariantCulture), Is.EqualTo(data[9])); + Assert.That(Join(command.TargetMask.Select(value => value ? 1 : 0)), Is.EqualTo(data[10])); + Assert.That(string.Join(";", port.Calls), Is.EqualTo(data[11])); + return; + } + Assert.Fail("Unknown native vector kind " + data[0]); + } + + [Test] + public void ActiveDemandProtectsItsValueUntilTheActionDisappears() + { + var (ai, port, _) = Create("PAL3"); + SetRoles(ai, new[] { 0 }, new[] { 10 }); + ai.Demand[0, 1].ActionId = 7; + port.Active = true; + ai.UpdateDemands(); + Assert.That(ai.Demand[0, 1].Satisfy, Is.EqualTo(100)); + Assert.That(ai.Demand[0, 1].Handled, Is.True); + port.Active = false; + ai.UpdateDemands(); + Assert.That(ai.Demand[0, 1].Handled, Is.False); + ai.UpdateDemands(); + Assert.That(ai.Demand[0, 1].Satisfy, Is.EqualTo(10)); + } + + [Test] + public void MadnessAndChaosPreserveIndependentCapabilityRules() + { + var (ai, _, _) = Create("PAL3"); + ai.Roles[0].Chaos = true; + Assert.That(ai.CapabilityEnabled(0, BattleAiAttemptKind.RecoverMagic), Is.True); + ai.Roles[0].Madness = true; + Assert.That(ai.CapabilityEnabled(0, BattleAiAttemptKind.RecoverMagic), Is.False); + Assert.That(ai.CapabilityEnabled(0, BattleAiAttemptKind.Normal), Is.True); + } + + private sealed class Port : BattleAiPort + { + public BattleAi Ai; + public string Success; + public int Scene, LastAbility; + public bool RepeatCan, RepeatDead, RepeatAttack, Fallback, Active; + public int RepeatTarget; + public HashSet Denied = new(); + public readonly List Attempts = new(); + public readonly List Eligibility = new(); + public readonly List Calls = new(); + + public override int SceneFiveSpiritMode => Scene; + + public override bool CanCast(int source, int skillId) + { + bool allowed = !Denied.Contains(skillId); + Eligibility.Add(skillId + ":" + (allowed ? 1 : 0)); + return allowed; + } + + public override long TryAttempt(BattleAiAttempt attempt) + { + if (Fallback) + { + Calls.Add("FallbackPlayerNormal"); + return 7; + } + bool accepted = attempt.Kind.ToString() == Success && !(attempt.Kind == BattleAiAttemptKind.Normal && attempt.Source == attempt.Target); + LastAbility = attempt.AbilityId; + string prefix = attempt.Kind + ":" + attempt.Source; + Attempts.Add(attempt.Kind == BattleAiAttemptKind.SpecAI ? prefix + ":" + (accepted ? 1 : 0) + : prefix + ":" + attempt.Target + ":" + DemandOffset(attempt.Demand) + ":" + attempt.AbilityId + ":" + (accepted ? 1 : 0)); + return accepted ? 7 : -1; + } + + private int DemandOffset(BattleAiDemand demand) + { + if (demand == null) + return -1; + for (int role = 0; role < 11; role++) + { + for (int kind = 0; kind < 10; kind++) + { + if (ReferenceEquals(Ai.Demand[role, kind], demand)) + return 0x630 + role * 160 + kind * 16; + } + } + for (int kind = 0; kind < 10; kind++) + { + if (ReferenceEquals(Ai.EnemyDemand[kind], demand)) + return 0xd10 + kind * 16; + if (ReferenceEquals(Ai.FriendDemand[kind], demand)) + return 0xdb0 + kind * 16; + } + throw new ArgumentException("Unknown demand."); + } + + public override bool IsActionActive(long actionId) => Active; + + public override bool CanRepeat(int source, BattleAiCommand command) + { + Calls.Add("CanCast"); + return RepeatCan; + } + + public override bool AllRepeatTargetsDead(BattleAiCommand command) + { + Calls.Add("AllTargetsDead"); + return RepeatDead; + } + + public override bool IsRepeatAttack(BattleAiCommand command) + { + Calls.Add("IsAttack"); + return RepeatAttack; + } + + public override int PickRepeatTarget(int source, bool enemy, bool filterBackRole) + { + Calls.Add("Pick:" + (enemy ? 2 : 1) + ":" + (filterBackRole ? source.ToString(CultureInfo.InvariantCulture) : "")); + return RepeatTarget; + } + + public override void ExpandRepeatRange(BattleAiCommand command) => Calls.Add("ExpandRange"); + + public override long SubmitRepeat(BattleAiCommand command) + { + Calls.Add("Submit:" + command.Kind + ":" + unchecked((uint)command.Target)); + return 7; + } + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleAiTests.cs.meta b/Assets/Tests/Battle/Editor/BattleAiTests.cs.meta new file mode 100644 index 00000000..e24ada93 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleAiTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8dec184c1caf4c05a2fb6321633c7298 diff --git a/Assets/Tests/Battle/Editor/BattleBodyAnimationBindingTests.cs b/Assets/Tests/Battle/Editor/BattleBodyAnimationBindingTests.cs new file mode 100644 index 00000000..42a77898 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleBodyAnimationBindingTests.cs @@ -0,0 +1,143 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleBodyAnimationBindingTests + { + // Executed installed PAL3 gbActor.Update + MVAction.GetTriggeredEvent. + // The synthetic fixtures contain no original resource content. A has no + // engine DLL locally; its published Role.Update supplies rate 1 or .65. + private static IEnumerable EngineGoldens() + { + yield return new TestCaseData(96u, 0.0f, false, new uint[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new string[] { "", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(96u, 0.0f, true, new uint[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new string[] { "", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(96u, 0.65f, false, new uint[] { 62, 124, 186, 248, 310, 372, 434, 496, 558, 620, 682, 744 }, new string[] { "257,258", "over,259,260,256,257", "258", "over,259,260,256,257", "over,258,259,260,256,257", "258", "over,259,260,256,257", "over,258,259,260,256,257", "258", "over,259,260,256,257", "over,258,259,260,256,257", "258" }); + yield return new TestCaseData(96u, 0.65f, true, new uint[] { 62, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92 }, new string[] { "257,258", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(96u, 1.0f, false, new uint[] { 96, 192, 288, 384, 480, 576, 672, 768, 864, 960, 1056, 1152 }, new string[] { "over,257,258,259,260,256", "over,257,258,259,260,256", "over,257,258,259,260,256", "over,257,258,259,260,256", "over,257,258,259,260,256", "over,257,258,259,260,256", "over,257,258,259,260,256", "over,257,258,259,260,256", "over,257,258,259,260,256", "over,257,258,259,260,256", "over,257,258,259,260,256", "over,257,258,259,260,256" }); + yield return new TestCaseData(96u, 1.0f, true, new uint[] { 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92 }, new string[] { "over", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(96u, 1.3f, true, new uint[] { 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92 }, new string[] { "over", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(125u, 0.0f, false, new uint[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new string[] { "", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(125u, 0.0f, true, new uint[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new string[] { "", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(125u, 0.65f, false, new uint[] { 62, 124, 186, 248, 310, 372, 434, 496, 558, 620, 682, 744 }, new string[] { "257,258", "259", "over,260,256,257", "258,259", "over,260,256,257", "258,259", "over,260,256,257", "258,259", "over,260,256,257", "258,259", "over,260,256,257", "258,259" }); + yield return new TestCaseData(125u, 0.65f, true, new uint[] { 62, 124, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121 }, new string[] { "257,258", "259", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(125u, 1.0f, false, new uint[] { 96, 192, 288, 384, 480, 576, 672, 768, 864, 960, 1056, 1152 }, new string[] { "257,258,259", "over,260,256,257,258", "over,259,260,256,257", "over,258,259,260,256,257", "258,259", "over,260,256,257,258", "over,259,260,256,257", "over,258,259,260,256,257", "258,259", "over,260,256,257,258", "over,259,260,256,257", "over,258,259,260,256,257" }); + yield return new TestCaseData(125u, 1.0f, true, new uint[] { 96, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121 }, new string[] { "257,258,259", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(125u, 1.3f, false, new uint[] { 124, 248, 372, 496, 620, 744, 868, 992, 1116, 1240, 1364, 1488 }, new string[] { "257,258,259", "over,260,256,257,258,259", "over,260,256,257,258,259", "over,260,256,257,258,259", "over,260,256,257,258,259", "over,260,256,257,258,259", "over,260,256,257,258,259", "over,260,256,257,258,259", "over,260,256,257,258,259", "over,260,256,257,258,259", "over,260,256,257,258,259", "over,260,256,257,258,259" }); + yield return new TestCaseData(125u, 1.3f, true, new uint[] { 124, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121 }, new string[] { "257,258,259", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(240u, 0.0f, false, new uint[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new string[] { "", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(240u, 0.0f, true, new uint[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new string[] { "", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(240u, 0.65f, false, new uint[] { 62, 124, 186, 248, 310, 372, 434, 496, 558, 620, 682, 744 }, new string[] { "257,258", "259", "", "over,260,256,257", "258", "259", "", "over,260,256,257", "258", "259", "", "over,260,256,257" }); + yield return new TestCaseData(240u, 0.65f, true, new uint[] { 62, 124, 186, 236, 236, 236, 236, 236, 236, 236, 236, 236 }, new string[] { "257,258", "259", "", "over", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(240u, 1.0f, false, new uint[] { 96, 192, 288, 384, 480, 576, 672, 768, 864, 960, 1056, 1152 }, new string[] { "257,258,259", "", "over,260,256,257", "258,259", "over,260,256", "257,258,259", "", "over,260,256,257", "258,259", "over,260,256", "257,258,259", "" }); + yield return new TestCaseData(240u, 1.0f, true, new uint[] { 96, 192, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236 }, new string[] { "257,258,259", "", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(240u, 1.3f, false, new uint[] { 124, 248, 372, 496, 620, 744, 868, 992, 1116, 1240, 1364, 1488 }, new string[] { "257,258,259", "over,260,256,257", "258,259", "over,260,256,257", "258,259", "over,260,256,257", "258,259", "over,260,256,257", "258,259", "over,260,256,257", "258,259", "over,260,256,257" }); + yield return new TestCaseData(240u, 1.3f, true, new uint[] { 124, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236, 236 }, new string[] { "257,258,259", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(480u, 0.0f, false, new uint[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new string[] { "", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(480u, 0.0f, true, new uint[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new string[] { "", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(480u, 0.65f, false, new uint[] { 62, 124, 186, 248, 310, 372, 434, 496, 558, 620, 682, 744 }, new string[] { "257,258", "259", "", "", "", "", "", "over,260,256,257", "258", "259", "", "" }); + yield return new TestCaseData(480u, 0.65f, true, new uint[] { 62, 124, 186, 248, 310, 372, 434, 476, 476, 476, 476, 476 }, new string[] { "257,258", "259", "", "", "", "", "", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(480u, 1.0f, false, new uint[] { 96, 192, 288, 384, 480, 576, 672, 768, 864, 960, 1056, 1152 }, new string[] { "257,258,259", "", "", "", "over,260,256", "257,258,259", "", "", "", "over,260,256", "257,258,259", "" }); + yield return new TestCaseData(480u, 1.0f, true, new uint[] { 96, 192, 288, 384, 476, 476, 476, 476, 476, 476, 476, 476 }, new string[] { "257,258,259", "", "", "", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(480u, 1.3f, false, new uint[] { 124, 248, 372, 496, 620, 744, 868, 992, 1116, 1240, 1364, 1488 }, new string[] { "257,258,259", "", "", "over,260,256,257", "258,259", "", "", "over,260,256,257", "258,259", "", "", "over,260,256,257" }); + yield return new TestCaseData(480u, 1.3f, true, new uint[] { 124, 248, 372, 476, 476, 476, 476, 476, 476, 476, 476, 476 }, new string[] { "257,258,259", "", "", "over", "over", "over", "over", "over", "over", "over", "over", "over" }); + yield return new TestCaseData(4800u, 0.0f, false, new uint[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new string[] { "", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(4800u, 0.0f, true, new uint[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new string[] { "", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(4800u, 0.65f, false, new uint[] { 62, 124, 186, 248, 310, 372, 434, 496, 558, 620, 682, 744 }, new string[] { "257,258", "259", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(4800u, 0.65f, true, new uint[] { 62, 124, 186, 248, 310, 372, 434, 496, 558, 620, 682, 744 }, new string[] { "257,258", "259", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(4800u, 1.0f, false, new uint[] { 96, 192, 288, 384, 480, 576, 672, 768, 864, 960, 1056, 1152 }, new string[] { "257,258,259", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(4800u, 1.0f, true, new uint[] { 96, 192, 288, 384, 480, 576, 672, 768, 864, 960, 1056, 1152 }, new string[] { "257,258,259", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(4800u, 1.3f, false, new uint[] { 124, 248, 372, 496, 620, 744, 868, 992, 1116, 1240, 1364, 1488 }, new string[] { "257,258,259", "", "", "", "", "", "", "", "", "", "", "" }); + yield return new TestCaseData(4800u, 1.3f, true, new uint[] { 124, 248, 372, 496, 620, 744, 868, 992, 1116, 1240, 1364, 1488 }, new string[] { "257,258,259", "", "", "", "", "", "", "", "", "", "", "" }); + } + + [TestCaseSource(nameof(EngineGoldens))] + public void ActorUpdateMatchesPublishedRawClockAndTriggerOrder(uint duration, float rate, bool once, uint[] times, string[] messages) + { + var markers = new[] + { + Marker(0, "256"), Marker(1, "257"), Marker(Math.Min(62u, duration), "258"), + Marker(Math.Min(96u, duration), "259"), Marker(duration, "260") + }; + var binding = new BattleBodyAnimationBinding(new BattlePhysicalAnimation("fixture", 100, 1, markers, duration), !once); + for (int index = 0; index < times.Length; index++) + { + binding.Advance(rate); + Assert.That(binding.GameBoxTime, Is.EqualTo(times[index]), "frame " + index); + Assert.That(Drain(binding), Is.EqualTo(messages[index]), "frame " + index); + } + } + + [Test] + public void UnknownMessageConsumesOneRolePassBeforeWork() + { + var animation = new BattlePhysicalAnimation("attack", 5, 1, new[] + { + Marker(1, "sound"), new BattlePhysicalMarker(0, BattlePhysicalMarkerKind.Work, 1, "work") + }); + var binding = new BattleBodyAnimationBinding(animation, false); + binding.Advance(); + binding.PopMessage(); + Assert.That(binding.LastPoppedMarker, Is.EqualTo(BattlePhysicalMarkerKind.Other)); + binding.PopMessage(); + Assert.That(binding.LastPoppedMarker, Is.EqualTo(BattlePhysicalMarkerKind.Work)); + } + + [Test] + public void FailedGotoAndResetKeepPendingMessagesButSuccessfulGotoClearsThem() + { + var animation = new BattlePhysicalAnimation("attack", 5, 1, new[] { Marker(1, "old1"), Marker(1, "old2") }); + var binding = new BattleBodyAnimationBinding(animation); + binding.Advance(); + binding.PopMessage(); + Assert.That(binding.TryPlay(null, false), Is.False); + Assert.That(binding.GameBoxTime, Is.EqualTo(96u)); + binding.Reset(); + Assert.That(binding.GameBoxTime, Is.Zero); + Assert.That(binding.PendingMessageCount, Is.EqualTo(1)); + Assert.That(binding.LastPoppedName, Is.EqualTo("old1")); + binding.TryPlay(animation, false); + Assert.That(binding.PendingMessageCount, Is.Zero); + Assert.That(binding.LastPoppedName, Is.EqualTo("old1")); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RealMessageOverridesEstimatedFlightMarkerTick(string variant) + { + var movement = new BattleMovement(variant, new BattleMovementPlan(BattleMovementKind.Fly, + new BattleMovementPoint(0, 0, 0), new BattleMovementPoint(100, 0, 0), 1, 3, 4)); + movement.Step(true, BattleMovementMessage.FlyUp); // activation ignores old clip's message + movement.Step(true, BattleMovementMessage.None); + Assert.That(movement.Position.X, Is.Zero); + movement.Step(true, BattleMovementMessage.FlyUp); + Assert.That(movement.Position.X, Is.GreaterThan(0)); + movement.Step(true, BattleMovementMessage.None); + movement.Step(true, BattleMovementMessage.None); + Assert.That(movement.Finished, Is.False); + movement.Step(true, BattleMovementMessage.Over); + Assert.That(movement.Finished, Is.True); + Assert.That(movement.Position.X, Is.EqualTo(100)); + } + + private static BattlePhysicalMarker Marker(uint tick, string name) => new(0, BattlePhysicalMarkerKind.Other, tick, name); + + private static string Drain(BattleBodyAnimationBinding binding) + { + var names = new List(); + while (binding.PendingMessageCount > 0) + { + binding.PopMessage(); + names.Add(binding.LastPoppedName); + } + return string.Join(",", names); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleBodyAnimationBindingTests.cs.meta b/Assets/Tests/Battle/Editor/BattleBodyAnimationBindingTests.cs.meta new file mode 100644 index 00000000..a276ac8f --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleBodyAnimationBindingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 456a963b7d4b4b019143d035e463523a diff --git a/Assets/Tests/Battle/Editor/BattleBodyAudioRulesTests.cs b/Assets/Tests/Battle/Editor/BattleBodyAudioRulesTests.cs new file mode 100644 index 00000000..1caa9bea --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleBodyAudioRulesTests.cs @@ -0,0 +1,882 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System.Collections.Generic; + using Battle; + using NUnit.Framework; + + public sealed class BattleBodyAudioRulesTests + { + // Frozen sound-port traces from published PAL3/PAL3A ProcAttack. + private static IEnumerable AttackGoldens() + { + yield return new TestCaseData("PAL3", 0, 1, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 1, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 1, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 1, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 1, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 1, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 2, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 2, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 2, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 2, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 2, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 2, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 3, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 3, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 3, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 3, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 3, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 3, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 4, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 4, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 4, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 4, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 4, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 4, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 5, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 5, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 5, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 5, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 5, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 5, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 6, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 6, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 6, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 6, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 6, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 6, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 7, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 7, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 7, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 7, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 7, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 7, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 8, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 8, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 8, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 8, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 8, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 8, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 9, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 9, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 9, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 9, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 9, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 9, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 10, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 10, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 10, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 10, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 10, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 0, 10, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 1, 1, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 1, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 1, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 1, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 1, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 1, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 2, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 2, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 2, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 2, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 2, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 2, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 3, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 3, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 3, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 3, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 3, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 3, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 4, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 4, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 4, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 4, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 4, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 4, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 5, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 5, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 5, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 5, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 5, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 5, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 6, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 6, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 6, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 6, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 6, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 6, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 7, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 7, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 7, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 7, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 7, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 7, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 8, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 8, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 8, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 8, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 8, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 8, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 9, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 9, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 9, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 9, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 9, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 9, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 10, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 10, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 10, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 10, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 10, false, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 1, 10, true, new string[] { "wd028", "wd028", null, null }); + yield return new TestCaseData("PAL3", 2, 1, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 1, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 1, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 1, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 1, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 1, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 2, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 2, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 2, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 2, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 2, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 2, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 3, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 3, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 3, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 3, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 3, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 3, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 4, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 4, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 4, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 4, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 4, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 4, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 5, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 5, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 5, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 5, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 5, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 5, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 6, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 6, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 6, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 6, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 6, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 6, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 7, false, new string[] { "wd030", "wd030", null, null }); + yield return new TestCaseData("PAL3", 2, 7, true, new string[] { "wd030", "wd030", null, null }); + yield return new TestCaseData("PAL3", 2, 7, false, new string[] { "wd030", "wd030", null, null }); + yield return new TestCaseData("PAL3", 2, 7, true, new string[] { "wd030", "wd030", null, null }); + yield return new TestCaseData("PAL3", 2, 7, false, new string[] { "wd030", "wd030", null, null }); + yield return new TestCaseData("PAL3", 2, 7, true, new string[] { "wd030", "wd030", null, null }); + yield return new TestCaseData("PAL3", 2, 8, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 8, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 8, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 8, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 8, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 8, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 9, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 9, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 9, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 9, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 9, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 9, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 10, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 10, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 10, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 10, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 10, false, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 2, 10, true, new string[] { null, "wd024", null, null }); + yield return new TestCaseData("PAL3", 3, 1, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 1, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 1, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 1, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 1, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 1, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 2, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 2, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 2, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 2, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 2, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 2, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 3, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 3, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 3, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 3, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 3, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 3, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 4, false, new string[] { "wd027", "wd027", null, null }); + yield return new TestCaseData("PAL3", 3, 4, true, new string[] { "wd027", "wd027", null, null }); + yield return new TestCaseData("PAL3", 3, 4, false, new string[] { "wd027", "wd027", null, null }); + yield return new TestCaseData("PAL3", 3, 4, true, new string[] { "wd027", "wd027", null, null }); + yield return new TestCaseData("PAL3", 3, 4, false, new string[] { "wd027", "wd027", null, null }); + yield return new TestCaseData("PAL3", 3, 4, true, new string[] { "wd027", "wd027", null, null }); + yield return new TestCaseData("PAL3", 3, 5, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 5, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 5, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 5, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 5, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 5, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 6, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 6, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 6, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 6, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 6, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 6, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 7, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 7, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 7, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 7, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 7, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 7, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 8, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 8, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 8, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 8, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 8, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 8, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 9, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 9, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 9, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 9, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 9, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 9, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 10, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 10, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 10, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 10, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 10, false, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 3, 10, true, new string[] { "wd026", "wd026", null, null }); + yield return new TestCaseData("PAL3", 4, 1, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 1, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 1, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 1, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 1, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 1, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 2, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 4, 2, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 4, 2, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 4, 2, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 4, 2, false, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 4, 2, true, new string[] { "wd025", "wd025", null, null }); + yield return new TestCaseData("PAL3", 4, 3, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 3, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 3, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 3, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 3, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 3, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 4, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 4, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 4, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 4, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 4, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 4, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 5, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 5, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 5, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 5, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 5, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 5, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 6, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 6, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 6, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 6, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 6, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 6, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 7, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 7, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 7, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 7, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 7, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 7, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 8, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 8, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 8, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 8, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 8, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 8, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 9, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 9, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 9, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 9, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 9, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 9, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 10, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 10, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 10, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 10, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 10, false, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", 4, 10, true, new string[] { "wd029", "wd029", null, null }); + yield return new TestCaseData("PAL3", -1, 1, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 1, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 1, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 1, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 1, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 1, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 2, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 2, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 2, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 2, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 2, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 2, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 3, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 3, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 3, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 3, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 3, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 3, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 4, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 4, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 4, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 4, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 4, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 4, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 5, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 5, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 5, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 5, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 5, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 5, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 6, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 6, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 6, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 6, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 6, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 6, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 7, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 7, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 7, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 7, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 7, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 7, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 8, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 8, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 8, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 8, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 8, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 8, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 9, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 9, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 9, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 9, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 9, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 9, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 10, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 10, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 10, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 10, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 10, false, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3", -1, 10, true, new string[] { "wd007", "wd007", null, null }); + yield return new TestCaseData("PAL3A", 0, 1, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 1, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 1, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 1, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 1, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 1, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 2, false, new string[] { null, null, null, null }); + yield return new TestCaseData("PAL3A", 0, 2, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 2, false, new string[] { null, null, null, null }); + yield return new TestCaseData("PAL3A", 0, 2, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 2, false, new string[] { null, null, null, null }); + yield return new TestCaseData("PAL3A", 0, 2, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 3, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 3, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 3, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 3, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 3, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 3, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 4, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 4, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 4, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 4, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 4, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 4, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 5, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 5, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 5, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 5, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 5, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 5, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 6, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 6, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 6, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 6, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 6, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 6, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 7, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 7, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 7, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 7, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 7, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 7, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 8, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 8, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 8, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 8, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 8, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 8, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 9, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 9, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 9, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 9, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 9, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 9, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 10, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 10, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 10, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 10, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 10, false, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 0, 10, true, new string[] { "wd025", "wd025", "wd025", "wd025" }); + yield return new TestCaseData("PAL3A", 1, 1, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 1, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 1, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 1, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 1, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 1, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 2, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 2, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 2, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 2, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 2, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 2, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 3, false, new string[] { "wd026", "wd026", "wd026", "wd026" }); + yield return new TestCaseData("PAL3A", 1, 3, true, new string[] { "wd026", "wd026", "wd026", "wd026" }); + yield return new TestCaseData("PAL3A", 1, 3, false, new string[] { "wd026", "wd026", "wd026", "wd026" }); + yield return new TestCaseData("PAL3A", 1, 3, true, new string[] { "wd026", "wd026", "wd026", "wd026" }); + yield return new TestCaseData("PAL3A", 1, 3, false, new string[] { "wd026", "wd026", "wd026", "wd026" }); + yield return new TestCaseData("PAL3A", 1, 3, true, new string[] { "wd026", "wd026", "wd026", "wd026" }); + yield return new TestCaseData("PAL3A", 1, 4, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 4, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 4, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 4, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 4, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 4, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 5, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 5, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 5, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 5, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 5, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 5, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 6, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 6, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 6, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 6, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 6, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 6, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 7, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 7, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 7, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 7, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 7, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 7, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 8, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 8, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 8, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 8, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 8, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 8, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 9, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 9, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 9, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 9, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 9, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 9, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 10, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 10, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 10, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 10, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 10, false, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 1, 10, true, new string[] { "wd023", "wd023", "wd023", "wd023" }); + yield return new TestCaseData("PAL3A", 2, 1, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 1, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 1, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 1, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 1, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 1, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 2, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 2, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 2, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 2, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 2, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 2, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 3, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 3, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 3, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 3, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 3, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 3, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 4, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 4, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 4, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 4, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 4, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 4, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 5, false, new string[] { "wd027", "wd027", "wd027", "wd027" }); + yield return new TestCaseData("PAL3A", 2, 5, true, new string[] { "wd027", "wd027", "wd027", "wd027" }); + yield return new TestCaseData("PAL3A", 2, 5, false, new string[] { "wd027", "wd027", "wd027", "wd027" }); + yield return new TestCaseData("PAL3A", 2, 5, true, new string[] { "wd027", "wd027", "wd027", "wd027" }); + yield return new TestCaseData("PAL3A", 2, 5, false, new string[] { "wd027", "wd027", "wd027", "wd027" }); + yield return new TestCaseData("PAL3A", 2, 5, true, new string[] { "wd027", "wd027", "wd027", "wd027" }); + yield return new TestCaseData("PAL3A", 2, 6, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 6, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 6, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 6, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 6, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 6, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 7, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 7, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 7, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 7, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 7, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 7, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 8, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 8, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 8, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 8, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 8, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 8, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 9, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 9, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 9, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 9, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 9, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 9, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 10, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 10, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 10, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 10, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 10, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 2, 10, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 1, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 1, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 1, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 1, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 1, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 1, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 2, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 2, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 2, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 2, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 2, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 2, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 3, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 3, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 3, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 3, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 3, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 3, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 4, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 4, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 4, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 4, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 4, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 4, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 5, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 5, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 5, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 5, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 5, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 5, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 6, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 6, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 6, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 6, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 6, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 6, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 7, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 7, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 7, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 7, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 7, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 7, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 8, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 8, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 8, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 8, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 8, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 8, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 9, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 9, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 9, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 9, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 9, false, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 9, true, new string[] { "wd028", "wd028", "wd028", "wd028" }); + yield return new TestCaseData("PAL3A", 3, 10, false, new string[] { null, null, null, null }); + yield return new TestCaseData("PAL3A", 3, 10, true, new string[] { null, null, null, null }); + yield return new TestCaseData("PAL3A", 3, 10, false, new string[] { null, null, null, null }); + yield return new TestCaseData("PAL3A", 3, 10, true, new string[] { null, null, null, null }); + yield return new TestCaseData("PAL3A", 3, 10, false, new string[] { null, null, null, null }); + yield return new TestCaseData("PAL3A", 3, 10, true, new string[] { null, null, null, null }); + yield return new TestCaseData("PAL3A", 4, 1, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 1, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 1, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 1, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 1, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 1, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 2, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 2, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 2, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 2, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 2, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 2, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 3, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 3, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 3, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 3, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 3, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 3, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 4, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 4, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 4, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 4, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 4, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 4, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 5, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 5, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 5, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 5, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 5, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 5, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 6, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 6, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 6, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 6, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 6, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 6, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 7, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 7, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 7, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 7, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 7, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 7, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 8, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 8, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 8, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 8, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 8, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 8, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 9, false, new string[] { "wd031", "wd031", "wd031", "wd031" }); + yield return new TestCaseData("PAL3A", 4, 9, true, new string[] { "wd031", "wd031", "wd031", "wd031" }); + yield return new TestCaseData("PAL3A", 4, 9, false, new string[] { "wd031", "wd031", "wd031", "wd031" }); + yield return new TestCaseData("PAL3A", 4, 9, true, new string[] { "wd031", "wd031", "wd031", "wd031" }); + yield return new TestCaseData("PAL3A", 4, 9, false, new string[] { "wd031", "wd031", "wd031", "wd031" }); + yield return new TestCaseData("PAL3A", 4, 9, true, new string[] { "wd031", "wd031", "wd031", "wd031" }); + yield return new TestCaseData("PAL3A", 4, 10, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 10, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 10, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 10, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 10, false, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", 4, 10, true, new string[] { "wd030", "wd030", "wd030", "wd030" }); + yield return new TestCaseData("PAL3A", -1, 1, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 1, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 1, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 1, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 1, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 1, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 2, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 2, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 2, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 2, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 2, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 2, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 3, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 3, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 3, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 3, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 3, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 3, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 4, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 4, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 4, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 4, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 4, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 4, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 5, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 5, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 5, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 5, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 5, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 5, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 6, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 6, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 6, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 6, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 6, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 6, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 7, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 7, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 7, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 7, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 7, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 7, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 8, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 8, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 8, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 8, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 8, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 8, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 9, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 9, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 9, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 9, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 9, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 9, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 10, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 10, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 10, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 10, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 10, false, new string[] { "wd007", "wd007", "wd007", "wd007" }); + yield return new TestCaseData("PAL3A", -1, 10, true, new string[] { "wd007", "wd007", "wd007", "wd007" }); + } + + [TestCaseSource(nameof(AttackGoldens))] + public void AttackSoundMatchesReleasedBodyMarkers(string variant, int identity, int weapon, bool transformed, string[] expected) + { + for (int marker = 0; marker < 4; marker++) + Assert.That(BattleBodyAudioRules.Attack(variant, identity, weapon, (BattlePhysicalMarkerKind)marker, + 7, transformed: transformed), Is.EqualTo(expected[marker])); + } + + [TestCase("PAL3", 0, "we015")] + [TestCase("PAL3", 4, "we019")] + [TestCase("PAL3A", 0, "we002")] + [TestCase("PAL3A", 4, "we006")] + [TestCase("PAL3A", -1, "we038")] + public void HurtUsesTheVariantActorIdentity(string variant, int identity, string expected) + { + Assert.That(BattleBodyAudioRules.Hurt(variant, identity, false, 38), Is.EqualTo(expected)); + Assert.That(BattleBodyAudioRules.Hurt(variant, identity, true, 38), Is.EqualTo(identity < 0 ? expected : "we020")); + } + + [Test] + public void MagicSwordAndAbsentMonsterSoundsKeepTheirNativeBoundaries() + { + Assert.That(BattleBodyAudioRules.Attack("PAL3", 0, 2, BattlePhysicalMarkerKind.Work, magicSword: true), Is.EqualTo("wd023")); + Assert.That(BattleBodyAudioRules.Attack("PAL3A", -1, 0, BattlePhysicalMarkerKind.Work), Is.Null); + Assert.That(BattleBodyAudioRules.Hurt("PAL3", -1, false), Is.Null); + Assert.That(BattleBodyAudioRules.Attack("PAL3A", 0, 1, BattlePhysicalMarkerKind.Over), Is.Null); + } + + [TestCase("PAL3", 0, BattleMovementKind.Run, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3", 1, BattleMovementKind.Run, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 2, BattleMovementKind.Run, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 3, BattleMovementKind.Run, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 4, BattleMovementKind.Run, 0f, 0f, 100f, "we011b", true)] + [TestCase("PAL3", -1, BattleMovementKind.Run, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.Run, 0f, 0f, 0f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.Run, -1000f, 0f, -1000f, "we011", false)] + [TestCase("PAL3", 0, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3", 1, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3", 2, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3", 3, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3", 4, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3", -1, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3", 0, BattleMovementKind.Teleport, 0f, 0f, 0f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.Teleport, -1000f, 0f, -1000f, "we014", false)] + [TestCase("PAL3", 0, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3", 0, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3", 0, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 1, BattleMovementKind.Fly, 0f, 0f, 100f, "we012", false)] + [TestCase("PAL3", 2, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 3, BattleMovementKind.Fly, 0f, 0f, 100f, "we013", false)] + [TestCase("PAL3", 4, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", -1, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.Fly, 0f, 0f, 0f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.Fly, -1000f, 0f, -1000f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.FlyRotate, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 1, BattleMovementKind.FlyRotate, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 2, BattleMovementKind.FlyRotate, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 3, BattleMovementKind.FlyRotate, 0f, 0f, 100f, "we013", false)] + [TestCase("PAL3", 4, BattleMovementKind.FlyRotate, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", -1, BattleMovementKind.FlyRotate, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.FlyRotate, 0f, 0f, 0f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.FlyRotate, -1000f, 0f, -1000f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.FlyRotate, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.FlyRotate, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.FlyRotate, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3", 1, BattleMovementKind.NpcFly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 2, BattleMovementKind.NpcFly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 3, BattleMovementKind.NpcFly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 4, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011b", true)] + [TestCase("PAL3", -1, BattleMovementKind.NpcFly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.NpcFly, 0f, 0f, 0f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.NpcFly, -1000f, 0f, -1000f, "we011", false)] + [TestCase("PAL3", 0, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3", 0, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3", 0, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3", 0, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 1, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 2, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 3, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 4, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", -1, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.FastRun, 0f, 0f, 0f, null, false)] + [TestCase("PAL3", 0, BattleMovementKind.FastRun, -1000f, 0f, -1000f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.Run, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3A", 1, BattleMovementKind.Run, 0f, 0f, 100f, "we001", true)] + [TestCase("PAL3A", 2, BattleMovementKind.Run, 0f, 0f, 100f, "we001", true)] + [TestCase("PAL3A", 3, BattleMovementKind.Run, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3A", 4, BattleMovementKind.Run, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3A", -1, BattleMovementKind.Run, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.Run, 0f, 0f, 0f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.Run, -1000f, 0f, -1000f, "we011", false)] + [TestCase("PAL3A", 0, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3A", 1, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3A", 2, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3A", 3, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3A", 4, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3A", -1, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3A", 0, BattleMovementKind.Teleport, 0f, 0f, 0f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.Teleport, -1000f, 0f, -1000f, "we014", false)] + [TestCase("PAL3A", 0, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3A", 0, BattleMovementKind.Teleport, 0f, 0f, 100f, "we014", false)] + [TestCase("PAL3A", 0, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 1, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 2, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 3, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 4, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", -1, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.Fly, 0f, 0f, 0f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.Fly, -1000f, 0f, -1000f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.Fly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3A", 1, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we001", true)] + [TestCase("PAL3A", 2, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we001", true)] + [TestCase("PAL3A", 3, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3A", 4, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3A", -1, BattleMovementKind.NpcFly, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.NpcFly, 0f, 0f, 0f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.NpcFly, -1000f, 0f, -1000f, "we011", false)] + [TestCase("PAL3A", 0, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3A", 0, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3A", 0, BattleMovementKind.NpcFly, 0f, 0f, 100f, "we011", true)] + [TestCase("PAL3A", 0, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 1, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 2, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 3, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 4, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", -1, BattleMovementKind.FastRun, 0f, 0f, 100f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.FastRun, 0f, 0f, 0f, null, false)] + [TestCase("PAL3A", 0, BattleMovementKind.FastRun, -1000f, 0f, -1000f, null, false)] + public void MovementVoiceMatchesReleasedActivation(string variant, int identity, BattleMovementKind kind, float x, float y, float z, string expected, bool loop) + { + var sound = BattleBodyAudioRules.Movement(variant, identity, new BattleMovementPlan(kind, default, new BattleMovementPoint(x, y, z))); + Assert.That(sound.Sound, Is.EqualTo(expected)); + if (expected != null) + Assert.That(sound.Loop, Is.EqualTo(loop)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleBodyAudioRulesTests.cs.meta b/Assets/Tests/Battle/Editor/BattleBodyAudioRulesTests.cs.meta new file mode 100644 index 00000000..03f488a6 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleBodyAudioRulesTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 35c4404722a74b44865e74c8afa4cb64 diff --git a/Assets/Tests/Battle/Editor/BattleBodyAudioSessionTests.cs b/Assets/Tests/Battle/Editor/BattleBodyAudioSessionTests.cs new file mode 100644 index 00000000..a7b6cd94 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleBodyAudioSessionTests.cs @@ -0,0 +1,137 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleBodyAudioSessionTests + { + private sealed class Catalog : IBattleCatalog, IBattlePhysicalTimings, IBattleStageGeometry, IBattleBodyAudioCatalog + { + private readonly string _variant; + + public Catalog(string variant) => _variant = variant; + + public BattlePhysicalStageProfile Physical(string actor) + { + var animations = Enum.GetValues(typeof(BattlePose)).Cast().ToDictionary(pose => pose, + pose => new BattlePhysicalAnimation(pose.ToString(), 5, 10, + pose == BattlePose.Attacking ? new[] { new BattlePhysicalMarker(2, BattlePhysicalMarkerKind.Work) } : null, 480)); + return new BattlePhysicalStageProfile(_variant, actor == "A" ? 101 : 701, actor == "A" ? 0 : -1, 1, 1, animations); + } + + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 5; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "A" ? 0 : 5; + + public int DamageDivisor(string actor) => 1; + + public BattleMovementPoint InitialHome(string actor) => actor == "A" ? default : new(100, 0, 0); + + public BattleMovementPoint FormationHome(string actor, BattleSlot slot) => InitialHome(actor); + + public BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint sourceHome, BattleMovementPoint targetHome) => new(Attack(source, target), sourceHome, sourceHome, targetHome); + + public IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint from, BattleMovementPoint to, bool midpoint) => new[] { new BattleMovementPlan(BattleMovementKind.Run, from, to) }; + + public BattleBodySoundProfile BodySounds(string actor) => new(121, 38); + } + + private sealed class Rules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => 0; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => new(-10, false, false); + } + + private sealed class Audio : IBattleEffectDirector, IBattleAudio, IBattleMovementAudio + { + public readonly List Cues = new(); + + public long Start(BattleEffectRequest request) => throw new InvalidOperationException("No effect is needed by this body fixture."); + + public bool IsRunning(long handle) => false; + + public void Stop(long handle) + { + } + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void PlaySound(string sound) => Cues.Add(sound); + + public void PlayMovementSound(string actor, string sound, bool loop) => Cues.Add("start:" + actor + ":" + sound + ":" + loop); + + public void StopMovementSound(string actor) => Cues.Add("stop:" + actor); + + public void StopBodySounds() => Cues.Add("clear"); + } + + private static BattleSession Session(string variant, Audio audio) + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "audio", Seed = 10 }; + foreach (var value in new[] { ("A", 101, BattleSide.Ally), ("E", 701, BattleSide.Enemy) }) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = value.Item1, + ActorId = value.Item2, + Side = value.Item3, + Slot = BattleSlot.Water, + Attributes = new[] { 500, 100, 200, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 10, 0 } + }); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, Array.Empty(), Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1, + NormalAttackMode = 924 + }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(variant), new Rules(), definitions, effects: audio); + session.SetAutomatic(BattleSide.Enemy, false); + session.Step(); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + return session; + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NativeBodyAudioEmitsOnceAndLeavesCombatResultsDeterministic(string variant) + { + var audio = new Audio(); + BattleSession audible = Session(variant, audio); + BattleSession silent = Session(variant, null); + for (int step = 0; step < 100; step++) + { + audible.Step(); + silent.Step(); + } + Assert.That(audible.Status, Is.EqualTo(BattleSessionStatus.Running)); + Assert.That(audio.Cues.Count(cue => cue == "wd025"), Is.EqualTo(1)); + Assert.That(audio.Cues.Count(cue => cue == "we038"), Is.EqualTo(1)); + Assert.That(audio.Cues, Does.Contain("start:A:we011:True")); + Assert.That(audio.Cues, Does.Contain("stop:A")); + Assert.That(audible.Actors.Select(actor => actor.Hp), Is.EqualTo(silent.Actors.Select(actor => actor.Hp))); + Assert.That(audible.Events.Select(entry => entry.Kind), Is.EqualTo(silent.Events.Select(entry => entry.Kind))); + audible.Abort(); + Assert.That(audio.Cues.Last(), Is.EqualTo("clear")); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleBodyAudioSessionTests.cs.meta b/Assets/Tests/Battle/Editor/BattleBodyAudioSessionTests.cs.meta new file mode 100644 index 00000000..e2b23735 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleBodyAudioSessionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9901cff95a524a73b4c43f5fd5b8e028 diff --git a/Assets/Tests/Battle/Editor/BattleCameraTests.cs b/Assets/Tests/Battle/Editor/BattleCameraTests.cs new file mode 100644 index 00000000..cbc3a4d2 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleCameraTests.cs @@ -0,0 +1,297 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using Battle; + using NUnit.Framework; + + public sealed class BattleCameraTests + { + private const BattleCameraFlags TimedLine = BattleCameraFlags.StartCamera | BattleCameraFlags.EndCamera | BattleCameraFlags.Time | BattleCameraFlags.Line; + + private static BattleCameraTask Line(float duration = 1) => new() + { + Flags = TimedLine, + ExpectedSeconds = duration, + Start = new BattleCameraPose(new BattleMovementPoint(10, 20, 30), 0, 0, 0), + End = new BattleCameraPose(new BattleMovementPoint(110, 20, 30), 1, 2, 3) + }; + + private static BattleCameraController Camera(params BattleCameraTask[] tasks) + => new(new IReadOnlyList[] { tasks }, new BattleCameraPose(new BattleMovementPoint(1, 2, 3), .1f, .2f, .3f)); + + [Test] + public void TaskCompletionAndNextTaskActivationOccupySeparateStageUpdates() + { + BattleCameraTask first = Line(0), second = Line(1); + second.Flags &= ~BattleCameraFlags.StartCamera; + second.End = new BattleCameraPose(new BattleMovementPoint(210, 20, 30), 2, 4, 6); + var camera = Camera(first, second); + Assert.That(camera.StartList(0), Is.True); + camera.Advance(.02f, .02f); + Assert.That(camera.Pose.Position.X, Is.EqualTo(110)); + Assert.That(camera.CurrentTask, Is.Zero); + Assert.That(camera.CurrentTaskFinished, Is.True); + camera.Advance(.02f, .02f); + Assert.That(camera.CurrentTask, Is.EqualTo(1)); + Assert.That(camera.Pose.Position.X, Is.EqualTo(110)); + camera.Advance(.02f, .02f); + Assert.That(camera.Pose.Position.X, Is.EqualTo(110)); + camera.Advance(.5f, .5f); + Assert.That(camera.Pose.Position.X, Is.EqualTo(160).Within(.0001)); + } + + [Test] + public void InitialSpeedSolverUsesBothAccelerationIntervalsBeforeTheirStartTimes() + { + BattleCameraTask task = Line(2); + task.FirstAccelerationStart = 3; + task.SecondAccelerationStart = 4; + task.FirstAcceleration = 10; + task.SecondAcceleration = 20; + var camera = Camera(task); + camera.StartList(0); + camera.Advance(0, 0); + camera.Advance(1, 1); + // v0=(100-(10*(-1)^2/2 + 30*(-2)^2/2))/2=17.5. + Assert.That(camera.Pose.Position.X, Is.EqualTo(27.5f)); + Assert.That(camera.Pose.Yaw, Is.EqualTo(.5f)); + } + + [Test] + public void AccelerationSecondIntervalAddsTheSumOfBothAccelerations() + { + BattleCameraTask task = Line(); + task.Flags = BattleCameraFlags.StartCamera | BattleCameraFlags.Speed | BattleCameraFlags.Time | BattleCameraFlags.Line; + task.StartSpeed = 5; + task.ExpectedSeconds = 4; + task.FirstAccelerationStart = 1; + task.SecondAccelerationStart = 2; + task.FirstAcceleration = 2; + task.SecondAcceleration = 3; + var camera = Camera(task); + camera.StartList(0); + camera.Advance(0, 0); + camera.Advance(3, 3); + Assert.That(camera.Pose.Position.X, Is.EqualTo(10 + 15 + 4 + 2.5)); + } + + [Test] + public void TimeUnknownClampsDistanceAndRetainsItsObservedDurationForReplay() + { + BattleCameraTask task = Line(); + task.Flags = BattleCameraFlags.StartCamera | BattleCameraFlags.EndCamera | BattleCameraFlags.Speed | BattleCameraFlags.Line; + task.StartSpeed = 80; + var camera = Camera(task); + camera.StartList(0); + camera.Advance(0, 0); + camera.Advance(2, 2); + Assert.That(camera.Pose.Position.X, Is.EqualTo(110)); + Assert.That(camera.CurrentExpectedSeconds, Is.EqualTo(2)); + Assert.That(camera.CurrentTaskFinished, Is.True); + camera.StartList(0); + Assert.That(camera.CurrentExpectedSeconds, Is.EqualTo(2)); + Assert.That(camera.CurrentTaskFinished, Is.False); + } + + [Test] + public void TargetUnknownDoesNotClampTravelOrOrientationAtTheLastSample() + { + BattleCameraTask task = Line(); + task.Flags &= ~BattleCameraFlags.EndCamera; + task.Flags |= BattleCameraFlags.Speed; + task.StartSpeed = 100; + var camera = Camera(task); + camera.StartList(0); + camera.Advance(0, 0); + camera.Advance(1.2f, 1.2f); + Assert.That(camera.Pose.Position.X, Is.EqualTo(130).Within(.0001)); + Assert.That(camera.Pose.Yaw, Is.EqualTo(1.2f).Within(.0001)); + Assert.That(camera.CurrentTaskFinished, Is.True); + } + + [Test] + public void NegativeSolvedSpeedAndTimeReviseCanFinishAtTheDestinationEarly() + { + BattleCameraTask task = Line(10); + task.FirstAcceleration = 100; + task.Flags |= BattleCameraFlags.TimeRevise; + var camera = Camera(task); + camera.StartList(0); + camera.Advance(0, 0); + camera.Advance(2, 2); + Assert.That(camera.Pose.Position.X, Is.EqualTo(110)); + Assert.That(camera.CurrentExpectedSeconds, Is.EqualTo(2)); + Assert.That(camera.CurrentTaskFinished, Is.True); + // Native angles use the requested-time ratio before time revision. + Assert.That(camera.Pose.Yaw, Is.EqualTo(.2f)); + } + + [Test] + public void AbsoluteTasksContinueWhileTheCombatClockIsFrozen() + { + BattleCameraTask task = Line(); + task.Flags |= BattleCameraFlags.AbsoluteTime; + var camera = Camera(task); + camera.StartList(0); + camera.Advance(0, .1f); + camera.Advance(0, .5f); + Assert.That(camera.Pose.Position.X, Is.EqualTo(60).Within(.0001)); + camera.StopList(); + Assert.That(camera.IsRunning, Is.False); + Assert.That(camera.StartList(99), Is.False); + } + + [Test] + public void CounterYawTakesTheLongArcWithoutApplyingUnusedAngleFlags() + { + BattleCameraTask task = Line(); + task.Flags |= BattleCameraFlags.CounterYaw | BattleCameraFlags.CounterPitch | BattleCameraFlags.CounterRoll; + var camera = Camera(task); + camera.StartList(0); + camera.Advance(0, 0); + camera.Advance(.5f, .5f); + Assert.That(camera.Pose.Yaw, Is.EqualTo((float)Math.PI + .5f).Within(.000001)); + Assert.That(camera.Pose.Pitch, Is.EqualTo(1)); + Assert.That(camera.Pose.Roll, Is.EqualTo(1.5)); + } + + [TestCase(90f, 90f, 0f, -100f)] + [TestCase(-90f, -90f, 0f, 100f)] + public void CircleUsesDegreesAndTheOriginalHeightRamp(float angle, float speed, float x, float z) + { + var task = new BattleCameraTask + { + Flags = BattleCameraFlags.StartCamera | BattleCameraFlags.EndCamera | BattleCameraFlags.Speed | BattleCameraFlags.Circle, + Start = new BattleCameraPose(new BattleMovementPoint(100, 30, 0), .2f, .3f, .4f), + CircleAngle = angle, + AngularSpeed = speed, + CircleCenter = new BattleMovementPoint(0, 10, 0), + CircleEnd = new BattleMovementPoint(900, 60, 900) + }; + var camera = Camera(task); + camera.StartList(0); + camera.Advance(0, 0); + camera.Advance(1, 1); + Assert.That(camera.Pose.Position.X, Is.EqualTo(x).Within(.00002)); + Assert.That(camera.Pose.Position.Z, Is.EqualTo(z).Within(.00002)); + Assert.That(camera.Pose.Position.Y, Is.EqualTo(80)); + Assert.That(camera.Pose.Yaw, Is.EqualTo(.2f)); + Assert.That(camera.CurrentTaskFinished, Is.True); + } + + [Test] + public void UnimplementedNativeCircleBranchesAndOverspecifiedLineStayIdle() + { + foreach (BattleCameraFlags flags in new[] { BattleCameraFlags.Circle | BattleCameraFlags.Time, TimedLine | BattleCameraFlags.Speed }) + { + BattleCameraTask task = Line(); + task.Flags = flags; + var camera = Camera(task); + camera.StartList(0); + camera.Advance(10, 10); + Assert.That(camera.Pose.Position.X, Is.EqualTo(1)); + Assert.That(camera.CurrentTaskFinished, Is.False); + } + } + + [Test] + public void ConsecutiveMechanicsTasksPreserveSpeedRegardlessOfSpliceAndInertia() + { + BattleCameraTask first = Line(.1f), second = Line(1); + first.Flags = second.Flags = BattleCameraFlags.StartCamera | BattleCameraFlags.Mechanics; + first.Start = new BattleCameraPose(default, 0, 0, 0); + first.End = new BattleCameraPose(new BattleMovementPoint(10, 0, 0), 0, 0, 0); + second.Start = new BattleCameraPose(new BattleMovementPoint(10, 0, 0), 0, 0, 0); + second.End = new BattleCameraPose(new BattleMovementPoint(10, 0, 100), 0, 0, 0); + second.Inertia = 999; + second.Splice = false; + second.TimeCompensation = .5f; + var camera = Camera(first, second); + camera.StartList(0); + camera.Advance(.1f, .1f); // Native mechanics integrates on its activation call. + camera.Advance(.1f, .1f); + camera.Advance(.1f, .1f); // Advances only the list cursor. + camera.Advance(.1f, .1f); + Assert.That(camera.Pose.Position.X, Is.EqualTo(19.95037).Within(.0001)); + Assert.That(camera.Pose.Position.Z, Is.EqualTo(.995037).Within(.0001)); + camera.Advance(1, 1); + Assert.That(camera.CurrentTaskFinished, Is.False); + camera.Advance(.5f, .5f); + Assert.That(camera.CurrentTaskFinished, Is.True); + } + + [Test] + public void PositionTraceCapturesLineOriginAndSightTracePreservesTheNativeDisplacementQuirk() + { + BattleCameraTask task = Line(); + task.Flags = BattleCameraFlags.StartCamera | BattleCameraFlags.Time | BattleCameraFlags.Speed | BattleCameraFlags.Line | BattleCameraFlags.PositionTrace | BattleCameraFlags.SightTrace; + task.StartSpeed = 100; + BattleMovementPoint trace = new(200, 60, 200); + var camera = new BattleCameraController(new IReadOnlyList[] { new[] { task } }, default, _ => trace); + camera.StartList(0); + camera.Advance(0, 0); + trace = new BattleMovementPoint(210, 60, 200); + camera.Advance(.5f, .5f); + Assert.That(camera.Pose.Position.X, Is.EqualTo(70)); + // Looking from displacement (60,0,0), rather than camera (70,20,30). + float expected = (float)Math.Atan(-150f / 200f) + (float)Math.PI; + Assert.That(camera.Pose.Yaw, Is.EqualTo(expected).Within(.000001)); + } + + [Test] + public void RandomSwingTogglesTrailWhileStoredFovSwingAndSpliceRemainUnused() + { + BattleCameraTask task = Line(); + task.Flags |= BattleCameraFlags.RandomSwing; + task.Splice = true; + task.StartFieldOfView = 5; + task.EndFieldOfView = 100; + task.SwingAmplitude = 100; + task.SwingFrequency = 100; + var camera = Camera(task); + camera.StartList(0); + camera.Advance(0, 0); + camera.Advance(.5f, .5f); + Assert.That(camera.TrailEnabled, Is.True); + Assert.That(camera.FieldOfView, Is.EqualTo(50)); + Assert.That(camera.Pose.Position.X, Is.EqualTo(60)); + Assert.That(camera.Pose.Position.Y, Is.EqualTo(20)); + } + + [Test] + public void QuakeDecaysBeforeSamplingAndUsesOnlyScaledTime() + { + var camera = Camera(); + camera.SetQuake(10, 2, 2); + camera.Advance(0, 1); + Assert.That(camera.Pose.Position.Y, Is.EqualTo(2)); + camera.Advance(.5f, 0); + Assert.That(camera.Pose.Position.Y, Is.EqualTo(2 + 9 * (float)Math.Sin(1)).Within(.000001)); + Assert.That(camera.Pose.Position.X, Is.EqualTo(1)); + } + + [Test] + public void StageTimeAccumulatesInDoubleBeforeItsFloatProjection() + { + var camera = Camera(); + double time = 0; + for (int frame = 0; frame < 100000; frame++) + { + time += .02d; + camera.Advance(.02d, .02d); + } + Assert.That(camera.ScaledTime, Is.EqualTo((float)time)); + Assert.That(camera.AbsoluteTime, Is.EqualTo((float)time)); + Assert.That(camera.ScaledTime, Is.EqualTo(2000)); + camera.AdvanceAt(3000.125d, 4000.25d, 1000.125d, 2000.25d); + Assert.That(camera.ScaledTime, Is.EqualTo(3000.125f)); + Assert.That(camera.AbsoluteTime, Is.EqualTo(4000.25f)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleCameraTests.cs.meta b/Assets/Tests/Battle/Editor/BattleCameraTests.cs.meta new file mode 100644 index 00000000..a55ec8c1 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleCameraTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c5138214263040bba30f958982d2eb96 diff --git a/Assets/Tests/Battle/Editor/BattleCoAttackRulesTests.cs b/Assets/Tests/Battle/Editor/BattleCoAttackRulesTests.cs new file mode 100644 index 00000000..7053599e --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleCoAttackRulesTests.cs @@ -0,0 +1,456 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System.Collections.Generic; + using System.Linq; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleCoAttackRulesTests + { + // These arithmetic/RNG outcomes execute original GetCoAttackPower. + public static IEnumerable NativeCases() + { + yield return new TestCaseData("PAL3", -1, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_0"); + yield return new TestCaseData("PAL3", -1, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_1"); + yield return new TestCaseData("PAL3", -1, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_2"); + yield return new TestCaseData("PAL3", -1, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_3"); + yield return new TestCaseData("PAL3", -1, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_4"); + yield return new TestCaseData("PAL3", -1, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_5"); + yield return new TestCaseData("PAL3", 0, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_6"); + yield return new TestCaseData("PAL3", 0, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_7"); + yield return new TestCaseData("PAL3", 0, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_8"); + yield return new TestCaseData("PAL3", 0, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_9"); + yield return new TestCaseData("PAL3", 0, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_10"); + yield return new TestCaseData("PAL3", 0, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_11"); + yield return new TestCaseData("PAL3", 1, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_12"); + yield return new TestCaseData("PAL3", 1, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_13"); + yield return new TestCaseData("PAL3", 1, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_14"); + yield return new TestCaseData("PAL3", 1, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_15"); + yield return new TestCaseData("PAL3", 1, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_16"); + yield return new TestCaseData("PAL3", 1, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_17"); + yield return new TestCaseData("PAL3", 49, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_18"); + yield return new TestCaseData("PAL3", 49, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_19"); + yield return new TestCaseData("PAL3", 49, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_20"); + yield return new TestCaseData("PAL3", 49, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_21"); + yield return new TestCaseData("PAL3", 49, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_22"); + yield return new TestCaseData("PAL3", 49, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_23"); + yield return new TestCaseData("PAL3", 50, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_24"); + yield return new TestCaseData("PAL3", 50, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_25"); + yield return new TestCaseData("PAL3", 50, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_26"); + yield return new TestCaseData("PAL3", 50, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_27"); + yield return new TestCaseData("PAL3", 50, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_28"); + yield return new TestCaseData("PAL3", 50, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_29"); + yield return new TestCaseData("PAL3", 51, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_30"); + yield return new TestCaseData("PAL3", 51, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_31"); + yield return new TestCaseData("PAL3", 51, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_32"); + yield return new TestCaseData("PAL3", 51, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_33"); + yield return new TestCaseData("PAL3", 51, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_34"); + yield return new TestCaseData("PAL3", 51, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_35"); + yield return new TestCaseData("PAL3", 99, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_36"); + yield return new TestCaseData("PAL3", 99, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_37"); + yield return new TestCaseData("PAL3", 99, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_38"); + yield return new TestCaseData("PAL3", 99, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_39"); + yield return new TestCaseData("PAL3", 99, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_40"); + yield return new TestCaseData("PAL3", 99, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_41"); + yield return new TestCaseData("PAL3", 100, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_42"); + yield return new TestCaseData("PAL3", 100, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_43"); + yield return new TestCaseData("PAL3", 100, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_44"); + yield return new TestCaseData("PAL3", 100, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_45"); + yield return new TestCaseData("PAL3", 100, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_46"); + yield return new TestCaseData("PAL3", 100, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_47"); + yield return new TestCaseData("PAL3", 149, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_48"); + yield return new TestCaseData("PAL3", 149, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_49"); + yield return new TestCaseData("PAL3", 149, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_50"); + yield return new TestCaseData("PAL3", 149, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_51"); + yield return new TestCaseData("PAL3", 149, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_52"); + yield return new TestCaseData("PAL3", 149, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_53"); + yield return new TestCaseData("PAL3", 150, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_54"); + yield return new TestCaseData("PAL3", 150, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_55"); + yield return new TestCaseData("PAL3", 150, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_56"); + yield return new TestCaseData("PAL3", 150, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_57"); + yield return new TestCaseData("PAL3", 150, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_58"); + yield return new TestCaseData("PAL3", 150, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_59"); + yield return new TestCaseData("PAL3", 151, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_60"); + yield return new TestCaseData("PAL3", 151, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_61"); + yield return new TestCaseData("PAL3", 151, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_62"); + yield return new TestCaseData("PAL3", 151, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_63"); + yield return new TestCaseData("PAL3", 151, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_64"); + yield return new TestCaseData("PAL3", 151, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_65"); + yield return new TestCaseData("PAL3", 199, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_66"); + yield return new TestCaseData("PAL3", 199, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_67"); + yield return new TestCaseData("PAL3", 199, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_68"); + yield return new TestCaseData("PAL3", 199, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_69"); + yield return new TestCaseData("PAL3", 199, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_70"); + yield return new TestCaseData("PAL3", 199, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_71"); + yield return new TestCaseData("PAL3", 200, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_72"); + yield return new TestCaseData("PAL3", 200, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_73"); + yield return new TestCaseData("PAL3", 200, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_74"); + yield return new TestCaseData("PAL3", 200, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_75"); + yield return new TestCaseData("PAL3", 200, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_76"); + yield return new TestCaseData("PAL3", 200, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_77"); + yield return new TestCaseData("PAL3", 249, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_78"); + yield return new TestCaseData("PAL3", 249, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_79"); + yield return new TestCaseData("PAL3", 249, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_80"); + yield return new TestCaseData("PAL3", 249, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_81"); + yield return new TestCaseData("PAL3", 249, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_82"); + yield return new TestCaseData("PAL3", 249, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_83"); + yield return new TestCaseData("PAL3", 250, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_84"); + yield return new TestCaseData("PAL3", 250, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_85"); + yield return new TestCaseData("PAL3", 250, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_86"); + yield return new TestCaseData("PAL3", 250, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_87"); + yield return new TestCaseData("PAL3", 250, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_88"); + yield return new TestCaseData("PAL3", 250, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_89"); + yield return new TestCaseData("PAL3", 251, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_90"); + yield return new TestCaseData("PAL3", 251, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_91"); + yield return new TestCaseData("PAL3", 251, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_92"); + yield return new TestCaseData("PAL3", 251, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_93"); + yield return new TestCaseData("PAL3", 251, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_94"); + yield return new TestCaseData("PAL3", 251, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_95"); + yield return new TestCaseData("PAL3", 300, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_96"); + yield return new TestCaseData("PAL3", 300, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_97"); + yield return new TestCaseData("PAL3", 300, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_98"); + yield return new TestCaseData("PAL3", 300, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_99"); + yield return new TestCaseData("PAL3", 300, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_100"); + yield return new TestCaseData("PAL3", 300, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_101"); + yield return new TestCaseData("PAL3", -1, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_102"); + yield return new TestCaseData("PAL3", -1, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_103"); + yield return new TestCaseData("PAL3", -1, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_104"); + yield return new TestCaseData("PAL3", -1, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_105"); + yield return new TestCaseData("PAL3", -1, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_106"); + yield return new TestCaseData("PAL3", -1, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_107"); + yield return new TestCaseData("PAL3", 0, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_108"); + yield return new TestCaseData("PAL3", 0, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_109"); + yield return new TestCaseData("PAL3", 0, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_110"); + yield return new TestCaseData("PAL3", 0, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_111"); + yield return new TestCaseData("PAL3", 0, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_112"); + yield return new TestCaseData("PAL3", 0, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_113"); + yield return new TestCaseData("PAL3", 1, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_114"); + yield return new TestCaseData("PAL3", 1, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_115"); + yield return new TestCaseData("PAL3", 1, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_116"); + yield return new TestCaseData("PAL3", 1, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_117"); + yield return new TestCaseData("PAL3", 1, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_118"); + yield return new TestCaseData("PAL3", 1, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_119"); + yield return new TestCaseData("PAL3", 49, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_120"); + yield return new TestCaseData("PAL3", 49, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_121"); + yield return new TestCaseData("PAL3", 49, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_122"); + yield return new TestCaseData("PAL3", 49, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_123"); + yield return new TestCaseData("PAL3", 49, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_124"); + yield return new TestCaseData("PAL3", 49, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_125"); + yield return new TestCaseData("PAL3", 50, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_126"); + yield return new TestCaseData("PAL3", 50, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_127"); + yield return new TestCaseData("PAL3", 50, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_128"); + yield return new TestCaseData("PAL3", 50, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_129"); + yield return new TestCaseData("PAL3", 50, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_130"); + yield return new TestCaseData("PAL3", 50, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_131"); + yield return new TestCaseData("PAL3", 51, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_132"); + yield return new TestCaseData("PAL3", 51, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_133"); + yield return new TestCaseData("PAL3", 51, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_134"); + yield return new TestCaseData("PAL3", 51, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_135"); + yield return new TestCaseData("PAL3", 51, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_136"); + yield return new TestCaseData("PAL3", 51, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_137"); + yield return new TestCaseData("PAL3", 99, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_138"); + yield return new TestCaseData("PAL3", 99, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_139"); + yield return new TestCaseData("PAL3", 99, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_140"); + yield return new TestCaseData("PAL3", 99, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_141"); + yield return new TestCaseData("PAL3", 99, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_142"); + yield return new TestCaseData("PAL3", 99, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_143"); + yield return new TestCaseData("PAL3", 100, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_144"); + yield return new TestCaseData("PAL3", 100, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_145"); + yield return new TestCaseData("PAL3", 100, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_146"); + yield return new TestCaseData("PAL3", 100, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_147"); + yield return new TestCaseData("PAL3", 100, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_148"); + yield return new TestCaseData("PAL3", 100, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_149"); + yield return new TestCaseData("PAL3", 149, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_150"); + yield return new TestCaseData("PAL3", 149, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_151"); + yield return new TestCaseData("PAL3", 149, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_152"); + yield return new TestCaseData("PAL3", 149, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_153"); + yield return new TestCaseData("PAL3", 149, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_154"); + yield return new TestCaseData("PAL3", 149, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_155"); + yield return new TestCaseData("PAL3", 150, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_156"); + yield return new TestCaseData("PAL3", 150, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_157"); + yield return new TestCaseData("PAL3", 150, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_158"); + yield return new TestCaseData("PAL3", 150, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_159"); + yield return new TestCaseData("PAL3", 150, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_160"); + yield return new TestCaseData("PAL3", 150, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_161"); + yield return new TestCaseData("PAL3", 151, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_162"); + yield return new TestCaseData("PAL3", 151, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_163"); + yield return new TestCaseData("PAL3", 151, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_164"); + yield return new TestCaseData("PAL3", 151, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_165"); + yield return new TestCaseData("PAL3", 151, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_166"); + yield return new TestCaseData("PAL3", 151, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_167"); + yield return new TestCaseData("PAL3", 199, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_168"); + yield return new TestCaseData("PAL3", 199, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_169"); + yield return new TestCaseData("PAL3", 199, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_170"); + yield return new TestCaseData("PAL3", 199, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_171"); + yield return new TestCaseData("PAL3", 199, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_172"); + yield return new TestCaseData("PAL3", 199, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_173"); + yield return new TestCaseData("PAL3", 200, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_174"); + yield return new TestCaseData("PAL3", 200, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_175"); + yield return new TestCaseData("PAL3", 200, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_176"); + yield return new TestCaseData("PAL3", 200, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_177"); + yield return new TestCaseData("PAL3", 200, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_178"); + yield return new TestCaseData("PAL3", 200, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_179"); + yield return new TestCaseData("PAL3", 249, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_180"); + yield return new TestCaseData("PAL3", 249, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_181"); + yield return new TestCaseData("PAL3", 249, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_182"); + yield return new TestCaseData("PAL3", 249, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_183"); + yield return new TestCaseData("PAL3", 249, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_184"); + yield return new TestCaseData("PAL3", 249, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_185"); + yield return new TestCaseData("PAL3", 250, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_186"); + yield return new TestCaseData("PAL3", 250, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_187"); + yield return new TestCaseData("PAL3", 250, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_188"); + yield return new TestCaseData("PAL3", 250, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_189"); + yield return new TestCaseData("PAL3", 250, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_190"); + yield return new TestCaseData("PAL3", 250, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_191"); + yield return new TestCaseData("PAL3", 251, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_192"); + yield return new TestCaseData("PAL3", 251, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_193"); + yield return new TestCaseData("PAL3", 251, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_194"); + yield return new TestCaseData("PAL3", 251, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_195"); + yield return new TestCaseData("PAL3", 251, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_196"); + yield return new TestCaseData("PAL3", 251, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_197"); + yield return new TestCaseData("PAL3", 300, -101, -37, 1u, -289, 3357800067u).SetName("PAL3_CoAttackNative_198"); + yield return new TestCaseData("PAL3", 300, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3_CoAttackNative_199"); + yield return new TestCaseData("PAL3", 300, 101, 37, 1u, 263, 3357800067u).SetName("PAL3_CoAttackNative_200"); + yield return new TestCaseData("PAL3", 300, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3_CoAttackNative_201"); + yield return new TestCaseData("PAL3", 300, 0, 0, 1u, 0, 1u).SetName("PAL3_CoAttackNative_202"); + yield return new TestCaseData("PAL3", 300, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3_CoAttackNative_203"); + yield return new TestCaseData("PAL3A", -1, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_0"); + yield return new TestCaseData("PAL3A", -1, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_1"); + yield return new TestCaseData("PAL3A", -1, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_2"); + yield return new TestCaseData("PAL3A", -1, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_3"); + yield return new TestCaseData("PAL3A", -1, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_4"); + yield return new TestCaseData("PAL3A", -1, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_5"); + yield return new TestCaseData("PAL3A", 0, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_6"); + yield return new TestCaseData("PAL3A", 0, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_7"); + yield return new TestCaseData("PAL3A", 0, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_8"); + yield return new TestCaseData("PAL3A", 0, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_9"); + yield return new TestCaseData("PAL3A", 0, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_10"); + yield return new TestCaseData("PAL3A", 0, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_11"); + yield return new TestCaseData("PAL3A", 1, -101, -37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_12"); + yield return new TestCaseData("PAL3A", 1, -101, -37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_13"); + yield return new TestCaseData("PAL3A", 1, 101, 37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_14"); + yield return new TestCaseData("PAL3A", 1, 101, 37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_15"); + yield return new TestCaseData("PAL3A", 1, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_16"); + yield return new TestCaseData("PAL3A", 1, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_17"); + yield return new TestCaseData("PAL3A", 49, -101, -37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_18"); + yield return new TestCaseData("PAL3A", 49, -101, -37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_19"); + yield return new TestCaseData("PAL3A", 49, 101, 37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_20"); + yield return new TestCaseData("PAL3A", 49, 101, 37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_21"); + yield return new TestCaseData("PAL3A", 49, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_22"); + yield return new TestCaseData("PAL3A", 49, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_23"); + yield return new TestCaseData("PAL3A", 50, -101, -37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_24"); + yield return new TestCaseData("PAL3A", 50, -101, -37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_25"); + yield return new TestCaseData("PAL3A", 50, 101, 37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_26"); + yield return new TestCaseData("PAL3A", 50, 101, 37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_27"); + yield return new TestCaseData("PAL3A", 50, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_28"); + yield return new TestCaseData("PAL3A", 50, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_29"); + yield return new TestCaseData("PAL3A", 51, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_30"); + yield return new TestCaseData("PAL3A", 51, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_31"); + yield return new TestCaseData("PAL3A", 51, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_32"); + yield return new TestCaseData("PAL3A", 51, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_33"); + yield return new TestCaseData("PAL3A", 51, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_34"); + yield return new TestCaseData("PAL3A", 51, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_35"); + yield return new TestCaseData("PAL3A", 99, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_36"); + yield return new TestCaseData("PAL3A", 99, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_37"); + yield return new TestCaseData("PAL3A", 99, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_38"); + yield return new TestCaseData("PAL3A", 99, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_39"); + yield return new TestCaseData("PAL3A", 99, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_40"); + yield return new TestCaseData("PAL3A", 99, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_41"); + yield return new TestCaseData("PAL3A", 100, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_42"); + yield return new TestCaseData("PAL3A", 100, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_43"); + yield return new TestCaseData("PAL3A", 100, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_44"); + yield return new TestCaseData("PAL3A", 100, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_45"); + yield return new TestCaseData("PAL3A", 100, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_46"); + yield return new TestCaseData("PAL3A", 100, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_47"); + yield return new TestCaseData("PAL3A", 149, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_48"); + yield return new TestCaseData("PAL3A", 149, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_49"); + yield return new TestCaseData("PAL3A", 149, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_50"); + yield return new TestCaseData("PAL3A", 149, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_51"); + yield return new TestCaseData("PAL3A", 149, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_52"); + yield return new TestCaseData("PAL3A", 149, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_53"); + yield return new TestCaseData("PAL3A", 150, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_54"); + yield return new TestCaseData("PAL3A", 150, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_55"); + yield return new TestCaseData("PAL3A", 150, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_56"); + yield return new TestCaseData("PAL3A", 150, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_57"); + yield return new TestCaseData("PAL3A", 150, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_58"); + yield return new TestCaseData("PAL3A", 150, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_59"); + yield return new TestCaseData("PAL3A", 151, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_60"); + yield return new TestCaseData("PAL3A", 151, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_61"); + yield return new TestCaseData("PAL3A", 151, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_62"); + yield return new TestCaseData("PAL3A", 151, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_63"); + yield return new TestCaseData("PAL3A", 151, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_64"); + yield return new TestCaseData("PAL3A", 151, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_65"); + yield return new TestCaseData("PAL3A", 199, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_66"); + yield return new TestCaseData("PAL3A", 199, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_67"); + yield return new TestCaseData("PAL3A", 199, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_68"); + yield return new TestCaseData("PAL3A", 199, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_69"); + yield return new TestCaseData("PAL3A", 199, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_70"); + yield return new TestCaseData("PAL3A", 199, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_71"); + yield return new TestCaseData("PAL3A", 200, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_72"); + yield return new TestCaseData("PAL3A", 200, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_73"); + yield return new TestCaseData("PAL3A", 200, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_74"); + yield return new TestCaseData("PAL3A", 200, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_75"); + yield return new TestCaseData("PAL3A", 200, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_76"); + yield return new TestCaseData("PAL3A", 200, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_77"); + yield return new TestCaseData("PAL3A", 249, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_78"); + yield return new TestCaseData("PAL3A", 249, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_79"); + yield return new TestCaseData("PAL3A", 249, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_80"); + yield return new TestCaseData("PAL3A", 249, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_81"); + yield return new TestCaseData("PAL3A", 249, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_82"); + yield return new TestCaseData("PAL3A", 249, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_83"); + yield return new TestCaseData("PAL3A", 250, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_84"); + yield return new TestCaseData("PAL3A", 250, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_85"); + yield return new TestCaseData("PAL3A", 250, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_86"); + yield return new TestCaseData("PAL3A", 250, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_87"); + yield return new TestCaseData("PAL3A", 250, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_88"); + yield return new TestCaseData("PAL3A", 250, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_89"); + yield return new TestCaseData("PAL3A", 251, -101, -37, 1u, -414, 3357800067u).SetName("PAL3A_CoAttackNative_90"); + yield return new TestCaseData("PAL3A", 251, -101, -37, 305419896u, -409, 1530878130u).SetName("PAL3A_CoAttackNative_91"); + yield return new TestCaseData("PAL3A", 251, 101, 37, 1u, 414, 3357800067u).SetName("PAL3A_CoAttackNative_92"); + yield return new TestCaseData("PAL3A", 251, 101, 37, 305419896u, 419, 1530878130u).SetName("PAL3A_CoAttackNative_93"); + yield return new TestCaseData("PAL3A", 251, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_94"); + yield return new TestCaseData("PAL3A", 251, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_95"); + yield return new TestCaseData("PAL3A", 300, -101, -37, 1u, -414, 3357800067u).SetName("PAL3A_CoAttackNative_96"); + yield return new TestCaseData("PAL3A", 300, -101, -37, 305419896u, -409, 1530878130u).SetName("PAL3A_CoAttackNative_97"); + yield return new TestCaseData("PAL3A", 300, 101, 37, 1u, 414, 3357800067u).SetName("PAL3A_CoAttackNative_98"); + yield return new TestCaseData("PAL3A", 300, 101, 37, 305419896u, 419, 1530878130u).SetName("PAL3A_CoAttackNative_99"); + yield return new TestCaseData("PAL3A", 300, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_100"); + yield return new TestCaseData("PAL3A", 300, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_101"); + yield return new TestCaseData("PAL3A", -1, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_102"); + yield return new TestCaseData("PAL3A", -1, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_103"); + yield return new TestCaseData("PAL3A", -1, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_104"); + yield return new TestCaseData("PAL3A", -1, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_105"); + yield return new TestCaseData("PAL3A", -1, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_106"); + yield return new TestCaseData("PAL3A", -1, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_107"); + yield return new TestCaseData("PAL3A", 0, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_108"); + yield return new TestCaseData("PAL3A", 0, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_109"); + yield return new TestCaseData("PAL3A", 0, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_110"); + yield return new TestCaseData("PAL3A", 0, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_111"); + yield return new TestCaseData("PAL3A", 0, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_112"); + yield return new TestCaseData("PAL3A", 0, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_113"); + yield return new TestCaseData("PAL3A", 1, -101, -37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_114"); + yield return new TestCaseData("PAL3A", 1, -101, -37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_115"); + yield return new TestCaseData("PAL3A", 1, 101, 37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_116"); + yield return new TestCaseData("PAL3A", 1, 101, 37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_117"); + yield return new TestCaseData("PAL3A", 1, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_118"); + yield return new TestCaseData("PAL3A", 1, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_119"); + yield return new TestCaseData("PAL3A", 49, -101, -37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_120"); + yield return new TestCaseData("PAL3A", 49, -101, -37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_121"); + yield return new TestCaseData("PAL3A", 49, 101, 37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_122"); + yield return new TestCaseData("PAL3A", 49, 101, 37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_123"); + yield return new TestCaseData("PAL3A", 49, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_124"); + yield return new TestCaseData("PAL3A", 49, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_125"); + yield return new TestCaseData("PAL3A", 50, -101, -37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_126"); + yield return new TestCaseData("PAL3A", 50, -101, -37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_127"); + yield return new TestCaseData("PAL3A", 50, 101, 37, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_128"); + yield return new TestCaseData("PAL3A", 50, 101, 37, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_129"); + yield return new TestCaseData("PAL3A", 50, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_130"); + yield return new TestCaseData("PAL3A", 50, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_131"); + yield return new TestCaseData("PAL3A", 51, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_132"); + yield return new TestCaseData("PAL3A", 51, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_133"); + yield return new TestCaseData("PAL3A", 51, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_134"); + yield return new TestCaseData("PAL3A", 51, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_135"); + yield return new TestCaseData("PAL3A", 51, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_136"); + yield return new TestCaseData("PAL3A", 51, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_137"); + yield return new TestCaseData("PAL3A", 99, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_138"); + yield return new TestCaseData("PAL3A", 99, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_139"); + yield return new TestCaseData("PAL3A", 99, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_140"); + yield return new TestCaseData("PAL3A", 99, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_141"); + yield return new TestCaseData("PAL3A", 99, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_142"); + yield return new TestCaseData("PAL3A", 99, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_143"); + yield return new TestCaseData("PAL3A", 100, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_144"); + yield return new TestCaseData("PAL3A", 100, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_145"); + yield return new TestCaseData("PAL3A", 100, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_146"); + yield return new TestCaseData("PAL3A", 100, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_147"); + yield return new TestCaseData("PAL3A", 100, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_148"); + yield return new TestCaseData("PAL3A", 100, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_149"); + yield return new TestCaseData("PAL3A", 149, -101, -37, 1u, -151, 3357800067u).SetName("PAL3A_CoAttackNative_150"); + yield return new TestCaseData("PAL3A", 149, -101, -37, 305419896u, -135, 1530878130u).SetName("PAL3A_CoAttackNative_151"); + yield return new TestCaseData("PAL3A", 149, 101, 37, 1u, 125, 3357800067u).SetName("PAL3A_CoAttackNative_152"); + yield return new TestCaseData("PAL3A", 149, 101, 37, 305419896u, 141, 1530878130u).SetName("PAL3A_CoAttackNative_153"); + yield return new TestCaseData("PAL3A", 149, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_154"); + yield return new TestCaseData("PAL3A", 149, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_155"); + yield return new TestCaseData("PAL3A", 150, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_156"); + yield return new TestCaseData("PAL3A", 150, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_157"); + yield return new TestCaseData("PAL3A", 150, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_158"); + yield return new TestCaseData("PAL3A", 150, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_159"); + yield return new TestCaseData("PAL3A", 150, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_160"); + yield return new TestCaseData("PAL3A", 150, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_161"); + yield return new TestCaseData("PAL3A", 151, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_162"); + yield return new TestCaseData("PAL3A", 151, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_163"); + yield return new TestCaseData("PAL3A", 151, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_164"); + yield return new TestCaseData("PAL3A", 151, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_165"); + yield return new TestCaseData("PAL3A", 151, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_166"); + yield return new TestCaseData("PAL3A", 151, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_167"); + yield return new TestCaseData("PAL3A", 199, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_168"); + yield return new TestCaseData("PAL3A", 199, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_169"); + yield return new TestCaseData("PAL3A", 199, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_170"); + yield return new TestCaseData("PAL3A", 199, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_171"); + yield return new TestCaseData("PAL3A", 199, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_172"); + yield return new TestCaseData("PAL3A", 199, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_173"); + yield return new TestCaseData("PAL3A", 200, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_174"); + yield return new TestCaseData("PAL3A", 200, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_175"); + yield return new TestCaseData("PAL3A", 200, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_176"); + yield return new TestCaseData("PAL3A", 200, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_177"); + yield return new TestCaseData("PAL3A", 200, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_178"); + yield return new TestCaseData("PAL3A", 200, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_179"); + yield return new TestCaseData("PAL3A", 249, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_180"); + yield return new TestCaseData("PAL3A", 249, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_181"); + yield return new TestCaseData("PAL3A", 249, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_182"); + yield return new TestCaseData("PAL3A", 249, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_183"); + yield return new TestCaseData("PAL3A", 249, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_184"); + yield return new TestCaseData("PAL3A", 249, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_185"); + yield return new TestCaseData("PAL3A", 250, -101, -37, 1u, -289, 3357800067u).SetName("PAL3A_CoAttackNative_186"); + yield return new TestCaseData("PAL3A", 250, -101, -37, 305419896u, -259, 1530878130u).SetName("PAL3A_CoAttackNative_187"); + yield return new TestCaseData("PAL3A", 250, 101, 37, 1u, 263, 3357800067u).SetName("PAL3A_CoAttackNative_188"); + yield return new TestCaseData("PAL3A", 250, 101, 37, 305419896u, 293, 1530878130u).SetName("PAL3A_CoAttackNative_189"); + yield return new TestCaseData("PAL3A", 250, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_190"); + yield return new TestCaseData("PAL3A", 250, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_191"); + yield return new TestCaseData("PAL3A", 251, -101, -37, 1u, -414, 3357800067u).SetName("PAL3A_CoAttackNative_192"); + yield return new TestCaseData("PAL3A", 251, -101, -37, 305419896u, -409, 1530878130u).SetName("PAL3A_CoAttackNative_193"); + yield return new TestCaseData("PAL3A", 251, 101, 37, 1u, 414, 3357800067u).SetName("PAL3A_CoAttackNative_194"); + yield return new TestCaseData("PAL3A", 251, 101, 37, 305419896u, 419, 1530878130u).SetName("PAL3A_CoAttackNative_195"); + yield return new TestCaseData("PAL3A", 251, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_196"); + yield return new TestCaseData("PAL3A", 251, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_197"); + yield return new TestCaseData("PAL3A", 300, -101, -37, 1u, -414, 3357800067u).SetName("PAL3A_CoAttackNative_198"); + yield return new TestCaseData("PAL3A", 300, -101, -37, 305419896u, -409, 1530878130u).SetName("PAL3A_CoAttackNative_199"); + yield return new TestCaseData("PAL3A", 300, 101, 37, 1u, 414, 3357800067u).SetName("PAL3A_CoAttackNative_200"); + yield return new TestCaseData("PAL3A", 300, 101, 37, 305419896u, 419, 1530878130u).SetName("PAL3A_CoAttackNative_201"); + yield return new TestCaseData("PAL3A", 300, 0, 0, 1u, 0, 1u).SetName("PAL3A_CoAttackNative_202"); + yield return new TestCaseData("PAL3A", 300, 0, 0, 305419896u, 0, 305419896u).SetName("PAL3A_CoAttackNative_203"); + } + + [TestCaseSource(nameof(NativeCases))] + public void MatchesOriginalPowerAndRandomState(string variant, int multiplier, int firstDamage, + int secondDamage, uint seed, int expected, uint finalState) + { + var random = new BattleRandom(unchecked((int)seed)); + var rules = new BattleCoAttackRules(variant); + var visited = new List(); + int power = rules.Power(new[] { 101, 102, 0, 0 }, id => + { + visited.Add(id); + return id == 101 ? firstDamage : secondDamage; + }, multiplier, random); + Assert.That(power, Is.EqualTo(expected)); + Assert.That(random.State, Is.EqualTo(finalState)); + Assert.That(visited, Is.EqualTo(new[] { 101, 102 })); + } + + [TestCase("PAL3", 0)] + [TestCase("PAL3A", 12)] + public void ZeroValuesFollowThePublishedLoop(string variant, int expectedCount) + { + var rules = new BattleCoAttackRules(variant); + Assert.That(rules.EvaluationIndices(new int[12]).Count, Is.EqualTo(expectedCount)); + Assert.That(Enumerable.Range(0, 12).Where(BattleCoAttackRules.WritesResource), Is.EqualTo(new[] { 0, 1, 2 })); + Assert.That(BattleCoAttackRules.SignedPower(-151, 0), Is.EqualTo(-151)); + Assert.That(BattleCoAttackRules.SignedPower(-151, 1), Is.EqualTo(151)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleCoAttackRulesTests.cs.meta b/Assets/Tests/Battle/Editor/BattleCoAttackRulesTests.cs.meta new file mode 100644 index 00000000..61723a94 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleCoAttackRulesTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cf5e36936e0d450fac067bd459de97e4 diff --git a/Assets/Tests/Battle/Editor/BattleCoAttackSessionTests.cs b/Assets/Tests/Battle/Editor/BattleCoAttackSessionTests.cs new file mode 100644 index 00000000..20b07879 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleCoAttackSessionTests.cs @@ -0,0 +1,606 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleCoAttackSessionTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattleCoAttackTimings, IBattleStageGeometry + { + private readonly Dictionary _actors; + internal BattleComboStageProfile Profile = new(439, 440, .05f, .2f, .1f, enemyCenter: new BattleMovementPoint(1500, 0, 0)); + + internal Catalog(BattleScenario scenario) => _actors = scenario.Participants.ToDictionary(actor => actor.InstanceId); + + public AttackTiming Attack(string source, string target) => new(0, 1000, new[] { 500 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 20, new[] { 5 }); + + public BattleComboStageProfile CoAttack(string actor, BattleComboDefinition combo) => Profile; + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 5; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor switch { "A" => 0, "B" => 1, "C" => 2, "D" => 3, "Z" => 10, _ => 5 }; + + public int DamageDivisor(string actor) => 1; + + public BattleMovementPoint CoAttackHome(string actor, BattleSlot slot) => FormationHome(actor, slot); + + public BattleMovementPoint InitialHome(string actor) => FormationHome(actor, _actors[actor].Slot); + + public BattleMovementPoint FormationHome(string actor, BattleSlot slot) => + new((_actors[actor].Side == BattleSide.Enemy ? 1000 : 0) + 100 * (int)slot, 0, 0); + + public BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint sourceHome, BattleMovementPoint targetHome) => + new(Attack(source, target), sourceHome, sourceHome, targetHome); + + public IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint from, BattleMovementPoint to, bool midpoint) => + new[] { new BattleMovementPlan(BattleMovementKind.Run, from, to) }; + } + + private sealed class Rules : IBattleRules + { + private readonly HashSet _ready; + + internal Rules(params string[] ready) => _ready = new HashSet(ready.Length == 0 ? new[] { "A" } : ready); + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + _ready.Contains(actor.InstanceId) ? BattleSession.FullGauge : 600; + + public int GaugePerStep(BattleParticipant actor) => 1; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => new(-10, false, false); + } + + private sealed class Director : IBattleEffectDirector, IBattleEffectPreloader + { + private readonly Dictionary _running = new(); + private long _next; + internal BattleSession Session; + internal float Duration = .4f; + internal readonly List Started = new(); + internal readonly List Stopped = new(); + internal readonly List Preloaded = new(); + + public void Preload(int groupId) => Preloaded.Add(groupId); + + public long Start(BattleEffectRequest request) + { + Started.Add(request); + _running.Add(++_next, Session.CoAttacks.Single().Steps[(int)BattleCoAttackStep.Act].StartTime); + return _next; + } + + public bool IsRunning(long handle) + { + if (!_running.TryGetValue(handle, out float actStarted)) + return false; + return (double)BattleStageScheduler.TimeAt(Session.SimulationTick) - actStarted < Duration; + } + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + _running.Remove(handle); + Stopped.Add(handle); + } + } + + private sealed class Occupied : IBattleStageJob + { + public bool Advance(BattleStageContext context) => false; + } + + private sealed class CompletedEffects : IBattleEffectDirector + { + private long _next; + + public long Start(BattleEffectRequest request) => ++_next; + + public bool IsRunning(long handle) => false; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + } + } + + private static BattleParticipant Participant(string id, int resource, BattleSide side, BattleSlot slot) => new() + { + InstanceId = id, + ActorId = resource, + Side = side, + Slot = slot, + Level = 1, + Attributes = new[] { 5000, 500, 500, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 5000, 500, 500 } + }; + + private static BattleScenario Scenario(string variant, bool party = false, bool centerEnemy = false) + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "coattack", Seed = 1 }; + scenario.Participants.Add(Participant("A", 101, BattleSide.Ally, BattleSlot.Water)); + if (party) + { + scenario.Participants.Add(Participant("B", variant == "PAL3" ? 104 : 102, BattleSide.Ally, BattleSlot.Fire)); + scenario.Participants.Add(Participant("C", variant == "PAL3" ? 105 : 103, BattleSide.Ally, BattleSlot.Wind)); + scenario.Participants.Add(Participant("D", variant == "PAL3" ? 107 : 104, BattleSide.Ally, BattleSlot.Center)); + } + scenario.Participants.Add(Participant("E", 701, BattleSide.Enemy, BattleSlot.Water)); + if (centerEnemy) + scenario.Participants.Add(Participant("Z", 702, BattleSide.Enemy, BattleSlot.Center)); + return scenario; + } + + private static BattleComboDefinition Combo(int id = 501, int trigger = 0, int range = 2, + int second = 0, int[] values = null, int first = 101) => new("native combo " + id, + new BattleComboRequirement(id, trigger, new[] { first, second, 0, 0 }, new int[4], new int[4], new[] { -1, -1, -1 }), + range, values ?? new int[12], 100); + + private static BattleSession Session(BattleScenario scenario, out Catalog catalog, out Director director, + IEnumerable combos = null, BattleAbilityDefinition ability = null, params string[] ready) + { + if (ability != null) + scenario.Participants[0].Skills.Add(new BattleSkill { Id = ability.Id, Level = 1, Mastered = true }); + catalog = new Catalog(scenario); + director = new Director(); + var definitions = new BattleDefinitions(scenario.Variant, scenario.DataFingerprint, + ability == null ? Array.Empty() : new[] { ability }, Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId switch { "A" => 0, "B" => 1, "C" => 2, "D" => 3, _ => -1 }, + NormalAttackMode = 924, + Boss = actor.InstanceId == "Z" + })), combos ?? new[] { Combo() }); + var session = new BattleSession(new BattleSetup(scenario), catalog, new Rules(ready), definitions, director); + director.Session = session; + return session; + } + + private static object NativeActor(BattleSession session, string id) => + ((IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session))[id]; + + private static void RequestEnd(BattleSession session) => typeof(BattleSession).GetMethod("RequestRoleEnd", BindingFlags.Instance | BindingFlags.NonPublic) + .Invoke(session, new[] { NativeActor(session, "A") }); + + private static BattleActorSnapshot Actor(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + private static void Step(BattleSession session) + { + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + } + + private static void Until(BattleSession session, Func done, int maximum = 700) + { + for (int i = 0; i < maximum && !done(); i++) + Step(session); + Assert.That(done(), Is.True, "The original combo boundary was not reached."); + } + + [Test] + public void ACompanionWithZeroInitialHpQualifiesForADeathConditionOnTheFirstCommand() + { + BattleScenario scenario = Scenario("PAL3", party: true); + scenario.Participants.Single(actor => actor.InstanceId == "B").Vitals[0] = 0; + var combo = new BattleComboDefinition("Death condition", + new BattleComboRequirement(501, 0, new[] { 101, 104, 0, 0 }, new int[4], new int[4], + new[] { (int)BattleState.Death, -1, -1 }), 2, new int[12], 100); + BattleSession session = Session(scenario, out _, out _, new[] { combo }); + + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Step(session); + + Assert.That(session.CoAttacks.Single().ComboId, Is.EqualTo(combo.Id)); + } + + public static IEnumerable NativeWriterCases() + { + yield return new TestCaseData("PAL3", -1, 0, false, 4812, 500, 0, 3403800452u); + yield return new TestCaseData("PAL3", -1, 0, true, 4812, 500, 0, 3884216597u); + yield return new TestCaseData("PAL3", -1, 5, false, 4812, 500, 5, 3403800452u); + yield return new TestCaseData("PAL3", -1, 5, true, 4812, 500, 5, 3884216597u); + yield return new TestCaseData("PAL3", -1, 500, false, 4812, 500, 500, 3403800452u); + yield return new TestCaseData("PAL3", -1, 500, true, 4812, 500, 500, 3884216597u); + yield return new TestCaseData("PAL3", 0, 0, false, 5000, 500, 0, 1u); + yield return new TestCaseData("PAL3", 0, 0, true, 5000, 500, 0, 1u); + yield return new TestCaseData("PAL3", 0, 5, false, 5000, 500, 5, 1u); + yield return new TestCaseData("PAL3", 0, 5, true, 5000, 500, 5, 1u); + yield return new TestCaseData("PAL3", 0, 500, false, 5000, 500, 500, 1u); + yield return new TestCaseData("PAL3", 0, 500, true, 5000, 500, 500, 1u); + yield return new TestCaseData("PAL3", 1, 0, false, 5188, 500, 0, 3403800452u); + yield return new TestCaseData("PAL3", 1, 0, true, 5188, 500, 0, 3884216597u); + yield return new TestCaseData("PAL3", 1, 5, false, 5188, 500, 5, 3403800452u); + yield return new TestCaseData("PAL3", 1, 5, true, 5188, 500, 5, 3884216597u); + yield return new TestCaseData("PAL3", 1, 500, false, 5188, 500, 500, 3403800452u); + yield return new TestCaseData("PAL3", 1, 500, true, 5188, 500, 500, 3884216597u); + yield return new TestCaseData("PAL3A", -1, 0, false, 4903, 396, 0, 2597632883u); + yield return new TestCaseData("PAL3A", -1, 0, true, 4903, 396, 0, 2652862833u); + yield return new TestCaseData("PAL3A", -1, 5, false, 4903, 396, 0, 2597632883u); + yield return new TestCaseData("PAL3A", -1, 5, true, 4903, 396, 0, 2652862833u); + yield return new TestCaseData("PAL3A", -1, 500, false, 4903, 396, 397, 2597632883u); + yield return new TestCaseData("PAL3A", -1, 500, true, 4903, 396, 397, 2652862833u); + yield return new TestCaseData("PAL3A", 0, 0, false, 4903, 396, 0, 2597632883u); + yield return new TestCaseData("PAL3A", 0, 0, true, 4903, 396, 0, 2652862833u); + yield return new TestCaseData("PAL3A", 0, 5, false, 4903, 396, 0, 2597632883u); + yield return new TestCaseData("PAL3A", 0, 5, true, 4903, 396, 0, 2652862833u); + yield return new TestCaseData("PAL3A", 0, 500, false, 4903, 396, 397, 2597632883u); + yield return new TestCaseData("PAL3A", 0, 500, true, 4903, 396, 397, 2652862833u); + yield return new TestCaseData("PAL3A", 1, 0, false, 5097, 396, 0, 2597632883u); + yield return new TestCaseData("PAL3A", 1, 0, true, 5097, 396, 0, 2652862833u); + yield return new TestCaseData("PAL3A", 1, 5, false, 5097, 396, 0, 2597632883u); + yield return new TestCaseData("PAL3A", 1, 5, true, 5097, 396, 0, 2652862833u); + yield return new TestCaseData("PAL3A", 1, 500, false, 5097, 396, 397, 2597632883u); + yield return new TestCaseData("PAL3A", 1, 500, true, 5097, 396, 397, 2652862833u); + } + + [TestCaseSource(nameof(NativeWriterCases))] + public void OriginalNormalDamagePowerAndWritersKeepNativeValuesAndRng(string variant, int rawHp, int initialMp, + bool poolFull, int hp, int sp, int mp, uint expectedSeed) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Attributes[0] = 6000; + scenario.Participants[1].Vitals[2] = initialMp; + BattleSession session = Session(scenario, out _, out _, new[] { Combo(values: new[] { rawHp, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) }); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Until(session, () => session.CoAttacks.SingleOrDefault()?.Steps[(int)BattleCoAttackStep.Act].Status == BattleCoAttackStepStatus.Running); + if (poolFull) + { + var stage = (BattleStageScheduler)typeof(BattleSession).GetField("_stage", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + while (stage.Count < BattleStageScheduler.DefaultCapacity) + stage.Add("occupied slot", "fixture", new Occupied(), BattleStageScheduler.TimeAt(session.SimulationTick)); + } + Until(session, () => session.CoAttacks.Single().Worked); + Assert.That((Actor(session, "E").Hp, Actor(session, "E").Sp, Actor(session, "E").Mp), Is.EqualTo((hp, sp, mp))); + var random = (BattleRandom)typeof(BattleSession).GetField("_random", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + Assert.That(random.State, Is.EqualTo(expectedSeed)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void PreloadRunsBehindTheFirstFadeBeforeAnyEffectStarts(string variant) + { + BattleSession session = Session(Scenario(variant), out _, out Director director); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Until(session, () => director.Preloaded.Count > 0); + Assert.That(director.Preloaded, Is.EqualTo(new[] { 439, 440 })); + Assert.That(director.Started, Is.Empty); + Assert.That(session.CoAttackScreenOpacity, Is.EqualTo(1f)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AnyKeyOnlySkipsPresentationAndCannotFastForwardNativeWork(string variant) + { + BattleSession session = Session(Scenario(variant), out _, out _); + Assert.That(session.SkipCoAttackPresentation(), Is.False); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + for (int tick = 0; tick < 20 && session.CoAttacks + .FirstOrDefault()?.Steps[(int)BattleCoAttackStep.Act].Status != BattleCoAttackStepStatus.Running; tick++) + { + if (session.IsCoAttackPresentationBlockingInput) + { + Assert.That(session.SkipCoAttackPresentation(), Is.True); + Assert.That(session.SkipCoAttackPresentation(), Is.False, "One skip applies to one presentation subtask."); + } + Step(session); + } + + BattleCoAttackSnapshot stage = session.CoAttacks.Single(); + Assert.That(stage.Steps[(int)BattleCoAttackStep.Act].Status, Is.EqualTo(BattleCoAttackStepStatus.Running)); + Assert.That(session.IsCoAttackPresentationBlockingInput, Is.False); + Assert.That(stage.Worked, Is.False); + Assert.That(stage.NameVisible, Is.True); + int inputs = session.Inputs.Count; + Assert.That(session.SkipCoAttackPresentation(), Is.False); + Step(session); + Assert.That(session.CoAttacks.Single().NameVisible, Is.True, "The title runs its own native timer."); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs)); + Until(session, () => session.CoAttacks.Single().Worked); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void PresentationSkipInputsReplayAtTheSameWallBoundaries(string variant) + { + BattleScenario scenario = Scenario(variant); + BattleSession session = Session(scenario, out Catalog catalog, out Director director); + director.Duration = 0; + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + for (int tick = 0; tick < 30; tick++) + { + session.SkipCoAttackPresentation(); + Step(session); + } + Assert.That(session.Inputs.Any(input => input.Kind == BattleInputKind.CoAttackPresentationSkip), Is.True); + BattleSession replay = BattleReplay.Play(new BattleSetup(scenario), catalog, session.Inputs, + session.Tick, new Rules(), session.Definitions, new CompletedEffects()); + Assert.That(replay.Actors.Select(actor => (actor.Id, actor.Hp, actor.Sp, actor.Mp, actor.Gauge, actor.Position)), + Is.EqualTo(session.Actors.Select(actor => (actor.Id, actor.Hp, actor.Sp, actor.Mp, actor.Gauge, actor.Position)))); + Assert.That(replay.Events.Select(value => (value.Tick, value.Kind, value.RandomState)), + Is.EqualTo(session.Events.Select(value => (value.Tick, value.Kind, value.RandomState)))); + } + + public static IEnumerable NativeStageCases() + { + yield return new TestCaseData("PAL3", 0.4f, 0, new[] { 1, 1, 52, 52, 52, 103, 104, 104, 124, 124, 175, 175, 226 }, 109, 227); + yield return new TestCaseData("PAL3", 0.4f, 1, new[] { 1, 1, 2, 2, 2, 3, 4, 4, 25, 25, 26, 26, 27 }, 9, 28); + yield return new TestCaseData("PAL3", 0.4f, 2, new[] { 1, 1, 52, 52, 52, 103, 104, 104, 124, 124, 125, 125, 126 }, 109, 127); + yield return new TestCaseData("PAL3", 5.0f, 0, new[] { 1, 1, 52, 52, 52, 103, 104, 104, 354, 354, 405, 405, 456 }, 109, 457); + yield return new TestCaseData("PAL3", 5.0f, 1, new[] { 1, 1, 2, 2, 2, 3, 4, 4, 255, 255, 256, 256, 257 }, 9, 258); + yield return new TestCaseData("PAL3", 5.0f, 2, new[] { 1, 1, 52, 52, 52, 103, 104, 104, 354, 354, 355, 355, 356 }, 109, 357); + yield return new TestCaseData("PAL3A", 0.4f, 0, new[] { 1, 1, 52, 52, 52, 103, 104, 104, 109, 109, 160, 160, 211 }, 109, 212); + yield return new TestCaseData("PAL3A", 0.4f, 1, new[] { 1, 1, 2, 2, 2, 3, 4, 4, 9, 9, 10, 10, 11 }, 9, 12); + yield return new TestCaseData("PAL3A", 0.4f, 2, new[] { 1, 1, 52, 52, 52, 103, 104, 104, 109, 109, 110, 110, 111 }, 109, 112); + yield return new TestCaseData("PAL3A", 5.0f, 0, new[] { 1, 1, 52, 52, 52, 103, 104, 104, 109, 109, 160, 160, 211 }, 109, 212); + yield return new TestCaseData("PAL3A", 5.0f, 1, new[] { 1, 1, 2, 2, 2, 3, 4, 4, 9, 9, 10, 10, 11 }, 9, 12); + yield return new TestCaseData("PAL3A", 5.0f, 2, new[] { 1, 1, 52, 52, 52, 103, 104, 104, 109, 109, 110, 110, 111 }, 109, 112); + } + + [TestCaseSource(nameof(NativeStageCases))] + public void ThirteenStagesMatchPublishedDoTaskFadeAndActVectors(string variant, float effectDuration, int requireMode, + int[] starts, int workTick, int finishTick) + { + BattleSession session = Session(Scenario(variant), out _, out Director director); + director.Duration = effectDuration; + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + if (requireMode == 1) + RequestEnd(session); + int? observedWork = null; + BattleCoAttackSnapshot last = null; + for (int tick = 1; tick <= finishTick; tick++) + { + Step(session); + last = session.CoAttacks.Single(); + if (last.Worked && !observedWork.HasValue) + observedWork = tick; + for (int index = 0; index < starts.Length; index++) + { + if (last.Steps[index].Status != BattleCoAttackStepStatus.Ready) + Assert.That(last.Steps[index].StartTime, Is.EqualTo(BattleStageScheduler.TimeAt(starts[index])), variant + " sub " + index); + } + if (requireMode == 2 && tick == starts[(int)BattleCoAttackStep.Act]) + RequestEnd(session); + Assert.That(last.Finished, Is.EqualTo(tick == finishTick), variant + " tick " + tick); + } + Assert.That(observedWork, Is.EqualTo(workTick)); + Assert.That(last.Steps.All(sub => sub.Status == BattleCoAttackStepStatus.Finished), Is.True); + Step(session); + Assert.That(session.CoAttacks, Is.Empty); + Assert.That(session.IsCoAttackAtbPaused, Is.False); + Assert.That(Actor(session, "A").CurrentAction, Is.Null); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AutomaticReplacementKeepsTheFirstMatchingRecord(string variant) + { + BattleSession session = Session(Scenario(variant), out _, out _, new[] { Combo(502), Combo(501) }); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Step(session); + Assert.That(session.CoAttacks.Single().ComboId, Is.EqualTo(502)); + Assert.That(Actor(session, "A").AbilityId, Is.EqualTo(502)); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Idle)); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", false)] + [TestCase("PAL3A", true)] + public void TriggerSkillDoesNotStartCastingOrPayItsOrdinaryCost(string variant, bool magic) + { + var ability = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 2001, + SkillTypeId = magic ? 1 : 0, + IsMagic = magic, + Range = BattleTargetRange.OpponentSingle, + Costs = new[] { new BattleCost(magic ? 2 : 1, BattleValueMode.Absolute, 50) }, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -20) } + }); + BattleSession session = Session(Scenario(variant), out _, out _, new[] { Combo(trigger: ability.Id) }, ability); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Step(session); + Assert.That(session.CoAttacks.Count, Is.EqualTo(1)); + Assert.That((Actor(session, "A").Gauge, Actor(session, "A").CastGauge), Is.EqualTo((0, 0))); + Until(session, () => session.CoAttacks.Count == 0); + Assert.That((Actor(session, "A").Sp, Actor(session, "A").Mp, Actor(session, "A").Skills.Single().Uses), Is.EqualTo((500, 500, 0))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void HelpersRetainTheirExistingActionsAndUnspentGauges(string variant) + { + BattleScenario scenario = Scenario(variant, true); + BattleSession session = Session(scenario, out _, out _, new[] { Combo(second: scenario.Participants[1].ActorId) }, ready: new[] { "A", "B" }); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Assert.That(session.Submit("B", BattleAction.Attack, "E"), Is.True); + long helperAction = Actor(session, "B").ActionId; + for (int i = 0; i < 10; i++) + Step(session); + Assert.That(Actor(session, "B").CurrentAction, Is.EqualTo(BattleAction.Attack)); + Assert.That((Actor(session, "B").ActionId, Actor(session, "B").ActionTick), Is.EqualTo((helperAction, 10))); + Assert.That((Actor(session, "C").Gauge, Actor(session, "D").Gauge), Is.EqualTo((600, 600))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void DeadAuxiliariesRemainEligibleAndTheirOriginalBodiesAreNotCleared(string variant) + { + BattleScenario scenario = Scenario(variant, true); + scenario.Participants[1].Vitals[0] = 0; + BattleSession session = Session(scenario, out _, out _, new[] { Combo(second: scenario.Participants[1].ActorId, values: new[] { -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) }); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Step(session); + Assert.That(session.CoAttacks.Count, Is.EqualTo(1)); + Until(session, () => session.CoAttacks.Single().Worked); + Assert.That(Actor(session, "E").Hp, Is.LessThan(5000)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void SourceDeathDuringActDoesNotPreventNativeWork(string variant) + { + BattleSession session = Session(Scenario(variant, true), out _, out _, new[] { Combo(values: new[] { -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) }); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Until(session, () => session.CoAttacks.SingleOrDefault()?.Steps[(int)BattleCoAttackStep.Act].Status == BattleCoAttackStepStatus.Running); + typeof(BattleSession).GetMethod("ChangeHp", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(session, + new[] { NativeActor(session, "A"), (object)-100000, null, 0L, "native death port", false, false, false }); + Until(session, () => session.CoAttacks.Single().Worked); + Assert.That(Actor(session, "A").AliveFlag, Is.False); + Assert.That(Actor(session, "E").Hp, Is.LessThan(5000)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RangeTwoCentersTheTargetAndRestoresBothTargetAndCenterVisibility(string variant) + { + BattleSession session = Session(Scenario(variant, true, true), out _, out _, new[] { Combo() }); + // The old enemy target is kept even when another target is a boss. + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Until(session, () => session.CoAttacks.SingleOrDefault()?.Steps[(int)BattleCoAttackStep.SetComboPositions].Status == BattleCoAttackStepStatus.Finished); + Assert.That(Actor(session, "E").Position.X, Is.EqualTo(1500)); + Assert.That(session.CoAttackActorVisible("Z"), Is.False); + Assert.That(session.CoAttackActorVisible("D"), Is.EqualTo(variant != "PAL3A")); + Until(session, () => session.CoAttacks.Count == 0); + Assert.That(Actor(session, "E").Position.X, Is.EqualTo(1000)); + Assert.That(session.CoAttackActorVisible("Z"), Is.True); + Assert.That(session.CoAttackActorVisible("D"), Is.True); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void CenterEnemyDeathDuringComboDoesNotLeaveAStaleVisibilityMask(string variant) + { + BattleSession session = Session(Scenario(variant, true, true), out _, out _); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Until(session, () => !session.CoAttackActorVisible("Z")); + typeof(BattleSession).GetMethod("ChangeHp", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(session, + new[] { NativeActor(session, "Z"), (object)-5000, null, 0L, "lethal during combo", false, false, false }); + Until(session, () => !Actor(session, "Z").ModelAliveFlag); + Assert.That(session.CoAttackActorVisible("Z"), Is.False); + Until(session, () => session.CoAttacks.Count == 0); + Assert.That(Actor(session, "Z").ModelAliveFlag, Is.False); + Assert.That(session.CoAttackActorVisible("Z"), Is.True); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void CancellingOneOverlappingComboKeepsTheOtherComboPresentation(string variant) + { + BattleScenario scenario = Scenario(variant, true, true); + BattleComboDefinition[] combos = { Combo(), Combo(id: 502, first: scenario.Participants[1].ActorId) }; + BattleSession session = Session(scenario, out _, out _, combos, ready: new[] { "A", "B" }); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Step(session); + Assert.That(session.Submit("B", BattleAction.Attack, "E"), Is.True); + Until(session, () => session.CoAttacks.Count == 2 && session.CoAttacks.All(combo => + combo.Steps[(int)BattleCoAttackStep.SetComboPositions].Status == BattleCoAttackStepStatus.Finished)); + float opacity = session.CoAttackScreenOpacity; + int enemyGauge = Actor(session, "E").Gauge; + + Assert.That(session.CancelAction("A"), Is.True); + Assert.That(session.CoAttacks.Single().Source, Is.EqualTo("B")); + Assert.That(session.IsCoAttackAtbPaused, Is.True); + Assert.That(session.CoAttackActorVisible("Z"), Is.False); + Assert.That(Actor(session, "E").Position.X, Is.EqualTo(1500)); + Assert.That(session.CoAttackScreenOpacity, Is.EqualTo(opacity)); + Step(session); + Assert.That(Actor(session, "E").Gauge, Is.EqualTo(enemyGauge)); + + Assert.That(session.CancelAction("B"), Is.True); + Assert.That(session.IsCoAttackAtbPaused, Is.False); + Assert.That(session.CoAttackActorVisible("Z"), Is.True); + Assert.That(Actor(session, "E").Position.X, Is.EqualTo(1000)); + Assert.That(session.CoAttackScreenOpacity, Is.Zero); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AlreadyReadyHelpersCanStillChooseCommandsWhileTheGaugeIsPaused(string variant) + { + BattleSession session = Session(Scenario(variant, true), out _, out _, ready: new[] { "A", "B" }); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Step(session); + Assert.That(session.IsCoAttackAtbPaused, Is.True); + Assert.That(session.WaitingActor, Is.EqualTo("B")); + Assert.That(session.Submit("B", BattleAction.Attack, "E"), Is.True); + } + + [Test] + public void Pal3RedLongkuiMemberUsesTheSameOriginalBodyAsBlueLongkui() + { + BattleSession session = Session(Scenario("PAL3", true), out _, out _, new[] { Combo(second: 106, values: new[] { -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) }); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Until(session, () => session.CoAttacks.SingleOrDefault()?.Worked == true); + Assert.That(Actor(session, "E").Hp, Is.LessThan(4700)); + } + + [Test] + public void Pal3AEarlyCompletionLetsEffectsRetireAfterTheDirectorThread() + { + BattleSession session = Session(Scenario("PAL3A"), out _, out Director director); + director.Duration = 5f; + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Step(session); + Until(session, () => session.CoAttacks.Count == 0); + Assert.That(director.Started.Count, Is.EqualTo(1)); + Assert.That(director.Stopped, Is.Empty); + session.Abort(); + Assert.That(director.Stopped.Count, Is.EqualTo(1)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void StageAllocationFailureClearsOnlySourceAndLeavesTheBattleRunning(string variant) + { + BattleSession session = Session(Scenario(variant, true), out _, out _); + var stage = (BattleStageScheduler)typeof(BattleSession).GetField("_stage", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + for (int i = 0; i < BattleStageScheduler.DefaultCapacity; i++) + stage.Add("occupied slot", "fixture", new Occupied(), 0); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Step(session); + Assert.That(session.CoAttacks, Is.Empty); + Assert.That(session.IsCoAttackAtbPaused, Is.False); + Assert.That(Actor(session, "A").CurrentAction, Is.Null); + Assert.That(Actor(session, "B").Gauge, Is.EqualTo(601)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AbortStopsOwnedEffectsAndReleasesThePresentation(string variant) + { + BattleSession session = Session(Scenario(variant), out _, out Director director); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Until(session, () => director.Started.Count > 0); + session.Abort(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Aborted)); + Assert.That(session.CoAttacks, Is.Empty); + Assert.That(session.IsCoAttackAtbPaused, Is.False); + Assert.That(session.CoAttackScreenOpacity, Is.Zero); + Assert.That(director.Stopped.Count, Is.GreaterThan(0)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleCoAttackSessionTests.cs.meta b/Assets/Tests/Battle/Editor/BattleCoAttackSessionTests.cs.meta new file mode 100644 index 00000000..1e682892 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleCoAttackSessionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a38a7dff2151497c9bdc36f8cb3d1460 diff --git a/Assets/Tests/Battle/Editor/BattleCoAttackTargetTests.cs b/Assets/Tests/Battle/Editor/BattleCoAttackTargetTests.cs new file mode 100644 index 00000000..24a7554d --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleCoAttackTargetTests.cs @@ -0,0 +1,224 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System.Collections.Generic; + using System.Linq; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleCoAttackTargetTests + { + // Independent outputs execute original GetCoAttackRange in both EXEs. + public static IEnumerable NativeCases() + { + yield return new TestCaseData("PAL3", 0, -1, "base", false, -1, "00000010100").SetName("PAL3_CoAttackTargetNative_0"); + yield return new TestCaseData("PAL3", 0, -1, "mixedDeadFledInvalid", false, -1, "00000010100").SetName("PAL3_CoAttackTargetNative_1"); + yield return new TestCaseData("PAL3", 0, -1, "bossFirst", false, -1, "00000010100").SetName("PAL3_CoAttackTargetNative_2"); + yield return new TestCaseData("PAL3", 0, -1, "bossDead", false, -1, "00000010100").SetName("PAL3_CoAttackTargetNative_3"); + yield return new TestCaseData("PAL3", 0, -1, "highestTie", false, -1, "00000010100").SetName("PAL3_CoAttackTargetNative_4"); + yield return new TestCaseData("PAL3", 0, 1, "base", false, 1, "00000010100").SetName("PAL3_CoAttackTargetNative_5"); + yield return new TestCaseData("PAL3", 0, 1, "mixedDeadFledInvalid", false, 1, "00000010100").SetName("PAL3_CoAttackTargetNative_6"); + yield return new TestCaseData("PAL3", 0, 1, "bossFirst", false, 1, "00000010100").SetName("PAL3_CoAttackTargetNative_7"); + yield return new TestCaseData("PAL3", 0, 1, "bossDead", false, 1, "00000010100").SetName("PAL3_CoAttackTargetNative_8"); + yield return new TestCaseData("PAL3", 0, 1, "highestTie", false, 1, "00000010100").SetName("PAL3_CoAttackTargetNative_9"); + yield return new TestCaseData("PAL3", 0, 5, "base", false, 5, "00000010100").SetName("PAL3_CoAttackTargetNative_10"); + yield return new TestCaseData("PAL3", 0, 5, "mixedDeadFledInvalid", false, 5, "00000010100").SetName("PAL3_CoAttackTargetNative_11"); + yield return new TestCaseData("PAL3", 0, 5, "bossFirst", false, 5, "00000010100").SetName("PAL3_CoAttackTargetNative_12"); + yield return new TestCaseData("PAL3", 0, 5, "bossDead", false, 5, "00000010100").SetName("PAL3_CoAttackTargetNative_13"); + yield return new TestCaseData("PAL3", 0, 5, "highestTie", false, 5, "00000010100").SetName("PAL3_CoAttackTargetNative_14"); + yield return new TestCaseData("PAL3", 1, -1, "base", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_15"); + yield return new TestCaseData("PAL3", 1, -1, "mixedDeadFledInvalid", true, -1, "11001000000").SetName("PAL3_CoAttackTargetNative_16"); + yield return new TestCaseData("PAL3", 1, -1, "bossFirst", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_17"); + yield return new TestCaseData("PAL3", 1, -1, "bossDead", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_18"); + yield return new TestCaseData("PAL3", 1, -1, "highestTie", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_19"); + yield return new TestCaseData("PAL3", 1, 1, "base", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_20"); + yield return new TestCaseData("PAL3", 1, 1, "mixedDeadFledInvalid", true, -1, "11001000000").SetName("PAL3_CoAttackTargetNative_21"); + yield return new TestCaseData("PAL3", 1, 1, "bossFirst", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_22"); + yield return new TestCaseData("PAL3", 1, 1, "bossDead", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_23"); + yield return new TestCaseData("PAL3", 1, 1, "highestTie", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_24"); + yield return new TestCaseData("PAL3", 1, 5, "base", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_25"); + yield return new TestCaseData("PAL3", 1, 5, "mixedDeadFledInvalid", true, -1, "11001000000").SetName("PAL3_CoAttackTargetNative_26"); + yield return new TestCaseData("PAL3", 1, 5, "bossFirst", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_27"); + yield return new TestCaseData("PAL3", 1, 5, "bossDead", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_28"); + yield return new TestCaseData("PAL3", 1, 5, "highestTie", true, -1, "11111000000").SetName("PAL3_CoAttackTargetNative_29"); + yield return new TestCaseData("PAL3", 2, -1, "base", false, 6, "00000010100").SetName("PAL3_CoAttackTargetNative_30"); + yield return new TestCaseData("PAL3", 2, -1, "mixedDeadFledInvalid", false, 6, "00000010100").SetName("PAL3_CoAttackTargetNative_31"); + yield return new TestCaseData("PAL3", 2, -1, "bossFirst", false, 6, "00000010100").SetName("PAL3_CoAttackTargetNative_32"); + yield return new TestCaseData("PAL3", 2, -1, "bossDead", false, 6, "00000010100").SetName("PAL3_CoAttackTargetNative_33"); + yield return new TestCaseData("PAL3", 2, -1, "highestTie", false, 6, "00000010100").SetName("PAL3_CoAttackTargetNative_34"); + yield return new TestCaseData("PAL3", 2, 1, "base", false, 10, "00000010100").SetName("PAL3_CoAttackTargetNative_35"); + yield return new TestCaseData("PAL3", 2, 1, "mixedDeadFledInvalid", false, 10, "00000010100").SetName("PAL3_CoAttackTargetNative_36"); + yield return new TestCaseData("PAL3", 2, 1, "bossFirst", false, 6, "00000010100").SetName("PAL3_CoAttackTargetNative_37"); + yield return new TestCaseData("PAL3", 2, 1, "bossDead", false, 8, "00000010100").SetName("PAL3_CoAttackTargetNative_38"); + yield return new TestCaseData("PAL3", 2, 1, "highestTie", false, 6, "00000010100").SetName("PAL3_CoAttackTargetNative_39"); + yield return new TestCaseData("PAL3", 2, 5, "base", false, 5, "00000010100").SetName("PAL3_CoAttackTargetNative_40"); + yield return new TestCaseData("PAL3", 2, 5, "mixedDeadFledInvalid", false, 5, "00000010100").SetName("PAL3_CoAttackTargetNative_41"); + yield return new TestCaseData("PAL3", 2, 5, "bossFirst", false, 5, "00000010100").SetName("PAL3_CoAttackTargetNative_42"); + yield return new TestCaseData("PAL3", 2, 5, "bossDead", false, 5, "00000010100").SetName("PAL3_CoAttackTargetNative_43"); + yield return new TestCaseData("PAL3", 2, 5, "highestTie", false, 5, "00000010100").SetName("PAL3_CoAttackTargetNative_44"); + yield return new TestCaseData("PAL3", 3, -1, "base", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_45"); + yield return new TestCaseData("PAL3", 3, -1, "mixedDeadFledInvalid", true, -1, "00000100111").SetName("PAL3_CoAttackTargetNative_46"); + yield return new TestCaseData("PAL3", 3, -1, "bossFirst", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_47"); + yield return new TestCaseData("PAL3", 3, -1, "bossDead", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_48"); + yield return new TestCaseData("PAL3", 3, -1, "highestTie", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_49"); + yield return new TestCaseData("PAL3", 3, 1, "base", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_50"); + yield return new TestCaseData("PAL3", 3, 1, "mixedDeadFledInvalid", true, -1, "00000100111").SetName("PAL3_CoAttackTargetNative_51"); + yield return new TestCaseData("PAL3", 3, 1, "bossFirst", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_52"); + yield return new TestCaseData("PAL3", 3, 1, "bossDead", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_53"); + yield return new TestCaseData("PAL3", 3, 1, "highestTie", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_54"); + yield return new TestCaseData("PAL3", 3, 5, "base", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_55"); + yield return new TestCaseData("PAL3", 3, 5, "mixedDeadFledInvalid", true, -1, "00000100111").SetName("PAL3_CoAttackTargetNative_56"); + yield return new TestCaseData("PAL3", 3, 5, "bossFirst", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_57"); + yield return new TestCaseData("PAL3", 3, 5, "bossDead", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_58"); + yield return new TestCaseData("PAL3", 3, 5, "highestTie", true, -1, "00000111111").SetName("PAL3_CoAttackTargetNative_59"); + yield return new TestCaseData("PAL3A", 0, -1, "base", false, -1, "00000010100").SetName("PAL3A_CoAttackTargetNative_0"); + yield return new TestCaseData("PAL3A", 0, -1, "mixedDeadFledInvalid", false, -1, "00000010100").SetName("PAL3A_CoAttackTargetNative_1"); + yield return new TestCaseData("PAL3A", 0, -1, "bossFirst", false, -1, "00000010100").SetName("PAL3A_CoAttackTargetNative_2"); + yield return new TestCaseData("PAL3A", 0, -1, "bossDead", false, -1, "00000010100").SetName("PAL3A_CoAttackTargetNative_3"); + yield return new TestCaseData("PAL3A", 0, -1, "highestTie", false, -1, "00000010100").SetName("PAL3A_CoAttackTargetNative_4"); + yield return new TestCaseData("PAL3A", 0, 1, "base", false, 1, "00000010100").SetName("PAL3A_CoAttackTargetNative_5"); + yield return new TestCaseData("PAL3A", 0, 1, "mixedDeadFledInvalid", false, 1, "00000010100").SetName("PAL3A_CoAttackTargetNative_6"); + yield return new TestCaseData("PAL3A", 0, 1, "bossFirst", false, 1, "00000010100").SetName("PAL3A_CoAttackTargetNative_7"); + yield return new TestCaseData("PAL3A", 0, 1, "bossDead", false, 1, "00000010100").SetName("PAL3A_CoAttackTargetNative_8"); + yield return new TestCaseData("PAL3A", 0, 1, "highestTie", false, 1, "00000010100").SetName("PAL3A_CoAttackTargetNative_9"); + yield return new TestCaseData("PAL3A", 0, 5, "base", false, 5, "00000010100").SetName("PAL3A_CoAttackTargetNative_10"); + yield return new TestCaseData("PAL3A", 0, 5, "mixedDeadFledInvalid", false, 5, "00000010100").SetName("PAL3A_CoAttackTargetNative_11"); + yield return new TestCaseData("PAL3A", 0, 5, "bossFirst", false, 5, "00000010100").SetName("PAL3A_CoAttackTargetNative_12"); + yield return new TestCaseData("PAL3A", 0, 5, "bossDead", false, 5, "00000010100").SetName("PAL3A_CoAttackTargetNative_13"); + yield return new TestCaseData("PAL3A", 0, 5, "highestTie", false, 5, "00000010100").SetName("PAL3A_CoAttackTargetNative_14"); + yield return new TestCaseData("PAL3A", 1, -1, "base", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_15"); + yield return new TestCaseData("PAL3A", 1, -1, "mixedDeadFledInvalid", true, -1, "11001000000").SetName("PAL3A_CoAttackTargetNative_16"); + yield return new TestCaseData("PAL3A", 1, -1, "bossFirst", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_17"); + yield return new TestCaseData("PAL3A", 1, -1, "bossDead", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_18"); + yield return new TestCaseData("PAL3A", 1, -1, "highestTie", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_19"); + yield return new TestCaseData("PAL3A", 1, 1, "base", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_20"); + yield return new TestCaseData("PAL3A", 1, 1, "mixedDeadFledInvalid", true, -1, "11001000000").SetName("PAL3A_CoAttackTargetNative_21"); + yield return new TestCaseData("PAL3A", 1, 1, "bossFirst", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_22"); + yield return new TestCaseData("PAL3A", 1, 1, "bossDead", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_23"); + yield return new TestCaseData("PAL3A", 1, 1, "highestTie", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_24"); + yield return new TestCaseData("PAL3A", 1, 5, "base", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_25"); + yield return new TestCaseData("PAL3A", 1, 5, "mixedDeadFledInvalid", true, -1, "11001000000").SetName("PAL3A_CoAttackTargetNative_26"); + yield return new TestCaseData("PAL3A", 1, 5, "bossFirst", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_27"); + yield return new TestCaseData("PAL3A", 1, 5, "bossDead", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_28"); + yield return new TestCaseData("PAL3A", 1, 5, "highestTie", true, -1, "11111000000").SetName("PAL3A_CoAttackTargetNative_29"); + yield return new TestCaseData("PAL3A", 2, -1, "base", false, 6, "00000010100").SetName("PAL3A_CoAttackTargetNative_30"); + yield return new TestCaseData("PAL3A", 2, -1, "mixedDeadFledInvalid", false, 6, "00000010100").SetName("PAL3A_CoAttackTargetNative_31"); + yield return new TestCaseData("PAL3A", 2, -1, "bossFirst", false, 6, "00000010100").SetName("PAL3A_CoAttackTargetNative_32"); + yield return new TestCaseData("PAL3A", 2, -1, "bossDead", false, 6, "00000010100").SetName("PAL3A_CoAttackTargetNative_33"); + yield return new TestCaseData("PAL3A", 2, -1, "highestTie", false, 6, "00000010100").SetName("PAL3A_CoAttackTargetNative_34"); + yield return new TestCaseData("PAL3A", 2, 1, "base", false, 10, "00000010100").SetName("PAL3A_CoAttackTargetNative_35"); + yield return new TestCaseData("PAL3A", 2, 1, "mixedDeadFledInvalid", false, 10, "00000010100").SetName("PAL3A_CoAttackTargetNative_36"); + yield return new TestCaseData("PAL3A", 2, 1, "bossFirst", false, 6, "00000010100").SetName("PAL3A_CoAttackTargetNative_37"); + yield return new TestCaseData("PAL3A", 2, 1, "bossDead", false, 8, "00000010100").SetName("PAL3A_CoAttackTargetNative_38"); + yield return new TestCaseData("PAL3A", 2, 1, "highestTie", false, 6, "00000010100").SetName("PAL3A_CoAttackTargetNative_39"); + yield return new TestCaseData("PAL3A", 2, 5, "base", false, 5, "00000010100").SetName("PAL3A_CoAttackTargetNative_40"); + yield return new TestCaseData("PAL3A", 2, 5, "mixedDeadFledInvalid", false, 5, "00000010100").SetName("PAL3A_CoAttackTargetNative_41"); + yield return new TestCaseData("PAL3A", 2, 5, "bossFirst", false, 5, "00000010100").SetName("PAL3A_CoAttackTargetNative_42"); + yield return new TestCaseData("PAL3A", 2, 5, "bossDead", false, 5, "00000010100").SetName("PAL3A_CoAttackTargetNative_43"); + yield return new TestCaseData("PAL3A", 2, 5, "highestTie", false, 5, "00000010100").SetName("PAL3A_CoAttackTargetNative_44"); + yield return new TestCaseData("PAL3A", 3, -1, "base", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_45"); + yield return new TestCaseData("PAL3A", 3, -1, "mixedDeadFledInvalid", true, -1, "00000100111").SetName("PAL3A_CoAttackTargetNative_46"); + yield return new TestCaseData("PAL3A", 3, -1, "bossFirst", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_47"); + yield return new TestCaseData("PAL3A", 3, -1, "bossDead", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_48"); + yield return new TestCaseData("PAL3A", 3, -1, "highestTie", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_49"); + yield return new TestCaseData("PAL3A", 3, 1, "base", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_50"); + yield return new TestCaseData("PAL3A", 3, 1, "mixedDeadFledInvalid", true, -1, "00000100111").SetName("PAL3A_CoAttackTargetNative_51"); + yield return new TestCaseData("PAL3A", 3, 1, "bossFirst", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_52"); + yield return new TestCaseData("PAL3A", 3, 1, "bossDead", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_53"); + yield return new TestCaseData("PAL3A", 3, 1, "highestTie", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_54"); + yield return new TestCaseData("PAL3A", 3, 5, "base", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_55"); + yield return new TestCaseData("PAL3A", 3, 5, "mixedDeadFledInvalid", true, -1, "00000100111").SetName("PAL3A_CoAttackTargetNative_56"); + yield return new TestCaseData("PAL3A", 3, 5, "bossFirst", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_57"); + yield return new TestCaseData("PAL3A", 3, 5, "bossDead", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_58"); + yield return new TestCaseData("PAL3A", 3, 5, "highestTie", true, -1, "00000111111").SetName("PAL3A_CoAttackTargetNative_59"); + yield return new TestCaseData("PAL3", 0, -1, "emptyMask", false, -1, "00000000000").SetName("PAL3_CoAttackTargetEdge_0"); + yield return new TestCaseData("PAL3", 1, 1, "allInvalid", true, -1, "00000000000").SetName("PAL3_CoAttackTargetEdge_1"); + yield return new TestCaseData("PAL3", 2, -1, "emptyMask", false, -1, "00000000000").SetName("PAL3_CoAttackTargetEdge_2"); + yield return new TestCaseData("PAL3", 2, 1, "noLivingEnemies", false, 0, "00000010100").SetName("PAL3_CoAttackTargetEdge_3"); + yield return new TestCaseData("PAL3", 2, 1, "nonpositiveHp", false, 0, "00000010100").SetName("PAL3_CoAttackTargetEdge_4"); + yield return new TestCaseData("PAL3", 3, 1, "allInvalid", true, -1, "00000000000").SetName("PAL3_CoAttackTargetEdge_5"); + yield return new TestCaseData("PAL3A", 0, -1, "emptyMask", false, -1, "00000000000").SetName("PAL3A_CoAttackTargetEdge_0"); + yield return new TestCaseData("PAL3A", 1, 1, "allInvalid", true, -1, "00000000000").SetName("PAL3A_CoAttackTargetEdge_1"); + yield return new TestCaseData("PAL3A", 2, -1, "emptyMask", false, -1, "00000000000").SetName("PAL3A_CoAttackTargetEdge_2"); + yield return new TestCaseData("PAL3A", 2, 1, "noLivingEnemies", false, 0, "00000010100").SetName("PAL3A_CoAttackTargetEdge_3"); + yield return new TestCaseData("PAL3A", 2, 1, "nonpositiveHp", false, 0, "00000010100").SetName("PAL3A_CoAttackTargetEdge_4"); + yield return new TestCaseData("PAL3A", 3, 1, "allInvalid", true, -1, "00000000000").SetName("PAL3A_CoAttackTargetEdge_5"); + } + + [TestCaseSource(nameof(NativeCases))] + public void MatchesOriginalTargetExpansion(string variant, int rawRange, int originalTarget, + string scenario, bool expectedMulti, int expectedTarget, string expectedMask) + { + var actors = Enumerable.Range(0, 11).Select(index => + new BattleCoAttackTargetActorSnapshot(true, true, false, false, 100 + index)).ToArray(); + if (scenario == "mixedDeadFledInvalid") + { + foreach (int index in new[] { 1, 5 }) + actors[index] = new BattleCoAttackTargetActorSnapshot(true, false, false, false, 0); + foreach (int index in new[] { 2, 6 }) + actors[index] = new BattleCoAttackTargetActorSnapshot(true, true, true, false, 100 + index); + foreach (int index in new[] { 3, 7 }) + actors[index] = new BattleCoAttackTargetActorSnapshot(false, true, false, false, 100 + index); + } + if (scenario is "bossFirst" or "bossDead") + { + actors[6] = new BattleCoAttackTargetActorSnapshot(true, scenario != "bossDead", false, true, 106); + actors[8] = new BattleCoAttackTargetActorSnapshot(true, true, false, true, 108); + } + if (scenario == "highestTie") + { + actors[6] = new BattleCoAttackTargetActorSnapshot(true, true, false, false, 300); + actors[8] = new BattleCoAttackTargetActorSnapshot(true, true, false, false, 300); + } + if (scenario == "noLivingEnemies") + { + for (int index = 5; index < 11; index++) + actors[index] = new BattleCoAttackTargetActorSnapshot(true, false, false, false, 100 + index); + } + if (scenario == "nonpositiveHp") + { + for (int index = 5; index < 11; index++) + actors[index] = new BattleCoAttackTargetActorSnapshot(true, true, false, false, 0); + } + if (scenario == "allInvalid") + { + for (int index = 0; index < 11; index++) + actors[index] = new BattleCoAttackTargetActorSnapshot(false, true, false, false, 100 + index); + } + var previousMask = new bool[11]; + if (scenario != "emptyMask") + previousMask[6] = previousMask[8] = true; + var input = new BattleCoAttackTargetInput(originalTarget, previousMask, rawRange, actors); + BattleCoAttackTargetSelection actual = new BattleCoAttackTargets(variant).Resolve(input); + Assert.That(actual.Multi, Is.EqualTo(expectedMulti)); + Assert.That(actual.NativeTargetIndex, Is.EqualTo(expectedTarget)); + Assert.That(new string(actual.TargetMask.Select(selected => selected ? '1' : '0').ToArray()), Is.EqualTo(expectedMask)); + int[] expectedIndices = expectedMulti + ? Enumerable.Range(0, 11).Where(index => expectedMask[index] == '1').ToArray() + : expectedTarget < 0 ? System.Array.Empty() : new[] { expectedTarget }; + Assert.That(actual.TargetIndices, Is.EqualTo(expectedIndices)); + } + + [Test] + public void InputAndResultCaptureCallerCollections() + { + var actors = Enumerable.Range(0, 11).Select(index => + new BattleCoAttackTargetActorSnapshot(true, true, false, false, 100)).ToArray(); + var mask = new bool[11]; + mask[7] = true; + var input = new BattleCoAttackTargetInput(-1, mask, 2, actors); + mask[0] = true; + actors[7] = new BattleCoAttackTargetActorSnapshot(false, false, true, false, 0); + var rules = new BattleCoAttackTargets("PAL3A"); + BattleCoAttackTargetSelection actual = rules.Resolve(input); + Assert.That(actual.NativeTargetIndex, Is.EqualTo(7)); + Assert.That(actual.TargetMask[0], Is.False); + Assert.That(input.Actors[7].Valid, Is.True); + Assert.That(actual.TargetIndices, Is.EqualTo(new[] { 7 })); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleCoAttackTargetTests.cs.meta b/Assets/Tests/Battle/Editor/BattleCoAttackTargetTests.cs.meta new file mode 100644 index 00000000..c3adc3a2 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleCoAttackTargetTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7f526fbc2b4e4b4bb342a6aeb7aa96ea diff --git a/Assets/Tests/Battle/Editor/BattleCorpseTests.cs b/Assets/Tests/Battle/Editor/BattleCorpseTests.cs new file mode 100644 index 00000000..379be447 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleCorpseTests.cs @@ -0,0 +1,144 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleCorpseTests + { + private sealed class Fixture : IBattleCatalog, IBattleAbilityTimings, IBattleRules + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => Attack(actor, actor); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + actor.InstanceId == "S" ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => 0; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => new(-1000, false, false); + } + + private static BattleSession Session(string variant, bool magic = true, bool item = false, int requiredSkill = 207, + BattleSlot sourceSlot = BattleSlot.Water, bool deadCenter = false) + { + BattleParticipant Participant(string id, BattleSide side, BattleSlot slot, int hp) => new() + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? id == "S" ? 101 : variant == "PAL3" ? 102 : 104 : 701, + Side = side, + Slot = slot, + Attributes = new[] { 100, 100, 100, 1000, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { hp, 100, 100 } + }; + var source = Participant("S", BattleSide.Ally, sourceSlot, 100); + source.Skills.Add(new BattleSkill { Id = 207, Mastered = true, Level = 4 }); + var scenario = new BattleScenario + { + Variant = variant, + Scene = "corpse-fixture", + DataFingerprint = "corpse-fixture", + Seed = 123, + Participants = new List { source, Participant("T", BattleSide.Enemy, BattleSlot.Water, 1) } + }; + if (deadCenter) + scenario.Participants.Add(Participant("C", BattleSide.Ally, BattleSlot.Center, 0)); + if (item) + scenario.Items.Add(new BattleItem { Id = 207, Count = 1 }); + var ability = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 207, + Name = "corpse-trigger fixture", + IsMagic = magic && !item, + IsItem = item, + ItemType = 2, + SuccessRate = 100, + SkillTypeId = magic ? 1 : 0, + Range = BattleTargetRange.OpponentSingle, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -1000) }, + Costs = item ? Array.Empty() : new[] { new BattleCost(2, BattleValueMode.Absolute, 10) } + }); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, + item ? Array.Empty() : new[] { ability }, item ? new[] { ability } : Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Enemy ? -1 : actor.InstanceId == "S" ? 0 : 1, + CorpseItem = actor.InstanceId == "T" ? 9001 : 0, + CorpseSkill = requiredSkill, + CorpsePercent = 100, + LootItem = actor.InstanceId == "T" ? 9001 : 0, + LootCount = 2 + }))); + var fixture = new Fixture(); + var session = new BattleSession(new BattleSetup(scenario), fixture, fixture, definitions); + session.SetAutomatic(BattleSide.Enemy, false); + var command = new BattleCommand("S", item ? BattleAction.Item : BattleAction.Skill, "T", 207); + Assert.That(session.Submit(command), Is.True, session.CanSubmit(command)); + for (int tick = 0; tick < 2000 && session.Status == BattleSessionStatus.Running; tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed), session.Result?.Reason); + return session; + } + + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + public void KillingMagicOrTechniqueRecordsTheCorpseBeforeCostAndCombinesItWithOrdinaryLoot(string variant, bool magic) + { + BattleSession session = Session(variant, magic); + BattleEvent corpse = session.Events.Single(entry => entry.Kind == BattleEventKind.CorpseObtained); + BattleEvent hit = session.Events.Last(entry => entry.Kind == BattleEventKind.Hit && entry.Target == "T"); + var random = new BattleRandom(unchecked((int)hit.RandomState), variant); + Assert.That(random.Probability(100), Is.True); + Assert.That(corpse.RandomState, Is.EqualTo(random.State)); + Assert.That(session.Events.First(entry => entry.Kind == BattleEventKind.ResourceChanged && entry.Resource == 2).RandomState, + Is.EqualTo(corpse.RandomState)); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "T").CorpseItem, Is.EqualTo(9001)); + Assert.That(session.Result.Loot.Single().Count, Is.EqualTo(3)); + Assert.That(session.Result.Items.Single(row => row.Id == 9001).Count, Is.EqualTo(3)); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void EveryValidAllyAtCenterBlocksTheCorpseIncludingADeadAlly(string variant, bool deadCenter) + { + BattleSession session = Session(variant, sourceSlot: deadCenter ? BattleSlot.Water : BattleSlot.Center, deadCenter: deadCenter); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.CorpseObtained), Is.False); + Assert.That(session.Result.Loot.Single().Count, Is.EqualTo(2)); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void WrongSkillAndLethalItemsCannotProduceTheCorpse(string variant, bool item) + { + BattleSession session = Session(variant, item: item, requiredSkill: item ? 207 : 208); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.CorpseObtained), Is.False); + Assert.That(session.Result.Loot.Single().Count, Is.EqualTo(2)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleCorpseTests.cs.meta b/Assets/Tests/Battle/Editor/BattleCorpseTests.cs.meta new file mode 100644 index 00000000..0432bb83 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleCorpseTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ecc73a46973b4086b95edb8b39b1e4bd diff --git a/Assets/Tests/Battle/Editor/BattleEffectAudioSessionTests.cs b/Assets/Tests/Battle/Editor/BattleEffectAudioSessionTests.cs new file mode 100644 index 00000000..88d4c07d --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleEffectAudioSessionTests.cs @@ -0,0 +1,286 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleEffectAudioSessionTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string source, BattleAbilityDefinition ability) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "A" ? 0 : 5; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class Rules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => BattleSession.FullGauge; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => new(-1, false, false); + } + + private sealed class Audio : IBattleEffectDirector, IBattleAudio + { + public readonly List Sounds = new(); + + public long Start(BattleEffectRequest request) => throw new InvalidOperationException("The fixture has no native effect groups."); + + public bool IsRunning(long handle) => false; + + public void Stop(long handle) + { + } + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void PlaySound(string sound) => Sounds.Add(sound); + } + + private static BattleParticipant Participant(string id, BattleSide side) => new() + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = BattleSlot.Water, + Attributes = new[] { 500, 100, 200, 10, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 200, 50, 50 } + }; + + private static BattleSession Create(string variant, Audio audio, BattleAbilityData item, + BattleState[] initial = null, BattleState[] permanent = null, bool deadRecipient = false, bool stealableItem = false, int stealableMoney = 0) + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "audio", Seed = 10 }; + scenario.Participants.Add(Participant("A", BattleSide.Ally)); + scenario.Participants.Add(Participant("E", BattleSide.Enemy)); + if (deadRecipient) + { + BattleParticipant dead = Participant("B", BattleSide.Ally); + dead.Slot = BattleSlot.Fire; + dead.Vitals[0] = 0; + scenario.Participants.Add(dead); + } + if (item.IsItem) + scenario.Items.Add(new BattleItem { Id = item.Id, Count = 10 }); + else + scenario.Participants[0].Skills.Add(new BattleSkill { Id = item.Id, Level = 4, Mastered = true }); + var definition = new BattleAbilityDefinition(item); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, + item.IsItem ? Array.Empty() : new[] { definition }, item.IsItem ? new[] { definition } : Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Enemy ? -1 : actor.InstanceId == "A" ? 0 : 1, + InitialStates = actor.InstanceId == "A" ? initial ?? Array.Empty() : Array.Empty(), + PermanentStates = actor.InstanceId == "A" ? permanent ?? Array.Empty() : Array.Empty(), + StealableMoney = actor.InstanceId == "E" ? stealableMoney : 0, + StealableItemId = actor.InstanceId == "E" && stealableItem ? 6202 : 0, + StealableItemCount = actor.InstanceId == "E" && stealableItem ? 4 : 0 + }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new Rules(), definitions, effects: audio); + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(audio?.Sounds ?? new List(), Is.Empty, "Authored and equipped initial states must not replay application sounds."); + return session; + } + + private static BattleAbilityData Item(params BattleStatusEffect[] states) => new() + { + Id = 6201, + IsItem = true, + ItemType = 1, + Range = BattleTargetRange.OwnSingle, + States = states + }; + + private static void Use(BattleSession session, string target = "A", bool steal = false) + { + Assert.That(session.Submit(new BattleCommand("A", steal ? BattleAction.Skill : BattleAction.Item, target, steal ? 4101 : 6201)), Is.True); + for (int index = 0; index < 5; index++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + } + + private static IEnumerable StateCues() + { + // Frozen native SetSpecState sound-port traces for all audible additions. + string[] added = { "wd005", "wd005", "wd005", "wd005", "wd005", "wd021", "wd022", "wd021", "wd022", "wd021", "wd022", "wd021", "wd022", "wd007", "wd008", "wd009", "wd010", "wd012", "wd011", "wd016", "wd013", "wd014", "wd015" }; + foreach (string variant in new[] { "PAL3", "PAL3A" }) + for (int state = 0; state < added.Length; state++) + yield return new TestCaseData(variant, (BattleState)state, added[state]); + } + + [TestCaseSource(nameof(StateCues))] + public void ApplyingAnItemStateEmitsTheNativeCueThroughTheSession(string variant, BattleState state, string expected) + { + var audio = new Audio(); + BattleSession session = Create(variant, audio, Item(new BattleStatusEffect(state, false))); + Use(session); + Assert.That(audio.Sounds, Is.EqualTo(new[] { expected })); + } + + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + public void CuringPoisonSoundsForEachRequestedRemovalEvenIfTheStateWasAbsent(string variant, bool present) + { + var audio = new Audio(); + var item = Item(Enumerable.Range(0, 5).Select(state => new BattleStatusEffect((BattleState)state, true)).ToArray()); + BattleSession session = Create(variant, audio, item, present ? new[] { BattleState.PoisonWater } : null); + Use(session); + Assert.That(audio.Sounds, Is.EqualTo(Enumerable.Repeat("wd006", 5))); + } + + private static IEnumerable GoodRemovals() + { + foreach (string variant in new[] { "PAL3", "PAL3A" }) + foreach (BattleState state in new[] { BattleState.Reflection, BattleState.Evade, BattleState.Barrier, BattleState.Invisible }) + foreach (bool present in new[] { false, true }) + yield return new TestCaseData(variant, state, present); + } + + [TestCaseSource(nameof(GoodRemovals))] + public void RemovingAProtectiveStatePlaysItsNativeCueEvenWhenAbsent(string variant, BattleState state, bool present) + { + var audio = new Audio(); + BattleSession session = Create(variant, audio, Item(new BattleStatusEffect(state, true)), present ? new[] { state } : null); + Use(session); + Assert.That(audio.Sounds, Is.EqualTo(new[] { "wd020" })); + } + + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + public void AilmentCuresAreGroupedAtTheAbilityBoundary(string variant, bool all) + { + var states = new[] { BattleState.Paralysis, BattleState.Seal, BattleState.Forbidden, BattleState.Sleep, BattleState.Madness, BattleState.Chaos }; + var item = Item(states.Take(all ? 6 : 5).Select(state => new BattleStatusEffect(state, true)).ToArray()); + var audio = new Audio(); + BattleSession session = Create(variant, audio, item); + Use(session); + Assert.That(audio.Sounds, Is.EqualTo(all ? new[] { "wd019" } : new[] { "wd017", "wd017", "wd017", "wd018", "wd018" })); + } + + [TestCase("PAL3", BattleState.AttackIncrease, "wd021")] + [TestCase("PAL3A", BattleState.AttackIncrease, "wd021")] + [TestCase("PAL3", BattleState.PoisonWater, null)] + [TestCase("PAL3A", BattleState.PoisonWater, null)] + public void BuffRefreshSoundsButDuplicatePoisonIsRejectedSilently(string variant, BattleState state, string expected) + { + var audio = new Audio(); + BattleSession session = Create(variant, audio, Item(new BattleStatusEffect(state, false)), new[] { state }); + Use(session); + Assert.That(audio.Sounds, Is.EqualTo(expected == null ? Array.Empty() : new[] { expected })); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void InvisibleRecipientsBlockStateSoundsAlongWithTheirChanges(string variant) + { + var audio = new Audio(); + BattleSession session = Create(variant, audio, Item(new BattleStatusEffect(BattleState.AttackIncrease, false)), new[] { BattleState.Invisible }); + Use(session); + Assert.That(audio.Sounds, Is.Empty); + } + + [TestCase("PAL3", 20, 0, 0, "wd001")] + [TestCase("PAL3A", 20, 0, 0, "wd001")] + [TestCase("PAL3", 0, 0, 20, "wd002")] + [TestCase("PAL3A", 0, 0, 20, "wd002")] + [TestCase("PAL3", 20, 0, 20, "wd003")] + [TestCase("PAL3A", 20, 0, 20, "wd003")] + [TestCase("PAL3", 0, 20, 0, null)] + [TestCase("PAL3A", 0, 20, 0, null)] + [TestCase("PAL3", -20, 0, -20, null)] + [TestCase("PAL3A", -20, 0, -20, null)] + public void RecoveryUsesOneCombinedCueAndDoesNotSoundForQiOrDamage(string variant, int hp, int sp, int mp, string expected) + { + var audio = new Audio(); + var item = Item(); + item.Attributes = new[] { hp, sp, mp }.Select((value, resource) => new BattleAttributeEffect(resource, BattleValueMode.Absolute, value)).ToArray(); + BattleSession audible = Create(variant, audio, item); + BattleSession silent = Create(variant, null, item); + Use(audible); + Use(silent); + Assert.That(audio.Sounds, Is.EqualTo(expected == null ? Array.Empty() : new[] { expected })); + Assert.That(audible.Actors.Select(actor => (actor.Hp, actor.Sp, actor.Mp)), Is.EqualTo(silent.Actors.Select(actor => (actor.Hp, actor.Sp, actor.Mp)))); + Assert.That(audible.Events.Select(entry => (entry.Kind, entry.RandomState)), Is.EqualTo(silent.Events.Select(entry => (entry.Kind, entry.RandomState)))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ResurrectionSoundsBeforeItsHpRecovery(string variant) + { + var audio = new Audio(); + var item = Item(new BattleStatusEffect(BattleState.Death, true)); + item.Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, 20) }; + BattleSession session = Create(variant, audio, item, deadRecipient: true); + Use(session, "B"); + Assert.That(audio.Sounds, Is.EqualTo(new[] { "wd004", "wd001" })); + Assert.That(session.Actors.Single(actor => actor.Id == "B").Hp, Is.EqualTo(20)); + } + + [TestCase("PAL3", true, 0)] + [TestCase("PAL3A", true, 0)] + [TestCase("PAL3", false, 10)] + [TestCase("PAL3A", false, 10)] + [TestCase("PAL3", false, 0)] + [TestCase("PAL3A", false, 0)] + public void SuccessfulItemTheftSoundsButMoneyOnlyAndEmptyPoolsDoNot(string variant, bool item, int money) + { + var audio = new Audio(); + var steal = new BattleAbilityData { Id = 4101, SkillTypeId = 0, Handler = BattleSpecialHandler.Steal, Range = BattleTargetRange.OpponentSingle }; + BattleSession session = Create(variant, audio, steal, stealableItem: item, stealableMoney: money); + Use(session, "E", true); + Assert.That(audio.Sounds, Is.EqualTo(item ? new[] { "wa006" } : Array.Empty())); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.ItemChanged), Is.EqualTo(item)); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void VictoryCleanupPlaysTheNativeRemovalCueForLivingAndDeadAllies(string variant, bool invisible) + { + var audio = new Audio(); + var item = Item(); + item.Range = BattleTargetRange.OpponentSingle; + item.Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -10000) }; + BattleSession session = Create(variant, audio, item, invisible ? new[] { BattleState.Invisible } : null, deadRecipient: true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "E", 6201)), Is.True); + for (int index = 0; index < 1000 && session.Status == BattleSessionStatus.Running; index++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed), session.Result?.Reason); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + Assert.That(audio.Sounds.Count(sound => sound == "wd020"), Is.EqualTo(2), + "Native EndAll removes Invisible for every valid ally, even if absent or dead."); + Assert.That(audio.Sounds, Does.Not.Contain("wd017").And.Not.Contain("wd018"), + "Direct cleanup is not an ability's grouped ailment cure."); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "B").Hp, Is.EqualTo(1), + "Sound output must preserve the existing settlement resource writes."); + } + + } +} diff --git a/Assets/Tests/Battle/Editor/BattleEffectAudioSessionTests.cs.meta b/Assets/Tests/Battle/Editor/BattleEffectAudioSessionTests.cs.meta new file mode 100644 index 00000000..b552c255 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleEffectAudioSessionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0ce48755108f48368271886efc2532ca diff --git a/Assets/Tests/Battle/Editor/BattleElementWheelTests.cs b/Assets/Tests/Battle/Editor/BattleElementWheelTests.cs new file mode 100644 index 00000000..a59dfccc --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleElementWheelTests.cs @@ -0,0 +1,303 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Battle; + using NUnit.Framework; + + public sealed class BattleElementWheelTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattleAbilityEffects, IBattleElementWheelTimings, IBattleAbilityBodyAnimations + { + public AttackTiming Attack(string actor, string target) => new(0, 3, new[] { 1 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 3, new[] { 1 }); + + public AttackTiming ElementWheel(string actor, BattleAbilityDefinition ability) => new(0, 3, new[] { 1 }); + + public BattleAbilityStageProfile ElementWheelStage(string actor, BattleAbilityDefinition ability) => new(BattleAbilityStageKind.ElementWheel, + new BattleAbilityEffectBinding(-1, 0), new BattleAbilityEffectBinding(-1, 0), .02f, BattleAbilityWorkBoundary.WorkTime, 0, false); + + public BattleAbilityStageProfile AbilityStage(string actor, BattleAbilityDefinition ability) => new(BattleAbilityStageKind.Magic, + new BattleAbilityEffectBinding(-1, 0), new BattleAbilityEffectBinding(-1, 0), .02f, BattleAbilityWorkBoundary.WorkTime, 0, false); + + public BattlePhysicalAnimation ElementWheelBody(string actor, BattleAbilityDefinition ability) => null; + + public BattlePhysicalAnimation AbilityBody(string actor, BattleAbilityDefinition ability) => null; + + public int? AbilityNativeAction(string actor, BattleAbilityDefinition ability) => null; + + public BattlePhysicalAnimation AbilityMovementBody(string actor, BattleAbilityDefinition ability, BattleMovementKind kind, bool returning) => null; + + public IReadOnlyList AbilityMovement(BattleActorSnapshot source, BattleActorSnapshot target, + BattleAbilityDefinition ability, BattleDefinitions definitions, bool returning) => Array.Empty(); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 1; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "N" ? 0 : 1; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class Rules : IBattleRules + { + private readonly bool _refillController; + + public Rules(bool refillController = false) => _refillController = refillController; + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + actor.Side == BattleSide.Ally ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => _refillController && actor.InstanceId == "N" ? BattleSession.FullGauge : 0; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => new(-1, false, false); + } + + private static BattleParticipant Participant(string id, int actorId, BattleSide side, BattleSlot slot) => new() + { + InstanceId = id, + ActorId = actorId, + Side = side, + Slot = slot, + Attributes = new[] { 500, 100, 100, 10, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 100, 0 } + }; + + private static (BattleSession Session, BattleSetup Setup, BattleDefinitions Definitions) Fixture(int charge = 9, string variant = "PAL3A", + BattleState? state = null, bool learned = false, bool refillController = false) + { + var scenario = new BattleScenario { Variant = variant, Scene = "wheel-fixture", DataFingerprint = "wheel", Seed = 12345 }; + scenario.Pal3A.SpiritWheel.Charges = Enumerable.Repeat(charge, 5).ToArray(); + BattleParticipant nangong = Participant("N", 101, BattleSide.Ally, BattleSlot.Water); + if (state.HasValue) + nangong.Statuses.Add(new BattleStatus { Id = (int)state.Value, Rounds = 20 }); + if (learned) + for (int id = 264; id <= 268; id++) + nangong.Skills.Add(new BattleSkill { Id = id, Level = 1, Uses = 12, Mastered = true }); + scenario.Participants.Add(nangong); + scenario.Participants.Add(Participant("W", 102, BattleSide.Ally, BattleSlot.Fire)); + scenario.Participants.Add(Participant("E", 7311, BattleSide.Enemy, BattleSlot.Water)); + var definitions = new BattleDefinitions(variant, "wheel", Enumerable.Range(264, 5).Select(id => + new BattleAbilityDefinition(new BattleAbilityData + { + Id = id, + IsMagic = true, + SkillTypeId = 0, + Range = BattleTargetRange.None, + ElementMask = 1 << (id == 266 ? 3 : id == 267 ? 2 : id - 264), + Costs = new[] { new BattleCost(2, BattleValueMode.Absolute, 5) } + })), Array.Empty(), scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId == "N" ? 0 : actor.InstanceId == "W" ? 1 : -1 + }))); + var setup = new BattleSetup(scenario); + var session = new BattleSession(setup, new Catalog(), new Rules(refillController), definitions); + session.SetAutomatic(BattleSide.Ally, false); + session.SetAutomatic(BattleSide.Enemy, false); + return (session, setup, definitions); + } + + private static uint RandomState(BattleSession session) => ((BattleRandom)typeof(BattleSession) + .GetField("_random", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session)).State; + + private static void Resolve(BattleSession session) + { + for (int tick = 0; tick < 20 && session.Actors.Single(actor => actor.Id == "N").ActionId != 0; tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + Assert.That(session.Actors.Single(actor => actor.Id == "N").ActionId, Is.Zero, "The wheel has no name/lineup wait."); + } + + [TestCase(264, 0, 1)] + [TestCase(265, 1, 2)] + [TestCase(266, 3, 4)] + [TestCase(267, 2, 3)] + [TestCase(268, 4, 5)] + public void ManualWheelUsesItsDedicatedNoTargetStageAndClearsOnlyItsCoreElement(int id, int coreElement, int field) + { + BattleSession session = Fixture(state: BattleState.Seal).Session; + Assert.That(session.CanSubmitElementWheel("N", id), Is.Null); + Assert.That(session.GetTargetCandidates(new BattleCommand("N", BattleAction.Skill, null, id)), Is.Empty); + int count = session.Inputs.Count; + uint random = RandomState(session); + Assert.That(session.SubmitElementWheel("N", id), Is.True); + BattleInput input = session.Inputs.Last(); + Assert.That((input.Kind, input.Actor, input.Target, input.Action, input.AbilityId, input.FromTestAi), + Is.EqualTo((BattleInputKind.ElementWheel, "N", (string)null, BattleAction.Skill, id, false))); + Assert.That(session.Inputs.Count, Is.EqualTo(count + 1)); + Assert.That(session.Actors.Single(actor => actor.Id == "N").CastGauge, Is.Zero); + Assert.That(session.Pal3AState.SpiritWheel.Charges[coreElement], Is.EqualTo(9), "Cost occurs at work, not submission."); + Resolve(session); + int[] expected = Enumerable.Repeat(9, 5).ToArray(); + expected[coreElement] = 0; + Assert.That(session.Pal3AState.SpiritWheel.Charges, Is.EqualTo(expected)); + Assert.That((session.FiveSpiritElement, session.FiveSpiritForce), Is.EqualTo((field, 1))); + Assert.That(session.Actors.Single(actor => actor.Id == "N").Mp, Is.Zero); + Assert.That(session.Actors.Single(actor => actor.Id == "N").Skills, Is.Empty); + Assert.That(session.Events.Count(entry => entry.Detail.Contains("consumed", StringComparison.Ordinal)), Is.EqualTo(1)); + Assert.That(session.Events.Any(entry => entry.Detail.StartsWith("skill cost", StringComparison.Ordinal)), Is.False); + Assert.That(RandomState(session), Is.EqualTo(random)); + } + + [TestCase(0)] + [TestCase(2)] + [TestCase(3)] + [TestCase(5)] + [TestCase(6)] + [TestCase(8)] + public void IncompleteElementCannotSubmitAndQueriesNeverChangeTheSession(int charge) + { + BattleSession session = Fixture(charge).Session; + uint random = RandomState(session); + int count = session.Inputs.Count; + for (int query = 0; query < 10; query++) + for (int id = 264; id <= 268; id++) + Assert.That(session.CanSubmitElementWheel("N", id), Is.Not.Null); + Assert.That(session.SubmitElementWheel("N", 264), Is.False); + Assert.That(session.Pal3AState.SpiritWheel.Charges, Is.All.EqualTo(charge)); + Assert.That(RandomState(session), Is.EqualTo(random)); + Assert.That(session.Inputs.Count, Is.EqualTo(count)); + } + + [TestCase("N", 0)] + [TestCase("N", 263)] + [TestCase("N", 269)] + [TestCase("W", 264)] + [TestCase("E", 264)] + [TestCase("missing", 264)] + [TestCase(null, 264)] + public void ManualWheelRejectsInvalidSkillAndAnyOtherController(string actor, int id) + { + BattleSession session = Fixture().Session; + int inputs = session.Inputs.Count; + Assert.That(session.CanSubmitElementWheel(actor, id), Is.Not.Null); + Assert.That(session.SubmitElementWheel(actor, id), Is.False); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs)); + } + + [TestCase(BattleState.Paralysis)] + [TestCase(BattleState.Sleep)] + [TestCase(BattleState.Chaos)] + [TestCase(BattleState.Madness)] + public void AbnormalControllersCannotUseTheManualWheel(BattleState state) + { + Assert.That(Fixture(state: state).Session.CanSubmitElementWheel("N", 264), Is.Not.Null); + } + + [Test] + public void CastingFromTheWheelKeepsTheLastOrdinaryCommand() + { + BattleSession session = Fixture(refillController: true).Session; + Assert.That(session.Submit("N", BattleAction.Defend), Is.True); + Assert.That(session.Submit("W", BattleAction.Defend), Is.True); + Resolve(session); + for (int tick = 0; tick < 500 && session.WaitingActor != "N"; tick++) + session.Step(); + Assert.That(session.SubmitElementWheel("N", 264), Is.True); + Resolve(session); + for (int tick = 0; tick < 500 && session.WaitingActor != "N"; tick++) + session.Step(); + + Assert.That(session.RequestAiRepeat("N"), Is.True); + Assert.That(session.Inputs.Last(input => input.Kind == BattleInputKind.Command).Action, Is.EqualTo(BattleAction.Defend)); + } + + [Test] + public void ManualEligibilityDoesNotGrantOrdinarySkillAccessOrFakeProficiency() + { + BattleSession session = Fixture(learned: true).Session; + Assert.That(session.CanSubmitElementWheel("N", 264), Is.Null); + Assert.That(session.CanSubmit(new BattleCommand("N", BattleAction.Skill, null, 264)), Is.Not.Null); + Assert.That(session.Submit(new BattleCommand("N", BattleAction.Skill, null, 264)), Is.False); + Assert.That(session.SubmitElementWheel("N", 264), Is.True); + Resolve(session); + Assert.That(session.Actors.Single(actor => actor.Id == "N").Skills.Select(skill => (skill.Id, skill.Level, skill.Uses)), + Is.EqualTo(Enumerable.Range(264, 5).Select(id => (id, 1, 12)))); + } + + [Test] + public void Pal3AndNonCurrentControllersCannotUseTheWheel() + { + Assert.That(Fixture(variant: "PAL3").Session.CanSubmitElementWheel("N", 264), Is.Not.Null); + BattleSession session = Fixture().Session; + session.SetAiProfile("N", 32); + Assert.That(session.WaitingActor, Is.EqualTo("W")); + Assert.That(session.CanSubmitElementWheel("N", 264), Is.Not.Null); + } + + [Test] + public void EnemyAiFieldMagicRetainsItsMpCostAndCannotConsumeThePlayerWheel() + { + BattleSession session = Fixture().Session; + object enemy = ((IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session))["E"]; + Type actorType = enemy.GetType(); + actorType.GetField("Ready").SetValue(enemy, true); + actorType.GetField("Gauge").SetValue(enemy, BattleSession.FullGauge); + actorType.GetField("Mp").SetValue(enemy, 100); + var command = new BattleCommand("E", BattleAction.Skill, null, 266); + Assert.That((long)typeof(BattleSession).GetMethod("SubmitAiCommand", BindingFlags.Instance | BindingFlags.NonPublic) + .Invoke(session, new object[] { command, true }), Is.GreaterThan(0)); + for (int tick = 0; tick < 300 && session.Actors.Single(actor => actor.Id == "E").ActionId != 0; tick++) + session.Step(); + Assert.That(session.Actors.Single(actor => actor.Id == "E").ActionId, Is.Zero); + Assert.That((session.FiveSpiritElement, session.FiveSpiritForce), Is.EqualTo((4, 2))); + Assert.That(session.Actors.Single(actor => actor.Id == "E").Mp, Is.EqualTo(95)); + Assert.That(session.Pal3AState.SpiritWheel.Charges, Is.All.EqualTo(9)); + Assert.That(session.Inputs.Last().Kind, Is.EqualTo(BattleInputKind.Command)); + Assert.That(session.Inputs.Last().FromTestAi, Is.True); + } + + [Test] + public void EndedAndAlreadySubmittedInputsCannotUseTheWheel() + { + BattleSession session = Fixture().Session; + Assert.That(session.SubmitElementWheel("N", 264), Is.True); + Assert.That(session.SubmitElementWheel("N", 265), Is.False); + session.Abort("test stop"); + Assert.That(session.SubmitElementWheel("N", 265), Is.False); + } + + [Test] + public void WheelUsesNativeChargeGateDuringBeastFormAndRejectsPendingTransition() + { + BattleSession session = Fixture().Session; + object state = ((IDictionary)typeof(BattleSession).GetField("_pal3AForms", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session))["N"]; + state.GetType().GetField("Kind", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).SetValue(state, BattlePal3AFormKind.NangongFireBeast); + Assert.That(session.CanSubmitElementWheel("N", 264), Is.Null, "The released wheel panel does not check the beast-form bit."); + Assert.That(session.CanSubmit(new BattleCommand("N", BattleAction.Skill, null, 264)), Is.Not.Null); + state.GetType().GetField("Pending", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).SetValue(state, true); + Assert.That(session.CanSubmitElementWheel("N", 264), Is.Not.Null); + } + + [Test] + public void DedicatedInputReplaysWithoutTheAiQualificationChannel() + { + var fixture = Fixture(); + BattleSession session = fixture.Session; + for (int id = 264; id <= 268; id++) + Assert.That(session.CanSubmitElementWheel("N", id), Is.Null); + Assert.That(session.SubmitElementWheel("N", 266), Is.True); + Resolve(session); + BattleSession replay = BattleReplay.Play(fixture.Setup, new Catalog(), session.Inputs, session.Tick, new Rules(), fixture.Definitions); + Assert.That(replay.Pal3AState.SpiritWheel.Charges, Is.EqualTo(session.Pal3AState.SpiritWheel.Charges)); + Assert.That((replay.FiveSpiritElement, replay.FiveSpiritForce, RandomState(replay)), + Is.EqualTo((session.FiveSpiritElement, session.FiveSpiritForce, RandomState(session)))); + Assert.That(replay.Events.Select(entry => (entry.Tick, entry.Kind, entry.Source, entry.Target, entry.Detail)), + Is.EqualTo(session.Events.Select(entry => (entry.Tick, entry.Kind, entry.Source, entry.Target, entry.Detail)))); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleElementWheelTests.cs.meta b/Assets/Tests/Battle/Editor/BattleElementWheelTests.cs.meta new file mode 100644 index 00000000..5e5387cf --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleElementWheelTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: df5cddfadc0544fb88216effb3442aec diff --git a/Assets/Tests/Battle/Editor/BattleEncounterRulesTests.cs b/Assets/Tests/Battle/Editor/BattleEncounterRulesTests.cs new file mode 100644 index 00000000..b85574b3 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleEncounterRulesTests.cs @@ -0,0 +1,146 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleEncounterRulesTests + { + [Test] + public void OnlyNativeCenterCountsTheEncounterLimitAndItStopsLaterRoundEffects() + { + int processed = 0; + int boss = 0; + Assert.That(BattleEncounterRules.BeginRound(5, 4, 2, ref processed, ref boss), Is.True); + Assert.That((processed, boss), Is.EqualTo((1, 0))); + processed = 0; + Assert.That(BattleEncounterRules.BeginRound(10, 4, 2, ref processed, ref boss), Is.True); + Assert.That((processed, boss), Is.EqualTo((1, 1))); + Assert.That(BattleEncounterRules.BeginRound(10, 4, 2, ref processed, ref boss), Is.True); + Assert.That((processed, boss), Is.EqualTo((2, 2))); + int other = 0; + Assert.That(BattleEncounterRules.BeginRound(0, 4, 2, ref other, ref boss), Is.False); + Assert.That((other, boss), Is.EqualTo((0, 2))); + Assert.That(BattleEncounterRules.RoundLimitReached(0, -1), Is.False); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void DefeatWinsTheSimultaneousDeathDecisionAndMustFailDoesNotForbidAnOrdinaryWin(string variant) + { + var rules = new BattleEncounterRules(variant); + Assert.That(rules.CheckOutcome(false, false, 0, -1, false, Array.Empty()), Is.EqualTo(BattleEncounterOutcome.Lose)); + Assert.That(rules.CheckOutcome(true, true, 3, 3, true, Array.Empty()), Is.EqualTo(BattleEncounterOutcome.None)); + Assert.That(rules.CheckOutcome(true, false, 3, 3, true, Array.Empty()), Is.EqualTo(BattleEncounterOutcome.Win)); + Assert.That(rules.CheckOutcome(true, true, 3, 3, false, Array.Empty()), Is.EqualTo(BattleEncounterOutcome.Win)); + } + + [TestCase("PAL3", 12, BattleEncounterOutcome.None, BattleEncounterOutcome.None)] + [TestCase("PAL3", 11, BattleEncounterOutcome.Lose, BattleEncounterOutcome.Win)] + [TestCase("PAL3A", 13, BattleEncounterOutcome.None, BattleEncounterOutcome.None)] + [TestCase("PAL3A", 17, BattleEncounterOutcome.None, BattleEncounterOutcome.None)] + [TestCase("PAL3A", 11, BattleEncounterOutcome.None, BattleEncounterOutcome.Win)] + [TestCase("PAL3A", 31, BattleEncounterOutcome.Lose, BattleEncounterOutcome.None)] + public void OutcomeWaitsForTheReleasedVariantsDistinctStageTasks(string variant, int task, BattleEncounterOutcome defeat, BattleEncounterOutcome victory) + { + var rules = new BattleEncounterRules(variant); + Assert.That(rules.CheckOutcome(false, true, 0, -1, false, new[] { task }), Is.EqualTo(defeat)); + Assert.That(rules.CheckOutcome(true, false, 0, -1, false, new[] { task }), Is.EqualTo(victory)); + } + + [Test] + public void PreparedMonsterCapturesItsParticipantBeforeTheLiveSlotChanges() + { + var participant = new BattleParticipant { InstanceId = "slot10", ActorId = 739, Side = BattleSide.Enemy, Slot = BattleSlot.Center }; + participant.Attributes[0] = participant.Vitals[0] = 500; + var definition = new BattleActorDefinition(new BattleActorData { InstanceId = "slot10" }); + var creation = new BattleMonsterCreation(10, participant, definition); + participant.ActorId = 701; + participant.Vitals[0] = 0; + Assert.That(creation.Participant.ActorId, Is.EqualTo(739)); + Assert.That(creation.Participant.Vitals[0], Is.EqualTo(500)); + BattleParticipant exposed = creation.Participant; + exposed.Vitals[0] = 1; + Assert.That(creation.Participant.Vitals[0], Is.EqualTo(500)); + } + + [Test] + public void MustFailRestoresOnlyNativeCenterToItsOwnMaximum() + { + Assert.That(BattleEncounterRules.HpAfterMustFail(true, 10, -100, 1000), Is.EqualTo(1000)); + Assert.That(BattleEncounterRules.HpAfterMustFail(true, 5, -100, 1000), Is.EqualTo(-100)); + Assert.That(BattleEncounterRules.HpAfterMustFail(false, 10, -100, 1000), Is.EqualTo(-100)); + } + + [Test] + public void SwordBossThirdRoundUsesTheActualVariantsStateOrder() + { + Assert.That(new BattleBossRules("PAL3").RoundStates(7372, 3), Is.EqualTo(new[] { BattleState.AttackIncrease })); + Assert.That(new BattleBossRules("PAL3A").RoundStates(7372, 3), Is.EqualTo(new[] + { + BattleState.AttackIncrease, BattleState.SpeedIncrease, BattleState.DefenseIncrease + })); + Assert.That(new BattleBossRules("PAL3A").RoundStates(7372, 4), Is.Empty); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void SwampSplitCanReuseDeadSlotsWhereBloodCloudNeedsAnInvalidSlot(string variant) + { + var rules = new BattleBossRules(variant); + BattleNativeEnemySlot[] slots = Enumerable.Range(0, 6).Select(index => new BattleNativeEnemySlot(true, index != 0)).ToArray(); + var swampRandom = new BattleRandom(1); + var cloudRandom = new BattleRandom(1); + Assert.That(rules.SplitSlot(7378, 3, slots, swampRandom), Is.EqualTo(5)); + Assert.That(rules.SplitSlot(7395, 2, slots, cloudRandom), Is.EqualTo(-1)); + Assert.That(swampRandom.State, Is.EqualTo(2745024u)); + Assert.That(cloudRandom.State, Is.EqualTo(swampRandom.State)); + slots[1] = default; + Assert.That(rules.SplitSlot(7395, 2, slots, new BattleRandom(1)), Is.EqualTo(6)); + var early = new BattleRandom(1); + Assert.That(rules.SplitSlot(7378, 2, slots, early), Is.EqualTo(-1)); + Assert.That(early.State, Is.EqualTo(1u)); + } + + [TestCase("PAL3", 5, 7370, 7, 7369, 1423890337u)] + [TestCase("PAL3A", 7, 7364, 8, 7365, 3357800067u)] + public void SummonUsesTheReleasedVariantsIdsSlotsAndRandomConsumption(string variant, int firstSlot, int firstActor, int secondSlot, int secondActor, uint seedAfter) + { + var random = new BattleRandom(1); + var summons = new BattleBossRules(variant).Summon(10, 1, new BattleNativeEnemySlot[6], random); + Assert.That(summons.Select(request => (request.NativeIndex, request.ActorId)), + Is.EqualTo(new[] { (firstSlot, firstActor), (secondSlot, secondActor) })); + Assert.That(random.State, Is.EqualTo(seedAfter)); + } + + [Test] + public void OriginalSummonRejectsALivingUnescapedFixedSlotBeforeDrawingRandom() + { + var slots = new BattleNativeEnemySlot[6]; + slots[0] = new BattleNativeEnemySlot(false, true); + var random = new BattleRandom(1); + var rules = new BattleBossRules("PAL3"); + Assert.That(rules.Summon(10, 1, slots, random), Is.Empty); + Assert.That(random.State, Is.EqualTo(1u)); + slots[0] = new BattleNativeEnemySlot(false, true, true); + Assert.That(rules.Summon(10, 1, slots, random), Has.Count.EqualTo(2)); + } + + [TestCase("PAL3", 210)] + [TestCase("PAL3A", 308)] + public void FireballSelfDestructionRequiresTheExactActorAndMagic(string variant, int magic) + { + var rules = new BattleBossRules(variant); + Assert.That(rules.SelfDestructsAfterMagic(7312, magic), Is.True); + Assert.That(rules.SelfDestructsAfterMagic(701, magic), Is.False); + Assert.That(rules.SelfDestructsAfterMagic(7312, magic + 1), Is.False); + Assert.That(rules.DeathReplacement(738), Is.EqualTo(variant == "PAL3" ? 739 : 0)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleEncounterRulesTests.cs.meta b/Assets/Tests/Battle/Editor/BattleEncounterRulesTests.cs.meta new file mode 100644 index 00000000..4eed553b --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleEncounterRulesTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 8d49d8c3d4934064b20c7bb254f211cf diff --git a/Assets/Tests/Battle/Editor/BattleEncounterSessionTests.cs b/Assets/Tests/Battle/Editor/BattleEncounterSessionTests.cs new file mode 100644 index 00000000..2016fa62 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleEncounterSessionTests.cs @@ -0,0 +1,368 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleEncounterSessionTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattleMonsterFactory + { + public readonly List<(int NativeIndex, int ActorId, string InstanceId)> Created = new(); + + public AttackTiming Attack(string source, string target) => new(0, 3, new[] { 1 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 3, new[] { 1 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + + public BattleMonsterCreation Prepare(int nativeIndex, int actorId, string instanceId) + { + BattleParticipant participant = Participant(instanceId, BattleSide.Enemy, (BattleSlot)(nativeIndex - 5), actorId); + return new BattleMonsterCreation(nativeIndex, participant, new BattleActorDefinition(new BattleActorData + { + InstanceId = instanceId, + NormalAttackMode = 901, + StealableMoney = actorId, + PermanentStates = new[] { BattleState.PoisonResist } + })); + } + + public Action OnCommit; + + public void Commit(BattleMonsterCreation creation) + { + OnCommit?.Invoke(creation); + Created.Add((creation.NativeIndex, creation.Participant.ActorId, creation.Participant.InstanceId)); + } + } + + private sealed class Rules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => BattleSession.FullGauge; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => new(0, false, false); + } + + private static BattleParticipant Participant(string id, BattleSide side, BattleSlot slot, int actorId) => new() + { + InstanceId = id, + ActorId = actorId, + Side = side, + Slot = slot, + Level = 20, + Attributes = new[] { 500, 100, 100, 20, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 100, 100 } + }; + + private static BattleScenario Scenario(string variant, int enemy = 701) => new() + { + Variant = variant, + Scene = "encounter-fixture", + DataFingerprint = "encounter-fixture", + Participants = new List + { + Participant("A", BattleSide.Ally, BattleSlot.Water, 101), + Participant("E", BattleSide.Enemy, BattleSlot.Center, enemy) + } + }; + + private static BattleSession Session(BattleScenario scenario, Catalog catalog = null, params BattleAbilityDefinition[] skills) + { + var definitions = new BattleDefinitions(scenario.Variant, scenario.DataFingerprint, skills, Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? actor.InstanceId == "A" ? 0 : 1 : -1, + NormalAttackMode = 901 + }))); + var session = new BattleSession(new BattleSetup(scenario), catalog ?? new Catalog(), new Rules(), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + + private static BattleAbilityDefinition Magic(int id, int power, int special = 0) => new(new BattleAbilityData + { + Id = id, + IsMagic = true, + SkillTypeId = 2, + Range = BattleTargetRange.OpponentSingle, + SpecialEffect = special, + Handler = BattleSpecialRules.AbilityHandler("PAL3", id, false, true, special), + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, power) }, + Costs = new[] { new BattleCost(2, BattleValueMode.Absolute, 7) } + }); + + private static void Learn(BattleParticipant actor, int id, int level = 4) => actor.Skills.Add(new BattleSkill { Id = id, Level = level, Mastered = true }); + + private static void Advance(BattleSession session, int count, bool defend = false) + { + for (int index = 0; index < count && session.Status == BattleSessionStatus.Running; index++) + { + if (defend) + while (session.WaitingActor is { } waiting) + Assert.That(session.Submit(waiting, BattleAction.Defend), Is.True); + session.Step(); + } + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + } + + private sealed class ReplacementEffects : IBattleEffectDirector, IBattleSpiritCaptureLayout, IBattleMovementAudio + { + public readonly List Calls = new(); + + public Func CurrentActor; + + private long _nextHandle; + + public long Start(BattleEffectRequest request) => ++_nextHandle; + + public bool IsRunning(long handle) => false; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + } + + public BattleSpiritPoint CaptureSpiritOrigin(string actorId, BattleMovementPoint world) => new(400, 300); + + public BattleSpiritRect SpiritWheelTarget(int coreElement) => new(722, 300, 750, 345); + + public void PlayMovementSound(string actor, string sound, bool loop) => Calls.Add("play:" + sound); + + public void StopMovementSound(string actor) => Calls.Add("stop:" + CurrentActor()); + + public void StopBodySounds() + { + } + } + + [Test] + public void SummonReusingCapturedSlotsClearsOnlyTheirCurrentCaptureMarker() + { + BattleScenario scenario = Scenario("PAL3A", 720); + Learn(scenario.Participants[0], 4102); + Learn(scenario.Participants[1], 274); + for (int slot = 1; slot <= 3; slot += 2) + { + BattleParticipant enemy = Participant("captured" + slot, BattleSide.Enemy, (BattleSlot)slot, slot == 1 ? 7364 : 7365); + enemy.Vitals[0] = 1; + scenario.Participants.Add(enemy); + } + var capture = new BattleAbilityDefinition(new BattleAbilityData { Id = 4102, Range = BattleTargetRange.OpponentAll }); + var definitions = new BattleDefinitions("PAL3A", scenario.DataFingerprint, + new[] { capture, Magic(274, 0, 29) }, Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1, + Boss = actor.InstanceId == "E", + PhysicalAttackElementValues = new[] { 1, 0, 0, 0, 0 } + }))); + var catalog = new Catalog(); + var effects = new ReplacementEffects(); + var session = new BattleSession(new BattleSetup(scenario), catalog, new Rules(), definitions, effects); + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 4102)), Is.True); + while (session.WaitingActor != "E") + Assert.That(session.Submit(session.WaitingActor, BattleAction.Defend), Is.True); + Advance(session, 2); + Assert.That(session.SpiritOrbs, Has.Count.EqualTo(2)); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 274)), Is.True); + Advance(session, 2); + Assert.That(catalog.Created, Has.Count.EqualTo(2)); + Assert.That(session.SpiritOrbs, Has.Count.EqualTo(2), "Previously emitted spirit orbs still belong to the capture."); + Assert.That(session.Events.Count(entry => entry.Detail == "original spirit capture"), Is.EqualTo(2)); + Assert.That(catalog.Created.Any(created => created.InstanceId.StartsWith("captured")), Is.True); + foreach (var created in catalog.Created) + { + Assert.That(session.MonsterGeneration(created.InstanceId), Is.EqualTo(1)); + Assert.That(session.WasSpiritCaptured(created.InstanceId), Is.False, created.InstanceId); + } + foreach (BattleParticipant enemy in scenario.Participants.Where(actor => actor.InstanceId.StartsWith("captured") && + catalog.Created.All(created => created.InstanceId != actor.InstanceId))) + Assert.That(session.WasSpiritCaptured(enemy.InstanceId), Is.True); + } + + [Test] + public void ReplacingAMovingMonsterStopsItsOldAudioInTheSameTick() + { + BattleScenario scenario = Scenario("PAL3", 738); + var catalog = new Catalog(); + var effects = new ReplacementEffects(); + var definitions = new BattleDefinitions("PAL3", scenario.DataFingerprint, Array.Empty(), + Array.Empty(), scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1 + }))); + var session = new BattleSession(new BattleSetup(scenario), catalog, new Rules(), definitions, effects); + effects.CurrentActor = () => session.CaptureParticipant("E").ActorId; + catalog.OnCommit = creation => effects.Calls.Add("commit:" + creation.Participant.ActorId); + const System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic; + object enemy = typeof(BattleSession).GetMethod("ActorAtNativeIndex", flags).Invoke(session, new object[] { 10 }); + var movement = new BattleMovement("PAL3", new BattleMovementPlan(BattleMovementKind.Teleport, + new BattleMovementPoint(100, 0, 0), new BattleMovementPoint(0, 0, 0))); + enemy.GetType().GetField("Movement", flags | System.Reflection.BindingFlags.Public).SetValue(enemy, movement); + typeof(BattleSession).GetMethod("AdvanceBodyMovement", flags).Invoke(session, new object[] { enemy, true, null }); + Assert.That(effects.Calls, Is.EqualTo(new[] { "play:we014" })); + long tick = session.Tick; + typeof(BattleSession).GetMethod("CreateOriginalMonster", flags).Invoke(session, new object[] { 10, 739, 42L }); + Assert.That(effects.Calls, Is.EqualTo(new[] { "play:we014", "commit:739", "stop:738" })); + Assert.That(session.Tick, Is.EqualTo(tick)); + Assert.That(session.CaptureParticipant("E").ActorId, Is.EqualTo(739)); + Assert.That(session.Events.Last(entry => entry.Detail == "native enemy slot 10 created actor 739").ActionId, Is.EqualTo(42)); + typeof(BattleSession).GetMethod("SyncBodyMovementSound", flags).Invoke(session, new[] { enemy }); + Assert.That(effects.Calls.Count(call => call.StartsWith("stop:")), Is.EqualTo(1)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NativeZeroRoundLimitCanWinBeforeAnyEnemyDies(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.RoundLimit = 0; + BattleSession session = Session(scenario); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + Assert.That(session.Actors.Single(actor => actor.Side == BattleSide.Enemy).Hp, Is.EqualTo(500)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void CenterGaugeRoundsEndTheEncounterAtTheConfiguredLimit(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.RoundLimit = 2; + BattleSession session = Session(scenario); + Advance(session, 40, true); + Assert.That(session.BossRounds, Is.EqualTo(2)); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void APartyRoundLimitDoesNotCountAnEnemyOutsideTheCenter(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.RoundLimit = 1; + scenario.Participants[1].Slot = BattleSlot.Water; + BattleSession session = Session(scenario); + Advance(session, 30, true); + Assert.That(session.BossRounds, Is.Zero); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + Assert.That(session.Actors.Any(actor => actor.Rounds > 1), Is.True); + } + + [TestCase("PAL3", 210)] + [TestCase("PAL3A", 308)] + public void FireballPaysItsMagicCostBeforeSelfDestruction(string variant, int magicId) + { + BattleScenario scenario = Scenario(variant, 7312); + Learn(scenario.Participants[1], magicId); + BattleSession session = Session(scenario, null, Magic(magicId, -10)); + Assert.That(session.Submit("A", BattleAction.Defend), Is.True); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", magicId)), Is.True); + Advance(session, 3); + BattleActorSnapshot enemy = session.Actors.Single(actor => actor.Id == "E"); + Assert.That(enemy.Mp, Is.EqualTo(93)); + Assert.That(enemy.Hp, Is.Zero); + int cost = session.Events.ToList().FindIndex(entry => entry.Detail == "skill cost " + magicId); + int suicide = session.Events.ToList().FindIndex(entry => entry.Detail.Contains("fireball self-destruction")); + Assert.That(cost, Is.GreaterThanOrEqualTo(0)); + Assert.That(suicide, Is.GreaterThan(cost)); + } + + [Test] + public void ChongLouReusesTheNativeSlotAndLaterQueuedTargetBindsToTheNewForm() + { + BattleScenario scenario = Scenario("PAL3", 738); + scenario.Participants.Insert(1, Participant("B", BattleSide.Ally, BattleSlot.Fire, 104)); + Learn(scenario.Participants[0], 9991); + Learn(scenario.Participants[1], 9992, 1); + var catalog = new Catalog(); + BattleSession session = Session(scenario, catalog, Magic(9991, -100000), Magic(9992, -30)); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 9991)), Is.True); + Assert.That(session.Submit(new BattleCommand("B", BattleAction.Skill, "E", 9992)), Is.True); + Advance(session, 3, true); + session.SetAutomatic(BattleSide.Enemy, false); + Advance(session, 100, true); + Assert.That(catalog.Created.Single(), Is.EqualTo((10, 739, "E"))); + Assert.That(session.CaptureParticipant("E").ActorId, Is.EqualTo(739)); + Assert.That(session.MonsterGeneration("E"), Is.EqualTo(1)); + Assert.That(session.ActiveScene, Is.EqualTo("z39")); + Assert.That(session.StealPools.Single(pool => pool.Actor == "E").Money, Is.EqualTo(739)); + Assert.That(session.Events.Any(entry => entry.Source == "B" && entry.Target == "E" && entry.HpBefore == 500 && entry.HpAfter < 500), Is.True); + } + + [TestCase("PAL3", 7710)] + [TestCase("PAL3A", 274)] + public void SummonedEnemiesHaveTheirOwnStealPoolsAndCanTakeManualTurns(string variant, int skillId) + { + BattleScenario scenario = Scenario(variant); + Learn(scenario.Participants[1], skillId); + var catalog = new Catalog(); + BattleSession session = Session(scenario, catalog, Magic(skillId, 0, 29)); + Assert.That(session.Submit("A", BattleAction.Defend), Is.True); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", skillId)), Is.True); + Advance(session, 2); + Assert.That(catalog.Created, Has.Count.EqualTo(2)); + Assert.That(session.Actors.Count(actor => actor.Side == BattleSide.Enemy), Is.EqualTo(3)); + foreach (var created in catalog.Created) + { + Assert.That(session.CaptureParticipant(created.InstanceId).ActorId, Is.EqualTo(created.ActorId)); + Assert.That(session.MonsterGeneration(created.InstanceId), Is.EqualTo(1)); + Assert.That(session.StealPools.Single(pool => pool.Actor == created.InstanceId).Money, Is.EqualTo(created.ActorId)); + Assert.That(session.GetAiProfile(created.InstanceId), Is.EqualTo(63)); + } + + session.SetAutomatic(BattleSide.Enemy, false); + string summoned = catalog.Created[0].InstanceId; + for (int tick = 0; tick < 50 && session.WaitingActor != summoned; tick++) + { + if (session.WaitingActor is { } waiting) + Assert.That(session.Submit(waiting, BattleAction.Defend), Is.True); + else + Advance(session, 1); + } + Assert.That(session.WaitingActor, Is.EqualTo(summoned)); + Assert.That(session.Submit(summoned, BattleAction.Attack, "A"), Is.True); + Assert.That(session.Inputs.Last().Actor, Is.EqualTo(summoned)); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Attack)); + } + + [TestCase("PAL3", true)] + [TestCase("PAL3A", false)] + public void DefeatReportsTheIndependentGameOverPolicy(string variant, bool gameOver) + { + BattleScenario scenario = Scenario(variant); + scenario.GameOverOnDefeat = gameOver; + scenario.Participants[0].Vitals[0] = 0; + BattleSession session = Session(scenario); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Enemy)); + Assert.That(session.Result.GameOver, Is.EqualTo(gameOver)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleEncounterSessionTests.cs.meta b/Assets/Tests/Battle/Editor/BattleEncounterSessionTests.cs.meta new file mode 100644 index 00000000..62e8375a --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleEncounterSessionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f3eb572fceb14ccea61c7cc153897ff3 diff --git a/Assets/Tests/Battle/Editor/BattleFleeTests.cs b/Assets/Tests/Battle/Editor/BattleFleeTests.cs new file mode 100644 index 00000000..63d0bcfe --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleFleeTests.cs @@ -0,0 +1,436 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleFleeTests + { + private sealed class Catalog : IBattleCatalog, IBattlePhysicalTimings, IBattleAbilityTimings, IBattleStageGeometry + { + private readonly string _variant; + + internal Catalog(string variant) => _variant = variant; + + public int Priority(string actor) => actor == "A" ? 0 : actor == "B" ? 1 : 5; + + public int GuardEntry(string actor) => 2; + + public int Hurt(string actor) => 5; + + public int SpImpact(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 5, new[] { 2 }); + + public BattlePhysicalStageProfile Physical(string actor) + { + var animations = Enum.GetValues(typeof(BattlePose)).Cast().ToDictionary(pose => pose, + pose => new BattlePhysicalAnimation(pose.ToString(), 5, 10, new[] { new BattlePhysicalMarker(4, BattlePhysicalMarkerKind.Over) })); + return new BattlePhysicalStageProfile(_variant, actor == "E" ? 701 : 101, actor == "E" ? -1 : actor == "A" ? 0 : 1, 1, 1, animations); + } + + public BattleMovementPoint InitialHome(string actor) => actor == "A" ? new(0, 0, 0) : actor == "B" ? new(100, 0, 0) : new(200, 0, 0); + + public BattleMovementPoint FormationHome(string actor, BattleSlot slot) => InitialHome(actor); + + public IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint from, BattleMovementPoint to, bool crossing) => new[] { new BattleMovementPlan(BattleMovementKind.Run, from, to) }; + + public BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint from, BattleMovementPoint to) => new(Attack(source, target), from, from, to); + } + + private sealed class ReadyRules : IBattleRules + { + private readonly string _ready; + + internal ReadyRules(string ready) => _ready = ready; + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => actor.InstanceId == _ready ? BattleSession.FullGauge - (_ready == "E" ? 1 : 0) : 0; + + public int GaugePerStep(BattleParticipant actor) => 1; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => new(-1, false, false); + } + + private static BattleParticipant Participant(string id, BattleSide side) => new() + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? id == "A" ? 101 : 104 : 701, + Side = side, + Slot = id == "B" ? BattleSlot.Fire : BattleSlot.Water, + Level = 10, + Attributes = new[] { 100, 100, 100, 10, 10, 3, 10, 0, 0, 0, 0, 0 }, + Vitals = new[] { 100, 100, 100 } + }; + + private static BattleSession Session(string variant, bool script = false, bool enemyFlee = false, bool secondAlly = false) + { + var scenario = new BattleScenario { Variant = variant, Scene = "portable", DataFingerprint = "flee-fixture", ScriptBattle = script, Seed = 1 }; + scenario.Participants.Add(Participant("A", BattleSide.Ally)); + scenario.Participants.Add(Participant("E", BattleSide.Enemy)); + if (secondAlly) + scenario.Participants.Add(Participant("B", BattleSide.Ally)); + scenario.Items.Add(new BattleItem { Id = 6114, Count = 2 }); + var item = new BattleAbilityData + { + Id = 6114, + IsItem = true, + Range = BattleTargetRange.OwnSingle, + Handler = BattleSpecialHandler.ForceFlee + }; + var definitions = new BattleDefinitions(variant, "flee-fixture", Array.Empty(), new[] { new BattleAbilityDefinition(item) }, scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Enemy ? -1 : actor.InstanceId == "A" ? 0 : 1, + EscapePercent = enemyFlee && actor.Side == BattleSide.Enemy ? 100 : 0 + }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(variant), new ReadyRules(enemyFlee ? "E" : "A"), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + session.SetAutomatic(BattleSide.Ally, false); + return session; + } + + private static BattleActorSnapshot Actor(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + private static void Steps(BattleSession session, int count) + { + for (int i = 0; i < count; i++) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + } + + private static void Until(BattleSession session, Func condition, int limit = 1200) + { + while (!condition() && session.Status == BattleSessionStatus.Running && limit-- > 0) + session.Step(); + Assert.That(condition(), Is.True, session.Result?.Reason); + } + + private static object NativeActor(BattleSession session, string id) => ((System.Collections.IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(session))[id]; + + private static object Invoke(BattleSession session, string name, params object[] arguments) => typeof(BattleSession).GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance).Invoke(session, arguments); + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void LastEnemyDeathAtTheFleeWaitBoundaryReleasesTheAttemptAndCompletesVictory(string variant) + { + var scenario = new BattleScenario + { + Variant = variant, + Scene = "portable", + DataFingerprint = "flee-boundary", + Encounter = BattleEncounter.AllyAmbush + }; + scenario.Participants.Add(Participant("A", BattleSide.Ally)); + scenario.Participants.Add(Participant("B", BattleSide.Ally)); + scenario.Participants.Add(Participant("E", BattleSide.Enemy)); + scenario.Participants[1].Attributes[3] = 1000; + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, + Array.Empty(), Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Enemy ? -1 : actor.InstanceId == "A" ? 0 : 1 + }))); + var catalog = new BattleSessionTests.Catalog { Timing = new AttackTiming(0, 300, new[] { 263 }) }; + var setup = new BattleSetup(scenario); + var session = new BattleSession(setup, catalog, definitions: definitions); + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Assert.That(session.Submit("B", BattleAction.Attack, "E"), Is.True); + Steps(session, 263); + Assert.That(Actor(session, "E").Hp, Is.Zero); + Assert.That(session.StageTasks.Any(task => task.Kind == "flee wait" && task.Finished), Is.True); + Until(session, () => session.Result != null); + Assert.That(session.Result.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + Assert.That(session.Result.Escaped, Is.False); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Escaped || entry.Detail == "escape failed"), Is.False); + Assert.That(session.StageTasks, Is.Empty); + Assert.That(((System.Collections.IDictionary)typeof(BattleSession).GetField("_bodyStageOwners", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session)).Count, Is.Zero); + BattleSession replay = BattleReplay.Play(setup, catalog, session.Inputs, session.Tick, definitions: definitions); + Assert.That(replay.Result.Winner, Is.EqualTo(BattleSide.Ally)); + Assert.That(replay.Result.Escaped, Is.False); + Assert.That(replay.Events.Select(entry => (entry.Tick, entry.Kind, entry.RandomState)), + Is.EqualTo(session.Events.Select(entry => (entry.Tick, entry.Kind, entry.RandomState)))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void SuccessWaitsForBothSlotsThenRunsThePartyBeforeEnding(string variant) + { + BattleSession session = Session(variant, secondAlly: true); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Steps(session, 1); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Fleeing)); + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(44)); + Until(session, () => session.FleeResult?.Success == true); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + Assert.That(Actor(session, "A").Position.X, Is.LessThan(0)); + Assert.That(Actor(session, "B").Position.X, Is.LessThan(100)); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Moving)); + int enemyGauge = Actor(session, "E").Gauge; + Steps(session, 10); + Assert.That(Actor(session, "E").Gauge, Is.EqualTo(enemyGauge)); + Until(session, () => session.Result != null); + Assert.That(session.Result.Escaped, Is.True); + Assert.That(Actor(session, "A").Position.X, Is.EqualTo(-800)); + Assert.That(Actor(session, "A").Position.Z, Is.EqualTo(-800)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void BusyBodyRepeatsTheNativeEscapeRollUntilItCanRun(string variant) + { + BattleSession session = Session(variant); + typeof(BattleSession).GetField("_fleeAlwaysSucceeds", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(session, true); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Until(session, () => session.StageTasks.Any(task => task.Kind == "flee wait" && task.Finished)); + object actor = NativeActor(session, "A"); + actor.GetType().GetField("HurtUntil").SetValue(actor, (int)session.SimulationTick + 4); + + Steps(session, 3); + BattleEvent[] success = session.Events.Where(entry => entry.Kind == BattleEventKind.Escaped).ToArray(); + Assert.That(success.Select(entry => entry.RandomState), Is.EqualTo(new uint[] { 2745024, 3357800067, 415139642 })); + Assert.That(Actor(session, "A").Position, Is.EqualTo(Actor(session, "A").Home)); + Steps(session, 1); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Moving)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ScriptFailureConsumesProbabilityAndKeepsAThreeSecondMessage(string variant) + { + BattleSession session = Session(variant, script: true); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Until(session, () => session.FleeResult != null); + Assert.That(session.FleeResult.Success, Is.False); + Assert.That(session.Events.Last(entry => entry.Detail == "escape failed").RandomState, Is.EqualTo(2745024)); + float started = session.FleeResult.StartedAtSeconds; + Until(session, () => BattleStageScheduler.TimeAt(session.SimulationTick + 1) - started > 3f); + Assert.That(session.FleeResult, Is.Not.Null); + Steps(session, 1); + Assert.That(session.FleeResult, Is.Null); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NegativeHpRequestInterruptsTheWaitBodyAndSchedulesFailure(string variant) + { + BattleSession session = Session(variant); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Steps(session, 5); + Invoke(session, "ChangeHp", NativeActor(session, "A"), -1, null, 0L, "native negative HP test", false, false, false); + Assert.That(Actor(session, "A").CurrentAction, Is.EqualTo(BattleAction.Flee)); + Assert.That(Actor(session, "A").CastGauge, Is.Zero); + Assert.That(session.FleeResult, Is.Null); + Until(session, () => session.FleeResult != null); + Assert.That(session.FleeResult.Success, Is.False); + Assert.That(Actor(session, "A").CurrentAction, Is.Null); + Assert.That(Actor(session, "A").Gauge, Is.GreaterThan(0)); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void GhostEscapeWaterUsesAnIndependentWaitThreadAndScriptBattlesDoNotSetItsFlag(string variant, bool script) + { + BattleSession session = Session(variant, script: script); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "A", 6114)), Is.True); + Until(session, () => session.FleeResult != null); + Assert.That(session.FleeAlwaysSucceeds, Is.EqualTo(!script)); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(1)); + Assert.That(session.FleeResult.Success, Is.EqualTo(!script)); + Assert.That(session.Events.Any(entry => entry.Detail == "item consumed when its action starts"), Is.True); + if (!script) + { + Assert.That(session.Tick, Is.LessThan(100)); + Until(session, () => session.Result != null); + Assert.That(session.Result.Escaped, Is.True); + } + } + + [TestCase("PAL3", false, 1u)] + [TestCase("PAL3A", false, 1u)] + [TestCase("PAL3", true, 2745024u)] + [TestCase("PAL3A", true, 1u)] + public void ProbabilityEndpointsPreserveThePublishedVariantRandomOrder(string variant, bool highChance, uint expectedSeed) + { + BattleSession session = Session(variant, script: true); + object actor = NativeActor(session, "A"); + object enemy = NativeActor(session, "E"); + actor.GetType().GetField("Level").SetValue(actor, highChance ? 1 : 100); + enemy.GetType().GetField("Level").SetValue(enemy, highChance ? 100 : 1); + ((int[])actor.GetType().GetField("Attributes").GetValue(actor))[6] = 0; + ((int[])enemy.GetType().GetField("Attributes").GetValue(enemy))[6] = 100; + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Until(session, () => session.FleeResult != null); + Assert.That(session.Events.Last(entry => entry.Detail == "escape failed").RandomState, Is.EqualTo(expectedSeed)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void CancellingThePartyRunReleasesItsSharedBodiesAndResumesTheGauges(string variant) + { + BattleSession session = Session(variant, secondAlly: true); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Until(session, () => session.FleeResult?.Success == true); + Steps(session, 5); + Assert.That(Actor(session, "A").Position, Is.Not.EqualTo(Actor(session, "A").Home)); + Assert.That(Actor(session, "B").Position, Is.Not.EqualTo(Actor(session, "B").Home)); + Assert.That(session.CancelAction("A"), Is.True); + Assert.That(Actor(session, "A").Position, Is.EqualTo(Actor(session, "A").Home)); + Assert.That(Actor(session, "B").Position, Is.EqualTo(Actor(session, "B").Home)); + Assert.That(((System.Collections.IDictionary)typeof(BattleSession).GetField("_bodyStageOwners", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session)).Count, Is.Zero); + Steps(session, 10); + Assert.That(Actor(session, "A").Movement, Is.Null); + Assert.That(Actor(session, "B").Movement, Is.Null); + Assert.That(Actor(session, "A").Gauge, Is.GreaterThan(0)); + Assert.That(Actor(session, "B").Gauge, Is.GreaterThan(0)); + Assert.That(Actor(session, "E").Gauge, Is.GreaterThan(264)); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void StoppingThePartyRunClearsThePauseAndAllBodiesIdempotently(string variant, bool fault) + { + BattleSession session = Session(variant, secondAlly: true); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Until(session, () => session.FleeResult?.Success == true); + if (fault) + session.Fault("flee fault test"); + else + session.Abort(); + Assert.That(typeof(BattleSession).GetField("_fleeAtbPaused", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session), Is.False); + Assert.That(((System.Collections.IDictionary)typeof(BattleSession).GetField("_bodyStageOwners", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session)).Count, Is.Zero); + Invoke(session, "StopFleeStages"); + Assert.That(session.Status, Is.EqualTo(fault ? BattleSessionStatus.Faulted : BattleSessionStatus.Aborted)); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void ACommittedPartyEscapeContinuesAfterLethalDamageUnlessTheWholePartyIsDead(string variant, bool allDead) + { + BattleSession session = Session(variant, secondAlly: true); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Until(session, () => session.FleeResult?.Success == true); + Invoke(session, "ChangeHp", NativeActor(session, "A"), -1000, null, 0L, "pending lethal during committed escape", false, false, false); + if (allDead) + Invoke(session, "ChangeHp", NativeActor(session, "B"), -1000, null, 0L, "last party member killed during escape", false, false, false); + Until(session, () => session.Result != null); + Assert.That(session.Result.Escaped, Is.EqualTo(!allDead)); + Assert.That(session.Result.Winner, Is.EqualTo(allDead ? (BattleSide?)BattleSide.Enemy : null)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Cancelled && entry.Source == "A" && entry.Detail == "physical stage received an end request"), Is.False); + } + + [TestCase("PAL3", BattleState.Chaos, false)] + [TestCase("PAL3A", BattleState.Chaos, false)] + [TestCase("PAL3", BattleState.Madness, false)] + [TestCase("PAL3A", BattleState.Madness, false)] + [TestCase("PAL3", BattleState.Chaos, true)] + [TestCase("PAL3A", BattleState.Chaos, true)] + [TestCase("PAL3", BattleState.Madness, true)] + [TestCase("PAL3A", BattleState.Madness, true)] + public void UncontrollableStatesResetOnlyOrdinaryEscapeWaiting(string variant, BattleState state, bool forced) + { + BattleSession session = Session(variant); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Steps(session, 5); + typeof(BattleSession).GetField("_fleeAlwaysSucceeds", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(session, forced); + int before = Actor(session, "A").CastGauge; + Invoke(session, "ApplyState", NativeActor(session, "A"), state, false, 99, true, null, 0L, true); + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(forced ? before : 0)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Interrupted && entry.Source == "A"), Is.EqualTo(!forced)); + Until(session, () => session.FleeResult != null); + Assert.That(session.FleeResult.Success, Is.EqualTo(forced)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void LethalDamageDuringWaitingStillFinishesTheNativeFailureMessage(string variant) + { + BattleSession session = Session(variant, secondAlly: true); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Steps(session, 5); + Invoke(session, "ChangeHp", NativeActor(session, "A"), -1000, null, 0L, "lethal request while waiting", false, false, false); + Until(session, () => session.FleeResult != null); + Assert.That(session.FleeResult.Success, Is.False); + Assert.That(Actor(session, "A").CurrentAction, Is.Null); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Cancelled && entry.Source == "A" && entry.Detail == "physical stage received an end request"), Is.False); + } + + [TestCase("PAL3", BattleState.Paralysis)] + [TestCase("PAL3A", BattleState.Paralysis)] + [TestCase("PAL3", BattleState.Sleep)] + [TestCase("PAL3A", BattleState.Sleep)] + [TestCase("PAL3", BattleState.Chaos)] + [TestCase("PAL3A", BattleState.Chaos)] + [TestCase("PAL3", BattleState.Madness)] + [TestCase("PAL3A", BattleState.Madness)] + public void UncontrollableStatesDoNotRevokeACommittedPartyEscape(string variant, BattleState state) + { + BattleSession session = Session(variant, secondAlly: true); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Until(session, () => session.FleeResult?.Success == true); + Invoke(session, "ApplyState", NativeActor(session, "A"), state, false, 99, true, null, 0L, true); + Assert.That(Actor(session, "A").CurrentAction, Is.EqualTo(BattleAction.Flee)); + Assert.That(Actor(session, "A").CastGauge, Is.Zero); + Until(session, () => session.Result != null); + Assert.That(session.Result.Escaped, Is.True); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void EnemyArrivalClearsNativeStatesAndModelLifeOnlyInPal3A(string variant) + { + BattleSession session = Session(variant, enemyFlee: true); + Steps(session, 1); + object enemy = NativeActor(session, "E"); + var states = (Dictionary)enemy.GetType().GetField("States").GetValue(enemy); + states[BattleState.Barrier] = new BattleStatusRules(variant).Create(BattleState.Barrier, 100, 99, true); + int rounds = Actor(session, "E").Rounds; + Until(session, () => Actor(session, "E").Escaped); + Assert.That(Actor(session, "E").Rounds, Is.EqualTo(rounds)); + Assert.That(Actor(session, "E").States.Any(state => state.State == BattleState.Barrier), Is.EqualTo(variant == "PAL3")); + Assert.That(Actor(session, "E").ModelAliveFlag, Is.EqualTo(variant == "PAL3")); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void EnemyBecomesFleeingBeforeWalkingAndFledOnlyAfterReachingItsDestination(string variant) + { + BattleSession session = Session(variant, enemyFlee: true); + Steps(session, 1); + BattleActorSnapshot before = Actor(session, "E"); + Assert.That(before.Fleeing, Is.True); + Assert.That(before.Escaped, Is.False); + Assert.That(before.Pose, Is.EqualTo(BattlePose.Moving)); + Invoke(session, "ChangeHp", NativeActor(session, "E"), -1, null, 0L, "pending damage can hit a fleeing target", false, false, false); + Assert.That(Actor(session, "E").Hp, Is.EqualTo(99)); + Until(session, () => Actor(session, "E").Escaped); + Assert.That(Actor(session, "E").Position.X, Is.EqualTo(800)); + Assert.That(Actor(session, "E").Position.Z, Is.EqualTo(800)); + Until(session, () => session.Result != null); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleFleeTests.cs.meta b/Assets/Tests/Battle/Editor/BattleFleeTests.cs.meta new file mode 100644 index 00000000..c1ae42a4 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleFleeTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 17eae6ea61db48f4a36200e4e3025cb2 diff --git a/Assets/Tests/Battle/Editor/BattleFormationRulesTests.cs b/Assets/Tests/Battle/Editor/BattleFormationRulesTests.cs new file mode 100644 index 00000000..7975c406 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleFormationRulesTests.cs @@ -0,0 +1,179 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + // The 232 expected outcomes were obtained by executing the two original EXEs. + // Fixtures and image fingerprints remain in workspace/Analysis/Battle-Stage4. + public sealed class BattleFormationRulesTests + { + private static readonly string[] ComboCases = + { + "base", "auxInvalid", "auxDeadZeroHp", "auxFled", "auxParalyzed", "auxTransformed", "sourceDead", + "weaponZeroRequired", "wrongTrigger", "wrongLead", "missingRequiredState", "matchingRequiredState", + "anyPoisonMissing", "anyPoisonPresent", + }; + + private static readonly string[] ProtectCases = + { + "base", "noSelection", "differentSelection", "notMiddle", "ownDead", "ownParalyzed", "targetDead", + "ownBusy", "ownAway", "targetAway", "targetInvalid", "guardianInvalid", + }; + + private static readonly string[] LineupCases = + { + "base", "actor0Busy", "actor4Busy", "enemyBusy", "invalidActorBusy", "deadActorBusy", + }; + + public static IEnumerable NativeCases() + { + foreach (string variant in new[] { "PAL3", "PAL3A" }) + { + string comboOutcomes = variant == "PAL3" ? "10111110000101" : "10111011000101"; + for (int index = 0; index < ComboCases.Length; index++) + yield return Case(variant, "combo", ComboCases[index], 0, 0, comboOutcomes[index] == '1'); + int[] nativePositionMasks = { 1, 2, 4, 8, 16, 32, 14, 19 }; + for (int required = 1; required <= 8; required++) + { + for (int actual = 1; actual <= 6; actual++) + yield return Case(variant, "combo", "auxPosition", required, actual, (nativePositionMasks[required - 1] & (1 << (actual - 1))) != 0); + } + string[] hpOutcomes = { "000", "110", "110" }; + for (int own = 49; own <= 51; own++) + { + for (int target = 9; target <= 11; target++) + yield return Case(variant, "protect", "hpBoundary", own, target, hpOutcomes[own - 49][target - 9] == '1'); + } + const string protectOutcomes = "100001100010"; + for (int index = 0; index < ProtectCases.Length; index++) + yield return Case(variant, "protect", ProtectCases[index], 0, 0, protectOutcomes[index] == '1'); + const string lineupOutcomes = "100110"; + for (int index = 0; index < LineupCases.Length; index++) + yield return Case(variant, "lineup", LineupCases[index], 0, 0, lineupOutcomes[index] == '1'); + for (int state = 0; state <= 26; state++) + yield return Case(variant, "move", "state", state, 0, state is not (14 or 17 or 18 or 19)); + } + } + + [TestCaseSource(nameof(NativeCases))] + public void MatchesOriginalEligibility(string variant, string category, string name, int first, int second, bool expected) + { + var rules = new BattleFormationRules(variant); + int[] ids = variant == "PAL3" ? new[] { 101, 104, 105, 107, 102 } : new[] { 101, 102, 103, 104, 105 }; + BattleFormationDecision decision; + if (category == "combo") + { + var actors = Enumerable.Range(0, 5).Select(index => Actor(index, ids)).ToArray(); + bool dead = name == "auxDeadZeroHp"; + BattleState[] states = name is "auxParalyzed" or "matchingRequiredState" ? new[] { BattleState.Paralysis } + : name == "anyPoisonPresent" ? new[] { BattleState.PoisonWater } : Array.Empty(); + actors[1] = Actor(1, ids, valid: name != "auxInvalid", alive: !dead, hp: dead ? 0 : 100, states: states, + fled: name == "auxFled", transformed: name == "auxTransformed", slot: name == "auxPosition" ? (BattleSlot)(second - 1) : null); + if (name == "sourceDead") + actors[0] = Actor(0, ids, alive: false, hp: 0); + var requirement = new BattleComboRequirement(9001, name == "wrongTrigger" ? 43 : 42, + new[] { name == "wrongLead" ? ids[1] : ids[0], ids[1], 0, 0 }, + new[] { 0, name == "auxPosition" ? first : 0, 0, 0 }, + new[] { 2, name == "weaponZeroRequired" ? 0 : 3, 0, 0 }, + new[] { name is "missingRequiredState" or "matchingRequiredState" ? 13 + : name is "anyPoisonMissing" or "anyPoisonPresent" ? 26 : -1, -1, -1 }); + decision = rules.CanCoAttack(0, 42, requirement, actors); + } + else if (category == "protect") + { + bool hpCase = name == "hpBoundary"; + var guardian = Actor(0, ids, hp: hpCase ? first : 50, maxHp: hpCase ? 101 : 100, + valid: name != "guardianInvalid", + slot: name == "notMiddle" ? BattleSlot.Water : BattleSlot.Center, + alive: name != "ownDead", states: name == "ownParalyzed" ? new[] { BattleState.Paralysis } : null, + idle: name != "ownBusy", home: name != "ownAway"); + var target = Actor(1, ids, hp: name == "targetDead" ? 0 : hpCase ? second : 10, + valid: name != "targetInvalid", + maxHp: hpCase ? 109 : 100, alive: name != "targetDead", home: name != "targetAway"); + decision = rules.CanProtect(name == "noSelection" ? 0 : name == "differentSelection" ? 2 : 1, guardian, target); + } + else if (category == "lineup") + { + var actors = Enumerable.Range(0, 5).Select(index => Actor(index, ids)).ToList(); + if (name == "actor0Busy") + actors[0] = Actor(0, ids, tasks: 1); + if (name == "actor4Busy") + actors[4] = Actor(4, ids, tasks: 2); + if (name == "enemyBusy") + actors.Add(Actor(5, ids, tasks: 1)); + if (name == "invalidActorBusy") + actors[1] = Actor(1, ids, valid: false, tasks: 1); + if (name == "deadActorBusy") + actors[1] = Actor(1, ids, alive: false, tasks: 1); + decision = rules.CanChangeLineup(actors); + } + else + { + decision = rules.CanMove(Actor(0, ids, states: first == 0 ? null : new[] { (BattleState)(first - 1) })); + } + Assert.That(decision.Allowed, Is.EqualTo(expected)); + if (!expected) + Assert.That(decision.FailureReason, Is.Not.Null.And.Not.Empty); + } + + [Test] + public void SnapshotsCaptureCallerCollections() + { + var states = new[] { BattleState.Seal }; + var actor = new BattleFormationActor(0, 101, BattleSlot.Water, 2, states: states); + var members = new[] { 101, 104, 0, 0 }; + var requirement = new BattleComboRequirement(9001, 42, members, new int[4], new int[4], new[] { -1, -1, -1 }); + states[0] = BattleState.Sleep; + members[0] = 999; + Assert.That(actor.States[0], Is.EqualTo(BattleState.Seal)); + Assert.That(requirement.Members[0], Is.EqualTo(101)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ZeroMaximumHpDoesNotAddALineupCondition(string variant) + { + var rules = new BattleFormationRules(variant); + var deadActor = new BattleFormationActor(1, 104, BattleSlot.Fire, 0, alive: false, hp: 0, maxHp: 0); + var absentActor = new BattleFormationActor(2, 105, BattleSlot.Wind, 0, valid: false, hp: 0, maxHp: 0, taskCount: 1); + Assert.That(rules.CanChangeLineup(new[] { deadActor, absentActor }).Allowed, Is.True); + } + + [TestCase("PAL3", 1, true)] + [TestCase("PAL3", 2, true)] + [TestCase("PAL3", 3, true)] + [TestCase("PAL3", 4, false)] + [TestCase("PAL3A", 1, true)] + [TestCase("PAL3A", 2, true)] + [TestCase("PAL3A", 3, false)] + [TestCase("PAL3A", 4, false)] + public void ProtectPanelExposesOriginalTargets(string variant, int targetIndex, bool expected) + { + var rules = new BattleFormationRules(variant); + var guardian = new BattleFormationActor(0, 101, BattleSlot.Center, 0); + var target = new BattleFormationActor(targetIndex, 102, BattleSlot.Fire, 0); + Assert.That(rules.CanSetProtect(guardian, target).Allowed, Is.EqualTo(expected)); + target = new BattleFormationActor(targetIndex, 102, BattleSlot.Fire, 0, alive: false); + Assert.That(rules.CanSetProtect(guardian, target).Allowed, Is.False); + target = new BattleFormationActor(targetIndex, 102, BattleSlot.Fire, 0, valid: false); + Assert.That(rules.CanSetProtect(guardian, target).Allowed, Is.False); + } + + private static TestCaseData Case(string variant, string category, string name, int first, int second, bool expected) + => new TestCaseData(variant, category, name, first, second, expected).SetName($"{variant}_{category}_{name}_{first}_{second}"); + + private static BattleFormationActor Actor(int index, IReadOnlyList ids, bool valid = true, bool alive = true, + int hp = 100, int maxHp = 100, IEnumerable states = null, bool fled = false, + bool transformed = false, BattleSlot? slot = null, bool idle = true, bool home = true, int tasks = 0) + => new(index, index < 5 ? ids[index] : 701, slot ?? (index < 5 ? (BattleSlot)index : BattleSlot.Center), index + 2, + valid, alive, hp, maxHp, states, tasks, home, idle, transformed, fled); + } +} diff --git a/Assets/Tests/Battle/Editor/BattleFormationRulesTests.cs.meta b/Assets/Tests/Battle/Editor/BattleFormationRulesTests.cs.meta new file mode 100644 index 00000000..e5ae980f --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleFormationRulesTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c83928866ed646b881c1338156ae9422 diff --git a/Assets/Tests/Battle/Editor/BattleInitializationTests.cs b/Assets/Tests/Battle/Editor/BattleInitializationTests.cs new file mode 100644 index 00000000..1231a081 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleInitializationTests.cs @@ -0,0 +1,99 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleInitializationTests + { + private sealed class Catalog : IBattleCatalog + { + public AttackTiming Attack(string source, string target) => new(0, 2, new[] { 1 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => int.Parse(actor.Substring(1)); + + public int DamageDivisor(string actor) => 1; + } + + // Full published InitSequen functions: PAL3 0x4dbb80, PAL3A 0x4cf38b. + // Independently executed by Battle-Stage23-InitializationReview/probe-initialization.py. + // Native slot 0 is dead whenever present; missing slots have bValid=false. + private static IEnumerable NativeInitialGauges() + { + var vectors = new[] + { + (BattleEncounter.Normal, new[] { 0, 1, 5 }, new[] { 1955, 2517, 2506 }, 415139642u), + (BattleEncounter.Normal, new[] { 1, 5 }, new[] { 1955, 2517 }, 3357800067u), + (BattleEncounter.Normal, new[] { 0, 4, 5, 10 }, new[] { 1955, 2517, 2506, 2256 }, 3884216597u), + (BattleEncounter.EnemyAmbush, new[] { 0, 1, 5 }, new[] { 0, 0, 11500 }, 1u), + (BattleEncounter.EnemyAmbush, new[] { 1, 5 }, new[] { 0, 11500 }, 1u), + (BattleEncounter.EnemyAmbush, new[] { 0, 4, 5, 10 }, new[] { 0, 0, 11500, 11500 }, 1u), + (BattleEncounter.AllyAmbush, new[] { 0, 1, 5 }, new[] { 11500, 11500, 0 }, 1u), + (BattleEncounter.AllyAmbush, new[] { 1, 5 }, new[] { 11500, 0 }, 1u), + (BattleEncounter.AllyAmbush, new[] { 0, 4, 5, 10 }, new[] { 11500, 11500, 0, 0 }, 1u) + }; + foreach (string variant in new[] { "PAL3", "PAL3A" }) + foreach (bool captured in new[] { false, true }) + foreach (var vector in vectors) + yield return new TestCaseData(variant, captured, vector.Item1, vector.Item2, vector.Item3, vector.Item4); + } + + [TestCaseSource(nameof(NativeInitialGauges))] + public void DeadParticipantsReceiveInitialGaugesAndMissingSlotsDoNotConsumeRandomness(string variant, bool captured, + BattleEncounter encounter, int[] nativeSlots, int[] expectedGauges, uint finalSeed) + { + var scenario = new BattleScenario + { + Variant = variant, + Scene = "native-initialization", + DataFingerprint = "native-initialization-fixture", + Seed = 1, + Encounter = encounter + }; + // Authoring order differs from the original identity / enemy-slot order. + foreach (int slot in nativeSlots.Reverse()) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = "N" + slot, + ActorId = slot < 5 ? 101 + slot : 701, + Side = slot < 5 ? BattleSide.Ally : BattleSide.Enemy, + Slot = (BattleSlot)(slot < 5 ? slot : slot - 5), + Attributes = new[] { 100, 50, 30, 40, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { slot == 0 ? 0 : 100, 0, 30 } + }); + BattleDefinitions definitions = captured ? new BattleDefinitions(variant, scenario.DataFingerprint, + Array.Empty(), Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? int.Parse(actor.InstanceId.Substring(1)) : -1 + }))) : null; + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), definitions: definitions); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + Assert.That(session.Actors.Count, Is.EqualTo(nativeSlots.Length)); + for (int index = 0; index < nativeSlots.Length; index++) + { + int slot = nativeSlots[index]; + BattleActorSnapshot actor = session.Actors.Single(actor => actor.Id == "N" + slot); + Assert.That(actor.Gauge, Is.EqualTo(expectedGauges[index]), "native slot " + slot); + Assert.That(actor.Ready, Is.EqualTo(slot != 0 && expectedGauges[index] >= BattleSession.FullGauge)); + Assert.That(actor.Rounds, Is.Zero); + } + Assert.That(session.Events.Single(entry => entry.Kind == BattleEventKind.Started).RandomState, Is.EqualTo(finalSeed)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Ready && entry.Source == "N0"), Is.False); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleInitializationTests.cs.meta b/Assets/Tests/Battle/Editor/BattleInitializationTests.cs.meta new file mode 100644 index 00000000..6effe2b5 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleInitializationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f3f54c0daeb1484b970d2ad5d8b7cf63 diff --git a/Assets/Tests/Battle/Editor/BattleLoadoutTests.cs b/Assets/Tests/Battle/Editor/BattleLoadoutTests.cs new file mode 100644 index 00000000..a0256066 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleLoadoutTests.cs @@ -0,0 +1,103 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleLoadoutTests + { + [TestCase("PAL3", 101, 0, 6603)] + [TestCase("PAL3", 104, 1, 6603)] + [TestCase("PAL3", 106, 2, 6603)] + [TestCase("PAL3", 107, 3, 6603)] + [TestCase("PAL3", 102, 4, 6603)] + [TestCase("PAL3A", 101, 0, 82110)] + [TestCase("PAL3A", 102, 1, 82209)] + [TestCase("PAL3A", 103, 2, 82310)] + [TestCase("PAL3A", 104, 3, 82402)] + [TestCase("PAL3A", 105, 4, 82508)] + public void MissingWeaponUsesTheCompletePublishedInitializationResult(string variant, int actorId, int identity, int weapon) + { + // Complete InitRoleState probes, not inferred weapon suitability: + // PAL3 0x4ed8c0 / PAL3A 0x4df83f. + var draft = new BattleParticipant { ActorId = actorId }; + BattleParticipant prepared = BattleLoadoutRules.Prepare(variant, draft); + Assert.That(BattleLoadoutRules.PlayerIdentity(variant, actorId), Is.EqualTo(identity)); + Assert.That(prepared.Equipment[0], Is.EqualTo(weapon)); + Assert.That(prepared.UsesNativeDefaultWeapon, Is.True); + Assert.That(draft.Equipment[0], Is.Zero); + Assert.That(draft.UsesNativeDefaultWeapon, Is.False); + Assert.That(prepared.MagicSword != null, Is.EqualTo(variant == "PAL3" && identity == 0)); + if (prepared.MagicSword != null) + { + Assert.That((prepared.MagicSword.AttackBonus, prepared.MagicSword.SelectedElement, prepared.MagicSword.SkillId, + prepared.MagicSword.ChargeCoefficient, prepared.MagicSword.Energy), + Is.EqualTo((35, BattleSwordPurificationElement.Wind, 2224, 10u, 0f))); + } + BattleParticipant again = BattleLoadoutRules.Prepare(variant, prepared); + Assert.That(again.Equipment, Is.EqualTo(prepared.Equipment)); + again.Equipment[0] = 1; + Assert.That(prepared.Equipment[0], Is.EqualTo(weapon)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void PreparationKeepsExplicitEquipmentAndDoesNotAssignMonsterWeapons(string variant) + { + var explicitActor = new BattleParticipant { ActorId = 101 }; + explicitActor.Equipment[0] = 123; + Assert.That(BattleLoadoutRules.Prepare(variant, explicitActor).Equipment[0], Is.EqualTo(123)); + Assert.That(BattleLoadoutRules.Prepare(variant, explicitActor).UsesNativeDefaultWeapon, Is.False); + var monster = new BattleParticipant { ActorId = 701, Side = BattleSide.Enemy }; + Assert.That(BattleLoadoutRules.Prepare(variant, monster).Equipment[0], Is.Zero); + Assert.That(BattleLoadoutRules.Prepare(variant, monster).UsesNativeDefaultWeapon, Is.False); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NativeDefaultProvenanceCannotAuthorizeAnotherWeapon(string variant) + { + BattleParticipant prepared = BattleLoadoutRules.Prepare(variant, new BattleParticipant { ActorId = 101 }); + prepared.Equipment[0]++; + var scenario = new BattleScenario { Variant = variant, Scene = "synthetic", Participants = { prepared } }; + Assert.That(scenario.Validate().Any(error => error.Contains("provenance")), Is.True); + Assert.That(BattleLoadoutRules.IsNativeDefaultWeapon(variant, prepared), Is.False); + Assert.That(BattleLoadoutRules.IsNativeDefaultWeapon("unknown", prepared), Is.False); + } + + [TestCase(104, 1)] + [TestCase(106, 2)] + [TestCase(107, 3)] + [TestCase(102, 4)] + public void DefaultSwordStatsDoNotRequireOrCreateAnotherCharactersCombatSwordState(int actorId, int identity) + { + BattleParticipant prepared = BattleLoadoutRules.Prepare("PAL3", new BattleParticipant + { + ActorId = actorId, + InstanceId = "P", + AttributeSource = BattleAttributeSource.BaseWithEquipment, + Attributes = new[] { 100, 20, 30, 40, 50, 6, 7, 8, 9, 10, 11, 12 } + }); + var definition = new BattleActorDefinition(new BattleActorData + { + InstanceId = "P", + Identity = identity, + Equipment = new[] { new BattleEquipmentDefinition(new BattleEquipmentData { Id = 6603, MagicSwordCultivation = new BattleMagicSword().Capture() }) } + }); + int[] attributes = BattleAttributeCalculator.Calculate(prepared, definition, "PAL3"); + Assert.That(attributes[3], Is.EqualTo(75)); + Assert.That(attributes[BattleMagicSwordRules.SelectedAttribute(BattleSwordPurificationElement.Wind)], + Is.EqualTo(prepared.Attributes[BattleMagicSwordRules.SelectedAttribute(BattleSwordPurificationElement.Wind)] + 1)); + Assert.That(prepared.MagicSword, Is.Null); + Assert.That(definition.MagicSword, Is.Null); + prepared.UsesNativeDefaultWeapon = false; + Assert.Throws(() => BattleAttributeCalculator.Calculate(prepared, definition, "PAL3")); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleLoadoutTests.cs.meta b/Assets/Tests/Battle/Editor/BattleLoadoutTests.cs.meta new file mode 100644 index 00000000..586153d3 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleLoadoutTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fc0f6e4cda5f4bfa822e97ec326e1402 diff --git a/Assets/Tests/Battle/Editor/BattleMagicSwordRulesTests.cs b/Assets/Tests/Battle/Editor/BattleMagicSwordRulesTests.cs new file mode 100644 index 00000000..05fc9e37 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMagicSwordRulesTests.cs @@ -0,0 +1,113 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using Battle; + using NUnit.Framework; + + public sealed class BattleMagicSwordRulesTests + { + private static BattleMagicSwordSnapshot Snapshot(float energy = 0, uint coefficient = 10, int skill = 2224, int purifications = 0) => + new(35, BattleSwordPurificationElement.Water, purifications, skill, coefficient, energy); + + [TestCase(BattleSwordPurificationElement.Water, 7)] + [TestCase(BattleSwordPurificationElement.Fire, 8)] + [TestCase(BattleSwordPurificationElement.Thunder, 10)] + [TestCase(BattleSwordPurificationElement.Wind, 9)] + [TestCase(BattleSwordPurificationElement.Earth, 11)] + [TestCase(BattleSwordPurificationElement.None, -1)] + public void EquipmentUsesSelectedPurificationElement(BattleSwordPurificationElement element, int attribute) + { + var snapshot = new BattleMagicSwordSnapshot(101, element, 0, 2224, 10, 0); + for (int index = 0; index < 12; index++) + Assert.That(BattleMagicSwordRules.EquipmentAttributeBonus(snapshot, index), Is.EqualTo(index == 3 ? 101 : index == attribute ? 1 : 0)); + } + + [TestCase(0f, 0u, 1f, 1u)] + [TestCase(190f, 20u, 200f, 20u)] + [TestCase(10f, uint.MaxValue, 200f, uint.MaxValue)] + [TestCase(199.9f, 1u, 200f, 1u)] + public void PhysicalWorkChargesAndRepairsZeroCoefficient(float energy, uint coefficient, float expected, uint effectiveCoefficient) + { + BattleMagicSwordSnapshot original = Snapshot(energy, coefficient); + BattleMagicSwordSnapshot charged = BattleMagicSwordRules.GainOnPhysicalWork(original, 0, true); + Assert.That(charged.Energy, Is.EqualTo(expected)); + Assert.That(charged.ChargeCoefficient, Is.EqualTo(effectiveCoefficient)); + Assert.That(original.Energy, Is.EqualTo(energy)); + Assert.That(original.ChargeCoefficient, Is.EqualTo(coefficient)); + } + + [TestCase(1, true, 2224)] + [TestCase(0, false, 2224)] + [TestCase(0, true, 0)] + public void InactiveSwordDoesNotChargeOrRepairCoefficient(int identity, bool equipped, int skill) + { + BattleMagicSwordSnapshot original = Snapshot(coefficient: 0, skill: skill); + Assert.That(BattleMagicSwordRules.GainOnPhysicalWork(original, identity, equipped), Is.SameAs(original)); + } + + [TestCase(199f, false)] + [TestCase(199.9f, false)] + [TestCase(199.90000915527344f, true)] + [TestCase(200f, true)] + public void ReadinessUsesStrictNativeFloatThreshold(float energy, bool expected) + { + Assert.That(BattleMagicSwordRules.IsReady(Snapshot(energy), 0, true), Is.EqualTo(expected)); + } + + [TestCase(0, -101)] + [TestCase(1, -151)] + [TestCase(2, -202)] + [TestCase(3, -252)] + [TestCase(20, -1111)] + public void ResidualSwordScalesByTotalPurificationAndTruncates(int count, int expected) + { + var snapshot = Snapshot(purifications: count); + Assert.That(BattleMagicSwordRules.SkillPower(snapshot, 2224, -101, BattleSide.Enemy, out BattleValueMode mode), Is.EqualTo(expected)); + Assert.That(mode, Is.EqualTo(BattleValueMode.Absolute)); + } + + [TestCase(2201)] + [TestCase(2218)] + [TestCase(2221)] + [TestCase(2223)] + public void OtherWeaponSkillsKeepRawPowerAndForceAllyPercentage(int id) + { + Assert.That(BattleMagicSwordRules.SkillPower(Snapshot(purifications: 20), id, 101, BattleSide.Ally, out BattleValueMode mode), Is.EqualTo(101)); + Assert.That(mode, Is.EqualTo(BattleValueMode.Percentage)); + } + + [Test] + public void StartingSkillConsumesEnergyWithoutChangingCultivation() + { + BattleMagicSwordSnapshot original = Snapshot(200, 0, 2223, 9); + BattleMagicSwordSnapshot consumed = BattleMagicSwordRules.ConsumeEnergy(original); + Assert.That(consumed.Energy, Is.Zero); + Assert.That(consumed.ChargeCoefficient, Is.Zero); + Assert.That(consumed.SkillId, Is.EqualTo(2223)); + Assert.That(consumed.PurificationCount, Is.EqualTo(9)); + Assert.That(original.Energy, Is.EqualTo(200)); + } + + [TestCase(-1f)] + [TestCase(201f)] + [TestCase(float.NaN)] + [TestCase(float.PositiveInfinity)] + public void InvalidEnergyIsRejected(float energy) + { + Assert.Throws(() => Snapshot(energy)); + } + + [TestCase(0)] + [TestCase(2200)] + [TestCase(2225)] + public void UnknownWeaponSkillIsExplicitlyUnsupported(int id) + { + Assert.Throws(() => BattleMagicSwordRules.SkillPower(Snapshot(), id, 100, BattleSide.Enemy, out _)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleMagicSwordRulesTests.cs.meta b/Assets/Tests/Battle/Editor/BattleMagicSwordRulesTests.cs.meta new file mode 100644 index 00000000..a7c026ff --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMagicSwordRulesTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f0b530ff3e49470d958a8565a8196446 diff --git a/Assets/Tests/Battle/Editor/BattleMagicSwordSessionTests.cs b/Assets/Tests/Battle/Editor/BattleMagicSwordSessionTests.cs new file mode 100644 index 00000000..95cc218a --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMagicSwordSessionTests.cs @@ -0,0 +1,357 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleMagicSwordSessionTests + { + private class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattleMagicSwordTimings + { + public BattleMagicSwordStageProfile Profile = new(438, -1, 0, 0, 5); + + public AttackTiming Attack(string source, string target) => new(0, 7, new[] { 2, 4 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 5, new[] { 0 }); + + public BattleMagicSwordStageProfile MagicSword(string actor, BattleAbilityDefinition ability) => Profile; + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "A" ? 0 : 1; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class BodyCatalog : Catalog, IBattleAbilityBodyAnimations, IBattlePhysicalTimings + { + public readonly BattlePhysicalAnimation Weapon = new("z13", 100, 10, gameBoxDuration: 1200); + + public BattlePhysicalAnimation AbilityBody(string actor, BattleAbilityDefinition ability) => Weapon; + + public int? AbilityNativeAction(string actor, BattleAbilityDefinition ability) => 40; + + public BattlePhysicalAnimation AbilityMovementBody(string actor, BattleAbilityDefinition ability, BattleMovementKind kind, bool returning) => null; + + public BattlePhysicalStageProfile Physical(string actor) => new("PAL3", actor == "A" ? 101 : 701, + actor == "A" ? 0 : -1, 1, 1, new Dictionary + { + [BattlePose.Idle] = new("z10", 100, 10) + }); + } + + private sealed class ReadyRules : IBattleRules + { + public int Speed = 1; + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => Speed; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => new(-1, false, false); + } + + private sealed class Director : IBattleEffectDirector + { + private readonly Dictionary _frames = new(); + private long _next; + public readonly List Started = new(); + public readonly List Stopped = new(); + public int RunningFrames = 4; + + public long Start(BattleEffectRequest request) + { + Started.Add(request); + _frames.Add(++_next, RunningFrames); + return _next; + } + + public bool IsRunning(long handle) => _frames.GetValueOrDefault(handle) > 0; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + foreach (long key in _frames.Keys.ToArray()) + if (unscaledSeconds > 0) + _frames[key]--; + } + + public void Stop(long handle) + { + Stopped.Add(handle); + _frames.Remove(handle); + } + } + + private static BattleParticipant Participant(string id, BattleSide side, int hp = 500) => new() + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Attributes = new[] { 500, 100, 100, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { hp, 100, 100 } + }; + + private static BattleScenario Scenario(float energy = 200, int skill = 2224) + { + var scenario = new BattleScenario { Scene = "fixture", DataFingerprint = "magic-sword", Seed = 1 }; + BattleParticipant source = Participant("A", BattleSide.Ally); + source.Equipment[0] = BattleMagicSwordRules.WeaponId; + source.MagicSword = new BattleMagicSword { Energy = energy, SkillId = skill }; + scenario.Participants.Add(source); + scenario.Participants.Add(Participant("E", BattleSide.Enemy)); + return scenario; + } + + private static BattleAbilityDefinition WeaponSkill(int id = 2224, BattleTargetRange range = BattleTargetRange.OpponentAll, int value = -100, bool revive = false) => new(new BattleAbilityData + { + Id = id, + Name = "native weapon " + id, + SkillTypeId = 4, + Range = range, + SuccessRate = 0, + ApplicableIdentities = new[] { 1, 2, 3, 4 }, + Attributes = revive ? new[] { new BattleAttributeEffect(0, BattleValueMode.Percentage, 100), new BattleAttributeEffect(2, BattleValueMode.Percentage, 100) } : + new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, value) }, + States = revive ? new[] { new BattleStatusEffect(BattleState.Death, true) } : Array.Empty() + }); + + private static BattleDefinitions Definitions(BattleScenario scenario, BattleAbilityDefinition ability, BattleState? enemyState = null) => new(scenario.Variant, scenario.DataFingerprint, + new[] { ability }, Array.Empty(), scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId == "A" ? 0 : actor.Side == BattleSide.Ally ? 1 : -1, + MagicSword = actor.MagicSword?.Capture(), + Equipment = actor.MagicSword == null ? Array.Empty() : new[] + { + new BattleEquipmentDefinition(new BattleEquipmentData { Id = BattleMagicSwordRules.WeaponId, Slot = 0 }) + }, + InitialStates = actor.InstanceId == "E" && enemyState.HasValue ? new[] { enemyState.Value } : Array.Empty() + }))); + + private static BattleSession Session(BattleScenario scenario, BattleAbilityDefinition ability, Director director = null, Catalog catalog = null, BattleState? enemyState = null) => + new(new BattleSetup(scenario), catalog ?? new Catalog(), new ReadyRules(), Definitions(scenario, ability, enemyState), director ?? new Director()); + + private static void Until(BattleSession session, Func done) + { + for (int index = 0; index < 250 && !done() && session.Status == BattleSessionStatus.Running; index++) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + Assert.That(done(), Is.True, "The expected native boundary was not reached."); + } + + [Test] + public void ReleasedDefaultsAndCapturedCopiesKeepTheActualRawWindIndex() + { + BattleScenario scenario = Scenario(); + var setup = new BattleSetup(scenario); + scenario.Participants[0].MagicSword.AttackBonus = 999; + BattleScenario first = setup.CreateInstance(); + first.Participants[0].MagicSword.Energy = 1; + BattleMagicSword captured = setup.CreateInstance().Participants[0].MagicSword; + Assert.That((captured.AttackBonus, (int)captured.SelectedElement, captured.SkillId, captured.ChargeCoefficient, captured.Energy), Is.EqualTo((35, 3, 2224, 10u, 200f))); + } + + [TestCase(-1f)] + [TestCase(201f)] + [TestCase(float.NaN)] + public void ScenarioRejectsInvalidCapturedEnergy(float energy) + { + Assert.Throws(() => new BattleSetup(Scenario(energy))); + } + + [Test] + public void ScenarioRejectsSwordWithoutCultivationAndPal3aSword() + { + BattleScenario scenario = Scenario(); + scenario.Variant = "PAL3A"; + Assert.That(scenario.Validate(), Is.Not.Empty); + scenario.Variant = "PAL3"; + scenario.Participants[0].MagicSword = null; + Assert.That(scenario.Validate(), Is.Not.Empty); + } + + [TestCase(199.9f, false)] + [TestCase(199.90000915527344f, true)] + public void WeaponCommandUsesStrictNativeEnergyAndIgnoresOrdinaryLearningAndIdentityLists(float energy, bool allowed) + { + BattleSession session = Session(Scenario(energy), WeaponSkill()); + Assert.That(session.Actors[0].Skills, Is.Empty); + Assert.That(session.CanSubmit(new BattleCommand("A", BattleAction.Skill, abilityId: 2224)) == null, Is.EqualTo(allowed)); + } + + [Test] + public void EveryPhysicalWorkChargesEvenWhenEvadeRejectsDamage() + { + BattleSession session = Session(Scenario(0), WeaponSkill(), enemyState: BattleState.Evade); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Attack, "E")), Is.True); + Until(session, () => session.Events.Count(entry => entry.Kind == BattleEventKind.Miss) >= 2); + Assert.That(session.MagicSwords["A"].Energy, Is.EqualTo(20)); + Assert.That(session.Actors.Single(actor => actor.Id == "E").Hp, Is.EqualTo(500)); + } + + [Test] + public void OriginalEffectCompletionFreezesCombatClockAndResumesBeforeDamage() + { + var director = new Director { RunningFrames = 8 }; + BattleSession session = Session(Scenario(), WeaponSkill(), director); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 2224)), Is.True); + Until(session, () => director.Started.Count > 0); + Assert.That(session.MagicSwords["A"].Energy, Is.Zero); + long combat = session.SimulationTick, wall = session.Tick; + session.Step(); + session.Step(); + Assert.That(session.Tick, Is.EqualTo(wall + 2)); + Assert.That(session.SimulationTick, Is.EqualTo(combat)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit), Is.False); + Assert.That(director.Started.Single().AbsoluteTime, Is.True); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.Hit)); + Assert.That(session.Events.Single(entry => entry.Kind == BattleEventKind.Hit).RequestedDelta, Is.EqualTo(-100)); + Until(session, () => session.SimulationTick > combat); + } + + [Test] + public void WeaponBodyUsesTheActualSharedClipAndAdvancesDuringTheAbsoluteEffect() + { + var director = new Director { RunningFrames = 8 }; + var catalog = new BodyCatalog(); + BattleSession session = Session(Scenario(), WeaponSkill(), director, catalog); + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 2224)), Is.True); + Until(session, () => director.Started.Count > 0); + BattleActorSnapshot first = session.Actors.Single(actor => actor.Id == "A"); + Assert.That(first.NativeAnimationClip, Is.EqualTo("z13")); + Assert.That(session.CurrentBodyAnimation("A"), Is.SameAs(catalog.Weapon)); + Assert.That(session.CurrentBladeSeconds("A"), Is.EqualTo(.25f)); + long combat = session.SimulationTick; + session.Step(); + BattleActorSnapshot next = session.Actors.Single(actor => actor.Id == "A"); + Assert.That(session.SimulationTick, Is.EqualTo(combat)); + Assert.That(next.NativeAnimationSeconds, Is.GreaterThan(first.NativeAnimationSeconds)); + Until(session, () => session.CurrentBladeSeconds("A") == .01f); + Assert.That(session.Tick, Is.LessThan(100), "Actual raw duration and popped Over finish the body before its deliberately overstated tick estimate."); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded)); + Assert.That(session.CurrentBodyAnimation("A").Clip, Is.EqualTo("z10")); + } + + [Test] + public void ResidualSwordUsesPurificationPowerAndBypassesOrdinaryBarrierAndTechniqueRolls() + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].MagicSword.PurificationCount = 3; + BattleSession session = Session(scenario, WeaponSkill(), enemyState: BattleState.Barrier); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 2224)), Is.True); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.Hit)); + Assert.That(session.Events.Single(entry => entry.Kind == BattleEventKind.Hit).RequestedDelta, Is.EqualTo(-250)); + Assert.That(session.MagicSwords["A"].Energy, Is.Zero); + } + + [Test] + public void AlliedWeaponPowerUsesMaxPercentageEvenWhenGdbModeIsAbsolute() + { + BattleScenario scenario = Scenario(skill: 2218); + scenario.Participants[0].Vitals[0] = 10; + BattleSession session = Session(scenario, WeaponSkill(2218, BattleTargetRange.OwnAll, 50)); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 2218)), Is.True); + Until(session, () => session.Events.Any(entry => entry.Resource == 0)); + BattleEvent recovery = session.Events.First(entry => entry.Resource == 0); + Assert.That((recovery.RequestedDelta, recovery.HpAfter), Is.EqualTo((250, 260))); + } + + [Test] + public void WeaponSkillCapturesUnselectedSlotsAndPreservesThePreviousPlayerCommandForRepeat() + { + BattleScenario scenario = Scenario(); + BattleParticipant dead = Participant("D", BattleSide.Enemy, 0); + dead.Slot = BattleSlot.Fire; + scenario.Participants.Add(dead); + var setup = new BattleSetup(scenario); + var definitions = Definitions(scenario, WeaponSkill(), BattleState.Invisible); + var director = new Director(); + var rules = new ReadyRules { Speed = BattleSession.FullGauge }; + var session = new BattleSession(setup, new Catalog(), rules, definitions, director); + session.SetAutomatic(BattleSide.Enemy, false); + void WaitForPlayer() + { + for (int step = 0; step < 250 && session.WaitingActor != "A"; step++) + { + if (session.WaitingActor == "E") + Assert.That(session.Submit("E", BattleAction.Defend), Is.True); + session.Step(); + } + Assert.That(session.WaitingActor, Is.EqualTo("A"), session.Result?.Reason); + } + + Assert.That(session.GetTargetCandidates(new BattleCommand("A", BattleAction.Attack)), Is.Empty); + Assert.That(session.Submit("A", BattleAction.Defend), Is.True); + WaitForPlayer(); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 2224)), Is.True); + WaitForPlayer(); + Assert.That(director.Started.First().Targets, Is.EqualTo(new[] { "E", "D" })); + Assert.That(session.RequestAiRepeat("A"), Is.True); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Defend)); + BattleSession replay = BattleReplay.Play(setup, new Catalog(), session.Inputs, session.Tick, rules, definitions, new Director()); + Assert.That(replay.Inputs.Last().Action, Is.EqualTo(BattleAction.Defend)); + } + + [Test] + public void Native2221AttemptsValuesBeforeDeathRemovalAndDoesNotGrantRecoveryToTheDead() + { + BattleScenario scenario = Scenario(skill: 2221); + BattleParticipant dead = Participant("D", BattleSide.Ally, 0); + dead.Slot = BattleSlot.Fire; + dead.Vitals[2] = 0; + scenario.Participants.Add(dead); + BattleSession session = Session(scenario, WeaponSkill(2221, BattleTargetRange.OwnAll, revive: true)); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 2221)), Is.True); + Until(session, () => session.Events.Any(entry => entry.Kind == BattleEventKind.StatusRemoved && entry.Target == "D")); + BattleActorSnapshot target = session.Actors.Single(actor => actor.Id == "D"); + Assert.That((target.Hp, target.Mp), Is.EqualTo((0, 0))); + Assert.That(session.Events.Any(entry => entry.Target == "D" && entry.Resource is 0 or 2 && entry.ActualDelta > 0), Is.False); + } + + [Test] + public void CancellingAnAbsoluteTimeActionRestoresTheClockAndRetainsSpentEnergy() + { + var director = new Director { RunningFrames = 100 }; + BattleSession session = Session(Scenario(), WeaponSkill(), director); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 2224)), Is.True); + Until(session, () => director.Started.Count > 0); + long before = session.SimulationTick; + Assert.That(session.CancelAction("A"), Is.True); + session.Step(); + Assert.That(session.SimulationTick, Is.GreaterThan(before)); + Assert.That(session.MagicSwords["A"].Energy, Is.Zero); + Assert.That(director.Stopped, Is.Not.Empty); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit), Is.False); + } + + [Test] + public void UnspentEnergyIsCapturedInTheResultAndReplayUsesItsOwnGauge() + { + BattleScenario scenario = Scenario(190); + var setup = new BattleSetup(scenario); + var catalog = new Catalog(); + BattleDefinitions definitions = Definitions(scenario, WeaponSkill()); + var session = new BattleSession(setup, catalog, new ReadyRules(), definitions, new Director()); + session.Submit(new BattleCommand("A", BattleAction.Attack, "E")); + Until(session, () => session.MagicSwords["A"].Energy == 200); + session.Abort(); + Assert.That(session.Result.MagicSwords["A"].Energy, Is.EqualTo(200)); + Assert.That(definitions.Actors["A"].MagicSword.Energy, Is.EqualTo(190)); + Assert.That(setup.CreateInstance().Participants[0].MagicSword.Energy, Is.EqualTo(190)); + BattleSession replay = BattleReplay.Play(setup, catalog, session.Inputs, session.Tick, new ReadyRules(), definitions); + Assert.That(replay.Result.MagicSwords["A"].Energy, Is.EqualTo(200)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleMagicSwordSessionTests.cs.meta b/Assets/Tests/Battle/Editor/BattleMagicSwordSessionTests.cs.meta new file mode 100644 index 00000000..b3fe870b --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMagicSwordSessionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f57201e37f5c475588d902931316aa7a diff --git a/Assets/Tests/Battle/Editor/BattleMechanicsTests.DefaultTarget.cs b/Assets/Tests/Battle/Editor/BattleMechanicsTests.DefaultTarget.cs new file mode 100644 index 00000000..1f2e16ee --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMechanicsTests.DefaultTarget.cs @@ -0,0 +1,118 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using Battle; + using NUnit.Framework; + + public sealed partial class BattleMechanicsTests + { + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void FriendlyDefaultPrefersACurableAilmentThenMissingMpForPureMpMedicineThenHp(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Vitals[0] = 125; + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire)); + scenario.Participants.Add(Participant("C", BattleSide.Ally, BattleSlot.Wind)); + scenario.Participants[2].Vitals[2] = scenario.Participants[3].Vitals[2] = 25; + var medicine = Item(); + medicine.Attributes = new[] { new BattleAttributeEffect(2, BattleValueMode.RecoverToMax, 0) }; + medicine.States = new[] { new BattleStatusEffect(BattleState.Seal, true), new BattleStatusEffect(BattleState.Reflection, true) }; + scenario.Items.Add(new BattleItem { Id = medicine.Id, Count = 1 }); + + string Focus() + { + BattleSession session = Session(scenario, new[] { medicine }); + return session.GetDefaultTarget(new BattleCommand("A", BattleAction.Item, abilityId: medicine.Id)); + } + + scenario.Participants[0].Statuses.Add(new BattleStatus { Id = (int)BattleState.Reflection, Rounds = 5 }); + scenario.Participants[3].Statuses.Add(new BattleStatus { Id = (int)BattleState.Seal, Rounds = 5 }); + Assert.That(Focus(), Is.EqualTo("C")); + scenario.Participants[3].Statuses.Clear(); + Assert.That(Focus(), Is.EqualTo("B"), "An exact 25/100 MP tie prefers the earlier native slot."); + scenario.Participants[2].Vitals[2] = scenario.Participants[3].Vitals[2] = 30; + Assert.That(Focus(), Is.EqualTo("C"), "The stored float for 30/100 is larger than the next x87 division."); + scenario.Participants[2].Vitals[2] = scenario.Participants[3].Vitals[2] = 100; + Assert.That(Focus(), Is.EqualTo("A"), "When everyone's MP is full the HP rule takes over."); + scenario.Participants[2].Vitals[2] = 1; + medicine.Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, 20), new BattleAttributeEffect(2, BattleValueMode.Absolute, 20) }; + scenario.Participants[3].Vitals[0] = 125; + Assert.That(Focus(), Is.EqualTo("C"), "Mixed medicine uses HP and the later native slot wins an exact tie."); + } + + [TestCase("PAL3", "Hurt")] + [TestCase("PAL3A", "Caster")] + public void EnemySinglePrefersTheNextCasterThenFallsBackToHpIfThatRoleCannotBeSelected(string variant, string hiddenFocus) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.Add(Participant("Caster", BattleSide.Enemy, BattleSlot.Fire)); + scenario.Participants.Add(Participant("Hurt", BattleSide.Enemy, BattleSlot.Wind, 20)); + Learn(scenario.Participants[0], 301); + Learn(scenario.Participants[2], 302, 1); + + string Focus() + { + BattleSession session = Session(scenario, new[] { Magic(301), Magic(302) }, bothSidesReady: true); + Assert.That(session.Submit(new BattleCommand("Caster", BattleAction.Skill, "A", 302)), Is.True); + session.Step(); + return session.GetDefaultTarget(new BattleCommand("A", BattleAction.Skill, abilityId: 301)); + } + + Assert.That(Focus(), Is.EqualTo("Caster")); + scenario.Participants[2].Statuses.Add(new BattleStatus { Id = (int)BattleState.Invisible, Rounds = 5 }); + Assert.That(Focus(), Is.EqualTo(hiddenFocus)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void EnemyDefaultUsesFirstGaugeSpeedBeforeAnyEnemyStartsCasting(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.Add(Participant("Fast", BattleSide.Enemy, BattleSlot.Fire)); + scenario.Participants[2].Attributes[5] = 20; + BattleSession session = Session(scenario, new[] { Magic() }); + Assert.That(session.GetDefaultTarget(new BattleCommand("A", BattleAction.Skill, abilityId: 301)), Is.EqualTo("Fast")); + } + + [TestCase("PAL3", null, "A")] + [TestCase("PAL3A", "E", null)] + public void DefaultTargetRespectsWholeSideInvisibilityAndFriendlyTransformation(string variant, string opponent, string friend) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Statuses.Add(new BattleStatus { Id = (int)BattleState.Invisible, Rounds = 5 }); + scenario.Pal3A.NangongStartsTransformed = variant == "PAL3A"; + BattleSession session = Session(scenario, new[] { Magic(), Magic(4401), Item() }); + Assert.That(session.GetDefaultTarget(new BattleCommand("A", BattleAction.Skill, abilityId: 301)), Is.EqualTo(opponent)); + Assert.That(session.GetDefaultTarget(new BattleCommand("A", BattleAction.Skill, abilityId: 4401)), Is.EqualTo("E")); + Assert.That(session.GetDefaultTarget(new BattleCommand("A", BattleAction.Item, abilityId: 6201)), Is.EqualTo(friend)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void EnemyDefaultsUseNativeLineOrderingAndLowestHpForAnAllEnemyAction(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.RemoveAt(1); + for (int slot = 0; slot < 6; slot++) + scenario.Participants.Add(Participant("E" + slot, BattleSide.Enemy, (BattleSlot)slot)); + scenario.Participants[1].Vitals[0] = 0; + scenario.Participants[5].Vitals[0] = 10; + string Focus(BattleTargetRange range) + { + BattleSession session = Session(scenario, new[] { Magic(range: range) }); + return session.GetDefaultTarget(new BattleCommand("A", BattleAction.Skill, abilityId: 301)); + } + + // Two front roles tie the two middle roles; the middle line wins and scans 5,10,7. + Assert.That(Focus(BattleTargetRange.OpponentRow), Is.EqualTo("E5")); + // Both later columns have two roles; the last column starts at native slot 7. + Assert.That(Focus(BattleTargetRange.OpponentColumn), Is.EqualTo("E2")); + Assert.That(Focus(BattleTargetRange.OpponentAll), Is.EqualTo("E4")); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleMechanicsTests.DefaultTarget.cs.meta b/Assets/Tests/Battle/Editor/BattleMechanicsTests.DefaultTarget.cs.meta new file mode 100644 index 00000000..4b6ae56a --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMechanicsTests.DefaultTarget.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 493c4b0e6de24390a973f7dc18c3a931 diff --git a/Assets/Tests/Battle/Editor/BattleMechanicsTests.ManualSelection.cs b/Assets/Tests/Battle/Editor/BattleMechanicsTests.ManualSelection.cs new file mode 100644 index 00000000..16fce4d9 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMechanicsTests.ManualSelection.cs @@ -0,0 +1,141 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed partial class BattleMechanicsTests + { + [TestCase("PAL3", false)] + [TestCase("PAL3A", true)] + public void ManualSelectionChecksInvisibleOpponentsByVariantAndCommandId(string variant, bool ordinaryAllowed) + { + BattleScenario scenario = Scenario(variant); + foreach (BattleParticipant actor in scenario.Participants) + actor.Statuses.Add(new BattleStatus { Id = (int)BattleState.Invisible, Rounds = 5 }); + BattleAbilityData poison = Item(6301, -20); + poison.Range = BattleTargetRange.OpponentSingle; + var medicine = Item(); + scenario.Items.Add(new BattleItem { Id = poison.Id, Count = 1 }); + scenario.Items.Add(new BattleItem { Id = medicine.Id, Count = 1 }); + Learn(scenario.Participants[0], 301); + Learn(scenario.Participants[0], 4401); + var special = new BattleAbilityData { Id = 4401, SkillTypeId = 0, Range = BattleTargetRange.OpponentSingle }; + if (variant == "PAL3") + special.States = new[] { new BattleStatusEffect(BattleState.Invisible, true) }; + else + special.Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -180) }; + BattleSession session = Session(scenario, new[] { Magic(), special, poison, medicine }); + + foreach (BattleCommand command in new[] + { + new BattleCommand("A", BattleAction.Attack, "E"), + new BattleCommand("A", BattleAction.Skill, "E", 301), + new BattleCommand("A", BattleAction.Item, "E", poison.Id) + }) + { + Assert.That(session.GetTargetCandidates(command).Any(target => target.Id == "E"), Is.EqualTo(ordinaryAllowed)); + Assert.That(session.CanSubmit(command) == null, Is.EqualTo(ordinaryAllowed)); + } + + var heal = new BattleCommand("A", BattleAction.Item, "A", medicine.Id); + Assert.That(session.GetTargetCandidates(heal).Single().Id, Is.EqualTo("A")); + Assert.That(session.CanSubmit(heal), Is.Null); + var skill4401 = new BattleCommand("A", BattleAction.Skill, "E", 4401); + Assert.That(session.GetTargetCandidates(skill4401).Single().Id, Is.EqualTo("E")); + Assert.That(session.Submit(skill4401), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "E").States.Any(state => state.State == BattleState.Invisible), Is.EqualTo(variant == "PAL3A")); + Assert.That(session.GetTargetCandidates(new BattleCommand("A", BattleAction.Attack)).Single().Id, Is.EqualTo("E")); + } + + [TestCase(BattleTargetRange.OpponentRow, BattleSlot.Wind)] + [TestCase(BattleTargetRange.OpponentColumn, BattleSlot.Thunder)] + [TestCase(BattleTargetRange.OpponentAll, BattleSlot.Fire)] + public void ManualPal3AreaSpellSkipsInvisibleMembersOfTheSelectedArea(BattleTargetRange range, BattleSlot alignedSlot) + { + BattleScenario scenario = Scenario(); + BattleParticipant hidden = Participant("Hidden", BattleSide.Enemy, alignedSlot); + hidden.Statuses.Add(new BattleStatus { Id = (int)BattleState.Invisible, Rounds = 5 }); + scenario.Participants.Add(hidden); + Learn(scenario.Participants[0], 301); + var spell = Magic(range: range); + // SP loss exposes the captured targets even though Hermit rejects HP changes. + spell.Attributes = new[] { new BattleAttributeEffect(1, BattleValueMode.Absolute, -20) }; + BattleSession session = Session(scenario, new[] { spell }); + var command = new BattleCommand("A", BattleAction.Skill, "E", 301); + Assert.That(session.GetTargetCandidates(command).Select(actor => actor.Id), Is.EqualTo(new[] { "E" })); + Assert.That(session.GetPotentialAffectedTargets(command).Select(actor => actor.Id), Is.EqualTo(new[] { "E" })); + Assert.That(session.Submit(command), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "E").Sp, Is.LessThan(100)); + Assert.That(Actor(session, "Hidden").Sp, Is.EqualTo(100)); + } + + [TestCase(false)] + [TestCase(true)] + public void ManualPal3AFriendlyItemsFollowBothTransformationFlags(bool transformed) + { + BattleSession session = FriendlyFormSession(transformed, BattleTargetRange.OwnAll, true); + string[] expected = transformed ? new[] { "A" } : new[] { "N", "A", "P" }; + var single = new BattleCommand("A", BattleAction.Item, "N", 6201); + var group = new BattleCommand("A", BattleAction.Item, abilityId: 6202); + Assert.That(session.GetTargetCandidates(single).Select(actor => actor.Id), Is.EqualTo(expected)); + Assert.That(session.CanSubmit(single) == null, Is.EqualTo(!transformed)); + Assert.That(session.CanSubmit(new BattleCommand("A", BattleAction.Item, "P", 6201)) == null, Is.EqualTo(!transformed)); + Assert.That(session.GetPotentialAffectedTargets(group).Select(actor => actor.Id), Is.EqualTo(expected)); + Assert.That(session.Submit(group), Is.True); + Steps(session, 2); + Assert.That(session.Events.Where(entry => entry.Source == "A" && entry.Resource == 0 && entry.RequestedDelta > 0) + .Select(entry => entry.Target), Is.EquivalentTo(expected)); + } + + [TestCase(BattleTargetRange.OwnSingle)] + [TestCase(BattleTargetRange.OwnAll)] + public void Pal3ARecoveryAiCanHealTransformedNangong(BattleTargetRange range) + { + BattleSession session = FriendlyFormSession(true, range, false); + session.SetAiProfile("A", 1 | 8 | 16 | 32); + Assert.That(session.Submit("N", BattleAction.Defend), Is.True); + Assert.That(session.Submit("P", BattleAction.Defend), Is.True); + session.Step(); + Assert.That(session.Inputs.Single(input => input.Kind == BattleInputKind.Command && input.Actor == "A").AbilityId, Is.EqualTo(6202)); + Steps(session, 4); + Assert.That(Actor(session, "N").Hp, Is.GreaterThan(10)); + if (range == BattleTargetRange.OwnAll) + Assert.That(session.Events.Any(entry => entry.Source == "A" && entry.Target == "P" && entry.RequestedDelta > 0), Is.True); + } + + private static BattleSession FriendlyFormSession(bool transformed, BattleTargetRange recoveryRange, bool includeSingle) + { + BattleScenario scenario = Scenario("PAL3A"); + scenario.Seed = 107; + scenario.Pal3A.NangongStartsTransformed = transformed; + scenario.Pal3A.PengxuStartsTransformed = transformed; + scenario.Participants[0].ActorId = 102; + scenario.Participants[0].Vitals[0] = 10; + scenario.Participants.Add(Participant("N", BattleSide.Ally, BattleSlot.Fire, 10)); + BattleParticipant pengxu = Participant("P", BattleSide.Ally, BattleSlot.Wind, 10); + pengxu.ActorId = 103; + scenario.Participants.Add(pengxu); + var recovery = Item(6202); + recovery.Range = recoveryRange; + scenario.Items.Add(new BattleItem { Id = recovery.Id, Count = 1 }); + if (includeSingle) + scenario.Items.Add(new BattleItem { Id = 6201, Count = 1 }); + BattleSession session = Session(scenario, new[] { Item(), recovery }, new[] + { + new BattleActorData { InstanceId = "N", Identity = 0 }, + new BattleActorData { InstanceId = "A", Identity = 1 }, + new BattleActorData { InstanceId = "P", Identity = 2 } + }); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleMechanicsTests.ManualSelection.cs.meta b/Assets/Tests/Battle/Editor/BattleMechanicsTests.ManualSelection.cs.meta new file mode 100644 index 00000000..ca1361af --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMechanicsTests.ManualSelection.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fed5e7bd56b042da8fa32fc9c237152b diff --git a/Assets/Tests/Battle/Editor/BattleMechanicsTests.cs b/Assets/Tests/Battle/Editor/BattleMechanicsTests.cs new file mode 100644 index 00000000..ec7371ac --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMechanicsTests.cs @@ -0,0 +1,1222 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + // Portable fixtures. Numeric oracles are recorded independently by executing + // the original EXEs in workspace/Analysis/Battle-Stage3, not by this session. + public sealed partial class BattleMechanicsTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings + { + public readonly Dictionary Timings = new(); + public int Sp = 0; + + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => + Timings.TryGetValue(ability.Id, out AttackTiming timing) ? timing : new AttackTiming(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => Sp; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class ReadyRules : IBattleRules + { + private readonly bool _bothSides; + private readonly BattleBasicRules _original = new(); + + public ReadyRules(bool bothSides = false) => _bothSides = bothSides; + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + _bothSides || actor.Side == BattleSide.Ally ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => _original.GaugePerStep(actor); + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => _original.Hit(source, target, guarding, random, targetAtHome, damageDivisor); + } + + private static BattleParticipant Participant(string id, BattleSide side, BattleSlot slot = BattleSlot.Water, int hp = 500) + { + return new BattleParticipant + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = slot, + Attributes = new[] { 500, 100, 100, 60, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { hp, 100, 100 } + }; + } + + private static BattleScenario Scenario(string variant = "PAL3") + { + var scenario = new BattleScenario { Variant = variant, Scene = "portable", DataFingerprint = "fixture", Encounter = BattleEncounter.AllyAmbush }; + scenario.Participants.Add(Participant("A", BattleSide.Ally)); + scenario.Participants.Add(Participant("E", BattleSide.Enemy)); + return scenario; + } + + private static BattleAbilityData Magic(int id = 301, int power = -20, BattleTargetRange range = BattleTargetRange.OpponentSingle) + { + return new BattleAbilityData + { + Id = id, + Name = "fixture magic", + IsMagic = true, + SkillTypeId = 2, + Range = range, + ApplicableIdentities = new[] { 0 }, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, power) }, + Costs = new[] { new BattleCost(2, BattleValueMode.Absolute, 10) } + }; + } + + private static BattleAbilityData Item(int id = 6201, int power = 30, bool revive = false) + { + return new BattleAbilityData + { + Id = id, + Name = "fixture medicine", + IsItem = true, + ItemType = 1, + Range = BattleTargetRange.OwnSingle, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, power) }, + States = revive ? new[] { new BattleStatusEffect(BattleState.Death, true) } : Array.Empty() + }; + } + + private static void Learn(BattleParticipant actor, int id, int level = 4, int uses = 0) => + actor.Skills.Add(new BattleSkill { Id = id, Level = level, Uses = uses, Mastered = true }); + + private static BattleSession Session(BattleScenario scenario, IEnumerable abilities, + IEnumerable actors = null, Catalog catalog = null, bool bothSidesReady = false, bool nativeGauge = false) + { + BattleAbilityDefinition[] captured = abilities.Select(data => new BattleAbilityDefinition(data)).ToArray(); + var overrides = (actors ?? Array.Empty()).ToDictionary(data => data.InstanceId); + var definitions = new BattleDefinitions(scenario.Variant, scenario.DataFingerprint, + captured.Where(ability => !ability.IsItem), captured.Where(ability => ability.IsItem), + scenario.Participants.Select(actor => new BattleActorDefinition(overrides.TryGetValue(actor.InstanceId, out BattleActorData data) + ? data : new BattleActorData { InstanceId = actor.InstanceId, Identity = actor.Side == BattleSide.Ally ? 0 : -1 }))); + return new BattleSession(new BattleSetup(scenario), catalog ?? new Catalog(), nativeGauge ? null : new ReadyRules(bothSidesReady), definitions); + } + + private static BattleActorSnapshot Actor(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + private static void Steps(BattleSession session, int count) + { + for (int index = 0; index < count; index++) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + } + + // Settlement follows the remaining native stage jobs, including numbers. + private static void Complete(BattleSession session) + { + for (int index = 0; index < 2000 && session.Status == BattleSessionStatus.Running; index++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed), session.Result?.Reason); + } + + private static void UntilReady(BattleSession session, string id) + { + for (int index = 0; index < 2000 && !Actor(session, id).Ready && session.Status == BattleSessionStatus.Running; index++) + { + if (session.WaitingActor != null && session.WaitingActor != id) + Assert.That(session.Submit(session.WaitingActor, BattleAction.Defend), Is.True); + session.Step(); + } + Assert.That(Actor(session, id).Ready, Is.True, session.Result?.Reason); + } + + private static string Trace(BattleSession session) => string.Join("\n", session.Events.Select(entry => + $"{entry.Tick}|{entry.Kind}|{entry.Source}|{entry.Target}|{entry.ActionId}|{entry.AbilityId}|{entry.Resource}|{entry.ValueBefore}|{entry.ValueAfter}|{entry.RequestedDelta}|{entry.ActualDelta}|{entry.RandomState}|{entry.Detail}")); + + [TestCase("PAL3", 48)] + [TestCase("PAL3A", 48)] + [TestCase("PAL3", 99)] + [TestCase("PAL3A", 99)] + public void InitialMagicCastClampsFullWidthSpeedBeforeStoringTheGaugeByte(string variant, int speed) + { + BattleScenario scenario = Scenario(variant); + BattleParticipant caster = scenario.Participants[0]; + caster.Attributes[5] = speed; + Learn(caster, 301, level: 1); + BattleSession session = Session(scenario, new[] { Magic() }, nativeGauge: true); + + UntilReady(session, "A"); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)), Is.True); + Steps(session, 1); + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(255)); + } + + [TestCase("PAL3", 3357800067u)] + [TestCase("PAL3A", 3357800067u)] + public void ManualGroupMagicSkipsEnemiesDefeatedBeforeSubmission(string variant, uint expectedState) + { + BattleScenario scenario = Scenario(variant); + scenario.Seed = 1; + scenario.Participants[1].Vitals[0] = 0; + scenario.Participants.Add(Participant("E1", BattleSide.Enemy, BattleSlot.Fire)); + Learn(scenario.Participants[0], 301); + BattleSession session = Session(scenario, new[] { Magic(range: BattleTargetRange.OpponentAll) }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 301)), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "E").Hp, Is.Zero); + Assert.That(Actor(session, "E1").Hp, Is.LessThan(500)); + Assert.That(session.Events.Last(entry => entry.Kind == BattleEventKind.ResourceChanged && entry.Resource == 2).RandomState, + Is.EqualTo(expectedState)); + } + + [Test] + public void ManualGroupMagicKeepsAnEnemyDefeatedBetweenSubmissionAndImpact() + { + BattleScenario scenario = Scenario(); + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire)); + scenario.Participants.Add(Participant("E1", BattleSide.Enemy, BattleSlot.Fire, 1)); + Learn(scenario.Participants[0], 301); + Learn(scenario.Participants[2], 302); + var catalog = new Catalog(); + catalog.Timings[301] = new AttackTiming(0, 5, new[] { 1 }); + BattleSession session = Session(scenario, new[] { Magic(301), Magic(302, range: BattleTargetRange.OpponentAll) }, catalog: catalog); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E1", 301)), Is.True); + Assert.That(session.Submit(new BattleCommand("B", BattleAction.Skill, abilityId: 302)), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "E1").Alive, Is.False); + BattleEvent hit = session.Events.Single(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "B" && entry.Target == "E"); + BattleEvent cost = session.Events.Single(entry => entry.Kind == BattleEventKind.ResourceChanged && entry.Source == "B" && entry.Resource == 2); + // MagicPower consumes two random draws for the captured, now defeated, higher slot. + var expected = new BattleRandom(unchecked((int)hit.RandomState)); + expected.Next(); + expected.Next(); + Assert.That(cost.RandomState, Is.EqualTo(expected.State)); + } + + [TestCase("PAL3", 1)] + [TestCase("PAL3", 2)] + [TestCase("PAL3A", 1)] + [TestCase("PAL3A", 2)] + public void ClampedResourceReturnControlsCastingInterruption(string variant, int resource) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Vitals[resource] = 0; + Learn(scenario.Participants[0], 4100); + Learn(scenario.Participants[1], 301, 1); + var drain = new BattleAbilityData + { + Id = 4100, + Range = BattleTargetRange.OpponentSingle, + Attributes = new[] { new BattleAttributeEffect(resource, BattleValueMode.Absolute, -10) } + }; + BattleAbilityData waiting = Magic(); + waiting.Costs = Array.Empty(); + BattleSession session = Session(scenario, new[] { drain, waiting }, bothSidesReady: true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4100)), Is.True); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 301)), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "E").CurrentAction, variant == "PAL3A" && resource == 2 + ? Is.EqualTo(BattleAction.Skill) : Is.Null); + BattleEvent change = session.Events.Single(entry => entry.Kind == BattleEventKind.ResourceChanged && entry.Target == "E" && entry.Resource == resource); + Assert.That((change.RequestedDelta, change.ActualDelta), Is.EqualTo((-10, 0))); + } + + [TestCase(BattleAttributeSource.BaseWithEquipment, 150)] + [TestCase(BattleAttributeSource.LevelGrowth, 500)] + public void InitialVitalsAreValidatedAgainstDerivedMaxima(BattleAttributeSource source, int maximum) + { + BattleScenario scenario = Scenario(); + BattleParticipant initial = scenario.Participants[0]; + initial.AttributeSource = source; + initial.Attributes[0] = 100; + initial.Vitals[0] = maximum; + var definition = new BattleActorData + { + InstanceId = "A", + AttributesByLevel = new[] { Array.Empty(), new[] { 450, 100, 100, 60, 10, 3, 0, 0, 0, 0, 0, 0 } }, + Equipment = new[] { new BattleEquipmentDefinition(new BattleEquipmentData + { + Id = 80001, Slot = 1, Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, 50) } + }) } + }; + Assert.That(scenario.Validate(), Is.Empty); + BattleSession session = Session(scenario, Array.Empty(), new[] { definition }); + Assert.That((Actor(session, "A").Hp, Actor(session, "A").MaxHp), Is.EqualTo((maximum, maximum))); + initial.Vitals[0]++; + Assert.Throws(() => Session(scenario, Array.Empty(), new[] { definition })); + } + + [TestCase(BattleAction.Attack)] + [TestCase(BattleAction.Defend)] + [TestCase(BattleAction.Flee)] + public void BasicActionsCannotSmuggleAnUnlearnedOrUnavailableAbility(BattleAction action) + { + BattleScenario scenario = Scenario(); + BattleAbilityData unavailable = Magic(); + unavailable.UnsupportedReason = "dedicated handler"; + BattleSession session = Session(scenario, new[] { unavailable }); + var command = new BattleCommand("A", action, "E", 301); + string before = Trace(session); + Assert.That(session.CanSubmit(command), Is.Not.Null); + Assert.That(session.Submit(command), Is.False); + Assert.That(session.Inputs, Is.Empty); + Assert.That(Trace(session), Is.EqualTo(before)); + Assert.That(session.GetCostEstimate(command), Is.Empty); + } + + [TestCase("PAL3", 0, -130)] + [TestCase("PAL3", 25, -162)] + [TestCase("PAL3A", 0, -150)] + [TestCase("PAL3A", 25, -188)] + public void CriticalDamageMatchesReleasedInstructions(string variant, int bonus, int expected) + { + Assert.That(new BattleEffectRules(variant).CriticalPower(-100, bonus), Is.EqualTo(expected)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void APhysicalKillGrantsSpBeforeTheFollowingStatePassMarksDeath(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Vitals = new[] { 1, 0, 100 }; + BattleSession session = Session(scenario, Array.Empty(), catalog: new Catalog { Sp = 10 }, bothSidesReady: true); + Assert.That(session.Submit("A", BattleAction.Defend), Is.True); + Assert.That(session.Submit("E", BattleAction.Attack, "A"), Is.True); + Steps(session, 2); + Assert.That((Actor(session, "A").Hp, Actor(session, "A").Sp), Is.EqualTo((0, 10))); + Assert.That(Actor(session, "A").Alive, Is.True); + Steps(session, 1); + Assert.That(Actor(session, "A").Alive, Is.False); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RawMagicCostMustBeAvailableBeforeEquipmentSavingsAndRejectionHasNoSideEffects(string variant) + { + BattleScenario scenario = Scenario(variant); + Learn(scenario.Participants[0], 301); + scenario.Participants[0].Vitals[2] = 9; + var actor = new BattleActorData + { + InstanceId = "A", + Identity = 0, + Equipment = new[] { new BattleEquipmentDefinition(new BattleEquipmentData { Id = 80001, Slot = 1, MpSaving = 50 }) } + }; + BattleSession session = Session(scenario, new[] { Magic() }, new[] { actor }); + var command = new BattleCommand("A", BattleAction.Skill, "E", 301); + BattleCostEstimate cost = session.GetCostEstimate(command).Single(); + Assert.That((cost.Required, cost.Payable, cost.Available), Is.EqualTo((10, 5, 9))); + string before = Trace(session); + Assert.That(session.CanSubmit(command), Is.Not.Null); + Assert.That(session.Submit(command), Is.False); + Assert.That(Trace(session), Is.EqualTo(before)); + Assert.That(session.Inputs, Is.Empty); + Assert.That((Actor(session, "A").Mp, Actor(session, "A").Ready), Is.EqualTo((9, true))); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.Zero); + } + + [TestCase(1, 165)] + [TestCase(2, 83)] + [TestCase(3, 55)] + public void MagicSecondSlotUses11500AndPaysOnlyAtItsWorkMarker(int proficiency, int chargeTicks) + { + BattleScenario scenario = Scenario(); + Learn(scenario.Participants[0], 301, proficiency); + BattleSession session = Session(scenario, new[] { Magic() }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)), Is.True); + Steps(session, chargeTicks - 1); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Casting)); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(100)); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.Zero); + Steps(session, 1); + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(11500)); + Assert.That(Actor(session, "A").Pose, Is.Not.EqualTo(BattlePose.Casting)); + Steps(session, 1); + Assert.That(Actor(session, "E").Hp, Is.EqualTo(500)); + Steps(session, 1); + Assert.That(Actor(session, "E").Hp, Is.LessThan(500)); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(90)); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.EqualTo(1)); + } + + [TestCase("PAL3", null)] + [TestCase("PAL3A", null)] + [TestCase("PAL3", "missing")] + [TestCase("PAL3A", "missing")] + [TestCase("PAL3", "A")] + [TestCase("PAL3A", "A")] + public void WholePartyPhysicalAttackRejectsInvalidAnchorBeforePlanningOrMutation(string variant, string target) + { + BattleSession session = Session(Scenario(variant), Array.Empty(), + new[] { new BattleActorData { InstanceId = "A", Identity = 0, NormalAttackRange = BattleTargetRange.OpponentAll } }); + var command = new BattleCommand("A", BattleAction.Attack, target); + int inputs = session.Inputs.Count; + string trace = Trace(session); + BattleActorSnapshot before = Actor(session, "A"); + Assert.That(session.CanSubmit(command), Is.Not.Null); + Assert.That(session.Submit(command), Is.False); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs)); + Assert.That(Trace(session), Is.EqualTo(trace)); + BattleActorSnapshot after = Actor(session, "A"); + Assert.That((after.Gauge, after.CastGauge, after.Ready, after.Hp, after.Sp, after.Mp), + Is.EqualTo((before.Gauge, before.CastGauge, before.Ready, before.Hp, before.Sp, before.Mp))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void WholePartyPhysicalAttackKeepsItsPlanningAnchorAndHitsEveryOpponent(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.Add(Participant("E2", BattleSide.Enemy, BattleSlot.Fire)); + BattleSession session = Session(scenario, Array.Empty(), + new[] { new BattleActorData { InstanceId = "A", Identity = 0, NormalAttackRange = BattleTargetRange.OpponentAll } }); + var command = new BattleCommand("A", BattleAction.Attack, "E"); + Assert.That(session.CanSubmit(command), Is.Null); + Assert.That(session.Submit(command), Is.True); + Assert.That(session.Inputs.Last().Target, Is.EqualTo("E")); + Steps(session, 10); + Assert.That(session.Events.Where(entry => entry.Kind == BattleEventKind.Hit).Select(entry => entry.Target), + Is.EquivalentTo(new[] { "E", "E2" })); + } + + [Test] + public void ManualInputPausesCastingButAcceptedLevelFourMagicStillReachesItsMarker() + { + BattleScenario scenario = Scenario(); + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire)); + Learn(scenario.Participants[0], 301, 1); + BattleSession session = Session(scenario, new[] { Magic() }); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + Steps(session, 20); + Assert.That(session.WaitingActor, Is.EqualTo("B")); + Assert.That(Actor(session, "A").CastGauge, Is.Zero); + Assert.That(session.Submit("B", BattleAction.Defend), Is.True); + Steps(session, 1); + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(70)); + + scenario.Participants[0].Skills[0].Level = 4; + session = Session(scenario, new[] { Magic() }); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + Steps(session, 2); + Assert.That(session.WaitingActor, Is.EqualTo("B")); + Assert.That(Actor(session, "E").Hp, Is.LessThan(500)); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(90)); + } + + [TestCase("PAL3", BattleState.Seal)] + [TestCase("PAL3", BattleState.Paralysis)] + [TestCase("PAL3", BattleState.Sleep)] + [TestCase("PAL3", BattleState.Chaos)] + [TestCase("PAL3", BattleState.Madness)] + [TestCase("PAL3A", BattleState.Seal)] + [TestCase("PAL3A", BattleState.Paralysis)] + [TestCase("PAL3A", BattleState.Sleep)] + [TestCase("PAL3A", BattleState.Chaos)] + [TestCase("PAL3A", BattleState.Madness)] + public void ControlStatusCancelsCastingWithoutLateCostOrProficiency(string variant, BattleState state) + { + BattleScenario scenario = Scenario(variant); + Learn(scenario.Participants[0], 301, 1); + Learn(scenario.Participants[1], 4100); + var interrupt = new BattleAbilityData + { + Id = 4100, + Range = BattleTargetRange.OpponentSingle, + States = new[] { new BattleStatusEffect(state, false) } + }; + BattleSession session = Session(scenario, new[] { Magic(), interrupt }, bothSidesReady: true); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 4100)), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "A").ActionId, Is.Zero); + Assert.That(Actor(session, "A").Gauge, Is.LessThan(BattleSession.FullGauge)); + Steps(session, 250); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(100)); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.Zero); + Assert.That(Actor(session, "E").Hp, Is.EqualTo(500)); + } + + [Test] + public void ControlStatusOnTheFinalCastTickOnlyInterruptsBeforeTheSpellStage( + [Values("PAL3", "PAL3A")] string variant, + [Values(BattleState.Paralysis, BattleState.Sleep, BattleState.Chaos, BattleState.Madness, BattleState.Seal)] BattleState state, + [Values(false, true)] bool afterStageStarts) + { + // A level-one caster gains 70 per step and reaches 11,500 on step 165. + const int gaugeFullTick = 165; + int statusTick = afterStageStarts ? gaugeFullTick + 1 : gaugeFullTick; + BattleScenario scenario = Scenario(variant); + Learn(scenario.Participants[0], 301, 1); + Learn(scenario.Participants[1], 4100); + var statusSkill = new BattleAbilityData + { + Id = 4100, + Range = BattleTargetRange.OpponentSingle, + States = new[] { new BattleStatusEffect(state, false) } + }; + var catalog = new Catalog(); + catalog.Timings[4100] = new AttackTiming(0, statusTick + 1, new[] { statusTick }); + BattleSession session = Session(scenario, new[] { Magic(), statusSkill }, catalog: catalog, bothSidesReady: true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)), Is.True); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 4100)), Is.True); + + Steps(session, gaugeFullTick - 1); + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(11480)); + Assert.That(session.StageTasks.Any(task => task.Owner == "A" && task.Kind == "ability"), Is.False); + Steps(session, statusTick - (gaugeFullTick - 1)); + Assert.That(Actor(session, "A").States.Any(active => active.State == state), Is.True); + Assert.That(Actor(session, "A").CurrentAction.HasValue, Is.EqualTo(afterStageStarts)); + Assert.That(session.StageTasks.Any(task => task.Owner == "A" && task.Kind == "ability"), Is.EqualTo(afterStageStarts)); + Steps(session, 10); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.EqualTo(afterStageStarts ? 1 : 0)); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(afterStageStarts ? 90 : 100)); + Assert.That(Actor(session, "E").Hp < 500, Is.EqualTo(afterStageStarts)); + } + + [TestCase("PAL3", BattleState.Paralysis)] + [TestCase("PAL3", BattleState.Sleep)] + [TestCase("PAL3A", BattleState.Paralysis)] + [TestCase("PAL3A", BattleState.Sleep)] + public void ControlStatusPreservesProgressInTheFirstGauge(string variant, BattleState state) + { + BattleScenario scenario = Scenario(variant); + Learn(scenario.Participants[0], 4100); + var technique = new BattleAbilityData + { + Id = 4100, + Range = BattleTargetRange.OpponentSingle, + States = new[] { new BattleStatusEffect(state, false) } + }; + BattleSession session = Session(scenario, new[] { technique }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4100)), Is.True); + Steps(session, 1); + int firstStep = Actor(session, "E").Gauge; + Assert.That(firstStep, Is.Positive); + Steps(session, 1); + BattleActorSnapshot target = Actor(session, "E"); + Assert.That(target.States.Any(active => active.State == state), Is.True); + Assert.That(target.Gauge, Is.EqualTo(2 * firstStep)); + } + + [Test] + public void ExplicitCancellationNeverProducesLateMagicPaymentOrHits() + { + BattleScenario scenario = Scenario(); + Learn(scenario.Participants[0], 301, 1); + BattleSession session = Session(scenario, new[] { Magic() }); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + Steps(session, 20); + Assert.That(session.CancelAction("A"), Is.True); + Assert.That(session.CancelAction("A"), Is.False); + Steps(session, 300); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(100)); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.Zero); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit), Is.False); + } + + [TestCase(false, 5750)] + [TestCase(true, 8625)] + public void PhysicalAndRankTwoMagicHitsInterruptTheSecondSlotAtDifferentFirstSlotPositions(bool magicHit, int expectedGauge) + { + BattleScenario scenario = Scenario(); + Learn(scenario.Participants[0], 301, 1); + Learn(scenario.Participants[1], 399); + BattleAbilityData incoming = Magic(399); + incoming.SpellRank = 2; + BattleSession session = Session(scenario, new[] { Magic(), incoming }, bothSidesReady: true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)), Is.True); + Assert.That(session.Submit(magicHit ? new BattleCommand("E", BattleAction.Skill, "A", 399) : + new BattleCommand("E", BattleAction.Attack, "A")), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "A").ActionId, Is.Zero); + Assert.That(Actor(session, "A").Gauge, Is.InRange(expectedGauge, expectedGauge + 35)); + Steps(session, 200); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(100)); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.Zero); + } + + [Test] + public void MagicInterruptUsesTheLastNonzeroResourceResultRatherThanTheHpLoss() + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].Vitals[2] = 50; + Learn(scenario.Participants[0], 301, 1); + Learn(scenario.Participants[1], 399); + BattleAbilityData incoming = Magic(399); + incoming.Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -20), + new BattleAttributeEffect(2, BattleValueMode.Absolute, 10) }; + BattleSession session = Session(scenario, new[] { Magic(), incoming }, bothSidesReady: true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)), Is.True); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 399)), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "A").Hp, Is.LessThan(500)); + Assert.That(Actor(session, "A").Mp, Is.GreaterThan(50)); + Assert.That(Actor(session, "A").CurrentAction, Is.EqualTo(BattleAction.Skill)); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Hurt)); + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(140)); + } + + [TestCase(false, 130)] + [TestCase(true, 30)] + public void MedicineConsumesInventoryAtStartAndRevivalClearsDeathBeforeHealing(bool revive, int expectedHp) + { + BattleScenario scenario = Scenario(); + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire, revive ? 0 : 100)); + scenario.Items.Add(new BattleItem { Id = 6201, Count = 2 }); + BattleSession session = Session(scenario, new[] { Item(revive: revive) }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "B", 6201)), Is.True); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(2)); + Assert.That(Actor(session, "B").Hp, Is.EqualTo(revive ? 0 : 100)); + Steps(session, 2); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(1)); + Assert.That(Actor(session, "B").Hp, Is.EqualTo(expectedHp)); + if (revive) + Assert.That(Actor(session, "B").Gauge, Is.GreaterThanOrEqualTo(11500 * 2 / 3)); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.ItemChanged), Is.EqualTo(1)); + Assert.That(scenario.Items.Single().Count, Is.EqualTo(2)); + Assert.That(scenario.Participants.Single(actor => actor.InstanceId == "B").Vitals[0], Is.EqualTo(revive ? 0 : 100)); + } + + [Test] + public void CancelledMedicineHasOneStartConsumptionAndNoLateHealingOrSecondConsumption() + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].Vitals[0] = 100; + scenario.Items.Add(new BattleItem { Id = 6201, Count = 1 }); + var catalog = new Catalog(); + catalog.Timings[6201] = new AttackTiming(0, 5, new[] { 3 }); + BattleSession session = Session(scenario, new[] { Item() }, catalog: catalog); + session.Submit(new BattleCommand("A", BattleAction.Item, "A", 6201)); + Steps(session, 1); + Assert.That(session.Inventory, Is.Empty); + session.CancelAction("A"); + Steps(session, 300); + Assert.That(Actor(session, "A").Hp, Is.EqualTo(100)); + Assert.That(session.Inventory, Is.Empty); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.ItemChanged), Is.EqualTo(1)); + UntilReady(session, "A"); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "A", 6201)), Is.False); + } + + [TestCase("PAL3", 255, 255)] + [TestCase("PAL3A", 255, 256)] + [TestCase("PAL3A", 65535, 65535)] + public void BlockedMagicStillPaysAndIncrementsOnceWithOriginalCounterWidth(string variant, int initialUses, int expectedUses) + { + BattleScenario scenario = Scenario(variant); + Learn(scenario.Participants[0], 301, 4, initialUses); + BattleAbilityData magic = Magic(); + magic.States = new[] { new BattleStatusEffect(BattleState.AttackDecrease, false) }; + BattleSession session = Session(scenario, new[] { magic }, new[] { new BattleActorData + { InstanceId = "E", InitialStates = new[] { BattleState.Barrier } } }); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + Steps(session, 5); + Assert.That(Actor(session, "E").Hp, Is.EqualTo(500)); + Assert.That(Actor(session, "E").States.Select(status => status.State), Is.EqualTo(new[] { BattleState.Barrier })); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(90)); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.EqualTo(expectedUses)); + } + + [TestCase("PAL3", 126, 76)] + [TestCase("PAL3A", 109, 93)] + public void NativeAttributeStatusVectorsKeepVariantAndBankersRounding(string variant, int increased, int decreased) + { + var rules = new BattleStatusRules(variant); + Assert.That(rules.ModifyAttribute(3, 101, new[] { BattleState.AttackIncrease }), Is.EqualTo(increased)); + Assert.That(rules.ModifyAttribute(3, 101, new[] { BattleState.AttackDecrease }), Is.EqualTo(decreased)); + Assert.That(rules.ModifyAttribute(5, 10, new[] { BattleState.SpeedIncrease }), Is.EqualTo(12)); + Assert.That(rules.ModifyAttribute(5, 10, new[] { BattleState.SpeedDecrease }), Is.EqualTo(8)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NativePoisonVectorsPreserveLatentRoundsAndEarthFloatAccumulator(string variant) + { + var rules = new BattleStatusRules(variant); + BattleStatusInstance water = rules.Create(BattleState.PoisonWater, 1001); + int hp = 999; + var deltas = new List(); + for (int index = 0; index < 5; index++) + { + int delta = rules.TickRound(water, 1001, hp); + deltas.Add(delta); + hp += delta; + } + Assert.That(deltas, Is.EqualTo(new[] { -499, -250, -125, -62, -31 })); + BattleStatusInstance earth = rules.Create(BattleState.PoisonEarth, 1001); + Assert.That(Enumerable.Range(0, 8).Select(_ => rules.TickRound(earth, 1001, 999)), + Is.EqualTo(new[] { -20, -30, -45, -68, -101, -152, -228, -342 })); + BattleStatusInstance wind = rules.Create(BattleState.PoisonWind, 1001); + Assert.That(Enumerable.Range(0, 3).Select(_ => rules.TickRound(wind, 1001, 999)), Is.EqualTo(new[] { 0, 0, 0 })); + Assert.That((wind.LatentRounds, wind.RemainingRounds), Is.EqualTo((0, 5))); + Assert.That(rules.TickRound(wind, 1001, 999), Is.EqualTo(-750)); + Assert.That(wind.RemainingRounds, Is.EqualTo(4)); + } + + [Test] + public void PoisonCannotRefreshOrStackAndPoisonResistanceDoesNotImmunizeSeal() + { + var rules = new BattleStatusRules("PAL3"); + Assert.That(rules.CanAdd(BattleState.PoisonWater, new[] { BattleState.PoisonWater }, Array.Empty()), Is.Not.Null); + Assert.That(rules.CanAdd(BattleState.PoisonFire, new[] { BattleState.PoisonWater }, Array.Empty()), Is.Not.Null); + Assert.That(rules.CanAdd(BattleState.PoisonFire, new[] { BattleState.PoisonResist }, Array.Empty()), Is.Not.Null); + Assert.That(rules.CanAdd(BattleState.Seal, new[] { BattleState.PoisonResist }, Array.Empty()), Is.Null); + Assert.That(rules.ReplacedBy(BattleState.Barrier), Does.Contain(BattleState.Reflection)); + Assert.That(rules.ReplacedBy(BattleState.Barrier), Does.Contain(BattleState.Sleep)); + Assert.That(rules.ReplacedBy(BattleState.Barrier), Has.No.Member(BattleState.PoisonWater)); + Assert.That(rules.CanAdd(BattleState.Seal, new[] { BattleState.Invisible }, Array.Empty()), Is.Not.Null); + } + + [TestCase(BattleState.Evade)] + [TestCase(BattleState.Reflection)] + public void EvadeAndReflectionAffectPhysicalAttacksButDoNotBlockMagic(BattleState state) + { + BattleScenario scenario = Scenario(); + Learn(scenario.Participants[0], 301); + var enemy = new BattleActorData { InstanceId = "E", InitialStates = new[] { state } }; + BattleSession physical = Session(scenario, new[] { Magic() }, new[] { enemy }); + physical.Submit("A", BattleAction.Attack, "E"); + Steps(physical, 2); + Assert.That(Actor(physical, "E").Hp, Is.EqualTo(500)); + Assert.That(Actor(physical, "A").Hp, state == BattleState.Reflection ? Is.LessThan(500) : Is.EqualTo(500)); + + BattleSession magic = Session(scenario, new[] { Magic() }, new[] { enemy }); + magic.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + Steps(magic, 2); + Assert.That(Actor(magic, "E").Hp, Is.LessThan(500)); + Assert.That(Actor(magic, "A").Hp, Is.EqualTo(500)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ManualRevivalCanSelectLivingAndDefeatedAllies(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire, 0)); + var group = Magic(range: BattleTargetRange.OwnAll); + group.States = new[] { new BattleStatusEffect(BattleState.Death, true) }; + group.Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, 20) }; + Learn(scenario.Participants[0], 301); + BattleSession session = Session(scenario, new[] { group, Item(6201), Item(6211, revive: true) }); + var command = new BattleCommand("A", BattleAction.Skill, abilityId: 301); + Assert.That(session.GetTargetCandidates(command).Select(target => target.Id), Is.EqualTo(new[] { "A", "B" })); + Assert.That(session.GetTargetCandidates(new BattleCommand("A", BattleAction.Item, abilityId: 6201)).Select(target => target.Id), Is.EqualTo(new[] { "A" })); + Assert.That(session.GetTargetCandidates(new BattleCommand("A", BattleAction.Item, abilityId: 6211)).Select(target => target.Id), Is.EqualTo(new[] { "A", "B" })); + Assert.That(session.Submit(command), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "B").Hp, Is.Positive); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ManualAttackRespectsTheCenterUntilItFallsAndKeepsPiercingRanges(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Slot = BattleSlot.Fire; + scenario.Participants.Add(Participant("Center", BattleSide.Enemy, BattleSlot.Center)); + Learn(scenario.Participants[0], 301); + var command = new BattleCommand("A", BattleAction.Attack, "E"); + BattleSession WithRange(BattleTargetRange range) => Session(scenario, new[] { Magic() }, + new[] { new BattleActorData { InstanceId = "A", Identity = 0, NormalAttackRange = range } }); + + foreach (BattleTargetRange range in new[] { BattleTargetRange.OpponentSingle, BattleTargetRange.OpponentRow }) + { + BattleSession session = WithRange(range); + Assert.That(session.GetTargetCandidates(command).Select(actor => actor.Id), Is.EqualTo(new[] { "Center" })); + Assert.That(session.Submit(command), Is.False); + Assert.That(session.CanSubmit(new BattleCommand("A", BattleAction.Skill, "E", 301)), Is.Null); + } + foreach (BattleTargetRange range in new[] { BattleTargetRange.OpponentColumn, BattleTargetRange.OpponentAll }) + { + BattleSession session = WithRange(range); + Assert.That(session.GetPotentialAffectedTargets(command).Select(actor => actor.Id), Is.EquivalentTo(new[] { "E", "Center" })); + Assert.That(session.Submit(command), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "E").Hp, Is.LessThan(500)); + Assert.That(Actor(session, "Center").Hp, Is.LessThan(500)); + } + scenario.Participants[2].Vitals[0] = 0; + Assert.That(WithRange(BattleTargetRange.OpponentSingle).Submit(command), Is.True); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RepeatKeepsTheSelectedRowAfterItsOriginalAnchorDies(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Vitals[0] = 1; + scenario.Participants.Add(Participant("OtherRow", BattleSide.Enemy, BattleSlot.Fire, 1)); + scenario.Participants.Add(Participant("SameRow", BattleSide.Enemy, BattleSlot.Wind)); + BattleSession session = Session(scenario, Array.Empty(), + new[] { new BattleActorData { InstanceId = "A", Identity = 0, NormalAttackRange = BattleTargetRange.OpponentRow } }); + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + UntilReady(session, "A"); + Assert.That(Actor(session, "E").Alive, Is.False); + int hp = Actor(session, "SameRow").Hp; + Assert.That(session.RequestAiRepeat("A"), Is.True); + Steps(session, 2); + Assert.That(Actor(session, "SameRow").Hp, Is.LessThan(hp)); + Assert.That(Actor(session, "OtherRow").Hp, Is.EqualTo(1)); + BattleSession replay = BattleReplay.Play(new BattleSetup(scenario), new Catalog(), session.Inputs, session.Tick, + new ReadyRules(), session.Definitions); + Assert.That(Trace(replay), Is.EqualTo(Trace(session))); + } + + [TestCase(BattleTargetRange.OpponentRow, new[] { "E0", "E2", "E5" })] + [TestCase(BattleTargetRange.OpponentColumn, new[] { "E0", "E3" })] + public void RowAndColumnExpandFromTheSelectedEnemyFormationSlot(BattleTargetRange range, string[] expected) + { + BattleScenario scenario = Scenario(); + scenario.Participants.RemoveAt(1); + for (int slot = 0; slot < 6; slot++) + scenario.Participants.Add(Participant("E" + slot, BattleSide.Enemy, (BattleSlot)slot)); + Learn(scenario.Participants[0], 301); + BattleSession session = Session(scenario, new[] { Magic(range: range) }); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E0", 301)); + Steps(session, 2); + Assert.That(session.Actors.Where(actor => actor.Side == BattleSide.Enemy && actor.Hp < 500).Select(actor => actor.Id), Is.EqualTo(expected)); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.EqualTo(1)); + } + + [TestCase(BattleTargetRange.OpponentRow, new[] { "E0", "E2", "E5" })] + [TestCase(BattleTargetRange.OpponentColumn, new[] { "E0", "E3" })] + [TestCase(BattleTargetRange.OpponentAll, new[] { "E0", "E1", "E2", "E3", "E4", "E5" })] + public void PhysicalWeaponRangeUsesCapturedActorDefinition(BattleTargetRange range, string[] expected) + { + BattleScenario scenario = Scenario(); + scenario.Participants.RemoveAt(1); + for (int slot = 0; slot < 6; slot++) + scenario.Participants.Add(Participant("E" + slot, BattleSide.Enemy, (BattleSlot)slot)); + BattleSession session = Session(scenario, Array.Empty(), + new[] { new BattleActorData { InstanceId = "A", Identity = 0, NormalAttackRange = range } }); + Assert.That(session.Submit("A", BattleAction.Attack, "E0"), Is.True); + Steps(session, 2); + Assert.That(session.Actors.Where(actor => actor.Side == BattleSide.Enemy && actor.Hp < 500).Select(actor => actor.Id), Is.EqualTo(expected)); + } + + [Test] + public void SpeedStatusReplacesAnExistingCastMultiplierWhileAttackStatusDoesNot() + { + foreach (BattleState state in new[] { BattleState.AttackIncrease, BattleState.SpeedIncrease }) + { + BattleScenario scenario = Scenario(); + Learn(scenario.Participants[0], 301, 2); + Learn(scenario.Participants[1], 4100); + var boost = new BattleAbilityData + { + Id = 4100, + Range = BattleTargetRange.OpponentSingle, + States = new[] { new BattleStatusEffect(state, false) } + }; + BattleSession session = Session(scenario, new[] { Magic(), boost }, bothSidesReady: true); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 4100)); + Steps(session, 2); + int before = Actor(session, "A").CastGauge; + Steps(session, 1); + Assert.That(Actor(session, "A").CastGauge - before, Is.EqualTo(state == BattleState.SpeedIncrease ? 40 : 140)); + } + } + + [Test] + public void IdenticalMonsterResourceIdsKeepIndependentHpAndStatusInstances() + { + BattleScenario scenario = Scenario(); + scenario.Participants.Add(Participant("E2", BattleSide.Enemy, BattleSlot.Fire)); + Learn(scenario.Participants[0], 301); + BattleAbilityData magic = Magic(); + magic.States = new[] { new BattleStatusEffect(BattleState.PoisonWater, false) }; + BattleSession session = Session(scenario, new[] { magic }); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + Steps(session, 2); + Assert.That(Actor(session, "E").Hp, Is.LessThan(500)); + Assert.That(Actor(session, "E").States.Select(state => state.State), Does.Contain(BattleState.PoisonWater)); + Assert.That(Actor(session, "E2").Hp, Is.EqualTo(500)); + Assert.That(Actor(session, "E2").States, Is.Empty); + Assert.That(scenario.Participants.Where(actor => actor.Side == BattleSide.Enemy).Select(actor => actor.Vitals[0]), Is.EqualTo(new[] { 500, 500 })); + } + + [TestCase("PAL3", 98, 99)] + [TestCase("PAL3", 99, 99)] + [TestCase("PAL3", 100, 100)] + [TestCase("PAL3A", 98, 99)] + [TestCase("PAL3A", 99, 99)] + [TestCase("PAL3A", 100, 100)] + public void SettlementLootReportsOnlyItemsAddedToTheInventory(string variant, int initialCount, int expectedCount) + { + BattleScenario scenario = Scenario(variant); + scenario.Items.Add(new BattleItem { Id = 6201, Count = initialCount }); + scenario.Participants[1].Vitals[0] = 0; + BattleSession session = Session(scenario, Array.Empty(), + new[] { new BattleActorData { InstanceId = "E", LootItem = 6201, LootCount = 2 } }); + + int added = expectedCount - initialCount; + Assert.That(session.Result.Loot.Select(item => (item.Id, item.Count)), + Is.EqualTo(added > 0 ? new[] { (6201, added) } : Array.Empty<(int, int)>())); + Assert.That(session.Result.Items.Single().Count, Is.EqualTo(expectedCount)); + BattleEvent change = session.Events.Single(entry => entry.Kind == BattleEventKind.ItemChanged); + Assert.That((change.RequestedDelta, change.ActualDelta), Is.EqualTo((2, added))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void SettlementRecoveryCannotPutHpAboveTheAuthoredMaximum(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Vitals[0] = 0; + BattleParticipant ally = Participant("B", BattleSide.Ally, BattleSlot.Fire, hp: 0); + ally.Attributes[0] = 0; + scenario.Participants.Add(ally); + BattleSession session = Session(scenario, Array.Empty()); + + Assert.That(session.Result.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + BattleActorSnapshot restored = session.Result.Actors.Single(actor => actor.Id == "B"); + Assert.That(restored.Hp, Is.EqualTo(0)); + Assert.That(restored.MaxHp, Is.EqualTo(0)); + } + + [TestCase("PAL3", false, false, 202, 353, 202)] + [TestCase("PAL3A", false, false, 202, 353, 202)] + [TestCase("PAL3", true, false, 303, 454, 0)] + [TestCase("PAL3A", true, false, 303, 454, 0)] + [TestCase("PAL3", false, true, 232, 353, 202)] + [TestCase("PAL3A", false, true, 232, 353, 202)] + public void NativeResultVectorsSplitOnlyAmongSurvivorsAndAwardEverySameTickFinalKill(string variant, + bool thirdDead, bool experienceBonus, int first, int second, int third) + { + // native-data-vectors.json: EXP [101,202,303], deaths [1,2,2], killers [0,1,1]. + BattleScenario scenario = Scenario(variant); + scenario.Money = 7; + scenario.Participants.RemoveAt(1); + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire)); + scenario.Participants.Add(Participant("C", BattleSide.Ally, BattleSlot.Wind, thirdDead ? 0 : 500)); + for (int slot = 0; slot < 3; slot++) + scenario.Participants.Add(Participant("E" + slot, BattleSide.Enemy, (BattleSlot)slot, 10)); + Learn(scenario.Participants[0], 301); + Learn(scenario.Participants[1], 302); + var definitions = new List(); + for (int slot = 0; slot < 3; slot++) + definitions.Add(new BattleActorData + { + InstanceId = "E" + slot, + ExperienceReward = new[] { 101, 202, 303 }[slot], + MoneyReward = new[] { 11, 22, 33 }[slot], + LootItem = 6201, + LootCount = slot + 1 + }); + if (experienceBonus) + definitions.Add(new BattleActorData + { + InstanceId = "A", + Identity = 0, + Equipment = new[] + { new BattleEquipmentDefinition(new BattleEquipmentData { Id = 80001, Slot = 1, SpecialEffect = 21 }) } + }); + var catalog = new Catalog(); + catalog.Timings[301] = new AttackTiming(0, 5, new[] { 1 }); + BattleSession session = Session(scenario, new[] { Magic(301, -1000), Magic(302, -1000, BattleTargetRange.OpponentAll) }, definitions, catalog); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E0", 301)), Is.True); + Assert.That(session.Submit(new BattleCommand("B", BattleAction.Skill, abilityId: 302)), Is.True); + Steps(session, 2); + Complete(session); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Rewards.OrderBy(reward => reward.Actor).Select(reward => reward.ExperienceGained), Is.EqualTo(new[] { first, second, third })); + Assert.That(session.Result.MoneyAfter, Is.EqualTo(experienceBonus ? 76 : 73)); + Assert.That(session.Result.Loot.Single().Count, Is.EqualTo(6)); + Assert.That(session.Result.Items.Single().Count, Is.EqualTo(6)); + Assert.That(Actor(session, "C").Hp, Is.EqualTo(thirdDead ? 1 : 500)); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(90)); + Assert.That(Actor(session, "B").Mp, Is.EqualTo(90)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void SkillUsesAccumulateDuringBattleAndOnlySettlementAdvancesTiersAndUnlocks(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Level = 35; + Learn(scenario.Participants[0], 301, 1, 5); + Learn(scenario.Participants[0], 319, 2); + Learn(scenario.Participants[0], 399); + BattleAbilityData first = Magic(301, -1); + first.UsesBeforeLevelUp = new[] { 0, 2, 4, 6 }; + first.NextSkillId = 302; + first.NextSkillRequiredProficiency = 2; + first.LearningLevel = 4; + BattleAbilityData second = Magic(302); + second.Unlocks = new[] { new BattleSkillUnlock(326, 319, 2, 1, 35) }; + BattleSession session = Session(scenario, new[] { first, second, Magic(319), Magic(326), Magic(399, -1000) }); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + Steps(session, 170); + Assert.That(Actor(session, "A").Skills.Single(skill => skill.Id == 301).Uses, Is.EqualTo(6)); + Assert.That(Actor(session, "A").Skills.Single(skill => skill.Id == 301).Level, Is.EqualTo(1)); + Assert.That(Actor(session, "A").Skills.Any(skill => skill.Id is 302 or 326), Is.False); + UntilReady(session, "A"); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 399)); + Steps(session, 2); + Complete(session); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(Actor(session, "A").Skills.Single(skill => skill.Id == 301).Level, Is.EqualTo(4)); + Assert.That(Actor(session, "A").Skills.Single(skill => skill.Id == 301).Uses, Is.EqualTo(6)); + Assert.That(Actor(session, "A").Skills.Where(skill => skill.Id is 302 or 326).Select(skill => (skill.Level, skill.Uses, skill.Mastered)), + Is.EqualTo(new[] { (1, 0, true), (1, 0, true) })); + } + + [TestCase(34, 2, true)] + [TestCase(35, 1, true)] + [TestCase(35, 2, false)] + public void CompositeUnlockRequiresActorLevelOtherTierAndTheOtherSkillsLegalIdentity(int actorLevel, int otherTier, bool legalOther) + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].Level = actorLevel; + Learn(scenario.Participants[0], 302, 3); + Learn(scenario.Participants[0], 319, otherTier); + Learn(scenario.Participants[0], 399); + BattleAbilityData prerequisite = Magic(302); + prerequisite.Unlocks = new[] { new BattleSkillUnlock(326, 319, 2, 3, 35) }; + BattleAbilityData other = Magic(319); + other.ApplicableIdentities = new[] { legalOther ? 0 : 1 }; + BattleSession session = Session(scenario, new[] { prerequisite, other, Magic(326), Magic(399, -1000) }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 399)), Is.True); + Steps(session, 2); + Complete(session); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(Actor(session, "A").Skills.Any(skill => skill.Id == 326 && skill.Mastered), Is.False); + } + + [TestCase("PAL3", 50)] + [TestCase("PAL3A", 0)] + public void EscapeUsesTheVariantsNativeExperiencePassAndKeepsDeadEnemyLoot(string variant, int experience) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].InstanceId = "E0"; + scenario.Participants[1].Vitals[0] = 10; + scenario.Participants.Add(Participant("E1", BattleSide.Enemy, BattleSlot.Fire)); + BattleParticipant escaping = Participant("B", BattleSide.Ally, BattleSlot.Fire); + escaping.Level = 10; + escaping.Attributes[6] = 10; + scenario.Participants.Add(escaping); + Learn(scenario.Participants[0], 399); + var enemy = new BattleActorData { InstanceId = "E0", ExperienceReward = 101, MoneyReward = 11, LootItem = 6201, LootCount = 2 }; + var catalog = new Catalog(); + catalog.Timings[399] = new AttackTiming(0, 5, new[] { 1 }); + BattleSession session = Session(scenario, new[] { Magic(399, -1000) }, new[] { enemy }, catalog); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E0", 399)), Is.True); + Assert.That(session.Submit("B", BattleAction.Flee), Is.True); + Steps(session, 261); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + Assert.That(Actor(session, "B").CastGauge, Is.EqualTo(11484)); + Steps(session, 1); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + Assert.That(Actor(session, "B").CastGauge, Is.EqualTo(11500)); + Steps(session, 1); + Complete(session); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Escaped, Is.True); + Assert.That(session.Result.Winner, Is.Null); + Assert.That(session.Result.Rewards.Select(reward => reward.ExperienceGained), Is.EqualTo(new[] { experience, experience })); + Assert.That(Actor(session, "A").Skills.Single(skill => skill.Id == 399).Uses, Is.EqualTo(1)); + Assert.That(session.Result.MoneyAfter, Is.EqualTo(11)); + Assert.That(session.Result.Loot.Single().Count, Is.EqualTo(2)); + } + + [TestCase(3, 44, 262)] + [TestCase(15, 140, 83)] + [TestCase(20, 180, 64)] + [TestCase(50, 164, 71)] + public void EscapeWaitsForTheSecondSlotAndUsesByteWrappedSpeedInsteadOfASaturatedMultiplier(int speed, int castSpeed, int ticks) + { + // Published EXEs: PAL3 0x515286..529f / PAL3A 0x509853..986a + // store BYTE(20 + 8 * speed). The available C++ source's x4 differs. + BattleScenario scenario = Scenario(); + scenario.Participants[0].Level = 10; + scenario.Participants[0].Attributes[5] = speed; + scenario.Participants[0].Attributes[6] = 10; + BattleSession session = Session(scenario, Array.Empty()); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Steps(session, 1); + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(castSpeed)); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Fleeing)); + Steps(session, ticks - 2); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + Assert.That(Actor(session, "A").CastGauge, Is.LessThan(11500)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Escaped), Is.False); + Steps(session, 1); + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(11500)); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + Steps(session, 1); + Complete(session); + Assert.That(session.Result.Escaped, Is.True); + } + + [Test] + public void AnotherManualInputPausesTheEscapeSecondSlot() + { + BattleScenario scenario = Scenario(); + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire)); + BattleSession session = Session(scenario, Array.Empty()); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + Steps(session, 20); + Assert.That(session.WaitingActor, Is.EqualTo("B")); + Assert.That(Actor(session, "A").CastGauge, Is.Zero); + Assert.That(session.Submit("B", BattleAction.Defend), Is.True); + Steps(session, 1); + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(44)); + } + + [TestCase(BattleState.Seal, true, false, true)] + [TestCase(BattleState.Forbidden, false, true, false)] + public void SealAndForbiddenHaveSeparateEscapeMagicAndItemAvailability(BattleState state, bool escapeAllowed, bool magicAllowed, bool itemAllowed) + { + BattleScenario scenario = Scenario(); + Learn(scenario.Participants[0], 301, 1); + scenario.Items.Add(new BattleItem { Id = 6201, Count = 1 }); + BattleSession session = Session(scenario, new[] { Magic(), Item() }, + new[] { new BattleActorData { InstanceId = "A", Identity = 0, InitialStates = new[] { state } } }); + Assert.That(session.CanSubmit(new BattleCommand("A", BattleAction.Flee)) == null, Is.EqualTo(escapeAllowed)); + Assert.That(session.CanSubmit(new BattleCommand("A", BattleAction.Skill, "E", 301)) == null, Is.EqualTo(magicAllowed)); + Assert.That(session.CanSubmit(new BattleCommand("A", BattleAction.Item, "A", 6201)) == null, Is.EqualTo(itemAllowed)); + Assert.That(session.Inputs, Is.Empty); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(1)); + } + + [TestCase(true, BattleState.Forbidden, true)] + [TestCase(true, BattleState.Seal, false)] + [TestCase(false, BattleState.Forbidden, false)] + [TestCase(false, BattleState.Seal, true)] + public void ForbiddenCancelsOnlyEscapeWaitingAndSealCancelsOnlyMagicWaiting(bool fleeing, BattleState state, bool cancelled) + { + BattleScenario scenario = Scenario(); + Learn(scenario.Participants[0], 301, 1); + Learn(scenario.Participants[1], 4100); + var interrupt = new BattleAbilityData + { + Id = 4100, + Range = BattleTargetRange.OpponentSingle, + States = new[] { new BattleStatusEffect(state, false) } + }; + BattleSession session = Session(scenario, new[] { Magic(), interrupt }, bothSidesReady: true); + Assert.That(session.Submit(fleeing ? new BattleCommand("A", BattleAction.Flee) : + new BattleCommand("A", BattleAction.Skill, "E", 301)), Is.True); + long action = Actor(session, "A").ActionId; + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 4100)), Is.True); + Steps(session, 2); + if (cancelled && fleeing) + Steps(session, 3); // Native escape waiting releases its body before the failure dialog thread ends. + Assert.That(Actor(session, "A").ActionId, Is.EqualTo(cancelled ? 0 : action)); + if (cancelled) + { + Steps(session, 200); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(100)); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.Zero); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Escaped), Is.False); + Assert.That(Actor(session, "E").Hp, Is.EqualTo(500)); + } + else + Assert.That(Actor(session, "A").CastGauge, Is.EqualTo(fleeing ? 88 : 140)); + } + + [Test] + public void DefeatDoesNotPayExperienceMoneyOrLootAndDoesNotReviveTheParty() + { + BattleScenario scenario = Scenario(); + Learn(scenario.Participants[1], 399); + var enemy = new BattleActorData { InstanceId = "E", ExperienceReward = 101, MoneyReward = 11, LootItem = 6201, LootCount = 2 }; + BattleSession session = Session(scenario, new[] { Magic(399, -10000) }, new[] { enemy }, bothSidesReady: true); + Assert.That(session.Submit("A", BattleAction.Defend), Is.True); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 399)), Is.True); + Steps(session, 2); + Complete(session); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Enemy)); + Assert.That(session.Result.Rewards, Is.Empty); + Assert.That(session.Result.Loot, Is.Empty); + Assert.That(session.Result.MoneyAfter, Is.Zero); + Assert.That(Actor(session, "A").Hp, Is.Zero); + } + + [TestCase("PAL3", 18, 1)] + [TestCase("PAL3", 19, 2)] + [TestCase("PAL3", 47, 3)] + [TestCase("PAL3A", 9, 1)] + [TestCase("PAL3A", 10, 2)] + [TestCase("PAL3A", 47, 3)] + [TestCase("PAL3", int.MaxValue, 100)] + [TestCase("PAL3A", int.MaxValue, 100)] + public void NativeCumulativeExperienceBoundariesPreservePermanentOffsetsAndFillNewVitals(string variant, int experience, int expectedLevel) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Experience = experience; + scenario.Participants[0].Vitals = new[] { 7, 8, 9 }; + Learn(scenario.Participants[0], 399); + int[] thresholds = Enumerable.Repeat(int.MaxValue, 101).ToArray(); + thresholds[1] = 0; + thresholds[2] = variant == "PAL3" ? 19 : 10; + thresholds[3] = 47; + for (int level = 4; level < 100; level++) + thresholds[level] = 100 + level; + var growth = Enumerable.Range(0, 101).Select(level => new[] { level * 8 + 80, level + 16, level * 4 + 25, level * 5 + 25, level * 4 + 16, 3, 0, 0, 0, 0, 0, 0 }).ToArray(); + var actor = new BattleActorData { InstanceId = "A", Identity = 0, ExperienceThresholds = thresholds, AttributesByLevel = growth }; + BattleAbilityData finishing = Magic(399, -1000); + finishing.Costs = Array.Empty(); + BattleSession session = Session(scenario, new[] { finishing }, new[] { actor }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 399)), Is.True); + Steps(session, 2); + Complete(session); + Assert.That(Actor(session, "A").Level, Is.EqualTo(expectedLevel)); + Assert.That(Actor(session, "A").Experience, Is.EqualTo(experience)); + if (expectedLevel > 1) + { + Assert.That(Actor(session, "A").MaxHp, Is.EqualTo(500 + (expectedLevel - 1) * 8)); + Assert.That(Actor(session, "A").Hp, Is.EqualTo(Actor(session, "A").MaxHp)); + Assert.That(Actor(session, "A").Sp, Is.EqualTo(Actor(session, "A").MaxSp)); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(Actor(session, "A").MaxMp)); + } + } + + [TestCase(30)] + [TestCase(60)] + [TestCase(144)] + public void AbilityReplayAndFrameRatePreserveCostsInventoryStatusesAndRewards(int frameRate) + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].Vitals[0] = 100; + Learn(scenario.Participants[0], 301, 1); + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire)); + scenario.Items.Add(new BattleItem { Id = 6201, Count = 2 }); + BattleSession expected = Session(scenario, new[] { Magic(301, -1000), Item() }); + expected.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + expected.Submit(new BattleCommand("B", BattleAction.Item, "A", 6201)); + Steps(expected, 167); + Complete(expected); + var setup = new BattleSetup(scenario); + BattleSession replay = BattleReplay.Play(setup, new Catalog(), expected.Inputs, expected.Tick, new ReadyRules(), expected.Definitions); + Assert.That(Trace(replay), Is.EqualTo(Trace(expected))); + BattleSession actual = Session(scenario, new[] { Magic(301, -1000), Item() }); + actual.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)); + actual.Submit(new BattleCommand("B", BattleAction.Item, "A", 6201)); + for (int index = 0; index < frameRate * 8 && actual.Status == BattleSessionStatus.Running; index++) + actual.Advance(1.0 / frameRate); + Assert.That(Trace(actual), Is.EqualTo(Trace(expected))); + Assert.That(actual.Result.Items.Single().Count, Is.EqualTo(1)); + Assert.That(actual.Result.Actors.Single(actor => actor.Id == "A").Mp, Is.EqualTo(90)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleMechanicsTests.cs.meta b/Assets/Tests/Battle/Editor/BattleMechanicsTests.cs.meta new file mode 100644 index 00000000..f926d00e --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMechanicsTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9eac30b1431549468b4be7284d444581 diff --git a/Assets/Tests/Battle/Editor/BattleModalPresentationTests.cs b/Assets/Tests/Battle/Editor/BattleModalPresentationTests.cs new file mode 100644 index 00000000..e52f2efb --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleModalPresentationTests.cs @@ -0,0 +1,214 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleModalPresentationTests + { + private sealed class Movies : IBattleEffectDirector, IBattleModalEffects, IBattlePresentationPreparation + { + internal readonly List ScaledDeltas = new(); + internal int Calls; + private readonly int _firstFrame, _lastFrame; + private bool _skipped; + + internal Movies(int firstFrame = 1, int lastFrame = 2) => + (_firstFrame, _lastFrame) = (firstFrame, lastFrame); + + public bool BlocksBattleTime + { + get; private set; + } + + public bool Busy + { + get; set; + } + + public bool IsPreparingPlayback => BlocksBattleTime && Busy; + + public bool SkipModalPresentation() + { + if (!BlocksBattleTime) + return false; + _skipped = true; + BlocksBattleTime = false; + return true; + } + + public long Start(BattleEffectRequest request) => 1; + + public bool IsRunning(long handle) => true; + + public void Stop(long handle) => BlocksBattleTime = false; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + ScaledDeltas.Add(scaledSeconds); + Calls++; + BlocksBattleTime = !_skipped && Calls >= _firstFrame && Calls <= _lastFrame; + } + } + + private sealed class EarlyGaugeRules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => 123; + + public int GaugePerStep(BattleParticipant actor) => 0; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => default; + } + + [Test] + public void RecreateRetainsInjectedSessionRules() + { + var setup = new BattleSetup(BattleSessionTests.Scenario()); + var catalog = new BattleSessionTests.Catalog(); + var original = new BattleSession(setup, catalog, new EarlyGaugeRules()); + BattleSession replay = BattleReplay.Recreate(setup, catalog, original); + Assert.That(replay.Actors.Select(actor => actor.Gauge), Is.EqualTo(new[] { 123, 123 })); + } + + private static BattleSession Session(string variant, Movies movies, out BattleSetup setup, + out BattleDefinitions definitions) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Variant = variant; + definitions = new BattleDefinitions(variant, scenario.DataFingerprint, + System.Array.Empty(), System.Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1, + NormalAttackMode = 924 + }))); + setup = new BattleSetup(scenario); + var session = new BattleSession(setup, new BattleSessionTests.Catalog(), definitions: definitions, effects: movies); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AModalMovieSuspendsTheCurrentFrameAndResumesItOnlyOnce(string variant) + { + var movies = new Movies(); + BattleSession session = Session(variant, movies, out _, out _); + session.Step(); + Assert.That(session.Tick, Is.EqualTo(1)); + Assert.That(session.SimulationTick, Is.Zero); + Assert.That(session.WaitingActor, Is.Null); + Assert.That(session.CanSubmit("Ally", BattleAction.Attack, "Enemy"), Does.Contain("movie")); + session.Step(); + Assert.That(session.SimulationTick, Is.Zero); + session.Step(); + Assert.That(session.Tick, Is.EqualTo(3)); + Assert.That(session.SimulationTick, Is.EqualTo(1)); + Assert.That(session.WaitingActor, Is.EqualTo("Ally")); + Assert.That(session.Actors[0].PoseTick, Is.EqualTo(1)); + session.Step(); + Assert.That(session.SimulationTick, Is.EqualTo(2)); + Assert.That(movies.ScaledDeltas, Is.EqualTo(new[] { 0.02f, 0f, 0f, 0.02f })); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void PreparingAMovieConsumesNoTicksAndReplayUsesTheSameTimeline(string variant) + { + var movies = new Movies { Busy = true }; + BattleSession session = Session(variant, movies, out BattleSetup setup, out _); + session.Step(); + Assert.That(session.IsPreparingPresentation, Is.True); + session.Advance(30); + session.Step(); + Assert.That(session.Tick, Is.EqualTo(1)); + Assert.That(movies.Calls, Is.EqualTo(1)); + + movies.Busy = false; + session.Advance(BattleSession.StepSeconds); + Assert.That(session.Tick, Is.EqualTo(2)); + session.Step(); + Assert.That(session.SimulationTick, Is.EqualTo(1)); + BattleSession replay = BattleReplay.Recreate(setup, new BattleSessionTests.Catalog(), session, new Movies()); + Assert.That(replay.SimulationTick, Is.EqualTo(session.SimulationTick)); + Assert.Throws(() => BattleReplay.Recreate( + setup, new BattleSessionTests.Catalog(), session, new Movies { Busy = true })); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void SkippingAMovieRecordsOnceAndReplayResumesTheSameFrame(string variant) + { + var movies = new Movies(lastFrame: 100); + BattleSession session = Session(variant, movies, out BattleSetup setup, out _); + Assert.That(session.SkipModalPresentation(), Is.False); + session.Step(); + + Assert.That(session.SkipModalPresentation(), Is.True); + Assert.That(session.SkipModalPresentation(), Is.False); + Assert.That(session.WaitingActor, Is.Null); + BattleInput skip = session.Inputs.Last(); + Assert.That(skip.Kind, Is.EqualTo(BattleInputKind.ModalPresentationSkip)); + Assert.That(skip.Tick, Is.EqualTo(1)); + + var replayMovies = new Movies(lastFrame: 100); + BattleSession pausedReplay = BattleReplay.Recreate(setup, new BattleSessionTests.Catalog(), session, replayMovies); + Assert.That(pausedReplay.WaitingActor, Is.Null); + session.Step(); + Assert.That(session.WaitingActor, Is.EqualTo("Ally")); + Assert.That(session.SimulationTick, Is.EqualTo(1)); + + BattleSession replay = BattleReplay.Recreate(setup, new BattleSessionTests.Catalog(), session, new Movies(lastFrame: 100)); + Assert.That(replay.SimulationTick, Is.EqualTo(1)); + Assert.That(replay.WaitingActor, Is.EqualTo(session.WaitingActor)); + } + + [TestCase(1, 0)] + [TestCase(3, 4)] + public void ReplayRejectsAnAbsentOrShiftedMovieEvenWithTheSameInputLog(int firstFrame, int lastFrame) + { + BattleSession session = Session("PAL3", new Movies(), out BattleSetup setup, out BattleDefinitions definitions); + for (int frame = 0; frame < 5; frame++) + session.Step(); + + BattleSession uncheckedReplay = BattleReplay.Play(setup, new BattleSessionTests.Catalog(), session.Inputs, session.Tick, + definitions: definitions, effects: new Movies(firstFrame, lastFrame)); + if (firstFrame == 3) + Assert.That(uncheckedReplay.SimulationTick, Is.EqualTo(session.SimulationTick), "Equal final clocks can hide different pauses."); + + var mismatch = Assert.Throws(() => BattleReplay.Recreate(setup, new BattleSessionTests.Catalog(), + session, new Movies(firstFrame, lastFrame))); + Assert.That(mismatch.Message, Does.Contain("battle movies")); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AReplayBindsItsEffectOwnerBeforeAdvancingTheFirstFrame(string variant) + { + var movies = new Movies(); + BattleSession session = Session(variant, movies, out BattleSetup setup, out BattleDefinitions definitions); + for (int index = 0; index < 5; index++) + session.Step(); + var replayMovies = new Movies(); + BattleSession bound = null; + BattleSession replay = BattleReplay.Play(setup, new BattleSessionTests.Catalog(), session.Inputs, session.Tick, + definitions: definitions, effects: replayMovies, onCreated: created => + { + Assert.That(replayMovies.Calls, Is.Zero); + bound = created; + }); + Assert.That(bound, Is.SameAs(replay)); + Assert.That(replay.SimulationTick, Is.EqualTo(session.SimulationTick)); + Assert.That(replayMovies.ScaledDeltas, Is.EqualTo(movies.ScaledDeltas)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleModalPresentationTests.cs.meta b/Assets/Tests/Battle/Editor/BattleModalPresentationTests.cs.meta new file mode 100644 index 00000000..5885e338 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleModalPresentationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e426ea8db34a424cacfc259b92066f69 diff --git a/Assets/Tests/Battle/Editor/BattleMovementTests.cs b/Assets/Tests/Battle/Editor/BattleMovementTests.cs new file mode 100644 index 00000000..0116018a --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMovementTests.cs @@ -0,0 +1,326 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleMovementTests + { + // Golden samples execute original stage-role x86, with explicit engine fixtures. + // workspace/Analysis/Battle-Stage4/probe-movement-native.py records those boundaries. + public static IEnumerable NativeCases() + { + yield return new TestCaseData("PAL3", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 0f), + null, null, null, 1f, -1, + "0,0,0,1,1").SetName("PAL3_Run_Native_0"); + yield return new TestCaseData("PAL3", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 1.99f), + null, null, null, 1f, -1, + "0,0,1.99000001,1,1").SetName("PAL3_Run_Native_1"); + yield return new TestCaseData("PAL3", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 2f), + null, null, null, 1f, -1, + "0,0,2,1,1").SetName("PAL3_Run_Native_2"); + yield return new TestCaseData("PAL3", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 9.6f), + null, null, null, 1f, -1, + "0,0,7.5999999,1,0|0,0,9.60000038,1,1").SetName("PAL3_Run_Native_3"); + yield return new TestCaseData("PAL3", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 1f, -1, + "0,0,7.5999999,1,0|0,0,15.1999998,1,0|0,0,22.7999992,1,0|0,0,30.3999996,1,0|0,0,38,1,0|0,0,45.5999985,1,0|0,0,53.1999969,1,0|0,0,60.7999954,1,0|0,0,68.3999939,1,0|0,0,75.9999924,1,0|0,0,83.5999908,1,0|0,0,91.1999893,1,0|0,0,100,1,1").SetName("PAL3_Run_Native_4"); + yield return new TestCaseData("PAL3", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 380f), + null, null, null, 1f, -1, + "0,0,7.5999999,1,0|0,0,15.1999998,1,0|0,0,22.7999992,1,0|0,0,30.3999996,1,0|0,0,38,1,0|0,0,45.5999985,1,0|0,0,53.1999969,1,0|0,0,60.7999954,1,0|0,0,68.3999939,1,0|0,0,75.9999924,1,0|0,0,83.5999908,1,0|0,0,91.1999893,1,0|0,0,98.7999878,1,0|0,0,106.399986,1,0|0,0,113.999985,1,0|0,0,121.599983,1,0|0,0,129.199982,1,0|0,0,136.799988,1,0|0,0,144.399994,1,0|0,0,152,1,0|0,0,159.600006,1,0|0,0,167.200012,1,0|0,0,174.800018,1,0|0,0,182.400024,1,0|0,0,190.000031,1,0|0,0,197.600037,1,0|0,0,205.200043,1,0|0,0,212.800049,1,0|0,0,220.400055,1,0|0,0,228.000061,1,0|0,0,235.600067,1,0|0,0,243.200073,1,0|0,0,250.800079,1,0|0,0,258.400085,1,0|0,0,266.000092,1,0|0,0,273.600098,1,0|0,0,281.200104,1,0|0,0,288.80011,1,0|0,0,296.400116,1,0|0,0,304.000122,1,0|0,0,311.600128,1,0|0,0,319.200134,1,0|0,0,326.80014,1,0|0,0,334.400146,1,0|0,0,342.000153,1,0|0,0,349.600159,1,0|0,0,357.200165,1,0|0,0,364.800171,1,0|0,0,372.400177,1,0|0,0,380,1,1").SetName("PAL3_Run_Native_5"); + yield return new TestCaseData("PAL3", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0.0005f, 0f, 1.99999988f), + null, null, null, 1f, -1, + "0.000500000024,0,1.99999988,1,1").SetName("PAL3_Run_Native_6"); + yield return new TestCaseData("PAL3", BattleMovementKind.Run, + new BattleMovementPoint(-17f, 12f, 42f), new BattleMovementPoint(123f, 0f, 456f), + null, null, null, 1f, -1, + "-14.5663071,11.791398,49.1967773,1,0|-12.1326141,11.5827961,56.3935547,1,0|-9.6989212,11.3741941,63.590332,1,0|-7.26522827,11.1655922,70.7871094,1,0|-4.83153534,10.9569902,77.9838867,1,0|-2.39784217,10.7483883,85.1806641,1,0|0.0358510017,10.5397863,92.3774414,1,0|2.46954417,10.3311844,99.5742188,1,0|4.90323734,10.1225824,106.770996,1,0|7.33693027,9.91398048,113.967773,1,0|9.77062321,9.70537853,121.164551,1,0|12.2043161,9.49677658,128.361328,1,0|14.6380091,9.28817463,135.558105,1,0|17.071703,9.07957268,142.754883,1,0|19.5053959,8.87097073,149.95166,1,0|21.9390888,8.66236877,157.148438,1,0|24.3727818,8.45376682,164.345215,1,0|26.8064747,8.24516487,171.541992,1,0|29.2401676,8.03656292,178.73877,1,0|31.6738605,7.82796049,185.935547,1,0|34.1075554,7.61935806,193.132324,1,0|36.5412483,7.41075563,200.329102,1,0|38.9749413,7.20215321,207.525879,1,0|41.4086342,6.99355078,214.722656,1,0|43.8423271,6.78494835,221.919434,1,0|46.2760201,6.57634592,229.116211,1,0|48.709713,6.36774349,236.312988,1,0|51.1434059,6.15914106,243.509766,1,0|53.5770988,5.95053864,250.706543,1,0|56.0107918,5.74193621,257.90332,1,0|58.4444847,5.53333378,265.100098,1,0|60.8781776,5.32473135,272.296875,1,0|63.3118706,5.11612892,279.493652,1,0|65.7455673,4.90752649,286.69043,1,0|68.1792603,4.69892406,293.887207,1,0|70.6129532,4.49032164,301.083984,1,0|73.0466461,4.28171921,308.280762,1,0|75.4803391,4.07311678,315.477539,1,0|77.914032,3.86451459,322.674316,1,0|80.3477249,3.6559124,329.871094,1,0|82.7814178,3.44731021,337.067871,1,0|85.2151108,3.23870802,344.264648,1,0|87.6488037,3.03010583,351.461426,1,0|90.0824966,2.82150364,358.658203,1,0|92.5161896,2.61290145,365.85498,1,0|94.9498825,2.40429926,373.051758,1,0|97.3835754,2.19569707,380.248535,1,0|99.8172684,1.98709476,387.445312,1,0|102.250961,1.77849245,394.64209,1,0|104.684654,1.56989014,401.838867,1,0|107.118347,1.36128783,409.035645,1,0|109.55204,1.15268552,416.232422,1,0|111.985733,0.944083214,423.429199,1,0|114.419426,0.735480905,430.625977,1,0|116.853119,0.526878595,437.822754,1,0|119.286812,0.318276316,445.019531,1,0|121.720505,0.109674037,452.216309,1,0|123,0,456,1,1").SetName("PAL3_Run_Native_7"); + yield return new TestCaseData("PAL3", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(-0.1f, 0f, 100f), + null, null, null, 1f, -1, + "-0.00759999594,0,7.59999657,1,0|-0.0151999919,0,15.1999931,1,0|-0.0227999873,0,22.7999897,1,0|-0.0303999837,0,30.3999863,1,0|-0.0379999802,0,37.9999809,1,0|-0.0455999747,0,45.5999756,1,0|-0.0531999692,0,53.1999702,1,0|-0.0607999638,0,60.7999649,1,0|-0.0683999583,0,68.3999634,1,0|-0.0759999529,0,75.9999619,1,0|-0.0835999474,0,83.5999603,1,0|-0.0911999419,0,91.1999588,1,0|-0.100000001,0,100,1,1").SetName("PAL3_Run_Native_8"); + yield return new TestCaseData("PAL3", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 1f, 0, + "0,0,7.5999999,1,1").SetName("PAL3_Run_Native_9"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 0f), + null, null, null, 1f, -1, + "0,0,0,1,1").SetName("PAL3_Teleport_Native_10"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 1.99f), + null, null, null, 1f, -1, + "0,0,1.99000001,1,1").SetName("PAL3_Teleport_Native_11"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 2f), + null, null, null, 1f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|0,0,2,-1.55717132e-07,0|0,0,2,0.0499998443,0|0,0,2,0.099999845,0|0,0,2,0.149999842,0|0,0,2,0.199999839,0|0,0,2,0.249999836,0|0,0,2,0.299999833,0|0,0,2,0.349999845,0|0,0,2,0.399999857,0|0,0,2,0.449999869,0|0,0,2,0.499999881,0|0,0,2,0.549999893,0|0,0,2,0.599999905,0|0,0,2,0.649999917,0|0,0,2,0.699999928,0|0,0,2,0.74999994,0|0,0,2,0.799999952,0|0,0,2,0.849999964,0|0,0,2,0.899999976,0|0,0,2,0.949999988,0|0,0,2,1,0|0,0,2,1,1").SetName("PAL3_Teleport_Native_12"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 9.6f), + null, null, null, 1f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|0,0,9.60000038,-1.55717132e-07,0|0,0,9.60000038,0.0499998443,0|0,0,9.60000038,0.099999845,0|0,0,9.60000038,0.149999842,0|0,0,9.60000038,0.199999839,0|0,0,9.60000038,0.249999836,0|0,0,9.60000038,0.299999833,0|0,0,9.60000038,0.349999845,0|0,0,9.60000038,0.399999857,0|0,0,9.60000038,0.449999869,0|0,0,9.60000038,0.499999881,0|0,0,9.60000038,0.549999893,0|0,0,9.60000038,0.599999905,0|0,0,9.60000038,0.649999917,0|0,0,9.60000038,0.699999928,0|0,0,9.60000038,0.74999994,0|0,0,9.60000038,0.799999952,0|0,0,9.60000038,0.849999964,0|0,0,9.60000038,0.899999976,0|0,0,9.60000038,0.949999988,0|0,0,9.60000038,1,0|0,0,9.60000038,1,1").SetName("PAL3_Teleport_Native_13"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 1f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|0,0,100,-1.55717132e-07,0|0,0,100,0.0499998443,0|0,0,100,0.099999845,0|0,0,100,0.149999842,0|0,0,100,0.199999839,0|0,0,100,0.249999836,0|0,0,100,0.299999833,0|0,0,100,0.349999845,0|0,0,100,0.399999857,0|0,0,100,0.449999869,0|0,0,100,0.499999881,0|0,0,100,0.549999893,0|0,0,100,0.599999905,0|0,0,100,0.649999917,0|0,0,100,0.699999928,0|0,0,100,0.74999994,0|0,0,100,0.799999952,0|0,0,100,0.849999964,0|0,0,100,0.899999976,0|0,0,100,0.949999988,0|0,0,100,1,0|0,0,100,1,1").SetName("PAL3_Teleport_Native_14"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 380f), + null, null, null, 1f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|0,0,380,-1.55717132e-07,0|0,0,380,0.0499998443,0|0,0,380,0.099999845,0|0,0,380,0.149999842,0|0,0,380,0.199999839,0|0,0,380,0.249999836,0|0,0,380,0.299999833,0|0,0,380,0.349999845,0|0,0,380,0.399999857,0|0,0,380,0.449999869,0|0,0,380,0.499999881,0|0,0,380,0.549999893,0|0,0,380,0.599999905,0|0,0,380,0.649999917,0|0,0,380,0.699999928,0|0,0,380,0.74999994,0|0,0,380,0.799999952,0|0,0,380,0.849999964,0|0,0,380,0.899999976,0|0,0,380,0.949999988,0|0,0,380,1,0|0,0,380,1,1").SetName("PAL3_Teleport_Native_15"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0.0005f, 0f, 1.99999988f), + null, null, null, 1f, -1, + "0.000500000024,0,1.99999988,1,1").SetName("PAL3_Teleport_Native_16"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(-17f, 12f, 42f), new BattleMovementPoint(123f, 0f, 456f), + null, null, null, 1f, -1, + "-17,12,42,0.949999988,0|-17,12,42,0.899999976,0|-17,12,42,0.849999964,0|-17,12,42,0.799999952,0|-17,12,42,0.74999994,0|-17,12,42,0.699999928,0|-17,12,42,0.649999917,0|-17,12,42,0.599999905,0|-17,12,42,0.549999893,0|-17,12,42,0.499999881,0|-17,12,42,0.449999869,0|-17,12,42,0.399999857,0|-17,12,42,0.349999845,0|-17,12,42,0.299999833,0|-17,12,42,0.249999836,0|-17,12,42,0.199999839,0|-17,12,42,0.149999842,0|-17,12,42,0.099999845,0|-17,12,42,0.0499998443,0|123,0,456,-1.55717132e-07,0|123,0,456,0.0499998443,0|123,0,456,0.099999845,0|123,0,456,0.149999842,0|123,0,456,0.199999839,0|123,0,456,0.249999836,0|123,0,456,0.299999833,0|123,0,456,0.349999845,0|123,0,456,0.399999857,0|123,0,456,0.449999869,0|123,0,456,0.499999881,0|123,0,456,0.549999893,0|123,0,456,0.599999905,0|123,0,456,0.649999917,0|123,0,456,0.699999928,0|123,0,456,0.74999994,0|123,0,456,0.799999952,0|123,0,456,0.849999964,0|123,0,456,0.899999976,0|123,0,456,0.949999988,0|123,0,456,1,0|123,0,456,1,1").SetName("PAL3_Teleport_Native_17"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(-0.1f, 0f, 100f), + null, null, null, 1f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|-0.100000001,0,100,-1.55717132e-07,0|-0.100000001,0,100,0.0499998443,0|-0.100000001,0,100,0.099999845,0|-0.100000001,0,100,0.149999842,0|-0.100000001,0,100,0.199999839,0|-0.100000001,0,100,0.249999836,0|-0.100000001,0,100,0.299999833,0|-0.100000001,0,100,0.349999845,0|-0.100000001,0,100,0.399999857,0|-0.100000001,0,100,0.449999869,0|-0.100000001,0,100,0.499999881,0|-0.100000001,0,100,0.549999893,0|-0.100000001,0,100,0.599999905,0|-0.100000001,0,100,0.649999917,0|-0.100000001,0,100,0.699999928,0|-0.100000001,0,100,0.74999994,0|-0.100000001,0,100,0.799999952,0|-0.100000001,0,100,0.849999964,0|-0.100000001,0,100,0.899999976,0|-0.100000001,0,100,0.949999988,0|-0.100000001,0,100,1,0|-0.100000001,0,100,1,1").SetName("PAL3_Teleport_Native_18"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 1f, 0, + "0,0,0,1,1").SetName("PAL3_Teleport_Native_19"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 0.44f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|0,0,100,-1.55717132e-07,0|0,0,100,0.0499998443,0|0,0,100,0.099999845,0|0,0,100,0.149999842,0|0,0,100,0.199999839,0|0,0,100,0.249999836,0|0,0,100,0.299999833,0|0,0,100,0.349999845,0|0,0,100,0.399999857,0|0,0,100,0.439999998,1").SetName("PAL3_Teleport_Native_20"); + yield return new TestCaseData("PAL3", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 1f, 5, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,1,1").SetName("PAL3_Teleport_Native_21"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 0f), + 5, 30, 35, 1f, -1, + "0,0,0,1,1").SetName("PAL3_Fly_Native_22"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 1.99f), + 5, 30, 35, 1f, -1, + "0,0,1.99000001,1,1").SetName("PAL3_Fly_Native_23"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 2f), + 5, 30, 35, 1f, -1, + "0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,2,1,1").SetName("PAL3_Fly_Native_24"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 9.6f), + 5, 30, 35, 1f, -1, + "0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0.384000003,1,0|0,0,0.768000007,1,0|0,0,1.15200007,1,0|0,0,1.53600013,1,0|0,0,1.9200002,1,0|0,0,2.30400014,1,0|0,0,2.6880002,1,0|0,0,3.07200027,1,0|0,0,3.45600033,1,0|0,0,3.84000039,1,0|0,0,4.22400045,1,0|0,0,4.60800028,1,0|0,0,4.9920001,1,0|0,0,5.37599993,1,0|0,0,5.75999975,1,0|0,0,6.14399958,1,0|0,0,6.5279994,1,0|0,0,6.91199923,1,0|0,0,7.29599905,1,0|0,0,7.67999887,1,0|0,0,7.67999887,1,0|0,0,7.67999887,1,0|0,0,7.67999887,1,0|0,0,7.67999887,1,0|0,0,7.67999887,1,0|0,0,7.67999887,1,0|0,0,7.67999887,1,0|0,0,7.67999887,1,0|0,0,7.67999887,1,0|0,0,7.67999887,1,0|0,0,9.60000038,1,1").SetName("PAL3_Fly_Native_25"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + 5, 30, 35, 1f, -1, + "0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,4,1,0|0,0,8,1,0|0,0,12,1,0|0,0,16,1,0|0,0,20,1,0|0,0,24,1,0|0,0,28,1,0|0,0,32,1,0|0,0,36,1,0|0,0,40,1,0|0,0,44,1,0|0,0,48,1,0|0,0,52,1,0|0,0,56,1,0|0,0,60,1,0|0,0,64,1,0|0,0,68,1,0|0,0,72,1,0|0,0,76,1,0|0,0,80,1,0|0,0,84,1,0|0,0,88,1,0|0,0,92,1,0|0,0,96,1,0|0,0,100,1,0|0,0,100,1,0|0,0,100,1,0|0,0,100,1,0|0,0,100,1,0|0,0,100,1,0|0,0,100,1,1").SetName("PAL3_Fly_Native_26"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 380f), + 5, 30, 35, 1f, -1, + "0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,15.1999998,1,0|0,0,30.3999996,1,0|0,0,45.5999985,1,0|0,0,60.7999992,1,0|0,0,76,1,0|0,0,91.1999969,1,0|0,0,106.399994,1,0|0,0,121.599991,1,0|0,0,136.799988,1,0|0,0,151.999985,1,0|0,0,167.199982,1,0|0,0,182.399979,1,0|0,0,197.599976,1,0|0,0,212.799973,1,0|0,0,227.999969,1,0|0,0,243.199966,1,0|0,0,258.399963,1,0|0,0,273.599976,1,0|0,0,288.799988,1,0|0,0,304,1,0|0,0,319.200012,1,0|0,0,334.400024,1,0|0,0,349.600037,1,0|0,0,364.800049,1,0|0,0,380.000061,1,0|0,0,380,1,0|0,0,380,1,0|0,0,380,1,0|0,0,380,1,0|0,0,380,1,0|0,0,380,1,1").SetName("PAL3_Fly_Native_27"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0.0005f, 0f, 1.99999988f), + 5, 30, 35, 1f, -1, + "0.000500000024,0,1.99999988,1,1").SetName("PAL3_Fly_Native_28"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(-17f, 12f, 42f), new BattleMovementPoint(123f, 0f, 456f), + 5, 30, 35, 1f, -1, + "-17,12,42,1,0|-17,12,42,1,0|-17,12,42,1,0|-17,12,42,1,0|-17,12,42,1,0|-11.3999996,11.5199995,58.5600014,1,0|-5.79999971,11.039999,75.1200027,1,0|-0.199999809,10.5599985,91.6800003,1,0|5.4000001,10.079998,108.239998,1,0|11,9.59999752,124.799995,1,0|16.6000004,9.11999702,141.360001,1,0|22.2000008,8.63999653,157.919998,1,0|27.8000011,8.15999603,174.479996,1,0|33.4000015,7.67999601,191.039993,1,0|39,7.19999599,207.599991,1,0|44.5999985,6.71999598,224.159988,1,0|50.1999969,6.23999596,240.719986,1,0|55.7999954,5.75999594,257.279999,1,0|61.3999939,5.27999592,273.839996,1,0|66.9999924,4.7999959,290.399994,1,0|72.5999908,4.31999588,306.959991,1,0|78.1999893,3.83999586,323.519989,1,0|83.7999878,3.35999584,340.079987,1,0|89.3999863,2.87999582,356.639984,1,0|94.9999847,2.3999958,373.199982,1,0|100.599983,1.91999578,389.759979,1,0|106.199982,1.43999577,406.319977,1,0|111.79998,0.959995747,422.879974,1,0|117.399979,0.479995698,439.439972,1,0|122.999977,-4.35113907e-06,455.999969,1,0|123,0,456,1,0|123,0,456,1,0|123,0,456,1,0|123,0,456,1,0|123,0,456,1,0|123,0,456,1,1").SetName("PAL3_Fly_Native_29"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(-0.1f, 0f, 100f), + 5, 30, 35, 1f, -1, + "0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|-0.00400000019,0,4.00000048,1,0|-0.00800000038,0,8.00000095,1,0|-0.0120000001,0,12.000001,1,0|-0.0160000008,0,16.0000019,1,0|-0.0200000014,0,20.0000019,1,0|-0.0240000021,0,24.0000019,1,0|-0.0280000027,0,28.0000019,1,0|-0.0320000015,0,32.0000038,1,0|-0.0360000022,0,36.0000038,1,0|-0.0400000028,0,40.0000038,1,0|-0.0440000035,0,44.0000038,1,0|-0.0480000041,0,48.0000038,1,0|-0.0520000048,0,52.0000038,1,0|-0.0560000055,0,56.0000038,1,0|-0.0600000061,0,60.0000038,1,0|-0.064000003,0,64.0000076,1,0|-0.0680000037,0,68.0000076,1,0|-0.0720000044,0,72.0000076,1,0|-0.076000005,0,76.0000076,1,0|-0.0800000057,0,80.0000076,1,0|-0.0840000063,0,84.0000076,1,0|-0.088000007,0,88.0000076,1,0|-0.0920000076,0,92.0000076,1,0|-0.0960000083,0,96.0000076,1,0|-0.100000009,0,100.000008,1,0|-0.100000001,0,100,1,0|-0.100000001,0,100,1,0|-0.100000001,0,100,1,0|-0.100000001,0,100,1,0|-0.100000001,0,100,1,0|-0.100000001,0,100,1,1").SetName("PAL3_Fly_Native_30"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + 5, 30, 35, 1f, 0, + "0,0,0,1,1").SetName("PAL3_Fly_Native_31"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + 0, 30, 10, 1f, -1, + "0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,100,1,1").SetName("PAL3_Fly_Native_32"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + 5, 30, 35, 1f, -1, + "0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,4,1,0|0,0,8,1,0|0,0,12,1,0|0,0,16,1,0|0,0,20,1,0|0,0,24,1,0|0,0,28,1,0|0,0,32,1,0|0,0,36,1,0|0,0,40,1,0|0,0,44,1,0|0,0,48,1,0|0,0,52,1,0|0,0,56,1,0|0,0,60,1,0|0,0,64,1,0|0,0,68,1,0|0,0,72,1,0|0,0,76,1,0|0,0,80,1,0|0,0,84,1,0|0,0,88,1,0|0,0,92,1,0|0,0,96,1,0|0,0,100,1,0|0,0,100,1,0|0,0,100,1,0|0,0,100,1,0|0,0,100,1,0|0,0,100,1,0|0,0,100,1,1").SetName("PAL3_Fly_Native_33"); + yield return new TestCaseData("PAL3", BattleMovementKind.Fly, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + 5, 30, 10, 1f, -1, + "0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,0,1,0|0,0,4,1,0|0,0,8,1,0|0,0,12,1,0|0,0,16,1,0|0,0,20,1,0|0,0,100,1,1").SetName("PAL3_Fly_Native_34"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 0f), + null, null, null, 1f, -1, + "0,0,0,1,1").SetName("PAL3A_Run_Native_0"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 1.99f), + null, null, null, 1f, -1, + "0,0,1.99000001,1,1").SetName("PAL3A_Run_Native_1"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 2f), + null, null, null, 1f, -1, + "0,0,2,1,1").SetName("PAL3A_Run_Native_2"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 9.6f), + null, null, null, 1f, -1, + "0,0,7.5999999,1,0|0,0,9.60000038,1,1").SetName("PAL3A_Run_Native_3"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 1f, -1, + "0,0,7.5999999,1,0|0,0,15.1999998,1,0|0,0,22.7999992,1,0|0,0,30.3999996,1,0|0,0,38,1,0|0,0,45.5999985,1,0|0,0,53.1999969,1,0|0,0,60.7999954,1,0|0,0,68.3999939,1,0|0,0,75.9999924,1,0|0,0,83.5999908,1,0|0,0,91.1999893,1,0|0,0,100,1,1").SetName("PAL3A_Run_Native_4"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 380f), + null, null, null, 1f, -1, + "0,0,7.5999999,1,0|0,0,15.1999998,1,0|0,0,22.7999992,1,0|0,0,30.3999996,1,0|0,0,38,1,0|0,0,45.5999985,1,0|0,0,53.1999969,1,0|0,0,60.7999954,1,0|0,0,68.3999939,1,0|0,0,75.9999924,1,0|0,0,83.5999908,1,0|0,0,91.1999893,1,0|0,0,98.7999878,1,0|0,0,106.399986,1,0|0,0,113.999985,1,0|0,0,121.599983,1,0|0,0,129.199982,1,0|0,0,136.799988,1,0|0,0,144.399994,1,0|0,0,152,1,0|0,0,159.600006,1,0|0,0,167.200012,1,0|0,0,174.800018,1,0|0,0,182.400024,1,0|0,0,190.000031,1,0|0,0,197.600037,1,0|0,0,205.200043,1,0|0,0,212.800049,1,0|0,0,220.400055,1,0|0,0,228.000061,1,0|0,0,235.600067,1,0|0,0,243.200073,1,0|0,0,250.800079,1,0|0,0,258.400085,1,0|0,0,266.000092,1,0|0,0,273.600098,1,0|0,0,281.200104,1,0|0,0,288.80011,1,0|0,0,296.400116,1,0|0,0,304.000122,1,0|0,0,311.600128,1,0|0,0,319.200134,1,0|0,0,326.80014,1,0|0,0,334.400146,1,0|0,0,342.000153,1,0|0,0,349.600159,1,0|0,0,357.200165,1,0|0,0,364.800171,1,0|0,0,372.400177,1,0|0,0,380,1,1").SetName("PAL3A_Run_Native_5"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0.0005f, 0f, 1.99999988f), + null, null, null, 1f, -1, + "0.000500000024,0,1.99999988,1,1").SetName("PAL3A_Run_Native_6"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Run, + new BattleMovementPoint(-17f, 12f, 42f), new BattleMovementPoint(123f, 0f, 456f), + null, null, null, 1f, -1, + "-14.5663071,11.791398,49.1967773,1,0|-12.1326141,11.5827961,56.3935547,1,0|-9.6989212,11.3741941,63.590332,1,0|-7.26522827,11.1655922,70.7871094,1,0|-4.83153534,10.9569902,77.9838867,1,0|-2.39784217,10.7483883,85.1806641,1,0|0.0358510017,10.5397863,92.3774414,1,0|2.46954417,10.3311844,99.5742188,1,0|4.90323734,10.1225824,106.770996,1,0|7.33693027,9.91398048,113.967773,1,0|9.77062321,9.70537853,121.164551,1,0|12.2043161,9.49677658,128.361328,1,0|14.6380091,9.28817463,135.558105,1,0|17.071703,9.07957268,142.754883,1,0|19.5053959,8.87097073,149.95166,1,0|21.9390888,8.66236877,157.148438,1,0|24.3727818,8.45376682,164.345215,1,0|26.8064747,8.24516487,171.541992,1,0|29.2401676,8.03656292,178.73877,1,0|31.6738605,7.82796049,185.935547,1,0|34.1075554,7.61935806,193.132324,1,0|36.5412483,7.41075563,200.329102,1,0|38.9749413,7.20215321,207.525879,1,0|41.4086342,6.99355078,214.722656,1,0|43.8423271,6.78494835,221.919434,1,0|46.2760201,6.57634592,229.116211,1,0|48.709713,6.36774349,236.312988,1,0|51.1434059,6.15914106,243.509766,1,0|53.5770988,5.95053864,250.706543,1,0|56.0107918,5.74193621,257.90332,1,0|58.4444847,5.53333378,265.100098,1,0|60.8781776,5.32473135,272.296875,1,0|63.3118706,5.11612892,279.493652,1,0|65.7455673,4.90752649,286.69043,1,0|68.1792603,4.69892406,293.887207,1,0|70.6129532,4.49032164,301.083984,1,0|73.0466461,4.28171921,308.280762,1,0|75.4803391,4.07311678,315.477539,1,0|77.914032,3.86451459,322.674316,1,0|80.3477249,3.6559124,329.871094,1,0|82.7814178,3.44731021,337.067871,1,0|85.2151108,3.23870802,344.264648,1,0|87.6488037,3.03010583,351.461426,1,0|90.0824966,2.82150364,358.658203,1,0|92.5161896,2.61290145,365.85498,1,0|94.9498825,2.40429926,373.051758,1,0|97.3835754,2.19569707,380.248535,1,0|99.8172684,1.98709476,387.445312,1,0|102.250961,1.77849245,394.64209,1,0|104.684654,1.56989014,401.838867,1,0|107.118347,1.36128783,409.035645,1,0|109.55204,1.15268552,416.232422,1,0|111.985733,0.944083214,423.429199,1,0|114.419426,0.735480905,430.625977,1,0|116.853119,0.526878595,437.822754,1,0|119.286812,0.318276316,445.019531,1,0|121.720505,0.109674037,452.216309,1,0|123,0,456,1,1").SetName("PAL3A_Run_Native_7"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(-0.1f, 0f, 100f), + null, null, null, 1f, -1, + "-0.00759999594,0,7.59999657,1,0|-0.0151999919,0,15.1999931,1,0|-0.0227999873,0,22.7999897,1,0|-0.0303999837,0,30.3999863,1,0|-0.0379999802,0,37.9999847,1,0|-0.0455999747,0,45.5999832,1,0|-0.0531999692,0,53.1999817,1,0|-0.0607999638,0,60.7999802,1,0|-0.0683999583,0,68.3999786,1,0|-0.0759999529,0,75.9999771,1,0|-0.0835999474,0,83.5999756,1,0|-0.0911999419,0,91.1999741,1,0|-0.100000001,0,100,1,1").SetName("PAL3A_Run_Native_8"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Run, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 1f, 0, + "0,0,7.5999999,1,1").SetName("PAL3A_Run_Native_9"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 0f), + null, null, null, 1f, -1, + "0,0,0,1,1").SetName("PAL3A_Teleport_Native_10"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 1.99f), + null, null, null, 1f, -1, + "0,0,1.99000001,1,1").SetName("PAL3A_Teleport_Native_11"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 2f), + null, null, null, 1f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|0,0,2,0,0|0,0,2,0.0500000007,0|0,0,2,0.100000001,0|0,0,2,0.150000006,0|0,0,2,0.200000003,0|0,0,2,0.25,0|0,0,2,0.300000012,0|0,0,2,0.350000024,0|0,0,2,0.400000036,0|0,0,2,0.450000048,0|0,0,2,0.50000006,0|0,0,2,0.550000072,0|0,0,2,0.600000083,0|0,0,2,0.650000095,0|0,0,2,0.700000107,0|0,0,2,0.750000119,0|0,0,2,0.800000131,0|0,0,2,0.850000143,0|0,0,2,0.900000155,0|0,0,2,0.950000167,0|0,0,2,1,1").SetName("PAL3A_Teleport_Native_12"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 9.6f), + null, null, null, 1f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|0,0,9.60000038,0,0|0,0,9.60000038,0.0500000007,0|0,0,9.60000038,0.100000001,0|0,0,9.60000038,0.150000006,0|0,0,9.60000038,0.200000003,0|0,0,9.60000038,0.25,0|0,0,9.60000038,0.300000012,0|0,0,9.60000038,0.350000024,0|0,0,9.60000038,0.400000036,0|0,0,9.60000038,0.450000048,0|0,0,9.60000038,0.50000006,0|0,0,9.60000038,0.550000072,0|0,0,9.60000038,0.600000083,0|0,0,9.60000038,0.650000095,0|0,0,9.60000038,0.700000107,0|0,0,9.60000038,0.750000119,0|0,0,9.60000038,0.800000131,0|0,0,9.60000038,0.850000143,0|0,0,9.60000038,0.900000155,0|0,0,9.60000038,0.950000167,0|0,0,9.60000038,1,1").SetName("PAL3A_Teleport_Native_13"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 1f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|0,0,100,0,0|0,0,100,0.0500000007,0|0,0,100,0.100000001,0|0,0,100,0.150000006,0|0,0,100,0.200000003,0|0,0,100,0.25,0|0,0,100,0.300000012,0|0,0,100,0.350000024,0|0,0,100,0.400000036,0|0,0,100,0.450000048,0|0,0,100,0.50000006,0|0,0,100,0.550000072,0|0,0,100,0.600000083,0|0,0,100,0.650000095,0|0,0,100,0.700000107,0|0,0,100,0.750000119,0|0,0,100,0.800000131,0|0,0,100,0.850000143,0|0,0,100,0.900000155,0|0,0,100,0.950000167,0|0,0,100,1,1").SetName("PAL3A_Teleport_Native_14"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 380f), + null, null, null, 1f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|0,0,380,0,0|0,0,380,0.0500000007,0|0,0,380,0.100000001,0|0,0,380,0.150000006,0|0,0,380,0.200000003,0|0,0,380,0.25,0|0,0,380,0.300000012,0|0,0,380,0.350000024,0|0,0,380,0.400000036,0|0,0,380,0.450000048,0|0,0,380,0.50000006,0|0,0,380,0.550000072,0|0,0,380,0.600000083,0|0,0,380,0.650000095,0|0,0,380,0.700000107,0|0,0,380,0.750000119,0|0,0,380,0.800000131,0|0,0,380,0.850000143,0|0,0,380,0.900000155,0|0,0,380,0.950000167,0|0,0,380,1,1").SetName("PAL3A_Teleport_Native_15"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0.0005f, 0f, 1.99999988f), + null, null, null, 1f, -1, + "0.000500000024,0,1.99999988,1,1").SetName("PAL3A_Teleport_Native_16"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(-17f, 12f, 42f), new BattleMovementPoint(123f, 0f, 456f), + null, null, null, 1f, -1, + "-17,12,42,0.949999988,0|-17,12,42,0.899999976,0|-17,12,42,0.849999964,0|-17,12,42,0.799999952,0|-17,12,42,0.74999994,0|-17,12,42,0.699999928,0|-17,12,42,0.649999917,0|-17,12,42,0.599999905,0|-17,12,42,0.549999893,0|-17,12,42,0.499999881,0|-17,12,42,0.449999869,0|-17,12,42,0.399999857,0|-17,12,42,0.349999845,0|-17,12,42,0.299999833,0|-17,12,42,0.249999836,0|-17,12,42,0.199999839,0|-17,12,42,0.149999842,0|-17,12,42,0.099999845,0|-17,12,42,0.0499998443,0|123,0,456,0,0|123,0,456,0.0500000007,0|123,0,456,0.100000001,0|123,0,456,0.150000006,0|123,0,456,0.200000003,0|123,0,456,0.25,0|123,0,456,0.300000012,0|123,0,456,0.350000024,0|123,0,456,0.400000036,0|123,0,456,0.450000048,0|123,0,456,0.50000006,0|123,0,456,0.550000072,0|123,0,456,0.600000083,0|123,0,456,0.650000095,0|123,0,456,0.700000107,0|123,0,456,0.750000119,0|123,0,456,0.800000131,0|123,0,456,0.850000143,0|123,0,456,0.900000155,0|123,0,456,0.950000167,0|123,0,456,1,1").SetName("PAL3A_Teleport_Native_17"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(-0.1f, 0f, 100f), + null, null, null, 1f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|-0.100000001,0,100,0,0|-0.100000001,0,100,0.0500000007,0|-0.100000001,0,100,0.100000001,0|-0.100000001,0,100,0.150000006,0|-0.100000001,0,100,0.200000003,0|-0.100000001,0,100,0.25,0|-0.100000001,0,100,0.300000012,0|-0.100000001,0,100,0.350000024,0|-0.100000001,0,100,0.400000036,0|-0.100000001,0,100,0.450000048,0|-0.100000001,0,100,0.50000006,0|-0.100000001,0,100,0.550000072,0|-0.100000001,0,100,0.600000083,0|-0.100000001,0,100,0.650000095,0|-0.100000001,0,100,0.700000107,0|-0.100000001,0,100,0.750000119,0|-0.100000001,0,100,0.800000131,0|-0.100000001,0,100,0.850000143,0|-0.100000001,0,100,0.900000155,0|-0.100000001,0,100,0.950000167,0|-0.100000001,0,100,1,1").SetName("PAL3A_Teleport_Native_18"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 1f, 0, + "0,0,0,1,1").SetName("PAL3A_Teleport_Native_19"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 0.44f, -1, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,0.699999928,0|0,0,0,0.649999917,0|0,0,0,0.599999905,0|0,0,0,0.549999893,0|0,0,0,0.499999881,0|0,0,0,0.449999869,0|0,0,0,0.399999857,0|0,0,0,0.349999845,0|0,0,0,0.299999833,0|0,0,0,0.249999836,0|0,0,0,0.199999839,0|0,0,0,0.149999842,0|0,0,0,0.099999845,0|0,0,0,0.0499998443,0|0,0,100,0,0|0,0,100,0.0500000007,0|0,0,100,0.100000001,0|0,0,100,0.150000006,0|0,0,100,0.200000003,0|0,0,100,0.25,0|0,0,100,0.300000012,0|0,0,100,0.350000024,0|0,0,100,0.400000036,0|0,0,100,0.439999998,1").SetName("PAL3A_Teleport_Native_20"); + yield return new TestCaseData("PAL3A", BattleMovementKind.Teleport, + new BattleMovementPoint(0f, 0f, 0f), new BattleMovementPoint(0f, 0f, 100f), + null, null, null, 1f, 5, + "0,0,0,0.949999988,0|0,0,0,0.899999976,0|0,0,0,0.849999964,0|0,0,0,0.799999952,0|0,0,0,0.74999994,0|0,0,0,1,1").SetName("PAL3A_Teleport_Native_21"); + } + + [TestCaseSource(nameof(NativeCases))] + public void MatchesOriginalEveryCall(string variant, BattleMovementKind kind, BattleMovementPoint from, + BattleMovementPoint to, int? flyUp, int? flyDown, int? over, float targetBlend, int deadAt, string expected) + { + var plan = new BattleMovementPlan(kind, from, to, flyUp, flyDown, over, targetBlend); + var movement = new BattleMovement(variant, plan); + string[] calls = expected.Split('|'); + for (int call = 0; call < calls.Length; call++) + { + movement.Step(call != deadAt); + string[] values = calls[call].Split(','); + Assert.That(movement.Position.X, Is.EqualTo(Parse(values[0])).Within(0.0002f), $"call {call}, X"); + Assert.That(movement.Position.Y, Is.EqualTo(Parse(values[1])).Within(0.0002f), $"call {call}, Y"); + Assert.That(movement.Position.Z, Is.EqualTo(Parse(values[2])).Within(0.0002f), $"call {call}, Z"); + Assert.That(movement.Blend, Is.EqualTo(Parse(values[3])), $"call {call}, blend"); + Assert.That(movement.Finished, Is.EqualTo(values[4] == "1"), $"call {call}, finished"); + Assert.That(movement.ElapsedTicks, Is.EqualTo(call + 1)); + } + int before = movement.ElapsedTicks; + if (movement.Finished) + { + movement.Step(); + Assert.That(movement.ElapsedTicks, Is.EqualTo(before)); + } + } + + [Test] + public void SnapshotDoesNotExposeTheWriter() + { + var plan = new BattleMovementPlan(BattleMovementKind.Run, new BattleMovementPoint(0f, 0f, 0f), + new BattleMovementPoint(0f, 0f, 100f)); + var movement = new BattleMovement("PAL3", plan); + BattleMovementSnapshot before = movement.Capture(); + movement.Step(); + BattleMovementSnapshot after = movement.Capture(); + Assert.That(before.Position.Z, Is.Zero); + Assert.That(before.ElapsedTicks, Is.Zero); + Assert.That(after.Position.Z, Is.EqualTo(7.6f)); + Assert.That(after.ElapsedTicks, Is.EqualTo(1)); + Assert.That(after.Plan, Is.SameAs(plan)); + Assert.That(after.ElapsedSeconds, Is.EqualTo(0.02d)); + } + + [Test] + public void ArrivalWithoutAnOverMarkerDoesNotFinishFlying() + { + var plan = new BattleMovementPlan(BattleMovementKind.Fly, new BattleMovementPoint(0f, 0f, 0f), + new BattleMovementPoint(0f, 0f, 100f), flyUpTick: 1, flyDownTick: 30); + var movement = new BattleMovement("PAL3", plan); + for (int call = 0; call < 120; call++) + movement.Step(); + Assert.That(movement.Position.Z, Is.EqualTo(100f)); + Assert.That(movement.Finished, Is.False); + movement.Step(alive: false); + Assert.That(movement.Finished, Is.True); + } + + [Test] + public void StopFreezesWithoutConsumingAnotherCall() + { + var plan = new BattleMovementPlan(BattleMovementKind.Run, new BattleMovementPoint(0f, 0f, 0f), + new BattleMovementPoint(0f, 0f, 100f)); + var movement = new BattleMovement("PAL3", plan); + movement.Step(); + BattleMovementSnapshot before = movement.Capture(); + movement.Stop(); + movement.Stop(); + movement.Step(); + Assert.That(movement.Finished, Is.True); + Assert.That(movement.Position.Z, Is.EqualTo(before.Position.Z)); + Assert.That(movement.Blend, Is.EqualTo(before.Blend)); + Assert.That(movement.ElapsedTicks, Is.EqualTo(before.ElapsedTicks)); + } + + private static float Parse(string value) => float.Parse(value, CultureInfo.InvariantCulture); + } +} diff --git a/Assets/Tests/Battle/Editor/BattleMovementTests.cs.meta b/Assets/Tests/Battle/Editor/BattleMovementTests.cs.meta new file mode 100644 index 00000000..fa1bab49 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleMovementTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 64da1d1c50f443ad95f9ca7111e22e3a diff --git a/Assets/Tests/Battle/Editor/BattleNativeArithmeticBoundaryTests.cs b/Assets/Tests/Battle/Editor/BattleNativeArithmeticBoundaryTests.cs new file mode 100644 index 00000000..42b4535e --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleNativeArithmeticBoundaryTests.cs @@ -0,0 +1,264 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using Battle; + using Newtonsoft.Json; + using NUnit.Framework; + + public sealed class BattleNativeArithmeticBoundaryTests + { + [TestCase("PAL3", int.MinValue, -30)] + [TestCase("PAL3", int.MaxValue, 27)] + [TestCase("PAL3A", int.MinValue, -30)] + [TestCase("PAL3A", int.MaxValue, 27)] + public void PublishedMagicFormulaKeepsTheLowWordOfItsTruncatingCast(string variant, int raw, int expected) + { + var caster = new BattleParticipant { Level = 20, Slot = BattleSlot.Center, Side = BattleSide.Ally }; + var target = new BattleParticipant { Level = 20, Slot = BattleSlot.Center, Side = BattleSide.Enemy }; + var random = new BattleRandom(1, variant); + Assert.That(new BattleEffectRules(variant).MagicPower(raw, caster, target, 0, random), Is.EqualTo(expected)); + Assert.That(random.State, Is.EqualTo(3357800067u)); + } + + [Test] + public void EventTextUsesAStableDecimalSeparator() + { + var previous = System.Globalization.CultureInfo.CurrentCulture; + try + { + System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("fr-FR"); + Assert.That(new BattleEvent().ToString(), Does.StartWith("0.00s")); + } + finally + { + System.Globalization.CultureInfo.CurrentCulture = previous; + } + } + + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings + { + public AttackTiming Attack(string source, string target) => new(0, 2, new[] { 1 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 2, new[] { 1 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 1; + + public int SpImpact(string actor) => 1; + + public int Priority(string actor) => actor == "Ally" ? 0 : 5; + + public int DamageDivisor(string actor) => 1; + } + + private static BattleScenario Scenario(string variant, int enemyCount = 1) + { + var scenario = new BattleScenario { Variant = variant, Scene = "native-boundary", DataFingerprint = "native-arithmetic-boundary", Encounter = BattleEncounter.AllyAmbush }; + for (int index = 0; index <= enemyCount; index++) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = index == 0 ? "Ally" : "Enemy" + index, + ActorId = index == 0 ? 101 : 701, + Side = index == 0 ? BattleSide.Ally : BattleSide.Enemy, + Slot = (BattleSlot)Math.Max(0, index - 1), + Attributes = new[] { 100, 100, 100, 10, 10, 10, 10, 0, 0, 0, 0, 0 }, + Vitals = new[] { index == 0 ? 100 : 10, 100, 100 } + }); + return scenario; + } + + private static BattleDefinitions Definitions(BattleScenario scenario, int reward = 0, int[] thresholds = null, int[][] growth = null) + { + return new BattleDefinitions(scenario.Variant, scenario.DataFingerprint, + new[] { 301, 302 }.Select(id => new BattleAbilityDefinition(new BattleAbilityData + { + Id = id, + IsMagic = true, + SkillTypeId = 2, + ElementMask = 1, + Range = BattleTargetRange.OpponentAll, + ApplicableIdentities = new[] { 0 }, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -1000) } + })), Array.Empty(), scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1, + ExperienceReward = actor.Side == BattleSide.Enemy ? reward : 0, + ExperienceThresholds = actor.Side == BattleSide.Ally ? thresholds : null, + AttributesByLevel = actor.Side == BattleSide.Ally ? growth : null + }))); + } + + [TestCase("PAL3", 256)] + [TestCase("PAL3", int.MaxValue)] + [TestCase("PAL3A", 65536)] + [TestCase("PAL3A", int.MaxValue)] + public void InitialSkillUsesOutsideThePublishedCounterCannotEnterALiveSession(string variant, int uses) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 301, Uses = uses, Mastered = true }); + Assert.That(scenario.Validate().Any(error => error.Contains("skill use", StringComparison.OrdinalIgnoreCase)), Is.True); + Assert.Throws(() => new BattleSetup(scenario)); + } + + [TestCase("PAL3", 255)] + [TestCase("PAL3A", 65535)] + public void MaximumInitialCountersRemainSaturatedAndTheirResultStatisticsAndReplayAreConsumable(string variant, int maximum) + { + BattleScenario scenario = Scenario(variant); + foreach (int id in new[] { 301, 302 }) + scenario.Participants[0].Skills.Add(new BattleSkill { Id = id, Level = 4, Uses = maximum, Mastered = true }); + var setup = new BattleSetup(scenario); + BattleDefinitions definitions = Definitions(scenario); + var catalog = new Catalog(); + var session = new BattleSession(setup, catalog, definitions: definitions); + Assert.That(session.Submit(new BattleCommand("Ally", BattleAction.Skill, abilityId: 301)), Is.True); + Complete(session); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "Ally").Skills.Select(skill => skill.Uses), Is.All.EqualTo(maximum)); + Assert.That(BattleResultStatistics.MagicUseCounts(variant, definitions, 0, session.Result.PreSettlementActors.Single(actor => actor.Id == "Ally").Skills), + Is.EqualTo(new[] { maximum * 2, 0, 0, 0, 0, 0 })); + AssertReplay(setup, catalog, definitions, session); + } + + // Executed released PAL3 0x4eef20..0x4ef20f, including its CRT _ftol. + // The caller retains EAX after int64 truncation, independently of f2i32. + [TestCase(-100, int.MaxValue, -50)] + [TestCase(-101, int.MaxValue, -1073741874)] + [TestCase(short.MinValue, int.MaxValue, -16384)] + [TestCase(short.MaxValue, int.MaxValue, -1073725441)] + [TestCase(-101, 3, -252)] + public void ResidualSwordRetainsThePublishedCrtTruncationAndLowWord(short raw, int count, int expected) + { + var snapshot = new BattleMagicSword { PurificationCount = count }.Capture(); + Assert.That(BattleMagicSwordRules.SkillPower(snapshot, 2224, raw, BattleSide.Enemy, out BattleValueMode mode), Is.EqualTo(expected)); + Assert.That(mode, Is.EqualTo(BattleValueMode.Absolute)); + } + + [TestCase("PAL3", int.MaxValue, 1, 1, int.MinValue)] + [TestCase("PAL3A", int.MaxValue, 1, 1, int.MinValue)] + [TestCase("PAL3", int.MaxValue - 1, 3, 1, int.MinValue + 1)] + [TestCase("PAL3A", int.MaxValue - 1, 3, 1, int.MinValue + 1)] + [TestCase("PAL3", 0, int.MaxValue, 2, -2)] + [TestCase("PAL3A", 0, int.MaxValue, 2, -2)] + [TestCase("PAL3", 123, 1, 1, 124)] + [TestCase("PAL3A", 123, 1, 1, 124)] + public void SettlementCommitsNativeSignedExperienceAndReplayRetainsTheResult(string variant, int before, int reward, int enemies, int expected) + { + BattleScenario scenario = Scenario(variant, enemies); + scenario.Participants[0].Level = 100; + scenario.Participants[0].Experience = before; + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 301, Level = 4, Mastered = true }); + var setup = new BattleSetup(scenario); + BattleDefinitions definitions = Definitions(scenario, reward); + var catalog = new Catalog(); + var session = new BattleSession(setup, catalog, definitions: definitions); + Assert.That(session.Submit(new BattleCommand("Ally", BattleAction.Skill, abilityId: 301)), Is.True); + Complete(session); + BattleActorReward result = session.Result.Rewards.Single(); + Assert.That(result.ExperienceBefore, Is.EqualTo(before)); + Assert.That(result.ExperienceAfter, Is.EqualTo(expected)); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "Ally").Experience, Is.EqualTo(expected)); + Assert.That(result.LevelAfter, Is.EqualTo(100)); + Assert.DoesNotThrow(() => new BattleResultPresentation(variant, session.Result, session.Events)); + Assert.That(BattleResultStatistics.Experience(result.ExperienceGained, 2), Is.EqualTo(result.ExperienceGained)); + Assert.That(scenario.Participants[0].Experience, Is.EqualTo(before)); + AssertReplay(setup, catalog, definitions, session); + } + + [TestCase("PAL3", 1, false)] + [TestCase("PAL3A", 1, false)] + [TestCase("PAL3", 50, false)] + [TestCase("PAL3A", 50, false)] + [TestCase("PAL3", 1, true)] + [TestCase("PAL3A", 1, true)] + [TestCase("PAL3", 50, true)] + [TestCase("PAL3A", 50, true)] + public void WrappedExperienceUsesUnsignedNativeLevelsAndCommitsGrowthThroughResultsAndReplay(string variant, int oldLevel, bool negativeGain) + { + BattleScenario scenario = Scenario(variant, negativeGain ? 2 : 1); + BattleParticipant initial = scenario.Participants[0]; + initial.Level = oldLevel; + initial.Experience = negativeGain ? 0 : int.MaxValue; + initial.Attributes[3] = 100; + initial.Attributes[4] = 100; + initial.Vitals = new[] { 7, 8, 9 }; + initial.Skills.Add(new BattleSkill { Id = 301, Level = 4, Mastered = true }); + var setup = new BattleSetup(scenario); + int[] thresholds = Enumerable.Range(0, 101).Select(level => Math.Max(0, level - 1) * 100).ToArray(); + thresholds[100] = int.MaxValue; + int[][] growth = Enumerable.Range(0, 101).Select(_ => new int[12]).ToArray(); + // Published growth functions for identity zero at levels 1/50/100. + // Full native CalCombatResult, CalLevel and growth were executed together. + growth[1] = variant == "PAL3" ? new[] { 88, 17, 29, 30, 20, 0, 0, 0, 0, 0, 0, 0 } : new[] { 78, 9, 24, 25, 22, 0, 0, 0, 0, 0, 0, 0 }; + growth[50] = variant == "PAL3" ? new[] { 480, 72, 225, 251, 182, 0, 0, 0, 0, 0, 0, 0 } : new[] { 470, 58, 220, 270, 218, 0, 0, 0, 0, 0, 0, 0 }; + growth[100] = variant == "PAL3" ? new[] { 880, 98, 425, 476, 347, 0, 0, 0, 0, 0, 0, 0 } : new[] { 870, 108, 420, 520, 418, 0, 0, 0, 0, 0, 0, 0 }; + int[] expected = (variant, oldLevel) switch + { + ("PAL3", 1) => new[] { 892, 181, 496, 546, 427, 10, 10 }, + ("PAL3", 50) => new[] { 500, 126, 300, 325, 265, 10, 10 }, + ("PAL3A", 1) => new[] { 892, 199, 496, 595, 496, 10, 10 }, + _ => new[] { 500, 150, 300, 350, 300, 10, 10 } + }; + BattleDefinitions definitions = Definitions(scenario, negativeGain ? int.MaxValue : 1, thresholds, growth); + var catalog = new Catalog(); + var session = new BattleSession(setup, catalog, definitions: definitions); + Assert.That(session.Submit(new BattleCommand("Ally", BattleAction.Skill, abilityId: 301)), Is.True); + Complete(session); + BattleActorReward reward = session.Result.Rewards.Single(); + BattleActorSnapshot actor = session.Result.Actors.Single(candidate => candidate.Id == "Ally"); + BattleActorSnapshot before = session.Result.PreSettlementActors.Single(candidate => candidate.Id == "Ally"); + Assert.That(reward.ExperienceAfter, Is.EqualTo(negativeGain ? -2 : int.MinValue)); + Assert.That(reward.LevelBefore, Is.EqualTo(oldLevel)); + Assert.That(reward.LevelAfter, Is.EqualTo(100)); + Assert.That(reward.AttributesBefore, Is.EqualTo(initial.Attributes)); + Assert.That(reward.AttributesAfter.Take(7), Is.EqualTo(expected)); + Assert.That(actor.Level, Is.EqualTo(100)); + Assert.That(actor.Experience, Is.EqualTo(reward.ExperienceAfter)); + Assert.That(actor.Attributes.Take(7), Is.EqualTo(expected)); + Assert.That(new[] { actor.Hp, actor.Sp, actor.Mp }, Is.EqualTo(expected.Take(3))); + Assert.That(new[] { before.Hp, before.Sp, before.Mp }, Is.EqualTo(new[] { 7, 8, 9 })); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.LevelUp && entry.Source == "Ally"), Is.EqualTo(1)); + var presentation = new BattleResultPresentation(variant, session.Result, session.Events); + Assert.That(presentation.Sequence.Single(step => step.Kind == BattleResultStepKind.LevelUp).Value, Is.EqualTo(100)); + Assert.That(presentation.Sequence.Count(step => step.Kind == BattleResultStepKind.LevelUpBody), Is.EqualTo(variant == "PAL3A" ? 1 : 0)); + for (int frame = 0; frame < 3000 && !presentation.Completed; frame++) + presentation.Step(); + Assert.That(presentation.Completed, Is.True); + Assert.That(initial.Level, Is.EqualTo(oldLevel)); + Assert.That(initial.Experience, Is.EqualTo(negativeGain ? 0 : int.MaxValue)); + Assert.That(initial.Vitals, Is.EqualTo(new[] { 7, 8, 9 })); + AssertReplay(setup, catalog, definitions, session); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NegativeInitialExperienceIsStillRejectedBeforeRuntimeSettlement(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Experience = -1; + Assert.That(scenario.Validate(), Is.Not.Empty); + Assert.Throws(() => new BattleSetup(scenario)); + } + + private static void Complete(BattleSession session) + { + for (int step = 0; step < 5000 && session.Status == BattleSessionStatus.Running; step++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed), session.Result?.Reason); + } + + private static void AssertReplay(BattleSetup setup, Catalog catalog, BattleDefinitions definitions, BattleSession session) + { + BattleSession replay = BattleReplay.Play(setup, catalog, session.Inputs, session.Tick, definitions: definitions); + Assert.That(JsonConvert.SerializeObject(replay.Result), Is.EqualTo(JsonConvert.SerializeObject(session.Result))); + Assert.That(JsonConvert.SerializeObject(replay.Events), Is.EqualTo(JsonConvert.SerializeObject(session.Events))); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleNativeArithmeticBoundaryTests.cs.meta b/Assets/Tests/Battle/Editor/BattleNativeArithmeticBoundaryTests.cs.meta new file mode 100644 index 00000000..23f60e3b --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleNativeArithmeticBoundaryTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c02e73afe7f0471c9bc967b4d1a00511 diff --git a/Assets/Tests/Battle/Editor/BattleNativeLifecycleTests.cs b/Assets/Tests/Battle/Editor/BattleNativeLifecycleTests.cs new file mode 100644 index 00000000..3942b5b1 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleNativeLifecycleTests.cs @@ -0,0 +1,406 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using NUnit.Framework; + using Pal3.Battle; + + // Expected behavior comes from the released EXE traces under + // workspace/Analysis/Battle-Stage4/review-{ability-clock,lethal-gp,death, + // block-death,absorb-writer,scheduler,physical-display}-native.json. + // Reflection supplies native writer/body/stage ports without adding product APIs. + public sealed class BattleNativeLifecycleTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattleStageGeometry + { + private readonly Dictionary _actors; + internal AttackTiming AbilityTiming = new(0, 20, new[] { 5 }); + internal AttackTiming PhysicalTiming = new(0, 5, new[] { 1 }); + internal int HurtTicks = 10; + + internal Catalog(BattleScenario scenario) => _actors = scenario.Participants.ToDictionary(actor => actor.InstanceId); + + public AttackTiming Attack(string source, string target) => PhysicalTiming; + + public AttackTiming Ability(string source, BattleAbilityDefinition ability) => AbilityTiming; + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => HurtTicks; + + public int SpImpact(string actor) => 7; + + public int Priority(string actor) => actor switch { "A" => 0, "B" => 1, "C" => 4, _ => 5 }; + + public int DamageDivisor(string actor) => 1; + + public BattleMovementPoint InitialHome(string actor) => FormationHome(actor, _actors[actor].Slot); + + public BattleMovementPoint FormationHome(string actor, BattleSlot slot) => + new((_actors[actor].Side == BattleSide.Enemy ? 1000 : 0) + 100 * (int)slot, 0, 0); + + public BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint sourceHome, BattleMovementPoint targetHome) => + new(PhysicalTiming, sourceHome, sourceHome, targetHome); + + public IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint from, + BattleMovementPoint to, bool midpoint) => new[] { new BattleMovementPlan(BattleMovementKind.Run, from, to) }; + } + + private sealed class ReadyRules : IBattleRules + { + private readonly HashSet _ready; + + internal ReadyRules(IEnumerable ready) => _ready = new HashSet(ready); + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + _ready.Contains(actor.InstanceId) ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => 0; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => new(-10, false, false); + } + + private sealed class OccupiedJob : IBattleStageJob + { + public bool Advance(BattleStageContext context) => false; + } + + private static BattleScenario Scenario(string variant, bool party = false) + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "native-lifecycle", Seed = 1 }; + scenario.Participants.Add(Participant("A", BattleSide.Ally, BattleSlot.Water)); + if (party) + { + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire)); + scenario.Participants.Add(Participant("C", BattleSide.Ally, BattleSlot.Earth)); + } + scenario.Participants.Add(Participant("E", BattleSide.Enemy, BattleSlot.Water)); + return scenario; + } + + private static BattleParticipant Participant(string id, BattleSide side, BattleSlot slot) => new() + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = slot, + Attributes = new[] { 500, 100, 200, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 10, 0 } + }; + + private static BattleAbilityData Technique(int id = 4305) => new() + { + Id = id, + Name = "native lifecycle work", + SkillTypeId = 0, + Range = BattleTargetRange.OpponentSingle, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -20) } + }; + + private static BattleSession Session(BattleScenario scenario, out Catalog catalog, + BattleAbilityData ability = null, params string[] ready) + { + if (ability != null) + scenario.Participants[0].Skills.Add(new BattleSkill { Id = ability.Id, Level = 4, Mastered = true }); + catalog = new Catalog(scenario); + var definitions = new BattleDefinitions(scenario.Variant, scenario.DataFingerprint, + ability == null ? Array.Empty() : new[] { new BattleAbilityDefinition(ability) }, + Array.Empty(), scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId switch { "A" => 0, "B" => 1, "C" => 4, _ => -1 }, + NormalAttackMode = 924 + }))); + return new BattleSession(new BattleSetup(scenario), catalog, new ReadyRules(ready.Length == 0 ? new[] { "A" } : ready), definitions); + } + + private static BattleActorSnapshot Actor(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + private static object NativeActor(BattleSession session, string id) => + ((IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session))[id]; + + private static object Invoke(BattleSession session, string name, params object[] arguments) => + typeof(BattleSession).GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic).Invoke(session, arguments); + + private static int WriteHp(BattleSession session, string id, int requested, bool showAction = false) => + (int)Invoke(session, "ChangeHp", NativeActor(session, id), requested, null, 0L, "native writer port", showAction, false, false); + + private static int WriteResource(BattleSession session, string id, int resource, int requested, bool showNumber = false) => + (int)Invoke(session, "ChangeResource", NativeActor(session, id), resource, requested, null, 0L, "native writer port", showNumber); + + private static BattleStageScheduler Stage(BattleSession session) => + (BattleStageScheduler)typeof(BattleSession).GetField("_stage", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + + private static void Steps(BattleSession session, int count) + { + for (int i = 0; i < count; i++) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AbilityWorkUsesStageTimeWhileItsBodyIsHurt(string variant) + { + BattleAbilityData ability = Technique(); + BattleSession session = Session(Scenario(variant), out _, ability); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Steps(session, 2); + WriteHp(session, "A", -1, true); + Steps(session, 3); + Assert.That(session.Events.Single(entry => entry.Target == "E" && entry.Resource == 0 && entry.Kind == BattleEventKind.Hit).Tick, Is.EqualTo(5)); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Hurt)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void DelayedBodyActivationDoesNotRestartTheActWorkClock(string variant) + { + BattleAbilityData ability = Technique(); + BattleSession session = Session(Scenario(variant), out _, ability); + WriteHp(session, "A", -1, true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Steps(session, 11); + Assert.That(session.Events.Single(entry => entry.Target == "E" && entry.Kind == BattleEventKind.Hit).Tick, Is.EqualTo(11)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void BodyCanReturnToIdleWhileTheStageStillWaits(string variant) + { + BattleAbilityData ability = Technique(); + BattleSession session = Session(Scenario(variant), out Catalog catalog, ability); + catalog.AbilityTiming = new AttackTiming(0, 5, new[] { 2 }, minimumEndTick: 20, bodyAnimationTicks: 2); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Steps(session, 4); + Assert.That(Actor(session, "A").CurrentAction, Is.EqualTo(BattleAction.Skill)); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Idle)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void LethalPhysicalDamageStillPaysSameCallSpBeforeTheNextStatePass(string variant) + { + BattleScenario scenario = Scenario(variant, true); + scenario.Participants[0].Vitals[0] = 1; + BattleSession session = Session(scenario, out _, ready: new[] { "E" }); + Assert.That(session.Submit("E", BattleAction.Attack, "A"), Is.True); + Steps(session, 1); + Assert.That((Actor(session, "A").Hp, Actor(session, "A").Sp, Actor(session, "A").AliveFlag), Is.EqualTo((0, 17, true))); + Steps(session, 1); + Assert.That(Actor(session, "A").AliveFlag, Is.False); + Assert.That(Actor(session, "A").ModelAliveFlag, Is.True); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Hurt)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void SameFrameHealingCanSaveAnHpZeroActorBeforeFixState(string variant) + { + BattleSession session = Session(Scenario(variant, true), out _); + WriteHp(session, "B", -1000); + Assert.That(Actor(session, "B").AliveFlag, Is.True); + Assert.That(WriteResource(session, "B", 1, 7), Is.EqualTo(7)); + WriteHp(session, "B", 1); + Steps(session, 1); + Assert.That((Actor(session, "B").Hp, Actor(session, "B").Sp, Actor(session, "B").AliveFlag), Is.EqualTo((1, 17, true))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void HpZeroWithAliveFlagRepeatsTheNativeDeathWriter(string variant) + { + BattleSession session = Session(Scenario(variant, true), out _); + WriteHp(session, "B", -1000); + WriteHp(session, "B", 0); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Death && entry.Target == "B"), Is.EqualTo(2)); + Assert.That(Actor(session, "B").AliveFlag, Is.True); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void DeathEndRequestDoesNotCancelPreviouslyRegisteredNumbers(string variant) + { + BattleSession session = Session(Scenario(variant, true), out _); + WriteHp(session, "B", -1); + WriteHp(session, "B", -1000); + Steps(session, 1); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.NumberShown && entry.Target == "B"), Is.EqualTo(2)); + Assert.That(session.StageTasks.Count(task => task.Owner == "B"), Is.EqualTo(2)); + Steps(session, 100); + Assert.That(session.StageTasks.Count(task => task.Owner == "B"), Is.EqualTo(2)); + Steps(session, 1); + Assert.That(session.StageTasks.Count(task => task.Owner == "B"), Is.Zero); + } + + [TestCase("PAL3", 0, false, 41)] + [TestCase("PAL3", 5, false, 41)] + [TestCase("PAL3", 100, false, 41)] + [TestCase("PAL3", 0, true, 41)] + [TestCase("PAL3A", 0, false, 0)] + [TestCase("PAL3A", 5, false, 5)] + [TestCase("PAL3A", 100, false, 100)] + [TestCase("PAL3A", 0, true, 161)] + [TestCase("PAL3A", 5, true, 161)] + [TestCase("PAL3A", 100, true, 161)] + public void MpAbsorptionUsesTheDisplayAllocationDependentNativeReturn(string variant, int targetMp, bool poolFull, int expectedAbsorption) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.Last().Vitals[2] = targetMp; + BattleAbilityData ability = Technique(variant == "PAL3" ? 4304 : 4504); + ability.Handler = BattleSpecialHandler.ReturnedMpAbsorb; + ability.Attributes = new[] { new BattleAttributeEffect(2, BattleValueMode.Absolute, variant == "PAL3" ? -40 : -150) }; + BattleSession session = Session(scenario, out _, ability); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Steps(session, 1); + if (poolFull) + { + BattleStageScheduler stage = Stage(session); + while (stage.Count < BattleStageScheduler.DefaultCapacity) + stage.Add("occupied native slot", "fixture", new OccupiedJob(), BattleStageScheduler.TimeAt(session.Tick)); + } + Steps(session, 5); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(expectedAbsorption)); + Assert.That(Actor(session, "E").Mp, Is.EqualTo(Math.Max(0, targetMp - (variant == "PAL3" ? 41 : 161)))); + BattleEvent returned = session.Events.Single(entry => entry.Detail == "native returned MP absorption"); + Assert.That(returned.RequestedDelta, Is.EqualTo(expectedAbsorption)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AFullHpRecoveryNumberKeepsFormationLockedUntilItsStageDeletion(string variant) + { + BattleSession session = Session(Scenario(variant, true), out _, ready: new[] { "C" }); + WriteHp(session, "A", 1); + Assert.That(session.CanBeginFormation("C"), Is.Not.Null); + Steps(session, 126); + Assert.That(session.CanBeginFormation("C"), Is.Not.Null); + Steps(session, 1); + Assert.That(session.CanBeginFormation("C"), Is.Null); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ABodyOnlyBlockDoesNotBecomeAStageTaskForFormation(string variant) + { + BattleSession session = Session(Scenario(variant, true), out _, ready: new[] { "C" }); + Invoke(session, "PushBodyBlock", NativeActor(session, "A"), false); + Assert.That(Actor(session, "A").Pose, Is.EqualTo(BattlePose.Hurt)); + Assert.That(session.CanBeginFormation("C"), Is.Null); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ZeroGpDoesNotCreateAStageNumberEvenWhenDisplayWasRequested(string variant) + { + BattleSession session = Session(Scenario(variant), out _); + Assert.That(WriteResource(session, "A", 1, 0, true), Is.Zero); + Assert.That(session.StageTasks, Is.Empty); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void HpRecoveryDisplaysTheClampedAmount(string variant) + { + BattleSession session = Session(Scenario(variant), out _); + Assert.That(WriteHp(session, "A", 10), Is.Zero); + Steps(session, 1); + BattleEvent number = session.Events.Single(entry => entry.Kind == BattleEventKind.NumberShown); + Assert.That(number.RequestedDelta, Is.Zero); + Assert.That(number.DurationSeconds, Is.EqualTo(2.5f)); + } + + [TestCase("PAL3", true, false, 5)] + [TestCase("PAL3A", true, false, 5)] + [TestCase("PAL3", true, true, 10)] + [TestCase("PAL3A", true, true, 10)] + [TestCase("PAL3", false, false, 10)] + [TestCase("PAL3A", false, false, 10)] + public void PositiveHpReturnAlsoDependsOnSuccessfulNumberRegistration(string variant, bool modelAlive, bool poolFull, int returned) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Vitals[0] = 495; + BattleSession session = Session(scenario, out _); + NativeActor(session, "A").GetType().GetField("ModelAlive").SetValue(NativeActor(session, "A"), modelAlive); + if (poolFull) + { + BattleStageScheduler stage = Stage(session); + while (stage.Count < BattleStageScheduler.DefaultCapacity) + stage.Add("occupied native slot", "fixture", new OccupiedJob(), 0f); + } + Assert.That(WriteHp(session, "A", 10), Is.EqualTo(returned)); + Assert.That(Actor(session, "A").Hp, Is.EqualTo(500)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ResurrectionRestoresBothLifeFlagsBeforeTheHpWriter(string variant) + { + BattleScenario scenario = Scenario(variant, true); + scenario.Participants[1].Vitals[0] = 0; + BattleSession session = Session(scenario, out _); + Invoke(session, "ApplyState", NativeActor(session, "B"), BattleState.Death, true, null, false, null, 0L, true); + Assert.That((Actor(session, "B").Hp, Actor(session, "B").AliveFlag, Actor(session, "B").ModelAliveFlag), Is.EqualTo((0, true, true))); + Assert.That(WriteHp(session, "B", 10), Is.EqualTo(10)); + Assert.That(session.StageTasks.Count(task => task.Owner == "B"), Is.EqualTo(1)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void FormationCloseStillReleasesBodiesWhenTheNativeStagePoolIsFull(string variant) + { + BattleSession session = Session(Scenario(variant, true), out _, ready: new[] { "C" }); + Assert.That(session.BeginFormation("C"), Is.True); + Assert.That(session.SwapFormation("A", BattleSlot.Fire), Is.True); + Steps(session, 3); + float current = Actor(session, "A").Position.X; + BattleStageScheduler stage = Stage(session); + while (stage.Count < BattleStageScheduler.DefaultCapacity) + stage.Add("occupied native slot", "fixture", new OccupiedJob(), BattleStageScheduler.TimeAt(session.Tick)); + Assert.That(session.EndFormation("C"), Is.True); + Assert.That(session.ActiveFormationController, Is.Null); + Assert.That(Actor(session, "A").Movement, Is.Null); + Assert.That(Actor(session, "A").Position.X, Is.EqualTo(current)); + Assert.That(Actor(session, "C").Gauge, Is.Zero); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ADeathEndRequestDoesNotWaitForTheOrdinaryAbilityMinimumEnd(string variant) + { + BattleAbilityData ability = Technique(); + BattleSession session = Session(Scenario(variant, true), out Catalog catalog, ability); + catalog.AbilityTiming = new AttackTiming(0, 50, new[] { 40 }, minimumEndTick: 100); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Steps(session, 1); + WriteHp(session, "A", -1000); + Steps(session, 9); + Assert.That(Actor(session, "A").CurrentAction, Is.Null); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit && entry.Target == "E"), Is.False); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void APhysicalNonnegativeResultCreatesItsNativeMissNumber(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Attributes[3] = 0; + scenario.Participants[1].Attributes[4] = 1000; + BattleSession session = Session(scenario, out _); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Steps(session, 2); + BattleEvent number = session.Events.Single(entry => entry.Kind == BattleEventKind.NumberShown); + Assert.That((number.Target, number.DurationSeconds, number.Detail), Is.EqualTo(("E", 1f, "native miss"))); + Assert.That(number.Tick, Is.EqualTo(2)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleNativeLifecycleTests.cs.meta b/Assets/Tests/Battle/Editor/BattleNativeLifecycleTests.cs.meta new file mode 100644 index 00000000..d0a50075 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleNativeLifecycleTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: de35ee761be3440e974361c42cf4de93 diff --git a/Assets/Tests/Battle/Editor/BattlePal3AFlightTests.cs b/Assets/Tests/Battle/Editor/BattlePal3AFlightTests.cs new file mode 100644 index 00000000..e15b0269 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattlePal3AFlightTests.cs @@ -0,0 +1,72 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using Battle; + using NUnit.Framework; + + public sealed class BattlePal3AFlightTests + { + // Published PAL3A ProcFlyRun 0x4ffb98: the near-distance test is + // eight units after integrating; only over or death finishes the task. + [TestCase(0f)] + [TestCase(1.99f)] + [TestCase(8f)] + public void ShortFlightsStillWaitForTheActualOverMarker(float distance) + { + var movement = new BattleMovement("PAL3A", new BattleMovementPlan(BattleMovementKind.Fly, default, + new BattleMovementPoint(0, 0, distance), flyUpTick: 5, flyDownTick: 30, overTick: 35)); + for (int call = 0; call < 35; call++) + { + movement.Step(); + Assert.That(movement.Finished, Is.False, "call " + call); + } + movement.Step(); + Assert.That(movement.Finished, Is.True); + Assert.That(movement.Position.Z, Is.EqualTo(distance)); + } + + [Test] + public void FlightDownStopsAnUnfinishedPal3aFlightImmediately() + { + var movement = new BattleMovement("PAL3A", new BattleMovementPlan(BattleMovementKind.Fly, default, + new BattleMovementPoint(0, 0, 100), flyUpTick: 5, flyDownTick: 6, overTick: 35)); + for (int call = 0; call <= 5; call++) + movement.Step(); + Assert.That(movement.Position.Z, Is.EqualTo(3.3333334922790527f)); + movement.Step(); + Assert.That(movement.Position.Z, Is.EqualTo(3.3333334922790527f)); + Assert.That(movement.Finished, Is.False); + for (int call = 7; call <= 35; call++) + movement.Step(); + Assert.That(movement.Position.Z, Is.EqualTo(100)); + Assert.That(movement.Finished, Is.True); + } + + [Test] + public void ActivationDiscardsFlyUpAndDoesNotInventAnOver() + { + var movement = new BattleMovement("PAL3A", new BattleMovementPlan(BattleMovementKind.Fly, default, + new BattleMovementPoint(0, 0, 100), flyUpTick: 0)); + for (int call = 0; call < 120; call++) + movement.Step(); + Assert.That(movement.Position.Z, Is.Zero); + Assert.That(movement.Finished, Is.False); + } + + [Test] + public void DeathKeepsTheNativeFirstIntegratedPosition() + { + var movement = new BattleMovement("PAL3A", new BattleMovementPlan(BattleMovementKind.Fly, default, + new BattleMovementPoint(0, 0, 100), flyUpTick: 5, overTick: 35)); + for (int call = 0; call < 5; call++) + movement.Step(); + movement.Step(alive: false); + Assert.That(movement.Position.Z, Is.EqualTo(3.3333334922790527f)); + Assert.That(movement.Finished, Is.True); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattlePal3AFlightTests.cs.meta b/Assets/Tests/Battle/Editor/BattlePal3AFlightTests.cs.meta new file mode 100644 index 00000000..aab98c42 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattlePal3AFlightTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5a4bf8a6fd014845abc82d9f84f2fc3a diff --git a/Assets/Tests/Battle/Editor/BattlePal3AFormRulesTests.cs b/Assets/Tests/Battle/Editor/BattlePal3AFormRulesTests.cs new file mode 100644 index 00000000..292c5a4b --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattlePal3AFormRulesTests.cs @@ -0,0 +1,843 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Linq; + using System.Reflection; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattlePal3AFormRulesTests + { + [TestCase(1, 0, 0, -1, false, 0, 1u)] + [TestCase(1, 0, 0, -1, true, 0, 3357800067u)] + [TestCase(1, 0, 0, 0, false, 0, 1u)] + [TestCase(1, 0, 0, 0, true, 0, 3357800067u)] + [TestCase(1, 0, 0, 1, false, 0, 1u)] + [TestCase(1, 0, 0, 1, true, 0, 3357800067u)] + [TestCase(1, 10, 500, -1, false, 551, 3357800067u)] + [TestCase(1, 10, 500, -1, true, 324, 3884216597u)] + [TestCase(1, 10, 500, 0, false, 525, 3357800067u)] + [TestCase(1, 10, 500, 0, true, 309, 3884216597u)] + [TestCase(1, 10, 500, 1, false, 499, 3357800067u)] + [TestCase(1, 10, 500, 1, true, 294, 3884216597u)] + [TestCase(1, 101, 17, -1, false, -103, 3357800067u)] + [TestCase(1, 101, 17, -1, true, -60, 3884216597u)] + [TestCase(1, 101, 17, 0, false, -98, 3357800067u)] + [TestCase(1, 101, 17, 0, true, -57, 3884216597u)] + [TestCase(1, 101, 17, 1, false, -93, 3357800067u)] + [TestCase(1, 101, 17, 1, true, -54, 3884216597u)] + [TestCase(1, 1000, 300, -1, false, -891, 3357800067u)] + [TestCase(1, 1000, 300, -1, true, -525, 3884216597u)] + [TestCase(1, 1000, 300, 0, false, -849, 3357800067u)] + [TestCase(1, 1000, 300, 0, true, -500, 3884216597u)] + [TestCase(1, 1000, 300, 1, false, -807, 3357800067u)] + [TestCase(1, 1000, 300, 1, true, -475, 3884216597u)] + [TestCase(7, 0, 0, -1, false, 0, 7u)] + [TestCase(7, 0, 0, -1, true, 0, 3289278137u)] + [TestCase(7, 0, 0, 0, false, 0, 7u)] + [TestCase(7, 0, 0, 0, true, 0, 3289278137u)] + [TestCase(7, 0, 0, 1, false, 0, 7u)] + [TestCase(7, 0, 0, 1, true, 0, 3289278137u)] + [TestCase(7, 10, 500, -1, false, 590, 3289278137u)] + [TestCase(7, 10, 500, -1, true, 324, 461394683u)] + [TestCase(7, 10, 500, 0, false, 562, 3289278137u)] + [TestCase(7, 10, 500, 0, true, 309, 461394683u)] + [TestCase(7, 10, 500, 1, false, 534, 3289278137u)] + [TestCase(7, 10, 500, 1, true, 294, 461394683u)] + [TestCase(7, 101, 17, -1, false, -103, 3289278137u)] + [TestCase(7, 101, 17, -1, true, -56, 461394683u)] + [TestCase(7, 101, 17, 0, false, -98, 3289278137u)] + [TestCase(7, 101, 17, 0, true, -53, 461394683u)] + [TestCase(7, 101, 17, 1, false, -93, 3289278137u)] + [TestCase(7, 101, 17, 1, true, -50, 461394683u)] + [TestCase(7, 1000, 300, -1, false, -912, 3289278137u)] + [TestCase(7, 1000, 300, -1, true, -501, 461394683u)] + [TestCase(7, 1000, 300, 0, false, -869, 3289278137u)] + [TestCase(7, 1000, 300, 0, true, -477, 461394683u)] + [TestCase(7, 1000, 300, 1, false, -826, 3289278137u)] + [TestCase(7, 1000, 300, 1, true, -453, 461394683u)] + [TestCase(12345, 0, 0, -1, false, 0, 12345u)] + [TestCase(12345, 0, 0, -1, true, 0, 1255958651u)] + [TestCase(12345, 0, 0, 0, false, 0, 12345u)] + [TestCase(12345, 0, 0, 0, true, 0, 1255958651u)] + [TestCase(12345, 0, 0, 1, false, 0, 12345u)] + [TestCase(12345, 0, 0, 1, true, 0, 1255958651u)] + [TestCase(12345, 10, 500, -1, false, 597, 1255958651u)] + [TestCase(12345, 10, 500, -1, true, 328, 1449997005u)] + [TestCase(12345, 10, 500, 0, false, 569, 1255958651u)] + [TestCase(12345, 10, 500, 0, true, 312, 1449997005u)] + [TestCase(12345, 10, 500, 1, false, 541, 1255958651u)] + [TestCase(12345, 10, 500, 1, true, 296, 1449997005u)] + [TestCase(12345, 101, 17, -1, false, -98, 1255958651u)] + [TestCase(12345, 101, 17, -1, true, -54, 1449997005u)] + [TestCase(12345, 101, 17, 0, false, -93, 1255958651u)] + [TestCase(12345, 101, 17, 0, true, -51, 1449997005u)] + [TestCase(12345, 101, 17, 1, false, -88, 1255958651u)] + [TestCase(12345, 101, 17, 1, true, -48, 1449997005u)] + [TestCase(12345, 1000, 300, -1, false, -795, 1255958651u)] + [TestCase(12345, 1000, 300, -1, true, -437, 1449997005u)] + [TestCase(12345, 1000, 300, 0, false, -757, 1255958651u)] + [TestCase(12345, 1000, 300, 0, true, -416, 1449997005u)] + [TestCase(12345, 1000, 300, 1, false, -719, 1255958651u)] + [TestCase(12345, 1000, 300, 1, true, -395, 1449997005u)] + public void CaptureForecastMatchesReleasedInstructions(int seed, int attack, int defense, int difference, bool row, int expected, uint finalSeed) + { + var random = new BattleRandom(seed); + Assert.That(BattlePal3ARules.CaptureForecast(31, attack, defense, difference, row, random), Is.EqualTo(expected)); + Assert.That(random.State, Is.EqualTo(finalSeed)); + } + + [TestCase(2, 9, 9, 9, 9, 0)] + [TestCase(3, 9, 6, 3, 5, 3)] + [TestCase(8, 9, 6, 9, 9, 6)] + [TestCase(9, 9, 9, 9, 9, 9)] + public void WheelUsesItsLeastChargedElement(int water, int fire, int wind, int thunder, int earth, int rounds) + { + var wheel = new BattleSpiritWheelSnapshot(new[] { water, fire, wind, thunder, earth }); + Assert.That(wheel.NangongRounds, Is.EqualTo(rounds)); + Assert.That(BattlePal3ARules.Gain(wheel, 0, 100).Charges[0], Is.EqualTo(9)); + Assert.That(wheel.Charges[0], Is.EqualTo(water)); + } + + [Test] + public void AuthoredAndRuntimeWheelSnapshotsDoNotAlias() + { + var authored = new BattleSpiritWheel { Charges = new[] { 1, 2, 3, 4, 5 } }; + var copy = authored.Copy(); + BattleSpiritWheelSnapshot captured = authored.Capture(); + authored.Charges[0] = 9; + Assert.That(copy.Charges[0], Is.EqualTo(1)); + Assert.That(captured.Charges[0], Is.EqualTo(1)); + Assert.Throws(() => new BattleSpiritWheelSnapshot(new[] { 1, 2, 3, 4, 10 })); + } + + [TestCase(0, -100, 100)] + [TestCase(100, -999999, 1000099)] + [TestCase(int.MaxValue, -1, int.MinValue)] + [TestCase(-1, -1, 0)] + [TestCase(0, 2, 0)] + public void LossUsesRequestedInt32MagnitudeBeforeResourceClamp(int before, int delta, int after) + => Assert.That(BattlePal3ARules.AddLoss(before, delta), Is.EqualTo(after)); + + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattlePal3AFormCatalog + { + internal bool MissingFormClip; + internal bool FailHumanModel; + internal uint FormDuration = 192; + + public AttackTiming Attack(string source, string target) => new(0, 3, new[] { 1 }); + + public AttackTiming Ability(string source, BattleAbilityDefinition ability) => new(0, 3, new[] { 1 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "P" ? 2 : 0; + + public int DamageDivisor(string actor) => 1; + + public BattlePhysicalAnimation FormChangeAnimation(string actorId, bool transformed) => MissingFormClip ? null : new("z20", 2, 1f, + Array.Empty(), FormDuration); + + public void ActivatePal3AForm(string actorId, BattlePal3AFormKind kind) + { + if (FailHumanModel && kind == BattlePal3AFormKind.Human) + throw new InvalidOperationException("Human model unavailable"); + } + } + + private sealed class ReadyRules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => 1000; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) + => new BattleBasicRules().Hit(source, target, guarding, random, targetAtHome, damageDivisor); + } + + private static BattleSession Session(bool nangong = false, bool pengxu = false, BattleTargetRange nangongRange = BattleTargetRange.OpponentSingle, Catalog catalog = null) + { + var scenario = new BattleScenario { Variant = "PAL3A", Scene = "native", DataFingerprint = "native" }; + scenario.Pal3A.NangongStartsTransformed = nangong; + scenario.Pal3A.PengxuStartsTransformed = pengxu; + scenario.Pal3A.SpiritWheel.Charges = new[] { 3, 3, 3, 3, 3 }; + scenario.Participants.AddRange(new[] + { + new BattleParticipant { InstanceId = "A", ActorId = 101, Side = BattleSide.Ally, Attributes = new[] { 1000, 100, 200, 100, 50, 5, 10, 0, 0, 0, 0, 0 }, Vitals = new[] { 777, 100, 200 } }, + new BattleParticipant { InstanceId = "P", ActorId = 103, Side = BattleSide.Ally, Slot = BattleSlot.Fire, Attributes = new[] { 2000, 100, 500, 100, 101, 5, 10, 0, 0, 0, 0, 0 }, Vitals = new[] { 1000, 100, 500 } }, + new BattleParticipant { InstanceId = "E", ActorId = 701, Side = BattleSide.Enemy, Attributes = new[] { 99999, 100, 500, 100, 30, 3, 0, 0, 0, 0, 0, 0 }, Vitals = new[] { 99999, 100, 500 } } + }); + var definitions = new BattleDefinitions("PAL3A", "native", Array.Empty(), Array.Empty(), new[] + { + new BattleActorDefinition(new BattleActorData { InstanceId = "A", Identity = 0, NormalAttackRange = nangongRange }), + new BattleActorDefinition(new BattleActorData { InstanceId = "P", Identity = 2 }), + new BattleActorDefinition(new BattleActorData { InstanceId = "E" }) + }); + var session = new BattleSession(new BattleSetup(scenario), catalog ?? new Catalog(), new ReadyRules(), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + + private static object Actor(BattleSession session, string id) => + ((IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(session))[id]; + + private static object Invoke(BattleSession session, string method, params object[] arguments) => + typeof(BattleSession).GetMethod(method, BindingFlags.NonPublic | BindingFlags.Instance).Invoke(session, arguments); + + [Test] + public void FailedHumanModelRestoreStillEndsBattle() + { + var catalog = new Catalog(); + BattleSession session = Session(nangong: true, pengxu: true, catalog: catalog); + catalog.FailHumanModel = true; + session.Fault("initial presentation failure"); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Faulted)); + Assert.That(session.Result.Reason, Is.EqualTo("initial presentation failure")); + Assert.That(session.Result.Winner, Is.Null); + Assert.That(session.StageTasks, Is.Empty); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "P").MaxHp, Is.EqualTo(2000)); + Assert.That(session.IsPal3ATransformed("A") || session.IsPal3ATransformed("P"), Is.False); + Assert.That(session.Events.Where(entry => entry.Kind == BattleEventKind.PresentationCleanupFailed) + .Select(entry => entry.Source), Is.EquivalentTo(new[] { "A", "P" })); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Ended), Is.EqualTo(1)); + } + + [Test] + public void SuccessfulPartyFleeCancelsActiveTeammateFormWithoutFreezingRun() + { + BattleSession session = Session(catalog: new Catalog { FormDuration = 19200 }); + typeof(BattleSession).GetField("_fleeAlwaysSucceeds", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(session, true); + Assert.That(session.Submit("A", BattleAction.Flee), Is.True); + object flee = null; + for (int tick = 0; tick < 20; tick++) + { + session.Step(); + flee = ((IDictionary)typeof(BattleSession).GetField("_fleeStages", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session)).Values.Cast().SingleOrDefault(); + if (flee != null && (bool)flee.GetType().GetField("BodyFinished", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(flee)) + break; + } + Assert.That(flee, Is.Not.Null); + Assert.That((bool)flee.GetType().GetField("BodyFinished", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(flee), Is.True); + Invoke(session, "QueuePal3AFormChange", Actor(session, "P"), true, false); + session.Step(); + Assert.That(session.Pal3AForm("P").Pending, Is.True); + Assert.That(session.IsPal3ATransformed("P"), Is.True); + session.Step(); + Assert.That(session.StageTasks.Any(task => task.Owner == "P" && task.Kind == "PAL3A form"), Is.False); + for (int tick = 0; tick < 1200 && session.Status == BattleSessionStatus.Running; tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed), session.Result?.Reason); + Assert.That(session.Result.Escaped, Is.True); + Assert.That(session.Pal3AForm("P").Pending, Is.False); + BattleActorSnapshot pengxu = session.Result.Actors.Single(actor => actor.Id == "P"); + Assert.That((pengxu.Hp, pengxu.MaxHp, pengxu.Attributes[4]), Is.EqualTo((1000, 2000, 101))); + } + + [TestCase(false)] + [TestCase(true)] + public void CancellingFormTaskReleasesOnlyItsAcquiredAbsoluteTime(bool acquired) + { + BattleSession session = Session(); + var handle = (BattleStageHandle)Invoke(session, "QueuePal3AFormChange", Actor(session, "P"), true, false); + if (acquired) + session.Step(); + else + typeof(BattleSession).GetField("_absoluteTimeActor", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(session, "P"); + var scheduler = (BattleStageScheduler)typeof(BattleSession).GetField("_stage", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + Assert.That(scheduler.Cancel(handle), Is.True); + Assert.That(session.Pal3AForm("P").Pending, Is.False); + Assert.That(typeof(BattleSession).GetField("_absoluteTimeActor", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session), Is.EqualTo(acquired ? null : "P")); + Assert.That(scheduler.Cancel(handle), Is.False); + session.Abort(); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "P").MaxHp, Is.EqualTo(2000)); + } + + [Test] + public void StoppingStageReleasesActiveFormOwnershipBeforeTerminalCleanup() + { + BattleSession session = Session(); + Invoke(session, "QueuePal3AFormChange", Actor(session, "P"), true, false); + session.Step(); + Assert.That(session.Pal3AForm("P").Pending, Is.True); + Invoke(session, "StopStage"); + Assert.That(session.Pal3AForm("P").Pending, Is.False); + Assert.That(typeof(BattleSession).GetField("_absoluteTimeActor", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session), Is.Null); + Assert.That(session.StageTasks, Is.Empty); + session.Abort(); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "P").MaxHp, Is.EqualTo(2000)); + } + + [Test] + public void CaptureIntMinForecastUsesSignedNativeAbs() + { + Assert.That(BattlePal3ARules.CanCapture(1, true, true, false, int.MinValue), Is.False); + Assert.That(BattlePal3ARules.CanCapture(int.MinValue, true, true, false, int.MinValue), Is.True); + } + + [Test] + public void OpeningFormsCaptureResourcesAndKeepNativeIdentity() + { + BattleSession session = Session(true, true); + Assert.That(session.Pal3AState.SpiritWheel.Charges, Is.All.Zero); + Assert.That(session.Pal3AForm("A").RoundLimit, Is.EqualTo(9)); + Assert.That(session.Pal3AForm("A").Model, Is.EqualTo("107")); + Assert.That(session.Actors.Single(actor => actor.Id == "A").Attributes[3], Is.EqualTo(200)); + Assert.That(session.Actors.Single(actor => actor.Id == "A").Attributes[4], Is.EqualTo(100)); + Assert.That(session.Actors.Single(actor => actor.Id == "P").Hp, Is.EqualTo(400)); + Assert.That(session.Actors.Single(actor => actor.Id == "P").Attributes[4], Is.EqualTo(202)); + Assert.That(session.Pal3AForm("P").RoundLimit, Is.EqualTo(5)); + Assert.That(session.Pal3AForm("P").Model, Is.EqualTo("106")); + Assert.That(session.CaptureParticipant("P").ActorId, Is.EqualTo(103)); + Assert.That(session.Actors.Single(actor => actor.Id == "P").States.Single(state => state.State == BattleState.Barrier).Permanent, Is.False); + } + + [Test] + public void PengxuMpImmunityPrecedesSavingAndLossAccounting() + { + BattleSession session = Session(pengxu: true); + object actor = Actor(session, "P"); + Assert.That(Invoke(session, "ChangeResource", actor, 2, -1000, null, 0L, "native MP", false), Is.EqualTo(0)); + Assert.That(session.Actors.Single(candidate => candidate.Id == "P").Mp, Is.EqualTo(500)); + Assert.That(session.Pal3AState.MpLoss, Is.Zero); + Assert.That(BattlePal3ARules.PengxuSpellPower(-101, true), Is.EqualTo(-152)); + } + + [TestCase(false)] + [TestCase(true)] + public void CancellingAnActiveTransitionPreservesOnlyEffectsAlreadyApplied(bool modelSwapped) + { + BattleSession session = Session(catalog: new Catalog { FormDuration = 192 }); + Assert.That(session.Submit("A", BattleAction.Transform), Is.True); + session.Step(); + Assert.That(session.Pal3AForm("A").Pending, Is.True); + if (modelSwapped) + for (int step = 0; step < 20 && !session.IsPal3ATransformed("A"); step++) + session.Step(); + Assert.That(session.IsPal3ATransformed("A"), Is.EqualTo(modelSwapped)); + Assert.That(session.CancelAction("A"), Is.True); + Assert.That(session.Pal3AForm("A").Pending, Is.False); + Assert.That(session.StageTasks.Any(task => task.Owner == "A" && task.Kind == "PAL3A form"), Is.False); + long simulationTick = session.SimulationTick; + session.Step(); + Assert.That(session.SimulationTick, Is.EqualTo(simulationTick + 1)); + Assert.That(session.IsPal3ATransformed("A"), Is.EqualTo(modelSwapped)); + Assert.That(session.Pal3AState.SpiritWheel.Charges, Is.All.EqualTo(modelSwapped ? 0 : 3)); + } + + [Test] + public void FirstRepeatInFireBeastFormOnlyInvalidatesAnIncompatibleLastCommand() + { + BattleSession session = Session(nangong: true); + var commands = (IDictionary)typeof(BattleSession).GetField("_aiLastCommands", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + commands[0] = new BattleAiCommand { Kind = 0x105, AbilityId = 301, Source = 0, Target = 5 }; + Assert.That(session.RequestAiRepeat("A"), Is.False); + Assert.That(commands.Contains(0), Is.False); + Assert.That(session.WaitingActor, Is.EqualTo("A")); + Assert.That(session.Inputs.Last().Kind, Is.EqualTo(BattleInputKind.AiRepeat)); + Assert.That(session.RequestAiRepeat("A"), Is.True); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Attack)); + } + + [Test] + public void RepeatChecksTheOtherTransformedRoleBeforeTheActiveController() + { + BattleSession session = Session(nangong: true, pengxu: true); + var commands = (IDictionary)typeof(BattleSession).GetField("_aiLastCommands", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + commands[0] = new BattleAiCommand { Kind = 0x105 }; + commands[2] = new BattleAiCommand { Kind = 0x103 }; + Assert.That(session.WaitingActor, Is.EqualTo("A")); + int count = session.Inputs.Count; + Assert.That(session.RequestAiRepeat("A"), Is.False); + Assert.That(commands.Contains(2), Is.False); + Assert.That(commands.Contains(0), Is.True); + Assert.That(session.Inputs.Count, Is.EqualTo(count + 1)); + Assert.That(session.RequestAiRepeat("A"), Is.False); + Assert.That(session.Inputs.Count, Is.EqualTo(count + 1)); + commands[2] = new BattleAiCommand { Kind = 0x105 }; + Assert.That(session.RequestAiRepeat("A"), Is.False); + Assert.That(commands.Contains(2), Is.True); + Assert.That(commands.Contains(0), Is.False); + Assert.That(session.RequestAiRepeat("A"), Is.True); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Attack)); + } + + [Test] + public void FairyBeastIgnoresNormalAttackShortcutWithoutOverwritingRepeat() + { + BattleSession session = Session(pengxu: true); + Assert.That(session.Submit("A", BattleAction.Defend), Is.True); + Assert.That(session.WaitingActor, Is.EqualTo("P")); + var commands = (IDictionary)typeof(BattleSession).GetField("_aiLastCommands", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + var previous = new BattleAiCommand { Kind = 0x109, Source = 2, Target = -1 }; + commands[2] = previous; + int inputs = session.Inputs.Count; + Assert.That(session.RequestAiNormal("P"), Is.False); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs)); + Assert.That(commands[2], Is.SameAs(previous)); + Assert.That(session.RequestAiRepeat("P"), Is.True); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Defend)); + } + + [Test] + public void FairyBeastRepeatCanFallBackToAiAttackWhileManualAttackIsHidden() + { + BattleSession session = Session(pengxu: true); + Assert.That(session.Submit("A", BattleAction.Defend), Is.True); + Assert.That(session.WaitingActor, Is.EqualTo("P")); + Assert.That(session.Submit("P", BattleAction.Attack, "E"), Is.False); + var commands = (IDictionary)typeof(BattleSession).GetField("_aiLastCommands", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + commands[2] = new BattleAiCommand { Source = 2, Kind = 0x105, AbilityId = 9001, Target = 5 }; + Assert.That(session.RequestAiRepeat("P"), Is.True); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Attack)); + } + + [Test] + public void ReadyFireBeastCannotAcceptCommandsWhileReturningToHumanForm() + { + BattleSession session = Session(nangong: true); + Assert.That(session.WaitingActor, Is.EqualTo("A")); + Invoke(session, "QueuePal3AFormChange", Actor(session, "A"), false, false); + Assert.That(session.WaitingActor, Is.Not.EqualTo("A")); + session.Step(); + Assert.That(session.Pal3AForm("A").Pending, Is.True); + int inputs = session.Inputs.Count; + Assert.That(session.RequestAiNormal("A"), Is.False); + Assert.That(session.CommitAiControl("A", 33), Is.False); + Assert.That(session.Submit("A", BattleAction.Defend), Is.False); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs)); + } + + [Test] + public void ManualNangongTransformationUsesRecordedCommandAndCompletesBodyQueue() + { + BattleSession session = Session(); + Assert.That(session.Submit("A", BattleAction.Transform), Is.True); + for (int tick = 0; tick < 40 && (!session.IsPal3ATransformed("A") || session.Pal3AForm("A").Pending); tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + Assert.That(session.IsPal3ATransformed("A"), Is.True); + Assert.That(session.Pal3AForm("A").Pending, Is.False); + Assert.That(session.Pal3AForm("A").RoundLimit, Is.EqualTo(3)); + Assert.That(session.Inputs.Any(input => input.Action == BattleAction.Transform), Is.True); + } + + [Test] + public void MissingFairyBeastFormActionKeepsSelectedModelClockAndFifoUntilOver() + { + BattleSession session = Session(catalog: new Catalog { MissingFormClip = true }); + object actor = Actor(session, "P"); + Invoke(session, "QueuePal3AFormChange", actor, true, false); + session.Step(); + Assert.That(session.Pal3AForm("P").Kind, Is.EqualTo(BattlePal3AFormKind.PengxuFairyBeast)); + var idle = new BattlePhysicalAnimation("z00", 5, 1, new[] + { + new BattlePhysicalMarker(0, BattlePhysicalMarkerKind.Other, 1, "sound"), + new BattlePhysicalMarker(0, BattlePhysicalMarkerKind.Work, 1, "work") + }, 480); + var binding = (BattleBodyAnimationBinding)Invoke(session, "GetBodyBinding", actor); + binding.TryPlay(idle, true); + binding.Advance(); + Assert.That(binding.PendingMessageCount, Is.EqualTo(2)); + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + Assert.That(binding.CurrentAnimation, Is.SameAs(idle)); + Assert.That(binding.RequestedNativeActionIndex, Is.EqualTo(60)); + Assert.That(binding.GameBoxTime, Is.EqualTo(192u)); + Assert.That(binding.LastPoppedName, Is.EqualTo("sound")); + Assert.That(binding.PendingMessageCount, Is.EqualTo(1)); + Assert.That(session.Pal3AForm("P").Pending, Is.True); + session.Step(); + Assert.That(binding.LastPoppedName, Is.EqualTo("work")); + Assert.That(session.Pal3AForm("P").Pending, Is.True); + for (int tick = 0; tick < 20 && session.Pal3AForm("P").Pending; tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + Assert.That(session.Pal3AForm("P").Pending, Is.False); + Assert.That(binding.CurrentAnimation, Is.SameAs(idle)); + } + + [Test] + public void MissingFormActionWithoutAnExistingModelAnimationCannotInventCompletion() + { + BattleSession session = Session(catalog: new Catalog { MissingFormClip = true }); + Invoke(session, "QueuePal3AFormChange", Actor(session, "P"), true, false); + for (int tick = 0; tick < 200; tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + Assert.That(session.Pal3AForm("P").Kind, Is.EqualTo(BattlePal3AFormKind.PengxuFairyBeast)); + Assert.That(session.Pal3AForm("P").Pending, Is.True); + Assert.That(session.CurrentBodyAnimation("P"), Is.Null); + } + + [Test] + public void NangongLethalHitReturnsHumanAtOneHpInsteadOfDying() + { + BattleSession session = Session(nangong: true); + Invoke(session, "ChangeHp", Actor(session, "A"), -10000, null, 0L, "native lethal", false, false, false); + Assert.That(session.Actors.Single(actor => actor.Id == "A").Hp, Is.EqualTo(1)); + for (int tick = 0; tick < 40 && session.IsPal3ATransformed("A"); tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + Assert.That(session.IsPal3ATransformed("A"), Is.False); + Assert.That(session.Actors.Single(actor => actor.Id == "A").Hp, Is.EqualTo(1)); + Assert.That(session.Pal3AState.HpLoss, Is.EqualTo(10000)); + } + + [TestCase(BattleTargetRange.OpponentSingle)] + [TestCase(BattleTargetRange.OpponentRow)] + public void NangongFireBeastClearsHumanWeaponRangeAndRestoresItOnReturn(BattleTargetRange humanRange) + { + BattleSession session = Session(nangong: true, nangongRange: humanRange); + object actor = Actor(session, "A"); + Assert.That(Invoke(session, "ActionRange", actor, null), Is.EqualTo(BattleTargetRange.OpponentSingle)); + Assert.That(Invoke(session, "CanPal3ASpiritCapture", Actor(session, "E"), actor), Is.False); + var random = (BattleRandom)typeof(BattleSession).GetField("_random", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(session); + Assert.That(random.State, Is.EqualTo(3357800067u), "Fire beast forecast uses cleared single-target flags, without the human weapon's extra row/column roll."); + Invoke(session, "QueuePal3AFormChange", actor, false, false); + for (int tick = 0; tick < 40 && session.IsPal3ATransformed("A"); tick++) + session.Step(); + Assert.That(session.IsPal3ATransformed("A"), Is.False); + Assert.That(Invoke(session, "ActionRange", actor, null), Is.EqualTo(humanRange)); + } + + [Test] + public void PengxuNormalReturnRestoresSavedHpMaximumAndDefense() + { + BattleSession session = Session(pengxu: true); + object actor = Actor(session, "P"); + Invoke(session, "ChangeHp", actor, -100, null, 0L, "native fairy damage", false, false, false); + Invoke(session, "QueuePal3AFormChange", actor, false, false); + for (int tick = 0; tick < 40 && session.IsPal3ATransformed("P"); tick++) + session.Step(); + BattleActorSnapshot restored = session.Actors.Single(candidate => candidate.Id == "P"); + Assert.That(restored.Hp, Is.EqualTo(1000)); + Assert.That(restored.MaxHp, Is.EqualTo(2000)); + Assert.That(restored.Attributes[4], Is.EqualTo(101)); + } + + private sealed class Effects : IBattleEffectDirector, IBattleSpiritCaptureLayout + { + public long Start(BattleEffectRequest request) => 1; + + public bool IsRunning(long handle) => false; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + } + + public BattleSpiritPoint CaptureSpiritOrigin(string actorId, BattleMovementPoint world) => new(400, 300); + + public BattleSpiritRect SpiritWheelTarget(int coreElement) => new(722, 300, 750, 345); + } + + private static BattleSession SkillSession(string variant, BattleAbilityDefinition ability, int guCount = 0, bool boss = false, bool invisible = false, int attackBonus = 0, int defense = 30, int captureHp = 1) + { + bool capture = ability.Id == 4102; + var scenario = new BattleScenario { Variant = variant, Scene = "native", DataFingerprint = "native" }; + var hero = new BattleParticipant + { + InstanceId = "A", + ActorId = capture ? 101 : variant == "PAL3" ? 107 : 103, + AttributeSource = attackBonus == 0 ? BattleAttributeSource.ExplicitEffective : BattleAttributeSource.BaseWithEquipment, + Side = BattleSide.Ally, + Attributes = new[] { 1000, 100, 100, 100, 10, 5, 10, 0, 0, 0, 0, 0 }, + Vitals = new[] { 1000, 100, 100 } + }; + hero.Skills.Add(new BattleSkill { Id = ability.Id, Level = 4, Mastered = true }); + var enemy = new BattleParticipant + { + InstanceId = "E", + ActorId = 7311, + Level = 31, + Side = BattleSide.Enemy, + Attributes = new[] { 99999, 100, 500, 100, defense, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { capture ? captureHp : 99999, 100, 500 } + }; + if (invisible) + enemy.Statuses.Add(new BattleStatus { Id = (int)BattleState.Invisible, Rounds = 5 }); + scenario.Participants.AddRange(new[] { hero, enemy }); + if (guCount > 0) + scenario.Items.Add(new BattleItem { Id = 6113, Count = guCount }); + var definitions = new BattleDefinitions(variant, "native", new[] { ability }, Array.Empty(), new[] + { + new BattleActorDefinition(new BattleActorData + { + InstanceId = "A", Identity = capture ? 0 : variant == "PAL3" ? 3 : 2, + Equipment = attackBonus == 0 ? Array.Empty() : new[] + { + new BattleEquipmentDefinition(new BattleEquipmentData + { + Id = 80001, Slot = 1, Attributes = new[] { new BattleAttributeEffect(3, BattleValueMode.Absolute, attackBonus) } + }) + } + }), + new BattleActorDefinition(new BattleActorData { InstanceId = "E", Boss = boss, PhysicalAttackElementValues = new[] { 1, 2, 0, 0, 1 } }) + }); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new ReadyRules(), definitions, new Effects()); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + + [TestCase(false)] + [TestCase(true)] + public void FullCaptureMatchesNativeStageAndKeepsVisualRngSeparate(bool invisible) + { + var ability = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 4102, + Range = BattleTargetRange.OpponentAll, + Costs = new[] { new BattleCost(1, BattleValueMode.Absolute, 4) } + }); + BattleSession session = SkillSession("PAL3A", ability, invisible: invisible); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 4102)), Is.True); + session.Step(); + Assert.That(session.WasSpiritCaptured("E"), Is.True); + Assert.That(session.SpiritOrbs.Select(orb => orb.Element), Is.EqualTo(new[] { 0, 1, 1, 4 })); + Assert.That(session.SpiritOrbs.Select(orb => orb.Acceleration), Is.EqualTo(new[] { 3.06f, 2.1599998f, 2.76f, 3.46f })); + Assert.That(session.Events.Single(entry => entry.Kind == BattleEventKind.Hit).RandomState, Is.EqualTo(3884216597u)); + for (int tick = 0; tick < 250 && session.Status == BattleSessionStatus.Running; tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed), session.Result?.Reason); + Assert.That(session.Result.Pal3A.SpiritWheel.Charges, Is.EqualTo(new[] { 1, 2, 0, 0, 1 })); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "A").Sp, Is.EqualTo(96)); + } + + [Test] + public void GuardHalvesTheNativeCaptureHpRequestAndKeepsTheSpiritOrbs() + { + var ability = new BattleAbilityDefinition(new BattleAbilityData { Id = 4102, Range = BattleTargetRange.OpponentAll }); + BattleSession session = SkillSession("PAL3A", ability, attackBonus: 400, captureHp: 100); + object enemy = Actor(session, "E"); + enemy.GetType().GetField("Guard").SetValue(enemy, true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 4102)), Is.True); + session.Step(); + + Assert.That(session.Actors.Single(actor => actor.Id == "E").Hp, Is.EqualTo(50)); + Assert.That(session.WasSpiritCaptured("E"), Is.True); + Assert.That(session.SpiritOrbs.Select(orb => orb.Element), Is.EqualTo(new[] { 0, 1, 1, 4 })); + } + + [Test] + public void FullCaptureWithIndefiniteForecastDoesNotFaultOrCapture() + { + var ability = new BattleAbilityDefinition(new BattleAbilityData { Id = 4102, Range = BattleTargetRange.OpponentAll }); + BattleSession session = SkillSession("PAL3A", ability, attackBonus: int.MinValue, defense: 0); + Assert.That(session.Actors.Single(actor => actor.Id == "A").Attributes[3], Is.EqualTo(int.MinValue + 100)); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 4102)), Is.True); + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + Assert.That(session.WasSpiritCaptured("E"), Is.False); + Assert.That(session.SpiritOrbs, Is.Empty); + Assert.That(session.Actors.Single(actor => actor.Id == "E").Hp, Is.EqualTo(1)); + var random = (BattleRandom)typeof(BattleSession).GetField("_random", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + Assert.That(random.State, Is.EqualTo(3357800067u)); + } + + [Test] + public void AlreadyFleeingEnemyIsSkippedBeforeAnyCaptureForecast() + { + var ability = new BattleAbilityDefinition(new BattleAbilityData { Id = 4102, Range = BattleTargetRange.OpponentAll }); + BattleSession session = SkillSession("PAL3A", ability); + object enemy = Actor(session, "E"); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 4102)), Is.True); + enemy.GetType().GetField("EnemyFleeing", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).SetValue(enemy, true); + session.Step(); + Assert.That(session.WasSpiritCaptured("E"), Is.False); + Assert.That(session.SpiritOrbs, Is.Empty); + Assert.That(session.Actors.Single(actor => actor.Id == "E").Hp, Is.EqualTo(1)); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(1u)); + } + + [Test] + public void BossCaptureFailsBeforeForecastRng() + { + var ability = new BattleAbilityDefinition(new BattleAbilityData { Id = 4102, Range = BattleTargetRange.OpponentAll }); + BattleSession session = SkillSession("PAL3A", ability, boss: true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 4102)), Is.True); + session.Step(); + Assert.That(session.WasSpiritCaptured("E"), Is.False); + Assert.That(session.SpiritOrbs, Is.Empty); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(1u)); + } + + [TestCase(true, false, true, true, 3884216597u)] + [TestCase(false, false, true, false, 3357800067u)] + [TestCase(true, true, false, true, 1924036713u)] + public void CaptureUsesPrimaryOffenseLevelRangeAndEnemyDefense(bool strongPrimary, bool primaryRow, bool enemyRow, bool captured, uint randomState) + { + var ability = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 4102, + Range = BattleTargetRange.OpponentAll, + Costs = new[] { new BattleCost(1, BattleValueMode.Absolute, 4) } + }); + var scenario = new BattleScenario { Variant = "PAL3A", Scene = "native", DataFingerprint = "native" }; + var primary = new BattleParticipant + { + InstanceId = "A", + ActorId = 101, + Side = BattleSide.Ally, + Level = 20, + Attributes = new[] { 1000, 100, 100, strongPrimary ? 500 : 20, strongPrimary ? 30 : 100, 5, 10, 0, 0, 0, 0, 0 }, + Vitals = new[] { 1000, 100, 100 } + }; + primary.Skills.Add(new BattleSkill { Id = 4102, Level = 4, Mastered = true }); + scenario.Participants.Add(primary); + scenario.Participants.Add(new BattleParticipant + { + InstanceId = "E", + ActorId = 7311, + Side = BattleSide.Enemy, + Level = 50, + Attributes = new[] { 1000, 100, 100, strongPrimary ? 20 : 500, strongPrimary ? 100 : 30, 5, 10, 0, 0, 0, 0, 0 }, + Vitals = new[] { 100, 100, 100 } + }); + var definitions = new BattleDefinitions("PAL3A", "native", new[] { ability }, Array.Empty(), new[] + { + new BattleActorDefinition(new BattleActorData + { + InstanceId = "A", Identity = 0, + NormalAttackRange = primaryRow ? BattleTargetRange.OpponentRow : BattleTargetRange.OpponentSingle + }), + new BattleActorDefinition(new BattleActorData + { + InstanceId = "E", PhysicalAttackElementValues = new[] { 1, 2, 0, 0, 1 }, + NormalAttackRange = enemyRow ? BattleTargetRange.OpponentRow : BattleTargetRange.OpponentSingle + }) + }); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new ReadyRules(), definitions, new Effects()); + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, abilityId: 4102)), Is.True); + session.Step(); + Assert.That(session.WasSpiritCaptured("E"), Is.EqualTo(captured)); + Assert.That(session.SpiritOrbs.Count, Is.EqualTo(captured ? 4 : 0)); + Assert.That(session.Events.Single(entry => entry.Kind == BattleEventKind.ResourceChanged && entry.Resource == 1).RandomState, Is.EqualTo(randomState)); + } + + [TestCase("PAL3", 4401)] + [TestCase("PAL3A", 4304)] + public void GuCostUsesActualItem6113InventoryAndThreeAndAHalfSecondPopup(string variant, int id) + { + var ability = new BattleAbilityDefinition(new BattleAbilityData + { + Id = id, + Range = BattleTargetRange.OpponentSingle, + Costs = new[] { new BattleCost(1, BattleValueMode.Absolute, 5), new BattleCost(16, BattleValueMode.Absolute, 1) } + }); + BattleSession session = SkillSession(variant, ability, 99); + var command = new BattleCommand("A", BattleAction.Skill, "E", id); + BattleCostEstimate estimate = session.GetCostEstimate(command).Single(cost => cost.Resource == 16); + Assert.That(estimate.Available, Is.EqualTo(99)); + Assert.That(estimate.Payable, Is.EqualTo(1)); + Assert.That(session.Submit(command), Is.True); + session.Step(); + Assert.That(session.Inventory.Single(item => item.Id == 6113).Count, Is.EqualTo(98)); + BattleEvent number = session.Events.Single(entry => entry.Kind == BattleEventKind.NumberShown && entry.Resource == 16); + Assert.That(number.DurationSeconds, Is.EqualTo(3.5f)); + Assert.That(number.RequestedDelta, Is.EqualTo(-1)); + BattleSession empty = SkillSession(variant, ability); + Assert.That(empty.CanSubmit(command), Does.Contain("Resource 16")); + } + + [Test] + public void OrbPositionMatchesOneHundredNativeUiFrames() + { + var orb = new BattleSpiritOrb(new BattleSpiritPoint(0, 0), new BattleSpiritRect(5980, 7980, 6020, 8020), 3.06f); + orb.Advance(.02f); + Assert.That(orb.Position.X, Is.Zero); + Assert.That(orb.Position.Y, Is.Zero); + for (int frame = 1; frame < 50; frame++) + orb.Advance(.02f); + Assert.That(orb.Position.X, Is.EqualTo(156)); + Assert.That(orb.Position.Y, Is.EqualTo(217)); + for (int frame = 50; frame < 100; frame++) + orb.Advance(.02f); + Assert.That(orb.Position.X, Is.EqualTo(3663)); + Assert.That(orb.Position.Y, Is.EqualTo(4903)); + } + + [Test] + public void VictoryRestoresBothHeroFormsBeforeSettlement() + { + BattleSession session = Session(nangong: true, pengxu: true); + Invoke(session, "ChangeHp", Actor(session, "E"), -1000000, null, 0L, "native victory", false, false, false); + for (int tick = 0; tick < 250 && session.Status == BattleSessionStatus.Running; tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed), session.Result?.Reason); + Assert.That(session.IsPal3ATransformed("A"), Is.False); + Assert.That(session.IsPal3ATransformed("P"), Is.False); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "P").Hp, Is.EqualTo(1000)); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "P").MaxHp, Is.EqualTo(2000)); + } + + [Test] + public void BeastCommandGateMatchesNativeMenuMatrix() + { + BattleSession session = Session(nangong: true, pengxu: true); + var magic = new BattleAbilityDefinition(new BattleAbilityData { Id = 301, IsMagic = true }); + var technique = new BattleAbilityDefinition(new BattleAbilityData { Id = 4101 }); + foreach (string id in new[] { "A", "P" }) + { + object actor = Actor(session, id); + Assert.That(Invoke(session, "ValidatePal3AFormCommand", actor, new BattleCommand(id, BattleAction.Defend), null, false), Is.Null); + Assert.That(Invoke(session, "ValidatePal3AFormCommand", actor, new BattleCommand(id, BattleAction.Item), null, false), Is.Not.Null); + Assert.That(Invoke(session, "ValidatePal3AFormCommand", actor, new BattleCommand(id, BattleAction.Flee), null, false), Is.Null); + Assert.That(Invoke(session, "ValidatePal3AFormCommand", actor, new BattleCommand(id, BattleAction.Skill, abilityId: 4101), technique, false), Is.Not.Null); + } + Assert.That(Invoke(session, "ValidatePal3AFormCommand", Actor(session, "A"), new BattleCommand("A", BattleAction.Attack), null, false), Is.Null); + Assert.That(Invoke(session, "ValidatePal3AFormCommand", Actor(session, "A"), new BattleCommand("A", BattleAction.Skill, abilityId: 301), magic, false), Is.Not.Null); + Assert.That(Invoke(session, "ValidatePal3AFormCommand", Actor(session, "P"), new BattleCommand("P", BattleAction.Attack), null, false), Is.Not.Null); + Assert.That(Invoke(session, "ValidatePal3AFormCommand", Actor(session, "P"), new BattleCommand("P", BattleAction.Skill, abilityId: 301), magic, false), Is.Null); + } + + [TestCase(0, 3, false)] + [TestCase(1, 3, false)] + [TestCase(2, 3, true)] + [TestCase(3, 5, false)] + [TestCase(4, 5, true)] + [TestCase(8, 9, true)] + public void FormRoundLimitUsesNativePreincrementBoundary(int completed, int limit, bool expired) + => Assert.That(BattlePal3ARules.ExpiresOnRound(completed, limit), Is.EqualTo(expired)); + + [Test] + public void LiaoRiCarryAppliesOnlyOnceToOriginalActor722() + { + var scenario = new BattleScenario { Variant = "PAL3A", Scene = "native", DataFingerprint = "native" }; + scenario.Pal3A.PreserveLiaoRiLosses = true; + scenario.Pal3A.HpLoss = 1000; + scenario.Pal3A.MpLoss = 700; + scenario.Participants.AddRange(new[] + { + new BattleParticipant { InstanceId = "A", ActorId = 101, Side = BattleSide.Ally, Attributes = new[] { 1000, 100, 100, 100, 10, 5, 10, 0, 0, 0, 0, 0 }, Vitals = new[] { 1000, 100, 100 } }, + new BattleParticipant { InstanceId = "E", ActorId = 722, Side = BattleSide.Enemy, Attributes = new[] { 30000, 0, 3500, 1100, 450, 7, 10, 0, 6, 0, 3, 0 }, Vitals = new[] { 30000, 0, 3500 } } + }); + var definitions = new BattleDefinitions("PAL3A", "native", Array.Empty(), Array.Empty(), new[] + { + new BattleActorDefinition(new BattleActorData { InstanceId = "A", Identity = 0 }), + new BattleActorDefinition(new BattleActorData { InstanceId = "E", Boss = true }) + }); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new ReadyRules(), definitions); + Assert.That(session.Actors.Single(actor => actor.Id == "E").MaxHp, Is.EqualTo(31000)); + Assert.That(session.Actors.Single(actor => actor.Id == "E").MaxMp, Is.EqualTo(4200)); + Assert.That(session.Pal3AState.PreserveLiaoRiLosses, Is.False); + Invoke(session, "ApplyPal3ALiaoRiCarry", Actor(session, "E")); + Assert.That(session.Actors.Single(actor => actor.Id == "E").MaxHp, Is.EqualTo(31000)); + Assert.That(scenario.Participants.Single(actor => actor.InstanceId == "E").Attributes[0], Is.EqualTo(30000)); + } + + } +} diff --git a/Assets/Tests/Battle/Editor/BattlePal3AFormRulesTests.cs.meta b/Assets/Tests/Battle/Editor/BattlePal3AFormRulesTests.cs.meta new file mode 100644 index 00000000..b2edae42 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattlePal3AFormRulesTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f50a30b98cc54c498993ad7a1b2e4e29 diff --git a/Assets/Tests/Battle/Editor/BattlePal3ARemainingSkillsTests.cs b/Assets/Tests/Battle/Editor/BattlePal3ARemainingSkillsTests.cs new file mode 100644 index 00000000..1eaaf7a2 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattlePal3ARemainingSkillsTests.cs @@ -0,0 +1,206 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Battle; + using NUnit.Framework; + + public sealed class BattlePal3ARemainingSkillsTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings + { + public AttackTiming Attack(string source, string target) => new(0, 3, new[] { 1 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 3, new[] { 1 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 1000; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "S" ? 4 : actor == "T" ? 0 : 6; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class ReadyRules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => actor.InstanceId == "S" ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => 0; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => new(-1, false, false); + } + + private static BattleAbilityData Ability(int id) => id switch + { + 205 or 273 => new BattleAbilityData + { + Id = id, + IsMagic = true, + SkillTypeId = 1, + Handler = BattleSpecialHandler.GenericOnly, + SpecialEffect = id == 273 ? 35 : 0, + Range = id == 205 ? BattleTargetRange.OpponentSingle : BattleTargetRange.OpponentAll, + Costs = new[] { new BattleCost(2, BattleValueMode.Absolute, id == 205 ? 3 : 30) } + }, + 4503 => new BattleAbilityData + { + Id = id, + SuccessRate = 50, + Range = BattleTargetRange.OwnSingle, + States = new[] { new BattleStatusEffect(BattleState.Death, true) }, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Percentage, 100), new BattleAttributeEffect(2, BattleValueMode.Percentage, 100) }, + Costs = new[] { new BattleCost(1, BattleValueMode.Absolute, 30) } + }, + 4505 => new BattleAbilityData + { + Id = id, + SuccessRate = 50, + Range = BattleTargetRange.OpponentSingle, + SpecialEffect = 37, + Handler = BattleSpecialHandler.GenericOnly, + States = new[] { new BattleStatusEffect(BattleState.Death, false) }, + Costs = new[] { new BattleCost(1, BattleValueMode.Absolute, 25) } + }, + 4507 => new BattleAbilityData + { + Id = id, + SuccessRate = 100, + Range = BattleTargetRange.OpponentAll, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -1000) }, + Costs = new[] { new BattleCost(1, BattleValueMode.Absolute, 60), new BattleCost(0, BattleValueMode.Percentage, 50) } + }, + _ => throw new ArgumentOutOfRangeException(nameof(id)) + }; + + private static BattleParticipant Participant(string id, BattleSide side, int hp) => new() + { + InstanceId = id, + ActorId = id == "S" ? 107 : side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = id == "S" ? BattleSlot.Water : id == "T" ? BattleSlot.Fire : BattleSlot.Earth, + Level = 10, + Attributes = new[] { 5000, 100, 200, 10, 10, 3, id == "S" ? 9999 : 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { hp, 100, id == "T" ? 0 : 200 } + }; + + private static BattleSession Session(int id, int seed = 1, bool boss = false, bool targetAlly = false, int sourceHp = 1000, int targetHp = 5000) + { + var scenario = new BattleScenario { Variant = "PAL3A", Scene = "portable", DataFingerprint = "remaining-skills", Seed = seed }; + BattleParticipant source = Participant("S", BattleSide.Ally, sourceHp); + source.Skills.Add(new BattleSkill { Id = id, Level = 4, Mastered = true }); + scenario.Participants.Add(source); + scenario.Participants.Add(Participant("T", targetAlly ? BattleSide.Ally : BattleSide.Enemy, targetHp)); + scenario.Participants.Add(Participant("E", BattleSide.Enemy, 5000)); + var definitions = new BattleDefinitions("PAL3A", "remaining-skills", new[] { new BattleAbilityDefinition(Ability(id)) }, Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId == "S" ? 4 : actor.Side == BattleSide.Ally ? 0 : -1, + Boss = boss && actor.InstanceId == "T", + Equipment = actor.InstanceId == "S" ? new[] { new BattleEquipmentDefinition(new BattleEquipmentData { Id = 1, Slot = 4, TechniqueSuccessBonus = 500 }) } : Array.Empty() + }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new ReadyRules(), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + session.SetAutomatic(BattleSide.Ally, false); + return session; + } + + private static BattleActorSnapshot Actor(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + private static object MutableActor(BattleSession session, string id) => ((IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(session))[id]; + + private static void Resolve(BattleSession session, int id) + { + Assert.That(session.Submit(new BattleCommand("S", BattleAction.Skill, "T", id)), Is.True); + int limit = 400; + while (session.Status == BattleSessionStatus.Running && Actor(session, "S").CurrentAction != null && limit-- > 0) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + } + + [TestCase(4503, 1, true)] + [TestCase(4503, 200, false)] + [TestCase(4505, 1, true)] + [TestCase(4505, 200, false)] + public void LiteralFiftyPercentIgnoresLuckAndEquipmentAndConsumesOneDraw(int id, int seed, bool succeeds) + { + BattleSession session = Session(id, seed, targetAlly: id == 4503, targetHp: id == 4503 ? 0 : 5000); + Resolve(session, id); + uint expectedSeed = unchecked((uint)seed * 214013 + 2531011); + BattleEvent payment = session.Events.Single(entry => entry.Source == "S" && entry.Detail == "skill cost " + id && entry.Resource == 1); + Assert.That(payment.RandomState, Is.EqualTo(expectedSeed)); + Assert.That(Actor(session, "S").Sp, Is.EqualTo(id == 4503 ? 70 : 75)); + Assert.That(Actor(session, "T").Hp, Is.EqualTo(id == 4503 ? succeeds ? 5000 : 0 : succeeds ? 0 : 5000)); + if (id == 4503) + Assert.That(Actor(session, "T").Mp, Is.EqualTo(succeeds ? 200 : 0)); + } + + [TestCase(1)] + [TestCase(200)] + public void DeathSkillRejectsBossBeforeDrawingOrApplyingDeathButStillPaysSp(int seed) + { + BattleSession session = Session(4505, seed, boss: true); + Resolve(session, 4505); + Assert.That(Actor(session, "T").Hp, Is.EqualTo(5000)); + Assert.That(Actor(session, "S").Sp, Is.EqualTo(75)); + Assert.That(session.Events.Single(entry => entry.Detail.StartsWith("original boss restriction", StringComparison.Ordinal)).RandomState, Is.EqualTo(unchecked((uint)seed))); + Assert.That(session.Events.Single(entry => entry.Source == "S" && entry.Detail == "skill cost 4505").RandomState, Is.EqualTo(unchecked((uint)seed))); + } + + [TestCase(49, false)] + [TestCase(50, true)] + [TestCase(51, true)] + [TestCase(1000, true)] + public void HpCostEligibilityAndPaymentUseFiftyAbsoluteHpInsteadOfHalfCurrentHp(int hp, bool allowed) + { + BattleSession session = Session(4507, sourceHp: hp); + var command = new BattleCommand("S", BattleAction.Skill, "T", 4507); + BattleCostEstimate cost = session.GetCostEstimate(command).Single(value => value.Resource == 0); + Assert.That(cost.Required, Is.EqualTo(50)); + Assert.That(cost.Payable, Is.EqualTo(50)); + Assert.That(session.CanSubmit(command) == null, Is.EqualTo(allowed)); + if (!allowed) + return; + Resolve(session, 4507); + Assert.That(Actor(session, "S").Hp, Is.EqualTo(Math.Max(0, hp - 50))); + Assert.That(Actor(session, "S").Sp, Is.EqualTo(40)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Interrupted && entry.Source == "S"), Is.False); + Assert.That(Actor(session, "S").Pose, Is.Not.EqualTo(BattlePose.Hurt)); + Assert.That(session.Events.Count(entry => entry.Detail == "skill cost 4507" && entry.Resource == 0), Is.EqualTo(1)); + } + + [TestCase(205, 197)] + [TestCase(273, 170)] + public void EmptyMagicRecordsOnlyPayTheirOriginalCostAndImproveProficiency(int id, int expectedMp) + { + BattleSession session = Session(id); + Resolve(session, id); + Assert.That(Actor(session, "T").Hp, Is.EqualTo(5000)); + Assert.That(Actor(session, "E").Hp, Is.EqualTo(5000)); + Assert.That(Actor(session, "S").Mp, Is.EqualTo(expectedMp)); + Assert.That(Actor(session, "S").Skills.Single().Uses, Is.EqualTo(1)); + Assert.That(session.Events.Any(entry => entry.Target is "T" or "E" && entry.Kind is BattleEventKind.Hit or BattleEventKind.StatusAdded or BattleEventKind.StatusRemoved), Is.False); + } + + [TestCase("PAL3A", 205, true, 0, BattleSpecialHandler.GenericOnly)] + [TestCase("PAL3A", 273, true, 35, BattleSpecialHandler.GenericOnly)] + [TestCase("PAL3A", 4505, false, 37, BattleSpecialHandler.GenericOnly)] + [TestCase("PAL3", 205, true, 0, BattleSpecialHandler.None)] + [TestCase("PAL3A", 274, true, 35, BattleSpecialHandler.None)] + public void VerifiedEmptyAndMarkerRecordsDoNotInventSpecialEffects(string variant, int id, bool magic, int special, BattleSpecialHandler expected) + { + Assert.That(BattleSpecialRules.AbilityHandler(variant, id, false, magic, special), Is.EqualTo(expected)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattlePal3ARemainingSkillsTests.cs.meta b/Assets/Tests/Battle/Editor/BattlePal3ARemainingSkillsTests.cs.meta new file mode 100644 index 00000000..cadfba09 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattlePal3ARemainingSkillsTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 69ae647aeb9b4bfd8d8f05aa55998366 diff --git a/Assets/Tests/Battle/Editor/BattlePhysicalPresentationTests.cs b/Assets/Tests/Battle/Editor/BattlePhysicalPresentationTests.cs new file mode 100644 index 00000000..d7cdbcaa --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattlePhysicalPresentationTests.cs @@ -0,0 +1,829 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattlePhysicalPresentationTests + { + private sealed class Catalog : IBattleCatalog, IBattleStageGeometry, IBattlePhysicalTimings, IBattleAbilityTimings, IBattleAbilityEffects, IBattleAbilityBodyAnimations + { + internal readonly BattleScenario Scenario; + internal readonly Dictionary Profiles = new(); + internal int AbilityBodyTicks = 200; + internal float AbilityWorkSeconds; + internal int AbilityEffectGroup = -1; + internal bool AbilityMoves; + + internal Catalog(BattleScenario scenario, bool thrown = false) + { + Scenario = scenario; + foreach (BattleParticipant actor in scenario.Participants) + { + var animations = Enum.GetValues(typeof(BattlePose)).Cast().ToDictionary(pose => pose, + pose => new BattlePhysicalAnimation(pose.ToString(), 5, 10, pose == BattlePose.Attacking ? new[] { new BattlePhysicalMarker(2, BattlePhysicalMarkerKind.Work) } : null, 480)); + Profiles.Add(actor.InstanceId, new BattlePhysicalStageProfile(scenario.Variant, actor.ActorId, + actor.Side == BattleSide.Ally ? actor.InstanceId == "A" ? 0 : 1 : -1, thrown && actor.InstanceId == "A" ? 2 : 1, 1, animations, + thrownStart: new BattlePhysicalAnimation("z021", 5, 10, new[] { new BattlePhysicalMarker(2, BattlePhysicalMarkerKind.Throwed) }, 480), + thrownReturn: new BattlePhysicalAnimation("z022", 5, 10, new[] { new BattlePhysicalMarker(2, BattlePhysicalMarkerKind.Catched) }, 480))); + } + } + + public BattlePhysicalStageProfile Physical(string actor) => Profiles[actor]; + + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 99; // native binding must finish on Over, independent of this estimate + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "A" ? 0 : actor == "B" ? 1 : 5; + + public int DamageDivisor(string actor) => 1; + + public BattleMovementPoint InitialHome(string actor) => actor == "A" ? new(0, 0, 0) : actor == "B" ? new(100, 0, 0) : new(Scenario.Participants.Count == 2 ? 100 : 200, 0, 0); + + public BattleMovementPoint FormationHome(string actor, BattleSlot slot) => InitialHome(actor); + + public BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint sourceHome, BattleMovementPoint targetHome) => new(Attack(source, target), sourceHome, sourceHome, targetHome); + + public IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint from, BattleMovementPoint to, bool midpoint) => new[] { new BattleMovementPlan(BattleMovementKind.Run, from, to) }; + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, AbilityBodyTicks, new[] { 0 }, bodyAnimationTicks: AbilityBodyTicks); + + public BattleAbilityStageProfile AbilityStage(string actor, BattleAbilityDefinition ability) => new(BattleAbilityStageKind.Skill, + new BattleAbilityEffectBinding(AbilityEffectGroup, 0, 0), new BattleAbilityEffectBinding(-1, 0, 0), AbilityWorkSeconds, BattleAbilityWorkBoundary.WorkTime, AbilityBodyTicks, true, + AbilityMoves ? BattleMovementKind.Run : null, AbilityMoves ? BattleMovementKind.Run : null); + + public IReadOnlyList AbilityMovement(BattleActorSnapshot actor, BattleActorSnapshot target, BattleAbilityDefinition ability, + BattleDefinitions definitions, bool returning) => new[] { new BattleMovementPlan(BattleMovementKind.Run, actor.Position, actor.Home) }; + + public BattlePhysicalAnimation AbilityBody(string actor, BattleAbilityDefinition ability) => new("skill-long", AbilityBodyTicks, 10, gameBoxDuration: checked((uint)AbilityBodyTicks * 96)); + + public int? AbilityNativeAction(string actor, BattleAbilityDefinition ability) => 35; + + public BattlePhysicalAnimation AbilityMovementBody(string actor, BattleAbilityDefinition ability, BattleMovementKind kind, bool returning) => + Physical(actor).Animation(BattlePose.Moving); + } + + private sealed class Rules : IBattleRules + { + internal readonly Dictionary InitialGauges = new(); + internal int GaugeIncrement; + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + InitialGauges.GetValueOrDefault(actor.InstanceId, BattleSession.FullGauge); + + public int GaugePerStep(BattleParticipant actor) => GaugeIncrement; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => new(-10, false, false); + } + + private sealed class Effects : IBattleEffectDirector, IBattleModalEffects + { + internal readonly List Started = new(); + internal readonly List Stopped = new(); + internal bool KeepRunning; + + public bool BlocksBattleTime + { + get; set; + } + + public bool SkipModalPresentation() + { + if (!BlocksBattleTime) + return false; + BlocksBattleTime = false; + return true; + } + + private readonly HashSet _running = new(); + private long _nextHandle; + + public long Start(BattleEffectRequest request) + { + Started.Add(request); + long handle = ++_nextHandle; + if (KeepRunning) + _running.Add(handle); + return handle; + } + + public bool IsRunning(long handle) => _running.Contains(handle); + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + Stopped.Add(handle); + _running.Remove(handle); + } + } + + private static BattleSession Session(string variant, out Catalog catalog, bool party = false, bool thrown = false, bool skill = false, + IBattleEffectDirector effects = null, Action configure = null, Rules rules = null, + BattleTargetRange enemyNormalRange = BattleTargetRange.OpponentSingle) + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "physical-native", Seed = 1 }; + scenario.Participants.Add(Participant("A", 101, BattleSide.Ally, BattleSlot.Center)); + if (party) + scenario.Participants.Add(Participant("B", 102, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(Participant("E", 701, BattleSide.Enemy, BattleSlot.Water)); + BattleAbilityDefinition ability = null; + if (skill) + { + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 4201, Mastered = true, Level = 4 }); + ability = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 4201, + Name = "native role ownership", + SuccessRate = 100, + Range = BattleTargetRange.OpponentSingle, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -1) } + }); + } + configure?.Invoke(scenario); + catalog = new Catalog(scenario, thrown); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, ability == null ? Array.Empty() : new[] { ability }, Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId == "A" ? 0 : actor.InstanceId == "B" ? 1 : -1, + NormalAttackMode = 924, + NormalAttackRange = actor.Side == BattleSide.Enemy ? enemyNormalRange : BattleTargetRange.OpponentSingle + }))); + var session = new BattleSession(new BattleSetup(scenario), catalog, rules ?? new Rules(), definitions, effects); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + + private static BattleParticipant Participant(string id, int resource, BattleSide side, BattleSlot slot) => new() + { + InstanceId = id, + ActorId = resource, + Side = side, + Slot = slot, + Attributes = new[] { 500, 100, 200, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 10, 0 } + }; + + private static object Actor(BattleSession session, string id) => ((IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session))[id]; + + private static object Invoke(BattleSession session, string method, params object[] args) + { + MethodInfo member = typeof(BattleSession).GetMethod(method, BindingFlags.Instance | BindingFlags.NonPublic); + object[] supplied = args.Concat(member.GetParameters().Skip(args.Length).Select(parameter => + parameter.IsOptional ? parameter.DefaultValue : throw new ArgumentException("A required private test argument is missing."))).ToArray(); + return member.Invoke(session, supplied); + } + + private static BattleActorSnapshot Snapshot(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + private static void Steps(BattleSession session, int count) + { + for (int index = 0; index < count; index++) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + } + + [TestCase("PAL3", BattleTargetRange.OpponentAll)] + [TestCase("PAL3A", BattleTargetRange.OpponentAll)] + [TestCase("PAL3A", BattleTargetRange.OpponentRow)] + public void EnemyMultiTargetAttackSettlesAtAnUnsetSceneElement(string variant, BattleTargetRange range) + { + var rules = new Rules(); + rules.InitialGauges["A"] = rules.InitialGauges["B"] = 0; + BattleSession session = Session(variant, out _, party: true, rules: rules, enemyNormalRange: range, + configure: scenario => scenario.Participants.Single(actor => actor.InstanceId == "B").Slot = BattleSlot.Fire); + var command = new BattleCommand("E", BattleAction.Attack, "A"); + Assert.That(session.GetPotentialAffectedTargets(command).Select(actor => actor.Id), Is.EquivalentTo(new[] { "A", "B" })); + Assert.That(session.Submit(command), Is.True); + Steps(session, 250); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded && entry.Source == "E"), Is.True); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void FormationCannotChangeWhileTheModalFrameIsSuspended(string variant) + { + var effects = new Effects(); + BattleSession session = Session(variant, out _, party: true, effects: effects); + Assert.That(session.BeginFormation("A"), Is.True); + effects.BlocksBattleTime = true; + session.Step(); + Assert.That(session.SwapFormation("B", BattleSlot.Fire), Is.False); + Assert.That(session.EndFormation("A"), Is.False); + Assert.That(session.SkipModalPresentation(), Is.True); + Assert.That(session.IsModalPresentation, Is.False); + Assert.That(session.SwapFormation("B", BattleSlot.Fire), Is.False); + Assert.That(session.EndFormation("A"), Is.False); + session.Step(); + Assert.That(session.SwapFormation("B", BattleSlot.Fire), Is.True); + Assert.That(session.EndFormation("A"), Is.True); + } + + [TestCase("formation")] + [TestCase("protection")] + [TestCase("sleep")] + [TestCase("paralysis")] + public void Pal3AFiveSpiritFieldCountsTheAnchorsSpentTurn(string operation) + { + BattleSession session = Session("PAL3A", out _, party: true, configure: scenario => + { + scenario.FiveSpiritElement = 1; + scenario.FiveSpiritForce = 2; + if (operation is "sleep" or "paralysis") + scenario.Participants[0].Statuses.Add(new BattleStatus + { + Id = (int)(operation == "sleep" ? BattleState.Sleep : BattleState.Paralysis), + Rounds = 8 + }); + }); + // Set up the fifth native turn and check each public dispatch path independently. + typeof(BattleSession).GetField("_fiveSpiritRounds", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(session, 4); + switch (operation) + { + case "formation": + Assert.That(session.BeginFormation("A"), Is.True); + Assert.That(session.EndFormation("A"), Is.True); + Assert.That(session.FiveSpiritElement, Is.EqualTo(1)); + Assert.That(session.BeginFormation("A"), Is.True); + Assert.That(session.SwapFormation("B", BattleSlot.Fire), Is.True); + Assert.That(session.EndFormation("A"), Is.True); + break; + case "protection": + Assert.That(session.SetProtection("A", "B"), Is.True); + break; + default: + Steps(session, 1); + break; + } + Assert.That(session.FiveSpiritElement, Is.Zero); + Assert.That(session.FiveSpiritForce, Is.Zero); + } + + private sealed class BodyReservation : IBattleStageJob + { + internal BattleSession Session; + internal object Actor; + internal bool Release; + internal long ReleasedTick; + + public bool Advance(BattleStageContext context) + { + if (!Release) + return false; + Invoke(Session, "ReleaseStageBody", Actor, context.Handle); + ReleasedTick = context.Tick; + return true; + } + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AttackUsesNativeSpeedAndCurrentClipRadiusThenReturnsHome(string variant) + { + BattleSession session = Session(variant, out _); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Attack, "E")), Is.True); + Steps(session, 1); + Assert.That(Snapshot(session, "A").Position.X, Is.EqualTo(7.6f)); + Steps(session, 10); + Assert.That(Snapshot(session, "A").Position.X, Is.EqualTo(80f)); + Steps(session, 30); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Hit && entry.Target == "E"), Is.EqualTo(1)); + Assert.That(Snapshot(session, "A").Position.X, Is.Zero); + Assert.That(Snapshot(session, "A").CurrentAction, Is.Null); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Idle")); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RoundLimitKeepsItsVictoryReasonWhenAnActiveAttackKillsTheLastAlly(string variant) + { + var rules = new Rules { GaugeIncrement = 1 }; + rules.InitialGauges.Add("A", 0); + rules.InitialGauges.Add("C", BattleSession.FullGauge - 1); + BattleSession session = Session(variant, out Catalog catalog, rules: rules, configure: scenario => + { + scenario.RoundLimit = 1; + scenario.Participants[0].Vitals[0] = 1; + scenario.Participants.Add(Participant("C", 702, BattleSide.Enemy, BattleSlot.Center)); + }); + Assert.That(session.Submit("E", BattleAction.Attack, "A"), Is.True); + Steps(session, 1); + Assert.That(session.BossRounds, Is.EqualTo(1)); + Assert.That(session.IsResolvingOutcome, Is.True); + Assert.That(Snapshot(session, "A").Hp, Is.EqualTo(1)); + + Steps(session, 200); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.PreSettlementActors.Single(actor => actor.Id == "A").Hp, Is.Zero); + Assert.That(session.Result.PreSettlementActors.Where(actor => actor.Side == BattleSide.Enemy).All(actor => actor.Alive), Is.True); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + Assert.That(session.Result.Reason, Is.EqualTo("original boss round limit reached")); + + BattleSession replay = BattleReplay.Play(new BattleSetup(catalog.Scenario), new Catalog(catalog.Scenario), + session.Inputs, session.Tick, rules, session.Definitions); + Assert.That(replay.Result.Winner, Is.EqualTo(session.Result.Winner)); + Assert.That(replay.Result.Reason, Is.EqualTo(session.Result.Reason)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void CancellingAnAttackApproachRestoresHomeAndReplaysTheNextEnemyHit(string variant) + { + BattleSession session = Session(variant, out Catalog catalog); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + Steps(session, 4); + Assert.That(Snapshot(session, "A").Position.X, Is.GreaterThan(13)); + Assert.That(session.CancelAction("A"), Is.True); + Assert.That(Snapshot(session, "A").Movement, Is.Null); + Assert.That(Snapshot(session, "A").Position, Is.EqualTo(Snapshot(session, "A").Home)); + + Assert.That(session.Submit("E", BattleAction.Attack, "A"), Is.True); + Steps(session, 200); + Assert.That(Snapshot(session, "A").Hp, Is.LessThan(500)); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "E" && entry.Target == "A"), Is.EqualTo(1)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "A"), Is.False); + + BattleSession replay = BattleReplay.Play(new BattleSetup(catalog.Scenario), new Catalog(catalog.Scenario), + session.Inputs, session.Tick, new Rules(), session.Definitions); + Assert.That(Snapshot(replay, "A").Position, Is.EqualTo(Snapshot(session, "A").Position)); + Assert.That(Snapshot(replay, "A").Hp, Is.EqualTo(Snapshot(session, "A").Hp)); + Assert.That(replay.Events.Select(entry => (entry.Tick, entry.Kind, entry.RandomState, entry.ActualDelta)), + Is.EqualTo(session.Events.Select(entry => (entry.Tick, entry.Kind, entry.RandomState, entry.ActualDelta)))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void CancellingAnActionWaitingForAnotherStageLeavesThatStagesBodyInPlace(string variant) + { + BattleSession session = Session(variant, out _, skill: true); + object actor = Actor(session, "A"); + var scheduler = (BattleStageScheduler)typeof(BattleSession).GetField("_stage", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + BattleStageHandle owner = scheduler.Add("A", "existing normal grab", new BodyReservation { Session = session, Actor = actor }, 0); + Assert.That(Invoke(session, "TryGrabStageBody", actor, owner), Is.True); + var position = new BattleMovementPoint(30, 0, 0); + session.SetEffectActorPosition("A", position); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + Steps(session, 1); + + Assert.That(session.CancelAction("A"), Is.True); + Assert.That(Snapshot(session, "A").Position, Is.EqualTo(position)); + Assert.That(Invoke(session, "OwnsStageBody", actor, owner), Is.True); + Assert.That(session.StageTasks.Single().Handle, Is.EqualTo(owner)); + } + + [TestCase("PAL3", 6)] + [TestCase("PAL3A", 7)] + public void IdleActorBlockFinishesOnNativeOverInsteadOfCatalogHurtEstimate(string variant, int endPass) + { + BattleSession session = Session(variant, out _); + Invoke(session, "PushBodyBlock", Actor(session, "A"), false); + Steps(session, 1); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Hurt")); + Assert.That(Snapshot(session, "A").NativeAnimationSeconds, Is.EqualTo(62 / 4800d)); + Steps(session, endPass - 1); + Assert.That((bool)Invoke(session, "PhysicalBodyBusy", Actor(session, "A")), Is.False); + Steps(session, 1); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Idle")); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void BlockUsesDefenceClipAndRestartDoesNotSelectIdle(string variant) + { + BattleSession session = Session(variant, out _); + object actor = Actor(session, "A"); + actor.GetType().GetField("Guard").SetValue(actor, true); + Invoke(session, "PushBodyBlock", actor, false); + Steps(session, 2); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("GuardHurt")); + Invoke(session, "PushBodyBlock", actor, false); + Steps(session, 1); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("GuardHurt")); + Assert.That(Snapshot(session, "A").NativeAnimationSeconds, Is.EqualTo((variant == "PAL3" ? 124 : 96) / 4800d)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void DefenceBecomesActiveOnlyWhenStartBodyPopsOver(string variant) + { + BattleSession session = Session(variant, out _); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Defend)), Is.True); + Steps(session, 1); + Assert.That(Snapshot(session, "A").Guarding, Is.False); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("GuardEntry")); + Steps(session, 6); + Assert.That(Snapshot(session, "A").Guarding, Is.True); + Steps(session, 4); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Guard")); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AttackDistanceUsesActualRetainedClipBoundsAtStageTime(string variant) + { + BattleSession session = Session(variant, out _); + var binding = (BattleBodyAnimationBinding)Invoke(session, "GetBodyBinding", Actor(session, "E")); + binding.TryPlay(new BattlePhysicalAnimation("retained", 5, 40), true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Attack, "E")), Is.True); + Steps(session, 7); + Assert.That(Snapshot(session, "A").Position.X, Is.EqualTo(50f)); + } + + [TestCase("PAL3", 124, "Dying")] + [TestCase("PAL3", 125, "Idle")] + [TestCase("PAL3A", 124, "Dying")] + [TestCase("PAL3A", 125, "Idle")] + public void ProperIdleAnimationUsesNativeQuarterHpBoundary(string variant, int hp, string clip) + { + BattleSession session = Session(variant, out _); + object actor = Actor(session, "A"); + actor.GetType().GetField("Hp").SetValue(actor, hp); + Steps(session, 1); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo(clip)); + } + + [Test] + public void ThrownWeaponRetainsItsCommandAfterStageReleasesAndRestoresBodyOnLanding() + { + BattleSession session = Session("PAL3A", out _, thrown: true); + object target = Actor(session, "E"); + foreach (string field in new[] { "Position", "Home" }) + target.GetType().GetField(field).SetValue(target, new BattleMovementPoint(600, 0, 0)); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Attack, "E")), Is.True); + Steps(session, 12); + Assert.That(Snapshot(session, "A").CurrentAction, Is.Null); + Assert.That(session.ThrownWeapons.Single().Active, Is.True); + Assert.That(session.WeaponDrawingEnabled("A"), Is.False); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Hit && entry.Target == "E"), Is.Zero); + Steps(session, 120); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Hit && entry.Target == "E"), Is.EqualTo(1)); + Assert.That(Snapshot(session, "A").Position.X, Is.Zero); + Assert.That(session.ThrownWeapons.Single().Active, Is.False); + Assert.That(session.WeaponDrawingEnabled("A"), Is.True); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Idle")); + } + + [Test] + public void ExplicitCancellationStopsItsLaunchedWeaponAndPreventsDelayedDamage() + { + BattleSession session = Session("PAL3A", out _, thrown: true); + object target = Actor(session, "E"); + foreach (string field in new[] { "Position", "Home" }) + target.GetType().GetField(field).SetValue(target, new BattleMovementPoint(600, 0, 0)); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Attack, "E")), Is.True); + long actionId = Snapshot(session, "A").ActionId; + for (int index = 0; index < 20 && !session.ThrownWeapons.Any(weapon => weapon.Active); index++) + Steps(session, 1); + Assert.That(session.ThrownWeapons.Single().Active, Is.True); + Assert.That(Snapshot(session, "A").CurrentAction, Is.EqualTo(BattleAction.Attack)); + Assert.That(session.CancelAction("A"), Is.True); + Assert.That(session.ThrownWeapons, Is.Empty); + Assert.That(session.WeaponDrawingEnabled("A"), Is.True); + Steps(session, 120); + Assert.That(Snapshot(session, "E").Hp, Is.EqualTo(500)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit && entry.ActionId == actionId), Is.False); + Assert.That(Snapshot(session, "A").CurrentAction, Is.Null); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Idle")); + } + + [Test] + public void CancellingANewerCommandPreservesAnOlderIndependentWeaponFlight() + { + BattleSession session = Session("PAL3A", out _, thrown: true); + object target = Actor(session, "E"); + foreach (string field in new[] { "Position", "Home" }) + target.GetType().GetField(field).SetValue(target, new BattleMovementPoint(600, 0, 0)); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Attack, "E")), Is.True); + long attackId = Snapshot(session, "A").ActionId; + Steps(session, 12); + Assert.That(Snapshot(session, "A").CurrentAction, Is.Null); + Assert.That(session.ThrownWeapons.Single().Active, Is.True); + object actor = Actor(session, "A"); + actor.GetType().GetField("Gauge").SetValue(actor, BattleSession.FullGauge); + actor.GetType().GetField("Ready").SetValue(actor, true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Defend)), Is.True); + Assert.That(Snapshot(session, "A").ActionId, Is.Not.EqualTo(attackId)); + Steps(session, 1); + Assert.That(Snapshot(session, "A").CurrentAction, Is.EqualTo(BattleAction.Defend)); + Assert.That(session.CancelAction("A"), Is.True); + Assert.That(session.ThrownWeapons.Single().Active, Is.True); + Assert.That(session.WeaponDrawingEnabled("A"), Is.False); + Steps(session, 120); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Hit && entry.ActionId == attackId), Is.EqualTo(1)); + Assert.That(Snapshot(session, "E").Hp, Is.LessThan(500)); + Assert.That(session.ThrownWeapons.Single().Active, Is.False); + Assert.That(session.WeaponDrawingEnabled("A"), Is.True); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ProtectedCriticalFeedbackUsesTheActualDamageReceiver(string variant) + { + var effects = new Effects(); + BattleSession session = Session(variant, out _, party: true, effects: effects); + Assert.That(session.SetProtection("A", "B"), Is.True); + object target = Actor(session, "B"); + target.GetType().GetField("Hp").SetValue(target, 50); + object enemy = Actor(session, "E"); + ((int[])enemy.GetType().GetField("Attributes").GetValue(enemy))[6] = 200; + Assert.That(Invoke(session, "SubmitCommand", new BattleCommand("E", BattleAction.Attack, "B"), true), Is.True); + for (int index = 0; index < 100 && effects.Started.All(request => request.GroupId != 470); index++) + Steps(session, 1); + BattleActorSnapshot guardian = Snapshot(session, "A"); + Assert.That(guardian.Hp, Is.LessThan(500)); + Assert.That(Snapshot(session, "B").Hp, Is.EqualTo(50)); + BattleEffectRequest critical = effects.Started.Single(request => request.GroupId == 470); + Assert.That(critical.Source, Is.EqualTo("A")); + Assert.That(critical.Targets, Is.EqualTo(new[] { "A" })); + Assert.That(critical.Origin, Is.EqualTo(guardian.Position)); + Assert.That(critical.Origin, Is.Not.EqualTo(Snapshot(session, "B").Position)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void LethalHitDuringExternalControlWaitsForReleaseAndHurtOverBeforeModelDeath(string variant) + { + BattleSession session = Session(variant, out _, party: true, skill: true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + Steps(session, 4); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("skill-long")); + session.SetEffectActorControlled("A", true); + Invoke(session, "ChangeHp", Actor(session, "A"), -1000, null, 0L, "external-control lethal fixture", true, false, false); + Steps(session, 20); + Assert.That(Snapshot(session, "A").Hp, Is.Zero); + Assert.That(Snapshot(session, "A").AliveFlag, Is.False); + Assert.That(Snapshot(session, "A").ModelAliveFlag, Is.True); + Assert.That(Snapshot(session, "A").CurrentAction, Is.Null); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("skill-long")); + session.SetEffectActorControlled("A", false); + Steps(session, 1); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Hurt")); + Assert.That(Snapshot(session, "A").ModelAliveFlag, Is.True); + for (int index = 0; index < 20 && Snapshot(session, "A").ModelAliveFlag; index++) + { + Assert.That(session.CaptureBodyAnimation("A").LastPoppedMarker, Is.Not.EqualTo(BattlePhysicalMarkerKind.Over)); + Steps(session, 1); + } + Assert.That(session.CaptureBodyAnimation("A").LastPoppedMarker, Is.EqualTo(BattlePhysicalMarkerKind.Over)); + Assert.That(Snapshot(session, "A").ModelAliveFlag, Is.False); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Hurt")); + Steps(session, 1); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Dead")); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AStartedEffectWithoutActorControlContinuesAfterItsOwnerDies(string variant) + { + var effects = new Effects { KeepRunning = true }; + BattleSession session = Session(variant, out Catalog catalog, party: true, skill: true, effects: effects); + catalog.AbilityEffectGroup = 7; + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + Steps(session, 4); + Assert.That(effects.Started.Single().GroupId, Is.EqualTo(7)); + Assert.That(session.IsActorExternallyControlled("A"), Is.False); + Invoke(session, "ChangeHp", Actor(session, "A"), -1000, null, 0L, "independent-effect lethal fixture", true, false, false); + Steps(session, 20); + Assert.That(Snapshot(session, "A").Hp, Is.Zero); + Assert.That(Snapshot(session, "A").AliveFlag, Is.False); + Assert.That(Snapshot(session, "A").ModelAliveFlag, Is.False); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Dead")); + Assert.That(effects.IsRunning(1), Is.True); + Assert.That(effects.Stopped, Is.Empty); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ProtectionSelectionCostsControllerOnlyWhenChangedAndNativeDirectorIntercepts(string variant) + { + BattleSession session = Session(variant, out _, true); + Assert.That(session.SetProtection("A", "B"), Is.True); + Assert.That(Snapshot(session, "A").Gauge, Is.Zero); + object protectedActor = Actor(session, "B"); + protectedActor.GetType().GetField("Hp").SetValue(protectedActor, 50); + Assert.That(Invoke(session, "SubmitCommand", new BattleCommand("E", BattleAction.Attack, "B"), true), Is.True); + Steps(session, 70); + Assert.That(Snapshot(session, "B").Hp, Is.EqualTo(50)); + Assert.That(Snapshot(session, "A").Hp, Is.LessThan(500)); + Assert.That(session.ProtectionTarget, Is.EqualTo("B")); + Assert.That(Snapshot(session, "A").Position.X, Is.Zero); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ProtectionCannotStealAnActiveAbilityBodyFromTheSharedNativeRoleQueue(string variant) + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "physical-ownership", Seed = 1 }; + scenario.Participants.Add(Participant("A", 101, BattleSide.Ally, BattleSlot.Center)); + scenario.Participants.Add(Participant("B", 102, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(Participant("E", 701, BattleSide.Enemy, BattleSlot.Water)); + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 4201, Mastered = true, Level = 4 }); + var ability = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 4201, + Name = "long native body", + SuccessRate = 100, + Range = BattleTargetRange.OpponentSingle, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -1) } + }); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, new[] { ability }, Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId == "A" ? 0 : actor.InstanceId == "B" ? 1 : -1, + NormalAttackMode = 924 + }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(scenario), new Rules(), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(session.SetProtection("A", "B"), Is.True); + object guardian = Actor(session, "A"); + guardian.GetType().GetField("Gauge").SetValue(guardian, BattleSession.FullGauge); + guardian.GetType().GetField("Ready").SetValue(guardian, true); + object target = Actor(session, "B"); + target.GetType().GetField("Hp").SetValue(target, 50); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + Steps(session, 20); + Assert.That((bool)Invoke(session, "HasActiveOrdinaryAbilityBody", guardian), Is.True); + Assert.That((bool)Invoke(session, "PhysicalBodyIdle", guardian), Is.False); + Assert.That(Invoke(session, "SubmitCommand", new BattleCommand("E", BattleAction.Attack, "B"), true), Is.True); + Steps(session, 40); + Assert.That(session.StageTasks.Any(task => task.Kind == "protection"), Is.False); + Assert.That(Snapshot(session, "A").Position.X, Is.Zero); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("skill-long")); + Assert.That(Snapshot(session, "B").Hp, Is.LessThan(50)); + Steps(session, 250); + Assert.That(Snapshot(session, "A").CurrentAction, Is.Null); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Idle")); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ProtectionWaitsForTheAbilityStageReleaseAfterItsBodyFinishes(string variant) + { + BattleSession session = Session(variant, out Catalog catalog, party: true, skill: true); + catalog.AbilityBodyTicks = 5; + catalog.AbilityWorkSeconds = 1.2f; + Assert.That(session.SetProtection("A", "B"), Is.True); + object guardian = Actor(session, "A"); + guardian.GetType().GetField("Gauge").SetValue(guardian, BattleSession.FullGauge); + guardian.GetType().GetField("Ready").SetValue(guardian, true); + object target = Actor(session, "B"); + target.GetType().GetField("Hp").SetValue(target, 50); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + Steps(session, 20); + Assert.That((bool)Invoke(session, "PhysicalBodyIdle", guardian), Is.True); + Assert.That(Snapshot(session, "A").CurrentAction, Is.EqualTo(BattleAction.Skill)); + BattleStageHandle ability = session.StageTasks.Single(task => task.Owner == "A").Handle; + Assert.That(Invoke(session, "SubmitCommand", new BattleCommand("E", BattleAction.Attack, "B"), true), Is.True); + Steps(session, 20); + Assert.That(session.StageTasks.Any(task => task.Kind == "protection"), Is.True); + Assert.That(Snapshot(session, "A").Position.X, Is.Zero); + for (int index = 0; index < 100 && Snapshot(session, "A").Position.X == 0; index++) + Steps(session, 1); + Assert.That(Snapshot(session, "A").Position.X, Is.GreaterThan(0)); + Assert.That(session.StageTasks.Single(task => task.Handle == ability).Finished, Is.True, + "The higher protection slot must acquire the role in the same pass as ability Release."); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AbilityWaitsForAnotherStageGrabAndAcquiresOnItsReleasePass(string variant) + { + BattleSession session = Session(variant, out _, skill: true); + object actor = Actor(session, "A"); + var scheduler = (BattleStageScheduler)typeof(BattleSession).GetField("_stage", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + var reservation = new BodyReservation { Session = session, Actor = actor }; + BattleStageHandle owner = scheduler.Add("A", "existing normal grab", reservation, 0); + Assert.That(Invoke(session, "TryGrabStageBody", actor, owner), Is.True); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + Steps(session, 20); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("Idle")); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit), Is.False); + reservation.Release = true; + Steps(session, 1); + var owners = (IDictionary)typeof(BattleSession).GetField("_bodyStageOwners", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + BattleStageHandle ability = session.StageTasks.Single(task => task.Kind == "ability").Handle; + Assert.That(owners["A"], Is.EqualTo(ability.Id)); + Assert.That(reservation.ReleasedTick, Is.EqualTo(session.SimulationTick)); + Steps(session, 4); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("skill-long")); + session.CancelAction("A"); + Assert.That(owners.Contains("A"), Is.False); + session.Abort(); + Assert.That(owners.Count, Is.Zero); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RetiringReleasedAbilityDoesNotClearItsSuccessorsMovement(string variant) + { + BattleSession session = Session(variant, out Catalog catalog, party: true, skill: true); + catalog.AbilityBodyTicks = 5; + catalog.AbilityMoves = true; + Assert.That(session.SetProtection("A", "B"), Is.True); + object guardian = Actor(session, "A"); + guardian.GetType().GetField("Gauge").SetValue(guardian, BattleSession.FullGauge); + guardian.GetType().GetField("Ready").SetValue(guardian, true); + object target = Actor(session, "B"); + target.GetType().GetField("Hp").SetValue(target, 50); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + Steps(session, 40); + Assert.That(Snapshot(session, "A").CurrentAction, Is.EqualTo(BattleAction.Skill), "The parallel name task still owns the command, after role Release."); + Assert.That(Invoke(session, "SubmitCommand", new BattleCommand("E", BattleAction.Attack, "B"), true), Is.True); + Steps(session, 11); + Assert.That(Snapshot(session, "A").Movement, Is.Not.Null); + Steps(session, 100); + Assert.That(Snapshot(session, "A").Position.X, Is.Zero); + Assert.That(Snapshot(session, "A").CurrentAction, Is.Null); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AbilityBecomingReadyDuringProtectionWaitsForTheProtectorsRelease(string variant) + { + BattleSession session = Session(variant, out _, party: true, skill: true); + Assert.That(session.SetProtection("A", "B"), Is.True); + object guardian = Actor(session, "A"); + guardian.GetType().GetField("Gauge").SetValue(guardian, BattleSession.FullGauge); + guardian.GetType().GetField("Ready").SetValue(guardian, true); + object target = Actor(session, "B"); + target.GetType().GetField("Hp").SetValue(target, 50); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + object run = guardian.GetType().GetField("Run").GetValue(guardian); + // Hold the native second-gauge wait, then complete it while the + // protector owns the role. This avoids an artificial ready command + // that the public input gate correctly rejects during movement. + run.GetType().GetField("Casting").SetValue(run, true); + guardian.GetType().GetField("Gauge").SetValue(guardian, BattleSession.FullGauge); + Assert.That(Invoke(session, "SubmitCommand", new BattleCommand("E", BattleAction.Attack, "B"), true), Is.True); + Steps(session, 4); + Assert.That(Snapshot(session, "A").Position.X, Is.GreaterThan(0)); + run.GetType().GetField("Casting").SetValue(run, false); + run.GetType().GetField("TimelineOriginTick").SetValue(run, session.SimulationTick); + Steps(session, 20); + Assert.That(session.StageTasks.Any(task => task.Kind == "ability"), Is.True); + Assert.That((bool)Invoke(session, "HasActiveOrdinaryAbilityBody", guardian), Is.False); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "A"), Is.False); + for (int index = 0; index < 200 && Snapshot(session, "A").NativeAnimationClip != "skill-long"; index++) + Steps(session, 1); + Assert.That(Snapshot(session, "A").NativeAnimationClip, Is.EqualTo("skill-long")); + Assert.That(Snapshot(session, "A").Position.X, Is.Zero); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ResurrectionAwayFromHomeQueuesNativeMovementAndReturnsAfterTheDeadCommandReleases(string variant) + { + BattleSession session = Session(variant, out _, party: true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Attack, "E")), Is.True); + Steps(session, 4); + float away = Snapshot(session, "A").Position.X; + Assert.That(away, Is.GreaterThan(13)); + object actor = Actor(session, "A"); + Invoke(session, "ChangeHp", actor, -1000, null, 0L, "lethal fixture", true, false, false); + Steps(session, 20); + Assert.That(Snapshot(session, "A").ModelAliveFlag, Is.False); + Assert.That(Invoke(session, "ApplyState", actor, BattleState.Death, true, null, false, null, 0L, true), Is.True); + Assert.That(session.StageTasks.Count(task => task.Kind == "revival return"), Is.EqualTo(1)); + Assert.That(Invoke(session, "ApplyState", actor, BattleState.Death, true, null, false, null, 0L, true), Is.False); + Assert.That(session.StageTasks.Count(task => task.Kind == "revival return"), Is.EqualTo(1)); + Invoke(session, "ChangeHp", actor, 100, null, 0L, "revival HP fixture", true, false, false); + Steps(session, 1); + Assert.That(Snapshot(session, "A").Position.X, Is.GreaterThan(0).And.LessThan(away)); + Assert.That(Snapshot(session, "A").Movement.Plan.Kind, Is.EqualTo(BattleMovementKind.Run)); + Steps(session, 30); + Assert.That(Snapshot(session, "A").Position.X, Is.Zero); + Assert.That(Snapshot(session, "A").FacingDegrees, Is.EqualTo(BattleFacingRules.Initial(BattleSide.Ally))); + Assert.That(session.StageTasks.Any(task => task.Kind == "revival return"), Is.False); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ResurrectionAtHomeDoesNotCreateAReturnStage(string variant) + { + BattleSession session = Session(variant, out _, party: true); + object actor = Actor(session, "A"); + Invoke(session, "ChangeHp", actor, -1000, null, 0L, "lethal fixture", true, false, false); + Steps(session, 20); + Assert.That(Invoke(session, "ApplyState", actor, BattleState.Death, true, null, false, null, 0L, true), Is.True); + Assert.That(session.StageTasks.Any(task => task.Kind == "revival return"), Is.False); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattlePhysicalPresentationTests.cs.meta b/Assets/Tests/Battle/Editor/BattlePhysicalPresentationTests.cs.meta new file mode 100644 index 00000000..9ee02a4d --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattlePhysicalPresentationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0cf218e3aab94c6c954f2aeb06b5997c diff --git a/Assets/Tests/Battle/Editor/BattleProbabilityTests.cs b/Assets/Tests/Battle/Editor/BattleProbabilityTests.cs new file mode 100644 index 00000000..b07320ad --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleProbabilityTests.cs @@ -0,0 +1,180 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleProbabilityTests + { + private sealed class AiPort : BattleAiPort + { + public override long TryAttempt(BattleAiAttempt attempt) => -1; + } + + private sealed class Catalog : IBattleCatalog + { + public AttackTiming Attack(string source, string target) => new(0, 2, new[] { 1 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class ReadyRules : IBattleRules + { + private readonly BattleBasicRules _original = new(); + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => actor.Side == BattleSide.Enemy ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => 1; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => _original.Hit(source, target, guarding, random, targetAtHome, damageDivisor); + } + + // Independent oracle: released PAL3 inline instructions and PAL3A helper + // 0x43268c, executed by Battle-Stage17-ProbabilityReview/probe-probability.py. + [TestCase(1, 2940990853u, true, 594484u)] + [TestCase(1, 3768644997u, false, 660020u)] + [TestCase(4, 2828465541u, true, 2626100u)] + [TestCase(4, 3656119685u, false, 2691636u)] + [TestCase(37, 3402691973u, true, 24777268u)] + [TestCase(37, 4230346117u, false, 24842804u)] + [TestCase(50, 1811543429u, true, 33493556u)] + [TestCase(50, 2639197573u, false, 33559092u)] + [TestCase(99, 682096005u, true, 66392628u)] + [TestCase(99, 1509750149u, false, 66458164u)] + public void NativeThresholdUses1024ResiduesAndStrictComparison(int percent, uint seed, bool expected, uint finalSeed) + { + foreach (string variant in new[] { "PAL3", "PAL3A" }) + { + var random = new BattleRandom(unchecked((int)seed), variant); + Assert.That(random.Probability(percent), Is.EqualTo(expected), variant); + Assert.That(random.State, Is.EqualTo(finalSeed), variant); + } + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NonpositiveProbabilityDoesNotConsumeTheStream(string variant) + { + var random = new BattleRandom(123, variant); + Assert.That(random.Probability(-10), Is.False); + Assert.That(random.Probability(0), Is.False); + Assert.That(random.State, Is.EqualTo(123u)); + } + + [TestCase("PAL3", 100, 28854610u)] + [TestCase("PAL3", 101, 28854610u)] + [TestCase("PAL3", 255, 28854610u)] + [TestCase("PAL3A", 100, 123u)] + [TestCase("PAL3A", 101, 123u)] + [TestCase("PAL3A", 255, 123u)] + public void CertainSuccessConsumesOneDrawOnlyInPal3(string variant, int percent, uint finalSeed) + { + var random = new BattleRandom(123, variant); + Assert.That(random.Probability(percent), Is.True); + Assert.That(random.State, Is.EqualTo(finalSeed)); + } + + [TestCase("PAL3", false, 3396176589u)] + [TestCase("PAL3A", true, 28854610u)] + public void CertainSuccessPreservesTheOriginalFollowingRoll(string variant, bool followingResult, uint finalSeed) + { + var random = new BattleRandom(123, variant); + Assert.That(random.Probability(100), Is.True); + Assert.That(random.Probability(50), Is.EqualTo(followingResult)); + Assert.That(random.State, Is.EqualTo(finalSeed)); + } + + [TestCase("PAL3", 1512272476u)] + [TestCase("PAL3A", 3396176589u)] + public void HighTechniqueSuccessRetainsItsWarpDrawsBeforeTheProbabilityGate(string variant, uint finalSeed) + { + var random = new BattleRandom(123, variant); + int percent = new BattleEffectRules(variant).TechniqueSuccessPercent(13, 10, 0, random); + Assert.That(percent, Is.EqualTo(110)); + Assert.That(random.State, Is.EqualTo(3396176589u)); + Assert.That(random.Probability(percent), Is.True); + Assert.That(random.State, Is.EqualTo(finalSeed)); + } + + [TestCase("PAL3", 28854610u)] + [TestCase("PAL3A", 123u)] + public void SingleOverfullAiCandidateUsesTheNativeCertainSuccessGate(string variant, uint finalSeed) + { + var random = new BattleRandom(123, variant); + var ai = new BattleAi(variant == "PAL3A", random, new AiPort()); + // HP above maximum deliberately bypasses the ordinary lowest-ratio + // selection and reaches the published 100/candidateCount fallback. + ai.Roles[5] = new BattleAiRole { Valid = true, Alive = true, Hp = 200, MaxHp = 100 }; + Assert.That(ai.SelectPlayerNormalTarget(0), Is.EqualTo(5)); + Assert.That(random.State, Is.EqualTo(finalSeed)); + } + + [TestCase(true, "PAL3")] + [TestCase(false, "PAL3A")] + public void AiRejectsAMismatchedProbabilityVariant(bool pal3A, string randomVariant) + { + Assert.Throws(() => new BattleAi(pal3A, new BattleRandom(123, randomVariant), new AiPort())); + } + + [Test] + public void RandomDefaultsToPal3AndRejectsUnknownVariants() + { + Assert.That(new BattleRandom(123).Variant, Is.EqualTo("PAL3")); + Assert.Throws(() => new BattleRandom(123, "other")); + } + + private static BattleParticipant Participant(string id, BattleSide side) => new() + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Level = 1, + Attributes = new[] { 100, 100, 100, 60, 10, side == BattleSide.Ally ? 23 : 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 100, 100, 100 } + }; + + [TestCase("PAL3", false, 1512272476u)] + [TestCase("PAL3A", false, 3396176589u)] + [TestCase("PAL3", true, 1512272476u)] + [TestCase("PAL3A", true, 3396176589u)] + public void SessionHighDodgeUsesItsVariantInBasicAndCapturedRules(string variant, bool capturedRules, uint finalSeed) + { + var scenario = new BattleScenario { Variant = variant, Scene = "portable", DataFingerprint = "probability-fixture", Seed = 123 }; + scenario.Participants.Add(Participant("A", BattleSide.Ally)); + scenario.Participants.Add(Participant("E", BattleSide.Enemy)); + BattleDefinitions definitions = capturedRules ? new BattleDefinitions(variant, scenario.DataFingerprint, + Array.Empty(), Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1 + }))) : null; + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new ReadyRules(), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + session.SetAutomatic(BattleSide.Ally, false); + Assert.That(session.Submit("E", BattleAction.Attack, "A"), Is.True); + for (int i = 0; i < 20 && !session.Events.Any(entry => entry.Kind == BattleEventKind.Miss); i++) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + BattleEvent miss = session.Events.Single(entry => entry.Kind == BattleEventKind.Miss); + Assert.That(miss.Dodged, Is.True); + Assert.That(miss.RandomState, Is.EqualTo(finalSeed)); + Assert.That(session.Actors.Single(actor => actor.Id == "A").Hp, Is.EqualTo(100)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleProbabilityTests.cs.meta b/Assets/Tests/Battle/Editor/BattleProbabilityTests.cs.meta new file mode 100644 index 00000000..fb1ff0d0 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleProbabilityTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0dcce80ad2804c09833d48efc3e5e07b diff --git a/Assets/Tests/Battle/Editor/BattleRelationRulesTests.cs b/Assets/Tests/Battle/Editor/BattleRelationRulesTests.cs new file mode 100644 index 00000000..cda8baa4 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleRelationRulesTests.cs @@ -0,0 +1,52 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleRelationRulesTests + { + [TestCase("PAL3", 3, true)] + [TestCase("PAL3", 4, false)] + [TestCase("PAL3A", 3, false)] + [TestCase("PAL3A", 4, false)] + [TestCase("PAL3", 0, true)] + [TestCase("PAL3A", 0, true)] + public void PublishedWriterFiltersOnlyItsSpecificNativeSlots(string variant, int index, bool applies) + { + BattleRelationChange change = BattleRelationRules.Change(variant, index, 40, 1, true); + Assert.That(change.Applied, Is.EqualTo(applies)); + Assert.That(change.Value, Is.EqualTo(applies ? 41 : 40)); + Assert.That(change.Sound, Is.EqualTo(applies ? "wa010" : null)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AbsentHeroLeavesValueAndSoundUntouched(string variant) + { + BattleRelationChange change = BattleRelationRules.Change(variant, 1, 999, -2, false); + Assert.That(change.Applied, Is.False); + Assert.That(change.Value, Is.EqualTo(999)); + Assert.That(change.Sound, Is.Null); + } + + [TestCase(999, 1, 999, "wa010")] + [TestCase(0, -2, 0, "wa048")] + [TestCase(999, 0, 999, null)] + [TestCase(int.MaxValue, 1, 0, "wa010")] + [TestCase(int.MinValue, -1, 999, "wa048")] + public void SoundUsesRequestSignBeforeUncheckedAdditionAndClamping(int before, int requested, int expected, string sound) + { + foreach (string variant in new[] { "PAL3", "PAL3A" }) + { + BattleRelationChange change = BattleRelationRules.Change(variant, 1, before, requested, true); + Assert.That(change.Value, Is.EqualTo(expected)); + Assert.That(change.Sound, Is.EqualTo(sound)); + } + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleRelationRulesTests.cs.meta b/Assets/Tests/Battle/Editor/BattleRelationRulesTests.cs.meta new file mode 100644 index 00000000..ee0c931f --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleRelationRulesTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 1e46206bfbbe428db08cfa086f20645f diff --git a/Assets/Tests/Battle/Editor/BattleRemainingSpecialsTests.cs b/Assets/Tests/Battle/Editor/BattleRemainingSpecialsTests.cs new file mode 100644 index 00000000..6821278c --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleRemainingSpecialsTests.cs @@ -0,0 +1,294 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Battle; + using NUnit.Framework; + + public sealed class BattleRemainingSpecialsTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattleStageGeometry + { + private readonly BattleScenario _scenario; + + internal Catalog(BattleScenario scenario) => _scenario = scenario; + + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "S" ? 0 : 1; + + public int DamageDivisor(string actor) => 1; + + public BattleMovementPoint InitialHome(string actor) => FormationHome(actor, _scenario.Participants.Single(value => value.InstanceId == actor).Slot); + + public BattleMovementPoint FormationHome(string actor, BattleSlot slot) => new(100 * ((int)slot + 1), 10 * ((int)slot + 1), 50 * ((int)slot + 1)); + + public BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint sourceHome, BattleMovementPoint targetHome) => + new(Attack(source, target), sourceHome, targetHome, targetHome); + + public IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint currentHome, BattleMovementPoint destination, bool passThroughMidpoint) => + Array.AsReadOnly(new[] { new BattleMovementPlan(BattleMovementKind.Run, currentHome, destination) }); + } + + private sealed class Rules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => actor.InstanceId == "S" ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => 0; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => new(-1, false, false); + } + + private sealed class WaitingStage : IBattleStageJob + { + public bool Advance(BattleStageContext context) => false; + } + + private static BattleParticipant Participant(string id, BattleSide side, BattleSlot slot) => new() + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = slot, + Attributes = new[] { 500, 100, 100, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 100, 100 } + }; + + private static BattleSession Session(string variant, BattleAbilityData ability, bool enemySource = false, bool secondAlly = false, bool extraEnemy = false) + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "remaining-specials", Seed = 1 }; + scenario.Participants.Add(Participant("S", enemySource ? BattleSide.Enemy : BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(Participant("T", enemySource ? BattleSide.Ally : BattleSide.Enemy, BattleSlot.Water)); + if (secondAlly) + { + scenario.Participants.Add(Participant("Z", BattleSide.Ally, BattleSlot.Earth)); + scenario.Participants[^1].Vitals[0] = 200; + } + if (extraEnemy) + scenario.Participants.Add(Participant("W", BattleSide.Enemy, BattleSlot.Fire)); + scenario.Participants[0].Skills.Add(new BattleSkill { Id = ability.Id, Level = 4, Mastered = true }); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, + new[] { new BattleAbilityDefinition(ability) }, Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Enemy ? -1 : actor.InstanceId == "Z" ? 3 : 0 + }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(scenario), new Rules(), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + + private static object MutableActor(BattleSession session, string id) => + ((IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(session))[id]; + + private static void SetField(BattleSession session, string id, string name, object value) + { + object actor = MutableActor(session, id); + actor.GetType().GetField(name, BindingFlags.Public | BindingFlags.Instance).SetValue(actor, value); + } + + private static void Resolve(BattleSession session, int skill) + { + int ended = session.Events.Count(value => value.Kind == BattleEventKind.ActionEnded && value.Source == "S"); + Assert.That(session.Submit(new BattleCommand("S", BattleAction.Skill, "T", skill)), Is.True); + for (int tick = 0; tick < 10 && session.Events.Count(value => value.Kind == BattleEventKind.ActionEnded && value.Source == "S") == ended; tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void Magic258DoesNotUseTechniqueMpAbsorption(string variant) + { + BattleSpecialHandler handler = BattleSpecialRules.AbilityHandler(variant, 258, false, true, 18); + Assert.That(handler, Is.EqualTo(BattleSpecialHandler.GenericOnly)); + BattleSession session = Session(variant, new BattleAbilityData + { + Id = 258, + IsMagic = true, + Handler = handler, + SpecialEffect = 18, + Range = BattleTargetRange.OpponentSingle, + Attributes = new[] { new BattleAttributeEffect(2, BattleValueMode.Absolute, -20) } + }); + SetField(session, "S", "Mp", 50); + Resolve(session, 258); + Assert.That(session.Actors.Single(value => value.Id == "S").Mp, Is.EqualTo(50)); + Assert.That(session.Actors.Single(value => value.Id == "T").Mp, Is.LessThan(100)); + Assert.That(BattleSpecialRules.AbilityHandler(variant, 999, false, true, 18), Is.EqualTo(BattleSpecialHandler.None)); + } + + [TestCase(0, 2219737664u, new[] { 0, 5, 4, 3, 1, 2 })] + [TestCase(1, 120733505u, new[] { 1, 0, 4, 3, 5, 2 })] + [TestCase(2, 2316696642u, new[] { 4, 5, 3, 2, 1, 0 })] + [TestCase(123, 1740263867u, new[] { 2, 1, 4, 3, 0, 5 })] + [TestCase(-1, 23774527u, new[] { 4, 0, 1, 3, 2, 5 })] + public void RandomFormationMatchesBothNativeSixtyFourDraws(int seed, uint finalSeed, int[] expected) + { + var random = new BattleRandom(seed); + Assert.That(BattleSpecialRules.RandomFormation(random).Select(slot => (int)slot), Is.EqualTo(expected)); + Assert.That(random.State, Is.EqualTo(finalSeed)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RandomFormationChangesHomeAndPositionByNativeIdentityWithoutGaugeCost(string variant) + { + var ability = new BattleAbilityData { Id = 263, IsMagic = true, Handler = BattleSpecialHandler.RandomFormation, Range = BattleTargetRange.OpponentSingle }; + BattleSession session = Session(variant, ability, enemySource: true, secondAlly: true); + Resolve(session, 263); + BattleActorSnapshot target = session.Actors.Single(value => value.Id == "T"); + BattleActorSnapshot zixuan = session.Actors.Single(value => value.Id == "Z"); + Assert.That((target.Slot, zixuan.Slot), Is.EqualTo((BattleSlot.Fire, BattleSlot.Thunder))); + Assert.That(target.Position.X, Is.EqualTo(200)); + Assert.That(target.Home.X, Is.EqualTo(200)); + Assert.That(zixuan.Position.X, Is.EqualTo(400)); + Assert.That(target.Gauge, Is.EqualTo(0)); + Assert.That(session.Events.Last(value => value.Kind == BattleEventKind.FormationChanged).RandomState, Is.EqualTo(120733505u)); + Assert.That(session.Events.Any(value => value.Kind == BattleEventKind.MovementStarted), Is.False); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RandomFormationFailureDoesNotDrawOrMoveOtherAllies(string variant) + { + var ability = new BattleAbilityData { Id = 263, IsMagic = true, Handler = BattleSpecialHandler.RandomFormation, Range = BattleTargetRange.OpponentSingle }; + BattleSession session = Session(variant, ability, enemySource: true, secondAlly: true); + // The magic target stays at home; another valid allied role is away. + SetField(session, "Z", "Position", new BattleMovementPoint(9999, 0, 0)); + Resolve(session, 263); + Assert.That(session.Events.Any(value => value.Kind == BattleEventKind.FormationChanged), Is.False); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(1u)); + Assert.That(session.Actors.Single(value => value.Id == "T").Slot, Is.EqualTo(BattleSlot.Water)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RandomFormationRepeatsPerTargetAndRespectsAnotherAlliedStageTask(string variant) + { + var ability = new BattleAbilityData { Id = 263, IsMagic = true, Handler = BattleSpecialHandler.RandomFormation, Range = BattleTargetRange.OpponentAll }; + BattleSession session = Session(variant, ability, enemySource: true, secondAlly: true); + Resolve(session, 263); + Assert.That(session.Events.Count(value => value.Kind == BattleEventKind.FormationChanged), Is.EqualTo(4)); + Assert.That(session.Events.Last(value => value.Kind == BattleEventKind.FormationChanged).RandomState, Is.EqualTo(3168190081u)); + + BattleSession busy = Session(variant, ability, enemySource: true, secondAlly: true); + var stage = (BattleStageScheduler)typeof(BattleSession).GetField("_stage", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(busy); + Assert.That(stage.TryAdd("Z", "native owned task", new WaitingStage(), 0, out _), Is.True); + Resolve(busy, 263); + Assert.That(busy.Events.Any(value => value.Kind == BattleEventKind.FormationChanged), Is.False); + Assert.That(busy.Events.Last().RandomState, Is.EqualTo(1u)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RandomFormationForcesFormationPanelClosedWithoutSpendingItsControllersGauge(string variant) + { + var ability = new BattleAbilityData { Id = 263, IsMagic = true, Handler = BattleSpecialHandler.RandomFormation, Range = BattleTargetRange.OpponentSingle }; + BattleSession session = Session(variant, ability, enemySource: true, secondAlly: true); + Assert.That(session.Submit(new BattleCommand("S", BattleAction.Skill, "T", 263)), Is.True); + SetField(session, "T", "Ready", true); + SetField(session, "T", "Gauge", BattleSession.FullGauge); + Assert.That(session.BeginFormation("T"), Is.True); + for (int tick = 0; tick < 10 && session.ActiveFormationController != null; tick++) + session.Step(); + Assert.That(session.ActiveFormationController, Is.Null); + Assert.That(session.Actors.Single(value => value.Id == "T").Gauge, Is.EqualTo(BattleSession.FullGauge)); + Assert.That(session.Events.Single(value => value.Kind == BattleEventKind.FormationClosed).Detail, Does.Contain("no gauge cost")); + } + + [TestCase("PAL3", 84006, 2, 32, true)] + [TestCase("PAL3A", 8148, 4, 33, true)] + [TestCase("PAL3A", 8151, 5, 34, true)] + [TestCase("PAL3A", 84006, 2, 32, false)] + [TestCase("PAL3", 8148, 4, 33, false)] + [TestCase("PAL3A", 8151, 0, 34, false)] + public void EquipmentDefaultDispatchDoesNotInventNamedPassives(string variant, int id, int slot, int special, bool supported) => + Assert.That(BattleSpecialRules.SupportsEquipmentSpecial(variant, id, slot, special), Is.EqualTo(supported)); + + [TestCase(19, 1, 0)] + [TestCase(20, 1, -1)] + [TestCase(999, 2, -99)] + [TestCase(65535, 3, -9830)] + [TestCase(1000000, 3, -150000)] + [TestCase(int.MaxValue, 3, -322122559)] + [TestCase(100, 4, 0)] + public void WormUsesPublishedFloatConstantBeforeIntegerTruncation(int maximumHp, int round, int expected) => + Assert.That(BattleSpecialRules.AbsorbHpWormRequest(maximumHp, round), Is.EqualTo(expected)); + + [Test] + public void WormRunsAfterStatesForThreeRoundsAndAlwaysRestoresZixuan() + { + BattleSpecialHandler handler = BattleSpecialRules.AbilityHandler("PAL3", 4402, false, false, 19); + Assert.That(handler, Is.EqualTo(BattleSpecialHandler.AbsorbHpWorm)); + Assert.That(BattleSpecialRules.AbilityHandler("PAL3A", 4402, false, false, 19), Is.EqualTo(BattleSpecialHandler.None)); + BattleSession session = Session("PAL3", new BattleAbilityData { Id = 4402, Handler = handler, Range = BattleTargetRange.OpponentSingle }, secondAlly: true); + Resolve(session, 4402); + Assert.That(session.AbsorbHpWormRound("T"), Is.EqualTo(0)); + SetField(session, "T", "Guard", true); + for (int round = 1; round <= 4; round++) + { + SetField(session, "T", "Rounds", round); + session.Step(); + Assert.That(session.AbsorbHpWormRound("T"), Is.EqualTo(round == 4 ? (int?)null : round)); + } + Assert.That(session.Actors.Single(value => value.Id == "T").Hp, Is.EqualTo(426)); + Assert.That(session.Actors.Single(value => value.Id == "Z").Hp, Is.EqualTo(350)); + Assert.That(session.Actors.Single(value => value.Id == "S").Hp, Is.EqualTo(500)); + Assert.That(session.Events.Where(value => value.Detail == "original absorb HP worm recovery").Select(value => value.RequestedDelta), Is.EqualTo(new[] { 25, 50, 75, 0 })); + } + + [Test] + public void WormReapplicationRestartsItsCounterAndInvisibleTargetStillFeedsZixuan() + { + BattleSession session = Session("PAL3", new BattleAbilityData { Id = 4402, Handler = BattleSpecialHandler.AbsorbHpWorm, Range = BattleTargetRange.OpponentSingle }, secondAlly: true); + Resolve(session, 4402); + SetField(session, "T", "Rounds", 1); + session.Step(); + Assert.That(session.AbsorbHpWormRound("T"), Is.EqualTo(1)); + SetField(session, "S", "Ready", true); + SetField(session, "S", "Gauge", BattleSession.FullGauge); + Resolve(session, 4402); + Assert.That(session.AbsorbHpWormRound("T"), Is.EqualTo(0)); + typeof(BattleSession).GetMethod("ApplyState", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(session, + new[] { MutableActor(session, "T"), BattleState.Invisible, false, (object)100, false, null, 0L, true }); + SetField(session, "T", "Rounds", 2); + session.Step(); + Assert.That(session.Actors.Single(value => value.Id == "T").Hp, Is.EqualTo(475)); + Assert.That(session.Actors.Single(value => value.Id == "Z").Hp, Is.EqualTo(250)); + } + + [Test] + public void WormKeepsItsMarkerAndProcessesAPendingDeadRolesRound() + { + BattleSession session = Session("PAL3", new BattleAbilityData { Id = 4402, Handler = BattleSpecialHandler.AbsorbHpWorm, Range = BattleTargetRange.OpponentSingle }, secondAlly: true, extraEnemy: true); + Resolve(session, 4402); + SetField(session, "T", "Hp", 0); + SetField(session, "T", "Alive", false); + SetField(session, "T", "ModelAlive", false); + SetField(session, "T", "Rounds", 1); + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + Assert.That(session.AbsorbHpWormRound("T"), Is.EqualTo(1)); + Assert.That(session.Actors.Single(value => value.Id == "T").Hp, Is.EqualTo(0)); + Assert.That(session.Actors.Single(value => value.Id == "Z").Hp, Is.EqualTo(225)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleRemainingSpecialsTests.cs.meta b/Assets/Tests/Battle/Editor/BattleRemainingSpecialsTests.cs.meta new file mode 100644 index 00000000..8bde5063 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleRemainingSpecialsTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 25bee771945242f29a8b4c660ea7985a diff --git a/Assets/Tests/Battle/Editor/BattleResultPresentationTests.cs b/Assets/Tests/Battle/Editor/BattleResultPresentationTests.cs new file mode 100644 index 00000000..f83b6e74 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleResultPresentationTests.cs @@ -0,0 +1,303 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleResultPresentationTests + { + private static BattleSession Finished(string variant, bool win = true) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Variant = variant; + scenario.DataFingerprint = "fixture"; + scenario.Money = 100; + scenario.Participants[win ? 1 : 0].Vitals[0] = 0; + BattleParticipant secondEnemy = scenario.Participants[1].Copy(); + secondEnemy.InstanceId = "Enemy2"; + secondEnemy.Slot = BattleSlot.Fire; + scenario.Participants.Add(secondEnemy); + var definitions = new BattleDefinitions(variant, "fixture", Array.Empty(), Array.Empty(), new[] + { + new BattleActorDefinition(new BattleActorData { InstanceId = "Ally", Identity = 0 }), + new BattleActorDefinition(new BattleActorData { InstanceId = "Enemy", MoneyReward = 9, LootItem = 9001, LootCount = 2 }), + new BattleActorDefinition(new BattleActorData { InstanceId = "Enemy2", LootItem = 9001, LootCount = 1 }) + }); + var session = new BattleSession(new BattleSetup(scenario), new BattleSessionTests.Catalog(), definitions: definitions); + for (int tick = 0; tick < 100 && session.Status == BattleSessionStatus.Running; tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + return session; + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void WinSequenceMatchesExecutedNativeRegistrationAndKeepsSeparateLootPrompts(string variant) + { + BattleSession combat = Finished(variant); + var result = new BattleResultPresentation(variant, combat.Result, combat.Events); + Assert.That(result.CameraList, Is.EqualTo(3)); + Assert.That(result.Sequence.Select(step => (step.Kind, step.Duration)), Is.EqualTo(new[] + { + (BattleResultStepKind.MusicFadeOut, .5f), (BattleResultStepKind.WinBanner, 3f), + (BattleResultStepKind.Statistics, 2f), (BattleResultStepKind.Money, 5f), + (BattleResultStepKind.Item, 4f), (BattleResultStepKind.Item, 4f), + (BattleResultStepKind.Wait, 5f), (BattleResultStepKind.MusicFadeIn, .2f), + (BattleResultStepKind.ScreenFadeOut, 1f) + })); + Assert.That(result.Sequence.Where(step => step.Kind == BattleResultStepKind.Item).Select(step => (step.Id, step.Value)), + Is.EqualTo(new[] { (9001, 2), (9001, 1) })); + Assert.That(combat.Result.Loot.Single().Count, Is.EqualTo(3)); + Assert.That(combat.Result.PreSettlementActors.Single(actor => actor.Id == "Enemy").AliveFlag, Is.False); + long tick = combat.Tick; + int events = combat.Events.Count; + for (int frame = 0; frame < 5000 && !result.Completed; frame++) + { + result.Step(); + result.SkipCurrent(); + } + Assert.That(result.Completed, Is.True); + Assert.That(result.ScreenOpacity, Is.Zero); + Assert.That(combat.Tick, Is.EqualTo(tick)); + Assert.That(combat.Events.Count, Is.EqualTo(events)); + Assert.That(combat.Result.Items.Single().Count, Is.EqualTo(3)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void LoseSequenceHasNoRewardStatisticsAndEndsWithMusicAfterScreenFade(string variant) + { + BattleSession combat = Finished(variant, false); + var result = new BattleResultPresentation(variant, combat.Result, combat.Events); + Assert.That(result.CameraList, Is.EqualTo(10)); + Assert.That(result.Sequence.Select(step => (step.Kind, step.Duration)), Is.EqualTo(new[] + { + (BattleResultStepKind.MusicFadeOut, .5f), (BattleResultStepKind.LoseBanner, 5f), + (BattleResultStepKind.ScreenFadeOut, 1f), (BattleResultStepKind.MusicFadeIn, .2f) + })); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void BannerFirstExecutionRejectsSkipAndUsesStrictNativeBoundary(string variant) + { + BattleSession combat = Finished(variant); + var result = new BattleResultPresentation(variant, combat.Result, combat.Events); + while (result.Current.Kind != BattleResultStepKind.WinBanner) + result.Step(); + Assert.That(result.SkipCurrent(), Is.False); + result.Step(); + Assert.That(result.HasExecuted, Is.True); + for (int frame = 1; frame < 150; frame++) + result.Step(); + Assert.That(result.Current.Kind, Is.EqualTo(BattleResultStepKind.WinBanner)); + Assert.That(result.Elapsed, Is.EqualTo(3).Within(.000001)); + result.Step(); + Assert.That(result.Current.Kind, Is.EqualTo(BattleResultStepKind.Statistics)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NativeReverseMusicRampAndStopAreIndependentOfSkip(string variant) + { + BattleSession combat = Finished(variant); + var result = new BattleResultPresentation(variant, combat.Result, combat.Events); + Assert.That(result.SkipCurrent(), Is.False); + result.Advance(.5); + Assert.That(result.MusicGain, Is.Zero.Within(.000001)); + Assert.That(result.MusicStopCount, Is.Zero); + result.Step(); + Assert.That(result.MusicStopCount, Is.EqualTo(1)); + while (result.Current.Kind != BattleResultStepKind.MusicFadeIn) + { + result.Step(); + result.SkipCurrent(); + } + result.Step(); + float first = result.MusicGain; + result.Step(); + Assert.That(result.MusicGain, Is.LessThan(first)); + while (result.Current.Kind == BattleResultStepKind.MusicFadeIn) + result.Step(); + Assert.That(result.MusicGain, Is.EqualTo(1)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void VictoryBodyWaitsForOneMessagePerPassAndFailedGotoRetainsPreviousClip(string variant) + { + var old = new BattlePhysicalAnimation("idle", 20, 1, gameBoxDuration: 480u); + var initial = new BattleBodyAnimationBinding(old); + initial.Advance(); + uint previous = initial.GameBoxTime; + var body = new BattleVictoryBody(variant, initial, null, old); + body.Step(); + Assert.That(body.Binding.CurrentAnimation, Is.SameAs(old)); + Assert.That(body.Binding.GameBoxTime, Is.GreaterThan(previous)); + Assert.That(initial.GameBoxTime, Is.EqualTo(previous)); + Assert.That(body.Binding.RequestedNativeActionIndex, Is.EqualTo(49)); + Assert.That(body.BladeSeconds, Is.EqualTo(.25f)); + for (int frame = 0; frame < 30 && !body.Completed; frame++) + body.Step(); + Assert.That(body.Completed, Is.True); + Assert.That(body.Binding.RequestedNativeActionIndex, Is.EqualTo(49)); + Assert.That(body.BladeSeconds, Is.EqualTo(.01f)); + body.Step(); + Assert.That(body.Binding.RequestedNativeActionIndex, Is.EqualTo(32)); + } + + [TestCase("PAL3", new[] { 4 })] + [TestCase("PAL3A", new[] { 4 })] + public void CommittedLevelLearningAndMagicGrowthEventsBecomeOrderedFiveSecondPrompts(string variant, int[] tiers) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Variant = variant; + scenario.DataFingerprint = "fixture"; + scenario.Participants[1].Vitals[0] = 0; + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 301, Mastered = true, Level = 1, Uses = 5 }); + int[] thresholds = Enumerable.Repeat(int.MaxValue, 101).ToArray(); + thresholds[0] = thresholds[1] = 0; + thresholds[2] = 10; + var definitions = new BattleDefinitions(variant, "fixture", new[] + { + new BattleAbilityDefinition(new BattleAbilityData { Id = 401, Name = "learned technique", SkillTypeId = 0, + ApplicableIdentities = new[] { 0 }, LearningLevel = 2 }), + new BattleAbilityDefinition(new BattleAbilityData { Id = 301, Name = "growing magic", IsMagic = true, + ApplicableIdentities = new[] { 0 }, UsesBeforeLevelUp = new[] { 0, 1, 3, 5 } }) + }, Array.Empty(), new[] + { + new BattleActorDefinition(new BattleActorData { InstanceId = "Ally", Identity = 0, ExperienceThresholds = thresholds, + AttributesByLevel = Enumerable.Range(0, 101).Select(_ => new int[12]).ToArray() }), + new BattleActorDefinition(new BattleActorData { InstanceId = "Enemy", ExperienceReward = 20 }) + }); + var combat = new BattleSession(new BattleSetup(scenario), new BattleSessionTests.Catalog(), definitions: definitions); + combat.Step(); + Assert.That(combat.Status, Is.EqualTo(BattleSessionStatus.Completed)); + var presentation = new BattleResultPresentation(variant, combat.Result, combat.Events); + BattleResultStep[] prompts = presentation.Sequence.Where(step => step.Kind is BattleResultStepKind.LevelUp or + BattleResultStepKind.SkillLearned or BattleResultStepKind.SkillImproved).ToArray(); + Assert.That(prompts[0].Kind, Is.EqualTo(BattleResultStepKind.LevelUp)); + Assert.That(prompts[0].Value, Is.EqualTo(2)); + Assert.That(prompts[1].Kind, Is.EqualTo(BattleResultStepKind.SkillLearned)); + Assert.That(prompts[1].Id, Is.EqualTo(401)); + Assert.That(prompts.Skip(2).Select(step => step.Value), Is.EqualTo(tiers)); + Assert.That(prompts.All(step => step.Duration == 5 && step.Actor == "Ally"), Is.True); + } + + [TestCase(0, 0, -256)] + [TestCase(0, .08, -246)] + [TestCase(0, .1, -240)] + [TestCase(0, .2, -195)] + [TestCase(0, .4, -15)] + [TestCase(0, .5, 0)] + [TestCase(1, .08, -256)] + [TestCase(1, .1, -255)] + [TestCase(1, .2, -234)] + [TestCase(1, .4, -102)] + [TestCase(1, .5, 0)] + [TestCase(2, .2, -253)] + [TestCase(2, .4, -169)] + [TestCase(2, .5, -82)] + [TestCase(2, .7, 0)] + [TestCase(3, .4, -217)] + [TestCase(3, .5, -154)] + [TestCase(3, .7, 0)] + public void StatisticsCardsMatchBothNativeGravityCallbacks(int column, double seconds, int y) + { + Assert.That(BattleResultStatistics.CardY(column, seconds), Is.EqualTo(y)); + } + + private sealed class ReadyRules : IBattleRules + { + private readonly BattleBasicRules _rules = new(); + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => _rules.GaugePerStep(actor); + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => + _rules.Hit(source, target, guarding, random, targetAtHome, damageDivisor); + } + + [TestCase("PAL3", false, 1, -2)] + [TestCase("PAL3A", false, 1, -2)] + [TestCase("PAL3", true, 0, 0)] + [TestCase("PAL3A", true, 1, -2)] + public void ResultRecoveryKeepsNativeAliveModelAndStateFlags(string variant, bool flee, int hp, int loveChange) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Variant = variant; + scenario.DataFingerprint = "fixture"; + scenario.Participants[0].Level = 100; + scenario.Participants[0].Attributes[5] = 20; + scenario.Participants[0].Attributes[6] = 100; + scenario.Participants[1].Vitals[0] = flee ? 100 : 0; + BattleParticipant dead = scenario.Participants[0].Copy(); + dead.InstanceId = "Dead"; + dead.Slot = BattleSlot.Fire; + dead.Vitals[0] = 0; + dead.Love = 50; + scenario.Participants.Add(dead); + var definitions = new BattleDefinitions(variant, "fixture", Array.Empty(), Array.Empty(), new[] + { + new BattleActorDefinition(new BattleActorData { InstanceId = "Ally", Identity = 0 }), + new BattleActorDefinition(new BattleActorData { InstanceId = "Dead", Identity = 1, + InitialStates = new[] { BattleState.PoisonFire, BattleState.Sleep, BattleState.Paralysis, BattleState.Invisible } }), + new BattleActorDefinition(new BattleActorData { InstanceId = "Enemy" }) + }); + var combat = new BattleSession(new BattleSetup(scenario), new BattleSessionTests.Catalog(), new ReadyRules(), definitions); + if (flee) + Assert.That(combat.Submit("Ally", BattleAction.Flee), Is.True); + for (int tick = 0; tick < 5000 && combat.Status == BattleSessionStatus.Running; tick++) + combat.Step(); + Assert.That(combat.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(combat.Result.Escaped, Is.EqualTo(flee)); + if (flee) + { + var presentation = new BattleResultPresentation(variant, combat.Result, combat.Events); + Assert.That(presentation.CameraList, Is.EqualTo(8)); + Assert.That(presentation.Sequence.Select(step => (step.Kind, step.Duration)), Is.EqualTo(new[] + { + (BattleResultStepKind.Statistics, 2f), (BattleResultStepKind.Wait, variant == "PAL3" ? 15f : 3f) + })); + } + BattleActorSnapshot final = combat.Result.Actors.Single(actor => actor.Id == "Dead"); + BattleActorSnapshot before = combat.Result.PreSettlementActors.Single(actor => actor.Id == "Dead"); + Assert.That(before.Hp, Is.Zero); + Assert.That(final.Hp, Is.EqualTo(hp)); + Assert.That(final.AliveFlag, Is.False); + Assert.That(final.ModelAliveFlag, Is.False); + Assert.That(final.Love - before.Love, Is.EqualTo(loveChange)); + if (flee) + Assert.That(before.States.Select(state => state.State), Does.Contain(BattleState.Death)); + Assert.That(final.States.Select(state => state.State), Is.EquivalentTo(before.States.Select(state => state.State))); + Assert.That(combat.Events.Skip(combat.Result.SettlementEventStart).Where(entry => entry.Kind == BattleEventKind.StatusRemoved).Any(entry => entry.Detail.Contains("post-result")), Is.False); + } + + [Test] + public void ClonedAnimationFifoAndClockRemainIndependent() + { + var animation = new BattlePhysicalAnimation("fixture", 10, 1, new[] + { + new BattlePhysicalMarker(1, BattlePhysicalMarkerKind.Other, 1, "sound"), + new BattlePhysicalMarker(1, BattlePhysicalMarkerKind.Over, 1, "over") + }); + var original = new BattleBodyAnimationBinding(animation); + original.Advance(); + BattleBodyAnimationBinding clone = original.Clone(); + clone.PopMessage(); + clone.ClearMessages(); + clone.Advance(); + Assert.That(original.PendingMessageCount, Is.EqualTo(2)); + Assert.That(original.GameBoxTime, Is.EqualTo(96)); + Assert.That(clone.GameBoxTime, Is.EqualTo(192)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleResultPresentationTests.cs.meta b/Assets/Tests/Battle/Editor/BattleResultPresentationTests.cs.meta new file mode 100644 index 00000000..c7026539 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleResultPresentationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9f2ad72cdb0b49048682bdec33a1c8d0 diff --git a/Assets/Tests/Battle/Editor/BattleResultRepairTests.cs b/Assets/Tests/Battle/Editor/BattleResultRepairTests.cs new file mode 100644 index 00000000..83395d1e --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleResultRepairTests.cs @@ -0,0 +1,265 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleResultRepairTests + { + private static BattlePhysicalAnimation Clip(string name, uint duration = 480) => new(name, 100, 1, gameBoxDuration: duration); + + [TestCase("PAL3", 49)] + [TestCase("PAL3A", 49)] + [TestCase("PAL3A", 59)] + public void NativeOverPassRetainsActionClipAndRateUntilTheFollowingFreePass(string variant, int action) + { + var clips = new Dictionary { [32] = Clip("idle"), [46] = Clip("dying"), [49] = Clip("win"), [59] = Clip("level") }; + var role = new BattleResultRoleBody(variant, new BattleBodyAnimationBinding(clips[32]), clips, + new BattleResultBodyState(1, 100), action == 49); + if (action == 59) + Assert.That(role.TryStartLevelUp(), Is.True); + role.Step(); + Assert.That(role.Binding.RequestedNativeActionIndex, Is.EqualTo(action)); + for (int frame = 0; frame < 30 && role.HasTask; frame++) + role.Step(); + Assert.That(role.HasTask, Is.False); + Assert.That(role.Binding.RequestedNativeActionIndex, Is.EqualTo(action)); + Assert.That(role.Binding.CurrentAnimation.Clip, Is.EqualTo(action == 49 ? "win" : "level")); + Assert.That(role.PlaybackRate, Is.EqualTo(variant == "PAL3" ? 1.3f : 1)); + Assert.That(role.BladeSeconds, Is.EqualTo(action == 49 ? .01f : .25f)); + role.Step(); + Assert.That(role.Binding.RequestedNativeActionIndex, Is.EqualTo(46)); + Assert.That(role.Binding.CurrentAnimation.Clip, Is.EqualTo("dying")); + Assert.That(role.BladeSeconds, Is.EqualTo(.01f)); + } + + [TestCase(0, false, false, false, 47)] + [TestCase(0, true, false, false, 47)] + [TestCase(1, false, false, false, 46)] + [TestCase(24, false, false, false, 46)] + [TestCase(25, false, false, false, 32)] + [TestCase(100, false, false, false, 32)] + [TestCase(1, true, false, false, 42)] + [TestCase(100, true, true, true, 42)] + [TestCase(1, false, true, false, 45)] + [TestCase(1, false, false, true, 45)] + public void ResultProperActionUsesNativeHpGuardAndSleepPrecedence(int hp, bool guard, bool sleep, bool stable, int action) + { + Assert.That(new BattleResultBodyState(hp, 100, guard, sleep, stable).ProperAction, Is.EqualTo(action)); + } + + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + public void NativeIntegerHpThresholdKeepsTinyMaximumHpZeroInTheOrdinaryAction(int maximum) + { + Assert.That(new BattleResultBodyState(0, maximum).ProperAction, Is.EqualTo(32)); + Assert.That(new BattleResultBodyState(0, maximum, true).ProperAction, Is.EqualTo(42)); + } + + [Test] + public void LevelUpWaitsForNormalWinReleaseButDoesNotWaitForItsOwnOver() + { + var clips = new Dictionary { [32] = Clip("idle"), [49] = Clip("win"), [59] = Clip("level", 48000) }; + var role = new BattleResultRoleBody("PAL3A", new BattleBodyAnimationBinding(clips[32]), clips, + new BattleResultBodyState(100, 100), true); + Assert.That(role.NormalGrab, Is.True); + Assert.That(role.TryStartLevelUp(), Is.False); + role.Step(); + while (role.HasTask) + role.Step(); + Assert.That(role.Owner, Is.EqualTo(BattleResultBodyOwner.Victory)); + Assert.That(role.TryStartLevelUp(), Is.False); + role.PrepareStagePass(); + Assert.That(role.Owner, Is.EqualTo(BattleResultBodyOwner.None)); + Assert.That(role.TryStartLevelUp(), Is.True); + Assert.That(role.Owner, Is.EqualTo(BattleResultBodyOwner.LevelUp)); + Assert.That(role.NormalGrab, Is.True); + role.Step(); + Assert.That(role.Binding.RequestedNativeActionIndex, Is.EqualTo(59)); + Assert.That(role.HasTask, Is.True); + } + + [TestCase(false, true)] + [TestCase(true, false)] + public void LevelUpCallbackForcesOnlyAnExistingNonNormalGrab(bool normal, bool acquired) + { + var role = new BattleResultRoleBody("PAL3A", new BattleBodyAnimationBinding(Clip("idle")), + new Dictionary(), new BattleResultBodyState(100, 100)); + Assert.That(role.TryGrab(BattleResultBodyOwner.External, normal), Is.True); + Assert.That(role.TryStartLevelUp(), Is.EqualTo(acquired)); + Assert.That(role.Owner, Is.EqualTo(acquired ? BattleResultBodyOwner.LevelUp : BattleResultBodyOwner.External)); + } + + private sealed class BodyPort : IBattleResultBodyPort + { + public BattleResultRoleBody Role; + + public bool TryStartLevelUp(string actor) => Role.TryStartLevelUp(); + } + + [Test] + public void NativeLevelUpCallbackWaitsForWinReleaseAndStartsTextInItsRegistrationPass() + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Variant = "PAL3A"; + scenario.DataFingerprint = "level"; + scenario.Participants[1].Vitals[0] = 0; + int[] thresholds = Enumerable.Repeat(int.MaxValue, 101).ToArray(); + thresholds[0] = thresholds[1] = 0; + thresholds[2] = 10; + var definitions = new BattleDefinitions("PAL3A", "level", Array.Empty(), Array.Empty(), new[] + { + new BattleActorDefinition(new BattleActorData { InstanceId = "Ally", ExperienceThresholds = thresholds, + AttributesByLevel = Enumerable.Range(0, 101).Select(_ => new int[12]).ToArray() }), + new BattleActorDefinition(new BattleActorData { InstanceId = "Enemy", ExperienceReward = 20 }) + }); + var combat = new BattleSession(new BattleSetup(scenario), new BattleSessionTests.Catalog(), definitions: definitions); + combat.Step(); + var clips = new Dictionary { [32] = Clip("idle"), [49] = Clip("win"), [59] = Clip("level", 48000) }; + var port = new BodyPort { Role = new BattleResultRoleBody("PAL3A", new BattleBodyAnimationBinding(clips[32]), clips, new BattleResultBodyState(100, 100), true) }; + var presentation = new BattleResultPresentation("PAL3A", combat.Result, combat.Events, port); + for (int frame = 0; frame < 100 && presentation.Current.Kind != BattleResultStepKind.LevelUpBody; frame++) + { + presentation.Step(); + presentation.SkipCurrent(); + } + Assert.That(presentation.Current.Kind, Is.EqualTo(BattleResultStepKind.LevelUpBody)); + presentation.Step(); + Assert.That(presentation.HasExecuted, Is.False); + Assert.That(presentation.CanSkip, Is.False); + port.Role.Step(); + while (port.Role.HasTask) + port.Role.Step(); + presentation.Step(); + Assert.That(presentation.Current.Kind, Is.EqualTo(BattleResultStepKind.LevelUpBody), "Win's normal grab is released by the next stage pass"); + port.Role.PrepareStagePass(); + presentation.Step(); + Assert.That(presentation.Current.Kind, Is.EqualTo(BattleResultStepKind.LevelUp)); + Assert.That(presentation.HasExecuted, Is.True); + Assert.That(presentation.Elapsed, Is.Zero); + port.Role.Step(); + Assert.That(port.Role.Binding.RequestedNativeActionIndex, Is.EqualTo(59)); + Assert.That(port.Role.HasTask, Is.True, "Five-second text begins without waiting for body59 Over"); + } + + private static BattleSession Growth(string variant, bool hasNext) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Variant = variant; + scenario.DataFingerprint = "phases"; + scenario.Participants[1].Vitals[0] = 0; + foreach ((int id, int group, int slot) in new[] { (316, 0, 0), (317, 0, 1), (319, 0, 2), (301, 3, 0), (302, 3, 1), (330, 5, 0), (331, 5, 1), (332, 5, 2) }) + scenario.Participants[0].Skills.Add(new BattleSkill { Id = id, NativeMagicGroup = group, NativeMagicSlot = slot, Mastered = id is 316 or 301, Uses = id is 316 or 301 ? 5 : 0 }); + BattleAbilityData Ability(int id, int group) => new() + { + Id = id, + IsMagic = true, + SkillTypeId = 1, + ElementMask = group == 0 ? 1 : group == 3 ? 4 : 5, + ApplicableIdentities = new[] { 0 }, + UsesBeforeLevelUp = new[] { 0, 1, 3, 5 }, + LearningLevel = 1, + NextSkillRequiredProficiency = 1 + }; + var data = scenario.Participants[0].Skills.Select(skill => Ability(skill.Id, skill.NativeMagicGroup)).ToDictionary(skill => skill.Id); + if (hasNext) + { + data[316].NextSkillId = 317; + data[317].NextSkillId = 319; + data[301].NextSkillId = 302; + data[316].Unlocks = new[] { new BattleSkillUnlock(330, 301, 4, 4, 1) }; + data[330].Unlocks = new[] { new BattleSkillUnlock(331, 301, 4, 1, 1) }; + data[319].Unlocks = new[] { new BattleSkillUnlock(332, 301, 4, 1, 1) }; + } + else + { + data[301].Unlocks = new[] { new BattleSkillUnlock(317, 316, 4, 4, 1) }; + data[317].Unlocks = new[] { new BattleSkillUnlock(332, 316, 1, 1, 1) }; + } + var definitions = new BattleDefinitions(variant, "phases", data.Values.Select(skill => new BattleAbilityDefinition(skill)), Array.Empty(), + new[] { new BattleActorDefinition(new BattleActorData { InstanceId = "Ally", Identity = 0 }), new BattleActorDefinition(new BattleActorData { InstanceId = "Enemy" }) }); + var combat = new BattleSession(new BattleSetup(scenario), new BattleSessionTests.Catalog(), definitions: definitions); + combat.Step(); + Assert.That(combat.Status, Is.EqualTo(BattleSessionStatus.Completed)); + return combat; + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void CompletePublishedMagicPhasesChooseHighestTiersAndRescanOnlyAfterNextLearning(string variant) + { + BattleSession combat = Growth(variant, true); + BattleEvent[] prompts = combat.Events.Where(entry => entry.Kind is BattleEventKind.SkillImproved or BattleEventKind.SkillLearned).ToArray(); + Assert.That(prompts.Select(entry => entry.AbilityId), Is.EqualTo(new[] { 316, 301, 330, 331, 317, 319, 302, 332 })); + Assert.That(prompts.Take(2).Select(entry => entry.ValueAfter), Is.EqualTo(new[] { 4, 4 })); + Assert.That(prompts.Skip(2).All(entry => entry.Kind == BattleEventKind.SkillLearned), Is.True); + BattleSession compositeOnly = Growth(variant, false); + Assert.That(compositeOnly.Events.Where(entry => entry.Kind is BattleEventKind.SkillImproved or BattleEventKind.SkillLearned).Select(entry => entry.AbilityId), + Is.EqualTo(new[] { 316, 301, 317 })); + Assert.That(compositeOnly.Result.Actors.Single(actor => actor.Id == "Ally").Skills.Single(skill => skill.Id == 332).Mastered, Is.False); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NativeMagicSlotsUseSixGroupsThenIdAndPreserveExplicitSaveSlots(string variant) + { + int[] ids = { 316, 301, 312, 330, 307, 345, 321 }; + int[] masks = { 1, 4, 1, 5, 8, 2, 16 }; + var definitions = new BattleDefinitions(variant, "layout", ids.Select((id, index) => new BattleAbilityDefinition(new BattleAbilityData + { + Id = id, + IsMagic = true, + SkillTypeId = 1, + ElementMask = masks[index], + ApplicableIdentities = new[] { 0 } + })), Array.Empty(), Array.Empty()); + var skills = new List(); + Assert.That(BattleMagicSlots.Capture(variant, definitions, 0, skills).Select(slot => slot.SkillId), Is.EqualTo(new[] { 312, 316, 345, 307, 301, 321, 330 })); + skills.Add(new BattleSkill { Id = 316, NativeMagicGroup = 0, NativeMagicSlot = 0 }); + skills.Add(new BattleSkill { Id = 312, NativeMagicGroup = 0, NativeMagicSlot = 1 }); + Assert.That(BattleMagicSlots.Capture(variant, definitions, 0, skills).Take(2).Select(slot => slot.SkillId), Is.EqualTo(new[] { 316, 312 })); + } + + [Test] + public void CataloguePreservesUnlearnedSlotsAndExcludesCombatOnlyFiveSpiritMagic() + { + var definitions = new BattleDefinitions("PAL3A", "layout", new[] + { + new BattleAbilityDefinition(new BattleAbilityData { Id = 264, IsMagic = true, SkillTypeId = 0, ElementMask = 1, ApplicableIdentities = new[] { 0 } }), + new BattleAbilityDefinition(new BattleAbilityData { Id = 312, IsMagic = true, SkillTypeId = 1, ElementMask = 1, ApplicableIdentities = new[] { 0 } }), + new BattleAbilityDefinition(new BattleAbilityData { Id = 316, IsMagic = true, SkillTypeId = 3, ElementMask = 1, ApplicableIdentities = new[] { 0 } }) + }, Array.Empty(), Array.Empty()); + IReadOnlyList slots = BattleMagicSlots.Capture("PAL3A", definitions, 0, + new[] { new BattleSkill { Id = 316, Mastered = true } }); + Assert.That(slots.Select(slot => (slot.SkillId, slot.Slot)), Is.EqualTo(new[] { (312, 0), (316, 1) })); + } + + [Test] + public void ScenarioRejectsDuplicateNativeMagicSlots() + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 301, NativeMagicGroup = 0, NativeMagicSlot = 0 }); + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 302, NativeMagicGroup = 0, NativeMagicSlot = 0 }); + Assert.That(scenario.Validate().Any(error => error.Contains("multiple skills occupy")), Is.True); + } + + [TestCase(-1, 0)] + [TestCase(0, -1)] + [TestCase(6, 0)] + [TestCase(0, 9)] + public void ScenarioRejectsHalfConfiguredOrOutOfBoundsNativeMagicSlots(int group, int slot) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 301, NativeMagicGroup = group, NativeMagicSlot = slot }); + Assert.That(scenario.Validate().Any(error => error.Contains("native magic group")), Is.True); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleResultRepairTests.cs.meta b/Assets/Tests/Battle/Editor/BattleResultRepairTests.cs.meta new file mode 100644 index 00000000..776d3af6 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleResultRepairTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 48e7832ce611448792235718101c3f31 diff --git a/Assets/Tests/Battle/Editor/BattleReviewBoundaryTests.cs b/Assets/Tests/Battle/Editor/BattleReviewBoundaryTests.cs new file mode 100644 index 00000000..f6a5b7b0 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleReviewBoundaryTests.cs @@ -0,0 +1,456 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleReviewBoundaryTests + { + private sealed class Catalog : IBattleCatalog, IBattlePal3AFormCatalog + { + public AttackTiming Attack(string source, string target) => new(0, 3, new[] { 1 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "P" ? 2 : 0; + + public int DamageDivisor(string actor) => 1; + + public BattlePhysicalAnimation FormChangeAnimation(string actorId, bool transformed) => new("z20", 2, 1, gameBoxDuration: 192); + + public void ActivatePal3AForm(string actorId, BattlePal3AFormKind kind) + { + } + } + + private static object Actor(BattleSession session, string id) => + ((IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session))[id]; + + private static object Invoke(BattleSession session, string name, params object[] arguments) => + typeof(BattleSession).GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic).Invoke(session, arguments); + + private static BattleSession Forms(bool transformed = false) + { + var scenario = new BattleScenario { Variant = "PAL3A", Scene = "fixture", DataFingerprint = "fixture", GameOverOnDefeat = false }; + scenario.Pal3A.NangongStartsTransformed = scenario.Pal3A.PengxuStartsTransformed = transformed; + scenario.Participants.AddRange(new[] + { + new BattleParticipant { InstanceId = "A", ActorId = 101, Side = BattleSide.Ally, Attributes = new[] { 1000, 100, 200, 100, 50, 5, 10, 0, 0, 0, 0, 0 }, Vitals = new[] { 777, 100, 200 } }, + new BattleParticipant { InstanceId = "P", ActorId = 103, Side = BattleSide.Ally, Slot = BattleSlot.Fire, Attributes = new[] { 2000, 100, 500, 100, 101, 5, 10, 0, 0, 0, 0, 0 }, Vitals = new[] { 1000, 100, 500 } }, + new BattleParticipant { InstanceId = "E", ActorId = 701, Side = BattleSide.Enemy, Attributes = new[] { 99999, 100, 500, 100, 30, 3, 0, 0, 0, 0, 0, 0 }, Vitals = new[] { 99999, 100, 500 } } + }); + var definitions = new BattleDefinitions("PAL3A", "fixture", Array.Empty(), Array.Empty(), new[] + { + new BattleActorDefinition(new BattleActorData { InstanceId = "A", Identity = 0 }), + new BattleActorDefinition(new BattleActorData { InstanceId = "P", Identity = 2 }), + new BattleActorDefinition(new BattleActorData { InstanceId = "E" }) + }); + return new BattleSession(new BattleSetup(scenario), new Catalog(), definitions: definitions); + } + + [TestCase("PAL3", int.MaxValue, 2f, 2147483606, 3357800067u)] + [TestCase("PAL3A", int.MaxValue, 2f, 2147483606, 3357800067u)] + [TestCase("PAL3", int.MinValue, 1f, 2147483607, 3357800067u)] + [TestCase("PAL3A", int.MinValue, 1f, 2147483607, 3357800067u)] + [TestCase("PAL3", 1, float.PositiveInfinity, -40, 3357800067u)] + [TestCase("PAL3A", 1, float.PositiveInfinity, -40, 3357800067u)] + [TestCase("PAL3", 100, .1f, 99, 3357800067u)] + [TestCase("PAL3A", 100, .1f, 99, 3357800067u)] + [TestCase("PAL3", 0, .1f, 0, 1u)] + [TestCase("PAL3A", 0, .1f, 0, 1u)] + [TestCase("PAL3", int.MaxValue, 0f, int.MaxValue, 1u)] + [TestCase("PAL3A", int.MaxValue, 0f, int.MaxValue, 1u)] + public void WarpSignedWidthMatchesNativeInt32AndRandomStream(string variant, int value, float fraction, int expected, uint seed) + { + var random = new BattleRandom(1, variant); + Assert.That(random.Warp(value, fraction), Is.EqualTo(expected)); + Assert.That(random.State, Is.EqualTo(seed)); + } + + private sealed class AiPort : BattleAiPort + { + public override int SceneFiveSpiritMode => 1; + + public override bool CanCast(int source, int skillId) => true; + + public override long TryAttempt(BattleAiAttempt attempt) => -1; + } + + [TestCase("PAL3", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", false)] + [TestCase("PAL3A", true)] + public void AiSelectionKeepsNativeSignedDistanceAtIntMinWeight(string variant, bool attack) + { + var random = new BattleRandom(1, variant); + var ai = new BattleAi(variant == "PAL3A", random, new AiPort()); + ai.Roles[5].Valid = ai.Roles[5].Alive = true; + ai.Roles[5].Skills = new[] { 10, 40, 100, 400 }.Select((power, index) => new BattleAiSkill + { + Id = 9001 + index, + Type = attack ? 2 : 3, + Range = attack ? 3 : 1, + Power = attack ? -power : power + }).ToArray(); + Assert.That(ai.SelectMagic(5, attack, false, int.MinValue), Is.EqualTo(9004)); + foreach (BattleAiSkill skill in ai.Roles[5].Skills) + { + skill.IsMagic = false; + skill.Type = 0; + } + Assert.That(ai.SelectSupport(5, attack ? BattleAiAttemptKind.AttackSkill : BattleAiAttemptKind.RecoverSkill, false, int.MinValue), Is.EqualTo(9004)); + Assert.That(random.State, Is.EqualTo(1u)); + } + + [Test] + public void FiveSpiritSelectionKeepsNativeSignedDistanceAtIntMinWeight() + { + var ai = new BattleAi(true, new BattleRandom(1, "PAL3A"), new AiPort()); + ai.Roles[0].Valid = ai.Roles[0].Alive = true; + ai.Roles[0].Skills = new[] + { + new BattleAiSkill { Id = 9001, Type = 2, Range = 4, Power = -10, ElementMask = 1 }, + new BattleAiSkill { Id = 265, Type = 2, Range = 4, Power = -40, ElementMask = 2 }, + new BattleAiSkill { Id = 264, Type = 2, Range = 4, Power = -100, ElementMask = 4 }, + new BattleAiSkill { Id = 9004, Type = 2, Range = 4, Power = -400, ElementMask = 8 } + }; + Assert.That(ai.SelectFiveSpiritMagic(0, true, int.MinValue), Is.EqualTo(9001)); + } + + [Test] + public void UndisplayedMpReturnRetainsNativeSignedAbsAtIntMin() + { + BattleSession session = Forms(); + int returned = (int)Invoke(session, "ChangeResource", Actor(session, "A"), 2, int.MinValue, null, 0L, "native return boundary", false); + Assert.That(returned, Is.EqualTo(int.MinValue)); + Assert.That(BattleSpecialRules.AbsorbedMp(returned), Is.EqualTo(int.MinValue)); + } + + [Test] + public void LiveFormationActorsRejectTransformedInitiatorsAndAuxiliaryMembers() + { + var requirement = new BattleComboRequirement(1, 0, new[] { 101, 103, 0, 0 }, new int[4], new int[4], new[] { -1, -1, -1 }); + var rules = new BattleFormationRules("PAL3A"); + BattleSession session = Forms(); + BattleFormationActor[] Formation() => new[] { "A", "P" }.Select(id => (BattleFormationActor)Invoke(session, "FormationActor", Actor(session, id))).ToArray(); + Assert.That(rules.CanCoAttack(0, 0, requirement, Formation()).Allowed, Is.True); + Invoke(session, "SwapPal3AForm", Actor(session, "A"), true); + Assert.That(rules.CanCoAttack(0, 0, requirement, Formation()).Allowed, Is.False); + Invoke(session, "SwapPal3AForm", Actor(session, "A"), false); + Invoke(session, "PreparePal3APengxuStats", Actor(session, "P")); + Invoke(session, "SwapPal3AForm", Actor(session, "P"), true); + Assert.That(rules.CanCoAttack(0, 0, requirement, Formation()).Allowed, Is.False); + } + + [TestCase(BattleSessionStatus.Aborted, null, false)] + [TestCase(BattleSessionStatus.Faulted, null, false)] + [TestCase(BattleSessionStatus.Completed, BattleSide.Enemy, false)] + [TestCase(BattleSessionStatus.Completed, BattleSide.Ally, true)] + public void StoppedFormsReturnHumanAttributesBeforeResultCapture(BattleSessionStatus status, BattleSide? winner, bool escaped) + { + BattleSession session = Forms(true); + typeof(BattleSession).GetField("_partyEscaped", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(session, escaped); + Invoke(session, "End", status, winner, "boundary fixture"); + Assert.That(session.Status, Is.EqualTo(status), session.Result.Reason); + BattleActorSnapshot pengxu = session.Result.Actors.Single(actor => actor.Id == "P"); + Assert.That((pengxu.Hp, pengxu.MaxHp, pengxu.Attributes[4], pengxu.Attributes[6]), Is.EqualTo((1000, 2000, 101, 10))); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "A").Attributes[6], Is.EqualTo(10)); + Assert.That(session.IsPal3ATransformed("A") || session.IsPal3ATransformed("P"), Is.False); + Assert.That(session.Pal3AForm("P").Pending, Is.False); + } + + [TestCase(false)] + [TestCase(true)] + public void StopBeforePengxuModelSwapRestoresQueuedStatsAndPreservesDeath(bool dead) + { + BattleSession session = Forms(); + object actor = Actor(session, "P"); + Invoke(session, "QueuePal3AFormChange", actor, true, false); + Assert.That(session.IsPal3ATransformed("P"), Is.False); + Assert.That(session.Actors.Single(value => value.Id == "P").MaxHp, Is.EqualTo(400)); + if (dead) + Invoke(session, "ChangeHp", actor, -1000, null, 0L, "pre-swap damage", false, false, false); + session.Abort(); + BattleActorSnapshot result = session.Result.Actors.Single(value => value.Id == "P"); + Assert.That((result.Hp, result.MaxHp, result.Attributes[4], result.Attributes[6]), Is.EqualTo((dead ? 0 : 1000, 2000, 101, 10))); + Assert.That(session.Pal3AForm("P").Pending, Is.False); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void MustFailSessionSurvivesEarthPoisonBeyondSignedInt32Damage(string variant) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Variant = variant; + scenario.MustFail = true; + scenario.DataFingerprint = "poison-boundary"; + scenario.Encounter = BattleEncounter.Normal; + scenario.Participants[1].Slot = BattleSlot.Center; + scenario.Participants[1].Attributes[0] = scenario.Participants[1].Vitals[0] = 1000000; + scenario.Participants[1].Statuses.Add(new BattleStatus { Id = (int)BattleState.PoisonEarth, Rounds = short.MaxValue }); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, Array.Empty(), Array.Empty(), scenario.Participants.Select(actor => + new BattleActorDefinition(new BattleActorData { InstanceId = actor.InstanceId }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), definitions: definitions); + session.SetAutomatic(BattleSide.Enemy, false); + object enemy = Actor(session, "Enemy"); + Type type = enemy.GetType(); + for (int round = 1; round <= 50; round++) + { + type.GetField("Rounds").SetValue(enemy, round); + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + } + Assert.That(session.Actors.Single(actor => actor.Id == "Enemy").Hp, Is.EqualTo(1000000)); + Assert.That(session.Events.Count(entry => entry.Target == "Enemy" && entry.Detail == "poison PoisonEarth" && entry.RequestedDelta == int.MinValue), Is.EqualTo(21)); + } + + [TestCase(0)] + [TestCase(2)] + public void CapturedLiaoRiLossesRejectAttributeOverflowBeforeCombatStarts(int resource) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Variant = "PAL3A"; + scenario.DataFingerprint = "loss-boundary"; + scenario.Participants[1].ActorId = BattlePal3ARules.LiaoRiCarryActor; + scenario.Pal3A.PreserveLiaoRiLosses = true; + int overflow = int.MaxValue - scenario.Participants[1].Attributes[resource] + 1; + if (resource == 0) + scenario.Pal3A.HpLoss = overflow; + else + scenario.Pal3A.MpLoss = overflow; + Assert.That(scenario.Validate(), Is.Empty); + var definitions = new BattleDefinitions("PAL3A", scenario.DataFingerprint, Array.Empty(), Array.Empty(), scenario.Participants.Select(actor => + new BattleActorDefinition(new BattleActorData { InstanceId = actor.InstanceId }))); + Assert.Throws(() => new BattleSession(new BattleSetup(scenario), new Catalog(), definitions: definitions)); + } + + [Test] + public void RuntimeLiaoRiCarryRetainsNativeInt32WrapAfterAuthoringValidation() + { + BattleSession session = Forms(); + object enemy = Actor(session, "E"); + ((BattleParticipant)enemy.GetType().GetField("Initial").GetValue(enemy)).ActorId = BattlePal3ARules.LiaoRiCarryActor; + typeof(BattleSession).GetField("_preserveLiaoRiLosses", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(session, true); + typeof(BattleSession).GetField("_pal3AHpLoss", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(session, int.MaxValue); + Assert.DoesNotThrow(() => Invoke(session, "ApplyPal3ALiaoRiCarry", enemy)); + Assert.That(session.Actors.Single(actor => actor.Id == "E").Hp, Is.EqualTo(unchecked(99999 + int.MaxValue))); + Assert.That(session.Pal3AState.PreserveLiaoRiLosses, Is.False); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void EarthPoisonKeepsNativeIndefiniteDamageThroughItsFullDuration(string variant) + { + var rules = new BattleStatusRules(variant); + BattleStatusInstance state = rules.Create(BattleState.PoisonEarth, 1000000); + int firstIndefinite = -1; + for (int round = 0; round < short.MaxValue; round++) + { + int delta = rules.TickRound(state, 1000000, 1000000); + if (delta == int.MinValue && firstIndefinite < 0) + firstIndefinite = round; + if (firstIndefinite >= 0) + Assert.That(delta, Is.EqualTo(int.MinValue)); + } + Assert.That(firstIndefinite, Is.EqualTo(29)); + Assert.That(float.IsNegativeInfinity(state.EarthDamage), Is.True); + Assert.That(state.RemainingRounds, Is.Zero); + } + + [TestCase(2147483520f, 2147483520)] + [TestCase(2147483648f, int.MinValue)] + [TestCase(-2147483904f, int.MinValue)] + [TestCase(float.PositiveInfinity, int.MinValue)] + [TestCase(float.NegativeInfinity, int.MinValue)] + [TestCase(float.NaN, int.MinValue)] + public void RoundMatchesPublishedMaskedFistp(float value, int expected) => Assert.That(BattleBasicRules.Round(value), Is.EqualTo(expected)); + + [Test] + public void OrbRetainsPublishedHalfSizeAndInt64TruncationAtTheRightEdge() + { + var orb = new BattleSpiritOrb(new BattleSpiritPoint(114, 0), new BattleSpiritRect(100, 100, 128, 128), 3.06f); + for (int frame = 1; frame <= 1000; frame++) + { + Assert.That(orb.Advance(.02f), Is.False); + if (frame == 500) + Assert.That(orb.Position.Y, Is.EqualTo(-1011351552)); + } + Assert.That((orb.Position.X, orb.Position.Y), Is.EqualTo((114f, 0f))); + var right = new BattleSpiritOrb(new BattleSpiritPoint(200, 0), new BattleSpiritRect(100, 100, 128, 128), 3.06f); + Assert.That(right.Advance(.02f), Is.True); + Assert.That((right.Position.X, right.Position.Y), Is.EqualTo((199f, 0f))); + } + + [TestCase(1u, 4294967293u)] + [TestCase(2u, 4294967294u)] + [TestCase(3u, uint.MaxValue)] + [TestCase(4u, 0u)] + public void ShortOneShotClipsRetainPublishedUnsignedGameBoxClock(uint duration, uint expected) + { + var binding = new BattleBodyAnimationBinding(new BattlePhysicalAnimation("short", 1, 1, gameBoxDuration: duration), false); + for (int frame = 0; frame < 3; frame++) + { + binding.Advance(); + Assert.That(binding.GameBoxTime, Is.EqualTo(expected)); + binding.PopMessage(); + Assert.That(binding.LastPoppedMarker, Is.EqualTo(BattlePhysicalMarkerKind.Over)); + } + } + + [Test] + public void PublicInputAndHitFlashReadsCannotWriteSessionHistoryOrCollections() + { + BattleSession session = Forms(); + session.SetAutomatic(BattleSide.Enemy, false); + BattleInput input = session.Inputs.Last(); + BattleInputKind kind = input.Kind; + input.Kind = BattleInputKind.Fault; + input.Tick = long.MaxValue; + input.Reason = "external mutation"; + Assert.That(session.Inputs.Last().Kind, Is.EqualTo(kind)); + Assert.That(session.Inputs.Last().Tick, Is.Zero); + Invoke(session, "ShowOriginalHitFlash", Actor(session, "E")); + var flashes = (IList)session.HitFlashes; + Assert.That(flashes.IsReadOnly, Is.True); + Assert.Throws(() => flashes[0] = null); + Assert.That(session.HitFlashes.Single(), Is.Not.Null); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ResultBodyBindingsAreDetachedForRoleAndVictoryControllers(string variant) + { + var animation = new BattlePhysicalAnimation("idle", 5, 1, new[] { new BattlePhysicalMarker(1, BattlePhysicalMarkerKind.Work) }); + var initial = new BattleBodyAnimationBinding(animation); + var role = new BattleResultRoleBody(variant, initial, new Dictionary { [32] = animation }, new BattleResultBodyState(100, 100)); + role.Step(); + BattleBodyAnimationBinding captured = role.Binding; + uint time = captured.GameBoxTime; + captured.Reset(); + captured.ClearMessages(); + captured.SetRequestedNativeAction(60); + Assert.That(role.Binding.GameBoxTime, Is.EqualTo(time)); + Assert.That(role.Binding.RequestedNativeActionIndex, Is.EqualTo(32)); + var victory = new BattleVictoryBody(variant, initial, animation, animation); + victory.Step(); + time = victory.Binding.GameBoxTime; + victory.Binding.Reset(); + Assert.That(victory.Binding.GameBoxTime, Is.EqualTo(time)); + } + + [TestCase(true)] + [TestCase(false)] + public void ScenarioRejectsDuplicateSkillAndStatusIdsBeforeSessionInitialization(bool skills) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + if (skills) + scenario.Participants[0].Skills.AddRange(new[] { new BattleSkill { Id = 301 }, new BattleSkill { Id = 301 } }); + else + scenario.Participants[0].Statuses.AddRange(new[] { new BattleStatus { Id = 1, Rounds = 2 }, new BattleStatus { Id = 1, Rounds = 3 } }); + Assert.That(scenario.Validate(), Is.Not.Empty); + Assert.Throws(() => new BattleSetup(scenario)); + } + + [Test] + public void ScenarioRejectsNullSkillAndStatusEntries() + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Participants[0].Skills.Add(null); + scenario.Participants[0].Statuses.Add(null); + Assert.That(scenario.Validate(), Has.Some.Contains("initial skill is missing")); + Assert.That(scenario.Validate(), Has.Some.Contains("initial status is missing")); + Assert.Throws(() => new BattleSetup(scenario)); + } + + [TestCase(-1, 0)] + [TestCase(0, -1)] + public void PreservedLossesRejectNegativeAuthoringValues(int hp, int mp) + { + var state = new BattlePal3AState { PreserveLiaoRiLosses = true, HpLoss = hp, MpLoss = mp }; + Assert.Throws(() => state.Validate()); + state.PreserveLiaoRiLosses = false; + Assert.DoesNotThrow(state.Validate); + } + + [TestCase(0, 20)] + [TestCase(252, 0)] + [TestCase(508, 0)] + [TestCase(1000000, 84)] + public void AtbRetainsPublishedByteStorageForAuthoredSpeeds(int speed, int expected) + { + BattleParticipant actor = BattleSessionTests.Scenario().Participants[0]; + actor.Attributes[5] = speed; + Assert.That(new BattleBasicRules().GaugePerStep(actor), Is.EqualTo(expected)); + } + + private static BattleSession ExtremeRewardSession(string variant) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Variant = variant; + scenario.DataFingerprint = "reward-boundary"; + scenario.Participants[1].Vitals[0] = 0; + BattleParticipant second = scenario.Participants[1].Copy(); + second.InstanceId = "Enemy2"; + second.Slot = BattleSlot.Fire; + scenario.Participants.Add(second); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, Array.Empty(), Array.Empty(), scenario.Participants.Select(actor => + new BattleActorDefinition(new BattleActorData { InstanceId = actor.InstanceId, ExperienceReward = int.MaxValue, MoneyReward = int.MaxValue }))); + return new BattleSession(new BattleSetup(scenario), new Catalog(), definitions: definitions); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ExtremeRewardTotalsUseNativeInt32AccumulationWithoutFaulting(string variant) + { + BattleSession session = ExtremeRewardSession(variant); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed), session.Result?.Reason); + Assert.That(session.Result.Rewards.Single().ExperienceGained, Is.EqualTo(-2)); + Assert.That(session.Result.MoneyAfter, Is.Zero); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void CompletedNativeSignedRewardsCanBeConsumedByResultStatistics(string variant) + { + BattleSession session = ExtremeRewardSession(variant); + BattleResult result = session.Result; + var presentation = new BattleResultPresentation(variant, result, session.Events); + for (int step = 0; step < 1000 && !presentation.StatisticsVisible; step++) + presentation.Step(); + Assert.That(presentation.StatisticsVisible, Is.True); + Assert.That(presentation.StatisticsSeconds, Is.Zero); + var experience = new List(); + for (int frame = 0; frame <= 100; frame++) + { + foreach (BattleActorSnapshot actor in presentation.Actors.Where(actor => actor.Side == BattleSide.Ally)) + { + BattleActorReward reward = result.Rewards.Single(value => value.Actor == actor.Id); + BattleActorSnapshot before = result.PreSettlementActors.Single(value => value.Id == actor.Id); + double seconds = presentation.StatisticsSeconds; + Assert.That(BattleResultStatistics.CardY(0, seconds), Is.InRange(-256, 0)); + Assert.That(BattleResultStatistics.MagicUseCounts(variant, session.Definitions, + session.Definitions.Actors[actor.Id].Identity, before.Skills), Is.EqualTo(new int[6])); + int projected = BattleResultStatistics.Experience(reward.ExperienceGained, seconds); + if (frame is 0 or 50 or 100) + experience.Add(projected); + } + presentation.Step(); + } + Assert.That(experience, Is.EqualTo(new[] { 0, -1, -2 })); + Assert.That(result.Rewards.Single().ExperienceGained, Is.EqualTo(-2)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleReviewBoundaryTests.cs.meta b/Assets/Tests/Battle/Editor/BattleReviewBoundaryTests.cs.meta new file mode 100644 index 00000000..4e83367e --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleReviewBoundaryTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ce7a534fca194325ae95b3d8d0797743 diff --git a/Assets/Tests/Battle/Editor/BattleSessionTests.cs b/Assets/Tests/Battle/Editor/BattleSessionTests.cs new file mode 100644 index 00000000..962c3ca0 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleSessionTests.cs @@ -0,0 +1,421 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleSessionTests + { + public sealed class Catalog : IBattleCatalog + { + public AttackTiming Timing = new(0, 10, new[] { 5 }); + public int HurtTicks = 2; + public AttackTiming EnemyTiming; + + public AttackTiming Attack(string source, string target) => source == "Enemy" && EnemyTiming != null ? EnemyTiming : Timing; + + public int GuardEntry(string actor) => 2; + + public int Hurt(string actor) => HurtTicks; + + public int SpImpact(string actor) => 8; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class ReadyRules : IBattleRules + { + private readonly BattleBasicRules _base = new(); + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => _base.GaugePerStep(actor); + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => _base.Hit(source, target, guarding, random, targetAtHome, damageDivisor); + } + + public static BattleScenario Scenario() + { + var scenario = new BattleScenario { Scene = "synthetic", Encounter = BattleEncounter.AllyAmbush }; + foreach (BattleSide side in Enum.GetValues(typeof(BattleSide))) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = side.ToString(), + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Attributes = new[] { 100, 50, 30, 40, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 100, 0, 30 } + }); + return scenario; + } + + [TestCase(BattleSessionStatus.Aborted)] + [TestCase(BattleSessionStatus.Faulted)] + [TestCase(BattleSessionStatus.Completed)] + public void TerminalSessionHasNoWaitingActor(BattleSessionStatus status) + { + var scenario = Scenario(); + if (status == BattleSessionStatus.Completed) + scenario.Participants[1].Vitals[0] = 0; + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new ReadyRules()); + if (status == BattleSessionStatus.Aborted) + session.Abort(); + else if (status == BattleSessionStatus.Faulted) + session.Fault("fixture"); + Assert.That(session.Status, Is.EqualTo(status)); + Assert.That(session.WaitingActor, Is.Null); + } + + private static string Trace(BattleSession session) => string.Join("\n", session.Events.Select(entry => + $"{entry.Tick}:{entry.Kind}:{entry.Source}:{entry.Target}:{entry.ActionId}:{entry.RequestedDelta}:{entry.ActualDelta}:{entry.Critical}:{entry.Dodged}:{entry.RandomState}:{entry.Detail}")); + + [TestCase(1, 26, 14, 3, 2, 14, 1, -12)] + [TestCase(20, 100, 20, 4, 9, 30, 1, -78)] + [TestCase(20, 100, 20, 4, 9, 30, 12345, -77)] + [TestCase(100, 500, 30, 5, 100, 100, 1, -641)] + [TestCase(100, 500, 30, 5, 100, 100, 12345, -576)] + [TestCase(1, 10, 10, 3, 1, 100, 1, 5)] + [TestCase(1, 10, 10, 3, 1, 100, 12345, 1)] + [TestCase(100, 2, 0, 9, 5, 1, 1, -2)] + public void MatchesNeutralDamageVectorsExecutedFromBothOriginalExecutables(int level, int attack, int defense, int speed, int luck, int targetDefense, int seed, int expected) + { + // Independent native oracle: workspace/Analysis/Battle-Stage2/probe-native-rules.py. + BattleScenario scenario = Scenario(); + BattleParticipant source = scenario.Participants[0], target = scenario.Participants[1]; + source.Level = level; + source.Attributes[3] = attack; + source.Attributes[4] = defense; + source.Attributes[5] = speed; + source.Attributes[6] = luck; + target.Attributes[4] = targetDefense; + Assert.That(new BattleBasicRules().NormalDamage(source, target, new BattleRandom(seed)), Is.EqualTo(expected)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ReplayReproducesCapturedInputsAndEvents(string variant) + { + BattleScenario scenario = Scenario(); + scenario.Variant = variant; + scenario.DataFingerprint = "replay-fixture"; + BattleDefinitions definitions = ReplayDefinitions(scenario); + var setup = new BattleSetup(scenario); + var catalog = new Catalog(); + var session = new BattleSession(setup, catalog, definitions: definitions); + session.Abort("recorded abort"); + bool created = false; + BattleSession replay = BattleReplay.Play(setup, catalog, session.Inputs, session.Tick, + definitions: definitions, onCreated: _ => created = true); + Assert.That(created, Is.True); + Assert.That(Trace(replay), Is.EqualTo(Trace(session))); + } + + private static BattleDefinitions ReplayDefinitions(BattleScenario scenario) => new(scenario.Variant, scenario.DataFingerprint, + Array.Empty(), Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1 + }))); + + [Test] + public void NativeRandomAndInitialGaugeUseIntegerRatioAndEncounterSide() + { + var random = new BattleRandom(1); + Assert.That(new[] { random.Next(), random.Next(), random.Next() }, Is.EqualTo(new[] { 41, 18467, 6334 })); + BattleScenario scenario = Scenario(); + scenario.Encounter = BattleEncounter.Normal; + var session = new BattleSession(new BattleSetup(scenario), new Catalog()); + Assert.That(session.Actors.Select(actor => actor.Gauge), Is.EqualTo(new[] { 1955, 2517 })); + session.Step(); + Assert.That(session.Actors.Select(actor => actor.Gauge), Is.EqualTo(new[] { 1990, 2552 })); + scenario.Encounter = BattleEncounter.EnemyAmbush; + session = new BattleSession(new BattleSetup(scenario), new Catalog()); + Assert.That(session.Actors.Select(actor => actor.Gauge), Is.EqualTo(new[] { 0, 11500 })); + } + + [Test] + public void ManualWaitStopsGaugesButNotAnAcceptedAttackAndNeverHitsBeforeMarker() + { + var session = new BattleSession(new BattleSetup(Scenario()), new Catalog()); + for (int i = 0; i < 10; i++) + session.Step(); + Assert.That(session.Actors[1].Gauge, Is.Zero); + Assert.That(session.Submit("Ally", BattleAction.Attack, "Enemy"), Is.True); + for (int i = 0; i < 4; i++) + session.Step(); + Assert.That(session.Actors[1].Hp, Is.EqualTo(100)); + session.Step(); + Assert.That(session.Actors[1].Hp, Is.LessThan(100)); + Assert.That(session.Actors[0].Gauge, Is.Zero); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Hit), Is.EqualTo(1)); + } + + [Test] + public void InvalidCommandsAndCancellationCannotRerollOrProduceDelayedHits() + { + var session = new BattleSession(new BattleSetup(Scenario()), new Catalog()); + string trace = Trace(session); + Assert.That(session.Submit("Ally", BattleAction.Attack, "Ally"), Is.False); + Assert.That(session.Submit("Enemy", BattleAction.Attack, "Ally"), Is.False); + Assert.That(Trace(session), Is.EqualTo(trace)); + session.Submit("Ally", BattleAction.Attack, "Enemy"); + session.Step(); + Assert.That(session.CancelAction("Ally"), Is.True); + Assert.That(session.CancelAction("Ally"), Is.False); + for (int i = 0; i < 15; i++) + session.Step(); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit), Is.False); + Assert.That(session.Actors[0].Gauge, Is.LessThan(BattleSession.FullGauge)); + } + + [Test] + public void GuardStartsAfterEntryHalvesDamageAndExpiresWhenGaugeFills() + { + var catalog = new Catalog(); + var session = new BattleSession(new BattleSetup(Scenario()), catalog, new ReadyRules()); + session.Submit("Ally", BattleAction.Defend); + session.Submit("Enemy", BattleAction.Attack, "Ally"); + session.Step(); + Assert.That(session.Actors[0].Guarding, Is.False); + session.Step(); + Assert.That(session.Actors[0].Guarding, Is.True); + for (int i = 0; i < 3; i++) + session.Step(); + BattleEvent hit = session.Events.Single(entry => entry.Kind == BattleEventKind.Hit); + Assert.That(hit.ActualDelta, Is.EqualTo(-16)); + Assert.That(session.Actors[0].Sp, Is.EqualTo(8)); + for (int i = 0; i < 400 && !session.Actors[0].Ready; i++) + session.Step(); + Assert.That(session.Actors[0].Ready, Is.True); + Assert.That(session.Actors[0].Guarding, Is.False); + Assert.That(session.Actors[0].Rounds, Is.EqualTo(1)); + } + + [Test] + public void SameTickLethalHitHasStablePriorityAndCancelsDeadActorsRemainingMarkers() + { + BattleScenario scenario = Scenario(); + foreach (BattleParticipant actor in scenario.Participants) + actor.Vitals[0] = 1; + var catalog = new Catalog { Timing = new AttackTiming(0, 10, new[] { 2, 4 }) }; + var session = new BattleSession(new BattleSetup(scenario), catalog, new ReadyRules()); + session.SetAutomatic(BattleSide.Ally, true); + session.SetAutomatic(BattleSide.Enemy, true); + for (int i = 0; i < 10; i++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Death), Is.EqualTo(1)); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Hit), Is.EqualTo(1)); + long stopped = session.Tick; + session.Advance(10); + Assert.That(session.Tick, Is.EqualTo(stopped)); + } + + [TestCase(30)] + [TestCase(60)] + [TestCase(144)] + public void FrameRateAndReplayProduceIdenticalEventsAndNaturalResult(int frameRate) + { + BattleScenario scenario = Scenario(); + var setup = new BattleSetup(scenario); + var catalog = new Catalog(); + var expected = new BattleSession(setup, catalog); + var actual = new BattleSession(setup, catalog); + foreach (BattleSession session in new[] { expected, actual }) + { + session.SetAutomatic(BattleSide.Ally, true); + session.SetAutomatic(BattleSide.Enemy, true); + } + for (int i = 0; i < 10000 && expected.Status == BattleSessionStatus.Running; i++) + expected.Step(); + for (int i = 0; i < 100000 && actual.Status == BattleSessionStatus.Running; i++) + actual.Advance(1.0 / frameRate); + Assert.That(actual.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(Trace(actual), Is.EqualTo(Trace(expected))); + BattleSession replay = BattleReplay.Play(setup, catalog, actual.Inputs, actual.Tick); + Assert.That(Trace(replay), Is.EqualTo(Trace(actual))); + Assert.That(scenario.Participants[0].Vitals[0], Is.EqualTo(100)); + } + + [Test] + public void BasicLethalHitRemovesDeadTargetsFromSnapshotsAndCommandValidation() + { + BattleScenario scenario = Scenario(); + scenario.Participants[1].Vitals[0] = 1; + BattleParticipant secondEnemy = scenario.Participants[1].Copy(); + secondEnemy.InstanceId = "Enemy2"; + secondEnemy.Slot = BattleSlot.Fire; + scenario.Participants.Add(secondEnemy); + var session = new BattleSession(new BattleSetup(scenario), new Catalog()); + Assert.That(session.Submit("Ally", BattleAction.Attack, "Enemy"), Is.True); + for (int i = 0; i < 10; i++) + session.Step(); + BattleActorSnapshot dead = session.Actors.Single(actor => actor.Id == "Enemy"); + Assert.That(dead.Hp, Is.Zero); + Assert.That(dead.Alive, Is.False); + Assert.That(dead.ModelAliveFlag, Is.False); + Assert.That(dead.Pose, Is.EqualTo(BattlePose.Dead)); + Assert.That(session.GetTargetCandidates(new BattleCommand("Ally", BattleAction.Attack)) + .Select(actor => actor.Id), Is.EqualTo(new[] { "Enemy2" })); + session.SetAutomatic(BattleSide.Enemy, true); + for (int i = 0; i < 1000 && session.WaitingActor != "Ally"; i++) + session.Step(); + Assert.That(session.WaitingActor, Is.EqualTo("Ally")); + Assert.That(session.CanSubmit("Ally", BattleAction.Attack, "Enemy"), Is.EqualTo("Choose a legal target for this action.")); + Assert.That(session.CanSubmit("Ally", BattleAction.Attack, "Enemy2"), Is.Null); + } + + [Test] + public void BasicAutomaticBattleProgressesPastFirstDefeatedEnemyAndReplays() + { + BattleScenario scenario = Scenario(); + scenario.Participants[1].Vitals[0] = 1; + BattleParticipant secondEnemy = scenario.Participants[1].Copy(); + secondEnemy.InstanceId = "Enemy2"; + secondEnemy.Slot = BattleSlot.Fire; + scenario.Participants.Add(secondEnemy); + var setup = new BattleSetup(scenario); + var catalog = new Catalog(); + var session = new BattleSession(setup, catalog); + session.SetAutomatic(BattleSide.Ally, true); + session.SetAutomatic(BattleSide.Enemy, true); + for (int i = 0; i < 1000 && session.Status == BattleSessionStatus.Running; i++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Death), Is.EqualTo(2)); + Assert.That(session.Result.Actors.Where(actor => actor.Side == BattleSide.Enemy) + .All(actor => !actor.Alive && !actor.ModelAliveFlag), Is.True); + Assert.That(Trace(BattleReplay.Play(setup, catalog, session.Inputs, session.Tick)), Is.EqualTo(Trace(session))); + } + + [Test] + public void EmptyLivingTeamsCompleteAndForcedStopIsNeverVictory() + { + BattleScenario scenario = Scenario(); + foreach (BattleParticipant actor in scenario.Participants) + actor.Vitals[0] = 0; + var session = new BattleSession(new BattleSetup(scenario), new Catalog()); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Result.Winner, Is.Null); + session = new BattleSession(new BattleSetup(Scenario()), new Catalog()); + session.Abort("test"); + Assert.That(session.Result.Status, Is.EqualTo(BattleSessionStatus.Aborted)); + Assert.That(session.Result.Winner, Is.Null); + } + + [Test] + public void MovingActorsWithEqualSpeedDoNotChaseEachOtherForever() + { + BattleScenario scenario = Scenario(); + scenario.Encounter = BattleEncounter.Normal; + foreach (BattleParticipant actor in scenario.Participants) + actor.Attributes[5] = 19; + var catalog = new Catalog { Timing = new AttackTiming(5, 10, new[] { 5 }) }; + var setup = new BattleSetup(scenario); + var session = new BattleSession(setup, catalog); + session.SetAutomatic(BattleSide.Ally, true); + session.SetAutomatic(BattleSide.Enemy, true); + for (int i = 0; i < 10000 && session.Status == BattleSessionStatus.Running; i++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit), Is.True); + Assert.That(Trace(BattleReplay.Play(setup, catalog, session.Inputs, session.Tick)), Is.EqualTo(Trace(session))); + } + + [Test] + public void ExternalFaultIsRecordedAndReplayedWithoutBecomingVictory() + { + var setup = new BattleSetup(Scenario()); + var catalog = new Catalog(); + var session = new BattleSession(setup, catalog); + session.Step(); + session.Fault("resource failure"); + BattleSession replay = BattleReplay.Play(setup, catalog, session.Inputs, session.Tick); + Assert.That(replay.Status, Is.EqualTo(BattleSessionStatus.Faulted)); + Assert.That(replay.Result.Winner, Is.Null); + Assert.That(Trace(replay), Is.EqualTo(Trace(session))); + } + + [Test] + public void UnsupportedInitialRulesRejectRatherThanSilentlyIgnore() + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].Statuses.Add(new BattleStatus { Id = 1 }); + Assert.Throws(() => new BattleSession(new BattleSetup(scenario), new Catalog())); + scenario.Participants[0].Statuses.Clear(); + scenario.RoundLimit = 2; + Assert.Throws(() => new BattleSession(new BattleSetup(scenario), new Catalog())); + } + + [Test] + public void HurtRecoveryPreventsImmediateCommandAndDefersInPlaceHitMarkers() + { + var setup = new BattleSetup(Scenario()); + var catalog = new Catalog { Timing = new AttackTiming(0, 20, new[] { 1, 5 }), HurtTicks = 10 }; + var session = new BattleSession(setup, catalog, new ReadyRules()); + session.SetAutomatic(BattleSide.Enemy, true); + session.Step(); + session.Step(); + Assert.That(session.Actors[0].Pose, Is.EqualTo(BattlePose.Hurt)); + Assert.That(session.Submit("Ally", BattleAction.Attack, "Enemy"), Is.False); + for (int i = 0; i < 9; i++) + session.Step(); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "Ally"), Is.False); + + session = new BattleSession(setup, catalog, new ReadyRules()); + session.Submit("Ally", BattleAction.Attack, "Enemy"); + session.Submit("Enemy", BattleAction.Attack, "Ally"); + session.Step(); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Hit), Is.EqualTo(1)); + Assert.That(session.Actors[1].ActionTick, Is.Zero, "Hurt pushes an in-place action instead of letting its marker fire through recovery."); + for (int i = 0; i < 5; i++) + session.Step(); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "Enemy"), Is.False); + } + + [TestCase(1, -6)] + [TestCase(12345, -6)] + public void NativeWeaponDivisorIsAppliedAfterWarpAndBeforeCritical(int seed, int expected) + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].Attributes[3] = 26; + scenario.Participants[1].Attributes[4] = 14; + Assert.That(new BattleBasicRules().NormalDamage(scenario.Participants[0], scenario.Participants[1], new BattleRandom(seed), 2), Is.EqualTo(expected)); + } + + [Test] + public void HurtRestartsPreHitAnimationButDiscardsMarkersAfterFirstWork() + { + var setup = new BattleSetup(Scenario()); + var catalog = new Catalog { Timing = new AttackTiming(0, 20, new[] { 10 }), EnemyTiming = new AttackTiming(0, 20, new[] { 1 }), HurtTicks = 10 }; + var session = new BattleSession(setup, catalog, new ReadyRules()); + session.Submit("Ally", BattleAction.Attack, "Enemy"); + session.Submit("Enemy", BattleAction.Attack, "Ally"); + for (int i = 0; i < 19; i++) + session.Step(); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "Ally"), Is.False); + session.Step(); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "Ally"), Is.EqualTo(1)); + + catalog = new Catalog { Timing = new AttackTiming(0, 20, new[] { 1, 5 }), EnemyTiming = new AttackTiming(0, 20, new[] { 1 }) }; + session = new BattleSession(setup, catalog, new ReadyRules()); + session.Submit("Ally", BattleAction.Attack, "Enemy"); + session.Submit("Enemy", BattleAction.Attack, "Ally"); + for (int i = 0; i < 20; i++) + session.Step(); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "Ally"), Is.EqualTo(1), "A pushed attack task is discarded after its first work marker."); + Assert.That(session.Actors[0].ActionId, Is.Zero); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleSessionTests.cs.meta b/Assets/Tests/Battle/Editor/BattleSessionTests.cs.meta new file mode 100644 index 00000000..de2fe18d --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleSessionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6e5d1023e3f1434b83bf973f73a5bdc0 diff --git a/Assets/Tests/Battle/Editor/BattleSnapshotTests.cs b/Assets/Tests/Battle/Editor/BattleSnapshotTests.cs new file mode 100644 index 00000000..900b2de8 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleSnapshotTests.cs @@ -0,0 +1,184 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Battle; + using Newtonsoft.Json; + using Newtonsoft.Json.Linq; + using NUnit.Framework; + + public sealed class BattleSnapshotTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 2; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + private static BattleScenario Scenario(string variant, bool completed = true) + { + BattleScenario scenario = BattleSessionTests.Scenario(); + scenario.Variant = variant; + scenario.DataFingerprint = "snapshot-fixture"; + scenario.Items.Add(new BattleItem { Id = 6201, Count = 3 }); + scenario.TreasureUses.Add(new BattleItem { Id = 6119, Count = 2 }); + scenario.Participants[0].Skills.Add(new BattleSkill + { + Id = 301, + Level = completed ? 2 : 4, + Uses = 7, + Mastered = true, + NativeMagicGroup = 1, + NativeMagicSlot = 3 + }); + if (completed) + scenario.Participants[1].Vitals[0] = 0; + return scenario; + } + + private static BattleSession Session(BattleScenario scenario) + { + var ability = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 301, + Name = "snapshot magic", + IsMagic = true, + SkillTypeId = 2, + ElementMask = 2, + ApplicableIdentities = new[] { 0 }, + Range = BattleTargetRange.OpponentSingle, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -20) } + }); + var definitions = new BattleDefinitions(scenario.Variant, scenario.DataFingerprint, + new[] { ability }, Array.Empty(), new[] + { + new BattleActorDefinition(new BattleActorData { InstanceId = "Ally", Identity = 0 }), + new BattleActorDefinition(new BattleActorData { InstanceId = "Enemy", LootItem = 6202, LootCount = 4 }) + }); + return new BattleSession(new BattleSetup(scenario), new Catalog(), definitions: definitions); + } + + [Test] + public void ValueSnapshotsCaptureAllAuthoringFieldsWithoutRetainingTheirSource() + { + var item = new BattleItem { Id = 6201, Count = 3 }; + var skill = new BattleSkill { Id = 301, Level = 2, Uses = 7, Mastered = true, NativeMagicGroup = 1, NativeMagicSlot = 3 }; + var capturedItem = new BattleItemSnapshot(item); + var capturedSkill = new BattleSkillSnapshot(skill); + item.Id = item.Count = 999; + skill.Id = skill.Level = skill.Uses = skill.NativeMagicGroup = skill.NativeMagicSlot = 999; + skill.Mastered = false; + Assert.That((capturedItem.Id, capturedItem.Count), Is.EqualTo((6201, 3))); + Assert.That((capturedSkill.Id, capturedSkill.Level, capturedSkill.Uses, capturedSkill.Mastered, + capturedSkill.NativeMagicGroup, capturedSkill.NativeMagicSlot), Is.EqualTo((301, 2, 7, true, 1, 3))); + Assert.Throws(() => new BattleItemSnapshot(null)); + Assert.Throws(() => new BattleSkillSnapshot(null)); + } + + [TestCase(typeof(BattleItemSnapshot))] + [TestCase(typeof(BattleSkillSnapshot))] + public void SnapshotElementsExposeOnlyGettersAndNoWritablePublicFields(Type type) + { + Assert.That(type.IsSealed, Is.True); + Assert.That(type.GetFields(BindingFlags.Instance | BindingFlags.Public), Is.Empty); + Assert.That(type.GetProperties(BindingFlags.Instance | BindingFlags.Public) + .All(property => property.GetMethod != null && property.SetMethod == null), Is.True); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RetainedResultsAndLiveReadsRejectCollectionWritesAndRemainIndependentOfAuthoring(string variant) + { + BattleScenario scenario = Scenario(variant); + BattleSession session = Session(scenario); + BattleResult result = session.Result; + Assert.That(result.Status, Is.EqualTo(BattleSessionStatus.Completed)); + BattleActorSnapshot actor = result.Actors.Single(value => value.Id == "Ally"); + AssertReadOnly(result.Items); + AssertReadOnly(result.Loot); + AssertReadOnly(result.TreasureUses); + AssertReadOnly(actor.Skills); + AssertReadOnly(session.Inventory); + AssertReadOnly(session.InventoryEntries); + AssertReadOnly(session.TreasureUses); + scenario.Items[0].Count = 999; + scenario.TreasureUses[0].Count = 999; + scenario.Participants[0].Skills[0].Uses = 999; + Assert.That(result.Items, Is.SameAs(result.Items)); + Assert.That(result.Actors[0].Skills, Is.SameAs(result.Actors[0].Skills)); + Assert.That(result.Items.Select(item => (item.Id, item.Count)), Is.EqualTo(new[] { (6201, 3), (6202, 4) })); + Assert.That(result.Loot.Select(item => (item.Id, item.Count)), Is.EqualTo(new[] { (6202, 4) })); + Assert.That(result.TreasureUses.Single().Count, Is.EqualTo(2)); + Assert.That(actor.Skills.Single().Uses, Is.EqualTo(7)); + Assert.That(session.Inventory.Select(item => (item.Id, item.Count)), Is.EqualTo(new[] { (6201, 3), (6202, 4) })); + Assert.That(session.Actors.Single(value => value.Id == "Ally").Skills.Single().Uses, Is.EqualTo(7)); + } + + private static void AssertReadOnly(IReadOnlyList values) + { + Assert.That(values, Is.Not.Empty); + var collection = (IList)values; + Assert.That(collection.IsReadOnly, Is.True); + Assert.Throws(() => collection[0] = collection[0]); + Assert.Throws(() => collection.Clear()); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void CapturedSkillValuesDoNotFollowLaterAuthoritativeSkillUse(string variant) + { + BattleSession session = Session(Scenario(variant, completed: false)); + BattleActorSnapshot before = session.Actors.Single(actor => actor.Id == "Ally"); + Assert.That(session.Submit(new BattleCommand("Ally", BattleAction.Skill, "Enemy", 301)), Is.True); + for (int tick = 0; tick < 10; tick++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running)); + Assert.That(before.Skills.Single().Uses, Is.EqualTo(7)); + Assert.That(session.Actors.Single(actor => actor.Id == "Ally").Skills.Single().Uses, Is.EqualTo(8)); + session.Abort(); + Assert.That(session.Result.Actors.Single(actor => actor.Id == "Ally").Skills.Single().Uses, Is.EqualTo(8)); + Assert.That(before.Skills.Single().Uses, Is.EqualTo(7)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void JsonReportExportPreservesEveryItemAndLearnedSkillField(string variant) + { + BattleSession session = Session(Scenario(variant)); + // Battle Editor report export uses the same default Newtonsoft settings. + JObject json = JObject.Parse(JsonConvert.SerializeObject(new + { + Result = session.Result + })); + JObject result = (JObject)json["Result"]; + Assert.That(JToken.DeepEquals(result["Items"], JArray.Parse("[{\"Id\":6201,\"Count\":3},{\"Id\":6202,\"Count\":4}]")), Is.True); + Assert.That(JToken.DeepEquals(result["Loot"], JArray.Parse("[{\"Id\":6202,\"Count\":4}]")), Is.True); + Assert.That(JToken.DeepEquals(result["TreasureUses"], JArray.Parse("[{\"Id\":6119,\"Count\":2}]")), Is.True); + JObject skill = (JObject)result["Actors"].Single(actor => (string)actor["Id"] == "Ally")["Skills"][0]; + Assert.That(skill.Properties().Select(property => property.Name), Is.EquivalentTo(new[] + { + "Id", "Level", "Uses", "Mastered", "NativeMagicGroup", "NativeMagicSlot" + })); + Assert.That(JToken.DeepEquals(skill, JObject.Parse("{\"Id\":301,\"Level\":2,\"Uses\":7,\"Mastered\":true,\"NativeMagicGroup\":1,\"NativeMagicSlot\":3}")), Is.True); + Assert.That(session.Actors.Single(actor => actor.Id == "Ally").Skills.Single().Uses, Is.EqualTo(7)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleSnapshotTests.cs.meta b/Assets/Tests/Battle/Editor/BattleSnapshotTests.cs.meta new file mode 100644 index 00000000..12c97b9e --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleSnapshotTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 336be4f6bfb34ec69818ffd8f1df1cc8 diff --git a/Assets/Tests/Battle/Editor/BattleSpecialMechanicsTests.cs b/Assets/Tests/Battle/Editor/BattleSpecialMechanicsTests.cs new file mode 100644 index 00000000..d4630445 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleSpecialMechanicsTests.cs @@ -0,0 +1,468 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Battle; + using NUnit.Framework; + + public sealed class BattleSpecialMechanicsTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string source, BattleAbilityDefinition ability) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class ReadyRules : IBattleRules + { + private readonly BattleBasicRules _original = new(); + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => _original.GaugePerStep(actor); + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) + => _original.Hit(source, target, guarding, random, targetAtHome, damageDivisor); + } + + private static BattleParticipant Participant(string id, BattleSide side, BattleSlot slot = BattleSlot.Water, int hp = 500) => new() + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = slot, + Attributes = new[] { 500, 100, 100, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { hp, 100, 100 } + }; + + private static BattleScenario Scenario(string variant = "PAL3") + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "special", Seed = 1 }; + scenario.Participants.Add(Participant("A", BattleSide.Ally)); + scenario.Participants.Add(Participant("E", BattleSide.Enemy)); + return scenario; + } + + private static BattleAbilityData Technique(string variant, BattleSpecialHandler handler, int attribute = 0, int value = -20) + { + int id = handler switch + { + BattleSpecialHandler.HalfActualHpAbsorb => variant == "PAL3" ? 4201 : 4301, + BattleSpecialHandler.ReturnedMpAbsorb => variant == "PAL3" ? 4304 : 4504, + BattleSpecialHandler.Steal => 4101, + BattleSpecialHandler.MoneyRecovery => variant == "PAL3" ? 4102 : 4106, + _ => variant == "PAL3" ? 4305 : 4206 + }; + return new BattleAbilityData + { + Id = id, + Handler = handler, + SkillTypeId = 0, + Range = BattleTargetRange.OpponentSingle, + Attributes = value == 0 ? Array.Empty() : new[] { new BattleAttributeEffect(attribute, BattleValueMode.Absolute, value) } + }; + } + + private static void Learn(BattleParticipant actor, int id, int level = 4) => actor.Skills.Add(new BattleSkill { Id = id, Level = level, Mastered = true }); + + private static BattleDefinitions Definitions(BattleScenario scenario, IEnumerable abilities, params BattleActorData[] actors) + { + BattleAbilityDefinition[] all = abilities.Select(data => new BattleAbilityDefinition(data)).ToArray(); + var overrides = actors.ToDictionary(actor => actor.InstanceId); + return new BattleDefinitions(scenario.Variant, scenario.DataFingerprint, all.Where(ability => !ability.IsItem), all.Where(ability => ability.IsItem), + scenario.Participants.Select(actor => new BattleActorDefinition(overrides.GetValueOrDefault(actor.InstanceId) ?? + new BattleActorData { InstanceId = actor.InstanceId, Identity = actor.Side == BattleSide.Ally ? 0 : -1 }))); + } + + private static BattleSession Session(BattleScenario scenario, IEnumerable abilities, params BattleActorData[] actors) + { + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new ReadyRules(), Definitions(scenario, abilities, actors)); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + + private static BattleActorSnapshot Actor(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + private static void Steps(BattleSession session, int count = 2) + { + for (int index = 0; index < count; index++) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + } + + [TestCase("PAL3", 98, 7, 1, 99, 7)] + [TestCase("PAL3A", 98, 7, 1, 99, 7)] + [TestCase("PAL3", 99, 7, 1, 99, 7)] + [TestCase("PAL3A", 99, 7, 1, 99, 7)] + [TestCase("PAL3", 90, 2, 1, 92, 2)] + [TestCase("PAL3A", 90, 2, 1, 92, 2)] + [TestCase("PAL3", int.MaxValue, 1, 1, int.MaxValue, 1)] + [TestCase("PAL3A", int.MaxValue, 1, 1, int.MaxValue, 1)] + [TestCase("PAL3", 0, 150, 20, 104, 104)] + [TestCase("PAL3A", 0, 150, 20, 104, 104)] + public void InventoryCapsGainsWithoutRemovingExistingStockOrReducingNewEntries(string variant, int before, int pool, int seed, int expected, int requested) + { + BattleScenario scenario = Scenario(variant); + scenario.Seed = seed; + if (before > 0) + scenario.Items.Add(new BattleItem { Id = 6201, Count = before }); + BattleAbilityData ability = Technique(variant, BattleSpecialHandler.Steal, value: 0); + Learn(scenario.Participants[0], ability.Id); + BattleSession session = Session(scenario, new[] { ability }, + new BattleActorData { InstanceId = "E", StealableItemId = 6201, StealableItemCount = pool }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Steps(session); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(expected)); + Assert.That(session.StealPools.Single(value => value.Actor == "E").ItemCount, Is.EqualTo(pool - requested)); + BattleEvent gain = session.Events.Single(entry => entry.Kind == BattleEventKind.ItemChanged); + Assert.That((gain.RequestedDelta, gain.ActualDelta), Is.EqualTo((requested, expected - before))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void HalfHpAbsorptionUsesActualOverkillLossAndRunsBeforeLethalSettlement(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[0].Vitals[0] = 400; + scenario.Participants[1].Vitals[0] = 5; + BattleAbilityData ability = Technique(variant, BattleSpecialHandler.HalfActualHpAbsorb); + ability.Costs = new[] { new BattleCost(1, BattleValueMode.Absolute, 10) }; + Learn(scenario.Participants[0], ability.Id); + BattleSession session = Session(scenario, new[] { ability }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Steps(session); + Assert.That(Actor(session, "A").Hp, Is.EqualTo(402)); + Assert.That(Actor(session, "A").Sp, Is.EqualTo(90)); + for (int index = 0; index < 1000 && session.Status == BattleSessionStatus.Running; index++) + session.Step(); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void MpAbsorptionUsesTheVariantsDisplayedResourceReturn(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.ForEach(actor => actor.Vitals[2] = 0); + BattleAbilityData ability = Technique(variant, BattleSpecialHandler.ReturnedMpAbsorb, 2, -150); + Learn(scenario.Participants[0], ability.Id); + BattleSession session = Session(scenario, new[] { ability }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Steps(session); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(variant == "PAL3" ? 100 : 0)); + Assert.That(Actor(session, "E").Mp, Is.Zero); + // Original full call chain: PAL3A showNum clamps the returned loss to zero; + // PAL3 does not display target MP and returns the warped request. + Assert.That(session.Events.Single(entry => entry.Detail == "native returned MP absorption").RequestedDelta, + Is.EqualTo(variant == "PAL3" ? 161 : 0)); + } + + [TestCase("PAL3", 0, 60)] // 洒金笺 charges for the last selected ally when the higher slot is dead. + [TestCase("PAL3", 490, 110)] + [TestCase("PAL3A", 490, 110)] + [TestCase("PAL3", 500, 120)] + [TestCase("PAL3A", 500, 120)] + public void MoneyRecoveryChecksTheWholePartyButOnlyChargesTheLastReturnedRecovery(string variant, int lastHp, int moneyAfter) + { + BattleScenario scenario = Scenario(variant); + int required = lastHp == 0 ? 80 : 120; + scenario.Money = required - 1; + scenario.Participants[0].Level = 10; + scenario.Participants[0].Vitals[0] = 400; + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire, lastHp)); + BattleAbilityData ability = Technique(variant, BattleSpecialHandler.MoneyRecovery, 0, 80); + ability.Range = BattleTargetRange.OwnAll; + ability.Costs = new[] { new BattleCost(10, BattleValueMode.Absolute, 80) }; + Learn(scenario.Participants[0], ability.Id); + var actors = new[] { new BattleActorData { InstanceId = "A", Identity = 0 }, new BattleActorData { InstanceId = "B", Identity = 1 } }; + BattleSession denied = Session(scenario, new[] { ability }, actors); + Assert.That(denied.CanSubmit(new BattleCommand("A", BattleAction.Skill, null, ability.Id)), Does.Contain(required.ToString())); + scenario.Money = 120; + BattleSession session = Session(scenario, new[] { ability }, actors); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, null, ability.Id)), Is.True); + Steps(session); + Assert.That(Actor(session, "A").Hp, Is.EqualTo(460)); + Assert.That(session.Money, Is.EqualTo(moneyAfter)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void MoneyThrowRequiresAndPaysRawThreeThousandInsteadOfTheRedundantOneThousandCheck(string variant) + { + BattleScenario scenario = Scenario(variant); + BattleAbilityData ability = Technique(variant, BattleSpecialHandler.MoneyThrow); + ability.Costs = new[] { new BattleCost(10, BattleValueMode.Absolute, 3000) }; + Learn(scenario.Participants[0], ability.Id); + scenario.Money = 2999; + Assert.That(Session(scenario, new[] { ability }).CanSubmit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Does.Contain("3000")); + scenario.Money = 3000; + BattleSession session = Session(scenario, new[] { ability }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Steps(session); + Assert.That(session.Money, Is.Zero); + } + + [TestCase("PAL3", 1000)] + [TestCase("PAL3A", 3000)] + public void ModifiedMoneyThrowCostKeepsTheReleasedVariantSpecificMinimum(string variant, int minimum) + { + BattleScenario scenario = Scenario(variant); + BattleAbilityData ability = Technique(variant, BattleSpecialHandler.MoneyThrow); + ability.Costs = new[] { new BattleCost(10, BattleValueMode.Absolute, 500) }; + Learn(scenario.Participants[0], ability.Id); + scenario.Money = minimum - 1; + Assert.That(Session(scenario, new[] { ability }).Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.False); + scenario.Money = minimum; + BattleSession session = Session(scenario, new[] { ability }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", ability.Id)), Is.True); + Steps(session); + Assert.That(session.Money, Is.EqualTo(minimum - 500)); + } + + [TestCase("PAL3", false, 0)] + [TestCase("PAL3A", false, 0)] + [TestCase("PAL3", true, 100)] + [TestCase("PAL3A", true, 100)] + public void PoisonDragonGallKillsOnlyTheUnpoisonedAndOtherwiseRemovesPoison(string variant, bool poisoned, int hpAfter) + { + BattleScenario scenario = Scenario(variant); + var target = Participant("B", BattleSide.Ally, BattleSlot.Fire, 100); + if (poisoned) + target.Statuses.Add(new BattleStatus { Id = (int)BattleState.PoisonWater, Rounds = 5 }); + scenario.Participants.Add(target); + scenario.Items.Add(new BattleItem { Id = 6230, Count = 1 }); + var item = new BattleAbilityData + { + Id = 6230, + IsItem = true, + Handler = BattleSpecialHandler.PoisonDragonGall, + ItemType = 1, + Range = BattleTargetRange.OwnSingle, + States = Enumerable.Range(0, 5).Select(state => new BattleStatusEffect((BattleState)state, true)).ToArray() + }; + BattleSession session = Session(scenario, new[] { item }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "B", 6230)), Is.True); + Steps(session); + Assert.That(Actor(session, "B").Hp, Is.EqualTo(hpAfter)); + Assert.That(Actor(session, "B").States, Is.Empty); + Assert.That(session.Inventory, Is.Empty); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void RandomPoisonConsumesOneRollOnlyWhenNoPoisonOrResistanceBlocksIt(string variant, bool alreadyPoisoned) + { + BattleScenario scenario = Scenario(variant); + if (alreadyPoisoned) + scenario.Participants[1].Statuses.Add(new BattleStatus { Id = (int)BattleState.PoisonWater, Rounds = 5 }); + var ability = new BattleAbilityData { Id = 254, IsMagic = true, Handler = BattleSpecialHandler.RandomPoison, Range = BattleTargetRange.OpponentSingle }; + Learn(scenario.Participants[0], ability.Id); + BattleSession session = Session(scenario, new[] { ability }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 254)), Is.True); + Steps(session); + Assert.That(Actor(session, "E").States.Single().State, Is.EqualTo(alreadyPoisoned ? BattleState.PoisonWater : BattleState.PoisonThunder)); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(alreadyPoisoned ? 1u : 2745024u)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void TreasureConsumesItsIndependentUseAtStartWithoutDeletingInventoryAndCancellationDoesNotRefund(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Items.Add(new BattleItem { Id = 6119, Count = 1 }); + scenario.TreasureUses.Add(new BattleItem { Id = 6119, Count = 1 }); + var item = new BattleAbilityData { Id = 6119, IsItem = true, IsTreasure = true, ItemType = 2, Range = BattleTargetRange.OpponentSingle }; + BattleDefinitions definitions = Definitions(scenario, new[] { item }); + BattleSession session = new(new BattleSetup(scenario), new Catalog(), new ReadyRules(), definitions); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "E", 6119)), Is.True); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(1)); + Assert.That(session.TreasureUses.Single().Count, Is.EqualTo(1)); + Steps(session, 1); + Assert.That(session.TreasureUses.Single().Count, Is.Zero); + Assert.That(session.CancelAction("A"), Is.True); + Steps(session); + var replay = BattleReplay.Play(new BattleSetup(scenario), new Catalog(), session.Inputs, session.Tick, new ReadyRules(), definitions); + Assert.That(replay.TreasureUses.Single().Count, Is.Zero); + Assert.That(replay.Inventory.Single().Count, Is.EqualTo(1)); + Assert.That(scenario.TreasureUses.Single().Count, Is.EqualTo(1)); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.TreasureUseChanged), Is.EqualTo(1)); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void CancellingAnItemBeforeTheFirstSystemPassRetainsItsStockAndUseCounter(string variant, bool treasure) + { + BattleScenario scenario = Scenario(variant); + int id = treasure ? 6119 : 6201; + scenario.Items.Add(new BattleItem { Id = id, Count = 1 }); + if (treasure) + scenario.TreasureUses.Add(new BattleItem { Id = id, Count = 1 }); + var item = new BattleAbilityData { Id = id, IsItem = true, IsTreasure = treasure, ItemType = 2, Range = BattleTargetRange.OpponentSingle }; + BattleSession session = Session(scenario, new[] { item }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "E", id)), Is.True); + Assert.That(session.CancelAction("A"), Is.True); + Steps(session, 10); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(1)); + if (treasure) + Assert.That(session.TreasureUses.Single().Count, Is.EqualTo(1)); + Assert.That(session.Events.Any(entry => entry.Kind is BattleEventKind.ItemChanged or BattleEventKind.TreasureUseChanged), Is.False); + } + + [Test] + public void Pal3aHasNoPoisonPearlResourceAndTreasureSnapshotsRejectDuplicateOrOutOfByteRangeCounters() + { + BattleScenario scenario = Scenario("PAL3A"); + scenario.TreasureUses.Add(new BattleItem { Id = 6125, Count = 1 }); + Assert.That(scenario.Validate(), Is.Not.Empty); + scenario.TreasureUses[0] = new BattleItem { Id = 6119, Count = 256 }; + Assert.That(scenario.Validate(), Is.Not.Empty); + scenario.TreasureUses[0].Count = 1; + scenario.TreasureUses.Add(scenario.TreasureUses[0].Copy()); + Assert.That(scenario.Validate(), Is.Not.Empty); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void StealUsesIndependentInstancePoolsMoneyThenItemsAndReplaysTheNativeTwoRollVector(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants.Add(Participant("E2", BattleSide.Enemy, BattleSlot.Fire)); + BattleAbilityData ability = Technique(variant, BattleSpecialHandler.Steal, value: 0); + Learn(scenario.Participants[0], ability.Id); + var actors = new[] { "E", "E2" }.Select(id => new BattleActorData { InstanceId = id, StealableMoney = 100, StealableItemId = 6201, StealableItemCount = 7 }).ToArray(); + BattleDefinitions definitions = Definitions(scenario, new[] { ability }, actors); + BattleSession session = new(new BattleSetup(scenario), new Catalog(), new ReadyRules(), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4101)), Is.True); + Steps(session); + Assert.That(session.Money, Is.EqualTo(42)); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(2)); + Assert.That(session.StealPools.Single(pool => pool.Actor == "E").Money, Is.EqualTo(58)); + Assert.That(session.StealPools.Single(pool => pool.Actor == "E").ItemCount, Is.EqualTo(5)); + Assert.That(session.StealPools.Single(pool => pool.Actor == "E2").Money, Is.EqualTo(100)); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(3357800067u)); + BattleSession replay = BattleReplay.Play(new BattleSetup(scenario), new Catalog(), session.Inputs, session.Tick, new ReadyRules(), definitions); + Assert.That(replay.Money, Is.EqualTo(session.Money)); + Assert.That(replay.StealPools.Single(pool => pool.Actor == "E").ItemCount, Is.EqualTo(5)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AttackStealPassiveUsesThePostHitProbabilityThenMoneyAndItemRolls(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Seed = 494; + var glove = new BattleEquipmentDefinition(new BattleEquipmentData { Id = 8130, Slot = 4, AttackStealPercent = 5 }); + BattleSession session = Session(scenario, Array.Empty(), + new BattleActorData { InstanceId = "A", Identity = 0, Equipment = new[] { glove } }, + new BattleActorData { InstanceId = "E", StealableMoney = 100, StealableItemId = 6201, StealableItemCount = 7 }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Attack, "E")), Is.True); + Steps(session); + Assert.That(session.Money, Is.EqualTo(16)); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(6)); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(3346129948u)); + } + + [TestCase("PAL3", 0)] + [TestCase("PAL3A", 6)] + public void EnemyItemTheftUsesTheOrderedRecoveryEntryPoolAndVariantSpecificRemovalQuantity(string variant, int remaining) + { + BattleScenario scenario = Scenario(variant); + scenario.Seed = 494; + scenario.Items.AddRange(new[] { new BattleItem { Id = 6202, Count = 3 }, new BattleItem { Id = 6113, Count = 5 }, new BattleItem { Id = 6201, Count = 7 } }); + BattleAbilityData[] items = new[] { 6201, 6202, 6113 }.Select(id => new BattleAbilityData + { + Id = id, + IsItem = true, + ItemType = id == 6113 ? 2 : 1, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, 1) } + }).ToArray(); + BattleSession session = Session(scenario, items, new BattleActorData { InstanceId = "E", NormalAttackMode = 914 }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Defend)), Is.True); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Attack, "A")), Is.True); + Steps(session); + Assert.That(session.Inventory.FirstOrDefault(item => item.Id == 6201)?.Count ?? 0, Is.EqualTo(remaining)); + Assert.That(session.Inventory.Single(item => item.Id == 6202).Count, Is.EqualTo(3)); + Assert.That(session.Inventory.Single(item => item.Id == 6113).Count, Is.EqualTo(5)); + Assert.That(session.InventoryEntries.First().Id, Is.EqualTo(6202)); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(1652494221u)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void TreasureWithoutAnExplicitUseSnapshotIsRejectedWithoutConsumingInventory(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Items.Add(new BattleItem { Id = 6119, Count = 1 }); + var item = new BattleAbilityData { Id = 6119, IsItem = true, IsTreasure = true, ItemType = 2, Range = BattleTargetRange.OpponentSingle }; + BattleSession session = Session(scenario, new[] { item }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "E", 6119)), Is.False); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(1)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.TreasureUseChanged), Is.False); + } + + [TestCase(false, 0, -100, 0)] + [TestCase(false, 5, -95, 5)] + [TestCase(false, 100, 0, 100)] + [TestCase(true, 5, -45, 5)] + [TestCase(true, 100, 0, 50)] + public void NativeMoneyShieldVectorsApplyAfterGuardAndUseMoneyBeforeHp(bool guard, int money, int remaining, int paid) + { + int request = guard ? -50 : -100; + Assert.That(BattleSpecialRules.ShieldedHpRequest(request, money, out int payment), Is.EqualTo(remaining)); + Assert.That(payment, Is.EqualTo(paid)); + } + + [Test] + public void MoneyShieldPreventsHpAndSleepChangesButThePhysicalSecondSlotInterruptPrecedesPayment() + { + BattleScenario scenario = Scenario(); + scenario.Money = 1000; + var ability = new BattleAbilityData { Id = 301, IsMagic = true, Range = BattleTargetRange.OpponentSingle }; + Learn(scenario.Participants[0], 301, 1); + BattleSession session = Session(scenario, new[] { ability }, new BattleActorData { InstanceId = "A", Identity = 0, MoneyShield = true }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 301)), Is.True); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Attack, "A")), Is.True); + Steps(session); + Assert.That(Actor(session, "A").Hp, Is.EqualTo(500)); + Assert.That(Actor(session, "A").CurrentAction, Is.Null); + Assert.That(Actor(session, "A").Gauge, Is.GreaterThanOrEqualTo(5750)); + Assert.That(session.Money, Is.LessThan(1000)); + } + + [TestCase("PAL3", 415139642u)] + [TestCase("PAL3A", 3357800067u)] + public void StartupInvisibilityRollFollowsEveryInitialGaugeAndDuplicateCharmsStillRollOnce(string variant, uint seedAfter) + { + BattleScenario scenario = Scenario(variant); + var charm = new BattleEquipmentDefinition(new BattleEquipmentData { Id = 8114, Slot = 4, StartupInvisibility = true }); + BattleDefinitions definitions = Definitions(scenario, Array.Empty(), new BattleActorData { InstanceId = "A", Identity = 0, Equipment = new[] { charm, charm } }); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new BattleBasicRules(), definitions); + Assert.That(Actor(session, "A").Gauge, Is.EqualTo(1955)); + Assert.That(Actor(session, "E").Gauge, Is.EqualTo(2517)); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(seedAfter)); + Assert.That(Actor(session, "A").States, Is.Empty); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleSpecialMechanicsTests.cs.meta b/Assets/Tests/Battle/Editor/BattleSpecialMechanicsTests.cs.meta new file mode 100644 index 00000000..918b6d8f --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleSpecialMechanicsTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f10946ba18584efdaf4867dae31796cf diff --git a/Assets/Tests/Battle/Editor/BattleStageSchedulerTests.cs b/Assets/Tests/Battle/Editor/BattleStageSchedulerTests.cs new file mode 100644 index 00000000..58d266a9 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleStageSchedulerTests.cs @@ -0,0 +1,420 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleStageSchedulerTests + { + // Golden cases execute the released EXE allocator, DoTask, and numeric + // comparison suffix. The activation/body callbacks are explicit fixtures. + // workspace/Analysis/Battle-Stage4/review-scheduler-native.py records them. + public static IEnumerable NativeNumberCases() + { + yield return new TestCaseData("PAL3", 2.0f, 0L, false, 0L, 101L, 102L); + yield return new TestCaseData("PAL3", 2.0f, 0L, true, 0L, 101L, 102L); + yield return new TestCaseData("PAL3", 2.0f, 1L, false, 0L, 102L, 103L); + yield return new TestCaseData("PAL3", 2.0f, 1L, true, 0L, 102L, 103L); + yield return new TestCaseData("PAL3", 2.0f, 7L, false, 0L, 107L, 108L); + yield return new TestCaseData("PAL3", 2.0f, 7L, true, 0L, 107L, 108L); + yield return new TestCaseData("PAL3", 2.0f, 51L, false, 0L, 152L, 153L); + yield return new TestCaseData("PAL3", 2.0f, 51L, true, 0L, 152L, 153L); + yield return new TestCaseData("PAL3", 2.0f, 1000L, false, 0L, 1101L, 1102L); + yield return new TestCaseData("PAL3", 2.0f, 1000L, true, 0L, 1101L, 1102L); + yield return new TestCaseData("PAL3", 2.5f, 0L, false, 0L, 126L, 127L); + yield return new TestCaseData("PAL3", 2.5f, 0L, true, 0L, 126L, 127L); + yield return new TestCaseData("PAL3", 2.5f, 1L, false, 0L, 127L, 128L); + yield return new TestCaseData("PAL3", 2.5f, 1L, true, 0L, 127L, 128L); + yield return new TestCaseData("PAL3", 2.5f, 7L, false, 0L, 132L, 133L); + yield return new TestCaseData("PAL3", 2.5f, 7L, true, 0L, 132L, 133L); + yield return new TestCaseData("PAL3", 2.5f, 51L, false, 0L, 177L, 178L); + yield return new TestCaseData("PAL3", 2.5f, 51L, true, 0L, 177L, 178L); + yield return new TestCaseData("PAL3", 2.5f, 1000L, false, 0L, 1126L, 1127L); + yield return new TestCaseData("PAL3", 2.5f, 1000L, true, 0L, 1126L, 1127L); + yield return new TestCaseData("PAL3", 2.0f, 0L, false, 1L, 101L, 102L); + yield return new TestCaseData("PAL3", 2.0f, 0L, true, 1L, 102L, 103L); + yield return new TestCaseData("PAL3", 2.0f, 1L, false, 1L, 102L, 103L); + yield return new TestCaseData("PAL3", 2.0f, 1L, true, 1L, 103L, 104L); + yield return new TestCaseData("PAL3", 2.0f, 7L, false, 1L, 107L, 108L); + yield return new TestCaseData("PAL3", 2.0f, 7L, true, 1L, 108L, 109L); + yield return new TestCaseData("PAL3", 2.0f, 51L, false, 1L, 152L, 153L); + yield return new TestCaseData("PAL3", 2.0f, 51L, true, 1L, 153L, 154L); + yield return new TestCaseData("PAL3", 2.0f, 1000L, false, 1L, 1101L, 1102L); + yield return new TestCaseData("PAL3", 2.0f, 1000L, true, 1L, 1102L, 1103L); + yield return new TestCaseData("PAL3", 2.5f, 0L, false, 1L, 126L, 127L); + yield return new TestCaseData("PAL3", 2.5f, 0L, true, 1L, 127L, 128L); + yield return new TestCaseData("PAL3", 2.5f, 1L, false, 1L, 127L, 128L); + yield return new TestCaseData("PAL3", 2.5f, 1L, true, 1L, 128L, 129L); + yield return new TestCaseData("PAL3", 2.5f, 7L, false, 1L, 132L, 133L); + yield return new TestCaseData("PAL3", 2.5f, 7L, true, 1L, 133L, 134L); + yield return new TestCaseData("PAL3", 2.5f, 51L, false, 1L, 177L, 178L); + yield return new TestCaseData("PAL3", 2.5f, 51L, true, 1L, 178L, 179L); + yield return new TestCaseData("PAL3", 2.5f, 1000L, false, 1L, 1126L, 1127L); + yield return new TestCaseData("PAL3", 2.5f, 1000L, true, 1L, 1127L, 1128L); + yield return new TestCaseData("PAL3A", 2.0f, 0L, false, 0L, 101L, 102L); + yield return new TestCaseData("PAL3A", 2.0f, 0L, true, 0L, 101L, 102L); + yield return new TestCaseData("PAL3A", 2.0f, 1L, false, 0L, 102L, 103L); + yield return new TestCaseData("PAL3A", 2.0f, 1L, true, 0L, 102L, 103L); + yield return new TestCaseData("PAL3A", 2.0f, 7L, false, 0L, 107L, 108L); + yield return new TestCaseData("PAL3A", 2.0f, 7L, true, 0L, 107L, 108L); + yield return new TestCaseData("PAL3A", 2.0f, 51L, false, 0L, 152L, 153L); + yield return new TestCaseData("PAL3A", 2.0f, 51L, true, 0L, 152L, 153L); + yield return new TestCaseData("PAL3A", 2.0f, 1000L, false, 0L, 1101L, 1102L); + yield return new TestCaseData("PAL3A", 2.0f, 1000L, true, 0L, 1101L, 1102L); + yield return new TestCaseData("PAL3A", 2.5f, 0L, false, 0L, 126L, 127L); + yield return new TestCaseData("PAL3A", 2.5f, 0L, true, 0L, 126L, 127L); + yield return new TestCaseData("PAL3A", 2.5f, 1L, false, 0L, 127L, 128L); + yield return new TestCaseData("PAL3A", 2.5f, 1L, true, 0L, 127L, 128L); + yield return new TestCaseData("PAL3A", 2.5f, 7L, false, 0L, 132L, 133L); + yield return new TestCaseData("PAL3A", 2.5f, 7L, true, 0L, 132L, 133L); + yield return new TestCaseData("PAL3A", 2.5f, 51L, false, 0L, 177L, 178L); + yield return new TestCaseData("PAL3A", 2.5f, 51L, true, 0L, 177L, 178L); + yield return new TestCaseData("PAL3A", 2.5f, 1000L, false, 0L, 1126L, 1127L); + yield return new TestCaseData("PAL3A", 2.5f, 1000L, true, 0L, 1126L, 1127L); + yield return new TestCaseData("PAL3A", 2.0f, 0L, false, 1L, 101L, 102L); + yield return new TestCaseData("PAL3A", 2.0f, 0L, true, 1L, 102L, 103L); + yield return new TestCaseData("PAL3A", 2.0f, 1L, false, 1L, 102L, 103L); + yield return new TestCaseData("PAL3A", 2.0f, 1L, true, 1L, 103L, 104L); + yield return new TestCaseData("PAL3A", 2.0f, 7L, false, 1L, 107L, 108L); + yield return new TestCaseData("PAL3A", 2.0f, 7L, true, 1L, 108L, 109L); + yield return new TestCaseData("PAL3A", 2.0f, 51L, false, 1L, 152L, 153L); + yield return new TestCaseData("PAL3A", 2.0f, 51L, true, 1L, 153L, 154L); + yield return new TestCaseData("PAL3A", 2.0f, 1000L, false, 1L, 1101L, 1102L); + yield return new TestCaseData("PAL3A", 2.0f, 1000L, true, 1L, 1102L, 1103L); + yield return new TestCaseData("PAL3A", 2.5f, 0L, false, 1L, 126L, 127L); + yield return new TestCaseData("PAL3A", 2.5f, 0L, true, 1L, 127L, 128L); + yield return new TestCaseData("PAL3A", 2.5f, 1L, false, 1L, 127L, 128L); + yield return new TestCaseData("PAL3A", 2.5f, 1L, true, 1L, 128L, 129L); + yield return new TestCaseData("PAL3A", 2.5f, 7L, false, 1L, 132L, 133L); + yield return new TestCaseData("PAL3A", 2.5f, 7L, true, 1L, 133L, 134L); + yield return new TestCaseData("PAL3A", 2.5f, 51L, false, 1L, 177L, 178L); + yield return new TestCaseData("PAL3A", 2.5f, 51L, true, 1L, 178L, 179L); + yield return new TestCaseData("PAL3A", 2.5f, 1000L, false, 1L, 1126L, 1127L); + yield return new TestCaseData("PAL3A", 2.5f, 1000L, true, 1L, 1127L, 1128L); + } + + [TestCaseSource(nameof(NativeNumberCases))] + public void NativeNumberLifetime(string variant, float duration, long createdTick, bool blocked, + long firstAdvanceDelay, long finishTick, long deleteTick) + { + var scheduler = new BattleStageScheduler(); + var trace = new List(); + var number = new BattleStageNumber(duration, context => trace.Add("start:" + context.Tick), + blocked ? context => trace.Add("block:" + context.Tick) : null); + BattleStageHandle handle = scheduler.Add("target", "number", number, BattleStageScheduler.TimeAt(createdTick)); + Assert.That(trace, Is.Empty, variant); + for (long tick = createdTick + firstAdvanceDelay; tick <= deleteTick; tick++) + { + scheduler.Advance(tick); + Assert.That(number.Finished, Is.EqualTo(tick >= finishTick), variant + ": " + tick); + Assert.That(scheduler.IsActive(handle), Is.EqualTo(tick < deleteTick), variant + ": " + tick); + Assert.That(scheduler.CountOwner("target"), Is.EqualTo(tick < deleteTick ? 1 : 0)); + } + Assert.That(trace, Is.EqualTo(blocked + ? new[] { "block:" + (createdTick + firstAdvanceDelay), "start:" + (createdTick + firstAdvanceDelay) } + : new[] { "start:" + (createdTick + firstAdvanceDelay) })); + } + + [TestCase("PAL3", "emptyAfter", 1, 0)] + [TestCase("PAL3", "emptyBefore", 0, 1)] + [TestCase("PAL3", "filledBefore", 4, 0)] + [TestCase("PAL3", "bodyAfterStage", 0, 1)] + [TestCase("PAL3A", "emptyAfter", 1, 0)] + [TestCase("PAL3A", "emptyBefore", 0, 1)] + [TestCase("PAL3A", "filledBefore", 4, 0)] + [TestCase("PAL3A", "bodyAfterStage", 0, 1)] + public void NativeSlotInsertion(string variant, string layout, int expectedSlot, long expectedActivation) + { + var scheduler = new BattleStageScheduler(); + var trace = new List(); + BattleStageHandle number = default; + bool CreateNumber(BattleStageContext context) + { + trace.Add("create:" + context.Tick); + number = scheduler.Add("target", "number", new BattleStageNumber(2f, + numberContext => trace.Add("start:" + numberContext.Tick)), context.Time); + trace.Add("slot:" + number.Slot); + return true; + } + var holes = new List(); + if (layout is "emptyBefore" or "filledBefore") + { + for (int i = 0; i < 3; i++) + holes.Add(scheduler.Add("placeholder", "idle", new Job(_ => false), 0f)); + } + if (layout != "bodyAfterStage") + scheduler.Add("source", "ability", new Job(CreateNumber), 0f); + if (layout == "emptyBefore") + { + foreach (BattleStageHandle hole in holes) + scheduler.Cancel(hole); + } + scheduler.Advance(0); + if (layout == "bodyAfterStage") + { + trace.Add("create:0"); + number = scheduler.Add("target", "number", new BattleStageNumber(2f, + context => trace.Add("start:" + context.Tick)), 0f); + trace.Add("slot:" + number.Slot); + } + scheduler.Advance(1); + Assert.That(trace, Is.EqualTo(new[] { "create:0", "slot:" + expectedSlot, "start:" + expectedActivation }), variant); + } + + [Test] + public void FinishingKeepsOwnerCountUntilNextPass() + { + var scheduler = new BattleStageScheduler(); + int calls = 0; + BattleStageHandle handle = scheduler.Add("actor", "action", new Job(_ => + { + calls++; + return true; + }), 0f); + scheduler.Advance(0); + Assert.That(calls, Is.EqualTo(1)); + Assert.That(scheduler.CountOwner("actor"), Is.EqualTo(1)); + Assert.That(scheduler.Snapshot()[0].Finished, Is.True); + scheduler.Advance(1); + Assert.That(calls, Is.EqualTo(1)); + Assert.That(scheduler.IsActive(handle), Is.False); + Assert.That(scheduler.Count, Is.Zero); + } + + [Test] + public void CancelledHandleCannotCancelReusedSlot() + { + var scheduler = new BattleStageScheduler(1); + BattleStageHandle old = scheduler.Add("old", "number", new Job(_ => false), 0f); + Assert.That(scheduler.Cancel(old), Is.True); + BattleStageHandle replacement = scheduler.Add("new", "action", new Job(_ => false), 0f); + Assert.That(replacement.Slot, Is.EqualTo(old.Slot)); + Assert.That(replacement.Id, Is.Not.EqualTo(old.Id)); + Assert.That(scheduler.Cancel(old), Is.False); + Assert.That(scheduler.IsActive(replacement), Is.True); + } + + [Test] + public void SelfCancellationDoesNotFinishReplacement() + { + var scheduler = new BattleStageScheduler(1); + int replacementCalls = 0; + BattleStageHandle replacement = default; + scheduler.Add("old", "action", new Job(context => + { + Assert.That(scheduler.Cancel(context.Handle), Is.True); + replacement = scheduler.Add("new", "number", new Job(_ => + { + replacementCalls++; + return false; + }), context.Time); + return true; + }), 0f); + scheduler.Advance(0); + Assert.That(replacementCalls, Is.Zero); + Assert.That(scheduler.Snapshot()[0].Finished, Is.False); + scheduler.Advance(1); + Assert.That(replacementCalls, Is.EqualTo(1)); + Assert.That(scheduler.IsActive(replacement), Is.True); + } + + [Test] + public void CallbackCanCancelLaterSlotBeforeItRuns() + { + var scheduler = new BattleStageScheduler(); + BattleStageHandle later = default; + int calls = 0; + scheduler.Add("source", "action", new Job(_ => + { + scheduler.Cancel(later); + return true; + }), 0f); + later = scheduler.Add("target", "action", new Job(_ => + { + calls++; + return false; + }), 0f); + scheduler.Advance(0); + Assert.That(calls, Is.Zero); + Assert.That(scheduler.IsActive(later), Is.False); + } + + [Test] + public void SnapshotsRetainValuesAndRejectCollectionMutation() + { + var scheduler = new BattleStageScheduler(); + BattleStageHandle handle = scheduler.Add("actor", "action", new Job(_ => true), 0.14f); + IReadOnlyList before = scheduler.Snapshot(); + scheduler.Advance(7); + Assert.That(before.Count, Is.EqualTo(1)); + Assert.That(before[0].Handle, Is.EqualTo(handle)); + Assert.That(before[0].Owner, Is.EqualTo("actor")); + Assert.That(before[0].Kind, Is.EqualTo("action")); + Assert.That(before[0].CreatedTime, Is.EqualTo(0.14f)); + Assert.That(before[0].Finished, Is.False); + IReadOnlyList finished = scheduler.Snapshot(); + scheduler.Advance(8); + Assert.That(finished[0].Finished, Is.True); + Assert.That(before[0].Finished, Is.False); + Assert.Throws(() => ((IList)before).Clear()); + } + + [TestCase(false, 101L)] + [TestCase(true, 102L)] + public void DelayedActivationPreservesCreationTimeUnlessBodyBlocks(bool blocked, long expectedFinish) + { + var scheduler = new BattleStageScheduler(); + int starts = 0; + int blocks = 0; + var number = new BattleStageNumber(2f, _ => starts++, blocked ? _ => blocks++ : null); + scheduler.Add("target", "number", number, 0f); + for (long tick = 1; tick <= expectedFinish; tick++) + { + scheduler.Advance(tick); + Assert.That(number.Finished, Is.EqualTo(tick == expectedFinish)); + } + Assert.That(number.StartTime, Is.EqualTo(blocked ? BattleStageScheduler.TimeAt(1) : 0f)); + Assert.That(starts, Is.EqualTo(1)); + Assert.That(blocks, Is.EqualTo(blocked ? 1 : 0)); + } + + [Test] + public void FloatStartAndDoubleDifferenceCanFinishOneTickEarlier() + { + var scheduler = new BattleStageScheduler(); + var number = new BattleStageNumber(2f, _ => { }); + scheduler.Add("target", "number", number, BattleStageScheduler.TimeAt(7)); + scheduler.Advance(7); + scheduler.Advance(106); + Assert.That(number.Finished, Is.False); + float now = BattleStageScheduler.TimeAt(107); + Assert.That(now - number.StartTime, Is.EqualTo(2f)); + Assert.That((double)now - number.StartTime, Is.GreaterThan(2d)); + scheduler.Advance(107); + Assert.That(number.Finished, Is.True); + } + + [Test] + public void DurationEqualityDoesNotFinishNumber() + { + var scheduler = new BattleStageScheduler(); + var number = new BattleStageNumber(2f, _ => { }); + scheduler.Add("target", "miss", number, 0f); + scheduler.Advance(0); + scheduler.Advance(100); + Assert.That(number.Finished, Is.False); + scheduler.Advance(101); + Assert.That(number.Finished, Is.True); + } + + [Test] + public void DefaultCapacityMatchesOriginalPool() + { + var scheduler = new BattleStageScheduler(); + for (int i = 0; i < 256; i++) + Assert.That(scheduler.Add("actor", "action", new Job(_ => false), 0f).Slot, Is.EqualTo(i)); + Assert.Throws(() => scheduler.Add("actor", "number", new Job(_ => false), 0f)); + } + + [Test] + public void HandleFromOtherPoolCannotCancelTask() + { + var first = new BattleStageScheduler(); + var second = new BattleStageScheduler(); + BattleStageHandle handle = first.Add("actor", "action", new Job(_ => false), 0f); + BattleStageHandle other = second.Add("actor", "action", new Job(_ => false), 0f); + Assert.That(handle, Is.Not.EqualTo(other)); + Assert.That(second.Cancel(handle), Is.False); + Assert.That(second.Count, Is.EqualTo(1)); + Assert.That(first.IsActive(default), Is.False); + } + + [Test] + public void RecursiveAdvanceIsRejectedAndPassCanRecover() + { + var scheduler = new BattleStageScheduler(); + scheduler.Add("actor", "action", new Job(context => + { + Assert.Throws(() => scheduler.Advance(context.Tick)); + return true; + }), 0f); + scheduler.Advance(0); + scheduler.Advance(1); + Assert.That(scheduler.Count, Is.Zero); + } + + [Test] + public void CancellationDetachesBeforeNotificationAndPreservesReplacementSlot() + { + var scheduler = new BattleStageScheduler(1); + BattleStageHandle handle = default, replacement = default; + int cancellations = 0, advances = 0; + handle = scheduler.Add("actor", "owning", new CancellableJob(() => + { + cancellations++; + Assert.That(scheduler.Cancel(handle), Is.False); + Assert.That(scheduler.Count, Is.Zero); + replacement = scheduler.Add("next", "replacement", new Job(_ => + { + advances++; + return true; + }), 0f); + }), 0f); + Assert.That(scheduler.Cancel(handle), Is.True); + Assert.That(scheduler.Cancel(handle), Is.False); + Assert.That(cancellations, Is.EqualTo(1)); + Assert.That(scheduler.IsActive(replacement), Is.True); + scheduler.Advance(0); + scheduler.Advance(1); + Assert.That(advances, Is.EqualTo(1)); + Assert.That(scheduler.Count, Is.Zero); + } + + [TestCase(false)] + [TestCase(true)] + public void FinishedTaskRemovalDoesNotNotifyCancellation(bool autoDelete) + { + var scheduler = new BattleStageScheduler(); + int cancellations = 0; + BattleStageHandle handle = scheduler.Add("actor", "finished", new CancellableJob(() => cancellations++, true), 0f, autoDelete); + scheduler.Advance(0); + if (autoDelete) + scheduler.Advance(1); + else + Assert.That(scheduler.Cancel(handle), Is.True); + Assert.That(cancellations, Is.Zero); + Assert.That(scheduler.Count, Is.Zero); + } + + private sealed class CancellableJob : IBattleStageCancellableJob + { + private readonly Action _cancel; + private readonly bool _finished; + + internal CancellableJob(Action cancel, bool finished = false) + { + _cancel = cancel; + _finished = finished; + } + + public bool Advance(BattleStageContext context) => _finished; + + public void Cancel() => _cancel(); + } + + private sealed class Job : IBattleStageJob + { + private readonly Func _advance; + + internal Job(Func advance) => _advance = advance; + + public bool Advance(BattleStageContext context) => _advance(context); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleStageSchedulerTests.cs.meta b/Assets/Tests/Battle/Editor/BattleStageSchedulerTests.cs.meta new file mode 100644 index 00000000..7776d088 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleStageSchedulerTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 930f765b99a84f3a8eb070d33e03f328 diff --git a/Assets/Tests/Battle/Editor/BattleStockAttackModeTests.cs b/Assets/Tests/Battle/Editor/BattleStockAttackModeTests.cs new file mode 100644 index 00000000..caf6535b --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleStockAttackModeTests.cs @@ -0,0 +1,33 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using Battle; + using NUnit.Framework; + + public sealed class BattleStockAttackModeTests + { + [TestCase("PAL3", 0)] + [TestCase("PAL3A", 0)] + [TestCase("PAL3A", 7714)] + public void StockExceptionsUseThePublishedDefaultPhysicalBranches(string variant, int mode) + { + // Full InitRoleState and AttackSpecAffect execution, both releases. + Assert.That(BattlePhysicalAttackModes.UnsupportedReason(variant, mode), Is.Empty); + Assert.That(BattlePhysicalAttackModes.Range(mode), Is.EqualTo(BattleTargetRange.OpponentSingle)); + Assert.That(BattlePhysicalAttackModes.AddedState(mode), Is.Null); + } + + [TestCase("PAL3", 7714)] + [TestCase("PAL3A", 7711)] + [TestCase("PAL3", -1)] + [TestCase("PAL3A", 999)] + public void AnUnverifiedDataValueStillHasAnExplicitDiagnostic(string variant, int mode) + { + Assert.That(BattlePhysicalAttackModes.UnsupportedReason(variant, mode), Is.Not.Empty); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleStockAttackModeTests.cs.meta b/Assets/Tests/Battle/Editor/BattleStockAttackModeTests.cs.meta new file mode 100644 index 00000000..999e86c5 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleStockAttackModeTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 30b3289fb1d742bca8ea123d754f6819 diff --git a/Assets/Tests/Battle/Editor/BattleSummonFleeOwnershipTests.cs b/Assets/Tests/Battle/Editor/BattleSummonFleeOwnershipTests.cs new file mode 100644 index 00000000..20cb0b48 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleSummonFleeOwnershipTests.cs @@ -0,0 +1,170 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleSummonFleeOwnershipTests + { + private const int Summon = 2001, FinishEncounter = 2002; + + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattlePhysicalTimings, IBattleStageGeometry, IBattleMonsterFactory + { + private readonly string _variant; + + internal Catalog(string variant) => _variant = variant; + + public int Priority(string actor) => actor == "Ally" ? 0 : 5; + + public int GuardEntry(string actor) => 2; + + public int Hurt(string actor) => 5; + + public int SpImpact(string actor) => 1; + + public int DamageDivisor(string actor) => 1; + + public AttackTiming Attack(string source, string target) => new(0, 10, new[] { 4 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 30, new[] { 3 }); + + public BattlePhysicalStageProfile Physical(string actor) => new(_variant, actor == "Ally" ? 101 : 701, + actor == "Ally" ? 0 : -1, 1, 1, Enum.GetValues(typeof(BattlePose)).Cast().ToDictionary(pose => pose, + pose => new BattlePhysicalAnimation(pose.ToString(), 10, 10, + new[] { new BattlePhysicalMarker(4, BattlePhysicalMarkerKind.Work), new BattlePhysicalMarker(9, BattlePhysicalMarkerKind.Over) }))); + + // Keep the native escape boundary short enough to put the summon + // Work immediately before the old enemy-flee callback on tick 3. + public BattleMovementPoint InitialHome(string actor) => actor == "Fleeing" ? new(790, 0, 790) : new(0, 0, actor == "Ally" ? 0 : 200); + + public BattleMovementPoint FormationHome(string actor, BattleSlot slot) => InitialHome(actor); + + public IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint from, BattleMovementPoint to, bool crossing) => + new[] { new BattleMovementPlan(BattleMovementKind.Run, from, to) }; + + public BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint from, BattleMovementPoint to) => + new(Attack(source, target), from, from, to); + + public BattleMonsterCreation Prepare(int nativeIndex, int actorId, string instanceId) => + new(nativeIndex, Participant(instanceId, BattleSide.Enemy, (BattleSlot)(nativeIndex - 5), actorId), + new BattleActorDefinition(new BattleActorData { InstanceId = instanceId })); + + public void Commit(BattleMonsterCreation creation) + { + } + } + + private sealed class Rules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + actor.InstanceId == "Fleeing" ? BattleSession.FullGauge - 1 : BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => 700; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => new(-100, false, false); + } + + private static BattleParticipant Participant(string id, BattleSide side, BattleSlot slot, int actorId = 701) => new() + { + InstanceId = id, + ActorId = actorId, + Side = side, + Slot = slot, + Level = 10, + Attributes = new[] { 1000, 100, 200, 60, 50, 4, 10, 0, 0, 0, 0, 0 }, + Vitals = new[] { 1000, 100, 200 } + }; + + private static (BattleSetup Setup, BattleDefinitions Definitions, BattleSession Session) Create(string variant) + { + var scenario = new BattleScenario { Variant = variant, Scene = "native-slot", DataFingerprint = "native-slot", Seed = variant == "PAL3" ? 1 : 2 }; + scenario.Participants.Add(Participant("Ally", BattleSide.Ally, BattleSlot.Water, 101)); + scenario.Participants.Add(Participant("Fleeing", BattleSide.Enemy, variant == "PAL3" ? BattleSlot.Water : BattleSlot.Fire)); + scenario.Participants.Add(Participant("Summoner", BattleSide.Enemy, BattleSlot.Center)); + scenario.Participants[0].Skills.Add(new BattleSkill { Id = FinishEncounter, Level = 4, Mastered = true }); + scenario.Participants[2].Skills.Add(new BattleSkill { Id = Summon, Level = 4, Mastered = true }); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, new[] + { + new BattleAbilityDefinition(new BattleAbilityData { Id = Summon, IsMagic = true, Range = BattleTargetRange.OpponentSingle, Handler = BattleSpecialHandler.Summon }), + new BattleAbilityDefinition(new BattleAbilityData { Id = FinishEncounter, Range = BattleTargetRange.OpponentAll, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -1000000) } }) + }, Array.Empty(), scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1, + EscapePercent = actor.InstanceId == "Fleeing" ? 100 : 0 + }))); + var setup = new BattleSetup(scenario); + var session = new BattleSession(setup, new Catalog(variant), new Rules(), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + return (setup, definitions, session); + } + + private static void Advance(BattleSession session, Func done, int maximum = 1000) + { + for (int step = 0; step < maximum && !done() && session.Status == BattleSessionStatus.Running; step++) + { + if (session.WaitingActor is { } waiting) + Assert.That(session.Submit(waiting, BattleAction.Defend), Is.True); + session.Step(); + } + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + Assert.That(done(), Is.True); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void OrdinaryEnemyFleeKeepsItsBodyUntilEscapeThenReleasesTheStage(string variant) + { + BattleSession session = Create(variant).Session; + Assert.That(session.Submit("Ally", BattleAction.Defend), Is.True); + Assert.That(session.Submit("Summoner", BattleAction.Defend), Is.True); + session.Step(); + Assert.That(session.Actors.Single(actor => actor.Id == "Fleeing").Fleeing, Is.True); + Assert.That(session.StageTasks.Single(task => task.Kind == "enemy flee").Finished, Is.False); + var group = new BattleCommand("Ally", BattleAction.Skill, abilityId: FinishEncounter); + Assert.That(session.GetTargetCandidates(group).Select(target => target.Id), Is.EqualTo(new[] { "Summoner" })); + Advance(session, () => session.Actors.Single(actor => actor.Id == "Fleeing").Escaped); + Advance(session, () => session.StageTasks.All(task => task.Kind != "enemy flee")); + Assert.That(session.Events.Count(entry => entry.Source == "Fleeing" && entry.Kind == BattleEventKind.Escaped), Is.EqualTo(1)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void SummoningIntoTheJustEscapedSlotReleasesTheOldBodyLeaseAndReplays(string variant) + { + var fixture = Create(variant); + BattleSession session = fixture.Session; + Assert.That(session.Submit("Ally", BattleAction.Defend), Is.True); + Assert.That(session.Submit(new BattleCommand("Summoner", BattleAction.Skill, "Ally", Summon)), Is.True); + for (int step = 0; step < 3; step++) + session.Step(); + Assert.That(session.MonsterGeneration("Fleeing"), Is.EqualTo(1)); + Assert.That(session.Events.Single(entry => entry.Source == "Fleeing" && entry.Kind == BattleEventKind.Escaped).Tick, Is.EqualTo(2)); + Assert.That(session.StageTasks.Single(task => task.Kind == "enemy flee").Finished, Is.True, + "The recreated native role no longer belongs to its previous escape stage."); + Advance(session, () => session.Events.Any(entry => entry.Source == "Fleeing" && entry.Kind == BattleEventKind.ActionEnded)); + Advance(session, () => session.WaitingActor == "Ally"); + Assert.That(session.Submit(new BattleCommand("Ally", BattleAction.Skill, "Fleeing", FinishEncounter)), Is.True); + Advance(session, () => session.Status == BattleSessionStatus.Completed); + Assert.That(session.Result.Winner, Is.EqualTo(BattleSide.Ally)); + Assert.That(session.StageTasks, Is.Empty); + + BattleSession replay = BattleReplay.Play(fixture.Setup, new Catalog(variant), session.Inputs, session.Tick, + new Rules(), fixture.Definitions); + Assert.That(replay.Status, Is.EqualTo(session.Status)); + Assert.That(replay.Result.Winner, Is.EqualTo(session.Result.Winner)); + Assert.That(replay.Events.Select(entry => (entry.Tick, entry.Kind, entry.Source, entry.Target, entry.ActionId, entry.ActualDelta, entry.RandomState)), + Is.EqualTo(session.Events.Select(entry => (entry.Tick, entry.Kind, entry.Source, entry.Target, entry.ActionId, entry.ActualDelta, entry.RandomState)))); + Assert.That(replay.StageTasks, Is.Empty); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleSummonFleeOwnershipTests.cs.meta b/Assets/Tests/Battle/Editor/BattleSummonFleeOwnershipTests.cs.meta new file mode 100644 index 00000000..df485026 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleSummonFleeOwnershipTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a5f1c9e4fe6a4a7ebf2f6ec68787e3f1 diff --git a/Assets/Tests/Battle/Editor/BattleThrownWeaponTests.cs b/Assets/Tests/Battle/Editor/BattleThrownWeaponTests.cs new file mode 100644 index 00000000..f8c91198 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleThrownWeaponTests.cs @@ -0,0 +1,70 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using NUnit.Framework; + using Pal3.Battle; + + public sealed class BattleThrownWeaponTests + { + // Original 500b29 + 50112e in actual Role order (updater before body). + [TestCase(0, 3, 5)] + [TestCase(100, 5, 10)] + [TestCase(300, 23, 46)] + [TestCase(600, 50, 99)] + [TestCase(2000, 175, 350)] + public void PublishedOutboundHitAndReturnRestoreFrames(int distance, int hitFrame, int restoreFrame) + { + var projectile = new BattleThrownWeapon(new(-17, 12, 42), new(-17 + distance, 0, 42)); + int hits = 0; + for (int frame = 0; frame <= restoreFrame; frame++) + { + projectile.Advance(true); + if (!projectile.BodyFinished) + projectile.AdvanceBody(frame == 2 ? BattlePhysicalMarkerKind.Throwed : null, true); + if (projectile.HitThisPass) + { + hits++; + Assert.That(frame, Is.EqualTo(hitFrame)); + } + Assert.That(projectile.RestoreRequested, Is.EqualTo(frame == restoreFrame)); + } + Assert.That(hits, Is.EqualTo(1)); + Assert.That(projectile.Active, Is.False); + Assert.That(projectile.WeaponVisible, Is.False); // restore body still owns the hidden weapon + projectile.FinishRestore(); + Assert.That(projectile.WeaponVisible, Is.True); + } + + [Test] + public void SourceDeathCancelsIndependentProjectileBeforeDamage() + { + var projectile = new BattleThrownWeapon(default, new(600, 0, 0)); + projectile.AdvanceBody(BattlePhysicalMarkerKind.Throwed, true); + for (int frame = 0; frame < 5; frame++) + projectile.Advance(true); + projectile.Advance(false); + Assert.That(projectile.Active, Is.False); + Assert.That(projectile.WeaponVisible, Is.True); + Assert.That(projectile.HitThisPass, Is.False); + Assert.That(projectile.RestoreRequested, Is.False); + } + + [Test] + public void ActivationStartsSecondModelWithoutMovingTheSourceOrAdvancingFlight() + { + var projectile = new BattleThrownWeapon(default, new(300, 0, 0)); + BattleMovementPoint origin = projectile.Position; + projectile.Advance(true); + projectile.AdvanceBody(BattlePhysicalMarkerKind.Throwed, true); + Assert.That(projectile.Position.X, Is.EqualTo(origin.X)); + Assert.That(projectile.Active, Is.True); + Assert.That(projectile.BodyFinished, Is.True); + projectile.Advance(true); + Assert.That(projectile.Position.X, Is.GreaterThan(origin.X)); + } + } +} diff --git a/Assets/Tests/Battle/Editor/BattleThrownWeaponTests.cs.meta b/Assets/Tests/Battle/Editor/BattleThrownWeaponTests.cs.meta new file mode 100644 index 00000000..36512ba3 --- /dev/null +++ b/Assets/Tests/Battle/Editor/BattleThrownWeaponTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 13773c7751be4019b3043846ae826de8 diff --git a/Assets/Tests/Battle/Editor/Pal3.Battle.Tests.asmdef b/Assets/Tests/Battle/Editor/Pal3.Battle.Tests.asmdef new file mode 100644 index 00000000..c5936a28 --- /dev/null +++ b/Assets/Tests/Battle/Editor/Pal3.Battle.Tests.asmdef @@ -0,0 +1,19 @@ +{ + "name": "Pal3.Battle.Tests", + "references": [ + "Pal3.Battle" + ], + "includePlatforms": [ + "Editor" + ], + "optionalUnityReferences": [ + "TestAssemblies" + ], + "autoReferenced": false, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll", + "Newtonsoft.Json.dll" + ], + "noEngineReferences": true +} diff --git a/Assets/Tests/Battle/Editor/Pal3.Battle.Tests.asmdef.meta b/Assets/Tests/Battle/Editor/Pal3.Battle.Tests.asmdef.meta new file mode 100644 index 00000000..54cde2ec --- /dev/null +++ b/Assets/Tests/Battle/Editor/Pal3.Battle.Tests.asmdef.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 008a129a766d47d5994caec13c9004d5 diff --git a/Assets/Tests/Battle/Presentation.meta b/Assets/Tests/Battle/Presentation.meta new file mode 100644 index 00000000..6e9c5681 --- /dev/null +++ b/Assets/Tests/Battle/Presentation.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 55dbe2b3f3434fee992189fcf97eeee5 +folderAsset: yes +DefaultImporter: + externalObjects: {} diff --git a/Assets/Tests/Battle/Presentation/Editor.meta b/Assets/Tests/Battle/Presentation/Editor.meta new file mode 100644 index 00000000..373f275f --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor.meta @@ -0,0 +1,5 @@ +fileFormatVersion: 2 +guid: 07d170cf2be74059bcbb4126ec521bb2 +folderAsset: yes +DefaultImporter: + externalObjects: {} diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleFormationSessionTests.cs b/Assets/Tests/Battle/Presentation/Editor/BattleFormationSessionTests.cs new file mode 100644 index 00000000..9d5171a3 --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleFormationSessionTests.cs @@ -0,0 +1,326 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + + public sealed class BattleFormationSessionTests + { + private sealed class Catalog : IBattleCatalog, IBattleStageGeometry + { + private readonly Dictionary _actors; + public bool InvalidMove; + + public Catalog(BattleScenario scenario) => _actors = scenario.Participants.ToDictionary(actor => actor.InstanceId); + + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor switch { "A" => 0, "B" => 1, "C" => 4, _ => 0 }; + + public int DamageDivisor(string actor) => 1; + + public BattleMovementPoint InitialHome(string actor) => FormationHome(actor, _actors[actor].Slot); + + public BattleMovementPoint FormationHome(string actor, BattleSlot slot) => + new((_actors[actor].Side == BattleSide.Enemy ? 1000 : 0) + 100 * (int)slot, 0, 0); + + public BattleAttackPlan PlanAttack(string source, string target, BattleMovementPoint sourceHome, BattleMovementPoint targetHome) => + new(Attack(source, target), sourceHome, targetHome, targetHome); + + public IReadOnlyList PlanFormationMove(string actor, BattleMovementPoint home, + BattleMovementPoint destination, bool midpoint) => Array.AsReadOnly(new[] + { + new BattleMovementPlan(InvalidMove ? (BattleMovementKind)999 : BattleMovementKind.Run, home, destination) + }); + } + + private sealed class Rules : IBattleRules + { + private readonly string _controller; + private readonly BattleBasicRules _original = new(); + + public Rules(string controller) => _controller = controller; + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + actor.InstanceId == _controller ? BattleSession.FullGauge : actor.Side == BattleSide.Ally ? 600 : 0; + + public int GaugePerStep(BattleParticipant actor) => _original.GaugePerStep(actor); + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => + _original.Hit(source, target, guarding, random, targetAtHome, damageDivisor); + } + + private static BattleParticipant Participant(string id, BattleSide side, BattleSlot slot) => new() + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = slot, + Attributes = new[] { 500, 100, 100, 60, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 100, 100 } + }; + + private static BattleScenario Scenario(string variant, bool third = false) + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "fixture" }; + scenario.Participants.Add(Participant("A", BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(Participant("B", BattleSide.Ally, BattleSlot.Fire)); + if (third) + scenario.Participants.Add(Participant("C", BattleSide.Ally, BattleSlot.Earth)); + scenario.Participants.Add(Participant("E", BattleSide.Enemy, BattleSlot.Water)); + return scenario; + } + + private static BattleSession Session(BattleScenario scenario, out BattleSetup setup, out Catalog catalog, + string controller = "A", bool invalid = false) + { + setup = new BattleSetup(scenario); + catalog = new Catalog(scenario) { InvalidMove = invalid }; + var definitions = new BattleDefinitions(scenario.Variant, scenario.DataFingerprint, + Array.Empty(), Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId switch { "A" => 0, "B" => 1, "C" => 4, _ => -1 }, + NormalAttackMode = 924 + }))); + return new BattleSession(setup, catalog, new Rules(controller), definitions); + } + + private static BattleActorSnapshot Actor(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + private static string Trace(BattleSession session) => string.Join("\n", session.Events.Select(entry => entry.ToString())); + + [TestCase("PAL3", "A", false)] + [TestCase("PAL3A", "A", false)] + [TestCase("PAL3", "C", false)] + [TestCase("PAL3A", "C", false)] + [TestCase("PAL3", "A", true)] + [TestCase("PAL3A", "A", true)] + [TestCase("PAL3", "C", true)] + [TestCase("PAL3A", "C", true)] + public void ConfirmationMatchesNativeGaugeAndGuardWriteOwnership(string variant, string controller, bool restored) + { + BattleSession session = Session(Scenario(variant, true), out _, out _, controller); + Assert.That(session.BeginFormation(controller), Is.True); + // Native full-handler vectors use sentinels to detect unintended + // writes. A normally readied controller already has Guard cleared + // by the separate defense watcher; this checks ownership only. + var actors = (IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + foreach (string id in new[] { "A", "B", "C" }) + { + object actor = actors[id]; + actor.GetType().GetField("CastGauge").SetValue(actor, 1000 + id[0]); + actor.GetType().GetField("Guard").SetValue(actor, true); + } + BattleActorSnapshot[] before = session.Actors.Where(actor => actor.Side == BattleSide.Ally).ToArray(); + Assert.That(session.SwapFormation("A", BattleSlot.Fire), Is.True); + if (restored) + Assert.That(session.SwapFormation("A", BattleSlot.Water), Is.True); + Assert.That(session.EndFormation(controller), Is.True); + foreach (BattleActorSnapshot original in before) + { + BattleActorSnapshot after = Actor(session, original.Id); + bool pays = !restored && original.Id == controller; + Assert.That((after.Gauge, after.CastGauge, after.Ready), + Is.EqualTo(pays ? (0, 0, false) : (original.Gauge, original.CastGauge, original.Ready)), original.Id); + Assert.That(after.Guarding, Is.True, original.Id); + } + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void FormationMovementDoesNotPauseEitherGaugeAndReplayCapturesRuntimeSlots(string variant) + { + BattleScenario scenario = Scenario(variant); + BattleSession session = Session(scenario, out BattleSetup setup, out Catalog catalog); + Assert.That(session.BeginFormation("A"), Is.True); + Assert.That(session.SwapFormation("A", BattleSlot.Fire), Is.True); + Assert.That((Actor(session, "A").Slot, Actor(session, "B").Slot), Is.EqualTo((BattleSlot.Fire, BattleSlot.Water))); + Assert.That((Actor(session, "A").Gauge, Actor(session, "B").Gauge), Is.EqualTo((11500, 600))); + Assert.That(session.EndFormation("A"), Is.True); + session.Step(); + Assert.That((Actor(session, "A").Gauge, Actor(session, "B").Gauge), Is.EqualTo((35, 635))); + Assert.That(Actor(session, "A").Movement.Position.X, Is.EqualTo(7.6f).Within(0.00001f)); + for (int step = 1; step < 13; step++) + session.Step(); + Assert.That(Actor(session, "A").Movement, Is.Null); + Assert.That(Actor(session, "B").Movement, Is.Null); + Assert.That((Actor(session, "A").Home.X, Actor(session, "B").Home.X), Is.EqualTo((100f, 0f))); + BattleSession replay = BattleReplay.Play(setup, catalog, session.Inputs, session.Tick, new Rules("A"), session.Definitions); + Assert.That(Trace(replay), Is.EqualTo(Trace(session))); + Assert.That((Actor(replay, "A").Slot, Actor(replay, "A").Gauge), Is.EqualTo((Actor(session, "A").Slot, Actor(session, "A").Gauge))); + Assert.That(scenario.Participants[0].Slot, Is.EqualTo(BattleSlot.Water)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void OnlyTheControllerPaysEvenWhenTwoOtherMembersSwap(string variant) + { + BattleSession session = Session(Scenario(variant, true), out _, out _, "C"); + Assert.That(session.BeginFormation("C"), Is.True); + Assert.That(session.SwapFormation("A", BattleSlot.Fire), Is.True); + Assert.That(session.EndFormation("C"), Is.True); + Assert.That((Actor(session, "A").Gauge, Actor(session, "B").Gauge, Actor(session, "C").Gauge), Is.EqualTo((600, 600, 0))); + session.Step(); + Assert.That((Actor(session, "A").Gauge, Actor(session, "B").Gauge, Actor(session, "C").Gauge), Is.EqualTo((635, 635, 35))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void RestoringTheEntryLineupClearsQueuedMovementAndHasNoGaugeCost(string variant) + { + BattleSession session = Session(Scenario(variant), out _, out _); + Assert.That(session.BeginFormation("A"), Is.True); + Assert.That(session.SwapFormation("A", BattleSlot.Fire), Is.True); + Assert.That(session.SwapFormation("A", BattleSlot.Water), Is.True); + Assert.That(session.EndFormation("A"), Is.True); + Assert.That(Actor(session, "A").Gauge, Is.EqualTo(11500)); + Assert.That(Actor(session, "A").Movement, Is.Null); + Assert.That(Actor(session, "B").Movement, Is.Null); + Assert.That((Actor(session, "A").Slot, Actor(session, "A").Home.X, Actor(session, "A").Gauge), Is.EqualTo((BattleSlot.Water, 0f, 11500))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void OpenFormationFreezesGaugesAndRejectsCombatCommands(string variant) + { + BattleSession session = Session(Scenario(variant), out _, out _); + Assert.That(session.BeginFormation("A"), Is.True); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.False); + for (int step = 0; step < 5; step++) + session.Step(); + Assert.That((Actor(session, "A").Gauge, Actor(session, "B").Gauge, Actor(session, "E").Gauge), Is.EqualTo((11500, 600, 0))); + Assert.That(session.EndFormation("A"), Is.True); + Assert.That(Actor(session, "A").Ready, Is.True); + } + + [Test] + public void InvalidProviderPlanLeavesBothActorsAndTheInputLogUntouched() + { + BattleSession session = Session(Scenario("PAL3A"), out _, out _, invalid: true); + Assert.That(session.BeginFormation("A"), Is.True); + string trace = Trace(session); + Assert.Throws(() => session.SwapFormation("A", BattleSlot.Fire)); + Assert.That(Trace(session), Is.EqualTo(trace)); + Assert.That(session.Inputs.Count, Is.EqualTo(1)); + Assert.That((Actor(session, "A").Slot, Actor(session, "B").Slot), Is.EqualTo((BattleSlot.Water, BattleSlot.Fire))); + Assert.That(Actor(session, "A").Movement, Is.Null); + } + + [TestCase("PAL3", "cancel")] + [TestCase("PAL3A", "cancel")] + [TestCase("PAL3", "same-slot")] + [TestCase("PAL3A", "same-slot")] + [TestCase("PAL3", "blank")] + [TestCase("PAL3A", "blank")] + [TestCase("PAL3", "same-actor")] + [TestCase("PAL3A", "same-actor")] + public void FinishedFormationDragsReleaseTheirActorWithoutChangingTheBattle(string variant, string release) + { + BattleSession session = Session(Scenario(variant), out _, out _); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(presenter.BeginFormation(), Is.True); + string trace = Trace(session); + int inputs = session.Inputs.Count; + int gauge = Actor(session, "A").Gauge; + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerDown, "actor:A", 17)), Is.True); + if (release == "cancel") + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerCancel, pointerId: 17)), Is.True); + else + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerUp, + release == "same-slot" ? "slot:" + (int)BattleSlot.Water : release == "same-actor" ? "actor:A" : null, 17)); + Assert.That(presenter.FormationActor, Is.Null); + Assert.That(presenter.CapturedPointerId, Is.Null); + Assert.That(presenter.FocusItems().Where(item => item.Id.StartsWith("actor:", StringComparison.Ordinal)).All(item => item.Enabled), Is.True); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerDown, "actor:B", 22)), Is.True); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerCancel, pointerId: 22)), Is.True); + Assert.That(Trace(session), Is.EqualTo(trace)); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs)); + Assert.That(Actor(session, "A").Gauge, Is.EqualTo(gauge)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void KeyboardFormationSelectionKeepsItsActorUntilTheSlotIsConfirmed(string variant) + { + BattleSession session = Session(Scenario(variant), out _, out _); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(presenter.BeginFormation(), Is.True); + int gauge = Actor(session, "A").Gauge; + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "actor:B")), Is.True); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Down)), Is.True); + Assert.That(presenter.FormationActor, Is.EqualTo("B")); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "slot:" + (int)BattleSlot.Earth)), Is.True); + Assert.That(Actor(session, "B").Slot, Is.EqualTo(BattleSlot.Earth)); + Assert.That(presenter.FormationActor, Is.Null); + Assert.That(session.Inputs.Count(input => input.Kind == BattleInputKind.SwapFormation), Is.EqualTo(1)); + Assert.That(Actor(session, "A").Gauge, Is.EqualTo(gauge)); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Back)), Is.True); + Assert.That(session.ActiveFormationController, Is.Null); + Assert.That(Actor(session, "A").Gauge, Is.Zero); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void FormationBackDeselectsButExplicitConfirmationClosesAndPaysOnlyOnce(string variant, bool changed) + { + BattleSession session = Session(Scenario(variant), out _, out _); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(presenter.BeginFormation(), Is.True); + int gauge = Actor(session, "A").Gauge; + if (changed) + Assert.That(presenter.MoveFormation("A", BattleSlot.Earth), Is.True); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "actor:B")), Is.True); + Assert.That(presenter.FormationActor, Is.EqualTo("B")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Back)); + Assert.That(presenter.FormationActor, Is.Null); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Formation)); + Assert.That(session.ActiveFormationController, Is.EqualTo("A")); + Assert.That(session.Inputs.Count(input => input.Kind == BattleInputKind.EndFormation), Is.Zero); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "actor:B")), Is.True); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "end")), Is.True); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(session.ActiveFormationController, Is.Null); + Assert.That(Actor(session, "A").Gauge, Is.EqualTo(changed ? 0 : gauge)); + Assert.That(session.Inputs.Count(input => input.Kind == BattleInputKind.EndFormation), Is.EqualTo(1)); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "end")), Is.False); + Assert.That(session.Inputs.Count(input => input.Kind == BattleInputKind.EndFormation), Is.EqualTo(1)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ADeadOccupantPreventsExchangeWithoutBlockingOpeningThePanel(string variant) + { + BattleScenario scenario = Scenario(variant); + scenario.Participants[1].Vitals[0] = 0; + BattleSession session = Session(scenario, out _, out _); + Assert.That(session.BeginFormation("A"), Is.True); + Assert.That(session.CanSwapFormation("A", BattleSlot.Fire), Is.Not.Null); + Assert.That(session.SwapFormation("A", BattleSlot.Fire), Is.False); + Assert.That(session.Inputs.Count, Is.EqualTo(1)); + } + } +} diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleFormationSessionTests.cs.meta b/Assets/Tests/Battle/Presentation/Editor/BattleFormationSessionTests.cs.meta new file mode 100644 index 00000000..8b6f572d --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleFormationSessionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7925693de70a49329e6617a6b43ff3a1 diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleLineupProjectionTests.cs b/Assets/Tests/Battle/Presentation/Editor/BattleLineupProjectionTests.cs new file mode 100644 index 00000000..34c81c45 --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleLineupProjectionTests.cs @@ -0,0 +1,40 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using Battle; + using Battle.Presentation; + using NUnit.Framework; + + public sealed class BattleLineupProjectionTests + { + [TestCase(0, 2, 0)] + [TestCase(.02, 2, 0)] + [TestCase(.52, 2, 85)] + [TestCase(1.02, 2, 170)] + [TestCase(1.52, 2, 255)] + [TestCase(1.82, 2, 102)] + [TestCase(2, 2, 10)] + [TestCase(2.02, 2, 0)] + [TestCase(2.02, 4, 170)] + [TestCase(3.02, 4, 255)] + [TestCase(4, 4, 5)] + public void NativeFadeSubmitsThePreviousPassAlpha(double elapsed, double duration, int alpha) => + Assert.That(BattleLineupProjection.Alpha(elapsed, duration), Is.EqualTo(alpha)); + + [Test] + public void RingUsesNativeGroundHeightWhileTheCenterTileIgnoresRoll() + { + var center = new BattleMovementPoint(10, 99, -20); + BattleMovementPoint ring = BattleLineupProjection.Corner(center, 2, 0, 0, false); + Assert.That((ring.X, ring.Y, ring.Z), Is.EqualTo((8f, .5f, -22f))); + BattleMovementPoint tile = BattleLineupProjection.Corner(center, 2, 1.234f, 2, true); + Assert.That((tile.X, tile.Y, tile.Z), Is.EqualTo((11f, 0f, -19f))); + Assert.That(BattleLineupProjection.CenterColor(3), Is.EqualTo(0x52b66b)); + Assert.That(BattleLineupProjection.CenterColor(4), Is.EqualTo(0xde75bd)); + } + } +} diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleLineupProjectionTests.cs.meta b/Assets/Tests/Battle/Presentation/Editor/BattleLineupProjectionTests.cs.meta new file mode 100644 index 00000000..e565e3fd --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleLineupProjectionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4444e14088204fd9a57d01c4be38814a diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleNumberActivationTests.cs b/Assets/Tests/Battle/Presentation/Editor/BattleNumberActivationTests.cs new file mode 100644 index 00000000..4623ac6d --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleNumberActivationTests.cs @@ -0,0 +1,98 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Linq; + using System.Reflection; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + + public sealed class BattleNumberActivationTests + { + private sealed class Catalog : IBattleCatalog + { + public AttackTiming Attack(string source, string target) => new(0, 2, new[] { 1 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 1; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class Rules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => 0; + + public int GaugePerStep(BattleParticipant actor) => 0; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => new(-10, false, false); + } + + [TestCase("PAL3", false, false)] + [TestCase("PAL3A", false, false)] + [TestCase("PAL3", true, false)] + [TestCase("PAL3A", true, false)] + [TestCase("PAL3", false, true)] + [TestCase("PAL3A", false, true)] + public void ActivationFreezesTheNativeAnchorAndConsumesOnlyTheOwnedRandomDraw(string variant, bool miss, bool block) + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "numbers", Seed = 1 }; + foreach (BattleSide side in Enum.GetValues(typeof(BattleSide))) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = side.ToString(), + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = BattleSlot.Water, + Attributes = new[] { 100, 100, 100, 10, 0, 10, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 100, 100, 100 } + }); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, + Array.Empty(), Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1 + }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new Rules(), definitions); + var actors = (IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + object target = actors["Enemy"]; + void Position(string name, BattleMovementPoint point) => target.GetType().GetField(name).SetValue(target, point); + Position("Position", new BattleMovementPoint(123, 456, 789)); + Position("Home", new BattleMovementPoint(12, 34, 56)); + typeof(BattleSession).GetMethod("QueueNumber", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(session, + new object[] { target, 0, -123, miss ? 1f : 2f, block, miss, false, false }); + session.Step(); + BattleEvent number = session.Events.Single(entry => entry.Kind == BattleEventKind.NumberShown); + Assert.That(number.NumberActivationTick, Is.EqualTo(1)); + Assert.That(number.NumberStartedTime, Is.EqualTo(block ? .02f : 0)); + Assert.That(number.NumberPosition.X, Is.EqualTo(miss ? 12 : 123)); + Assert.That(number.NumberPosition.Y, Is.EqualTo(miss ? 114 : 50)); + Assert.That(number.NumberPosition.Z, Is.EqualTo(miss ? 56 : 789)); + var expectedRandom = new BattleRandom(1); + int expectedOffset = expectedRandom.Next() % 32; + Assert.That(number.NumberOffset, Is.EqualTo(expectedOffset)); + Assert.That(number.RandomState, Is.EqualTo(expectedRandom.State)); + Position("Position", new BattleMovementPoint(999, 999, 999)); + var projection = new BattleNumberProjection(); + projection.Synchronize(session.Events, session.SimulationTick); + BattleNumberFrame frame = projection.Sample().Single(); + Assert.That(frame.Position.X, Is.EqualTo(number.NumberPosition.X)); + Assert.That(frame.Position.Z, Is.EqualTo(number.NumberPosition.Z)); + var random = (BattleRandom)typeof(BattleSession).GetField("_random", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + Assert.That(random.State, Is.EqualTo(number.RandomState), "Projection must never draw from battle RNG."); + } + } +} diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleNumberActivationTests.cs.meta b/Assets/Tests/Battle/Presentation/Editor/BattleNumberActivationTests.cs.meta new file mode 100644 index 00000000..5d606bab --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleNumberActivationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7fd564b68a194e289aae169a62de8bb4 diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleNumberProjectionTests.cs b/Assets/Tests/Battle/Presentation/Editor/BattleNumberProjectionTests.cs new file mode 100644 index 00000000..93af8d7b --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleNumberProjectionTests.cs @@ -0,0 +1,176 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + + public sealed class BattleNumberProjectionTests + { + // Both released ShowDamage/ShowMiss callbacks, with a stub camera + // projecting the captured world anchor to (400,300), produce these + // vectors. See Battle-Stage41-Feedback/Numbers/native-number-vectors.json. + [TestCase(-123, 0, 2f, false, false, 0, 10, 255, 0x3232ff)] + [TestCase(-123, 0, 2f, false, false, 25, -5, 191, 0x3232ff)] + [TestCase(-123, 0, 2f, false, false, 50, -20, 128, 0x3232ff)] + [TestCase(0, 0, 2.5f, false, true, 25, -5, 204, 0x00ff00)] + [TestCase(0, 0, 2.5f, false, true, 50, -20, 153, 0x00ff00)] + [TestCase(-10, 1, 2.5f, false, false, 25, -5, 204, 0xfbe0a2)] + [TestCase(20, 2, 2.5f, false, false, 25, -5, 204, 0xfaa8d5)] + [TestCase(0, 0, 1f, true, false, 0, 16, 255, 0x32ffff)] + [TestCase(0, 0, 1f, true, false, 25, 0, 128, 0x32ffff)] + [TestCase(0, 0, 1f, true, false, 50, -16, 0, 0x32ffff)] + [TestCase(-1, 16, 3.5f, false, false, 25, -5, 219, 0x32ffff)] + public void MatchesReleasedNativeVectors(int value, int resource, float duration, bool miss, bool recovery, + int tick, int baselineOffset, int alpha, int color) + { + var projection = new BattleNumberProjection(); + projection.Synchronize(new[] { Number(value, resource, duration, miss, recovery, offset: 9) }, tick); + BattleNumberFrame frame = projection.Sample().Single(); + Assert.That(frame.OffsetX, Is.EqualTo(resource == 16 ? -23 : -7)); + Assert.That(frame.OffsetY, Is.EqualTo(baselineOffset)); + Assert.That(frame.Alpha, Is.EqualTo(alpha)); + Assert.That(frame.Color, Is.EqualTo((uint)color)); + } + + private static BattleEvent Number(int value = -123, int resource = 0, float duration = 2, + bool miss = false, bool recovery = false, long tick = 0, float start = 0, int offset = 31) + { + var entry = new BattleEvent(); + void Set(string name, object value) => typeof(BattleEvent).GetProperty(name).SetValue(entry, value); + Set(nameof(BattleEvent.Kind), BattleEventKind.NumberShown); + Set(nameof(BattleEvent.Target), "target"); + Set(nameof(BattleEvent.RequestedDelta), value); + Set(nameof(BattleEvent.Resource), resource); + Set(nameof(BattleEvent.DurationSeconds), duration); + Set(nameof(BattleEvent.NumberIsMiss), miss); + Set(nameof(BattleEvent.NumberIsRecovery), recovery); + Set(nameof(BattleEvent.NumberActivationTick), tick); + Set(nameof(BattleEvent.NumberStartedTime), start); + Set(nameof(BattleEvent.NumberOffset), offset); + Set(nameof(BattleEvent.NumberPosition), new BattleMovementPoint(120, 50, -30)); + return entry; + } + + [Test] + public void NativeDamageKeepsItsSignAndAnchorAndRisesThirtyPixelsPerSecond() + { + var projection = new BattleNumberProjection(); + BattleEvent entry = Number(); + projection.Synchronize(new[] { entry }, 25); + BattleNumberFrame frame = projection.Sample().Single(); + Assert.That(frame.Text, Is.EqualTo("-123")); + Assert.That(frame.Color, Is.EqualTo(0x3232ff)); + Assert.That(frame.Position.X, Is.EqualTo(120)); + Assert.That(frame.Position.Y, Is.EqualTo(50)); + Assert.That(frame.OffsetX, Is.EqualTo(15)); + Assert.That(frame.OffsetY, Is.EqualTo(-5)); + Assert.That(frame.Alpha, Is.EqualTo(191)); + projection.Synchronize(new[] { entry }, 25); + Assert.That(projection.Sample().Single().OffsetY, Is.EqualTo(frame.OffsetY), "A frozen simulation clock must freeze text."); + projection.Synchronize(new[] { entry }, 101); + Assert.That(projection.Sample(), Is.Empty); + } + + [TestCase(0, 0, true, 0x00ff00)] + [TestCase(0, 15, true, 0x00ff00)] + [TestCase(1, -10, false, 0xfbe0a2)] + [TestCase(2, 20, false, 0xfaa8d5)] + public void ResourceNumbersUseTheReleasedColorsIncludingCappedHealing(int resource, int value, bool recovery, int color) + { + var projection = new BattleNumberProjection(); + projection.Synchronize(new[] { Number(value, resource, 2.5f, recovery: recovery) }, 50); + BattleNumberFrame frame = projection.Sample().Single(); + Assert.That(frame.Text, Is.EqualTo(value.ToString(System.Globalization.CultureInfo.InvariantCulture))); + Assert.That(frame.Color, Is.EqualTo((uint)color)); + Assert.That(frame.Alpha, Is.EqualTo(153)); + } + + [Test] + public void NativeMissUsesItsOwnOneSecondThirtyTwoPixelRiseAndCyanColor() + { + var projection = new BattleNumberProjection(); + projection.Synchronize(new[] { Number(0, duration: 1, miss: true) }, 25); + BattleNumberFrame frame = projection.Sample().Single(); + Assert.That(frame.Text, Is.EqualTo("MISS")); + Assert.That(frame.Color, Is.EqualTo(0x32ffff)); + Assert.That(frame.OffsetY, Is.Zero); + Assert.That(frame.Alpha, Is.EqualTo(128)); + } + + [Test] + public void GuCostKeepsTheCostCaptionAndWiderNativeOffset() + { + var projection = new BattleNumberProjection("蠱"); + projection.Synchronize(new[] { Number(-1, 16, 3.5f) }, 0); + BattleNumberFrame frame = projection.Sample().Single(); + Assert.That(frame.Text, Is.EqualTo("蠱 -1")); + Assert.That(frame.OffsetX, Is.EqualTo(-1)); + Assert.That(frame.Color, Is.EqualTo(0x32ffff)); + } + + [Test] + public void SimultaneousNumbersStackAndBatchedSteppingPreservesTheirOrder() + { + var events = new List { Number(), Number(), Number(tick: 10, start: .2f) }; + var projection = new BattleNumberProjection(); + projection.Synchronize(events, 10); + BattleNumberFrame[] frames = projection.Sample().ToArray(); + Assert.That(frames.Select(frame => frame.OffsetY), Is.EqualTo(new[] { 4, 14, 24 })); + // Exceeding the cap in one pass resets to 160 before the next pass; + // it does not cap each number registered within that same pass. + events = Enumerable.Range(0, 20).Select(_ => Number()).Append(Number(tick: 1)).ToList(); + projection = new BattleNumberProjection(); + projection.Synchronize(events, 1); + Assert.That(projection.Sample().Last().OffsetY, Is.EqualTo(169)); + } + + [Test] + public void MissDoesNotConsumeTheNumericVerticalStack() + { + var projection = new BattleNumberProjection(); + projection.Synchronize(new[] { Number(), Number(miss: true), Number() }, 0); + Assert.That(projection.Sample().Select(frame => frame.OffsetY), Is.EqualTo(new[] { 10, 16, 20 })); + } + + [Test] + public void NativeTftUsesContinuousLowBitFirstGlyphBitsAndHalfWidthAscii() + { + byte[] bytes = FontBytes(); + int start = 20 + '0' * 50; + foreach (int pixel in new[] { 0, 19, 20, 399 }) + bytes[start + pixel / 8] |= (byte)(1 << (pixel % 8)); + byte[] alpha = new BattleNumberFont(bytes).GlyphAlpha('0'); + Assert.That(alpha.Select((value, index) => (value, index)).Where(pair => pair.value != 0).Select(pair => pair.index), + Is.EqualTo(new[] { 0, 19, 20, 399 })); + Assert.That(BattleNumberFont.Advance('0'), Is.EqualTo(10)); + Assert.That(BattleNumberFont.Advance('M'), Is.EqualTo(10)); + Assert.That(BattleNumberFont.Advance('蛊'), Is.EqualTo(20)); + Assert.Throws(() => new BattleNumberFont(bytes[..^1])); + bytes[8] = 16; + Assert.Throws(() => new BattleNumberFont(bytes)); + } + + private static byte[] FontBytes() + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(0u); + writer.Write(1u); + writer.Write(20u); + writer.Write(1u); + writer.Write(128); + writer.Write(new byte[128 * 50]); + return stream.ToArray(); + } + } +} diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleNumberProjectionTests.cs.meta b/Assets/Tests/Battle/Presentation/Editor/BattleNumberProjectionTests.cs.meta new file mode 100644 index 00000000..92b007a5 --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleNumberProjectionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e9d1c78e802c4dc4a2207f4f993dcc2d diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleStageFeedbackTests.cs b/Assets/Tests/Battle/Presentation/Editor/BattleStageFeedbackTests.cs new file mode 100644 index 00000000..90a5e1f8 --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleStageFeedbackTests.cs @@ -0,0 +1,293 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + + public sealed class BattleStageFeedbackTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattleAbilityEffects + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 1 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 1, new[] { 0 }); + + public BattleAbilityStageProfile AbilityStage(string actor, BattleAbilityDefinition ability) => new( + ability.IsItem ? BattleAbilityStageKind.Item : ability.IsMagic ? BattleAbilityStageKind.Magic : BattleAbilityStageKind.Skill, + new BattleAbilityEffectBinding(-1, 0), new BattleAbilityEffectBinding(-1, 0), 0, + BattleAbilityWorkBoundary.WorkTime, 1, true); + + public IReadOnlyList AbilityMovement(BattleActorSnapshot source, BattleActorSnapshot target, + BattleAbilityDefinition ability, BattleDefinitions definitions, bool returning) => Array.Empty(); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "A" ? 0 : actor == "B" ? 1 : 2; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class Rules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + actor.Side == BattleSide.Ally ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => 1; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => new(-1, false, false); + } + + private sealed class StageObserver : IBattleEffectDirector, IBattleStagePresentation + { + public BattleSession Session; + public readonly BattleStageMessageProjection Projection = new(); + public readonly List Frames = new(); + + public long Start(BattleEffectRequest request) => throw new InvalidOperationException("This message fixture has no effect groups."); + + public bool IsRunning(long handle) => false; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + } + + public void AdvanceStage(double scaledSeconds, double absoluteSeconds) + { + Projection.Synchronize(Session.StageMessageReferences, Session.Tick is > 8 and < 30); + Frames.Add(Session.Tick + ":" + Projection.VisibleReferenceCount(BattleSide.Ally) + ":" + + string.Join("|", Projection.Messages.Select(message => message.Text ?? message.LanguageKey))); + } + } + + private static BattleSession Session(string variant, BattleEncounter encounter = BattleEncounter.Normal, bool magic = false, + IBattleEffectDirector effects = null, Action capture = null) + { + var scenario = new BattleScenario { Variant = variant, Scene = "fixture", DataFingerprint = "feedback", Encounter = encounter, ScriptBattle = true }; + foreach (string id in new[] { "A", "B", "E" }) + { + var actor = new BattleParticipant + { + InstanceId = id, + ActorId = id == "A" ? 101 : id == "B" ? 104 : 701, + Side = id == "E" ? BattleSide.Enemy : BattleSide.Ally, + Slot = id == "B" ? BattleSlot.Fire : BattleSlot.Water, + Attributes = new[] { 500, 100, 100, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 100, 100 } + }; + if (id != "E") + actor.Skills.Add(new BattleSkill { Id = 4201, Mastered = true, Level = 4 }); + scenario.Participants.Add(actor); + } + scenario.Items.Add(new BattleItem { Id = 1001, Count = 2 }); + BattleAbilityDefinition Ability(bool item) => new(new BattleAbilityData + { + Id = item ? 1001 : 4201, + Name = item ? "物品标题" : "招式标题", + IsItem = item, + IsMagic = !item && magic, + SkillTypeId = magic ? 2 : 0, + ItemType = item ? 2 : 0, + ElementMask = magic ? 4 : 0, + Range = BattleTargetRange.OpponentSingle, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, -1) } + }); + var definitions = new BattleDefinitions(variant, scenario.DataFingerprint, new[] { Ability(false) }, new[] { Ability(true) }, + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId == "A" ? 0 : actor.InstanceId == "B" ? 1 : -1 + }))); + var setup = new BattleSetup(scenario); + capture?.Invoke(setup); + var session = new BattleSession(setup, new Catalog(), new Rules(), definitions, effects); + session.SetAutomatic(BattleSide.Ally, false); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + + private static void Until(BattleSession session, Func condition) + { + for (int index = 0; index < 500 && !condition() && session.Status == BattleSessionStatus.Running; index++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + Assert.That(condition(), Is.True); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void LaterNameEndingKeepsItsTextUntilTheOlderItemReferenceEnds(string variant) + { + BattleSession session = Session(variant); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "E", 1001)), Is.True); + Until(session, () => session.StageMessages.Count > 0); + for (int index = 0; index < 10; index++) + session.Step(); + Assert.That(session.Submit(new BattleCommand("B", BattleAction.Skill, "E", 4201)), Is.True); + Until(session, () => session.StageMessages.Single().ReferenceCount == 2); + Assert.That(session.StageMessages.Single().Text, Is.EqualTo("招式标题")); + Until(session, () => session.StageMessages.Single().ReferenceCount == 1); + Assert.That(session.StageMessages.Single().Text, Is.EqualTo("招式标题"), "UIStaticCB retains the last SetText while another ShowWindow reference survives."); + Until(session, () => session.StageMessages.Count == 0); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void CancelingOneActionReleasesOnlyItsOwnMessageReference(string variant) + { + BattleSession session = Session(variant); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "E", 1001)), Is.True); + Until(session, () => session.StageMessages.Count > 0); + Assert.That(session.Submit(new BattleCommand("B", BattleAction.Skill, "E", 4201)), Is.True); + Until(session, () => session.StageMessages.Single().ReferenceCount == 2); + Assert.That(session.CancelAction("B"), Is.True); + Assert.That(session.StageMessages.Single().ReferenceCount, Is.EqualTo(1)); + Assert.That(session.StageMessages.Single().Text, Is.EqualTo("招式标题")); + Assert.That(session.CancelAction("A"), Is.True); + Assert.That(session.StageMessages, Is.Empty); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void FailedFleeActivatesTheNativeSharedTitleInsteadOfOnlyItsDebugSnapshot(string variant) + { + BattleSession session = Session(variant); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Flee)), Is.True); + Assert.That(session.Submit(new BattleCommand("B", BattleAction.Defend)), Is.True); + Until(session, () => session.FleeResult != null); + Assert.That(session.FleeResult.Success, Is.False); + Assert.That(session.StageMessages.Single().LanguageKey, Is.EqualTo("FleeFail")); + float started = session.FleeResult.StartedAtSeconds; + while (BattleStageScheduler.TimeAt(session.SimulationTick) - started <= 3f) + session.Step(); + Assert.That(session.StageMessages, Is.Empty); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void TrailDoesNotLetANewSkillOverwriteTheItemOrResurrectAnInterruptedName(string variant) + { + BattleSession session = Session(variant); + var projection = new BattleStageMessageProjection(); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "E", 1001)), Is.True); + Until(session, () => session.StageMessageReferences.Count > 0); + projection.Synchronize(session.StageMessageReferences, false); + Assert.That(projection.Messages.Single().Text, Is.EqualTo("物品标题")); + projection.Synchronize(session.StageMessageReferences, true); + Assert.That(session.Submit(new BattleCommand("B", BattleAction.Skill, "E", 4201)), Is.True); + Until(session, () => session.StageMessageReferences.Count == 2); + projection.Synchronize(session.StageMessageReferences, true); + Assert.That(projection.Messages.Single().Text, Is.EqualTo("物品标题")); + projection.Synchronize(session.StageMessageReferences, false); + Assert.That(projection.VisibleReferenceCount(BattleSide.Ally), Is.EqualTo(1)); + Assert.That(projection.Messages.Single().Text, Is.EqualTo("物品标题")); + session.CancelAction("A"); + projection.Synchronize(session.StageMessageReferences, false); + Assert.That(projection.Messages, Is.Empty, "The skill that began during Trail must not reappear."); + + session = Session(variant); + projection.Clear(); + session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)); + Until(session, () => session.StageMessageReferences.Count > 0); + projection.Synchronize(session.StageMessageReferences, false); + Assert.That(projection.Messages.Single().Text, Is.EqualTo("招式标题")); + projection.Synchronize(session.StageMessageReferences, true); + projection.Synchronize(session.StageMessageReferences, false); + Assert.That(projection.Messages, Is.Empty, "A previously visible name interrupted by Trail must not reappear."); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void PerStageConsumptionAndReplayKeepTheSameTitleHistoryAcrossTrailAndPausedInspection(string variant) + { + var observer = new StageObserver(); + BattleSetup setup = null; + BattleSession session = Session(variant, effects: observer, capture: value => setup = value); + observer.Session = session; + session.Submit(new BattleCommand("A", BattleAction.Item, "E", 1001)); + for (int index = 0; index < 12; index++) + session.Step(); + session.Submit(new BattleCommand("B", BattleAction.Skill, "E", 4201)); + for (int index = 0; index < 48; index++) + session.Step(); + Assert.That(observer.Projection.Messages.Single().Text, Is.EqualTo("物品标题")); + long tick = session.Tick; + for (int index = 0; index < 10; index++) + observer.Projection.Synchronize(session.StageMessageReferences, false); + Assert.That(session.Tick, Is.EqualTo(tick)); + Assert.That(observer.Projection.Messages.Single().Text, Is.EqualTo("物品标题")); + var replayObserver = new StageObserver(); + BattleSession replay = BattleReplay.Play(setup, new Catalog(), session.Inputs, session.Tick, new Rules(), + session.Definitions, replayObserver, created => replayObserver.Session = created); + Assert.That(replayObserver.Frames, Is.EqualTo(observer.Frames)); + Assert.That(replayObserver.Projection.Messages.Single().Text, Is.EqualTo("物品标题")); + Assert.That(replay.StageMessageReferences.Select(message => message.ReferenceId), + Is.EqualTo(session.StageMessageReferences.Select(message => message.ReferenceId))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void StageQueriesAreImmutableAndExposeParallelMagicLineupAfterTheNameEnds(string variant) + { + BattleSession session = Session(variant, magic: true); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", 4201)), Is.True); + Until(session, () => session.AbilityPresentations.Any(value => value.NameVisible && value.LineupVisible)); + BattleAbilityPresentationSnapshot captured = session.AbilityPresentations.Single(); + long tick = session.Tick; + int events = session.Events.Count, inputs = session.Inputs.Count; + var random = (BattleRandom)typeof(BattleSession).GetField("_random", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + uint randomState = random.State; + for (int index = 0; index < 10; index++) + { + Assert.That(session.StageMessages.Single().Text, Is.EqualTo("招式标题")); + Assert.That(session.AbilityPresentations.Single().ElementMask, Is.EqualTo(4)); + } + Assert.That((session.Tick, session.Events.Count, session.Inputs.Count), Is.EqualTo((tick, events, inputs))); + Assert.That(random.State, Is.EqualTo(randomState)); + Until(session, () => session.AbilityPresentations.Any(value => !value.NameVisible && value.LineupVisible)); + Assert.That(session.StageMessages, Is.Empty); + Assert.That(captured.NameVisible, Is.True); + Assert.That(captured.LineupDurationSeconds, Is.EqualTo(2)); + session.Abort(); + Assert.That(session.StageMessages, Is.Empty); + Assert.That(session.AbilityPresentations, Is.Empty); + } + + [TestCase("PAL3", BattleEncounter.AllyAmbush, BattleSide.Ally, "WeSneakAttackEnemy")] + [TestCase("PAL3", BattleEncounter.EnemyAmbush, BattleSide.Enemy, "EnemySneakAttackUs")] + [TestCase("PAL3A", BattleEncounter.AllyAmbush, BattleSide.Ally, "WeSneakAttackEnemy")] + [TestCase("PAL3A", BattleEncounter.EnemyAmbush, BattleSide.Enemy, "EnemySneakAttackUs")] + public void AmbushFeedbackUsesTheThreeSecondSimulationClockWithoutOwningTheStage(string variant, BattleEncounter encounter, BattleSide side, string key) + { + BattleSession session = Session(variant, encounter); + session.Step(); + Assert.That(session.StageMessages.Single().Side, Is.EqualTo(side)); + Assert.That(session.StageMessages.Single().LanguageKey, Is.EqualTo(key)); + Assert.That(session.StageTasks, Is.Empty); + Assert.That(session.WaitingActor, Is.EqualTo("A")); + for (int index = 1; index < 150; index++) + session.Step(); + Assert.That(session.StageMessages.Count, Is.EqualTo(1), "The original end boundary is strict > 3 seconds."); + session.Step(); + Assert.That(session.StageMessages, Is.Empty); + Assert.That(session.WaitingActor, Is.EqualTo("A")); + } + } +} diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleStageFeedbackTests.cs.meta b/Assets/Tests/Battle/Presentation/Editor/BattleStageFeedbackTests.cs.meta new file mode 100644 index 00000000..17c1c1a2 --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleStageFeedbackTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a4b7c0acf9be44bebc6ba7b09d7f01dc diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleSwordSparkProjectionTests.cs b/Assets/Tests/Battle/Presentation/Editor/BattleSwordSparkProjectionTests.cs new file mode 100644 index 00000000..63341046 --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleSwordSparkProjectionTests.cs @@ -0,0 +1,92 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using Battle.Presentation; + using NUnit.Framework; + + public sealed class BattleSwordSparkProjectionTests + { + [Test] + public void StrictEmissionBoundaryAndNativeRandomStoresMatchTheSource() + { + var projection = new BattleSwordSparkProjection(17); + projection.Advance(.1, true, 100); + Assert.That(projection.Frames, Is.Empty); + projection.Advance(.02, true, 100); + BattleSwordSparkFrame frame = projection.Frames.Single(); + // Independent MSVC rand vector for seed 17: 94, 26602, 30017, + // 18297. Native CreateStars consumes luminosity, x, y, then ay. + Assert.That(frame.X, Is.EqualTo(12)); + Assert.That(frame.Y, Is.EqualTo(561.7812f).Within(.0001f)); + Assert.That(frame.Size, Is.EqualTo(10)); + Assert.That(frame.Alpha, Is.EqualTo(204)); + projection.Advance(.02, false, 100); + Assert.That(projection.Frames.Single().Y, Is.EqualTo(561.5436f).Within(.0001f)); + Assert.That(projection.Frames.Single().Alpha, Is.EqualTo(202)); + } + + [TestCase(199.9f, 1)] + [TestCase(200f, 2)] + public void FullChargeAddsTheSecondStarWithoutReplayingAStalledBacklog(float energy, int count) + { + var projection = new BattleSwordSparkProjection(17); + projection.Advance(1, true, energy); + Assert.That(projection.Frames, Has.Count.EqualTo(count)); + Assert.That(projection.Time, Is.EqualTo(1)); + } + + [Test] + public void SamplingAndZeroDeltaNeverAdvanceThePrivateClockOrRandomStream() + { + var sampled = new BattleSwordSparkProjection(17); + var untouched = new BattleSwordSparkProjection(17); + sampled.Advance(.12, true, 200); + untouched.Advance(.12, true, 200); + BattleSwordSparkFrame[] before = sampled.Frames.ToArray(); + for (int repaint = 0; repaint < 200; repaint++) + { + _ = sampled.Frames; + sampled.Advance(0, true, 200); + } + Assert.That(sampled.Time, Is.EqualTo(.12)); + Assert.That(sampled.Frames, Is.EqualTo(before)); + sampled.Advance(.12, true, 200); + untouched.Advance(.12, true, 200); + Assert.That(sampled.Frames, Is.EqualTo(untouched.Frames)); + } + + [Test] + public void HiddenOrDeadHudStopsEmissionAndClearReleasesEveryParticle() + { + var projection = new BattleSwordSparkProjection(17); + projection.Advance(.12, false, 200); + Assert.That(projection.Frames, Is.Empty); + projection.Advance(.02, true, 200); + Assert.That(projection.Frames, Has.Count.EqualTo(2)); + for (int step = 0; step < 150; step++) + projection.Advance(.02, false, 200); + Assert.That(projection.Frames, Is.Empty); + projection.Advance(.02, true, 200); + Assert.That(projection.Frames, Is.Not.Empty); + projection.Clear(); + Assert.That(projection.Frames, Is.Empty); + } + + [Test] + public void ZeroEnergyHasNoVisibleParticleAndInvalidClockInputsAreRejected() + { + var projection = new BattleSwordSparkProjection(17); + projection.Advance(.12, true, 0); + Assert.That(projection.Frames, Is.Empty); + Assert.Throws(() => projection.Advance(-1, true, 200)); + Assert.Throws(() => projection.Advance(double.NaN, true, 200)); + Assert.Throws(() => projection.Advance(.02, true, float.NaN)); + } + } +} diff --git a/Assets/Tests/Battle/Presentation/Editor/BattleSwordSparkProjectionTests.cs.meta b/Assets/Tests/Battle/Presentation/Editor/BattleSwordSparkProjectionTests.cs.meta new file mode 100644 index 00000000..c64f1a5d --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/BattleSwordSparkProjectionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e03676d28e40476b9b255a9286d1a659 diff --git a/Assets/Tests/Battle/Presentation/Editor/Pal3.Battle.Presentation.Tests.asmdef b/Assets/Tests/Battle/Presentation/Editor/Pal3.Battle.Presentation.Tests.asmdef new file mode 100644 index 00000000..4b873024 --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/Pal3.Battle.Presentation.Tests.asmdef @@ -0,0 +1,19 @@ +{ + "name": "Pal3.Battle.Presentation.Tests", + "references": [ + "Pal3.Battle", + "Pal3.Battle.Presentation" + ], + "includePlatforms": [ + "Editor" + ], + "optionalUnityReferences": [ + "TestAssemblies" + ], + "autoReferenced": false, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll" + ], + "noEngineReferences": true +} diff --git a/Assets/Tests/Battle/Presentation/Editor/Pal3.Battle.Presentation.Tests.asmdef.meta b/Assets/Tests/Battle/Presentation/Editor/Pal3.Battle.Presentation.Tests.asmdef.meta new file mode 100644 index 00000000..7699d53f --- /dev/null +++ b/Assets/Tests/Battle/Presentation/Editor/Pal3.Battle.Presentation.Tests.asmdef.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fa6584c538e14bad90e6c7d370b51cf8 diff --git a/Assets/Tests/BattleEditor.meta b/Assets/Tests/BattleEditor.meta new file mode 100644 index 00000000..ef336558 --- /dev/null +++ b/Assets/Tests/BattleEditor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0d1ec611f6d1643c5b9766954ac34d95 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/BattleEditor/Editor.meta b/Assets/Tests/BattleEditor/Editor.meta new file mode 100644 index 00000000..b59856d5 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: cb8127bc0fba343fa9f6295a5f963c72 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/BattleEditor/Editor/Authoring.meta b/Assets/Tests/BattleEditor/Editor/Authoring.meta new file mode 100644 index 00000000..7b4e5bf3 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 25864e9027ae4eae9cfc9599a41cfc6d +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleCameraProjectionTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleCameraProjectionTests.cs new file mode 100644 index 00000000..1ea52f5d --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleCameraProjectionTests.cs @@ -0,0 +1,60 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using Battle; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed class BattleCameraProjectionTests + { + [TestCase(50, 0, 0, 0)] + [TestCase(39, .7f, -.2f, .1f)] + [TestCase(85, -1.2f, .3f, -.6f)] + [TestCase(25, 2.1f, -.4f, .4f)] + public void FixedReferenceProjectionMatchesUnityCameraWithoutOwningItsMutableState(float horizontal, float yaw, float pitch, float roll) + { + var pose = new BattleCameraPose(new BattleMovementPoint(100, 60, -200), yaw, pitch, roll); + var projection = new BattleCameraProjection(pose, horizontal); + var owner = new GameObject("Projection oracle") { hideFlags = HideFlags.HideAndDontSave }; + try + { + Camera camera = owner.AddComponent(); + camera.enabled = false; + camera.aspect = 4f / 3; + camera.fieldOfView = Camera.HorizontalToVerticalFieldOfView(horizontal, camera.aspect); + camera.transform.SetPositionAndRotation(BattleAnimationCatalog.UnityPosition(pose.Position), + Quaternion.LookRotation(new Vector3(-pose.Forward.X, pose.Forward.Y, pose.Forward.Z), + new Vector3(-pose.Up.X, pose.Up.Y, pose.Up.Z))); + // Sample visible, offscreen and rear points at stable depths; + // points on the camera plane have ill-conditioned pixel values. + BattleMovementPoint Point(float depth, float height, float offset) => new( + pose.Position.X + pose.Forward.X * depth + pose.Up.X * height + offset, + pose.Position.Y + pose.Forward.Y * depth + pose.Up.Y * height, + pose.Position.Z + pose.Forward.Z * depth + pose.Up.Z * height); + foreach (BattleMovementPoint world in new[] { Point(700, 80, 50), Point(700, -30, -800), Point(-500, 50, 50) }) + { + Vector3 point = camera.WorldToViewportPoint(BattleAnimationCatalog.UnityPosition(world)); + BattleSpiritPoint actual = projection.Project(world); + Assert.That(actual.X, Is.EqualTo(point.x * 800).Within(.003)); + Assert.That(actual.Y, Is.EqualTo((1 - point.y) * 600).Within(.003)); + } + BattleMovementPoint sample = Point(700, 80, 50); + BattleSpiritPoint before = projection.Project(sample); + camera.transform.position = Vector3.one * 100; + camera.fieldOfView = 80; + camera.aspect = 21f / 9; + BattleSpiritPoint after = projection.Project(sample); + Assert.That((after.X, after.Y), Is.EqualTo((before.X, before.Y))); + } + finally + { + Object.DestroyImmediate(owner); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleCameraProjectionTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleCameraProjectionTests.cs.meta new file mode 100644 index 00000000..421cdd26 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleCameraProjectionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0f5a10130f2843d7ac3c0dd2203de06e diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorBoundaryTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorBoundaryTests.cs new file mode 100644 index 00000000..3280f0e6 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorBoundaryTests.cs @@ -0,0 +1,714 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Threading.Tasks; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + using UnityEditor; + using UnityEngine; + using Object = UnityEngine.Object; + + // These boundaries require neither a native window nor the active scene. + public sealed class BattleEditorBoundaryTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private readonly Dictionary _paths = new(); + private readonly Dictionary _codepages = new(); + private BattleEditorWindow _window; + + private static T Get(object owner, string field) => (T)owner.GetType().GetField(field, Members).GetValue(owner); + + private static void Set(object owner, string field, object value) => owner.GetType().GetField(field, Members).SetValue(owner, value); + + private static object Call(object owner, string method, params object[] args) => owner.GetType().GetMethod(method, Members).Invoke(owner, args); + + private BattleScenario Draft => Get(_window, "_draft").Scenario; + + [SetUp] + public void SetUp() + { + foreach (string variant in new[] { "PAL3", "PAL3A" }) + { + string path = variant + ".BattleEditor.Path", codepage = variant + ".BattleEditor.Codepage"; + _paths[path] = (EditorPrefs.HasKey(path), EditorPrefs.GetString(path)); + _codepages[codepage] = (EditorPrefs.HasKey(codepage), EditorPrefs.GetInt(codepage)); + EditorPrefs.SetString(path, Path.Combine(Application.temporaryCachePath, "missing-battle-boundary-" + variant + Guid.NewGuid().ToString("N"))); + EditorPrefs.SetInt(codepage, variant == "PAL3" ? 936 : 950); + } + _window = ScriptableObject.CreateInstance(); + } + + [TearDown] + public void TearDown() + { + try + { + if (_window != null) + { + Object.DestroyImmediate(_window); + } + } + finally + { + foreach (var pair in _paths) + if (pair.Value.Exists) + EditorPrefs.SetString(pair.Key, pair.Value.Value); + else + EditorPrefs.DeleteKey(pair.Key); + foreach (var pair in _codepages) + if (pair.Value.Exists) + EditorPrefs.SetInt(pair.Key, pair.Value.Value); + else + EditorPrefs.DeleteKey(pair.Key); + _paths.Clear(); + _codepages.Clear(); + } + } + + [TestCase(false)] + [TestCase(true)] + [Category("LocalGameData")] + public void ReloadReconnectsWithTheAppliedSettingsAndPreservesPendingConnectionEdits(bool emptyPath) + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original game data is required to reconnect."); + Set(_window, "_root", root); + Set(_window, "_codepage", 936); + Call(_window, "LoadData"); + string appliedRoot = Get(_window, "_session").Data.Resources.Root; + string pendingRoot = emptyPath ? "" : Path.Combine(root, "basedata"); + Set(_window, "_root", pendingRoot); + Set(_window, "_codepage", 950); + + if (!emptyPath) + { + Assert.Throws(() => Call(_window, "LoadData")); + Assert.That(Get(_window, "_session").Data.Resources.Root, Is.EqualTo(appliedRoot)); + } + + string otherWindowRoot = Path.Combine(root, "scene"); + EditorPrefs.SetString(BattleData.Variant + ".BattleEditor.Path", otherWindowRoot); + EditorPrefs.SetInt(BattleData.Variant + ".BattleEditor.Codepage", 950); + string otherVariant = BattleData.Variant == "PAL3" ? "PAL3A" : "PAL3"; + Call(_window, "RestoreAuthoringVariant", otherVariant); + Call(_window, "OnDisable"); + Call(_window, "OnEnable"); + + BattleEditorSession session = Get(_window, "_session"); + Assert.That(session.Data, Is.Null, "Window enable must return before adopting the resource index."); + Task pending = Get>(_window, "_reconnect"); + Assert.That(pending.Wait(TimeSpan.FromSeconds(15)), Is.True); + Call(_window, "CompleteReconnect"); + BattleData data = session.Data; + Assert.That(data, Is.Not.Null); + Assert.That(data.Resources.Root, Is.EqualTo(appliedRoot)); + Assert.That(data.Resources.Codepage, Is.EqualTo(936)); + Assert.That(Get(_window, "_root"), Is.EqualTo(pendingRoot)); + Assert.That(Get(_window, "_codepage"), Is.EqualTo(950)); + Assert.That(EditorPrefs.GetString(BattleData.Variant + ".BattleEditor.Path"), Is.EqualTo(otherWindowRoot)); + Assert.That(EditorPrefs.GetInt(BattleData.Variant + ".BattleEditor.Codepage"), Is.EqualTo(950)); + } + + [Test] + [Category("LocalGameData")] + public void ManualConnectionSupersedesACompletedReloadCandidateThatHasNotBeenAdopted() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original game data is required to reconnect."); + Call(_window, "BeginReconnect", root, 936); + Task pending = Get>(_window, "_reconnect"); + Assert.That(pending.Wait(TimeSpan.FromSeconds(15)), Is.True); + Assert.That(Get(_window, "_session").Data, Is.Null); + + Call(_window, "ConnectData", root, 936); + BattleData manual = Get(_window, "_session").Data; + Call(_window, "CompleteReconnect"); + Assert.That(manual, Is.Not.SameAs(pending.Result)); + Assert.That(Get(_window, "_session").Data, Is.SameAs(manual)); + Assert.That(Get>(_window, "_reconnect"), Is.Null); + } + + [Test] + public void UndoAndRedoOutsideTheBattleDraftPreservePlayback() + { + var sceneObject = new GameObject("Battle Editor unrelated Undo"); + BattleEditorSession session = Get(_window, "_session"); + try + { + Undo.IncrementCurrentGroup(); + Undo.RecordObject(sceneObject.transform, "Move scene object"); + sceneObject.transform.localPosition = Vector3.right; + Undo.FlushUndoRecordObjects(); + session.IsPlaying = true; + + Undo.PerformUndo(); + Assert.That(sceneObject.transform.localPosition, Is.EqualTo(Vector3.zero)); + Assert.That(session.IsPlaying, Is.True); + Undo.PerformRedo(); + Assert.That(sceneObject.transform.localPosition, Is.EqualTo(Vector3.right)); + Assert.That(session.IsPlaying, Is.True); + } + finally + { + Undo.ClearUndo(sceneObject.transform); + Object.DestroyImmediate(sceneObject); + } + } + + [TestCase(false)] + [TestCase(true)] + public void FailedConnectionKeepsPlaybackAndItsDiagnostic(bool playing) + { + BattleEditorSession session = Get(_window, "_session"); + session.IsPlaying = playing; + string unavailable = Path.Combine(Application.dataPath, "missing-data-" + Guid.NewGuid().ToString("N")); + Set(_window, "_root", unavailable); + + Call(_window, "TryLoadData"); + string error = Get(_window, "_error"); + Assert.That(error, Does.Contain(unavailable)); + Assert.That(session.IsPlaying, Is.EqualTo(playing)); + + Call(_window, "Tick"); + Assert.That(Get(_window, "_error"), Is.EqualTo(error)); + } + + [Test] + public void UndoAndRedoOfTheBattleDraftPausePlayback() + { + BattleEditorSession session = Get(_window, "_session"); + BattleScenarioAsset draft = Get(_window, "_draft"); + try + { + Undo.IncrementCurrentGroup(); + Call(_window, "Edit", "Change battle money", (Action)(() => Draft.Money = 10)); + Undo.FlushUndoRecordObjects(); + session.IsPlaying = true; + + Undo.PerformUndo(); + Assert.That(Draft.Money, Is.Zero); + Assert.That(session.IsPlaying, Is.False); + Assert.That(_window.hasUnsavedChanges, Is.False); + + session.IsPlaying = true; + Undo.PerformRedo(); + Assert.That(Draft.Money, Is.EqualTo(10)); + Assert.That(session.IsPlaying, Is.False); + Assert.That(_window.hasUnsavedChanges, Is.True); + } + finally + { + Undo.ClearUndo(draft); + } + } + + [Test] + public void SavingTheCurrentPresetLeavesOtherEditedAssetsUnsaved() + { + string prefix = "Assets/__BattleSave_" + Guid.NewGuid().ToString("N"); + string currentPath = prefix + "_current.asset", otherPath = prefix + "_other.asset"; + var current = ScriptableObject.CreateInstance(); + var other = ScriptableObject.CreateInstance(); + try + { + AssetDatabase.CreateAsset(current, currentPath); + AssetDatabase.CreateAsset(other, otherPath); + byte[] currentBefore = File.ReadAllBytes(currentPath); + byte[] otherBefore = File.ReadAllBytes(otherPath); + Call(_window, "LoadAsset", current); + other.Scenario.Money = 200; + EditorUtility.SetDirty(other); + Call(_window, "Edit", "Change current preset", (Action)(() => Draft.Money = 100)); + Call(_window, "SaveScenario", false); + + Assert.That(current.Scenario.Money, Is.EqualTo(100)); + Assert.That(File.ReadAllBytes(currentPath), Is.Not.EqualTo(currentBefore)); + Assert.That(EditorUtility.IsDirty(current), Is.False); + Assert.That(File.ReadAllBytes(otherPath), Is.EqualTo(otherBefore)); + Assert.That(EditorUtility.IsDirty(other), Is.True); + Assert.That(other.Scenario.Money, Is.EqualTo(200)); + } + finally + { + AssetDatabase.DeleteAsset(currentPath); + AssetDatabase.DeleteAsset(otherPath); + } + } + + [Test] + public void SerializedVariantSwitchKeepsBothUnsavedDraftsPresetBindingsAndConnections() + { + string first = BattleData.Variant, second = first == "PAL3" ? "PAL3A" : "PAL3"; + var firstAsset = ScriptableObject.CreateInstance(); + var secondAsset = ScriptableObject.CreateInstance(); + string prefix = "Assets/__BattleReload_" + Guid.NewGuid().ToString("N"); + string firstPath = prefix + first + ".asset", secondPath = prefix + second + ".asset"; + BattleScenarioAsset oldDraft = null; + try + { + firstAsset.Scenario = new BattleScenario { Variant = first, Money = 10 }; + AssetDatabase.CreateAsset(firstAsset, firstPath); + Set(_window, "_asset", firstAsset); + Set(_window, "_savedJson", BattleScenarioJson.Serialize(firstAsset.Scenario)); + Draft.Money = 111; + Set(_window, "_root", "/missing/first-unsaved-connection"); + Set(_window, "_codepage", 951); + Call(_window, "RestoreAuthoringVariant", second); + Assert.That(Draft.Variant, Is.EqualTo(second)); + Assert.That(Get(_window, "_asset"), Is.Null); + Assert.That(Get(_window, "_root"), Is.EqualTo(EditorPrefs.GetString(second + ".BattleEditor.Path"))); + Assert.That(Get(_window, "_codepage"), Is.EqualTo(EditorPrefs.GetInt(second + ".BattleEditor.Codepage"))); + secondAsset.Scenario = new BattleScenario { Variant = second, Money = 20 }; + AssetDatabase.CreateAsset(secondAsset, secondPath); + Set(_window, "_asset", secondAsset); + Set(_window, "_savedJson", BattleScenarioJson.Serialize(secondAsset.Scenario)); + Draft.Money = 222; + Set(_window, "_root", "/missing/second-unsaved-connection"); + Set(_window, "_codepage", 952); + // Domain reload keeps the serialized authoring state, while its + // nonpersistent draft object may need to be reconstructed. + Call(_window, "OnDisable"); + oldDraft = Get(_window, "_draft"); + Set(_window, "_draft", null); + string serialized = EditorJsonUtility.ToJson(_window); + string report = Environment.GetEnvironmentVariable("PAL3_BATTLE_REPORT_DIR"); + if (report != null) + File.WriteAllText(Path.Combine(report, BattleData.Variant + "-window-state.json"), serialized); + Object.DestroyImmediate(_window); + _window = ScriptableObject.CreateInstance(); + Call(_window, "OnDisable"); + Object.DestroyImmediate(Get(_window, "_draft")); + EditorJsonUtility.FromJsonOverwrite(serialized, _window); + Call(_window, "OnEnable"); + Assert.That(Draft.Variant, Is.EqualTo(first)); + Assert.That(Draft.Money, Is.EqualTo(111)); + Assert.That(_window.hasUnsavedChanges, Is.True); + Assert.That(Get(_window, "_asset"), Is.SameAs(firstAsset)); + Assert.That(Get(_window, "_root"), Is.EqualTo("/missing/first-unsaved-connection")); + Assert.That(Get(_window, "_codepage"), Is.EqualTo(951)); + Call(_window, "RestoreAuthoringVariant", second); + Call(_window, "UpdateDirty"); + Assert.That(Draft.Variant, Is.EqualTo(second)); + Assert.That(Draft.Money, Is.EqualTo(222)); + Assert.That(_window.hasUnsavedChanges, Is.True); + Assert.That(Get(_window, "_asset"), Is.SameAs(secondAsset)); + Assert.That(Get(_window, "_root"), Is.EqualTo("/missing/second-unsaved-connection")); + Assert.That(Get(_window, "_codepage"), Is.EqualTo(952)); + Assert.That(firstAsset.Scenario.Money, Is.EqualTo(10)); + Assert.That(secondAsset.Scenario.Money, Is.EqualTo(20)); + Assert.That(typeof(EditorWindow).GetField("m_Parent", Members).GetValue(_window), Is.Null); + } + finally + { + if (oldDraft != null) + Object.DestroyImmediate(oldDraft); + AssetDatabase.DeleteAsset(firstPath); + AssetDatabase.DeleteAsset(secondPath); + } + } + + [Test] + public void CancelingOneVariantSaveAsLeavesThePreviouslyBoundAssetUnchanged() + { + string first = BattleData.Variant, second = first == "PAL3" ? "PAL3A" : "PAL3"; + var asset = ScriptableObject.CreateInstance(); + string path = "Assets/__BattleCloseCancel_" + Guid.NewGuid().ToString("N") + ".asset"; + try + { + asset.Scenario = new BattleScenario { Variant = first, Money = 10 }; + AssetDatabase.CreateAsset(asset, path); + Set(_window, "_asset", asset); + Draft.Money = 100; + Call(_window, "UpdateDirty"); + Call(_window, "RestoreAuthoringVariant", second); + Draft.Money = 200; + Call(_window, "UpdateDirty"); + Call(_window, "SaveDrafts", (Func)(_ => null)); + Assert.That(asset.Scenario.Money, Is.EqualTo(10)); + Assert.That(_window.hasUnsavedChanges, Is.True); + Assert.That(_window.saveChangesMessage, Does.Contain(first).And.Contain(second)); + } + finally + { + AssetDatabase.DeleteAsset(path); + } + } + + [Test] + public void ClosingAccountsForInactiveDirtyDraftsAndSavesOrDiscardsEveryVariant() + { + string first = BattleData.Variant, second = first == "PAL3" ? "PAL3A" : "PAL3"; + var firstAsset = ScriptableObject.CreateInstance(); + var secondAsset = ScriptableObject.CreateInstance(); + string prefix = "Assets/__BattleClose_" + Guid.NewGuid().ToString("N"); + string firstPath = prefix + first + ".asset", secondPath = prefix + second + ".asset"; + try + { + firstAsset.Scenario = new BattleScenario { Variant = first, Money = 10 }; + secondAsset.Scenario = new BattleScenario { Variant = second, Money = 20 }; + AssetDatabase.CreateAsset(firstAsset, firstPath); + AssetDatabase.CreateAsset(secondAsset, secondPath); + Set(_window, "_asset", firstAsset); + Draft.Money = 10; + Call(_window, "UpdateDirty"); + Call(_window, "RestoreAuthoringVariant", second); + Set(_window, "_asset", secondAsset); + Draft.Money = 222; + Call(_window, "UpdateDirty"); + Call(_window, "RestoreAuthoringVariant", first); + Call(_window, "UpdateDirty"); + Assert.That(_window.hasUnsavedChanges, Is.True, "An inactive dirty draft must participate in the Editor's close prompt."); + Assert.That(_window.saveChangesMessage, Does.Contain(second)); + Assert.That((bool)typeof(BattleEditorWindow).GetProperty("CurrentDraftDirty", Members).GetValue(_window), Is.False); + Assert.That(Call(_window, "CanReplace"), Is.True, "Creating/replacing a clean current draft must not prompt about another variant."); + Call(_window, "SaveScenario", false); + Assert.That(secondAsset.Scenario.Money, Is.EqualTo(20), "The File menu's Save action still owns only the current draft."); + Assert.That(_window.hasUnsavedChanges, Is.True); + _window.SaveChanges(); + Assert.That(secondAsset.Scenario.Money, Is.EqualTo(222)); + Assert.That(_window.hasUnsavedChanges, Is.False); + Draft.Money = 333; + Call(_window, "UpdateDirty"); + Call(_window, "RestoreAuthoringVariant", second); + Draft.Money = 444; + Call(_window, "UpdateDirty"); + Assert.That(_window.saveChangesMessage, Does.Contain(first).And.Contain(second)); + _window.SaveChanges(); + Assert.That(firstAsset.Scenario.Money, Is.EqualTo(333)); + Assert.That(secondAsset.Scenario.Money, Is.EqualTo(444)); + Assert.That(_window.hasUnsavedChanges, Is.False); + Draft.Money = 555; + Call(_window, "UpdateDirty"); + Call(_window, "RestoreAuthoringVariant", first); + Draft.Money = 666; + Call(_window, "UpdateDirty"); + _window.DiscardChanges(); + Assert.That(Draft.Money, Is.EqualTo(333)); + Assert.That(_window.hasUnsavedChanges, Is.False); + Call(_window, "RestoreAuthoringVariant", second); + Call(_window, "UpdateDirty"); + Assert.That(Draft.Money, Is.EqualTo(444)); + Assert.That(_window.hasUnsavedChanges, Is.False); + } + finally + { + AssetDatabase.DeleteAsset(firstPath); + AssetDatabase.DeleteAsset(secondPath); + } + } + + [TestCase(true)] + [TestCase(false)] + public void LegacyUnownedWindowCanonicalizesBothSidesBeforeVariantMigration(bool keepDraftObject) + { + Call(_window, "OnDisable"); + string previous = BattleData.Variant == "PAL3" ? "PAL3A" : "PAL3"; + BattleScenario scenario = BattleScenarioTests.Scenario(); + scenario.Variant = previous; + scenario.Money = 123; + string legacy = JsonUtility.ToJson(scenario); + BattleScenarioAsset draft = Get(_window, "_draft"); + draft.Scenario = BattleScenarioJson.Deserialize(legacy); + if (!keepDraftObject) + { + Object.DestroyImmediate(draft); + Set(_window, "_draft", null); + } + Get(_window, "_variantDrafts").Clear(); + Set(_window, "_authoringVariant", ""); + Set(_window, "_draftJson", legacy); + Set(_window, "_savedJson", legacy); + Set(_window, "_asset", null); + Set(_window, "_root", "/missing/legacy-owner"); + Set(_window, "_initializeTestInventory", false); + Call(_window, "OnEnable"); + Assert.That(Draft.Variant, Is.EqualTo(BattleData.Variant)); + Assert.That(_window.hasUnsavedChanges, Is.False, "A clean legacy draft must not acquire a dirty inactive variant during migration."); + Call(_window, "RestoreAuthoringVariant", previous); + Call(_window, "UpdateDirty"); + Assert.That(Draft.Money, Is.EqualTo(123)); + Assert.That(Draft.Participants.All(actor => actor.MagicSword == null), Is.True, "Migrate the old inline optional snapshots before storing the old owner."); + Assert.That(Get(_window, "_savedJson"), Is.EqualTo(Get(_window, "_draftJson"))); + Assert.That(_window.hasUnsavedChanges, Is.False); + Draft.Money++; + Call(_window, "UpdateDirty"); + Assert.That(_window.hasUnsavedChanges, Is.True, "Canonicalization must still preserve a real authoring edit."); + Assert.That(BattleScenarioJson.Deserialize(Get(_window, "_savedJson")).Money, Is.EqualTo(123)); + } + + [Test] + public void PreviouslyStoredLegacyBaselineDoesNotKeepAnInactiveVariantDirtyAfterReload() + { + string current = BattleData.Variant, previous = current == "PAL3" ? "PAL3A" : "PAL3"; + Call(_window, "RestoreAuthoringVariant", previous); + BattleScenario scenario = BattleScenarioTests.Scenario(); + scenario.Variant = previous; + scenario.Money = 234; + string legacy = JsonUtility.ToJson(scenario); + Get(_window, "_draft").Scenario = BattleScenarioJson.RestoreDraft(legacy); + Set(_window, "_savedJson", legacy); + Call(_window, "UpdateDirty"); + Assert.That(_window.hasUnsavedChanges, Is.True, "Recreate the previously stored raw-baseline/canonical-draft mismatch."); + Call(_window, "RestoreAuthoringVariant", current); + Call(_window, "OnDisable"); + Call(_window, "OnEnable"); + Assert.That(_window.hasUnsavedChanges, Is.False); + Call(_window, "RestoreAuthoringVariant", previous); + Call(_window, "UpdateDirty"); + Assert.That(Draft.Money, Is.EqualTo(234)); + Assert.That(_window.hasUnsavedChanges, Is.False); + } + + [Test] + public void DiscardUnboundDraftsRebuildsDefaultsForBothActiveAndInactiveVariants() + { + string current = BattleData.Variant, other = current == "PAL3" ? "PAL3A" : "PAL3"; + Draft.Money = 111; + Draft.Scene = "current-baseline"; + Set(_window, "_savedJson", BattleScenarioJson.Serialize(Draft)); + Draft.Money++; + Call(_window, "UpdateDirty"); + Call(_window, "RestoreAuthoringVariant", other); + Draft.Money = 222; + Draft.Scene = "inactive-baseline"; + Set(_window, "_savedJson", BattleScenarioJson.Serialize(Draft)); + Draft.Money++; + Call(_window, "UpdateDirty"); + Call(_window, "RestoreAuthoringVariant", current); + Call(_window, "UpdateDirty"); + Assert.That(_window.hasUnsavedChanges, Is.True); + _window.DiscardChanges(); + Assert.That(Draft.Money, Is.Zero); + Assert.That(Draft.Scene, Is.Empty); + Assert.That(_window.hasUnsavedChanges, Is.False); + Call(_window, "RestoreAuthoringVariant", other); + Call(_window, "UpdateDirty"); + Assert.That(Draft.Variant, Is.EqualTo(other)); + Assert.That(Draft.Money, Is.Zero, "Inactive unbound drafts reset to defaults just like the active draft."); + Assert.That(Draft.Scene, Is.Empty); + Assert.That(Draft.Items, Is.Empty); + Assert.That(Draft.DataFingerprint, Is.Empty); + Assert.That(Get(_window, "_initializeTestInventory"), Is.True, "The other variant must initialize its own test inventory when its data is next loaded."); + Assert.That(_window.hasUnsavedChanges, Is.False); + } + + [TestCase("en-US")] + [TestCase("fr-FR")] + [TestCase("de-DE")] + [Category("LocalGameData")] + public void CompleteNativeBattleDataLoadKeepsAllCameraValuesAcrossEditorCultures(string culture) + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Local game data is required to verify the entire battle loading path."); + CultureInfo previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); + using var reference = new BattleData(root, 936); + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + using var actual = new BattleData(root, 936); + float[] Values(BattleData data) => data.Cameras.DefaultCamConfigs.SelectMany(camera => new[] + { + camera.GameBoxPositionX, camera.GameBoxPositionY, camera.GameBoxPositionZ, + camera.Yaw, camera.Pitch, camera.Roll + }).ToArray(); + Assert.That(actual.Cameras.DefaultCamConfigs, Is.Not.Empty); + Assert.That(Values(actual), Is.EqualTo(Values(reference)), "Loading must reject locale-based decimal/group separator reinterpretation, including silent de-DE corruption."); + float[] Positions(BattleData data) => data.Layout.ActorGameBoxPositions.SelectMany(position => new[] { position.X, position.Y, position.Z }).ToArray(); + Assert.That(Positions(actual), Is.EqualTo(Positions(reference))); + Assert.That(actual.Fingerprint, Is.EqualTo(reference.Fingerprint)); + string report = Environment.GetEnvironmentVariable("PAL3_BATTLE_REPORT_DIR"); + if (report != null) + File.WriteAllText(Path.Combine(report, BattleData.Variant + "-battle-data-" + culture + ".json"), Newtonsoft.Json.JsonConvert.SerializeObject(new + { + variant = BattleData.Variant, + culture, + cameras = actual.Cameras.DefaultCamConfigs, + actual.Fingerprint + }, Newtonsoft.Json.Formatting.Indented)); + } + finally + { + CultureInfo.CurrentCulture = previous; + } + } + + [Test] + public void LegacyWindowInfersTheOldDraftOwnerBeforeOpeningTheCompiledVariant() + { + string previous = BattleData.Variant == "PAL3" ? "PAL3A" : "PAL3"; + Draft.Variant = previous; + Draft.Money = 333; + Set(_window, "_authoringVariant", ""); + Set(_window, "_root", "/missing/legacy-connection"); + Call(_window, "RestoreAuthoringVariant", BattleData.Variant); + Assert.That(Draft.Variant, Is.EqualTo(BattleData.Variant)); + Assert.That(Draft.Money, Is.Zero); + Call(_window, "RestoreAuthoringVariant", previous); + Assert.That(Draft.Variant, Is.EqualTo(previous)); + Assert.That(Draft.Money, Is.EqualTo(333)); + Assert.That(Get(_window, "_root"), Is.EqualTo("/missing/legacy-connection")); + } + + [TestCase(EventModifiers.Command)] + [TestCase(EventModifiers.Control)] + [TestCase(EventModifiers.Alt)] + public void ModifiedEditorShortcutsReachTheEditorWithoutNavigatingOrSubmitting(EventModifiers modifiers) + { + BattleSession battle = BattleHudTests.Session(); + var view = new BattleHudView(); + view.Presenter.Synchronize(battle); + Set(view, "_battle", battle); + Set(view, "_inputEnabled", true); + int inputs = battle.Inputs.Count; + string focus = view.Presenter.FocusedId; + bool editing = EditorGUIUtility.editingTextField; + int hot = GUIUtility.hotControl; + try + { + EditorGUIUtility.editingTextField = false; + GUIUtility.hotControl = 0; + foreach (KeyCode key in new[] { KeyCode.S, KeyCode.Z, KeyCode.R }) + { + var input = new Event { type = EventType.KeyDown, keyCode = key, modifiers = modifiers, mousePosition = new Vector2(5, 5) }; + Call(view, "HandleGuiInput", input, new Rect(0, 0, 800, 600)); + Assert.That(input.type, Is.EqualTo(EventType.KeyDown), key + " must remain available to Editor shortcuts."); + Assert.That(view.Presenter.FocusedId, Is.EqualTo(focus)); + Assert.That(battle.Inputs.Count, Is.EqualTo(inputs)); + } + var bare = new Event { type = EventType.KeyDown, keyCode = KeyCode.S, mousePosition = new Vector2(5, 5) }; + Call(view, "HandleGuiInput", bare, new Rect(0, 0, 800, 600)); + Assert.That(bare.type, Is.EqualTo(EventType.Used)); + Assert.That(view.Presenter.FocusedId, Is.EqualTo("items")); + Assert.That(battle.Inputs.Count, Is.EqualTo(inputs)); + } + finally + { + GUIUtility.hotControl = hot; + EditorGUIUtility.editingTextField = editing; + view.Release(); + } + } + + [TestCase("Stop")] + [TestCase("Dispose")] + [TestCase("Preview")] + [TestCase("Battle")] + [TestCase("Replay")] + [Category("LocalGameData")] + public void FailingReleaseNotificationCannotRetainOldOrCandidatePreviewScenes(string operation) + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Local game data is required for preview ownership verification."); + BattleEditorSession session = Get(_window, "_session"); + session.Load(root, 936); + BattleData data = session.Data; + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = data.Scenes.First(), DataFingerprint = data.Fingerprint, Music = "NONE" }; + scenario.Participants.Add(data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(data, id)); + scenario.Participants.Add(data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + int scenes = UnityEditor.SceneManagement.EditorSceneManager.previewSceneCount; + if (operation is "Replay" or "Battle" or "Preview") + session.StartBattle(scenario); + else + session.Start(scenario); + BattlePreview previous = session.Preview; + Assert.That(UnityEditor.SceneManagement.EditorSceneManager.previewSceneCount, Is.EqualTo(scenes + 1)); + Action notification = Get(session, "PreviewReleased"); + Set(session, "PreviewReleased", notification + (Action)(() => throw new InvalidOperationException("Injected release failure"))); + try + { + Action change = operation switch + { + "Stop" => session.Stop, + "Dispose" => session.Dispose, + "Preview" => () => session.Start(scenario), + "Battle" => () => session.StartBattle(scenario), + _ => session.ReplayBattle + }; + Assert.Throws(() => change()); + Assert.That(session.Preview, Is.Null); + Assert.That(session.Battle, Is.Null); + Assert.That(session.CapturedScenario, Is.Null); + Assert.That(session.ResultPresentation, Is.Null); + Assert.That(session.IsPlaying, Is.False); + Assert.That(previous.View.Root == null, Is.True); + Assert.That(UnityEditor.SceneManagement.EditorSceneManager.previewSceneCount, Is.EqualTo(scenes), + "Both the old preview and a fully constructed replacement must be disposed when a release notification fails."); + if (operation == "Dispose") + Assert.That(session.Data, Is.Null); + else + Assert.That(session.Data, Is.SameAs(data), "Stopping/replacing a preview keeps its read-only data connection."); + } + finally + { + Set(session, "PreviewReleased", notification); + } + } + + [Test] + [Category("LocalGameData")] + public void SessionStopReleasesHudBattlePreviewPointersAndDecodedPixelCaches() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Local game data is required to verify the complete preview ownership chain."); + BattleEditorSession session = Get(_window, "_session"); + session.Load(root, 936); + BattleScenario scenario = BattleTestLoadoutBuilder.CreateScenario(session.Data); + scenario.Scene = session.Data.Scenes.First(); + scenario.Music = "NONE"; + scenario.Encounter = BattleEncounter.AllyAmbush; + scenario.Participants.Add(session.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = session.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(session.Data, id)); + scenario.Participants.Add(session.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + session.StartBattle(scenario); + for (int step = 0; step < 3000 && session.Battle.WaitingActor == null; step++) + session.Battle.Step(); + Assert.That(session.Battle.WaitingActor, Is.Not.Null); + BattleHudView view = Get(_window, "_hud"); + view.TakeNavigationInput(session.Battle); + Set(view, "_data", session.Data); + Set(view, "_preview", session.Preview); + Set(view, "_changed", (Action)(() => _window.Repaint())); + view.PreparePointers(session.Battle, session.Data, session.Preview); + var sprite = new Texture2D(2, 2) { hideFlags = HideFlags.HideAndDontSave }; + try + { + IDictionary pixels = Get(view, "_spritePixels"); + Type pixelType = typeof(BattleHudView).GetNestedType("SpritePixels", BindingFlags.NonPublic); + pixels.Add(sprite, Activator.CreateInstance(pixelType, new object[] { sprite })); + Assert.That(Get(view, "_pointers").Count, Is.GreaterThan(0)); + session.Stop(); + foreach (string field in new[] { "_battle", "_data", "_preview", "_selectionOwner", "_pointerOwner", "_pointerModel", "_changed", "_repaint", "_selectActor" }) + Assert.That(Get(view, field), Is.Null, field + " retained a stopped preview."); + Assert.That(pixels.Count, Is.Zero); + Assert.That(Get(view, "_pointers").Count, Is.Zero); + Assert.That(view.Presenter.Controller, Is.Null); + Assert.That(view.Presenter.FocusItems(), Is.Empty); + Assert.That(view.SendIntent(new BattleHudIntent(BattleHudIntentKind.Repeat)), Is.False); + session.Stop(); + } + finally + { + Object.DestroyImmediate(sprite); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorBoundaryTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorBoundaryTests.cs.meta new file mode 100644 index 00000000..ea96771e --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorBoundaryTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f8b1b82c35924f6dac062c3be19a8924 diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorGamepadInputTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorGamepadInputTests.cs new file mode 100644 index 00000000..e263399c --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorGamepadInputTests.cs @@ -0,0 +1,1105 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Reflection; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + using UnityEditor; + using UnityEngine; + using UnityEngine.InputSystem; + using UnityEngine.InputSystem.LowLevel; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + public sealed class BattleEditorGamepadInputTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private Gamepad _gamepad, _otherGamepad; + private BattleEditorGamepadInput _input; + private BattleEditorWindow _window; + private EditorWindow _otherWindow, _focusedWindow; + private InputDevice _awaitedDevice; + private int _receivedEvents; + private InputUpdateType _receivedUpdate; + private bool _eventHandled, _savedPreference, _hadPreference; + private string _path; + + // Point-only events carry wheel position without becoming list steps. + private static Action CaptureActions(List actions) => input => + { + if (input.Kind != BattleEditorGamepadIntentKind.Point) + actions.Add(input); + }; + + private string Preference => BattleData.Variant + ".BattleEditor.Path"; + + private sealed class Catalog : IBattleCatalog + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + [SetUp] + public void SetUp() + { + _input = null; + _otherGamepad = null; + _window = null; + _otherWindow = null; + _focusedWindow = null; + _savedPreference = false; + _receivedEvents = 0; + _gamepad = InputSystem.AddDevice(); + InputSystem.onEvent += ObserveEvent; + } + + [TearDown] + public void TearDown() + { + _input?.Dispose(); + InputSystem.onEvent -= ObserveEvent; + if (_window != null) + { + _window.DiscardChanges(); + Object.DestroyImmediate(_window); + } + if (_otherWindow != null) + Object.DestroyImmediate(_otherWindow); + if (_otherGamepad != null && _otherGamepad.added) + InputSystem.RemoveDevice(_otherGamepad); + if (_gamepad != null && _gamepad.added) + InputSystem.RemoveDevice(_gamepad); + if (_savedPreference) + { + if (_hadPreference) + EditorPrefs.SetString(Preference, _path); + else + EditorPrefs.DeleteKey(Preference); + } + } + + private void ObserveEvent(InputEventPtr input, InputDevice device) + { + if (device != _awaitedDevice || !(input.IsA() || input.IsA())) + return; + _receivedEvents++; + _receivedUpdate = InputState.currentUpdateType; + _eventHandled = input.handled; + } + + private void CreateOffscreenWindow() + { + _savedPreference = true; + _hadPreference = EditorPrefs.HasKey(Preference); + _path = EditorPrefs.GetString(Preference); + EditorPrefs.SetString(Preference, Path.Combine(Application.temporaryCachePath, "missing-gamepad-test-" + Guid.NewGuid().ToString("N"))); + _window = ScriptableObject.CreateInstance(); + typeof(BattleEditorWindow).GetField("_gamepadFocusedWindow", Members).SetValue(_window, (Func)(() => _focusedWindow)); + ChangeFocus(_window); + } + + private void ChangeFocus(EditorWindow next) + { + if (_focusedWindow == _window) + typeof(BattleEditorWindow).GetMethod("OnLostFocus", Members).Invoke(_window, null); + _focusedWindow = next; + if (_focusedWindow == _window) + typeof(BattleEditorWindow).GetMethod("OnFocus", Members).Invoke(_window, null); + } + + private IEnumerator Send(GamepadState state, Gamepad gamepad = null) + { + _awaitedDevice = gamepad ?? _gamepad; + // Observe after the adapter to detect accidental event consumption. + InputSystem.onEvent -= ObserveEvent; + InputSystem.onEvent += ObserveEvent; + int before = _receivedEvents; + InputSystem.QueueStateEvent((Gamepad)_awaitedDevice, state); + double deadline = EditorApplication.timeSinceStartup + 5; + while (_receivedEvents == before && EditorApplication.timeSinceStartup < deadline) + yield return null; + Assert.That(_receivedEvents, Is.GreaterThan(before), "Unity must pump the queued virtual gamepad event without a manual InputSystem.Update."); + Assert.That(_receivedUpdate, Is.EqualTo(InputUpdateType.Editor), "Exercise the real Edit Mode event route, where ordinary InputAction callbacks are suppressed."); + Assert.That(_eventHandled, Is.False, "Leave the complete gamepad state event available to Unity and other tools."); + } + + private static BattleSession Battle() + { + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = "gamepad-cancel", + DataFingerprint = "gamepad-cancel", + Encounter = BattleEncounter.AllyAmbush + }; + foreach ((string id, BattleSide side, int actor) in new[] { ("A", BattleSide.Ally, 101), ("E", BattleSide.Enemy, 701) }) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = id, + ActorId = actor, + Side = side, + Slot = BattleSlot.Water, + Attributes = new[] { 100, 100, 100, 20, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 100, 100, 100 } + }); + var battle = new BattleSession(new BattleSetup(scenario), new Catalog()); + battle.SetAutomatic(BattleSide.Enemy, false); + battle.Step(); + Assert.That(battle.WaitingActor, Is.EqualTo("A")); + return battle; + } + + private static BattleHudView Hud(BattleSession battle) + { + var hud = new BattleHudView(); + PrepareHud(hud, battle); + return hud; + } + + private static void PrepareHud(BattleHudView hud, BattleSession battle) + { + typeof(BattleHudView).GetField("_battle", Members).SetValue(hud, battle); + hud.Presenter.Synchronize(battle); + hud.SetInputFocus(true); + hud.Presenter.Open(BattleHudPage.Magic); + Assert.That(hud.Presenter.ChooseAction(BattleAction.Attack), Is.True); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + } + + [UnityTest] + public IEnumerator EastButtonReturnsOneHudLevelPerPressAndOtherFaceButtonsDoNotCancel() + { + BattleSession battle = Battle(); + BattleHudView hud = Hud(battle); + int inputs = battle.Inputs.Count; + _input = new BattleEditorGamepadInput(() => true, input => + { + if (input.Kind == BattleEditorGamepadIntentKind.Cancel) + hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Back)); + }); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic)); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic), "Holding B/Circle must not skip another submenu level."); + yield return Send(new GamepadState()); + yield return Send(new GamepadState().WithButton(GamepadButton.South).WithButton(GamepadButton.West).WithButton(GamepadButton.North)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic)); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(battle.Inputs.Count, Is.EqualTo(inputs), "Cancel must not submit a battle command."); + } + + [UnityTest] + public IEnumerator UnfocusedPressIsNotReplayedAndDisposalRemovesTheCallback() + { + bool focused = false; + int cancels = 0; + _input = new BattleEditorGamepadInput(() => focused, input => + { + if (input.Kind == BattleEditorGamepadIntentKind.Cancel) + cancels++; + }); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(cancels, Is.Zero); + focused = true; + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(cancels, Is.Zero, "Regaining focus while held must wait for a release and a new press."); + yield return Send(new GamepadState()); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(cancels, Is.EqualTo(1)); + _input.Dispose(); + _input.Dispose(); + yield return Send(new GamepadState()); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(cancels, Is.EqualTo(1)); + } + + [UnityTest] + public IEnumerator ConnectedGamepadsKeepIndependentPressEdges() + { + int cancels = 0; + _input = new BattleEditorGamepadInput(() => true, input => + { + if (input.Kind == BattleEditorGamepadIntentKind.Cancel) + cancels++; + }); + _otherGamepad = InputSystem.AddDevice(); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + yield return Send(new GamepadState().WithButton(GamepadButton.East), _otherGamepad); + Assert.That(cancels, Is.EqualTo(2)); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + yield return Send(new GamepadState().WithButton(GamepadButton.East), _otherGamepad); + Assert.That(cancels, Is.EqualTo(2)); + } + + [UnityTest] + public IEnumerator FocusedBattleEditorWindowReceivesNativeCancelAndIgnoresItAfterLosingFocus() + { + CreateOffscreenWindow(); + var session = (BattleEditorSession)typeof(BattleEditorWindow).GetField("_session", Members).GetValue(_window); + BattleSession battle = BattleHudTests.Session(BattleData.Variant); + typeof(BattleEditorSession).GetProperty(nameof(BattleEditorSession.Battle)).SetValue(session, battle); + var hud = (BattleHudView)typeof(BattleEditorWindow).GetField("_hud", Members).GetValue(_window); + PrepareHud(hud, battle); + yield return Send(new GamepadState().WithButton(GamepadButton.Start)); + Assert.That(session.Battle, Is.SameAs(battle), "Start without an existing preview must not start authoring actions or open a data-folder dialog."); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + yield return Send(new GamepadState()); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic), "The real window lifecycle must connect gamepad Cancel to its HUD."); + _otherWindow = ScriptableObject.CreateInstance(); + ChangeFocus(_otherWindow); + yield return Send(new GamepadState()); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic)); + ChangeFocus(_window); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic), "Restoring focus must not replay a held cancel."); + yield return Send(new GamepadState()); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + _window.DiscardChanges(); + Object.DestroyImmediate(_window); + Assert.That(typeof(BattleEditorWindow).GetField("_gamepadInput", Members).GetValue(_window), Is.Null); + _window = null; + } + + [UnityTest] + public IEnumerator GamepadCannotSubmitTheTargetBehindAComboCurtain() + { + CreateOffscreenWindow(); + var session = (BattleEditorSession)typeof(BattleEditorWindow).GetField("_session", Members).GetValue(_window); + BattleSession battle = BattleHudTests.Session(BattleData.Variant); + typeof(BattleEditorSession).GetProperty(nameof(BattleEditorSession.Battle)).SetValue(session, battle); + var hud = (BattleHudView)typeof(BattleEditorWindow).GetField("_hud", Members).GetValue(_window); + PrepareHud(hud, battle); + PropertyInfo opacity = typeof(BattleSession).GetProperty(nameof(BattleSession.CoAttackScreenOpacity)); + opacity.SetValue(battle, 1f); + int inputs = battle.Inputs.Count; + yield return Send(new GamepadState().WithButton(GamepadButton.South)); + yield return Send(new GamepadState()); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + Assert.That(battle.Inputs.Count, Is.EqualTo(inputs)); + + opacity.SetValue(battle, 0f); + yield return Send(new GamepadState()); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic)); + } + + private static IEnumerator EditorInputUpdate() + { + bool updated = false; + void AfterUpdate() + { + if (InputState.currentUpdateType == InputUpdateType.Editor) + updated = true; + } + InputSystem.onAfterUpdate += AfterUpdate; + try + { + double deadline = EditorApplication.timeSinceStartup + 5; + while (!updated && EditorApplication.timeSinceStartup < deadline) + yield return null; + Assert.That(updated, Is.True, "Wait for the engine's own Editor input update."); + } + finally + { + InputSystem.onAfterUpdate -= AfterUpdate; + } + } + + private IEnumerator SendDelta(UnityEngine.InputSystem.Controls.AxisControl control, float value) + { + _awaitedDevice = control.device; + InputSystem.onEvent -= ObserveEvent; + InputSystem.onEvent += ObserveEvent; + int before = _receivedEvents; + InputSystem.QueueDeltaStateEvent(control, value); + double deadline = EditorApplication.timeSinceStartup + 5; + while (_receivedEvents == before && EditorApplication.timeSinceStartup < deadline) + yield return null; + Assert.That(_receivedEvents, Is.GreaterThan(before)); + Assert.That(_receivedUpdate, Is.EqualTo(InputUpdateType.Editor)); + Assert.That(_eventHandled, Is.False); + } + + [TestCase(1, 0, BattleHudDirection.Right)] + [TestCase(1, 1, BattleHudDirection.UpRight)] + [TestCase(0, 1, BattleHudDirection.Up)] + [TestCase(-1, 1, BattleHudDirection.UpLeft)] + [TestCase(-1, 0, BattleHudDirection.Left)] + [TestCase(-1, -1, BattleHudDirection.DownLeft)] + [TestCase(0, -1, BattleHudDirection.Down)] + [TestCase(1, -1, BattleHudDirection.DownRight)] + public void DpadAndStickProduceTheSameEightDirections(int x, int y, BattleHudDirection expected) + { + foreach (bool dpad in new[] { false, true }) + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + policy.Sample(dpad ? new BattleEditorGamepadSnapshot(dpadX: x, dpadY: y) : new BattleEditorGamepadSnapshot(x, y), true); + policy.Advance(0, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Navigate)); + Assert.That(intents[0].Direction, Is.EqualTo(expected)); + Assert.That(intents[0].IsRepeat, Is.False); + } + } + + [Test] + public void StickUsesRadialAndSectorHysteresisAndDpadHasPriority() + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + policy.Sample(new BattleEditorGamepadSnapshot(.49f, 0), true); + policy.Advance(0, true, CaptureActions(intents)); + Assert.That(intents, Is.Empty); + policy.Sample(new BattleEditorGamepadSnapshot(.51f, 0), true); + policy.Advance(.01, true, CaptureActions(intents)); + Assert.That(intents[0].Direction, Is.EqualTo(BattleHudDirection.Right)); + policy.Sample(new BattleEditorGamepadSnapshot(.4f, 0), true); + policy.Advance(.02, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1), "Stay active above the lower exit threshold."); + float X(double degrees) => (float)Math.Cos(degrees * Math.PI / 180); + float Y(double degrees) => (float)Math.Sin(degrees * Math.PI / 180); + policy.Sample(new BattleEditorGamepadSnapshot(X(24), Y(24)), true); + policy.Advance(.03, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1), "Do not chatter at the 22.5-degree sector boundary."); + policy.Sample(new BattleEditorGamepadSnapshot(X(29), Y(29)), true); + policy.Advance(.04, true, CaptureActions(intents)); + Assert.That(intents[1].Direction, Is.EqualTo(BattleHudDirection.UpRight)); + policy.Sample(new BattleEditorGamepadSnapshot(1, 0, dpadY: -1), true); + policy.Advance(.05, true, CaptureActions(intents)); + Assert.That(intents[2].Direction, Is.EqualTo(BattleHudDirection.Down)); + } + + [Test] + public void RepeatUsesUiTimeAndNeverReplaysAStalledBacklog() + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + policy.Sample(new BattleEditorGamepadSnapshot(dpadY: 1), true); + policy.Advance(0, true, CaptureActions(intents)); + policy.Advance(.349, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1)); + policy.Advance(.35, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(2)); + Assert.That(intents[1].IsRepeat, Is.True); + policy.Advance(.449, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(2)); + policy.Advance(.45, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(3)); + policy.Advance(100, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(4)); + policy.Advance(100, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(4)); + } + + [Test] + public void NavigationResetKeepsFreshConfirmButRequiresStickToReturnToNeutral() + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + policy.Sample(new BattleEditorGamepadSnapshot(1, 0), true); + policy.Advance(0, true, CaptureActions(intents)); + policy.ResetNavigation(); + policy.Sample(new BattleEditorGamepadSnapshot(1, 0, buttons: BattleEditorGamepadButtons.Confirm), true); + policy.Advance(10, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(2)); + Assert.That(intents[1].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Confirm)); + policy.Sample(default, true); + policy.Advance(10.1, true, CaptureActions(intents)); + policy.Sample(new BattleEditorGamepadSnapshot(1, 0), true); + policy.Advance(10.2, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(3)); + Assert.That(intents[2].IsRepeat, Is.False); + } + + [Test] + public void UnfocusedDirectionDoesNotReplayUntilReleasedAndPressedAgain() + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: -1), false); + policy.Advance(0, false, CaptureActions(intents)); + policy.Advance(1, true, CaptureActions(intents)); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: -1), true); + policy.Advance(2, true, CaptureActions(intents)); + Assert.That(intents, Is.Empty); + policy.Sample(default, true); + policy.Advance(3, true, CaptureActions(intents)); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: -1), true); + policy.Advance(4, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Direction, Is.EqualTo(BattleHudDirection.Left)); + } + + [Test] + public void FreshDpadRemainsUsableWithAnInactiveDriftingStick() + { + var policy = new BattleEditorGamepadState(new BattleEditorGamepadSnapshot(.4f, 0)); + var intents = new List(); + policy.Sample(new BattleEditorGamepadSnapshot(.4f, 0, dpadY: 1), true); + policy.Advance(0, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Direction, Is.EqualTo(BattleHudDirection.Up)); + } + + [Test] + public void ShortDirectionPulseAndSameDirectionRepressAreNotLost() + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + policy.Sample(new BattleEditorGamepadSnapshot(dpadY: 1), true); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: 1, dpadY: 1), true); + policy.Sample(default, true); + policy.Advance(0, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Direction, Is.EqualTo(BattleHudDirection.UpRight)); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: 1), true); + policy.Advance(.01, true, CaptureActions(intents)); + policy.Sample(default, true); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: 1), true); + policy.Advance(.02, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(3), "A new physical press is immediate, without waiting for the repeat delay."); + Assert.That(intents[2].IsRepeat, Is.False); + } + + [Test] + public void ReleasingAnExistingHeldDirectionNeverSynthesizesAnotherPress() + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: 1), true); + policy.Advance(0, true, CaptureActions(intents)); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: 1), true); + policy.Sample(default, true); + policy.Advance(.01, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1)); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: 1), false); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: 1), true); + policy.Sample(default, true); + policy.Advance(.02, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1), "Releasing a press that began unfocused cannot replay it."); + } + + [TestCase(BattleEditorGamepadButtons.Confirm, BattleEditorGamepadIntentKind.Confirm)] + [TestCase(BattleEditorGamepadButtons.Cancel, BattleEditorGamepadIntentKind.Cancel)] + [TestCase(BattleEditorGamepadButtons.PreviousSection, BattleEditorGamepadIntentKind.PreviousSection)] + [TestCase(BattleEditorGamepadButtons.NextSection, BattleEditorGamepadIntentKind.NextSection)] + [TestCase(BattleEditorGamepadButtons.Primary, BattleEditorGamepadIntentKind.Primary)] + [TestCase(BattleEditorGamepadButtons.Repeat, BattleEditorGamepadIntentKind.Repeat)] + [TestCase(BattleEditorGamepadButtons.Transport, BattleEditorGamepadIntentKind.Transport)] + public void ButtonsAreEdgesAndShortPressReleaseIsNotLost(BattleEditorGamepadButtons button, BattleEditorGamepadIntentKind expected) + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + policy.Sample(new BattleEditorGamepadSnapshot(buttons: button), true); + policy.Sample(default, true); + policy.Advance(0, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Kind, Is.EqualTo(expected)); + policy.Advance(100, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1)); + } + + [TestCase(true)] + [TestCase(false)] + public void ConfirmAndDirectionFollowTheirNativeEventOrder(bool confirmFirst) + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + var confirm = new BattleEditorGamepadSnapshot(buttons: BattleEditorGamepadButtons.Confirm); + var down = new BattleEditorGamepadSnapshot(dpadY: -1); + policy.Sample(confirmFirst ? confirm : down, true); + policy.Sample(default, true); + policy.Sample(confirmFirst ? down : confirm, true); + policy.Sample(default, true); + policy.Advance(0, true, input => + { + if (input.Kind != BattleEditorGamepadIntentKind.Point) + intents.Add(input); + if (input.Kind == BattleEditorGamepadIntentKind.Confirm) + policy.ResetNavigation(); + }); + Assert.That(intents.Count, Is.EqualTo(2)); + Assert.That(intents[0].Kind, Is.EqualTo(confirmFirst ? BattleEditorGamepadIntentKind.Confirm : BattleEditorGamepadIntentKind.Navigate)); + Assert.That(intents[1].Kind, Is.EqualTo(confirmFirst ? BattleEditorGamepadIntentKind.Navigate : BattleEditorGamepadIntentKind.Confirm)); + Assert.That(intents.Find(input => input.Kind == BattleEditorGamepadIntentKind.Navigate).Direction, Is.EqualTo(BattleHudDirection.Down)); + Assert.That(intents.TrueForAll(input => !input.IsRepeat), Is.True); + } + + [TestCase(BattleEditorGamepadButtons.Confirm, BattleEditorGamepadButtons.Cancel)] + [TestCase(BattleEditorGamepadButtons.Cancel, BattleEditorGamepadButtons.Confirm)] + [TestCase(BattleEditorGamepadButtons.Confirm, BattleEditorGamepadButtons.Confirm)] + public void SeparateButtonEdgesAreNeverCollapsedByPriorityOrPageReset(BattleEditorGamepadButtons first, BattleEditorGamepadButtons second) + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + policy.Sample(new BattleEditorGamepadSnapshot(buttons: first), true); + policy.Sample(default, true); + policy.Sample(new BattleEditorGamepadSnapshot(buttons: second), true); + policy.Sample(default, true); + policy.Advance(0, true, input => + { + if (input.Kind != BattleEditorGamepadIntentKind.Point) + intents.Add(input); + policy.ResetNavigation(); + }); + Assert.That(intents.Count, Is.EqualTo(2)); + Assert.That(intents[0].Kind, Is.EqualTo(first == BattleEditorGamepadButtons.Confirm ? BattleEditorGamepadIntentKind.Confirm : BattleEditorGamepadIntentKind.Cancel)); + Assert.That(intents[1].Kind, Is.EqualTo(second == BattleEditorGamepadButtons.Confirm ? BattleEditorGamepadIntentKind.Confirm : BattleEditorGamepadIntentKind.Cancel)); + } + + [Test] + public void ComponentsMergeBeforeConfirmButSimultaneousCancelHasPriority() + { + var policy = new BattleEditorGamepadState(); + var intents = new List(); + policy.Sample(new BattleEditorGamepadSnapshot(dpadY: 1), true); + policy.Sample(new BattleEditorGamepadSnapshot(dpadX: 1, dpadY: 1, buttons: BattleEditorGamepadButtons.Confirm), true); + policy.Sample(default, true); + policy.Advance(0, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(2)); + Assert.That(intents[0].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Navigate)); + Assert.That(intents[0].Direction, Is.EqualTo(BattleHudDirection.UpRight)); + Assert.That(intents[1].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Confirm)); + intents.Clear(); + policy.Sample(new BattleEditorGamepadSnapshot(dpadY: -1, buttons: BattleEditorGamepadButtons.Confirm | BattleEditorGamepadButtons.Cancel), true); + policy.Sample(default, true); + policy.Advance(.01, true, CaptureActions(intents)); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Cancel)); + } + + [UnityTest] + public IEnumerator NativeEditorStreamPreservesShortTapsAndCancelWinsSimultaneousConfirm() + { + var intents = new List(); + _input = new BattleEditorGamepadInput(() => true, CaptureActions(intents)); + InputSystem.QueueStateEvent(_gamepad, new GamepadState().WithButton(GamepadButton.South)); + InputSystem.QueueStateEvent(_gamepad, new GamepadState()); + yield return EditorInputUpdate(); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Confirm)); + intents.Clear(); + InputSystem.QueueStateEvent(_gamepad, new GamepadState().WithButton(GamepadButton.DpadUp)); + InputSystem.QueueStateEvent(_gamepad, new GamepadState()); + yield return EditorInputUpdate(); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Navigate)); + Assert.That(intents[0].Direction, Is.EqualTo(BattleHudDirection.Up)); + intents.Clear(); + yield return Send(new GamepadState().WithButton(GamepadButton.South).WithButton(GamepadButton.East)); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Cancel)); + yield return EditorInputUpdate(); + Assert.That(intents.Count, Is.EqualTo(1)); + } + + [UnityTest] + public IEnumerator DeltaEventsKeepAbsentButtonsAndTheOtherStickAxis() + { + var intents = new List(); + _input = new BattleEditorGamepadInput(() => true, CaptureActions(intents), () => 0); + yield return Send(new GamepadState().WithButton(GamepadButton.East)); + yield return SendDelta(_gamepad.leftStick.x, 1); + yield return SendDelta(_gamepad.leftStick.y, 1); + yield return SendDelta(_gamepad.leftStick.x, 0); + Assert.That(intents.FindAll(input => input.Kind == BattleEditorGamepadIntentKind.Cancel).Count, Is.EqualTo(1)); + Assert.That(intents.FindAll(input => input.Kind == BattleEditorGamepadIntentKind.Navigate).ConvertAll(input => input.Direction), + Is.EqualTo(new[] { BattleHudDirection.Right, BattleHudDirection.UpRight, BattleHudDirection.Up })); + } + + [UnityTest] + public IEnumerator NativeEditorUpdatesRepeatWithoutAnotherDeviceEvent() + { + double now = 0; + var intents = new List(); + _input = new BattleEditorGamepadInput(() => true, CaptureActions(intents), () => now); + yield return Send(new GamepadState().WithButton(GamepadButton.DpadDown)); + Assert.That(intents.Count, Is.EqualTo(1)); + now = .349; + yield return EditorInputUpdate(); + Assert.That(intents.Count, Is.EqualTo(1)); + now = .35; + yield return EditorInputUpdate(); + Assert.That(intents.Count, Is.EqualTo(2)); + Assert.That(intents[1].Direction, Is.EqualTo(BattleHudDirection.Down)); + Assert.That(intents[1].IsRepeat, Is.True); + now = 100; + yield return EditorInputUpdate(); + Assert.That(intents.Count, Is.EqualTo(3)); + } + + [UnityTest] + public IEnumerator NativeDpadAndStickReachAllEightDirections() + { + var intents = new List(); + _input = new BattleEditorGamepadInput(() => true, CaptureActions(intents), () => 0); + foreach (bool dpad in new[] { true, false }) + foreach ((int x, int y, BattleHudDirection direction) in new[] + { + (1, 0, BattleHudDirection.Right), (1, 1, BattleHudDirection.UpRight), + (0, 1, BattleHudDirection.Up), (-1, 1, BattleHudDirection.UpLeft), + (-1, 0, BattleHudDirection.Left), (-1, -1, BattleHudDirection.DownLeft), + (0, -1, BattleHudDirection.Down), (1, -1, BattleHudDirection.DownRight) + }) + { + yield return Send(new GamepadState()); + intents.Clear(); + var state = new GamepadState(); + if (dpad) + { + if (x != 0) + state = state.WithButton(x > 0 ? GamepadButton.DpadRight : GamepadButton.DpadLeft); + if (y != 0) + state = state.WithButton(y > 0 ? GamepadButton.DpadUp : GamepadButton.DpadDown); + } + else + state.leftStick = new Vector2(x, y); + yield return Send(state); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Navigate)); + Assert.That(intents[0].Direction, Is.EqualTo(direction)); + } + } + + [UnityTest] + public IEnumerator NativeButtonsMapToSemanticActionsWithoutHeldRepeats() + { + var intents = new List(); + _input = new BattleEditorGamepadInput(() => true, CaptureActions(intents), () => 0); + foreach ((GamepadButton button, BattleEditorGamepadIntentKind kind) in new[] + { + (GamepadButton.South, BattleEditorGamepadIntentKind.Confirm), + (GamepadButton.East, BattleEditorGamepadIntentKind.Cancel), + (GamepadButton.West, BattleEditorGamepadIntentKind.Primary), + (GamepadButton.North, BattleEditorGamepadIntentKind.Repeat), + (GamepadButton.LeftShoulder, BattleEditorGamepadIntentKind.PreviousSection), + (GamepadButton.RightShoulder, BattleEditorGamepadIntentKind.NextSection), + (GamepadButton.Start, BattleEditorGamepadIntentKind.Transport) + }) + { + yield return Send(new GamepadState()); + intents.Clear(); + yield return Send(new GamepadState().WithButton(button)); + yield return Send(new GamepadState().WithButton(button)); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Kind, Is.EqualTo(kind)); + } + } + + private IEnumerator TapInWindow(GamepadState state) + { + // Neutral and release happen through the same real input stream; + // a held direction must not carry into a newly opened submenu. + yield return Send(new GamepadState()); + yield return Send(state); + } + + [UnityTest] + public IEnumerator OffscreenWindowNavigatesAiMagicListsAndRecordsOneTargetedCommand() + { + CreateOffscreenWindow(); + var editor = (BattleEditorSession)typeof(BattleEditorWindow).GetField("_session", Members).GetValue(_window); + BattleSession battle = BattleHudTests.Session(BattleData.Variant); + typeof(BattleEditorSession).GetProperty(nameof(BattleEditorSession.Battle)).SetValue(editor, battle); + var hud = (BattleHudView)typeof(BattleEditorWindow).GetField("_hud", Members).GetValue(_window); + hud.TakeNavigationInput(battle); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("attack")); + int initialInputs = battle.Inputs.Count; + int aiProfile = battle.GetAiProfile("A"); + + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.DpadUp).WithButton(GamepadButton.DpadLeft)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("ai")); + yield return Send(new GamepadState().WithButton(GamepadButton.DpadUp).WithButton(GamepadButton.DpadLeft).WithButton(GamepadButton.South)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Ai)); + Assert.That(hud.Presenter.AiActor, Is.EqualTo("A")); + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.RightShoulder)); + Assert.That(hud.Presenter.AiActor, Is.EqualTo("B")); + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.LeftShoulder)); + Assert.That(hud.Presenter.AiActor, Is.EqualTo("A")); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("flag:0")); + for (int row = 0; row < 5; row++) + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.DpadDown)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("flag:5")); + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.South)); + Assert.That(hud.Presenter.AiFlags("A"), Is.Not.EqualTo(aiProfile), "A toggles the selected draft option."); + Assert.That(battle.GetAiProfile("A"), Is.EqualTo(aiProfile)); + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.East)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(battle.GetAiProfile("A"), Is.EqualTo(aiProfile), "B discards the AI draft without consuming the waiting actor's turn."); + Assert.That(battle.Inputs.Count, Is.EqualTo(initialInputs)); + + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.DpadLeft)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("magic")); + yield return Send(new GamepadState().WithButton(GamepadButton.DpadLeft).WithButton(GamepadButton.South)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic)); + Assert.That(hud.Presenter.Category, Is.Zero); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("ability:301")); + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.RightShoulder)); + Assert.That(hud.Presenter.Category, Is.EqualTo(1)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("ability:302")); + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.LeftShoulder)); + Assert.That(hud.Presenter.Category, Is.Zero); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("ability:301")); + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.DpadDown)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("ability:301"), "The one-row category wraps on down navigation."); + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.DpadUp)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("ability:301"), "The same list also supports up navigation."); + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.South)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + string firstTarget = hud.Presenter.Target; + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.DpadRight)); + string chosenTarget = hud.Presenter.Target; + Assert.That(chosenTarget, Is.Not.EqualTo(firstTarget)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("target:" + chosenTarget)); + Assert.That(battle.Inputs.Count, Is.EqualTo(initialInputs), "Browsing menus, changing categories and choosing a target remain read-only."); + yield return TapInWindow(new GamepadState().WithButton(GamepadButton.South)); + Assert.That(battle.Inputs.Count, Is.EqualTo(initialInputs + 1)); + BattleInput command = battle.Inputs[battle.Inputs.Count - 1]; + Assert.That(command.Kind, Is.EqualTo(BattleInputKind.Command)); + Assert.That(command.Actor, Is.EqualTo("A")); + Assert.That(command.Action, Is.EqualTo(BattleAction.Skill)); + Assert.That(command.AbilityId, Is.EqualTo(301)); + Assert.That(command.Target, Is.EqualTo(chosenTarget)); + yield return Send(new GamepadState().WithButton(GamepadButton.South)); + Assert.That(battle.Inputs.Count, Is.EqualTo(initialInputs + 1), "Holding A across the controller change must not submit a second command."); + } + + private IEnumerator SendBatchInWindow(params GamepadState[] states) + { + _awaitedDevice = _gamepad; + InputSystem.onEvent -= ObserveEvent; + InputSystem.onEvent += ObserveEvent; + int before = _receivedEvents; + bool queued = false; + void QueueBatch() + { + if (queued || InputState.currentUpdateType != InputUpdateType.Editor) + return; + foreach (GamepadState state in states) + InputSystem.QueueStateEvent(_gamepad, state); + queued = true; + } + InputSystem.onBeforeUpdate += QueueBatch; + try + { + double deadline = EditorApplication.timeSinceStartup + 5; + while (_receivedEvents - before < states.Length && EditorApplication.timeSinceStartup < deadline) + yield return null; + Assert.That(queued, Is.True); + Assert.That(_receivedEvents - before, Is.EqualTo(states.Length), "Every state in the ordered batch must reach the engine's native Editor event stream."); + Assert.That(_receivedUpdate, Is.EqualTo(InputUpdateType.Editor)); + Assert.That(_eventHandled, Is.False); + } + finally + { + InputSystem.onBeforeUpdate -= QueueBatch; + } + } + + [UnityTest] + public IEnumerator OffscreenWindowKeepsOppositeConfirmAndDirectionOrdersInTheSameUpdate() + { + CreateOffscreenWindow(); + var editor = (BattleEditorSession)typeof(BattleEditorWindow).GetField("_session", Members).GetValue(_window); + var hud = (BattleHudView)typeof(BattleEditorWindow).GetField("_hud", Members).GetValue(_window); + BattleSession BindBattle() + { + BattleSession battle = BattleHudTests.Session(BattleData.Variant); + typeof(BattleEditorSession).GetProperty(nameof(BattleEditorSession.Battle)).SetValue(editor, battle); + hud.TakeNavigationInput(battle); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("attack")); + return battle; + } + var confirm = new GamepadState().WithButton(GamepadButton.South); + var cancel = new GamepadState().WithButton(GamepadButton.East); + var down = new GamepadState().WithButton(GamepadButton.DpadDown); + var neutral = new GamepadState(); + BattleSession first = BindBattle(); + int inputs = first.Inputs.Count; + yield return SendBatchInWindow(confirm, neutral, down, neutral); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets), "A opens Attack before the later Down chooses a target."); + // This fixture uses native slot order: Fire (E3) precedes Wind (E2). + Assert.That(hud.Presenter.Target, Is.EqualTo("E3")); + Assert.That(first.Inputs.Count, Is.EqualTo(inputs)); + BattleSession reverse = BindBattle(); + inputs = reverse.Inputs.Count; + yield return SendBatchInWindow(down, neutral, confirm, neutral); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets), "Releasing Down returns the command wheel to Attack before the later A."); + Assert.That(reverse.Inputs.Count, Is.EqualTo(inputs)); + BindBattle(); + yield return SendBatchInWindow(confirm, neutral, cancel, neutral); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands), "Separate A then B must both execute in order."); + BindBattle(); + yield return SendBatchInWindow(cancel, neutral, confirm, neutral); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets), "Separate B then A cannot collapse to B alone."); + BattleSession doubleConfirm = BindBattle(); + inputs = doubleConfirm.Inputs.Count; + yield return SendBatchInWindow(confirm, neutral, confirm, neutral); + Assert.That(doubleConfirm.Inputs.Count, Is.EqualTo(inputs + 1), "Two full A gestures select Attack and then submit its default target."); + Assert.That(doubleConfirm.Inputs[inputs].Action, Is.EqualTo(BattleAction.Attack)); + } + + [UnityTest] + public IEnumerator NativeResetRebasesPartialDeltasBeforeFreshNavigation() + { + var intents = new List(); + _input = new BattleEditorGamepadInput(() => true, CaptureActions(intents), () => 0); + foreach (bool hard in new[] { false, true }) + foreach (bool waitForUpdate in new[] { false, true }) + { + yield return Send(new GamepadState()); + intents.Clear(); + yield return Send(new GamepadState().WithButton(GamepadButton.DpadRight)); + Assert.That(intents.Count, Is.EqualTo(1)); + Assert.That(intents[0].Direction, Is.EqualTo(BattleHudDirection.Right)); + InputSystem.ResetDevice(_gamepad, hard); + if (waitForUpdate) + yield return EditorInputUpdate(); + Assert.That(_gamepad.dpad.ReadValue(), Is.EqualTo(Vector2.zero)); + yield return SendDelta(_gamepad.leftStick.y, 1); + Assert.That(intents.Count, Is.EqualTo(2), "A partial delta after reset must use the real neutral baseline rather than cached DpadRight."); + Assert.That(intents[1].Direction, Is.EqualTo(BattleHudDirection.Up)); + Assert.That(intents[1].IsRepeat, Is.False); + } + } + + [UnityTest] + public IEnumerator ControllersKeepNativeOrderAcrossButtonBarriers() + { + var intents = new List(); + _input = new BattleEditorGamepadInput(() => true, CaptureActions(intents), () => 0); + _otherGamepad = InputSystem.AddDevice(); + InputSystem.QueueStateEvent(_otherGamepad, new GamepadState().WithButton(GamepadButton.South)); + InputSystem.QueueStateEvent(_otherGamepad, new GamepadState()); + InputSystem.QueueStateEvent(_gamepad, new GamepadState().WithButton(GamepadButton.DpadDown)); + InputSystem.QueueStateEvent(_gamepad, new GamepadState()); + yield return EditorInputUpdate(); + Assert.That(intents.Count, Is.EqualTo(2)); + Assert.That(intents[0].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Confirm)); + Assert.That(intents[1].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Navigate)); + Assert.That(intents[1].Direction, Is.EqualTo(BattleHudDirection.Down)); + intents.Clear(); + InputSystem.QueueStateEvent(_gamepad, new GamepadState().WithButton(GamepadButton.DpadUp)); + InputSystem.QueueStateEvent(_otherGamepad, new GamepadState().WithButton(GamepadButton.South)); + InputSystem.QueueStateEvent(_otherGamepad, new GamepadState()); + InputSystem.QueueStateEvent(_gamepad, new GamepadState().WithButton(GamepadButton.DpadUp).WithButton(GamepadButton.DpadRight)); + InputSystem.QueueStateEvent(_gamepad, new GamepadState()); + yield return EditorInputUpdate(); + Assert.That(intents.Count, Is.EqualTo(3)); + Assert.That(intents[0].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Navigate)); + Assert.That(intents[0].Direction, Is.EqualTo(BattleHudDirection.Up)); + Assert.That(intents[1].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Confirm)); + Assert.That(intents[2].Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Navigate)); + Assert.That(intents[2].Direction, Is.EqualTo(BattleHudDirection.UpRight)); + } + + [UnityTest] + public IEnumerator NativeNeutralConfirmAndHeldConfirmUseTheirOwnEventSnapshotsWithoutAWindow() + { + BattleSession battle = BattleHudTests.Session(); + var hud = new BattleHudView(); + hud.TakeNavigationInput(battle); + typeof(BattleHudView).GetField("_inputEnabled", Members).SetValue(hud, true); + _input = new BattleEditorGamepadInput(() => true, input => + { + BattleHudPage before = hud.Presenter.Page; + hud.TakeGamepadInput(battle); + hud.SendGamepadIntent(input); + if (before != hud.Presenter.Page) + _input.ResetNavigation(); + }, () => 0); + yield return Send(new GamepadState().WithButton(GamepadButton.DpadUp)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("skills")); + InputSystem.QueueStateEvent(_gamepad, new GamepadState().WithButton(GamepadButton.South)); + InputSystem.QueueStateEvent(_gamepad, new GamepadState()); + yield return EditorInputUpdate(); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + Assert.That(hud.Presenter.Command.Action, Is.EqualTo(BattleAction.Attack)); + hud.Presenter.Back(); + InputSystem.QueueStateEvent(_gamepad, new GamepadState().WithButton(GamepadButton.DpadUp).WithButton(GamepadButton.South)); + InputSystem.QueueStateEvent(_gamepad, new GamepadState()); + yield return EditorInputUpdate(); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Skills), "The later release cannot rewrite the earlier held-direction Confirm."); + } + + [UnityTest] + public IEnumerator NativeResetDisableAndRemovalReturnTheOwnedWheelToCenterWithoutAWindow() + { + BattleSession battle = BattleHudTests.Session(); + var hud = new BattleHudView(); + hud.TakeNavigationInput(battle); + typeof(BattleHudView).GetField("_inputEnabled", Members).SetValue(hud, true); + _input = new BattleEditorGamepadInput(() => true, input => + { + hud.TakeGamepadInput(battle); + hud.SendGamepadIntent(input); + }, () => 0); + yield return Send(new GamepadState().WithButton(GamepadButton.DpadUp)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("skills")); + InputSystem.ResetDevice(_gamepad); + yield return EditorInputUpdate(); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("attack")); + yield return SendDelta(_gamepad.leftStick.x, 1); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("defend")); + InputSystem.DisableDevice(_gamepad); + yield return EditorInputUpdate(); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("attack")); + InputSystem.EnableDevice(_gamepad); + yield return Send(new GamepadState()); + yield return Send(new GamepadState().WithButton(GamepadButton.DpadLeft)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("magic")); + InputSystem.RemoveDevice(_gamepad); + yield return EditorInputUpdate(); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("attack")); + } + + [UnityTest] + public IEnumerator NativeKeyboardTakeoverSuppressesTheOldGamepadReleaseWithoutAWindow() + { + BattleSession battle = BattleHudTests.Session(); + var hud = new BattleHudView(); + hud.TakeGamepadInput(battle); + typeof(BattleHudView).GetField("_inputEnabled", Members).SetValue(hud, true); + _input = new BattleEditorGamepadInput(() => true, input => + { + hud.TakeGamepadInput(battle); + hud.SendGamepadIntent(input); + }, () => 0); + hud.KeyboardTookControl += _input.Suspend; + yield return Send(new GamepadState().WithButton(GamepadButton.DpadUp)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("skills")); + hud.TakeNavigationInput(); + hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Left)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("magic")); + yield return Send(new GamepadState()); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("magic")); + yield return Send(new GamepadState().WithButton(GamepadButton.DpadRight)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("defend")); + } + + [UnityTest] + public IEnumerator NativeResetAndRemovalKeepTheControllerThatOwnsTheWheelAtThatSequenceWithoutAWindow() + { + foreach (bool remove in new[] { false, true }) + for (int order = 0; order < 4; order++) + { + _input?.Dispose(); + if (_gamepad.added) + InputSystem.RemoveDevice(_gamepad); + if (_otherGamepad != null && _otherGamepad.added) + InputSystem.RemoveDevice(_otherGamepad); + _gamepad = InputSystem.AddDevice(); + _otherGamepad = InputSystem.AddDevice(); + BattleSession battle = BattleHudTests.Session(); + var hud = new BattleHudView(); + hud.TakeGamepadInput(battle); + typeof(BattleHudView).GetField("_inputEnabled", Members).SetValue(hud, true); + bool changeAfterState = false, changed = false; + void Change(Gamepad device) + { + changed = true; + if (remove) + InputSystem.RemoveDevice(device); + else + InputSystem.ResetDevice(device); + } + void BeforeAdapterFlush() + { + if (InputState.currentUpdateType == InputUpdateType.Editor && changeAfterState && !changed) + Change(order >= 2 ? _otherGamepad : _gamepad); + } + void AfterState(InputEventPtr input, InputDevice device) + { + if (device == _otherGamepad && (input.IsA() || input.IsA())) + changeAfterState = order != 0; + } + // Device state has been applied when onAfterUpdate starts. + // Register before the adapter so the reset is ordered after + // B's state event and before the adapter's deferred flush. + InputSystem.onAfterUpdate += BeforeAdapterFlush; + _input = new BattleEditorGamepadInput(() => true, input => + { + hud.TakeGamepadInput(battle); + hud.SendGamepadIntent(input); + }, () => 0); + InputSystem.onEvent += AfterState; + try + { + yield return Send(new GamepadState().WithButton(GamepadButton.DpadUp)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("skills")); + int before = battle.Inputs.Count; + if (order == 0) + Change(_gamepad); + GamepadState next = new GamepadState().WithButton(GamepadButton.DpadRight); + if (order == 3) + next = next.WithButton(GamepadButton.South); + yield return Send(next, _otherGamepad); + Assert.That(changed, Is.True); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo(order >= 2 ? "attack" : "defend"), + "Reset applies only to the owner at its place in the native stream, including a newly acquired owner resetting itself."); + Assert.That(battle.Inputs.Count, Is.EqualTo(before), "A reset preserves accepted pointing order without reviving a queued Confirm."); + } + finally + { + InputSystem.onEvent -= AfterState; + InputSystem.onAfterUpdate -= BeforeAdapterFlush; + } + } + } + + [UnityTest] + public IEnumerator FormerOwnerRepeatsAndReleasesKeepTheCurrentWheelDirection() + { + BattleSession battle = BattleHudTests.Session(); + var hud = new BattleHudView(); + hud.TakeGamepadInput(battle); + _otherGamepad = InputSystem.AddDevice(); + double now = 0; + _input = new BattleEditorGamepadInput(() => true, input => + { + hud.TakeGamepadInput(battle); + hud.SendGamepadIntent(input); + }, () => now); + + yield return Send(new GamepadState().WithButton(GamepadButton.DpadUp)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("skills")); + now = .1; + GamepadState right = new GamepadState().WithButton(GamepadButton.DpadRight); + yield return Send(right, _otherGamepad); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("defend")); + now = .36; + yield return Send(right, _otherGamepad); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("defend"), "A's repeat must not move B's wheel."); + yield return Send(new GamepadState()); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("defend"), "A's release must not clear B's direction."); + yield return Send(new GamepadState(), _otherGamepad); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("attack")); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorGamepadInputTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorGamepadInputTests.cs.meta new file mode 100644 index 00000000..7cae8a71 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorGamepadInputTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: aa48b75078f948fc804349d9942abe68 diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorWorkbenchTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorWorkbenchTests.cs new file mode 100644 index 00000000..af3b0af6 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorWorkbenchTests.cs @@ -0,0 +1,578 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using UnityEditor; + using UnityEngine; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + public sealed class BattleEditorWorkbenchTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private BattleEditorWindow _window; + private OffscreenGui _gui; + private float _pixelsPerPointDuringDraw; + private bool _hadPath; + private string _path; + private bool _hadCodepage; + private int _codepage; + + private string Preference => BattleData.Variant + ".BattleEditor.Path"; + private BattleEditorSession Session => Get("_session"); + private BattleScenario Draft => Get("_draft").Scenario; + + private T Get(string field) => (T)typeof(BattleEditorWindow).GetField(field, Members).GetValue(_window); + + private void Set(string field, object value) => typeof(BattleEditorWindow).GetField(field, Members).SetValue(_window, value); + + private object Call(string method, params object[] values) => typeof(BattleEditorWindow).GetMethod(method, Members).Invoke(_window, values); + + [SetUp] + public void SetUp() + { + _hadPath = EditorPrefs.HasKey(Preference); + _path = EditorPrefs.GetString(Preference); + _hadCodepage = EditorPrefs.HasKey(BattleData.Variant + ".BattleEditor.Codepage"); + _codepage = EditorPrefs.GetInt(BattleData.Variant + ".BattleEditor.Codepage"); + EditorPrefs.SetString(Preference, Path.Combine(Application.temporaryCachePath, "missing-battle-ux-" + Guid.NewGuid().ToString("N"))); + _window = ScriptableObject.CreateInstance(); + _window.position = new Rect(0, 0, 1200, 800); + var draw = (Action)typeof(BattleEditorWindow).GetMethod("DrawWindow", Members).CreateDelegate(typeof(Action), _window); + _gui = new OffscreenGui(() => + { + // The host display and detached IMGUI panel can have different pixel scales. + if (Event.current.type == EventType.Repaint) + _pixelsPerPointDuringDraw = EditorGUIUtility.pixelsPerPoint; + draw(); + }); + } + + [TearDown] + public void TearDown() + { + try + { + _gui?.Dispose(); + if (_window != null) + { + _window.DiscardChanges(); + Object.DestroyImmediate(_window); + } + } + finally + { + if (_hadPath) + EditorPrefs.SetString(Preference, _path); + else + EditorPrefs.DeleteKey(Preference); + if (_hadCodepage) + EditorPrefs.SetInt(BattleData.Variant + ".BattleEditor.Codepage", _codepage); + else + EditorPrefs.DeleteKey(BattleData.Variant + ".BattleEditor.Codepage"); + } + } + + private void Paint() + { + _gui.Paint(_window.position.size); + var controls = Get>("_workspaceControls"); + Assert.That(controls, Contains.Key("primary")); + Rect primary = controls["primary"]; + Assert.That(Get("_workspaceCanvasRect").yMax, Is.EqualTo(_window.position.height - 8), "The removed status bar must not reserve space below the canvas."); + foreach (string id in new[] { "stop", "speed", "configuration", "diagnostics" }) + if (controls.TryGetValue(id, out Rect control)) + { + Assert.That(control.yMin, Is.EqualTo(primary.yMin), id + " baseline"); + Assert.That(control.height, Is.EqualTo(primary.height), id + " height"); + } + foreach (var pair in controls.Where(pair => pair.Key.StartsWith("tabs:", StringComparison.Ordinal))) + Assert.That(pair.Value.height, Is.EqualTo(primary.height), pair.Key + " height"); + Assert.That(Get("_workspaceCanvasRect").yMin - primary.yMax, Is.InRange(3, 5), "Keep only a small gap below the transport buttons."); + if (!Get>("_sections").GetValueOrDefault("rules") && + controls.TryGetValue("section:rules", out Rect rules) && controls.TryGetValue("section:presentation", out Rect presentation)) + { + Assert.That(presentation.yMin - rules.yMax, Is.InRange(8, 14), "Collapsed groups need visible separation."); + Assert.That(presentation.xMin, Is.EqualTo(rules.xMin)); + Assert.That(presentation.width, Is.EqualTo(rules.width)); + } + } + + private void Click(string id) => Click(Get>("_workspaceControls")[id].center); + + private void Click(Vector2 point) + { + SendEvent(new Event { type = EventType.MouseDown, button = 0, mousePosition = point }); + SendEvent(new Event { type = EventType.MouseUp, button = 0, mousePosition = point }); + } + + private void SendEvent(Event input) => _gui.SendEvent(input, _window.position.size); + + private void SetEnum(string field, string name) + { + FieldInfo info = typeof(BattleEditorWindow).GetField(field, Members); + info.SetValue(_window, Enum.Parse(info.FieldType, name)); + } + + private void LoadData() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + Assert.That(Directory.Exists(root), Is.True, "Local game data is required."); + Set("_root", root); + Call("LoadData"); + } + + [Test] + public void FirstUseButtonsStartPauseAndApplyAnEditedBattle() + { + Paint(); + Assert.That(Call("PrimaryLabel"), Is.EqualTo("选择数据目录")); + Assert.That(Session.Data, Is.Null); + Capture("first-use"); + LoadData(); + Paint(); + Assert.That(Call("PrimaryLabel"), Is.EqualTo("创建随机战斗")); + Click("welcome-primary"); + Paint(); + Assert.That(Session.Preview, Is.Not.Null); + Assert.That(Session.Battle, Is.Null); + Assert.That(Session.IsPlaying, Is.False); + Assert.That(Call("PrimaryLabel"), Is.EqualTo("开始测试")); + Call("Edit", "Silent test", (Action)(() => + { + Draft.Music = "NONE"; + Draft.Encounter = BattleEncounter.AllyAmbush; + })); + Set("_autoEnemies", false); + Session.Speed = .4f; + Click("primary"); + Assert.That(Session.Battle, Is.Not.Null); + Assert.That(Session.Speed, Is.EqualTo(.4f)); + Assert.That(Session.IsPlaying, Is.True); + Session.Preview.Audio.Muted = Session.Preview.Effects.Muted = true; + Paint(); + Capture("running"); + for (int step = 0; step < 3000 && Session.Battle.WaitingActor == null; step++) + Session.Battle.Step(); + Assert.That(Session.Battle.WaitingActor, Is.Not.Null); + Session.SyncBattle(); + Call("OnFocus"); + Paint(); + Vector2 point = Get("_workspaceCanvasRect").position + new Vector2(32, 32); + Click(point); + int inputs = Session.Battle.Inputs.Count; + SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.F, mousePosition = point }); + Assert.That(Session.Battle.Inputs.Count, Is.GreaterThan(inputs), "The real workbench HUD keyboard route must record a battle command."); + Capture("hud-command-submitted"); + Click("primary"); + Assert.That(Session.IsPlaying, Is.False); + BattleSession original = Session.Battle; + Call("Edit", "Edit seed", (Action)(() => Draft.Seed++)); + Paint(); + Assert.That(Call("PrimaryLabel"), Is.EqualTo("应用并重新开始")); + Click("configuration"); + Paint(); + Capture("pending-configuration"); + Click("primary"); + Assert.That(Session.Battle, Is.Not.SameAs(original)); + Assert.That(Session.IsPlaying, Is.True); + Session.Preview.Audio.Muted = Session.Preview.Effects.Muted = true; + Assert.That(Session.CapturedScenario.Seed, Is.EqualTo(Draft.Seed)); + Session.Battle.Abort(); + Session.SyncBattle(); + Paint(); + Assert.That(Call("PrimaryLabel"), Is.EqualTo("重新测试")); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void ResultKeyboardInputFollowsFocusWhenThePointerIsOutsideTheCanvas() + { + LoadData(); + Call("Edit", "Prepare a completed battle", (Action)(() => + { + BattleData data = Session.Data; + Draft.Scene = data.Scenes.First(); + Draft.Music = "NONE"; + Draft.Participants.Add(data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemyId = data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(data, id)); + BattleParticipant enemy = data.CreateParticipant(enemyId, BattleSide.Enemy, BattleSlot.Water); + enemy.Vitals[0] = 0; + Draft.Participants.Add(enemy); + })); + Call("StartBattle"); + Session.Preview.Audio.Muted = Session.Preview.Effects.Muted = true; + Session.StepBattle(); + BattleResultPresentation result = Session.ResultPresentation; + Assert.That(result, Is.Not.Null); + for (int step = 0; step < 300 && !result.CanSkip; step++) + Session.StepBattle(); + Assert.That(result.CanSkip, Is.True); + int index = result.Index; + + SetEnum("_drawer", "Configuration"); + Paint(); + Click("tab:configuration:0"); + Rect canvas = Get("_workspaceCanvasRect"); + Vector2 toolbar = Get>("_workspaceControls")["primary"].center; + Assert.That(canvas.Contains(toolbar), Is.False); + SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.Return, mousePosition = toolbar }); + Assert.That(result.Index, Is.EqualTo(index), "The sidebar still owns the keyboard."); + + // Release the sidebar's keyboard focus through the canvas input path. + Click(canvas.center); + for (int step = 0; step < 300 && !result.CanSkip; step++) + Session.StepBattle(); + Assert.That(result.CanSkip, Is.True); + index = result.Index; + SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.Return, mousePosition = toolbar }); + Assert.That(result.Index, Is.EqualTo(index + 1), "Moving the pointer away leaves the result keyboard route active."); + } + + [Test] + public void EmptyStateIsCenteredWithEveryDrawerAndPagesRenderWithoutErrors() + { + foreach (Vector2 size in new[] { new Vector2(960, 640), new Vector2(1600, 800), new Vector2(1000, 1000) }) + { + _window.position = new Rect(0, 0, size.x, size.y); + foreach (string drawer in new[] { "None", "Configuration", "Diagnostics", "Connection" }) + { + SetEnum("_drawer", drawer); + Paint(); + Rect canvas = Get("_workspaceCanvasRect"), welcome = Get("_welcomeRect"); + Assert.That(Vector2.Distance(canvas.center, welcome.center), Is.LessThan(.1f)); + Assert.That(welcome.xMin, Is.GreaterThanOrEqualTo(canvas.xMin)); + Assert.That(welcome.xMax, Is.LessThanOrEqualTo(canvas.xMax)); + Assert.That(canvas.width, Is.GreaterThan(500)); + Capture($"empty-{(int)size.x}x{(int)size.y}-{drawer}"); + } + } + LoadData(); + Call("CreateRandomExample"); + SetEnum("_drawer", "Configuration"); + Paint(); + Click("tab:configuration:0"); + Vector2 tabPoint = Get>("_workspaceControls")["tab:configuration:0"].center; + SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.RightArrow, mousePosition = tabPoint }); + Assert.That(Get("_configurationPage"), Is.EqualTo(1), "Clicking a native tab must also focus its keyboard navigation."); + Paint(); + SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.LeftArrow, mousePosition = tabPoint }); + Assert.That(Get("_configurationPage"), Is.Zero); + Paint(); + for (int page = 0; page < 3; page++) + { + Click("tab:configuration:" + page); + Paint(); + Assert.That(Get("_configurationPage"), Is.EqualTo(page)); + Capture("configuration-" + page); + if (page == 0) + { + var sections = Get>("_sections"); + sections["rules"] = sections["presentation"] = true; + Paint(); + Capture("configuration-expanded"); + sections["rules"] = sections["presentation"] = false; + } + } + SetEnum("_drawer", "Diagnostics"); + Paint(); + for (int page = 0; page < 3; page++) + { + Click("tab:diagnostics:" + page); + Paint(); + Assert.That(Get("_diagnosticPage"), Is.EqualTo(page)); + Capture("diagnostics-" + page); + if (page == 0) + { + Get>("_sections")["display"] = true; + Paint(); + Capture("display-settings"); + Get>("_sections")["display"] = false; + } + } + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void RandomNewDraftDetachesSavedAssetAndFailedConnectionKeepsActualData() + { + LoadData(); + Call("CreateRandomExample"); + var asset = ScriptableObject.CreateInstance(); + try + { + asset.Scenario = Draft.Copy(); + string saved = BattleScenarioJson.Serialize(asset.Scenario); + Set("_asset", asset); + Call("UpdateDirty"); + Assert.That(_window.hasUnsavedChanges, Is.False); + Call("CreateRandomExample"); + Assert.That(Get("_asset"), Is.Null); + Assert.That(BattleScenarioJson.Serialize(asset.Scenario), Is.EqualTo(saved)); + Assert.That(_window.hasUnsavedChanges, Is.True); + BattleData connected = Session.Data; + Set("_root", Path.Combine(Application.temporaryCachePath, "missing-" + Guid.NewGuid().ToString("N"))); + Assert.Throws(() => Call("LoadData")); + Assert.That(Session.Data, Is.SameAs(connected)); + SetEnum("_drawer", "Connection"); + Paint(); + Capture("failed-reconnection"); + Set("_savedJson", BattleScenarioJson.Serialize(Draft)); + Call("UpdateDirty"); + Call("StartBattle"); + Session.IsPlaying = true; + Session.Preview.Audio.Muted = Session.Preview.Effects.Muted = true; + Undo.IncrementCurrentGroup(); + Call("Edit", "Seed change", (Action)(() => Draft.Seed++)); + Assert.That(Session.IsPlaying, Is.False); + Undo.FlushUndoRecordObjects(); + Undo.PerformUndo(); + Assert.That(Session.IsPlaying, Is.False); + Assert.That(Draft.Seed, Is.EqualTo(Session.CapturedScenario.Seed)); + Paint(); + Assert.That((bool)typeof(BattleEditorWindow).GetProperty("DraftPending", Members).GetValue(_window), Is.False); + } + finally { Object.DestroyImmediate(asset); } + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void RenderModesAndRetinaDrawUseTheExpectedLightsAndPixelResolution() + { + LoadData(); + Call("CreateRandomExample"); + Call("Edit", "Original lighting fixture", (Action)(() => Draft.ToonRendering = false)); + Call("StartPreview"); + Session.Preview.Trail.Suspended = true; + Paint(); + Rect canvas = Get("_workspaceCanvasRect"); + float height = Math.Min(canvas.height, canvas.width); + RenderTexture target = (RenderTexture)typeof(ResourceBrowser.ResourceModelPreview).GetField("_target", Members).GetValue(Session.Preview.View); + Assert.That(_pixelsPerPointDuringDraw, Is.Positive); + Assert.That(target.width, Is.EqualTo(Mathf.CeilToInt(canvas.width * _pixelsPerPointDuringDraw))); + Assert.That(target.height, Is.EqualTo(Mathf.CeilToInt(height * _pixelsPerPointDuringDraw))); + Assert.That(Session.Preview.View.NativeLighting, Is.Not.Null); + Light[] Lights() => Session.Preview.View.Root.scene.GetRootGameObjects().SelectMany(go => go.GetComponentsInChildren()).ToArray(); + Assert.That(Lights(), Is.Empty, "Original rendering must not create a Unity realtime light."); + Capture("retina-original"); + Call("Edit", "Toon fixture", (Action)(() => + { + Draft.ToonRendering = true; + Draft.Music = "NONE"; + })); + Paint(); + Call("StartPreview"); + Session.IsPlaying = false; + Session.Preview.Audio.Muted = Session.Preview.Effects.Muted = true; + Session.Preview.Trail.Suspended = true; + Paint(); + Assert.That(Session.Preview.View.NativeLighting, Is.Null); + Assert.That(Lights().Length, Is.EqualTo(1)); + Assert.That(Lights()[0].type, Is.EqualTo(LightType.Directional)); + Assert.That(Lights()[0].enabled, Is.True); + Capture("retina-toon"); + Assert.That(Session.Preview.View.Render(96, 64).width, Is.EqualTo(96)); + Assert.That(Session.Preview.View.Render(96, 64).height, Is.EqualTo(64)); + Session.Preview.Trail.Suspended = false; + Session.Preview.Trail.Enabled = true; + Paint(); + target = (RenderTexture)typeof(ResourceBrowser.ResourceModelPreview).GetField("_target", Members).GetValue(Session.Preview.View); + Assert.That(target.width, Is.EqualTo(256)); + Assert.That(target.height, Is.EqualTo(256)); + Capture("native-trail"); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void PresetSaveReopenAndStopPreserveTheConfiguredBattle() + { + LoadData(); + Call("CreateRandomExample"); + var asset = ScriptableObject.CreateInstance(); + string path = "Assets/__BattleVisualFlow_" + Guid.NewGuid().ToString("N") + ".asset"; + try + { + asset.Scenario = Draft.Copy(); + AssetDatabase.CreateAsset(asset, path); + Set("_asset", asset); + Call("Edit", "Configure fixture", (Action)(() => + { + Draft.Music = "NONE"; + Draft.Money = 1234; + })); + _window.SaveChanges(); + Assert.That(_window.hasUnsavedChanges, Is.False); + Assert.That(AssetDatabase.LoadAssetAtPath(path).Scenario.Money, Is.EqualTo(1234)); + Call("NewScenario"); + _window.DiscardChanges(); + Call("LoadAsset", asset); + Assert.That(Draft.Money, Is.EqualTo(1234)); + Paint(); + Click("primary"); + Session.Preview.Audio.Muted = Session.Preview.Effects.Muted = true; + Assert.That(Session.IsPlaying, Is.True); + Paint(); + Capture("saved-preset-running"); + Click("stop"); + Assert.That(Session.Preview, Is.Null); + Assert.That(Session.Battle, Is.Null); + Assert.That(Draft.Money, Is.EqualTo(1234)); + Assert.That(_window.hasUnsavedChanges, Is.False); + } + finally + { + _window.DiscardChanges(); + Set("_asset", null); + AssetDatabase.DeleteAsset(path); + } + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void CompletedResultOffersRestartAfterThePresentationFinishes() + { + LoadData(); + Call("CreateRandomExample"); + Call("Edit", "Result fixture", (Action)(() => + { + Draft.Music = "NONE"; + foreach (BattleParticipant actor in Draft.Participants) + if (actor.Side == BattleSide.Enemy) + actor.Vitals[0] = 0; + })); + Call("StartBattle"); + Session.Preview.Audio.Muted = Session.Preview.Effects.Muted = true; + for (int step = 0; step < 100 && Session.Battle.Status == BattleSessionStatus.Running; step++) + Session.StepBattle(); + Session.SyncBattle(); + Assert.That(Session.Battle.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(Session.ResultPresentation, Is.Not.Null); + Session.IsPlaying = false; + Paint(); + Assert.That(Call("PrimaryLabel"), Is.EqualTo("继续结果")); + Click("primary"); + Assert.That(Session.IsPlaying, Is.True); + for (int second = 0; second < 120 && !Session.ResultPresentation.Completed; second++) + { + Session.SkipResultStep(); + Session.Tick(1f); + } + Assert.That(Session.ResultPresentation.Completed, Is.True); + Paint(); + Assert.That(Call("PrimaryLabel"), Is.EqualTo("重新测试")); + Capture("completed-result"); + BattleSession previous = Session.Battle; + Click("primary"); + Assert.That(Session.Battle, Is.Not.SameAs(previous), "The final result action must rebuild a test instead of attempting to resume an already finished presentation."); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void MenuPickerCallbackIsSafeAndErrorBadgeOpensTheLog() + { + Paint(); + // The file menu invokes the picker callback after the original event. + int? pickerControl = null; + Set("_showAssetPicker", (Action)((asset, id) => pickerControl = id)); + Assert.DoesNotThrow(() => Call("OpenAssetPicker")); + Assert.That(pickerControl, Is.EqualTo(Get("_assetPickerId"))); + Set("_error", "A deliberately long load error for the diagnostic link."); + Set("_diagnosticPage", 0); + Paint(); + Click("diagnostics"); + Assert.That(Get("_diagnosticPage"), Is.EqualTo(2)); + Paint(); + Capture("error-log"); + LogAssert.NoUnexpectedReceived(); + } + + private void AssertRenderedTransport(Texture2D image) + { + Vector2 size = _window.position.size; + Vector2 scale = new(image.width / size.x, image.height / size.y); + Color32[] pixels = image.GetPixels32(); + Color32 Pixel(int x, int y) => pixels[(image.height - 1 - y) * image.width + x]; + var controls = Get>("_workspaceControls"); + Rect primary = controls["primary"]; + foreach (string id in new[] { "file", "connection", "primary", "stop", "speed", "configuration", "diagnostics" }) + { + if (!controls.TryGetValue(id, out Rect rect)) + continue; + Assert.That(rect.y, Is.EqualTo(primary.y), id + " baseline"); + Assert.That(rect.height, Is.EqualTo(primary.height), id + " height"); + Color32 background = Pixel(Mathf.RoundToInt((rect.x - 2) * scale.x), Mathf.RoundToInt(rect.center.y * scale.y)); + int visible = 0; + // Flat native toolbar controls intentionally draw only their + // content until hovered. Check the entire content area rather + // than demanding a raised button border in its left margin. + for (int y = Mathf.CeilToInt(rect.y * scale.y); y < rect.yMax * scale.y; y++) + for (int x = Mathf.CeilToInt(rect.x * scale.x); x < rect.xMax * scale.x; x++) + { + Color32 pixel = Pixel(x, y); + if (Math.Max(Math.Abs(pixel.r - background.r), Math.Max(Math.Abs(pixel.g - background.g), Math.Abs(pixel.b - background.b))) > 32) + visible++; + } + Assert.That(visible, Is.GreaterThan(12 * scale.x * scale.y), id + " must have visible rendered content."); + } + } + + private void Capture(string name) + { + string root = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (string.IsNullOrEmpty(root)) + return; + RenderTexture buffer = _gui.RenderTarget; + Assert.That(buffer, Is.Not.Null); + var image = new Texture2D(buffer.width, buffer.height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = buffer; + image.ReadPixels(new Rect(0, 0, buffer.width, buffer.height), 0, 0); + image.Apply(); + if (name == "running" || name == "saved-preset-running") + AssertRenderedTransport(image); + if (name.StartsWith("configuration-", StringComparison.Ordinal) || name.StartsWith("diagnostics-", StringComparison.Ordinal)) + { + Rect canvas = Get("_workspaceCanvasRect"); + Vector2 size = _window.position.size; + Vector2 scale = new(image.width / size.x, image.height / size.y); + int colored = 0; + Color32[] pixels = image.GetPixels32(); + for (int y = Mathf.CeilToInt(canvas.yMin * scale.y); y < canvas.yMax * scale.y; y += 4) + for (int x = Mathf.CeilToInt(canvas.xMin * scale.x); x < canvas.xMax * scale.x; x += 4) + { + int row = image.height - 1 - y; + if (x < 0 || x >= image.width || row < 0 || row >= image.height) + continue; + Color32 color = pixels[row * image.width + x]; + if (Math.Max(color.r, Math.Max(color.g, color.b)) > 50 && + Math.Max(Math.Abs(color.r - color.g), Math.Abs(color.g - color.b)) > 12) + colored++; + } + Assert.That(colored, Is.GreaterThan(100), "Switching a drawer page must preserve the actual scene pixels in the canvas: " + name); + } + string folder = Path.Combine(root, "Workbench"); + Directory.CreateDirectory(folder); + File.WriteAllBytes(Path.Combine(folder, BattleData.Variant + "-" + name + ".png"), image.EncodeToPNG()); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorWorkbenchTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorWorkbenchTests.cs.meta new file mode 100644 index 00000000..51273b68 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleEditorWorkbenchTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: abf889fbe34b4236b164b55b3a73b052 diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleGamepadWheelTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleGamepadWheelTests.cs new file mode 100644 index 00000000..a2d3e7f7 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleGamepadWheelTests.cs @@ -0,0 +1,390 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + + // No editor windows or native focus are needed for these routing checks. + public sealed class BattleGamepadWheelTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.NonPublic; + + private sealed class InputRoute + { + public readonly BattleSession Battle; + public readonly BattleHudView Hud = new(); + public readonly BattleEditorGamepadState Policy; + public readonly List Events = new(); + private double _time; + + public InputRoute(string variant = "PAL3", BattleEditorGamepadSnapshot initial = default, BattleSession battle = null) + { + Battle = battle ?? BattleHudTests.Session(variant); + Hud.TakeGamepadInput(Battle); + typeof(BattleHudView).GetField("_inputEnabled", Members).SetValue(Hud, true); + Policy = new BattleEditorGamepadState(initial); + Hud.KeyboardTookControl += Policy.Suspend; + } + + public void Sample(BattleEditorGamepadSnapshot snapshot, bool receive = true) => Policy.Sample(snapshot, receive); + + public void Flush() + { + Policy.Advance(_time += .01, true, input => + { + Events.Add(input); + var before = (Hud.Presenter.Page, Hud.Presenter.Category, Hud.Presenter.FormationActor); + Hud.TakeGamepadInput(Battle); + Hud.SendGamepadIntent(input); + if (before != (Hud.Presenter.Page, Hud.Presenter.Category, Hud.Presenter.FormationActor)) + Policy.ResetNavigation(); + }); + } + } + + private sealed class SwordCatalog : IBattleCatalog, IBattleAbilityTimings, IBattleMagicSwordTimings + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => Attack(actor, null); + + public BattleMagicSwordStageProfile MagicSword(string actor, BattleAbilityDefinition ability) => new(438, -1, 0, 0, 5); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "A" ? 0 : 1; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class SwordRules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => + actor.Side == BattleSide.Ally ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => 1; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => new(-1, false, false); + } + + private sealed class SwordDirector : IBattleEffectDirector + { + public long Start(BattleEffectRequest request) => 1; + + public bool IsRunning(long handle) => false; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + } + } + + private static BattleSession ChargedSwordBattle() + { + var scenario = new BattleScenario { Variant = "PAL3", Scene = "wheel-sword", DataFingerprint = "wheel-sword" }; + foreach ((string id, BattleSide side) in new[] { ("A", BattleSide.Ally), ("E", BattleSide.Enemy) }) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = BattleSlot.Water, + Attributes = new[] { 500, 100, 100, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 100, 100 } + }); + scenario.Participants[0].Equipment[0] = BattleMagicSwordRules.WeaponId; + scenario.Participants[0].MagicSword = new BattleMagicSword { Energy = 200, SkillId = 2224 }; + var skill = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 2224, + Name = "charged sword", + SkillTypeId = 4, + Range = BattleTargetRange.OpponentAll, + ApplicableIdentities = new[] { 1, 2, 3, 4 }, + SuccessRate = 0 + }); + var definitions = new BattleDefinitions("PAL3", scenario.DataFingerprint, new[] { skill }, Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1, + MagicSword = actor.MagicSword?.Capture(), + Equipment = actor.MagicSword == null ? Array.Empty() : new[] + { + new BattleEquipmentDefinition(new BattleEquipmentData { Id = BattleMagicSwordRules.WeaponId, Slot = 0 }) + } + }))); + var battle = new BattleSession(new BattleSetup(scenario), new SwordCatalog(), new SwordRules(), definitions, new SwordDirector()); + battle.SetAutomatic(BattleSide.Enemy, false); + battle.Step(); + return battle; + } + + [TestCase(1, 0, "defend")] + [TestCase(1, 1, "protection")] + [TestCase(0, 1, "skills")] + [TestCase(-1, 1, "ai")] + [TestCase(-1, 0, "magic")] + [TestCase(-1, -1, "formation")] + [TestCase(0, -1, "items")] + [TestCase(1, -1, "flee")] + public void CurrentDpadAndStickDirectionSelectEachSectorAndNeutralReturnsToAttack(int x, int y, string expected) + { + foreach (string variant in new[] { "PAL3", "PAL3A" }) + foreach (bool dpad in new[] { false, true }) + { + var route = new InputRoute(variant); + int inputs = route.Battle.Inputs.Count; + route.Sample(new BattleEditorGamepadSnapshot(dpadX: -1)); + route.Flush(); + route.Sample(dpad ? new BattleEditorGamepadSnapshot(dpadX: x, dpadY: y) : new BattleEditorGamepadSnapshot(x, y)); + route.Flush(); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo(expected), "Select from the wheel center, independently of the previous selection."); + route.Sample(default); + route.Flush(); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("attack")); + Assert.That(route.Events.Last().Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Point)); + Assert.That(route.Events.Last().PointingDirection, Is.EqualTo(BattleHudDirection.Neutral)); + Assert.That(route.Battle.Inputs.Count, Is.EqualTo(inputs)); + } + } + + [Test] + public void NeutralAndConfirmInOneUpdateUseTheCurrentCenterBeforeConfirming() + { + foreach (bool sameEvent in new[] { false, true }) + { + var route = new InputRoute(); + route.Sample(new BattleEditorGamepadSnapshot(dpadY: 1)); + route.Flush(); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("skills")); + if (!sameEvent) + route.Sample(default); + route.Sample(new BattleEditorGamepadSnapshot(buttons: BattleEditorGamepadButtons.Confirm)); + route.Flush(); + Assert.That(route.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + Assert.That(route.Hud.Presenter.Command.Action, Is.EqualTo(BattleAction.Attack)); + Assert.That(route.Events.Last().PointingDirection, Is.EqualTo(BattleHudDirection.Neutral)); + } + } + + [Test] + public void ConfirmKeepsItsEventDirectionBeforeALaterNativeRelease() + { + var route = new InputRoute(); + route.Sample(new BattleEditorGamepadSnapshot(0, 1, buttons: BattleEditorGamepadButtons.Confirm)); + route.Sample(default); + route.Flush(); + Assert.That(route.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Skills)); + Assert.That(route.Events.Single(input => input.Kind == BattleEditorGamepadIntentKind.Confirm).PointingDirection, + Is.EqualTo(BattleHudDirection.Up), "Use the Confirm event's position, not the later final device state."); + } + + [Test] + public void ConfirmWithoutADeviceSnapshotPreservesKeyboardAndMouseSelection() + { + var route = new InputRoute(); + route.Hud.Presenter.SetFocus("skills"); + route.Hud.SendGamepadIntent(new BattleEditorGamepadIntent(BattleEditorGamepadIntentKind.Confirm)); + Assert.That(route.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Skills)); + route.Hud.Presenter.Back(); + route.Hud.Presenter.SetFocus("magic"); + route.Hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Confirm)); + Assert.That(route.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic)); + } + + [Test] + public void PageResetStillTracksHeldPositionWithoutMovingTheListAndBackRestoresItImmediately() + { + var route = new InputRoute(); + route.Sample(new BattleEditorGamepadSnapshot(0, 1, buttons: BattleEditorGamepadButtons.Confirm)); + route.Flush(); + Assert.That(route.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Skills)); + string focus = route.Hud.Presenter.FocusedId; + route.Sample(new BattleEditorGamepadSnapshot(1, 0)); + route.Flush(); + Assert.That(route.Events.Last().Kind, Is.EqualTo(BattleEditorGamepadIntentKind.Point)); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo(focus)); + route.Sample(new BattleEditorGamepadSnapshot(1, 0, buttons: BattleEditorGamepadButtons.Cancel)); + route.Flush(); + Assert.That(route.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("defend"), "Returning to Commands shows the still-held current position before a repeat or Confirm."); + } + + [TestCase(BattleHudPage.Skills)] + [TestCase(BattleHudPage.Magic)] + [TestCase(BattleHudPage.Items)] + [TestCase(BattleHudPage.Targets)] + public void NeutralDoesNotStepListsTargetsOrFormation(BattleHudPage page) + { + var route = new InputRoute(); + if (page == BattleHudPage.Targets) + route.Hud.Presenter.ChooseAction(BattleAction.Attack); + else + route.Hud.Presenter.Open(page); + route.Sample(new BattleEditorGamepadSnapshot(dpadY: -1)); + route.Flush(); + string focus = route.Hud.Presenter.FocusedId; + string target = route.Hud.Presenter.Target; + int inputs = route.Battle.Inputs.Count; + route.Sample(default); + route.Flush(); + Assert.That(route.Hud.Presenter.Page, Is.EqualTo(page)); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo(focus)); + Assert.That(route.Hud.Presenter.Target, Is.EqualTo(target)); + Assert.That(route.Battle.Inputs.Count, Is.EqualTo(inputs)); + } + + [Test] + public void NeutralHasNoNavigationMeaningOnTheFormationPanel() + { + var route = new InputRoute(); + route.Hud.Presenter.Open(BattleHudPage.Formation); + string focus = route.Hud.Presenter.FocusedId; + int inputs = route.Battle.Inputs.Count; + Assert.That(route.Hud.Presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Neutral)), Is.False); + Assert.That(route.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Formation)); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo(focus)); + Assert.That(route.Battle.Inputs.Count, Is.EqualTo(inputs)); + } + + [Test] + public void DpadReleaseFallsBackToHeldStickBeforeReturningToCenter() + { + var route = new InputRoute(); + route.Sample(new BattleEditorGamepadSnapshot(1, 0, dpadY: 1)); + route.Flush(); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("skills")); + route.Sample(new BattleEditorGamepadSnapshot(1, 0)); + route.Flush(); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("defend")); + route.Sample(default); + route.Flush(); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("attack")); + } + + [Test] + public void FocusLossDoesNotReplayHeldPositionAndReleaseAfterPointerTakeoverDoesNotStealFocus() + { + var route = new InputRoute(); + route.Sample(new BattleEditorGamepadSnapshot(dpadY: 1)); + route.Flush(); + route.Policy.Suspend(); + route.Hud.SetInputFocus(false); + route.Sample(new BattleEditorGamepadSnapshot(dpadX: 1), false); + route.Hud.SetInputFocus(true); + route.Events.Clear(); + route.Sample(new BattleEditorGamepadSnapshot(dpadX: 1)); + route.Flush(); + Assert.That(route.Events, Is.Empty); + route.Hud.Presenter.SetFocus("magic"); + typeof(BattleHudView).GetField("_navigationInput", Members).SetValue(route.Hud, false); + route.Policy.Suspend(); + route.Sample(default); + route.Flush(); + Assert.That(route.Events, Is.Empty, "A release after mouse takeover cannot become a fresh gamepad selection."); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("magic")); + } + + [Test] + public void SynchronizeRestoresCurrentWheelPositionWhenACommandsPageReopensWithoutAnInputEvent() + { + var route = new InputRoute(); + route.Sample(new BattleEditorGamepadSnapshot(dpadX: -1)); + route.Flush(); + route.Hud.Presenter.Open(BattleHudPage.Skills); + // Record the non-command page before the next synchronization. + typeof(BattleHudView).GetMethod("Synchronize", Members).Invoke(route.Hud, new object[] { route.Battle }); + route.Hud.Presenter.Back(); + typeof(BattleHudView).GetMethod("Synchronize", Members).Invoke(route.Hud, new object[] { route.Battle }); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("magic")); + } + + [Test] + public void KeyboardTakeoverSuspendsHeldAndAlreadyQueuedGamepadReleaseUntilAFreshGesture() + { + foreach (bool releaseWasQueued in new[] { false, true }) + { + var route = new InputRoute(); + route.Sample(new BattleEditorGamepadSnapshot(0, 1)); + route.Flush(); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("skills")); + if (releaseWasQueued) + route.Sample(default); + route.Hud.TakeNavigationInput(); + route.Hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Left)); + if (!releaseWasQueued) + route.Sample(default); + route.Events.Clear(); + route.Flush(); + Assert.That(route.Events, Is.Empty); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("magic"), "The released old gamepad gesture cannot replace a keyboard selection."); + route.Sample(new BattleEditorGamepadSnapshot(1, 0)); + route.Flush(); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("defend"), "A new physical gamepad gesture can deliberately take control again."); + } + } + + [Test] + public void PageResetRetainsTheCurrentStickSectorUntilTheRealExitThreshold() + { + var route = new InputRoute(); + route.Sample(new BattleEditorGamepadSnapshot(0, 1)); + route.Flush(); + route.Sample(new BattleEditorGamepadSnapshot(0, .4f)); + route.Flush(); + route.Policy.ResetNavigation(); + route.Hud.Presenter.Open(BattleHudPage.Skills); + route.Sample(new BattleEditorGamepadSnapshot(0, .4f, buttons: BattleEditorGamepadButtons.Cancel)); + route.Flush(); + Assert.That(route.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("skills")); + Assert.That(route.Events.Last().PointingDirection, Is.EqualTo(BattleHudDirection.Up)); + route.Sample(new BattleEditorGamepadSnapshot(0, .34f)); + route.Flush(); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("attack")); + } + + [Test] + public void ShoulderNavigationSurvivesRepaintAndNeutralConfirmExecutesTheChargedSword() + { + var route = new InputRoute(battle: ChargedSwordBattle()); + Assert.That(route.Hud.Presenter.FocusItems().Single(item => item.Id == "sword").Enabled, Is.True, route.Hud.Presenter.Reason(BattleAction.Skill, 2224)); + for (int attempt = 0; attempt < 12 && route.Hud.Presenter.FocusedId != "sword"; attempt++) + { + route.Sample(new BattleEditorGamepadSnapshot(buttons: BattleEditorGamepadButtons.NextSection)); + route.Flush(); + string selected = route.Hud.Presenter.FocusedId; + typeof(BattleHudView).GetMethod("Synchronize", Members).Invoke(route.Hud, new object[] { route.Battle }); + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo(selected), "An ordinary repaint cannot snap a shoulder selection back to the wheel center."); + route.Sample(default); + route.Flush(); + } + Assert.That(route.Hud.Presenter.FocusedId, Is.EqualTo("sword")); + int before = route.Battle.Inputs.Count; + route.Sample(new BattleEditorGamepadSnapshot(buttons: BattleEditorGamepadButtons.Confirm)); + route.Flush(); + Assert.That(route.Battle.Inputs.Count, Is.EqualTo(before + 1)); + Assert.That(route.Battle.Inputs.Last().Kind, Is.EqualTo(BattleInputKind.Command)); + Assert.That(route.Battle.Inputs.Last().Action, Is.EqualTo(BattleAction.Skill)); + Assert.That(route.Battle.Inputs.Last().AbilityId, Is.EqualTo(2224)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleGamepadWheelTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleGamepadWheelTests.cs.meta new file mode 100644 index 00000000..5923416a --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleGamepadWheelTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d21e52c7673244b29cb3bad5e026e7d1 diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleOriginalControlTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleOriginalControlTests.cs new file mode 100644 index 00000000..d409accb --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleOriginalControlTests.cs @@ -0,0 +1,313 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Reflection; + using Core.DataReader.Data; + using Core.DataReader.Cpk; + using Core.FileSystem; + using Game.Effect.Runtime; + using Newtonsoft.Json.Linq; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed class BattleOriginalControlTests + { + private sealed class Actor : IEffectActor + { + public Vector3 Position + { + get; set; + } + + public float FacingDegrees { get; set; } = 45; + + public float Blend { get; set; } = 1; + + public bool ActionOver + { + get; set; + } + + public bool Controlled, LongBlade; + public float Left, Right; + public string Action; + + public void SetExternalTask(bool controlled, object owner) => Controlled = controlled; + + public void SetAction(string action) => Action = action; + + public void SetLongBlade(bool enabled) => LongBlade = enabled; + + public void SetWeapons(float left, float right) + { + Left = left; + Right = right; + } + } + + private sealed class CameraPort : IEffectCamera + { + public int Starts, Stops, Index; + public Vector3 Quake; + + public void StopList() => Stops++; + + public bool StartList(int index) + { + Starts++; + Index = index; + return true; + } + + public void SetQuake(float amplitude, float frequency, float decay) => Quake = new Vector3(amplitude, frequency, decay); + } + + private sealed class Movie : IEffectMovie + { + public bool Finished + { + get; set; + } + + public bool Disposed; + + public void Dispose() => Disposed = true; + } + + private sealed class Context : IBattleEffectContext + { + private readonly Battle.BattleRandom _effectRandom = new(1); + + public int NextEffectRandom() => _effectRandom.Next(); + + public readonly Actor Role = new(); + public readonly CameraPort Cam = new(); + public readonly Movie Film = new(); + public readonly List Movies = new(); + + public IEffectActor Actor(int nativeIndex, uint modelCrc = 0) => Role; + + public IEffectCamera Camera => Cam; + + public bool IsModalPresentationRunning => Movies.Count > 0 && !Film.Finished; + + public IEffectMovie PlayMovie(string originalPath) + { + Movies.Add(originalPath); + return Film; + } + } + + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + private static Type NodeType => typeof(EffectPlayer).Assembly.GetType("Pal3.Game.Effect.Runtime.BattleControlNode", true); + private static Type ClockType => typeof(EffectPlayer).Assembly.GetType("Pal3.Game.Effect.Runtime.EffectTaskClock", true); + + private static object Node(GameObject root, EffectTask task, Context context, string kind, bool externalNames = false) => + Activator.CreateInstance(NodeType, Members, null, new object[] { root, new EffectDefinition { VideoFileNamePrefix = "2DEFFECT\\t" }, new[] { task }, Vector3.zero, 0f, context, kind, externalNames }, null); + + private static bool Apply(object node, EffectTask task, float elapsed, float delta, bool started = true, bool finished = false) + { + object clock = Activator.CreateInstance(ClockType, true); + ClockType.GetProperty("StartedAt", Members).SetValue(clock, 0f); + ClockType.GetProperty("StartedNow", Members).SetValue(clock, started); + ClockType.GetField("_finished", Members).SetValue(clock, finished); + NodeType.BaseType.GetField("LocalTime", Members).SetValue(node, elapsed); + NodeType.GetMethod("Apply", Members).Invoke(node, new[] { task, clock, (object)delta }); + return (bool)ClockType.GetProperty("Finished", Members).GetValue(clock); + } + + [Test] + [Category("LocalNativeEvidence")] + public void CombatTaskDurationUsesThePublishedStrictBoundaryWithoutAnEarlyEpsilon() + { + string directory = Environment.GetEnvironmentVariable("PAL3_NATIVE_VECTORS_ROOT"); + if (directory == null) + Assert.Ignore("Published native vectors are local analysis artifacts."); + JObject evidence = JObject.Parse(File.ReadAllText(Path.Combine(directory, "effect-duration-native-vectors.json"))); + int count = 0; + foreach (JProperty variant in evidence.Properties()) + foreach (JToken row in variant.Value["rows"]) + { + var task = new EffectTask { Duration = (float)row["config"]["duration"] }; + object clock = Activator.CreateInstance(ClockType, true); + ClockType.GetField("NativeComparison", Members).SetValue(clock, true); + ClockType.GetField("_initialized", Members).SetValue(clock, true); + ClockType.GetProperty("StartedAt", Members).SetValue(clock, 0f); + object[] parameters = { (float)row["config"]["elapsed"], .02f, task, 0f }; + Assert.That(ClockType.GetMethod("Tick", Members).Invoke(clock, parameters), Is.True); + Assert.That(ClockType.GetProperty("Finished", Members).GetValue(clock), Is.EqualTo((bool)row["finished"]), variant.Name + ": " + row["config"]); + count++; + } + Assert.That(count, Is.EqualTo(50)); + } + + [Test] + public void ModalMovieResumesTheRemainingNodesAtTheSameEffectTime() + { + var hash = new Crc32Hash(); + hash.Init(); + using var resources = new EffectResources(new CpkFileSystem(Application.temporaryCachePath, hash, 936)); + var definitions = new EffectDefinition[1324]; + definitions[0] = new EffectDefinition { IsValid = true, TypeNameCrc = 1, ClassNameCrc = hash.Compute("bink", 936), VideoFileNamePrefix = "2DEFFECT\\t" }; + definitions[1] = new EffectDefinition { IsValid = true, TypeNameCrc = 2, ClassNameCrc = hash.Compute("action", 936) }; + var group = new EffectGroup + { + Objects = new[] + { + new EffectGroupObject { TypeCrc = 1, Tasks = new[] { new EffectTask { IsValid = true, XStretchSpeed = 102, StartTime = -1, Duration = 1 } } }, + new EffectGroupObject { TypeCrc = 2, Tasks = new[] { new EffectTask { IsValid = true, XStretchSpeed = 17, SpeedX = 10, StartTime = -1, Duration = 1 } } } + } + }; + typeof(EffectResources).GetField("_definitions", Members).SetValue(resources, new EffectDefinitionFile(definitions, new[] { group })); + var context = new Context(); + var root = new GameObject("modal effect continuation"); + var player = root.AddComponent(); + player.AutoAdvance = false; + try + { + player.Initialize(resources, 0, battleContext: context, clockOrigin: 1000); + player.AdvanceTo(1000.02); + Assert.That(player.Error, Is.Null); + Assert.That(context.IsModalPresentationRunning, Is.True); + Assert.That(context.Role.Action, Is.Null); + float paused = player.Time; + Assert.That(player.ResumeBattleStep(), Is.False); + Assert.That(player.Time, Is.EqualTo(paused)); + context.Film.Finished = true; + Assert.That(player.ResumeBattleStep(), Is.True); + Assert.That(player.Time, Is.EqualTo(paused)); + Assert.That(context.Role.Action, Is.EqualTo("z17")); + Assert.That(context.Role.Position.x, Is.EqualTo(((float)1000.02 - 1000f) * 10).Within(0.000001f)); + Assert.That(player.Error, Is.Null); + } + finally { Object.DestroyImmediate(root); } + } + + [Test] + public void CameraAndQuakeDispatchTheirNativeFieldsAndCancellation() + { + var context = new Context(); + var root = new GameObject("original control fixture") { hideFlags = HideFlags.HideAndDontSave }; + object node = null; + try + { + var camera = new EffectTask { XStretchSpeed = 54, Duration = 10 }; + node = Node(root, camera, context, "camera"); + Apply(node, camera, 0, 0.02f); + Assert.That((context.Cam.Stops, context.Cam.Starts, context.Cam.Index), Is.EqualTo((1, 1, 54))); + ((IDisposable)node).Dispose(); + node = null; + Assert.That(context.Cam.Stops, Is.EqualTo(2)); + var quake = new EffectTask { XStretchSpeed = 9, SpeedX = 2, SpeedY = 80 }; + node = Node(root, quake, context, "quake"); + Apply(node, quake, 0, 0.02f); + Assert.That(context.Cam.Quake, Is.EqualTo(new Vector3(9, 80, 2))); + } + finally + { + try + { + ((IDisposable)node)?.Dispose(); + } + finally { Object.DestroyImmediate(root); } + } + } + + [Test] + public void MovieKeepsItsTaskUntilTheModalPresentationFinishes() + { + var context = new Context(); + var root = new GameObject("original Bink fixture") { hideFlags = HideFlags.HideAndDontSave }; + object node = null; + try + { + var task = new EffectTask { XStretchSpeed = 102, SpeedX = 0.1f, Duration = 1 }; + node = Node(root, task, context, "bink"); + Assert.That(Apply(node, task, 0.02f, 0.02f), Is.False); + Assert.That(context.Movies, Is.Empty); + Assert.That(Apply(node, task, 0.1f, 0.02f), Is.False); + Assert.That(context.Movies, Is.EqualTo(new[] { "2DEFFECT\\t102.bik" })); + Assert.That(Apply(node, task, 2, 0.02f, finished: true), Is.False); + context.Film.Finished = true; + Assert.That(Apply(node, task, 2, 0.02f), Is.True); + ((IDisposable)node).Dispose(); + node = null; + Assert.That(context.Film.Disposed, Is.True); + } + finally + { + try + { + ((IDisposable)node)?.Dispose(); + } + finally { Object.DestroyImmediate(root); } + } + } + + [Test] + [Category("LocalNativeEvidence")] + public void PublishedActionControlVectorsMatchAllNativeStoresAndBoundaries() + { + string directory = Environment.GetEnvironmentVariable("PAL3_NATIVE_VECTORS_ROOT"); + if (directory == null) + Assert.Ignore("Published native vectors are local analysis artifacts."); + JObject document = JObject.Parse(File.ReadAllText(Path.Combine(directory, "action-control-native-vectors.json"))); + int count = 0; + foreach (JProperty variant in document.Properties()) + foreach (JToken row in variant.Value["rows"]) + { + JToken config = row["config"]; + Vector3 Read(JToken token) => new((float)token[0], (float)token[1], (float)token[2]); + Vector3 speed = Read(config["speed"]), destination = Read(config["destination"]); + var task = new EffectTask + { + XStretchSpeed = 17, + SpeedX = speed.x, + SpeedY = speed.y, + SpeedZ = speed.z, + RotAxisX = destination.x, + RotAxisY = destination.y, + RotAxisZ = destination.z, + SpeedAlpha = (float)config["alpha"], + SpeedRed = 1, + SpeedGreen = -1, + SpeedBlue = (bool)config["target"] ? 1 : 0, + Duration = (float)config["duration"], + RequireLoops = 1, + CreateNew = (bool)config["front"], + ModifyLast = (bool)config["byOver"], + YStretchSpeed = 123 + }; + var context = new Context(); + context.Role.Position = Read(config["position"]); + context.Role.Blend = (float)config["blend"]; + context.Role.ActionOver = (bool)config["over"]; + object node = Node(new GameObject("native action vector"), task, context, "action", variant.Name == "PAL3A"); + try + { + float elapsed = (float)config["elapsed"]; + float delta = (float)((double)0.02f - Math.Max(0, (double)elapsed - task.Duration)); + bool finished = Apply(node, task, elapsed, delta, finished: (bool)config["ended"] || elapsed >= task.Duration); + Vector3 expected = Read(row["position"]); + Assert.That(Vector3.Distance(context.Role.Position, expected), Is.LessThanOrEqualTo(0.0002f), variant.Name + " position: " + count); + Assert.That(context.Role.FacingDegrees, Is.EqualTo((float)row["face"]).Within(0.0002f), variant.Name + " face: " + count); + Assert.That(context.Role.Blend, Is.EqualTo((float)row["blend"]).Within(0.000002f)); + Assert.That((context.Role.Left, context.Role.Right, context.Role.Controlled, finished), + Is.EqualTo(((float)row["left"], (float)row["right"], (bool)row["external"], (bool)row["finished"]))); + count++; + } + finally { ((IDisposable)node).Dispose(); } + } + Assert.That(count, Is.EqualTo(722)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleOriginalControlTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleOriginalControlTests.cs.meta new file mode 100644 index 00000000..35483cc7 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleOriginalControlTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cec942bf69b84a179e523a0cbef52f91 diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattlePreviewProjectionTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattlePreviewProjectionTests.cs new file mode 100644 index 00000000..a1012910 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattlePreviewProjectionTests.cs @@ -0,0 +1,151 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using Battle; + using NUnit.Framework; + using ResourceBrowser; + using UnityEngine; + + public sealed class BattlePreviewProjectionTests + { + [TestCase(EventType.MouseDrag, 0, EventModifiers.None)] + [TestCase(EventType.MouseDrag, 0, EventModifiers.Shift)] + [TestCase(EventType.MouseDrag, 2, EventModifiers.None)] + [TestCase(EventType.ScrollWheel, 0, EventModifiers.None)] + [TestCase(EventType.KeyDown, 0, EventModifiers.None)] + public void LockedCameraIgnoresInspectionGesturesWhilePreviewCameraStillResponds(EventType type, int button, EventModifiers modifiers) + { + using var preview = new ResourceModelPreview(null, false); + preview.SetHorizontalCameraOrientation(Vector3.back * 10, Vector3.forward, Vector3.up, 50); + var viewport = new Rect(0, 0, 800, 600); + var marker = new Vector3(2, 1, 10); + Vector2 before = preview.ProjectReference(marker, 800, 600); + var input = new Event + { + type = type, + button = button, + modifiers = modifiers, + keyCode = KeyCode.F, + mousePosition = viewport.center, + delta = new Vector2(36, 24) + }; + var handle = typeof(ResourceModelPreview).GetMethod("HandleCameraInput", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + handle.Invoke(preview, new object[] { input, viewport, false }); + Assert.That(Vector2.Distance(preview.ProjectReference(marker, 800, 600), before), Is.LessThan(.0001)); + Assert.That(input.type, Is.EqualTo(type), "Locked camera must leave HUD input available."); + handle.Invoke(preview, new object[] { input, viewport, true }); + Assert.That(Vector2.Distance(preview.ProjectReference(marker, 800, 600), before), Is.GreaterThan(1)); + Assert.That(input.type, Is.EqualTo(EventType.Used)); + } + + [TestCase(800, 600)] + [TestCase(1600, 900)] + public void NativeHorizontalFrustumProjectsTheSameHorizontalEdge(int width, int height) + { + using var preview = new ResourceModelPreview(null, false); + preview.SetHorizontalCameraOrientation(Vector3.zero, Vector3.forward, Vector3.up, 50); + // gbCamera: hw = near*tan(fov/2); hh = hw*height/width. + const float depth = 10; + float halfWidth = depth * 0.466307658f; + Vector2 right = preview.ProjectReference(new Vector3(halfWidth, 0, depth), width, height); + Vector2 top = preview.ProjectReference(new Vector3(0, halfWidth * height / width, depth), width, height); + Assert.That(right.x, Is.EqualTo(width).Within(.002)); + Assert.That(right.y, Is.EqualTo(height / 2f).Within(.002)); + Assert.That(top.y, Is.Zero.Within(.002)); + Assert.That(preview.HorizontalFieldOfView, Is.EqualTo(50)); + } + + [TestCase(800, 600, false)] + [TestCase(1600, 900, false)] + [TestCase(800, 800, false)] + [TestCase(600, 900, false)] + [TestCase(1600, 900, true)] + public void TrailPixelsProjectionAndPickingShareThePresentedFrustum(int width, int height, bool expand) + { + using var preview = new ResourceModelPreview(null, false) { ExpandReferenceFraming = expand }; + using var trail = new BattleTrailPreview { Enabled = true }; + preview.FrameEffect = trail; + preview.SetHorizontalCameraOrientation(Vector3.zero, Vector3.forward, Vector3.up, 50); + var view = new Rect(17, 29, width, height); + var world = new Vector3(1, 1, 10); + preview.SetViewportContext(view); + preview.Project(world, view, out Vector2 before); + var target = preview.CreateObject("Projection marker"); + target.transform.position = world; + var mesh = new Mesh { hideFlags = HideFlags.HideAndDontSave }; + mesh.vertices = new[] { new Vector3(-.25f, -.25f, 0), new Vector3(-.25f, .25f, 0), new Vector3(.25f, .25f, 0), new Vector3(.25f, -.25f, 0) }; + mesh.triangles = new[] { 0, 1, 2, 0, 2, 3 }; + target.AddComponent().sharedMesh = mesh; + var material = new Material(Shader.Find("Universal Render Pipeline/Unlit")) { hideFlags = HideFlags.HideAndDontSave }; + material.SetColor("_BaseColor", Color.red); + target.AddComponent().sharedMaterial = material; + preview.Rendering += camera => camera.backgroundColor = Color.black; + var image = new Texture2D(width, height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = preview.Render(width, height); + image.ReadPixels(new Rect(0, 0, width, height), 0, 0); + image.Apply(); + string output = System.Environment.GetEnvironmentVariable("PAL3_PROJECTION_QA_ROOT"); + if (output != null) + { + System.IO.Directory.CreateDirectory(output); + System.IO.File.WriteAllBytes(System.IO.Path.Combine(output, $"trail-{width}-{height}-{expand}.png"), image.EncodeToPNG()); + } + preview.Project(world, view, out Vector2 after); + Assert.That(Vector2.Distance(before, after), Is.LessThan(.002), "Rendering must not change the input/overlay camera."); + Ray ray = preview.ScreenRay(after, view); + Assert.That(Vector3.Distance(ray.GetPoint((world.z - ray.origin.z) / ray.direction.z), world), Is.LessThan(.0001)); + var pixels = image.GetPixels32(); + double x = 0, y = 0, weight = 0; + for (int index = 0; index < pixels.Length; index++) + { + int red = pixels[index].r - System.Math.Max(pixels[index].g, pixels[index].b); + if (red <= 4) + continue; + weight += red; + x += (index % width + .5) * red; + y += (height - index / width - .5) * red; + } + Assert.That(weight, Is.GreaterThan(100)); + var visible = new Vector2(view.x + (float)(x / weight), view.y + (float)(y / weight)); + Assert.That(Vector2.Distance(visible, after), Is.LessThan(width / 256f * 1.5f), "The rendered marker must agree with HUD projection and picking."); + TestContext.WriteLine($"{width}x{height}, expand={expand}: projected={after}, visible={visible}"); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + + [Test] + public void AuthoringCameraRetainsItsVerticalAngleAndUpdatesBeforeRepaint() + { + using var preview = new ResourceModelPreview(null, false); + preview.SetHorizontalCameraOrientation(Vector3.zero, Vector3.forward, Vector3.up, 50); + preview.ProjectReference(Vector3.forward, 800, 600); + preview.SetCamera(new Vector3(10, 0, 0), new Vector3(10, 0, 5), 60); + Vector2 center = preview.ProjectReference(new Vector3(10, 0, 10), 800, 600); + Assert.That(Vector2.Distance(center, new Vector2(400, 300)), Is.LessThan(.0001)); + preview.GetCamera(out Vector3 position, out _, out float fieldOfView); + Assert.That(Vector3.Distance(position, new Vector3(10, 0, 0)), Is.LessThan(.00001)); + Assert.That(fieldOfView, Is.EqualTo(60)); + } + + [Test] + public void ThrownWeaponUsesTheMirroredNativeRotationStack() + { + // Source rows: Rz(90)*Rx(90)*Ry(90), followed by X reflection. + Quaternion rotation = BattlePreview.ThrownWeaponRotation(new BattleMovementPoint(90, 90, 90)); + Assert.That(Vector3.Distance(rotation * Vector3.left, Vector3.left), Is.LessThan(.00001)); + Assert.That(Vector3.Distance(rotation * Vector3.up, Vector3.forward), Is.LessThan(.00001)); + Assert.That(Vector3.Distance(rotation * Vector3.forward, Vector3.down), Is.LessThan(.00001)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattlePreviewProjectionTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattlePreviewProjectionTests.cs.meta new file mode 100644 index 00000000..b1f771c8 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattlePreviewProjectionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 010e7da92ee749da8203b551c894edd2 diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioCodecTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioCodecTests.cs new file mode 100644 index 00000000..ddc39ef8 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioCodecTests.cs @@ -0,0 +1,170 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using System.Reflection; + using Battle; + using Newtonsoft.Json; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed class BattleScenarioCodecTests + { + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void LegacyUnityDraftRecoversAbsentSwordSnapshotsWithoutChangingOtherInputs(string variant) + { + BattleScenario scenario = BattleScenarioTests.Scenario(); + scenario.Variant = variant; + string legacy = JsonUtility.ToJson(scenario); + BattleScenario unmodified = BattleScenarioJson.Deserialize(legacy); + Assert.That(unmodified.Participants[1].MagicSword, Is.Not.Null, "Exercise the actual old Unity codec defect."); + BattleScenario restored = BattleScenarioJson.RestoreDraft(legacy); + Assert.That(restored.Participants.All(actor => actor.MagicSword == null), Is.True); + Assert.That(restored.Participants[0].Attributes, Is.EqualTo(scenario.Participants[0].Attributes)); + Assert.That(restored.Participants[0].Vitals, Is.EqualTo(scenario.Participants[0].Vitals)); + Assert.That(restored.Validate(), Is.Empty); + } + + [Test] + public void LegacyEquippedSwordRetainsItsRealCultivationAndEnergy() + { + BattleScenario scenario = BattleScenarioTests.Scenario(); + scenario.Participants[0].Equipment[0] = 6603; + scenario.Participants[0].MagicSword = new BattleMagicSword { AttackBonus = 77, Energy = 132.5f }; + BattleScenario restored = BattleScenarioJson.RestoreDraft(JsonUtility.ToJson(scenario)); + Assert.That(restored.Participants[0].MagicSword.AttackBonus, Is.EqualTo(77)); + Assert.That(restored.Participants[0].MagicSword.Energy, Is.EqualTo(132.5f)); + Assert.That(restored.Participants[1].MagicSword, Is.Null); + Assert.That(restored.Validate(), Is.Empty); + } + + [TestCase(false)] + [TestCase(true)] + public void CanonicalDraftKeepsExplicitInvalidInputForValidation(bool beforeMarker) + { + BattleScenario scenario = BattleScenarioTests.Scenario(); + scenario.Participants[1].MagicSword = new BattleMagicSword { AttackBonus = 777 }; + string json = beforeMarker ? JsonConvert.SerializeObject(scenario) : BattleScenarioJson.Serialize(scenario); + BattleScenario restored = BattleScenarioJson.RestoreDraft(json); + Assert.That(restored.Participants[1].MagicSword.AttackBonus, Is.EqualTo(777)); + Assert.That(restored.Validate().Any(error => error.Contains("magic sword snapshot requires")), Is.True); + } + + [Test] + public void OldWindowJsonIsMigratedByTheActualOnEnablePath() + { + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; + var window = ScriptableObject.CreateInstance(); + MethodInfo disable = typeof(BattleEditorWindow).GetMethod("OnDisable", flags); + try + { + disable.Invoke(window, null); + string legacy = JsonUtility.ToJson(BattleScenarioTests.Scenario()); + typeof(BattleEditorWindow).GetField("_draftJson", flags).SetValue(window, legacy); + typeof(BattleEditorWindow).GetField("_savedJson", flags).SetValue(window, legacy); + typeof(BattleEditorWindow).GetMethod("OnEnable", flags).Invoke(window, null); + var draft = (BattleScenarioAsset)typeof(BattleEditorWindow).GetField("_draft", flags).GetValue(window); + Assert.That(draft.Scenario.Participants.All(actor => actor.MagicSword == null), Is.True); + Assert.That(draft.Scenario.Validate(), Is.Empty); + disable.Invoke(window, null); + Assert.That((string)typeof(BattleEditorWindow).GetField("_draftJson", flags).GetValue(window), Does.Contain("$battleScenarioFormat")); + } + finally + { + window.DiscardChanges(); + Object.DestroyImmediate(window); + } + } + + [Test] + public void AnUnsetAuthoringAssetDoesNotThrowDuringUndoSerialization() + { + var asset = ScriptableObject.CreateInstance(); + try + { + Assert.That(asset.Scenario.Variant, Is.EqualTo(BattleData.Variant)); + asset.Scenario = null; + Assert.DoesNotThrow(asset.OnBeforeSerialize); + asset.OnAfterDeserialize(); + Assert.That(asset.Scenario.Variant, Is.EqualTo(BattleData.Variant)); + Assert.That(BattleScenarioEditing.NeedsRepair(asset.Scenario), Is.False); + } + finally + { + Object.DestroyImmediate(asset); + } + } + + [Test] + public void UnsupportedAuthoredStatusIsDiagnosedBeforeStartingBattle() + { + var scenario = new BattleScenario { Scene = "fixture" }; + var actor = new BattleParticipant { ActorId = 101, InstanceId = "ally" }; + scenario.Participants.Add(actor); + actor.Statuses.Add(new BattleStatus { Id = (int)BattleState.ExpIncrease, Rounds = 1 }); + Assert.That(scenario.Validate(), Has.Some.Contains("not supported as an initial status")); + } + + [Test] + public void MissingAuthoringContainersHaveAnExplicitLosslessRepair() + { + var actor = new BattleParticipant + { + ActorId = 101, + Attributes = new[] { 77, 8 }, + Vitals = null, + Equipment = new[] { 123 }, + Skills = null, + Statuses = new() { null, new BattleStatus { Id = 2 } } + }; + var scenario = new BattleScenario + { + Camera = null, + Pal3A = null, + Items = null, + TreasureUses = new() { null, new BattleItem { Id = 9, Count = 2 } }, + Participants = new() { actor, null } + }; + Assert.That(BattleScenarioEditing.NeedsRepair(scenario), Is.True); + BattleScenario roundTrip = BattleScenarioJson.Deserialize(BattleScenarioJson.Serialize(scenario)); + Assert.That(roundTrip.Items, Is.Null, "Serialization must not silently repair invalid authoring input."); + BattleScenario repaired = BattleScenarioEditing.Repair(roundTrip); + Assert.That(BattleScenarioEditing.NeedsRepair(repaired), Is.False); + Assert.That(repaired.Participants, Has.Count.EqualTo(1)); + Assert.That(repaired.Participants[0].Attributes.Take(2), Is.EqualTo(new[] { 77, 8 })); + Assert.That(repaired.Participants[0].Equipment[0], Is.EqualTo(123)); + repaired.Participants[0].Skills.Add(new BattleSkill { Id = 301 }); + repaired.Participants[0].Statuses.Add(new BattleStatus { Id = 3 }); + repaired.Items.Add(new BattleItem { Id = 10 }); + Assert.That(repaired.TreasureUses.Single().Count, Is.EqualTo(2)); + Assert.That(scenario.Participants, Has.Count.EqualTo(2), "Repairing a deserialized draft must not mutate the source."); + string stable = BattleScenarioJson.Serialize(repaired); + Assert.That(BattleScenarioJson.Serialize(BattleScenarioEditing.Repair(repaired)), Is.EqualTo(stable)); + } + + [TestCase(typeof(byte), -1, 0L)] + [TestCase(typeof(byte), 300, 255L)] + [TestCase(typeof(sbyte), -17, -17L)] + [TestCase(typeof(short), -17, -17L)] + [TestCase(typeof(ushort), -1, 0L)] + [TestCase(typeof(uint), -1, 0L)] + [TestCase(typeof(uint), long.MaxValue, 4294967295L)] + [TestCase(typeof(int), -17, -17L)] + [TestCase(typeof(int), long.MaxValue, 2147483647L)] + [TestCase(typeof(long), -17, -17L)] + public void TypedIntegerEditsRetainTheirClrType(Type type, long input, long expected) + { + MethodInfo convert = typeof(BattleScenarioTypedFields).GetMethod("IntegerValue", BindingFlags.Static | BindingFlags.NonPublic); + object value = convert.Invoke(null, new object[] { type, input }); + Assert.That(value.GetType(), Is.EqualTo(type), "Reflection assignment must receive the exact field type."); + Assert.That(Convert.ToInt64(value), Is.EqualTo(expected)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioCodecTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioCodecTests.cs.meta new file mode 100644 index 00000000..1f2d24c0 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioCodecTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4befb1e05f3e40eab23551aac24cf476 diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioTests.cs new file mode 100644 index 00000000..0a832248 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioTests.cs @@ -0,0 +1,358 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Linq; + using System.Reflection; + using Battle; + using Engine.Core.Abstraction; + using Engine.Core.Implementation; + using NUnit.Framework; + using UnityEditor; + using UnityEditor.TestTools; + using UnityEngine; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + public sealed class BattleScenarioTests + { + private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic; + private const string ReloadWindow = "BattleScenarioReloadTest"; + + private const string ReloadEnvironment = ReloadWindow + ".Environment"; + + private static void IsolateReloadSource() + { + string preference = BattleData.Variant + ".BattleEditor.Path"; + SessionState.SetBool(ReloadEnvironment + ".HadPath", EditorPrefs.HasKey(preference)); + SessionState.SetString(ReloadEnvironment + ".Path", EditorPrefs.GetString(preference)); + SessionState.SetBool(ReloadEnvironment, true); + EditorPrefs.SetString(preference, System.IO.Path.GetFullPath(System.IO.Path.Combine(Application.dataPath, + "../../workspace/ResourceBrowserQA/battle-missing-source", Guid.NewGuid().ToString("N")))); + } + + [TearDown] + public void CleanupReloadState() + { + string draftId = SessionState.GetString(ReloadWindow + ".DraftId", ""); + try + { + foreach (BattleEditorWindow window in Resources.FindObjectsOfTypeAll().Where(value => value.name == ReloadWindow)) + { + window.DiscardChanges(); + Object.DestroyImmediate(window); + } + } + finally + { + try + { + foreach (BattleScenarioAsset draft in Resources.FindObjectsOfTypeAll().Where(value => value.GetEntityId().ToString() == draftId)) + { + Undo.ClearUndo(draft); + Object.DestroyImmediate(draft); + } + } + finally + { + try + { + if (SessionState.GetBool(ReloadEnvironment, false)) + { + string preference = BattleData.Variant + ".BattleEditor.Path"; + if (SessionState.GetBool(ReloadEnvironment + ".HadPath", false)) + EditorPrefs.SetString(preference, SessionState.GetString(ReloadEnvironment + ".Path", "")); + else + EditorPrefs.DeleteKey(preference); + } + } + finally + { + SessionState.EraseBool(ReloadWindow); + SessionState.EraseString(ReloadWindow + ".WindowId"); + SessionState.EraseString(ReloadWindow + ".DraftId"); + SessionState.EraseBool(ReloadEnvironment); + SessionState.EraseBool(ReloadEnvironment + ".HadPath"); + SessionState.EraseString(ReloadEnvironment + ".Path"); + } + } + } + } + + private sealed class FailingTextureSource : ITextureDataSource + { + public int Width => 4; + + public int Height => 4; + + public int MipCount => 1; + + public TextureDataFormat Format => TextureDataFormat.Rgba32; + + public bool HasTransparency => false; + + public ArraySegment GetMipData(int mip) => throw new System.IO.IOException("Injected texture read failure"); + + public void CopyMipToRgba32(int mip, byte[] destination) => throw new NotSupportedException(); + + public ITexturePixelReader CreatePixelReader() => throw new NotSupportedException(); + + public void Dispose() + { + } + } + + [Test] + public void TextureReadFailureReleasesNativeTextureImmediately() + { + int before = Resources.FindObjectsOfTypeAll().Length; + using var source = new FailingTextureSource(); + Assert.Throws(() => new UnityTextureFactory().CreateTexture(source, TextureCreateOptions.Readable)); + Assert.That(Resources.FindObjectsOfTypeAll().Length, Is.EqualTo(before)); + } + + internal static BattleScenario Scenario() + { + return new BattleScenario + { + Scene = "synthetic", + Participants = + { + new BattleParticipant { ActorId = 101, Side = BattleSide.Ally, Attributes = new[] { 100, 50, 60, 20, 10, 5, 2, 0, 0, 0, 0, 0 }, Vitals = new[] { 80, 40, 30 } }, + new BattleParticipant { ActorId = 701, Side = BattleSide.Enemy }, + }, + Items = { new BattleItem { Id = 8001, Count = 2 } }, + }; + } + + [Test] + public void CapturingAndRestartingDoNotShareWritableState() + { + BattleScenario draft = Scenario(); + draft.Participants[0].Skills.Add(new BattleSkill { Id = 2001, Level = 2 }); + draft.Participants[0].Statuses.Add(new BattleStatus { Id = 0, Rounds = 3 }); + var setup = new BattleSetup(draft); + draft.Participants[0].Attributes[0] = 999; + draft.Items[0].Count = 999; + BattleScenario first = setup.CreateInstance(); + first.Participants[0].Attributes[0] = 1; + first.Participants[0].Vitals[0] = 1; + first.Participants[0].Equipment[0] = 42; + first.Participants[0].Skills[0].Level = 9; + first.Participants[0].Statuses[0].Rounds = 1; + first.Items[0].Count = 1; + first.Camera.FieldOfView = 90; + BattleScenario second = setup.CreateInstance(); + Assert.That(second.Participants[0].Attributes[0], Is.EqualTo(100)); + Assert.That(second.Participants[0].Vitals[0], Is.EqualTo(80)); + Assert.That(second.Participants[0].Equipment[0], Is.Zero); + Assert.That(second.Participants[0].Skills[0].Level, Is.EqualTo(2)); + Assert.That(second.Participants[0].Statuses[0].Rounds, Is.EqualTo(3)); + Assert.That(second.Items[0].Count, Is.EqualTo(2)); + Assert.That(second.Camera.FieldOfView, Is.EqualTo(39)); + } + + [Test] + public void SameSpeciesNeedsDifferentInstanceIdsAndSlots() + { + BattleScenario scenario = Scenario(); + BattleParticipant enemy = scenario.Participants[1].Copy(); + scenario.Participants.Add(enemy); + Assert.That(scenario.Validate().Any(error => error.Contains("instance ID")), Is.True); + Assert.That(scenario.Validate().Any(error => error.Contains("occupies")), Is.True); + enemy.InstanceId = Guid.NewGuid().ToString("N"); + enemy.Slot = BattleSlot.Fire; + Assert.That(scenario.Validate(), Is.Empty); + enemy.Attributes[0] = 100; + Assert.That(scenario.Participants[1].Attributes[0], Is.Zero); + } + + [Test] + public void InvalidInitialValuesAreRejectedBeforeStarting() + { + BattleScenario scenario = Scenario(); + scenario.Version++; + scenario.Participants[0].Vitals[0] = 101; + scenario.Participants[1].Position.X = float.NaN; + scenario.Camera.FieldOfView = float.PositiveInfinity; + scenario.Items.Add(new BattleItem { Id = 8001, Count = 3 }); + Assert.That(scenario.Validate().Count, Is.GreaterThanOrEqualTo(5)); + Assert.Throws(() => new BattleSetup(scenario)); + scenario.Participants = null; + Assert.That(scenario.Validate(), Is.Not.Empty); + } + + [Test] + public void CoincidentCameraOverrideIsRejected() + { + BattleScenario scenario = Scenario(); + scenario.Camera.Override = true; + Assert.That(scenario.Validate().Any(error => error.Contains("must differ")), Is.True); + } + + [Test] + public void LoadingFutureSchemaKeepsDraftAndSavingCannotOverwriteIt() + { + var window = ScriptableObject.CreateInstance(); + var future = ScriptableObject.CreateInstance(); + try + { + var draft = (BattleScenarioAsset)typeof(BattleEditorWindow).GetField("_draft", Private).GetValue(window); + string before = JsonUtility.ToJson(draft.Scenario); + future.Scenario.Version = BattleScenario.CurrentVersion + 1; + future.Scenario.Variant = BattleData.Variant; + var error = Assert.Throws(() => typeof(BattleEditorWindow).GetMethod("LoadAsset", Private).Invoke(window, new object[] { future })); + Assert.That(error.InnerException, Is.TypeOf()); + Assert.That(JsonUtility.ToJson(draft.Scenario), Is.EqualTo(before)); + draft.Scenario.Version++; + error = Assert.Throws(() => typeof(BattleEditorWindow).GetMethod("SaveScenario", Private).Invoke(window, new object[] { false })); + Assert.That(error.InnerException, Is.TypeOf()); + } + finally + { + window.DiscardChanges(); + Object.DestroyImmediate(window); + Object.DestroyImmediate(future); + } + } + + [Test] + public void UndoAfterSaveMarksDraftDirtyWithoutUndoingSavedAsset() + { + string path = "Assets/__BattleSaveTest_" + Guid.NewGuid().ToString("N") + ".asset"; + var asset = ScriptableObject.CreateInstance(); + asset.Scenario.Variant = BattleData.Variant; + AssetDatabase.CreateAsset(asset, path); + var window = ScriptableObject.CreateInstance(); + try + { + typeof(BattleEditorWindow).GetMethod("LoadAsset", Private).Invoke(window, new object[] { asset }); + var draft = (BattleScenarioAsset)typeof(BattleEditorWindow).GetField("_draft", Private).GetValue(window); + Undo.RecordObject(draft, "Change local money"); + draft.Scenario.Money = 321; + Undo.FlushUndoRecordObjects(); + window.SaveChanges(); + Assert.That(asset.Scenario.Money, Is.EqualTo(321)); + Assert.That(window.hasUnsavedChanges, Is.False); + Undo.PerformUndo(); + Assert.That(asset.Scenario.Money, Is.EqualTo(321)); + Assert.That(draft.Scenario.Money, Is.Zero); + Assert.That(window.hasUnsavedChanges, Is.True); + } + finally + { + window.DiscardChanges(); + Object.DestroyImmediate(window); + AssetDatabase.DeleteAsset(path); + } + } + + [Test] + public void PresetRoundTripPreservesNestedInputsAndDoesNotAliasDraft() + { + string path = "Assets/__BattleScenarioTest_" + Guid.NewGuid().ToString("N") + ".asset"; + var asset = ScriptableObject.CreateInstance(); + try + { + BattleScenario draft = Scenario(); + draft.Participants[0].Skills.Add(new BattleSkill { Id = 2, Level = 3, Uses = 8, Mastered = true }); + draft.Participants[0].Statuses.Add(new BattleStatus { Id = 3, Rounds = 4 }); + asset.Scenario = draft.Copy(); + AssetDatabase.CreateAsset(asset, path); + AssetDatabase.SaveAssets(); + AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); + var loaded = AssetDatabase.LoadAssetAtPath(path); + Assert.That(JsonUtility.ToJson(loaded.Scenario), Is.EqualTo(JsonUtility.ToJson(draft))); + Assert.That(loaded.Scenario.Participants.All(actor => actor.MagicSword == null), Is.True); + draft.Participants[0].Skills[0].Uses = 99; + Assert.That(loaded.Scenario.Participants[0].Skills[0].Uses, Is.EqualTo(8)); + } + finally + { + AssetDatabase.DeleteAsset(path); + if (asset != null) + Object.DestroyImmediate(asset); + } + } + + [Test] + public void OptionalSwordSnapshotsSurviveJsonAndActualAssetReload() + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].Equipment[0] = BattleMagicSwordRules.WeaponId; + scenario.Participants[0].MagicSword = new BattleMagicSword { AttackBonus = 77, Energy = 132.5f }; + BattleScenario copy = BattleScenarioJson.Deserialize(BattleScenarioJson.Serialize(scenario)); + Assert.That(copy.Participants[1].MagicSword, Is.Null); + Assert.That(copy.Participants[0].MagicSword.AttackBonus, Is.EqualTo(77)); + Assert.That(copy.Participants[0].MagicSword.Energy, Is.EqualTo(132.5f)); + string path = "Assets/__BattleScenarioTest_" + Guid.NewGuid().ToString("N") + ".asset"; + var asset = ScriptableObject.CreateInstance(); + try + { + asset.Scenario = scenario; + AssetDatabase.CreateAsset(asset, path); + AssetDatabase.SaveAssets(); + Resources.UnloadAsset(asset); + asset = AssetDatabase.LoadAssetAtPath(path); + Assert.That(asset.Scenario.Participants[1].MagicSword, Is.Null); + Assert.That(asset.Scenario.Participants[0].MagicSword.AttackBonus, Is.EqualTo(77)); + Assert.That(asset.Scenario.Participants[0].MagicSword.Energy, Is.EqualTo(132.5f)); + Undo.RecordObject(asset, "Remove sword snapshot"); + asset.Scenario.Participants[0].MagicSword = null; + Undo.FlushUndoRecordObjects(); + Undo.PerformUndo(); + Assert.That(asset.Scenario.Participants[0].MagicSword.Energy, Is.EqualTo(132.5f)); + Undo.PerformRedo(); + Assert.That(asset.Scenario.Participants[0].MagicSword, Is.Null); + } + finally + { + Undo.ClearUndo(asset); + AssetDatabase.DeleteAsset(path); + } + } + + [UnityTest] + public IEnumerator UndoAndRealAssemblyReloadPreserveUnsavedDraft() + { + if (!SessionState.GetBool(ReloadWindow, false)) + { + IsolateReloadSource(); + var window = ScriptableObject.CreateInstance(); + window.name = ReloadWindow; + var draft = (BattleScenarioAsset)typeof(BattleEditorWindow).GetField("_draft", Private).GetValue(window); + Undo.RecordObject(draft, "Test battle draft"); + draft.Scenario.Money = 123; + Undo.FlushUndoRecordObjects(); + Undo.PerformUndo(); + Assert.That(draft.Scenario.Money, Is.Zero); + Undo.PerformRedo(); + Assert.That(draft.Scenario.Money, Is.EqualTo(123)); + SessionState.SetString(ReloadWindow + ".WindowId", window.GetEntityId().ToString()); + SessionState.SetString(ReloadWindow + ".DraftId", draft.GetEntityId().ToString()); + SessionState.SetBool(ReloadWindow, true); + EditorUtility.RequestScriptReload(); + } + yield return new WaitForDomainReload(); + var restored = Resources.FindObjectsOfTypeAll().Single(window => window.name == ReloadWindow); + var restoredDraft = (BattleScenarioAsset)typeof(BattleEditorWindow).GetField("_draft", Private).GetValue(restored); + Assert.That(restored.GetEntityId().ToString(), Is.EqualTo(SessionState.GetString(ReloadWindow + ".WindowId", ""))); + Assert.That(restoredDraft.GetEntityId().ToString(), Is.EqualTo(SessionState.GetString(ReloadWindow + ".DraftId", ""))); + Assert.That(typeof(EditorWindow).GetField("m_Parent", Private).GetValue(restored), Is.Null); + var session = (BattleEditorSession)typeof(BattleEditorWindow).GetField("_session", Private).GetValue(restored); + Assert.That(session.Data, Is.Null, "Draft persistence must not load user game data."); + Assert.That(restoredDraft.Scenario.Money, Is.EqualTo(123)); + Assert.That(restored.hasUnsavedChanges, Is.True); + restored.DiscardChanges(); + Assert.That(restored.hasUnsavedChanges, Is.False); + Object.DestroyImmediate(restored); + Assert.That(restored == null, Is.True); + Assert.That(restoredDraft == null, Is.True); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioTests.cs.meta new file mode 100644 index 00000000..32ca9d54 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleScenarioTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 78d7637d15dde4ba78e4d220f2aee3a9 \ No newline at end of file diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleTestInventoryLifecycleTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleTestInventoryLifecycleTests.cs new file mode 100644 index 00000000..2ffdc5c2 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleTestInventoryLifecycleTests.cs @@ -0,0 +1,186 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Threading.Tasks; + using Battle; + using NUnit.Framework; + using UnityEditor; + using UnityEngine; + + // Exercise authoring lifecycle without creating or showing a native window. + [Category("LocalGameData")] + public sealed class BattleTestInventoryLifecycleTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.NonPublic; + private BattleEditorWindow _window; + private bool _hadPath; + private string _path; + + private string Preference => BattleData.Variant + ".BattleEditor.Path"; + private BattleScenario Draft => Get("_draft").Scenario; + + private T Get(string field) => (T)typeof(BattleEditorWindow).GetField(field, Members).GetValue(_window); + + private void Set(string field, object value) => typeof(BattleEditorWindow).GetField(field, Members).SetValue(_window, value); + + private void Call(string method, params object[] arguments) => typeof(BattleEditorWindow).GetMethod(method, Members).Invoke(_window, arguments); + + [SetUp] + public void SetUp() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original game data is required."); + _hadPath = EditorPrefs.HasKey(Preference); + _path = EditorPrefs.GetString(Preference); + EditorPrefs.SetString(Preference, Path.Combine(Application.temporaryCachePath, "missing-inventory-" + Guid.NewGuid().ToString("N"))); + _window = ScriptableObject.CreateInstance(); + Set("_root", root); + } + + [TearDown] + public void TearDown() + { + if (_window != null) + UnityEngine.Object.DestroyImmediate(_window); + if (_hadPath) + EditorPrefs.SetString(Preference, _path); + else + EditorPrefs.DeleteKey(Preference); + } + + [Test] + public void FirstConnectionInitializesCleanTestDefaultsButReconnectionPreservesExplicitEmptyInventory() + { + Call("LoadData"); + Assert.That(Draft.Items.Count, Is.GreaterThan(50)); + Assert.That(Draft.DataFingerprint, Is.EqualTo(Get("_session").Data.Fingerprint)); + Assert.That(_window.hasUnsavedChanges, Is.False); + Assert.That(Draft.TreasureUses.Select(item => item.Id), Is.EqualTo(Enumerable.Range(6119, BattleData.Variant == "PAL3" ? 7 : 6))); + Assert.That(Draft.TreasureUses.Select(item => item.Count), Is.All.EqualTo(3)); + Draft.Items.Clear(); + Draft.TreasureUses.Clear(); + Call("UpdateDirty"); + Call("LoadData"); + Assert.That(Draft.Items, Is.Empty); + Assert.That(Draft.TreasureUses, Is.Empty); + Assert.That(_window.hasUnsavedChanges, Is.True); + } + + [TestCase(true)] + [TestCase(false)] + public void SavedTreasureUseEditsSurvivePresetReplacementAndDataReload(bool clearCounters) + { + Call("LoadData"); + string path = "Assets/__BattleTreasure_" + Guid.NewGuid().ToString("N") + ".asset"; + var asset = ScriptableObject.CreateInstance(); + try + { + asset.Scenario = Draft.Copy(); + AssetDatabase.CreateAsset(asset, path); + Call("LoadAsset", asset); + Call("Edit", "Edit treasure uses", (Action)(() => + { + if (clearCounters) + Draft.TreasureUses.Clear(); + else + Draft.TreasureUses.First(item => item.Id == 6119).Count = 0; + })); + Assert.That(_window.hasUnsavedChanges, Is.True); + Call("SaveScenario", false); + Assert.That(_window.hasUnsavedChanges, Is.False); + + Call("NewScenario"); + Assert.That(Draft.TreasureUses.First(item => item.Id == 6119).Count, Is.EqualTo(3)); + AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); + Call("LoadAsset", AssetDatabase.LoadAssetAtPath(path)); + Call("LoadData"); + if (clearCounters) + Assert.That(Draft.TreasureUses, Is.Empty); + else + Assert.That(Draft.TreasureUses.First(item => item.Id == 6119).Count, Is.Zero); + Assert.That(Draft.Items.First(item => item.Id == 6119).Count, Is.EqualTo(99)); + } + finally + { + AssetDatabase.DeleteAsset(path); + } + } + + [Test] + public void SavingBeforeFirstConnectionPreservesTheSavedInventory() + { + string path = "Assets/__BattleEarlySave_" + Guid.NewGuid().ToString("N") + ".asset"; + try + { + Draft.Money = 50; + Call("UpdateDirty"); + Call("SaveDrafts", (Func)(_ => path)); + BattleScenarioAsset asset = AssetDatabase.LoadAssetAtPath(path); + Assert.That(asset.Scenario.Items, Is.Empty); + Call("LoadData"); + Assert.That(Draft.Items, Is.Empty); + Assert.That(Draft.DataFingerprint, Is.EqualTo(asset.Scenario.DataFingerprint)); + Assert.That(_window.hasUnsavedChanges, Is.False); + } + finally + { + AssetDatabase.DeleteAsset(path); + } + } + + [Test] + public void UndoOfAnEditBeforeConnectionPreservesGeneratedDefaults() + { + Call("Edit", "Edit initial money", (Action)(() => Draft.Money = 50)); + Undo.FlushUndoRecordObjects(); + Call("LoadData"); + string fingerprint = Draft.DataFingerprint; + int items = Draft.Items.Count; + Assert.That(items, Is.GreaterThan(50)); + Assert.That(_window.hasUnsavedChanges, Is.True); + + Undo.PerformUndo(); + Assert.That(Draft.Money, Is.Zero); + Assert.That(Draft.Items.Count, Is.EqualTo(items)); + Assert.That(Draft.DataFingerprint, Is.EqualTo(fingerprint)); + Assert.That(_window.hasUnsavedChanges, Is.False); + + Undo.PerformRedo(); + Assert.That(Draft.Money, Is.EqualTo(50)); + Assert.That(Draft.Items.Count, Is.EqualTo(items)); + Assert.That(_window.hasUnsavedChanges, Is.True); + } + + [Test] + public void RestoredEmptyDraftStaysEmptyAndExplicitNewDraftGetsTestDefaults() + { + Call("LoadData"); + Draft.Items.Clear(); + Call("UpdateDirty"); + Call("OnDisable"); + UnityEngine.Object.DestroyImmediate(Get("_draft")); + Set("_draft", null); + Call("OnEnable"); + Assert.That(Get>("_reconnect").Wait(TimeSpan.FromSeconds(15)), Is.True); + Call("CompleteReconnect"); + Assert.That(Draft.Items, Is.Empty, "Reconnect must preserve an intentionally empty inventory."); + Set("_savedJson", BattleScenarioJson.Serialize(Draft)); + Call("UpdateDirty"); + Call("NewScenario"); + Assert.That(Draft.Items.Count, Is.GreaterThan(50)); + Assert.That(_window.hasUnsavedChanges, Is.False, "An untouched new draft must use its own defaults as the saved baseline."); + Draft.Money++; + Call("UpdateDirty"); + Assert.That(_window.hasUnsavedChanges, Is.True, "Editing the new draft still requires saving."); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleTestInventoryLifecycleTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleTestInventoryLifecycleTests.cs.meta new file mode 100644 index 00000000..b5edc1e3 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleTestInventoryLifecycleTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 57131367ce2d4f2c8370fe0e3ec472e4 diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleTrailTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleTrailTests.cs new file mode 100644 index 00000000..e9c59675 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleTrailTests.cs @@ -0,0 +1,119 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System.Linq; + using Battle; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed class BattleTrailTests + { + [Test] + public void OriginalTrailUsesEightAgeOrderedAdditiveFrames() + { + var state = new BattleTrailState(); + Assert.That(Enumerable.Range(0, 8).Select(state.TextureAt), Is.EqualTo(new[] { 1, 2, 3, 4, 5, 6, 7, 0 })); + Assert.That(Enumerable.Range(0, 8).Select(BattleTrailState.AlphaAt), Is.EqualTo(new byte[] { 102, 110, 118, 126, 134, 142, 150, 158 })); + state.Advance(.01); + Assert.That(state.Frame, Is.Zero); + state.Advance(.01); + Assert.That(state.Frame, Is.EqualTo(1)); + state.Advance(0); + Assert.That(state.Frame, Is.EqualTo(1)); + // Native CTrail::Update uses one if, so it does not catch up in a loop. + state.Advance(.1); + Assert.That(state.Frame, Is.EqualTo(2)); + } + + private static Color Pixel(RenderTexture texture) + { + RenderTexture previous = RenderTexture.active; + var readback = new Texture2D(1, 1, TextureFormat.RGBA32, false); + try + { + RenderTexture.active = texture; + readback.ReadPixels(new Rect(texture.width / 2, texture.height / 2, 1, 1), 0, 0); + readback.Apply(); + return readback.GetPixel(0, 0); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(readback); + } + } + + private static void Fill(RenderTexture texture, Color color) + { + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = texture; + GL.Clear(false, true, color); + } + finally + { + RenderTexture.active = previous; + } + } + + [Test] + public void InitialCompositeResizeAndDisposePreserveTheCallersRenderTarget() + { + using var trail = new BattleTrailPreview { Enabled = true }; + var source = new RenderTexture(256, 256, 0, RenderTextureFormat.ARGB32); + source.Create(); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = source; + trail.Composite(source, 64, 48); + Assert.That(RenderTexture.active, Is.SameAs(source)); + trail.Composite(source, 96, 64); + Assert.That(RenderTexture.active, Is.SameAs(source)); + trail.Dispose(); + Assert.That(RenderTexture.active, Is.SameAs(source)); + } + finally + { + RenderTexture.active = previous; + source.Release(); + Object.DestroyImmediate(source); + } + } + + [Test] + public void TrailShaderUsesOriginalDiffuseAlphaAndRepaintsDoNotAgeTheRing() + { + using var trail = new BattleTrailPreview { Enabled = true }; + var source = new RenderTexture(256, 256, 0, RenderTextureFormat.ARGB32); + source.Create(); + try + { + Fill(source, Color.red); + Color first = Pixel(trail.Composite(source, 64, 48)); + Assert.That(first.r, Is.EqualTo(BattleTrailState.ContributionAt(7)).Within(2f / 255)); + Assert.That(first.g, Is.Zero.Within(1f / 255)); + Color repeated = Pixel(trail.Composite(source, 64, 48)); + Assert.That(repeated.r, Is.EqualTo(first.r).Within(1f / 255)); + trail.Advance(.02, .02); + Fill(source, Color.green); + Color second = Pixel(trail.Composite(source, 64, 48)); + Assert.That(second.r, Is.EqualTo(BattleTrailState.ContributionAt(6)).Within(2f / 255)); + Assert.That(second.g, Is.EqualTo(BattleTrailState.ContributionAt(7)).Within(2f / 255)); + trail.Enabled = false; + Assert.That(trail.Composite(source, 64, 48), Is.SameAs(source)); + } + finally + { + source.Release(); + Object.DestroyImmediate(source); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleTrailTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleTrailTests.cs.meta new file mode 100644 index 00000000..8502e2a9 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleTrailTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f7836e097d364a61b68a7eff5d1cb416 diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleWeaponPresentationTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/BattleWeaponPresentationTests.cs new file mode 100644 index 00000000..e775c321 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleWeaponPresentationTests.cs @@ -0,0 +1,207 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Core.DataReader.Pol; + using Core.Primitives; + using Game.Rendering.Renderer; + using Newtonsoft.Json.Linq; + using NUnit.Framework; + using ResourceBrowser; + using UnityEngine; + using Object = UnityEngine.Object; + using Color32 = UnityEngine.Color32; + + public sealed class BattleWeaponPresentationTests + { + [TestCase("PAL3", 0, true, true)] + [TestCase("PAL3A", 0, false, false)] + [TestCase("PAL3A", -1, false, true)] + [TestCase("PAL3A", 1, true, true)] + public void ExternalFlagsUseEachPublishedGamesZeroConvention(string variant, float flag, bool left, bool right) + { + BattleWeaponVisibility actual = BattleWeaponPresentationRules.Visible(variant, 0, 29, 1, external: true, leftFlag: flag, rightFlag: flag); + Assert.That((actual.Left, actual.Right), Is.EqualTo((left, right))); + } + + [Test] + [Category("LocalNativeEvidence")] + public void EveryPublishedAttachVisibilityCombinationMatches() + { + JObject document = JObject.Parse(File.ReadAllText(Path.Combine(NativeDirectory(), "weapon-visibility-native-vectors.json"))); + int count = 0; + foreach (JProperty variant in document.Properties()) + foreach (JToken row in variant.Value["rows"]) + { + BattleWeaponVisibility actual = BattleWeaponPresentationRules.Visible(variant.Name, (int)row["identity"], (int)row["action"], + (int)row["weapon"], (bool)row["form"], true, (bool)row["external"], (float)row["leftFlag"], (float)row["rightFlag"]); + Assert.That((actual.Left, actual.Right), Is.EqualTo(((bool)row["left"], (bool)row["right"])), variant.Name + ": " + count); + count++; + } + Assert.That(count, Is.EqualTo(37600)); + } + + [Test] + [Category("LocalNativeEvidence")] + public void WeaponTrailSamplingAndColorsMatchTheInstalledEngine() + { + JObject document = JObject.Parse(File.ReadAllText(Path.Combine(NativeDirectory(), "weapon-blade-native-vectors.json"))); + Type type = typeof(WeaponBlade); + const BindingFlags members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + var owner = new GameObject("original weapon blade fixture"); + try + { + foreach (JToken row in document["rows"]) + { + TagNode[] tags = { + new() { GameBoxTransformMatrix = new GameBoxMatrix4x4(), TintColor = 0xff336699 }, + new() { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Tx = -40, Tz = 140 }, TintColor = 0xff336699 } + }; + object blade = Activator.CreateInstance(type, members, null, new object[] { tags }, null); + try + { + foreach (JToken sample in row["samples"]) + { + JToken origin = sample["vertices"][0]; + owner.transform.position = new Vector3((float)origin[0], (float)origin[1], (float)origin[2]); + type.GetMethod("Sample", members).Invoke(blade, new object[] { owner.transform, (bool)sample["visible"], + (int)sample["tick"] == 0 ? 0f : 0.02f, (float)row["rate"], (float)row["lifetime"] }); + int count = (int)type.GetField("_count", members).GetValue(blade); + Assert.That(count, Is.EqualTo((int)sample["count"]), row["mode"] + " " + sample["tick"]); + if (count < 3) + continue; + Mesh mesh = (Mesh)type.GetField("_mesh", members).GetValue(blade); + Vector3[] vertices = mesh.vertices; + Color32[] colors = mesh.colors32; + for (int frame = 0; frame < count; frame++) + for (int index = 0; index < 2; index++) + { + JToken expected = sample["frames"][frame]["vertices"][index]; + JToken position = expected["position"]; + Assert.That(Vector3.Distance(vertices[frame * 2 + index], new Vector3((float)position[0], (float)position[1], (float)position[2])), Is.LessThan(0.00001f)); + uint color = (uint)expected["color"]; + Assert.That(colors[frame * 2 + index], Is.EqualTo(new Color32((byte)(color >> 16), (byte)(color >> 8), (byte)color, (byte)(color >> 24)))); + } + } + } + finally { type.GetMethod("Dispose", members).Invoke(blade, null); } + } + } + finally { Object.DestroyImmediate(owner); } + } + + [Test] + public void PublishedSnapshotsRetainCompatibilityGeometryWithoutRebuildingTheUnusedMesh() + { + using var preview = new ResourceModelPreview(null, false); + GameObject owner = preview.CreateObject("Blade buffer regression"); + Camera camera = preview.Root.scene.GetRootGameObjects().Select(root => root.GetComponent()).First(value => value != null); + var tags = new[] + { + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Ty = 10 }, TintColor = 0xff336699 }, + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Tx = -40, Tz = 140 }, TintColor = 0xccee8855 } + }; + using var compatibility = new WeaponBlade(tags); + using var published = new WeaponBlade(tags); + var material = WeaponBlade.CreateMaterial(); + const BindingFlags members = BindingFlags.Instance | BindingFlags.NonPublic; + var type = typeof(WeaponBlade); + object vertices = type.GetField("_vertices", members).GetValue(published); + object colors = type.GetField("_colors", members).GetValue(published); + object triangles = type.GetField("_triangles", members).GetValue(published); + try + { + for (int frame = 0; frame < 160; frame++) + { + owner.transform.SetPositionAndRotation(new Vector3(frame * .01f, Mathf.Sin(frame * .13f), Mathf.Cos(frame * .11f)), Quaternion.Euler(frame, frame * 3, 0)); + bool visible = frame % 19 < 14; + float lifetime = frame < 60 ? .12f : .25f; + float delta = frame < 30 ? .02f : frame < 80 ? 1f / 60 : frame < 110 ? 0 : .01f; + float rate = frame < 60 || frame > 120 ? 1 : frame < 100 ? 2 : 0; + if (frame == 130) + delta = 30; + compatibility.SamplePose(owner.transform, visible, lifetime); + published.SamplePose(owner.transform, visible, lifetime, rebuildMesh: false); + for (int flush = 0; flush < 2; flush++) + { + compatibility.Advance(delta, rate); + published.Advance(delta, rate, rebuildMesh: false); + compatibility.RenderFlush(camera, material, 0, flush, true); + published.RenderFlush(camera, material, 0, flush, true); + var expected = (Mesh[])type.GetField("_flushMeshes", members).GetValue(compatibility); + var actual = (Mesh[])type.GetField("_flushMeshes", members).GetValue(published); + Assert.That(actual[flush].vertices, Is.EqualTo(expected[flush].vertices), $"Frame {frame}, flush {flush}"); + Assert.That(actual[flush].colors32, Is.EqualTo(expected[flush].colors32), $"Frame {frame}, flush {flush}"); + Assert.That(actual[flush].triangles, Is.EqualTo(expected[flush].triangles), $"Frame {frame}, flush {flush}"); + Assert.That(actual[0], Is.Not.SameAs(actual[1])); + } + Assert.That(published.TriangleCount, Is.EqualTo(compatibility.TriangleCount)); + Assert.That(((Mesh)type.GetField("_mesh", members).GetValue(published)).vertexCount, Is.Zero); + } + Assert.That(type.GetField("_vertices", members).GetValue(published), Is.SameAs(vertices)); + Assert.That(type.GetField("_colors", members).GetValue(published), Is.SameAs(colors)); + Assert.That(type.GetField("_triangles", members).GetValue(published), Is.SameAs(triangles)); + } + finally { Object.DestroyImmediate(material); } + } + + [Test] + public void PublishedFlushKeepsAnExplicitPreviewSceneOverride() + { + using var preview = new ResourceModelPreview(null, false); + var owner = new GameObject("Explicit preview blade camera") { hideFlags = HideFlags.HideAndDontSave }; + var camera = owner.AddComponent(); + camera.enabled = false; + camera.scene = preview.Root.scene; + Assert.That(camera.scene.IsValid(), Is.True); + Assert.That(owner.scene, Is.Not.EqualTo(camera.scene), "The fixture must distinguish the override from the camera object's scene."); + var tags = new[] + { + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4(), TintColor = 0xffffffff }, + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Ty = 20 }, TintColor = 0xffffffff }, + }; + using var blade = new WeaponBlade(tags); + Material material = WeaponBlade.CreateMaterial(); + try + { + blade.SamplePose(owner.transform, true, .12f, false); + blade.Advance(.02f, 1, false); + owner.transform.position = Vector3.right; + blade.SamplePose(owner.transform, true, .12f, false); + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + for (int flush = 0; flush < 2; flush++) + blade.RenderFlush(camera, material, 0, flush, true); + var renderers = (MeshRenderer[])typeof(WeaponBlade).GetField("_flushRenderers", fields).GetValue(blade); + foreach (MeshRenderer renderer in renderers) + { + Assert.That(renderer.gameObject.scene, Is.EqualTo(preview.Root.scene)); + Assert.That(renderer.enabled, Is.True); + } + blade.Dispose(); + foreach (MeshRenderer renderer in renderers) + Assert.That(renderer == null, Is.True); + } + finally + { + Object.DestroyImmediate(material); + Object.DestroyImmediate(owner); + } + } + + private static string NativeDirectory() + { + string directory = Environment.GetEnvironmentVariable("PAL3_NATIVE_VECTORS_ROOT"); + if (directory == null) + Assert.Ignore("Published native vectors are local analysis artifacts."); + return directory; + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/BattleWeaponPresentationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/BattleWeaponPresentationTests.cs.meta new file mode 100644 index 00000000..6c8479bd --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/BattleWeaponPresentationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9ce061c180244220ace0208a8f21bee2 diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/DisplayFrameRateTests.cs b/Assets/Tests/BattleEditor/Editor/Authoring/DisplayFrameRateTests.cs new file mode 100644 index 00000000..de2177a1 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/DisplayFrameRateTests.cs @@ -0,0 +1,58 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using Engine.Utilities; + using NUnit.Framework; + + public sealed class DisplayFrameRateTests + { + [TestCase(-1, 120, 120)] + [TestCase(240, 60, 60)] + [TestCase(30, 120, 30)] + [TestCase(-1, 59.94, 59)] + [TestCase(-1, 0, 60)] + [TestCase(-1, double.NaN, 60)] + public void DisplayCapsExplicitAndAutomaticLimits(int requested, double refresh, int expected) => + Assert.That(DisplayFrameRate.Limit(requested, refresh), Is.EqualTo(expected)); + + [TestCase(1, 30, 120, 0)] + [TestCase(1, 59, 59.94, 0)] + [TestCase(1, 60, 59.94, 1)] + [TestCase(1, -1, 120, 1)] + [TestCase(2, 60, 120, 2)] + [TestCase(0, 30, 120, 0)] + public void OnlyAnIncompatibleExplicitCapOverridesConfiguredVSync(int configured, int limit, double refresh, int expected) => + Assert.That(DisplayFrameRate.VSyncForLimit(configured, limit, refresh), Is.EqualTo(expected)); + + [TestCase(60)] + [TestCase(120)] + public void CallbacksOnTheRefreshPeriodAllProduceFrames(int refreshRate) + { + var pacer = new DisplayFramePacer(); + for (int frame = 0; frame < refreshRate * 10; frame++) + Assert.That(pacer.TryAdvance(frame / (double)refreshRate, refreshRate), Is.True, "Frame " + frame); + } + + [Test] + public void RepeatedInputCannotExceedRefreshAndLongPausesDoNotProduceCatchupFrames() + { + var pacer = new DisplayFramePacer(); + int frames = 0; + for (int sample = 0; sample < 10000; sample++) + if (pacer.TryAdvance(sample / 10000d, 60)) + frames++; + Assert.That(frames, Is.InRange(59, 60)); + Assert.That(pacer.TryAdvance(10, 60), Is.True); + Assert.That(pacer.TryAdvance(10, 60), Is.False); + Assert.That(pacer.TryAdvance(10.001, 60), Is.False); + Assert.That(pacer.TryAdvance(11, 120), Is.True); + Assert.That(pacer.TryAdvance(11.009, 120), Is.True); + Assert.That(pacer.TryAdvance(double.NaN, 120), Is.False); + Assert.That(pacer.TryAdvance(1, 60), Is.True, "A restarted presentation clock must recover."); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Authoring/DisplayFrameRateTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Authoring/DisplayFrameRateTests.cs.meta new file mode 100644 index 00000000..2f54ab6a --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Authoring/DisplayFrameRateTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 91f5efe95d6f4259ad764c0ce07ab84a diff --git a/Assets/Tests/BattleEditor/Editor/Hud.meta b/Assets/Tests/BattleEditor/Editor/Hud.meta new file mode 100644 index 00000000..6dd6e6e7 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 703255f14af141b28d14c9b0dece6b72 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleDamageNumberColorsTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleDamageNumberColorsTests.cs new file mode 100644 index 00000000..39a3b36a --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleDamageNumberColorsTests.cs @@ -0,0 +1,69 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System.Linq; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + + public sealed class BattleDamageNumberColorsTests + { + [TestCase(-123, BattleDamageNumberColorMode.Original, 0x3232ff)] + [TestCase(0, BattleDamageNumberColorMode.Original, 0x3232ff)] + [TestCase(-123, BattleDamageNumberColorMode.Yellow, 0xffff00)] + [TestCase(0, BattleDamageNumberColorMode.Yellow, 0xffff00)] + [TestCase(-123, BattleDamageNumberColorMode.White, 0xffffff)] + [TestCase(0, BattleDamageNumberColorMode.White, 0xffffff)] + public void OnlyTheDrawingColorChangesForHpDamageAndZero(int value, BattleDamageNumberColorMode mode, int expected) + { + BattleNumberFrame frame = Frame(value, 0, false, false); + Assert.That(BattleDamageNumberColors.Resolve(frame.Color, mode), Is.EqualTo((uint)expected)); + Assert.That(frame.Color, Is.EqualTo(0x3232ffu), "The native projection must retain the released color."); + Assert.That(frame.Text, Is.EqualTo(value.ToString(System.Globalization.CultureInfo.InvariantCulture))); + Assert.That(frame.Alpha, Is.EqualTo(191)); + } + + [TestCase(0, 0, true, false, 0x00ff00)] + [TestCase(123, 0, true, false, 0x00ff00)] + [TestCase(-10, 1, false, false, 0xfbe0a2)] + [TestCase(10, 1, true, false, 0xfbe0a2)] + [TestCase(-10, 2, false, false, 0xfaa8d5)] + [TestCase(10, 2, true, false, 0xfaa8d5)] + [TestCase(0, 0, false, true, 0x32ffff)] + [TestCase(-1, 16, false, false, 0x32ffff)] + public void EveryModePreservesRecoveryGpMpMissAndGu(int value, int resource, bool recovery, bool miss, int expected) + { + BattleNumberFrame frame = Frame(value, resource, recovery, miss); + foreach (BattleDamageNumberColorMode mode in System.Enum.GetValues(typeof(BattleDamageNumberColorMode))) + Assert.That(BattleDamageNumberColors.Resolve(frame.Color, mode), Is.EqualTo((uint)expected)); + } + + [Test] + public void UnrecognizedColorsAndModesKeepTheirOriginalValue() + { + Assert.That(default(BattleDamageNumberColorMode), Is.EqualTo(BattleDamageNumberColorMode.Original)); + Assert.That(BattleDamageNumberColors.Resolve(0x3232ffu, (BattleDamageNumberColorMode)99), Is.EqualTo(0x3232ffu)); + Assert.That(BattleDamageNumberColors.Resolve(0x123456u, BattleDamageNumberColorMode.Yellow), Is.EqualTo(0x123456u)); + } + + private static BattleNumberFrame Frame(int value, int resource, bool recovery, bool miss) + { + var entry = new BattleEvent(); + void Set(string name, object value) => typeof(BattleEvent).GetProperty(name).SetValue(entry, value); + Set(nameof(BattleEvent.Kind), BattleEventKind.NumberShown); + Set(nameof(BattleEvent.Target), "target"); + Set(nameof(BattleEvent.RequestedDelta), value); + Set(nameof(BattleEvent.Resource), resource); + Set(nameof(BattleEvent.NumberIsRecovery), recovery); + Set(nameof(BattleEvent.NumberIsMiss), miss); + Set(nameof(BattleEvent.DurationSeconds), 2f); + var projection = new BattleNumberProjection(); + projection.Synchronize(new[] { entry }, 25); + return projection.Sample().Single(); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleDamageNumberColorsTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleDamageNumberColorsTests.cs.meta new file mode 100644 index 00000000..1f3fe0f4 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleDamageNumberColorsTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 17842a7c9a2546b8a106647a5967c42a diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleDirectTargetingTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleDirectTargetingTests.cs new file mode 100644 index 00000000..696b69e4 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleDirectTargetingTests.cs @@ -0,0 +1,290 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using UnityEngine; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + public sealed class BattleDirectNavigationTests + { + [TestCase(BattleHudDirection.Up, "skills")] + [TestCase(BattleHudDirection.UpRight, "protection")] + [TestCase(BattleHudDirection.Right, "defend")] + [TestCase(BattleHudDirection.DownRight, "flee")] + [TestCase(BattleHudDirection.Down, "items")] + [TestCase(BattleHudDirection.DownLeft, "formation")] + [TestCase(BattleHudDirection.Left, "magic")] + [TestCase(BattleHudDirection.UpLeft, "ai")] + public void RingDirectionSelectsItsNativePositionWithoutSubmitting(BattleHudDirection direction, string expected) + { + foreach (string variant in new[] { "PAL3", "PAL3A" }) + { + var battle = BattleHudTests.Session(variant); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(battle); + int inputs = battle.Inputs.Count; + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Down)); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: direction)), Is.True); + Assert.That(presenter.FocusedId, Is.EqualTo(expected)); + Assert.That(battle.Inputs.Count, Is.EqualTo(inputs)); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Primary)); + Assert.That(presenter.FocusedId, Is.EqualTo("attack")); + } + } + + [Test] + public void AiDefaultsToTheCurrentControllerInsteadOfTheFirstActor() + { + var battle = BattleHudTests.Session(); + Assert.That(battle.RequestAiNormal(battle.WaitingActor), Is.True); + for (int step = 0; step < 500 && (battle.WaitingActor == null || battle.WaitingActor == "A"); step++) + battle.Step(); + Assert.That(battle.WaitingActor, Is.Not.Null.And.Not.EqualTo("A")); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(battle); + presenter.Open(BattleHudPage.Ai); + Assert.That(presenter.FocusedId, Is.EqualTo("flag:0")); + Assert.That(presenter.AiActor, Is.EqualTo(battle.WaitingActor)); + Assert.That(BattleHudView.PointerActors(battle, presenter), Is.EqualTo(new[] { battle.WaitingActor })); + } + + [Test] + public void TargetsUseProjectedDirectionsAndHaveNoHiddenBackControl() + { + var battle = BattleHudTests.Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(battle); + presenter.ChooseAction(BattleAction.Attack); + presenter.SetFocusLayout(new[] { ("target:E", 100f, 100f), ("target:E2", 200f, 90f), ("target:E3", 150f, 200f) }); + Assert.That(presenter.FocusItems().Select(item => item.Id), Does.Not.Contain("back")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Right)); + Assert.That(presenter.Target, Is.EqualTo("E2")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Down)); + Assert.That(presenter.Target, Is.EqualTo("E3")); + Assert.That(battle.Inputs.Count(input => input.Kind == BattleInputKind.Command), Is.Zero); + } + } + + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleDirectTargetingTests + { + private BattleEditorSession _editor; + private SelectionCanvas _canvas; + private string _enemy; + + private sealed class SelectionCanvas : IDisposable + { + private static readonly Vector2 Size = new(1260, 850); + private readonly OffscreenGui _gui; + private readonly BattleEditorSession _editor; + + public readonly BattleHudView Hud = new(); + public Rect Area = new(20, 30, 800, 600); + public bool Touch; + public int Repaints; + public double Clock; + public int DrawerClicks; + public Vector2? Pointer; + + public SelectionCanvas(BattleEditorSession editor) + { + _editor = editor; + _gui = new OffscreenGui(Draw); + } + + public RenderTexture RenderTarget => _gui.RenderTarget; + + public void Paint() + { + int previous = Repaints; + _gui.Paint(Size); + Assert.That(Repaints, Is.GreaterThan(previous)); + } + + public void SendEvent(Event input) => _gui.SendEvent(input, Size); + + public void Dispose() => _gui.Dispose(); + + private void Draw() + { + if (Pointer is { } point) + Event.current.mousePosition = point; + _editor.Preview.View.SetViewportContext(Area); + if (Event.current.type != EventType.Repaint) + DrawHud(); + Hud.PreparePointers(_editor.Battle, _editor.Data, _editor.Preview, Clock); + _editor.Preview.View.Draw(Area); + if (Event.current.type == EventType.Repaint) + { + DrawHud(); + Repaints++; + } + if (GUI.Button(new Rect(Area.xMax + 4, Area.y + 24, 180, 24), "Drawer test")) + DrawerClicks++; + } + + private void DrawHud() => Hud.Draw(_editor.Battle, _editor.Data, _editor.Preview, Area, + () => _editor.SyncBattle(), _ => { }, interaction: new BattleHudInteractionProfile(Touch)); + } + + [SetUp] + public void SetUp() + { + _editor = new BattleEditorSession(); + string configured = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root) && configured == null) + Assert.Ignore("Original local data unavailable."); + _editor.Load(root, 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = _editor.Data.Scenes.First(), + DataFingerprint = _editor.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush, + Music = "NONE" + }; + scenario.Participants.Add(_editor.Data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = _editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(_editor.Data, id)); + scenario.Participants.Add(_editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + scenario.Participants.Add(_editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Fire)); + _enemy = scenario.Participants[1].InstanceId; + _editor.StartBattle(scenario); + _editor.Preview.Audio.Muted = _editor.Preview.Effects.Muted = true; + Vector3 center = _editor.Battle.Actors.Select(actor => BattleAnimationCatalog.UnityPosition(actor.Position)).Aggregate(Vector3.zero, (sum, value) => sum + value) / 3; + _editor.Preview.View.SetCamera(center + new Vector3(9, 9, -14), center + Vector3.up, 50); + _canvas = new SelectionCanvas(_editor); + _canvas.Hud.TakeNavigationInput(_editor.Battle); + Assert.That(_canvas.Hud.Presenter.ChooseAction(BattleAction.Attack), Is.True); + } + + [TearDown] + public void TearDown() + { + _canvas?.Dispose(); + _editor?.Dispose(); + } + + private Vector2 TargetPoint() + { + Assert.That(_editor.Preview.TryActorSelectionPoint(_enemy, _canvas.Area, out Vector2 point), Is.True); + Assert.That(_canvas.Area.Contains(point), Is.True); + Assert.That(_editor.Preview.PickActor(point, _canvas.Area, new[] { _enemy }), Is.EqualTo(_enemy)); + return point; + } + + private int Commands => _editor.Battle.Inputs.Count(input => input.Kind == BattleInputKind.Command); + + [Test] + public void MouseHoversTheBodyAndClicksOnceAcrossLandscapeAspects() + { + foreach (Vector2 size in new[] { new Vector2(800, 600), new Vector2(1050, 450), new Vector2(1000, 500), new Vector2(700, 700) }) + { + _canvas.Area = new Rect(new Vector2(20, 30), size); + _canvas.Paint(); + Vector2 point = TargetPoint(); + _canvas.Pointer = point; + Assert.That(_canvas.Hud.SendPointer(BattleHudIntentKind.PointerMove, 0, point), Is.True); + Assert.That(_canvas.Hud.Presenter.Target, Is.EqualTo(_enemy)); + _canvas.Clock = .1; + _canvas.Paint(); + Assert.That(Commands, Is.Zero); + Transform pointer = _editor.Preview.View.Root.transform.Find("Battle selection pointer " + _enemy); + Assert.That(pointer, Is.Not.Null); + Assert.That(pointer.GetComponentsInChildren().Any(renderer => renderer.enabled), Is.True); + Capture("mouse-" + size.x + "x" + size.y); + } + Vector2 target = TargetPoint(); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 0, target); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerUp, 0, target); + Assert.That(Commands, Is.EqualTo(1)); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void TouchTapConfirmsAndIdleMouseCannotOverrideNavigation() + { + _canvas.Touch = true; + _canvas.Paint(); + Vector2 target = TargetPoint(); + Vector2 outside = new(_canvas.Area.xMax + 1, target.y); + Assert.That(_canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 40, outside), Is.False); + _canvas.Hud.Presenter.Open(BattleHudPage.Magic); + _canvas.Paint(); + Vector2 background = _canvas.Area.position + new Vector2(620, 170); + int takeovers = 0; + void TakePointer() => takeovers++; + _canvas.Hud.PointerTookControl += TakePointer; + _canvas.Hud.TakeNavigationInput(_editor.Battle); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 100, background); + Assert.That(takeovers, Is.EqualTo(1)); + _canvas.Hud.PointerTookControl -= TakePointer; + Assert.That(_canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 101, outside), Is.True); + Assert.That(_canvas.Hud.SendPointer(BattleHudIntentKind.PointerUp, 101, outside), Is.True); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerCancel, 100, background); + Assert.That(_canvas.Hud.Presenter.ChooseAction(BattleAction.Attack), Is.True); + _canvas.Paint(); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 0, target); + Vector2 drawer = new(_canvas.Area.xMax + 40, _canvas.Area.y + 36); + _canvas.Pointer = drawer; + _canvas.SendEvent(new Event { type = EventType.MouseDown, button = 0, mousePosition = drawer }); + _canvas.SendEvent(new Event { type = EventType.MouseUp, button = 0, mousePosition = drawer }); + Assert.That(_canvas.DrawerClicks, Is.EqualTo(1)); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 6, target); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerCancel, 6, target); + Assert.That(Commands, Is.Zero, "An incomplete or cancelled touch cannot cast."); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 6, target); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 6, target); + Assert.That(Commands, Is.Zero, "A fresh Down after a missing Up still waits for release."); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerCancel, 6, target); + _canvas.Hud.TakeNavigationInput(_editor.Battle); + _canvas.Hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Down)); + string navigated = _canvas.Hud.Presenter.Target; + _canvas.Pointer = target; + _canvas.Paint(); + Assert.That(_canvas.Hud.Presenter.Target, Is.EqualTo(navigated)); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 8, target); + Assert.That(Commands, Is.Zero); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerUp, 8, target); + Assert.That(Commands, Is.EqualTo(1), "One complete tap on the recipient casts once."); + LogAssert.NoUnexpectedReceived(); + } + + private void Capture(string name) + { + string root = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (string.IsNullOrEmpty(root)) + return; + string folder = Path.Combine(root, "DirectSelection"); + Directory.CreateDirectory(folder); + RenderTexture buffer = _canvas.RenderTarget; + var image = new Texture2D(buffer.width, buffer.height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = buffer; + image.ReadPixels(new Rect(0, 0, buffer.width, buffer.height), 0, 0); + image.Apply(); + + File.WriteAllBytes(Path.Combine(folder, BattleData.Variant + (_editor.CapturedScenario.ToonRendering ? "-toon-" : "-native-") + name + ".png"), image.EncodeToPNG()); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleDirectTargetingTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleDirectTargetingTests.cs.meta new file mode 100644 index 00000000..d0b7d89a --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleDirectTargetingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d5dc280c4f7943449e7ef16b0c1ef5ea diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudDenialTextTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudDenialTextTests.cs new file mode 100644 index 00000000..f7b6287b --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudDenialTextTests.cs @@ -0,0 +1,217 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using System.Reflection; + using Battle; + using Battle.Presentation; + using Newtonsoft.Json; + using NUnit.Framework; + + public sealed class BattleHudDenialTextTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class Rules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => 1; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => new BattleBasicRules().Hit(source, target, guarding, random, targetAtHome, damageDivisor); + } + + private static BattleSession Session(string variant, int mp = 9) + { + var scenario = new BattleScenario { Variant = variant, Scene = "denial", DataFingerprint = "denial" }; + foreach ((string id, BattleSide side) in new[] { ("A", BattleSide.Ally), ("E", BattleSide.Enemy) }) + { + var actor = new BattleParticipant + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? 101 : 701, + Side = side, + Slot = BattleSlot.Water, + Attributes = new[] { 100, 100, 100, 20, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 100, 100, mp } + }; + actor.Skills.Add(new BattleSkill { Id = 301, Level = 4, Mastered = true }); + scenario.Participants.Add(actor); + } + var skill = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 301, + Name = "水术", + IsMagic = true, + Range = BattleTargetRange.OpponentSingle, + ApplicableIdentities = new[] { 0 }, + Costs = new[] { new BattleCost(2, BattleValueMode.Absolute, 10) } + }); + var definitions = new BattleDefinitions(variant, "denial", new[] { skill }, Array.Empty(), + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? 0 : -1, + Equipment = new[] { new BattleEquipmentDefinition(new BattleEquipmentData { Id = 80001, Slot = 1, MpSaving = 50 }) } + }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new Rules(), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + session.Step(); + return session; + } + + private static string State(BattleSession session) + { + object random = typeof(BattleSession).GetField("_random", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(session); + return JsonConvert.SerializeObject(new + { + session.Tick, + session.SimulationTick, + session.Events, + session.Inputs, + session.Actors, + session.Inventory, + session.Money, + session.Pal3AState, + session.StageTasks, + RandomState = random.GetType().GetProperty("State").GetValue(random) + }); + } + + [TestCase(0, "精")] + [TestCase(1, "气")] + [TestCase(2, "神")] + [TestCase(10, "金钱")] + [TestCase(16, "蛊")] + public void ResourceNamesAndAmountsComeFromTypedEstimatesRatherThanDiagnosticFields(int resource, string name) + { + var costs = new[] { new BattleCostEstimate(resource, 80, 20, 30) }; + string brief = BattleHudDenialText.Format("Resource 999: need 999, available 999.", costs); + Assert.That(brief, Is.EqualTo(name + "不足:需80,现30")); + Assert.That(brief.Sum(character => character < 0x80 ? 1 : 2), Is.LessThanOrEqualTo(20)); + Assert.That(BattleHudDenialText.Format("Resource 999: need 999, available 999.", costs, detailed: true), + Is.EqualTo(name + "不足:需要 80,当前 30。")); + } + + [Test] + public void ResourceDenialUsesTheFirstInsufficientRequirementInDomainOrder() + { + var costs = new[] + { + new BattleCostEstimate(0, 3, 3, 50), + new BattleCostEstimate(2, 80, 20, 30), + new BattleCostEstimate(10, 100, 100, 0) + }; + Assert.That(BattleHudDenialText.Format("Resource 2: need 80, available 30.", costs), Is.EqualTo("神不足:需80,现30")); + Assert.That(BattleHudDenialText.Format("This actor has not mastered the skill.", costs), Is.EqualTo("尚未学会此技能")); + Assert.That(BattleHudDenialText.Format(null, costs), Is.Null); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AbilityDenialKeepsTheOriginalGateAndLeavesSessionAndRandomStateUntouched(string variant) + { + BattleSession session = Session(variant); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + BattleAbilityDefinition skill = session.Definitions.Skills[301]; + BattleCostEstimate estimate = session.GetCostEstimate(new BattleCommand("A", BattleAction.Skill, abilityId: 301)).Single(); + Assert.That((estimate.Required, estimate.Payable, estimate.Available), Is.EqualTo((10, 5, 9))); + string diagnostic = presenter.Reason(BattleAction.Skill, 301); + Assert.That(diagnostic, Is.EqualTo("Resource 2: need 10, available 9.")); + string before = State(session); + for (int index = 0; index < 20; index++) + Assert.That(BattleHudDenialText.ForAbility(session, presenter, skill), Is.EqualTo("神不足:需10,现9")); + Assert.That(BattleHudDenialText.ForAbility(session, presenter, skill, detailed: true), Is.EqualTo("神不足:需要 10,当前 9。")); + Assert.That(presenter.Reason(BattleAction.Skill, 301), Is.EqualTo(diagnostic)); + Assert.That(State(session), Is.EqualTo(before)); + Assert.That(presenter.Message, Is.Null); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void UsableAbilitiesDoNotReplaceTheirOriginalDescriptionWithADenial(string variant) + { + BattleSession session = Session(variant, 100); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(BattleHudDenialText.ForAbility(session, presenter, session.Definitions.Skills[301]), Is.Null); + Assert.That(BattleHudDenialText.ForAbility(session, presenter, session.Definitions.Skills[301], detailed: true), Is.Null); + } + + [TestCase("Actor is not ready.", "等待角色就绪。")] + [TestCase("There is no legal target.", "没有可选目标。")] + [TestCase("No item remains in this battle inventory.", "此物品已用完或已被其他指令占用。")] + [TestCase("封期间不能施放仙术。", "封期间不能施放仙术。")] + [TestCase("乱/狂期间由原版异常状态 AI 接管。", "乱/狂期间不能手动下达指令。")] + [TestCase("The magic sword energy must be greater than 199.9.", "魔剑能量不足。")] + [TestCase("朱仙变 requires full SP before equipment savings.", "气满后才能使用朱仙变。")] + [TestCase("This spirit wheel element needs nine charges.", "此系五灵轮需充能九次。")] + [TestCase("The ability has no verified action timeline.", "此技能暂时无法使用。")] + public void CommonFailuresUsePlayerFacingChinese(string diagnostic, string expected) => + Assert.That(BattleHudDenialText.Format(diagnostic, detailed: true), Is.EqualTo(expected)); + + [TestCase("")] + [TestCase("Missing EffectLinker group 12345 in /local/assets.")] + [TestCase("角色处于Paralysis,不能换位。")] + [TestCase("未核实成员资源12345的原版身份映射。")] + public void UnknownDiagnosticsNeverEnterThePlayerPanel(string diagnostic) + { + Assert.That(BattleHudDenialText.Format(diagnostic), Is.EqualTo("当前无法使用")); + Assert.That(BattleHudDenialText.Format(diagnostic, detailed: true), Is.EqualTo("当前无法使用。")); + } + + [TestCase(0, "精")] + [TestCase(1, "气")] + [TestCase(2, "神")] + [TestCase(10, "金钱")] + [TestCase(16, "蛊")] + public void LargeAmountsUseAShortLabelAndRetainCompleteTooltipValues(int resource, string name) + { + var costs = new[] { new BattleCostEstimate(resource, int.MaxValue, 1, int.MaxValue - 1) }; + const string diagnostic = "Resource 999: need 999, available 999."; + Assert.That(BattleHudDenialText.Format(diagnostic, costs), Is.EqualTo(name + "不足")); + Assert.That(BattleHudDenialText.Format(diagnostic, costs, detailed: true), + Is.EqualTo(name + "不足:需要 2147483647,当前 2147483646。")); + } + + [TestCase("No item remains in this battle inventory.", "此物品无可用数量")] + [TestCase("乱/狂期间由原版异常状态 AI 接管。", "乱/狂期间自动行动")] + [TestCase("The original fire beast form permits only physical attack, defense, or escape.", "炎兽仅可攻、防、逃")] + public void BriefReasonsFitTheNarrowDescriptionBand(string diagnostic, string expected) + { + string brief = BattleHudDenialText.Format(diagnostic); + Assert.That(brief, Is.EqualTo(expected)); + Assert.That(brief.Sum(character => character < 0x80 ? 1 : 2), Is.LessThanOrEqualTo(20)); + } + + [Test] + public void UnknownOrUnavailableResourceContextNeverLeaksRawResourceNumbers() + { + Assert.That(BattleHudDenialText.Format("Resource 999: need 10, available 0.", new[] { new BattleCostEstimate(999, 10, 10, 0) }), + Is.EqualTo("所需资源不足")); + Assert.That(BattleHudDenialText.Format("Resource 2: need 80, available 30."), Is.EqualTo("所需资源不足")); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudDenialTextTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudDenialTextTests.cs.meta new file mode 100644 index 00000000..06494330 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudDenialTextTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9d357b356f9342a4a0f90e874e9539b1 diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudPolishTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudPolishTests.cs new file mode 100644 index 00000000..27313506 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudPolishTests.cs @@ -0,0 +1,331 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using UnityEditor; + using UnityEngine; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleHudPolishTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private BattleEditorSession _session; + private Canvas _canvas; + private int _magicSkill; + + private sealed class Canvas : IDisposable + { + public static readonly Vector2 Size = new(980, 760); + private readonly OffscreenGui _gui; + + public readonly BattleEditorSession Editor; + public readonly BattleHudView Hud = new(); + public readonly Rect Area = new(30, 40, 800, 600); + public bool Enabled = true; + public bool Touch; + public int HotControl; + public Vector2? Pointer; + public int Repaints; + public string Tooltip; + + public Canvas(BattleEditorSession editor) + { + Editor = editor; + _gui = new OffscreenGui(Draw); + } + + public RenderTexture RenderTarget => _gui.RenderTarget; + + public void Paint() + { + int before = Repaints; + _gui.Paint(Size); + Assert.That(Repaints, Is.GreaterThan(before)); + } + + public void SendEvent(Event input) => _gui.SendEvent(input, Size); + + public void Dispose() => _gui.Dispose(); + + private void Draw() + { + if (Editor?.Battle == null) + return; + if (Pointer is { } pointer) + Event.current.mousePosition = pointer; + EditorGUI.DrawRect(Area, new Color(.28f, .28f, .28f)); + using (new EditorGUI.DisabledScope(!Enabled)) + Hud.Draw(Editor.Battle, Editor.Data, Editor.Preview, Area, () => Editor.SyncBattle(), _ => { }, + interaction: new BattleHudInteractionProfile(Touch)); + HotControl = GUIUtility.hotControl; + if (Event.current.type == EventType.Repaint) + { + Tooltip = GUI.tooltip; + Repaints++; + } + } + } + + [SetUp] + public void SetUp() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + Assert.That(Directory.Exists(root), Is.True); + _session = new BattleEditorSession(); + _session.Load(root, 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = _session.Data.Scenes.First(), + DataFingerprint = _session.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush, + Music = "NONE" + }; + BattleParticipant ally = _session.Data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water); + ally.Vitals[2] = 0; + _magicSkill = ally.Skills.First(skill => + { + var info = _session.Data.Database.SkillInfos[skill.Id]; + return (int)info.Type is >= 1 and <= 3 && info.ElementAttributes.Count == 1 && info.MpConsumeValue > 0; + }).Id; + ally.Skills.Clear(); + ally.Skills.Add(new BattleSkill { Id = _magicSkill, Level = 4, Mastered = true }); + scenario.Participants.Add(ally); + int enemy = _session.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(_session.Data, id)); + scenario.Participants.Add(_session.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + _session.StartBattle(scenario); + _session.Preview.Audio.Muted = _session.Preview.Effects.Muted = true; + _canvas = new Canvas(_session); + _canvas.Hud.Presenter.Synchronize(_session.Battle); + } + + [TearDown] + public void TearDown() + { + _canvas?.Dispose(); + _session?.Dispose(); + } + + private T Field(string name) => (T)typeof(BattleHudView).GetField(name, Members).GetValue(_canvas.Hud); + + [Test] + public void EmptyAndDisabledDescriptionsStayInTheBottomStripWithReadableHoverText() + { + BattleHudPresenter presenter = _canvas.Hud.Presenter; + presenter.Open(BattleHudPage.Magic); + int category = -1; + for (int index = 0; index < 6; index++) + { + presenter.SetCategory(index); + if (presenter.Abilities().Any(row => row.Definition.Id == _magicSkill)) + { + category = index; + break; + } + } + Assert.That(category, Is.GreaterThanOrEqualTo(0)); + presenter.SetCategory((category + 1) % 6); + _canvas.Paint(); + Assert.That(presenter.Abilities(), Is.Empty); + Assert.That(Field("_descriptionText"), Is.EqualTo("此分类没有可用条目")); + Rect strip = Field("_descriptionRect"); + Assert.That(strip.yMin, Is.EqualTo(BattleData.Variant == "PAL3A" ? 460 : 454)); + Assert.That(strip.height, Is.EqualTo(BattleData.Variant == "PAL3A" ? 16 : 20)); + Object.DestroyImmediate(Capture("empty-category")); + presenter.SetCategory(category); + _canvas.Paint(); + BattleHudAbility row = presenter.Abilities().Single(); + Assert.That(row.Denied, Does.StartWith("Resource 2:")); + Rect panel = BattleHudText.AbilityPanelBounds(BattleHudPage.Magic, BattleData.Variant == "PAL3A"); + Rect list = BattleHudText.ListBounds(BattleHudPage.Magic, BattleData.Variant == "PAL3A"); + Rect ink = new Rect(_canvas.Area.position + panel.position + list.position + new Vector2(5, 3), new Vector2(80, 13)); + _canvas.Pointer = Vector2.zero; + _canvas.Paint(); + Texture2D normal = Capture("disabled-normal"); + int normalInk; + try + { + normalInk = DarkPixels(normal, ink); + } + finally { Object.DestroyImmediate(normal); } + Assert.That(normalInk, Is.GreaterThan(20)); + Vector2 point = _canvas.Area.position + panel.position + list.position + new Vector2(30, 9); + _canvas.Pointer = point; + _canvas.SendEvent(new Event { type = EventType.MouseMove, mousePosition = point }); + _canvas.Paint(); + Assert.That(Field("_descriptionText"), Does.StartWith("神不足")); + Assert.That(Field("_descriptionText"), Does.Not.Contain("Resource")); + Assert.That(Field("_descriptionTooltip"), Does.Contain("需要").And.Contain("当前")); + Assert.That(_canvas.Tooltip, Does.Contain("需要").And.Contain("当前"), "The full denial must be available while hovering the disabled row, without moving to the description strip."); + Assert.That(BattleHudText.DescriptionFontSize, Is.EqualTo(14)); + Texture2D capture = Capture("disabled-hover"); + try + { + // Exclude the native grid lines and name/cost separator. + Assert.That(DarkPixels(capture, ink), Is.GreaterThan(normalInk * .7f), "Hover text must remain dark on the pale native list, rather than switching to white."); + } + finally { Object.DestroyImmediate(capture); } + _canvas.Pointer = _canvas.Area.position + panel.position + list.position + new Vector2(115, 9); + _canvas.Paint(); + Assert.That(_canvas.Tooltip, Does.Contain("需要").And.Contain("当前"), "The denial tooltip must cover the cost column as well as the skill name."); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void OutsideTapRetiresSecondaryAndDisabledGestureTails() + { + var hud = _canvas.Hud; + Vector2 outside = _canvas.Area.position + new Vector2(620, 170); + hud.Presenter.Open(BattleHudPage.Magic); + _canvas.Paint(); + hud.SendPointer(BattleHudIntentKind.PointerDown, 1, outside); + hud.SendPointer(BattleHudIntentKind.PointerDown, 2, outside); + Assert.That(hud.SendPointer(BattleHudIntentKind.PointerUp, 1, outside), Is.True); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(hud.SendPointer(BattleHudIntentKind.PointerMove, 2, outside + Vector2.right * 40), Is.True, "A swallowed second touch must not leak a camera drag after the first touch closes the menu."); + Assert.That(hud.SendPointer(BattleHudIntentKind.PointerUp, 2, outside), Is.True); + hud.Presenter.Open(BattleHudPage.Magic); + _canvas.Paint(); + hud.SendPointer(BattleHudIntentKind.PointerDown, 3, outside); + _canvas.Enabled = false; + _canvas.Paint(); + _canvas.Enabled = true; + _canvas.Paint(); + Assert.That(hud.SendPointer(BattleHudIntentKind.PointerUp, 3, outside), Is.True); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic), "A gesture invalidated during disabled input cannot dismiss a resumed menu."); + hud.SendPointer(BattleHudIntentKind.PointerDown, 3, outside); + hud.SendPointer(BattleHudIntentKind.PointerUp, 3, outside); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands), "A fresh gesture may reuse an old pointer ID."); + hud.Presenter.Open(BattleHudPage.Magic); + _canvas.Paint(); + hud.SendPointer(BattleHudIntentKind.PointerDown, 4, outside); + hud.SendPointer(BattleHudIntentKind.PointerMove, 4, outside + Vector2.right * 40); + // The old release happened outside the host. A fresh Down must + // reset the drag state even when focus and the pointer ID survive. + hud.SendPointer(BattleHudIntentKind.PointerDown, 4, outside); + hud.SendPointer(BattleHudIntentKind.PointerUp, 4, outside); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void TouchListLeavesTheNativeScrollbarDragAndReleaseWithItsOwner() + { + BattleScenario scenario = _session.CapturedScenario; + scenario.Items = _session.Data.Database.GameItemInfos.Values.Where(item => (int)item.Type == 1) + .Take(20).Select(item => new BattleItem { Id = checked((int)item.Id), Count = 1 }).ToList(); + Assert.That(scenario.Items.Count, Is.GreaterThan(8)); + _session.StartBattle(scenario); + _canvas.Touch = true; + _canvas.Hud.Presenter.Synchronize(_session.Battle); + _canvas.Hud.Presenter.Open(BattleHudPage.Items); + _canvas.Paint(); + Assert.That(Field("_touchScrollLimit"), Is.GreaterThan(0)); + Rect list = Field("_touchPanel"); + Vector2 point = new(list.xMax - 1, list.center.y); + _canvas.SendEvent(new Event { type = EventType.MouseDown, button = 0, mousePosition = point }); + int scrollbar = _canvas.HotControl; + Assert.That(scrollbar, Is.Not.Zero, "The real GUI scrollbar must capture this press before testing its release."); + Assert.That(Field("_guiCapturedControl"), Is.Zero, "Scrollbar input belongs to Unity's native control."); + _canvas.SendEvent(new Event { type = EventType.MouseDrag, button = 0, mousePosition = point + Vector2.down * 24 }); + Assert.That(_canvas.HotControl, Is.EqualTo(scrollbar)); + _canvas.SendEvent(new Event { type = EventType.MouseUp, button = 0, mousePosition = point + Vector2.down * 24 }); + Assert.That(Field("_touchCandidatePointer"), Is.Null); + Assert.That(_canvas.HotControl, Is.Zero, "Touch panning must not swallow the native scrollbar's release."); + Assert.That(_canvas.Hud.Presenter.CapturedPointerId, Is.Null); + Assert.That(_canvas.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Items)); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void RightEdgeOfNativeMagicScrollbarIsInsideTheMenu() + { + _canvas.Hud.Presenter.Open(BattleHudPage.Magic); + _canvas.Paint(); + // PAL3A's real list ends at native X=263, four pixels beyond its + // panel sprite. This point must not be treated as a background tap. + float x = BattleData.Variant == "PAL3A" ? 261 : 248; + float y = BattleData.Variant == "PAL3A" ? 356 : 374; + Vector2 point = _canvas.Area.position + new Vector2(x, y); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 17, point); + Assert.That(Field("_outsidePointer"), Is.Null); + _canvas.Hud.SendPointer(BattleHudIntentKind.PointerUp, 17, point); + Assert.That(_canvas.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Magic)); + Object.DestroyImmediate(Capture("scrollbar-edge")); + _canvas.Hud.Presenter.Open(BattleHudPage.Commands); + Assert.That(_canvas.Hud.Presenter.SetFocus("magic"), Is.True); + _canvas.Pointer = Vector2.zero; + _canvas.Paint(); + Texture2D image = Capture("native-focus"); + try + { + Vector2 scale = new(image.width / Canvas.Size.x, image.height / Canvas.Size.y); + int gold = 0; + for (int edge = 0; edge < 4; edge++) + for (int offset = 0; offset < 46; offset++) + { + Vector2 local = new(12 + (edge < 2 ? offset : edge == 2 ? 0 : 45), 378 + (edge < 2 ? edge * 45 : offset)); + Vector2 pixel = Vector2.Scale(_canvas.Area.position + local, scale); + Color color = image.GetPixel(Mathf.FloorToInt(pixel.x), image.height - 1 - Mathf.FloorToInt(pixel.y)); + if (color.r > .7f && color.g > .55f && color.b < .47f) + gold++; + } + Assert.That(gold, Is.LessThan(48), "Native focus may change the circular sprite, but must not add a gold rectangular outline around it."); + } + finally { Object.DestroyImmediate(image); } + LogAssert.NoUnexpectedReceived(); + } + + private static int DarkPixels(Texture2D image, Rect gui) + { + Vector2 scale = new(image.width / Canvas.Size.x, image.height / Canvas.Size.y); + int count = 0; + for (int y = Mathf.CeilToInt(gui.yMin * scale.y); y < gui.yMax * scale.y; y++) + for (int x = Mathf.CeilToInt(gui.xMin * scale.x); x < gui.xMax * scale.x; x++) + { + Color pixel = image.GetPixel(x, image.height - 1 - y); + if (pixel.a > .8f && pixel.r < .55f && pixel.g < .55f && pixel.b < .55f) + count++; + } + return count; + } + + private Texture2D Capture(string name) + { + _canvas.Paint(); + RenderTexture buffer = _canvas.RenderTarget; + Assert.That(buffer, Is.Not.Null); + var image = new Texture2D(buffer.width, buffer.height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = buffer; + image.ReadPixels(new Rect(0, 0, buffer.width, buffer.height), 0, 0); + image.Apply(); + string root = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (!string.IsNullOrEmpty(root)) + { + string folder = Path.Combine(root, "HudPolish"); + Directory.CreateDirectory(folder); + File.WriteAllBytes(Path.Combine(folder, BattleData.Variant + "-" + name + ".png"), image.EncodeToPNG()); + } + return image; + } + finally { RenderTexture.active = previous; } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudPolishTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudPolishTests.cs.meta new file mode 100644 index 00000000..74c98d09 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudPolishTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e0a9aa89ee604fee95fd227567f71f0c diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudRenderingTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudRenderingTests.cs new file mode 100644 index 00000000..104746da --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudRenderingTests.cs @@ -0,0 +1,304 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using ResourceBrowser; + using UnityEditor; + using UnityEngine; + using UnityEngine.TestTools; + + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleHudRenderingTests + { + private sealed class Canvas : IDisposable + { + public static readonly Vector2 Size = new(1320, 920); + private readonly OffscreenGui _gui; + + public readonly BattleEditorSession Editor; + public readonly BattleHudView View = new(); + public Rect Area; + public bool Touch; + public bool Enabled = true, InputFocus = true; + public int Downs; + public int Repaints; + public bool BottomVisible, Restored; + public bool PixelOracle; + public Rect Clip; + + public Canvas(BattleEditorSession editor) + { + Editor = editor; + _gui = new OffscreenGui(Draw); + } + + public void Paint() + { + int before = Repaints; + _gui.Paint(Size); + Assert.That(Repaints, Is.GreaterThan(before), "The real IMGUI view must repaint."); + } + + public void SendEvent(Event input) => _gui.SendEvent(input, Size); + + public void Dispose() => _gui.Dispose(); + + private void Draw() + { + if (Editor?.Battle == null) + return; + if (Event.current.type == EventType.MouseDown) + Downs++; + Editor.Preview.View.SetViewportContext(Area); + View.SetInputFocus(InputFocus); + var viewport = new BattleHudViewport(Area, new Vector4(13, 9, 17, 11)); + if (PixelOracle) + EditorGUI.DrawRect(Area, new Color(0, .65f, .2f)); + Matrix4x4 matrix = GUI.matrix; + Color color = GUI.color; + using (new EditorGUI.DisabledScope(!Enabled)) + View.Draw(Editor.Battle, Editor.Data, Editor.Preview, Area, () => { }, _ => { }, new Vector4(13, 9, 17, 11), interaction: new BattleHudInteractionProfile(Touch)); + Restored = GUI.matrix == matrix && GUI.color == color; + using (new BattleHudCanvas(viewport)) + { + Type clip = typeof(GUI).Assembly.GetType("UnityEngine.GUIClip"); + Clip = (Rect)clip.GetProperty("visibleRect", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null); + BottomVisible = Clip.Contains(new Vector2(viewport.CanvasSize.x - 5, viewport.CanvasSize.y - 5)); + } + if (Event.current.type == EventType.Repaint) + Repaints++; + } + } + + private static string DataRoot() + { + string configured = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root) && configured == null) + Assert.Ignore("Original local data unavailable."); + return root; + } + + [Test] + public void ActualHudRestoresGuiStateAndKeepsBottomControlsInsideTheScaledClip() + { + using var editor = new BattleEditorSession(); + editor.Load(DataRoot(), 936); + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = editor.Data.Scenes.First(), DataFingerprint = editor.Data.Fingerprint, Encounter = BattleEncounter.AllyAmbush }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + foreach (BattleState state in new[] { BattleState.AttackIncrease, BattleState.DefenseIncrease, BattleState.SpeedIncrease, BattleState.LuckIncrease }) + scenario.Participants[0].Statuses.Add(new BattleStatus { Id = (int)state, Rounds = 9 }); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + using var canvas = new Canvas(editor); + foreach (bool touch in new[] { false, true }) + foreach (Vector2 size in new[] { new Vector2(600, 450), new Vector2(880, 660) }) + { + canvas.Touch = touch; + canvas.Area = new Rect(new Vector2(40, 70), size); + canvas.Paint(); + Assert.That(canvas.Restored, Is.True, "HUD rendering must restore the caller's matrix and color."); + Assert.That(canvas.BottomVisible, Is.True, "The shared production canvas cut its bottom/right controls: " + canvas.Clip); + } + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void AbilityMenusUseOutsideTapsWithoutAnInvisibleBackControl() + { + using var editor = new BattleEditorSession(); + editor.Load(DataRoot(), 936); + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = editor.Data.Scenes.First(), DataFingerprint = editor.Data.Fingerprint, Encounter = BattleEncounter.AllyAmbush }; + scenario.Participants.Add(editor.Data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + using var canvas = new Canvas(editor); + canvas.View.Presenter.Synchronize(editor.Battle); + foreach (bool touch in new[] { false, true }) + foreach (Rect area in new[] { new Rect(40, 70, 800, 600), new Rect(21, 110, 1050, 450), new Rect(40, 70, 700, 700) }) + foreach (Battle.Presentation.BattleHudPage page in new[] { Battle.Presentation.BattleHudPage.Skills, Battle.Presentation.BattleHudPage.Magic, Battle.Presentation.BattleHudPage.Items }) + { + canvas.Touch = touch; + canvas.Area = area; + canvas.View.Presenter.Open(page); + canvas.Paint(); + var controls = (System.Collections.Generic.List<(string Id, Rect Rect)>)typeof(BattleHudView).GetField("_hitControls", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(canvas.View); + Assert.That(controls.Any(control => control.Id == "back"), Is.False); + Assert.That(canvas.View.Presenter.FocusItems().Any(control => control.Id == "back"), Is.False); + var viewport = new BattleHudViewport(area, new Vector4(13, 9, 17, 11)); + Vector2 outside = viewport.ToViewport(new Vector2(viewport.CanvasSize.x - 20, 150)); + int inputs = editor.Battle.Inputs.Count; + Assert.That(canvas.View.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerDown, 71, outside), Is.True); + Assert.That(canvas.View.Presenter.Page, Is.EqualTo(page), "A tap confirms on release."); + Assert.That(canvas.View.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerDown, 72, outside), Is.True); + Assert.That(canvas.View.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerUp, 72, outside), Is.True); + Assert.That(canvas.View.Presenter.Page, Is.EqualTo(page), "A second finger cannot cancel the captured tap."); + Assert.That(canvas.View.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerUp, 71, outside), Is.True); + Assert.That(canvas.View.Presenter.Page, Is.EqualTo(Battle.Presentation.BattleHudPage.Commands)); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(inputs), "Closing a menu must not issue a parent-page battle command."); + canvas.View.Presenter.Open(page); + canvas.Paint(); + canvas.View.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerDown, 73, outside); + canvas.View.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerMove, 73, outside + new Vector2(30, 0)); + canvas.View.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerUp, 73, outside + new Vector2(30, 0)); + Assert.That(canvas.View.Presenter.Page, Is.EqualTo(page), "An outside drag is not a tap."); + canvas.View.SendIntent(new Battle.Presentation.BattleHudIntent(Battle.Presentation.BattleHudIntentKind.Back)); + Assert.That(canvas.View.Presenter.Page, Is.EqualTo(Battle.Presentation.BattleHudPage.Commands)); + } + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void ClippedItemRowsCannotReceivePointerInputUntilScrolledIntoView() + { + using var editor = new BattleEditorSession(); + editor.Load(DataRoot(), 936); + bool pal3A = BattleData.Variant == "PAL3A"; + Rect list = BattleHudText.ListBounds(Battle.Presentation.BattleHudPage.Items, pal3A); + int hiddenIndex = Mathf.CeilToInt(list.height / 19); + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = editor.Data.Scenes.First(), DataFingerprint = editor.Data.Fingerprint, Encounter = BattleEncounter.AllyAmbush }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + scenario.Items = editor.Data.Database.GameItemInfos.Values.Where(item => item.Type == Core.Contract.Enums.ItemType.Healing && item.Id != 6201) + .Take(hiddenIndex).Select(item => new BattleItem { Id = checked((int)item.Id) }).ToList(); + Assert.That(scenario.Items.Count, Is.EqualTo(hiddenIndex)); + scenario.Items.Add(new BattleItem { Id = 6201 }); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + using var canvas = new Canvas(editor); + canvas.Area = new Rect(40, 70, 800, 600); + canvas.View.Presenter.Synchronize(editor.Battle); + canvas.View.Presenter.Open(Battle.Presentation.BattleHudPage.Items); + Assert.That(canvas.View.Presenter.Abilities()[hiddenIndex].Definition.Id, Is.EqualTo(6201)); + Assert.That(canvas.View.Presenter.Abilities()[hiddenIndex].Denied, Is.Null); + Assert.That(canvas.View.Presenter.SetFocus("category:0"), Is.True); + canvas.Paint(); + var viewport = new BattleHudViewport(canvas.Area, new Vector4(13, 9, 17, 11)); + Vector2 panel = new(10, pal3A ? 258 : 278); + Vector2 hiddenRow = panel + list.position + new Vector2(30, hiddenIndex * 19 + 9); + Vector2 canvasPoint = hiddenRow + new Vector2(0, viewport.CanvasSize.y - 600); + Vector2 point = viewport.ToViewport(canvasPoint); + canvas.SendEvent(new Event { type = EventType.MouseDown, button = 0, mousePosition = point }); + canvas.SendEvent(new Event { type = EventType.MouseUp, button = 0, mousePosition = point }); + Assert.That(canvas.View.Presenter.Page, Is.EqualTo(Battle.Presentation.BattleHudPage.Items), "The clipped row below the list must not activate through a drawing fallback."); + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; + typeof(BattleHudView).GetField("_listScroll", flags).SetValue(canvas.View, new Vector2(0, hiddenIndex * 19)); + canvas.Paint(); + var controls = (System.Collections.Generic.List<(string Id, Rect Rect)>)typeof(BattleHudView).GetField("_hitControls", flags).GetValue(canvas.View); + Rect visible = controls.Single(control => control.Id == "ability:6201").Rect; + point = viewport.ToViewport(visible.center); + canvas.SendEvent(new Event { type = EventType.MouseDown, button = 0, mousePosition = point }); + Assert.That(canvas.View.Presenter.Page, Is.EqualTo(Battle.Presentation.BattleHudPage.Items), "Pointer-down only captures; release confirms the same native control."); + canvas.SendEvent(new Event { type = EventType.MouseUp, button = 0, mousePosition = point }); + Assert.That(canvas.View.Presenter.Page, Is.EqualTo(Battle.Presentation.BattleHudPage.Targets)); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void UnfocusedTargetPointerCannotBypassTheViewInputGate() => CheckTargetInputGate(false, true); + + [Test] + public void DisabledTargetPointerCannotBypassTheViewInputGate() => CheckTargetInputGate(true, false); + + private static void CheckTargetInputGate(bool focus, bool enabled) + { + using var editor = new BattleEditorSession(); + editor.Load(DataRoot(), 936); + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = editor.Data.Scenes.First(), DataFingerprint = editor.Data.Fingerprint, Encounter = BattleEncounter.AllyAmbush }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemyId = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemyId, BattleSide.Enemy, BattleSlot.Water)); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + using var canvas = new Canvas(editor); + canvas.InputFocus = focus; + canvas.Enabled = enabled; + canvas.Area = new Rect(40, 70, 800, 600); + canvas.View.Presenter.Synchronize(editor.Battle); + Assert.That(canvas.View.Presenter.ChooseAction(BattleAction.Attack), Is.True); + canvas.Paint(); + BattleActorSnapshot enemy = editor.Battle.Actors.First(actor => actor.Side == BattleSide.Enemy); + Assert.That(editor.Preview.View.Project(BattleAnimationCatalog.UnityPosition(enemy.Position) + Vector3.up, canvas.Area, out Vector2 point), Is.True); + int before = editor.Battle.Inputs.Count; + canvas.SendEvent(new Event { type = EventType.MouseDown, button = 0, mousePosition = point }); + Assert.That(canvas.Downs, Is.GreaterThan(0)); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(before), "An unfocused/disabled view must block target input."); + canvas.Enabled = canvas.InputFocus = true; + canvas.SendEvent(new Event { type = EventType.MouseDown, button = 0, mousePosition = point }); + canvas.SendEvent(new Event { type = EventType.MouseUp, button = 0, mousePosition = point }); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(before + 1), "The exact same point must submit when enabled, validating the negative test."); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void RealAttackPortraitAndProgressBottomPixelsSurviveTheProductionSpriteCrop() + { + using var data = new BattleData(DataRoot(), 936); + using var preview = new ResourceModelPreview(data.Resources, false); + var layout = new BattleHudLayout(BattleData.Variant); + foreach ((string resource, int width, int height) in new[] + { + ("control/attack0", 46, 46), (layout.StateFace(0), 64, layout.IsPal3A ? 93 : 82), ("state/ProgBar_HP", 85, 12) + }) + { + Texture2D original = preview.GetTexture("basedata.cpk\\ui\\combat\\" + resource.Replace('/', '\\') + ".tga"); + Color32[] source = original.GetPixels32(); + var opaque = Enumerable.Range(0, source.Length).Where(index => source[index].a > 200).ToArray(); + Assert.That(opaque.Length, Is.GreaterThan(8), resource); + int bottom = opaque.Min(index => index / original.width); + int top = opaque.Max(index => index / original.width); + int band = bottom + Math.Max(1, (top - bottom + 1) / 4); + // The oracle comes from the complete original bitmap's opaque + // ink bounds, independently of the production UV calculation. + int[] samples = opaque.Where(index => index % original.width < width && index / original.width < height && index / original.width < band).ToArray(); + Assert.That(samples.Length, Is.GreaterThan(8), resource); + Rect uv = BattleHudCanvas.SpriteUv(original, new Vector2(width, height)); + var target = new RenderTexture(width * 2, height * 2, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); + var pixels = new Texture2D(width * 2, height * 2, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + FilterMode filter = original.filterMode; + try + { + target.Create(); + original.filterMode = FilterMode.Point; + Graphics.Blit(original, target, uv.size, uv.position); + RenderTexture.active = target; + pixels.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0); + pixels.Apply(); + Color32[] actual = pixels.GetPixels32(); + int matched = samples.Count(index => + { + int x = index % original.width, y = index / original.width; + Color32 expected = source[index], found = actual[(y * 2 + 1) * target.width + x * 2 + 1]; + return found.a > 200 && Math.Abs(found.r - expected.r) < 48 && Math.Abs(found.g - expected.g) < 48 && Math.Abs(found.b - expected.b) < 48; + }); + Assert.That(matched / (double)samples.Length, Is.GreaterThan(.9), resource + " lost the native bitmap's bottom pixels."); + } + finally + { + original.filterMode = filter; + RenderTexture.active = previous; + UnityEngine.Object.DestroyImmediate(target); + UnityEngine.Object.DestroyImmediate(pixels); + } + } + LogAssert.NoUnexpectedReceived(); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudRenderingTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudRenderingTests.cs.meta new file mode 100644 index 00000000..026eacc1 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudRenderingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9522ff26466544d890966e6653e561cb diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudResourceTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudResourceTests.cs new file mode 100644 index 00000000..f7eac67d --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudResourceTests.cs @@ -0,0 +1,318 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using NUnit.Framework; + using Core.DataReader.Cvd; + using Battle; + using System.Linq; + using ResourceBrowser; + using UnityEngine; + + [Category("LocalGameData")] + public sealed class BattleHudResourceTests + { + [Test] + public void CompositeCvdDoesNotFrameOrJoinStandaloneSamplingAndRollsBackFailure() + { + using var preview = new ResourceModelPreview(null, false); + preview.SetCamera(new Vector3(11, 12, 13), new Vector3(2, 3, 4), 54); + preview.GetCamera(out Vector3 beforePosition, out Vector3 beforeTarget, out float beforeFov); + GameObject target = preview.CreateObject("CVD owner"); + var renderer = preview.SetHierarchicalModel(target, "fixture.cvd", new CvdFile(5, Array.Empty())); + renderer.SetCurrentTime(3); + preview.Sample(12); + Assert.That(renderer.GetCurrentAnimationTime(), Is.EqualTo(3)); + Assert.That(preview.Duration, Is.Zero); + preview.GetCamera(out Vector3 position, out Vector3 aim, out float fov); + Assert.That(position, Is.EqualTo(beforePosition)); + Assert.That(aim, Is.EqualTo(beforeTarget)); + Assert.That(fov, Is.EqualTo(beforeFov)); + Assert.Throws(() => preview.SetHierarchicalModel(target, "bad.cvd", new CvdFile(1, null))); + Assert.That(target.GetComponentsInChildren().Length, Is.EqualTo(1)); + Assert.That(renderer == null, Is.False); + preview.ReleaseCompositeObject(target); + Assert.That(renderer == null, Is.True); + Assert.That(target == null, Is.True); + preview.Dispose(); + Assert.Throws(() => preview.SetHierarchicalModel(target, "fixture.cvd", new CvdFile(1, Array.Empty()))); + } + + [TestCase(false)] + [TestCase(true)] + public void PointerCvdFollowsThePreviewOwnerAcrossRestartAndNeverSamplesDisposedModels(bool toon) + { + string configured = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root) && configured == null) + Assert.Ignore("Original local data unavailable."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = editor.Data.Scenes.First(), + DataFingerprint = editor.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + scenario.ToonRendering = toon; + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + var hud = new BattleHudView(); + hud.PreparePointers(editor.Battle, editor.Data, editor.Preview); + string name = "Battle selection pointer " + scenario.Participants[0].InstanceId; + Transform oldPointer = editor.Preview.View.Root.transform.Find(name); + Assert.That(oldPointer, Is.Not.Null); + bool nativePhase = !toon && Pal3.Game.Rendering.Native.GameBoxBattleRenderOrder.Actor(BattleData.Variant == "PAL3A", true, 101) > 0; + Assert.That(oldPointer.GetComponent() != null, Is.EqualTo(nativePhase)); + foreach (Material material in oldPointer.GetComponentsInChildren().SelectMany(renderer => renderer.sharedMaterials)) + { + int expectedQueue = nativePhase ? material.shader.renderQueue <= 2500 ? 3002 : 3003 : material.shader.renderQueue; + Assert.That(material.renderQueue, Is.EqualTo(expectedQueue)); + if (toon && material.renderQueue <= 2500) + Assert.That(material.FindPass("DepthNormals"), Is.GreaterThanOrEqualTo(0)); + } + var mesh = oldPointer.GetComponentInChildren().sharedMesh; + hud.Presenter.Open(Battle.Presentation.BattleHudPage.Skills); + hud.PreparePointers(editor.Battle, editor.Data, editor.Preview); + hud.Presenter.Back(); + hud.PreparePointers(editor.Battle, editor.Data, editor.Preview); + Assert.That(oldPointer.GetComponentInChildren().sharedMesh, Is.SameAs(mesh)); + BattlePreview previous = editor.Preview; + BattleSession previousCombat = editor.Battle; + editor.Restart(); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + Assert.That(oldPointer == null, Is.True); + Assert.DoesNotThrow(() => hud.PreparePointers(previousCombat, editor.Data, previous)); + Assert.DoesNotThrow(() => hud.PreparePointers(editor.Battle, editor.Data, editor.Preview)); + Assert.That(editor.Preview.View.Root.transform.Find(name), Is.Not.Null); + } + + [TestCase(false)] + [TestCase(true)] + public void PointerFormationGestureCommitsOneSwapAndOnlyConfirmationSpendsTheControllerGauge(bool externalEntry) + { + string configured = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root) && configured == null) + Assert.Ignore("Original local data unavailable."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = editor.Data.Scenes.First(), + DataFingerprint = editor.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(editor.Data.CreateParticipant(BattleData.Variant == "PAL3" ? 104 : 102, BattleSide.Ally, BattleSlot.Fire)); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + var view = new BattleHudView(); + var presenter = view.Presenter; + presenter.Synchronize(editor.Battle); + string controller = presenter.Controller; + string moved = scenario.Participants[1].InstanceId; + int gauge = editor.Battle.Actors.First(actor => actor.Id == controller).Gauge; + Assert.That(editor.Battle.CanBeginFormation(controller), Is.Null); + if (externalEntry) + { + Assert.That(presenter.ChooseAction(BattleAction.Attack), Is.True); + string target = presenter.Target; + Assert.That(target, Is.Not.Null); + Assert.That(presenter.Handle(new Battle.Presentation.BattleHudIntent(Battle.Presentation.BattleHudIntentKind.PointerDown, "target:" + target, 37)), Is.True); + Assert.That(presenter.CapturedPointerId, Is.EqualTo(37)); + Assert.That(editor.Battle.BeginFormation(controller), Is.True); + presenter.Synchronize(editor.Battle); + Assert.That(presenter.CapturedPointerId, Is.Null); + Assert.That(presenter.Target, Is.Null); + } + else + { + Assert.That(presenter.Handle(new Battle.Presentation.BattleHudIntent(Battle.Presentation.BattleHudIntentKind.Confirm, "formation")), Is.True); + } + int before = editor.Battle.Inputs.Count; + void Set(string name, object value) => typeof(BattleHudView).GetField(name, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(view, value); + Set("_battle", editor.Battle); + Set("_inputEnabled", true); + Set("_interaction", new BattleHudInteractionProfile(true)); + Set("_viewport", new BattleHudViewport(new Rect(0, 0, 800, 600), default)); + var hits = (List<(string, Rect)>)typeof(BattleHudView).GetField("_hitControls", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(view); + hits.Add(("slot:1", new Rect(100, 100, 40, 38))); + hits.Add(("actor:" + moved, new Rect(100, 100, 40, 38))); + hits.Add(("slot:2", new Rect(180, 100, 40, 38))); + + Assert.That(view.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerDown, 9, new Vector2(120, 119)), Is.True); + view.SetInputFocus(false); + Assert.That(presenter.FormationActor, Is.Null, "Losing input focus must release the dragged actor along with its pointer."); + Assert.That(presenter.CapturedPointerId, Is.Null); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(before)); + view.SetInputFocus(true); + Assert.That(view.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerDown, 9, new Vector2(120, 119)), Is.True); + Assert.That(presenter.CapturedPointerId, Is.EqualTo(9)); + view.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerMove, 9, new Vector2(200, 119)); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(before)); + Assert.That(editor.Battle.Actors.First(actor => actor.Id == controller).Gauge, Is.EqualTo(gauge)); + Assert.That(view.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerUp, 9, new Vector2(200, 119)), Is.True); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(before + 1)); + Assert.That(editor.Battle.Actors.First(actor => actor.Id == moved).Slot, Is.EqualTo(BattleSlot.Wind)); + Assert.That(view.SendPointer(Battle.Presentation.BattleHudIntentKind.PointerUp, 9, new Vector2(200, 119)), Is.False); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(before + 1)); + Assert.That(presenter.Handle(new Battle.Presentation.BattleHudIntent(Battle.Presentation.BattleHudIntentKind.Confirm, "end")), Is.True); + Assert.That(editor.Battle.Actors.First(actor => actor.Id == controller).Gauge, Is.Zero); + } + + [Test] + public void ProtectionDraftBackAndUnchangedConfirmationAreFreeWhileAChangedConfirmationPaysOnce() + { + string configured = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root) && configured == null) + Assert.Ignore("Original local data unavailable."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = editor.Data.Scenes.First(), DataFingerprint = editor.Data.Fingerprint, Encounter = BattleEncounter.AllyAmbush }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Center)); + scenario.Participants.Add(editor.Data.CreateParticipant(BattleData.Variant == "PAL3" ? 104 : 102, BattleSide.Ally, BattleSlot.Fire)); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + var presenter = new Battle.Presentation.BattleHudPresenter(); + presenter.Synchronize(editor.Battle); + string controller = presenter.Controller, target = scenario.Participants[1].InstanceId; + int before = editor.Battle.Inputs.Count; + presenter.Open(Battle.Presentation.BattleHudPage.Protection); + Assert.That(presenter.SetProtection(target), Is.True); + Assert.That(editor.Battle.ProtectionTarget, Is.Null); + presenter.Back(); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(before)); + presenter.Open(Battle.Presentation.BattleHudPage.Protection); + Assert.That(presenter.CommitProtection(), Is.True); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(before)); + Assert.That(editor.Battle.WaitingActor, Is.EqualTo(controller)); + presenter.Open(Battle.Presentation.BattleHudPage.Protection); + Assert.That(presenter.SetProtection(target), Is.True); + Assert.That(presenter.CommitProtection(), Is.True); + Assert.That(editor.Battle.ProtectionTarget, Is.EqualTo(target)); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(before + 1)); + Assert.That(editor.Battle.Inputs.Last().Kind, Is.EqualTo(BattleInputKind.SetProtection)); + Assert.That(editor.Battle.Actors.First(actor => actor.Id == controller).Gauge, Is.Zero); + } + +#if PAL3A + [Test] + public void ElementWheelHudUsesTheDedicatedNativeInputWithoutEnteringOrdinaryMagicTargets() + { + string configured = Environment.GetEnvironmentVariable("PAL3A_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data/PAL3A")); + if (!Directory.Exists(root) && configured == null) + Assert.Ignore("Original local data unavailable."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario { Variant = "PAL3A", Scene = editor.Data.Scenes.First(), DataFingerprint = editor.Data.Fingerprint, Encounter = BattleEncounter.AllyAmbush }; + scenario.Pal3A.SpiritWheel.Charges = new[] { 9, 9, 9, 9, 9 }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + var presenter = new Battle.Presentation.BattleHudPresenter(); + presenter.Synchronize(editor.Battle); + string controller = presenter.Controller; + BattleActorSnapshot before = editor.Battle.Actors.First(actor => actor.Id == controller); + int inputs = editor.Battle.Inputs.Count; + for (int attempt = 0; attempt < 10; attempt++) + Assert.That(presenter.WheelReason(267), Is.Null); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(inputs)); + var reached = new HashSet { presenter.FocusedId }; + var pending = new Queue(reached); + while (pending.Count > 0) + { + string from = pending.Dequeue(); + foreach (Battle.Presentation.BattleHudDirection direction in Enum.GetValues(typeof(Battle.Presentation.BattleHudDirection))) + { + presenter.SetFocus(from); + presenter.Handle(new Battle.Presentation.BattleHudIntent(Battle.Presentation.BattleHudIntentKind.Navigate, direction: direction)); + if (reached.Add(presenter.FocusedId)) + pending.Enqueue(presenter.FocusedId); + } + // The eight directions address the original command ring; + // shoulder buttons reach the separate wheel/special controls. + foreach (Battle.Presentation.BattleHudIntentKind kind in new[] { Battle.Presentation.BattleHudIntentKind.CyclePrevious, Battle.Presentation.BattleHudIntentKind.CycleNext }) + { + presenter.SetFocus(from); + presenter.Handle(new Battle.Presentation.BattleHudIntent(kind)); + if (reached.Add(presenter.FocusedId)) + pending.Enqueue(presenter.FocusedId); + } + } + Assert.That(Enumerable.Range(264, 5).All(id => reached.Contains("wheel:" + id)), Is.True, "All native wheel controls must be reachable through command navigation and shoulder buttons."); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(inputs), "Browsing the ring and wheel must not submit a battle input."); + Assert.That(presenter.Handle(new Battle.Presentation.BattleHudIntent(Battle.Presentation.BattleHudIntentKind.Confirm, "wheel:267")), Is.True); + Assert.That(presenter.Page, Is.EqualTo(Battle.Presentation.BattleHudPage.Commands)); + Assert.That(editor.Battle.Inputs.Last().Kind, Is.EqualTo(BattleInputKind.ElementWheel)); + Assert.That(editor.Battle.Inputs.Last().AbilityId, Is.EqualTo(267)); + Assert.That(editor.Battle.Inputs.Last().Target, Is.Null); + BattleActorSnapshot after = editor.Battle.Actors.First(actor => actor.Id == controller); + Assert.That((after.Sp, after.Mp), Is.EqualTo((before.Sp, before.Mp))); + } +#endif + + [Test] + public void ReleasedHudProfilesResolveRealResourcesAndBorrowThePreviewTextureCache() + { + string configured = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root) && configured == null) + Assert.Ignore("Original local data unavailable."); + using var data = new BattleData(root, 936); + using var preview = new ResourceModelPreview(data.Resources, false); + var layout = new BattleHudLayout(BattleData.Variant); + var paths = new List { "state/StatePanel", "state/ProgBar", "state/ProgBar_HP", "state/ProgBar_GP", "state/ProgBar_MP", + "AttackSequen/Back", "control/back", "control/ItemList/ItemPanel", "control/MagicList/MagicPanel", "control/SkillList/SkillPanel", + "control/Lineup/back", "control/AI/back", "control/Protect/back" }; + if (!layout.IsPal3A) + paths.AddRange(new[] { "state/StatePanel0", "state/sword", "state/swordbar", "control/mj0", "control/mj1" }); + else + { + paths.AddRange(new[] { "control/bs0", "control/bs1", "control/wll", "control/unbs" }); + for (int element = 0; element < 5; element++) + { + paths.Add("control/wt" + element + "0"); + for (int tier = 0; tier < 3; tier++) + paths.Add("control/unwt" + element + tier); + } + } + foreach (int actorId in (layout.IsPal3A ? new[] { 101, 102, 103, 104, 105 } : new[] { 101, 104, 106, 107, 102 })) + paths.Add("attacksequen/" + data.Model(data.CreateParticipant(actorId, BattleSide.Ally, BattleSlot.Water))); + for (int identity = 0; identity < 5; identity++) + paths.AddRange(new[] { layout.StateFace(identity), layout.StateName(identity), layout.FormationFace(identity, false), + layout.FormationFace(identity, true), layout.AiName(identity) }); + foreach (string control in new[] { "attack", "skill", "magic", "item", "defence", "flee", "lineup", "ai", "protect" }) + for (int frame = 0; frame < 4; frame++) + paths.Add("control/" + control + frame); + foreach (string path in paths) + { + string original = "basedata.cpk\\ui\\combat\\" + path.Replace('/', '\\') + ".tga"; + Assert.That(data.Resources.Find(original), Is.Not.Null, original); + Texture2D first = preview.GetTexture(original); + Assert.That(first, Is.Not.SameAs(Texture2D.whiteTexture), original); + Assert.That(first.width, Is.GreaterThan(1), original); + Assert.That(preview.GetTexture(original), Is.SameAs(first), "HUD must borrow the cached resource: " + original); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudResourceTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudResourceTests.cs.meta new file mode 100644 index 00000000..c5ef1828 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudResourceTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d3406771b44f418ea81b43943e448c9c diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpiritReplayTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpiritReplayTests.cs new file mode 100644 index 00000000..8e288ea7 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpiritReplayTests.cs @@ -0,0 +1,106 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +#if PAL3A +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using Newtonsoft.Json; + using NUnit.Framework; + using UnityEngine; + + [Category("LocalGameData")] + public sealed class BattleHudSpiritReplayTests + { + [TestCase(true)] + [TestCase(false)] + public void Actual4102RecordingKeepsTicksEventsAndRandomStateAcrossResizeSafeAreasAndReplay(bool expand) + { + string root = Environment.GetEnvironmentVariable("PAL3A_TEST_DATA_ROOT"); + if (root == null || !Directory.Exists(root)) + Assert.Ignore("Original PAL3A data is required."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario + { + Variant = "PAL3A", + Scene = editor.Data.Scenes.First(), + DataFingerprint = editor.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(editor.Data.CreateParticipant(7311, BattleSide.Enemy, BattleSlot.Water)); + scenario.Participants.Add(editor.Data.CreateParticipant(7311, BattleSide.Enemy, BattleSlot.Fire)); + foreach (BattleParticipant actor in scenario.Participants) + { + actor.Attributes = new[] { 50000, 100, 1000, 5000, 1, 5, 0, 0, 0, 0, 0, 0 }; + actor.Vitals = new[] { 50000, 100, 1000 }; + actor.Skills.Clear(); + } + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 4102, Level = 4, Mastered = true }); + scenario.Participants[1].Vitals[0] = 1; + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = true; + editor.Preview.Effects.Muted = true; + editor.Preview.View.ExpandReferenceFraming = expand; + editor.Preview.View.SetViewportContext(new Rect(23, 41, 800, 600)); + string source = scenario.Participants[0].InstanceId; + string target = editor.Battle.GetTargetCandidates(new BattleCommand(source, BattleAction.Skill, abilityId: 4102)).First().Id; + Assert.That(editor.Battle.Submit(new BattleCommand(source, BattleAction.Skill, target, 4102)), Is.True); + for (int step = 0; step < 600 && editor.Battle.SpiritOrbs.Count == 0; step++) + editor.StepBattle(); + Assert.That(editor.Battle.SpiritOrbs.Count, Is.EqualTo(4)); + foreach (BattleSpiritOrbSnapshot orb in editor.Battle.SpiritOrbs) + Assert.That(orb.Origin.X, Is.EqualTo((int)orb.Origin.X)); + long appeared = editor.Battle.Tick; + int frame = 0; + while (editor.Battle.SpiritOrbs.Count > 0 && frame++ < 600) + { + Rect viewport = frame % 2 == 0 ? new Rect(37, 51, 1600, 900) : new Rect(17, 23, 2520, 1080); + var context = new BattleHudViewport(viewport, frame % 2 == 0 ? new Vector4(16, 12, 30, 8) : new Vector4(40, 20, 24, 18)); + editor.Preview.View.SetViewportContext(viewport); + foreach (BattleSpiritOrbSnapshot orb in editor.Battle.SpiritOrbs) + { + Vector2 display = context.SpiritOrbPoint(orb, editor.Preview.View.ReferenceProjectionScale(viewport)); + Assert.That(float.IsFinite(display.x) && float.IsFinite(display.y), Is.True); + } + editor.StepBattle(); + } + Assert.That(editor.Battle.SpiritOrbs, Is.Empty); + Assert.That(editor.Battle.Tick, Is.GreaterThan(appeared)); + long ended = editor.Battle.Tick; + string before = JsonConvert.SerializeObject(new + { + editor.Battle.Tick, + editor.Battle.SimulationTick, + editor.Battle.Events, + editor.Battle.Inputs, + editor.Battle.Pal3AState, + editor.Battle.Inventory, + editor.Battle.Actors + }); + editor.Preview.View.SetViewportContext(new Rect(111, 29, 320, 640)); + editor.ReplayBattle(); + editor.Preview.Audio.Muted = true; + editor.Preview.Effects.Muted = true; + Assert.That(editor.Battle.Tick, Is.EqualTo(ended)); + string after = JsonConvert.SerializeObject(new + { + editor.Battle.Tick, + editor.Battle.SimulationTick, + editor.Battle.Events, + editor.Battle.Inputs, + editor.Battle.Pal3AState, + editor.Battle.Inventory, + editor.Battle.Actors + }); + Assert.That(after, Is.EqualTo(before)); + } + } +} +#endif diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpiritReplayTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpiritReplayTests.cs.meta new file mode 100644 index 00000000..56ecb717 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpiritReplayTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 85a54b33205847b39e0bef913a7d0567 diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpriteRoutingTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpriteRoutingTests.cs new file mode 100644 index 00000000..e1c07309 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpriteRoutingTests.cs @@ -0,0 +1,310 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using UnityEditor; + using UnityEngine; + using UnityEngine.TestTools; + + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleHudSpriteRoutingTests + { + private static readonly Vector4 Insets = new(13, 9, 17, 11); + private static readonly Rect[] Areas = { new(30, 40, 1050, 450), new(30, 40, 800, 600), new(30, 40, 1000, 500), new(30, 40, 600, 600) }; + + private sealed class Canvas : IDisposable + { + public static readonly Vector2 Size = new(1200, 780); + private readonly OffscreenGui _gui; + + public readonly BattleEditorSession Editor; + public readonly BattleHudView Hud = new(); + public Rect Area; + public bool Touch; + public int ProbeCore = -1; + public int Repaints; + + public Canvas(BattleEditorSession editor) + { + Editor = editor; + _gui = new OffscreenGui(Draw); + } + + public RenderTexture RenderTarget => _gui.RenderTarget; + + public void Paint() + { + int before = Repaints; + _gui.Paint(Size); + Assert.That(Repaints, Is.GreaterThan(before), "The production Draw/RegisterControl path must repaint."); + } + + public void Dispose() => _gui.Dispose(); + + private void Draw() + { + if (Editor?.Battle == null) + return; + Editor.Preview.View.SetViewportContext(Area); + Hud.Draw(Editor.Battle, Editor.Data, Editor.Preview, Area, () => { }, _ => { }, Insets, + interaction: new BattleHudInteractionProfile(Touch)); + if (ProbeCore >= 0) + { + // Keep production Draw/RegisterControl, then isolate one + // asymmetric enabled sprite for a GPU-only pixel oracle. + EditorGUI.DrawRect(Area, Color.black); + int[] ids = { 264, 265, 267, 266, 268 }; + var control = Controls(this).LastOrDefault(control => control.Id == "wheel:" + ids[ProbeCore]); + if (control.Id != null) + { + var viewport = new BattleHudViewport(Area, Insets); + int ui = ProbeCore switch + { + 2 => 3, + 3 => 2, + _ => ProbeCore + }; + Texture2D sprite = Editor.Preview.View.GetTexture("basedata.cpk\\ui\\combat\\control\\wt" + (4 - ui) + "0.tga"); + Rect drawn = new(viewport.ToViewport(control.Rect.position), control.Rect.size * viewport.Scale); + BattleSpiritRect native = BattlePreview.SpiritWheelTarget(ProbeCore); + GUI.DrawTextureWithTexCoords(drawn, sprite, BattleHudCanvas.SpriteUv(sprite, + new Vector2(native.Right - native.Left, native.Bottom - native.Top)), true); + } + } + if (Event.current.type == EventType.Repaint) + Repaints++; + } + } + + private readonly struct SpriteOracle + { + public readonly Color32[] Pixels; + public readonly int Width; + public readonly Vector2 Size; + + public SpriteOracle(Texture2D texture, Vector2 size) + { + Pixels = texture.GetPixels32(); + Width = texture.width; + Size = new Vector2(Math.Min(size.x, texture.width), Math.Min(size.y, texture.height)); + } + + public bool Contains(Rect rect, Vector2 point) + { + if (!rect.Contains(point)) + return false; + int x = (int)((point.x - rect.x) * Size.x / rect.width); + int y = (int)Size.y - 1 - (int)((point.y - rect.y) * Size.y / rect.height); + return Pixels[y * Width + x].a >= 6; + } + } + + private static BattleScenario Scenario(BattleEditorSession editor) + { + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = editor.Data.Scenes.First(), + DataFingerprint = editor.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); +#if PAL3 + scenario.Participants[0].Equipment[0] = BattleMagicSwordRules.WeaponId; + scenario.Participants[0].MagicSword = new BattleMagicSword { Energy = 200, SkillId = 2201 }; +#endif + return scenario; + } + + private static string DataRoot() + { + string configured = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root) && configured == null) + Assert.Ignore("Original local data unavailable."); + return root; + } + + private static List<(string Id, Rect Rect)> Controls(Canvas canvas) => + (List<(string Id, Rect Rect)>)typeof(BattleHudView).GetField("_hitControls", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(canvas.Hud); + + private static void AssertGpuVisiblePixelsRouteToTheIsolatedWheel(Canvas canvas, string expected) + { + RenderTexture buffer = canvas.RenderTarget; + Assert.That(buffer, Is.Not.Null); + Vector2 pixelsPerPoint = new(buffer.width / Canvas.Size.x, buffer.height / Canvas.Size.y); + var viewport = new BattleHudViewport(canvas.Area, Insets); + Rect control = Controls(canvas).Single(control => control.Id == expected).Rect; + Vector2 origin = viewport.ToViewport(control.position); + var drawn = new Rect(Vector2.Scale(origin, pixelsPerPoint), Vector2.Scale(control.size * viewport.Scale, pixelsPerPoint)); + var texture = new Texture2D(buffer.width, buffer.height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = buffer; + texture.ReadPixels(new Rect(0, 0, buffer.width, buffer.height), 0, 0); + texture.Apply(); + Color32[] pixels = texture.GetPixels32(); + bool Visible(int x, int y) + { + if (x < 0 || x >= buffer.width || y < 0 || y >= buffer.height) + return false; + int row = buffer.height - 1 - y; + Color32 pixel = pixels[row * buffer.width + x]; + return Math.Max(pixel.r, Math.Max(pixel.g, pixel.b)) > 30; + } + int checkedPixels = 0; + for (int y = Math.Max(1, Mathf.CeilToInt(drawn.y)); y < Math.Min(buffer.height - 1, drawn.yMax); y++) + for (int x = Math.Max(1, Mathf.CeilToInt(drawn.x)); x < Math.Min(buffer.width - 1, drawn.xMax); x++) + { + // Erode one physical pixel to avoid bilinear alpha + // fringes. Expected hits come only from the GPU image. + if (!Visible(x, y) || !Visible(x - 1, y) || !Visible(x + 1, y) || !Visible(x, y - 1) || !Visible(x, y + 1)) + continue; + Vector2 point = new Vector2((x + .5f) / pixelsPerPoint.x, (y + .5f) / pixelsPerPoint.y); + Assert.That(canvas.Hud.SendPointer(BattleHudIntentKind.PointerMove, 84, point), Is.True, + $"GPU-visible {expected}, aspect={canvas.Area.size}, touch={canvas.Touch}, point={point}"); + Assert.That(canvas.Hud.Presenter.FocusedId, Is.EqualTo(expected), $"GPU-visible point={point}"); + checkedPixels++; + } + Assert.That(checkedPixels, Is.GreaterThan(20), "The offscreen buffer must expose the asymmetric wheel sprite."); + } + finally + { + RenderTexture.active = previous; + UnityEngine.Object.DestroyImmediate(texture); + } + } + + private static Dictionary Sprites(Canvas canvas) + { + var sprites = new Dictionary(StringComparer.Ordinal); + void Add(string id, string image, Vector2 size) => sprites.Add(id, new SpriteOracle(canvas.Editor.Preview.View.GetTexture("basedata.cpk\\ui\\combat\\control\\" + image + ".tga"), size)); + foreach ((string id, string image) in new[] { ("attack", "attack0"), ("skills", "skill0"), ("magic", "magic0"), ("items", "item0"), ("defend", "defence0"), ("flee", "flee0"), ("formation", "lineup0"), ("ai", "ai0"), ("protection", "protect0") }) + Add(id, image, new Vector2(46, 46)); +#if PAL3 + Add("sword", "mj0", new Vector2(84, 84)); +#else + int[] ids = { 264, 265, 267, 266, 268 }; + for (int core = 0; core < 5; core++) + { + int ui = core switch + { + 2 => 3, + 3 => 2, + _ => core + }; + int tier = canvas.Editor.Battle.Pal3AState.SpiritWheel.Charges[core] / 3; + string image = (tier < 3 ? "unwt" : "wt") + (4 - ui) + (tier < 3 ? tier : 0); + BattleSpiritRect rect = BattlePreview.SpiritWheelTarget(core); + Add("wheel:" + ids[core], image, new Vector2(rect.Right - rect.Left, rect.Bottom - rect.Top)); + } + Add("transform", "bs0", new Vector2(45, 37)); +#endif + return sprites; + } + + // The oracle independently samples the resource pixels in native draw + // order. It does not read the production mask or its hit-test helper. + private static Dictionary AssertPixelRouting(Canvas canvas, params string[] required) + { + var viewport = new BattleHudViewport(canvas.Area, Insets); + var enabled = new HashSet(canvas.Hud.Presenter.FocusItems().Where(item => item.Enabled).Select(item => item.Id)); + var sprites = Sprites(canvas); + var controls = Controls(canvas).Where(control => enabled.Contains(control.Id) && sprites.ContainsKey(control.Id)).ToArray(); + var exposed = new Dictionary(); + int checkedPixels = 0; + foreach (var control in controls.Where(control => required.Contains(control.Id))) + { + SpriteOracle sprite = sprites[control.Id]; + for (int y = 0; y < sprite.Size.y; y += 3) + for (int x = 0; x < sprite.Size.x; x += 3) + { + Vector2 point = control.Rect.position + new Vector2((x + .5f) * control.Rect.width / sprite.Size.x, (y + .5f) * control.Rect.height / sprite.Size.y); + var top = controls.LastOrDefault(candidate => sprites[candidate.Id].Contains(candidate.Rect, point)); + if (top.Id == null) + continue; + Assert.That(canvas.Hud.SendPointer(BattleHudIntentKind.PointerMove, 83, viewport.ToViewport(point)), Is.True, top.Id); + Assert.That(canvas.Hud.Presenter.FocusedId, Is.EqualTo(top.Id), $"{canvas.Area.size}, touch={canvas.Touch}, pixel={point}"); + exposed[top.Id] = viewport.ToViewport(point); + checkedPixels++; + } + } + Assert.That(checkedPixels, Is.GreaterThan(20)); + foreach (string id in required) + { + Assert.That(exposed.ContainsKey(id), Is.True, id + " needs its own visible, clickable sprite pixels."); + Assert.That(canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 83, exposed[id]), Is.True, id); + Assert.That(canvas.Hud.Presenter.FocusedId, Is.EqualTo(id)); + Assert.That(canvas.Hud.SendPointer(BattleHudIntentKind.PointerCancel, 83, exposed[id]), Is.True); + } + return exposed; + } + + [Test] + public void OverlappingNativeSpritesRouteVisiblePixelsAcrossFourAspectsAndBothInteractionProfiles() + { + using var editor = new BattleEditorSession(); + editor.Load(DataRoot(), 936); + BattleScenario scenario = Scenario(editor); + using var canvas = new Canvas(editor); + foreach (bool touch in new[] { false, true }) + foreach (Rect area in Areas) + { + canvas.Touch = touch; + canvas.Area = area; +#if PAL3 + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + canvas.Paint(); + var points = AssertPixelRouting(canvas, "sword", "formation", "items"); + int before = editor.Battle.Inputs.Count; + Assert.That(canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 83, points["formation"]), Is.True); + Assert.That(canvas.Hud.SendPointer(BattleHudIntentKind.PointerUp, 83, points["formation"]), Is.True); + Assert.That(canvas.Hud.Presenter.Page, Is.EqualTo(BattleHudPage.Formation)); + Assert.That(editor.Battle.Inputs.Skip(before).Any(input => input.Kind == BattleInputKind.Command && input.AbilityId == 2201), Is.False, "Opening formation must never fire the charged sword."); +#else + foreach (int fullElement in Enumerable.Range(-1, 6)) + { + canvas.ProbeCore = fullElement; + scenario.Pal3A.SpiritWheel.Charges = Enumerable.Range(0, 5).Select(index => fullElement < 0 || index == fullElement ? 9 : 0).ToArray(); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + canvas.Paint(); + int[] ids = { 264, 265, 267, 266, 268 }; + string[] required = fullElement < 0 ? ids.Select(id => "wheel:" + id).Append("transform").ToArray() : new[] { "wheel:" + ids[fullElement] }; + var points = AssertPixelRouting(canvas, required); + if (fullElement >= 0) + AssertGpuVisiblePixelsRouteToTheIsolatedWheel(canvas, required[0]); + string chosen = fullElement < 0 ? "transform" : required[0]; + int before = editor.Battle.Inputs.Count; + Assert.That(canvas.Hud.SendPointer(BattleHudIntentKind.PointerDown, 83, points[chosen]), Is.True); + Assert.That(canvas.Hud.SendPointer(BattleHudIntentKind.PointerUp, 83, points[chosen]), Is.True); + Assert.That(editor.Battle.Inputs.Count, Is.EqualTo(before + 1)); + Assert.That(editor.Battle.Inputs.Last().Kind, Is.EqualTo(fullElement < 0 ? BattleInputKind.Command : BattleInputKind.ElementWheel)); + if (fullElement < 0) + Assert.That(editor.Battle.Inputs.Last().Action, Is.EqualTo(BattleAction.Transform)); + else + Assert.That(editor.Battle.Inputs.Last().AbilityId, Is.EqualTo(int.Parse(chosen[6..]))); + } +#endif + } + LogAssert.NoUnexpectedReceived(); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpriteRoutingTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpriteRoutingTests.cs.meta new file mode 100644 index 00000000..28fc2bb1 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudSpriteRoutingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 061ba705aff147c29b9cf755c08bc12c diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTests.cs new file mode 100644 index 00000000..6e0880ef --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTests.cs @@ -0,0 +1,1054 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using System.Reflection; + using Battle; + using Battle.Presentation; + using Newtonsoft.Json; + using NUnit.Framework; + using UnityEngine; + + public sealed class BattleHudTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class Rules : IBattleRules + { + public int GaugeRate = 1; + + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => BattleSession.FullGauge; + + public int GaugePerStep(BattleParticipant actor) => GaugeRate; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, + bool targetAtHome = true, int damageDivisor = 1) => new BattleBasicRules().Hit(source, target, guarding, random, targetAtHome, damageDivisor); + } + + internal static BattleSession Session(string variant = "PAL3", BattleTargetRange normalRange = BattleTargetRange.OpponentSingle, Action configure = null, BattleState? skillState = null, int gaugeRate = 1, bool withDefinitions = true) + { + var scenario = new BattleScenario { Variant = variant, Scene = "hud", SceneElement = 1, DataFingerprint = "hud", Money = 100 }; + foreach ((string id, BattleSide side, BattleSlot slot, int hp) in new[] + { + ("A", BattleSide.Ally, BattleSlot.Water, 100), ("B", BattleSide.Ally, BattleSlot.Fire, 0), + ("E", BattleSide.Enemy, BattleSlot.Water, 100), ("E2", BattleSide.Enemy, BattleSlot.Wind, 100), + ("E3", BattleSide.Enemy, BattleSlot.Fire, 100) + }) + { + var actor = new BattleParticipant + { + InstanceId = id, + ActorId = side == BattleSide.Ally ? id == "A" ? 101 : 104 : 701, + Side = side, + Slot = slot, + Attributes = new[] { 100, 100, 100, 20, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { hp, 100, 100 } + }; + actor.Skills.Add(new BattleSkill { Id = 301, Level = 4, Mastered = true }); + actor.Skills.Add(new BattleSkill { Id = 302, Level = 4, Mastered = true }); + actor.Skills.Add(new BattleSkill { Id = 401, Level = 4, Mastered = true }); + scenario.Participants.Add(actor); + } + scenario.Items.Add(new BattleItem { Id = 6201, Count = 3 }); + configure?.Invoke(scenario); + var definitions = new BattleDefinitions(variant, "hud", new[] + { + new BattleAbilityDefinition(new BattleAbilityData { Id = 301, Name = "水术", IsMagic = true, ElementMask = 1, + Range = BattleTargetRange.OpponentRow, SkillTypeId = 2, + ApplicableIdentities = new[] { 0 }, Costs = new[] { new BattleCost(2, BattleValueMode.Absolute, 10) } }), + new BattleAbilityDefinition(new BattleAbilityData { Id = 302, Name = "群体火术", IsMagic = true, ElementMask = 2, + Range = BattleTargetRange.OpponentAll, SkillTypeId = 2, ApplicableIdentities = new[] { 0 } }), + new BattleAbilityDefinition(new BattleAbilityData { Id = 401, Name = "特技", Range = BattleTargetRange.OpponentSingle, + SkillTypeId = 0, ApplicableIdentities = new[] { 0 }, + States = skillState.HasValue ? new[] { new BattleStatusEffect(skillState.Value, false) } : Array.Empty() }) + }, new[] + { + new BattleAbilityDefinition(new BattleAbilityData { Id = 6201, Name = "还魂", IsItem = true, ItemType = 1, + Range = BattleTargetRange.OwnSingle, States = new[] { new BattleStatusEffect(BattleState.Death, true) } }) + }, scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.Side == BattleSide.Ally ? actor.InstanceId == "A" ? 0 : 1 : -1, + NormalAttackRange = normalRange + }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new Rules { GaugeRate = gaugeRate }, withDefinitions ? definitions : null); + session.SetAutomatic(BattleSide.Enemy, false); + session.Step(); + return session; + } + + [TestCase(false)] + [TestCase(true)] + public void CommandRingDisablesUnlearnedAbilitiesAndToleratesMissingDefinitions(bool withDefinitions) + { + BattleSession session = Session(BattleData.Variant, configure: scenario => + { + foreach (BattleSkill skill in scenario.Participants[0].Skills) + skill.Mastered = false; + }, withDefinitions: withDefinitions); + var hud = new BattleHudPresenter(); + hud.Synchronize(session); + var focus = hud.FocusItems().ToDictionary(item => item.Id); + Assert.That(focus["attack"].Enabled, Is.True); + Assert.That(focus["skills"].Enabled, Is.False); + Assert.That(focus["magic"].Enabled, Is.False); + Assert.That(focus["items"].Enabled, Is.EqualTo(withDefinitions)); + Assert.That(focus["ai"].Enabled, Is.EqualTo(withDefinitions)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ViewCanBindADefinitionFreeSession(string variant) + { + BattleSession session = Session(variant, withDefinitions: false); + var view = new BattleHudView(); + view.BindBattle(session, null, null, null, null); + Assert.That(view.Presenter.Controller, Is.EqualTo("A")); + Assert.That(BattleHudView.ElementWheelVisible(session, view.Presenter), Is.False); + var layout = (BattleHudLayout)typeof(BattleHudView).GetField("_layout", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(view); + Assert.That(layout.IsPal3A, Is.EqualTo(variant == "PAL3A")); + view.Release(); + } + + [TestCase(BattleHudPage.Items, BattleState.Forbidden, false)] + [TestCase(BattleHudPage.Items, BattleState.Forbidden, true)] + [TestCase(BattleHudPage.Magic, BattleState.Seal, false)] + [TestCase(BattleHudPage.Magic, BattleState.Seal, true)] + [TestCase(BattleHudPage.Commands, BattleState.Seal, true)] + [TestCase(BattleHudPage.Commands, BattleState.Forbidden, true)] + public void IncomingStateClosesItsListAndCancelsPendingTargetInput(BattleHudPage page, BattleState state, bool choose) + { + bool item = state == BattleState.Forbidden; + BattleSession session = Session(BattleData.Variant, skillState: state); + session.SetAutomatic(BattleSide.Enemy, true); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 401)), Is.True); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + presenter.Open(page); + if (choose) + Assert.That(presenter.ChooseAction(item ? BattleAction.Item : BattleAction.Skill, item ? 6201 : 301), Is.True); + string control = choose ? "target:" + presenter.Target : "category:0"; + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerDown, control, 37)), Is.True); + for (int tick = 0; tick < 30 && presenter.Page != BattleHudPage.Commands; tick++) + { + session.Step(); + presenter.Synchronize(session); + } + Assert.That(session.Actors.Single(actor => actor.Id == "A").States.Any(value => value.State == state), Is.True); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(presenter.CapturedPointerId, Is.Null); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerUp, control, 37)), Is.False); + Assert.That(session.WaitingActor, Is.EqualTo("A")); + Assert.That(session.Inputs.Any(input => input.Actor == "A" && input.Kind == BattleInputKind.Command), Is.False); + } + + [Test] + public void UnrelatedStateAndInsufficientMpKeepTheMagicListOpen() + { + BattleSession session = Session(BattleData.Variant, configure: scenario => scenario.Participants[0].Vitals[2] = 0, + skillState: BattleState.Forbidden); + session.SetAutomatic(BattleSide.Enemy, true); + Assert.That(session.Submit(new BattleCommand("E", BattleAction.Skill, "A", 401)), Is.True); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + presenter.Open(BattleHudPage.Magic); + for (int tick = 0; tick < 5; tick++) + { + session.Step(); + presenter.Synchronize(session); + } + Assert.That(session.Actors.Single(actor => actor.Id == "A").States.Any(value => value.State == BattleState.Forbidden), Is.True); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Magic)); + Assert.That(presenter.Reason(BattleAction.Skill, 301), Does.Contain("Resource")); + } + + private static string State(BattleSession session) + { + object random = typeof(BattleSession).GetField("_random", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(session); + return JsonConvert.SerializeObject(new + { + session.Tick, + session.SimulationTick, + session.Events, + session.Inputs, + session.Actors, + session.Inventory, + session.Money, + session.Pal3AState, + session.StageTasks, + RandomState = random.GetType().GetProperty("State").GetValue(random) + }); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void BrowsingAndPotentialAreaQueriesAreCompletelyReadOnly(string variant) + { + BattleSession session = Session(variant); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + string before = State(session); + for (int index = 0; index < 20; index++) + { + presenter.Open(BattleHudPage.Magic); + Assert.That(presenter.Abilities().Select(row => row.Definition.Id), Is.EqualTo(new[] { 301 })); + Assert.That(presenter.ChooseAbility(301), Is.True); + Assert.That(presenter.HoverTarget("E"), Is.True); + Assert.That(presenter.Affected.Select(actor => actor.Id), Is.EqualTo(new[] { "E", "E2" })); + Assert.That(presenter.Costs.Count, Is.EqualTo(1)); + presenter.Back(); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Magic)); + presenter.Back(); + } + Assert.That(State(session), Is.EqualTo(before)); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + public void TargetingStaysConsistentWhenAQueuedAttackKillsTheSelectedEnemy(string variant, bool hideSurvivors) + { + BattleSession session = Session(variant, configure: scenario => + { + scenario.Participants.Single(actor => actor.InstanceId == "B").Vitals[0] = 100; + scenario.Participants.Single(actor => actor.InstanceId == "E").Vitals[0] = 1; + if (hideSurvivors) + foreach (BattleParticipant actor in scenario.Participants.Where(actor => actor.Side == BattleSide.Enemy && actor.InstanceId != "E")) + actor.Statuses.Add(new BattleStatus { Id = (int)BattleState.Invisible, Rounds = 5 }); + }); + Assert.That(session.Submit("A", BattleAction.Attack, "E"), Is.True); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(presenter.Controller, Is.EqualTo("B")); + Assert.That(presenter.ChooseAction(BattleAction.Attack), Is.True); + Assert.That(presenter.HoverTarget("E"), Is.True); + for (int i = 0; i < 120 && session.Actors.Single(actor => actor.Id == "E").Alive; i++) + session.Step(); + Assert.That(session.Actors.Single(actor => actor.Id == "E").Alive, Is.False); + presenter.Synchronize(session); + if (hideSurvivors) + { + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(session.Inputs.Count(input => input.Kind == BattleInputKind.Command), Is.EqualTo(1)); + return; + } + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + string survivor = presenter.Target; + Assert.That(presenter.Targets.Any(actor => actor.Id == survivor && actor.Alive), Is.True); + Assert.That(BattleHudView.PointerActors(session, presenter), Is.EqualTo(new[] { survivor })); + Assert.That(presenter.FocusedId, Is.EqualTo("target:" + survivor)); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm)), Is.True); + Assert.That(session.Inputs.Last(input => input.Kind == BattleInputKind.Command).Target, Is.EqualTo(survivor)); + } + + [Test] + public void RevivalTargetRecoveringRemainsSelectableWithoutSpendingAnotherItem() + { + BattleSession session = Session(configure: scenario => + { + BattleParticipant caster = scenario.Participants[0].Copy(); + caster.InstanceId = "C"; + caster.ActorId = 105; + caster.Slot = BattleSlot.Thunder; + scenario.Participants.Insert(1, caster); + }); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "B", 6201)), Is.True); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(presenter.Controller, Is.EqualTo("C")); + presenter.Open(BattleHudPage.Items); + Assert.That(presenter.ChooseAbility(6201), Is.True); + for (int i = 0; i < 120 && !session.Actors.Single(actor => actor.Id == "B").Alive; i++) + session.Step(); + Assert.That(session.Actors.Single(actor => actor.Id == "B").Alive, Is.True); + presenter.Synchronize(session); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + Assert.That(presenter.Target, Is.EqualTo("B")); + Assert.That(session.Inputs.Count(input => input.Kind == BattleInputKind.Command), Is.EqualTo(1)); + } + + [TestCase(BattleHudPage.Magic, 3)] + [TestCase(BattleHudPage.Items, 1)] + public void ConfirmInAnEmptyCategoryKeepsTheDisplayedTab(BattleHudPage page, int category) + { + var presenter = new BattleHudPresenter(); + presenter.Synchronize(Session()); + presenter.Open(page); + presenter.SetCategory(category); + Assert.That(presenter.Abilities(), Is.Empty); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm)), Is.True); + Assert.That(presenter.Category, Is.EqualTo(category)); + Assert.That(presenter.FocusedId, Is.EqualTo("category:" + category)); + } + + [Test] + public void ClickingOnlyALegalTargetCommitsExactlyOnce() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + int inputs = session.Inputs.Count; + Assert.That(presenter.ChooseAction(BattleAction.Attack), Is.True); + Assert.That(presenter.SelectTarget("B"), Is.False); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs)); + Assert.That(presenter.SelectTarget("E"), Is.True); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs + 1)); + Assert.That(presenter.SelectTarget("E"), Is.False); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs + 1)); + } + + [Test] + public void RevivalSelectionDefaultsToTheFallenAllyAndAllowsALivingRecipient() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + presenter.Open(BattleHudPage.Items); + Assert.That(presenter.ChooseAbility(6201), Is.True); + Assert.That(presenter.Targets.Select(actor => actor.Id), Is.EquivalentTo(new[] { "A", "B" })); + Assert.That(presenter.Target, Is.EqualTo("B")); + Assert.That(presenter.FocusedId, Is.EqualTo("target:B")); + Assert.That(presenter.SelectTarget("A"), Is.True); + } + + [Test] + public void WaitingControllerChangesClearTheOldSelectionAndPermitManualEnemies() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + presenter.ChooseAction(BattleAction.Attack); + presenter.HoverTarget("E"); + Assert.That(session.Submit("A", BattleAction.Defend), Is.True); + presenter.Synchronize(session); + Assert.That(presenter.Controller, Is.EqualTo("E")); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(presenter.Target, Is.Null); + Assert.That(presenter.ChooseAction(BattleAction.Attack), Is.True); + Assert.That(presenter.Targets.Select(actor => actor.Id), Is.EqualTo(new[] { "A" })); + Assert.That(presenter.SelectTarget("A"), Is.True); + } + + [Test] + public void AbortedSessionsClearSelectionAndCannotRequestAi() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + presenter.ChooseAction(BattleAction.Attack); + session.Abort(); + presenter.Synchronize(session); + string before = State(session); + Assert.That(presenter.Controller, Is.Null); + Assert.That(presenter.RequestAi(false), Is.False); + Assert.That(presenter.RequestAi(true), Is.False); + Assert.That(State(session), Is.EqualTo(before)); + } + + [Test] + public void UnknownActionsAndAbilitiesNeverBorrowNormalAttackRange() + { + BattleSession session = Session(); + string before = State(session); + foreach (BattleCommand command in new[] + { + new BattleCommand("A", (BattleAction)999), new BattleCommand("A", BattleAction.Skill, abilityId: 999), + new BattleCommand("A", BattleAction.Item, abilityId: 999), new BattleCommand("missing", BattleAction.Attack) + }) + { + Assert.That(session.GetActionTargetRange(command), Is.EqualTo(BattleTargetRange.None)); + Assert.That(session.GetPotentialAffectedTargets(command), Is.Empty); + } + Assert.That(State(session), Is.EqualTo(before)); + } + + [TestCase("PAL3", 2)] + [TestCase("PAL3A", 2)] + public void NativePointerSetsChangeFromTheControllerToTheWholePotentialArea(string variant, int enemyPointers) + { + BattleSession session = Session(variant); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(BattleHudView.PointerActors(session, presenter), Is.EqualTo(new[] { "A" })); + presenter.Open(BattleHudPage.Magic); + Assert.That(BattleHudView.PointerActors(session, presenter), Is.EqualTo(new[] { "A" })); + presenter.ChooseAbility(301); + presenter.HoverTarget("E"); + Assert.That(BattleHudView.PointerActors(session, presenter).Count, Is.EqualTo(enemyPointers)); + Assert.That(BattleHudView.PointerActors(session, presenter), Does.Not.Contain("A")); + } + + [Test] + public void KeyboardNavigationUsesTheSameFocusAndConfirmationIntentAsControllers() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(presenter.FocusedId, Is.EqualTo("attack")); + string before = State(session); + presenter.Handle(BattleHudView.KeyboardIntent(KeyCode.UpArrow).Value); + Assert.That(presenter.FocusedId, Is.EqualTo("skills")); + presenter.Handle(BattleHudView.KeyboardIntent(KeyCode.Return).Value); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Skills)); + Assert.That(presenter.FocusedId, Is.EqualTo("ability:401")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm)); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + Assert.That(presenter.Target, Is.EqualTo("E")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Down)); + Assert.That(presenter.Target, Is.EqualTo("E3")); + Assert.That(State(session), Is.EqualTo(before)); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm)); + Assert.That(session.Inputs.Count(input => input.Kind == BattleInputKind.Command), Is.EqualTo(1)); + } + + [Test] + public void PointerCaptureRejectsSecondPointerAndCancelsWithoutSubmitting() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + string before = State(session); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerDown, "attack", 17)), Is.True); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerDown, "defend", 22)), Is.False); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerUp, "defend", 22)), Is.False); + Assert.That(presenter.CapturedPointerId, Is.EqualTo(17)); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerCancel, pointerId: 17)), Is.True); + Assert.That(presenter.CapturedPointerId, Is.Null); + Assert.That(State(session), Is.EqualTo(before)); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerDown, "attack", 17)); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerUp, "attack", 17)); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerDown, "target:E", 17)); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerMove, "target:E2", 17)); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerUp, "target:E2", 17)); + Assert.That(State(session), Is.EqualTo(before)); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerDown, "target:E2", 17)); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerUp, "target:E2", 17)); + Assert.That(session.Inputs.Count(input => input.Kind == BattleInputKind.Command), Is.EqualTo(1)); + } + + [Test] + public void ChangingMenuOrWaitingActorClearsCapturedPointer() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerDown, "attack", 2)); + presenter.Open(BattleHudPage.Skills); + Assert.That(presenter.CapturedPointerId, Is.Null); + presenter.Back(); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.PointerDown, "attack", 2)); + session.Submit("A", BattleAction.Defend); + presenter.Synchronize(session); + Assert.That(presenter.CapturedPointerId, Is.Null); + Assert.That(presenter.Controller, Is.EqualTo("E")); + } + + [TestCase(320, 640)] + [TestCase(1600, 900)] + [TestCase(2520, 1080)] + public void AdaptiveHudUsesFullViewportAndKeepsCardsInsideExternalSafeArea(float width, float height) + { + Rect viewport = new(37, 91, width, height); + var context = new BattleHudViewport(viewport, new Vector4(16, 12, 24, 18)); + Assert.That(context.Viewport, Is.EqualTo(viewport)); + Assert.That(context.SafeRect.x, Is.EqualTo(53)); + Assert.That(context.SafeRect.y, Is.EqualTo(103)); + for (int index = 0; index < 4; index++) + { + Rect logical = context.StateCard(index); + Vector2 topLeft = context.ToViewport(logical.position); + Vector2 bottomRight = context.ToViewport(logical.max); + Assert.That(topLeft.x, Is.GreaterThanOrEqualTo(context.SafeRect.x - .001)); + Assert.That(bottomRight.x, Is.LessThanOrEqualTo(context.SafeRect.xMax + .001)); + Assert.That(bottomRight.y, Is.LessThanOrEqualTo(context.SafeRect.yMax + .001)); + Assert.That(Vector2.Distance(context.ToCanvas(topLeft), logical.position), Is.LessThan(.001)); + } + Assert.That(context.ReferenceRect.width / context.ReferenceRect.height, Is.EqualTo(4f / 3).Within(.00001)); + } + + [TestCase(900, 675)] + [TestCase(1260, 540)] + [TestCase(1200, 600)] + [TestCase(700, 700)] + public void TouchKeepsTheNativeCanvasAndOnlyEnlargesTheLocalMenu(int width, int height) + { + var viewport = new BattleHudViewport(new Rect(29, 43, width, height), new Vector4(16, 12, 24, 18)); + var touch = new BattleHudInteractionProfile(true); + float scale = touch.ScaleFor(viewport); + Assert.That(scale, Is.EqualTo(1.2f)); + float maximum = new BattleHudInteractionProfile(true, 2).ScaleFor(viewport); + Assert.That(viewport.CanvasSize.y - 118 - 322 * maximum, Is.GreaterThanOrEqualTo(0)); + Assert.That(new BattleHudInteractionProfile(false).ScaleFor(viewport), Is.EqualTo(1)); + Assert.That(viewport.StateCard(0).yMax, Is.LessThanOrEqualTo(viewport.CanvasSize.y)); + } + + [Test] + public void ExpandedTouchHitsChooseTheNearestNativeControlInsteadOfRegistrationOrder() + { + BattleSession session = Session(); + var view = new BattleHudView(); + view.Presenter.Synchronize(session); + void Set(string name, object value) => typeof(BattleHudView).GetField(name, BindingFlags.NonPublic | BindingFlags.Instance).SetValue(view, value); + Set("_battle", session); + Set("_inputEnabled", true); + Set("_interaction", new BattleHudInteractionProfile(true)); + Set("_viewport", new BattleHudViewport(new Rect(0, 0, 800, 600), default)); + var hits = (System.Collections.Generic.List<(string, Rect)>)typeof(BattleHudView).GetField("_hitControls", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(view); + hits.Add(("defend", new Rect(146, 100, 40, 40))); + hits.Add(("attack", new Rect(100, 100, 40, 40))); + string before = State(session); + Assert.That(view.SendPointer(BattleHudIntentKind.PointerDown, 11, new Vector2(142, 120)), Is.True); + Assert.That(view.SendPointer(BattleHudIntentKind.PointerUp, 11, new Vector2(142, 120)), Is.True); + Assert.That(view.Presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + Assert.That(State(session), Is.EqualTo(before)); + } + + [TestCase(320, 640)] + [TestCase(1600, 900)] + [TestCase(2520, 1080)] + public void SpiritWheelPiecesShareOneUniformRightAnchoredMapping(int width, int height) + { + var context = new BattleHudViewport(new Rect(29, 43, width, height), new Vector4(16, 12, 16, 18)); + Vector2 water = new(722, 48), fire = new(732, 22); + Assert.That(Vector2.Distance(context.NativeToViewport(fire) - context.NativeToViewport(water), (fire - water) * context.Scale), Is.LessThan(.001)); + Assert.That(context.NativeToViewport(new Vector2(800, 0)), Is.EqualTo(new Vector2(context.SafeRect.xMax, context.SafeRect.y))); + } + + [TestCase(1600, 900, true)] + [TestCase(2520, 1080, true)] + [TestCase(700, 1000, true)] + [TestCase(1600, 900, false)] + public void DisplayFramingMapsTheNativeProjectionWithoutChangingCameraSamples(int width, int height, bool expand) + { + using var preview = new ResourceBrowser.ResourceModelPreview(null, false); + preview.SetHorizontalCameraOrientation(Vector3.zero, Vector3.forward, Vector3.up, 50); + Vector3 world = new(1, 1, 10); + Vector2 native = preview.ProjectReference(world, 800, 600); + Rect viewport = new(23, 49, width, height); + preview.ExpandReferenceFraming = expand; + preview.SetViewportContext(viewport); + Assert.That(preview.Project(world, viewport, out Vector2 actual), Is.True); + var context = new BattleHudViewport(viewport, Vector4.zero); + Vector2 mapped = context.ProjectionReferencePoint(native, expand); + Assert.That(Vector2.Distance(actual, mapped), Is.LessThan(.01)); + Assert.That(preview.HorizontalFieldOfView, Is.EqualTo(50)); + } + + [TestCase(320, 640)] + [TestCase(1600, 900)] + public void ExplicitAuthoringCameraKeepsItsDeclaredVerticalFovAndMapsTheReferenceConsistently(int width, int height) + { + using var preview = new ResourceBrowser.ResourceModelPreview(null, false); + preview.SetCamera(Vector3.zero, Vector3.forward * 5, 54); + Vector3 world = new(1, 1, 10); + Vector2 native = preview.ProjectReference(world, 800, 600); + Rect viewport = new(37, 71, width, height); + preview.ExpandReferenceFraming = true; + preview.SetViewportContext(viewport); + preview.Project(world, viewport, out Vector2 actual); + var context = new BattleHudViewport(viewport, Vector4.zero); + Assert.That(Vector2.Distance(context.ProjectionReferencePoint(native, preview.ReferenceProjectionScale(viewport)), actual), Is.LessThan(.01)); + preview.GetCamera(out _, out _, out float fieldOfView); + Assert.That(fieldOfView, Is.EqualTo(54)); + } + + [Test] + public void SpiritMappingIsExactAtFourByThreeAndNeverFollowsLaterCameraMovement() + { + var context = new BattleHudViewport(new Rect(0, 0, 800, 600), Vector4.zero); + Vector2 origin = new(311, 432), destination = new(748, 81); + foreach (Vector2 point in new[] { origin, new Vector2(500, 250), destination }) + Assert.That(context.SpiritOrbPoint(point, origin, destination, true), Is.EqualTo(point)); + context = new BattleHudViewport(new Rect(40, 20, 2520, 1080), new Vector4(20, 10, 30, 15)); + Vector2 before = context.SpiritOrbPoint(new Vector2(500, 250), origin, destination, true); + using var preview = new ResourceBrowser.ResourceModelPreview(null, false); + preview.SetCamera(new Vector3(20, 30, 40), Vector3.zero, 80); + preview.SetViewportContext(context.Viewport); + Assert.That(context.SpiritOrbPoint(new Vector2(500, 250), origin, destination, true), Is.EqualTo(before)); + Assert.That(context.SpiritOrbPoint(destination, origin, destination, true), Is.EqualTo(context.NativeToViewport(destination))); + } + + [TestCase(0, 5, 33)] + [TestCase(31, 5, 63)] + [TestCase(63, 5, 16)] + [TestCase(63, 0, 16)] + [TestCase(16, 0, 16)] + [TestCase(32, 0, 33)] + [TestCase(0, 1, 0)] + [TestCase(2, 1, 0)] + [TestCase(63, 1, 61)] + [TestCase(63, 2, 59)] + [TestCase(63, 3, 55)] + [TestCase(16, 4, 16)] + [TestCase(0, 4, 0)] + [TestCase(63, 4, 47)] + [TestCase(32, 3, 40)] + public void AiMenuTogglesMatchBothReleasedPrograms(int flags, int bit, int expected) + { + // Captured by executing each real ProcAIList switch. Full evidence: + // Hud/probe-ai-control-native.py: 768 widget cases per variant. + Assert.That(BattleHudPresenter.ToggleAiFlag(flags, bit), Is.EqualTo(expected)); + } + + [Test] + public void AiDraftDoesNotChangeTheLiveControllerBeforeConfirmationAndBackDiscardsIt() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + string before = State(session); + int live = session.GetAiProfile("A"); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "ai")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "flag:5")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "flag:1")); + Assert.That(presenter.AiFlags("A"), Is.Not.EqualTo(live)); + Assert.That(session.GetAiProfile("A"), Is.EqualTo(live)); + Assert.That(session.WaitingActor, Is.EqualTo("A")); + Assert.That(State(session), Is.EqualTo(before)); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Back)); + Assert.That(session.GetAiProfile("A"), Is.EqualTo(live)); + Assert.That(State(session), Is.EqualTo(before)); + } + + [Test] + public void AiConfirmationUsesOneAtomicNativeCommandAndLeavesPoseAndResourcesAlone() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + BattleActorSnapshot before = session.Actors.First(actor => actor.Id == "A"); + int input = session.Inputs.Count; + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "ai")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "flag:5")); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "end")), Is.True); + Assert.That(session.Inputs.Skip(input).Select(value => value.Kind.ToString()), Is.EqualTo(new[] { "AiControl" })); + BattleActorSnapshot after = session.Actors.First(actor => actor.Id == "A"); + Assert.That(after.Gauge, Is.Zero); + Assert.That(after.CastGauge, Is.Zero); + Assert.That(after.Pose, Is.EqualTo(before.Pose)); + Assert.That((after.Hp, after.Sp, after.Mp), Is.EqualTo((before.Hp, before.Sp, before.Mp))); + } + + [TestCase("PAL3", false)] + [TestCase("PAL3A", false)] + [TestCase("PAL3", true)] + [TestCase("PAL3A", true)] + public void AiConfirmationPreservesUntouchedFlagsChangedInTheDrawer(string variant, bool editSkill) + { + BattleSession session = Session(variant); + session.SetAiProfile("E", 33); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "ai")), Is.True); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "ai-actor:E")), Is.True); + if (editSkill) + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "flag:2")), Is.True); + + session.SetAiProfile("E", 49); + int inputCount = session.RecordedInputCount; + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "end")), Is.True); + Assert.That(session.GetAiProfile("E"), Is.EqualTo(editSkill ? 53 : 49)); + Assert.That(session.RecordedInputCount, Is.EqualTo(inputCount + (editSkill ? 1 : 0))); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void AiDraftFromAPreviousMonsterGenerationDoesNotOverwriteTheReplacement(string variant) + { + BattleSession session = Session(variant); + session.SetAiProfile("E", 33); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "ai")), Is.True); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "ai-actor:E")), Is.True); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "flag:2")), Is.True); + + var generations = (System.Collections.Generic.Dictionary)typeof(BattleSession) + .GetField("_monsterGenerations", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + generations["E"] = 1; + session.SetAiProfile("E", 49); + int inputCount = session.RecordedInputCount; + Assert.That(presenter.AiFlags("E"), Is.EqualTo(49)); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "end")), Is.True); + Assert.That(session.GetAiProfile("E"), Is.EqualTo(49)); + Assert.That(session.RecordedInputCount, Is.EqualTo(inputCount)); + } + + [Test] + public void EditingAnotherActorsAiIsRecordedAsAToolProfileWithoutSpendingTheControllerGauge() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + int gauge = session.Actors.First(actor => actor.Id == "A").Gauge; + int input = session.Inputs.Count; + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "ai")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "ai-actor:E")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "flag:5")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "end")); + Assert.That(session.Inputs.Skip(input).Select(value => value.Kind), Is.EqualTo(new[] { BattleInputKind.AiProfile })); + Assert.That(session.Actors.First(actor => actor.Id == "A").Gauge, Is.EqualTo(gauge)); + } + + [Test] + public void EnemyWaterFieldDisablesItsTabWithoutErasingRepeatOnEntry() + { + BattleSession session = Session("PAL3A", configure: scenario => + { + scenario.FiveSpiritElement = 1; + scenario.FiveSpiritForce = 2; + }, gaugeRate: BattleSession.FullGauge); + Assert.That(session.Submit("A", BattleAction.Defend), Is.True); + for (int tick = 0; tick < 1000 && session.WaitingActor != "A"; tick++) + { + if (session.WaitingActor is { } other) + Assert.That(session.Submit(other, BattleAction.Defend), Is.True); + session.Step(); + } + Assert.That(session.WaitingActor, Is.EqualTo("A")); + var hud = new BattleHudPresenter(); + hud.Synchronize(session); + int inputs = session.RecordedInputCount; + hud.Open(BattleHudPage.Magic); + Assert.That(hud.Category, Is.EqualTo(1)); + Assert.That(hud.FocusItems().Single(item => item.Id == "category:0").Enabled, Is.False); + hud.SetCategory(0); + Assert.That(hud.Category, Is.EqualTo(1)); + Assert.That(hud.Handle(new BattleHudIntent(BattleHudIntentKind.CyclePrevious)), Is.True); + Assert.That(hud.Category, Is.EqualTo(5)); + Assert.That(session.RecordedInputCount, Is.EqualTo(inputs)); + hud.Back(); + Assert.That(session.RequestAiRepeat("A"), Is.True); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Defend)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void MagicCategoryMemoryIsPerControllerAndSession(string variant) + { + BattleSession Create() => Session(variant, configure: scenario => scenario.Participants[1].Vitals[0] = 100, + gaugeRate: BattleSession.FullGauge); + BattleSession session = Create(); + var hud = new BattleHudPresenter(); + hud.Synchronize(session); + Assert.That(hud.Controller, Is.EqualTo("A")); + hud.Open(BattleHudPage.Magic); + hud.SetCategory(3); + hud.Back(); + hud.Open(BattleHudPage.Magic); + Assert.That(hud.Category, Is.EqualTo(3)); + + ReadyAfterDefending(session, "B"); + hud.Synchronize(session); + hud.Open(BattleHudPage.Magic); + Assert.That(hud.Category, Is.Zero); + hud.SetCategory(4); + + ReadyAfterDefending(session, "A"); + hud.Synchronize(session); + hud.Open(BattleHudPage.Magic); + Assert.That(hud.Category, Is.EqualTo(3)); + + hud.Synchronize(Create()); + hud.Open(BattleHudPage.Magic); + Assert.That(hud.Category, Is.Zero); + } + + [Test] + public void InactiveMagicRowIgnoresOldGeometryButVisibleForbiddenRowStillInvalidatesRepeat() + { + BattleSession session = Session("PAL3A", configure: scenario => + { + // Render the water spell in an authored slot on an enabled tab, + // while the enemy water field makes that individual spell unavailable. + scenario.FiveSpiritElement = 1; + scenario.FiveSpiritForce = 2; + BattleSkill spell = scenario.Participants[0].Skills.Single(skill => skill.Id == 301); + spell.NativeMagicGroup = 1; + spell.NativeMagicSlot = 0; + }, gaugeRate: BattleSession.FullGauge); + ReadyAfterDefending(session, "A"); + var view = new BattleHudView(); + BattleHudPresenter hud = view.Presenter; + hud.Synchronize(session); + hud.Open(BattleHudPage.Magic); + Assert.That(hud.Category, Is.EqualTo(1)); + const string row = "ability:301"; + Assert.That(hud.FocusItems().Single(item => item.Id == row).Enabled, Is.False); + + const BindingFlags fields = BindingFlags.NonPublic | BindingFlags.Instance; + typeof(BattleHudView).GetField("_inputEnabled", fields).SetValue(view, true); + typeof(BattleHudView).GetField("_viewport", fields).SetValue(view, new BattleHudViewport(new Rect(0, 0, 800, 600), default)); + var hits = (System.Collections.Generic.List<(string, Rect)>)typeof(BattleHudView).GetField("_hitControls", fields).GetValue(view); + hits.Add((row, new Rect(100, 100, 40, 40))); + var pointer = new Vector2(120, 120); + int before = session.RecordedInputCount; + hud.SetCategory(3); + Assert.That(view.SendPointer(BattleHudIntentKind.PointerMove, 0, pointer), Is.False); + Assert.That(hud.InspectAbilityRow(row), Is.False); + Assert.That(session.RecordedInputCount, Is.EqualTo(before)); + + hud.SetCategory(1); + Assert.That(view.SendPointer(BattleHudIntentKind.PointerMove, 0, pointer), Is.True); + Assert.That(session.RecordedInputCount, Is.EqualTo(before + 1)); + Assert.That(session.Inputs.Last().Kind, Is.EqualTo(BattleInputKind.MagicMenuFieldDenial)); + } + + private static void ReadyAfterDefending(BattleSession session, string actor) + { + Assert.That(session.Submit(session.WaitingActor, BattleAction.Defend), Is.True); + for (int tick = 0; tick < 1000 && session.WaitingActor != actor; tick++) + { + if (session.WaitingActor is { } other) + Assert.That(session.Submit(other, BattleAction.Defend), Is.True); + session.Step(); + } + Assert.That(session.WaitingActor, Is.EqualTo(actor)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ANewMonsterGenerationRequiresAFreshPointerPress(string variant) + { + BattleSession session = Session(variant); + var hud = new BattleHudPresenter(); + hud.Synchronize(session); + Assert.That(hud.ChooseAction(BattleAction.Attack), Is.True); + var down = new BattleHudIntent(BattleHudIntentKind.PointerDown, "target:E", 7); + var up = new BattleHudIntent(BattleHudIntentKind.PointerUp, "target:E", 7); + Assert.That(hud.Handle(down), Is.True); + var generations = (System.Collections.Generic.Dictionary)typeof(BattleSession) + .GetField("_monsterGenerations", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + generations["E"] = 1; + hud.Synchronize(session); + Assert.That(hud.Handle(up), Is.False); + Assert.That(session.Inputs.Any(input => input.Kind == BattleInputKind.Command), Is.False); + Assert.That(hud.Handle(down), Is.True); + Assert.That(hud.Handle(up), Is.True); + Assert.That(session.Inputs.Last().Action, Is.EqualTo(BattleAction.Attack)); + } + + [Test] + public void ManualEnemyControllerKeepsItsExplicitToolAiEditingPath() + { + BattleSession session = Session(); + session.Submit("A", BattleAction.Defend); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(presenter.Controller, Is.EqualTo("E")); + int input = session.Inputs.Count; + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "ai")); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "flag:5")); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "end")), Is.True); + Assert.That(session.Inputs.Skip(input).Select(value => value.Kind), Is.EqualTo(new[] { BattleInputKind.AiProfile })); + } + + [Test] + public void AllTargetConfirmationRecordsTheNativeGroupMaskWithoutAnInventedSingleRecipient() + { + BattleSession session = Session(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + presenter.Open(BattleHudPage.Magic); + presenter.SetCategory(1); + Assert.That(presenter.ChooseAbility(302), Is.True); + Assert.That(presenter.SelectTarget("E3"), Is.True); + BattleInput command = session.Inputs.Last(input => input.Kind == BattleInputKind.Command); + Assert.That(command.Target, Is.Null); + Assert.That(command.AbilityId, Is.EqualTo(302)); + } + + [Test] + public void AllTargetNormalAttackKeepsTheRequiredLegalAnchor() + { + BattleSession session = Session(normalRange: BattleTargetRange.OpponentAll); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + Assert.That(presenter.ChooseAction(BattleAction.Attack), Is.True); + Assert.That(presenter.SelectTarget("E"), Is.True); + Assert.That(session.Inputs.Last(input => input.Kind == BattleInputKind.Command).Target, Is.EqualTo("E")); + } + + [Test] + public void TouchPanCanStartFromADisabledRowAndAnotherPointerCannotTakeIt() + { + var view = new BattleHudView(); + view.Presenter.Synchronize(Session()); + view.Presenter.Open(BattleHudPage.Magic); + void Set(string name, object value) => typeof(BattleHudView).GetField(name, BindingFlags.NonPublic | BindingFlags.Instance).SetValue(view, value); + Set("_interaction", new BattleHudInteractionProfile(true)); + Set("_viewport", new BattleHudViewport(new Rect(0, 0, 320, 640), default)); + Set("_touchPanel", new Rect(10, 100, 300, 400)); + Set("_touchScrollLimit", 1000f); + Set("_touchPanelScale", .5f); + var gesture = typeof(BattleHudView).GetMethod("TouchGesture", BindingFlags.NonPublic | BindingFlags.Instance); + bool Send(BattleHudIntentKind kind, int pointer, Vector2 point) => (bool)gesture.Invoke(view, new object[] { kind, pointer, point }); + Assert.That(Send(BattleHudIntentKind.PointerDown, 11, new Vector2(50, 300)), Is.False); + Assert.That(view.Presenter.CapturedPointerId, Is.Null); + Assert.That(Send(BattleHudIntentKind.PointerDown, 12, new Vector2(50, 310)), Is.True); + Assert.That(Send(BattleHudIntentKind.PointerMove, 11, new Vector2(50, 200)), Is.True); + Vector2 scroll = (Vector2)typeof(BattleHudView).GetField("_listScroll", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(view); + Assert.That(scroll.y, Is.GreaterThan(0)); + Assert.That(typeof(BattleHudView).GetField("_scrollFocus", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(view), Is.EqualTo(view.Presenter.FocusedId), "A pan must not become an automatic scroll-to-focus on the next repaint."); + Assert.That(Send(BattleHudIntentKind.PointerUp, 12, new Vector2(50, 190)), Is.True); + Assert.That(Send(BattleHudIntentKind.PointerUp, 11, new Vector2(50, 200)), Is.True); + Assert.That(typeof(BattleHudView).GetField("_touchCandidatePointer", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(view), Is.Null); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NativeScrollbarCaptureReceivesTheWholeGestureWithoutBreakingRowPan(string variant) + { + var view = new BattleHudView(); + view.Presenter.Synchronize(Session(variant)); + view.Presenter.Open(BattleHudPage.Magic); + const BindingFlags fields = BindingFlags.NonPublic | BindingFlags.Instance; + void Set(string name, object value) => typeof(BattleHudView).GetField(name, fields).SetValue(view, value); + Set("_interaction", new BattleHudInteractionProfile(true)); + Set("_touchPanel", new Rect(10, 100, 300, 400)); + Set("_touchScrollLimit", 1000f); + var gesture = typeof(BattleHudView).GetMethod("TouchGesture", fields); + bool Send(BattleHudIntentKind kind, Vector2 point) => (bool)gesture.Invoke(view, new object[] { kind, 11, point }); + int previous = GUIUtility.hotControl; + try + { + GUIUtility.hotControl = 0; + Assert.That(Send(BattleHudIntentKind.PointerDown, new Vector2(300, 300)), Is.False); + // Model the owner established by BeginScrollView after Down. + // The adapter must leave Move/Up and the native capture alone; + // the separate desktop test exercises the actual scrollbar. + GUIUtility.hotControl = 7001; + Assert.That(Send(BattleHudIntentKind.PointerMove, new Vector2(300, 200)), Is.False); + Assert.That(Send(BattleHudIntentKind.PointerUp, new Vector2(300, 200)), Is.False); + Assert.That(GUIUtility.hotControl, Is.EqualTo(7001)); + Assert.That(typeof(BattleHudView).GetField("_touchCandidatePointer", fields).GetValue(view), Is.Null); + Assert.That((Vector2)typeof(BattleHudView).GetField("_listScroll", fields).GetValue(view), Is.EqualTo(Vector2.zero)); + GUIUtility.hotControl = 0; + Assert.That(Send(BattleHudIntentKind.PointerDown, new Vector2(50, 300)), Is.False); + Assert.That(Send(BattleHudIntentKind.PointerMove, new Vector2(50, 200)), Is.True); + Assert.That(Send(BattleHudIntentKind.PointerUp, new Vector2(50, 200)), Is.True); + Assert.That(((Vector2)typeof(BattleHudView).GetField("_listScroll", fields).GetValue(view)).y, Is.GreaterThan(0)); + } + finally + { + GUIUtility.hotControl = previous; + } + } + + [TestCase(100, 30, 1600, 900)] + [TestCase(17, 51, 700, 1000)] + public void LetterboxingAndHitTestingShareTheSameNonzeroViewport(float x, float y, float width, float height) + { + Rect available = new(x, y, width, height); + Rect content = BattleHudLayout.ContentRect(available); + Assert.That(content.width / content.height, Is.EqualTo(4f / 3).Within(.00001)); + Assert.That(Vector2.Distance(content.center, available.center), Is.LessThan(.001)); + Vector2 point = new(75, 400); + Vector2 pixel = BattleHudLayout.ToViewport(point, content); + Assert.That(Vector2.Distance(BattleHudLayout.ToCanvas(pixel, content), point), Is.LessThan(.001)); + Assert.That(BattleHudLayout.Hit(new Rect(63, 381, 46, 46), pixel, content), Is.True); + Assert.That(BattleHudLayout.Hit(new Rect(63, 381, 46, 46), available.position, content), Is.False); + } + + [TestCase(0d, 200f / 255)] + [TestCase(Math.PI / 24, 250f / 255)] + [TestCase(Math.PI / 8, 150f / 255)] + public void NativeStatusPulseKeepsFractionalLuminance(double seconds, float expected) + { + Assert.That(BattleHudLayout.StatusLuminance(seconds), Is.EqualTo(expected).Within(.00001)); + Assert.That(BattleHudLayout.StatusLuminance(seconds), Is.GreaterThan(.5f)); + } + + [TestCase(BattleHudPage.Skills, BattleHudDirection.Down, 400)] + [TestCase(BattleHudPage.Skills, BattleHudDirection.Up, 402)] + [TestCase(BattleHudPage.Magic, BattleHudDirection.Down, 400)] + [TestCase(BattleHudPage.Magic, BattleHudDirection.Up, 402)] + [TestCase(BattleHudPage.Items, BattleHudDirection.Down, 400)] + [TestCase(BattleHudPage.Items, BattleHudDirection.Up, 402)] + public void FirstNavigationIntoAnAllDisabledListInspectsItsBoundaryRow(BattleHudPage page, BattleHudDirection direction, int expected) + { + var scenario = new BattleScenario { Scene = "disabled-list", DataFingerprint = "disabled-list" }; + foreach (var entry in new[] { (Id: "A", Actor: 101, Side: BattleSide.Ally), (Id: "E", Actor: 701, Side: BattleSide.Enemy) }) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = entry.Id, + ActorId = entry.Actor, + Side = entry.Side, + Attributes = new[] { 100, 100, 100, 20, 10, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 100, 100, 100 } + }); + BattleAbilityDefinition[] abilities = Enumerable.Range(400, 3).Select(id => new BattleAbilityDefinition(new BattleAbilityData + { + Id = id, + Name = "Unavailable " + id, + UnsupportedReason = "This authored effect has no verified battle handler.", + IsMagic = page == BattleHudPage.Magic, + SkillTypeId = page == BattleHudPage.Magic ? 2 : 0, + ElementMask = 1, + IsItem = page == BattleHudPage.Items, + ItemType = 1, + Range = BattleTargetRange.OpponentSingle, + ApplicableIdentities = new[] { 0 }, + Costs = new[] { new BattleCost(2, BattleValueMode.Absolute, 100000) } + })).ToArray(); + foreach (BattleAbilityDefinition ability in abilities) + { + scenario.Participants[0].Skills.Add(new BattleSkill { Id = ability.Id, Mastered = true }); + scenario.Items.Add(new BattleItem { Id = ability.Id, Count = 1 }); + } + bool item = page == BattleHudPage.Items; + var definitions = new BattleDefinitions("PAL3", "disabled-list", item ? Array.Empty() : abilities, + item ? abilities : Array.Empty(), scenario.Participants.Select(actor => + new BattleActorDefinition(new BattleActorData { InstanceId = actor.InstanceId, Identity = actor.Side == BattleSide.Ally ? 0 : -1 }))); + var session = new BattleSession(new BattleSetup(scenario), new Catalog(), new Rules(), definitions); + session.SetAutomatic(BattleSide.Enemy, false); + session.Step(); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session); + presenter.Open(page); + Assert.That(presenter.Abilities().Count, Is.EqualTo(3)); + Assert.That(presenter.Abilities().All(ability => ability.Denied != null), Is.True); + int inputs = session.Inputs.Count; + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: direction)), Is.True); + Assert.That(presenter.FocusedId, Is.EqualTo("ability:" + expected)); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm)), Is.False); + Assert.That(session.Inputs.Count, Is.EqualTo(inputs), "Disabled rows are inspectable without issuing a command."); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: direction)); + Assert.That(presenter.FocusedId, Is.EqualTo("ability:401")); + } + + [Test] + public void ReleasedVariantsHaveIndependentPortraitAndQueueProfiles() + { + var pal3 = new BattleHudLayout("PAL3"); + var pal3a = new BattleHudLayout("PAL3A"); + Assert.That(pal3.StateFace(0), Is.EqualTo("state/jingtian")); + Assert.That(pal3a.StateFace(0), Is.EqualTo("state/tx1")); + Assert.That(pal3a.StateName(2), Is.EqualTo("state/wz_px")); + Assert.That(pal3.AttackPortrait(0, 0, false).x, Is.EqualTo(460)); + Assert.That(pal3a.AttackPortrait(0, 0, false).x, Is.EqualTo(387)); + Assert.That(BattleHudLayout.StateCard(4, 1), Is.EqualTo(BattleHudLayout.StateCard(0))); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTests.cs.meta new file mode 100644 index 00000000..8275df4b --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 116e9843869340f48e7f655368b96f78 diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTextTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTextTests.cs new file mode 100644 index 00000000..47f0f059 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTextTests.cs @@ -0,0 +1,84 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using NUnit.Framework; + using Battle.Presentation; + using UnityEngine; + + public sealed class BattleHudTextTests + { + [TestCase(null, "")] + [TestCase("", "")] + [TestCase("Only an inventory description", "")] + [TestCase("Long inventory text$Short battle text", "Short battle text")] + [TestCase("First$Second$Last", "Last")] + [TestCase("Inventory$主#", "主#")] + [TestCase("Inventory$", "")] + public void DescriptionUsesOnlyTheLastNativeSuffix(string original, string expected) => + Assert.That(BattleHudText.Description(original), Is.EqualTo(expected)); + + [Test] + public void NativeCellsWrapPerGlyphAndStopAtTheBottom() + { + var glyphs = BattleHudText.Layout("AB中文C", 32, 32, 16); + Assert.That(glyphs.Select(glyph => (glyph.Text, glyph.Column, glyph.Row)), Is.EqualTo(new[] + { + ("A", 0, 0), ("B", 1, 0), ("中", 2, 0), ("文", 0, 1), ("C", 2, 1) + })); + Assert.That(string.Concat(BattleHudText.Layout("AB中文C", 32, 16, 16).Select(glyph => glyph.Text)), Is.EqualTo("AB中")); + Assert.That(BattleHudText.Layout("中", 200, 15, 16), Is.Empty); + } + + [Test] + public void NativeEscapesUseNewlineAndEightCellTabWithoutInterpretingHash() + { + var glyphs = BattleHudText.Layout(@"甲\n乙\t丙#\9丁", 160, 32, 16); + Assert.That(glyphs.Select(glyph => (glyph.Text, glyph.Column, glyph.Row)), Is.EqualTo(new[] + { + ("甲", 0, 0), ("乙", 0, 1), ("丙", 8, 1), ("#", 10, 1), ("丁", 11, 1) + })); + Assert.That(BattleHudText.Layout("甲\r\n乙\0丙", 160, 32, 16).Select(glyph => (glyph.Text, glyph.Column, glyph.Row)), Is.EqualTo(new[] { ("甲", 0, 0), ("乙", 4, 0) })); + } + + [Test] + public void OriginalTextRegionsKeepDescriptionGlyphsBelowTheListAndAboveStateCards() + { + foreach (bool pal3A in new[] { false, true }) + foreach (BattleHudPage page in new[] { BattleHudPage.Skills, BattleHudPage.Magic, BattleHudPage.Items }) + { + Rect list = BattleHudText.ListBounds(page, pal3A), description = BattleHudText.DescriptionBounds(page, pal3A); + Assert.That(description.y, Is.GreaterThanOrEqualTo(list.yMax)); + Assert.That(description.height, Is.GreaterThanOrEqualTo(BattleHudText.DescriptionFontSize)); + float panelY = page == BattleHudPage.Skills ? 237 : pal3A ? 258 : page == BattleHudPage.Magic ? 276 : 278; + Assert.That(panelY + description.y + BattleHudText.DescriptionFontSize, Is.LessThan(491)); + } + Assert.That(BattleHudText.ListBounds(BattleHudPage.Skills, true).y, Is.EqualTo(92)); + Assert.That(BattleHudText.ListBounds(BattleHudPage.Skills, false).y, Is.EqualTo(110)); + } + + [Test] + [Category("LocalGameData")] + public void RealDatabaseDescriptionsKeepTheOriginalBattleSuffix() + { + string configured = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root) && configured == null) + Assert.Ignore("Original local data unavailable."); + using var data = new BattleData(root, 936); + foreach ((int id, string expected) in new[] { (316, "全 减少精"), (317, "单 解除眠乱狂"), (4101, "偷取物品或金钱") }) + { + string original = data.Database.SkillInfos[id].Description; + Assert.That(BattleHudText.Description(original).TrimEnd('\r', '\n'), Is.EqualTo(expected)); + Assert.That(string.Concat(BattleHudText.Layout(BattleHudText.Description(original), 193, 20, 16).Select(glyph => glyph.Text)), Is.EqualTo(expected)); + Assert.That(data.Database.SkillInfos[id].Description, Is.EqualTo(original)); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTextTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTextTests.cs.meta new file mode 100644 index 00000000..4326cd9b --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleHudTextTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: e3bfbd47fb3a4de9b1ae3ac0678549f6 diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberLayoutTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberLayoutTests.cs new file mode 100644 index 00000000..7bc7144f --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberLayoutTests.cs @@ -0,0 +1,32 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using Battle.Presentation; + using NUnit.Framework; + using UnityEngine; + + public sealed class BattleNumberLayoutTests + { + [TestCase(2100, 900)] + [TestCase(800, 600)] + [TestCase(1200, 600)] + [TestCase(800, 800)] + public void NumberPlacementUsesTheWorldProjectionAndUniformSafeAreaScale(int width, int height) + { + var viewport = new BattleHudViewport(new Rect(43, 27, width, height), new Vector4(31, 17, 29, 23)); + var point = new Vector2(43 + width * .4f, 27 + height * .3f); + var frame = new BattleNumberFrame("-123", default, -16, 10, 0x3232ff, 255); + Rect bounds = BattlePreview.NumberBounds(frame, point, viewport); + Assert.That(bounds.x, Is.EqualTo(point.x - 16 * viewport.Scale)); + Assert.That(bounds.y, Is.EqualTo(point.y - 10 * viewport.Scale)); + Assert.That(bounds.width, Is.EqualTo(40 * viewport.Scale)); + Assert.That(bounds.height, Is.EqualTo(20 * viewport.Scale)); + Assert.That(viewport.SafeRect.Contains(bounds.min), Is.True); + Assert.That(viewport.SafeRect.Contains(bounds.max), Is.True); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberLayoutTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberLayoutTests.cs.meta new file mode 100644 index 00000000..d1fa01a1 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberLayoutTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f22a23063e5d4baa8b7d66d2f2f03607 diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberRenderingTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberRenderingTests.cs new file mode 100644 index 00000000..269bb76f --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberRenderingTests.cs @@ -0,0 +1,211 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using UnityEditor; + using UnityEngine; + using UnityEngine.TestTools; + + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleNumberRenderingTests + { + private sealed class Canvas : IDisposable + { + public static readonly Vector2 Size = new(1320, 940); + private readonly OffscreenGui _gui; + + public readonly BattleEditorSession Editor; + public Rect Area; + public int Repaints; + public bool Restored; + + public Canvas(BattleEditorSession editor) + { + Editor = editor; + _gui = new OffscreenGui(Draw); + } + + public RenderTexture RenderTarget => _gui.RenderTarget; + + public void Paint() + { + int before = Repaints; + _gui.Paint(Size); + Assert.That(Repaints, Is.GreaterThan(before)); + } + + public void Dispose() => _gui.Dispose(); + + private void Draw() + { + if (Editor?.Battle == null) + return; + EditorGUI.DrawRect(Area, Color.black); + Color color = GUI.color; + Matrix4x4 matrix = GUI.matrix; + Editor.Preview.DrawBattleNumbers(Editor.Battle, Area, new Vector4(13, 9, 17, 11)); + Restored = GUI.color == color && GUI.matrix == matrix; + if (Event.current.type == EventType.Repaint) + Repaints++; + } + } + + [Test] + public void OriginalGlyphInkIsActuallyDrawnAtTheWorldProjectionInAllFourViewports() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT") ?? + Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root)) + Assert.Ignore("Original local data unavailable."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = editor.Data.Scenes.First(), + DataFingerprint = editor.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + editor.Preview.View.SetHorizontalCameraOrientation(new Vector3(0, 0, -10), Vector3.forward, Vector3.up, 50); + // A published activation is an immutable presentation input. Avoid + // running AI while independently testing the real IMGUI draw path. + var events = (List)typeof(BattleSession).GetField("_events", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(editor.Battle); + var number = new BattleEvent(); + void Set(string name, object value) => typeof(BattleEvent).GetProperty(name).SetValue(number, value); + Set(nameof(BattleEvent.Kind), BattleEventKind.NumberShown); + Set(nameof(BattleEvent.Target), scenario.Participants[0].InstanceId); + Set(nameof(BattleEvent.RequestedDelta), -123); + Set(nameof(BattleEvent.Resource), 0); + Set(nameof(BattleEvent.DurationSeconds), 2f); + Set(nameof(BattleEvent.NumberPosition), new BattleMovementPoint(0, 0, 0)); + Set(nameof(BattleEvent.NumberOffset), 16); + events.Add(number); + using var canvas = new Canvas(editor); + foreach (Vector2 size in new[] { new Vector2(1050, 450), new Vector2(800, 600), new Vector2(1200, 600), new Vector2(800, 800) }) + { + canvas.Area = new Rect(new Vector2(30, 60), size); + canvas.Paint(); + Assert.That(canvas.Restored, Is.True, "Number drawing must restore the caller's GUI state."); + AssertGlyphPixels(canvas); + } + var cache = (Dictionary)typeof(BattlePreview).GetField("_numberGlyphs", BindingFlags.Instance | BindingFlags.NonPublic) + .GetValue(editor.Preview); + Texture2D[] glyphs = cache.Values.ToArray(); + Assert.That(cache.ContainsKey('1'), Is.True); + editor.Dispose(); + Assert.That(glyphs.All(texture => texture == null), Is.True, + "Disposing the preview must release its generated native glyph cache."); + LogAssert.NoUnexpectedReceived(); + } + + [Test] + public void RealPhysicalWorkPublishesAndDrawsItsDamageNumber() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original local data unavailable."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = editor.Data.Scenes.First(), + DataFingerprint = editor.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + BattleParticipant ally = editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + int enemyId = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + BattleParticipant enemy = editor.Data.CreateParticipant(enemyId, BattleSide.Enemy, BattleSlot.Water); + foreach (BattleParticipant actor in new[] { ally, enemy }) + { + actor.Attributes = new[] { 5000, 100, 100, 70, 10, 3, 0, 0, 0, 0, 0, 0 }; + actor.Vitals = new[] { 5000, 100, 100 }; + actor.Skills.Clear(); + scenario.Participants.Add(actor); + } +#if PAL3 + ally.Equipment[0] = 6601; +#endif + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + Assert.That(editor.Battle.Submit(ally.InstanceId, BattleAction.Attack, enemy.InstanceId), Is.True); + for (int step = 0; step < 500 && !editor.Battle.Events.Any(entry => entry.Kind == BattleEventKind.NumberShown); step++) + editor.StepBattle(); + BattleEvent number = editor.Battle.Events.Single(entry => entry.Kind == BattleEventKind.NumberShown); + Assert.That(number.Target, Is.EqualTo(enemy.InstanceId)); + Assert.That(number.RequestedDelta, Is.LessThan(0)); + Assert.That(editor.Battle.Events.Any(entry => entry.Kind == BattleEventKind.Hit && entry.Target == number.Target), Is.True); + Assert.That(editor.Preview.NumberFrames.Count, Is.EqualTo(1), "Session synchronization must feed the production projection."); + Vector3 anchor = BattleAnimationCatalog.UnityPosition(number.NumberPosition); + editor.Preview.View.SetHorizontalCameraOrientation(anchor + new Vector3(0, 0, -10), Vector3.forward, Vector3.up, 50); + using var canvas = new Canvas(editor); + canvas.Area = new Rect(30, 60, 800, 600); + canvas.Paint(); + Assert.That(canvas.Restored, Is.True); + AssertGlyphPixels(canvas, number); + LogAssert.NoUnexpectedReceived(); + } + + private static void AssertGlyphPixels(Canvas canvas, BattleEvent activation = null) + { + RenderTexture buffer = canvas.RenderTarget; + Assert.That(buffer, Is.Not.Null); + Vector2 density = new(buffer.width / Canvas.Size.x, buffer.height / Canvas.Size.y); + // The independent camera centers the anchor. The first stack raises + // the glyphs by ten points and the native glyph height is twenty. + var context = new BattleHudViewport(canvas.Area, new Vector4(13, 9, 17, 11)); + float elapsed = activation == null ? 0 : Math.Max(0, BattleStageScheduler.TimeAt(canvas.Editor.Battle.SimulationTick) - activation.NumberStartedTime); + int offset = activation == null ? 0 : activation.NumberOffset - 16; + int rise = (int)Math.Round(elapsed * 30, MidpointRounding.ToEven); + int width = activation == null ? 40 : activation.RequestedDelta.ToString(System.Globalization.CultureInfo.InvariantCulture).Length * 10; + Vector2 start = canvas.Area.center + new Vector2(offset, -10 - rise) * context.Scale; + Rect expected = new(Vector2.Scale(start, density), Vector2.Scale(new Vector2(width, 20) * context.Scale, density)); + Rect area = new(Vector2.Scale(canvas.Area.position, density), Vector2.Scale(canvas.Area.size, density)); + var texture = new Texture2D(buffer.width, buffer.height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = buffer; + texture.ReadPixels(new Rect(0, 0, buffer.width, buffer.height), 0, 0); + texture.Apply(); + Color32[] pixels = texture.GetPixels32(); + int ink = 0, outside = 0; + Rect tolerance = Rect.MinMaxRect(expected.xMin - 2, expected.yMin - 2, expected.xMax + 2, expected.yMax + 2); + for (int y = Math.Max(0, (int)area.yMin); y < Math.Min(buffer.height, area.yMax); y++) + for (int x = Math.Max(0, (int)area.xMin); x < Math.Min(buffer.width, area.xMax); x++) + { + Color32 pixel = pixels[(buffer.height - 1 - y) * buffer.width + x]; + if (pixel.b < 140 || pixel.r > 120 || pixel.g > 120) + continue; + ink++; + if (!tolerance.Contains(new Vector2(x, y))) + outside++; + } + Assert.That(ink, Is.GreaterThan(20), "The production draw path must render native TFT glyph ink."); + Assert.That(outside, Is.Zero, "Actual glyph pixels drifted away from the projected 10-pixel cells: " + expected); + } + finally + { + RenderTexture.active = previous; + UnityEngine.Object.DestroyImmediate(texture); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberRenderingTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberRenderingTests.cs.meta new file mode 100644 index 00000000..a5feaa68 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleNumberRenderingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 922e6a6df6a6400bb790e8c99832295d diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleSceneFieldRenderingTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleSceneFieldRenderingTests.cs new file mode 100644 index 00000000..24b89ecb --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleSceneFieldRenderingTests.cs @@ -0,0 +1,183 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using UnityEditor; + using UnityEngine; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + +#if PAL3A + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleSceneFieldRenderingTests + { + private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + private sealed class Canvas : IDisposable + { + public static readonly Vector2 Size = new(1180, 800); + private readonly OffscreenGui _gui; + + public readonly BattleEditorSession Editor; + public readonly BattleHudView Hud = new(); + public Rect Area = new(20, 40, 800, 600); + public Texture2D Reference; + public Rect ReferenceArea; + + public Canvas(BattleEditorSession editor) + { + Editor = editor; + _gui = new OffscreenGui(Draw); + } + + public RenderTexture RenderTarget => _gui.RenderTarget; + + public void Paint() => _gui.Paint(Size); + + public void Dispose() => _gui.Dispose(); + + private void Draw() + { + if (Editor?.Battle == null) + return; + EditorGUI.DrawRect(Area, Color.black); + Hud.Draw(Editor.Battle, Editor.Data, Editor.Preview, Area, () => { }, _ => { }); + if (Reference != null) + using (new BattleHudCanvas(new BattleHudViewport(Area, default))) + GUI.DrawTextureWithTexCoords(ReferenceArea, Reference, + new Rect(0, 0, 45f / Reference.width, 60f / Reference.height), true); + } + } + + private static object Actor(BattleSession battle, BattleSide side) => + ((IDictionary)typeof(BattleSession).GetField("_byId", Flags).GetValue(battle))[ + battle.Actors.First(actor => actor.Side == side).Id]; + + private static Color32[] Region(Canvas canvas, Rect native) => Regions(canvas, native)[0]; + + private static Color32[][] Regions(Canvas canvas, params Rect[] regions) + { + RenderTexture buffer = canvas.RenderTarget; + Assert.That(buffer, Is.Not.Null); + var viewport = new BattleHudViewport(canvas.Area, default); + Vector2 pixelsPerPoint = new(buffer.width / Canvas.Size.x, buffer.height / Canvas.Size.y); + var image = new Texture2D(buffer.width, buffer.height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = buffer; + image.ReadPixels(new Rect(0, 0, buffer.width, buffer.height), 0, 0); + image.Apply(); + Color32[] pixels = image.GetPixels32(); + string evidenceRoot = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (regions.Length > 1 && !string.IsNullOrEmpty(evidenceRoot)) + { + string folder = Path.Combine(evidenceRoot, "SceneField"); + Directory.CreateDirectory(folder); + string name = $"{canvas.Area.width}x{canvas.Area.height}-{canvas.Editor.Battle.FiveSpiritForce}-{canvas.Editor.Battle.FiveSpiritElement}"; + File.WriteAllBytes(Path.Combine(folder, name + ".png"), image.EncodeToPNG()); + string pixelsAt = string.Join("; ", regions.Select(rect => Vector2.Scale(viewport.ToViewport(rect.position), pixelsPerPoint).ToString("F3"))); + File.WriteAllText(Path.Combine(folder, name + ".txt"), $"Area={canvas.Area}; buffer={buffer.width}x{buffer.height}; pixelsPerPoint={pixelsPerPoint}; pixel origins={pixelsAt}; regions={string.Join("; ", regions.Select(rect => rect.ToString()))}"); + } + return regions.Select(native => Enumerable.Range(0, 45 * 60).Select(index => + { + Vector2 sample = native.position + new Vector2(index % 45 + .5f, index / 45 + .5f); + Vector2 point = Vector2.Scale(viewport.ToViewport(sample), pixelsPerPoint); + int x = Mathf.Clamp((int)point.x, 0, buffer.width - 1); + int y = Mathf.Clamp((int)point.y, 0, buffer.height - 1); + return pixels[(buffer.height - 1 - y) * buffer.width + x]; + }).ToArray()).ToArray(); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + + [Test] + public void ActualHudShowsAllTenNativeTemporaryFieldPicturesAndHidesAfterTheFifthAnchorAction() + { + string root = Environment.GetEnvironmentVariable("PAL3A_TEST_DATA_ROOT") ?? + Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data/PAL3A")); + if (!Directory.Exists(root)) + Assert.Ignore("Original local data unavailable."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = editor.Data.Scenes.First(), DataFingerprint = editor.Data.Fingerprint }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + string initialScene = editor.Battle.ActiveScene; + int initialElement = editor.Battle.SceneElement; + using var canvas = new Canvas(editor); + foreach (Rect area in new[] { new Rect(20, 40, 800, 600), new Rect(20, 100, 1050, 450) }) + { + canvas.Area = area; + canvas.Reference = null; + canvas.Paint(); + var viewport = new BattleHudViewport(area, default); + Rect indicator = new(viewport.CanvasSize.x - 56, 81, 45, 60); + // Keep both Point-filtered images at the same subpixel phase. + // The tested scales (1 and .75) map this gap to 600/450 points. + canvas.ReferenceArea = new Rect(indicator.x - 600, indicator.y, 45, 60); + Color32[] neutral = Region(canvas, indicator); + foreach (int force in new[] { 1, 2 }) + foreach (int element in Enumerable.Range(1, 5)) + { + int skill = new[] { 264, 265, 267, 266, 268 }[element - 1]; + typeof(BattleSession).GetMethod("ResolveAiSceneMagic", Flags).Invoke(editor.Battle, + new[] { Actor(editor.Battle, force == 1 ? BattleSide.Ally : BattleSide.Enemy), editor.Battle.Definitions.Skills[skill] }); + Assert.That((editor.Battle.FiveSpiritElement, editor.Battle.FiveSpiritForce), Is.EqualTo((element, force))); + int resource = new[] { 0, 1, 3, 2, 4 }[element - 1]; + canvas.Reference = editor.Preview.View.GetTexture($"basedata.cpk\\ui\\combat\\control\\{(force == 1 ? "w" : "e")}_sx{resource}.tga"); + Assert.That((canvas.Reference.width, canvas.Reference.height), Is.EqualTo((64, 128))); + FilterMode filter = canvas.Reference.filterMode; + canvas.Reference.filterMode = FilterMode.Point; + canvas.Paint(); + Color32[][] regions = Regions(canvas, indicator, canvas.ReferenceArea); + Color32[] shown = regions[0], reference = regions[1]; + Color32[] source = canvas.Reference.GetPixels32(); + int samples = 0, matches = 0; + for (int y = 1; y < 59; y++) + for (int x = 1; x < 44; x++) + { + if (source[(59 - y) * 64 + x].a < 250) + continue; + samples++; + Color32 a = shown[y * 45 + x], b = reference[y * 45 + x]; + if (Math.Abs(a.r - b.r) < 16 && Math.Abs(a.g - b.g) < 16 && Math.Abs(a.b - b.b) < 16) + matches++; + } + canvas.Reference.filterMode = filter; + Assert.That(samples, Is.GreaterThan(30)); + Assert.That(matches / (double)samples, Is.GreaterThan(.9), $"field {element}:{force} at {area} must show its original cropped bitmap at the native right anchor."); + for (int action = 0; action < 5; action++) + typeof(BattleSession).GetMethod("AdvanceFiveSpiritFieldTurn", Flags).Invoke(editor.Battle, new[] { Actor(editor.Battle, BattleSide.Ally) }); + Assert.That((editor.Battle.FiveSpiritElement, editor.Battle.FiveSpiritForce), Is.EqualTo((0, 0))); + canvas.Reference = null; + canvas.Paint(); + Assert.That(Region(canvas, indicator), Is.EqualTo(neutral), "Expiry must hide the persistent indicator and restore the underlying HUD."); + Assert.That(editor.Battle.ActiveScene, Is.EqualTo(initialScene)); + Assert.That(editor.Battle.SceneElement, Is.EqualTo(initialElement), "Temporary field UI must not recolor the base scene formation."); + } + } + LogAssert.NoUnexpectedReceived(); + } + } +#endif +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleSceneFieldRenderingTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleSceneFieldRenderingTests.cs.meta new file mode 100644 index 00000000..c6c8350a --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleSceneFieldRenderingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 594e751ec881455abed5e34e58b9b025 diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleSpiritNavigationTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleSpiritNavigationTests.cs new file mode 100644 index 00000000..3d84814e --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleSpiritNavigationTests.cs @@ -0,0 +1,142 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +#if PAL3A +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using Battle; + using Newtonsoft.Json; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using UnityEngine; + + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleSpiritNavigationTests + { + private static string Frame(BattleEditorSession editor) => JsonConvert.SerializeObject(new + { + editor.Battle.Tick, + editor.Battle.SimulationTick, + editor.Battle.SpiritOrbs, + editor.Battle.Pal3AState, + Events = editor.Battle.Events.ToArray(), + Inputs = editor.Battle.Inputs.ToArray(), + editor.Battle.Actors + }); + + private static void Start(BattleEditorSession editor, BattleScenario scenario) + { + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = true; + editor.Preview.Effects.Muted = true; + editor.Preview.View.SetViewportContext(new Rect(0, 0, 800, 600)); + string source = scenario.Participants[0].InstanceId; + string target = editor.Battle.GetTargetCandidates(new BattleCommand(source, BattleAction.Skill, abilityId: 4102)).First().Id; + Assert.That(editor.Battle.Submit(new BattleCommand(source, BattleAction.Skill, target, 4102)), Is.True); + } + + private static void Navigate(BattleEditorSession editor, string kind) + { + if (kind == "frame") + { + editor.Preview.View.Frame(); + return; + } + Vector2 size = new(820, 620); + using var gui = new OffscreenGui(() => editor.Preview.View.Draw(new Rect(0, 0, 800, 600))); + gui.Paint(size); + if (kind == "middle") + gui.SendEvent(new Event { type = EventType.MouseDown, button = 2, mousePosition = new Vector2(100, 100) }, size); + gui.SendEvent(new Event + { + mousePosition = new Vector2(200, 150), + type = kind == "scroll" ? EventType.ScrollWheel : EventType.MouseDrag, + button = kind == "scroll" ? 0 : 2, + delta = kind == "scroll" ? new Vector2(0, 8) : new Vector2(100, 50) + }, size); + if (kind == "middle") + gui.SendEvent(new Event { type = EventType.MouseUp, button = 2, mousePosition = new Vector2(200, 150) }, size); + } + + [TestCase("scroll", false)] + [TestCase("middle", false)] + [TestCase("frame", false)] + [TestCase("scroll", true)] + public void ActualCaptureTrajectoryAndReplayIgnoreUnrecordedPreviewNavigation(string navigation, bool authoredCamera) + { + string root = Environment.GetEnvironmentVariable("PAL3A_TEST_DATA_ROOT"); + if (root == null || !Directory.Exists(root)) + Assert.Ignore("Original PAL3A data is required."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario + { + Variant = "PAL3A", + Scene = editor.Data.Scenes.First(), + DataFingerprint = editor.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush, + Seed = 1 + }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(editor.Data.CreateParticipant(7311, BattleSide.Enemy, BattleSlot.Water)); + scenario.Participants.Add(editor.Data.CreateParticipant(7311, BattleSide.Enemy, BattleSlot.Fire)); + foreach (BattleParticipant actor in scenario.Participants) + { + actor.Attributes = new[] { 50000, 100, 1000, 5000, 1, 5, 0, 0, 0, 0, 0, 0 }; + actor.Vitals = new[] { 50000, 100, 1000 }; + actor.Skills.Clear(); + } + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 4102, Level = 4, Mastered = true }); + scenario.Participants[1].Vitals[0] = 1; + if (authoredCamera) + { + Start(editor, scenario); + editor.Preview.View.GetCamera(out Vector3 position, out Vector3 target, out float fieldOfView); + scenario.Camera = new BattleCamera + { + Override = true, + Position = new BattlePoint { X = position.x, Y = position.y, Z = position.z }, + Target = new BattlePoint { X = target.x, Y = target.y, Z = target.z }, + FieldOfView = fieldOfView + }; + } + Start(editor, scenario); + while (editor.Battle.SpiritOrbs.Count == 0 && editor.Battle.Tick < 600) + editor.StepBattle(); + Assert.That(editor.Battle.SpiritOrbs.Count, Is.EqualTo(4)); + long birth = editor.Battle.Tick; + var expected = new List { Frame(editor) }; + while (editor.Battle.SpiritOrbs.Count > 0 && expected.Count < 900) + { + editor.StepBattle(); + expected.Add(Frame(editor)); + } + Assert.That(editor.Battle.SpiritOrbs, Is.Empty); + Start(editor, scenario); + while (editor.Battle.Tick < birth - 1) + editor.StepBattle(); + editor.Preview.View.GetCamera(out Vector3 before, out _, out _); + Navigate(editor, navigation); + editor.Preview.View.GetCamera(out Vector3 changed, out _, out _); + Assert.That(changed, Is.Not.EqualTo(before), "The public preview navigation must actually change its camera."); + editor.StepBattle(); + Assert.That(Frame(editor), Is.EqualTo(expected[0])); + string atBirth = Frame(editor); + editor.ReplayBattle(); + Assert.That(Frame(editor), Is.EqualTo(atBirth)); + for (int index = 1; index < expected.Count; index++) + { + editor.StepBattle(); + Assert.That(Frame(editor), Is.EqualTo(expected[index]), $"trajectory index={index}"); + } + } + } +} +#endif diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleSpiritNavigationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleSpiritNavigationTests.cs.meta new file mode 100644 index 00000000..f6d646f0 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleSpiritNavigationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: fd7d819274874b359c0138d925879b93 diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleStageMessageRenderingTests.cs b/Assets/Tests/BattleEditor/Editor/Hud/BattleStageMessageRenderingTests.cs new file mode 100644 index 00000000..920f548a --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleStageMessageRenderingTests.cs @@ -0,0 +1,142 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using UnityEditor; + using UnityEngine; + using UnityEngine.TestTools; + + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleStageMessageRenderingTests + { + private sealed class Canvas : IDisposable + { + public static readonly Vector2 Size = new(1320, 940); + private readonly OffscreenGui _gui; + + public readonly BattleEditorSession Editor; + public Rect Area; + public int Repaints; + public bool Restored; + + public Canvas(BattleEditorSession editor) + { + Editor = editor; + _gui = new OffscreenGui(Draw); + } + + public RenderTexture RenderTarget => _gui.RenderTarget; + + public void Paint() + { + int before = Repaints; + _gui.Paint(Size); + Assert.That(Repaints, Is.GreaterThan(before)); + } + + public void Dispose() => _gui.Dispose(); + + private void Draw() + { + if (Editor?.Battle == null) + return; + EditorGUI.DrawRect(Area, Color.black); + Color color = GUI.color; + Matrix4x4 matrix = GUI.matrix; + Editor.Preview.DrawBattleMessages(Editor.Battle, Area, new Vector4(13, 9, 17, 11)); + Restored = color == GUI.color && matrix == GUI.matrix; + if (Event.current.type == EventType.Repaint) + Repaints++; + } + } + + [Test] + public void OriginalTitleTextureAndFontReachAllFourViewportBuffers() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT") ?? + Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root)) + Assert.Ignore("Original local data unavailable."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = editor.Data.Scenes.First(), + DataFingerprint = editor.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush, + MotionBlur = false + }; + scenario.Participants.Add(editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + editor.StepBattle(); + Assert.That(editor.Preview.BattleMessageText(editor.Battle.StageMessages.Single()), Is.EqualTo("我方偷袭成功")); + using var canvas = new Canvas(editor); + foreach (Vector2 size in new[] { new Vector2(1050, 450), new Vector2(800, 600), new Vector2(1200, 600), new Vector2(800, 800) }) + { + canvas.Area = new Rect(new Vector2(30, 60), size); + canvas.Paint(); + Assert.That(canvas.Restored, Is.True); + AssertMessagePixels(canvas); + } + LogAssert.NoUnexpectedReceived(); + } + + private static void AssertMessagePixels(Canvas canvas) + { + RenderTexture buffer = canvas.RenderTarget; + Assert.That(buffer, Is.Not.Null); + Vector2 density = new(buffer.width / Canvas.Size.x, buffer.height / Canvas.Size.y); + var context = new BattleHudViewport(canvas.Area, new Vector4(13, 9, 17, 11)); + float nativeX = BattleData.Variant == "PAL3A" ? ((int)context.CanvasSize.x - 161) / 2 : 300 + (context.CanvasSize.x - 800) / 2; + // Independent native UIStatic arithmetic: inset8, six 20px Chinese + // cells, center inside145x41; the glyph top is y30+8+10=48. + Vector2 location = context.ToViewport(new Vector2(nativeX + 20, 48)); + Rect text = new(Vector2.Scale(location, density), Vector2.Scale(new Vector2(120, 20) * context.Scale, density)); + Vector2 panelLocation = context.ToViewport(new Vector2(nativeX, 30)); + Rect panel = new(Vector2.Scale(panelLocation, density), Vector2.Scale(new Vector2(161, 57) * context.Scale, density)); + var image = new Texture2D(buffer.width, buffer.height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = buffer; + image.ReadPixels(new Rect(0, 0, buffer.width, buffer.height), 0, 0); + image.Apply(); + Color32[] pixels = image.GetPixels32(); + int ink = 0, background = 0; + for (int y = Math.Max(0, (int)panel.yMin); y < Math.Min(buffer.height, (int)panel.yMax); y++) + for (int x = Math.Max(0, (int)panel.xMin); x < Math.Min(buffer.width, (int)panel.xMax); x++) + { + Color32 pixel = pixels[(buffer.height - 1 - y) * buffer.width + x]; + if (text.Contains(new Vector2(x, y)) && pixel.r > 235 && pixel.g > 235 && pixel.b > 235) + ink++; + if (!text.Contains(new Vector2(x, y)) && Math.Max(pixel.r, Math.Max(pixel.g, pixel.b)) > 35) + background++; + } + Assert.That(ink, Is.GreaterThan(40), "The native TFT title must reach the expected text rectangle."); + Assert.That(background, Is.GreaterThan(30), "The original padded title background must also be rendered."); + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (!string.IsNullOrEmpty(output)) + File.WriteAllBytes(Path.Combine(output, BattleData.Variant + "-stage-title-" + canvas.Area.width + "x" + canvas.Area.height + ".png"), image.EncodeToPNG()); + } + finally + { + RenderTexture.active = previous; + UnityEngine.Object.DestroyImmediate(image); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Hud/BattleStageMessageRenderingTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Hud/BattleStageMessageRenderingTests.cs.meta new file mode 100644 index 00000000..61c3d950 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Hud/BattleStageMessageRenderingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cdb657cb85494626aa0d142cc0f0aa38 diff --git a/Assets/Tests/BattleEditor/Editor/Integration.meta b/Assets/Tests/BattleEditor/Editor/Integration.meta new file mode 100644 index 00000000..813df3b1 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a1ac2ee454ee4cf699c75aaf3af1e225 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilitiesIntegrationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilitiesIntegrationTests.cs new file mode 100644 index 00000000..97f1d21c --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilitiesIntegrationTests.cs @@ -0,0 +1,286 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Collections.Generic; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using Core.DataReader.Dat; + using NUnit.Framework; + using UnityEngine; + + // These tests load original records and action clips. A present but invalid + // data root or a failed supported resource is a failure, never a skipped case. + [Category("LocalGameData")] + public sealed class BattleAbilitiesIntegrationTests + { + private BattleData _data; + private readonly List _previews = new(); + + [SetUp] + public void Load() + { + string configured = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root) && configured == null) + Assert.Ignore("Local original data unavailable."); + Assert.That(Directory.Exists(root), Is.True, "The current variant test data root must point to its original data."); + _data = new BattleData(root, 936); + } + + [TearDown] + public void Dispose() + { + foreach (BattlePreview preview in _previews) + preview.Dispose(); + _previews.Clear(); + _data?.Dispose(); + } + + private BattleScenario Scenario() + { + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = _data.Scenes.First(), + DataFingerprint = _data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + BattleParticipant ally = _data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + ally.InstanceId = "A"; + int enemyId = _data.Database.CombatActorInfos.Keys.OrderBy(id => id).First(id => BattleAnimationCatalog.IsBasicEnemy(_data, id) && + _data.Resources.Find(FileConstants.GetActorFolderVirtualPath(_data.Database.CombatActorInfos[id].ModelId) + _data.Database.CombatActorInfos[id].ModelId + ".ini") != null); + BattleParticipant enemy = _data.CreateParticipant(enemyId, BattleSide.Enemy, BattleSlot.Fire); + enemy.InstanceId = "E"; + foreach (BattleParticipant actor in new[] { ally, enemy }) + { + actor.Level = 1; + actor.Attributes = new[] { 1000, 100, 100, 60, 10, 3, 0, 0, 0, 0, 0, 0 }; + actor.Vitals = new[] { 1000, 100, 100 }; + actor.Skills.Clear(); +#if PAL3 + if (actor.ActorId == 101) + actor.Equipment[0] = 6601; // Ordinary sword; magic-sword cultivation is a separate scenario. +#endif + scenario.Participants.Add(actor); + } + return scenario; + } + + private BattleSession Create(BattleScenario scenario, out BattleSetup setup, out BattleAnimationCatalog catalog) + { + setup = new BattleSetup(scenario); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, setup); + catalog = new BattleAnimationCatalog(_data, setup, definitions); + var preview = new BattlePreview(_data, setup); + _previews.Add(preview); + preview.Audio.Muted = true; + preview.Effects.Muted = true; + var session = new BattleSession(setup, catalog, definitions: definitions, effects: preview.Effects); + preview.BindBattle(session, catalog); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + + private static BattleActorSnapshot Actor(BattleSession session, string id) => session.Actors.Single(actor => actor.Id == id); + + private static void Steps(BattleSession session, int count) + { + for (int index = 0; index < count; index++) + session.Step(); + Assert.That(session.Status, Is.EqualTo(BattleSessionStatus.Running), session.Result?.Reason); + } + + private int NativeWorkTick(int abilityId, int preparationTicks) + { + float work = _data.Read("basedata.cpk\\cbdata\\efflinker.dat", new EffectLinkerFileReader()) + .SkillIdToEffectGroupMap[abilityId][0].WorkTimeInSeconds; + int tick = preparationTicks; + while ((double)(float)(tick * BattleSession.StepSeconds) - (float)(preparationTicks * BattleSession.StepSeconds) < work) + tick++; + return tick; + } + + private static string Trace(BattleSession session) => string.Join("\n", session.Events.Select(entry => + $"{entry.Tick}|{entry.Kind}|{entry.Source}|{entry.Target}|{entry.ActionId}|{entry.AbilityId}|{entry.Resource}|{entry.ValueBefore}|{entry.ValueAfter}|{entry.RequestedDelta}|{entry.ActualDelta}|{entry.RandomState}|{entry.Detail}")); + + [Test] + public void SpecialItemsAreClassifiedByTheirVerifiedOriginalHandlers() + { + BattleScenario scenario = Scenario(); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, new BattleSetup(scenario)); +#if PAL3 + const int lastTreasure = 6125; +#else + const int lastTreasure = 6124; + Assert.That(definitions.Items.ContainsKey(6125), Is.False); +#endif + for (int id = 6119; id <= lastTreasure; id++) + { + Assert.That(definitions.Items[id].IsTreasure, Is.True, "Treasure ID " + id); + Assert.That(definitions.Items[id].Supported, Is.True, definitions.Items[id].UnsupportedReason); + } + Assert.That(definitions.Items[6230].Handler, Is.EqualTo(BattleSpecialHandler.PoisonDragonGall)); + Assert.That(definitions.Items[6230].Supported, Is.True, definitions.Items[6230].UnsupportedReason); +#if PAL3A + Assert.That(definitions.Skills[4504].Handler, Is.EqualTo(BattleSpecialHandler.ReturnedMpAbsorb)); + Assert.That(definitions.Skills[4504].Supported, Is.True, definitions.Skills[4504].UnsupportedReason); +#endif + } + + [Test] + public void FourthMonsterSkillUsesNativeFixedProficiencyAndDoesNotReadPadding() + { +#if PAL3 + const int actorId = 726; + const int skillId = 217; +#else + const int actorId = 703; + const int skillId = 251; +#endif + var record = _data.Database.CombatActorInfos[actorId]; + Assert.That(record.SkillLevels.Length, Is.EqualTo(3)); + Assert.That(record.SkillIds[3], Is.EqualTo(skillId)); + BattleParticipant actor = _data.CreateParticipant(actorId, BattleSide.Enemy, BattleSlot.Water); + Assert.That(actor.Skills.Single(skill => skill.Id == skillId).Level, Is.EqualTo(4)); + } + + [Test] + public void RealWindSpellUsesNativeWorkTimingAndPaysFourMpAfterItsEffect() + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].Skills.Add(new BattleSkill { Id = 301, Level = 4, Mastered = true }); + BattleSession session = Create(scenario, out BattleSetup setup, out BattleAnimationCatalog catalog); + BattleAbilityDefinition wind = session.Definitions.Skills[301]; + Assert.That(wind.Supported, Is.True, wind.UnsupportedReason); + Assert.That(wind.IsMagic, Is.True); + Assert.That(wind.SkillTypeId, Is.EqualTo(2)); + Assert.That(wind.Costs.Single(cost => cost.Resource == 2).Value, Is.EqualTo(4)); +#if PAL3A + Assert.That(wind.UsesBeforeLevelUp, Is.EqualTo(new[] { 0, 10, 20, 30 })); +#else + Assert.That(wind.UsesBeforeLevelUp, Is.EqualTo(new[] { 0, 15, 30, 45 })); +#endif + var command = new BattleCommand("A", BattleAction.Skill, "E", 301); + Assert.That(session.CanSubmit(command), Is.Null, "LearningActorLevel gates the next unlock, not an already mastered spell."); + Assert.That(session.Submit(command), Is.True); + int workTick = NativeWorkTick(301, 3); + Steps(session, workTick - 1); + Assert.That(Actor(session, "E").Hp, Is.EqualTo(1000)); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(100)); + Steps(session, 1); + Assert.That(Actor(session, "E").Hp, Is.LessThan(1000)); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(96)); + Assert.That(Actor(session, "A").Skills.Single().Uses, Is.EqualTo(1)); + BattleEvent[] effects = session.Events.Where(entry => entry.Kind == BattleEventKind.Hit || entry.Kind == BattleEventKind.ResourceChanged && entry.Resource == 2).ToArray(); + Assert.That(effects.Select(entry => entry.Resource), Is.EqualTo(new[] { 0, 2 })); + var replayPreview = new BattlePreview(_data, setup); + _previews.Add(replayPreview); + replayPreview.Audio.Muted = replayPreview.Effects.Muted = true; + BattleSession replay = BattleReplay.Play(setup, catalog, session.Inputs, session.Tick, definitions: session.Definitions, + effects: replayPreview.Effects, onCreated: created => replayPreview.BindBattle(created, catalog)); + Assert.That(Trace(replay), Is.EqualTo(Trace(session))); + Assert.That(scenario.Participants[0].Vitals[2], Is.EqualTo(100)); + Assert.That(scenario.Participants[0].Skills.Single().Uses, Is.Zero); + } + + [Test] + public void RealFlameTechniqueApproachesHitsAndReturnsWithoutFaulting() + { +#if PAL3A + const int sourceId = 105, skillId = 4506, remainingSp = 75; + const BattleMovementKind approach = BattleMovementKind.Fly; +#else + const int sourceId = 102, skillId = 4505, remainingSp = 65; + const BattleMovementKind approach = BattleMovementKind.Run; +#endif + BattleScenario scenario = Scenario(); + var source = _data.CreateParticipant(sourceId, BattleSide.Ally, BattleSlot.Water); + source.InstanceId = "A"; + source.Level = 45; + source.Attributes[1] = source.Vitals[1] = 100; + source.Skills.Clear(); + source.Skills.Add(new BattleSkill { Id = skillId, Level = 4, Mastered = true }); + scenario.Participants[0] = source; + BattleParticipant enemy = scenario.Participants[1]; + enemy.Attributes[0] = enemy.Vitals[0] = 100000; + BattleSession session = Create(scenario, out _, out BattleAnimationCatalog catalog); + BattlePreview preview = _previews.Last(); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Skill, "E", skillId)), Is.True); + + bool travelled = false; + for (int step = 0; step < 500 && !session.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded && entry.Source == "A"); step++) + { + Steps(session, 1); + preview.ApplyBattle(session, catalog); + BattleActorSnapshot actor = Actor(session, "A"); + if (actor.Movement is { } motion && motion.Plan.Kind == approach && + !actor.Position.Equals(motion.Plan.From) && !actor.Position.Equals(motion.Plan.To) && + !session.Events.Any(entry => entry.Kind == BattleEventKind.Hit && entry.Source == "A")) + travelled = true; + } + + Assert.That(travelled, Is.True, "The actor must travel before impact, including when takeoff comes from a jump marker."); + Assert.That(Actor(session, "E").Hp, Is.LessThan(100000)); + Assert.That(session.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded && entry.Source == "A"), Is.True); + Assert.That(Actor(session, "A").Position, Is.EqualTo(Actor(session, "A").Home)); + Assert.That(Actor(session, "A").Sp, Is.EqualTo(remainingSp)); + } + + [Test] + public void RealMedicineConsumesOneAtStartAndHealsExactlyItsOriginalAbsoluteValue() + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].Vitals[0] = 50; + scenario.Items.Add(new BattleItem { Id = 6201, Count = 2 }); + BattleSession session = Create(scenario, out _, out _); + BattleAbilityDefinition medicine = session.Definitions.Items[6201]; + Assert.That(medicine.Supported, Is.True, medicine.UnsupportedReason); + Assert.That(medicine.BattleUsable, Is.True); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "A", 6201)), Is.True); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(2)); + Assert.That(Actor(session, "A").Hp, Is.EqualTo(50)); + Steps(session, 1); + Assert.That(session.Inventory.Single().Count, Is.EqualTo(1)); + int workTick = NativeWorkTick(6201, 2); + Steps(session, workTick - 2); + Assert.That(Actor(session, "A").Hp, Is.EqualTo(50)); + Steps(session, 1); + Assert.That(Actor(session, "A").Hp, Is.EqualTo(150)); + Assert.That(Actor(session, "A").Mp, Is.EqualTo(100)); + Assert.That(session.Events.Count(entry => entry.Kind == BattleEventKind.ItemChanged), Is.EqualTo(1)); + Assert.That(scenario.Items.Single().Count, Is.EqualTo(2)); + } + + [Test] + public void RealRevivalMedicineCanSelectEitherAllyAndRestoresTenPercentOnRevival() + { + BattleScenario scenario = Scenario(); + BattleParticipant dead = _data.CreateParticipant(104, BattleSide.Ally, BattleSlot.Fire); + dead.InstanceId = "B"; + dead.Attributes = new[] { 500, 100, 100, 60, 10, 3, 0, 0, 0, 0, 0, 0 }; + dead.Vitals = new[] { 0, 100, 100 }; + dead.Skills.Clear(); + scenario.Participants.Add(dead); + scenario.Items.Add(new BattleItem { Id = 6211, Count = 1 }); + BattleSession session = Create(scenario, out _, out _); + BattleAbilityDefinition revival = session.Definitions.Items[6211]; + Assert.That(revival.Supported, Is.True, revival.UnsupportedReason); + Assert.That(revival.Revives, Is.True); + var command = new BattleCommand("A", BattleAction.Item, "B", 6211); + Assert.That(session.GetTargetCandidates(command).Select(actor => actor.Id), Is.EquivalentTo(new[] { "A", "B" })); + Assert.That(session.Submit(command), Is.True); + Steps(session, NativeWorkTick(6211, 2)); + Assert.That(Actor(session, "B").Hp, Is.EqualTo(50)); + Assert.That(Actor(session, "B").Gauge, Is.GreaterThanOrEqualTo(11500 * 2 / 3)); + Assert.That(session.Inventory, Is.Empty); + Assert.That(dead.Vitals[0], Is.Zero); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilitiesIntegrationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilitiesIntegrationTests.cs.meta new file mode 100644 index 00000000..2b4f8c6e --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilitiesIntegrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f38835cae1d442a39ef85320e57030ce diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilityResourceTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilityResourceTests.cs new file mode 100644 index 00000000..8a2ef013 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilityResourceTests.cs @@ -0,0 +1,375 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Core.Contract.Constants; + using Core.DataReader.Dat; + using Game.Effect.Runtime; + using Newtonsoft.Json; + using NUnit.Framework; + using ResourceBrowser; + using UnityEngine; + using UnityEngine.TestTools; + + [Category("LocalGameData")] + public sealed class BattleAbilityResourceTests + { + private BattleData _data; + private readonly List _coverage = new(); + + [SetUp] + public void LoadOriginalData() + { + string configured = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + string root = configured ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root)) + { + if (configured != null) + Assert.Fail("Configured original-game data is missing: " + root); + Assert.Ignore("Local original-game data is not available."); + } + _data = new BattleData(root, 936); + _coverage.Clear(); + } + + [TearDown] + public void Dispose() + { + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_REPORT_DIR"); + if (output != null) + { + Directory.CreateDirectory(output); + File.WriteAllText(Path.Combine(output, BattleData.Variant + "-" + TestContext.CurrentContext.Test.Name + ".json"), + JsonConvert.SerializeObject(_coverage, Formatting.Indented)); + } + _data?.Dispose(); + } + + private BattleScenario Scenario(int source = 101) + { + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = _data.Scenes.First(), DataFingerprint = _data.Fingerprint }; + bool main = ActorConstants.MainActorCombatActorIdMap.ContainsValue(source); + scenario.Participants.Add(_data.CreateParticipant(main ? source : 101, BattleSide.Ally, BattleSlot.Water)); + int enemy = main ? _data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(_data, id)) : source; + scenario.Participants.Add(_data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + // These tests compile each requested record explicitly, so initial actor skills + // do not cause unrelated numeric-handler diagnostics during catalog construction. + foreach (BattleParticipant actor in scenario.Participants) + actor.Skills.Clear(); + return scenario; + } + + [Test] + public void AllReachableOrdinaryRecordsCompileTheirOriginalBodyAndBothLinkers() + { + BattleScenario basic = Scenario(); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, new BattleSetup(basic)); + var errors = new List(); + int compiled = 0; + foreach (BattleAbilityDefinition ability in definitions.Skills.Values.Concat(definitions.Items.Values) + .Where(ability => ability.BattleUsable && (ability.IsItem || ability.SkillTypeId != 4)).OrderBy(ability => ability.Id)) + { + if (!ability.Supported) + { + _coverage.Add(new + { + ability.Id, + ability.IsItem, + status = "numeric-dependency", + reason = ability.UnsupportedReason + }); + continue; + } + int[] sources = ability.IsItem ? new[] { 101 } : ability.ApplicableIdentities + .Where(identity => ActorConstants.MainActorCombatActorIdMap.ContainsKey((Core.Contract.Enums.PlayerActorId)identity)) + .Select(identity => ActorConstants.MainActorCombatActorIdMap[(Core.Contract.Enums.PlayerActorId)identity]).Distinct().ToArray(); + if (sources.Length == 0) + sources = _data.Database.CombatActorInfos.Values.Where(actor => actor.SkillIds.Contains((uint)ability.Id)).Select(actor => (int)actor.Id).ToArray(); + if (sources.Length == 0) + { + _coverage.Add(new + { + ability.Id, + ability.IsItem, + status = "unreferenced-record" + }); + continue; + } + foreach (int source in sources) + { + try + { + BattleScenario scenario = Scenario(source); + var setup = new BattleSetup(scenario); + var catalog = new BattleAnimationCatalog(_data, setup); + string actor = scenario.Participants[ActorConstants.MainActorCombatActorIdMap.ContainsValue(source) ? 0 : 1].InstanceId; + BattleAbilityStageProfile profile = catalog.AbilityStage(actor, ability); + AttackTiming timing = catalog.Ability(actor, ability); + Assert.That(timing.NativeWorkTimeSeconds, Is.EqualTo(profile.WorkSeconds)); + Assert.That(profile.BodyAnimationTicks, Is.GreaterThanOrEqualTo(0)); + Assert.That(profile.First.GroupId, Is.GreaterThanOrEqualTo(-1)); + Assert.That(profile.Second.GroupId, Is.GreaterThanOrEqualTo(-1)); + _coverage.Add(new + { + ability.Id, + ability.IsItem, + source, + status = "compiled", + profile.Kind, + profile.BodyAnimationTicks, + profile.WorkSeconds, + profile.ApproachKind, + profile.ReturnKind, + first = profile.First.GroupId, + second = profile.Second.GroupId + }); + compiled++; + } + catch (Exception error) + { + errors.Add($"{ability.Id}, actor {source}: {error.Message}"); + _coverage.Add(new + { + ability.Id, + ability.IsItem, + source, + status = "resource-error", + reason = error.Message + }); + } + } + } + Assert.That(compiled, Is.GreaterThan(100)); + Assert.That(errors, Is.Empty, string.Join("\n", errors)); + } + + [Test] + public void ApproachSkillUsesCurrentBodyRadiusWhenAnEnemySlotIsPopulatedAndReplaced() + { + BattleScenario scenario = Scenario(); + scenario.SceneElement = 2; + var setup = new BattleSetup(scenario); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, setup); + var catalog = new BattleAnimationCatalog(_data, setup, definitions); + var session = new BattleSession(setup, catalog, definitions: definitions); + BattleActorSnapshot source = session.Actors.Single(actor => actor.Side == BattleSide.Ally); + MethodInfo create = typeof(BattleSession).GetMethod("CreateOriginalMonster", BindingFlags.Instance | BindingFlags.NonPublic); + int[] monsters = _data.Database.CombatActorInfos.Keys.Where(id => id != 706 && BattleAnimationCatalog.IsBasicEnemy(_data, id)).Take(2).ToArray(); + Assert.That(monsters, Has.Length.EqualTo(2)); + foreach (int monster in monsters) + { + create.Invoke(session, new object[] { 6, monster, 0L }); + BattleActorSnapshot target = session.Actors.Single(actor => actor.NativeIndex == 6); + Assert.That(target.ActorId, Is.EqualTo(monster)); + BattleMovementPlan plan = catalog.AbilityMovement(source, target, definitions.Skills[4101], definitions, false).Single(); + BattleParticipant participant = session.CaptureParticipant(target.Id); + BattleAnimationMetadata idle = _data.GetAnimationMetadata(_data.ActionPath(participant, _data.IdleAction(participant))); + BattleAttackPlan attack = catalog.PlanAttack(source.Id, target.Id, catalog.InitialHome(source.Id), catalog.InitialHome(target.Id)); + Assert.That(catalog.Approach(source.Id, target.Id), Is.EqualTo(BattleAnimationCatalog.UnityPosition(attack.Approach))); + float distance = catalog.Physical(source.Id).Radius(BattlePose.Idle) + (idle.MaximumZ - idle.MinimumZ) * .5f; +#if PAL3A + if (catalog.Physical(source.Id).WeaponType == 1) + distance += 40f; +#endif + Assert.That(BattleMovement.Distance(plan.To, target.Home), Is.EqualTo(distance).Within(.001)); + } + } + + [Test] + public void NpcItemsUseEachPublishedGamesDedicatedItemBodyPath() + { + BattleScenario scenario = Scenario(); + var setup = new BattleSetup(scenario); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, setup); + var catalog = new BattleAnimationCatalog(_data, setup); + string actor = scenario.Participants[1].InstanceId; + int count = 0; + foreach (BattleAbilityDefinition item in definitions.Items.Values.Where(item => item.BattleUsable)) + { + BattleAbilityStageProfile profile = catalog.AbilityStage(actor, item); + int? nativeAction = catalog.AbilityNativeAction(actor, item); + Assert.That(profile.Kind, Is.EqualTo(BattleAbilityStageKind.Item)); + Assert.That(profile.NpcItemIdle, Is.EqualTo(BattleData.Variant == "PAL3A")); + if (BattleData.Variant == "PAL3A" || item.IsTreasure) + Assert.That(nativeAction, Is.Null); + else + Assert.That(nativeAction, Is.EqualTo(38).Or.EqualTo(39), "NPC items do not use the NPC magic slots 55/56/57."); + catalog.Ability(actor, item); + catalog.AbilityBody(actor, item); + _coverage.Add(new + { + item.Id, + source = scenario.Participants[1].ActorId, + profile.NpcItemIdle, + nativeAction, + profile.RetainsBody + }); + count++; + } + Assert.That(count, Is.GreaterThan(50)); + } + +#if PAL3 + [UnityTest] + public IEnumerator OriginalTreasureMovieDecodesAndPresentsItsActualFrames() + { + using var preview = new ResourceModelPreview(_data.Resources, false); + using var movies = new BattleMoviePlayer(_data, preview) { Muted = true }; + preview.Rendering += movies.Render; + using IEffectMovie film = movies.Play("2DEFFECT\\t102.bik"); + Assert.That(movies.MissingMovies, Is.Empty, "The original local movie archive must contain t102.BIK."); + bool decoded = false; + int frames = 0; + var timeout = Stopwatch.StartNew(); + while (!film.Finished && timeout.Elapsed.TotalSeconds < 60) + { + movies.Advance((float)BattleSession.StepSeconds); + decoded |= movies.HasDecodedFrame; + if (movies.HasDecodedFrame) + { + RenderTexture rendered = preview.Render(800, 600); + if (++frames == 60) + VerifyMovieImage(movies.CurrentTexture as Texture2D, rendered); + } + yield return null; + } + Assert.That(decoded, Is.True, "The actual Bink-derived frames were not decoded by the editor video player."); + Assert.That(film.Finished, Is.True, "The modal movie did not finish on its original frame clock."); + Assert.That(movies.BlocksBattleTime, Is.False); + } + + private static void VerifyMovieImage(Texture2D source, RenderTexture rendered) + { + Assert.That(source, Is.Not.Null); + var image = new Texture2D(rendered.width, rendered.height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = rendered; + image.ReadPixels(new Rect(0, 0, rendered.width, rendered.height), 0, 0); + image.Apply(); + float error = 0; + for (int y = 50; y < 600; y += 100) + for (int x = 50; x < 800; x += 100) + { + Color expected = source.GetPixel(x, 599 - y); + Color actual = image.GetPixel(x, y); + error = Mathf.Max(error, Mathf.Abs(expected.r - actual.r), Mathf.Abs(expected.g - actual.g), Mathf.Abs(expected.b - actual.b)); + } + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_REPORT_DIR"); + if (output != null) + File.WriteAllBytes(Path.Combine(output, "PAL3-t102-editor-frame.png"), image.EncodeToPNG()); + Assert.That(error, Is.LessThan(0.025f), "The rendered overlay must preserve the decoded original image and its vertical orientation."); + } + finally + { + RenderTexture.active = previous; + UnityEngine.Object.DestroyImmediate(image); + } + } +#endif + + private sealed class CameraPort : IEffectCamera + { + public void StopList() + { + } + + public bool StartList(int index) => true; + + public void SetQuake(float amplitude, float frequency, float decay) + { + } + } + + [UnityTest] + public IEnumerator EveryOrdinaryEffectGroupRunsToCompletionOnTheScaledClock() + { + BattleScenario scenario = Scenario(); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, new BattleSetup(scenario)); + EffectLinkerFile linkers = _data.Read("basedata.cpk\\cbdata\\efflinker.dat", new EffectLinkerFileReader()); + int[] groups = definitions.Skills.Values.Concat(definitions.Items.Values) + .Where(ability => ability.BattleUsable && (ability.IsItem || ability.SkillTypeId != 4)) + .SelectMany(ability => linkers.SkillIdToEffectGroupMap.TryGetValue(ability.Id, out EffectGroupInfo[] found) ? found : Array.Empty()) + .Select(group => group.EffGroupId).Where(group => group >= 0).Distinct().OrderBy(group => group).ToArray(); + using var preview = new ResourceModelPreview(_data.Resources, false); + using var director = new BattleEffectDirector(_data, preview); + var catalog = new BattleAnimationCatalog(_data, new BattleSetup(scenario), definitions); + var session = new BattleSession(new BattleSetup(scenario), catalog, definitions: definitions, effects: director); + director.Bind(session, new CameraPort()); + long frame = 0; + var errors = new List(); + foreach (int group in groups) + { + long handle = 0; + Exception failure = null; + try + { + director.Preload(group); + handle = director.Start(new BattleEffectRequest(group, "A", new[] { "E" }, default, 1)); + } + catch (Exception error) { failure = error; } + int steps = 0; + var timeout = Stopwatch.StartNew(); + while (failure == null && director.IsRunning(handle) && steps++ < 1000000 && timeout.Elapsed.TotalSeconds < 120) + { + try + { + director.Advance(++frame, director.BlocksBattleTime ? 0 : (float)BattleSession.StepSeconds, (float)BattleSession.StepSeconds); + } + catch (Exception error) { failure = error; } + if (director.BlocksBattleTime) + yield return null; + } + if (failure == null && director.IsRunning(handle)) + failure = new InvalidDataException("Original group did not complete within 120 seconds."); + if (failure == null) + _coverage.Add(new + { + group, + status = "completed", + steps + }); + else + { + errors.Add($"Group {group}: {failure.Message}"); + _coverage.Add(new + { + group, + status = "resource-error", + reason = failure.Message + }); + } + if (handle != 0) + director.Stop(handle); + } + foreach (string missing in director.MissingMovies.Distinct()) + _coverage.Add(new + { + movie = missing, + status = "original-open-failed", + reason = "The supplied game data and local original installation contain no matching movie." + }); + foreach (string missing in director.MissingBattleTextures) + _coverage.Add(new + { + texture = missing, + status = "original-texture-load-failed", + reason = "The native effect ignores the failed texture load and draws its vertex color with the original blend operation." + }); + Assert.That(groups.Length, Is.GreaterThan(100)); + Assert.That(errors, Is.Empty, string.Join("\n", errors)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilityResourceTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilityResourceTests.cs.meta new file mode 100644 index 00000000..a1252e5a --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleAbilityResourceTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 09907ded733b4c4187dc20f6205d6c96 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleActorPresentationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleActorPresentationTests.cs new file mode 100644 index 00000000..7f855d88 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleActorPresentationTests.cs @@ -0,0 +1,171 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Core.Contract.Enums; + using NUnit.Framework; + using UnityEngine; + + [Category("LocalGameData")] + public sealed class BattleActorPresentationTests + { + private BattleEditorSession _editor; + + [SetUp] + public void Load() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original data is required."); + _editor = new BattleEditorSession(); + _editor.Load(root, 936); + } + + [TearDown] + public void Dispose() => _editor?.Dispose(); + + private BattleScenario Scenario() + { + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + DataFingerprint = _editor.Data.Fingerprint, + Scene = _editor.Data.Scenes.First(), + Encounter = BattleEncounter.AllyAmbush + }; + int enemy = _editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(_editor.Data, id)); + scenario.Participants.Add(_editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(_editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + foreach (BattleParticipant actor in scenario.Participants) + { + actor.InstanceId = actor.Side.ToString(); + actor.Attributes = new[] { 5000, 100, 500, 70, 10, 12, 0, 0, 0, 0, 0, 0 }; + actor.Attributes[5] = actor.Side == BattleSide.Ally ? 3 : 12; + actor.Vitals = new[] { 5000, 100, 500 }; + actor.Skills.Clear(); + } + return scenario; + } + + private (bool Visible, string Clip, GameObject Body) Body(string id) + { + object actor = ((IDictionary)typeof(BattlePreview).GetField("_actors", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(_editor.Preview))[id]; + Type type = actor.GetType(); + return ((bool)type.GetField("Visible").GetValue(actor), (string)type.GetField("Action").GetValue(actor), + (GameObject)type.GetField("Object").GetValue(actor)); + } + + [Test] + public void AuthoringAttackSamplesTheEquippedHeroAndMonsterAttackClips() + { + BattleScenario scenario = Scenario(); + BattleData data = _editor.Data; + const int identity = 4; + int hero = data.Database.CombatActorInfos.Keys.First(id => BattleData.PlayerIdentity(id) == identity); + BattleParticipant ally = data.CreateParticipant(hero, BattleSide.Ally, BattleSlot.Water); + ally.InstanceId = "Ally"; + int alternateWeaponType = BattleData.Variant == "PAL3" ? 2 : 9; + ally.Equipment[0] = data.Database.GameItemInfos.First(item => item.Value.Type == ItemType.Weapon && item.Key != BattleMagicSwordRules.WeaponId && + (int)item.Value.WeaponType == alternateWeaponType && item.Value.ApplicableActors.Contains((PlayerActorId)identity)).Key; + scenario.Participants[0] = ally; + _editor.Start(scenario); + void AssertAttack(string source, string target, string expected) + { + _editor.Preview.PlayAttack(source, target); + _editor.Preview.Sample(_editor.Preview.Duration / 2); + Assert.That(Body(source).Clip, Is.EqualTo(expected)); + } + AssertAttack("Ally", "Enemy", "z02"); + AssertAttack("Enemy", "Ally", "g"); + + BattleScenario unequipped = Scenario(); + unequipped.Participants[0].Equipment = Array.Empty(); + Assert.That(data.AttackAction(unequipped.Participants[0]), Is.EqualTo("z01")); + _editor.Start(unequipped); + AssertAttack("Ally", "Enemy", "z01"); + } + + [TestCase(0, 4101)] + [TestCase(1, 4205)] + public void RealSkillReturnRestoresTheActorAndRenderedBodyFacing(int identity, int skill) + { + BattleScenario scenario = Scenario(); + int id = _editor.Data.Database.CombatActorInfos.Keys.First(actor => BattleData.PlayerIdentity(actor) == identity); + BattleParticipant ally = _editor.Data.CreateTestParticipant(id, BattleSide.Ally, BattleSlot.Water); + ally.InstanceId = "Ally"; + ally.Attributes = new[] { 50000, 100, 1000, 70, 10, 3, 0, 0, 0, 0, 0, 0 }; + ally.Vitals = ally.Attributes.Take(3).ToArray(); + scenario.Participants[0] = ally; + scenario.Participants[1].Attributes[0] = scenario.Participants[1].Vitals[0] = 50000; + _editor.StartBattle(scenario); + _editor.Preview.Audio.Muted = _editor.Preview.Effects.Muted = true; + var command = new BattleCommand("Ally", BattleAction.Skill, "Enemy", skill); + Assert.That(_editor.Battle.Submit(command), Is.True, _editor.Battle.CanSubmit(command)); + for (int step = 0; step < 5000 && !_editor.Battle.Events.Any(entry => entry.Source == "Ally" && entry.Kind == BattleEventKind.ActionEnded); step++) + _editor.StepBattle(); + Assert.That(_editor.Battle.Events.Any(entry => entry.Source == "Ally" && entry.Kind == BattleEventKind.ActionEnded), Is.True, _editor.Battle.Result?.Reason); + BattleActorSnapshot state = _editor.Battle.Actors.Single(actor => actor.Id == "Ally"); + double x = state.Position.X - state.Home.X, y = state.Position.Y - state.Home.Y, z = state.Position.Z - state.Home.Z; + Assert.That(Math.Sqrt(x * x + y * y + z * z), Is.LessThanOrEqualTo(13)); + Assert.That(state.FacingDegrees, Is.EqualTo(BattleFacingRules.Initial(BattleSide.Ally))); + Assert.That(Quaternion.Angle(Body("Ally").Body.transform.rotation, Quaternion.Euler(0, -state.FacingDegrees, 0)), Is.LessThan(.001f)); + } + + [Test] + public void ActualGuardHitUsesTheBoundClipWithoutHidingTheCharacter() + { + _editor.StartBattle(Scenario()); + _editor.Preview.Audio.Muted = _editor.Preview.Effects.Muted = true; + Assert.That(_editor.Battle.Submit("Ally", BattleAction.Defend), Is.True); + for (int step = 0; step < 1000 && !_editor.Battle.Actors.Single(actor => actor.Id == "Enemy").Ready; step++) + _editor.StepBattle(); + Assert.That(_editor.Battle.Actors.Single(actor => actor.Id == "Ally").Guarding, Is.True); + Assert.That(_editor.Battle.Submit("Enemy", BattleAction.Attack, "Ally"), Is.True); + for (int step = 0; step < 500 && _editor.Battle.Actors.Single(actor => actor.Id == "Ally").Pose != BattlePose.GuardHurt; step++) + _editor.StepBattle(); + BattleActorSnapshot state = _editor.Battle.Actors.Single(actor => actor.Id == "Ally"); + Assert.That(state.Pose, Is.EqualTo(BattlePose.GuardHurt)); + Assert.That(state.NativeAnimationClip, Is.EqualTo(BattleData.Variant == "PAL3" ? "z142" : "z063")); + var body = Body("Ally"); + Assert.That(body.Visible, Is.True); + Assert.That(body.Clip, Is.EqualTo(state.NativeAnimationClip)); + Assert.That(body.Body.GetComponentsInChildren().Any(renderer => renderer.enabled), Is.True); + Assert.That(_editor.Preview.View.Render(800, 600), Is.Not.Null); + } + + [TestCase(BattleState.Sleep)] + [TestCase(BattleState.Paralysis)] + public void InactiveBodiesStillUseTheirNativeStatusAnimation(BattleState status) + { + BattleScenario scenario = Scenario(); + scenario.Participants[0].Statuses.Add(new BattleStatus { Id = (int)status, Rounds = 5 }); + _editor.StartBattle(scenario); + _editor.StepBattle(); + BattleActorSnapshot state = _editor.Battle.Actors.Single(actor => actor.Id == "Ally"); + Assert.That(Body("Ally").Visible, Is.True); + Assert.That(Body("Ally").Clip, Is.EqualTo(state.NativeAnimationClip)); + } + + [Test] + public void RetainedNativeIdleDoesNotResurrectAHiddenDeadMonster() + { + BattleScenario scenario = Scenario(); + scenario.Participants[1].Vitals[0] = 0; + _editor.StartBattle(scenario); + BattleActorSnapshot state = _editor.Battle.Actors.Single(actor => actor.Id == "Enemy"); + Assert.That(state.ModelAliveFlag, Is.False); + Assert.That(state.NativeAnimationClip, Is.Not.Null); + Assert.That(Body("Enemy").Visible, Is.False); + Assert.That(Body("Enemy").Body.GetComponentsInChildren().All(renderer => !renderer.enabled), Is.True); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleActorPresentationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleActorPresentationTests.cs.meta new file mode 100644 index 00000000..350aeb14 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleActorPresentationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 40b84fa17bdf414fafbb99ace30d2eab diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleAnimationMetadataTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleAnimationMetadataTests.cs new file mode 100644 index 00000000..f7b60a4b --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleAnimationMetadataTests.cs @@ -0,0 +1,76 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using Battle; + using Core.DataReader.Mv3; + using Core.Primitives; + using NUnit.Framework; + + public sealed class BattleAnimationMetadataTests + { + [Test] + public void MetadataOwnsItsMarkersAndAggregatesTheOriginalMeshBounds() + { + var events = new[] { new Mv3AnimationEvent { Name = "work", GameBoxTick = 123 } }; + var meshes = new[] + { + new Mv3Mesh { GameBoxBoundsMin = new GameBoxVector3 { Z = -4 }, GameBoxBoundsMax = new GameBoxVector3 { Z = 3 } }, + new Mv3Mesh { GameBoxBoundsMin = new GameBoxVector3 { Z = -9 }, GameBoxBoundsMax = new GameBoxVector3 { Z = 13 } } + }; + var source = new Mv3File(600, events, Array.Empty(), meshes, Array.Empty()); + var metadata = new BattleAnimationMetadata(source); + Assert.That(metadata.TotalGameBoxTicks, Is.EqualTo(600)); + Assert.That(metadata.HasBounds, Is.True); + Assert.That((metadata.MinimumZ, metadata.MaximumZ), Is.EqualTo((-9f, 13f))); + events[0].Name = "changed"; + meshes[1] = default; + Assert.That(metadata.AnimationEvents[0].Name, Is.EqualTo("work")); + Assert.That(metadata.AnimationEvents[0].GameBoxTick, Is.EqualTo(123)); + Assert.That((metadata.MinimumZ, metadata.MaximumZ), Is.EqualTo((-9f, 13f))); + Assert.Throws(() => ((IList)metadata.AnimationEvents)[0] = default); + } + + [Test] + public void MissingBoundsRemainExplicitInsteadOfBecomingAZeroRadius() + { + var source = new Mv3File(0, Array.Empty(), Array.Empty(), + Array.Empty(), Array.Empty()); + Assert.That(new BattleAnimationMetadata(source).HasBounds, Is.False); + } + + [Test, Category("LocalGameData")] + public void CanonicalPathsShareMetadataOnlyWithinTheirLiveDataOwner() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original local data unavailable."); + using var first = new BattleData(root, 936); + using var second = new BattleData(root, 936); + BattleParticipant actor = first.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + string idle = first.ActionPath(actor, first.IdleAction(actor)); + Assert.That(first.TryActionPath(actor, "z01", out string attack), Is.True); + BattleAnimationMetadata metadata = first.GetAnimationMetadata(idle); + Assert.That(first.GetAnimationMetadata(idle.ToUpperInvariant().Replace('\\', '/')), Is.SameAs(metadata)); + Assert.That(first.GetAnimationMetadata(attack), Is.Not.SameAs(metadata), "Different animation paths must not alias."); + BattleAnimationMetadata separate = second.GetAnimationMetadata(idle); + Assert.That(separate, Is.Not.SameAs(metadata), "A new data owner must not inherit cached original data."); + Mv3File original = first.Read(idle, new Mv3FileReader()); + Assert.That(metadata.TotalGameBoxTicks, Is.EqualTo(original.TotalGameBoxTicks)); + Assert.That(metadata.AnimationEvents.Select(marker => (marker.GameBoxTick, marker.Name)), + Is.EqualTo(original.AnimationEvents.Select(marker => (marker.GameBoxTick, marker.Name)))); + Assert.That(metadata.MinimumZ, Is.EqualTo(original.Meshes.Min(mesh => mesh.GameBoxBoundsMin.Z))); + Assert.That(metadata.MaximumZ, Is.EqualTo(original.Meshes.Max(mesh => mesh.GameBoxBoundsMax.Z))); + first.Dispose(); + Assert.Throws(() => first.GetAnimationMetadata(idle)); + Assert.That(second.GetAnimationMetadata(idle), Is.SameAs(separate)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleAnimationMetadataTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleAnimationMetadataTests.cs.meta new file mode 100644 index 00000000..c03dd4be --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleAnimationMetadataTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 926a7d6d2c4d479384a102d199e5a4f2 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioOneShotTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioOneShotTests.cs new file mode 100644 index 00000000..c3dc441e --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioOneShotTests.cs @@ -0,0 +1,334 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using NUnit.Framework; + using ResourceBrowser; + using Unity.Collections; + using UnityEditor; + using UnityEngine; + using UnityEngine.SceneManagement; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + public sealed class BattleAudioOneShotTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private ResourceCatalog _resources; + private BattleAudioPreview _audio; + private AudioClip _movie; + private string _sound, _directory; + private bool _recording, _listenerPause; + private float _captureDelta, _listenerVolume, _peak; + + private GameObject Root => (GameObject)typeof(BattleAudioPreview).GetField("_root", Members).GetValue(_audio); + + private AudioSource[] Sources => Root.GetComponentsInChildren(); + + private IDictionary Clips => (IDictionary)typeof(BattleAudioPreview).GetField("_clips", Members).GetValue(_audio); + + private IDictionary State(string name) => (IDictionary)typeof(BattleAudioPreview).GetField(name, Members).GetValue(_audio); + + [SetUp] + public void SetUp() + { + _listenerVolume = AudioListener.volume; + _listenerPause = AudioListener.pause; + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (root == null) + Assert.Ignore("One-shot audio verification requires local game resources."); + _resources = ResourceCatalog.OpenBaseData(root, 936); + _audio = new BattleAudioPreview(_resources) { PlaybackEnabled = false }; + var files = (IDictionary)typeof(BattleAudioPreview).GetField("_soundFiles", Members).GetValue(_audio); + _sound = files.Keys.First(); + var body = AudioClip.Create("cached overlap fixture", 480000, 1, 48000, false); + var signal = new float[body.samples]; + Array.Fill(signal, .1f); + body.SetData(signal, 0); + Clips.Add(_sound, body); + Clips.Add("music:silent.mp3", AudioClip.Create("music ownership fixture", 480000, 1, 48000, false)); + _movie = AudioClip.Create("movie ownership fixture", 480000, 1, 48000, false); + _directory = Path.Combine(Environment.GetEnvironmentVariable("PAL3_BATTLE_REPORT_DIR") ?? Application.temporaryCachePath, + "AudioOneShots-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_directory); + } + + [TearDown] + public void TearDown() + { + EndCapture(); + _audio?.Dispose(); + _resources?.Dispose(); + if (_movie != null) + Object.DestroyImmediate(_movie); + if (_directory != null) + Directory.Delete(_directory, true); + Assert.That(AudioListener.volume, Is.EqualTo(_listenerVolume)); + Assert.That(AudioListener.pause, Is.EqualTo(_listenerPause)); + } + + private int BeginCapture() + { + int channels = AudioSettings.speakerMode switch + { + AudioSpeakerMode.Mono => 1, + AudioSpeakerMode.Stereo or AudioSpeakerMode.Prologic => 2, + AudioSpeakerMode.Quad => 4, + AudioSpeakerMode.Surround => 5, + AudioSpeakerMode.Mode5point1 => 6, + AudioSpeakerMode.Mode7point1 => 8, + _ => 0 + }; + if (channels == 0) + Assert.Ignore("The current speaker layout has no PCM capture mapping."); + _captureDelta = Time.captureDeltaTime; + Time.captureDeltaTime = 1f / 60f; + _recording = AudioRenderer.Start(); + if (!_recording) + { + Time.captureDeltaTime = _captureDelta; + Assert.Ignore("This editor cannot enter offline audio recording mode."); + } + return channels; + } + + private void EndCapture() + { + // Stop every source before leaving recording mode, which guarantees + // external silence even when an assertion interrupts a PCM fixture. + _audio?.Stop(); + if (_audio != null) + _audio.PlaybackEnabled = false; + if (!_recording) + return; + AudioRenderer.Stop(); + Time.captureDeltaTime = _captureDelta; + _recording = false; + } + + private IEnumerator CapturePeak(int channels, float minimum) + { + Assert.That(_recording, Is.True, "Only route test signals while Unity has taken the speaker output offline."); + foreach (AudioSource source in Sources) + source.mute = false; + _peak = 0; + double deadline = EditorApplication.timeSinceStartup + .5; + while (EditorApplication.timeSinceStartup < deadline && _peak <= minimum) + { + yield return null; + int frames = AudioRenderer.GetSampleCountForCaptureFrame(); + // The first capture frame can be empty; rendering it still + // advances the offline recording clock for subsequent blocks. + using var samples = new NativeArray(frames * channels, Allocator.Temp); + Assert.That(AudioRenderer.Render(samples), Is.True); + foreach (float sample in samples) + _peak = Math.Max(_peak, Math.Abs(sample)); + } + Assert.That(_peak, Is.GreaterThan(minimum), "The requested independent voices must reach the actual output graph."); + } + + private string AddWave(string name, float value) + { + string path = Path.Combine(_directory, name); + const int frames = 48000 * 5; + using (var writer = new BinaryWriter(File.Create(path))) + { + writer.Write(System.Text.Encoding.ASCII.GetBytes("RIFF")); + writer.Write(36 + frames * 2); + writer.Write(System.Text.Encoding.ASCII.GetBytes("WAVEfmt ")); + writer.Write(16); + writer.Write((ushort)1); + writer.Write((ushort)1); + writer.Write(48000); + writer.Write(96000); + writer.Write((ushort)2); + writer.Write((ushort)16); + writer.Write(System.Text.Encoding.ASCII.GetBytes("data")); + writer.Write(frames * 2); + short amplitude = (short)MathF.Round(value * short.MaxValue); + for (int frame = 0; frame < frames; frame++) + writer.Write(amplitude); + } + var files = (IDictionary)typeof(BattleAudioPreview).GetField("_soundFiles", Members).GetValue(_audio); + files.Add(name, path); + return name; + } + + private IEnumerator WaitForDecoders() + { + double deadline = EditorApplication.timeSinceStartup + 10; + while (State("_pending").Count > 0 && EditorApplication.timeSinceStartup < deadline) + yield return null; + Assert.That(State("_pending").Count, Is.Zero); + Assert.That(_audio.Diagnostics, Is.Empty); + } + + [UnityTest] + public IEnumerator CachedSameNameOneShotsMixBothOriginalVoices() + { + int channels = BeginCapture(); + try + { + _audio.PlaybackEnabled = true; + _audio.Play(_sound); + AudioSource first = Sources.Single(); + yield return CapturePeak(channels, .01f); + float single = _peak; + _audio.Play(_sound); + Assert.That(Sources.Length, Is.EqualTo(2)); + Assert.That(first == null, Is.False, "A repeated name must preserve the preceding sound's tail."); + Assert.That(Sources.All(source => ReferenceEquals(source.clip, first.clip)), Is.True, "Only the decoded clip is shared."); + yield return CapturePeak(channels, single * 1.8f); + Assert.That(_peak, Is.EqualTo(single * 2).Within(single * .1f)); + Debug.Log($"Cached one-shot output: single={single}, overlap={_peak}"); + } + finally + { + EndCapture(); + } + } + + [UnityTest] + public IEnumerator PendingSameNameRequestsShareDecodeAndRetainIndependentClocks() + { + string sound = AddWave("pending-overlap.wav", .1f); + _audio.Play(sound); + _audio.SetTime(.25); + _audio.Play(sound); + Assert.That(State("_pending").Count, Is.EqualTo(1)); + Assert.That(State("_desired").Count, Is.EqualTo(2)); + yield return WaitForDecoders(); + AudioSource[] sources = Sources; + Assert.That(sources.Length, Is.EqualTo(2)); + Assert.That(ReferenceEquals(sources[0].clip, sources[1].clip), Is.True); + AudioClip clip = sources[0].clip; + Assert.That(Clips.Count, Is.EqualTo(3)); + int channels = BeginCapture(); + try + { + _audio.PlaybackEnabled = true; + sources = Sources.OrderByDescending(source => source.timeSamples).ToArray(); + AudioSource earlier = sources[0], later = sources[1]; + Assert.That(earlier.timeSamples, Is.InRange(11000, 13000)); + Assert.That(later.timeSamples, Is.InRange(0, 1024)); + later.volume = 0; + yield return CapturePeak(channels, .01f); + float single = _peak; + later.volume = 1; + yield return CapturePeak(channels, single * 1.8f); + Assert.That(_peak, Is.EqualTo(single * 2).Within(single * .1f)); + Debug.Log($"Pending one-shot output: single={single}, overlap={_peak}"); + _audio.PlaybackEnabled = false; + double duration = clip.samples / (double)clip.frequency; + _audio.SetTime(duration + .01); + Assert.That(earlier == null, Is.True); + Assert.That(later == null, Is.False); + Assert.That(Sources.Length, Is.EqualTo(1)); + _audio.SetTime(duration + .25); + Assert.That(Sources, Is.Empty); + Assert.That(State("_desired").Count, Is.Zero); + Assert.That(State("_voices").Count, Is.Zero); + Assert.That(clip == null, Is.False, "The owned cache remains reusable after individual voices expire."); + string expired = AddWave("expired-pending.wav", 0); + _audio.Play(expired); + _audio.SetTime(20); + yield return WaitForDecoders(); + Assert.That(Sources, Is.Empty); + Assert.That(State("_desired").Count, Is.Zero, "A request that expires during decode must be reclaimed immediately."); + } + finally + { + EndCapture(); + } + } + + [UnityTest] + public IEnumerator StopBoundariesClearEveryRepeatedRequestWithoutTakingOtherOwners() + { + _audio.SetMusic("silent"); + _audio.SynchronizeMovie(new object(), _movie, 0, false); + _audio.PlayMovement("A", _sound, true); + _audio.Play(_sound); + _audio.Play(_sound); + string sound = AddWave("stopped-pending.wav", 0); + _audio.Play(sound); + _audio.Play(sound); + Assert.That(Sources.Length, Is.EqualTo(5)); + Assert.That(State("_pending").Count, Is.EqualTo(1)); + _audio.StopBodySounds(); + Assert.That(Sources.Length, Is.EqualTo(2), "Music and movie owners survive a body stop."); + Assert.That(Sources.All(source => source.clip.name.Contains("ownership fixture")), Is.True); + Assert.That(State("_desired").Count, Is.EqualTo(1)); + yield return WaitForDecoders(); + Assert.That(Sources.Length, Is.EqualTo(2), "A completed shared decode cannot resurrect stopped requests."); + string aborted = AddWave("aborted-pending.wav", 0); + _audio.Play(aborted); + _audio.Play(aborted); + Assert.That(State("_pending").Count, Is.EqualTo(1)); + _audio.Stop(); + Assert.That(Sources, Is.Empty); + Assert.That(State("_desired").Count, Is.Zero); + Assert.That(State("_voices").Count, Is.Zero); + Assert.That(State("_pending").Count, Is.Zero); + yield return null; + Assert.That(Sources, Is.Empty); + AudioClip[] clips = Clips.Values.ToArray(); + GameObject root = Root; + Scene scene = root.scene; + _audio.Dispose(); + Assert.That(root == null, Is.True); + Assert.That(scene.IsValid(), Is.False); + Assert.That(clips.All(clip => clip == null), Is.True); + Assert.That(_movie == null, Is.False, "The movie clip remains with its own owner."); + } + + [UnityTest] + public IEnumerator CancellationFromTheFirstDecodeCallbackCannotResurrectAnotherVoice() + { + foreach (int boundary in new[] { 0, 1, 2 }) + { + _audio.PlaybackEnabled = false; + string sound = AddWave($"callback-{boundary}.wav", 0); + _audio.Play(sound); + _audio.Play(sound); + _audio.Play(AddWave($"callback-other-{boundary}.wav", 0)); + int callbacks = 0; + Action cancel = null; + cancel = played => + { + if (!played.Equals(sound, StringComparison.OrdinalIgnoreCase)) + return; + _audio.SoundPlayed -= cancel; + callbacks++; + if (boundary == 0) + _audio.StopBodySounds(); + else if (boundary == 1) + _audio.Stop(); + else + _audio.Dispose(); + }; + _audio.SoundPlayed += cancel; + GameObject root = Root; + _audio.PlaybackEnabled = true; // Every file in this fixture is digital silence. + yield return WaitForDecoders(); + Assert.That(callbacks, Is.EqualTo(1)); + Assert.That(State("_desired").Count, Is.Zero); + Assert.That(State("_voices").Count, Is.Zero); + if (boundary == 2) + Assert.That(root == null, Is.True); + else + Assert.That(Sources, Is.Empty); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioOneShotTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioOneShotTests.cs.meta new file mode 100644 index 00000000..6c1d1218 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioOneShotTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ab8da36e22a0481aa58047865f9889bd diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioVoiceTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioVoiceTests.cs new file mode 100644 index 00000000..34ab93b5 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioVoiceTests.cs @@ -0,0 +1,383 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using NUnit.Framework; + using ResourceBrowser; + using Unity.Collections; + using UnityEditor; + using UnityEngine; + using UnityEngine.SceneManagement; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + public sealed class BattleAudioVoiceTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private ResourceCatalog _resources; + private BattleAudioPreview _audio; + private AudioClip _movie; + private string _sound; + private float _listenerVolume; + private bool _listenerPause; + + private GameObject Root => (GameObject)typeof(BattleAudioPreview).GetField("_root", Members).GetValue(_audio); + + private AudioSource Source(string name) => Root.GetComponentsInChildren().Single(source => source.clip.name == name); + + private AudioClip Silent(string name) => AudioClip.Create(name, 480000, 1, 48000, false); + + [SetUp] + public void SetUp() + { + _listenerVolume = AudioListener.volume; + _listenerPause = AudioListener.pause; + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (root == null) + Assert.Ignore("Audio scene verification requires local game resources."); + _resources = ResourceCatalog.OpenBaseData(root, 936); + _audio = new BattleAudioPreview(_resources) { PlaybackEnabled = false }; + var files = (IDictionary)typeof(BattleAudioPreview).GetField("_soundFiles", Members).GetValue(_audio); + _sound = files.Keys.First(); + var clips = (IDictionary)typeof(BattleAudioPreview).GetField("_clips", Members).GetValue(_audio); + // Every actual device fixture is ten seconds of digital silence. + // Real files supply only path lookup; no game sound is played. + clips.Add(_sound, Silent("body fixture")); + clips.Add("music:silent.mp3", Silent("music fixture")); + _movie = Silent("movie fixture"); + } + + [TearDown] + public void TearDown() + { + _audio?.Dispose(); + _resources?.Dispose(); + if (_movie != null) + Object.DestroyImmediate(_movie); + Assert.That(AudioListener.volume, Is.EqualTo(_listenerVolume)); + Assert.That(AudioListener.pause, Is.EqualTo(_listenerPause)); + } + + private static IEnumerator Wait(double seconds) + { + double until = EditorApplication.timeSinceStartup + seconds; + while (EditorApplication.timeSinceStartup < until) + yield return null; + } + + [UnityTest] + public IEnumerator PerVoiceStopPreservesMusicMovieAndOneShotOutput() + { + _audio.SetMusic("silent"); + _audio.PlayMovement("A", _sound, true); + _audio.Play(_sound); + var owner = new object(); + _audio.SynchronizeMovie(owner, _movie, 1, true); + _audio.PlaybackEnabled = true; + yield return Wait(.25); + AudioSource music = Source("music fixture"); + AudioSource movie = Source("movie fixture"); + AudioSource oneShot = Root.GetComponentsInChildren().Single(source => source.clip.name == "body fixture" && !source.loop); + Assert.That(music.timeSamples, Is.GreaterThan(4800)); + Assert.That(movie.timeSamples, Is.GreaterThan(48000)); + Assert.That(oneShot.timeSamples, Is.GreaterThan(4800)); + _audio.StopMovement("A"); + Assert.That(Root.GetComponentsInChildren().Length, Is.EqualTo(3)); + Assert.That(music.isPlaying && movie.isPlaying && oneShot.isPlaying, Is.True); + int musicAtStop = music.timeSamples; + _audio.StopMovie(owner); + yield return Wait(.1); + Assert.That(music.timeSamples, Is.GreaterThan(musicAtStop)); + Assert.That(oneShot.isPlaying, Is.True); + Assert.That(movie == null, Is.True); + } + + [UnityTest] + public IEnumerator RepeatedInputSynchronizationDoesNotRewindRunningMusic() + { + _audio.SetMusic("silent"); + _audio.PlaybackEnabled = true; + yield return Wait(.25); + AudioSource music = Source("music fixture"); + Assert.That(music.timeSamples, Is.GreaterThan(4800)); + var samples = new List(); + for (int input = 0; input < 8; input++) + { + int before = music.timeSamples; + // HUD commands publish the current battle state immediately, + // even when no fixed simulation step occurred between inputs. + // The editor also caps elapsed simulation time after a stall. + _audio.SetTime(input * .02); + _audio.PlaybackEnabled = true; + Assert.That(Source("music fixture"), Is.SameAs(music)); + Assert.That(music.isPlaying, Is.True); + samples.Add($"{before}->{music.timeSamples}"); + Assert.That(music.timeSamples, Is.GreaterThanOrEqualTo(before - 1024), + "Publishing a battle tick must not seek a continuously playing music voice back to the simulation clock."); + yield return Wait(.15); + } + Debug.Log("Continuous music samples across input synchronization: " + string.Join(", ", samples)); + _audio.PlaybackEnabled = false; + _audio.SetTime(1.5); + _audio.PlaybackEnabled = true; + Assert.That(music.timeSamples, Is.InRange(70000, 78000), + "Resuming after silent inspection must still seek to the inspected battle time."); + } + + [UnityTest] + public IEnumerator SlowOrRepeatedEditorTicksCannotRewindRunningSoundVoices() + { + _audio.SetMusic("silent"); + _audio.Play(_sound); + _audio.PlayMovement("actor", _sound, true); + _audio.PlaybackEnabled = true; + yield return Wait(.3); + AudioSource[] voices = Root.GetComponentsInChildren(); + Assert.That(voices, Has.Length.EqualTo(3)); + Assert.That(voices.Select(voice => voice.mute), Is.All.EqualTo(Application.isBatchMode)); + Assert.That(voices.Select(voice => voice.timeSamples), Is.All.GreaterThan(4800)); + for (int input = 0; input < 5; input++) + { + int[] before = voices.Select(voice => voice.timeSamples).ToArray(); + _audio.SetTime(input * .02); + for (int index = 0; index < voices.Length; index++) + Assert.That(voices[index].timeSamples, Is.GreaterThanOrEqualTo(before[index] - 1024), + "A throttled or repeated editor tick must not rewind " + voices[index].clip.name); + yield return Wait(.12); + } + _audio.PlaybackEnabled = false; + _audio.SetTime(1.5); + _audio.PlaybackEnabled = true; + Assert.That(voices.Select(voice => voice.timeSamples), Is.All.InRange(70000, 78000)); + } + + [UnityTest] + public IEnumerator PauseSingleStepAndMovieSeekRetainIndependentPhases() + { + _audio.SetMusic("silent"); + var owner = new object(); + _audio.SynchronizeMovie(owner, _movie, .5, true); + _audio.PlaybackEnabled = true; + yield return Wait(.15); + AudioSource music = Source("music fixture"); + AudioSource movie = Source("movie fixture"); + _audio.PlaybackEnabled = false; + int pausedMusic = music.timeSamples; + int pausedMovie = movie.timeSamples; + yield return Wait(.1); + Assert.That(music.timeSamples, Is.EqualTo(pausedMusic).Within(1024)); + Assert.That(movie.timeSamples, Is.EqualTo(pausedMovie).Within(1024)); + _audio.SetTime(1.5); // Silent inspection advances the battle clock. + _audio.SynchronizeMovie(owner, _movie, 2, false); + _audio.PlaybackEnabled = true; + _audio.SynchronizeMovie(owner, _movie, 2, true); + yield return null; + Assert.That(music.timeSamples, Is.InRange(70000, 78000)); + Assert.That(movie.timeSamples, Is.InRange(94000, 102000)); + _audio.SetMusicGain(.25f); + Assert.That(music.volume, Is.EqualTo(.25f)); + Assert.That(movie.volume, Is.EqualTo(1)); + } + + [UnityTest] + public IEnumerator MutingPausesEveryVoiceAndDisposalClosesOnlyItsPreviewScene() + { + _audio.SetMusic("silent"); + _audio.PlayMovement("A", _sound, true); + _audio.PlaybackEnabled = true; + yield return Wait(.1); + AudioSource music = Source("music fixture"); + Scene scene = music.gameObject.scene; + Assert.That(UnityEditor.SceneManagement.EditorSceneManager.IsPreviewScene(scene), Is.True); + _audio.Muted = true; + Assert.That(Root.GetComponentsInChildren().All(source => !source.isPlaying), Is.True); + _audio.StopBodySounds(); + Assert.That(Root.GetComponentsInChildren().Length, Is.EqualTo(1)); + _audio.Muted = false; + Assert.That(music.isPlaying, Is.True); + _audio.Dispose(); + Assert.That(scene.IsValid(), Is.False); + Assert.That(music == null, Is.True); + } + + [UnityTest] + public IEnumerator PreviewSceneRoutesSignalToTheSilentOfflineAudioRenderer() + { + int channels = AudioSettings.speakerMode switch + { + AudioSpeakerMode.Mono => 1, + AudioSpeakerMode.Stereo or AudioSpeakerMode.Prologic => 2, + AudioSpeakerMode.Quad => 4, + AudioSpeakerMode.Surround => 5, + AudioSpeakerMode.Mode5point1 => 6, + AudioSpeakerMode.Mode7point1 => 8, + _ => 0 + }; + if (channels == 0) + Assert.Ignore("The current speaker layout has no PCM capture mapping."); + float captureDelta = Time.captureDeltaTime; + Time.captureDeltaTime = 1f / 60f; + bool recording = AudioRenderer.Start(); + if (!recording) + { + Time.captureDeltaTime = captureDelta; + Assert.Ignore("This editor cannot enter offline audio recording mode."); + } + var owner = new object(); + try + { + // Unity's bundled AudioModule documentation guarantees physical + // output is silence throughout AudioRenderer recording mode. + // A synthetic signal can therefore verify the actual output + // graph without playing it through the user's speakers. + var signal = new float[_movie.samples]; + for (int sample = 0; sample < signal.Length; sample++) + signal[sample] = .25f * MathF.Sin(sample * .1f); + _movie.SetData(signal, 0); + _audio.PlaybackEnabled = true; + _audio.SynchronizeMovie(owner, _movie, 0, true); + Source("movie fixture").mute = false; + float peak = 0; + double deadline = EditorApplication.timeSinceStartup + .5; + while (EditorApplication.timeSinceStartup < deadline && peak <= .01f) + { + yield return null; + int samples = AudioRenderer.GetSampleCountForCaptureFrame(); + // Even an empty initial frame must be rendered so the + // recording clock can begin producing subsequent blocks. + using var output = new NativeArray(samples * channels, Allocator.Temp); + Assert.That(AudioRenderer.Render(output), Is.True); + foreach (float value in output) + peak = Math.Max(peak, Math.Abs(value)); + } + Assert.That(peak, Is.GreaterThan(.01f), "An editor preview source must reach the real output graph without adding or modifying a listener."); + } + finally + { + _audio.StopMovie(owner); + _audio.PlaybackEnabled = false; + AudioRenderer.Stop(); + Time.captureDeltaTime = captureDelta; + } + } + + [UnityTest] + public IEnumerator EveryNativeCommonCueDecodesIntoAnOwnedVoice() + { + using var actual = new BattleAudioPreview(_resources) { PlaybackEnabled = false }; + string[] cues = new[] { 1, 2, 3, 4, 6 }.Select(id => "wa" + id.ToString("000")) + .Concat(Enumerable.Range(1, 22).Select(id => "wd" + id.ToString("000"))).ToArray(); + foreach (string cue in cues) + actual.Play(cue); + var pending = (IDictionary)typeof(BattleAudioPreview).GetField("_pending", Members).GetValue(actual); + double deadline = EditorApplication.timeSinceStartup + 15; + while (pending.Count > 0 && EditorApplication.timeSinceStartup < deadline) + yield return null; + Assert.That(pending.Count, Is.Zero); + Assert.That(actual.Diagnostics, Is.Empty); + var root = (GameObject)typeof(BattleAudioPreview).GetField("_root", Members).GetValue(actual); + AudioSource[] voices = root.GetComponentsInChildren(); + Assert.That(voices.Select(voice => voice.clip.name), Is.EquivalentTo(cues.Select(cue => cue + ".wav"))); + foreach (AudioSource voice in voices) + { + Assert.That(voice.isPlaying, Is.False, "Decoding original assets must remain silent during background QA."); + AudioClip clip = voice.clip; + Assert.That(clip.samples, Is.GreaterThan(0), clip.name); + var samples = new float[clip.samples * clip.channels]; + Assert.That(clip.GetData(samples, 0), Is.True, clip.name); + Assert.That(samples.Any(sample => Math.Abs(sample) > .001f), Is.True, + clip.name + " must contain audible PCM, not just a successful file lookup."); + } + } + + [Test] + public void FailedAudioRequestCreationReleasesTheExtractedFileAndDesiredVoice() + { + string temporary = Path.GetTempFileName(); + try + { + MethodInfo queue = typeof(BattleAudioPreview).GetMethod("Queue", Members); + const string voice = "fixture voice"; + var failure = Assert.Throws(() => + queue.Invoke(_audio, new object[] { voice, "fixture.mp3", "", AudioType.MPEG, true, temporary })); + Assert.That(failure.InnerException, Is.TypeOf()); + Assert.That(File.Exists(temporary), Is.False); + var desired = (IDictionary)typeof(BattleAudioPreview).GetField("_desired", Members).GetValue(_audio); + var pending = (IDictionary)typeof(BattleAudioPreview).GetField("_pending", Members).GetValue(_audio); + Assert.That(desired.Contains(voice), Is.False); + Assert.That(pending.Count, Is.Zero); + } + finally + { + File.Delete(temporary); + } + } + + [Test] + public void DisposeCleansUpWhenAChildVoiceIsGoneAndATemporaryFileCannotBeDeleted() + { + GameObject root = Root; + Scene scene = root.scene; + _audio.Play(_sound); + AudioSource voice = Source("body fixture"); + AudioClip clip = voice.clip; + Object.DestroyImmediate(voice.gameObject); + + string music = BattleData.Variant == "PAL3" ? "PI24" : "P54"; + _audio.SetMusic(music); + var pending = (IDictionary)typeof(BattleAudioPreview).GetField("_pending", Members).GetValue(_audio); + object decode = pending.Values.Cast().Single(); + FieldInfo temporary = decode.GetType().GetField("Temporary", Members); + string extracted = (string)temporary.GetValue(decode); + string directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + try + { + // File.Delete rejects directories on all desktop platforms. + temporary.SetValue(decode, directory); + Assert.DoesNotThrow(_audio.Dispose); + Assert.That(_audio.Diagnostics, Has.Some.Contains(directory)); + Assert.That(pending.Count, Is.Zero); + Assert.That(clip == null && root == null && !scene.IsValid(), Is.True); + Assert.DoesNotThrow(_audio.Dispose); + } + finally + { + if (extracted != null) + File.Delete(extracted); + Directory.Delete(directory); + } + } + + [UnityTest] + public IEnumerator PackedMusicDecodesWithoutPlaybackAndStopAbortsItsPendingOwner() + { + string music = BattleData.Variant == "PAL3" ? "PI24" : "P54"; + _audio.Muted = true; + _audio.SetMusic(music); + double until = EditorApplication.timeSinceStartup + 15; + var pending = (IDictionary)typeof(BattleAudioPreview).GetField("_pending", Members).GetValue(_audio); + while (pending.Count > 0 && EditorApplication.timeSinceStartup < until) + yield return null; + Assert.That(pending.Count, Is.Zero); + Assert.That(_audio.Diagnostics, Is.Empty); + AudioSource source = Root.GetComponentsInChildren().Single(); + Assert.That(source.clip.samples, Is.GreaterThan(48000)); + Assert.That(source.loop, Is.True); + Assert.That(source.isPlaying, Is.False); + _audio.Stop(); + Assert.That(Root.GetComponentsInChildren(), Is.Empty); + Assert.That(pending.Count, Is.Zero); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioVoiceTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioVoiceTests.cs.meta new file mode 100644 index 00000000..7dd93f7b --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleAudioVoiceTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c8ddbff329984b99bff3d69b2cb073ee diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleCorpseIntegrationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleCorpseIntegrationTests.cs new file mode 100644 index 00000000..e3012ff0 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleCorpseIntegrationTests.cs @@ -0,0 +1,118 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + public sealed class BattleCorpseIntegrationTests + { + private sealed class CompletedEffects : IBattleEffectDirector + { + public long Start(BattleEffectRequest request) => 1; + + public bool IsRunning(long handle) => false; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + } + } + + [Test] + public void ActualKillingSpellAwardsAndDisplaysTheOriginalCorpseModelAndSkin() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Original game data is required for corpse geometry verification."); + using var data = new BattleData(root, 936); + int skill = BattleData.Variant == "PAL3" ? 315 : 319; + BattleParticipant source = data.CreateParticipant(104, BattleSide.Ally, BattleSlot.Water); + BattleParticipant target = data.CreateParticipant(7354, BattleSide.Enemy, BattleSlot.Water); + source.InstanceId = "S"; + target.InstanceId = "T"; + source.Level = 100; + foreach (BattleParticipant actor in new[] { source, target }) + { + actor.Attributes = new[] { 50000, 9999, 9999, 5000, 0, 5, 0, 0, 0, 0, 0, 0 }; + actor.Vitals = new[] { 50000, 9999, 9999 }; + actor.Skills.Clear(); + } + target.Vitals[0] = 1; + source.Skills.Add(new BattleSkill { Id = skill, Mastered = true, Level = 4 }); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = data.Scenes.First(), + DataFingerprint = data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush, + Seed = 123 + }; + scenario.Participants.Add(source); + scenario.Participants.Add(target); + var setup = new BattleSetup(scenario); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(data, setup); + var catalog = new BattleAnimationCatalog(data, setup, definitions); + // This case verifies the corpse downstream of real damage and + // settlement. Ordinary effect rendering has its own GPU fixtures. + var combat = new BattleSession(setup, catalog, definitions: definitions, effects: new CompletedEffects()); + combat.SetAutomatic(BattleSide.Enemy, false); + using var preview = new BattlePreview(data, setup); + preview.BindBattle(combat, catalog); + var command = new BattleCommand("S", BattleAction.Skill, "T", skill); + Assert.That(combat.Submit(command), Is.True, combat.CanSubmit(command)); + for (int tick = 0; tick < 3000 && combat.Status == BattleSessionStatus.Running; tick++) + { + combat.Step(); + preview.ApplyBattle(combat, catalog); + } + Assert.That(combat.Status, Is.EqualTo(BattleSessionStatus.Completed), combat.Result?.Reason); + Assert.That(combat.Result.Loot.Any(item => item.Id == 6527 && item.Count == 1), Is.True); + Transform corpse = preview.View.Root.transform.Find("Corpse T"); + Assert.That(corpse, Is.Not.Null); + var center = data.Layout.AllyFormationConfig.CenterGameBoxPosition; + Vector3 expected = BattleAnimationCatalog.UnityPosition(new BattleMovementPoint(center.X, center.Y + 2, center.Z + 20)); + Assert.That(Vector3.Distance(corpse.position, expected), Is.LessThan(.000001f)); + Assert.That(corpse.GetComponentsInChildren().Sum(mesh => mesh.sharedMesh.triangles.Length), Is.GreaterThan(0)); + Assert.That(preview.View.Dependencies.Any(entry => entry.Value && (entry.Key.EndsWith("dye3.dds", StringComparison.OrdinalIgnoreCase) || entry.Key.EndsWith("dye3.tga", StringComparison.OrdinalIgnoreCase))), Is.True); + Capture(preview); + } + + private static void Capture(BattlePreview preview) + { + RenderTexture render = preview.View.Render(800, 600); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(800, 600, TextureFormat.RGB24, false); + try + { + RenderTexture.active = render; + image.ReadPixels(new Rect(0, 0, 800, 600), 0, 0); + image.Apply(); + Assert.That(image.GetPixels32().Select(pixel => (pixel.r, pixel.g, pixel.b)).Distinct().Take(100).Count(), Is.GreaterThan(20)); + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (output != null) + { + Directory.CreateDirectory(output); + File.WriteAllBytes(Path.Combine(output, BattleData.Variant + "-corpse-result.png"), image.EncodeToPNG()); + } + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleCorpseIntegrationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleCorpseIntegrationTests.cs.meta new file mode 100644 index 00000000..802beb9e --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleCorpseIntegrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 123888c9775640cfb5a2405217ba64e6 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleDefaultWeaponIntegrationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleDefaultWeaponIntegrationTests.cs new file mode 100644 index 00000000..fa2c0a53 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleDefaultWeaponIntegrationTests.cs @@ -0,0 +1,116 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using Game.Rendering.Renderer; + using NUnit.Framework; + + [Category("LocalGameData")] + public sealed class BattleDefaultWeaponIntegrationTests + { +#if PAL3 + [Test] + public void NativeFallbackSharesCapturedCultivationAttributesWithoutSharingSwordEnergy() + { + string root = Environment.GetEnvironmentVariable("PAL3_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Original game data is required."); + using var session = new BattleEditorSession(); + session.Load(root, 936); + BattleData data = session.Data; + var scenario = new BattleScenario { Variant = "PAL3", Scene = data.Scenes.First(), DataFingerprint = data.Fingerprint }; + BattleParticipant jingtian = data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + jingtian.Equipment[0] = 6603; + jingtian.MagicSword = new BattleMagicSword { AttackBonus = 777, SelectedElement = BattleSwordPurificationElement.Earth, Energy = 123 }; + BattleParticipant xuejian = data.CreateParticipant(104, BattleSide.Ally, BattleSlot.Fire); + xuejian.Equipment[0] = 0; + xuejian.AttributeSource = BattleAttributeSource.BaseWithEquipment; + scenario.Participants.Add(jingtian); + scenario.Participants.Add(xuejian); + scenario.Participants.Add(data.CreateParticipant(7311, BattleSide.Enemy, BattleSlot.Water)); + session.StartBattle(scenario); + BattleActorDefinition definition = session.Battle.Definitions.Actors[xuejian.InstanceId]; + Assert.That(definition.MagicSword, Is.Null); + BattleMagicSwordSnapshot cultivation = definition.Equipment.Single(item => item.Slot == 0).MagicSwordCultivation; + Assert.That(cultivation.AttackBonus, Is.EqualTo(777)); + Assert.That(cultivation.SelectedElement, Is.EqualTo(BattleSwordPurificationElement.Earth)); + Assert.That(session.Battle.Actors.Single(actor => actor.Id == xuejian.InstanceId).Attributes[3], Is.EqualTo(xuejian.Attributes[3] + 777)); + Assert.That(session.Battle.MagicSwords.Keys, Is.EquivalentTo(new[] { jingtian.InstanceId })); + jingtian.MagicSword.AttackBonus = 1; + jingtian.MagicSword.Energy = 0; + Assert.That(cultivation.AttackBonus, Is.EqualTo(777)); + Assert.That(session.Battle.MagicSwords[jingtian.InstanceId].Energy, Is.EqualTo(123)); + session.ReplayBattle(); + } +#endif + + [TestCase(0)] + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + public void EveryPlayersEmptyWeaponUsesOneCapturedLoadoutForRulesBodiesAndPreview(int identity) + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Original game data is required."); + using var session = new BattleEditorSession(); + session.Load(root, 936); + BattleData data = session.Data; + int actorId = ActorConstants.MainActorCombatActorIdMap.Single(pair => (int)pair.Key == identity).Value; + Assert.That(BattleLoadoutRules.PlayerIdentity(BattleData.Variant, actorId), Is.EqualTo(identity)); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = data.Scenes.First(), + DataFingerprint = data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + BattleParticipant player = data.CreateParticipant(actorId, BattleSide.Ally, BattleSlot.Water); + player.Equipment[0] = 0; + player.MagicSword = null; + player.AttributeSource = BattleAttributeSource.BaseWithEquipment; + scenario.Participants.Add(player); + scenario.Participants.Add(data.CreateParticipant(7311, BattleSide.Enemy, BattleSlot.Fire)); + session.StartBattle(scenario); + BattleParticipant captured = session.CapturedScenario.Participants[0]; +#if PAL3 + const int weapon = 6603; +#else + int weapon = new[] { 82110, 82209, 82310, 82402, 82508 }[identity]; +#endif + Assert.That(captured.Equipment[0], Is.EqualTo(weapon)); + Assert.That(captured.UsesNativeDefaultWeapon, Is.True); + Assert.That(session.Battle.Definitions.Actors[player.InstanceId].UnsupportedReason, Is.Empty); + Assert.That(session.Battle.Definitions.Actors[player.InstanceId].Equipment.Select(item => item.UnsupportedReason), Is.All.Empty); + Assert.That(session.Battle.Definitions.Actors[player.InstanceId].Equipment.Single(item => item.Slot == 0).Id, Is.EqualTo(weapon)); + Assert.That(session.Battle.MagicSwordAbilityId(player.InstanceId), Is.EqualTo(BattleData.Variant == "PAL3" && identity == 0 ? 2224 : 0)); + Assert.That(player.Equipment[0], Is.Zero); + Assert.That(player.UsesNativeDefaultWeapon, Is.False); + Assert.That(player.MagicSword, Is.Null); + BattleScenario roundtrip = BattleScenarioJson.Deserialize(BattleScenarioJson.Serialize(session.CapturedScenario)); + Assert.That(roundtrip.Validate(), Is.Empty); + Assert.That(roundtrip.Participants[0].UsesNativeDefaultWeapon, Is.True); + Assert.That(roundtrip.Participants[1].MagicSword, Is.Null); + var command = new BattleCommand(player.InstanceId, BattleAction.Attack, scenario.Participants[1].InstanceId); + Assert.That(session.Battle.Submit(command), Is.True, session.Battle.CanSubmit(command)); + for (int tick = 0; tick < 2000 && !session.Battle.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded); tick++) + session.StepBattle(); + Assert.That(session.Battle.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded), Is.True); + Assert.That(session.Preview.View.Root.transform.Find(player.InstanceId).GetComponentsInChildren(true), Is.Not.Empty); + string weaponPath = FileConstants.GetWeaponModelFileVirtualPath(data.Database.GameItemInfos[weapon].ModelName); + string weaponFolder = weaponPath.Substring(0, weaponPath.LastIndexOf('\\') + 1); + Assert.That(session.Preview.View.Dependencies.Keys.Any(path => path.StartsWith(weaponFolder, StringComparison.OrdinalIgnoreCase)), Is.True); + session.ReplayBattle(); + Assert.That(session.CapturedScenario.Participants[0].Equipment[0], Is.EqualTo(weapon)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleDefaultWeaponIntegrationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleDefaultWeaponIntegrationTests.cs.meta new file mode 100644 index 00000000..01760be9 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleDefaultWeaponIntegrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3e267e42a8394524a48f6ad45563d592 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectLifecycleTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectLifecycleTests.cs new file mode 100644 index 00000000..0f7716bd --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectLifecycleTests.cs @@ -0,0 +1,608 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Core.DataReader.Cpk; + using Core.DataReader.Data; + using Core.FileSystem; + using Engine.Core.Abstraction; + using Game.Effect.Runtime; + using Game.Rendering.Material; + using Game.Rendering.Native; + using NUnit.Framework; + using ResourceBrowser; + using UnityEngine; + using Object = UnityEngine.Object; + + // These ownership tests use isolated preview scenes and never create a window. + public sealed class BattleEffectLifecycleTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + private sealed class Actor : IEffectActor + { + public Vector3 Position + { + get; set; + } + + public float FacingDegrees + { + get; set; + } + + public float Blend { get; set; } = 1; + public bool ActionOver => false; + + public bool Controlled; + public int Releases; + public string Action; + + public void SetExternalTask(bool controlled, object owner) + { + Controlled = controlled; + if (!controlled) + Releases++; + } + + public void SetAction(string action) => Action = action; + + public void SetLongBlade(bool enabled) + { + } + + public void SetWeapons(float left, float right) + { + } + } + + private sealed class Film : IEffectMovie + { + public bool Finished + { + get; set; + } + + public int Disposals; + + public void Dispose() => Disposals++; + } + + private sealed class TestCamera : IEffectCamera + { + public int List + { + get; private set; + } + + public void StopList() => List = 0; + + public bool StartList(int index) + { + List = index; + return true; + } + + public void SetQuake(float amplitude, float frequency, float decay) + { + } + } + + private sealed class Context : IBattleEffectContext, IEffectTimeControl + { + public readonly Actor Role = new(); + public readonly List Films = new(); + public readonly Dictionary Scales = new(); + + public void SetTimeScale(object owner, float scale) => Scales.Add(owner, scale); + + public void ClearTimeScale(object owner) => Scales.Remove(owner); + + public IEffectCamera Camera { get; } = new TestCamera(); + public bool IsModalPresentationRunning => Films.Any(film => !film.Finished && film.Disposals == 0); + + public int NextEffectRandom() => 1; + + public IEffectActor Actor(int nativeIndex, uint modelCrc = 0) => Role; + + public IEffectMovie PlayMovie(string originalPath) + { + var film = new Film(); + Films.Add(film); + return film; + } + } + + private static EffectResources ControlResources(bool movies) + { + var hash = new Crc32Hash(); + hash.Init(); + var resources = new EffectResources(new CpkFileSystem(Application.temporaryCachePath, hash, 936)); + var definitions = new EffectDefinition[1324]; + definitions[0] = new EffectDefinition { IsValid = true, TypeNameCrc = 1, ClassNameCrc = hash.Compute("action", 936) }; + definitions[1] = new EffectDefinition { IsValid = true, TypeNameCrc = 2, ClassNameCrc = hash.Compute("bink", 936), VideoFileNamePrefix = "review" }; + var objects = new List(); + if (movies) + objects.Add(new EffectGroupObject + { + TypeCrc = 2, + Tasks = new[] + { + new EffectTask { IsValid = true, XStretchSpeed = 1, StartTime = -1, Duration = 10 }, + new EffectTask { IsValid = true, XStretchSpeed = 2, StartTime = -1, Duration = 10 }, + } + }); + objects.Add(ActionObject(definitions[0])); + typeof(EffectResources).GetField("_definitions", Members).SetValue(resources, + new EffectDefinitionFile(definitions, new[] { new EffectGroup { Objects = objects.ToArray() } })); + return resources; + } + + private static EffectGroupObject ActionObject(EffectDefinition definition) => new() + { + TypeCrc = definition.TypeNameCrc, + Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 10, XStretchSpeed = 17, SpeedX = 10 } } + }; + + [TestCase("absolute")] + [TestCase("dispose")] + [TestCase("delta")] + [TestCase("frame")] + [TestCase("seek")] + [TestCase("manager")] + [TestCase("mixed")] + [TestCase("return to external clock")] + [TestCase("external clock has caught up")] + [TestCase("external clock catches up within float precision")] + public void BattleTimeTaskReleasesItsScaleOnEveryClockPath(string clock) + { + using var resources = ControlResources(false); + var hash = new Crc32Hash(); + hash.Init(); + resources.Definitions.EffectDefinitions[2] = new EffectDefinition + { + IsValid = true, + TypeNameCrc = 3, + ClassNameCrc = hash.Compute("time", 936) + }; + typeof(EffectResources).GetField("_definitions", Members).SetValue(resources, new EffectDefinitionFile( + resources.Definitions.EffectDefinitions, new[] + { + new EffectGroup + { + Objects = new[] + { + new EffectGroupObject + { + TypeCrc = 3, + Tasks = new[] { new EffectTask + { + IsValid = true, StartTime = -1, Duration = 2, XStretchSpeed = 0, CreateNew = true, ModifyLast = true, + SpeedRot = 5 // The rotation union slot is unused by the time task. + } } + } + } + } + })); + Assert.That(resources.Diagnose(0, battleContext: true), Is.Empty); + Assert.That(resources.Preload(0, battleContext: true).Distinct(), Is.EqualTo(new[] { 0 })); + + var root = new GameObject("Battle time effect"); + var player = root.AddComponent(); + var context = new Context(); + player.AutoAdvance = false; + try + { + player.Initialize(resources, 0, battleContext: context); + switch (clock) + { + case "absolute": + case "dispose": + player.AdvanceTo(.25, 1); + Assert.That(context.Scales.Values, Is.EqualTo(new[] { 0f })); + if (clock == "dispose") + player.Dispose(); + else + { + player.AdvanceTo(.25, 2.9); + Assert.That(context.Scales, Has.Count.EqualTo(1)); + player.AdvanceTo(.25, 3); + } + break; + case "delta": + player.Advance(3); + break; + case "frame": + player.AdvanceFrame(.25f); + player.AdvanceFrame(2f); + break; + case "seek": + player.Seek(3); + break; + case "manager": + player.AdvanceTo(.25); + player.AdvanceTo(2.25); + break; + case "mixed": + player.AdvanceTo(.25); + player.AdvanceTo(.5, 100.5); + Assert.That(context.Scales, Has.Count.EqualTo(1)); + player.AdvanceTo(.75); + player.AdvanceFrame(.25f); + player.AdvanceTo(1, 102.25); + break; + case "return to external clock": + player.AdvanceTo(.25, 1); + player.AdvanceFrame(.5f); + player.AdvanceTo(1, 1.125); + Assert.That(context.Scales, Has.Count.EqualTo(1)); + player.AdvanceTo(1, 2.375); + break; + case "external clock has caught up": + player.AdvanceTo(.25, 1); + player.AdvanceFrame(.5f); + player.AdvanceTo(2.25, 1.75); + Assert.That(context.Scales, Has.Count.EqualTo(1)); + player.AdvanceTo(2.25, 3); + break; + case "external clock catches up within float precision": + player.AdvanceTo(.25, 1); + player.AdvanceFrame(.1f); + player.AdvanceTo(2.5, 1.1); + Assert.That(context.Scales, Has.Count.EqualTo(1)); + player.AdvanceTo(2.5, 3.1); + break; + } + + Assert.That(context.Scales, Is.Empty); + Assert.That(player.IsAlive, Is.False); + Assert.That(player.Error, Is.Null); + } + finally + { + player.Dispose(); + Object.DestroyImmediate(root); + } + } + + [Test] + public void ExplicitDisposalReleasesLiveActionOnceAndRejectsReinitialization() + { + using var resources = ControlResources(false); + var root = new GameObject("Action disposal"); + var player = root.AddComponent(); + var context = new Context(); + player.AutoAdvance = false; + try + { + player.Initialize(resources, 0, battleContext: context); + player.AdvanceFrame(.02f); + Assert.That(context.Role.Controlled, Is.True); + player.Dispose(); + player.Dispose(); + Assert.That(context.Role.Controlled, Is.False); + Assert.That(context.Role.Releases, Is.EqualTo(1)); + Assert.That(player.NodeCount, Is.Zero); + Assert.That(player.IsAlive, Is.False); + float time = player.Time; + player.AdvanceFrame(1); + player.AdvanceTo(1); + Assert.That(player.ResumeBattleStep(), Is.True); + Assert.That(player.Time, Is.EqualTo(time)); + Assert.Throws(() => player.Initialize(resources, 0)); + } + finally + { + player.Dispose(); + Object.DestroyImmediate(root); + } + } + + [TestCase(false, 0)] + [TestCase(true, 2)] + public void DisposingACameraEffectStopsOnlyItsStillRunningTask(bool expired, int expectedList) + { + using var resources = ControlResources(false); + var hash = new Crc32Hash(); + hash.Init(); + var definitions = resources.Definitions.EffectDefinitions; + definitions[2] = new EffectDefinition { IsValid = true, TypeNameCrc = 3, ClassNameCrc = hash.Compute("camera", 936) }; + typeof(EffectResources).GetField("_definitions", Members).SetValue(resources, new EffectDefinitionFile(definitions, new[] + { + new EffectGroup + { + Objects = new[] + { + new EffectGroupObject { TypeCrc = 3, Tasks = new[] + { + new EffectTask { IsValid = true, StartTime = -1, Duration = .1f, XStretchSpeed = 1 }, + new EffectTask { IsValid = true, StartTime = 1, Duration = .1f } + } } + } + } + })); + var root = new GameObject("Camera effect owner"); + var player = root.AddComponent(); + var context = new Context(); + var camera = (TestCamera)context.Camera; + try + { + player.Initialize(resources, 0, battleContext: context); + player.AdvanceTo(.02); + Assert.That(camera.List, Is.EqualTo(1)); + if (expired) + { + player.AdvanceTo(.25); + Assert.That(player.IsAlive, Is.True); + camera.StartList(2); + } + player.Dispose(); + Assert.That(camera.List, Is.EqualTo(expectedList)); + } + finally + { + player.Dispose(); + Object.DestroyImmediate(root); + } + } + + [Test] + public void SeekingABattleEffectNeverStartsMovieOrControlsAnActor() + { + using var resources = ControlResources(true); + var root = new GameObject("Modal seek"); + var player = root.AddComponent(); + var context = new Context(); + try + { + player.Initialize(resources, 0, battleContext: context); + player.Seek(.4f); + Assert.That(player.Time, Is.EqualTo(.4f).Within(.001f)); + Assert.That(context.Films, Is.Empty); + Assert.That(context.Role.Action, Is.Null); + Assert.That(context.Role.Controlled, Is.False); + Assert.That(player.ResumeBattleStep(), Is.True); + } + finally + { + player.Dispose(); + Object.DestroyImmediate(root); + } + } + + [Test] + public void ResumingAfterASeekDoesNotApplyAnUninitializedActorAction() + { + using var resources = ControlResources(false); + var root = new GameObject("Action seek"); + var player = root.AddComponent(); + var context = new Context(); + try + { + EffectTask moving = resources.Definitions.Groups[0].Objects[0].Tasks[0]; + moving.SpeedBlue = 1; + moving.RotAxisX = 10; + moving.Duration = 1; + context.Role.Position = new Vector3(40, 0, 0); + player.Initialize(resources, 0, battleContext: context); + player.Seek(.4f); + player.AdvanceFrame(.02f); + Assert.That(context.Role.Position.x, Is.EqualTo(40)); + Assert.That(context.Role.Controlled, Is.False); + Assert.That(context.Role.Action, Is.Null); + } + finally + { + player.Dispose(); + Object.DestroyImmediate(root); + } + } + + [TestCase(false)] + [TestCase(true)] + public void ConsecutiveModalTasksResumeAtOneTimeAndDisposeTheirRemainingOwner(bool cancelDuringMovie) + { + using var resources = ControlResources(true); + var root = new GameObject("Modal cancellation"); + var player = root.AddComponent(); + var context = new Context(); + player.AutoAdvance = false; + try + { + player.Initialize(resources, 0, battleContext: context, clockOrigin: 1024); + player.AdvanceTo(1024.02); + float time = player.Time; + Assert.That(context.Films.Count, Is.EqualTo(1)); + Assert.That(context.Role.Action, Is.Null); + player.AdvanceTo(1024.2); + player.Advance(.2f); + player.AdvanceFrame(.2f); + Assert.That(player.Time, Is.EqualTo(time)); + context.Films[0].Finished = true; + Assert.That(player.ResumeBattleStep(), Is.False); + Assert.That(context.Films.Count, Is.EqualTo(2)); + Assert.That(context.Role.Action, Is.Null); + if (!cancelDuringMovie) + { + context.Films[1].Finished = true; + Assert.That(player.ResumeBattleStep(), Is.True); + Assert.That(context.Role.Action, Is.EqualTo("z17")); + Assert.That(context.Role.Position.x, Is.EqualTo((time - 1024) * 10).Within(.000001f)); + Assert.That(context.Role.Controlled, Is.True); + } + Assert.That(player.Time, Is.EqualTo(time)); + player.Dispose(); + player.Dispose(); + Assert.That(context.Role.Controlled, Is.False); + Assert.That(context.Role.Releases, Is.EqualTo(cancelDuringMovie ? 0 : 1)); + Assert.That(context.Films.All(film => film.Disposals == 1), Is.True); + Assert.That(player.ResumeBattleStep(), Is.True); + Assert.That(player.NodeCount, Is.Zero); + } + finally + { + player.Dispose(); + Object.DestroyImmediate(root); + } + } + + private static BattleData LocalData() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original game data is required for model ownership regression."); + return new BattleData(root, 936); + } + + private static EffectResources DirectorResources(BattleEffectDirector director) => + (EffectResources)typeof(BattleEffectDirector).GetField("_resources", Members).GetValue(director); + + private static void ModelGroup(EffectResources resources, string extension) + { + EffectDefinitionFile definitions = resources.Definitions; + EffectDefinition model = definitions.EffectDefinitions.First(definition => definition.IsValid && + EffectClass.Name(definition.ClassNameCrc) == "model" && definition.TextureName.EndsWith("." + extension, StringComparison.OrdinalIgnoreCase)); + EffectDefinition action = definitions.EffectDefinitions.First(definition => definition.IsValid && EffectClass.Name(definition.ClassNameCrc) == "action"); + definitions.Groups[0] = new EffectGroup + { + Objects = new[] + { + ActionObject(action), + new EffectGroupObject { TypeCrc = model.TypeNameCrc, Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 10, SpeedAlpha = -.5f } } } + } + }; + } + + private static int LightBindings(GameBoxNativeLighting lighting) => + ((ICollection)typeof(GameBoxNativeLighting).GetField("_bindings", Members).GetValue(lighting)).Count; + + private static Material[] OwnedMaterials(EffectPlayer player) + { + var materials = new HashSet(player.GetComponentsInChildren().SelectMany(renderer => renderer.sharedMaterials)); + foreach (GameBoxBattleRenderPhase phase in player.GetComponentsInChildren()) + materials.UnionWith(phase.SourceMaterials); + foreach (object node in (IEnumerable)typeof(EffectPlayer).GetField("_nodes", Members).GetValue(player)) + { + if (node.GetType().GetField("_materials", Members)?.GetValue(node) is not GameMaterialManager manager) + continue; + foreach (FieldInfo field in typeof(GameMaterialManager).GetFields(Members)) + if (field.GetValue(manager) is IMaterial material) + materials.Add((Material)material.NativeObject); + } + return materials.Where(material => material != null).ToArray(); + } + + [TestCase("POL")] + [TestCase("CVD")] + [Category("LocalGameData")] + public void DirectorStopReleasesLiveModelMeshesMaterialsLightingAndActorControl(string extension) + { + using var data = LocalData(); + using var lighting = new GameBoxNativeLighting(BattleData.Variant); + using var preview = new ResourceModelPreview(data.Resources, false, lighting); + using var director = new BattleEffectDirector(data, preview); + EffectResources resources = DirectorResources(director); + ModelGroup(resources, extension); + long handle = director.Start(new BattleEffectRequest(0, "Ally", new[] { "Enemy" }, default, 1)); + EffectPlayer player = preview.Root.GetComponentInChildren(); + var context = new Context(); + player.Initialize(resources, 0, battleContext: context, nativeLighting: lighting); + player.AdvanceFrame(.02f); + player.Render(null); + Assert.That(player.Error, Is.Null); + Assert.That(context.Role.Controlled, Is.True); + Mesh[] meshes = player.GetComponentsInChildren().Select(filter => filter.sharedMesh).ToArray(); + Material[] materials = OwnedMaterials(player); + Assert.That(meshes, Is.Not.Empty); + Assert.That(materials.Length, Is.GreaterThan(4)); + Assert.That(LightBindings(lighting), Is.GreaterThan(0)); + director.Stop(handle); + director.Stop(handle); + player.Dispose(); + Assert.That(player.NodeCount, Is.Zero); + Assert.That(context.Role.Controlled, Is.False); + Assert.That(context.Role.Releases, Is.EqualTo(1)); + Assert.That(meshes.All(mesh => mesh == null), Is.True); + Assert.That(materials.All(material => material == null), Is.True); + Assert.That(LightBindings(lighting), Is.Zero); + Assert.That(director.IsRunning(handle), Is.False); + } + + [TestCase("POL")] + [TestCase("CVD")] + [Category("LocalGameData")] + public void FailedStartAfterModelCreationReleasesItsPrivateResources(string extension) + { + using var data = LocalData(); + using var lighting = new GameBoxNativeLighting(BattleData.Variant); + using var preview = new ResourceModelPreview(data.Resources, false, lighting); + using var director = new BattleEffectDirector(data, preview); + ModelGroup(DirectorResources(director), extension); + director.Preload(0); + var materials = new HashSet(Resources.FindObjectsOfTypeAll()); + var meshes = new HashSet(Resources.FindObjectsOfTypeAll()); + typeof(BattleEffectDirector).GetField("_nextHandle", Members).SetValue(director, long.MaxValue); + Assert.Throws(() => director.Start(new BattleEffectRequest(0, "Ally", new[] { "Enemy" }, default, 1))); + Assert.That(preview.Root.GetComponentsInChildren(), Is.Empty); + Assert.That(Resources.FindObjectsOfTypeAll().Except(materials), Is.Empty); + Assert.That(Resources.FindObjectsOfTypeAll().Except(meshes), Is.Empty); + Assert.That(LightBindings(lighting), Is.Zero); + } + + [TestCase(false)] + [TestCase(true)] + public void CompositePreviewDisposesUnregisteredEffectPlayersBeforeDestroyingTheirObjects(bool wholePreview) + { + using var resources = ControlResources(false); + using var preview = new ResourceModelPreview(null, false); + GameObject root = preview.CreateObject("Composite effect"); + var player = root.AddComponent(); + var context = new Context(); + player.AutoAdvance = false; + player.Initialize(resources, 0, battleContext: context); + player.AdvanceFrame(.02f); + Assert.That(context.Role.Controlled, Is.True); + if (wholePreview) + preview.Dispose(); + else + preview.ReleaseCompositeObject(root); + Assert.That(context.Role.Controlled, Is.False); + Assert.That(context.Role.Releases, Is.EqualTo(1)); + Assert.That(player.NodeCount, Is.Zero); + } + + [TestCase(false)] + [TestCase(true)] + [Category("LocalGameData")] + public void CompositePreviewReleasesPortalMeshesWhileKeepingSharedMaterialsBorrowed(bool wholePreview) + { + using var data = LocalData(); + using var resources = new EffectResources(data.Resources.FileSystem, 936); + using var preview = new ResourceModelPreview(data.Resources, false); + GameObject root = preview.CreateObject("Composite portal"); + var portal = root.AddComponent(); + portal.AutoAdvance = false; + portal.Initialize(resources); + Mesh[] meshes = root.GetComponentsInChildren().Select(filter => filter.sharedMesh).ToArray(); + Material[] materials = root.GetComponentsInChildren().Select(renderer => renderer.sharedMaterial).ToArray(); + Assert.That(meshes.Length, Is.EqualTo(3)); + if (wholePreview) + preview.Dispose(); + else + preview.ReleaseCompositeObject(root); + portal.Dispose(); + Assert.That(meshes.All(mesh => mesh == null), Is.True); + Assert.That(materials.All(material => material != null), Is.True); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectLifecycleTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectLifecycleTests.cs.meta new file mode 100644 index 00000000..7be5f0c5 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectLifecycleTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b0e82f03efab4c2cbb4ffe30a9d47164 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectRandomTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectRandomTests.cs new file mode 100644 index 00000000..3f772ce0 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectRandomTests.cs @@ -0,0 +1,190 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Core.DataReader.Data; + using Core.DataReader.Cpk; + using Core.FileSystem; + using Game.Effect.Runtime; + using Newtonsoft.Json; + using Newtonsoft.Json.Linq; + using NUnit.Framework; + using ResourceBrowser; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed class BattleEffectRandomTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + + private static Type NodeType(string name) => typeof(EffectPlayer).Assembly.GetType("Pal3.Game.Effect.Runtime." + name, true); + + [Test] + [Category("LocalNativeEvidence")] + public void ShockSharesOnlyTheOriginalEffectStreamAcrossObjectsAndGroups() + { + string directory = Environment.GetEnvironmentVariable("PAL3_EFFECT_RANDOM_VECTORS_ROOT"); + if (directory == null) + Assert.Ignore("The independently executed original effect vectors are local artifacts."); + JObject document = JObject.Parse(File.ReadAllText(Path.Combine(directory, "effect-random-native-vectors.json"))); + var hash = new Crc32Hash(); + hash.Init(); + using var resources = new EffectResources(new CpkFileSystem(Application.temporaryCachePath, hash, 936)); + int count = 0; + foreach (JProperty variant in document.Properties()) + { + BattleRandom random = null; + foreach (JToken row in variant.Value["rows"]) + { + if ((int)row["repeat"] == 0) + random = new BattleRandom((int)row["seed"]); + var definition = new EffectDefinition + { + RotationAngle = (int)row["nodes"], + Width = (int)row["cascades"], + FrameCount = (int)row["frames"], + BottomRadius = .25f + }; + var task = new EffectTask { StartTime = -1, Duration = 1, RequireLoops = 2 }; + var root = new GameObject("native shock random") { hideFlags = HideFlags.HideAndDontSave }; + object node = null; + try + { + node = Activator.CreateInstance(NodeType("TrailNode"), Members, null, + new object[] { root, definition, new[] { task }, Vector3.zero, 0f, resources, "shock", 99u, true, (Func)random.Next }, null); + node.GetType().GetMethod("Step", Members).Invoke(node, new object[] { 0f, 0f }); + float[] frames = (float[])node.GetType().GetField("_shockFrame", Members).GetValue(node); + float[] limits = (float[])node.GetType().GetField("_shockLimit", Members).GetValue(node); + Assert.That(frames, Is.EqualTo(row["startedFrames"].Select(value => (float)value).ToArray())); + Assert.That(limits, Is.EqualTo(row["limits"].Select(value => (float)value).ToArray())); + Assert.That(random.State, Is.EqualTo((uint)row["effectState"])); + Assert.That((uint)row["domainState"], Is.EqualTo(0x12345678u)); + count++; + } + finally + { + try + { + ((IDisposable)node)?.Dispose(); + } + finally { Object.DestroyImmediate(root); } + } + } + } + Assert.That(count, Is.EqualTo(144)); + } + + [Test] + [Category("LocalNativeEvidence")] + public void ExplosiveMatchesTheReleasedEffectStreamWithoutChangingCombatRandom() + { + string directory = Environment.GetEnvironmentVariable("PAL3_EFFECT_RANDOM_VECTORS_ROOT"); + if (directory == null) + Assert.Ignore("The independently executed original effect vectors are local artifacts."); + JObject document = JObject.Parse(File.ReadAllText(Path.Combine(directory, "effect-random-native-vectors.json"))); + var hash = new Crc32Hash(); + hash.Init(); + using var resources = new EffectResources(new CpkFileSystem(Application.temporaryCachePath, hash, 936)); + int count = 0; + foreach (JProperty variant in document.Properties()) + foreach (JToken row in variant.Value["explosiveRows"]) + { + var random = new BattleRandom((int)row["seed"]); + var definition = new EffectDefinition { RotationAngle = (int)row["columns"], DivisionCount = (int)row["rows"], TopRadius = (int)row["power"] }; + var root = new GameObject("native explosive random") { hideFlags = HideFlags.HideAndDontSave }; + object node = null; + try + { + node = Activator.CreateInstance(NodeType("ExplosiveNode"), Members, null, + new object[] { root, definition, Array.Empty(), Vector3.zero, 0f, resources, 999u, true, (Func)random.Next }, null); + node.GetType().GetMethod("Explode", Members).Invoke(node, null); + Vector3[] velocity = (Vector3[])node.GetType().GetField("_velocity", Members).GetValue(node); + Vector3[] spin = (Vector3[])node.GetType().GetField("_spin", Members).GetValue(node); + Vector3 Read(JToken value) => new((float)value[0], (float)value[1], (float)value[2]); + Assert.That(velocity, Is.EqualTo(row["velocity"].Select(Read).ToArray())); + Assert.That(spin, Is.EqualTo(row["spin"].Select(Read).ToArray())); + Assert.That(random.State, Is.EqualTo((uint)row["effectState"])); + Assert.That((uint)row["domainState"], Is.EqualTo(0x12345678u)); + count++; + } + finally + { + try + { + ((IDisposable)node)?.Dispose(); + } + finally { Object.DestroyImmediate(root); } + } + } + Assert.That(count, Is.EqualTo(48)); + } + + [Test] + [Category("LocalGameData")] + public void RealShockGroupsRetainOneVisualStreamWithoutChangingCombatRandom() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (root == null) + Assert.Ignore("Original game data is required for the real-group random regression."); + using var data = new BattleData(root, 936); + using var preview = new ResourceModelPreview(data.Resources, false); + using var director = new BattleEffectDirector(data, preview); + var resources = (EffectResources)typeof(BattleEffectDirector).GetField("_resources", Members).GetValue(director); + var source = resources.Definitions; + int group = Enumerable.Range(0, source.Groups.Length).First(id => source.Groups[id].Objects.Any(obj => + source.TryGetType(obj.TypeCrc, out EffectDefinition definition) && EffectClass.Name(definition.ClassNameCrc) == "shock")); + var scenario = BattleSessionTests.Scenario(); + scenario.Seed = 1; + var combat = new BattleSession(new BattleSetup(scenario), new BattleSessionTests.Catalog(), effects: director); + var combatRandom = (BattleRandom)typeof(BattleSession).GetField("_random", Members).GetValue(combat); + uint before = combatRandom.State; + var samples = new List(); + uint finalState = 0; + for (int repeat = 0; repeat < 2; repeat++) + { + long handle = director.Start(new BattleEffectRequest(group, "Ally", new[] { "Enemy" }, default, 1)); + var players = (IDictionary)typeof(BattleEffectDirector).GetField("_players", Members).GetValue(director); + object instance = players[handle]; + var player = (EffectPlayer)instance.GetType().GetField("Player", Members).GetValue(instance); + var nodes = (IList)typeof(EffectPlayer).GetField("_nodes", Members).GetValue(player); + object shock = nodes.Cast().First(node => node.GetType() == NodeType("TrailNode") && + (string)node.GetType().GetField("_kind", Members).GetValue(node) == "shock"); + for (int step = 1; step <= 100; step++) + { + player.AdvanceTo(step * BattleSession.StepSeconds); + var current = ((float[])shock.GetType().GetField("_shockFrame", Members).GetValue(shock)).ToArray(); + var random = (BattleRandom)typeof(BattleEffectDirector).GetField("_effectRandom", Members).GetValue(director); + if (random.State != (repeat == 0 ? 1u : finalState)) + { + samples.Add(current); + finalState = random.State; + break; + } + } + director.Stop(handle); + } + Assert.That(samples.Count, Is.EqualTo(2)); + Assert.That(samples[1], Is.Not.EqualTo(samples[0]), "A second original group must continue the GT util random stream."); + Assert.That(combatRandom.State, Is.EqualTo(before)); + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_REPORT_DIR"); + if (output != null) + File.WriteAllText(Path.Combine(output, BattleData.Variant + "-real-effect-random.json"), JsonConvert.SerializeObject(new + { + group, + samples, + finalState, + combatRandom = before + }, Formatting.Indented)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectRandomTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectRandomTests.cs.meta new file mode 100644 index 00000000..40b62b78 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleEffectRandomTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 77a69344f8e94a448d3ee1cda423b47e diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleElementWheelIntegrationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleElementWheelIntegrationTests.cs new file mode 100644 index 00000000..4333815f --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleElementWheelIntegrationTests.cs @@ -0,0 +1,89 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +#if PAL3A +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using NUnit.Framework; + + [Category("LocalGameData")] + public sealed class BattleElementWheelIntegrationTests + { + private BattleEditorSession _session; + + [SetUp] + public void LoadData() + { + string root = Environment.GetEnvironmentVariable("PAL3A_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Original PAL3A data is required for the wheel presentation tests."); + _session = new BattleEditorSession(); + _session.Load(root, 936); + } + + [TearDown] + public void Dispose() => _session?.Dispose(); + + [TestCase(264, 0, 1)] + [TestCase(265, 1, 2)] + [TestCase(266, 3, 4)] + [TestCase(267, 2, 3)] + [TestCase(268, 4, 5)] + public void ActualWheelUsesZ24AndBothLinkerGroupsWithoutMagicCostsAndReplays(int skillId, int coreElement, int field) + { + BattleData data = _session.Data; + var scenario = new BattleScenario + { + Variant = "PAL3A", + Scene = data.Scenes.First(), + DataFingerprint = data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + scenario.Pal3A.SpiritWheel.Charges = Enumerable.Repeat(9, 5).ToArray(); + scenario.Participants.Add(data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(data.CreateParticipant(7311, BattleSide.Enemy, BattleSlot.Water)); + foreach (BattleParticipant actor in scenario.Participants) + { + actor.Attributes = new[] { 5000, 100, 1000, 50, 50, 5, 0, 0, 0, 0, 0, 0 }; + actor.Vitals = new[] { 5000, 100, 0 }; + actor.Skills.Clear(); + } + scenario.Participants[0].Statuses.Add(new BattleStatus { Id = (int)BattleState.Seal, Rounds = 20 }); + _session.StartBattle(scenario); + BattleSession combat = _session.Battle; + string source = scenario.Participants[0].InstanceId; + var catalog = new BattleAnimationCatalog(data, new BattleSetup(scenario), combat.Definitions); + BattleAbilityDefinition ability = combat.Definitions.Skills[skillId]; + Assert.That((ability.SkillTypeId, ability.Range, ability.IsMagic), Is.EqualTo((0, BattleTargetRange.None, true))); + Assert.That(ability.Costs.Single(cost => cost.Resource == 2).Value, Is.EqualTo(5)); + Assert.That(catalog.AbilityStage(source, ability).Kind, Is.EqualTo(BattleAbilityStageKind.Magic), "AI keeps the ordinary magic stage."); + BattleAbilityStageProfile wheel = catalog.ElementWheelStage(source, ability); + Assert.That(wheel.Kind, Is.EqualTo(BattleAbilityStageKind.ElementWheel)); + Assert.That(catalog.ElementWheelBody(source, ability).Clip, Is.EqualTo("z24")); + Assert.That(combat.CanSubmitElementWheel(source, skillId), Is.Null); + Assert.That(combat.SubmitElementWheel(source, skillId), Is.True); + for (int tick = 0; tick < 1500 && combat.Status == BattleSessionStatus.Running && combat.Actors.Single(actor => actor.Id == source).ActionId != 0; tick++) + _session.StepBattle(); + Assert.That(combat.Status, Is.EqualTo(BattleSessionStatus.Running), combat.Result?.Reason); + Assert.That(combat.Actors.Single(actor => actor.Id == source).ActionId, Is.Zero); + Assert.That((combat.FiveSpiritElement, combat.FiveSpiritForce), Is.EqualTo((field, 1))); + int[] expected = Enumerable.Repeat(9, 5).ToArray(); + expected[coreElement] = 0; + Assert.That(combat.Pal3AState.SpiritWheel.Charges, Is.EqualTo(expected)); + Assert.That(combat.Actors.Single(actor => actor.Id == source).Mp, Is.Zero); + Assert.That(combat.Actors.Single(actor => actor.Id == source).Skills, Is.Empty); + Assert.That(combat.Events.Any(entry => entry.Detail.StartsWith("skill cost", StringComparison.Ordinal)), Is.False); + var events = combat.Events.Select(entry => (entry.Tick, entry.Kind, entry.Source, entry.Target, entry.RandomState, entry.Detail)).ToArray(); + _session.ReplayBattle(); + Assert.That(_session.Battle.Events.Select(entry => (entry.Tick, entry.Kind, entry.Source, entry.Target, entry.RandomState, entry.Detail)), Is.EqualTo(events)); + Assert.That(_session.Battle.Pal3AState.SpiritWheel.Charges, Is.EqualTo(expected)); + } + } +} +#endif diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleElementWheelIntegrationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleElementWheelIntegrationTests.cs.meta new file mode 100644 index 00000000..c6bb5c10 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleElementWheelIntegrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4f67a0a9a61f48329e17eb6050615fe0 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleEquipmentIntegrationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleEquipmentIntegrationTests.cs new file mode 100644 index 00000000..39091246 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleEquipmentIntegrationTests.cs @@ -0,0 +1,208 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using Core.Contract.Enums; + using Core.DataReader.Gdb; + using NUnit.Framework; + + [Category("LocalGameData")] + public sealed class BattleEquipmentIntegrationTests + { + private sealed class Catalog : IBattleCatalog + { + public AttackTiming Attack(string source, string target) => new(0, 5, new[] { 2 }); + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => 0; + + public int DamageDivisor(string actor) => 1; + } + + private static BattleData Load() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Original game data is required."); + return new BattleData(root, 936); + } + + [Test] + public void CombatRosterRejectsOppositeSidesAndNonstandardMainFormsWithoutRestrictingPreviewCapture() + { + using BattleData data = Load(); + foreach (var entry in data.Database.CombatActorInfos.Where(entry => entry.Key > 0)) + { + bool main = entry.Value.Type == CombatActorType.MainActor; + bool standard = BattleData.PlayerIdentity(entry.Key) >= 0; + Assert.That(data.CombatRosterDenial(entry.Key, BattleSide.Ally) == null, Is.EqualTo(main && standard), "ally " + entry.Key); + Assert.That(data.CombatRosterDenial(entry.Key, BattleSide.Enemy) == null, Is.EqualTo(!main), "enemy " + entry.Key); + } + BattleScenario scenario = Setup(data, 0, 0, 0).CreateInstance(); + Assert.That(data.Validate(scenario, forBattle: true), Is.Empty); + scenario.Participants = scenario.Participants.Select(actor => data.CreateParticipant(actor.ActorId, + actor.Side == BattleSide.Ally ? BattleSide.Enemy : BattleSide.Ally, actor.Slot)).ToList(); + Assert.That(data.Validate(scenario), Is.Empty, "Action previews retain their existing roster freedom."); + Assert.DoesNotThrow(() => data.Capture(scenario)); + string[] reasons = data.Validate(scenario, forBattle: true).ToArray(); + foreach (BattleParticipant actor in scenario.Participants) + Assert.That(reasons.Any(reason => reason.Contains(actor.ActorId.ToString()) && reason.Contains(data.Database.CombatActorInfos[actor.ActorId].Name)), Is.True); + Assert.Throws(() => new BattleAnimationCatalog(data, data.Capture(scenario))); + } + + private static BattleSetup Setup(BattleData data, int identity, int item, int slot) + { + int actorId = ActorConstants.MainActorCombatActorIdMap.Single(pair => (int)pair.Key == identity).Value; + BattleParticipant player = data.CreateParticipant(actorId, BattleSide.Ally, BattleSlot.Water); + player.AttributeSource = BattleAttributeSource.BaseWithEquipment; + player.Attributes = new[] { 100, 20, 30, 40, 50, 6, 7, 8, 9, 10, 11, 12 }; + player.Vitals = new[] { 100, 20, 30 }; + player.Equipment = new int[6]; + player.Equipment[0] = BattleLoadoutRules.DefaultWeapon(BattleData.Variant, identity); + player.UsesNativeDefaultWeapon = true; + player.MagicSword = BattleData.Variant == "PAL3" && identity == 0 ? new BattleMagicSword() : null; + if (item != 0) + { + player.Equipment[slot] = item; + if (slot == 0) + { + player.UsesNativeDefaultWeapon = false; + player.MagicSword = BattleData.Variant == "PAL3" && item == 6603 ? new BattleMagicSword() : null; + } + } + return new BattleSetup(new BattleScenario + { + Variant = BattleData.Variant, + DataFingerprint = data.Fingerprint, + Scene = data.Scenes.First(), + Seed = 12345, + Participants = { player, data.CreateParticipant(7311, BattleSide.Enemy, BattleSlot.Water) } + }); + } + + private static BattleSession Start(BattleData data, BattleSetup setup) => + new(setup, new Catalog(), definitions: BattleDefinitionCompiler.Build(data, setup)); + + [Test] + public void EveryLegalStockEquipmentAndPlayerCombinationCompilesInBothOrnamentSlots() + { + using BattleData data = Load(); + int canonicalPairs = 0; + foreach (GameItemInfo item in data.Database.GameItemInfos.Values.Where(item => (int)item.Type is >= 7 and <= 11)) + { + int slot = (int)item.Type switch + { + 11 => 0, + 8 => 1, + 7 => 2, + 9 => 3, + _ => 4 + }; + foreach (PlayerActorId identity in item.ApplicableActors) + { + canonicalPairs++; + foreach (int position in slot == 4 ? new[] { 4, 5 } : new[] { slot }) + { + BattleSetup setup = Setup(data, (int)identity, (int)item.Id, position); + BattleActorDefinition actor = BattleDefinitionCompiler.Build(data, setup).Actors.Values.Single(actor => actor.Identity == (int)identity); + string context = $"item={item.Id}, identity={identity}, slot={position}"; + Assert.That(actor.UnsupportedReason, Is.Empty, context); + Assert.That(actor.Equipment.Select(equipment => equipment.UnsupportedReason), Is.All.Empty, context); + } + } + } + Assert.That(canonicalPairs, Is.EqualTo(BattleData.Variant == "PAL3" ? 438 : 442)); + } + + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + [TestCase(4)] + [TestCase(5)] + public void NonweaponPoisonResistanceUsesEveryNonzeroSignedWordAndIgnoresFlags(int slot) + { + using BattleData data = Load(); + int type = slot switch + { + 1 => 8, + 2 => 7, + 3 => 9, + _ => 10 + }; + GameItemInfo original = data.Database.GameItemInfos.Values.First(item => (int)item.Type == type && item.ApplicableActors.Contains((PlayerActorId)0)); + GameItemInfo changed = original; + changed.CombatStates = new Dictionary + { + [ActorCombatStateType.Invisible] = new() { Flags = 1, Value = 15 } + }; + BattleSetup setup = Setup(data, 0, (int)original.Id, slot); + uint? seed = null; + try + { + foreach (byte flags in new byte[] { 0, 1, 255 }) + foreach (short value in new short[] { 0, 1, 2, 15, -1, short.MinValue, short.MaxValue }) + { + changed.CombatStates[ActorCombatStateType.PoisonResist] = new ItemCombatStateValue { Flags = flags, Value = value }; + data.Database.GameItemInfos[(int)original.Id] = changed; + BattleSession session = Start(data, setup); + BattleActorSnapshot player = session.Actors.Single(actor => actor.Side == BattleSide.Ally); + Assert.That(player.States.Select(state => state.State), + Is.EquivalentTo(value == 0 ? Array.Empty() : new[] { BattleState.PoisonResist }), $"flags={flags}, word={value}"); + if (value != 0) + Assert.That(player.States.Single().Permanent, Is.True); + uint current = session.Events.Single(entry => entry.Kind == BattleEventKind.Started).RandomState; + seed ??= current; + Assert.That(current, Is.EqualTo(seed), $"flags={flags}, word={value}"); + Assert.That(data.Database.GameItemInfos[(int)original.Id].CombatStates[ActorCombatStateType.PoisonResist].Value, Is.EqualTo(value)); + } + } + finally + { + data.Database.GameItemInfos[(int)original.Id] = original; + } + } + +#if PAL3A + [TestCase(8144, 1, 4)] + [TestCase(8144, 1, 5)] + [TestCase(8144, 2, 4)] + [TestCase(8144, 2, 5)] + [TestCase(8146, 0, 4)] + [TestCase(8146, 0, 5)] + [TestCase(8146, 3, 4)] + [TestCase(8146, 3, 5)] + [TestCase(8146, 4, 4)] + [TestCase(8146, 4, 5)] + public void StockOrnamentsPreserveAttributesWithoutInventingPassiveStates(int item, int identity, int slot) + { + using BattleData data = Load(); + BattleSession baseline = Start(data, Setup(data, identity, 0, slot)); + BattleSession session = Start(data, Setup(data, identity, item, slot)); + BattleActorSnapshot player = session.Actors.Single(actor => actor.Side == BattleSide.Ally); + BattleActorSnapshot before = baseline.Actors.Single(actor => actor.Side == BattleSide.Ally); + int[] expected = before.Attributes.ToArray(); + expected[4] += item == 8144 ? 8 : 5; + expected[item == 8144 ? 11 : 10]++; + Assert.That(player.Attributes, Is.EqualTo(expected)); + Assert.That(player.States, Is.Empty); + Assert.That(session.Definitions.Actors[player.Id].Equipment.Single(equipment => equipment.Slot == slot).States, Is.Empty); + Assert.That(session.Events.Last().RandomState, Is.EqualTo(baseline.Events.Last().RandomState)); + Assert.That(data.Database.GameItemInfos[item].CombatStates.Values.Any(state => state.Value != 0), Is.True); + } +#endif + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleEquipmentIntegrationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleEquipmentIntegrationTests.cs.meta new file mode 100644 index 00000000..089e0d38 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleEquipmentIntegrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: df8c5a5884464bbc9a2ec115828cc54c diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleHitFeedbackTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleHitFeedbackTests.cs new file mode 100644 index 00000000..543f8878 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleHitFeedbackTests.cs @@ -0,0 +1,370 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Core.Contract.Enums; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed class BattleHitFeedbackRulesTests + { + [Test] + public void SimpleAtlasStartsAfterTheCreationPassAndHasOneSixteenFrameLoop() + { + Assert.That(BattleHitFlashSnapshot.FrameAt(-1), Is.EqualTo(-1)); + Assert.That(BattleHitFlashSnapshot.FrameAt(0), Is.EqualTo(1)); + Assert.That(BattleHitFlashSnapshot.FrameAt(14), Is.EqualTo(15)); + Assert.That(BattleHitFlashSnapshot.FrameAt(15), Is.EqualTo(16)); + } + + [Test] + public void PublishedRedSparkIntegratesGravityBeforeMovementAndExpiresOnLuminosity() + { + var random = new BattleRandom(1); + var spark = new BattleWeaponSpark(new BattleMovementPoint(12, 40, -7), random); + // MSVC rand seed 1: 41%10 = 1, (18467%5760)/16 = 74 degrees. + Assert.That(spark.Velocity.X, Is.EqualTo(MathF.Sin(74 * MathF.PI / 180)).Within(.000001)); + Assert.That(spark.Velocity.Z, Is.EqualTo(MathF.Cos(74 * MathF.PI / 180)).Within(.000001)); + spark.Advance(.02f); + Assert.That(spark.Velocity.Y, Is.EqualTo(-10.4f).Within(.00001)); + Assert.That(spark.Position.Y, Is.EqualTo(39.792f).Within(.00001)); + Assert.That(spark.Alpha, Is.EqualTo(195)); + for (int tick = 1; tick < 40; tick++) + spark.Advance(.02f); + Assert.That(spark.Alive, Is.False); + Assert.That(random.State, Is.EqualTo(3357800067u), "Sparks use exactly two presentation random draws."); + } + } + + [Category("LocalGameData")] + public sealed class BattleHitFeedbackTests + { + private static object Actor(BattleSession session, string id) => + ((IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session))[id]; + + private static void Block(BattleSession session, string id, bool dodge = false) => + typeof(BattleSession).GetMethod("PushBodyBlock", BindingFlags.Instance | BindingFlags.NonPublic) + .Invoke(session, new[] { Actor(session, id), (object)dodge }); + + private static BattleEditorSession Editor(bool ziXuan = false, bool toon = false) + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT") ?? + Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root)) + Assert.Ignore("Original local data unavailable."); + var editor = new BattleEditorSession(); + try + { + editor.Load(root, 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = editor.Data.Scenes.First(), + DataFingerprint = editor.Data.Fingerprint, + Encounter = BattleEncounter.EnemyAmbush, + MotionBlur = false, + ToonRendering = toon + }; + BattleParticipant ally = editor.Data.CreateParticipant(ziXuan ? 107 : 101, BattleSide.Ally, BattleSlot.Water); +#if PAL3 + if (ziXuan) + ally.Equipment[0] = (int)editor.Data.Database.GameItemInfos.Values.First(item => item.Type == ItemType.Weapon && + (int)item.WeaponType == 3 && item.ApplicableActors.Contains(PlayerActorId.ZiXuan)).Id; +#endif + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + scenario.Participants.Add(ally); + scenario.Participants.Add(editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + return editor; + } + catch + { + editor.Dispose(); + throw; + } + } + + private static void HideOrdinaryMeshes(BattlePreview preview) + { + foreach (Renderer renderer in preview.View.Root.GetComponentsInChildren(true)) + renderer.enabled = false; + } + + private static Texture2D Read(RenderTexture source) + { + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = source; + var image = new Texture2D(source.width, source.height, TextureFormat.RGBA32, false); + image.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0); + image.Apply(); + return image; + } + finally + { + RenderTexture.active = previous; + } + } + + [TestCase(false, false)] + [TestCase(false, true)] + [TestCase(true, false)] + [TestCase(true, true)] + public void ModalMovieHidesFrozenPostCompositeHitFlashesAndRestoresThemAfterward(bool toon, bool trail) + { + using BattleEditorSession editor = Editor(toon: toon); + BattleActorSnapshot enemy = editor.Battle.Actors.Single(actor => actor.Side == BattleSide.Enemy); + Block(editor.Battle, enemy.Id); + editor.StepBattle(); + BattleHitFlashSnapshot flash = editor.Battle.HitFlashes.Single(); + Vector3 center = BattleAnimationCatalog.UnityPosition(flash.Position); + editor.Preview.View.SetCamera(center + Vector3.up * 20, center, 35); + editor.Preview.Trail.Enabled = trail; + HideOrdinaryMeshes(editor.Preview); + const BindingFlags members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + var movies = (BattleMoviePlayer)typeof(BattleEffectDirector).GetField("_movies", members).GetValue(editor.Preview.Effects); + string directory = Path.Combine(Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT") ?? Application.temporaryCachePath, + "ModalHitFeedback-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + object movie = null; + try + { + // A tiny decoded black movie exercises the actual movie mesh, + // modal owner and post-composite pass without an external codec. + File.WriteAllBytes(Path.Combine(directory, "video.rgba"), new byte[2 * 2 * 4 * 30]); + Type decodedType = typeof(BattleMoviePlayer).GetNestedType("DecodedMovie", BindingFlags.NonPublic); + object decoded = Activator.CreateInstance(decodedType, true); + foreach (var pair in new[] { ("Width", 2), ("Height", 2), ("Frames", 30) }) + decodedType.GetField(pair.Item1, members).SetValue(decoded, pair.Item2); + decodedType.GetField("Directory", members).SetValue(decoded, directory); + decodedType.GetField("Rate", members).SetValue(decoded, 30u); + decodedType.GetField("Divisor", members).SetValue(decoded, 1u); + movie = Activator.CreateInstance(typeof(BattleMoviePlayer).GetNestedType("Movie", BindingFlags.NonPublic), members, null, + new[] { (object)movies, decoded }, null); + ((IList)typeof(BattleMoviePlayer).GetField("_movies", members).GetValue(movies)).Add(movie); + long simulationTick = editor.Battle.SimulationTick; + editor.StepBattle(); + Assert.That(editor.Battle.IsModalPresentation, Is.True); + Assert.That(editor.Battle.SimulationTick, Is.EqualTo(simulationTick)); + Assert.That(editor.Battle.HitFlashes.Single().Frame, Is.EqualTo(flash.Frame)); + HideOrdinaryMeshes(editor.Preview); + Texture2D during = Read(editor.Preview.View.Render(256, 256)); + try + { + Assert.That(during.GetPixels().Any(pixel => pixel.r > .1f || pixel.g > .1f || pixel.b > .1f), Is.False, + "The black modal movie must cover the frozen world's post-composite hit flash."); + } + finally + { + Object.DestroyImmediate(during); + } + movies.Advance(2); + editor.SyncBattle(); + Assert.That(editor.Battle.IsModalPresentation, Is.False); + Assert.That(editor.Battle.HitFlashes.Single().Frame, Is.EqualTo(flash.Frame)); + HideOrdinaryMeshes(editor.Preview); + Texture2D resumed = Read(editor.Preview.View.Render(256, 256)); + try + { + Assert.That(resumed.GetPixels().Any(pixel => pixel.r > .35f && pixel.g > .35f), Is.True, + "Modal drawing must not consume or permanently discard the frozen hit flash."); + } + finally + { + Object.DestroyImmediate(resumed); + } + } + finally + { + (movie as IDisposable)?.Dispose(); + Directory.Delete(directory, true); + } + } + + [TestCase(false)] + [TestCase(true)] + public void RealEnemyBlockDrawsItsOriginalAtlasOnTheFlatNativeQuadAndExpires(bool trail) + { + using BattleEditorSession editor = Editor(); + BattleActorSnapshot enemy = editor.Battle.Actors.Single(actor => actor.Side == BattleSide.Enemy); + Block(editor.Battle, enemy.Id); + editor.StepBattle(); + BattleHitFlashSnapshot flash = editor.Battle.HitFlashes.Single(); + Assert.That(flash.Position.X, Is.EqualTo(enemy.Position.X)); + Assert.That(flash.Position.Y, Is.EqualTo(20)); + Assert.That(flash.Position.Z, Is.EqualTo(enemy.Position.Z)); + Assert.That(flash.Frame, Is.EqualTo(1)); + Vector3 center = BattleAnimationCatalog.UnityPosition(flash.Position); + editor.Preview.View.SetCamera(center + Vector3.up * 20, center, 35); + editor.Preview.Trail.Enabled = trail; + HideOrdinaryMeshes(editor.Preview); + Texture2D image = Read(editor.Preview.View.Render(256, 256)); + try + { + MeshFilter mesh = editor.Preview.View.Root.GetComponentsInChildren().Single(filter => filter.name == "Original monster hit flashes"); + Assert.That(mesh.sharedMesh.vertexCount, Is.EqualTo(4)); + Assert.That(mesh.sharedMesh.vertices.All(point => Math.Abs(point.y - 1) < .00001), Is.True, "Native Simple is an XZ plane, not a camera billboard."); + Assert.That(mesh.sharedMesh.bounds.size.x, Is.EqualTo(10).Within(.00001)); + Assert.That(mesh.sharedMesh.bounds.size.z, Is.EqualTo(10).Within(.00001)); + Assert.That(mesh.sharedMesh.uv, Is.EqualTo(new[] + { + new Vector2(.25f, 0), new Vector2(.5f, 0), new Vector2(.5f, .25f), new Vector2(.25f, .25f) + }), "Native frame 1 uses Set256UV's first raw row and preserves vec0(-X,+Z) through vec3(-X,-Z)."); + Assert.That(image.GetPixels().Any(pixel => pixel.r > .35f && pixel.g > .35f), Is.True, "The real atlas must reach the rendered image."); + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (!string.IsNullOrEmpty(output)) + File.WriteAllBytes(Path.Combine(output, BattleData.Variant + "-hit-flash-trail-" + trail + ".png"), image.EncodeToPNG()); + } + finally + { + Object.DestroyImmediate(image); + } + for (int index = 0; index < 15; index++) + editor.StepBattle(); + Assert.That(editor.Battle.HitFlashes, Is.Empty); + HideOrdinaryMeshes(editor.Preview); + Texture2D expired = Read(editor.Preview.View.Render(256, 256)); + try + { + Assert.That(expired.GetPixels().Any(pixel => pixel.r > .35f && pixel.g > .35f), Is.False, + "The post-trail flash must leave no stale atlas cell in scene history."); + } + finally + { + Object.DestroyImmediate(expired); + } + Assert.That(editor.Preview.View.Root.GetComponentsInChildren().Single(renderer => renderer.name == "Original monster hit flashes").enabled, Is.False); + } + + [Test] + public void PartyAndDodgeBlocksDoNotProduceTheEnemySimpleEffect() + { + using BattleEditorSession editor = Editor(); + Block(editor.Battle, editor.Battle.Actors.Single(actor => actor.Side == BattleSide.Ally).Id); + editor.StepBattle(); + Assert.That(editor.Battle.HitFlashes, Is.Empty); + Block(editor.Battle, editor.Battle.Actors.Single(actor => actor.Side == BattleSide.Enemy).Id, true); + editor.StepBattle(); + Assert.That(editor.Battle.HitFlashes, Is.Empty); + } + + [Test] + public void AllSixteenSimpleCellsAndTheirAsymmetricCornersReachTheGpuWithoutRowOrZFlips() + { + using BattleEditorSession editor = Editor(); + BattleActorSnapshot enemy = editor.Battle.Actors.Single(actor => actor.Side == BattleSide.Enemy); + Block(editor.Battle, enemy.Id); + editor.StepBattle(); + BattleMovementPoint origin = editor.Battle.HitFlashes.Single().Position; + Vector3 center = BattleAnimationCatalog.UnityPosition(origin); + editor.Preview.View.SetCamera(center + Vector3.up * 20, center, 35); + editor.Preview.Trail.Enabled = false; + HideOrdinaryMeshes(editor.Preview); + editor.Preview.View.Render(256, 256); + const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; + FieldInfo frames = typeof(BattlePreview).GetField("_hitFeedbackFrames", flags); + var material = (Material)typeof(BattlePreview).GetField("_hitFlashMaterial", flags).GetValue(editor.Preview); + Texture original = material.mainTexture; + var atlas = new Texture2D(32, 32, TextureFormat.RGBA32, false, true) { filterMode = FilterMode.Point }; + Color Ink(int frame, int corner) => new((frame + 1) / 20f, (corner + 1) / 10f, .05f, 1); + for (int frame = 0; frame < 16; frame++) + for (int y = 0; y < 8; y++) + for (int x = 0; x < 8; x++) + atlas.SetPixel(frame % 4 * 8 + x, frame / 4 * 8 + y, Ink(frame, (x >= 4 ? 1 : 0) + (y >= 4 ? 2 : 0))); + atlas.Apply(); + material.mainTexture = atlas; + try + { + frames.SetValue(editor.Preview, Array.Empty()); + Texture2D background = Read(editor.Preview.View.Render(256, 256)); + try + { + ConstructorInfo constructor = typeof(BattleHitFlashSnapshot).GetConstructors(flags).Single(); + for (int frame = 0; frame < 16; frame++) + { + var snapshot = (BattleHitFlashSnapshot)constructor.Invoke(new object[] { 1L, enemy.Id, origin, frame }); + frames.SetValue(editor.Preview, new[] { snapshot }); + Texture2D actual = Read(editor.Preview.View.Render(256, 256)); + try + { + for (int corner = 0; corner < 4; corner++) + { + var point = new BattleMovementPoint(origin.X + (corner % 2 == 0 ? -50 : 50), origin.Y, + origin.Z + (corner < 2 ? 50 : -50)); + Assert.That(editor.Preview.View.Project(BattleAnimationCatalog.UnityPosition(point), new Rect(0, 0, 256, 256), out Vector2 screen), Is.True); + int x = Mathf.Clamp((int)screen.x, 0, 255), y = Mathf.Clamp(255 - (int)screen.y, 0, 255); + Color clear = background.GetPixel(x, y); + Color expected = QualitySettings.activeColorSpace == ColorSpace.Linear ? (clear.linear + Ink(frame, corner)).gamma : clear + Ink(frame, corner); + Color found = actual.GetPixel(x, y); + Assert.That(found.r, Is.EqualTo(Mathf.Clamp01(expected.r)).Within(.035f), $"cell {frame}, native XZ corner {corner}, R"); + Assert.That(found.g, Is.EqualTo(Mathf.Clamp01(expected.g)).Within(.035f), $"cell {frame}, native XZ corner {corner}, G"); + Assert.That(found.b, Is.EqualTo(Mathf.Clamp01(expected.b)).Within(.035f), $"cell {frame}, native XZ corner {corner}, B"); + } + } + finally + { + Object.DestroyImmediate(actual); + } + } + } + finally + { + Object.DestroyImmediate(background); + } + } + finally + { + material.mainTexture = original; + Object.DestroyImmediate(atlas); + } + } + +#if PAL3 + [Test] + public void RenderWeaponSparksAfterAnEnemyJoinsAnEmptySlot() + { + using BattleEditorSession editor = Editor(); + int monster = editor.Battle.Actors.Single(actor => actor.Side == BattleSide.Enemy).ActorId; + typeof(BattleSession).GetMethod("CreateOriginalMonster", BindingFlags.Instance | BindingFlags.NonPublic) + .Invoke(editor.Battle, new object[] { 6, monster, 0L }); + editor.SyncBattle(); + Assert.That(editor.Battle.Actors.Count(actor => actor.Side == BattleSide.Enemy), Is.EqualTo(2)); + editor.Preview.View.LimitToDisplayRefreshRate = false; + Assert.That(editor.Preview.View.Render(256, 256), Is.Not.Null); + } + + [Test] + public void ZiXuanNativeWeaponEmitsRedSparksOncePerDisplayedFrameAndRepeatedRepaintIsStable() + { + using BattleEditorSession editor = Editor(true); + var random = (BattleRandom)typeof(BattleSession).GetField("_random", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(editor.Battle); + uint randomState = random.State; + for (int frame = 0; frame < 8; frame++) + { + editor.StepBattle(); + editor.Preview.View.Render(256, 256); + } + Assert.That(editor.Preview.WeaponSparkCount, Is.GreaterThan(0)); + int count = editor.Preview.WeaponSparkCount; + var sparkMesh = editor.Preview.View.Root.GetComponentsInChildren().Single(filter => filter.name == "Original weapon red sparks"); + Vector3[] vertices = sparkMesh.sharedMesh.vertices; + editor.Preview.View.Render(256, 256); + Assert.That(editor.Preview.WeaponSparkCount, Is.EqualTo(count)); + Assert.That(sparkMesh.sharedMesh.vertices, Is.EqualTo(vertices)); + Assert.That(random.State, Is.EqualTo(randomState), "The visual stream must not consume combat CUtil RNG."); + } +#endif + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleHitFeedbackTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleHitFeedbackTests.cs.meta new file mode 100644 index 00000000..6d7f0c60 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleHitFeedbackTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 94ed9edeace24974b5ad5f3d34f96a0f diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleHudAudioTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleHudAudioTests.cs new file mode 100644 index 00000000..544c46a1 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleHudAudioTests.cs @@ -0,0 +1,261 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Battle; + using Battle.Presentation; + using NUnit.Framework; + using UnityEngine; + + // Exercises production HUD dispatch and its real AudioSource sink without + // opening an EditorWindow. Cached digital silence keeps device QA unobtrusive. + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleHudAudioTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.NonPublic; + private BattleEditorSession _session; + private BattleHudView _hud; + private readonly List _sounds = new(); + + private void Bind(string field, object value) => typeof(BattleHudView).GetField(field, Members).SetValue(_hud, value); + + [SetUp] + public void SetUp() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + Assert.That(root, Is.Not.Null, "The offscreen audio route requires the selected game's local data."); + _session = new BattleEditorSession(); + _session.Load(root, 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = _session.Data.Scenes.First(), + DataFingerprint = _session.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush, + Music = "NONE" + }; + scenario.Participants.Add(_session.Data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = _session.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(_session.Data, id)); + scenario.Participants.Add(_session.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + _session.StartBattle(scenario); + BattleAudioPreview audio = _session.Preview.Audio; + audio.Stop(); + var clips = (IDictionary)typeof(BattleAudioPreview).GetField("_clips", Members).GetValue(audio); + foreach (string cue in new[] { "wa001", "wa002", "wa003", "wa004" }) + clips.Add(cue + ".wav", AudioClip.Create("silent HUD route: " + cue, 48000, 1, 48000, false)); + audio.PlaybackEnabled = true; + audio.Muted = false; + _sounds.Clear(); + audio.SoundPlayed += _sounds.Add; + _hud = new BattleHudView(); + Bind("_battle", _session.Battle); + Bind("_data", _session.Data); + Bind("_preview", _session.Preview); + Bind("_inputEnabled", true); + typeof(BattleHudView).GetMethod("Synchronize", Members).Invoke(_hud, new object[] { _session.Battle }); + Assert.That(_sounds, Is.EqualTo(new[] { "wa003.wav" }), "The first ready command panel must open audibly exactly once."); + typeof(BattleHudView).GetMethod("Synchronize", Members).Invoke(_hud, new object[] { _session.Battle }); + Assert.That(_sounds.Count, Is.EqualTo(1), "Repaint synchronization must not repeat the panel sound."); + _sounds.Clear(); + } + + [TearDown] + public void TearDown() + { + _hud?.Release(); + _session?.Dispose(); + } + + private void Confirm(string control) => Assert.That(_hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Confirm, control)), Is.True); + + private void Check(params string[] sounds) + { + Assert.That(_sounds, Is.EqualTo(sounds.Select(sound => sound + ".wav"))); + Assert.That(_session.Preview.Audio.Diagnostics, Is.Empty); + var root = (GameObject)typeof(BattleAudioPreview).GetField("_root", Members).GetValue(_session.Preview.Audio); + Assert.That(root.GetComponentsInChildren().All(source => source.isPlaying), Is.True, + "Menu requests must reach running owned AudioSources, not only a presenter notification."); + _sounds.Clear(); + } + + [TestCase("start")] + [TestCase("restart")] + [TestCase("replay")] + public void ReplacementBindsAudioAndCommandSynchronizationBeforeAnyGuiPass(string replacement) + { + _hud.Release(); // The window's PreviewReleased subscription does this during replacement. + if (replacement == "start") + _session.StartBattle(_session.CapturedScenario); + else if (replacement == "restart") + _session.Restart(); + else + _session.ReplayBattle(); + PrepareReplacementAudio(); + _session.IsPlaying = true; + int synchronized = 0; + void Changed() + { + synchronized++; + _session.SyncBattle(); + } + _hud.BindBattle(_session.Battle, _session.Data, _session.Preview, Changed, null); + _hud.TakeGamepadInput(_session.Battle); + Assert.That(_sounds, Is.EqualTo(new[] { "wa003.wav" })); + _hud.BindBattle(_session.Battle, _session.Data, _session.Preview, Changed, null); + Assert.That(_sounds.Count, Is.EqualTo(1), "The subsequent GUI bind must not repeat the ready cue."); + _session.IsPlaying = false; + _sounds.Clear(); + int before = _session.Battle.RecordedInputCount; + Assert.That(_hud.Presenter.SetFocus("defend"), Is.True); + Assert.That(_hud.SendGamepadIntent(new BattleEditorGamepadIntent(BattleEditorGamepadIntentKind.Confirm)), Is.True); + Assert.That(_session.Battle.RecordedInputCount, Is.GreaterThan(before)); + Assert.That(synchronized, Is.EqualTo(1), "Paused commands must update the preview immediately without waiting for a GUI pass or simulation tick."); + Assert.That(_sounds, Is.Empty); + } + + private void PrepareReplacementAudio() + { + BattleAudioPreview audio = _session.Preview.Audio; + audio.Stop(); + var clips = (IDictionary)typeof(BattleAudioPreview).GetField("_clips", Members).GetValue(audio); + foreach (string cue in new[] { "wa001", "wa002", "wa003", "wa004" }) + clips.Add(cue + ".wav", AudioClip.Create("silent replacement route: " + cue, 48000, 1, 48000, false)); + _sounds.Clear(); + audio.SoundPlayed += _sounds.Add; + } + + [TestCase(false, true)] + [TestCase(true, false)] + public void ReplacementBindingStaysSilentWhilePausedOrUnfocused(bool playing, bool focused) + { + _hud.Release(); + _session.Restart(); + PrepareReplacementAudio(); + _session.IsPlaying = playing; + _hud.SetInputFocus(focused); + _hud.BindBattle(_session.Battle, _session.Data, _session.Preview, _session.SyncBattle, null); + Assert.That(_sounds, Is.Empty); + _hud.SetInputFocus(true); + _session.IsPlaying = true; + _hud.BindBattle(_session.Battle, _session.Data, _session.Preview, _session.SyncBattle, null); + Assert.That(_sounds, Is.Empty, "A suppressed ready cue must not be queued for focus or playback resume."); + } + + [TestCase(false, 1f, false)] + [TestCase(true, 1f, true)] + [TestCase(true, 2f, false)] + public void SilentMenuNavigationDoesNotQueueSoundsForResume(bool playing, float speed, bool muted) + { + BattleAudioPreview audio = _session.Preview.Audio; + audio.Stop(); + _session.Speed = speed; + _session.IsPlaying = playing; + audio.Muted = muted; + + Confirm("skills"); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Back)); + var root = (GameObject)typeof(BattleAudioPreview).GetField("_root", Members).GetValue(audio); + Assert.That(root.GetComponentsInChildren(), Is.Empty); + Assert.That(_sounds, Is.Empty); + + audio.Muted = false; + _session.Speed = 1; + _session.IsPlaying = true; + Assert.That(root.GetComponentsInChildren(), Is.Empty); + Confirm("skills"); + Check("wa001", "wa003"); + } + + [Test] + public void MenusAndCategoriesSoundOnActivationWithoutHoverOrRepaintNoise() + { + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerMove, "magic", 4)); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Up)); + Check(); + Confirm("skills"); + Check("wa001", "wa003"); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Back)); + Check("wa003"); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerDown, "items", 4)); + Check(); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerUp, "items", 4)); + Check("wa001", "wa003"); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Navigate, direction: BattleHudDirection.Right)); + Check("wa001"); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.CycleNext)); + Check("wa001"); + } + + [Test] + public void RepeatingTheSameDeniedActivationSoundsEveryTimeWithoutSoundingOnStrayReleases() + { + Confirm("ai"); + Check("wa001", "wa003"); + // AI starts disabled. Each deliberate activation gets the native + // error cue even when the description has not changed. + for (int attempt = 0; attempt < 3; attempt++) + { + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Confirm, "flag:1")); + Check("wa004"); + } + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerUp, "flag:1", 8)); + Check(); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerDown, "flag:1", 8)); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerUp, "flag:1", 8)); + Check("wa004"); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerDown, "flag:1", 8)); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerCancel, pointerId: 8)); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerUp, "flag:1", 8)); + Check(); + if ((_hud.Presenter.AiFlags(_hud.Presenter.Controller) & 1) != 0) + { + Confirm("flag:0"); + Check("wa001"); + } + for (int attempt = 0; attempt < 2; attempt++) + { + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Confirm, "flag:0")); + Check("wa004"); + } + string enemy = _session.Battle.Actors.First(actor => actor.Side == BattleSide.Enemy).Id; + Confirm("ai-actor:" + enemy); + Check("wa001"); + Assert.That(_hud.Presenter.Message, Is.Null, "A successful new activation must clear stale failure feedback."); + Confirm("end"); + Check("wa001", "wa003"); + } + + [Test] + public void AbilityConfirmationSoundsOnceAndCancelledOrStrayReleasesAreSilent() + { + Confirm("skills"); + Check("wa001", "wa003"); + int skill = _hud.Presenter.Abilities().First(ability => ability.Denied == null && + ability.Definition.Range == BattleTargetRange.OpponentSingle).Definition.Id; + string control = "ability:" + skill; + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerUp, control, 8)); + Check(); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerDown, control, 8)); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerCancel, pointerId: 8)); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerUp, control, 8)); + Check(); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerDown, control, 8)); + Check(); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.PointerUp, control, 8)); + Check("wa002"); + Assert.That(_hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + _hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Back)); + Check("wa003"); + Confirm(control); + Check("wa002"); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleHudAudioTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleHudAudioTests.cs.meta new file mode 100644 index 00000000..309927e1 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleHudAudioTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 43f493ab655643b2b10b3c4c48da2f9d diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleIntegrationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleIntegrationTests.cs new file mode 100644 index 00000000..2f6ec57a --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleIntegrationTests.cs @@ -0,0 +1,285 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Core.Contract.Constants; + using NUnit.Framework; + using UnityEditor.SceneManagement; + using UnityEngine; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + public sealed class BattleIntegrationTests + { + private BattleEditorSession _session; + + [SetUp] + public void Load() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT") ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root)) + Assert.Ignore("Local original data unavailable."); + _session = new BattleEditorSession(); + _session.Load(root, 936); + } + + [TearDown] + public void Dispose() => _session?.Dispose(); + + [TestCase(0, new[] { 0, 1, 3, 2, 4 })] + [TestCase(1, new[] { 0, 1, 3, 2, 4 })] + [TestCase(2, new[] { 4, 0, 2, 1, 3 })] + [TestCase(3, new[] { 2, 3, 0, 4, 1 })] + [TestCase(4, new[] { 3, 4, 1, 0, 2 })] + [TestCase(5, new[] { 1, 2, 4, 3, 0 })] + public void FormationHomesUseTheNativeRoleCoordinates(int sceneElement, int[] nativeOrder) + { + BattleScenario scenario = Create(false); + scenario.SceneElement = sceneElement; + BattleParticipant ally = scenario.Participants[0], enemy = scenario.Participants[1]; + ally.Slot = BattleSlot.Wind; + enemy.Slot = BattleSlot.Center; + var catalog = new BattleAnimationCatalog(_session.Data, new BattleSetup(scenario)); + var positions = _session.Data.Layout.ActorGameBoxPositions; + BattleMovementPoint Point(int index) => new(positions[index].X, positions[index].Y, positions[index].Z); + for (int slot = 0; slot < nativeOrder.Length; slot++) + { + BattleMovementPoint expected = Point(nativeOrder[slot]); + BattleMovementPoint actual = catalog.FormationHome(ally.InstanceId, (BattleSlot)slot); + Assert.That(actual.X, Is.EqualTo(expected.X).Within(.001f)); + Assert.That(actual.Y, Is.EqualTo(expected.Y).Within(.001f)); + Assert.That(actual.Z, Is.EqualTo(expected.Z).Within(.001f)); + } + Assert.That(catalog.InitialHome(ally.InstanceId), Is.EqualTo(catalog.FormationHome(ally.InstanceId, ally.Slot))); + Assert.That(catalog.CoAttackHome(ally.InstanceId, BattleSlot.Wind).Z, Is.EqualTo(positions[3].Z).Within(.001f)); + Assert.That(catalog.InitialHome(enemy.InstanceId).Z, Is.EqualTo(151.262329f).Within(.001f)); + } + + private BattleScenario Create(bool multiple) + { + BattleData data = _session.Data; + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = data.Scenes.First(), DataFingerprint = data.Fingerprint, Encounter = BattleEncounter.AllyAmbush }; + scenario.Participants.Add(data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = data.Database.CombatActorInfos.Keys.OrderBy(id => id).First(id => BattleAnimationCatalog.IsBasicEnemy(data, id) && + data.Resources.Find(FileConstants.GetActorFolderVirtualPath(data.Database.CombatActorInfos[id].ModelId) + data.Database.CombatActorInfos[id].ModelId + ".ini") != null); + scenario.Participants.Add(data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + if (multiple) + { + scenario.Participants.Add(data.CreateParticipant(104, BattleSide.Ally, BattleSlot.Fire)); + scenario.Participants.Add(data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Fire)); + } + foreach (BattleParticipant actor in scenario.Participants) + { + actor.Attributes = new[] { 80, 50, 30, actor.Side == BattleSide.Ally ? 70 : 25, 10, 3, 0, 0, 0, 0, 0, 0 }; + actor.Vitals = new[] { 80, 0, 30 }; + actor.Skills.Clear(); +#if PAL3 + if (actor.ActorId == 101) + actor.Equipment[0] = 6601; // Ordinary sword; magic-sword cultivation is a separate scenario. +#endif + } + return scenario; + } + + [Test] + public void QueuedReplayKeepsTheOriginalUntilCompletionAndCanBeCanceled() + { + _session.StartBattle(Create(false)); + BattleSession original = _session.Battle; + for (int tick = 0; tick < 200; tick++) + original.Step(); + _session.SyncBattle(); + + void Call(string name) => + typeof(BattleEditorSession).GetMethod(name, BindingFlags.Instance | BindingFlags.NonPublic).Invoke(_session, null); + + Call("BeginReplay"); + Assert.That(_session.Battle, Is.SameAs(original)); + Call("CancelReplay"); + Call("TickReplay"); + Assert.That(_session.Battle, Is.SameAs(original)); + + Call("BeginReplay"); + for (int slice = 0; slice < 200 && _session.Battle == original; slice++) + Call("TickReplay"); + Assert.That(_session.Battle, Is.Not.SameAs(original)); + Assert.That(_session.Battle.Tick, Is.EqualTo(200)); + Assert.That(_session.Battle.Status, Is.EqualTo(BattleSessionStatus.Running)); + } + + [TestCase(false, false)] + [TestCase(true, false)] + [TestCase(false, true)] + [TestCase(true, true)] + public void RealResourcesReachNaturalResultAndReplayWithoutMutatingDraft(bool multiple, bool toon) + { + BattleScenario scenario = Create(multiple); + scenario.ToonRendering = toon; + string original = JsonUtility.ToJson(scenario); + int sceneCount = EditorSceneManager.previewSceneCount; + _session.StartBattle(scenario, true, true); + BattleSession combat = _session.Battle; + int firstHit = 0; + for (int i = 0; i < 15000 && combat.Status == BattleSessionStatus.Running; i++) + { + combat.Step(); + if (firstHit == 0 && combat.Events.Any(entry => entry.Kind == BattleEventKind.Hit)) + { + firstHit = i + 1; + _session.SyncBattle(); + Capture(multiple, toon); + } + } + _session.SyncBattle(); + Assert.That(firstHit, Is.GreaterThan(0)); + Assert.That(combat.Status, Is.EqualTo(BattleSessionStatus.Completed), string.Join("\n", combat.Events)); + Assert.That(combat.Result.Winner, Is.EqualTo(BattleSide.Ally)); + string events = Newtonsoft.Json.JsonConvert.SerializeObject(combat.Events); + _session.ReplayBattle(); + Assert.That(Newtonsoft.Json.JsonConvert.SerializeObject(_session.Battle.Events), Is.EqualTo(events)); + Assert.That(JsonUtility.ToJson(scenario), Is.EqualTo(original)); + Assert.That(_session.Preview.Diagnostics, Is.Empty); + for (int i = 0; i < 5; i++) + { + _session.Restart(); + Assert.That(_session.Battle.Status, Is.EqualTo(BattleSessionStatus.Running)); + _session.StepBattle(); + Assert.That(EditorSceneManager.previewSceneCount, Is.EqualTo(sceneCount + 1)); + } + _session.Stop(); + Assert.That(EditorSceneManager.previewSceneCount, Is.EqualTo(sceneCount)); + } + + [Test] + public void FailedCombatStartKeepsExistingBattleAndPresentation() + { + BattleScenario scenario = Create(false); + _session.StartBattle(scenario); + BattleSession previous = _session.Battle; + BattlePreview view = _session.Preview; + scenario.Participants[0].Statuses.Add(new BattleStatus { Id = int.MaxValue }); + Assert.Throws(() => _session.StartBattle(scenario)); + Assert.That(_session.Battle, Is.SameAs(previous)); + Assert.That(_session.Preview, Is.SameAs(view)); + scenario.Participants[0].Statuses.Clear(); + scenario.Participants[0].Model = "missingfixture"; + Assert.Throws(() => _session.StartBattle(scenario)); + Assert.That(_session.Battle, Is.SameAs(previous)); + Assert.That(_session.Preview, Is.SameAs(view)); + } + + [Test] + public void BasicWeaponMetadataUsesTheNativeDivisorAndExactWorkMarkers() + { + BattleScenario scenario = Create(false); + var catalog = new BattleAnimationCatalog(_session.Data, new BattleSetup(scenario)); + BattleParticipant source = scenario.Participants[0], target = scenario.Participants[1]; +#if PAL3A + Assert.That(catalog.DamageDivisor(source.InstanceId), Is.EqualTo(2)); + Assert.That(catalog.Attack(source.InstanceId, target.InstanceId).HitTicks, Is.EqualTo(new[] { 14, 30 })); +#else + Assert.That(catalog.DamageDivisor(source.InstanceId), Is.EqualTo(1)); + Assert.That(catalog.Attack(source.InstanceId, target.InstanceId).HitTicks, Is.EqualTo(new[] { 25 })); +#endif + } + + [Test] + public void NextHitAdvancesRunningActionsWhileAnotherActorWaitsForInput() + { + BattleScenario scenario = Create(true); + _session.StartBattle(scenario); + string attacker = _session.Battle.WaitingActor; + string target = _session.Battle.Actors.First(actor => actor.Side == BattleSide.Enemy).Id; + Assert.That(_session.Battle.Submit(attacker, BattleAction.Attack, target), Is.True); + Assert.That(_session.Battle.WaitingActor, Is.Not.Null); + _session.AdvanceTo(BattleEventKind.Hit); + Assert.That(_session.Battle.Events.Any(entry => entry.Kind == BattleEventKind.Hit), Is.True); + Assert.That(_session.Battle.Tick, Is.GreaterThan(1)); + } + +#if PAL3A + [TestCase(103)] + [TestCase(105)] + public void FluteAndCrossbowUseStationaryTimelines(int actorId) + { + BattleScenario scenario = Create(false); + scenario.Participants[0] = _session.Data.CreateParticipant(actorId, BattleSide.Ally, BattleSlot.Water); + if (actorId == 103) + scenario.Participants[0].Equipment[0] = 82301; + var catalog = new BattleAnimationCatalog(_session.Data, new BattleSetup(scenario)); + BattleParticipant source = scenario.Participants[0], target = scenario.Participants[1]; + Assert.That(catalog.Attack(source.InstanceId, target.InstanceId).TravelTicks, Is.Zero); + Assert.That(catalog.Approach(source.InstanceId, target.InstanceId), Is.EqualTo(_session.Data.Position(source, scenario.SceneElement))); + } + + [Test] + public void AlternateWeaponUsesItsCapturedSecondAttackClip() + { + BattleScenario scenario = Create(false); + scenario.Participants[0] = _session.Data.CreateParticipant(102, BattleSide.Ally, BattleSlot.Water); + scenario.Participants[0].Equipment[0] = 82209; // Type 4 spear uses z02, not z01. + _session.StartBattle(scenario); + string source = scenario.Participants[0].InstanceId; + Assert.That(_session.Battle.WaitingActor, Is.EqualTo(source)); + Assert.That(_session.Battle.Submit(source, BattleAction.Attack, scenario.Participants[1].InstanceId), Is.True); + bool seen = false; + for (int tick = 0; tick < 400 && _session.Battle.Status == BattleSessionStatus.Running; tick++) + { + _session.StepBattle(); + if (_session.Battle.Actors.Single(actor => actor.Id == source).NativeAnimationClip == "z02") + { + seen = true; + break; + } + } + Assert.That(seen, Is.True, "The type 4 spear must bind its actual second attack clip."); + } +#else + [Test] + public void EmptyWeaponUsesThePublishedLongkuiDefaultWithoutGrantingJingtiansSwordAbility() + { + BattleScenario scenario = Create(false); + scenario.Participants[0] = _session.Data.CreateParticipant(106, BattleSide.Ally, BattleSlot.Water); + scenario.Participants[0].Equipment[0] = 0; + _session.StartBattle(scenario); + BattleParticipant captured = _session.CapturedScenario.Participants[0]; + Assert.That(captured.Equipment[0], Is.EqualTo(6603)); + Assert.That(captured.UsesNativeDefaultWeapon, Is.True); + Assert.That(_session.Battle.MagicSwords, Is.Empty); + Assert.That(scenario.Participants[0].Equipment[0], Is.Zero); + } +#endif + + private void Capture(bool multiple, bool toon) + { + RenderTexture target = _session.Preview.View.Render(800, 600); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(800, 600, TextureFormat.RGB24, false); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, 800, 600), 0, 0); + image.Apply(); + Assert.That(image.GetPixels32().Select(pixel => (pixel.r, pixel.g, pixel.b)).Distinct().Take(100).Count(), Is.GreaterThan(20)); + string directory = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (string.IsNullOrEmpty(directory)) + return; + Directory.CreateDirectory(directory); + File.WriteAllBytes(Path.Combine(directory, $"{BattleData.Variant}-{(multiple ? "party" : "duel")}-{(toon ? "toon" : "original")}.png"), image.EncodeToPNG()); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleIntegrationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleIntegrationTests.cs.meta new file mode 100644 index 00000000..d8f7900f --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleIntegrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5cc91e792219423cb3bd667eb8ec9237 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleLineupRenderingTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleLineupRenderingTests.cs new file mode 100644 index 00000000..4b82d00a --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleLineupRenderingTests.cs @@ -0,0 +1,167 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + public sealed class BattleLineupRenderingTests + { + [Test] + public void RealMagicPreparationShowsTheNativeGroundLineupAndRepaintDoesNotAgeIt() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original data is required."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + Assert.That(editor.Data.Layout.AllyFormationConfig.RollRadians, Is.EqualTo(-.500003f)); + Assert.That(editor.Data.Layout.EnemyFormationConfig.RollRadians, Is.EqualTo(.156633f)); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + DataFingerprint = editor.Data.Fingerprint, + Scene = editor.Data.Scenes.First(), + SceneElement = 1, + Encounter = BattleEncounter.AllyAmbush + }; + BattleParticipant ally = editor.Data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water); + int enemyId = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + BattleParticipant enemy = editor.Data.CreateParticipant(enemyId, BattleSide.Enemy, BattleSlot.Water); + foreach (BattleParticipant actor in new[] { ally, enemy }) + { + actor.Attributes = new[] { 5000, 100, 1000, 70, 10, 12, 0, 0, 0, 0, 0, 0 }; + actor.Vitals = new[] { 5000, 100, 1000 }; + scenario.Participants.Add(actor); + } + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + for (int step = 0; step < 2000 && (editor.Battle.SimulationTick <= 210 || !editor.Battle.Actors.Single(actor => actor.Id == ally.InstanceId).Ready); step++) + editor.StepBattle(); + Assert.That(editor.Battle.Submit(new BattleCommand(ally.InstanceId, BattleAction.Skill, enemy.InstanceId, 301)), Is.True); + for (int step = 0; step < 2000 && !editor.Battle.AbilityPresentations.Any(stage => stage.LineupVisible && stage.LineupElapsedSeconds > .5); step++) + editor.StepBattle(); + Assert.That(editor.Battle.AbilityPresentations.Any(stage => stage.LineupVisible), Is.True); + Assert.That(editor.Preview.LineupFrames.Any(frame => frame.Side == BattleSide.Ally && frame.Alpha > 0), Is.True); + GameObject[] quads = editor.Preview.View.Root.GetComponentsInChildren() + .Where(renderer => renderer.name.StartsWith("Original Ally", StringComparison.Ordinal) && renderer.name.Contains("lineup")) + .Select(renderer => renderer.gameObject).ToArray(); + Assert.That(quads.Length, Is.EqualTo(2)); + var center = editor.Data.Layout.AllyFormationConfig.CenterGameBoxPosition; + Vector3 focus = BattleAnimationCatalog.UnityPosition(new BattleMovementPoint(center.X, 0, center.Z)); + editor.Preview.View.SetHorizontalCameraOrientation(focus + Vector3.up * 50, Vector3.down, Vector3.forward, 50); + Texture2D shown = Capture(editor.Preview.View.Render(800, 600)); + Texture2D hidden = null; + try + { + foreach (GameObject quad in quads) + quad.GetComponent().enabled = false; + hidden = Capture(editor.Preview.View.Render(800, 600)); + Color32[] a = shown.GetPixels32(), b = hidden.GetPixels32(); + int changed = a.Zip(b, (x, y) => Math.Abs(x.r - y.r) + Math.Abs(x.g - y.g) + Math.Abs(x.b - y.b)).Count(delta => delta > 6); + Assert.That(changed, Is.GreaterThan(100), "A real spell's lineup must reach actual GPU pixels."); + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (!string.IsNullOrEmpty(output)) + { + File.WriteAllBytes(Path.Combine(output, BattleData.Variant + "-lineup-shown.png"), shown.EncodeToPNG()); + File.WriteAllBytes(Path.Combine(output, BattleData.Variant + "-lineup-hidden.png"), hidden.EncodeToPNG()); + } + } + finally + { + foreach (GameObject quad in quads) + quad.GetComponent().enabled = true; + Object.DestroyImmediate(shown); + if (hidden != null) + Object.DestroyImmediate(hidden); + } + var frames = editor.Preview.LineupFrames.Select(frame => (frame.Side, frame.Alpha)).ToArray(); + editor.Preview.View.Render(800, 600); + Assert.That(editor.Preview.LineupFrames.Select(frame => (frame.Side, frame.Alpha)), Is.EqualTo(frames)); + AssertNativeTextureOrientation(editor, quads.Single(quad => quad.name.Contains("five-spirit"))); + for (int step = 0; step < 150; step++) + editor.StepBattle(); + Assert.That(editor.Preview.LineupFrames, Is.Empty); + Assert.That(quads.All(quad => !quad.GetComponent().enabled), Is.True); + } + + private static void AssertNativeTextureOrientation(BattleEditorSession editor, GameObject ring) + { + // Native RenderGeomQuad maps its (-radius,-radius) corner to (0,0). + // A deliberately asymmetric texture detects a v inversion even + // when both orientations have the same number of bright pixels. + var texture = new Texture2D(4, 4, TextureFormat.RGBA32, false) { filterMode = FilterMode.Point }; + Color[] pattern = Enumerable.Range(0, 16).Select(index => index / 4 < 2 + ? index % 4 < 2 ? Color.red : Color.green + : index % 4 < 2 ? Color.blue : Color.white).ToArray(); + texture.SetPixels(pattern); + texture.Apply(); + Renderer[] renderers = editor.Preview.View.Root.GetComponentsInChildren(); + bool[] enabled = renderers.Select(renderer => renderer.enabled).ToArray(); + var renderer = ring.GetComponent(); + Texture original = renderer.sharedMaterial.mainTexture; + Texture2D shown = null, hidden = null; + try + { + foreach (Renderer other in renderers) + other.enabled = false; + hidden = Capture(editor.Preview.View.Render(800, 600)); + renderer.sharedMaterial.mainTexture = texture; + renderer.enabled = true; + shown = Capture(editor.Preview.View.Render(800, 600)); + var layout = editor.Data.Layout.AllyFormationConfig; + foreach ((float u, float v, Color expected) in new[] { (.25f, .25f, Color.red), (.75f, .25f, Color.green), (.25f, .75f, Color.blue) }) + { + float x = (2 * u - 1) * layout.GameBoxRadius, z = (2 * v - 1) * layout.GameBoxRadius; + double sine = Math.Sin(layout.RollRadians), cosine = Math.Cos(layout.RollRadians); + var native = new BattleMovementPoint((float)(layout.CenterGameBoxPosition.X + x * cosine + z * sine), .5f, + (float)(layout.CenterGameBoxPosition.Z - x * sine + z * cosine)); + Assert.That(editor.Preview.View.Project(BattleAnimationCatalog.UnityPosition(native), new Rect(0, 0, 800, 600), out Vector2 point), Is.True); + int px = Mathf.RoundToInt(point.x), py = 599 - Mathf.RoundToInt(point.y); + Color difference = shown.GetPixel(px, py) - hidden.GetPixel(px, py); + float wanted = expected.r * difference.r + expected.g * difference.g + expected.b * difference.b; + float unwanted = (1 - expected.r) * difference.r + (1 - expected.g) * difference.g + (1 - expected.b) * difference.b; + Assert.That(wanted, Is.GreaterThan(.05f), $"Native UV ({u},{v}) must reach its own asymmetric texel, delta={difference}."); + Assert.That(unwanted, Is.LessThan(.02f), $"Native UV ({u},{v}) sampled another texture row, delta={difference}."); + } + } + finally + { + renderer.sharedMaterial.mainTexture = original; + for (int index = 0; index < renderers.Length; index++) + renderers[index].enabled = enabled[index]; + Object.DestroyImmediate(texture); + if (shown != null) + Object.DestroyImmediate(shown); + if (hidden != null) + Object.DestroyImmediate(hidden); + } + } + + private static Texture2D Capture(RenderTexture target) + { + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(target.width, target.height, TextureFormat.RGBA32, false); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0); + image.Apply(); + return image; + } + finally + { + RenderTexture.active = previous; + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleLineupRenderingTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleLineupRenderingTests.cs.meta new file mode 100644 index 00000000..e6fa4ed7 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleLineupRenderingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6703a5da44304172be14dcc46f75471c diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleMagicSwordResourceTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleMagicSwordResourceTests.cs new file mode 100644 index 00000000..567d0ee4 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleMagicSwordResourceTests.cs @@ -0,0 +1,100 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using NUnit.Framework; + using ResourceBrowser; + using UnityEngine; + + [Category("LocalGameData")] + public sealed class BattleMagicSwordResourceTests + { + private BattleData _data; + + [SetUp] + public void LoadOriginalData() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT") ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root)) + Assert.Ignore("Local original-game data is not available."); + _data = new BattleData(root, 936); + } + + [TearDown] + public void Dispose() => _data?.Dispose(); + + private BattleScenario Scenario() + { + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = _data.Scenes.First(), DataFingerprint = _data.Fingerprint }; + scenario.Participants.Add(_data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = _data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(_data, id)); + scenario.Participants.Add(_data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + return scenario; + } + + [Test] + public void AllOriginalDualElementSpellsAreCapturedAsSupportedOrdinaryMagic() + { + BattleScenario scenario = Scenario(); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, new BattleSetup(scenario)); + int[] ids = Enumerable.Range(326, 8).Concat(BattleData.Variant == "PAL3" ? Enumerable.Range(241, 7) : Array.Empty()).ToArray(); + foreach (int id in ids) + { + BattleAbilityDefinition skill = definitions.Skills[id]; + Assert.That(skill.Supported, Is.True, id + ": " + skill.UnsupportedReason); + Assert.That(skill.IsMagic, Is.True, id.ToString()); + Assert.That(skill.SkillTypeId, Is.InRange(1, 3)); + Assert.That(skill.Handler, Is.EqualTo(BattleSpecialHandler.None)); + Assert.That((skill.ElementMask & (skill.ElementMask - 1)) != 0, Is.True, id.ToString()); + } + } + +#if PAL3 + [Test] + public void AllTwentyFourWeaponSkillsUseTheirActualLinkersAndWeaponAnimation() + { + BattleScenario scenario = Scenario(); + BattleParticipant source = scenario.Participants[0]; + source.Equipment[0] = BattleMagicSwordRules.WeaponId; + source.MagicSword = new BattleMagicSword { Energy = 200 }; + foreach (int id in Enumerable.Range(2201, 24)) + { + source.MagicSword.SkillId = id; + var setup = new BattleSetup(scenario); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, setup); + var catalog = new BattleAnimationCatalog(_data, setup, definitions); + BattleAbilityDefinition skill = definitions.Skills[id]; + Assert.That(skill.Supported, Is.True, id + ": " + skill.UnsupportedReason); + BattleMagicSwordStageProfile profile = catalog.MagicSword(source.InstanceId, skill); + Assert.That((profile.FirstGroupId, profile.SecondGroupId, profile.FirstWaitSeconds, profile.SecondWaitSeconds), + Is.EqualTo((415 + id - 2201, id == 2215 ? 7 : -1, 0f, 0f)), id.ToString()); + Assert.That(catalog.Ability(source.InstanceId, skill).NativeWorkTimeSeconds, Is.Null); + Assert.That(profile.BodyAnimationTicks, Is.GreaterThan(0)); + } + } + + [Test] + public void ActualWeaponGroupsAndTheirCallbacksFinishWithoutRenderingOrCombatTime() + { + using var preview = new ResourceModelPreview(_data.Resources, false); + using var director = new BattleEffectDirector(_data, preview); + long frame = 0; + foreach (int group in Enumerable.Range(415, 24).Append(7)) + { + long handle = director.Start(new BattleEffectRequest(group, "A", new[] { "E" }, default, 1, absoluteTime: true)); + int steps = 0; + while (director.IsRunning(handle) && steps++ < 3000) + director.Advance(++frame, 0, (float)BattleSession.StepSeconds); + Assert.That(director.IsRunning(handle), Is.False, "Native effect group " + group + " did not finish on the absolute clock."); + } + } +#endif + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleMagicSwordResourceTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleMagicSwordResourceTests.cs.meta new file mode 100644 index 00000000..def16c18 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleMagicSwordResourceTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 7e58cb258d5d4039bedda73d7e670853 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleMovieAudioTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleMovieAudioTests.cs new file mode 100644 index 00000000..10886b4d --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleMovieAudioTests.cs @@ -0,0 +1,810 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Threading; + using System.Threading.Tasks; + using Battle; + using Battle.Presentation; + using Game.Rendering.Native; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using ResourceBrowser; + using UnityEditor; + using UnityEngine; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + public sealed class BattleMovieAudioTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private const BindingFlags Static = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + private BattleData _data; + private ResourceModelPreview _preview; + private BattleMoviePlayer _movies; + private object _movie; + private string _directory; + + private static Type Device => typeof(BattleAudioPreview).Assembly.GetType("Pal3.BattleEditor.BattleAudioPreviewDevice", true); + + private static object Call(string name, params object[] arguments) => Device.GetMethod(name, Static).Invoke(null, arguments); + + [SetUp] + public void SetUp() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (root == null) + Assert.Ignore("The editor transport tests require local game resources."); + _data = new BattleData(root, 936); + _preview = new ResourceModelPreview(_data.Resources, false); + _movies = new BattleMoviePlayer(_data, _preview) { AudioPlaybackEnabled = false }; + // A named, silent transport fixture exercises the actual editor + // audio device in both variants without substituting absent A media. + _directory = Path.Combine(Environment.GetEnvironmentVariable("PAL3_BATTLE_REPORT_DIR") ?? Application.temporaryCachePath, "AudioTransport-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_directory); + var frames = new byte[4 * 3 * 4 * 300]; + for (int pixel = 0; pixel < 4 * 3; pixel++) + { + frames[pixel * 4] = 255; + frames[pixel * 4 + 3] = 255; + } + File.WriteAllBytes(Path.Combine(_directory, "video.rgba"), frames); + using (var writer = new BinaryWriter(File.Create(Path.Combine(_directory, "audio.wav")))) + { + writer.Write(System.Text.Encoding.ASCII.GetBytes("RIFF")); + writer.Write(36 + 48000 * 10 * 2); + writer.Write(System.Text.Encoding.ASCII.GetBytes("WAVEfmt ")); + writer.Write(16); + writer.Write((ushort)1); + writer.Write((ushort)1); + writer.Write(48000); + writer.Write(96000); + writer.Write((ushort)2); + writer.Write((ushort)16); + writer.Write(System.Text.Encoding.ASCII.GetBytes("data")); + writer.Write(48000 * 10 * 2); + writer.Write(new byte[48000 * 10 * 2]); + } + _movie = AddMovie(_movies); + } + + private object AddMovie(BattleMoviePlayer player) + { + Type decodedType = typeof(BattleMoviePlayer).GetNestedType("DecodedMovie", BindingFlags.NonPublic); + object decoded = Activator.CreateInstance(decodedType, true); + foreach (var pair in new[] { ("Width", 4), ("Height", 3), ("Frames", 300) }) + decodedType.GetField(pair.Item1, Members).SetValue(decoded, pair.Item2); + decodedType.GetField("Directory", Members).SetValue(decoded, _directory); + decodedType.GetField("Name", Members).SetValue(decoded, "fixture.bik"); + decodedType.GetField("Rate", Members).SetValue(decoded, 30u); + decodedType.GetField("Divisor", Members).SetValue(decoded, 1u); + decodedType.GetField("HasAudio", Members).SetValue(decoded, true); + object movie = Activator.CreateInstance(typeof(BattleMoviePlayer).GetNestedType("Movie", BindingFlags.NonPublic), Members, null, + new[] { (object)player, decoded }, null); + ((IList)typeof(BattleMoviePlayer).GetField("_movies", Members).GetValue(player)).Add(movie); + return movie; + } + + [TearDown] + public void TearDown() + { + _movies?.Dispose(); + _preview?.Dispose(); + _data?.Dispose(); + if (_directory != null) + Directory.Delete(_directory, true); + } + + [Test] + public void ModalMovieCoversSortedBattleGeometryUntilSkipped() + { + _preview.SetCamera(new Vector3(0, 0, -5), Vector3.zero, 40); + var geometry = _preview.CreateObject("Battle geometry behind modal video"); + var quad = new Mesh + { + vertices = new[] { new Vector3(-2, -2, 0), new Vector3(2, -2, 0), new Vector3(2, 2, 0), new Vector3(-2, 2, 0) }, + uv = new[] { Vector2.zero, Vector2.right, Vector2.one, Vector2.up }, + colors = new[] { Color.green, Color.green, Color.green, Color.green }, + triangles = new[] { 0, 1, 2, 0, 2, 3 } + }; + var material = new Material(Shader.Find("Pal3/Effect")) { renderQueue = 3003 }; + material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); + geometry.AddComponent().sharedMesh = quad; + var renderer = geometry.AddComponent(); + renderer.sharedMaterial = material; + renderer.sortingOrder = GameBoxBattleRenderOrder.DirectEffects; + _preview.Rendering += camera => geometry.transform.SetPositionAndRotation( + camera.transform.position + camera.transform.forward, camera.transform.rotation); + + var image = new Texture2D(420, 180); + RenderTexture previous = RenderTexture.active; + try + { + void ReadFrame() + { + RenderTexture.active = _preview.Render(420, 180); + image.ReadPixels(new Rect(0, 0, 420, 180), 0, 0); + image.Apply(); + } + + ReadFrame(); + Assert.That(image.GetPixel(20, 90).g, Is.EqualTo(1f).Within(.03), "The geometry fills the bar area."); + _preview.Rendering += _movies.Render; + ReadFrame(); + Color bar = image.GetPixel(20, 90), video = image.GetPixel(210, 90); + Assert.That(bar.g, Is.Zero.Within(.03), $"Black bar at 20,90: {bar}"); + Assert.That(video.r, Is.EqualTo(1f).Within(.03), $"Red frame at 210,90: {video}"); + Assert.That(video.g, Is.Zero.Within(.03), $"Red frame at 210,90: {video}"); + + Assert.That(_movies.Skip(), Is.True); + ReadFrame(); + Assert.That(image.GetPixel(20, 90).g, Is.EqualTo(1f).Within(.03), "The stage returns after skipping."); + Assert.That(image.GetPixel(210, 90).g, Is.EqualTo(1f).Within(.03)); + _preview.Frame(); + _preview.GetCamera(out _, out Vector3 target, out _); + Assert.That(Vector3.Distance(target, renderer.bounds.center), Is.LessThan(.001f), + "The movie overlay must stay outside the stage's framing bounds."); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + Object.DestroyImmediate(geometry); + Object.DestroyImmediate(quad); + Object.DestroyImmediate(material); + } + } + + [TestCase(320, 240)] + [TestCase(420, 180)] + [TestCase(300, 150)] + [TestCase(240, 240)] + public void MovieKeepsItsAspectAndFillsTheUnusedCanvasWithBlack(int width, int height) + { + _preview.Rendering += _movies.Render; + RenderTexture target = _preview.Render(width, height); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(width, height); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, width, height), 0, 0); + image.Apply(); + int frameWidth = Mathf.Min(width, height * 4 / 3); + int frameHeight = Mathf.Min(height, width * 3 / 4); + int x = (width - frameWidth) / 2; + int y = (height - frameHeight) / 2; + + void AssertPixel(int sampleX, int sampleY, bool visible) + { + Color color = image.GetPixel(sampleX, sampleY); + Assert.That(color.r, Is.EqualTo(visible ? 1f : 0f).Within(.03), $"Red at {sampleX},{sampleY}"); + Assert.That(color.g, Is.Zero.Within(.03)); + Assert.That(color.b, Is.Zero.Within(.03)); + } + + AssertPixel(x + 2, height / 2, true); + AssertPixel(width / 2, y + 2, true); + if (x > 0) + { + AssertPixel(x - 2, height / 2, false); + AssertPixel(width - x + 2, height / 2, false); + } + if (y > 0) + { + AssertPixel(width / 2, y - 2, false); + AssertPixel(width / 2, height - y + 2, false); + } + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + + private static void RequireAudioPreviewApi() + { + if (!(bool)Device.GetProperty("IsAvailable", Static).GetValue(null)) + Assert.Ignore("This editor does not expose Unity's audio preview controls."); + } + + private static IEnumerator RequireRunningAudioClock() + { + RequireAudioPreviewApi(); + var owner = new object(); + AudioClip silent = AudioClip.Create("audio clock probe", 48000, 1, 48000, false); + try + { + Assert.That(Call("Play", owner, silent, 0, false), Is.True); + int first = (int)Call("Position", owner); + int now = first; + double timeout = EditorApplication.timeSinceStartup + .5; + while (now <= Math.Max(0, first) && EditorApplication.timeSinceStartup < timeout) + { + yield return null; + now = (int)Call("Position", owner); + } + if (now <= Math.Max(0, first)) + Assert.Ignore("The editor audio preview backend has no advancing sample clock."); + } + finally + { + Call("Stop", owner); + Object.DestroyImmediate(silent); + } + } + + [UnityTest] + public IEnumerator PauseFreezesTheRealAudioTransportAndResumeSeeksToTheVideoClock() + { + yield return RequireRunningAudioClock(); + _movies.AudioPlaybackEnabled = true; + _movies.Advance(.8); + _movies.AudioPlaybackEnabled = false; + Assert.That((bool)_movie.GetType().GetField("_audioPaused", Members).GetValue(_movie), Is.True); + int start = (int)Call("Position", _movie); + Assert.That(start, Is.GreaterThanOrEqualTo(0)); + double until = EditorApplication.timeSinceStartup + .15; + while (EditorApplication.timeSinceStartup < until) + yield return null; + int paused = (int)Call("Position", _movie); + Assert.That(Math.Abs(paused - start), Is.LessThanOrEqualTo(2048), "The real preview transport must stop advancing when the editor pauses."); + _movies.Advance(.4); // Silent single-step/inspection may move video. + _movies.AudioPlaybackEnabled = true; + Assert.That((bool)_movie.GetType().GetField("_audioPaused", Members).GetValue(_movie), Is.False); + yield return null; + int resumed = (int)Call("Position", _movie); + Assert.That(resumed, Is.InRange((int)(1.1 * 48000), (int)(1.4 * 48000)), "Resume must seek to the current video sample rather than restarting or retaining the old sample."); + } + + [Test] + public void MovieOwnsOneTransportAndFormerSoundOwnersCannotStopIt() + { + RequireAudioPreviewApi(); + AudioClip clip = AudioClip.Create("silent ownership probe", 48000, 1, 48000, false); + var soundOwner = new object(); + try + { + Assert.That(Call("Play", soundOwner, clip, 0, false), Is.True); + _movies.AudioPlaybackEnabled = true; + Assert.That(Call("Owns", _movie), Is.True); + Call("Stop", soundOwner); + Assert.That(Call("Owns", _movie), Is.True); + Assert.That(Call("Play", soundOwner, clip, 0, false), Is.False, "A pending SFX decode cannot replace a modal movie soundtrack."); + _movies.Muted = true; + Assert.That(Call("Owns", _movie), Is.False, "Muting must release audio immediately without requiring a simulation step."); + Assert.That(Call("Play", soundOwner, clip, 0, false), Is.True); + _movies.Dispose(); + Assert.That(Call("Owns", soundOwner), Is.True, "Disposing a former movie owner must preserve the new sound owner."); + } + finally + { + Call("Stop", soundOwner); + Object.DestroyImmediate(clip); + } + } + + [TestCase(PlayModeStateChange.ExitingEditMode)] + [TestCase(PlayModeStateChange.ExitingPlayMode)] + public void ModeTransitionReleasesAnAbandonedPreviewLease(PlayModeStateChange change) + { + var abandoned = new object(); + Device.GetField("_owner", Static).SetValue(null, abandoned); + Device.GetField("_exclusive", Static).SetValue(null, true); + try + { + Call("OnPlayModeStateChanged", change); + Assert.That(Call("Owns", abandoned), Is.False); + Assert.That(Device.GetField("_exclusive", Static).GetValue(null), Is.False); + } + finally + { + Call("Reset"); + } + } + + private sealed class UnsupportedMovieAudio : IBattleMovieAudioTransport + { + private readonly Exception _error; + + public int Attempts + { + get; private set; + } + + public UnsupportedMovieAudio(Exception error) => _error = error; + + public void SynchronizeMovie(object owner, AudioClip clip, double elapsed, bool playing) + { + if (playing) + { + Attempts++; + throw _error; + } + } + + public void StopMovie(object owner) + { + } + } + + [TestCase(false)] + [TestCase(true)] + public void UnavailableAudioBackendLeavesTheVideoRunningAndReportsOnce(bool reflectionFailure) + { + Exception unsupported = new NotSupportedException("Audio backend unavailable"); + if (reflectionFailure) + unsupported = new TargetInvocationException(new TypeInitializationException("AudioUtil", unsupported)); + var transport = new UnsupportedMovieAudio(unsupported); + using var player = new BattleMoviePlayer(_data, _preview, transport) { AudioPlaybackEnabled = false }; + object movie = AddMovie(player); + + player.AudioPlaybackEnabled = true; + player.Advance(.5); + Assert.That((double)movie.GetType().GetField("Elapsed", Members).GetValue(movie), Is.EqualTo(.5)); + Assert.That(player.BlocksBattleTime, Is.True); + Assert.That(player.HasDecodedFrame, Is.True); + Assert.That(transport.Attempts, Is.EqualTo(1)); + Assert.That(player.Diagnostics.Single(), Does.Contain("fixture.bik").And.Contain("Audio backend unavailable")); + + player.Advance(10); + Assert.That(player.BlocksBattleTime, Is.False); + } + + [TestCase(false)] + [TestCase(true)] + public void MissingConfiguredRootStillSearchesInstallationAndReportsAbsentMovies(bool installed) + { + const string option = "PAL3_BATTLE_MOVIE_ROOT"; + string saved = Environment.GetEnvironmentVariable(option); + string name = Guid.NewGuid().ToString("N") + ".bik"; + try + { + Environment.SetEnvironmentVariable(option, Path.Combine(_directory, "missing-override")); + typeof(BattleMoviePlayer).GetField("_workspace", Members).SetValue(_movies, Path.Combine(_directory, "workspace")); + if (installed) + { + string install = Directory.CreateDirectory(Path.Combine(_directory, BattleData.Variant + " Installation")).FullName; + // The invalid Bink header identifies the file that was found without invoking a decoder. + File.WriteAllBytes(Path.Combine(install, name), new byte[4]); + } + PrepareMovie(_movies, name); + _movies.Advance(0); + Assert.That(_movies.MissingMovies.Contains(name), Is.EqualTo(!installed)); + Assert.That(_movies.Diagnostics.Single(), Does.Contain(installed ? "Invalid original Bink header" : "未找到影片文件")); + } + finally + { + Environment.SetEnvironmentVariable(option, saved); + } + } + + [TestCase("PAL3_BATTLE_FFMPEG")] + [TestCase("video.rgba")] + [TestCase("audio.wav")] + [TestCase("Invalid decoded PCM")] + public void UnavailableDecoderOrBrokenCacheSkipsTheMovieAndExplainsWhy(string expectedDiagnostic) + { + const string movie = "decoder-fixture.bik"; + byte[] bytes = new byte[44]; + bytes[0] = (byte)'B'; + bytes[1] = (byte)'I'; + bytes[2] = (byte)'K'; + foreach (int offset in new[] { 8, 20, 24, 28, 32 }) + BitConverter.GetBytes(1u).CopyTo(bytes, offset); + if (expectedDiagnostic is "audio.wav" or "Invalid decoded PCM") + BitConverter.GetBytes(1u).CopyTo(bytes, 40); + File.WriteAllBytes(Path.Combine(_directory, movie), bytes); + string cache = Path.Combine(_directory, "cache"); + string ready = null; + if (expectedDiagnostic != "PAL3_BATTLE_FFMPEG") + { + using var sha = System.Security.Cryptography.SHA256.Create(); + string hash = BitConverter.ToString(sha.ComputeHash(bytes)) + .Replace("-", "").ToLowerInvariant(); + string entry = Path.Combine(cache, hash, "rgba-pcm-v1"); + Directory.CreateDirectory(entry); + ready = Path.Combine(entry, "complete"); + File.WriteAllText(ready, ""); + if (expectedDiagnostic is "audio.wav" or "Invalid decoded PCM") + File.WriteAllBytes(Path.Combine(entry, "video.rgba"), new byte[4]); + if (expectedDiagnostic == "Invalid decoded PCM") + { + byte[] emptyWave = File.ReadAllBytes(Path.Combine(_directory, "audio.wav"))[..44]; + BitConverter.GetBytes(36).CopyTo(emptyWave, 4); + BitConverter.GetBytes(0).CopyTo(emptyWave, 40); + File.WriteAllBytes(Path.Combine(entry, "audio.wav"), emptyWave); + } + } + const string rootKey = "PAL3_BATTLE_MOVIE_ROOT"; + const string cacheKey = "PAL3_BATTLE_MOVIE_CACHE"; + const string decoderKey = "PAL3_BATTLE_FFMPEG"; + string previousRoot = Environment.GetEnvironmentVariable(rootKey); + string previousCache = Environment.GetEnvironmentVariable(cacheKey); + string previousDecoder = Environment.GetEnvironmentVariable(decoderKey); + try + { + Environment.SetEnvironmentVariable(rootKey, _directory); + Environment.SetEnvironmentVariable(cacheKey, cache); + Environment.SetEnvironmentVariable(decoderKey, Path.Combine(_directory, "missing-ffmpeg")); + using var player = new BattleMoviePlayer(_data, _preview); + PrepareMovie(player, movie); + using var first = player.Play(movie); + using var repeat = player.Play(movie); + player.Advance(0); + Assert.That(first.Finished && repeat.Finished, Is.True); + Assert.That(player.BlocksBattleTime, Is.False); + Assert.That(player.MissingMovies, Is.Empty, "The source was found."); + Assert.That(player.Diagnostics.Single(), Does.Contain(movie).And.Contain(expectedDiagnostic)); + if (ready != null) + Assert.That(File.Exists(ready), Is.False, "A future preview must be able to rebuild the broken entry."); + } + finally + { + Environment.SetEnvironmentVariable(rootKey, previousRoot); + Environment.SetEnvironmentVariable(cacheKey, previousCache); + Environment.SetEnvironmentVariable(decoderKey, previousDecoder); + } + } + + [TestCase(false)] + [TestCase(true)] + public void FailedPreparationEndsTheMovieAndReportsOnlyOnce(bool canceled) + { + const string name = "preparation-failed.bik"; + Type result = typeof(BattleMoviePlayer).GetNestedType("Preparation", BindingFlags.NonPublic); + MethodInfo factory = typeof(Task).GetMethods().Single(method => + method.Name == (canceled ? nameof(Task.FromCanceled) : nameof(Task.FromException)) && method.IsGenericMethod); + object reason = canceled ? new CancellationToken(true) : new InvalidOperationException("test movie preparation fault"); + object prepared = factory.MakeGenericMethod(result).Invoke(null, new[] { reason }); + using var player = new BattleMoviePlayer(_data, _preview); + var cache = (IDictionary)typeof(BattleMoviePlayer).GetField("_prepared", Members).GetValue(player); + cache.Add(name, prepared); + + using var first = player.Play(name); + player.Advance(.02); + Assert.That(first.Finished, Is.True); + using var second = player.Play(name); + player.Advance(.02); + Assert.That(second.Finished, Is.True); + Assert.That(player.BlocksBattleTime, Is.False); + Assert.That(player.Diagnostics.Single(), Does.Contain(name).And.Contain(canceled ? "已取消" : "test movie preparation fault")); + } + + private static void PrepareMovie(BattleMoviePlayer player, string name) + { + player.Preload(name); + var pending = (IDictionary)typeof(BattleMoviePlayer).GetField("_prepared", Members).GetValue(player); + Assert.That(((Task)pending[name]).Wait(TimeSpan.FromSeconds(30)), Is.True, "The fixture's movie preparation did not finish."); + } + +#if UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX + [Test] + public void ColdPlaybackReturnsWhileTheDecoderRunsAndDisposingCancelsIt() + { + const string movie = "slow-movie.bik"; + byte[] header = new byte[44]; + header[0] = (byte)'B'; + header[1] = (byte)'I'; + header[2] = (byte)'K'; + foreach (int offset in new[] { 8, 20, 24, 28, 32 }) + BitConverter.GetBytes(1u).CopyTo(header, offset); + File.WriteAllBytes(Path.Combine(_directory, movie), header); + string decoder = Path.Combine(_directory, "slow-decoder"); + File.WriteAllText(decoder, "#!/bin/sh\nprintf '%s\\n' \"$@\" > \"$0.args\"\n: > \"$0.started\"\nexec /bin/sleep 30\n"); + using (var chmod = System.Diagnostics.Process.Start("/bin/chmod", "+x \"" + decoder + "\"")) + { + Assert.That(chmod.WaitForExit(2000), Is.True); + Assert.That(chmod.ExitCode, Is.Zero); + } + + const string rootKey = "PAL3_BATTLE_MOVIE_ROOT"; + const string cacheKey = "PAL3_BATTLE_MOVIE_CACHE"; + const string decoderKey = "PAL3_BATTLE_FFMPEG"; + string previousRoot = Environment.GetEnvironmentVariable(rootKey); + string previousCache = Environment.GetEnvironmentVariable(cacheKey); + string previousDecoder = Environment.GetEnvironmentVariable(decoderKey); + try + { + Environment.SetEnvironmentVariable(rootKey, _directory); + Environment.SetEnvironmentVariable(cacheKey, Path.Combine(_directory, "slow cache")); + Environment.SetEnvironmentVariable(decoderKey, decoder); + using var player = new BattleMoviePlayer(_data, _preview); + using var playback = player.Play(movie); + Assert.That(player.IsPreparingPlayback, Is.True); + Assert.That(playback.Finished, Is.False); + Assert.That(SpinWait.SpinUntil(() => File.Exists(decoder + ".started"), TimeSpan.FromSeconds(5)), Is.True); + string[] arguments = File.ReadAllLines(decoder + ".args"); + int inputIndex = Array.IndexOf(arguments, "-i"); + Assert.That(inputIndex, Is.GreaterThanOrEqualTo(0)); + string input = arguments[inputIndex + 1]; + Assert.That(input, Does.StartWith(Path.Combine(_directory, "slow cache") + Path.DirectorySeparatorChar)); + Assert.That(Path.GetFileName(input), Is.EqualTo("original.bik")); + Assert.That(arguments[^1], Is.EqualTo(Path.Combine(Path.GetDirectoryName(input), "video.rgba"))); + var pending = (IDictionary)typeof(BattleMoviePlayer).GetField("_prepared", Members).GetValue(player); + var preparation = (Task)pending[movie]; + Assert.That(preparation.IsCompleted, Is.False); + Assert.That(player.Skip(), Is.True); + Assert.That(player.BlocksBattleTime, Is.False); + player.Dispose(); + Assert.That(SpinWait.SpinUntil(() => preparation.IsCompleted, TimeSpan.FromSeconds(5)), Is.True); + Assert.That(preparation.IsCanceled, Is.True); + } + finally + { + Environment.SetEnvironmentVariable(rootKey, previousRoot); + Environment.SetEnvironmentVariable(cacheKey, previousCache); + Environment.SetEnvironmentVariable(decoderKey, previousDecoder); + } + } + + [TestCase(false)] + [TestCase(true)] + public void StalledDecoderIsStoppedOnTimeoutOrCancellation(bool cancel) + { + using var process = new System.Diagnostics.Process + { + StartInfo = new System.Diagnostics.ProcessStartInfo("/bin/sleep", "30") + { + UseShellExecute = false, + RedirectStandardError = true + } + }; + using var cancellation = new CancellationTokenSource(); + if (cancel) + cancellation.CancelAfter(TimeSpan.FromMilliseconds(250)); + MethodInfo run = typeof(BattleMoviePlayer).GetMethod("RunDecoder", Static); + TimeSpan timeout = TimeSpan.FromSeconds(cancel ? 4 : .15); + var error = Assert.Throws(() => run.Invoke(null, new object[] + { + process, "stalled.bik", timeout, cancellation.Token + })); + Assert.That(error.InnerException, Is.TypeOf(cancel ? typeof(OperationCanceledException) : typeof(TimeoutException))); + Assert.That(process.HasExited, Is.True); + } +#endif + + [Test] + public void CompletingAMovieReleasesItsFrameAudioAndOwnerEntry() + { + Texture texture = _movies.CurrentTexture; + _movies.Advance(11); + Assert.That(_movies.BlocksBattleTime, Is.False); + Assert.That(_movies.CurrentTexture, Is.Null); + Assert.That(texture == null, Is.True); + Assert.That(((IList)typeof(BattleMoviePlayer).GetField("_movies", Members).GetValue(_movies)).Count, Is.Zero); + } + + [Test] + public void SkippingAMovieReleasesItsTextureAndAudioImmediately() + { + RequireAudioPreviewApi(); + _movies.AudioPlaybackEnabled = true; + Assert.That(Call("Owns", _movie), Is.True); + Texture texture = _movies.CurrentTexture; + Assert.That(_movies.Skip(), Is.True); + Assert.That(_movies.Skip(), Is.False); + Assert.That(_movies.BlocksBattleTime, Is.False); + Assert.That(_movies.CurrentTexture, Is.Null); + Assert.That(texture == null, Is.True); + Assert.That(Call("Owns", _movie), Is.False); + } + + [TestCase(false)] +#if PAL3 + [TestCase(true)] +#endif + public void EscapeInTheWorkbenchSkipsTheMovieAndReleasesThePausedBattleFrame(bool originalMovie) + { + var window = ScriptableObject.CreateInstance(); + try + { + window.position = new Rect(0, 0, 1000, 720); + Type windowType = typeof(BattleEditorWindow); + var session = (BattleEditorSession)windowType.GetField("_session", Members).GetValue(window); + windowType.GetMethod("ConnectData", Members).Invoke(window, new object[] { _data.Resources.Root, 936 }); + var draft = (BattleScenarioAsset)windowType.GetField("_draft", Members).GetValue(window); + draft.Scenario = Scenario(session.Data); + windowType.GetMethod("UpdateDirty", Members).Invoke(window, null); + windowType.GetMethod("StartBattle", Members).Invoke(window, null); + Assert.That(session.Battle, Is.Not.Null); + session.IsPlaying = false; + + var player = (BattleMoviePlayer)typeof(BattleEffectDirector).GetField("_movies", Members).GetValue(session.Preview.Effects); + if (originalMovie) + { + const string name = @"2DEFFECT\t102.bik"; + PrepareMovie(player, name); + player.Play(name); + } + else + AddMovie(player); + Assert.That(player.Diagnostics, Is.Empty); + session.StepBattle(); + Assert.That(session.Battle.IsModalPresentation, Is.True); + Assert.That(session.Preview.Trail.Suspended, Is.True); + Assert.That(session.Battle.SimulationTick, Is.Zero); + var draw = (Action)windowType.GetMethod("DrawWindow", Members).CreateDelegate(typeof(Action), window); + using var gui = new OffscreenGui(draw); + gui.Paint(window.position.size); + if (gui.RenderTarget != null) + { + Color32[] moviePixels = ReadCanvasPixels(gui.RenderTarget); + windowType.GetField("_debugBattle", Members).SetValue(window, true); + gui.Paint(window.position.size); + Assert.That(ReadCanvasPixels(gui.RenderTarget).SequenceEqual(moviePixels), Is.True, + "Debug actor labels must stay behind the modal movie."); + } + + foreach (var tab in new[] + { + new Event { type = EventType.KeyDown, keyCode = KeyCode.Tab, character = '\t' }, + new Event { type = EventType.KeyDown, character = '\t' } + }) + { + gui.SendEvent(tab, window.position.size); + Assert.That(tab.type, Is.EqualTo(EventType.Used)); + } + gui.SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.F }, window.position.size); + Assert.That(session.Battle.IsModalPresentation, Is.True); + gui.SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.Escape }, window.position.size); + Assert.That(session.Battle.IsModalPresentation, Is.False); + Assert.That(session.Preview.Trail.Suspended, Is.False); + Assert.That(session.Battle.Inputs.Count(input => input.Kind == BattleInputKind.ModalPresentationSkip), Is.EqualTo(1)); + session.StepBattle(); + Assert.That(session.Battle.SimulationTick, Is.EqualTo(1)); + } + finally + { + window.DiscardChanges(); + Object.DestroyImmediate(window); + } + } + + [Test] + public void ReplayWithADifferentMovieTimelinePreservesTheLiveBattleAndPlayback() + { + using var session = new BattleEditorSession(); + StartBattle(session); + BattleSession original = session.Battle; + BattlePreview preview = session.Preview; + var player = (BattleMoviePlayer)typeof(BattleEffectDirector).GetField("_movies", Members).GetValue(preview.Effects); + AddMovie(player); + session.StepBattle(); + session.IsPlaying = true; + Assert.That(original.IsModalPresentation, Is.True); + Assert.That(original.SimulationTick, Is.Zero); + + var error = Assert.Throws(session.ReplayBattle); + Assert.That(error.Message, Does.Contain("battle movies")); + Assert.That(session.Battle, Is.SameAs(original)); + Assert.That(session.Preview, Is.SameAs(preview)); + Assert.That(session.IsPlaying, Is.True); + Assert.That(original.IsModalPresentation, Is.True); + } + + [Test] + public void EditorPlaybackInspectionSpeedAndReplayHaveExplicitAudioBoundaries() + { + using var session = new BattleEditorSession(); + StartBattle(session); + Assert.That(session.Preview.Effects.AudioPlaybackEnabled, Is.False); + Assert.That(session.Preview.Audio.PlaybackEnabled, Is.False); + session.IsPlaying = true; + Assert.That(session.Preview.Effects.AudioPlaybackEnabled, Is.True); + session.Speed = 2; + Assert.That(session.Preview.Effects.AudioPlaybackEnabled, Is.False); + session.Speed = 1; + Assert.That(session.Preview.Effects.AudioPlaybackEnabled, Is.True); + session.StepBattle(); + Assert.That(session.IsPlaying, Is.False); + Assert.That(session.Preview.Effects.AudioPlaybackEnabled, Is.False); + session.IsPlaying = true; + session.AdvanceTo(BattleEventKind.Hit, 1); + Assert.That(session.Preview.Effects.AudioPlaybackEnabled, Is.False); + session.ReplayBattle(); + Assert.That(session.Preview.Effects.AudioPlaybackEnabled, Is.False); + Assert.That(session.Preview.Audio.PlaybackEnabled, Is.False); + } + + private static Color32[] ReadCanvasPixels(RenderTexture target) + { + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(target.width, target.height, TextureFormat.RGBA32, false); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0); + return image.GetPixels32(); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + + [TestCase(KeyCode.Return)] + [TestCase(KeyCode.Escape)] + public void HeldKeyboardActionsDoNotConsumeTwoHudPages(KeyCode key) + { + var window = ScriptableObject.CreateInstance(); + try + { + window.position = new Rect(0, 0, 1000, 720); + var session = (BattleEditorSession)typeof(BattleEditorWindow).GetField("_session", Members).GetValue(window); + var hud = (BattleHudView)typeof(BattleEditorWindow).GetField("_hud", Members).GetValue(window); + typeof(BattleEditorWindow).GetMethod("ConnectData", Members).Invoke(window, new object[] { _data.Resources.Root, 936 }); + var draft = (BattleScenarioAsset)typeof(BattleEditorWindow).GetField("_draft", Members).GetValue(window); + draft.Scenario = Scenario(session.Data); + draft.Scenario.Participants[0] = session.Data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water); + typeof(BattleEditorWindow).GetMethod("UpdateDirty", Members).Invoke(window, null); + typeof(BattleEditorWindow).GetMethod("StartBattle", Members).Invoke(window, null); + string ally = draft.Scenario.Participants[0].InstanceId; + string enemy = draft.Scenario.Participants[1].InstanceId; + for (int step = 0; step < 5000 && session.Battle.WaitingActor != ally; step++) + { + if (session.Battle.WaitingActor is { } waiting) + session.Battle.Submit(waiting, BattleAction.Defend); + session.StepBattle(); + } + Assert.That(session.Battle.WaitingActor, Is.EqualTo(ally)); + var draw = (Action)typeof(BattleEditorWindow).GetMethod("DrawWindow", Members).CreateDelegate(typeof(Action), window); + using var gui = new OffscreenGui(draw); + gui.Paint(window.position.size); + if (key == KeyCode.Escape) + { + hud.Presenter.Open(BattleHudPage.Skills); + int skill = session.Battle.Definitions.Skills.Values + .First(ability => !ability.IsMagic && ability.Range == BattleTargetRange.OpponentSingle && + session.Battle.CanSubmit(new BattleCommand(ally, BattleAction.Skill, enemy, ability.Id)) == null).Id; + Assert.That(hud.Presenter.ChooseAbility(skill), Is.True); + gui.Paint(window.position.size); + } + int inputs = session.Battle.RecordedInputCount; + BattleHudPage expected = key == KeyCode.Return ? BattleHudPage.Targets : BattleHudPage.Skills; + gui.SendEvent(new Event { type = EventType.KeyDown, keyCode = key }, window.position.size); + Assert.That(hud.Presenter.Page, Is.EqualTo(expected)); + gui.SendEvent(new Event { type = EventType.KeyDown, keyCode = key }, window.position.size); + Assert.That(hud.Presenter.Page, Is.EqualTo(expected)); + Assert.That(session.Battle.RecordedInputCount, Is.EqualTo(inputs)); + gui.SendEvent(new Event { type = EventType.KeyUp, keyCode = key }, window.position.size); + gui.SendEvent(new Event { type = EventType.KeyDown, keyCode = key }, window.position.size); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(session.Battle.RecordedInputCount, Is.EqualTo(inputs + (key == KeyCode.Return ? 1 : 0))); + } + finally + { + window.DiscardChanges(); + Object.DestroyImmediate(window); + } + } + + private void StartBattle(BattleEditorSession session) + { + session.Load(_data.Resources.Root, 936); + session.StartBattle(Scenario(session.Data)); + } + + private static BattleScenario Scenario(BattleData data) + { + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = data.Scenes.First(), DataFingerprint = data.Fingerprint }; + scenario.Participants.Add(data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(data, id)); + scenario.Participants.Add(data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + foreach (BattleParticipant actor in scenario.Participants) + actor.Skills.Clear(); + return scenario; + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleMovieAudioTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleMovieAudioTests.cs.meta new file mode 100644 index 00000000..371496ee --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleMovieAudioTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b91ae31e28ca422ebc89f15dd867db30 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleNumberFontTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleNumberFontTests.cs new file mode 100644 index 00000000..3d8083f4 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleNumberFontTests.cs @@ -0,0 +1,34 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle.Presentation; + using NUnit.Framework; + using ResourceBrowser; + using UnityEngine; + + [Category("LocalGameData")] + public sealed class BattleNumberFontTests + { + [Test] + public void OriginalFontSuppliesEveryDamageMissAndGuCostGlyph() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT") ?? + Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root)) + Assert.Ignore("Local original-game data is not available."); + using var resources = ResourceCatalog.OpenBaseData(root, 936); + var entry = resources.Find("basedata.cpk\\gbdata\\unicode20.tft"); + Assert.That(entry, Is.Not.Null); + var font = new BattleNumberFont(resources.Read(entry)); + foreach (char character in "0123456789-MIS蛊") + Assert.That(font.GlyphAlpha(character).Any(alpha => alpha != 0), Is.True, "Missing native glyph " + character); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleNumberFontTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleNumberFontTests.cs.meta new file mode 100644 index 00000000..2f3294b8 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleNumberFontTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 39ed386ceac345128c38ad6339b48824 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattlePal3AFormsIntegrationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattlePal3AFormsIntegrationTests.cs new file mode 100644 index 00000000..90d2c928 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattlePal3AFormsIntegrationTests.cs @@ -0,0 +1,198 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +#if PAL3A +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using Core.Contract.Constants; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + public sealed class BattlePal3AFormsIntegrationTests + { + private BattleEditorSession _session; + + [SetUp] + public void LoadData() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Original PAL3A data is required for the form presentation tests."); + _session = new BattleEditorSession(); + _session.Load(root, 936); + } + + [TearDown] + public void Dispose() => _session?.Dispose(); + + private BattleScenario Scenario(int actorId, int ability = 0) + { + BattleData data = _session.Data; + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = data.Scenes.First(), + DataFingerprint = data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + scenario.Participants.Add(data.CreateParticipant(actorId, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(data.CreateParticipant(7311, BattleSide.Enemy, BattleSlot.Water)); + foreach (BattleParticipant actor in scenario.Participants) + { + actor.Attributes = new[] { 50000, 100, 1000, 5000, 1, 5, 0, 0, 0, 0, 0, 0 }; + actor.Vitals = new[] { 50000, 100, 1000 }; + actor.Skills.Clear(); + } + if (ability != 0) + scenario.Participants[0].Skills.Add(new BattleSkill { Id = ability, Level = 4, Mastered = true }); + return scenario; + } + + private void FinishAction(string source) + { + for (int tick = 0; tick < 1500 && _session.Battle.Status == BattleSessionStatus.Running && + (_session.Battle.Actors.Single(actor => actor.Id == source).ActionId != 0 || _session.Battle.Pal3AForm(source).Pending); tick++) + _session.StepBattle(); + Assert.That(_session.Battle.Status, Is.EqualTo(BattleSessionStatus.Running), _session.Battle.Result?.Reason); + Assert.That(_session.Battle.Actors.Single(actor => actor.Id == source).ActionId, Is.Zero); + Assert.That(_session.Battle.Pal3AForm(source).Pending, Is.False); + } + + [Test] + public void NangongTransformationLoadsBothActualZ20BodiesAndTheBeastGeometry() + { + BattleScenario scenario = Scenario(101); + scenario.Pal3A.SpiritWheel.Charges = new[] { 3, 3, 3, 3, 3 }; + _session.StartBattle(scenario); + string source = scenario.Participants[0].InstanceId; + Assert.That(_session.Battle.Submit(source, BattleAction.Transform), Is.True); + FinishAction(source); + Assert.That(_session.Battle.Pal3AForm(source).Kind, Is.EqualTo(BattlePal3AFormKind.NangongFireBeast)); + Assert.That(_session.Battle.Pal3AState.SpiritWheel.Charges, Is.All.Zero); + Assert.That(_session.Preview.View.Dependencies.Keys.Any(path => path.StartsWith(FileConstants.GetActorFolderVirtualPath("107"), StringComparison.OrdinalIgnoreCase)), Is.True); + Capture("nangong-107"); + CaptureForm(source, "107", "nangong-107-inspection"); + } + + [Test] + public void PengxuActual4308SwapsTo106AndPaysItsCapturedMaximumSp() + { + BattleScenario scenario = Scenario(103, 4308); + _session.StartBattle(scenario); + string source = scenario.Participants[0].InstanceId; + string target = _session.Battle.GetTargetCandidates(new BattleCommand(source, BattleAction.Skill, null, 4308)).First().Id; + var command = new BattleCommand(source, BattleAction.Skill, target, 4308); + Assert.That(_session.Battle.Submit(command), Is.True, _session.Battle.CanSubmit(command)); + FinishAction(source); + var catalog = new BattleAnimationCatalog(_session.Data, new BattleSetup(scenario), _session.Battle.Definitions); + Assert.That(catalog.FormChangeAnimation(source, true), Is.Null, "The released 106 model has no z20 action."); + catalog.ActivatePal3AForm(source, BattlePal3AFormKind.PengxuFairyBeast); + Assert.That(catalog.Physical(source).Animation(BattlePose.Idle).Clip, Is.EqualTo("z03")); + foreach ((string attacker, string defender) in new[] { (source, target), (target, source) }) + { + BattleAttackPlan plan = catalog.PlanAttack(attacker, defender, catalog.InitialHome(attacker), catalog.InitialHome(defender)); + Assert.That(catalog.Approach(attacker, defender), Is.EqualTo(BattleAnimationCatalog.UnityPosition(plan.Approach))); + AttackTiming timing = catalog.Attack(attacker, defender); + Assert.That(timing.TravelTicks, Is.EqualTo(plan.Timing.TravelTicks)); + Assert.That(timing.HitTicks, Is.EqualTo(plan.Timing.HitTicks)); + } + Assert.That(_session.Battle.Pal3AForm(source).Kind, Is.EqualTo(BattlePal3AFormKind.PengxuFairyBeast)); + BattleActorSnapshot actor = _session.Battle.Actors.Single(actor => actor.Id == source); + Assert.That((actor.Hp, actor.MaxHp, actor.Sp), Is.EqualTo((400, 400, 0))); + Assert.That(_session.Preview.View.Dependencies.Keys.Any(path => path.StartsWith(FileConstants.GetActorFolderVirtualPath("106"), StringComparison.OrdinalIgnoreCase)), Is.True); + Capture("pengxu-106"); + CaptureForm(source, "106", "pengxu-106-inspection"); + } + + [Test] + public void ActualCaptureProjectsOrbsAndChargesTheWheelWithoutEndingTheBattle() + { + BattleScenario scenario = Scenario(101, 4102); + BattleParticipant survivor = scenario.Participants[1].Copy(); + survivor.InstanceId = Guid.NewGuid().ToString("N"); + survivor.Slot = BattleSlot.Fire; + scenario.Participants.Add(survivor); + scenario.Participants[1].Vitals[0] = 1; + _session.StartBattle(scenario); + string source = scenario.Participants[0].InstanceId; + string target = _session.Battle.GetTargetCandidates(new BattleCommand(source, BattleAction.Skill, null, 4102)).First().Id; + var command = new BattleCommand(source, BattleAction.Skill, target, 4102); + Assert.That(_session.Battle.Submit(command), Is.True, _session.Battle.CanSubmit(command)); + for (int tick = 0; tick < 600 && _session.Battle.SpiritOrbs.Count == 0; tick++) + _session.StepBattle(); + Assert.That(_session.Battle.SpiritOrbs.Count, Is.EqualTo(4)); + Assert.That(_session.Battle.WasSpiritCaptured(scenario.Participants[1].InstanceId), Is.True); + Assert.That(_session.Battle.SpiritOrbs.All(orb => float.IsFinite(orb.Position.X) && float.IsFinite(orb.Position.Y)), Is.True); + foreach (BattleSpiritOrbSnapshot orb in _session.Battle.SpiritOrbs) + Assert.That(orb.Destination.Right, Is.GreaterThan(700)); + for (int tick = 0; tick < 600 && _session.Battle.SpiritOrbs.Count > 0; tick++) + _session.StepBattle(); + Assert.That(_session.Battle.SpiritOrbs, Is.Empty); + Assert.That(_session.Battle.Pal3AState.SpiritWheel.Charges, Is.EqualTo(new[] { 1, 2, 0, 0, 1 })); + Assert.That(_session.Battle.Status, Is.EqualTo(BattleSessionStatus.Running), _session.Battle.Result?.Reason); + for (int element = 0; element < 5; element++) + Assert.That(_session.Preview.View.GetTexture($"basedata.cpk\\ui\\combat\\control\\ImbibeNimbus{element}.tga").width, Is.GreaterThan(2)); + Capture("capture-wheel"); + } + + private void CaptureForm(string source, string model, string name) + { + Transform actor = _session.Preview.View.Root.transform.Find(source); + Assert.That(actor, Is.Not.Null); + MeshFilter[] meshes = actor.GetComponentsInChildren(); + Assert.That(meshes.Length, Is.GreaterThan(0)); + Assert.That(meshes.All(mesh => mesh.sharedMesh != null && mesh.sharedMesh.vertexCount > 0), Is.True); + Renderer[] renderers = actor.GetComponentsInChildren(); + Assert.That(renderers.SelectMany(renderer => renderer.sharedMaterials) + .Any(material => material.mainTexture != null && material.mainTexture.name.Split('\\').Last().StartsWith(model + ".", StringComparison.OrdinalIgnoreCase)), Is.True, + "The transformed actor must bind its own model texture, not merely preload the dependency."); + Bounds bounds = renderers[0].bounds; + foreach (Renderer renderer in renderers.Skip(1)) + bounds.Encapsulate(renderer.bounds); + float distance = Mathf.Max(1, bounds.size.magnitude * 1.5f); + try + { + _session.Preview.View.SetCamera(bounds.center + new Vector3(distance, distance * .3f, -distance), bounds.center, 35); + Capture(name); + } + finally + { + _session.Preview.Camera.Publish(); + } + } + + private void Capture(string name) + { + RenderTexture target = _session.Preview.View.Render(800, 600); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(800, 600, TextureFormat.RGB24, false); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, 800, 600), 0, 0); + image.Apply(); + Assert.That(image.GetPixels32().Select(pixel => (pixel.r, pixel.g, pixel.b)).Distinct().Take(100).Count(), Is.GreaterThan(20)); + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (output != null) + { + Directory.CreateDirectory(output); + File.WriteAllBytes(Path.Combine(output, "PAL3A-" + name + ".png"), image.EncodeToPNG()); + } + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + } +} +#endif diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattlePal3AFormsIntegrationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattlePal3AFormsIntegrationTests.cs.meta new file mode 100644 index 00000000..4b49e44b --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattlePal3AFormsIntegrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 01d8fc92ac1c45459a9ce769dce2e085 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattlePreviewTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattlePreviewTests.cs new file mode 100644 index 00000000..6565ba14 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattlePreviewTests.cs @@ -0,0 +1,672 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Collections; + using System.Collections.Generic; + using System.Reflection; + using System.Linq; + using Battle; + using Core.Contract.Enums; + using Core.DataReader.Mv3; + using Core.DataReader.Data; + using Engine.Extensions; + using Game.Rendering.Renderer; + using Game.Effect.Runtime; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + public sealed class BattlePreviewTests + { + private BattleEditorSession _session; + + [SetUp] + public void LoadData() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT") ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root)) + Assert.Ignore("Local original-game data is not available."); + _session = new BattleEditorSession(); + _session.Load(root, 936); + } + + [TearDown] + public void Dispose() => _session?.Dispose(); + + private BattleScenario CreateScenario() + { + BattleData data = _session.Data; + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = data.Scenes.First(), DataFingerprint = data.Fingerprint }; + foreach (BattleSide side in Enum.GetValues(typeof(BattleSide))) + { + var info = data.Database.CombatActorInfos.OrderBy(pair => pair.Key).First(pair => pair.Key > 0 && + (pair.Value.Type == CombatActorType.MainActor) == (side == BattleSide.Ally) && + data.Resources.Find(Core.Contract.Constants.FileConstants.GetActorFolderVirtualPath(pair.Value.Type == CombatActorType.MainActor ? pair.Key.ToString() : pair.Value.ModelId) + + (pair.Value.Type == CombatActorType.MainActor ? pair.Key.ToString() : pair.Value.ModelId) + ".ini") != null); + scenario.Participants.Add(data.CreateParticipant(info.Key, side, BattleSlot.Water)); + } + BattleParticipant duplicate = scenario.Participants[1].Copy(); + duplicate.InstanceId = Guid.NewGuid().ToString("N"); + duplicate.Slot = BattleSlot.Fire; + scenario.Participants.Add(duplicate); + return scenario; + } + + [TestCase(800, 800, false)] + [TestCase(800, 800, true)] + [TestCase(800, 600, false)] + [TestCase(800, 600, true)] + [TestCase(1600, 900, false)] + [TestCase(1600, 900, true)] + public void CustomCameraKeepsItsProjectionThroughBattleBindingAndCaptureUntilNativeListTakesOver(int width, int height, bool expand) + { + BattleScenario scenario = CreateScenario(); + scenario.Camera = new BattleCamera + { + Override = true, + Position = new BattlePoint { X = 0, Y = 10, Z = -20 }, + Target = new BattlePoint { X = 0, Y = 0, Z = 0 }, + FieldOfView = 60 + }; + var viewport = new Rect(0, 0, width, height); + var world = new Vector3(2, 1, 1); + void ConfigureViewport() + { + _session.Preview.View.ExpandReferenceFraming = expand; + _session.Preview.View.SetViewportContext(viewport); + } + Vector2 Project() + { + ConfigureViewport(); + Assert.That(_session.Preview.View.Project(world, viewport, out Vector2 point), Is.True); + return point; + } + void AssertCustomProjection(Vector2 expected) + { + Assert.That(Vector2.Distance(Project(), expected), Is.LessThan(.003)); + _session.Preview.View.GetCamera(out _, out _, out float vertical); + Assert.That(vertical, Is.EqualTo(60).Within(.0001)); + } + + _session.Start(scenario); + Vector2 authored = Project(); + _session.StartBattle(scenario); + AssertCustomProjection(authored); + Assert.That(_session.Preview.Camera.StartList(-1), Is.False); + _session.Preview.Camera.Advance(BattleSession.StepSeconds, BattleSession.StepSeconds); + AssertCustomProjection(authored); + + // Exercise the same GetCamera -> BattleCamera fields used by the + // authoring Save Current View action, without opening its window. + _session.Preview.View.GetCamera(out Vector3 position, out Vector3 target, out float fieldOfView); + scenario.Camera = new BattleCamera + { + Override = true, + Position = new BattlePoint { X = position.x, Y = position.y, Z = position.z }, + Target = new BattlePoint { X = target.x, Y = target.y, Z = target.z }, + FieldOfView = fieldOfView + }; + _session.StartBattle(scenario); + AssertCustomProjection(authored); + + Assert.That(_session.Preview.Camera.StartList(0), Is.True); + _session.Preview.Camera.Advance(BattleSession.StepSeconds, BattleSession.StepSeconds); + ConfigureViewport(); + float nativeHorizontal = _session.Preview.Camera.Controller.FieldOfView; + float aspect = width / (float)height; + float nativeVertical = Camera.HorizontalToVerticalFieldOfView(nativeHorizontal, expand ? Math.Min(aspect, 4f / 3) : aspect); + _session.Preview.View.GetCamera(out _, out _, out float actualVertical); + Assert.That(_session.Preview.View.HorizontalFieldOfView, Is.EqualTo(nativeHorizontal)); + Assert.That(actualVertical, Is.EqualTo(nativeVertical).Within(.0001)); + + _session.Preview.Camera.StopList(); + _session.Preview.Camera.Advance(BattleSession.StepSeconds, BattleSession.StepSeconds); + ConfigureViewport(); + _session.Preview.View.GetCamera(out _, out _, out actualVertical); + Assert.That(actualVertical, Is.EqualTo(nativeVertical).Within(.0001), + "Stopping a native list must not restore the old authoring projection."); + } + + [Test] + public void LoadsOnlyBaseDataAndRejectsInvalidStartWithoutLosingCurrentPreview() + { + BattleScenario scenario = CreateScenario(); + Assert.That(_session.Data.Resources.Entries.All(entry => entry.Path.StartsWith("basedata.cpk\\", StringComparison.OrdinalIgnoreCase)), Is.True); + Assert.That(_session.Data.Validate(scenario), Is.Empty); + _session.Start(scenario); + BattlePreview previous = _session.Preview; + scenario.Participants[0].ActorId = int.MaxValue; + Assert.Throws(() => _session.Start(scenario)); + Assert.That(_session.Preview, Is.SameAs(previous)); + Assert.Throws(() => _session.Load(Path.Combine(_session.Data.Resources.Root, "missing-" + Guid.NewGuid().ToString("N")), 936)); + Assert.That(_session.Preview, Is.SameAs(previous)); + scenario = CreateScenario(); + scenario.DataFingerprint = "other revision"; + Assert.That(_session.Data.Validate(scenario).Any(error => error.Contains("fingerprint")), Is.True); + } + + [Test] + public void EffectInitializationFailureReleasesPartialOwnersAndKeepsTheCurrentPreview() + { + BattleScenario scenario = CreateScenario(); + _session.Start(scenario); + BattlePreview previous = _session.Preview; + int scenes = UnityEditor.SceneManagement.EditorSceneManager.previewSceneCount; + int audioOwners = Resources.FindObjectsOfTypeAll().Count(value => value.name == "Battle audio preview"); + var archives = (IDictionary)_session.Data.Resources.FileSystem.GetType() + .GetField("_cpkArchives", BindingFlags.Instance | BindingFlags.NonPublic) + .GetValue(_session.Data.Resources.FileSystem); + var mounted = new System.Collections.Generic.List(); + foreach (DictionaryEntry archive in archives) + mounted.Add(archive); + archives.Clear(); // Simulate a dependency disappearing after database capture, without editing original files. + try + { + for (int attempt = 0; attempt < 3; attempt++) + { + Assert.Throws(() => _session.Start(scenario)); + Assert.That(_session.Preview, Is.SameAs(previous)); + Assert.That(UnityEditor.SceneManagement.EditorSceneManager.previewSceneCount, Is.EqualTo(scenes)); + Assert.That(Resources.FindObjectsOfTypeAll().Count(value => value.name == "Battle audio preview"), Is.EqualTo(audioOwners)); + } + } + finally + { + foreach (DictionaryEntry archive in mounted) + archives.Add(archive.Key, archive.Value); + } + previous.Sample(.5f); + } + + [TestCase("POL")] + [TestCase("CVD")] + public void BattleCompositionSuppliesSceneLightingToModelEffects(string kind) + { + BattleScenario scenario = CreateScenario(); + scenario.ToonRendering = false; + _session.Start(scenario); + BattlePreview preview = _session.Preview; + var resources = (EffectResources)typeof(BattleEffectDirector) + .GetField("_resources", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview.Effects); + EffectDefinition definition = resources.Definitions.EffectDefinitions.First(value => value.IsValid && + EffectClass.Name(value.ClassNameCrc) == "model" && value.TextureName.EndsWith("." + kind, StringComparison.OrdinalIgnoreCase)); + resources.Definitions.Groups[0] = new EffectGroup + { + Objects = new[] + { + new EffectGroupObject { TypeCrc = definition.TypeNameCrc, Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 10 } } } + } + }; + preview.Effects.Start(new BattleEffectRequest(0, "model probe", Array.Empty(), default, 1)); + preview.Effects.Advance(1, .02f, .02f); + preview.View.Render(64, 64); + MeshRenderer[] renderers = preview.View.Root.transform.Find("Battle effect 0").GetComponentsInChildren(); + Assert.That(renderers, Is.Not.Empty, definition.TextureName); + Assert.That(renderers.SelectMany(renderer => renderer.sharedMaterials) + .All(material => material.GetFloat("_GbNativeLighting") == 1), Is.True, + "The BattlePreview composition root must pass its native scene-lighting owner to original model effects."); + } + + [TestCase(false)] + [TestCase(true)] + public void RepeatedStartSampleAndDisposeAreIsolatedAndRender(bool toon) + { + BattleScenario scenario = CreateScenario(); + scenario.ToonRendering = toon; + string original = JsonUtility.ToJson(scenario); + int actorId = scenario.Participants[0].ActorId; + int originalHp = _session.Data.Database.CombatActorInfos[actorId].AttributeValues[ActorAttributeType.Hp]; + int scenes = UnityEditor.SceneManagement.EditorSceneManager.previewSceneCount; + for (int i = 0; i < 20; i++) + { + _session.Start(scenario); + _session.Preview.Sample(0.7f); + Assert.That(UnityEditor.SceneManagement.EditorSceneManager.previewSceneCount, Is.EqualTo(scenes + 1)); + BattleScenario copy = _session.CapturedScenario; + copy.Participants[0].Attributes[0] = 999999; + Assert.That(_session.CapturedScenario.Participants[0].Attributes[0], Is.Not.EqualTo(999999)); + if (i == 0) + Capture(_session.Preview, toon); + _session.Stop(); + Assert.That(UnityEditor.SceneManagement.EditorSceneManager.previewSceneCount, Is.EqualTo(scenes)); + } + Assert.That(JsonUtility.ToJson(scenario), Is.EqualTo(original)); + Assert.That(_session.Data.Database.CombatActorInfos[actorId].AttributeValues[ActorAttributeType.Hp], Is.EqualTo(originalHp)); + } + + [Test] + public void RejectsOtherGameDataInBothDirections() + { + string current = _session.Data.Resources.Root; + string other = Path.Combine(Directory.GetParent(current).FullName, BattleData.Variant == "PAL3" ? "PAL3A" : "PAL3"); + if (!Directory.Exists(other)) + Assert.Ignore("Other game's data is not available."); + BattleData original = _session.Data; + Assert.Throws(() => _session.Load(other, 936)); + Assert.That(_session.Data, Is.SameAs(original)); + } + + [Test] + public void PartialModelFailureKeepsPreviousPoseAndDoesNotGrowNativeResources() + { + BattleScenario scenario = CreateScenario(); + _session.Start(scenario); + BattleParticipant actor = scenario.Participants[0]; + string path = _session.Data.ActionPath(actor, _session.Data.IdleAction(actor)); + Mv3File good = _session.Data.Read(path, new Mv3FileReader()); + Mv3Mesh invalid = good.Meshes[0]; + invalid.Attributes = invalid.Attributes.ToArray(); + invalid.Attributes[0].MaterialId = int.MaxValue; + var bad = new Mv3File(good.TotalGameBoxTicks, good.AnimationEvents, Array.Empty(), new[] { good.Meshes[0], invalid }, good.Materials); + var view = _session.Preview.View; + GameObject target = view.CreateObject("Failure recovery probe"); + var renderer = view.SetVertexModel(target, path, good); + int children = target.GetComponentsInChildren().Length; + Assert.Throws(() => view.SetVertexModel(target, path, bad)); + int meshes = Resources.FindObjectsOfTypeAll().Length; + int materials = Resources.FindObjectsOfTypeAll().Length; + int textures = Resources.FindObjectsOfTypeAll().Length; + for (int i = 0; i < 20; i++) + { + Assert.Throws(() => view.SetVertexModel(target, path, bad)); + Assert.That(target.GetComponentsInChildren().Length, Is.EqualTo(children)); + Assert.That(target.GetComponentInChildren(), Is.SameAs(renderer)); + renderer.SampleAnimation(0.1f); + } + Assert.That(Resources.FindObjectsOfTypeAll().Length, Is.EqualTo(meshes)); + Assert.That(Resources.FindObjectsOfTypeAll().Length, Is.EqualTo(materials)); + Assert.That(Resources.FindObjectsOfTypeAll().Length, Is.EqualTo(textures)); + view.SetVertexModel(target, path, good).SampleAnimation(0.2f); + Assert.That(target.GetComponentsInChildren().Length, Is.EqualTo(children)); + } + +#if PAL3A + [TestCase(false)] + [TestCase(true)] + public void Combo507ReleasesOnlyItsOwnActorsOnCompletionOrStop(bool stopEarly) + { + BattleScenario scenario = CreateScenario(); + scenario.Participants.RemoveAll(actor => actor.Side == BattleSide.Ally); + BattleParticipant first = _session.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + BattleParticipant second = _session.Data.CreateParticipant(103, BattleSide.Ally, BattleSlot.Fire); + BattleParticipant third = _session.Data.CreateParticipant(104, BattleSide.Ally, BattleSlot.Wind); + scenario.Participants.AddRange(new[] { first, second, third }); + _session.StartBattle(scenario); + BattleSession battle = _session.Battle; + BattleEffectDirector effects = _session.Preview.Effects; + var request = new BattleEffectRequest(957, first.InstanceId, Array.Empty(), default, 1); + int frame = 0; + void Advance() => effects.Advance(++frame, (float)BattleSession.StepSeconds, (float)BattleSession.StepSeconds); + + // Combo 507 invokes group 957 through group 1014. One action node + // controls slots 3 and 0, and two other nodes control slot 2. + long handle = effects.Start(request); + for (int i = 0; i < 8; i++) + { + Advance(); + } + Assert.That(battle.IsActorExternallyControlled(first.InstanceId), Is.True); + Assert.That(battle.IsActorExternallyControlled(second.InstanceId), Is.True); + Assert.That(battle.IsActorExternallyControlled(third.InstanceId), Is.True); + + long overlapping = effects.Start(request); + for (int i = 0; i < 8; i++) + { + Advance(); + } + battle.SetEffectActorControlled(first.InstanceId, true); + battle.SetEffectActorControlled(first.InstanceId, false); + Assert.That(battle.IsActorExternallyControlled(first.InstanceId), Is.True); + battle.SetEffectActorControlled(second.InstanceId, true); + + if (stopEarly) + { + effects.Stop(handle); + } + else + { + while (effects.IsRunning(handle) && frame < 1000) + { + Advance(); + } + } + Assert.That(effects.IsRunning(handle), Is.False); + Assert.That(effects.IsRunning(overlapping), Is.True); + Assert.That(battle.IsActorExternallyControlled(third.InstanceId), Is.True); + effects.Stop(overlapping); + Assert.That(battle.IsActorExternallyControlled(first.InstanceId), Is.False); + Assert.That(battle.IsActorExternallyControlled(third.InstanceId), Is.False); + Assert.That(battle.IsActorExternallyControlled(second.InstanceId), Is.True); + battle.SetEffectActorControlled(second.InstanceId, false); + Assert.That(battle.IsActorExternallyControlled(second.InstanceId), Is.False); + } +#endif + +#if PAL3 + [Test] + public void ResultSparksUseTheActiveZiXuanWeaponVisibility() + { + BattleData data = _session.Data; + int actorId = Core.Contract.Constants.ActorConstants.MainActorCombatActorIdMap.Single(pair => (int)pair.Key == 3).Value; + BattleParticipant ziXuan = data.CreateParticipant(actorId, BattleSide.Ally, BattleSlot.Water); + ziXuan.Equipment[0] = data.Database.GameItemInfos.First(pair => (int)pair.Value.WeaponType == 3 && pair.Value.ApplicableActors.Contains((PlayerActorId)3)).Key; + BattleScenario scenario = CreateScenario(); + scenario.Participants.Clear(); + scenario.Participants.Add(ziXuan); + BattleParticipant enemy = data.CreateParticipant(data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(data, id)), BattleSide.Enemy, BattleSlot.Water); + enemy.Vitals[0] = 0; + scenario.Participants.Add(enemy); + _session.StartBattle(scenario); + _session.Preview.Audio.Muted = _session.Preview.Effects.Muted = true; + for (int tick = 0; tick < 20 && _session.ResultPresentation == null; tick++) + _session.StepBattle(); + Assert.That(_session.ResultPresentation, Is.Not.Null); + // An ended battle retains its external attachment state. Result + // bodies own their new action and do not inherit that override. + _session.Battle.SetEffectActorControlled(ziXuan.InstanceId, true); + _session.Battle.SetEffectActorWeapons(ziXuan.InstanceId, -1, -1); + Assert.That(_session.Battle.WeaponVisibility(ziXuan.InstanceId).Right, Is.False); + var renderer = _session.Preview.View.Root.transform.Find(ziXuan.InstanceId).GetComponentInChildren(); + Assert.That(renderer.RightWeaponVisible, Is.True); + for (int frame = 0; frame < 12; frame++) + { + _session.StepBattle(); + _session.Preview.View.Render(256, 192); + } + var sparks = (IList)typeof(BattlePreview).GetField("_weaponSparks", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(_session.Preview); + Assert.That(sparks.Count, Is.GreaterThan(0), "The visible result weapon must emit despite the frozen combat override."); + } +#endif + + private BattleScenario TaggedAuthoringScenario() + { + BattleScenario scenario = CreateScenario(); + scenario.Participants.Clear(); + var equipped = _session.Data.Database.GameItemInfos.Where(pair => pair.Value.Type == ItemType.Weapon) + .SelectMany(pair => pair.Value.ApplicableActors.Where(player => Core.Contract.Constants.ActorConstants.MainActorCombatActorIdMap.ContainsKey(player)) + .Select(player => (Item: pair.Key, Player: player))); + var tagged = equipped.First(entry => + { + string path = Core.Contract.Constants.FileConstants.GetWeaponModelFileVirtualPath(_session.Data.Database.GameItemInfos[entry.Item].ModelName); + if (_session.Data.Resources.Find(path) == null || _session.Data.Read(path, new Core.DataReader.Pol.PolFileReader()).TagNodes.Length < 2) + return false; + var actor = _session.Data.CreateParticipant(Core.Contract.Constants.ActorConstants.MainActorCombatActorIdMap[entry.Player], BattleSide.Ally, BattleSlot.Water); + return _session.Data.Read(_session.Data.ActionPath(actor, _session.Data.IdleAction(actor)), new Mv3FileReader()).TagNodes.Any(tag => tag.Name.Equals("tag_weapon1", StringComparison.OrdinalIgnoreCase)); + }); + BattleParticipant source = _session.Data.CreateParticipant(Core.Contract.Constants.ActorConstants.MainActorCombatActorIdMap[tagged.Player], BattleSide.Ally, BattleSlot.Water); + source.Equipment[0] = tagged.Item; + TestContext.WriteLine($"Tagged authoring actor={source.ActorId}, weapon={source.Equipment[0]}"); + scenario.Participants.Add(source); + scenario.Participants.Add(_session.Data.CreateParticipant(_session.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(_session.Data, id)), BattleSide.Enemy, BattleSlot.Water)); + return scenario; + } + + private static Dictionary WeaponPose(Mv3ModelRenderer renderer) + { + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + var type = typeof(Mv3ModelRenderer); + var tags = (Mv3TagNode[])type.GetField("_tagNodesInfo", fields).GetValue(renderer); + var entities = (Engine.Core.Abstraction.IGameEntity[])type.GetField("_tagNodes", fields).GetValue(renderer); + var weapon = (Core.DataReader.Pol.PolFile)type.GetField("_tagNodePolFile", fields).GetValue(renderer); + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (weapon == null) + return result; + for (int index = 0; index < tags.Length; index++) + { + string name = tags[index].Name; + if (!name.Equals("tag_weapon1", StringComparison.OrdinalIgnoreCase) && !name.Equals("tag_weapon2", StringComparison.OrdinalIgnoreCase) || + entities[index]?.NativeObject is not GameObject owner) + continue; + result.Add(name, weapon.TagNodes.Select(tag => + { + var matrix = tag.GameBoxTransformMatrix; + return owner.transform.TransformPoint(new Core.Primitives.GameBoxVector3(matrix.Tx, matrix.Ty, matrix.Tz).ToUnityPosition()); + }).ToArray()); + } + return result; + } + + private static bool SameWeaponPoints(Vector3[] first, Vector3[] second) => first.Length == second.Length && + first.Zip(second, (left, right) => Vector3.Distance(left, right) < .00001f).All(equal => equal); + + private static void AssertRetainedWeaponPoses(Mv3ModelRenderer renderer, params Dictionary[] allowed) + { + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + var blades = (IDictionary)typeof(Mv3ModelRenderer).GetField("_weaponBlades", fields).GetValue(renderer); + Assert.That(blades.Keys.Cast(), Is.EquivalentTo(allowed[0].Keys)); + foreach (DictionaryEntry pair in blades) + { + var blade = (WeaponBlade)pair.Value; + int count = (int)typeof(WeaponBlade).GetField("_count", fields).GetValue(blade); + var frames = (Vector3[][])typeof(WeaponBlade).GetField("_frames", fields).GetValue(blade); + Assert.That(count, Is.GreaterThanOrEqualTo(2)); + for (int frame = 0; frame < count; frame++) + Assert.That(allowed.Any(pose => pose.TryGetValue((string)pair.Key, out Vector3[] expected) && SameWeaponPoints(frames[frame], expected)), + Is.True, $"{pair.Key} retained frame {frame} includes a pose from the previous action."); + } + } + + [TestCase(false)] + [TestCase(true)] + public void AuthoringRestartsKeepOnlyTheFinalActionInEveryRetainedBladeFrame(bool attackPreview) + { + BattleScenario scenario = TaggedAuthoringScenario(); + BattleParticipant source = scenario.Participants[0]; + Vector3 home = _session.Data.Position(source, scenario.SceneElement); + scenario.Participants[1].OverridePosition = true; + scenario.Participants[1].Position = new BattlePoint { X = home.x + 10, Y = home.y, Z = home.z + 7 }; + _session.Start(scenario); + BattlePreview preview = _session.Preview; + Mv3ModelRenderer Renderer() => preview.View.Root.transform.Find(source.InstanceId).GetComponentInChildren(); + var idle = WeaponPose(Renderer()); + Assert.That(idle.ContainsKey("tag_weapon1"), Is.True); + Dictionary start = null; + if (attackPreview) + { + preview.PlayAttack(source.InstanceId, scenario.Participants[1].InstanceId); + start = WeaponPose(Renderer()); + } + else + { + string idleAction = _session.Data.IdleAction(source); + foreach (var action in _session.Data.Actions(source)) + { + if (string.IsNullOrEmpty(action.ActionName) || action.ActionName.Equals(idleAction, StringComparison.OrdinalIgnoreCase) || + !_session.Data.TryActionPath(source, action.ActionName, out _)) + continue; + preview.PlayAction(source.InstanceId, action.ActionName); + var pose = WeaponPose(Renderer()); + if (!pose.TryGetValue("tag_weapon1", out Vector3[] points) || SameWeaponPoints(idle["tag_weapon1"], points)) + continue; + start = pose; + TestContext.WriteLine("Restart action: " + action.ActionName); + break; + } + } + Assert.That(start, Is.Not.Null, "The fixture needs a genuinely different tagged action."); + Assert.That(start.ContainsKey("tag_weapon1"), Is.True); + Assert.That(SameWeaponPoints(idle["tag_weapon1"], start["tag_weapon1"]), Is.False, + "The final action's t=0 endpoints must differ from the idle endpoints."); + preview.View.Render(256, 192); + AssertRetainedWeaponPoses(Renderer(), start); + preview.Sample(.02f); + var next = WeaponPose(Renderer()); + preview.View.Render(256, 192); + AssertRetainedWeaponPoses(Renderer(), start, next); + } + + [Test] + public void AuthoringBladeClocksRewindAndRefreshClipChangesAtZero() + { + BattleScenario scenario = TaggedAuthoringScenario(); + _session.Start(scenario); + BattlePreview preview = _session.Preview; + string id = scenario.Participants[0].InstanceId; + var type = typeof(Game.Rendering.Renderer.Mv3ModelRenderer); + const BindingFlags fields = BindingFlags.NonPublic | BindingFlags.Instance; + Game.Rendering.Renderer.Mv3ModelRenderer Renderer() => preview.View.Root.transform.Find(id).GetComponentInChildren(); + double? Clock() => (double?)type.GetField("_lastWeaponClock", fields).GetValue(Renderer()); + preview.PlayAttack(id, scenario.Participants[1].InstanceId); + for (int frame = 1; frame <= 10; frame++) + { + preview.Sample(frame * .02f); + preview.View.Render(256, 192); + } + Assert.That(Clock(), Is.EqualTo((double)preview.Time)); + preview.Sample(0); + Assert.That(Clock(), Is.Null.Or.Zero); + var blades = (IDictionary)type.GetField("_weaponBlades", fields).GetValue(Renderer()); + foreach (Game.Rendering.Renderer.WeaponBlade blade in blades.Values) + Assert.That((int)typeof(Game.Rendering.Renderer.WeaponBlade).GetField("_count", fields).GetValue(blade), Is.LessThanOrEqualTo(2)); + preview.View.Render(256, 192); + // Swapping back to the equipped idle clip at the same zero time + // must publish its current attachment pose. + preview.PlayAction(id, _session.Data.IdleAction(scenario.Participants[0])); + Assert.That(Clock(), Is.Zero); + preview.View.Render(256, 192); + Assert.That(Renderer().TryGetRightWeaponBladeTip(out Vector3 actual), Is.True); + var tags = (Mv3TagNode[])type.GetField("_tagNodesInfo", fields).GetValue(Renderer()); + var entities = (Engine.Core.Abstraction.IGameEntity[])type.GetField("_tagNodes", fields).GetValue(Renderer()); + var weapon = (Core.DataReader.Pol.PolFile)type.GetField("_tagNodePolFile", fields).GetValue(Renderer()); + int right = Array.FindIndex(tags, tag => tag.Name.Equals("tag_weapon1", StringComparison.OrdinalIgnoreCase)); + var matrix = weapon.TagNodes[0].GameBoxTransformMatrix; + Vector3 point = new Vector3(-matrix.Tx, matrix.Ty, matrix.Tz) / 20; + Vector3 expected = ((GameObject)entities[right].NativeObject).transform.TransformPoint(point); + Assert.That(Vector3.Distance(actual, expected), Is.LessThan(.00001), "A t=0 clip swap must publish its new weapon pose."); + } + + [Test] + public void WeaponDrawingFlagsKeepTheLoadedGeometryAvailableForRestoration() + { + _session.Start(CreateScenario()); + var renderer = _session.Preview.View.Root.GetComponentsInChildren() + .First(actor => actor.GetComponentsInChildren().Length > 0); + MeshFilter[] meshes = renderer.GetComponentsInChildren() + .SelectMany(weapon => weapon.GetComponentsInChildren()).ToArray(); + Assert.That(meshes, Is.Not.Empty); + Mesh[] originals = meshes.Select(mesh => mesh.sharedMesh).ToArray(); + for (int iteration = 0; iteration < 8; iteration++) + { + renderer.SetWeaponVisibility(false, false); + Assert.That(meshes.All(mesh => mesh != null && mesh.sharedMesh != null && mesh.gameObject.activeInHierarchy), Is.True); + Assert.That(meshes.All(mesh => !mesh.GetComponent().enabled), Is.True); + renderer.SetWeaponVisibility(true, true); + Assert.That(meshes.Select(mesh => mesh.sharedMesh), Is.EqualTo(originals)); + Assert.That(meshes.All(mesh => mesh.GetComponent().enabled), Is.True); + } + } + +#if PAL3A + [TestCase(101, 2)] + [TestCase(104, 10)] + public void ThrownWeaponRendersItsOwnModelAndRetainsGeometryAfterPickup(int actorId, int weaponType) + { + BattleData data = _session.Data; + BattleScenario scenario = CreateScenario(); + scenario.Encounter = BattleEncounter.AllyAmbush; + scenario.Participants.RemoveAt(2); + BattleParticipant source = data.CreateParticipant(actorId, BattleSide.Ally, BattleSlot.Water); + source.Equipment[0] = data.Database.GameItemInfos.First(pair => pair.Value.Type == Core.Contract.Enums.ItemType.Weapon && + (int)pair.Value.WeaponType == weaponType && pair.Value.ApplicableActors.Contains((PlayerActorId)(actorId - 101))).Key; + scenario.Participants[0] = source; + foreach (BattleParticipant participant in scenario.Participants) + { + participant.Attributes = new[] { 20000, 100, 100, 20, 1, 5, 0, 0, 0, 0, 0, 0 }; + participant.Vitals = new[] { 20000, 100, 100 }; + participant.Skills.Clear(); + } + _session.StartBattle(scenario); + for (int tick = 0; tick < 2000 && _session.Battle.WaitingActor != source.InstanceId; tick++) + _session.StepBattle(); + Assert.That(_session.Battle.WaitingActor, Is.EqualTo(source.InstanceId)); + Assert.That(_session.Battle.Submit(source.InstanceId, BattleAction.Attack, scenario.Participants[1].InstanceId), Is.True); + for (int tick = 0; tick < 400 && !_session.Battle.ThrownWeapons.Any(weapon => weapon.Active); tick++) + _session.StepBattle(); + BattleThrownWeaponSnapshot projectile = _session.Battle.ThrownWeapons.Single(); + Assert.That(projectile.Active, Is.True); + Transform model = _session.Preview.View.Root.transform.Find("Thrown weapon " + source.InstanceId); + Assert.That(model, Is.Not.Null); + MeshFilter[] meshes = model.GetComponentsInChildren(); + Assert.That(meshes, Is.Not.Empty); + Assert.That(meshes.All(mesh => mesh.sharedMesh != null && mesh.GetComponent().enabled), Is.True); + Assert.That(Vector3.Distance(model.position, BattleAnimationCatalog.UnityPosition(projectile.Position)), Is.LessThan(.00001)); + Capture(_session.Preview, false, "-thrown-" + weaponType); + for (int tick = 0; tick < 500 && _session.Battle.ThrownWeapons.Any(weapon => weapon.Active); tick++) + _session.StepBattle(); + Assert.That(_session.Battle.ThrownWeapons.Any(weapon => weapon.Active), Is.False); + Assert.That(meshes.All(mesh => mesh != null && mesh.sharedMesh != null && !mesh.GetComponent().enabled), Is.True); + Assert.That(_session.Battle.Status, Is.EqualTo(BattleSessionStatus.Running)); + } +#endif + + [Test] + public void RejectingCoincidentAttackPreviewKeepsTheCurrentActionAndTimeline() + { + BattleScenario scenario = CreateScenario(); + BattleParticipant source = scenario.Participants[0], target = scenario.Participants[1]; + source.OverridePosition = target.OverridePosition = true; + source.Position = target.Position = new BattlePoint(); + _session.Start(scenario); + BattlePreview preview = _session.Preview; + preview.PlayAction(source.InstanceId, _session.Data.AttackAction(source)); + preview.Sample(preview.Duration / 2); + float time = preview.Time, duration = preview.Duration; + + Assert.Throws(() => preview.PlayAttack(source.InstanceId, target.InstanceId)); + Assert.That(preview.Time, Is.EqualTo(time)); + Assert.That(preview.Duration, Is.EqualTo(duration)); + } + + [Test] + public void ExplicitAttackTargetsAndTimelineSamplingCanBeStoppedAndRestarted() + { + BattleScenario scenario = CreateScenario(); + _session.Start(scenario); + BattlePreview preview = _session.Preview; + string attacker = scenario.Participants[0].InstanceId; + string target = scenario.Participants[1].InstanceId; + Assert.Throws(() => preview.PlayAttack(attacker, "missing")); + Assert.Throws(() => preview.PlayAttack(attacker, attacker)); + preview.PlayAttack(attacker, target); + foreach (float fraction in new[] { 0f, 0.5f, 1f, 0.25f, 0f }) + preview.Sample(preview.Duration * fraction); + _session.IsPlaying = true; + _session.Tick(0.02f); + Assert.That(preview.Time, Is.GreaterThan(0)); + scenario.Participants[0].Attributes[0] = 999999; + _session.Restart(); + Assert.That(_session.Preview.Time, Is.Zero); + Assert.That(_session.CapturedScenario.Participants[0].Attributes[0], Is.Not.EqualTo(999999)); + Assert.That(_session.IsPlaying, Is.False); + } + + private static void Capture(BattlePreview preview, bool toon, string suffix = "") + { + RenderTexture target = preview.View.Render(800, 600); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(800, 600, TextureFormat.RGB24, false); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, 800, 600), 0, 0); + image.Apply(); + Assert.That(image.GetPixels32().Select(pixel => (pixel.r, pixel.g, pixel.b)).Distinct().Take(100).Count(), Is.GreaterThan(20), "The scene and actors must render more than a clear color."); + string directory = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT") ?? Path.GetFullPath(Path.Combine(Application.dataPath, "../../workspace/Implementation/BattleEditor/QA")); + Directory.CreateDirectory(directory); + File.WriteAllBytes(Path.Combine(directory, BattleData.Variant + (toon ? "-toon" : "-original") + suffix + ".png"), image.EncodeToPNG()); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattlePreviewTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattlePreviewTests.cs.meta new file mode 100644 index 00000000..b1beec8c --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattlePreviewTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5ebface4325e24b1c85ef547db5b5a25 \ No newline at end of file diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleRandomExampleTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleRandomExampleTests.cs new file mode 100644 index 00000000..a7ade62f --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleRandomExampleTests.cs @@ -0,0 +1,257 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Core.Contract.Enums; + using NUnit.Framework; + using UnityEditor; + using UnityEngine; + using UnityEngine.TestTools; + using Random = System.Random; + + [Category("LocalGameData")] + public sealed class BattleRandomExampleTests + { + private BattleData _data; + private BattleRandomExampleBuilder _builder; + + [OneTimeSetUp] + public void Load() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original game data is required."); + _data = new BattleData(root, 936); + _builder = new BattleRandomExampleBuilder(_data); + } + + [OneTimeTearDown] + public void Dispose() => _data?.Dispose(); + + [Test] + public void ManualRosterCandidatesMatchCombatSidesAndSearchOriginalNames() + { + MethodInfo candidates = typeof(BattleEditorWindow).GetMethod("RosterCandidates", BindingFlags.Static | BindingFlags.NonPublic); + foreach (BattleSide side in Enum.GetValues(typeof(BattleSide))) + { + int[] ids = (int[])candidates.Invoke(null, new object[] { _data, side, "", Array.Empty() }); + int[] expected = _data.Database.CombatActorInfos.Where(pair => pair.Key > 0 && + (side == BattleSide.Ally ? pair.Value.Type == CombatActorType.MainActor && BattleData.PlayerIdentity(pair.Key) >= 0 : + pair.Value.Type != CombatActorType.MainActor)).Select(pair => pair.Key).OrderBy(id => id).ToArray(); + Assert.That(ids, Is.EqualTo(expected)); + Assert.That(ids, Is.Not.Empty); + string name = _data.Database.CombatActorInfos[ids[0]].Name; + Assert.That((int[])candidates.Invoke(null, new object[] { _data, side, name, Array.Empty() }), Does.Contain(ids[0])); + BattleParticipant existing = _data.CreateParticipant(ids[0], side, BattleSlot.Water); + int[] available = (int[])candidates.Invoke(null, new object[] { _data, side, name, new[] { existing } }); + Assert.That(available.Contains(ids[0]), Is.EqualTo(side == BattleSide.Enemy)); + } + } + + [Test] + public void ImportedOppositeSideRosterIsRejectedBeforeCreatingBattlePreview() + { + BattleScenario scenario = _builder.Create(new Random(13)); + BattleParticipant main = scenario.Participants.First(actor => actor.Side == BattleSide.Ally); + BattleParticipant monster = scenario.Participants.First(actor => actor.Side == BattleSide.Enemy); + (main.Side, monster.Side) = (monster.Side, main.Side); + (main.Slot, monster.Slot) = (monster.Slot, main.Slot); + Assert.That(_data.Validate(scenario), Is.Empty); + using var session = new BattleEditorSession(); + session.Load(_data.Resources.Root, 936); + ArgumentException error = Assert.Throws(() => session.StartBattle(scenario)); + Assert.That(error.Message, Does.Contain(main.ActorId.ToString())); + Assert.That(error.Message, Does.Contain(monster.ActorId.ToString())); + Assert.That(session.Preview, Is.Null); + Assert.That(session.Battle, Is.Null); + } + + [Test] + public void ImportedDuplicateMainActorCanBePreviewedButCannotStartABattle() + { + BattleScenario scenario = _builder.Create(new Random(13)); + BattleParticipant main = scenario.Participants.First(actor => actor.Side == BattleSide.Ally); + BattleParticipant other = scenario.Participants.First(actor => actor.Side == BattleSide.Ally && actor != main); + BattleParticipant duplicate = main.Copy(); + duplicate.InstanceId = other.InstanceId; + duplicate.Slot = other.Slot; + scenario.Participants[scenario.Participants.IndexOf(other)] = duplicate; + scenario = BattleScenarioJson.Deserialize(BattleScenarioJson.Serialize(scenario)); + + Assert.That(_data.Validate(scenario), Is.Empty); + using var session = new BattleEditorSession(); + session.Load(_data.Resources.Root, 936); + ArgumentException error = Assert.Throws(() => session.StartBattle(scenario)); + Assert.That(error.Message, Does.Contain($"{main.ActorId}:同一主角只能参加一次战斗")); + Assert.That(session.Preview, Is.Null); + Assert.That(session.Battle, Is.Null); + } + + [Test] + public void RandomExamplesUseFourFullyEquippedAlliesSlightlyAboveTheEnemyLevel() + { + var scenes = new HashSet(); + var allies = new HashSet(); + var enemies = new HashSet(); + var levels = new HashSet(); + var weapons = new HashSet(); + for (int seed = 0; seed < 128; seed++) + { + BattleScenario scenario = _builder.Create(new Random(seed)); + Assert.That(_data.Validate(scenario, forBattle: true), Is.Empty, "seed " + seed); + scenes.Add(scenario.Scene); + BattleParticipant[] team = scenario.Participants.Where(actor => actor.Side == BattleSide.Ally).ToArray(); + BattleParticipant[] opponents = scenario.Participants.Where(actor => actor.Side == BattleSide.Enemy).ToArray(); + Assert.That(team.Length, Is.EqualTo(4)); + Assert.That(opponents.Length, Is.InRange(1, 6)); + Assert.That(team.Select(actor => actor.ActorId).Distinct().Count(), Is.EqualTo(team.Length)); + Assert.That(opponents.Select(actor => actor.Level).Distinct().Count(), Is.EqualTo(1)); + Assert.That(team.Select(actor => actor.Level), Is.All.EqualTo(Math.Min(100, opponents[0].Level + 3))); + Assert.That(scenario.ToonRendering, Is.True); + levels.Add(team[0].Level); + foreach (var actor in team) + allies.Add(actor.ActorId); + foreach (var actor in opponents) + enemies.Add(actor.ActorId); + BattleSetup setup = _data.Capture(scenario); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, setup); + Assert.That(scenario.Items.Select(item => item.Id), Is.EquivalentTo(definitions.Items.Values + .Where(item => item.BattleUsable && item.Supported).Select(item => item.Id))); + Assert.That(scenario.Items.Select(item => item.Count), Is.All.EqualTo(99)); + foreach (BattleParticipant actor in team) + { + weapons.Add(actor.Equipment[0]); + Assert.That(actor.Equipment, Has.Length.EqualTo(6)); + Assert.That(actor.Equipment, Is.All.GreaterThan(0)); + Assert.That(actor.Statuses, Is.Empty, "Only equipment effects may add statuses."); + BattleActorDefinition compiled = definitions.Actors[actor.InstanceId]; + Assert.That(compiled.UnsupportedReason, Is.Empty); + Assert.That(compiled.Equipment.Select(item => item.UnsupportedReason), Is.All.Empty); + foreach (int id in actor.Equipment) + Assert.That(_data.Database.GameItemInfos[id].ApplicableActors.Select(identity => (int)identity), + Does.Contain(BattleData.PlayerIdentity(actor.ActorId))); + Assert.That(actor.Experience, Is.EqualTo(_data.Layout.LevelExperienceTable[actor.Level])); + Assert.That(actor.AttributeSource, Is.EqualTo(BattleAttributeSource.LevelGrowth)); + Assert.That(actor.Attributes, Is.EqualTo(BattleAttributeCalculator.Calculate(actor, definitions.Actors[actor.InstanceId], scenario.Variant))); + Assert.That(actor.Vitals, Is.EqualTo(actor.Attributes.Take(3))); + } + var catalog = new BattleAnimationCatalog(_data, setup, definitions); + var battle = new BattleSession(setup, catalog, definitions: definitions); + Assert.That(battle.Status, Is.EqualTo(BattleSessionStatus.Running), "seed " + seed); + battle.Step(); + Assert.That(battle.Status, Is.EqualTo(BattleSessionStatus.Running), "seed " + seed); + } + Assert.That(scenes.Count, Is.GreaterThan(8)); + Assert.That(allies.Count, Is.EqualTo(5)); + Assert.That(enemies.Count, Is.GreaterThan(20)); + Assert.That(levels.Count, Is.GreaterThan(10)); + Assert.That(weapons.Count, Is.GreaterThan(10)); + } + + [UnityTest] + public IEnumerator AutomaticMusicSurvivesPreviewRefreshAndSharesTransportWithRealBattle() + { + BattleScenario scenario = _builder.Create(new Random(871)); +#if PAL3 + scenario.Scene = "z39"; +#else + scenario.Scene = "q09"; +#endif + BattleSetup setup = _data.Capture(scenario); + using var preview = new BattlePreview(_data, setup); + const BindingFlags members = BindingFlags.Instance | BindingFlags.NonPublic; + var pending = (IDictionary)typeof(BattleAudioPreview).GetField("_pending", members).GetValue(preview.Audio); + double until = EditorApplication.timeSinceStartup + 15; + while (pending.Count > 0 && EditorApplication.timeSinceStartup < until) + yield return null; + Assert.That(pending.Count, Is.Zero); + Assert.That(preview.Audio.Diagnostics, Is.Empty); + var root = (GameObject)typeof(BattleAudioPreview).GetField("_root", members).GetValue(preview.Audio); + AudioSource music = root.GetComponentsInChildren().Single(); + Assert.That(music.clip.samples, Is.GreaterThan(48000)); + Assert.That(music.loop, Is.True); + preview.Sample(2.5f); + Assert.That(preview.Diagnostics.Any(message => message.Contains("Editor fallback")), Is.True); + Assert.That(typeof(BattleAudioPreview).GetField("_time", members).GetValue(preview.Audio), Is.EqualTo(2.5d)); + preview.Audio.PlaybackEnabled = true; + double started = EditorApplication.timeSinceStartup; + while (EditorApplication.timeSinceStartup - started < .3) + { + preview.Sample(2.5f + (float)(EditorApplication.timeSinceStartup - started)); + yield return null; + } + Assert.That(music.time, Is.InRange(2.5f, 3.1f), "Animation preview must advance the same logical clock as music."); + preview.Audio.PlaybackEnabled = false; + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, setup); + var catalog = new BattleAnimationCatalog(_data, setup, definitions); + var battle = new BattleSession(setup, catalog, definitions: definitions, effects: preview.Effects); + preview.BindBattle(battle, catalog); + preview.ApplyBattle(battle, catalog); + Assert.That(root.GetComponentsInChildren().Single(), Is.SameAs(music), "Binding a real battle must not restart the common music owner."); + Assert.That(preview.Diagnostics.Any(message => message.Contains("Editor fallback")), Is.True); + preview.Audio.Diagnostics.Add("missing explicit music fixture"); + preview.ApplyBattle(battle, catalog); + Assert.That(preview.Diagnostics, Does.Contain("missing explicit music fixture")); + } + + [Test] + public void SameAuthoringSeedReproducesRosterAndSceneWithoutMutatingData() + { + BattleScenario first = _builder.Create(new Random(871)); + BattleScenario second = _builder.Create(new Random(871)); + Assert.That(second.Scene, Is.EqualTo(first.Scene)); + Assert.That(second.Seed, Is.EqualTo(first.Seed)); + Assert.That(second.Participants.Select(actor => (actor.ActorId, actor.Side, actor.Slot, actor.Level)), + Is.EqualTo(first.Participants.Select(actor => (actor.ActorId, actor.Side, actor.Slot, actor.Level)))); + Assert.That(second.Participants.SelectMany(actor => actor.Equipment), Is.EqualTo(first.Participants.SelectMany(actor => actor.Equipment))); + first.Participants[0].Attributes[0] = 987654; + Assert.That(_builder.Create(new Random(871)).Participants[0].Attributes[0], Is.Not.EqualTo(987654)); + } + + [Test] + public void MusicUsesVerifiedCityMappingAndDocumentsMissingContext() + { + var diagnostics = new List(); + var scenario = new BattleScenario + { +#if PAL3 + Scene = "z01" +#else + Scene = "m01a" +#endif + }; + Assert.That(BattleMusicResolver.Resolve(_data, scenario, diagnostics).ToUpperInvariant(), +#if PAL3 + Is.EqualTo("PI24")); +#else + Is.EqualTo("P54")); +#endif + Assert.That(diagnostics, Is.Empty); +#if PAL3 + scenario.Scene = "z08"; + Assert.That(BattleMusicResolver.Resolve(_data, scenario, diagnostics).ToUpperInvariant(), Is.EqualTo("PI24").Or.EqualTo("PI26").Or.EqualTo("PI26A")); + Assert.That(diagnostics, Has.Count.EqualTo(1)); + diagnostics.Clear(); + scenario.Scene = "z39"; +#else + scenario.Scene = "q09"; +#endif + Assert.That(BattleMusicResolver.Resolve(_data, scenario, diagnostics), Is.Not.Empty); + Assert.That(diagnostics, Has.Count.EqualTo(1)); + scenario.Music = "SpecialBoss.mp3"; + Assert.That(BattleMusicResolver.Resolve(_data, scenario, diagnostics), Is.EqualTo("SpecialBoss.mp3")); + scenario.Music = "NONE"; + Assert.That(BattleMusicResolver.Resolve(_data, scenario, diagnostics), Is.EqualTo("NONE")); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleRandomExampleTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleRandomExampleTests.cs.meta new file mode 100644 index 00000000..736c179f --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleRandomExampleTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0c9a0f8a0ceb4b1999be6f5a2326ea84 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleResultPresentationIntegrationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleResultPresentationIntegrationTests.cs new file mode 100644 index 00000000..d7f83d4e --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleResultPresentationIntegrationTests.cs @@ -0,0 +1,388 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Collections; + using System.Collections.Generic; + using System.Reflection; + using System.Linq; + using Battle; + using Core.Contract.Enums; + using Game.Rendering.Native; + using Game.Rendering.Renderer; + using NUnit.Framework; + using UnityEngine; + + [Category("LocalGameData")] + public sealed class BattleResultPresentationIntegrationTests + { + + private static BattleEditorSession Start(bool flee, int enemies = 1, bool deadAlly = false, bool toon = false, + BattleEncounter encounter = BattleEncounter.AllyAmbush) + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Original game data is required for result presentation verification."); + var session = new BattleEditorSession(); + try + { + session.Load(root, 936); + BattleData data = session.Data; + BattleParticipant ally = data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + ally.InstanceId = "A"; + ally.Level = 100; + ally.Attributes[5] = 20; + ally.Attributes[6] = 100; + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + DataFingerprint = data.Fingerprint, + Scene = data.Scenes.First(), + Encounter = encounter, + ToonRendering = toon + }; + scenario.Participants.Add(ally); + if (deadAlly) + { + BattleParticipant dead = data.CreateParticipant(102, BattleSide.Ally, BattleSlot.Fire); + dead.InstanceId = "D"; + dead.Vitals[0] = 0; + scenario.Participants.Add(dead); + } + int enemyId = data.Database.CombatActorInfos.First(pair => pair.Value.Type != CombatActorType.MainActor && pair.Value.NormalLoot > 0 && pair.Value.NormalLootCount > 0).Key; + for (int index = 0; index < enemies; index++) + { + BattleParticipant enemy = data.CreateParticipant(enemyId, BattleSide.Enemy, index == 0 ? BattleSlot.Water : BattleSlot.Fire); + enemy.InstanceId = "E" + index; + if (!flee) + enemy.Vitals[0] = 0; + scenario.Participants.Add(enemy); + } + session.StartBattle(scenario); + session.Preview.Audio.Muted = true; + session.Preview.Effects.Muted = true; + if (flee) + { + Assert.That(session.Battle.Submit("A", BattleAction.Flee), Is.True); + for (int tick = 0; tick < 5000 && session.Battle.Status == BattleSessionStatus.Running; tick++) + session.Battle.Step(); + Assert.That(session.Battle.Result.Escaped, Is.True); + session.SyncBattle(); + } + return session; + } + catch + { + session.Dispose(); + throw; + } + } + + private static IDictionary Clips(BattleAudioPreview audio) => + (IDictionary)typeof(BattleAudioPreview).GetField("_clips", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(audio); + + private static IDictionary Requests(BattleAudioPreview audio) => + (IDictionary)typeof(BattleAudioPreview).GetField("_desired", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(audio); + + private static BattleResultRoleBody ResultBody(BattlePreview preview, string actor) => + (BattleResultRoleBody)((IDictionary)typeof(BattlePreview).GetField("_resultBodies", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview))[actor]; + + private static object ActorView(BattlePreview preview, string actor) => + ((IDictionary)typeof(BattlePreview).GetField("_actors", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview))[actor]; + + private static bool ActorVisible(BattlePreview preview, string actor) + { + object view = ActorView(preview, actor); + return (bool)view.GetType().GetField("Visible").GetValue(view); + } + + private static Mv3ModelRenderer ActorRenderer(BattlePreview preview, string actor) + { + object view = ActorView(preview, actor); + return (Mv3ModelRenderer)view.GetType().GetField("Renderer").GetValue(view); + } + + private static float ActorOpacity(BattlePreview preview, string actor) => + (float)typeof(Mv3ModelRenderer).GetField("_opacity", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ActorRenderer(preview, actor)); + + [Test] + public void VictoryAfterEnemyAmbushFacesThePartyFormation() + { + using BattleEditorSession session = Start(false, encounter: BattleEncounter.EnemyAmbush); + Transform body = ActorRenderer(session.Preview, "A").transform; + Quaternion formation = Quaternion.Euler(0, -BattleFacingRules.Initial(BattleSide.Ally), 0); + Assert.That(Quaternion.Angle(body.rotation, formation), Is.EqualTo(180).Within(.01f)); + session.StepBattle(); + Assert.That(session.ResultPresentation, Is.Not.Null); + Assert.That(Quaternion.Angle(ActorRenderer(session.Preview, "A").transform.rotation, formation), Is.LessThan(.01f)); + } + + [TestCase(false)] + [TestCase(true)] + public void ResultBodyClipChangesRetainTheCapturedExternalBlend(bool toon) + { + using BattleEditorSession session = Start(false, toon: toon); + session.Battle.SetEffectActorBlend("A", .2f); + session.StepBattle(); + Assert.That(session.ResultPresentation, Is.Not.Null); + Assert.That(ActorOpacity(session.Preview, "A"), Is.EqualTo(.2f).Within(.00001f)); + Mv3ModelRenderer before = ActorRenderer(session.Preview, "A"); + session.StepBattle(); + Assert.That(ActorRenderer(session.Preview, "A"), Is.Not.SameAs(before), "Victory starts its own body clip."); + Assert.That(session.Battle.EffectActor("A").Blend, Is.EqualTo(.2f).Within(.00001f)); + session.Preview.View.Render(800, 600); + Material[] materials = ActorRenderer(session.Preview, "A").GetComponentsInChildren() + .SelectMany(renderer => renderer.sharedMaterials).Where(material => material.HasProperty("_TintColor")).ToArray(); + Assert.That(materials, Is.Not.Empty); + Assert.That(materials.All(material => Math.Abs(material.GetColor("_TintColor").a - .2f) < .00001f), Is.True, + "The rendered body and attachments retain the captured alpha after replacing their clip."); + Assert.That(ActorOpacity(session.Preview, "A"), Is.EqualTo(.2f).Within(.00001f)); + } + + private static int ShadowCount(BattlePreview preview) => + ((GameBoxBattleShadowRenderer)typeof(BattlePreview).GetField("_shadows", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview)).Count; + + private static void ReplayResults(BattleEditorSession session) + { + BattleSession original = session.Battle; + session.ReplayResults(); + Assert.That(session.Battle, Is.SameAs(original), "Result replay must be queued."); + MethodInfo tick = typeof(BattleEditorSession).GetMethod("TickReplay", BindingFlags.Instance | BindingFlags.NonPublic); + for (int slice = 0; slice < 5000 && session.Battle == original; slice++) + tick.Invoke(session, null); + Assert.That(session.Battle, Is.Not.SameAs(original)); + } + + [Test] + public void ResultRecreatesAnActorViewWhenItHasNotBeenBound() + { + using BattleEditorSession session = Start(true); + BattlePreview preview = session.Preview; + var flags = BindingFlags.Instance | BindingFlags.NonPublic; + var actors = (IDictionary)typeof(BattlePreview).GetField("_actors", flags).GetValue(preview); + object old = actors["A"]; + preview.View.ReleaseCompositeObject((GameObject)old.GetType().GetField("Object").GetValue(old)); + actors.Remove("A"); + + var catalog = (BattleAnimationCatalog)typeof(BattleEditorSession).GetField("_battleCatalog", flags).GetValue(session); + preview.BeginResultPresentation(session.Battle, catalog, session.ResultPresentation); + Assert.That(ActorView(preview, "A"), Is.Not.SameAs(old)); + Assert.That(ActorRenderer(preview, "A"), Is.Not.Null); + session.StepBattle(); + Assert.That(ResultBody(preview, "A"), Is.Not.Null); + } + + [Test] + public void OriginalFleeRetainsDeadAllyHpPoseVisibilityAndShadowUntilPresentationCompletes() + { + using BattleEditorSession session = Start(true, deadAlly: true); + BattleResult final = session.Battle.Result; + BattleActorSnapshot before = final.PreSettlementActors.Single(actor => actor.Id == "D"); + BattleActorSnapshot after = final.Actors.Single(actor => actor.Id == "D"); + Assert.That(before.Hp, Is.Zero); + Assert.That(after.Hp, Is.EqualTo(BattleData.Variant == "PAL3A" ? 1 : 0)); + Assert.That(after.AliveFlag, Is.False); + Assert.That(after.ModelAliveFlag, Is.False); + Assert.That(after.States.Select(state => state.State), Is.EqualTo(before.States.Select(state => state.State))); + int events = session.Battle.Events.Count; + int money = session.Battle.Money; + for (int pass = 0; pass < 10; pass++) + { + Assert.That(session.ResultPresentation.Actors.Single(actor => actor.Id == "D").Hp, Is.Zero, "Statistics/body use presentation HP"); + Assert.That(ActorVisible(session.Preview, "D"), Is.False, "Hidden even before first result step"); + object view = ActorView(session.Preview, "D"); + var root = (GameObject)view.GetType().GetField("Object").GetValue(view); + Assert.That(root.GetComponentsInChildren(true).Any(renderer => renderer.enabled), Is.False); + Assert.That(ShadowCount(session.Preview), Is.EqualTo(2), "Only live ally and enemy cast shadows"); + session.StepBattle(); + Assert.That(ResultBody(session.Preview, "D").Binding.RequestedNativeActionIndex, Is.EqualTo(47)); + } + for (int frame = 0; frame < 1000 && !session.ResultPresentation.Completed; frame++) + { + session.StepBattle(); + session.SkipResultStep(); + } + Assert.That(session.ResultPresentation.Completed, Is.True); + Assert.That(session.ResultPresentation.Actors.Single(actor => actor.Id == "D").Hp, Is.EqualTo(after.Hp)); + Assert.That(ActorVisible(session.Preview, "D"), Is.EqualTo(BattleData.Variant == "PAL3A")); + Assert.That(ShadowCount(session.Preview), Is.EqualTo(BattleData.Variant == "PAL3A" ? 3 : 2)); + Assert.That(session.Battle.Events.Count, Is.EqualTo(events)); + Assert.That(session.Battle.Money, Is.EqualTo(money)); + ReplayResults(session); + session.Preview.Audio.Muted = true; + session.Preview.Effects.Muted = true; + Assert.That(session.ResultPresentation.Actors.Single(actor => actor.Id == "D").Hp, Is.Zero); + Assert.That(ActorVisible(session.Preview, "D"), Is.False); + Assert.That(ShadowCount(session.Preview), Is.EqualTo(2)); + session.StepBattle(); + Assert.That(ResultBody(session.Preview, "D").Binding.RequestedNativeActionIndex, Is.EqualTo(47)); + Assert.That(session.Battle.Events.Count, Is.EqualTo(events)); + } + + [Test] + public void WinPresentsRecoveredHpBeforeItsTasksAndReturnsRecoveredAllyToNativeDyingAction() + { + using BattleEditorSession session = Start(false, deadAlly: true); + session.StepBattle(); + Assert.That(session.Battle.Result.PreSettlementActors.Single(actor => actor.Id == "D").Hp, Is.Zero); + Assert.That(session.Battle.Result.Actors.Single(actor => actor.Id == "D").Hp, Is.EqualTo(1)); + Assert.That(session.ResultPresentation.Actors.Single(actor => actor.Id == "D").Hp, Is.EqualTo(1)); + Assert.That(ActorVisible(session.Preview, "D"), Is.True); + Assert.That(ShadowCount(session.Preview), Is.EqualTo(2), "Both recovered/living allies cast shadows; dead enemy does not"); + BattleResultRoleBody body = ResultBody(session.Preview, "D"); + for (int frame = 0; frame < 1000 && body.Binding.RequestedNativeActionIndex != 46; frame++) + session.StepBattle(); + Assert.That(body.Binding.RequestedNativeActionIndex, Is.EqualTo(46)); + Assert.That(session.Battle.Result.Actors.Single(actor => actor.Id == "D").AliveFlag, Is.False); + Assert.That(session.Battle.Result.Actors.Single(actor => actor.Id == "D").ModelAliveFlag, Is.False); + } + + [TestCase(false)] + [TestCase(true)] + public void FinalFleeWaitReleasesSilentMusicForTimedAndSkippedCompletion(bool skip) + { + using BattleEditorSession session = Start(true); + Clips(session.Preview.Audio).Add("music:silent.mp3", AudioClip.Create("silent result test", 48000, 1, 48000, false)); + session.Preview.Audio.SetMusic("silent"); + while (session.ResultPresentation.Index < session.ResultPresentation.Sequence.Count - 1) + { + session.StepBattle(); + session.SkipResultStep(); + } + session.StepBattle(); + IDictionary desired = Requests(session.Preview.Audio); + Assert.That(desired.Count, Is.GreaterThanOrEqualTo(1)); + if (skip) + Assert.That(session.SkipResultStep(), Is.True); + else + for (int tick = 0; tick < 1000 && !session.ResultPresentation.Completed; tick++) + session.StepBattle(); + Assert.That(session.ResultPresentation.Completed, Is.True); + Assert.That(desired.Count, Is.Zero); + session.IsPlaying = true; + session.Tick(1); + Assert.That(session.IsPlaying, Is.False); + Assert.That(session.Preview.Audio.PlaybackEnabled, Is.False); + Assert.That(desired.Count, Is.Zero); + } + + [Test] + public void SeparateLootAwardsRequestSeparateMutedSoundsAtRegistrationTime() + { + using BattleEditorSession session = Start(false, 2); + Clips(session.Preview.Audio).Add("wa006.wav", AudioClip.Create("silent loot test", 48000, 1, 48000, false)); + session.StepBattle(); + BattleResultStep[] awards = session.ResultPresentation.Sequence.Where(step => step.Kind == BattleResultStepKind.Item).ToArray(); + Assert.That(awards.Length, Is.EqualTo(2)); + object[] requests = Requests(session.Preview.Audio).Values.Cast().Where(request => + (string)request.GetType().GetField("File").GetValue(request) == "wa006.wav").ToArray(); + Assert.That(requests.Length, Is.EqualTo(awards.Length)); + double time = session.Battle.Tick * BattleSession.StepSeconds; + Assert.That(requests.Select(request => (double)request.GetType().GetField("Start").GetValue(request)), Is.All.EqualTo(time).Within(1e-5)); + Assert.That(session.ResultPresentation.Tick, Is.Zero); + Assert.That(session.Preview.Audio.PlaybackEnabled, Is.False); + } + +#if PAL3A + [Test] + public void EveryOriginalAlliedWeaponTypeProvidesItsPublishedLevelUpAnimation() + { + string root = Environment.GetEnvironmentVariable("PAL3A_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Original game data is required for action59 verification."); + using var data = new BattleData(root, 936); + var verified = new HashSet<(int Identity, int Weapon)>(); + foreach (int id in data.Database.CombatActorInfos.Where(pair => pair.Value.Type == CombatActorType.MainActor).Select(pair => pair.Key)) + { + int identity = BattleData.PlayerIdentity(id); + foreach (int itemId in data.Database.GameItemInfos.Where(pair => pair.Value.Type == ItemType.Weapon && + pair.Value.ApplicableActors.Contains((PlayerActorId)identity)).GroupBy(pair => pair.Value.WeaponType).Select(group => group.First().Key)) + { + var scenario = new BattleScenario { Variant = BattleData.Variant, DataFingerprint = data.Fingerprint, Scene = data.Scenes.First() }; + BattleParticipant actor = data.CreateParticipant(id, BattleSide.Ally, BattleSlot.Water); + actor.Equipment[0] = itemId; + scenario.Participants.Add(actor); + scenario.Participants.Add(data.CreateParticipant(701, BattleSide.Enemy, BattleSlot.Water)); + BattleSetup setup = data.Capture(scenario); + var catalog = new BattleAnimationCatalog(data, setup); + BattlePhysicalAnimation animation = catalog.ResultBodyAnimations(setup.CreateInstance().Participants.First(participant => participant.Side == BattleSide.Ally))[59]; + int weapon = (int)data.Database.GameItemInfos[itemId].WeaponType; + verified.Add((identity, weapon)); + Assert.That(animation, Is.Not.Null, "actor " + id + ", weapon type " + weapon); + Assert.That(animation.Clip, Is.EqualTo(identity == 1 && weapon == 3 || identity == 4 && weapon == 8 ? "z162" : "z16")); + } + } + Assert.That(verified.Contains((1, 3)), Is.True); + Assert.That(verified.Contains((4, 8)), Is.True); + Assert.That(verified.Count, Is.GreaterThan(2)); + } +#endif + + [Test] + public void EndedCombatHasIndependentPausableResultClockAndReplayWithoutASecondRewardCommit() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Original game data is required for result presentation verification."); + using var session = new BattleEditorSession(); + session.Load(root, 936); + BattleData data = session.Data; + BattleParticipant ally = data.CreateParticipant(data.Database.CombatActorInfos.First(pair => pair.Value.Type == CombatActorType.MainActor).Key, + BattleSide.Ally, BattleSlot.Water); + BattleParticipant enemy = data.CreateParticipant(701, BattleSide.Enemy, BattleSlot.Water); + ally.InstanceId = "A"; + enemy.InstanceId = "E"; + enemy.Vitals[0] = 0; + var scenario = new BattleScenario { Variant = BattleData.Variant, DataFingerprint = data.Fingerprint, Scene = data.Scenes.First() }; + scenario.Participants.Add(ally); + scenario.Participants.Add(enemy); + session.StartBattle(scenario); + session.Preview.Audio.Muted = true; + session.Preview.Effects.Muted = true; + session.StepBattle(); + Assert.That(session.Battle.Status, Is.EqualTo(BattleSessionStatus.Completed)); + Assert.That(session.ResultPresentation, Is.Not.Null); + long combatTick = session.Battle.Tick; + int events = session.Battle.Events.Count; + int money = session.Battle.Money; + session.IsPlaying = true; + session.Tick(.2f); + long presentationTick = session.ResultPresentation.Tick; + Assert.That(presentationTick, Is.EqualTo(10)); + Assert.That(session.Battle.Tick, Is.EqualTo(combatTick)); + session.IsPlaying = false; + session.Tick(1); + Assert.That(session.ResultPresentation.Tick, Is.EqualTo(presentationTick)); + session.StepBattle(); + Assert.That(session.ResultPresentation.Tick, Is.EqualTo(presentationTick + 1)); + Assert.That(session.Preview.View.GetTexture("basedata.cpk\\ui\\combat\\result\\bigwin.tga").width, Is.EqualTo(256)); + foreach (string file in new[] { "back", "face/0", "face/HP", "face/GP", "face/MP", "face/SLOT", "face/HP-GP-MP", "panel/levelup", "panel/getitem", "panel/waterlvup", "panel/doublelvup" }) + Assert.That(session.Preview.View.GetTexture("basedata.cpk\\ui\\combat\\result\\" + file + ".tga"), Is.Not.Null, file); + session.Speed = 4; + session.IsPlaying = true; + for (int frame = 0; frame < 1000 && !session.ResultPresentation.Completed; frame++) + { + session.Tick(.1f); + session.SkipResultStep(); + } + Assert.That(session.ResultPresentation.Completed, Is.True); + Assert.That(session.IsPlaying, Is.False); + Assert.That(session.ResultPresentation.ScreenOpacity, Is.Zero); + Assert.That(session.Battle.Events.Count, Is.EqualTo(events)); + Assert.That(session.Battle.Money, Is.EqualTo(money)); + ReplayResults(session); + Assert.That(session.ResultPresentation.Tick, Is.Zero); + Assert.That(session.Battle.Tick, Is.EqualTo(combatTick)); + Assert.That(session.Battle.Money, Is.EqualTo(money)); + Assert.That(session.Battle.Events.Count, Is.EqualTo(events)); + Assert.That(session.Preview.Diagnostics.Where(message => message.Contains("Missing texture dependency")), Is.Empty); + session.Stop(); + Assert.That(session.ResultPresentation, Is.Null); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleResultPresentationIntegrationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleResultPresentationIntegrationTests.cs.meta new file mode 100644 index 00000000..0970be20 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleResultPresentationIntegrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d236f2c4968045f296351a89405c82e5 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleSceneAppearanceRenderingTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleSceneAppearanceRenderingTests.cs new file mode 100644 index 00000000..8cd33aab --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleSceneAppearanceRenderingTests.cs @@ -0,0 +1,390 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using NUnit.Framework; + using ResourceBrowser; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed class BattleSceneAppearanceRenderingTests + { + [TestCase(0f)] + [TestCase(.44f)] + [TestCase(1f)] + [Category("LocalGameData")] + public void PaintedBackgroundsIgnoreDynamicLightsAcrossFadesAndDoNotLeakThroughMaterialReuse(float opacity) + { + using var data = new BattleData(Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"), 936); +#if PAL3 + const string scene = "Z01"; +#else + const string scene = "M06A"; +#endif + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = scene, + DataFingerprint = data.Fingerprint, + ToonRendering = true, + Music = "NONE" + }; + scenario.Participants.Add(data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(data.CreateParticipant(data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(data, id)), BattleSide.Enemy, BattleSlot.Water)); + using var preview = new BattlePreview(data, new BattleSetup(scenario)); + var properties = new MaterialPropertyBlock(); + bool Background(MeshRenderer renderer) + { + renderer.GetPropertyBlock(properties); + return properties.GetFloat("_UnlitBackground") > .5f; + } + MeshRenderer[] all = preview.View.Root.GetComponentsInChildren(); + MeshRenderer[] backgrounds = all.Where(Background).ToArray(); + Assert.That(backgrounds, Is.Not.Empty); + Assert.That(all.Except(backgrounds), Is.Not.Empty, "The selection must not encompass the ground or bodies."); + foreach (MeshRenderer renderer in backgrounds) + { + Assert.That(renderer.shadowCastingMode, Is.EqualTo(UnityEngine.Rendering.ShadowCastingMode.Off)); + Assert.That(renderer.receiveShadows, Is.False); + } + var backgroundMaterials = backgrounds.SelectMany(renderer => renderer.sharedMaterials).ToHashSet(); + var environment = backgrounds[0].GetComponentInParent(); + environment.SetOpacity(opacity); + backgroundMaterials.UnionWith(backgrounds.SelectMany(renderer => renderer.sharedMaterials)); + foreach (MeshRenderer renderer in all) + renderer.enabled = Background(renderer); + FrameSelectedTriangle(preview.View, backgrounds[0]); + var camera = (Camera)typeof(ResourceModelPreview).GetField("_camera", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview.View); + camera.backgroundColor = UnityEngine.Color.clear; + Light light = preview.View.Root.GetComponentInChildren(); + light.intensity = 0; + Texture2D unlit = Read(preview.View.Render(400, 300)); + Texture2D bright = null; + try + { + light.intensity = 3; + light.transform.rotation = Quaternion.Euler(20, 130, 0); + light.color = UnityEngine.Color.red; + bright = Read(preview.View.Render(400, 300)); + Assert.That(bright.GetPixels32(), Is.EqualTo(unlit.GetPixels32()), "Painted backgrounds must not acquire light bands, AO shading or received shadows."); + if (opacity > 0) + Assert.That(unlit.GetPixels32().Count(pixel => pixel.a > 0), Is.GreaterThan(100), "The image comparison must actually contain background pixels."); + else + Assert.That(unlit.GetPixels32().All(pixel => pixel.a == 0), Is.True, "Zero opacity must remove the painted layer."); + } + finally + { + Object.DestroyImmediate(unlit); + Object.DestroyImmediate(bright); + } + string path = Core.Contract.Constants.FileConstants.CombatSceneFolderVirtualPath + scene + "\\" + scene + ".pol"; + var model = data.Read(path, new Core.DataReader.Pol.PolFileReader()); + // Replacement constructs its candidate before releasing the old environment. + // The second replacement can rent the original background materials. + preview.View.ReplaceEnvironment(data.Resources.Find(path), model); + preview.View.ReplaceEnvironment(data.Resources.Find(path), model); + MeshRenderer[] reused = preview.View.Root.transform.Find("Battle environment " + data.Resources.Find(path).Name).GetComponentsInChildren(); + Assert.That(reused.SelectMany(renderer => renderer.sharedMaterials).Any(backgroundMaterials.Contains), Is.True, + "This assertion must exercise materials actually returned by the background environment."); + foreach (MeshRenderer renderer in reused) + { + Assert.That(Background(renderer), Is.False); + Assert.That(renderer.sharedMaterials.All(material => material.GetFloat("_UnlitBackground") == 0), Is.True); + Assert.That(renderer.shadowCastingMode, Is.EqualTo(UnityEngine.Rendering.ShadowCastingMode.On)); + } + } + +#if PAL3A + [Test] + [Category("LocalGameData")] + public void PaintedFarWaterKeepsItsOpaquePolBlendAndCannotMixTheCameraClearColor() + { + using var data = new BattleData(Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"), 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = "m14a", + DataFingerprint = data.Fingerprint, + ToonRendering = true, + Music = "NONE" + }; + scenario.Participants.Add(data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(data.CreateParticipant(data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(data, id)), BattleSide.Enemy, BattleSlot.Water)); + using var preview = new BattlePreview(data, new BattleSetup(scenario)); + var group = preview.View.Root.GetComponentsInChildren().Single(presenter => + presenter.sources.Any(source => source.nodeName == "Plane02" && source.material.TextureFileNames.Contains("w0001.tga", StringComparer.OrdinalIgnoreCase))); + MeshRenderer water = group.GetComponent(); + Assert.That(water.sharedMaterial.shader.name, Is.EqualTo("Pal3/ToonOpaque"), "The source POL group is Opaque, despite its water-texture filename."); + foreach (MeshRenderer renderer in preview.View.Root.GetComponentsInChildren()) + renderer.enabled = renderer == water; + FrameSelectedTriangle(preview.View, water); + var camera = (Camera)typeof(ResourceModelPreview).GetField("_camera", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview.View); + camera.backgroundColor = UnityEngine.Color.red; + Texture2D red = Read(preview.View.Render(128, 128)); + Texture2D blue = null; + try + { + camera.backgroundColor = UnityEngine.Color.blue; + blue = Read(preview.View.Render(128, 128)); + UnityEngine.Color pixel = red.GetPixel(64, 64); + Assert.That(blue.GetPixel(64, 64), Is.EqualTo(pixel), "The painted opaque layer cannot leak the camera's bottom color."); + Assert.That(pixel.a, Is.EqualTo(1)); + Assert.That(pixel, Is.Not.EqualTo(UnityEngine.Color.red).And.Not.EqualTo(UnityEngine.Color.blue)); + } + finally + { + Object.DestroyImmediate(red); + Object.DestroyImmediate(blue); + } + } + + [TestCase(false)] + [TestCase(true)] + [Category("LocalGameData")] + public void ExplicitFloorNormalsKeepTheStandingSurfaceLitAndPreserveNativeAndAdjacentGroupNormals(bool toon) + { + using var data = new BattleData(Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"), 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = "M06B", + DataFingerprint = data.Fingerprint, + ToonRendering = toon, + Music = "NONE" + }; + scenario.Participants.Add(data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + scenario.Participants.Add(data.CreateParticipant(data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(data, id)), BattleSide.Enemy, BattleSlot.Water)); + using var preview = new BattlePreview(data, new BattleSetup(scenario)); + string geometry = Core.Contract.Constants.FileConstants.CombatSceneFolderVirtualPath + "M06B\\M06B.pol"; + var sourceMesh = data.Read(geometry, new Core.DataReader.Pol.PolFileReader()).Meshes[25]; + Vector3[] authoredNormals = sourceMesh.VertexInfo.GameBoxNormals.Select(normal => new Vector3(-normal.X, normal.Y, normal.Z)).ToArray(); + var selected = new List(); + var adjacent = new List(); + foreach (var presenter in preview.View.Root.GetComponentsInChildren()) + foreach (var source in presenter.sources.Where(source => source.nodeName == "Cylinder02")) + { + Vector3[] normals = presenter.GetComponent().sharedMesh.normals.Skip(source.vertexStart).Take(source.vertexCount).ToArray(); + if (source.materialGroupIndex is 0 or 1 && (!toon || source.materialGroupIndex == 1)) + { + var map = new Core.DataReader.Pol.PolMeshIndexMap(authoredNormals.Length, sourceMesh.Textures[source.materialGroupIndex].GameBoxTriangles); + Assert.That(normals.Length, Is.EqualTo(map.SourceIndices.Length)); + for (int index = 0; index < normals.Length; index++) + Assert.That(Vector3.Distance(normals[index], authoredNormals[map.SourceIndices[index]]), Is.LessThan(1e-6f), + "Native and unselected adjacent groups retain each original source normal."); + } + if (source.materialGroupIndex == 0 && source.material.TextureFileNames.Contains("di.tga", StringComparer.OrdinalIgnoreCase)) + { + selected.AddRange(normals); + var renderer = presenter.GetComponent(); + Assert.That(renderer.shadowCastingMode, Is.EqualTo(UnityEngine.Rendering.ShadowCastingMode.On)); + Assert.That(renderer.receiveShadows, Is.True); + var properties = new MaterialPropertyBlock(); + renderer.GetPropertyBlock(properties); + Assert.That(properties.GetFloat("_UnlitBackground"), Is.Zero); + } + else if (source.materialGroupIndex == 1 && source.material.TextureFileNames.Contains("bj.tga", StringComparer.OrdinalIgnoreCase)) + adjacent.AddRange(normals); + } + Assert.That(selected.Count, Is.GreaterThan(3)); + Assert.That(adjacent.Count, Is.GreaterThan(3)); + Assert.That(selected.All(normal => Vector3.Dot(normal, Vector3.up) > .999f), Is.EqualTo(toon), + "Only Toon reconstructs this verified horizontal floor; Native retains the released vertex normals."); + Assert.That(adjacent.Any(normal => Vector3.Dot(normal, Vector3.up) < .9f), Is.True, + "The adjacent painted horizon must not inherit the floor's normal reconstruction."); + } +#endif + + [TestCase(.25f, .99f, 1f, 1f, false, true)] + [TestCase(.6f, .99f, 1f, 1f, false, true)] + [TestCase(.8f, .35f, 1f, 1f, false, true)] + [TestCase(.8f, .99f, .44f, .6f, false, true)] + [TestCase(.95f, 1f, 1f, 1f, false, true)] + [TestCase(.6f, 1f, .75f, 1f, true, true)] + [TestCase(.6f, 1f, .75f, 1f, true, false)] + [TestCase(.2f, .2f, 1f, .5f, true, true)] + public void PaintedTransparentStagesMatchNativeRgbAlphaAndPostStageClassificationOnGpu( + float textureAlpha, float diffuseAlpha, float tintAlpha, float bakedAlpha, bool vertexColors, bool baked) + { + using var preview = new ResourceModelPreview(null, false); + var texture = new Texture2D(1, 1, TextureFormat.RGBA32, false); + var lightmap = new Texture2D(1, 1, TextureFormat.RGBA32, false); + texture.SetPixel(0, 0, new Color(.25f, .5f, .75f, textureAlpha)); + texture.Apply(); + lightmap.SetPixel(0, 0, new Color(.6f, .7f, .8f, bakedAlpha)); + lightmap.Apply(); + var mesh = new Mesh + { + vertices = new[] { new Vector3(-2, -2, 0), new Vector3(2, -2, 0), new Vector3(2, 2, 0), new Vector3(-2, 2, 0) }, + normals = Enumerable.Repeat(Vector3.forward, 4).ToArray(), + colors = Enumerable.Repeat(new Color(.7f, .8f, .9f, .35f), 4).ToArray(), + uv = new[] { Vector2.zero, Vector2.right, Vector2.one, Vector2.up }, + uv2 = new[] { Vector2.zero, Vector2.right, Vector2.one, Vector2.up }, + triangles = new[] { 0, 1, 2, 0, 2, 3 } + }; + var materials = new List(); + try + { + GameObject quad = preview.CreateObject("Painted original-stage comparison"); + quad.AddComponent().sharedMesh = mesh; + MeshRenderer renderer = quad.AddComponent(); + var properties = new MaterialPropertyBlock(); + properties.SetFloat("_GbVertexColor", vertexColors ? 1 : 0); + properties.SetFloat("_GbLightCount", 0); + renderer.SetPropertyBlock(properties); + preview.SetCamera(new Vector3(0, 0, 5), Vector3.zero, 40); + renderer.enabled = false; + Texture2D clear = Read(preview.Render(128, 128)); + Color clearPixel; + try + { + clearPixel = clear.GetPixel(64, 64); + } + finally { Object.DestroyImmediate(clear); } + renderer.enabled = true; + for (int part = -1; part < 2; part++) + { + Color native = Render(false, part); + Color toon = Render(true, part); + for (int channel = 0; channel < 4; channel++) + Assert.That(Math.Abs(toon[channel] - native[channel]), Is.LessThanOrEqualTo(2f / 255), + "Native and Painted must agree for the combined image and each classified pass independently."); + if (part == -1) + Assert.That(native, Is.Not.EqualTo(clearPixel), "The comparison must contain rendered surface pixels."); + } + + Color Render(bool painted, int part) + { + var pair = new Material[2]; + string[] shaders = painted ? new[] { "Pal3/ToonCutout", "Pal3/ToonTransparent" } : + new[] { "Pal3/TransparentOpaquePart", "Pal3/Transparent" }; + for (int index = 0; index < pair.Length; index++) + { + var material = new Material(Shader.Find(shaders[index])); + materials.Add(material); + material.mainTexture = texture; + material.SetTexture("_ShadowTex", lightmap); + material.SetFloat("_HasShadowTex", baked ? 1 : 0); + material.SetFloat("_LightmapScale", 2); + material.SetFloat("_Threshold", .9f); + material.SetColor("_TintColor", new Color(1, 1, 1, tintAlpha)); + if (painted) + { + material.SetFloat("_UnlitBackground", 1); + material.SetFloat("_BackgroundBrightness", 1); + material.SetFloat("_SourceDiffuseAlpha", diffuseAlpha); + } + else + { + material.SetFloat("_GbNativeLighting", 1); + material.SetVector("_GbMaterialDiffuse", new Vector4(1, 1, 1, diffuseAlpha)); + material.SetVector("_GbMaterialAmbient", Vector4.one); + } + pair[index] = material; + } + renderer.sharedMaterials = part < 0 ? pair : new[] { pair[part] }; + Texture2D image = Read(preview.Render(128, 128)); + try + { + return image.GetPixel(64, 64); + } + finally { Object.DestroyImmediate(image); } + } + } + finally + { + foreach (Material material in materials) + Object.DestroyImmediate(material); + Object.DestroyImmediate(mesh); + Object.DestroyImmediate(texture); + Object.DestroyImmediate(lightmap); + } + } + + [TestCase(false)] + [TestCase(true)] + public void MixedVertexColorChannelsStayCompleteAndUseIndependentBatchBindings(bool coloredFirst) + { + using var preview = new ResourceModelPreview(null, true); + Core.DataReader.Pol.PolMesh MakeMesh(bool colored, float offset) + { + return new Core.DataReader.Pol.PolMesh + { + VertexFvfFlag = (uint)(Core.Primitives.GameBoxVertexType.XYZ | Core.Primitives.GameBoxVertexType.Normal | + Core.Primitives.GameBoxVertexType.UV0 | (colored ? Core.Primitives.GameBoxVertexType.Diffuse : 0)), + VertexInfo = new Core.DataReader.Pol.PolVertexInfo + { + GameBoxPositions = new[] { new Core.Primitives.GameBoxVector3(offset, 0, 0), + new Core.Primitives.GameBoxVector3(offset + 10, 0, 0), new Core.Primitives.GameBoxVector3(offset, 10, 0) }, + GameBoxNormals = Enumerable.Repeat(new Core.Primitives.GameBoxVector3(0, 0, 1), 3).ToArray(), + DiffuseColors = colored ? Enumerable.Repeat(new Core.Primitives.Color32(255, 128, 64, 90), 3).ToArray() : Array.Empty(), + Uvs = new[] { new[] { new Core.Primitives.GameBoxVector2(0, 0), new Core.Primitives.GameBoxVector2(1, 0), new Core.Primitives.GameBoxVector2(0, 1) } } + }, + Textures = new[] { new Core.DataReader.Pol.PolTexture + { + BlendFlag = Core.Primitives.GameBoxBlendFlag.Opaque, + Material = new Core.Primitives.GameBoxMaterial { Diffuse = Core.Primitives.Color.White, + Ambient = Core.Primitives.Color.White, TextureFileNames = new[] { string.Empty } }, + GameBoxTriangles = new[] { 0, 1, 2 } + } } + }; + } + var model = new Core.DataReader.Pol.PolFile(100, + new[] { new Core.DataReader.Pol.PolGeometryNode { Name = "first" }, new Core.DataReader.Pol.PolGeometryNode { Name = "second" } }, + new[] { MakeMesh(coloredFirst, 1), MakeMesh(!coloredFirst, 12) }, Array.Empty()); + preview.ReplaceEnvironment(new ResourceEntry("basedata.cpk\\mixed.pol"), model, (_, _) => null); + MeshFilter[] meshes = preview.Root.GetComponentsInChildren(); + Assert.That(meshes.Length, Is.EqualTo(2), "A renderer-wide vertex-color flag requires separate bindings for unlike channels."); + foreach (MeshFilter filter in meshes) + { + Mesh mesh = filter.sharedMesh; + Assert.That(mesh.colors32.Length, Is.EqualTo(0).Or.EqualTo(mesh.vertexCount), "Every enabled channel must cover every batched vertex."); + var properties = new MaterialPropertyBlock(); + filter.GetComponent().GetPropertyBlock(properties); + Assert.That(properties.GetFloat("_GbVertexColor"), Is.EqualTo(mesh.colors32.Length > 0 ? 1 : 0)); + } + } + + private static void FrameSelectedTriangle(ResourceModelPreview preview, MeshRenderer renderer) + { + // The authored battle camera may contain no sky at all. Frame an + // actual selected triangle so the pixel comparison cannot pass empty. + MeshFilter surface = renderer.GetComponent(); + Vector3[] vertices = surface.sharedMesh.vertices; + int[] triangles = surface.sharedMesh.triangles; + Vector3 a = surface.transform.TransformPoint(vertices[triangles[0]]); + Vector3 b = surface.transform.TransformPoint(vertices[triangles[1]]); + Vector3 c = surface.transform.TransformPoint(vertices[triangles[2]]); + Vector3 center = (a + b + c) / 3; + Vector3 normal = Vector3.Cross(b - a, c - a).normalized; + Assert.That(normal.sqrMagnitude, Is.GreaterThan(.9f)); + float distance = Math.Max(.1f, Math.Min(Vector3.Distance(a, b), Vector3.Distance(a, c)) * .5f); + preview.SetCamera(center + normal * distance, center, 50); + } + + private static Texture2D Read(RenderTexture target) + { + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(target.width, target.height, TextureFormat.RGBA32, false); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0); + image.Apply(); + return image; + } + finally + { + RenderTexture.active = previous; + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleSceneAppearanceRenderingTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleSceneAppearanceRenderingTests.cs.meta new file mode 100644 index 00000000..54bc03ab --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleSceneAppearanceRenderingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 825688aa373d45648a8cfaf2ae220fe8 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleSelectionOffscreenTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleSelectionOffscreenTests.cs new file mode 100644 index 00000000..e98a1ed0 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleSelectionOffscreenTests.cs @@ -0,0 +1,773 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Runtime.Serialization; + using Battle; + using Battle.Presentation; + using Core.DataReader.Mv3; + using NUnit.Framework; + using ResourceBrowser; + using UnityEditor; + using UnityEngine; + using Object = UnityEngine.Object; + + // Uses only preview scenes and RenderTextures. Never creates an EditorWindow. + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleSelectionOffscreenTests + { + private static BattleHudView BoundHud(BattleEditorSession session, bool touch, Rect viewport) + { + var hud = new BattleHudView(); + hud.BindBattle(session.Battle, session.Data, session.Preview, null, null); + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + typeof(BattleHudView).GetField("_viewport", fields).SetValue(hud, new BattleHudViewport(viewport, default)); + typeof(BattleHudView).GetField("_interaction", fields).SetValue(hud, new BattleHudInteractionProfile(touch)); + hud.SetInputFocus(true); + return hud; + } + + private static BattleHudView TargetHud(BattleEditorSession session, bool touch, string enemy, Rect viewport) + { + BattleHudView hud = BoundHud(session, touch, viewport); + hud.Presenter.Open(BattleHudPage.Skills); + int skill = session.Battle.Definitions.Skills.Values.Where(ability => !ability.IsMagic && ability.Range == BattleTargetRange.OpponentSingle) + .Where(ability => session.Battle.CanSubmit(new BattleCommand(hud.Presenter.Controller, BattleAction.Skill, enemy, ability.Id)) == null) + .Select(ability => ability.Id).First(); + Assert.That(hud.Presenter.ChooseAbility(skill), Is.True); + return hud; + } + + [TestCase(false)] + [TestCase(true)] + public void OneCompleteTapOnALegalSkillRecipientSubmitsExactlyOnce(bool touch) + { + using var session = Create(false, out string enemy); + var viewport = new Rect(0, 0, 800, 600); + session.Preview.View.SetViewportContext(viewport); + BattleHudView hud = TargetHud(session, touch, enemy, viewport); + Assert.That(session.Preview.TryActorSelectionPoint(enemy, viewport, out Vector2 point), Is.True); + hud.SendPointer(BattleHudIntentKind.PointerDown, 9, point); + Assert.That(session.Battle.Inputs.Count(input => input.Kind == BattleInputKind.Command), Is.Zero); + hud.SendPointer(BattleHudIntentKind.PointerUp, 9, point); + Assert.That(session.Battle.Inputs.Count(input => input.Kind == BattleInputKind.Command), Is.EqualTo(1)); + Assert.That(session.Battle.Inputs.Last(input => input.Kind == BattleInputKind.Command).Target, Is.EqualTo(enemy)); + } + + [TestCase(false, false)] + [TestCase(false, true)] + [TestCase(true, false)] + [TestCase(true, true)] + public void InvalidSkillRecipientOrEmptyWorldReturnsToTheSkillListWithoutCasting(bool touch, bool invalidActor) + { + using var session = Create(false, out string enemy); + var viewport = new Rect(0, 0, 800, 600); + session.Preview.View.SetViewportContext(viewport); + BattleHudView hud = TargetHud(session, touch, enemy, viewport); + Vector2 point = new(5, 5); + if (invalidActor) + Assert.That(session.Preview.TryActorSelectionPoint(hud.Presenter.Controller, viewport, out point), Is.True); + else + Assert.That(session.Preview.PickActor(point, viewport, session.Battle.Actors.Select(actor => actor.Id)), Is.Null); + hud.SendPointer(BattleHudIntentKind.PointerDown, 9, point); + hud.SendPointer(BattleHudIntentKind.PointerUp, 9, point); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Skills)); + Assert.That(session.Battle.Inputs.Count(input => input.Kind == BattleInputKind.Command), Is.Zero); + } + + // A native GUI state and viewport exercise control ownership without + // creating a window. Unity ignores mouse presses outside its GUI clip. + private sealed class NativeGuiState : IDisposable + { + private const BindingFlags Static = BindingFlags.Static | BindingFlags.NonPublic; + private static readonly Type StateType = typeof(GUIUtility).Assembly.GetType("UnityEngine.ObjectGUIState", true); + private static readonly MethodInfo Begin = typeof(GUIUtility).GetMethod("BeginContainer", Static, null, new[] { StateType }, null); + private static readonly MethodInfo End = typeof(GUIUtility).GetMethod("EndContainer", Static, null, Type.EmptyTypes, null); + private static readonly Type ClipType = typeof(GUIUtility).Assembly.GetType("UnityEngine.GUIClip", true); + private static readonly MethodInfo PushClip = ClipType.GetMethod("Internal_PushParentClip", Static, null, new[] { typeof(Matrix4x4), typeof(Matrix4x4), typeof(Rect) }, null); + private static readonly MethodInfo PopClip = ClipType.GetMethod("Internal_PopParentClip", Static, null, Type.EmptyTypes, null); + private readonly object _state = Activator.CreateInstance(StateType); + + public void Run(BattleHudView hud, Event input, Action body) + { + Event previous = Event.current; + Vector2 mousePosition = input.mousePosition; + Begin.Invoke(null, new[] { _state }); + bool clipped = false; + try + { + Event.current = input; + PushClip.Invoke(null, new object[] { Matrix4x4.identity, Matrix4x4.identity, new Rect(0, 0, 800, 600) }); + clipped = true; + Event.current.mousePosition = mousePosition; + GUI.enabled = true; + typeof(BattleHudView).GetMethod("PrepareGuiInput", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(hud, null); + body(Event.current); + } + finally + { + if (clipped) + PopClip.Invoke(null, null); + End.Invoke(null, null); + Event.current = previous; + } + } + + public void Dispose() => ((IDisposable)_state).Dispose(); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void DrawerKeyboardFocusSurvivesPointerMovementUntilTheCanvasIsClicked(string variant) + { + BattleSession battle = BattleHudTests.Session(variant); + var hud = new BattleHudView(); + hud.BindBattle(battle, null, null, null, null); + hud.SetInputFocus(true); + var canvas = new Rect(0, 0, 400, 500); + var drawer = new Rect(420, 0, 280, 500); + const BindingFlags methods = BindingFlags.Instance | BindingFlags.NonPublic; + MethodInfo handle = typeof(BattleHudView).GetMethod("HandleGuiInput", methods); + MethodInfo complete = typeof(BattleHudView).GetMethod("CompleteGuiInput", methods); + using var gui = new NativeGuiState(); + int tab = 0; + gui.Run(hud, new Event { type = EventType.MouseDown, mousePosition = drawer.center }, _ => + { + tab = GUIUtility.GetControlID(73401, FocusType.Keyboard, drawer); + GUIUtility.keyboardControl = tab; + Assert.That(tab, Is.Not.Zero); + }); + gui.Run(hud, new Event { type = EventType.KeyDown, mousePosition = canvas.center, keyCode = KeyCode.RightArrow }, input => + { + Assert.That(GUIUtility.keyboardControl, Is.EqualTo(tab)); + Assert.That(EditorGUIUtility.editingTextField, Is.False); + handle.Invoke(hud, new object[] { input, canvas }); + Assert.That(input.type, Is.EqualTo(EventType.KeyDown)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("attack")); + }); + gui.Run(hud, new Event { type = EventType.MouseDown, mousePosition = canvas.center }, input => + { + complete.Invoke(hud, new object[] { input, canvas }); + Assert.That(GUIUtility.keyboardControl, Is.Zero); + }); + gui.Run(hud, new Event { type = EventType.MouseUp, mousePosition = canvas.center }, input => + complete.Invoke(hud, new object[] { input, canvas })); + gui.Run(hud, new Event { type = EventType.KeyDown, mousePosition = canvas.center, keyCode = KeyCode.RightArrow }, input => + { + handle.Invoke(hud, new object[] { input, canvas }); + Assert.That(input.type, Is.EqualTo(EventType.Used)); + Assert.That(hud.Presenter.FocusedId, Is.EqualTo("defend")); + }); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void GamepadTargetNavigationUsesScreenPositionsBeforeTheFirstTargetPageDraw(string variant) + { + BattleSession battle = BattleHudTests.Session(variant); + var command = new BattleCommand(battle.WaitingActor, BattleAction.Attack); + string[] candidates = battle.GetTargetCandidates(command).Select(actor => actor.Id).ToArray(); + string center = battle.GetDefaultTarget(command); + int index = Array.IndexOf(candidates, center); + string left = candidates[(index + 1) % candidates.Length]; + string right = candidates[(index + 2) % candidates.Length]; + using var view = new ResourceModelPreview(null, false); + view.SetCamera(new Vector3(0, 0, -10), Vector3.zero, 45); + var viewport = new Rect(0, 0, 800, 600); + view.SetViewportContext(viewport); + + // This fixture supplies only actor bounds and a real preview camera. + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + var preview = (BattlePreview)FormatterServices.GetUninitializedObject(typeof(BattlePreview)); + Type type = typeof(BattlePreview); + type.GetField("k__BackingField", fields).SetValue(preview, view); + FieldInfo field = type.GetField("_actors", fields); + var actorViews = (IDictionary)Activator.CreateInstance(field.FieldType); + field.SetValue(preview, actorViews); + Type actorType = type.GetNestedType("ActorView", BindingFlags.NonPublic); + var model = new Mv3File(0, null, null, new[] { new Mv3Mesh() }, null); + foreach ((string id, float x) in new[] { (left, -2f), (center, 0f), (right, 2f) }) + { + object actor = Activator.CreateInstance(actorType); + GameObject body = view.CreateObject(id); + body.transform.position = new Vector3(x, 0, 0); + actorType.GetField("Object").SetValue(actor, body); + actorType.GetField("Model").SetValue(actor, model); + actorViews.Add(id, actor); + } + Assert.That(preview.TryActorSelectionPoint(center, viewport, out Vector2 origin), Is.True); + Assert.That(preview.TryActorSelectionPoint(right, viewport, out Vector2 expected), Is.True); + Assert.That(expected.x, Is.GreaterThan(origin.x)); + + var hud = new BattleHudView(); + hud.BindBattle(battle, null, preview, null, null); + typeof(BattleHudView).GetField("_viewport", fields).SetValue(hud, new BattleHudViewport(viewport, default)); + hud.Presenter.SetFocusLayout(new[] { ("attack", 40f, 410f) }); + var gamepad = new BattleEditorGamepadState(); + gamepad.Sample(new BattleEditorGamepadSnapshot(buttons: BattleEditorGamepadButtons.Confirm), true); + gamepad.Sample(default, true); + gamepad.Sample(new BattleEditorGamepadSnapshot(dpadX: 1), true); + gamepad.Sample(new BattleEditorGamepadSnapshot(dpadX: 1, buttons: BattleEditorGamepadButtons.Confirm), true); + gamepad.Advance(1, true, intent => + { + hud.TakeGamepadInput(); + Assert.That(hud.SendGamepadIntent(intent), Is.True); + }); + Assert.That(battle.Inputs.Single(input => input.Kind == BattleInputKind.Command).Target, Is.EqualTo(right)); + } + + [TestCase(false, 0)] + [TestCase(false, 1)] + [TestCase(false, 2)] + [TestCase(true, 0)] + [TestCase(true, 1)] + [TestCase(true, 2)] + public void NativePointerCaptureIsReleasedByOutsideReleaseEscapeAndFocusLoss(bool touch, int cancellation) + { + using var session = Create(false, out string enemy); + var viewport = new Rect(0, 0, 800, 600); + session.Preview.View.SetViewportContext(viewport); + BattleHudView hud = TargetHud(session, touch, enemy, viewport); + Assert.That(session.Preview.TryActorSelectionPoint(enemy, viewport, out Vector2 point), Is.True); + MethodInfo handler = typeof(BattleHudView).GetMethod("HandleGuiInput", BindingFlags.Instance | BindingFlags.NonPublic); + using var gui = new NativeGuiState(); + try + { + gui.Run(hud, new Event { type = EventType.Layout }, _ => { }); + gui.Run(hud, new Event { type = EventType.MouseDown, button = 0, mousePosition = point }, input => + { + Assert.That(input.type, Is.EqualTo(EventType.MouseDown)); + handler.Invoke(hud, new object[] { input, viewport }); + Assert.That(input.type, Is.EqualTo(EventType.Used)); + Assert.That(GUIUtility.hotControl, Is.Not.Zero); + Assert.That(hud.Presenter.CapturedPointerId, Is.EqualTo(0)); + }); + Event end = cancellation == 0 ? new Event { type = EventType.MouseUp, button = 0, mousePosition = new Vector2(-20, -20) } : + cancellation == 1 ? new Event { type = EventType.KeyDown, keyCode = KeyCode.Escape } : new Event { type = EventType.Layout }; + gui.Run(hud, end, input => + { + if (cancellation == 2) + hud.SetInputFocus(false); + else + handler.Invoke(hud, new object[] { input, viewport }); + Assert.That(GUIUtility.hotControl, Is.Zero); + Assert.That(hud.Presenter.CapturedPointerId, Is.Null); + Assert.That(session.Battle.Inputs.Count(entry => entry.Kind == BattleInputKind.Command), Is.Zero); + }); + } + finally + { + gui.Run(hud, new Event { type = EventType.Layout }, _ => hud.Release()); + } + } + + [Test] + public void ScrollbarClaimAfterTouchDownReleasesPendingPanForTheNextFinger() + { + var hud = new BattleHudView(); + var list = new Rect(10, 10, 160, 100); + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + var type = typeof(BattleHudView); + type.GetField("_interaction", fields).SetValue(hud, new BattleHudInteractionProfile(true)); + type.GetField("_touchPanel", fields).SetValue(hud, list); + MethodInfo gesture = type.GetMethod("TouchGesture", fields); + FieldInfo candidate = type.GetField("_touchCandidatePointer", fields); + using var gui = new NativeGuiState(); + gui.Run(hud, new Event { type = EventType.MouseDown, button = 0, mousePosition = list.center }, input => + { + gesture.Invoke(hud, new object[] { BattleHudIntentKind.PointerDown, 0, input.mousePosition }); + Assert.That(candidate.GetValue(hud), Is.EqualTo(0)); + GUIUtility.hotControl = GUIUtility.GetControlID(FocusType.Passive); + }); + gui.Run(hud, new Event { type = EventType.MouseUp, button = 0 }, _ => + { + Assert.That(GUIUtility.hotControl, Is.Not.Zero); + Assert.That(candidate.GetValue(hud), Is.Null); + GUIUtility.hotControl = 0; + }); + gui.Run(hud, new Event { type = EventType.MouseDown, button = 0, mousePosition = list.center }, input => + { + gesture.Invoke(hud, new object[] { BattleHudIntentKind.PointerDown, 7, input.mousePosition }); + Assert.That(candidate.GetValue(hud), Is.EqualTo(7)); + }); + } + + [Test] + public void NativeScrollbarCaptureCannotBeStolenByHudClicksBackOrCancellation() + { + using var session = Create(false, out string enemy); + var viewport = new Rect(0, 0, 800, 600); + session.Preview.View.SetViewportContext(viewport); + BattleHudView hud = TargetHud(session, true, enemy, viewport); + Assert.That(session.Preview.TryActorSelectionPoint(enemy, viewport, out Vector2 point), Is.True); + MethodInfo handler = typeof(BattleHudView).GetMethod("HandleGuiInput", BindingFlags.Instance | BindingFlags.NonPublic); + using var gui = new NativeGuiState(); + try + { + foreach (int button in new[] { 0, 1 }) + gui.Run(hud, new Event { type = EventType.MouseDown, button = button, mousePosition = point }, input => + { + int scrollbar = GUIUtility.GetControlID(0x5363726c, FocusType.Passive); + GUIUtility.hotControl = scrollbar; + handler.Invoke(hud, new object[] { input, viewport }); + Assert.That(input.type, Is.EqualTo(EventType.MouseDown)); + hud.CancelInput(); + Assert.That(GUIUtility.hotControl, Is.EqualTo(scrollbar)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + Assert.That(hud.Presenter.CapturedPointerId, Is.Null); + Assert.That(session.Battle.Inputs.Count(entry => entry.Kind == BattleInputKind.Command), Is.Zero); + GUIUtility.hotControl = 0; + }); + } + finally + { + gui.Run(hud, new Event { type = EventType.Layout }, _ => hud.Release()); + } + } + + [TestCase(false)] + [TestCase(true)] + public void FocusLossOutsideTheOwnerGuiStateReleasesOnlyTheOwnerOnItsNextPass(bool anotherGuiActive) + { + using var session = Create(false, out string enemy); + var viewport = new Rect(0, 0, 800, 600); + session.Preview.View.SetViewportContext(viewport); + BattleHudView hud = TargetHud(session, true, enemy, viewport); + Assert.That(session.Preview.TryActorSelectionPoint(enemy, viewport, out Vector2 point), Is.True); + MethodInfo handler = typeof(BattleHudView).GetMethod("HandleGuiInput", BindingFlags.Instance | BindingFlags.NonPublic); + using var owner = new NativeGuiState(); + using var other = new NativeGuiState(); + var otherHud = new BattleHudView(); + try + { + owner.Run(hud, new Event { type = EventType.MouseDown, button = 0, mousePosition = point }, input => + { + handler.Invoke(hud, new object[] { input, viewport }); + Assert.That(GUIUtility.hotControl, Is.Not.Zero); + Assert.That(hud.Presenter.CapturedPointerId, Is.EqualTo(0)); + }); + owner.Run(hud, new Event { type = EventType.Layout }, _ => Assert.That(GUIUtility.hotControl, Is.Not.Zero, + "The native owner state must retain capture between GUI passes for this lifecycle fixture.")); + if (anotherGuiActive) + other.Run(otherHud, new Event { type = EventType.Layout }, _ => + { + int foreign = GUIUtility.GetControlID(0x5363726c, FocusType.Passive); + GUIUtility.hotControl = foreign; + hud.SetInputFocus(false); + Assert.That(GUIUtility.hotControl, Is.EqualTo(foreign), "Losing focus must not clear another window's capture."); + GUIUtility.hotControl = 0; + }); + else + hud.SetInputFocus(false); + Assert.That(hud.Presenter.CapturedPointerId, Is.Null); + owner.Run(hud, new Event { type = EventType.Layout }, _ => + Assert.That(GUIUtility.hotControl, Is.Zero, "The next pass must release the original window's capture, rather than lose its ID.")); + } + finally + { + owner.Run(hud, new Event { type = EventType.Layout }, _ => hud.Release()); + other.Run(otherHud, new Event { type = EventType.Layout }, _ => otherHud.Release()); + } + } + + private static BattleEditorSession Create(bool toon, out string enemy) + { + var session = new BattleEditorSession(); + session.Load(Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"), 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = session.Data.Scenes.First(), + DataFingerprint = session.Data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush, + ToonRendering = toon, + Music = "NONE" + }; + scenario.Participants.Add(session.Data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int id = session.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(session.Data, id)); + scenario.Participants.Add(session.Data.CreateParticipant(id, BattleSide.Enemy, BattleSlot.Water)); + enemy = scenario.Participants[1].InstanceId; + session.StartBattle(scenario); + session.Preview.Audio.Muted = session.Preview.Effects.Muted = true; + Vector3 center = session.Battle.Actors.Select(actor => BattleAnimationCatalog.UnityPosition(actor.Position)).Aggregate(Vector3.zero, (sum, value) => sum + value) / 2; + session.Preview.View.SetCamera(center + new Vector3(9, 9, -14), center + Vector3.up, 50); + return session; + } + + private static Color32[] Pixels(RenderTexture texture, string name) + { + var image = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = texture; + image.ReadPixels(new Rect(0, 0, image.width, image.height), 0, 0); + image.Apply(); + string root = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (!string.IsNullOrEmpty(root)) + { + string folder = Path.Combine(root, "SelectionOffscreen"); + Directory.CreateDirectory(folder); + File.WriteAllBytes(Path.Combine(folder, BattleData.Variant + "-" + name + ".png"), image.EncodeToPNG()); + } + return image.GetPixels32(); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + + [TestCase(false)] + [TestCase(true)] + public void SelectedBodyChangesActualRgbAndPreservesItsAlphaAndSimulation(bool toon) + { + using var session = Create(toon, out string enemy); + Transform actor = session.Preview.View.Root.transform.Find(enemy); + var body = actor.GetComponentInChildren(); + body.SetOpacity(.44f); + var mesh = body.GameEntity.GetComponentsInChildren().First(); + var properties = new MaterialPropertyBlock(); + mesh.GetPropertyBlock(properties); + properties.SetFloat("_SelectionTestSentinel", .375f); + mesh.SetPropertyBlock(properties); + Material[] materials = mesh.sharedMaterials; + Assert.That(materials, Is.Not.Empty); + Assert.That(materials.All(material => Math.Abs(material.GetColor("_TintColor").a - .44f) < .00001f), Is.True, + "The fixture must inspect the actual faded materials, rather than an unset property-block value."); + long tick = session.Battle.Tick; + int events = session.Battle.Events.Count; + var hud = new BattleHudView(); + hud.TakeNavigationInput(session.Battle); + Assert.That(hud.Presenter.ChooseAction(BattleAction.Attack), Is.True); + Assert.That(hud.Presenter.Target, Is.EqualTo(enemy)); + hud.PreparePointers(session.Battle, session.Data, session.Preview, Math.PI * .5 / 7.8); + mesh.GetPropertyBlock(properties); + Assert.That(properties.GetFloat("_BattleSelection"), Is.EqualTo(1f).Within(.001f)); + Color32[] high = Pixels(session.Preview.View.Render(800, 600), (toon ? "toon" : "native") + "-high"); + hud.PreparePointers(session.Battle, session.Data, session.Preview, Math.PI * 1.5 / 7.8); + mesh.GetPropertyBlock(properties); + Assert.That(properties.GetFloat("_BattleSelection"), Is.EqualTo(.3f).Within(.001f)); + Color32[] low = Pixels(session.Preview.View.Render(800, 600), (toon ? "toon" : "native") + "-low"); + double energy = 0; + int changed = 0; + Assert.That(session.Preview.TryActorSelectionPoint(enemy, new Rect(0, 0, 800, 600), out Vector2 point), Is.True); + int centerX = Mathf.RoundToInt(point.x); + int centerY = 599 - Mathf.RoundToInt(point.y); + for (int y = Math.Max(0, centerY - 15); y <= Math.Min(599, centerY + 15); y++) + for (int x = Math.Max(0, centerX - 15); x <= Math.Min(799, centerX + 15); x++) + { + int index = y * 800 + x; + int delta = high[index].r + high[index].g + high[index].b - low[index].r - low[index].g - low[index].b; + energy += delta; + if (delta > 5) + changed++; + } + Assert.That(changed, Is.GreaterThan(40), "The body pulse must reach the rendered pixels in both material modes."); + Assert.That(energy, Is.GreaterThan(200)); + mesh.GetPropertyBlock(properties); + Assert.That(properties.GetFloat("_SelectionTestSentinel"), Is.EqualTo(.375f), "Selection must merge the existing property block."); + Assert.That(materials.All(material => Math.Abs(material.GetColor("_TintColor").a - .44f) < .00001f), Is.True); + hud.Presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Back)); + hud.PreparePointers(session.Battle, session.Data, session.Preview, 0); + mesh.GetPropertyBlock(properties); + Assert.That(properties.GetFloat("_BattleSelection"), Is.EqualTo(-1)); + Assert.That(materials.All(material => Math.Abs(material.GetColor("_TintColor").a - .44f) < .00001f), Is.True); + Assert.That(session.Battle.Tick, Is.EqualTo(tick)); + Assert.That(session.Battle.Events.Count, Is.EqualTo(events)); + } + + [Test] + public void ReturningFromTargetSelectionPreservesTheSkillToBeReconsidered() + { + using var session = Create(false, out _); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session.Battle); + presenter.Open(BattleHudPage.Skills); + BattleHudAbility row = presenter.Abilities().Where(entry => entry.Denied == null).Skip(1).First(); + string control = "ability:" + row.Definition.Id; + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, control)), Is.True); + presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Back)); + Assert.That(presenter.FocusedId, Is.EqualTo(control)); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm)), Is.True); + Assert.That(presenter.Command.AbilityId, Is.EqualTo(row.Definition.Id)); + } + + [Test] + public void TouchCanLeaveProtectionWithoutIssuingACommand() + { + using var session = Create(false, out _); + BattleScenario scenario = session.CapturedScenario; + scenario.Participants[0].Slot = BattleSlot.Center; + int companionId = BattleData.Variant == "PAL3A" ? 102 : 104; + scenario.Participants.Add(session.Data.CreateParticipant(companionId, BattleSide.Ally, BattleSlot.Fire)); + session.StartBattle(scenario); + var viewport = new Rect(0, 0, 800, 600); + BattleHudView hud = BoundHud(session, true, viewport); + Assert.That(hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Confirm, "protection")), Is.True); + int inputs = session.Battle.RecordedInputCount; + Vector2 ground = new(5, 5); + Assert.That(session.Preview.PickActor(ground, viewport, session.Battle.Actors.Select(actor => actor.Id)), Is.Null); + hud.SendPointer(BattleHudIntentKind.PointerDown, 1, ground); + hud.SendPointer(BattleHudIntentKind.PointerUp, 1, ground); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(session.Battle.RecordedInputCount, Is.EqualTo(inputs)); + } + + [Test] + public void TouchOnTheDisabledSideOfASkillRowBoundaryCannotActivateItsNeighbour() + { + using var session = Create(false, out _); + var viewport = new Rect(0, 0, 800, 600); + BattleHudView hud = BoundHud(session, true, viewport); + hud.Presenter.Open(BattleHudPage.Skills); + var rows = hud.Presenter.Abilities(); + BattleHudAbility available = rows.First(row => row.Denied == null); + BattleHudAbility disabled = rows.First(row => row.Denied != null); + // Place a disabled row directly below an enabled row in the native + // skill list, at its actual scroll-view position and row height. + Rect list = BattleHudText.ListBounds(BattleHudPage.Skills, BattleData.Variant == "PAL3A"); + list.position += BattleHudText.AbilityPanelBounds(BattleHudPage.Skills, BattleData.Variant == "PAL3A").position; + const BindingFlags members = BindingFlags.Instance | BindingFlags.NonPublic; + var hitControls = (System.Collections.Generic.List<(string Id, Rect Rect)>)typeof(BattleHudView).GetField("_hitControls", members).GetValue(hud); + Rect rowRect = new(list.x, list.y, list.width - 16, 19); + hitControls.Add(("ability:" + available.Definition.Id, rowRect)); + rowRect.y += rowRect.height; + hitControls.Add(("ability:" + disabled.Definition.Id, rowRect)); + typeof(BattleHudView).GetField("_touchPanel", members).SetValue(hud, list); + Vector2 tap = new(rowRect.center.x, rowRect.yMin + 1); + hud.SendPointer(BattleHudIntentKind.PointerDown, 2, tap); + hud.SendPointer(BattleHudIntentKind.PointerUp, 2, tap); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Skills)); + } + + [Test] + public void OffensiveGroupSkillOnlyMarksAndSelectsSurvivingEnemies() + { + using var session = Create(false, out string defeated); + BattleScenario scenario = session.CapturedScenario; + BattleParticipant first = scenario.Participants.Single(actor => actor.InstanceId == defeated); + first.Vitals[0] = 0; + BattleParticipant survivor = session.Data.CreateParticipant(first.ActorId, BattleSide.Enemy, BattleSlot.Fire); + scenario.Participants.Add(survivor); + session.StartBattle(scenario); + + var hud = new BattleHudView(); + hud.TakeNavigationInput(session.Battle); + hud.Presenter.Open(BattleHudPage.Magic); + int skill = session.Battle.Definitions.Skills.Values.First(ability => ability.IsMagic && + ability.Range == BattleTargetRange.OpponentAll && hud.Presenter.Reason(BattleAction.Skill, ability.Id) == null).Id; + Assert.That(hud.Presenter.ChooseAbility(skill), Is.True); + hud.PreparePointers(session.Battle, session.Data, session.Preview, .1); + + Transform root = session.Preview.View.Root.transform; + Assert.That(root.Find("Battle selection pointer " + defeated), Is.Null); + Transform marker = root.Find("Battle selection pointer " + survivor.InstanceId); + Assert.That(marker, Is.Not.Null); + Assert.That(marker.GetComponentsInChildren().Any(renderer => renderer.enabled), Is.True); + Assert.That(hud.Presenter.Target, Is.EqualTo(survivor.InstanceId)); + Assert.That(hud.Presenter.SelectTarget(defeated), Is.False); + Assert.That(hud.Presenter.SelectTarget(survivor.InstanceId), Is.True); + } + + [Test] + public void ObbPickingAndOriginalCvdPointersWorkAcrossAllFourAspectsWithoutAWindow() + { + using var session = Create(false, out string enemy); + var hud = new BattleHudView(); + hud.TakeNavigationInput(session.Battle); + Assert.That(hud.Presenter.ChooseAction(BattleAction.Attack), Is.True); + int inputs = session.Battle.Inputs.Count; + foreach (Vector2Int size in new[] { new Vector2Int(800, 600), new Vector2Int(1050, 450), new Vector2Int(1000, 500), new Vector2Int(700, 700) }) + { + Rect viewport = new(0, 0, size.x, size.y); + session.Preview.View.SetViewportContext(viewport); + Assert.That(session.Preview.TryActorSelectionPoint(enemy, viewport, out Vector2 center), Is.True); + Assert.That(session.Preview.PickActor(center, viewport, hud.Presenter.Targets.Select(target => target.Id)), Is.EqualTo(enemy)); + Assert.That(session.Preview.PickActor(new Vector2(-1, center.y), viewport, new[] { enemy }), Is.Null); + hud.PreparePointers(session.Battle, session.Data, session.Preview, .1); + var marker = session.Preview.View.Root.transform.Find("Battle selection pointer " + enemy); + Assert.That(marker, Is.Not.Null); + Assert.That(marker.GetComponentsInChildren().Any(renderer => renderer.enabled), Is.True); + // Bind only the input adapter's world-picking dependencies. + // This exercises real SendPointer/PreparePointers transitions + // without claiming to execute the IMGUI Draw/window lifecycle. + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + typeof(BattleHudView).GetField("_preview", fields).SetValue(hud, session.Preview); + typeof(BattleHudView).GetField("_viewport", fields).SetValue(hud, new BattleHudViewport(viewport, default)); + typeof(BattleHudView).GetField("_inputEnabled", fields).SetValue(hud, true); + Assert.That(hud.SendPointer(BattleHudIntentKind.PointerMove, 0, center), Is.True); + hud.PreparePointers(session.Battle, session.Data, session.Preview, .1); + Assert.That(marker.GetComponentsInChildren().Any(renderer => renderer.enabled), Is.True, "Mouse hover must preserve the navigation marker."); + hud.SendPointer(BattleHudIntentKind.PointerMove, 0, new Vector2(-1, center.y)); + hud.PreparePointers(session.Battle, session.Data, session.Preview, .1); + Assert.That(marker.GetComponentsInChildren().All(renderer => !renderer.enabled), Is.True, "Leaving the body must hide the marker."); + Assert.That(hud.SendPointer(BattleHudIntentKind.PointerMove, 0, center), Is.True); + hud.PreparePointers(session.Battle, session.Data, session.Preview, .1); + Assert.That(marker.GetComponentsInChildren().Any(renderer => renderer.enabled), Is.True, "Returning to the body must reuse and show the cached marker."); + Pixels(session.Preview.View.Render(size.x, size.y), "marker-" + size.x + "x" + size.y); + hud.TakeNavigationInput(); + } + Assert.That(session.Battle.Inputs.Count, Is.EqualTo(inputs)); + } + + [TestCase(-1, false)] + [TestCase(1, false)] + [TestCase(3, true)] + [TestCase(4, true)] + public void ProtectionMenuChecksThePresenceOfNativeCompanions(int role, bool alive) + { + using var session = Create(false, out _); + BattleScenario scenario = session.CapturedScenario; + scenario.Participants[0].Slot = BattleSlot.Center; + bool pal3A = BattleData.Variant == "PAL3A"; + if (role != -1) + { + int actorId = pal3A ? 101 + role : new[] { 101, 104, 106, 107, 102 }[role]; + BattleParticipant companion = session.Data.CreateParticipant(actorId, BattleSide.Ally, BattleSlot.Fire); + if (!alive) + companion.Vitals[0] = 0; + scenario.Participants.Add(companion); + } + session.StartBattle(scenario); + var presenter = new BattleHudPresenter(); + presenter.Synchronize(session.Battle); + bool offered = role == 1 || role == 3 && !pal3A; + Assert.That(presenter.FocusItems().Single(control => control.Id == "protection").Enabled, Is.EqualTo(offered)); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "protection")), Is.EqualTo(offered)); + if (offered) + Assert.That(presenter.FocusItems().Any(control => control.Id.StartsWith("protect:", StringComparison.Ordinal)), Is.EqualTo(alive)); + } + +#if PAL3A + [TestCase(101)] + [TestCase(103)] + public void TransformedCommandWheelPreventsForbiddenMenusAndAiGaugeCosts(int playerId) + { + using var session = Create(false, out _); + BattleScenario scenario = session.CapturedScenario; + scenario.Participants[0] = session.Data.CreateTestParticipant(playerId, BattleSide.Ally, BattleSlot.Water); + bool fireBeast = playerId == 101; + scenario.Pal3A.NangongStartsTransformed = fireBeast; + scenario.Pal3A.PengxuStartsTransformed = !fireBeast; + session.StartBattle(scenario); + BattleSession battle = session.Battle; + var presenter = new BattleHudPresenter(); + presenter.Synchronize(battle); + string actor = presenter.Controller; + Assert.That(battle.IsPal3ATransformed(actor), Is.True); + var controls = presenter.FocusItems().ToDictionary(control => control.Id); + Assert.That(controls["attack"].Enabled, Is.EqualTo(fireBeast)); + Assert.That(controls["magic"].Enabled, Is.EqualTo(!fireBeast)); + Assert.That(controls["defend"].Enabled, Is.True); + int inputs = battle.RecordedInputCount; + int profile = battle.GetAiProfile(actor); + BattleActorSnapshot before = battle.Actors.Single(player => player.Id == actor); + foreach (string id in new[] { "skills", "items", "ai" }) + { + Assert.That(controls[id].Enabled, Is.False, id); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, id)), Is.False); + Assert.That(presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + } + Assert.That(battle.CommitAiControl(actor, BattleHudPresenter.ToggleAiFlag(profile, 5)), Is.False); + Assert.That(battle.GetAiProfile(actor), Is.EqualTo(profile)); + Assert.That(battle.RecordedInputCount, Is.EqualTo(inputs)); + BattleActorSnapshot after = battle.Actors.Single(player => player.Id == actor); + Assert.That((after.Gauge, after.CastGauge), Is.EqualTo((before.Gauge, before.CastGauge))); + Assert.That(controls["flee"].Enabled, Is.True); + Assert.That(presenter.Handle(new BattleHudIntent(BattleHudIntentKind.Confirm, "flee")), Is.True); + Assert.That(battle.Inputs.Last(input => input.Kind == BattleInputKind.Command).Action, Is.EqualTo(BattleAction.Flee)); + } +#endif + + [TestCase(false)] + [TestCase(true)] + public void OnlyACompletedTapOnEmptyGroundDiscardsTheAiDraft(bool touch) + { + using var session = Create(false, out string enemy); + var viewport = new Rect(0, 0, 800, 600); + session.Preview.View.SetViewportContext(viewport); + BattleHudView hud = BoundHud(session, touch, viewport); + BattleSession battle = session.Battle; + string controller = battle.WaitingActor; + BattleActorSnapshot before = battle.Actors.Single(actor => actor.Id == controller); + int inputs = battle.RecordedInputCount; + int profile = battle.GetAiProfile(controller); + Assert.That(hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Confirm, "ai")), Is.True); + Assert.That(hud.SendIntent(new BattleHudIntent(BattleHudIntentKind.Confirm, "flag:5")), Is.True); + int draft = hud.Presenter.AiFlags(controller); + Assert.That(draft, Is.Not.EqualTo(profile)); + + void Tap(Vector2 point) + { + hud.SendPointer(BattleHudIntentKind.PointerDown, 1, point); + hud.SendPointer(BattleHudIntentKind.PointerUp, 1, point); + } + + // This point is inside the native AI panel, above its buttons, + // in both desktop and enlarged touch layout at 800 x 600. + Tap(new Vector2(80, 325)); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Ai)); + Assert.That(session.Preview.TryActorSelectionPoint(enemy, viewport, out Vector2 target), Is.True); + Tap(target); + if (touch) + Tap(target); + Assert.That(hud.Presenter.AiActor, Is.EqualTo(enemy)); + + Vector2 ground = new(5, 5); + hud.SendPointer(BattleHudIntentKind.PointerDown, 1, ground); + hud.SendPointer(BattleHudIntentKind.PointerMove, 1, ground + Vector2.right * 24); + hud.SendPointer(BattleHudIntentKind.PointerUp, 1, ground); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Ai)); + hud.SendPointer(BattleHudIntentKind.PointerDown, 1, ground); + hud.SendPointer(BattleHudIntentKind.PointerUp, 1, ground + Vector2.right * 24); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Ai)); + Assert.That(hud.Presenter.AiFlags(controller), Is.EqualTo(draft)); + + hud.SendPointer(BattleHudIntentKind.PointerDown, 1, ground); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Ai)); + hud.SendPointer(BattleHudIntentKind.PointerUp, 1, ground); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Commands)); + Assert.That(hud.Presenter.AiFlags(controller), Is.EqualTo(profile)); + Assert.That(battle.GetAiProfile(controller), Is.EqualTo(profile)); + Assert.That(battle.WaitingActor, Is.EqualTo(controller)); + Assert.That(battle.RecordedInputCount, Is.EqualTo(inputs)); + BattleActorSnapshot after = battle.Actors.Single(actor => actor.Id == controller); + Assert.That((after.Gauge, after.CastGauge), Is.EqualTo((before.Gauge, before.CastGauge))); + } + + [Test] + public void TouchReleaseBeyondTheTapThresholdOverTheSameTargetDoesNotSubmit() + { + using var session = Create(false, out string enemy); + var viewport = new Rect(0, 0, 800, 600); + session.Preview.View.SetViewportContext(viewport); + BattleHudView hud = TargetHud(session, true, enemy, viewport); + Assert.That(session.Preview.TryActorSelectionPoint(enemy, viewport, out Vector2 start), Is.True); + Vector2 end = start + Vector2.right * 12; + BattleActorSnapshot before = session.Battle.Actors.Single(actor => actor.Id == hud.Presenter.Controller); + int inputs = session.Battle.RecordedInputCount; + + hud.SendPointer(BattleHudIntentKind.PointerDown, 9, start); + hud.SendPointer(BattleHudIntentKind.PointerUp, 9, end); + Assert.That(hud.Presenter.Page, Is.EqualTo(BattleHudPage.Targets)); + Assert.That(session.Battle.RecordedInputCount, Is.EqualTo(inputs)); + BattleActorSnapshot after = session.Battle.Actors.Single(actor => actor.Id == before.Id); + Assert.That((after.Gauge, after.CastGauge), Is.EqualTo((before.Gauge, before.CastGauge))); + + hud.SendPointer(BattleHudIntentKind.PointerDown, 9, end); + hud.SendPointer(BattleHudIntentKind.PointerUp, 9, end); + Assert.That(session.Battle.Inputs.Single(input => input.Kind == BattleInputKind.Command).Target, Is.EqualTo(enemy)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleSelectionOffscreenTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleSelectionOffscreenTests.cs.meta new file mode 100644 index 00000000..31129b2d --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleSelectionOffscreenTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a17b4fd389044b11a7f19cc811b52822 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowPhaseTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowPhaseTests.cs new file mode 100644 index 00000000..a77671ce --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowPhaseTests.cs @@ -0,0 +1,524 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.IO; + using Battle; + using Core.Contract.Enums; + using System.Reflection; + using Core.DataReader.Pol; + using Core.DataReader.Mv3; + using Core.DataReader.Cpk; + using Core.FileSystem; + using Game.Effect.Runtime; + using Core.Primitives; + using Game.Rendering.Native; + using Game.Rendering.Renderer; + using NUnit.Framework; + using ResourceBrowser; + using UnityEngine; + using Object = UnityEngine.Object; + using Color = UnityEngine.Color; + + public sealed class BattleShadowPhaseTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.NonPublic; + + [TestCase(.25f)] + [TestCase(2f)] + public void NativePostShadowOpaqueDrawExecutesAfterShadowAtEitherDepth(float nativeHeight) + { + using var preview = new ResourceModelPreview(null, false); + var material = new Material(Shader.Find("Pal3/Opaque")) { mainTexture = Texture2D.whiteTexture }; + var texture = new Texture2D(1, 1); + texture.SetPixel(0, 0, new Color(0, 0, 0, .5f)); + texture.Apply(); + Mesh mesh = Plane(nativeHeight / 20); + try + { + GameObject root = preview.CreateObject("Native opaque post-shadow boundary"); + root.AddComponent().sharedMesh = mesh; + root.AddComponent().sharedMaterial = material; + GameBoxBattleRenderPhase.Apply(root, 1); + using var shadow = new GameBoxBattleShadowRenderer("PAL3A", texture); + shadow.Begin(); + shadow.Add(new GameBoxBattleShadow(Vector3.zero, 60)); + shadow.End(); + preview.Rendering += camera => shadow.Render(camera, preview.Root.layer); + preview.SetCamera(new Vector3(0, 5, -1), Vector3.zero, 40); + Assert.That(Center(preview).r, Is.EqualTo(1).Within(.015f)); + Assert.That(material.renderQueue, Is.EqualTo(2000), "The pooled source material must retain its original phase."); + } + finally + { + Object.DestroyImmediate(material); + Object.DestroyImmediate(texture); + Object.DestroyImmediate(mesh); + } + } + + [TestCase(101)] + [TestCase(102)] + [TestCase(104)] +#if PAL3A + [TestCase(105)] +#endif + [Category("LocalGameData")] + public void ActualIdleBodyMatchesExplicitOpaqueThenAlphaPostShadowReference(int id) + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Local original-game data is not available."); + using var data = new BattleData(root, 936); + BattleParticipant participant = data.CreateParticipant(id, BattleSide.Ally, BattleSlot.Water); + string path = data.ActionPath(participant, data.IdleAction(participant)); + Mv3File model = data.Read(path, new Mv3FileReader()); + using var preview = new ResourceModelPreview(data.Resources, false); + GameObject body = preview.CreateObject("Actual post-shadow body " + id); + preview.SetVertexModel(body, path, model); + var renderers = body.GetComponentsInChildren(true); + var originals = renderers.Select(renderer => renderer.sharedMaterials).ToArray(); + using var shadow = new GameBoxBattleShadowRenderer("PAL3A", preview.GetTexture("basedata.cpk\\shadow.tga")); + shadow.Begin(); + shadow.Add(new GameBoxBattleShadow(Vector3.zero, GameBoxBattleShadow.CaptureRadius(model))); + shadow.End(); + preview.Rendering += camera => shadow.Render(camera, preview.Root.layer); + preview.SetCamera(new Vector3(3, 2, -5), new Vector3(0, .5f, 0), 40); + GameBoxBattleRenderPhase.Apply(body, 1); + Texture2D Capture() + { + RenderTexture target = preview.Render(256, 256); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(256, 256); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, 256, 256), 0, 0); + image.Apply(); + return image; + } + finally { RenderTexture.active = previous; } + } + Texture2D actual = Capture(); + var copies = new List(); + Texture2D reference = null; + try + { + for (int i = 0; i < renderers.Length; i++) + renderers[i].sharedMaterials = originals[i].Select(source => + { + var copy = new Material(source) { renderQueue = source.renderQueue <= 2500 ? 3002 : 3003 }; + copies.Add(copy); + return copy; + }).ToArray(); + reference = Capture(); + var actualPixels = actual.GetPixels32(); + var expectedPixels = reference.GetPixels32(); + int changed = actualPixels.Where((pixel, index) => Math.Abs(pixel.r - expectedPixels[index].r) > 1 || + Math.Abs(pixel.g - expectedPixels[index].g) > 1 || Math.Abs(pixel.b - expectedPixels[index].b) > 1).Count(); + Assert.That(changed, Is.Zero, "The actual body must keep the independently specified opaque-before-alpha post-shadow pass."); + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_SHADOW_QA_ROOT"); + if (!string.IsNullOrEmpty(output)) + { + Directory.CreateDirectory(output); + File.WriteAllBytes(Path.Combine(output, BattleData.Variant + "-body-" + id + "-phase.png"), actual.EncodeToPNG()); + File.WriteAllBytes(Path.Combine(output, BattleData.Variant + "-body-" + id + "-reference.png"), reference.EncodeToPNG()); + } + } + finally + { + for (int i = 0; i < renderers.Length; i++) + renderers[i].sharedMaterials = originals[i]; + GameBoxBattleRenderPhase.Apply(body, 1); + foreach (Material copy in copies) + Object.DestroyImmediate(copy); + Object.DestroyImmediate(actual); + Object.DestroyImmediate(reference); + } + } + + [Test] + public void PhaseCopiesTrackUniformsAndMaterialReplacementWithoutChangingTheSharedViewer() + { + var root = new GameObject("Post-shadow source replacement"); + var viewer = new GameObject("Shared ordinary viewer"); + var source = new Material(Shader.Find("Pal3/Opaque")); + var alpha = new Material(Shader.Find("Pal3/Transparent")); + try + { + var renderer = root.AddComponent(); + viewer.AddComponent().sharedMaterial = source; + renderer.sharedMaterial = source; + GameBoxBattleRenderPhase.Apply(root, 1); + Material first = renderer.sharedMaterial; + Assert.That(first, Is.Not.SameAs(source)); + Assert.That(first.renderQueue, Is.EqualTo(3002)); + source.SetColor("_TintColor", new Color(.2f, .3f, .4f, .6f)); + GameBoxBattleRenderPhase.Apply(root, 1); + Assert.That(renderer.sharedMaterial.GetColor("_TintColor"), Is.EqualTo(source.GetColor("_TintColor"))); + Assert.That(viewer.GetComponent().sharedMaterial, Is.SameAs(source)); + Assert.That(source.renderQueue, Is.EqualTo(2000)); + renderer.sharedMaterial = alpha; + GameBoxBattleRenderPhase.Apply(root, 1); + Material second = renderer.sharedMaterial; + Assert.That(first == null, Is.True, "A replaced material's private phase copy must be released."); + Assert.That(second.renderQueue, Is.EqualTo(3003)); + Assert.That(second.shader, Is.SameAs(alpha.shader)); + GameBoxBattleRenderPhase.Apply(root, -1); + Assert.That(second == null, Is.True); + Assert.That(renderer.sharedMaterial, Is.SameAs(alpha)); + GameBoxBattleRenderPhase.Apply(root, 1); + Material last = renderer.sharedMaterial; + Object.DestroyImmediate(root); + Assert.That(last == null, Is.True, "The owning object must release its private material copies."); + Assert.That(source != null && alpha != null, Is.True); + } + finally + { + Object.DestroyImmediate(root); + Object.DestroyImmediate(viewer); + Object.DestroyImmediate(source); + Object.DestroyImmediate(alpha); + } + } + + [Test] + public void PhaseSourcesAndTexturesSurviveEffectCacheTrimUntilTheirOwnerIsReleased() + { + var hash = new Crc32Hash(); + hash.Init(); + using var resources = new EffectResources(new CpkFileSystem(Application.temporaryCachePath, hash, 936)); + GameObject root = new("Combat phase cache lease"); + try + { + Material source = resources.Material("", false, false); + root.AddComponent().sharedMaterial = source; + GameBoxBattleRenderPhase.Apply(root, 2); + Material copy = root.GetComponent().sharedMaterial; + resources.TrimUnusedRenderAssets(new[] { root }); + Assert.That(source != null, Is.True); + Assert.That(resources.Material("", false, false), Is.SameAs(source)); + GameBoxBattleRenderPhase.Apply(root, 2); + Assert.That(root.GetComponent().sharedMaterial, Is.SameAs(copy)); + Object.DestroyImmediate(root); + Assert.That(copy == null, Is.True); + resources.TrimUnusedRenderAssets(Array.Empty()); + Assert.That(source == null, Is.True); + } + finally { Object.DestroyImmediate(root); } + } + + [Test] + public void NativeBladeUpdatesAgeTwiceWithoutAddingPoseSamplesAndKeepDistinctFlushSnapshots() + { + using var preview = new ResourceModelPreview(null, false); + GameObject owner = preview.CreateObject("Blade pose fixture"); + using var blade = new WeaponBlade(new[] + { + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Tx = 20 }, TintColor = 0xff101010 }, + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Tx = -20 }, TintColor = 0xff101010 } + }); + var material = WeaponBlade.CreateMaterial(); + try + { + blade.SamplePose(owner.transform, true, .12f); + blade.Advance(.02f, 1); + blade.Advance(.02f, 1); + owner.transform.position = Vector3.forward; + blade.SamplePose(owner.transform, true, .12f); + int count = (int)typeof(WeaponBlade).GetField("_count", Members).GetValue(blade); + Camera camera = preview.Root.scene.GetRootGameObjects().Select(root => root.GetComponent()).First(value => value != null); + blade.Advance(.02f, 1); + blade.RenderFlush(camera, material, owner.layer, 0, true); + blade.Advance(.02f, 1); + blade.RenderFlush(camera, material, owner.layer, 1, true); + Assert.That((float)typeof(WeaponBlade).GetField("_time", Members).GetValue(blade), Is.EqualTo(.08f).Within(.000001f)); + Assert.That((int)typeof(WeaponBlade).GetField("_count", Members).GetValue(blade), Is.EqualTo(count)); + Mesh[] meshes = (Mesh[])typeof(WeaponBlade).GetField("_flushMeshes", Members).GetValue(blade); + Assert.That(meshes[0], Is.Not.SameAs(meshes[1])); + Assert.That(meshes[0].vertices, Is.EqualTo(meshes[1].vertices)); + Assert.That(meshes[0].colors32[0].a, Is.GreaterThan(meshes[1].colors32[0].a)); + var renderers = (MeshRenderer[])typeof(WeaponBlade).GetField("_flushRenderers", Members).GetValue(blade); + Assert.That(renderers.Select(renderer => renderer.sortingOrder), Is.EqualTo(new[] { 0, 3 })); + UnityEngine.Color32[] saved = meshes[0].colors32; + blade.RenderFlush(camera, material, owner.layer, 0, false); + Assert.That(meshes[0].colors32, Is.EqualTo(saved)); + } + finally { Object.DestroyImmediate(material); } + } + + [Test] + public void SecondBladeFlushCompositesAfterDirectEffectsAndFirstFlushBeforeShadow() + { + using var preview = new ResourceModelPreview(null, false); + GameObject owner = preview.CreateObject("Blade GPU fixture"); + using var blade = new WeaponBlade(new[] + { + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Tx = 20 }, TintColor = 0xffcc0000 }, + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Tx = -20 }, TintColor = 0xffcc0000 } + }); + var bladeMaterial = WeaponBlade.CreateMaterial(); + var shadowTexture = new Texture2D(1, 1); + shadowTexture.SetPixel(0, 0, new Color(.5f, .5f, .5f, 1)); + shadowTexture.Apply(); + var directTexture = new Texture2D(1, 1); + directTexture.SetPixel(0, 0, new Color(0, 0, 1, .5f)); + directTexture.Apply(); + var directMaterial = new Material(Shader.Find("Pal3/Effect")) { mainTexture = directTexture }; + directMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); + directMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); + Mesh plane = Plane(-.01f); + try + { + GameObject effect = preview.CreateObject("Direct effect order fixture"); + effect.AddComponent().sharedMesh = plane; + effect.AddComponent().sharedMaterial = directMaterial; + GameBoxBattleRenderPhase.Apply(effect, 2); + using var shadow = new GameBoxBattleShadowRenderer("PAL3", shadowTexture); + shadow.Begin(); + shadow.Add(new GameBoxBattleShadow(Vector3.zero, 60)); + shadow.End(); + preview.Rendering += camera => shadow.Render(camera, preview.Root.layer); + owner.transform.position = new Vector3(0, 0, -1); + blade.SamplePose(owner.transform, true, .12f); + blade.Advance(.02f, 1); + blade.Advance(.02f, 1); + owner.transform.position = new Vector3(0, 0, 1); + blade.SamplePose(owner.transform, true, .12f); + Camera camera = preview.Root.scene.GetRootGameObjects().Select(root => root.GetComponent()).First(value => value != null); + blade.Advance(.02f, 1); + blade.RenderFlush(camera, bladeMaterial, owner.layer, 0, true); + blade.Advance(.02f, 1); + blade.RenderFlush(camera, bladeMaterial, owner.layer, 1, true); + Mesh[] meshes = (Mesh[])typeof(WeaponBlade).GetField("_flushMeshes", Members).GetValue(blade); + float first = (meshes[0].colors32[2].a + meshes[0].colors32[4].a) / 510f; + float second = (meshes[1].colors32[2].a + meshes[1].colors32[4].a) / 510f; + float alpha = directTexture.GetPixel(0, 0).a; + float expected = (.12f + .8f * first) * shadowTexture.GetPixel(0, 0).r * (1 - alpha) + .8f * second; + preview.SetCamera(new Vector3(0, 5, -.001f), Vector3.zero, 40); + Color correct = Center(preview); + Assert.That(correct.r, Is.EqualTo(expected).Within(.02f)); + var renderers = (MeshRenderer[])typeof(WeaponBlade).GetField("_flushRenderers", Members).GetValue(blade); + renderers[1].sortingOrder = 1; + Color wrong = Center(preview); + Assert.That(correct.r - wrong.r, Is.GreaterThan(.05f), "Moving the second Flush ahead of the direct effect must change its composition."); + } + finally + { + Object.DestroyImmediate(bladeMaterial); + Object.DestroyImmediate(shadowTexture); + Object.DestroyImmediate(directTexture); + Object.DestroyImmediate(directMaterial); + Object.DestroyImmediate(plane); + } + } + +#if PAL3 + [Test] + [Category("LocalGameData")] + public void PausedPresentationRepaintsReuseBothBladeSnapshotsWithoutAgingAgain() + { + string root = Environment.GetEnvironmentVariable("PAL3_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Local original-game data is not available."); + using var data = new BattleData(root, 936); + var scenario = new BattleScenario { Variant = "PAL3", Scene = data.Scenes.First(), DataFingerprint = data.Fingerprint }; + BattleParticipant ally = data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + scenario.Participants.Add(ally); + int enemy = data.Database.CombatActorInfos.First(pair => pair.Key > 0 && pair.Value.Type != CombatActorType.MainActor && + !string.IsNullOrEmpty(pair.Value.ModelId) && data.Resources.Find(Core.Contract.Constants.FileConstants.GetActorFolderVirtualPath(pair.Value.ModelId) + pair.Value.ModelId + ".ini") != null).Key; + scenario.Participants.Add(data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + using var preview = new BattlePreview(data, new BattleSetup(scenario)); + var actor = preview.View.Root.transform.Find(ally.InstanceId).GetComponentInChildren(); + var blade = new WeaponBlade(new[] + { + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Tx = 20 }, TintColor = 0xff101010 }, + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Tx = -20 }, TintColor = 0xff101010 } + }); + GameObject pose = preview.View.CreateObject("Cached blade pose fixture"); + blade.SamplePose(pose.transform, true, .12f); + blade.Advance(.02f, 1); + blade.Advance(.02f, 1); + pose.transform.position = Vector3.forward; + blade.SamplePose(pose.transform, true, .12f); + var blades = (Dictionary)typeof(Mv3ModelRenderer).GetField("_weaponBlades", Members).GetValue(actor); + blades.Add("fixture", blade); + actor.SampleWeaponBlades(0, 1, .12f); + preview.View.Render(128, 128); + float clock = (float)typeof(WeaponBlade).GetField("_time", Members).GetValue(blade); + int count = (int)typeof(WeaponBlade).GetField("_count", Members).GetValue(blade); + Mesh[] meshes = (Mesh[])typeof(WeaponBlade).GetField("_flushMeshes", Members).GetValue(blade); + var first = meshes[0].colors32; + var second = meshes[1].colors32; + for (int repaint = 0; repaint < 3; repaint++) + preview.View.Render(128, 128); + Assert.That((float)typeof(WeaponBlade).GetField("_time", Members).GetValue(blade), Is.EqualTo(clock)); + Assert.That((int)typeof(WeaponBlade).GetField("_count", Members).GetValue(blade), Is.EqualTo(count)); + Assert.That(meshes[0].colors32, Is.EqualTo(first)); + Assert.That(meshes[1].colors32, Is.EqualTo(second)); + // Sample advances both the authoring clock and its actors. A second + // actor sample at an earlier time would seek and dispose this trail. + preview.Sample(.02f); + preview.View.Render(128, 128); + Assert.That(Blades(actor)["fixture"], Is.SameAs(blade)); + Assert.That(BladeClock(blade), Is.EqualTo(clock + .04f).Within(.000001f)); + preview.Sample(.02f); + preview.View.Render(128, 128); + Assert.That(BladeClock(blade), Is.EqualTo(clock + .04f).Within(.000001f)); + } +#endif + + [TestCase(false, false)] + [TestCase(true, false)] + [TestCase(true, true)] + public void PendingBladeAdvanceSurvivesDuplicatePreparationAndTransferThenResetsForFreeze(bool duplicate, bool transfer) + { + using var preview = new ResourceModelPreview(null, false); + GameObject owner = preview.CreateObject("Pending blade clock fixture"); + var renderer = owner.AddComponent(); + renderer.UseRenderBladeClock = true; + var blade = SeedBlade(owner.transform); + Blades(renderer).Add("fixture", blade); + try + { + Camera camera = preview.Root.scene.GetRootGameObjects().Select(root => root.GetComponent()).First(value => value != null); + renderer.SampleWeaponBlades(0, 1, .12f); + renderer.RenderPublishedWeaponBlades(camera, .02f, true, false); + float before = BladeClock(blade); + renderer.SampleWeaponBlades(.02, 1, .12f); + if (duplicate) + renderer.SampleWeaponBlades(.02, 1, .12f); + if (transfer) + { + var replacement = preview.CreateObject("Replacement pending blade owner").AddComponent(); + replacement.UseRenderBladeClock = true; + replacement.MoveWeaponPresentationFrom(renderer); + renderer.Dispose(); + renderer = replacement; + renderer.SampleWeaponBlades(.02, 1, .12f); + } + renderer.RenderPublishedWeaponBlades(camera, .02f, true, false); + Assert.That(BladeClock(blade), Is.EqualTo(before + .04f).Within(.000001f)); + float advanced = BladeClock(blade); + renderer.SampleWeaponBlades(.02, 1, .12f); + renderer.SampleWeaponBlades(.02, 1, .12f); + renderer.RenderPublishedWeaponBlades(camera, .02f, true, false); + Assert.That(BladeClock(blade), Is.EqualTo(advanced), "The next genuinely frozen frame must consume no aging."); + renderer.RenderPublishedWeaponBlades(camera, .02f, false, false); + Assert.That(BladeClock(blade), Is.EqualTo(advanced)); + renderer.SampleWeaponBlades(.04, 1, .12f); + renderer.SampleWeaponBlades(.06, 1, .12f); + renderer.SampleWeaponBlades(.06, 1, .12f); + renderer.RenderPublishedWeaponBlades(camera, .04f, true, false); + Assert.That(BladeClock(blade), Is.EqualTo(advanced + .08f).Within(.000001f), "Coalesced preparation must retain its unconsumed advance."); + } + finally { renderer.Dispose(); } + } + +#if PAL3 + [TestCase(false)] + [TestCase(true)] + [Category("LocalGameData")] + public void NormalSessionStepAndTickKeepBothNativeAgingUpdatesAcrossTheirDoubleApply(bool tick) + { + string root = Environment.GetEnvironmentVariable("PAL3_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Local original-game data is not available."); + using var session = new BattleEditorSession(); + session.Load(root, 936); + BattleData data = session.Data; + var scenario = new BattleScenario { Variant = "PAL3", Scene = data.Scenes.First(), DataFingerprint = data.Fingerprint }; + BattleParticipant ally = data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + scenario.Participants.Add(ally); + int enemy = data.Database.CombatActorInfos.First(pair => pair.Key > 0 && pair.Value.Type != CombatActorType.MainActor && + !string.IsNullOrEmpty(pair.Value.ModelId) && data.Resources.Find(Core.Contract.Constants.FileConstants.GetActorFolderVirtualPath(pair.Value.ModelId) + pair.Value.ModelId + ".ini") != null).Key; + scenario.Participants.Add(data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + session.StartBattle(scenario); + var renderer = session.Preview.View.Root.transform.Find(ally.InstanceId).GetComponentInChildren(); + var blade = SeedBlade(renderer.transform); + Blades(renderer).Add("fixture", blade); + session.Preview.View.Render(128, 128); + float before = BladeClock(blade); + long initial = session.Battle.Actors.Single(actor => actor.Id == ally.InstanceId).NativePresentationTick; + if (tick) + { + session.IsPlaying = true; + session.Tick(.020001f); + } + else + session.StepBattle(); + BattleActorSnapshot state = session.Battle.Actors.Single(actor => actor.Id == ally.InstanceId); + Assert.That(state.NativePresentationTick, Is.GreaterThan(initial)); + session.Preview.View.Render(128, 128); + float expected = before + .04f * state.NativePlaybackRate; + Assert.That(BladeClock(blade), Is.EqualTo(expected).Within(.000001f)); + var random = (BattleRandom)typeof(BattleSession).GetField("_random", Members).GetValue(session.Battle); + uint randomState = random.State; + long frame = session.Battle.Tick; + for (int repaint = 0; repaint < 3; repaint++) + { + session.SyncBattle(); + session.Preview.View.Render(128, 128); + } + Assert.That(BladeClock(blade), Is.EqualTo(expected).Within(.000001f)); + Assert.That(session.Battle.Tick, Is.EqualTo(frame)); + Assert.That(random.State, Is.EqualTo(randomState)); + Assert.That(session.Battle.Actors.Single(actor => actor.Id == ally.InstanceId).NativePresentationTick, Is.EqualTo(state.NativePresentationTick)); + } +#endif + + private static Dictionary Blades(Mv3ModelRenderer renderer) => + (Dictionary)typeof(Mv3ModelRenderer).GetField("_weaponBlades", Members).GetValue(renderer); + + private static float BladeClock(WeaponBlade blade) => + (float)typeof(WeaponBlade).GetField("_time", Members).GetValue(blade); + + private static WeaponBlade SeedBlade(Transform pose) + { + var blade = new WeaponBlade(new[] + { + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Tx = 20 }, TintColor = 0xff101010 }, + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Tx = -20 }, TintColor = 0xff101010 } + }); + blade.SamplePose(pose, true, .12f); + blade.Advance(.02f, 1); + pose.position += Vector3.forward; + blade.SamplePose(pose, true, .12f); + return blade; + } + + private static Mesh Plane(float y) => new() + { + vertices = new[] { new Vector3(-3, y, -3), new Vector3(3, y, -3), new Vector3(3, y, 3), new Vector3(-3, y, 3) }, + triangles = new[] { 0, 2, 1, 0, 3, 2 }, + uv = new[] { Vector2.zero, Vector2.right, Vector2.one, Vector2.up }, + colors = Enumerable.Repeat(Color.white, 4).ToArray(), + normals = Enumerable.Repeat(Vector3.up, 4).ToArray() + }; + + private static Color Center(ResourceModelPreview preview) + { + RenderTexture target = preview.Render(128, 128); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(1, 1); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(64, 64, 1, 1), 0, 0); + image.Apply(); + return image.GetPixel(0, 0); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowPhaseTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowPhaseTests.cs.meta new file mode 100644 index 00000000..dd23b096 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowPhaseTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c7e70a9494cf41e4b924a44c33819ff5 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowTests.cs new file mode 100644 index 00000000..45c89af6 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowTests.cs @@ -0,0 +1,518 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Core.Contract.Enums; + using Core.DataReader.Mv3; + using Core.DataReader.Data; + using Game.Effect.Runtime; + using Core.Primitives; + using Game.Rendering.Native; + using NUnit.Framework; + using ResourceBrowser; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed class BattleShadowTests + { + [Test] + public void NativeRadiusUsesAuthoredActionUnionAndCompleteWidths() + { + var model = new Mv3File(0, Array.Empty(), Array.Empty(), new[] + { + new Mv3Mesh { GameBoxBoundsMin = new GameBoxVector3(-10, -5, -20), GameBoxBoundsMax = new GameBoxVector3(15, 50, 10) }, + new Mv3Mesh { GameBoxBoundsMin = new GameBoxVector3(-20, -10, -30), GameBoxBoundsMax = new GameBoxVector3(10, 70, 30) } + }, Array.Empty()); + Assert.That(GameBoxBattleShadow.CaptureRadius(model), Is.EqualTo(35)); + var shadow = new GameBoxBattleShadow(new Vector3(-2, 4, 3), 35); + Assert.That(shadow.Corner(0), Is.EqualTo(new Vector3(-.25f, 4.025f, 4.75f))); + Assert.That(shadow.Corner(2), Is.EqualTo(new Vector3(-3.75f, 4.025f, 1.25f))); + } + + [TestCase(false)] + [TestCase(true)] + public void ReleasedVisibilityMatrixRetainsAllyHpExceptionAndPal3ABlendThreshold(bool pal3A) + { + // Released Shadow.Render oracle: 160 combinations per executable, + // including native slots 0, 4, 5, 10 and values adjacent to .5. + int visible = 0; + foreach (int index in new[] { 0, 4, 5, 10 }) + foreach (bool valid in new[] { false, true }) + foreach (bool modelAlive in new[] { false, true }) + foreach (int hp in new[] { 0, 1 }) + foreach (float blend in new[] { 0, .44f, .49999997f, .5f, 1 }) + if (GameBoxBattleShadow.IsVisible(pal3A, valid, modelAlive, index < 5, hp, blend)) + visible++; + Assert.That(visible, Is.EqualTo(pal3A ? 20 : 50)); + Assert.That(GameBoxBattleShadow.IsVisible(pal3A, true, false, true, 1, 1), Is.True); + Assert.That(GameBoxBattleShadow.IsVisible(pal3A, true, false, false, 1, 1), Is.False); + Assert.That(GameBoxBattleShadow.IsVisible(pal3A, true, true, false, 0, .44f), Is.EqualTo(!pal3A)); + Assert.That(GameBoxBattleShadow.IsVisible(pal3A, true, true, false, 0, .5f), Is.True); + } + + [TestCase(false, false, 7310, -1)] + [TestCase(false, true, 101, -1)] + [TestCase(true, false, 7310, 1)] + [TestCase(true, false, 7311, -1)] + [TestCase(true, true, 101, 1)] + public void PublishedActorFlushGroupsBracketShadows(bool pal3A, bool ally, int actorId, int expected) + { + Assert.That(GameBoxBattleRenderOrder.Actor(pal3A, ally, actorId), Is.EqualTo(expected)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ShippedBlendEquationsRenderOnGpu(string variant) + { + Assert.That(SystemInfo.graphicsDeviceType, Is.Not.EqualTo(UnityEngine.Rendering.GraphicsDeviceType.Null)); + using var preview = new ResourceModelPreview(null, false); + var texture = new Texture2D(1, 1, TextureFormat.RGBA32, false); + texture.SetPixel(0, 0, new UnityEngine.Color(.25f, .5f, .75f, .25f)); + texture.Apply(); + try + { + using var shadow = new GameBoxBattleShadowRenderer(variant, texture); + shadow.Begin(); + shadow.Add(new GameBoxBattleShadow(Vector3.zero, 60)); + shadow.End(); + preview.Rendering += camera => shadow.Render(camera, preview.Root.layer); + preview.SetCamera(new Vector3(0, 5, -1), Vector3.zero, 40); + Texture2D image = Read(preview.Render(128, 128)); + try + { + UnityEngine.Color actual = image.GetPixel(64, 64); + UnityEngine.Color background = new(.12f, .13f, .15f); + UnityEngine.Color sample = texture.GetPixel(0, 0); + UnityEngine.Color expected = variant == "PAL3" ? background * sample : sample * (1 - sample.a) + background * sample.a; + Assert.That(actual.r, Is.EqualTo(expected.r).Within(.015f)); + Assert.That(actual.g, Is.EqualTo(expected.g).Within(.015f)); + Assert.That(actual.b, Is.EqualTo(expected.b).Within(.015f)); + } + finally { Object.DestroyImmediate(image); } + } + finally { Object.DestroyImmediate(texture); } + } + + [TestCase(-1, false)] + [TestCase(1, true)] + [TestCase(2, true)] + public void TransparentSortingCanBracketTheNativeShadow(int order, bool after) + { + using var preview = new ResourceModelPreview(null, false); + var shadowTexture = new Texture2D(1, 1, TextureFormat.RGBA32, false); + var bodyTexture = new Texture2D(1, 1, TextureFormat.RGBA32, false); + shadowTexture.SetPixel(0, 0, new UnityEngine.Color(.5f, .5f, .5f, 1)); + bodyTexture.SetPixel(0, 0, new UnityEngine.Color(1, 0, 0, .5f)); + shadowTexture.Apply(); + bodyTexture.Apply(); + var bodyMaterial = new Material(Shader.Find("Pal3/Effect")) { mainTexture = bodyTexture }; + bodyMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); + bodyMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); + var mesh = new Mesh + { + vertices = new[] { new Vector3(-3, .1f, -3), new Vector3(3, .1f, -3), new Vector3(3, .1f, 3), new Vector3(-3, .1f, 3) }, + uv = new[] { Vector2.zero, Vector2.right, Vector2.one, Vector2.up }, + colors = Enumerable.Repeat(UnityEngine.Color.white, 4).ToArray(), + triangles = new[] { 0, 1, 2, 0, 2, 3 } + }; + try + { + GameObject body = preview.CreateObject("Transparent role-order fixture"); + body.AddComponent().sharedMesh = mesh; + var bodyRenderer = body.AddComponent(); + bodyRenderer.sharedMaterial = bodyMaterial; + bodyRenderer.sortingOrder = order; + using var shadow = new GameBoxBattleShadowRenderer("PAL3", shadowTexture); + shadow.Begin(); + shadow.Add(new GameBoxBattleShadow(Vector3.zero, 60)); + shadow.End(); + preview.Rendering += camera => shadow.Render(camera, preview.Root.layer); + preview.SetCamera(new Vector3(0, 5, -1), Vector3.zero, 40); + Texture2D image = Read(preview.Render(128, 128)); + try + { + float background = .12f, bodyAlpha = bodyTexture.GetPixel(0, 0).a, shade = shadowTexture.GetPixel(0, 0).r; + float expected = after ? background * shade * (1 - bodyAlpha) + bodyAlpha : + (background * (1 - bodyAlpha) + bodyAlpha) * shade; + Assert.That(image.GetPixel(64, 64).r, Is.EqualTo(expected).Within(.015f)); + } + finally { Object.DestroyImmediate(image); } + } + finally + { + Object.DestroyImmediate(bodyMaterial); + Object.DestroyImmediate(mesh); + Object.DestroyImmediate(bodyTexture); + Object.DestroyImmediate(shadowTexture); + } + } + + [TestCase(false)] + [Category("LocalGameData")] + public void RealBattleShadowKeepsCapturedRadiusAcrossActionsAndFollowsCurrentHeight(bool toon) + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT") ?? + Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root)) + Assert.Ignore("Local original-game data is not available."); + using var data = new BattleData(root, 936); + int ally = data.Database.CombatActorInfos.Keys.First(id => id > 0 && data.Database.CombatActorInfos[id].Type == CombatActorType.MainActor); + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = data.Scenes.First(), DataFingerprint = data.Fingerprint, ToonRendering = toon }; + BattleParticipant actor = data.CreateParticipant(ally, BattleSide.Ally, BattleSlot.Water); + scenario.Participants.Add(actor); + int enemy = data.Database.CombatActorInfos.Keys.First(id => id > 0 && + data.Database.CombatActorInfos[id].Type != CombatActorType.MainActor && + !string.IsNullOrEmpty(data.Database.CombatActorInfos[id].ModelId) && + data.Resources.Find(Core.Contract.Constants.FileConstants.GetActorFolderVirtualPath(data.Database.CombatActorInfos[id].ModelId) + + data.Database.CombatActorInfos[id].ModelId + ".ini") != null); + scenario.Participants.Add(data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); +#if PAL3A + scenario.Participants.Add(data.CreateParticipant(7310, BattleSide.Enemy, BattleSlot.Fire)); +#endif + using var preview = new BattlePreview(data, new BattleSetup(scenario)); + var radii = (Dictionary)typeof(BattlePreview).GetField("_shadowRadii", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview); + float initial = radii[actor.InstanceId]; + string attack = data.AttackAction(actor); + preview.PlayAction(actor.InstanceId, attack); + Assert.That(radii[actor.InstanceId], Is.EqualTo(initial)); + var renderer = (GameBoxBattleShadowRenderer)typeof(BattlePreview).GetField("_shadows", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview); + Assert.That(renderer.Count, Is.EqualTo(scenario.Participants.Count)); + Transform body = preview.View.Root.transform.Find(actor.InstanceId); + body.position += new Vector3(1, 2, 3); + typeof(BattlePreview).GetMethod("SampleShadows", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(preview, null); + var mesh = (Mesh)typeof(GameBoxBattleShadowRenderer).GetField("_mesh", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(renderer); + Assert.That(mesh.vertices.Take(4).All(vertex => Mathf.Abs(vertex.y - (body.position.y + .025f)) < .00001f), Is.True); + Assert.That(mesh.vertices.Take(4).Average(vertex => vertex.x), Is.EqualTo(body.position.x).Within(.00001f)); + Assert.That(preview.View.Dependencies["basedata.cpk\\shadow.tga"], Is.True); + preview.Sample(.2f); + preview.View.SetCamera(body.position + new Vector3(3, 7, -7), body.position, 40); + Texture2D image = Read(preview.View.Render(800, 600)); + try + { + Assert.That(image.GetPixels32().Select(pixel => (pixel.r, pixel.g, pixel.b)).Distinct().Take(100).Count(), Is.GreaterThan(30)); + foreach (BattleParticipant participant in scenario.Participants) + { + int expected = BattleData.Variant == "PAL3A" && (participant.Side == BattleSide.Ally || participant.ActorId == 7310) ? 1 : -1; + Transform actorRoot = preview.View.Root.transform.Find(participant.InstanceId); + Assert.That(actorRoot.GetComponentsInChildren(true).All(part => part.sortingOrder == expected), Is.True, + $"Original body/equipment flush group for {participant.ActorId}"); + } + renderer.Begin(); + renderer.End(); + Texture2D without = Read(preview.View.Render(800, 600)); + try + { + UnityEngine.Color32[] withPixels = image.GetPixels32(); + UnityEngine.Color32[] withoutPixels = without.GetPixels32(); + int changed = withPixels.Where((pixel, index) => Math.Abs(pixel.r - withoutPixels[index].r) > 1 || + Math.Abs(pixel.g - withoutPixels[index].g) > 1 || Math.Abs(pixel.b - withoutPixels[index].b) > 1).Count(); + Assert.That(changed, Is.GreaterThan(20), "The original texture shadow must visibly affect the actual battle floor."); + } + finally { Object.DestroyImmediate(without); } + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_SHADOW_QA_ROOT"); + if (!string.IsNullOrEmpty(output)) + { + Directory.CreateDirectory(output); + File.WriteAllBytes(Path.Combine(output, BattleData.Variant + (toon ? "-toon" : "-original") + "-shadows.png"), image.EncodeToPNG()); + } + } + finally { Object.DestroyImmediate(image); } + } + + [TestCase(null)] +#if PAL3 + [TestCase("Z06")] +#endif +#if PAL3A + [TestCase("M06C")] + [TestCase("m06d")] + [TestCase("M10A")] + [TestCase("M10B")] + [TestCase("M15A")] +#endif + [Category("LocalGameData")] + public void ToonBattleUsesModelShadowCastersAndKeepsNativeBlobAndQueuesOut(string scene) + { + using var data = new BattleData(Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"), 936); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = scene ?? data.Scenes.First(), + DataFingerprint = data.Fingerprint, + ToonRendering = true, + Music = "NONE" + }; + scenario.Participants.Add(data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(data, id)); + scenario.Participants.Add(data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + using var preview = new BattlePreview(data, new BattleSetup(scenario)); + preview.Audio.Muted = preview.Effects.Muted = true; + Assert.That(typeof(BattlePreview).GetField("_shadows", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview), Is.Null); + Assert.That(preview.View.Dependencies.ContainsKey("basedata.cpk\\shadow.tga"), Is.False); + MeshRenderer[] bodies = scenario.Participants.SelectMany(actor => preview.View.Root.transform.Find(actor.InstanceId).GetComponentsInChildren()).ToArray(); + Assert.That(bodies, Is.Not.Empty); + Assert.That(bodies.All(body => body.shadowCastingMode == UnityEngine.Rendering.ShadowCastingMode.On), Is.True); + Assert.That(bodies.SelectMany(body => body.sharedMaterials).Where(material => material.shader.name is "Pal3/ToonOpaque" or "Pal3/ToonCutout") + .All(material => material.renderQueue <= 2500), Is.True, "Native post-shadow queues must not remove Toon bodies from opaque render passes."); + Light light = preview.View.Root.GetComponentInChildren(); + Assert.That(light.shadows, Is.EqualTo(LightShadows.Soft)); + Bounds allBodies = bodies[0].bounds; + foreach (MeshRenderer body in bodies.Skip(1)) + allBodies.Encapsulate(body.bounds); + float distance = Math.Max(12, allBodies.extents.magnitude * 2.8f); + // Look across the key's ground projection so received shadows are + // visible beside bodies rather than hidden behind their bounds. + preview.View.SetCamera(allBodies.center + new Vector3(14, 12, 8).normalized * distance, allBodies.center, 50); + Texture2D with = Read(preview.View.Render(800, 600)); + var camera = (Camera)typeof(ResourceModelPreview).GetField("_camera", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview.View); + Rect[] bodyPixels = bodies.Select(body => + { + Bounds bounds = body.bounds; + var points = Enumerable.Range(0, 8).Select(corner => camera.WorldToViewportPoint(new Vector3( + (corner & 1) == 0 ? bounds.min.x : bounds.max.x, + (corner & 2) == 0 ? bounds.min.y : bounds.max.y, + (corner & 4) == 0 ? bounds.min.z : bounds.max.z))).ToArray(); + Assert.That(points.All(point => point.z > camera.nearClipPlane), Is.True, "The caster exclusion bounds must remain in front of the test camera."); + return Rect.MinMaxRect(points.Min(point => point.x) * with.width - 2, points.Min(point => point.y) * with.height - 2, + points.Max(point => point.x) * with.width + 2, points.Max(point => point.y) * with.height + 2); + }).ToArray(); + foreach (MeshRenderer body in bodies) + body.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + Texture2D without = Read(preview.View.Render(800, 600)); + Renderer[] environment = preview.View.Root.GetComponentsInChildren().Where(renderer => !bodies.Contains(renderer)).ToArray(); + bool[] visible = environment.Select(renderer => renderer.enabled).ToArray(); + UnityEngine.Color background = camera.backgroundColor; + Texture2D silhouette; + try + { + foreach (Renderer renderer in environment) + renderer.enabled = false; + camera.backgroundColor = UnityEngine.Color.clear; + silhouette = Read(preview.View.Render(800, 600)); + } + finally + { + for (int index = 0; index < environment.Length; index++) + environment[index].enabled = visible[index]; + camera.backgroundColor = background; + } + try + { + UnityEngine.Color32[] first = with.GetPixels32(), second = without.GetPixels32(); + UnityEngine.Color32[] maskPixels = silhouette.GetPixels32(); + Assert.That(maskPixels.Count(pixel => pixel.a == 0), Is.GreaterThan(maskPixels.Length / 2), "A body-only render must preserve its transparent background."); + Assert.That(maskPixels.Count(pixel => pixel.a > 16), Is.GreaterThan(100)); + var bodyMask = new bool[maskPixels.Length]; + for (int index = 0; index < maskPixels.Length; index++) + if (maskPixels[index].a > 16) + for (int y = Math.Max(0, index / with.width - 1); y <= Math.Min(with.height - 1, index / with.width + 1); y++) + for (int x = Math.Max(0, index % with.width - 1); x <= Math.Min(with.width - 1, index % with.width + 1); x++) + bodyMask[y * with.width + x] = true; + int changed = first.Where((pixel, index) => !bodyMask[index] && + pixel.r + pixel.g + pixel.b + 5 < second[index].r + second[index].g + second[index].b).Count(); + SaveLightingImage(with, scenario.Scene + "-toon-real-shadows"); + SaveLightingImage(without, scenario.Scene + "-toon-no-body-shadows"); + SaveLightingImage(silhouette, scenario.Scene + "-body-mask"); + string diagnostics = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (!string.IsNullOrEmpty(diagnostics)) + File.WriteAllText(Path.Combine(diagnostics, "ToonLighting", BattleData.Variant + "-" + scenario.Scene + "-shadow-mask.json"), + Newtonsoft.Json.JsonConvert.SerializeObject(new + { + receivedShadowPixels = changed, + excludedBodyRects = bodyPixels.Select(rect => new[] { rect.x, rect.y, rect.width, rect.height }).ToArray() + })); + Assert.That(changed, Is.GreaterThan(20), "Disabling model casters must remove received shadows outside the rendered body silhouette, not just self-shadowing."); + if (scene == "Z06") + { + // Reproduce the old preview's missing camera profile and + // unshadowed 1.2 key on the same snow, geometry and camera. + camera.GetComponent().Detach(); + light.intensity = 1.2f; + light.color = UnityEngine.Color.white; + light.shadows = LightShadows.None; + light.transform.rotation = Quaternion.Euler(45, -35, 0); + Texture2D legacy = Read(preview.View.Render(800, 600)); + try + { + int Clipped(UnityEngine.Color32[] pixels) => pixels.Count(pixel => pixel.r >= 248 && pixel.g >= 248 && pixel.b >= 248); + int previousClipping = Clipped(legacy.GetPixels32()), currentClipping = Clipped(first); + Assert.That(previousClipping, Is.GreaterThan(1000), "The snow fixture must expose the old excessive lighting."); + Assert.That(currentClipping, Is.LessThan(previousClipping / 4), "The corrected snow must retain substantially more highlight detail."); + SaveLightingImage(legacy, scenario.Scene + "-legacy-lighting-config"); + string output = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (!string.IsNullOrEmpty(output)) + File.WriteAllText(Path.Combine(output, "ToonLighting", BattleData.Variant + "-" + scenario.Scene + "-comparison.json"), + Newtonsoft.Json.JsonConvert.SerializeObject(new + { + previousClipping, + currentClipping, + totalPixels = first.Length + })); + } + finally + { + Object.DestroyImmediate(legacy); + } + } + } + finally + { + Object.DestroyImmediate(with); + Object.DestroyImmediate(without); + Object.DestroyImmediate(silhouette); + } + } + + [Test] + public void ToonPreviewAppliesItsOwnCameraProfileAndPreservesBrightSurfaceDetail() + { + using var view = new ResourceModelPreview(null, true); + var camera = (Camera)typeof(ResourceModelPreview).GetField("_camera", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(view); + GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane); + UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene(plane, view.Root.scene); + plane.transform.SetParent(view.Root.transform, false); + MeshFilter planeMesh = plane.GetComponent(); + planeMesh.sharedMesh = Object.Instantiate(planeMesh.sharedMesh); + var texture = new Texture2D(1, 1); + texture.SetPixel(0, 0, new UnityEngine.Color(.8f, .8f, .8f, 1)); + texture.Apply(); + var material = new Material(Shader.Find("Pal3/ToonOpaque")); + material.SetTexture("_MainTex", texture); + plane.GetComponent().sharedMaterial = material; + Vector4 sceneParameters = default, effects = default; + float character = 0; + void CaptureParameters(UnityEngine.Rendering.ScriptableRenderContext context, Camera rendering) + { + if (rendering != camera) + return; + sceneParameters = Shader.GetGlobalVector("_Pal3ToonSceneLighting"); + effects = Shader.GetGlobalVector("_Pal3ToonEffectStrengths"); + character = Shader.GetGlobalFloat("_Pal3ToonCharacterLighting"); + } + UnityEngine.Rendering.RenderPipelineManager.beginCameraRendering += CaptureParameters; + try + { + view.SetCamera(new Vector3(0, 5, -6), Vector3.zero, 50); + Texture2D image = Read(view.Render(800, 600)); + try + { + Assert.That(sceneParameters.z, Is.EqualTo(1)); + Assert.That(effects.y, Is.EqualTo(.65f)); + Assert.That(character, Is.EqualTo(.9f)); + Assert.That(Shader.GetGlobalVector("_Pal3ToonSceneLighting"), Is.EqualTo(Vector4.zero)); + Assert.That(Shader.GetGlobalVector("_Pal3ToonEffectStrengths"), Is.EqualTo(Vector4.zero)); + UnityEngine.Color32[] pixels = image.GetPixels32(); + Assert.That(pixels.Count(pixel => pixel.r > 140 && pixel.g > 140 && pixel.b > 140), Is.GreaterThan(10000)); + Assert.That(pixels.Count(pixel => pixel.r >= 248 && pixel.g >= 248 && pixel.b >= 248), Is.LessThan(100), + "A textured bright surface must not be blown out by an unconfigured preview key light."); + SaveLightingImage(image, "bright-surface-profile"); + } + finally + { + Object.DestroyImmediate(image); + } + } + finally + { + UnityEngine.Rendering.RenderPipelineManager.beginCameraRendering -= CaptureParameters; + Object.DestroyImmediate(material); + Object.DestroyImmediate(texture); + } + } + + private static void SaveLightingImage(Texture2D image, string name) + { + string root = Environment.GetEnvironmentVariable("PAL3_BATTLE_QA_ROOT"); + if (string.IsNullOrEmpty(root)) + return; + string folder = Path.Combine(root, "ToonLighting"); + Directory.CreateDirectory(folder); + File.WriteAllBytes(Path.Combine(folder, BattleData.Variant + "-" + name + ".png"), image.EncodeToPNG()); + } + + [TestCase("model")] + [TestCase("quad")] + [Category("LocalGameData")] + public void ActualCombatEffectRenderersUseTheirNativeFlushGroupAndViewersKeepDefault(string kind) + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Local original-game data is not available."); + using var data = new BattleData(root, 936); + using var view = new ResourceModelPreview(data.Resources, false); + using var director = new BattleEffectDirector(data, view); + var resources = (EffectResources)typeof(BattleEffectDirector).GetField("_resources", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(director); + EffectDefinitionFile definitions = resources.Definitions; + string Kind(EffectGroupObject obj) => definitions.TryGetType(obj.TypeCrc, out EffectDefinition definition) ? EffectClass.Name(definition.ClassNameCrc) : "missing"; + string[] viewerKinds = { "model", "quad", "particle", "S-Particle", "cylinder", "grid", "meteor", "shock", "explosive", "audio", "callback" }; + int group = Enumerable.Range(0, definitions.Groups.Length).First(index => definitions.Groups[index].Objects.Any(obj => Kind(obj) == kind) && + definitions.Groups[index].Objects.All(obj => viewerKinds.Contains(Kind(obj))) && resources.Diagnose(index).Length == 0); + long handle = director.Start(new BattleEffectRequest(group, "source", Array.Empty(), default, 1)); + EffectPlayer combat = view.Root.GetComponentInChildren(); + UnityEngine.Renderer[] renderers = Enumerable.Range(0, definitions.Groups[group].Objects.Length) + .Where(index => Kind(definitions.Groups[group].Objects[index]) == kind) + .SelectMany(index => combat.transform.GetChild(index).GetComponentsInChildren(true)).ToArray(); + Assert.That(renderers, Is.Not.Empty); + int expected = kind == "model" ? BattleData.Variant == "PAL3A" ? 1 : -1 : 2; + Assert.That(renderers.All(renderer => renderer.sortingOrder == expected), Is.True); + director.Stop(handle); + GameObject viewerRoot = view.CreateObject("Ordinary effect viewer"); + var viewer = viewerRoot.AddComponent(); + viewer.AutoAdvance = false; + viewer.Initialize(resources, group); + Assert.That(viewer.Error, Is.Null); + renderers = viewer.GetComponentsInChildren(true); + Assert.That(renderers, Is.Not.Empty); + Assert.That(renderers.All(renderer => renderer.sortingOrder == 0), Is.True); + Object.DestroyImmediate(viewerRoot); + } + +#if PAL3A + [TestCase(101, "107")] + [TestCase(103, "106")] + [Category("LocalGameData")] + public void InitialBeastFormCapturesItsOwnIdleBounds(int actorId, string beast) + { + string root = Environment.GetEnvironmentVariable("PAL3A_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Local original-game data is not available."); + using var data = new BattleData(root, 936); + var scenario = new BattleScenario { Variant = "PAL3A", Scene = data.Scenes.First(), DataFingerprint = data.Fingerprint, ToonRendering = false }; + BattleParticipant actor = data.CreateParticipant(actorId, BattleSide.Ally, BattleSlot.Water); + scenario.Participants.Add(actor); + scenario.Participants.Add(data.CreateParticipant(7311, BattleSide.Enemy, BattleSlot.Water)); + scenario.Pal3A.NangongStartsTransformed = actorId == 101; + scenario.Pal3A.PengxuStartsTransformed = actorId == 103; + BattleParticipant transformed = actor.Copy(); + transformed.Model = beast; + Mv3File idle = data.Read(data.ActionPath(transformed, data.IdleAction(transformed)), new Mv3FileReader()); + using var preview = new BattlePreview(data, new BattleSetup(scenario)); + var radii = (Dictionary)typeof(BattlePreview).GetField("_shadowRadii", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(preview); + Assert.That(radii[actor.InstanceId], Is.EqualTo(GameBoxBattleShadow.CaptureRadius(idle))); + } +#endif + + private static Texture2D Read(RenderTexture target) + { + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(target.width, target.height, TextureFormat.RGBA32, false); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, target.width, target.height), 0, 0); + image.Apply(); + return image; + } + finally { RenderTexture.active = previous; } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowTests.cs.meta new file mode 100644 index 00000000..0cbeb960 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleShadowTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c8cfb3abdc1f4da588c60926dc8509bc diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleStockAttackModeIntegrationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleStockAttackModeIntegrationTests.cs new file mode 100644 index 00000000..6e9f086c --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleStockAttackModeIntegrationTests.cs @@ -0,0 +1,77 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using Core.Contract.Enums; + using NUnit.Framework; + + [Category("LocalGameData")] + public sealed class BattleStockAttackModeIntegrationTests + { + private string Root() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) + Assert.Ignore("Original game data is required."); + return root; + } + + [Test] + public void EveryStockMonsterRecordHasAVerifiedPhysicalDispatch() + { + using var data = new BattleData(Root(), 936); + foreach (var entry in data.Database.CombatActorInfos.Where(entry => entry.Value.Type != CombatActorType.MainActor)) + { + BattleParticipant actor = data.CreateParticipant(entry.Key, BattleSide.Enemy, BattleSlot.Water); + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = data.Scenes.First(), + DataFingerprint = data.Fingerprint, + Participants = { data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water), actor } + }; + BattleActorDefinition definition = BattleDefinitionCompiler.Build(data, new BattleSetup(scenario)).Actors[actor.InstanceId]; + Assert.That(definition.UnsupportedReason, Is.Empty, $"Actor {entry.Key}: {entry.Value.Name}"); + Assert.That(definition.NormalAttackRange, Is.Not.EqualTo(BattleTargetRange.None)); + } + } + +#if PAL3A + [Test] + public void Actual7398NormalAttack7714RemainsPhysicalAndCompletesWithItsOriginalBody() + { + using var session = new BattleEditorSession(); + session.Load(Root(), 936); + BattleData data = session.Data; + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = data.Scenes.First(), + DataFingerprint = data.Fingerprint, + Encounter = BattleEncounter.EnemyAmbush + }; + BattleParticipant player = data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + player.Attributes[0] = player.Vitals[0] = 50000; + BattleParticipant enemy = data.CreateParticipant(7398, BattleSide.Enemy, BattleSlot.Water); + scenario.Participants.Add(player); + scenario.Participants.Add(enemy); + Assert.That(data.Database.CombatActorInfos[7398].NormalAttackModeId, Is.EqualTo(7714)); + session.StartBattle(scenario); + var command = new BattleCommand(enemy.InstanceId, BattleAction.Attack, player.InstanceId); + Assert.That(session.Battle.Submit(command), Is.True, session.Battle.CanSubmit(command)); + for (int tick = 0; tick < 2000 && !session.Battle.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded); tick++) + session.StepBattle(); + Assert.That(session.Battle.Events.Any(entry => entry.Kind == BattleEventKind.ActionEnded), Is.True); + Assert.That(session.Battle.Events.Where(entry => entry.Kind == BattleEventKind.Command).Select(entry => entry.AbilityId), Is.All.Zero); + session.ReplayBattle(); + } +#endif + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleStockAttackModeIntegrationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleStockAttackModeIntegrationTests.cs.meta new file mode 100644 index 00000000..904325ba --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleStockAttackModeIntegrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c1de746f5c7e40e3b721ce9c714b5a67 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleSwordSparkTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleSwordSparkTests.cs new file mode 100644 index 00000000..73dbbd90 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleSwordSparkTests.cs @@ -0,0 +1,108 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using System.Reflection; + using Battle; + using Newtonsoft.Json; + using NUnit.Framework; + using UnityEngine; + + [Category("LocalGameData")] + public sealed class BattleSwordSparkTests + { + private const BindingFlags Members = BindingFlags.Instance | BindingFlags.NonPublic; + + private static BattleScenario Scenario(BattleData data) + { + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = data.Scenes.First(), + DataFingerprint = data.Fingerprint, + Music = "NONE", + MotionBlur = false, + Seed = 17 + }; + scenario.Participants.Add(data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water)); + int enemy = data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(data, id)); + scenario.Participants.Add(data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water)); + foreach (BattleParticipant actor in scenario.Participants) + { + actor.Skills.Clear(); + actor.AttributeSource = BattleAttributeSource.ExplicitEffective; + actor.Attributes = new[] { 1000, 100, 100, 1, 10, 1, 0, 0, 0, 0, 0, 0 }; + actor.Vitals = new[] { 1000, 100, 100 }; + } +#if PAL3 + scenario.Participants[0].Equipment[0] = BattleMagicSwordRules.WeaponId; + scenario.Participants[0].MagicSword = new BattleMagicSword { Energy = 200 }; +#endif + return scenario; + } + + [Test] + public void PausedPublicationPreservesStarsBothRandomStreamsAndBattleStateWhileRestartAndStopReleaseOwners() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original game data is required."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + editor.StartBattle(Scenario(editor.Data)); + for (int step = 0; step < 50; step++) + editor.StepBattle(); + BattlePreview previous = editor.Preview; + if (editor.Battle.Definitions.Variant == "PAL3A") + { + Assert.That(previous.SwordSparkFrames, Is.Empty); + return; + } + Assert.That(previous.SwordSparkFrames, Is.Not.Empty); + BattleRandom gameplay = (BattleRandom)typeof(BattleSession).GetField("_random", Members).GetValue(editor.Battle); + var effects = new BattleRandom(888); + typeof(BattleEffectDirector).GetField("_effectRandom", Members).SetValue(previous.Effects, effects); + string BattleState() => JsonConvert.SerializeObject(new + { + editor.Battle.Tick, + editor.Battle.SimulationTick, + editor.Battle.Actors, + editor.Battle.Events, + editor.Battle.Inputs, + editor.Battle.Inventory, + GameplayRandom = gameplay.State, + EffectsRandom = effects.State + }); + string state = BattleState(); + string stars = JsonConvert.SerializeObject(previous.SwordSparkFrames); + editor.IsPlaying = false; + for (int repaint = 0; repaint < 100; repaint++) + { + editor.Tick(1); + editor.SyncBattle(); + } + Assert.That(BattleState(), Is.EqualTo(state)); + Assert.That(JsonConvert.SerializeObject(previous.SwordSparkFrames), Is.EqualTo(stars)); + Material MaterialOwner(BattlePreview preview) + { + var material = new Material(Shader.Find("Pal3/Effect")); + typeof(BattlePreview).GetField("_swordSparkMaterial", Members).SetValue(preview, material); + return material; + } + Material oldMaterial = MaterialOwner(previous); + editor.Restart(); + Assert.That(oldMaterial == null, Is.True); + Assert.That(previous.SwordSparkFrames, Is.Empty); + Assert.That(editor.Preview.SwordSparkFrames, Is.Empty); + Material nextMaterial = MaterialOwner(editor.Preview); + editor.Stop(); + Assert.That(nextMaterial == null, Is.True); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleSwordSparkTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleSwordSparkTests.cs.meta new file mode 100644 index 00000000..9f77613f --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleSwordSparkTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: be2be2ea0fd7469abe38f9da3145c39d diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleTestLoadoutTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleTestLoadoutTests.cs new file mode 100644 index 00000000..618100e4 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleTestLoadoutTests.cs @@ -0,0 +1,201 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using Battle.Presentation; + using Core.Contract.Constants; + using Core.Contract.Enums; + using NUnit.Framework; + + [Category("LocalGameData")] + public sealed class BattleTestLoadoutTests + { + private BattleData _data; + + [OneTimeSetUp] + public void Load() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original game data is required."); + _data = new BattleData(root, 936); + } + + [OneTimeTearDown] + public void Dispose() => _data?.Dispose(); + + [Test] + public void FreshTestInventoryContainsEverySupportedBattleItemAndIsCapturedWithoutChangingOtherScenarios() + { + BattleScenario scenario = BattleTestLoadoutBuilder.CreateScenario(_data); + BattleScenario other = BattleTestLoadoutBuilder.CreateScenario(_data); + scenario.Scene = _data.Scenes.First(); + scenario.Encounter = BattleEncounter.AllyAmbush; + scenario.Participants = Scenario(_data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water)).Participants; + BattleSetup setup = _data.Capture(scenario); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, setup); + int[] expected = definitions.Items.Values.Where(item => item.BattleUsable && item.Supported).Select(item => item.Id).OrderBy(id => id).ToArray(); + Assert.That(expected.Length, Is.GreaterThan(50)); + Assert.That(scenario.Items.Select(item => item.Id), Is.EqualTo(expected)); + var catalog = new BattleAnimationCatalog(_data, setup, definitions); + using var preview = new BattlePreview(_data, setup); + var battle = new BattleSession(setup, catalog, definitions: definitions, effects: preview.Effects); + preview.BindBattle(battle, catalog); + Assert.That(battle.Inventory.Select(item => item.Id), Is.EqualTo(expected)); + Assert.That(battle.Inventory.Select(item => item.Count), Is.All.EqualTo(99)); + int[] treasureIds = Enumerable.Range(6119, BattleData.Variant == "PAL3" ? 7 : 6).ToArray(); + Assert.That(battle.TreasureUses.Select(item => item.Id), Is.EqualTo(treasureIds)); + Assert.That(battle.TreasureUses.Select(item => item.Count), Is.All.EqualTo(3)); + var hud = new BattleHudPresenter(); + hud.Synchronize(battle); + hud.Open(BattleHudPage.Items); + hud.SetCategory(definitions.Items[6119].ItemType - 1); + Assert.That(hud.Abilities().Single(item => item.Definition.Id == 6119).Denied, Is.Null); + scenario.TreasureUses[0].Count = 0; + Assert.That(other.TreasureUses[0].Count, Is.EqualTo(3)); + Assert.That(battle.TreasureUses[0].Count, Is.EqualTo(3)); + scenario.Items[0].Count = 1; + Assert.That(other.Items[0].Count, Is.EqualTo(99)); + Assert.That(battle.Inventory[0].Count, Is.EqualTo(99)); + Assert.That(new BattleScenario().Items, Is.Empty, "Runtime or loaded scenarios must not receive editor test defaults."); + } + + private BattleScenario Scenario(BattleParticipant ally) + { + var scenario = new BattleScenario + { + Variant = BattleData.Variant, + Scene = _data.Scenes.First(), + DataFingerprint = _data.Fingerprint, + Encounter = BattleEncounter.AllyAmbush + }; + scenario.Participants.Add(ally); + int enemyId = _data.Database.CombatActorInfos.Keys.OrderBy(id => id) + .First(id => id > 0 && BattleAnimationCatalog.IsBasicEnemy(_data, id)); + scenario.Participants.Add(_data.CreateParticipant(enemyId, BattleSide.Enemy, BattleSlot.Water)); + return scenario; + } + +#if PAL3 + [TestCase(0, 34, 6)] + [TestCase(1, 32, 5)] + [TestCase(2, 30, 5)] + [TestCase(3, 34, 5)] + [TestCase(4, 33, 5)] +#else + [TestCase(0, 32, 8)] + [TestCase(1, 35, 7)] + [TestCase(2, 33, 7)] + [TestCase(3, 33, 7)] + [TestCase(4, 31, 7)] +#endif + public void EveryLegalPersonalAbilityAppearsAtMaximumProficiencyInItsNativeMenu(int identity, int total, int techniques) + { + int actorId = ActorConstants.MainActorCombatActorIdMap[(PlayerActorId)identity]; + BattleParticipant actor = _data.CreateTestParticipant(actorId, BattleSide.Ally, BattleSlot.Water); + Assert.That(actor.Skills, Has.Count.EqualTo(total)); + Assert.That(actor.Skills.All(skill => skill.Mastered && skill.Level == 4 && skill.Uses == 0), Is.True); + Assert.That(actor.Skills.Select(skill => skill.Id).Distinct().Count(), Is.EqualTo(total)); + foreach (BattleSkill skill in actor.Skills) + { + var original = _data.Database.SkillInfos[skill.Id]; + Assert.That(original.ApplicableActors, Does.Contain((PlayerActorId)identity)); + Assert.That((int)original.Type, Is.InRange(0, 3)); + } + BattleSetup setup = _data.Capture(Scenario(actor)); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, setup); + foreach (BattleSkill skill in actor.Skills) + Assert.That(definitions.Skills[skill.Id].Supported, Is.True, definitions.Skills[skill.Id].UnsupportedReason); + var slots = BattleMagicSlots.Capture(BattleData.Variant, definitions, identity, actor.Skills); + Assert.That(slots, Has.Count.EqualTo(total - techniques)); + Assert.That(slots.All(slot => slot.Group < 6 && slot.Slot < (BattleData.Variant == "PAL3A" ? 9 : 8)), Is.True); + var battle = new BattleSession(setup, new BattleAnimationCatalog(_data, setup, definitions), definitions: definitions); + battle.SetAutomatic(BattleSide.Enemy, false); + var hud = new BattleHudPresenter(); + hud.Synchronize(battle); + Assert.That(hud.Controller, Is.EqualTo(actor.InstanceId)); + hud.Open(BattleHudPage.Skills); + Assert.That(hud.Abilities().Count, Is.EqualTo(techniques)); + var displayed = hud.Abilities().Select(ability => ability.Definition.Id).ToList(); + hud.Open(BattleHudPage.Magic); + for (int group = 0; group < 6; group++) + { + hud.SetCategory(group); + displayed.AddRange(hud.Abilities().Select(ability => ability.Definition.Id)); + } + Assert.That(displayed, Is.EquivalentTo(actor.Skills.Select(skill => skill.Id))); + } + + [Test] + public void RandomExamplesUnlockAllPersonalSkillsEvenAtLowLevels() + { + var builder = new BattleRandomExampleBuilder(_data); + bool lowLevel = false; + for (int seed = 0; seed < 32; seed++) + { + BattleScenario scenario = builder.Create(new Random(seed)); + foreach (BattleParticipant actor in scenario.Participants.Where(actor => actor.Side == BattleSide.Ally)) + { + BattleParticipant expected = _data.CreateTestParticipant(actor.ActorId, actor.Side, actor.Slot); + Assert.That(actor.Skills.Select(skill => (skill.Id, skill.Level, skill.Mastered)), + Is.EqualTo(expected.Skills.Select(skill => (skill.Id, skill.Level, skill.Mastered)))); + lowLevel |= actor.Level < 10; + } + } + Assert.That(lowLevel, Is.True); + } + + [Test] + public void OriginalFactoryEnemyLoadoutsAndDatabaseRemainUnchanged() + { + BattleParticipant original = _data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + BattleParticipant test = _data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water); + Assert.That(test.Equipment, Is.EqualTo(original.Equipment)); + Assert.That(test.Attributes, Is.EqualTo(original.Attributes)); + Assert.That(test.Vitals, Is.EqualTo(original.Vitals)); + Assert.That(test.MagicSword, Is.Null); + Assert.That((test.Level, test.Experience), Is.EqualTo((original.Level, original.Experience))); + test.Skills[0].Mastered = false; + test.Skills[0].Level = 1; + Assert.That(_data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water).Skills[0].Level, Is.EqualTo(4)); + Assert.That(_data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water).Skills.Select(skill => (skill.Id, skill.Level, skill.Mastered)), + Is.EqualTo(original.Skills.Select(skill => (skill.Id, skill.Level, skill.Mastered)))); + int enemyId = _data.Database.CombatActorInfos.Keys.First(id => id > 0 && _data.Database.CombatActorInfos[id].Type != CombatActorType.MainActor); + foreach (BattleSide side in new[] { BattleSide.Ally, BattleSide.Enemy }) + Assert.That(_data.CreateTestParticipant(enemyId, side, BattleSlot.Water).Skills.Select(skill => (skill.Id, skill.Level, skill.Mastered)), + Is.EqualTo(_data.CreateParticipant(enemyId, side, BattleSlot.Water).Skills.Select(skill => (skill.Id, skill.Level, skill.Mastered)))); + } + + [Test] + public void MasteryDoesNotBypassMpOrDedicatedWeaponWheelAndTransformationGates() + { + BattleParticipant actor = _data.CreateTestParticipant(101, BattleSide.Ally, BattleSlot.Water); + actor.Vitals[2] = 0; + BattleSetup setup = _data.Capture(Scenario(actor)); + BattleDefinitions definitions = BattleDefinitionCompiler.Build(_data, setup); + var battle = new BattleSession(setup, new BattleAnimationCatalog(_data, setup, definitions), definitions: definitions); + var query = new BattleCommand(actor.InstanceId, BattleAction.Skill, abilityId: 301); + string target = battle.GetTargetCandidates(query).First().Id; + Assert.That(battle.CanSubmit(new BattleCommand(actor.InstanceId, BattleAction.Skill, target, 301)), Does.Contain("Resource 2")); + Assert.That(battle.MagicSwordAbilityId(actor.InstanceId), Is.Zero); +#if PAL3A + Assert.That(actor.Skills.Any(skill => skill.Id is >= 264 and <= 268), Is.False); + Assert.That(battle.CanSubmitElementWheel(actor.InstanceId, 264), Does.Contain("nine charges")); + Assert.That(battle.CanSubmit(new BattleCommand(actor.InstanceId, BattleAction.Transform)), Does.Contain("reach three")); + Assert.That(actor.Skills.Any(skill => skill.Id == BattlePal3ARules.SpiritCaptureSkill), Is.True); + Assert.That(actor.Skills.Any(skill => skill.Id == BattlePal3ARules.PengxuTransformSkill), Is.False); + Assert.That(_data.CreateTestParticipant(103, BattleSide.Ally, BattleSlot.Water).Skills + .Any(skill => skill.Id == BattlePal3ARules.PengxuTransformSkill && skill.Mastered), Is.True); +#else + Assert.That(actor.Skills.Any(skill => definitions.Skills[skill.Id].SkillTypeId == 4), Is.False); +#endif + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleTestLoadoutTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleTestLoadoutTests.cs.meta new file mode 100644 index 00000000..1c462aa9 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleTestLoadoutTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: ffd4af8704854f1181954cf674f89ff4 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleToonLightingTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleToonLightingTests.cs new file mode 100644 index 00000000..3df16b8e --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleToonLightingTests.cs @@ -0,0 +1,501 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Runtime.ExceptionServices; + using Core.Contract.Constants; + using Core.DataReader.Pol; + using Game.Rendering.Renderer; + using Game.Rendering.Toon; + using Newtonsoft.Json; + using Newtonsoft.Json.Linq; + using NUnit.Framework; + using UnityEngine; + + public sealed class BattleToonLightingTests + { + [TestCase(null, true)] + [TestCase(false, false)] + [TestCase(true, true)] + public void GameDefaultsToToonLightingAndHonorsAnExplicitSelection(bool? stored, bool expected) + { + var store = new Core.Utilities.InMemoryKeyValueStore(); + if (stored.HasValue) + store.Set(nameof(Game.Settings.GameSettings.ToonRendering), stored.Value); + using var settings = new Game.Settings.GameSettings(store); + settings.InitOrLoadSettings(); + Assert.That(settings.ToonRendering, Is.EqualTo(expected)); + Assert.That(new Battle.BattleScenario().ToonRendering, Is.True); + } + + private static ToonLightingProfile Profile(Quaternion? rotation = null, Color? color = null, + float intensity = 1, float shadow = .95f, float fill = .9f, float contrast = 1, + float baked = .65f, float contact = 1.25f) => + new(rotation ?? Quaternion.identity, color ?? Color.white, intensity, shadow, fill, contrast, baked, contact, false, false); + + private static JObject Entry(string variant = "PAL3", string scene = "Z01", float intensity = 1) => + new() + { + ["variant"] = variant, + ["scene"] = scene, + ["label"] = "test lighting", + ["keyEuler"] = new JArray(58, -30, 0), + ["temperature"] = 6500, + ["tint"] = new JArray(1, .94f, .86f), + ["intensity"] = intensity, + ["shadowStrength"] = .95f, + ["characterFill"] = .9f, + ["contrast"] = 1, + ["bakedStrength"] = .65f, + ["contactStrength"] = 1.25f, + ["night"] = false, + ["indoors"] = false + }; + + private static string Document(params JObject[] entries) => + new JObject { ["schemaVersion"] = 1, ["profiles"] = new JArray(entries) }.ToString(Formatting.None); + + private static BattleSurfaceOverride Painted(int node, int group, string name, string texture, float brightness = 1) => + new(node, group, name, texture, PolSurfaceAppearance.Painted(brightness)); + + private static JObject Background(int node = 0, int group = 1, string name = "painted horizon", string texture = "distant.tga") => + new() + { + ["nodeIndex"] = node, + ["materialGroupIndex"] = group, + ["nodeName"] = name, + ["texture"] = texture + }; + + private static PolFile Model() => new(1, + new[] { new PolGeometryNode { Name = "painted horizon" }, new PolGeometryNode { Name = "real ground" } }, + new[] + { + new PolMesh { Textures = new[] + { + new PolTexture { Material = new Core.Primitives.GameBoxMaterial { TextureFileNames = new[] { "ground.tga" } } }, + new PolTexture { Material = new Core.Primitives.GameBoxMaterial { TextureFileNames = new[] { "^L_horizon.bmp", "distant.tga" } } } + } }, + new PolMesh { Textures = new[] + { + new PolTexture { Material = new Core.Primitives.GameBoxMaterial { TextureFileNames = new[] { "ground.tga" } } } + } } + }, Array.Empty()); + + private static Dictionary Parse(string text) + { + try + { + return (Dictionary)typeof(BattleToonLightingCatalog) + .GetMethod("Parse", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { text }); + } + catch (TargetInvocationException exception) when (exception.InnerException != null) + { + ExceptionDispatchInfo.Capture(exception.InnerException).Throw(); + throw; + } + } + + private static void RejectDocument(string text) + { + Exception exception = Assert.Catch(() => Parse(text)); + Assert.That(exception, Is.InstanceOf().Or.InstanceOf().Or.InstanceOf()); + } + + [TestCase(float.NaN)] + [TestCase(float.PositiveInfinity)] + [TestCase(float.NegativeInfinity)] + public void ProfilesRejectNonfiniteValuesInEveryStoredChannel(float value) + { + Func[] invalid = + { + () => Profile(intensity: value), + () => Profile(shadow: value), + () => Profile(fill: value), + () => Profile(contrast: value), + () => Profile(baked: value), + () => Profile(contact: value), + () => Profile(color: new Color(value, 1, 1, 1)), + () => Profile(color: new Color(1, value, 1, 1)), + () => Profile(color: new Color(1, 1, value, 1)), + () => Profile(color: new Color(1, 1, 1, value)), + () => Profile(rotation: new Quaternion(value, 0, 0, 1)) + }; + foreach (Func create in invalid) + Assert.Catch(() => create()); + } + + [Test] + public void ProfilesAcceptSupportedEndpointsAndRejectOutOfRangeValuesAndNonunitRotation() + { + Assert.DoesNotThrow(() => Profile(color: Color.black, intensity: 0, shadow: 0, fill: 0, contrast: 0, baked: 0, contact: 0)); + Assert.DoesNotThrow(() => Profile(color: Color.white, intensity: 4, shadow: 1, fill: 1, contrast: 1, baked: 1, contact: 2)); + Assert.Catch(() => Profile(rotation: new Quaternion(0, 0, 0, 0))); + Assert.Catch(() => Profile(rotation: new Quaternion(0, 0, 0, 2))); + Assert.Catch(() => default(ToonLightingProfile).Validate()); + foreach (float value in new[] { -.01f, 1.01f }) + { + Assert.Catch(() => Profile(shadow: value)); + Assert.Catch(() => Profile(fill: value)); + Assert.Catch(() => Profile(contrast: value)); + Assert.Catch(() => Profile(baked: value)); + Assert.Catch(() => Profile(color: new Color(value, 1, 1))); + } + Assert.Catch(() => Profile(intensity: -.01f)); + Assert.Catch(() => Profile(intensity: 4.01f)); + Assert.Catch(() => Profile(contact: -.01f)); + Assert.Catch(() => Profile(contact: 2.01f)); + } + + [Test] + public void CapturedProfilesDoNotShareMutableColorRotationOrLaterParsedConfiguration() + { + var color = new Color(.2f, .3f, .4f, 1); + Quaternion rotation = Quaternion.identity; + ToonLightingProfile captured = Profile(rotation, color); + color.r = 1; + rotation.x = 1; + Color returned = captured.LightColor; + returned.g = 1; + Assert.That(captured.LightColor, Is.EqualTo(new Color(.2f, .3f, .4f, 1))); + Assert.That(captured.Rotation, Is.EqualTo(Quaternion.identity)); + JObject entry = Entry(intensity: .8f); + Dictionary first = Parse(Document(entry)); + BattleSceneAppearance saved = first["PAL3/Z01"]; + entry["intensity"] = 2; + entry["tint"][0] = .1f; + Dictionary second = Parse(Document(entry)); + first.Clear(); + Assert.That(saved.Lighting.Intensity, Is.EqualTo(.8f)); + Assert.That(second["PAL3/Z01"].Lighting.Intensity, Is.EqualTo(2)); + Assert.That(saved.Lighting.LightColor, Is.Not.EqualTo(second["PAL3/Z01"].Lighting.LightColor)); + } + + [Test] + public void ParsedKeysKeepVariantsSeparateAndMatchSceneCaseInsensitively() + { + Dictionary profiles = Parse(Document(Entry("PAL3", "Z01", .8f), Entry("PAL3A", "z01", 1.8f))); + Assert.That(profiles.Count, Is.EqualTo(2)); + Assert.That(profiles["pal3/z01"].Lighting.Intensity, Is.EqualTo(.8f)); + Assert.That(profiles["PAL3A/Z01"].Lighting.Intensity, Is.EqualTo(1.8f)); + RejectDocument(Document(Entry("PAL3", "Z01"), Entry("PAL3", "z01"))); + } + + [TestCase("null")] + [TestCase("{}")] + [TestCase("{\"schemaVersion\":2,\"profiles\":[]}")] + [TestCase("{\"schemaVersion\":1}")] + [TestCase("{\"schemaVersion\":1,\"profiles\":[null]}")] + [TestCase("{\"schemaVersion\":1,\"profiles\":[],\"unknownOption\":true}")] + public void UnsupportedOrIncompleteDocumentsAreRejected(string text) => RejectDocument(text); + + [TestCase("keyEuler", "[0,361,0]")] + [TestCase("keyEuler", "[0,0]")] + [TestCase("keyEuler", "[0,\"NaN\",0]")] + [TestCase("temperature", "999")] + [TestCase("temperature", "12001")] + [TestCase("tint", "[1,1]")] + [TestCase("tint", "[1,-0.1,1]")] + [TestCase("intensity", "\"Infinity\"")] + [TestCase("scene", "\" \"")] + [TestCase("variant", "\"PAL4\"")] + public void InvalidAuthoredValuesAreRejected(string property, string value) + { + JObject entry = Entry(); + entry[property] = JToken.Parse(value); + RejectDocument(Document(entry)); + } + + [Test] + public void BackgroundSelectionValidatesIndicesNamesAndAnyTextureSlotWithoutMatchingNeighborGroups() + { + PolFile model = Model(); + var appearance = new BattleSceneAppearance(Profile(), new[] { Painted(0, 1, "painted horizon", "DISTANT.TGA") }); + Func selected = appearance.ResolveSurfaces(model); + Assert.That(selected(0, 1)?.Brightness, Is.EqualTo(1)); + Assert.That(selected(0, 0), Is.Null, "A shared POL node may contain both real ground and a painted background."); + Assert.That(selected(1, 0), Is.Null); + Assert.That(selected(-1, 1), Is.Null); + Assert.That(selected(0, 2), Is.Null); + var firstTexture = new BattleSceneAppearance(Profile(), new[] { Painted(0, 1, "painted horizon", "^L_horizon.bmp") }); + Assert.That(firstTexture.ResolveSurfaces(model)(0, 1)?.Brightness, Is.EqualTo(1)); + Assert.That(new BattleSceneAppearance(Profile()).ResolveSurfaces(model), Is.Null); + } + + [Test] + public void BackgroundSelectionsAndResolvedBrightnessOwnTheirCapturedState() + { + var declaration = Painted(0, 1, "painted horizon", "distant.tga", .65f); + BattleSurfaceOverride[] source = { declaration }; + var appearance = new BattleSceneAppearance(Profile(), source); + source[0] = Painted(1, 0, "real ground", "ground.tga", .2f); + Assert.That(appearance.Surfaces[0], Is.EqualTo(declaration)); + Assert.Throws(() => ((IList)appearance.Surfaces)[0] = source[0]); + PolFile model = Model(); + Func selected = appearance.ResolveSurfaces(model); + Func other = new BattleSceneAppearance(Profile(), source).ResolveSurfaces(model); + PolSurfaceAppearance value = selected(0, 1).Value; + value = PolSurfaceAppearance.Painted(2); + Assert.That(value.Brightness, Is.EqualTo(2)); + model.NodeDescriptions[0].Name = "changed after validation"; + model.Meshes[0].Textures[1].Material.TextureFileNames[1] = "changed.tga"; + Assert.That(selected(0, 1)?.Brightness, Is.EqualTo(.65f)); + Assert.That(selected(1, 0), Is.Null); + Assert.That(other(0, 1), Is.Null); + Assert.That(other(1, 0)?.Brightness, Is.EqualTo(.2f)); + Assert.Throws(() => appearance.ResolveSurfaces(model)); + } + + [Test] + public void InvalidOrDuplicateBackgroundDeclarationsAreRejectedAtCapture() + { + Assert.Throws(() => Painted(-1, 0, "node", "texture")); + Assert.Throws(() => Painted(0, -1, "node", "texture")); + Assert.Throws(() => Painted(0, 0, " ", "texture")); + Assert.Throws(() => Painted(0, 0, "node", null)); + Assert.Throws(() => new BattleSceneAppearance(Profile(), new[] { default(BattleSurfaceOverride) })); + var one = Painted(0, 1, "node", "a.tga"); + var duplicate = Painted(0, 1, "different name", "b.tga"); + Assert.Throws(() => new BattleSceneAppearance(Profile(), new[] { one, duplicate })); + Assert.Throws(() => new BattleSceneAppearance(default)); + } + + [TestCase(float.NaN)] + [TestCase(float.PositiveInfinity)] + [TestCase(float.NegativeInfinity)] + [TestCase(-.01f)] + [TestCase(2.01f)] + public void BackgroundBrightnessRejectsNonfiniteAndOutOfRangeValues(float value) + { + Assert.Catch(() => Painted(0, 1, "painted horizon", "distant.tga", value)); + } + + [TestCase(0f)] + [TestCase(2f)] + public void BackgroundBrightnessAcceptsEndpointsWithoutSelectingTheRealGround(float value) + { + var appearance = new BattleSceneAppearance(Profile(), new[] { Painted(0, 1, "painted horizon", "distant.tga", value) }); + Func selected = appearance.ResolveSurfaces(Model()); + Assert.That(selected(0, 1)?.Brightness, Is.EqualTo(value)); + Assert.That(selected(0, 0), Is.Null, "Even a zero-brightness background must not disable the real ground receiver."); + } + + [Test] + public void SurfaceOverridesKeepGeometricNormalGroundLitAndTheAdjacentPaintedHorizonIndependent() + { + BattleSurfaceOverride[] source = + { + new(0, 0, "painted horizon", "ground.tga", PolSurfaceAppearance.RecalculateNormals), + Painted(0, 1, "painted horizon", "distant.tga", .7f) + }; + var appearance = new BattleSceneAppearance(Profile(), source); + Func selected = appearance.ResolveSurfaces(Model()); + source[0] = Painted(0, 0, "painted horizon", "ground.tga", 2); + source[1] = new BattleSurfaceOverride(0, 1, "painted horizon", "distant.tga", PolSurfaceAppearance.RecalculateNormals); + PolSurfaceAppearance ground = selected(0, 0).Value; + Assert.That(ground.UnlitBackground, Is.False, "Repairing group-local normals must retain the real ground's dynamic lighting and shadow receiver."); + Assert.That(ground.GeometricNormals, Is.True); + Assert.That(ground.Brightness, Is.EqualTo(1)); + PolSurfaceAppearance horizon = selected(0, 1).Value; + Assert.That(horizon.UnlitBackground, Is.True); + Assert.That(horizon.GeometricNormals, Is.False); + Assert.That(horizon.Brightness, Is.EqualTo(.7f)); + Assert.That(selected(1, 0), Is.Null); + Assert.That(appearance.Surfaces[0].Appearance, Is.EqualTo(ground)); + Assert.That(appearance.Surfaces[1].Appearance, Is.EqualTo(horizon)); + } + + [Test] + public void SurfaceOverridesRejectDuplicateCoordinatesAcrossDifferentAppearanceKinds() + { + var painted = Painted(0, 1, "painted horizon", "distant.tga"); + var normals = new BattleSurfaceOverride(0, 1, "painted horizon", "distant.tga", PolSurfaceAppearance.RecalculateNormals); + Assert.Throws(() => new BattleSceneAppearance(Profile(), new[] { painted, normals })); + } + + [TestCase("node index")] + [TestCase("group index")] + [TestCase("node name")] + [TestCase("texture name")] + [TestCase("null groups")] + [TestCase("null filenames")] + public void BackgroundReferencesMustMatchTheActualPolBeforeResolving(string mismatch) + { + PolFile model = Model(); + int node = mismatch == "node index" ? 2 : 0; + int group = mismatch == "group index" ? 2 : 1; + string name = mismatch == "node name" ? "Painted horizon" : "painted horizon"; + string texture = mismatch == "texture name" ? "another.tga" : "distant.tga"; + if (mismatch == "null groups") + model.Meshes[0].Textures = null; + if (mismatch == "null filenames") + model.Meshes[0].Textures[1].Material.TextureFileNames = null; + var appearance = new BattleSceneAppearance(Profile(), new[] + { + Painted(1, 0, "real ground", "ground.tga"), + Painted(node, group, name, texture) + }); + Assert.Throws(() => appearance.ResolveSurfaces(model)); + } + + [Test] + public void ParsedBackgroundSelectionsAreIndependentOfLaterAuthoredConfiguration() + { + JObject declaration = Background(); + declaration["brightness"] = .65f; + JObject entry = Entry(); + entry["backgroundSurfaces"] = new JArray(declaration); + BattleSceneAppearance appearance = Parse(Document(entry))["PAL3/Z01"]; + declaration["texture"] = "changed.tga"; + declaration["brightness"] = .1f; + entry["backgroundSurfaces"] = new JArray(); + Assert.That(appearance.Surfaces.Count, Is.EqualTo(1)); + Assert.That(appearance.Surfaces[0].Appearance.Brightness, Is.EqualTo(.65f)); + Assert.That(appearance.ResolveSurfaces(Model())(0, 1)?.Brightness, Is.EqualTo(.65f)); + Assert.That(Parse(Document(entry))["PAL3/Z01"].ResolveSurfaces(Model()), Is.Null); + } + + [Test] + public void OmittedAuthoredBackgroundBrightnessDefaultsToOne() + { + JObject entry = Entry(); + entry["backgroundSurfaces"] = new JArray(Background()); + BattleSceneAppearance appearance = Parse(Document(entry))["PAL3/Z01"]; + Assert.That(appearance.Surfaces[0].Appearance.Brightness, Is.EqualTo(1)); + Assert.That(appearance.ResolveSurfaces(Model())(0, 1)?.Brightness, Is.EqualTo(1)); + } + + [TestCase("\"NaN\"")] + [TestCase("\"Infinity\"")] + [TestCase("\"-Infinity\"")] + [TestCase("-0.01")] + [TestCase("2.01")] + public void InvalidAuthoredBackgroundBrightnessIsRejected(string value) + { + JObject declaration = Background(); + declaration["brightness"] = JToken.Parse(value); + JObject entry = Entry(); + entry["backgroundSurfaces"] = new JArray(declaration); + RejectDocument(Document(entry)); + } + + [TestCase("[null]")] + [TestCase("[{}]")] + [TestCase("[{\"nodeIndex\":-1,\"materialGroupIndex\":0,\"nodeName\":\"node\",\"texture\":\"x.tga\"}]")] + [TestCase("[{\"nodeIndex\":0,\"materialGroupIndex\":-1,\"nodeName\":\"node\",\"texture\":\"x.tga\"}]")] + [TestCase("[{\"nodeIndex\":0,\"materialGroupIndex\":0,\"nodeName\":\" \",\"texture\":\"x.tga\"}]")] + [TestCase("[{\"nodeIndex\":0,\"materialGroupIndex\":0,\"nodeName\":\"node\"}]")] + [TestCase("[{\"nodeIndex\":0,\"materialGroupIndex\":0,\"nodeName\":\"node\",\"texture\":\"x.tga\",\"guessByName\":true}]")] + public void InvalidAuthoredBackgroundDeclarationsAreRejected(string json) + { + JObject entry = Entry(); + entry["backgroundSurfaces"] = JToken.Parse(json); + RejectDocument(Document(entry)); + } + + [Test] + public void DuplicateAuthoredBackgroundGroupsAreRejectedEvenWithDifferentGuards() + { + JObject entry = Entry(); + entry["backgroundSurfaces"] = new JArray(Background(), Background(texture: "another.tga")); + RejectDocument(Document(entry)); + } + + [Test] + public void ParsedGeometricNormalSurfacesPreserveTheirTypedAppearanceAndCapturedReferences() + { + JObject ground = Background(group: 0, texture: "ground.tga"); + JObject entry = Entry(); + entry["backgroundSurfaces"] = new JArray(Background()); + entry["geometricNormalSurfaces"] = new JArray(ground); + BattleSceneAppearance appearance = Parse(Document(entry))["PAL3/Z01"]; + ground["nodeName"] = "changed after capture"; + entry["geometricNormalSurfaces"] = new JArray(); + Func selected = appearance.ResolveSurfaces(Model()); + Assert.That(appearance.Surfaces.Count, Is.EqualTo(2)); + Assert.That(selected(0, 0), Is.EqualTo(PolSurfaceAppearance.RecalculateNormals)); + Assert.That(selected(0, 1), Is.EqualTo(PolSurfaceAppearance.Painted())); + Assert.That(Parse(Document(entry))["PAL3/Z01"].ResolveSurfaces(Model())(0, 0), Is.Null); + } + + [TestCase("[null]")] + [TestCase("[{}]")] + [TestCase("[{\"nodeIndex\":0,\"materialGroupIndex\":0,\"nodeName\":\"node\"}]")] + [TestCase("[{\"nodeIndex\":0,\"materialGroupIndex\":0,\"nodeName\":\"node\",\"texture\":\"x.tga\",\"brightness\":0.5}]")] + public void InvalidAuthoredGeometricNormalReferencesAreRejected(string value) + { + JObject entry = Entry(); + entry["geometricNormalSurfaces"] = JToken.Parse(value); + RejectDocument(Document(entry)); + } + + [TestCase(false)] + [TestCase(true)] + public void DuplicateAuthoredSurfaceCoordinatesAreRejectedWithinAndAcrossKinds(bool paintedToo) + { + JObject entry = Entry(); + entry["geometricNormalSurfaces"] = paintedToo ? new JArray(Background()) : new JArray(Background(), Background()); + if (paintedToo) + entry["backgroundSurfaces"] = new JArray(Background()); + RejectDocument(Document(entry)); + } + + private const string ProfileAssetPath = "Assets/Scripts/Editor/BattleEditor/Data/BattleToonLightingProfiles.json"; + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void ResourceLookupMatchesSceneCaseAndUnknownScenesUseTheDefault(string variant) + { + TextAsset asset = UnityEditor.AssetDatabase.LoadAssetAtPath(ProfileAssetPath); + Assert.That(asset, Is.Not.Null); + Dictionary profiles = Parse(asset.text); + string scene = profiles.Keys.First(key => key.StartsWith(variant + "/", StringComparison.Ordinal)).Split('/')[1]; + Assert.That(BattleToonLightingCatalog.Resolve(variant, scene.ToLowerInvariant()), Is.EqualTo(profiles[variant + "/" + scene].Lighting)); + Assert.That(BattleToonLightingCatalog.Resolve(variant, "__missing_lighting_scene__"), Is.EqualTo(ToonLightingProfile.Default)); + Assert.That(BattleToonLightingCatalog.Resolve(variant, null), Is.EqualTo(ToonLightingProfile.Default)); + Assert.That(BattleToonLightingCatalog.ResolveScene(variant, scene).Lighting, Is.EqualTo(profiles[variant + "/" + scene].Lighting)); + Assert.That(BattleToonLightingCatalog.ResolveScene(variant, "__missing_lighting_scene__").Surfaces, Is.Empty); + RejectDocument(null); + Assert.Catch(() => BattleToonLightingCatalog.Resolve("PAL4", scene)); + } + + [Test] + [Category("LocalGameData")] + public void EveryActualBattleSceneHasAnExplicitProfileAndValidatedSurfaceReferences() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT") ?? + Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", BattleData.Variant)); + if (!Directory.Exists(root)) + Assert.Ignore("Local original-game data is not available."); + TextAsset asset = UnityEditor.AssetDatabase.LoadAssetAtPath(ProfileAssetPath); + Assert.That(asset, Is.Not.Null); + Dictionary profiles = Parse(asset.text); + using var data = new BattleData(root, 936); + foreach (string scene in data.Scenes) + { + Assert.That(profiles.ContainsKey(BattleData.Variant + "/" + scene), Is.True, BattleData.Variant + "/" + scene); + BattleSceneAppearance appearance = profiles[BattleData.Variant + "/" + scene]; + PolFile model = data.Read(FileConstants.CombatSceneFolderVirtualPath + scene + "\\" + scene + ".pol", new PolFileReader()); + Func selected = appearance.ResolveSurfaces(model); + for (int node = 0; node < model.Meshes.Length; node++) + for (int group = 0; group < model.Meshes[node].Textures.Length; group++) + { + PolSurfaceAppearance? surfaceAppearance = selected?.Invoke(node, group); + Assert.That(surfaceAppearance.HasValue, Is.EqualTo(appearance.Surfaces.Any(surface => surface.NodeIndex == node && surface.MaterialGroupIndex == group)), + $"{BattleData.Variant}/{scene} node {node}, group {group}"); + if (surfaceAppearance.HasValue) + Assert.That(surfaceAppearance.Value, Is.EqualTo(appearance.Surfaces.First(surface => surface.NodeIndex == node && surface.MaterialGroupIndex == group).Appearance)); + } + } + Assert.That(profiles.Keys.Count(key => key.StartsWith(BattleData.Variant + "/", StringComparison.Ordinal)), Is.EqualTo(data.Scenes.Length)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleToonLightingTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleToonLightingTests.cs.meta new file mode 100644 index 00000000..2a96df2c --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleToonLightingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 156eb72bbb574c149048304cde17b567 diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleViewportFadeTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleViewportFadeTests.cs new file mode 100644 index 00000000..3feb085d --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleViewportFadeTests.cs @@ -0,0 +1,109 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.IO; + using System.Linq; + using Battle; + using NUnit.Framework; + using Pal3.Tests.EditorSupport; + using UnityEditor; + using UnityEngine; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + [Category("LocalGameData")] + [Category("OffscreenGraphics")] + public sealed class BattleViewportFadeTests + { + [Test] + public void ExitFadeCoversTheWholeViewportAtAllSupportedAspectRatios() + { + string root = Environment.GetEnvironmentVariable(BattleData.Variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(root)) + Assert.Ignore("Original game data is required."); + using var editor = new BattleEditorSession(); + editor.Load(root, 936); + var scenario = new BattleScenario { Variant = BattleData.Variant, Scene = editor.Data.Scenes.First(), DataFingerprint = editor.Data.Fingerprint }; + BattleParticipant ally = editor.Data.CreateParticipant(101, BattleSide.Ally, BattleSlot.Water); + ally.Level = 100; + scenario.Participants.Add(ally); + int enemy = editor.Data.Database.CombatActorInfos.Keys.First(id => BattleAnimationCatalog.IsBasicEnemy(editor.Data, id)); + BattleParticipant target = editor.Data.CreateParticipant(enemy, BattleSide.Enemy, BattleSlot.Water); + target.Vitals[0] = 0; + scenario.Participants.Add(target); + editor.StartBattle(scenario); + editor.Preview.Audio.Muted = editor.Preview.Effects.Muted = true; + editor.StepBattle(); + Assert.That(editor.Battle.Status, Is.EqualTo(BattleSessionStatus.Completed)); + for (int step = 0; step < 5000 && editor.ResultPresentation.ScreenOpacity < .9f && !editor.ResultPresentation.Completed; step++) + { + editor.StepBattle(); + if (editor.ResultPresentation.Current?.CanSkip == true && editor.ResultPresentation.HasExecuted && + editor.ResultPresentation.Current.Kind != BattleResultStepKind.ScreenFadeOut) + editor.SkipResultStep(); + } + Assert.That(editor.ResultPresentation.ScreenOpacity, Is.GreaterThanOrEqualTo(.9f)); + Assert.That(editor.ResultPresentation.Completed, Is.False); + Vector2 canvasSize = new(1100, 760); + Rect area = default; + using var canvas = new OffscreenGui(() => + { + EditorGUI.DrawRect(new Rect(Vector2.zero, canvasSize), Color.magenta); + EditorGUI.DrawRect(area, Color.green); + editor.Preview.DrawResultOverlay(editor.ResultPresentation, area, new Vector4(21, 13, 19, 17)); + }); + foreach (Vector2 size in new[] { new Vector2(840, 360), new Vector2(640, 480), new Vector2(840, 420), new Vector2(480, 480) }) + { + area = new Rect(new Vector2(35, 80), size); + canvas.Paint(canvasSize); + AssertPixels(canvas.RenderTarget, canvasSize, area); + } + LogAssert.NoUnexpectedReceived(); + } + + private static void AssertPixels(RenderTexture buffer, Vector2 canvasSize, Rect area) + { + Assert.That(buffer, Is.Not.Null); + Vector2 scale = new(buffer.width / canvasSize.x, buffer.height / canvasSize.y); + var pixels = new Texture2D(buffer.width, buffer.height, TextureFormat.RGBA32, false); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = buffer; + pixels.ReadPixels(new Rect(0, 0, buffer.width, buffer.height), 0, 0); + pixels.Apply(); + Color At(Vector2 point) + { + int x = Mathf.Clamp(Mathf.RoundToInt(point.x * scale.x), 0, buffer.width - 1); + int y = Mathf.Clamp(Mathf.RoundToInt(point.y * scale.y), 0, buffer.height - 1); + return pixels.GetPixel(x, buffer.height - y - 1); + } + foreach (Vector2 point in new[] + { + area.min + new Vector2(3, 3), new Vector2(area.xMax - 3, area.yMin + 3), + area.max - new Vector2(3, 3), new Vector2(area.xMin + 3, area.yMax - 3), + new Vector2(area.xMin + 3, area.center.y), new Vector2(area.xMax - 3, area.center.y), + new Vector2(area.center.x, area.yMin + 3), new Vector2(area.center.x, area.yMax - 3) + }) + { + Color color = At(point); + Assert.That(Math.Max(color.r, Math.Max(color.g, color.b)), Is.LessThan(.17f), + $"Fade leaked at {point}, viewport {area}, color {color}."); + } + Color outside = At(area.min - new Vector2(8, 8)); + Assert.That(outside.r, Is.GreaterThan(.9f)); + Assert.That(outside.b, Is.GreaterThan(.9f), "The viewport fade must not paint over editor controls."); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(pixels); + } + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleViewportFadeTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleViewportFadeTests.cs.meta new file mode 100644 index 00000000..7ccb2812 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleViewportFadeTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9d93279fa5854705bf758c018709c77c diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleWeaponBodyIntegrationTests.cs b/Assets/Tests/BattleEditor/Editor/Integration/BattleWeaponBodyIntegrationTests.cs new file mode 100644 index 00000000..027e7020 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleWeaponBodyIntegrationTests.cs @@ -0,0 +1,217 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.BattleEditor.Tests +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Battle; + using NUnit.Framework; + + public sealed class BattleWeaponBodyIntegrationTests + { + private sealed class Catalog : IBattleCatalog, IBattleAbilityTimings, IBattleAbilityEffects, + IBattleAbilityBodyAnimations, IBattlePhysicalTimings, IBattleEffectActorAnimations + { + public readonly BattlePhysicalAnimation Idle = new("z10", 500, 10); + public readonly BattlePhysicalAnimation External = new("z33", 20, 10); + public int NativeAction = 38; + public bool NpcItemIdle; + + public AttackTiming Attack(string source, string target) => new(0, 1, new[] { 0 }); + + public AttackTiming Ability(string actor, BattleAbilityDefinition ability) => new(0, 1, new[] { 0 }); + + public BattleAbilityStageProfile AbilityStage(string actor, BattleAbilityDefinition ability) => + new(BattleAbilityStageKind.Item, new BattleAbilityEffectBinding(-1, 0, 0), new BattleAbilityEffectBinding(-1, 0, 0), + 10, BattleAbilityWorkBoundary.WorkTime, 0, true, retainsBody: !NpcItemIdle, npcItemIdle: NpcItemIdle); + + public IReadOnlyList AbilityMovement(BattleActorSnapshot source, BattleActorSnapshot target, + BattleAbilityDefinition ability, BattleDefinitions definitions, bool returning) => Array.Empty(); + + public BattlePhysicalAnimation AbilityBody(string actor, BattleAbilityDefinition ability) => NpcItemIdle ? External : null; + + public int? AbilityNativeAction(string actor, BattleAbilityDefinition ability) => NativeAction; + + public BattlePhysicalAnimation AbilityMovementBody(string actor, BattleAbilityDefinition ability, BattleMovementKind kind, bool returning) => null; + + public BattlePhysicalStageProfile Physical(string actor) => new("PAL3A", actor == "A" ? 101 : 701, + actor == "A" ? 0 : -1, 1, 1, new Dictionary { [BattlePose.Idle] = Idle }); + + public BattlePhysicalAnimation ExternalBody(BattleActorSnapshot actor, string requested, BattleDefinitions definitions) => requested == "z33" ? External : null; + + public string EffectActor(uint modelCrc) => null; + + public int GuardEntry(string actor) => 1; + + public int Hurt(string actor) => 0; + + public int SpImpact(string actor) => 0; + + public int Priority(string actor) => actor == "A" ? 0 : 5; + + public int DamageDivisor(string actor) => 1; + } + + private sealed class Rules : IBattleRules + { + public int InitialGauge(BattleParticipant actor, BattleEncounter encounter, BattleRandom random) => actor.Side == BattleSide.Ally ? BattleSession.FullGauge : 0; + + public int GaugePerStep(BattleParticipant actor) => 0; + + public PhysicalHit Hit(BattleParticipant source, BattleParticipant target, bool guarding, BattleRandom random, bool targetAtHome = true, int damageDivisor = 1) => new(0, false, false); + } + + private sealed class Director : IBattleEffectDirector, IBattleAudio + { + public readonly List Sounds = new(); + + public void PlaySound(string sound) => Sounds.Add(sound); + + public long Start(BattleEffectRequest request) => throw new InvalidOperationException("This fixture has no effect groups."); + + public bool IsRunning(long handle) => false; + + public void Advance(long frame, float scaledSeconds, float unscaledSeconds) + { + } + + public void Stop(long handle) + { + } + } + + private static BattleSession Session(Catalog catalog, Director director = null) + { + var scenario = new BattleScenario { Variant = "PAL3A", Scene = "fixture", DataFingerprint = "native-action-binding" }; + foreach (string id in new[] { "A", "E" }) + scenario.Participants.Add(new BattleParticipant + { + InstanceId = id, + ActorId = id == "A" ? 101 : 701, + Side = id == "A" ? BattleSide.Ally : BattleSide.Enemy, + Attributes = new[] { 500, 100, 100, 100, 0, 3, 0, 0, 0, 0, 0, 0 }, + Vitals = new[] { 500, 100, 100 } + }); + scenario.Participants[0].Equipment[0] = 80001; + scenario.Items.Add(new BattleItem { Id = 6201, Count = 2 }); + var item = new BattleAbilityDefinition(new BattleAbilityData + { + Id = 6201, + IsItem = true, + ItemType = 2, + Range = BattleTargetRange.OwnSingle, + Attributes = new[] { new BattleAttributeEffect(0, BattleValueMode.Absolute, 1) } + }); + var definitions = new BattleDefinitions(scenario.Variant, scenario.DataFingerprint, Array.Empty(), new[] { item }, + scenario.Participants.Select(actor => new BattleActorDefinition(new BattleActorData + { + InstanceId = actor.InstanceId, + Identity = actor.InstanceId == "A" ? 0 : -1, + Equipment = actor.InstanceId == "A" ? new[] { new BattleEquipmentDefinition(new BattleEquipmentData { Id = 80001, Slot = 0, WeaponType = 1 }) } : Array.Empty() + }))); + var session = new BattleSession(new BattleSetup(scenario), catalog, new Rules(), definitions, director); + session.SetAutomatic(BattleSide.Enemy, false); + return session; + } + + private static BattleBodyAnimationBinding Binding(BattleSession session) + { + var actors = (IDictionary)typeof(BattleSession).GetField("_byId", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(session); + return (BattleBodyAnimationBinding)typeof(BattleSession).GetMethod("GetBodyBinding", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(session, new[] { actors["A"] }); + } + + private static void StartItem(BattleSession session, int nativeAction) + { + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "A", 6201)), Is.True); + for (int step = 0; step < 20 && Binding(session).RequestedNativeActionIndex != nativeAction; step++) + session.Step(); + Assert.That(session.Status, Is.Not.EqualTo(BattleSessionStatus.Faulted), session.Result?.Reason); + Assert.That(Binding(session).RequestedNativeActionIndex, Is.EqualTo(nativeAction)); + } + + [TestCase(38, false)] + [TestCase(39, true)] + public void FailedItemGotoKeepsTheActualClipButChangesNativeWeaponAndClockRules(int nativeAction, bool right) + { + var catalog = new Catalog { NativeAction = nativeAction }; + BattleSession session = Session(catalog); + Assert.That(session.WeaponVisibility("A").Right, Is.True); + StartItem(session, nativeAction); + BattleBodyAnimationBinding body = Binding(session); + Assert.That(body.CurrentAnimation, Is.SameAs(catalog.Idle)); + Assert.That(session.WeaponVisibility("A").Right, Is.EqualTo(right)); + uint before = body.GameBoxTime; + session.Step(); + Assert.That(body.GameBoxTime - before, Is.EqualTo(96), "PAL3A active action uses 1.0 even while the actual idle clip is retained."); + } + + [Test] + public void ExternalGotoAndFailedResetRetainTheUnderlyingNativeAction() + { + var catalog = new Catalog(); + BattleSession session = Session(catalog); + StartItem(session, 38); + session.SetEffectActorControlled("A", true); + session.SetEffectActorAction("A", "z33"); + Assert.That(Binding(session).CurrentAnimation, Is.SameAs(catalog.External)); + Assert.That(Binding(session).RequestedNativeActionIndex, Is.EqualTo(38)); + session.Step(); + session.SetEffectActorAction("A", "missing"); + Assert.That(Binding(session).CurrentAnimation, Is.SameAs(catalog.External)); + Assert.That(Binding(session).GameBoxTime, Is.Zero); + Assert.That(Binding(session).RequestedNativeActionIndex, Is.EqualTo(38)); + session.SetEffectActorControlled("A", false); + Assert.That(session.WeaponVisibility("A").Right, Is.False); + } + + [TestCase(38, 0)] + [TestCase(39, 1)] + public void AttackItemBodyPlaysThePublishedHeavyThrowSoundOnceOnItsFirstRolePass(int nativeAction, int sounds) + { + var catalog = new Catalog { NativeAction = nativeAction }; + var director = new Director(); + BattleSession session = Session(catalog, director); + StartItem(session, nativeAction); + Assert.That(director.Sounds.Count, Is.EqualTo(sounds)); + Assert.That(director.Sounds.All(sound => sound == "we033"), Is.True); + session.Step(); + Assert.That(director.Sounds.Count, Is.EqualTo(sounds)); + } + + [TestCase(true, 55)] + [TestCase(false, 32)] + public void Pal3aNpcItemFinishesImmediatelyAndOnlyChangesTheActionWhenEnteringIdle(bool alreadyIdle, int nativeAction) + { + var catalog = new Catalog { NpcItemIdle = true }; + var director = new Director(); + BattleSession session = Session(catalog, director); + Assert.That(session.Submit(new BattleCommand("A", BattleAction.Item, "A", 6201)), Is.True); + session.Step(); + session.Step(); + const BindingFlags members = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; + var actors = (IDictionary)typeof(BattleSession).GetField("_byId", members).GetValue(session); + object actor = actors["A"]; + object run = actor.GetType().GetField("Run", members).GetValue(actor); + long action = (long)run.GetType().GetField("Id", members).GetValue(run); + var stages = (IDictionary)typeof(BattleSession).GetField("_abilityPresentations", members).GetValue(session); + object stage = stages[action]; + stage.GetType().GetField("BodyExecuted", members).SetValue(stage, false); + stage.GetType().GetField("BodyFinished", members).SetValue(stage, false); + BattleBodyAnimationBinding body = Binding(session); + body.SetLogicalPose(alreadyIdle ? BattlePose.Idle : BattlePose.UsingSkill); + body.SetRequestedNativeAction(55); + typeof(BattleSession).GetMethod("TryAdvanceOrdinaryAbilityBody", members).Invoke(session, new[] { actor, run }); + Assert.That(body.RequestedNativeActionIndex, Is.EqualTo(nativeAction), "Published PAL3A 502d2e / 502e37 preserves the action if its state is already idle."); + Assert.That(stage.GetType().GetField("BodyFinished", members).GetValue(stage), Is.True); + Assert.That(session.CurrentBladeSeconds("A"), Is.EqualTo(.01f)); + Assert.That(director.Sounds, Is.Empty); + Assert.That(body.CurrentAnimation, Is.SameAs(alreadyIdle ? catalog.Idle : catalog.External)); + } + } +} diff --git a/Assets/Tests/BattleEditor/Editor/Integration/BattleWeaponBodyIntegrationTests.cs.meta b/Assets/Tests/BattleEditor/Editor/Integration/BattleWeaponBodyIntegrationTests.cs.meta new file mode 100644 index 00000000..97de0c08 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Integration/BattleWeaponBodyIntegrationTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d268762f73c9454d9c734278c8d3a922 diff --git a/Assets/Tests/BattleEditor/Editor/Pal3.BattleEditor.Tests.asmdef b/Assets/Tests/BattleEditor/Editor/Pal3.BattleEditor.Tests.asmdef new file mode 100644 index 00000000..3e2fd0d0 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Pal3.BattleEditor.Tests.asmdef @@ -0,0 +1,27 @@ +{ + "name": "Pal3.BattleEditor.Tests", + "references": [ + "Pal3.Battle", + "Pal3.BattleEditor", + "Pal3.Core", + "Pal3.Game", + "Engine", + "Pal3.ResourceBrowser.Editor", + "Pal3.Battle.Presentation", + "Unity.InputSystem", + "Pal3.Battle.Tests", + "Pal3.Editor.TestSupport" + ], + "includePlatforms": [ + "Editor" + ], + "optionalUnityReferences": [ + "TestAssemblies" + ], + "autoReferenced": false, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll", + "Newtonsoft.Json.dll" + ] +} diff --git a/Assets/Tests/BattleEditor/Editor/Pal3.BattleEditor.Tests.asmdef.meta b/Assets/Tests/BattleEditor/Editor/Pal3.BattleEditor.Tests.asmdef.meta new file mode 100644 index 00000000..676af77e --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/Pal3.BattleEditor.Tests.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 2f48130550c6e4defbeb6d605ea0765f +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/BattleEditor/Editor/README.md b/Assets/Tests/BattleEditor/Editor/README.md new file mode 100644 index 00000000..45197736 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/README.md @@ -0,0 +1,51 @@ +# Battle Editor checks + +The test assemblies follow their dependencies: + +- `Pal3.Core.Tests`: binary readers and original resource records. +- `Pal3.Battle.Tests` (`Tests/Battle/Editor`): engine-independent rules, simulation, scheduling and replay. +- `Pal3.Battle.Presentation.Tests` (`Tests/Battle/Presentation/Editor`): engine-independent feedback and projection. +- `Pal3.BattleEditor.Tests`: Unity resource adapters, authoring, HUD and integration. + +Run the affected assemblies once per game using the existing Switch Variant +menu, and restore PAL3 after validation. The namespaces of existing battle tests +are retained so saved test filters remain valid. Integration fixtures reference +the domain test assembly for the shared synthetic scenario/catalogue. + +Default automated validation uses isolated batch projects, a positive test filter +for windowless cases, and either `-nographics` or GPU RenderTexture rendering. +Do not run all editor-window tests unattended: native focus, file-picker and +window routing checks may show windows and need a separately requested desktop +session. Workbench IMGUI can also be checked with the workspace's windowless +Panel driver, without adding private Unity APIs to product code. + +Portable cases cover initial-state isolation, malformed inputs, native texture +failure cleanup, preset persistence, schema guards, saving and Undo, and a real +assembly reload with an unsaved editor draft. The domain and semantic presentation assemblies have no Unity references and +can also be compiled independently; authoring and resource integration use Unity. + +`LocalGameData` cases use `PAL3_TEST_DATA_ROOT` or `../Game Data/` relative +to the project. Without local data they skip. They check both wrong-game loading +directions, immutable database inputs, captured preview isolation, explicit +attack targets and seeking, failed second-mesh initialization with recovery, and +20 start/sample/stop cycles in both rendering modes. Failure recovery checks native +Mesh, Material and Texture counts as well as scene ownership. + +Rendering samples are written to `../workspace/Implementation/BattleEditor/QA/`. +Original game files, captures and local presets stay outside committed fixtures. +The preceding checks cover stage 1 scene/animation authoring. Stage 2 combat +checks are described below. + + +第二阶段新增 `BattleSessionTests`:两作原函数独立数值预期、初始条与回合计数、命中标记、暴击/闪避/防御、受击重启与取消剩余标记、死亡/取消、故障与输入重放、30/60/144Hz一致性、同速移动双方自然结束。领域程序集不引用Unity。 + +`BattleIntegrationTests` 使用真实两作CPK/GDB/MV3;覆盖一对一/多对多、两画风自然结束与渲染、重放、反复重开释放、失败保留旧会话、原始work时间、PAL3A分段除数与笛/弩原地时间线、备用武器拒绝,以及存在其他待输入角色时的下一命中推进。通过 `PAL3_TEST_DATA_ROOT` 指定当前作品原数据目录,`PAL3_BATTLE_QA_ROOT` 可选保存截图。未配置环境变量时使用工作区默认 `Game Data/`。 + +完整工作区验证脚本位于 `workspace/Implementation/BattleStage2/validate.py`(工作区根目录下)。结果与审阅记录保存在同目录 `QA/`;仓库不包含原始资料或测试截图。当前50Hz更新只是明确的兼容参考;完整机制与手动鼠标体验验收仍按工作区分阶段计划记录。 + + +第三阶段新增 `BattleMechanicsTests`,可脱离Unity运行:原版成本前置与减耗顺序、双槽蓄力/中断、物品开局消耗、治疗/复活、状态互斥与潜伏、镜避界、行列、逃跑、熟练/技能解锁、经验/升级/奖励及重放;暴击和群体死亡目标的随机顺序使用发布EXE独立预期。`BattleAbilitiesIntegrationTests` 使用真实风咒301、止血草6201、还魂香6211及怪物第四技能,验证原始类型、阈值、生效时间、扣费时点和固定熟练度。资源报告写入的目录/文件/悬空符号链接另由Resource Browser测试拒绝。 + +第三阶段完整验证入口为工作区 `workspace/Implementation/BattleStage3/validate.py`;原指令向量、反汇编及独立审查位于 `workspace/Analysis/Battle-Stage3/`,验证汇总与审查修复记录在 `workspace/Implementation/BattleStage3/QA/`。纯数值/分支向量不能代替后续完整AI、导演与原版主循环的动态对照。 + +随机示例与音乐回归见 `BattleRandomExampleTests`:128 个 authoring seeds 覆盖两作随机场景/阵容、等级及原版实际属性、正确累计经验、可启动会话;固定种子可重现选材;真实 MP3 自动解码与播放、动画时钟、绑定战斗复用音源,以及缺少剧情来源和音频失败诊断保持可见。 diff --git a/Assets/Tests/BattleEditor/Editor/README.md.meta b/Assets/Tests/BattleEditor/Editor/README.md.meta new file mode 100644 index 00000000..ae907220 --- /dev/null +++ b/Assets/Tests/BattleEditor/Editor/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 938ed061b8aed4d10a0181a1b5f6a6e2 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/Editor/BattleDataReaderTests.cs b/Assets/Tests/Editor/BattleDataReaderTests.cs new file mode 100644 index 00000000..21b9275c --- /dev/null +++ b/Assets/Tests/Editor/BattleDataReaderTests.cs @@ -0,0 +1,133 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Core.Tests +{ + using System.IO; + using Core.Contract.Enums; + using Core.DataReader; + using Core.DataReader.Gdb; + using Core.DataReader.Mv3; + using NUnit.Framework; + + public sealed class BattleDataReaderTests + { + [TestCase("animation event", int.MaxValue)] + [TestCase("vertex", int.MaxValue)] + [TestCase("vertex frame", int.MaxValue)] + [TestCase("vertex frame", -1)] + [TestCase("texture coordinate", int.MaxValue)] + [TestCase("triangle", int.MaxValue)] + [TestCase("command", int.MaxValue)] + public void Mv3RejectsCountsThatDoNotFitInTheFile(string field, int value) + { + byte[] data = Mv3Fixture(field, value); + var reader = (IFileReader)new Mv3FileReader(); + var error = Assert.Throws(() => reader.Read(data, 936)); + Assert.That(error.Message, Does.Contain(field + " count")); + } + + [TestCase("vertex", false)] + [TestCase("vertex", true)] + [TestCase("texture coordinate", false)] + [TestCase("texture coordinate", true)] + public void Mv3RejectsOutOfRangeTriangleCornersWithEitherNormalMode(string field, bool nativeNormals) + { + byte[] data = Mv3Fixture(field + " index", ushort.MaxValue); + var reader = (IFileReader)new Mv3FileReader(nativeNormals); + var error = Assert.Throws(() => reader.Read(data, 936)); + Assert.That(error.Message, Does.Contain(field + " index")); + } + + private static byte[] Mv3Fixture(string field, int invalid) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + void Count(string name, int value) => writer.Write(field == name ? invalid : value); + void Index(string name, ushort value) => writer.Write(field == name + " index" ? (ushort)invalid : value); + + writer.Write(new byte[] { (byte)'M', (byte)'V', (byte)'3', 0 }); + writer.Write(100); + writer.Write(0u); + Count("material", 1); + Count("tag node", 0); + Count("mesh", 1); + Count("animation event", 0); + writer.Write(new byte[84]); // material and empty texture names + writer.Write(new byte[64]); // mesh name + Count("vertex", 3); + writer.Write(new byte[24]); // bounds + Count("vertex frame", 1); + writer.Write(new byte[28]); // packed frame + Count("texture coordinate", 0); + Count("mesh attribute", 1); + writer.Write(0); // material index + Count("triangle", 1); + Index("vertex", 0); + writer.Write((ushort)1); + writer.Write((ushort)2); + Index("texture coordinate", 0); + writer.Write(new byte[4]); // remaining UV corners + Count("command", 0); + return stream.ToArray(); + } + + [Test] + public void ComboValuesUseTheNativeShortAlignmentAndKeepTheNextRecordAligned() + { +#if PAL3 + const int stride = 0x278; +#else + const int stride = 0x27c; +#endif + var bytes = new byte[160 + stride * 2]; + using (var writer = new BinaryWriter(new MemoryStream(bytes))) + { + writer.BaseStream.Position = 128; + for (int section = 0; section < 4; section++) + { + writer.Write(160); + writer.Write(section == 3 ? 2 : 0); + } + for (int record = 0; record < 2; record++) + { + int offset = 160 + record * stride; + writer.BaseStream.Position = offset + 32; + writer.Write(501 + record); + writer.BaseStream.Position = offset + 68; + writer.Write(-1); + writer.Write(0); + writer.Write(26); + writer.BaseStream.Position = offset + 0x250; + writer.Write((byte)(record == 0 ? 0 : 3)); + writer.BaseStream.Position = offset + 0x25d; + writer.Write((byte)0x7f); // Alignment bytes must not become a resource value. + for (int attribute = 0; attribute < 12; attribute++) + writer.Write((short)(attribute == 0 ? -300 - record : record == 1 && attribute == 4 ? 0 : attribute + record + 1)); + writer.Write((short)0x1234); // Record-tail alignment is also excluded. +#if PAL3A + writer.Write(12345 + record); +#endif + } + } + GdbFile database = ((IFileReader)new GdbFileReader()).Read(bytes, 936); + Assert.That(database.ComboSkillInfos.Count, Is.EqualTo(2)); + Assert.That(database.ComboSkillOrder, Is.EqualTo(new[] { 501, 502 })); + for (int record = 0; record < 2; record++) + { + ComboSkillInfo combo = database.ComboSkillInfos[501 + record]; + Assert.That(combo.AuxiliaryStateConditions, Is.EqualTo(new[] { -1, 0, 26 })); + Assert.That(combo.TargetRangeType, Is.EqualTo(record == 0 ? ComboTargetRangeType.PreserveSingleTarget : ComboTargetRangeType.OpponentAll)); + Assert.That(combo.AttributeImpacts.Count, Is.EqualTo(12)); + for (int attribute = 0; attribute < 12; attribute++) + Assert.That(combo.AttributeImpacts[(ActorAttributeType)attribute].Value, + Is.EqualTo(attribute == 0 ? -300 - record : record == 1 && attribute == 4 ? 0 : attribute + record + 1)); +#if PAL3A + Assert.That(combo.PowerMultiplierPercentage, Is.EqualTo(12345 + record)); +#endif + } + } + } +} diff --git a/Assets/Tests/Editor/BattleDataReaderTests.cs.meta b/Assets/Tests/Editor/BattleDataReaderTests.cs.meta new file mode 100644 index 00000000..b1e8ee8b --- /dev/null +++ b/Assets/Tests/Editor/BattleDataReaderTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5d74afe50fdf40f9a66bd826f16d295f diff --git a/Assets/Tests/Editor/CombatCameraConfigFileReaderTests.cs b/Assets/Tests/Editor/CombatCameraConfigFileReaderTests.cs new file mode 100644 index 00000000..992279a4 --- /dev/null +++ b/Assets/Tests/Editor/CombatCameraConfigFileReaderTests.cs @@ -0,0 +1,69 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Core.Tests +{ + using System; + using System.Globalization; + using System.Text; + using Core.DataReader.Ini; + using NUnit.Framework; + + public sealed class CombatCameraConfigFileReaderTests + { + private const string Camera = "[DefaultCam0]\nx=-70.413155\ny=.125\nz=140.5\nyaw=-3.171740\npitch=-.500003\nroll=1.25e-2\n"; + + private static CombatCameraConfig Read(string text) => new CombatCameraConfigFileReader().Read(Encoding.ASCII.GetBytes(text), 936).DefaultCamConfigs[0]; + + [TestCase("en-US")] + [TestCase("fr-FR")] + [TestCase("de-DE")] + public void NativeCameraCoordinatesAndAnglesIgnoreTheEditorsCulture(string culture) + { + CultureInfo previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + CombatCameraConfig camera = Read(Camera); + Assert.That(camera.GameBoxPositionX, Is.EqualTo(-70.413155f)); + Assert.That(camera.GameBoxPositionY, Is.EqualTo(.125f)); + Assert.That(camera.GameBoxPositionZ, Is.EqualTo(140.5f)); + Assert.That(camera.Yaw, Is.EqualTo(-3.171740f)); + Assert.That(camera.Pitch, Is.EqualTo(-.500003f)); + Assert.That(camera.Roll, Is.EqualTo(.0125f)); + } + finally + { + CultureInfo.CurrentCulture = previous; + } + } + + [TestCase("en-US")] + [TestCase("fr-FR")] + [TestCase("de-DE")] + public void NativeCameraNumbersNeverInterpretCommasAsThousandsSeparators(string culture) + { + CultureInfo previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + const string grouped = "[DefaultCam0]\nx=-70,413155\ny=1\nz=2\nyaw=-3\npitch=-1\nroll=0\n"; + Assert.Throws(() => Read(grouped)); + } + finally + { + CultureInfo.CurrentCulture = previous; + } + } + + [Test] + public void CameraValuesAllowNativeInlineCommentsWithoutChangingTheirValue() + { + CombatCameraConfig camera = Read(Camera.Replace("-70.413155", "-70.413155 ; position").Replace("-3.171740", "-3.171740 ; angle")); + Assert.That(camera.GameBoxPositionX, Is.EqualTo(-70.413155f)); + Assert.That(camera.Yaw, Is.EqualTo(-3.171740f)); + } + } +} diff --git a/Assets/Tests/Editor/CombatCameraConfigFileReaderTests.cs.meta b/Assets/Tests/Editor/CombatCameraConfigFileReaderTests.cs.meta new file mode 100644 index 00000000..1c12bf16 --- /dev/null +++ b/Assets/Tests/Editor/CombatCameraConfigFileReaderTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f0ecc5834ab84a8c9cd7854cdada49fa diff --git a/Assets/Tests/Editor/CombatConfigFileReaderTests.cs b/Assets/Tests/Editor/CombatConfigFileReaderTests.cs new file mode 100644 index 00000000..f0a99bb2 --- /dev/null +++ b/Assets/Tests/Editor/CombatConfigFileReaderTests.cs @@ -0,0 +1,68 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Core.Tests +{ + using System; + using System.Globalization; + using System.Text; + using Core.DataReader.Ini; + using NUnit.Framework; + + public sealed class CombatConfigFileReaderTests + { + [Test] + public void OptionalEnemyCenterRequiresBothAxesWhenPresent() + { + var text = new StringBuilder("[RolePos]\n"); + for (int actor = 0; actor < 10; actor++) + text.AppendFormat(CultureInfo.InvariantCulture, "Role{0}-x=1\nRole{0}-z=2\n", actor); + var reader = new CombatConfigFileReader(); + Assert.That(reader.Read(Encoding.UTF8.GetBytes(text.ToString()), 65001).ActorGameBoxPositions, Has.Length.EqualTo(11)); + text.Append("Role10-x=3\n"); + var error = Assert.Throws(() => reader.Read(Encoding.UTF8.GetBytes(text.ToString()), 65001)); + Assert.That(error.Message, Does.Contain("Role10-z")); + } + + [Test] + public void MissingFormationRollDefaultsToZeroWhileAnInvalidValueStillFails() + { + const string ini = "[AllyFiveLineup]\nx=1\ny=2\nz=3\nradius=4\n"; + var reader = new CombatConfigFileReader(); + CombatConfigFile layout = reader.Read(Encoding.UTF8.GetBytes(ini), 65001); + Assert.That(layout.AllyFormationConfig.GameBoxRadius, Is.EqualTo(4)); + Assert.That(layout.AllyFormationConfig.RollRadians, Is.Zero); + Assert.Throws(() => reader.Read(Encoding.UTF8.GetBytes(ini + "roll=invalid\n"), 65001)); + } + + [TestCase("en-US")] + [TestCase("de-DE")] + [TestCase("fr-FR")] + public void NativeDecimalCoordinatesAndRollIgnoreTheEditorsCulture(string culture) + { + CultureInfo previous = CultureInfo.CurrentCulture; + try + { + CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture); + var text = new StringBuilder("[RolePos]\n"); + for (int actor = 0; actor < 11; actor++) + text.AppendFormat(CultureInfo.InvariantCulture, "Role{0}-x=-1.25 ; position\nRole{0}-z=2.5\n", actor); + text.Append("[AllyFiveLineup]\nx=1.5 ; center\ny=-2.25\nz=3.125\nradius=4.5 ; radius\nroll=-.500003 ; angle\n"); + text.Append("[EnemyFiveLineup]\nx=-1.5\ny=2.25\nz=-3.125\nradius=4.5\nroll=.156633\n"); + CombatConfigFile layout = new CombatConfigFileReader().Read(Encoding.UTF8.GetBytes(text.ToString()), 65001); + Assert.That(layout.ActorGameBoxPositions[0].X, Is.EqualTo(-1.25f)); + Assert.That(layout.ActorGameBoxPositions[10].Z, Is.EqualTo(2.5f)); + Assert.That(layout.AllyFormationConfig.CenterGameBoxPosition.X, Is.EqualTo(1.5f)); + Assert.That(layout.AllyFormationConfig.GameBoxRadius, Is.EqualTo(4.5f)); + Assert.That(layout.AllyFormationConfig.RollRadians, Is.EqualTo(-.500003f)); + Assert.That(layout.EnemyFormationConfig.RollRadians, Is.EqualTo(.156633f)); + } + finally + { + CultureInfo.CurrentCulture = previous; + } + } + } +} diff --git a/Assets/Tests/Editor/CombatConfigFileReaderTests.cs.meta b/Assets/Tests/Editor/CombatConfigFileReaderTests.cs.meta new file mode 100644 index 00000000..664014db --- /dev/null +++ b/Assets/Tests/Editor/CombatConfigFileReaderTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 9269d1656cdd4e56a1e558abe54eb0a5 diff --git a/Assets/Tests/Editor/OriginalEffectFormatTests.cs b/Assets/Tests/Editor/EffectFormatTests.cs similarity index 98% rename from Assets/Tests/Editor/OriginalEffectFormatTests.cs rename to Assets/Tests/Editor/EffectFormatTests.cs index a31c23bb..d9111b5b 100644 --- a/Assets/Tests/Editor/OriginalEffectFormatTests.cs +++ b/Assets/Tests/Editor/EffectFormatTests.cs @@ -15,7 +15,7 @@ namespace Pal3.Core.Tests using DataReader.Par; using NUnit.Framework; - public sealed class OriginalEffectFormatTests + public sealed class EffectFormatTests { [Test] public void FlexeffReadsFloatSizeTaskPaddingAndFirstValidDuplicate() diff --git a/Assets/Tests/Editor/EffectFormatTests.cs.meta b/Assets/Tests/Editor/EffectFormatTests.cs.meta new file mode 100644 index 00000000..12e38ff4 --- /dev/null +++ b/Assets/Tests/Editor/EffectFormatTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c8efb240fc6a64537ba57e4b865f14de diff --git a/Assets/Tests/Editor/FlexCameraReaderTests.cs b/Assets/Tests/Editor/FlexCameraReaderTests.cs new file mode 100644 index 00000000..9439ae00 --- /dev/null +++ b/Assets/Tests/Editor/FlexCameraReaderTests.cs @@ -0,0 +1,102 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Core.Tests +{ + using System.IO; + using Core.DataReader; + using Core.DataReader.Dat; + using NUnit.Framework; + + public sealed class FlexCameraReaderTests + { + [Test] + public void BothGamesUseTheSixteenByteDispatchAreaAnd204ByteRecordStride() + { + byte[] bytes = Empty(); + using (var writer = new BinaryWriter(new MemoryStream(bytes))) + { + for (int record = 0; record < 2; record++) + { + writer.BaseStream.Position = record * 204; + for (uint word = 0; word < 4; word++) + writer.Write(0x10000000u + word); + writer.Write((uint)(700 + record)); + writer.Write(true); + writer.Write(false); + writer.Write(true); + writer.Write(true); + for (int value = 0; value < 14; value++) + writer.Write(1.25f + value); + writer.Write(21); + writer.Write(22); + for (int bit = 0; bit < 15; bit++) + writer.Write(bit % 2 == 0); + writer.Write((byte)0xfe); // Alignment must never become part of nTraceRole. + writer.Write(-1); + for (int value = 0; value < 22; value++) + writer.Write(30.5f + value); + writer.Write(0x11223344u); + writer.Write(0x55667788u); + } + writer.BaseStream.Position = 408000; + writer.Write(true); + writer.BaseStream.Position = 410000; + writer.Write(1); + } + FlexCameraFile file = ((IFileReader)new FlexCameraFileReader()).Read(bytes, 936); + Assert.That(file.Pool.Count, Is.EqualTo(2000)); + Assert.That(file.Lists.Count, Is.EqualTo(100)); + Assert.That(file.Lists[0][0], Is.EqualTo(1)); + Assert.That(file.InUse[0], Is.True); + Assert.That(file.InUse[1], Is.False); + for (int record = 0; record < 2; record++) + { + FlexCameraTask task = file.Pool[record]; + Assert.That(task.SerializedDispatchWords, Is.EqualTo(new uint[] { 0x10000000, 0x10000001, 0x10000002, 0x10000003 })); + Assert.That(task.Id, Is.EqualTo(700 + record)); + Assert.That(task.SavedStartTime, Is.EqualTo(1.25f)); + Assert.That(task.ExpectedSeconds, Is.EqualTo(2.25f)); + Assert.That(task.Start.Position.X, Is.EqualTo(3.25f)); + Assert.That(task.Start.Yaw, Is.EqualTo(6.25f)); + Assert.That(task.End.Roll, Is.EqualTo(14.25f)); + Assert.That(task.StartCameraIndex, Is.EqualTo(21)); + Assert.That(task.EndCameraIndex, Is.EqualTo(22)); + Assert.That((int)task.Flags, Is.EqualTo(0x5555)); + Assert.That(task.TraceActor, Is.EqualTo(-1)); + Assert.That(task.StartSpeed, Is.EqualTo(30.5f)); + Assert.That(task.CircleAngle, Is.EqualTo(36.5f)); + Assert.That(task.CircleCenter.X, Is.EqualTo(38.5f)); + Assert.That(task.TimeCompensation, Is.EqualTo(46.5f)); + Assert.That(task.StartFieldOfView, Is.EqualTo(47.5f)); + Assert.That(task.SavedTraceStart.Z, Is.EqualTo(51.5f)); + Assert.That(task.ExtensionWords, Is.EqualTo(new uint[] { 0x11223344, 0x55667788 })); + } + } + + [Test] + public void TruncatedExtendedAndOutOfPoolFilesAreRejected() + { + var reader = (IFileReader)new FlexCameraFileReader(); + Assert.Throws(() => reader.Read(new byte[FlexCameraFileReader.FileBytes - 1], 936)); + Assert.Throws(() => reader.Read(new byte[FlexCameraFileReader.FileBytes + 1], 936)); + byte[] bytes = Empty(); + using (var writer = new BinaryWriter(new MemoryStream(bytes))) + { + writer.BaseStream.Position = 410000; + writer.Write(2000); + } + Assert.Throws(() => reader.Read(bytes, 936)); + } + + private static byte[] Empty() + { + var bytes = new byte[FlexCameraFileReader.FileBytes]; + for (int i = 410000; i < bytes.Length; i++) + bytes[i] = 0xff; + return bytes; + } + } +} diff --git a/Assets/Tests/Editor/FlexCameraReaderTests.cs.meta b/Assets/Tests/Editor/FlexCameraReaderTests.cs.meta new file mode 100644 index 00000000..e541b693 --- /dev/null +++ b/Assets/Tests/Editor/FlexCameraReaderTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 3a51263d15c140fa8a533d6e5f5151f4 diff --git a/Assets/Tests/Editor/GameBoxVector3Tests.cs b/Assets/Tests/Editor/GameBoxVector3Tests.cs new file mode 100644 index 00000000..61b901c5 --- /dev/null +++ b/Assets/Tests/Editor/GameBoxVector3Tests.cs @@ -0,0 +1,37 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Core.Tests +{ + using Core.Primitives; + using NUnit.Framework; + + public sealed class GameBoxVector3Tests + { + [TestCase(1, 2, 3)] + [TestCase(-70.413155f, .125f, 140.5f)] + public void EqualityIsReflexiveForDistinctAxisValues(float x, float y, float z) + { + var value = new GameBoxVector3(x, y, z); + var copy = new GameBoxVector3(x, y, z); + Assert.That(value.Equals(value), Is.True); + Assert.That(value.Equals((object)copy), Is.True); + Assert.That(value == copy, Is.True); + Assert.That(value != copy, Is.False); + } + + [Test] + public void DifferentZCoordinatesAreUnequalInBothDirections() + { + var first = new GameBoxVector3(1, 2, 1); + var second = new GameBoxVector3(1, 2, 3); + Assert.That(first.Equals(second), Is.False); + Assert.That(second.Equals(first), Is.False); + Assert.That(first == second, Is.False); + Assert.That(second == first, Is.False); + Assert.That(first != second, Is.True); + } + } +} diff --git a/Assets/Tests/Editor/GameBoxVector3Tests.cs.meta b/Assets/Tests/Editor/GameBoxVector3Tests.cs.meta new file mode 100644 index 00000000..e35343f5 --- /dev/null +++ b/Assets/Tests/Editor/GameBoxVector3Tests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b429f36c035f422ca3127a4cebddb569 diff --git a/Assets/Tests/Editor/LgtFileReaderTests.cs b/Assets/Tests/Editor/LgtFileReaderTests.cs new file mode 100644 index 00000000..ba278ac3 --- /dev/null +++ b/Assets/Tests/Editor/LgtFileReaderTests.cs @@ -0,0 +1,77 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Core.Tests +{ + using System.IO; + using DataReader; + using DataReader.Lgt; + using NUnit.Framework; + using Primitives; + + public sealed class LgtFileReaderTests + { + [TestCase(false)] + [TestCase(true)] + public void NativeInt32BooleanFieldsPreserveTheFollowingFieldsAndRecord(bool unsafeReader) + { + using var stream = new MemoryStream(); + using (var writer = new BinaryWriter(stream, System.Text.Encoding.UTF8, true)) + { + writer.Write(2); + for (int index = 0; index < 2; index++) + { + for (int element = 0; element < 16; element++) + writer.Write(element % 5 == 0 ? 1f : 0f); + writer.Write(index == 0 ? 0 : 2); + for (int component = 0; component < 8; component++) + writer.Write((float)(component + index)); + writer.Write(index == 0 ? -1 : 0); // gbBOOL is signed int32, not a serialized byte. + writer.Write(index == 0 ? 0 : 1); + foreach (float distance in new[] { 11f, 22f, 33f, 44f }) + writer.Write(distance + index); + writer.Write(2); + writer.Write(40f + index); + writer.Write(1); + writer.Write(70f + index); + writer.Write(80f + index); + writer.Write(1.25f + index); + } + } + Assert.That(stream.Length, Is.EqualTo(4 + 2 * 148)); + using IBinaryReader reader = unsafeReader ? new UnsafeBinaryReader(stream.ToArray()) : new SafeBinaryReader(stream.ToArray()); + LgtFile file = new LgtFileReader().Read(reader, 936); + Assert.That(reader.Position, Is.EqualTo(reader.Length)); + Assert.That(file.LightNodes.Length, Is.EqualTo(2)); + for (int index = 0; index < 2; index++) + { + LightNode light = file.LightNodes[index]; + Assert.That(light.UseDiffuse, Is.EqualTo(index == 0)); + Assert.That(light.UseSpecular, Is.EqualTo(index == 1)); + Assert.That(light.LightType, Is.EqualTo(index == 0 ? GameBoxLightType.Omni : GameBoxLightType.Directional)); + Assert.That(light.NearStart, Is.EqualTo(11 + index)); + Assert.That(light.FarEnd, Is.EqualTo(44 + index)); + Assert.That(light.LightDecayType, Is.EqualTo(GameBoxLightDecayType.Square)); + Assert.That(light.DecayRadius, Is.EqualTo(40 + index)); + Assert.That(light.LightShapeType, Is.EqualTo(GameBoxLightShapeType.Square)); + Assert.That(light.Size, Is.EqualTo(70 + index)); + Assert.That(light.Falloff, Is.EqualTo(80 + index)); + Assert.That(light.AspectRatio, Is.EqualTo(1.25f + index)); + } + } + + [TestCase(-1)] + [TestCase(1)] + [TestCase(int.MaxValue)] + public void RejectsCountsThatCannotFitTheRemainingFile(int count) + { + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write(count); + using IBinaryReader reader = new SafeBinaryReader(stream.ToArray()); + Assert.Throws(() => new LgtFileReader().Read(reader, 936)); + } + } +} diff --git a/Assets/Tests/Editor/LgtFileReaderTests.cs.meta b/Assets/Tests/Editor/LgtFileReaderTests.cs.meta new file mode 100644 index 00000000..2288fd71 --- /dev/null +++ b/Assets/Tests/Editor/LgtFileReaderTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 429afcc7be274dfa9734a879b9436fd4 diff --git a/Assets/Tests/Editor/LocalGameDataTests.cs b/Assets/Tests/Editor/LocalGameDataTests.cs index c914c37f..f94da8a5 100644 --- a/Assets/Tests/Editor/LocalGameDataTests.cs +++ b/Assets/Tests/Editor/LocalGameDataTests.cs @@ -34,9 +34,10 @@ namespace Pal3.Core.Tests private static string DataRoot() { - string root = Environment.GetEnvironmentVariable("PAL3_TEST_DATA_ROOT") ?? + string root = Environment.GetEnvironmentVariable(Variant + "_TEST_DATA_ROOT") ?? Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "..", "Game Data", Variant)); - if (!Directory.Exists(root)) Assert.Ignore($"Set PAL3_TEST_DATA_ROOT to the {Variant} data directory"); + if (!Directory.Exists(root)) + Assert.Ignore($"Set {Variant}_TEST_DATA_ROOT to the {Variant} data directory"); return root; } diff --git a/Assets/Tests/Editor/OriginalEffectFormatTests.cs.meta b/Assets/Tests/Editor/OriginalEffectFormatTests.cs.meta deleted file mode 100644 index fa0af252..00000000 --- a/Assets/Tests/Editor/OriginalEffectFormatTests.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: c8efb240fc6a64537ba57e4b865f14de \ No newline at end of file diff --git a/Assets/Tests/EditorSupport.meta b/Assets/Tests/EditorSupport.meta new file mode 100644 index 00000000..74ef2a8e --- /dev/null +++ b/Assets/Tests/EditorSupport.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4efc038bc32447df95b80581af292064 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/EditorSupport/OffscreenGui.cs b/Assets/Tests/EditorSupport/OffscreenGui.cs new file mode 100644 index 00000000..c2992ca2 --- /dev/null +++ b/Assets/Tests/EditorSupport/OffscreenGui.cs @@ -0,0 +1,200 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tests.EditorSupport +{ + using System; + using System.Reflection; + using System.Runtime.ExceptionServices; + using UnityEditor; + using UnityEngine; + using UnityEngine.Rendering; + using UnityEngine.TestTools; + using UnityEngine.UIElements; + using Object = UnityEngine.Object; + + /// Runs editor IMGUI on a detached panel with persistent layout and control state. + public sealed class OffscreenGui : IDisposable + { + private sealed class Owner : ScriptableObject + { + } + + private const BindingFlags Instance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; + private const BindingFlags Static = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; + private static readonly Type PanelType = typeof(VisualElement).Assembly.GetType("UnityEngine.UIElements.Panel", true); + private static readonly MethodInfo CreatePanel = PanelType.GetMethod("CreateEditorPanel", Static, null, new[] { typeof(ScriptableObject) }, null); + private static readonly PropertyInfo VisualTree = PanelType.GetProperty("visualTree", Instance); + private static readonly MethodInfo DoOnGui = typeof(IMGUIContainer).GetMethod("DoOnGUI", Instance, null, + new[] { typeof(Event), typeof(Matrix4x4), typeof(Rect), typeof(bool), typeof(Rect), typeof(Action), typeof(bool) }, null); + + private static readonly Type ContainerWindow = typeof(EditorWindow).Assembly.GetType("UnityEditor.ContainerWindow", true); + + private readonly ScriptableObject _owner; + private readonly IDisposable _panel; + private readonly VisualElement _tree; + private readonly IMGUIContainer _container; + private readonly Action _draw; + private readonly int _windowCount; + private Event _input; + private bool _editingTextField, _disposed; + private int _keyboardControl, _hotControl; + + public RenderTexture RenderTarget + { + get; private set; + } + + public OffscreenGui(Action draw) + { + _windowCount = Resources.FindObjectsOfTypeAll(ContainerWindow).Length; + _owner = ScriptableObject.CreateInstance(); + _panel = (IDisposable)CreatePanel.Invoke(null, new object[] { _owner }); + _tree = (VisualElement)VisualTree.GetValue(_panel); + _draw = () => + { + GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector); + Event.current.mousePosition = _input.mousePosition; + Event.current.delta = _input.delta; + Event.current.button = _input.button; + draw(); + }; + _container = new IMGUIContainer(_draw) { contextType = ContextType.Editor, cullingEnabled = false }; + _tree.Add(_container); + } + + public void Paint(Vector2 size) + { + Run(new Event { type = EventType.Layout }, size); + Run(new Event { type = EventType.Repaint }, size); + } + + public void SendEvent(Event input, Vector2 size) + { + if (input.type is not (EventType.Layout or EventType.Repaint)) + Run(new Event { type = EventType.Layout, mousePosition = input.mousePosition }, size); + Run(input, size); + } + + private static bool IsPointer(Event input) => input.isMouse || input.type == EventType.ScrollWheel; + + private void Run(Event input, Vector2 size) + { + _tree.style.width = _container.style.width = size.x; + _tree.style.height = _container.style.height = size.y; + bool graphics = SystemInfo.graphicsDeviceType != GraphicsDeviceType.Null; + if (graphics) + EnsureTarget(size); + var layout = new Rect(Vector2.zero, size); + Event previousEvent = Event.current; + RenderTexture previousTarget = graphics ? RenderTexture.active : null; + Application.logMessageReceived += AllowCursorRectWithoutWindow; + try + { + _input = new Event(input); + Event.current = input; + if (graphics) + { + RenderTexture.active = RenderTarget; + GL.PushMatrix(); + } + try + { + if (graphics) + { + GL.Viewport(layout); + GL.LoadPixelMatrix(0, size.x, size.y, 0); + if (input.type == EventType.Repaint) + GL.Clear(true, true, Color.black); + } + // Translate the detached panel's pointer origin for native controls in nested clips. + Vector2 offset = IsPointer(_input) ? -_input.mousePosition : Vector2.zero; + // The text editor flag is global even though IMGUIContainer saves its own control state. + bool previousEditing = EditorGUIUtility.editingTextField; + int previousKeyboardControl = GUIUtility.keyboardControl; + int previousHotControl = GUIUtility.hotControl; + try + { + EditorGUIUtility.editingTextField = _editingTextField; + GUIUtility.keyboardControl = _keyboardControl; + GUIUtility.hotControl = _hotControl; + DoOnGui.Invoke(_container, new object[] { input, Matrix4x4.Translate(offset), new Rect(offset, size), false, layout, _draw, true }); + } + finally + { + _editingTextField = EditorGUIUtility.editingTextField; + _keyboardControl = GUIUtility.keyboardControl; + _hotControl = input.rawType == EventType.MouseUp ? 0 : GUIUtility.hotControl; + EditorGUIUtility.editingTextField = previousEditing; + GUIUtility.keyboardControl = previousKeyboardControl; + GUIUtility.hotControl = previousHotControl; + } + } + finally + { + if (graphics) + GL.PopMatrix(); + } + } + catch (TargetInvocationException exception) when (exception.InnerException is ExitGUIException) + { + // Standard IMGUI control flow. A detached panel has no host view to catch it. + } + catch (TargetInvocationException exception) when (exception.InnerException != null) + { + ExceptionDispatchInfo.Capture(exception.InnerException).Throw(); + } + finally + { + Application.logMessageReceived -= AllowCursorRectWithoutWindow; + Event.current = previousEvent; + if (graphics) + RenderTexture.active = previousTarget; + } + + if (Resources.FindObjectsOfTypeAll(ContainerWindow).Length > _windowCount) + throw new InvalidOperationException("An offscreen GUI test opened a native Unity window."); + } + + private void EnsureTarget(Vector2 size) + { + int width = Mathf.Max(1, Mathf.CeilToInt(size.x)); + int height = Mathf.Max(1, Mathf.CeilToInt(size.y)); + if (RenderTarget != null && RenderTarget.width == width && RenderTarget.height == height) + return; + ReleaseTarget(); + RenderTarget = new RenderTexture(width, height, 24, RenderTextureFormat.ARGB32); + RenderTarget.Create(); + } + + private static void AllowCursorRectWithoutWindow(string message, string stackTrace, LogType type) + { + // Editor controls register resize cursors with GUIView, which is deliberately absent. + if (type == LogType.Error && message == "EditorGUIUtility.AddCursorRect called outside an editor OnGUI") + LogAssert.Expect(type, message); + } + + private void ReleaseTarget() + { + if (RenderTarget == null) + return; + RenderTarget.Release(); + Object.DestroyImmediate(RenderTarget); + RenderTarget = null; + } + + public void Dispose() + { + if (_disposed) + return; + _disposed = true; + _container.RemoveFromHierarchy(); + _container.Dispose(); + _panel.Dispose(); + Object.DestroyImmediate(_owner); + ReleaseTarget(); + } + } +} diff --git a/Assets/Tests/EditorSupport/OffscreenGui.cs.meta b/Assets/Tests/EditorSupport/OffscreenGui.cs.meta new file mode 100644 index 00000000..cc0fbaa9 --- /dev/null +++ b/Assets/Tests/EditorSupport/OffscreenGui.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 54c063ca65084782b3eb3d3edebd226a diff --git a/Assets/Tests/EditorSupport/Pal3.Editor.TestSupport.asmdef b/Assets/Tests/EditorSupport/Pal3.Editor.TestSupport.asmdef new file mode 100644 index 00000000..920d4b51 --- /dev/null +++ b/Assets/Tests/EditorSupport/Pal3.Editor.TestSupport.asmdef @@ -0,0 +1,6 @@ +{ + "name": "Pal3.Editor.TestSupport", + "includePlatforms": ["Editor"], + "optionalUnityReferences": ["TestAssemblies"], + "autoReferenced": false +} diff --git a/Assets/Tests/EditorSupport/Pal3.Editor.TestSupport.asmdef.meta b/Assets/Tests/EditorSupport/Pal3.Editor.TestSupport.asmdef.meta new file mode 100644 index 00000000..8dedb450 --- /dev/null +++ b/Assets/Tests/EditorSupport/Pal3.Editor.TestSupport.asmdef.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 5cb8f6c09e054247bf08fbc0cdf6144f diff --git a/Assets/Tests/Game/Editor/BattleSceneTargetTests.cs b/Assets/Tests/Game/Editor/BattleSceneTargetTests.cs new file mode 100644 index 00000000..facf3567 --- /dev/null +++ b/Assets/Tests/Game/Editor/BattleSceneTargetTests.cs @@ -0,0 +1,42 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.Tests +{ + using System.Collections.Generic; + using System.Reflection; + using GameSystems.Battle; + using GameSystems.Battle.Actor.Controllers; + using GameSystems.Battle.Scene; + using NUnit.Framework; + using UnityEngine; + + public sealed class BattleSceneTargetTests + { + [TestCase(ElementPosition.AllyCenter, ElementPosition.EnemyEarth)] + [TestCase(ElementPosition.EnemyWind, ElementPosition.AllyCenter)] + public void RandomOpponentUsesOccupiedSlotsOnTheOtherSide(ElementPosition from, ElementPosition to) + { + var root = new GameObject(); + try + { + var scene = root.AddComponent(); + scene.LoadActors(new(), default); + var actors = (Dictionary)typeof(BattleScene) + .GetField("_battleActorControllers", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(scene); + actors[from] = root.AddComponent(); + Assert.That(scene.GetRandomOpponent(from), Is.Null); + + var target = root.AddComponent(); + actors[to] = target; + Assert.That(scene.GetRandomOpponent(from), Is.SameAs(target)); + } + finally + { + Object.DestroyImmediate(root); + } + } + } +} diff --git a/Assets/Tests/Game/Editor/BattleSceneTargetTests.cs.meta b/Assets/Tests/Game/Editor/BattleSceneTargetTests.cs.meta new file mode 100644 index 00000000..b0d3b0e6 --- /dev/null +++ b/Assets/Tests/Game/Editor/BattleSceneTargetTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 55da7c3b7d7a480797221c702e2c1764 diff --git a/Assets/Tests/Game/Editor/OriginalEffectReviewTests.cs b/Assets/Tests/Game/Editor/EffectReviewTests.cs similarity index 89% rename from Assets/Tests/Game/Editor/OriginalEffectReviewTests.cs rename to Assets/Tests/Game/Editor/EffectReviewTests.cs index 597eeed5..fc1745a3 100644 --- a/Assets/Tests/Game/Editor/OriginalEffectReviewTests.cs +++ b/Assets/Tests/Game/Editor/EffectReviewTests.cs @@ -19,7 +19,7 @@ namespace Pal3.Game.Tests using Core.Primitives; using Core.Utilities; using Effect; - using Effect.Original; + using Effect.Runtime; using Engine.Core.Implementation; using Engine.Extensions; using NUnit.Framework; @@ -27,11 +27,11 @@ namespace Pal3.Game.Tests using UnityEngine; [Category("LocalGameData")] - public sealed class OriginalEffectReviewTests + public sealed class EffectReviewTests { - private static OriginalEffectResources Open(string variant) + private static EffectResources Open(string variant) { - return new OriginalEffectResources(OpenFileSystem(variant)); + return new EffectResources(OpenFileSystem(variant)); } private static CpkFileSystem OpenFileSystem(string variant) @@ -51,7 +51,7 @@ namespace Pal3.Game.Tests public readonly GameObject Root = new("Effect position regression"); public readonly GameScene Scene; public readonly EffectManager Manager; - public readonly OriginalEffectResources Resources; + public readonly EffectResources Resources; public readonly EffectRuntime Runtime; public EffectScene() @@ -64,7 +64,7 @@ namespace Pal3.Game.Tests Root.SetActive(false); Scene = Root.AddComponent(); Runtime = new EffectRuntime(fs, 936); - Resources = Runtime.Original; + Resources = Runtime.Resources; const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; var scenes = (SceneManager)FormatterServices.GetUninitializedObject(typeof(SceneManager)); typeof(SceneManager).GetField("_currentGameScene", flags).SetValue(scenes, Scene); @@ -74,13 +74,13 @@ namespace Pal3.Game.Tests typeof(EffectManager).GetField("_effects", flags).SetValue(Manager, Runtime); } - public OriginalEffectPlayer PlayOriginal(int group = 15) + public EffectPlayer PlayOriginal(int group = 15) { // These tests exercise command dispatch and placement, including // PAL3A's shape-change IDs, without requiring their SPar renderer. Resources.Definitions.Groups[group] = new EffectGroup(); Manager.Execute(new EffectPlayCommand(group)); - OriginalEffectPlayer[] players = Root.GetComponentsInChildren(true); + EffectPlayer[] players = Root.GetComponentsInChildren(true); Assert.That(players, Has.Length.EqualTo(1), "Missing actors must not suppress native playback"); Assert.That(players[0].Error, Is.Null); return players[0]; @@ -162,24 +162,24 @@ namespace Pal3.Game.Tests } } - private static OriginalEffectObjectOverride Object(OriginalEffectResources resources, int group, string kind) + private static EffectObjectOverride Object(EffectResources resources, int group, string kind) { for (int index = 0; index < resources.Definitions.Groups[group].Objects.Length; index++) { EffectGroupObject obj = resources.Definitions.Groups[group].Objects[index]; resources.Definitions.TryGetType(obj.TypeCrc, out var definition); if (EffectClass.Name(definition.ClassNameCrc) == kind) - return new OriginalEffectObjectOverride { GroupId = group, ObjectIndex = index, Definition = definition, Tasks = obj.Tasks }; + return new EffectObjectOverride { GroupId = group, ObjectIndex = index, Definition = definition, Tasks = obj.Tasks }; } throw new InvalidOperationException($"Group {group} has no {kind}"); } - private static void HideOtherObjects(OriginalEffectResources resources, OriginalEffectOverrides edits, OriginalEffectObjectOverride selected) + private static void HideOtherObjects(EffectResources resources, EffectOverrides edits, EffectObjectOverride selected) { edits.Objects.Add(selected); for (int i = 0; i < resources.Definitions.Groups[selected.GroupId].Objects.Length; i++) if (i != selected.ObjectIndex) - edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = selected.GroupId, ObjectIndex = i, Hidden = true }); + edits.Objects.Add(new EffectObjectOverride { GroupId = selected.GroupId, ObjectIndex = i, Hidden = true }); } [TestCase(".cvd")] @@ -187,7 +187,7 @@ namespace Pal3.Game.Tests public void ModelDiagnosisRejectsMissingAndUnknownFormats(string extension) { using var resources = Open("PAL3"); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); try { var edit = Object(resources, 173, "model"); @@ -236,12 +236,12 @@ namespace Pal3.Game.Tests public void LivePolModelRetainsItsAuxiliaryTextureWhenResourcesAreTrimmed() { using var resources = Open("PAL3A"); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("POL lightmap lifetime"); try { HideOtherObjects(resources, edits, Object(resources, 157, "model")); - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 157, overrides: edits); player.Advance(0.5f); @@ -277,7 +277,7 @@ namespace Pal3.Game.Tests public void ExplosiveSubdivisionsUseTheOriginalFloatToIntTruncation() { using var resources = Open("PAL3A"); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("Explosive subdivisions"); try { @@ -286,7 +286,7 @@ namespace Pal3.Game.Tests edit.Definition.DivisionCount = 2.9f; edit.Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 1 } }; HideOtherObjects(resources, edits, edit); - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 173, overrides: edits); player.AdvanceFrame(0.1f); diff --git a/Assets/Tests/Game/Editor/OriginalEffectReviewTests.cs.meta b/Assets/Tests/Game/Editor/EffectReviewTests.cs.meta similarity index 100% rename from Assets/Tests/Game/Editor/OriginalEffectReviewTests.cs.meta rename to Assets/Tests/Game/Editor/EffectReviewTests.cs.meta diff --git a/Assets/Tests/Game/Editor/OriginalEffectTests.cs b/Assets/Tests/Game/Editor/EffectTests.cs similarity index 90% rename from Assets/Tests/Game/Editor/OriginalEffectTests.cs rename to Assets/Tests/Game/Editor/EffectTests.cs index 4172d40f..7ad4499c 100644 --- a/Assets/Tests/Game/Editor/OriginalEffectTests.cs +++ b/Assets/Tests/Game/Editor/EffectTests.cs @@ -11,7 +11,7 @@ namespace Pal3.Game.Tests using System.Collections.Generic; using Core.DataReader.Cpk; using Core.FileSystem; - using Effect.Original; + using Effect.Runtime; using Core.DataReader.Data; using Core.Utilities; using Engine.Core.Implementation; @@ -22,7 +22,7 @@ namespace Pal3.Game.Tests using UnityEngine; [Category("LocalGameData")] - public sealed class OriginalEffectTests + public sealed class EffectTests { // Script groups plus the scene groups. Numeric IDs are integration // contracts, not copied original binary fixtures. @@ -30,7 +30,7 @@ namespace Pal3.Game.Tests 259,260,261,262,263,264,265,266,270,275,276,277,278,290,295,297,314,331,332,337,339,341, 368,369,376,389,400,450,451,452,453,454,455,456,457,458,465,467,468,515 }; - private static OriginalEffectResources Open() + private static EffectResources Open() { string path = Environment.GetEnvironmentVariable("PAL3_TEST_DATA_ROOT") ?? Path.GetFullPath("../Game Data/PAL3"); if (!Directory.Exists(path)) @@ -39,7 +39,7 @@ namespace Pal3.Game.Tests crc.Init(); var fs = new CpkFileSystem(path, crc, 936); fs.Mount("basedata/basedata.cpk", 936); - return new OriginalEffectResources(fs); + return new EffectResources(fs); } [Test] @@ -65,7 +65,7 @@ namespace Pal3.Game.Tests var root = new GameObject($"Original effect test {id}"); try { - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, id, 123); Assert.That(player.Error, Is.Null, $"{id} initialization"); @@ -112,7 +112,7 @@ namespace Pal3.Game.Tests try { int audio = 0; - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 254, 123, sound: _ => audio++); for (int i = 0; i < 150; i++) @@ -138,14 +138,14 @@ namespace Pal3.Game.Tests public void ParticleCurveOverridesDoNotMutateCachedOriginalData() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); try { const string path = "effect\\gbParticle\\yiwai3.par"; - Assert.That(OriginalEffectResources.RelativeTo("effect/gbParticle/yiwai3.par", "partexture/guangdianer.jpg"), + Assert.That(EffectResources.RelativeTo("effect/gbParticle/yiwai3.par", "partexture/guangdianer.jpg"), Is.EqualTo("effect\\gbParticle\\partexture\\guangdianer.jpg")); float original = resources.Particle(path).Particles[0].Size.Evaluate(0.5f); - edits.ParticleCurves.Add(new OriginalParticleCurveOverride + edits.ParticleCurves.Add(new ParticleCurveOverride { File = path, Parameter = "Size", @@ -171,7 +171,7 @@ namespace Pal3.Game.Tests camera.enabled = false; try { - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 175, 123); for (int i = 0; i < 100; i++) @@ -198,7 +198,7 @@ namespace Pal3.Game.Tests var root = new GameObject("Persistent effect test"); try { - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 275); player.Loop = true; @@ -223,7 +223,7 @@ namespace Pal3.Game.Tests var root = new GameObject("Transport test"); try { - var portal = root.AddComponent(); + var portal = root.AddComponent(); portal.AutoAdvance = false; portal.Initialize(resources); portal.Sample(2); @@ -243,7 +243,7 @@ namespace Pal3.Game.Tests public void ZeroOrbitAxisPreservesRadiusAndInvalidTasksStayDisabled() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("Orbit semantics"); var cameraRoot = new GameObject("Camera"); try @@ -251,13 +251,13 @@ namespace Pal3.Game.Tests var edit = OverrideObject(resources, 15, 0); edits.Objects.Add(edit); for (int i = 1; i < resources.Definitions.Groups[15].Objects.Length; i++) - edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = 15, ObjectIndex = i, Hidden = true }); + edits.Objects.Add(new EffectObjectOverride { GroupId = 15, ObjectIndex = i, Hidden = true }); edit.Definition.InitXPosition = edit.Definition.InitYPosition = edit.Definition.InitZPosition = 0; edit.Definition.FramePerSecond = 0; edit.Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 10, CircleRadius = 20 } }; var camera = cameraRoot.AddComponent(); camera.enabled = false; - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 15, overrides: edits); player.Advance(0.04f); @@ -284,7 +284,7 @@ namespace Pal3.Game.Tests public void DiagnosisIncludesCallbackOverridesAndDoesNotPoisonOriginalCache() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); try { Assert.That(resources.Diagnose(275), Is.Empty); @@ -306,7 +306,7 @@ namespace Pal3.Game.Tests public void NonFiniteOverrideParametersAreRejectedBeforeSimulation() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); try { var edit = OverrideObject(resources, 15, 0); @@ -324,7 +324,7 @@ namespace Pal3.Game.Tests public void TaperedMeteorStripSharesEndpointsAndInterpolatesLuminosity() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("Meteor strip continuity"); var cameraRoot = new GameObject("Camera"); try @@ -332,7 +332,7 @@ namespace Pal3.Game.Tests var edit = OverrideObject(resources, 240, 0); edits.Objects.Add(edit); for (int i = 1; i < resources.Definitions.Groups[240].Objects.Length; i++) - edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = 240, ObjectIndex = i, Hidden = true }); + edits.Objects.Add(new EffectObjectOverride { GroupId = 240, ObjectIndex = i, Hidden = true }); Assert.That(EffectClass.Name(edit.Definition.ClassNameCrc), Is.EqualTo("meteor")); edit.Definition.RotationAngle = -1; edit.Definition.Width = 20; @@ -350,7 +350,7 @@ namespace Pal3.Game.Tests edit.Definition.TopRadiusIncreaseSpeed = edit.Definition.BottomRadiusIncreaseSpeed = edit.Definition.TopRiseSpeed = 0; edit.Definition.RotationAngle = 1; edit.Tasks[0].SpeedX = 20; - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 240, overrides: edits); player.Advance(0.04f); @@ -384,7 +384,7 @@ namespace Pal3.Game.Tests public void ParticleEmitterRunsItsInitialCycleBeforeTheDelayedTaskEnablesLooping() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("Initial particle cycle"); var cameraRoot = new GameObject("Camera"); try @@ -392,12 +392,12 @@ namespace Pal3.Game.Tests var edit = OverrideObject(resources, 175, 0); edits.Objects.Add(edit); for (int i = 1; i < resources.Definitions.Groups[175].Objects.Length; i++) - edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = 175, ObjectIndex = i, Hidden = true }); + edits.Objects.Add(new EffectObjectOverride { GroupId = 175, ObjectIndex = i, Hidden = true }); var par = resources.Particle(edit.Definition.ParticleFileName); float cycle = par.Emitters.Max(e => e.CycleMin - e.CycleMax); edit.Tasks = new[] { new EffectTask { IsValid = true, StartTime = cycle + 1, Duration = 0.2f } }; for (int i = 0; i < par.Emitters.Length; i++) - edits.ParticleCurves.Add(new OriginalParticleCurveOverride + edits.ParticleCurves.Add(new ParticleCurveOverride { File = edit.Definition.ParticleFileName, Emitter = true, @@ -408,7 +408,7 @@ namespace Pal3.Game.Tests }); var camera = cameraRoot.AddComponent(); camera.enabled = false; - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 175, overrides: edits); player.Seek(0.1f); @@ -430,7 +430,7 @@ namespace Pal3.Game.Tests public void CombatParticleTaskMotionMovesTheWholeCloudInWorldSpaceParFiles() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("Combat particle task motion"); var cameraRoot = new GameObject("Camera"); try @@ -438,12 +438,12 @@ namespace Pal3.Game.Tests var edit = OverrideObject(resources, 175, 0); edits.Objects.Add(edit); for (int i = 1; i < resources.Definitions.Groups[175].Objects.Length; i++) - edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = 175, ObjectIndex = i, Hidden = true }); + edits.Objects.Add(new EffectObjectOverride { GroupId = 175, ObjectIndex = i, Hidden = true }); Assert.That(resources.Particle(edit.Definition.ParticleFileName).Space, Is.Zero); edit.Tasks = new[] { new EffectTask { IsValid = true, Duration = 2 } }; var camera = cameraRoot.AddComponent(); camera.enabled = false; - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 175, 123, edits); player.Seek(0.5f); @@ -472,7 +472,7 @@ namespace Pal3.Game.Tests public void FailedTextureAndModelInitializationReleaseMaterials() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("Failed resource cleanup"); try { @@ -484,7 +484,7 @@ namespace Pal3.Game.Tests edits.Objects.Add(edit); Assert.That(EffectClass.Name(edit.Definition.ClassNameCrc), Is.EqualTo("model")); edit.Definition.TextureName = "effect\\missing-review-model.cvd"; - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; for (int i = 0; i < 3; i++) { @@ -511,7 +511,7 @@ namespace Pal3.Game.Tests void Call(string name) => type.GetMethod(name, flags).Invoke(window, null); try { - var working = (OriginalEffectOverrides)type.GetField("_edits", flags).GetValue(window); + var working = (EffectOverrides)type.GetField("_edits", flags).GetValue(window); working.Objects.Add(OverrideObject(resources, 15, 0)); Call("MarkChanged"); Assert.That(window.hasUnsavedChanges, Is.True); @@ -537,7 +537,7 @@ namespace Pal3.Game.Tests public void RuntimeFrameClockMovesOnEveryFrameWhileFixedSeekingStaysRepeatable(int fps) { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("Frame clock"); var cameraRoot = new GameObject("Camera"); try @@ -547,7 +547,7 @@ namespace Pal3.Game.Tests edit.Tasks = new[] { new EffectTask { IsValid = true, Duration = 5, SpeedX = 20 } }; var camera = cameraRoot.AddComponent(); camera.enabled = false; - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 15, 123, edits); float dt = 1f / fps; @@ -592,7 +592,7 @@ namespace Pal3.Game.Tests public void ModelRotationAndStretchUse60FpsReferenceAcrossFrameRatesAndSeeking(int fps) { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("Model frame rate"); try { @@ -606,7 +606,7 @@ namespace Pal3.Game.Tests edit.Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 5, SpeedX = 20, SpeedY = 10, SpeedZ = 5, RotAxisX = 0.2f, RotAxisY = 0.4f, RotAxisZ = -0.1f, XStretchSpeed = 0.01f, YStretchSpeed = 0.02f, CreateTimeSlot = -0.005f } }; - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 173, 123, edits); Assert.That(player.Error, Is.Null); @@ -653,14 +653,14 @@ namespace Pal3.Game.Tests public void ModelOpacityTasksUseNormalizedAlphaAndSeparateMaterials() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("Model opacity"); try { var edit = SoloObject(resources, edits, 173); edit.Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 2, SpeedAlpha = -0.5f } }; Assert.That(resources.Diagnose(173, edits), Is.Empty); - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 173, overrides: edits); player.AdvanceFrame(0.5f); @@ -687,7 +687,7 @@ namespace Pal3.Game.Tests public void CombatParticleScalingAndBlendFollowPal3ParticleEffectRatherThanEngineGbParticleEffect() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); var root = new GameObject("Legacy combat particle semantics"); var cameraRoot = new GameObject("Camera"); try @@ -715,7 +715,7 @@ namespace Pal3.Game.Tests } var camera = cameraRoot.AddComponent(); camera.enabled = false; - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; edit.Definition.InitSize = 20; player.Initialize(resources, 175, 123, edits); @@ -760,11 +760,11 @@ namespace Pal3.Game.Tests public void UnchangedOverridesReuseParticleAndDiagnosticCachesAndEditsInvalidateBoth() { using var resources = Open(); - var edits = ScriptableObject.CreateInstance(); + var edits = ScriptableObject.CreateInstance(); try { const string path = "effect\\gbParticle\\yiwai3.par"; - var curve = new OriginalParticleCurveOverride + var curve = new ParticleCurveOverride { File = path, Parameter = "Size", @@ -800,7 +800,7 @@ namespace Pal3.Game.Tests var root = new GameObject("Live render assets"); try { - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, 175); Material live = root.GetComponentInChildren().sharedMaterial; @@ -835,15 +835,15 @@ namespace Pal3.Game.Tests var scene = new GameObject("Effect scene"); try { - runtime.Original.Definitions.Groups[15] = new EffectGroup(); + runtime.Resources.Definitions.Groups[15] = new EffectGroup(); using var attachment = runtime.Attach(15, new GameEntity(scene)); Assert.That(runtime.Play(15, new GameEntity(scene), new Vector3(10, 0, 0)), Is.True); - var players = scene.GetComponentsInChildren(); + var players = scene.GetComponentsInChildren(); Assert.That(players, Has.Length.EqualTo(2)); Assert.That(players.Single(p => p.Loop).DestroyOnComplete, Is.False); Assert.That(players.Single(p => !p.Loop).transform.localPosition.x, Is.EqualTo(10)); runtime.ClearPlayedEffects(); - players = scene.GetComponentsInChildren(); + players = scene.GetComponentsInChildren(); Assert.That(players, Has.Length.EqualTo(1)); Assert.That(players[0].Loop, Is.True); attachment.Dispose(); @@ -865,7 +865,7 @@ namespace Pal3.Game.Tests const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; try { - var player = (OriginalEffectPlayer)type.GetField("_player", flags).GetValue(window); + var player = (EffectPlayer)type.GetField("_player", flags).GetValue(window); Assert.That(player, Is.Not.Null); type.GetMethod("QueueSeek", flags).Invoke(window, new object[] { 1f }); type.GetMethod("QueueSeek", flags).Invoke(window, new object[] { 2f }); @@ -881,20 +881,20 @@ namespace Pal3.Game.Tests } } - private static OriginalEffectObjectOverride SoloObject(OriginalEffectResources resources, OriginalEffectOverrides edits, int group) + private static EffectObjectOverride SoloObject(EffectResources resources, EffectOverrides edits, int group) { var edit = OverrideObject(resources, group, 0); edits.Objects.Add(edit); for (int i = 1; i < resources.Definitions.Groups[group].Objects.Length; i++) - edits.Objects.Add(new OriginalEffectObjectOverride { GroupId = group, ObjectIndex = i, Hidden = true }); + edits.Objects.Add(new EffectObjectOverride { GroupId = group, ObjectIndex = i, Hidden = true }); return edit; } - private static OriginalEffectObjectOverride OverrideObject(OriginalEffectResources resources, int group, int index) + private static EffectObjectOverride OverrideObject(EffectResources resources, int group, int index) { EffectGroupObject source = resources.Definitions.Groups[group].Objects[index]; resources.Definitions.TryGetType(source.TypeCrc, out EffectDefinition definition); - return new OriginalEffectObjectOverride + return new EffectObjectOverride { GroupId = group, ObjectIndex = index, diff --git a/Assets/Tests/Game/Editor/EffectTests.cs.meta b/Assets/Tests/Game/Editor/EffectTests.cs.meta new file mode 100644 index 00000000..25502fad --- /dev/null +++ b/Assets/Tests/Game/Editor/EffectTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 100011eb82a8643f695ea64a052075b4 diff --git a/Assets/Tests/Game/Editor/OriginalEffectTests.cs.meta b/Assets/Tests/Game/Editor/OriginalEffectTests.cs.meta deleted file mode 100644 index 3dd8bedd..00000000 --- a/Assets/Tests/Game/Editor/OriginalEffectTests.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 100011eb82a8643f695ea64a052075b4 \ No newline at end of file diff --git a/Assets/Tests/Game/Editor/OriginalPal3AEffectTests.cs b/Assets/Tests/Game/Editor/Pal3AEffectTests.cs similarity index 93% rename from Assets/Tests/Game/Editor/OriginalPal3AEffectTests.cs rename to Assets/Tests/Game/Editor/Pal3AEffectTests.cs index 8c29f946..554db834 100644 --- a/Assets/Tests/Game/Editor/OriginalPal3AEffectTests.cs +++ b/Assets/Tests/Game/Editor/Pal3AEffectTests.cs @@ -12,17 +12,17 @@ namespace Pal3.Game.Tests using Core.DataReader.Cpk; using Core.FileSystem; using Core.DataReader.Data; - using Effect.Original; + using Effect.Runtime; using NUnit.Framework; using UnityEngine; [Category("LocalGameData")] - public sealed class OriginalPal3AEffectTests + public sealed class Pal3AEffectTests { public static readonly int[] NativeGroups = { 9, 27, 29, 34, 40, 50, 91, 157, 160, 172, 173, 175, 176, 177, 178, 179, 181, 182, 186, 187, 189, 194, 198, 201, 202, 205, 206, 209, 217, 230, 231, 254, 257, 258, 259, 261, 281, 282, 283, 285, 287, 290, 292, 297, 299, 314, 316, 320, 322, 330, 331, 333, 335, 351, 355, 356, 359, 362, 365, 373, 377, 381, 385, 388, 389, 400, 424 }; public static readonly int[] SparGroups = { 45, 164, 170, 171, 174, 211, 289, 315, 318, 323, 325, 328, 344, 345, 358, 360, 361, 367, 397, 401, 404, 407, 408, 409, 411, 570 }; - private static OriginalEffectResources Open() + private static EffectResources Open() { string path = Environment.GetEnvironmentVariable("PAL3A_TEST_DATA_ROOT") ?? Path.GetFullPath("../Game Data/PAL3A"); if (!Directory.Exists(path)) @@ -31,7 +31,7 @@ namespace Pal3.Game.Tests crc.Init(); var fs = new CpkFileSystem(path, crc, 936); fs.Mount("basedata/basedata.cpk", 936); - return new OriginalEffectResources(fs); + return new EffectResources(fs); } [Test] @@ -47,7 +47,7 @@ namespace Pal3.Game.Tests try { Assert.That(resources.Diagnose(id), Is.Empty, $"Group {id}"); - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, id, 1234); bool rendered = false; @@ -89,14 +89,14 @@ namespace Pal3.Game.Tests definition.InitSize = 100; var file = resources.Spar(definition.ParticleFileName); var group = file.Groups[0]; - var key = OriginalSparTests.Key(); + var key = SparTests.Key(); key.RotationMinimum = key.RotationMaximum = Mathf.PI / 2; group.Keyframes = new[] { key }; group.TextureFrames = new[] { new[] { 0.2f, 0.3f, 0.7f, 0.8f } }; file.Groups = new[] { group }; var root = new GameObject("SPar native billboard"); var task = new EffectTask { StartTime = -1, Duration = 10, SpeedX = 10, RotAxisZ = 900, XStretchSpeed = 100, SpeedAlpha = -255 }; - var node = new OriginalSparNode(root, definition, new[] { task }, Vector3.zero, 0, resources, 1); + var node = new SparNode(root, definition, new[] { task }, Vector3.zero, 0, resources, 1); try { node.Step(0.02f, 0.02f); @@ -134,7 +134,7 @@ namespace Pal3.Game.Tests var root = new GameObject("PAL3A transport"); try { - var portal = root.AddComponent(); + var portal = root.AddComponent(); portal.AutoAdvance = false; portal.Initialize(resources, (uint)type); portal.Sample(2); @@ -142,7 +142,7 @@ namespace Pal3.Game.Tests Assert.That(meshes.Select(m => m.sharedMesh.vertexCount), Is.EqualTo(new[] { 4, 24, 24 })); Assert.That(meshes[0].GetComponent().sharedMaterial.mainTexture.name, Does.EndWith(texture)); Assert.That(meshes[1].sharedMesh.colors32[0], Is.EqualTo(new Color32((byte)red, (byte)green, (byte)blue, 255))); - Assert.That(root.GetComponentsInChildren(), Is.Empty); + Assert.That(root.GetComponentsInChildren(), Is.Empty); } finally { @@ -184,7 +184,7 @@ namespace Pal3.Game.Tests var root = new GameObject($"SPar group {id}"); try { - var player = root.AddComponent(); + var player = root.AddComponent(); player.AutoAdvance = false; player.Initialize(resources, id, 1234); int maximum = 0; @@ -197,7 +197,7 @@ namespace Pal3.Game.Tests { player.Render(null); maximum = Math.Max(maximum, player.QuadCount); - bool hasSpar = root.GetComponentsInChildren().Any(r => r.enabled && r.sharedMaterial.shader.name == "Pal3/OriginalEffect" && r.sharedMaterial.GetInt("_Cull") == 2); + bool hasSpar = root.GetComponentsInChildren().Any(r => r.enabled && r.sharedMaterial.shader.name == "Pal3/Effect" && r.sharedMaterial.GetInt("_Cull") == 2); if (sampleTime == 0 && hasSpar) sampleTime = player.Time; sparRendered |= hasSpar; diff --git a/Assets/Tests/Game/Editor/OriginalPal3AEffectTests.cs.meta b/Assets/Tests/Game/Editor/Pal3AEffectTests.cs.meta similarity index 100% rename from Assets/Tests/Game/Editor/OriginalPal3AEffectTests.cs.meta rename to Assets/Tests/Game/Editor/Pal3AEffectTests.cs.meta diff --git a/Assets/Tests/Game/Editor/OriginalSparTests.cs b/Assets/Tests/Game/Editor/SparTests.cs similarity index 91% rename from Assets/Tests/Game/Editor/OriginalSparTests.cs rename to Assets/Tests/Game/Editor/SparTests.cs index 9dd3f0fd..d63ca58a 100644 --- a/Assets/Tests/Game/Editor/OriginalSparTests.cs +++ b/Assets/Tests/Game/Editor/SparTests.cs @@ -9,11 +9,11 @@ namespace Pal3.Game.Tests using System.Linq; using Core.DataReader.Par; using Core.Primitives; - using Effect.Original; + using Effect.Runtime; using NUnit.Framework; using UnityEngine; - public sealed class OriginalSparTests + public sealed class SparTests { internal static SparKeyframe Key(float time = 0) { @@ -52,7 +52,7 @@ namespace Pal3.Game.Tests { SparKeyframe key = Key(); key.Controllers[0].Kind = 1; - var emitter = new OriginalSparEmitter(Group(key), 1); + var emitter = new SparEmitter(Group(key), 1); emitter.Step(0.1f); Assert.That(emitter.Count, Is.EqualTo(2)); Assert.That(emitter.Units[0].Age, Is.EqualTo(0.1f)); @@ -70,7 +70,7 @@ namespace Pal3.Game.Tests { SparKeyframe key = Key(); key.Controllers[0] = new SparController { Kind = kind, Parameters = new[] { force, y, z, 0.5f } }; - var emitter = new OriginalSparEmitter(Group(key), 123); + var emitter = new SparEmitter(Group(key), 123); emitter.Step(0.1f); Assert.That(emitter.Units[0].Position.x, Is.EqualTo(expectedX).Within(0.000001)); } @@ -84,7 +84,7 @@ namespace Pal3.Game.Tests key.Shape = 2; key.ShapeParameters = new[] { 4f, 0, 0, 4f, 0, 0 }; key.Controllers[0].Kind = kind; - var emitter = new OriginalSparEmitter(Group(key), 1); + var emitter = new SparEmitter(Group(key), 1); emitter.Step(0.1f); Assert.That(emitter.Units[0].Position.x, Is.EqualTo(expectedX).Within(0.000001)); Assert.That(emitter.Units[0].Velocity.x, Is.EqualTo(10)); @@ -99,7 +99,7 @@ namespace Pal3.Game.Tests key.PathPoints = new[] { new GameBoxVector3(2, 0, 0), new GameBoxVector3(8, 0, 0) }; SparGroup group = Group(key); group.Capacity = 10; - var emitter = new OriginalSparEmitter(group, 1); + var emitter = new SparEmitter(group, 1); emitter.Step(0.1f); Assert.That(emitter.Units[0].Position.x, Is.EqualTo(8)); emitter.Stop(); @@ -115,7 +115,7 @@ namespace Pal3.Game.Tests key.Shape = 3; key.ShapeParameters = new[] { 1f, 0, 0 }; key.Controllers[5] = new SparController { Kind = 1, Parameters = new[] { 0f, 0, 1, Mathf.PI } }; - var emitter = new OriginalSparEmitter(Group(key), 1); + var emitter = new SparEmitter(Group(key), 1); emitter.Step(0.5f); Assert.That(emitter.Units[0].Position.x, Is.EqualTo(0).Within(0.000001)); Assert.That(emitter.Units[0].Position.y, Is.EqualTo(1).Within(0.000001)); @@ -130,7 +130,7 @@ namespace Pal3.Game.Tests b.SizeMinimum = b.SizeMaximum = 6; SparGroup group = Group(a, b, c); group.Loop = true; - var emitter = new OriginalSparEmitter(group, 1); + var emitter = new SparEmitter(group, 1); emitter.Step(1); Assert.That(emitter.Units[0].Size, Is.EqualTo(6)); Assert.That(emitter.Units[0].Position.x, Is.EqualTo(10)); @@ -147,7 +147,7 @@ namespace Pal3.Game.Tests SparKeyframe key = Key(); key.FrameMinimum = key.FrameMaximum = 1; key.Controllers[4] = new SparController { Kind = kind, Parameters = new[] { 0.125f } }; - var emitter = new OriginalSparEmitter(Group(key), 1); + var emitter = new SparEmitter(Group(key), 1); emitter.Step(0.5f); Assert.That(emitter.Units[0].Frame, Is.EqualTo(expectedFrame)); } @@ -168,7 +168,7 @@ namespace Pal3.Game.Tests SparGroup group = Group(first, last); group.Capacity = 64; group.TextureFrames = Enumerable.Range(0, 16).Select(i => new[] { i / 16f, 0, (i + 1) / 16f, 1 }).ToArray(); - var emitter = new OriginalSparEmitter(group, 1); + var emitter = new SparEmitter(group, 1); for (int i = 0; i < 3; i++) emitter.Step(0.02f); Assert.That(emitter.Count, Is.GreaterThan(20)); @@ -183,7 +183,7 @@ namespace Pal3.Game.Tests key.LifeMinimum = key.LifeMaximum = 1; key.Controllers[2] = new SparController { Kind = 2, Parameters = new[] { 1f, 0, 0, 0, 0, 1 } }; key.Controllers[3].Kind = 1; - var emitter = new OriginalSparEmitter(Group(key), 1); + var emitter = new SparEmitter(Group(key), 1); emitter.Step(0.25f); Assert.That(emitter.Units[0].Alpha, Is.EqualTo(0.75f)); Assert.That(emitter.Units[0].Color, Is.EqualTo(new Vector3(0.75f, 0, 0.25f))); @@ -194,7 +194,7 @@ namespace Pal3.Game.Tests { SparKeyframe key = Key(); key.LifeMinimum = key.LifeMaximum = 0.01f; - var emitter = new OriginalSparEmitter(Group(key), 1); + var emitter = new SparEmitter(Group(key), 1); emitter.Step(0.1f); Assert.That(emitter.Count, Is.EqualTo(1)); Assert.That(emitter.Units[0].Age, Is.Zero); diff --git a/Assets/Tests/Game/Editor/OriginalSparTests.cs.meta b/Assets/Tests/Game/Editor/SparTests.cs.meta similarity index 100% rename from Assets/Tests/Game/Editor/OriginalSparTests.cs.meta rename to Assets/Tests/Game/Editor/SparTests.cs.meta diff --git a/Assets/Tests/Game/Runtime.meta b/Assets/Tests/Game/Runtime.meta new file mode 100644 index 00000000..205e4cc0 --- /dev/null +++ b/Assets/Tests/Game/Runtime.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 44774decb9a04559a83f66584e6951ab +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Tests/Game/Runtime/EffectLifetimeTests.cs b/Assets/Tests/Game/Runtime/EffectLifetimeTests.cs new file mode 100644 index 00000000..0f7ada2c --- /dev/null +++ b/Assets/Tests/Game/Runtime/EffectLifetimeTests.cs @@ -0,0 +1,143 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.PlayMode.Tests +{ + using System; + using System.Collections; + using System.IO; + using System.Linq; + using Core.DataReader.Cpk; + using Core.DataReader.Data; + using Core.FileSystem; + using Effect.Runtime; + using NUnit.Framework; + using Rendering.Native; + using UnityEngine; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + public sealed class EffectLifetimeTests + { + private sealed class Actor : IEffectActor + { + public Vector3 Position + { + get; set; + } + + public float FacingDegrees + { + get; set; + } + + public float Blend { get; set; } = 1; + public bool ActionOver => false; + + public bool Controlled; + public int Releases; + + public void SetExternalTask(bool controlled, object owner) + { + Controlled = controlled; + if (!controlled) + Releases++; + } + + public void SetAction(string action) + { + } + + public void SetLongBlade(bool enabled) + { + } + + public void SetWeapons(float left, float right) + { + } + } + + private sealed class Context : IBattleEffectContext + { + public readonly Actor Role = new(); + + public IEffectCamera Camera => null; + public bool IsModalPresentationRunning => false; + + public int NextEffectRandom() => 1; + + public IEffectActor Actor(int nativeIndex, uint modelCrc = 0) => Role; + + public IEffectMovie PlayMovie(string originalPath) => throw new NotSupportedException(); + } + + [UnityTest] + [Category("LocalGameData")] + public IEnumerator RuntimeDestructionFallsBackToDisposingLiveActionAndOriginalModel() + { +#if PAL3 + const string variant = "PAL3"; +#else + const string variant = "PAL3A"; +#endif + string directory = Environment.GetEnvironmentVariable(variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(directory)) + Assert.Ignore("Original game data is required for the runtime destruction regression."); + var hash = new Crc32Hash(); + hash.Init(); + var fileSystem = new CpkFileSystem(directory, hash, 936); + string archive = Directory.EnumerateFiles(Path.Combine(directory, "basedata")).Single(file => + Path.GetFileName(file).Equals("basedata.cpk", StringComparison.OrdinalIgnoreCase)); + fileSystem.Mount(Path.GetRelativePath(directory, archive), 936); + using var resources = new EffectResources(fileSystem, 936); + using var lighting = new GameBoxNativeLighting(variant); + EffectDefinitionFile definitions = resources.Definitions; + EffectDefinition action = definitions.EffectDefinitions.First(definition => definition.IsValid && EffectClass.Name(definition.ClassNameCrc) == "action"); + EffectDefinition model = definitions.EffectDefinitions.First(definition => definition.IsValid && EffectClass.Name(definition.ClassNameCrc) == "model" && definition.TextureName.EndsWith(".pol", StringComparison.OrdinalIgnoreCase)); + definitions.Groups[0] = new EffectGroup + { + Objects = new[] + { + new EffectGroupObject { TypeCrc = action.TypeNameCrc, Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 10, XStretchSpeed = 17 } } }, + new EffectGroupObject { TypeCrc = model.TypeNameCrc, Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 10 } } } + } + }; + var root = new GameObject("Runtime effect cleanup"); + var player = root.AddComponent(); + var context = new Context(); + player.AutoAdvance = false; + try + { + player.Initialize(resources, 0, battleContext: context, nativeLighting: lighting); + player.AdvanceFrame(.02f); + Assert.That(player.Error, Is.Null); + Assert.That(context.Role.Controlled, Is.True); + Mesh[] meshes = root.GetComponentsInChildren().Select(filter => filter.sharedMesh).ToArray(); + Material[] materials = root.GetComponentsInChildren().SelectMany(renderer => renderer.sharedMaterials).ToArray(); + Assert.That(meshes, Is.Not.Empty); + yield return null; + // Exercise Unity's real runtime callback; no explicit owner Dispose. + Object.Destroy(root); + yield return null; + yield return null; + Assert.That(root == null, Is.True); + Assert.That(player.NodeCount, Is.Zero); + Assert.That(player.IsAlive, Is.False); + Assert.That(context.Role.Controlled, Is.False); + Assert.That(context.Role.Releases, Is.EqualTo(1)); + Assert.That(meshes.All(mesh => mesh == null), Is.True); + Assert.That(materials.All(material => material == null), Is.True); + player.Dispose(); + Assert.That(context.Role.Releases, Is.EqualTo(1)); + } + finally + { + player.Dispose(); + if (root != null) + Object.Destroy(root); + } + } + } +} diff --git a/Assets/Tests/Game/Runtime/EffectLifetimeTests.cs.meta b/Assets/Tests/Game/Runtime/EffectLifetimeTests.cs.meta new file mode 100644 index 00000000..5f38be42 --- /dev/null +++ b/Assets/Tests/Game/Runtime/EffectLifetimeTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 79fc57ce940b479f8b14046c3d6e3f2b diff --git a/Assets/Tests/Game/Runtime/Pal3.Game.PlayMode.Tests.asmdef b/Assets/Tests/Game/Runtime/Pal3.Game.PlayMode.Tests.asmdef new file mode 100644 index 00000000..02a30d8d --- /dev/null +++ b/Assets/Tests/Game/Runtime/Pal3.Game.PlayMode.Tests.asmdef @@ -0,0 +1,8 @@ +{ + "name": "Pal3.Game.PlayMode.Tests", + "references": ["Pal3.Core", "Pal3.Game", "Engine"], + "optionalUnityReferences": ["TestAssemblies"], + "autoReferenced": false, + "overrideReferences": true, + "precompiledReferences": ["nunit.framework.dll"] +} diff --git a/Assets/Tests/Game/Runtime/Pal3.Game.PlayMode.Tests.asmdef.meta b/Assets/Tests/Game/Runtime/Pal3.Game.PlayMode.Tests.asmdef.meta new file mode 100644 index 00000000..5ea61f13 --- /dev/null +++ b/Assets/Tests/Game/Runtime/Pal3.Game.PlayMode.Tests.asmdef.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: cefcf6e387c34d119644ecfe0ceea3e5 diff --git a/Assets/Tests/Game/Runtime/WeaponBladeLifetimeTests.cs b/Assets/Tests/Game/Runtime/WeaponBladeLifetimeTests.cs new file mode 100644 index 00000000..8e6805fb --- /dev/null +++ b/Assets/Tests/Game/Runtime/WeaponBladeLifetimeTests.cs @@ -0,0 +1,73 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Game.PlayMode.Tests +{ + using System.Collections; + using System.Reflection; + using Core.DataReader.Pol; + using Core.Primitives; + using NUnit.Framework; + using Rendering.Renderer; + using UnityEngine; + using UnityEngine.TestTools; + using Object = UnityEngine.Object; + + public sealed class WeaponBladeLifetimeTests + { + [UnityTest] + public IEnumerator RuntimeCameraWithoutSceneOverrideRendersAndDisposesActiveBlades() + { + var owner = new GameObject("Runtime blade owner"); + var camera = owner.AddComponent(); + camera.enabled = false; + Assert.That(camera.scene.IsValid(), Is.False, "A normal runtime camera must keep its default scene override."); + var tags = new[] + { + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4(), TintColor = 0xffffffff }, + new TagNode { GameBoxTransformMatrix = new GameBoxMatrix4x4 { Ty = 20 }, TintColor = 0xffffffff }, + }; + using var blade = new WeaponBlade(tags); + var material = WeaponBlade.CreateMaterial(); + Mesh mesh = null; + GameObject flush = null; + try + { + blade.SamplePose(owner.transform, true, .12f, false); + blade.Advance(.02f, 1, false); + owner.transform.position = Vector3.right; + blade.SamplePose(owner.transform, true, .12f, false); + blade.RenderFlush(camera, material, 0, 0, true); + blade.RenderFlush(camera, material, 0, 1, true); + Assert.That(camera.scene.IsValid(), Is.False, "Rendering must not install a camera scene override."); + const BindingFlags fields = BindingFlags.Instance | BindingFlags.NonPublic; + mesh = (Mesh)typeof(WeaponBlade).GetField("_mesh", fields).GetValue(blade); + flush = ((MeshRenderer[])typeof(WeaponBlade).GetField("_flushRenderers", fields).GetValue(blade))[0].gameObject; + var renderers = (MeshRenderer[])typeof(WeaponBlade).GetField("_flushRenderers", fields).GetValue(blade); + var flushMeshes = (Mesh[])typeof(WeaponBlade).GetField("_flushMeshes", fields).GetValue(blade); + foreach (MeshRenderer renderer in renderers) + { + Assert.That(renderer.enabled, Is.True); + Assert.That(renderer.gameObject.scene, Is.EqualTo(owner.scene)); + } + blade.Dispose(); + Assert.That(mesh == null, Is.False, "Runtime disposal must use deferred Destroy."); + Assert.That(flush == null, Is.False); + yield return null; + Assert.That(mesh == null, Is.True); + Assert.That(flush == null, Is.True); + foreach (MeshRenderer renderer in renderers) + Assert.That(renderer == null, Is.True); + foreach (Mesh snapshot in flushMeshes) + Assert.That(snapshot == null, Is.True); + } + finally + { + Object.Destroy(owner); + Object.Destroy(material); + } + } + } +} diff --git a/Assets/Tests/Game/Runtime/WeaponBladeLifetimeTests.cs.meta b/Assets/Tests/Game/Runtime/WeaponBladeLifetimeTests.cs.meta new file mode 100644 index 00000000..bf9c9d99 --- /dev/null +++ b/Assets/Tests/Game/Runtime/WeaponBladeLifetimeTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 63adefac3eab4f95ab2abf4a146da95b diff --git a/Assets/Tests/ResourceBrowser/Editor/ModelOpacityTests.cs b/Assets/Tests/ResourceBrowser/Editor/ModelOpacityTests.cs new file mode 100644 index 00000000..14b1fc68 --- /dev/null +++ b/Assets/Tests/ResourceBrowser/Editor/ModelOpacityTests.cs @@ -0,0 +1,355 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.ResourceBrowser.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using Core.DataReader.Mv3; + using Core.DataReader.Pol; + using Core.Primitives; + using Engine.Core.Abstraction; + using Engine.Core.Implementation; + using Game.Rendering.Material; + using Game.Rendering.Renderer; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + using Color = Core.Primitives.Color; + + public sealed class ModelOpacityTests + { + private sealed class CountingFactory : IMaterialFactory + { + public readonly List Materials = new(); + private readonly UnityMaterialFactory _factory = new(); + + public IMaterial CreateMaterial(string shaderName) + { + IMaterial material = _factory.CreateMaterial(shaderName); + Materials.Add(material); + return material; + } + + public IMaterial CreateMaterialFrom(IMaterial template) + { + IMaterial material = _factory.CreateMaterialFrom(template); + Materials.Add(material); + return material; + } + } + + private sealed class Textures : ITextureResourceProvider, IDisposable + { + private readonly UnityTexture2D _texture; + + public Textures() + { + var texture = new Texture2D(1, 1, TextureFormat.RGBA32, false); + texture.SetPixel(0, 0, UnityEngine.Color.white); + texture.Apply(); + _texture = new UnityTexture2D(texture); + } + + public string GetTexturePath(string name) => "opacity/" + name; + + public ITexture2D GetTexture(string name) => GetTexture(name, out _); + + public ITexture2D GetTexture(string name, out bool alpha) + { + alpha = name.StartsWith("alpha", StringComparison.Ordinal); + return _texture; + } + + public void Dispose() => _texture.Destroy(); + } + + private static readonly GameBoxVector3[] Vertices = + { + new(-10, -10, 0), new(0, 10, 0), new(10, -10, 0) + }; + + private static Mv3File Model() => new(4800, Array.Empty(), + new[] { new Mv3TagNode { Name = "tag_weapon", TagFrames = new[] { new Mv3TagFrame { GameBoxRotation = new GameBoxQuaternion(0, 0, 0, 1) } } } }, + new[] + { + new Mv3Mesh + { + Name = "body", Attributes = new[] { new Mv3Attribute { MaterialId = 0 } }, + GameBoxTriangles = new[] { 0, 1, 2 }, NormalIndices = new[] { 0, 1, 2 }, NormalCount = 3, + Uvs = new[] { new GameBoxVector2(0, 0), new GameBoxVector2(0, 1), new GameBoxVector2(1, 0) }, + KeyFrames = new[] { new Mv3AnimationKeyFrame { GameBoxVertices = Vertices } } + } + }, new[] { new GameBoxMaterial { TextureFileNames = new[] { "opaque.tga" } } }); + + private static PolFile Weapon(GameBoxBlendFlag blend = GameBoxBlendFlag.Opaque, string texture = "opaque.tga") => new(1, + new[] { new PolGeometryNode { Name = "weapon" } }, + new[] + { + new PolMesh + { + VertexInfo = new PolVertexInfo + { + GameBoxPositions = Vertices, GameBoxNormals = new[] { new GameBoxVector3(0, 0, 1), new GameBoxVector3(0, 0, 1), new GameBoxVector3(0, 0, 1) }, + Uvs = new[] { new[] { new GameBoxVector2(0, 0), new GameBoxVector2(0, 1), new GameBoxVector2(1, 0) } } + }, + Textures = new[] { new PolTexture { BlendFlag = blend, Material = new GameBoxMaterial { TextureFileNames = new[] { texture } }, GameBoxTriangles = new[] { 0, 1, 2 } } } + } + }, Array.Empty()); + + [TestCase(false)] + [TestCase(true)] + public void ContinuousFadeKeepsMaterialsPooledAndWeaponOpacityAcrossRebuilds(bool toon) + { + var factory = new CountingFactory(); + using var manager = new GameMaterialManager(factory, toon); + using var textures = new Textures(); + var root = new GameObject("Opacity lifecycle"); + try + { + var renderer = root.AddComponent(); + renderer.SetOpacity(0.44f); + renderer.Init(Model(), manager, textures, tagNodePolFile: Weapon(), tagNodeTextureProvider: textures, + textureFactory: new UnityTextureFactory(), animateTagWater: false); + AssertFade(root, 0.44f, 2); + int allocated = factory.Materials.Count; + for (int cycle = 0; cycle < 4; cycle++) + { + for (int step = 0; step <= 50; step++) + renderer.SetOpacity(step / 50f); + renderer.SetOpacity(0.44f); + AssertFade(root, 0.44f, 2); + } + Assert.That(factory.Materials.Count, Is.EqualTo(allocated), "A fade must reuse its material pair."); + renderer.ChangeTexture("alpha.tga"); + AssertFade(root, 0.44f, 2); + renderer.ChangeTexture("opaque2.tga"); + AssertFade(root, 0.44f, 2); + renderer.Init(Model(), manager, textures, tagNodePolFile: Weapon(), tagNodeTextureProvider: textures, + textureFactory: new UnityTextureFactory(), animateTagWater: false); + AssertFade(root, 0.44f, 2); + renderer.SetOpacity(1f); + Assert.That(root.GetComponentsInChildren().All(mesh => mesh.sharedMaterials.Length == 1), Is.True); + renderer.Dispose(); + Assert.That(root.GetComponentsInChildren(), Is.Empty); + renderer.Dispose(); + manager.Dispose(); + Assert.That(factory.Materials.All(material => material.IsNativeObjectDisposed), Is.True); + } + finally { Object.DestroyImmediate(root); } + } + + [TestCase(false)] + [TestCase(true)] + public void AlphaTextureCutoutIsDisabledDuringFadeAndRestoredAtFullOpacity(bool toon) + { + using var manager = new GameMaterialManager(new UnityMaterialFactory(), toon); + using var textures = new Textures(); + var root = new GameObject("Alpha opacity"); + try + { + var renderer = root.AddComponent(); + renderer.Render(Weapon(GameBoxBlendFlag.AlphaBlend), textures, manager, false, + tintColor: new Color(0.5f, 0.6f, 0.7f, 0.8f), textureFactory: new UnityTextureFactory(), animateWater: false); + Material[] materials = root.GetComponentInChildren().sharedMaterials; + float[] thresholds = materials.Select(material => material.GetFloat("_Threshold")).ToArray(); + renderer.SetOpacity(0.44f); + Assert.That(materials.All(material => material.GetFloat("_Threshold") == 2f), Is.True); + Assert.That(materials.All(material => Math.Abs(material.GetColor("_TintColor").a - 0.352f) < 0.0001f), Is.True); + renderer.SetOpacity(1f); + Assert.That(materials.Select(material => material.GetFloat("_Threshold")), Is.EqualTo(thresholds)); + Assert.That(materials[0].GetColor("_TintColor").r, Is.EqualTo(0.5f)); + Assert.That(materials[0].GetColor("_TintColor").a, Is.EqualTo(0.8f)); + } + finally { Object.DestroyImmediate(root); } + } + + [TestCase(false)] + [TestCase(true)] + public void SelectionReleasesItsOwnPropertyBlockAndPreservesExistingLighting(bool existing) + { + using var manager = new GameMaterialManager(new UnityMaterialFactory(), true); + using var textures = new Textures(); + var root = new GameObject("Selection batching") { hideFlags = HideFlags.HideAndDontSave }; + try + { + var model = root.AddComponent(); + model.Init(Model(), manager, textures); + MeshRenderer renderer = root.GetComponentInChildren(); + if (existing) + { + var lighting = new MaterialPropertyBlock(); + lighting.SetFloat("_GbLightCount", 2); + renderer.SetPropertyBlock(lighting); + } + model.SetSelectionLuminance(-1); + Assert.That(renderer.HasPropertyBlock(), Is.EqualTo(existing)); + model.SetSelectionLuminance(.8f); + Assert.That(renderer.HasPropertyBlock(), Is.True); + model.SetOpacity(.44f); + model.SetSelectionLuminance(-1); + Assert.That(renderer.HasPropertyBlock(), Is.EqualTo(existing)); + var restored = new MaterialPropertyBlock(); + renderer.GetPropertyBlock(restored); + if (existing) + Assert.That(restored.GetFloat("_GbLightCount"), Is.EqualTo(2)); + model.Dispose(); + } + finally + { + Object.DestroyImmediate(root); + } + } + + [Test] + public void OpacityRejectsNonFiniteValuesAndClampsFiniteValues() + { + var root = new GameObject("Opacity bounds"); + try + { + var renderer = root.AddComponent(); + Assert.Throws(() => renderer.SetOpacity(float.NaN)); + Assert.Throws(() => renderer.SetOpacity(float.PositiveInfinity)); + Assert.DoesNotThrow(() => renderer.SetOpacity(-1f)); + Assert.DoesNotThrow(() => renderer.SetOpacity(2f)); + } + finally { Object.DestroyImmediate(root); } + } + + [TestCase(false)] + [TestCase(true)] + public void WaterFadeSurvivesPolRerenderAndReleasesItsGeometry(bool toon) + { + var factory = new CountingFactory(); + using var manager = new GameMaterialManager(factory, toon); + using var textures = new Textures(); + var root = new GameObject("Water opacity"); + try + { + var renderer = root.AddComponent(); + renderer.SetOpacity(0.44f); + for (int i = 0; i < 3; i++) + { + renderer.Render(Weapon(texture: "w0001.dds"), textures, manager, false, + textureFactory: new UnityTextureFactory(), animateWater: false); + Assert.That(root.GetComponentsInChildren(), Has.Length.EqualTo(1)); + Material material = root.GetComponentInChildren().sharedMaterial; + Assert.That(material.GetFloat("_Alpha"), Is.EqualTo(0.44f).Within(0.00001f)); + } + Assert.That(factory.Materials.Count, Is.EqualTo(5), "Re-render must reuse the returned water material."); + renderer.Dispose(); + Assert.That(root.transform.childCount, Is.Zero); + manager.Dispose(); + Assert.That(factory.Materials.All(material => material.IsNativeObjectDisposed), Is.True); + } + finally { Object.DestroyImmediate(root); } + } + + private static void AssertFade(GameObject root, float opacity, int count) + { + MeshRenderer[] renderers = root.GetComponentsInChildren(); + Assert.That(renderers, Has.Length.EqualTo(count)); + foreach (MeshRenderer renderer in renderers) + { + Assert.That(renderer.sharedMaterials, Has.Length.EqualTo(2)); + foreach (Material material in renderer.sharedMaterials) + { + Assert.That(material.GetColor("_TintColor").a, Is.EqualTo(opacity).Within(0.00001f)); + Assert.That(material.GetFloat("_Threshold"), Is.EqualTo(2f)); + } + } + } + + [TestCase(false)] + [TestCase(true)] + [Category("ResourceBrowserLocalData")] + public void RealActorAndWeaponFadeToBackgroundInBothMaterialStyles(bool toon) + { + string variant = ResourceBrowserWindow.Variant; + string dataRoot = Environment.GetEnvironmentVariable(variant + "_TEST_DATA_ROOT") ?? + Path.GetFullPath(Path.Combine(Application.dataPath, "../../Game Data", variant)); + if (!Directory.Exists(dataRoot)) + Assert.Ignore("Local game data is unavailable: " + dataRoot); + using var catalog = ResourceCatalog.Load(dataRoot, 936, variant); + var actorModel = catalog.Entries.Where(entry => entry.Extension == ".mv3") + .Select(entry => (entry, model: (Mv3File)ResourceFormats.Read(entry, catalog.Read(entry), catalog.Codepage))) + .First(value => value.model.TagNodes.Any(tag => !tag.Name.Equals("tag_weapon3", StringComparison.OrdinalIgnoreCase))); + ResourceEntry actor = actorModel.entry; + Mv3File model = actorModel.model; + ResourceEntry weaponEntry = catalog.Entries.First(entry => entry.Extension == ".pol" && entry.Path.IndexOf("weapon", StringComparison.OrdinalIgnoreCase) >= 0); + var weapon = (PolFile)ResourceFormats.Read(weaponEntry, catalog.Read(weaponEntry), catalog.Codepage); + using var preview = new ResourceModelPreview(catalog, toon); + GameObject target = preview.CreateObject("Opacity actor"); + Mv3ModelRenderer renderer = preview.SetVertexModel(target, actor.Path, model, weaponEntry.Path, weapon); + Assert.That(target.GetComponentsInChildren(), Is.Not.Empty, "The real tag hierarchy must include its weapon."); + TestContext.WriteLine(variant + ": actor=" + actor.Path + "; weapon=" + weaponEntry.Path + "; toon=" + toon); + preview.Frame(); + renderer.SetOpacity(1f); + UnityEngine.Color32[] opaque = Read(preview); + renderer.SetOpacity(0f); + UnityEngine.Color32[] background = Read(preview); + MeshRenderer[] meshes = target.GetComponentsInChildren(); + foreach (MeshRenderer mesh in meshes) + mesh.enabled = false; + UnityEngine.Color32[] empty = Read(preview); + Assert.That(background.Zip(empty, (a, b) => Math.Abs(a.r - b.r) + Math.Abs(a.g - b.g) + Math.Abs(a.b - b.b)).Sum(), + Is.LessThan(64), "Zero opacity must match the empty background."); + foreach (MeshRenderer mesh in meshes) + mesh.enabled = true; + renderer.SetOpacity(0.44f); + UnityEngine.Color32[] faded = Read(preview); + Material[] fadedMaterials = target.GetComponentsInChildren() + .SelectMany(mesh => mesh.sharedMaterials).ToArray(); + for (int step = 0; step < 204; step++) + renderer.SetOpacity(step % 51 / 50f); + renderer.SetOpacity(0.44f); + Assert.That(target.GetComponentsInChildren().SelectMany(mesh => mesh.sharedMaterials), + Is.EqualTo(fadedMaterials), "Continuous real-model fading must reuse the same materials."); + Assert.That(Read(preview), Is.EqualTo(faded), "Repeated fading must produce the same pixels."); + long Distance(UnityEngine.Color32[] pixels) => pixels.Zip(background, (a, b) => + (long)Math.Abs(a.r - b.r) + Math.Abs(a.g - b.g) + Math.Abs(a.b - b.b)).Sum(); + Assert.That(Distance(opaque), Is.GreaterThan(1000), actor.Path); + Assert.That(Distance(faded), Is.GreaterThan(100).And.LessThan(Distance(opaque)), actor.Path); + TestContext.WriteLine("opaqueDiff=" + Distance(opaque) + "; faded044Diff=" + Distance(faded)); + string output = Environment.GetEnvironmentVariable("PAL3_OPACITY_QA_ROOT"); + if (!string.IsNullOrEmpty(output)) + { + Directory.CreateDirectory(output); + foreach (var sample in new[] { ("opaque", opaque), ("invisible044", faded), ("zero", background) }) + { + var image = new Texture2D(256, 256, TextureFormat.RGBA32, false); + try + { + image.SetPixels32(sample.Item2); + image.Apply(); + File.WriteAllBytes(Path.Combine(output, variant + (toon ? "-toon-" : "-original-") + sample.Item1 + ".png"), image.EncodeToPNG()); + } + finally { Object.DestroyImmediate(image); } + } + } + } + + private static UnityEngine.Color32[] Read(ResourceModelPreview preview) + { + RenderTexture target = preview.Render(256, 256); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(256, 256, TextureFormat.RGBA32, false); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, 256, 256), 0, 0); + image.Apply(); + return image.GetPixels32(); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + } +} diff --git a/Assets/Tests/ResourceBrowser/Editor/ModelOpacityTests.cs.meta b/Assets/Tests/ResourceBrowser/Editor/ModelOpacityTests.cs.meta new file mode 100644 index 00000000..960a1e76 --- /dev/null +++ b/Assets/Tests/ResourceBrowser/Editor/ModelOpacityTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6baf69bb1606468a86796e6773963692 diff --git a/Assets/Tests/ResourceBrowser/Editor/NativeLightingTests.cs b/Assets/Tests/ResourceBrowser/Editor/NativeLightingTests.cs new file mode 100644 index 00000000..32b2ff95 --- /dev/null +++ b/Assets/Tests/ResourceBrowser/Editor/NativeLightingTests.cs @@ -0,0 +1,423 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.ResourceBrowser.Tests +{ + using System; + using System.IO; + using System.Linq; + using System.Reflection; + using Core.DataReader.Lgt; + using Core.DataReader.Mv3; + using Core.Primitives; + using Core.Utilities; + using Engine.Core.Abstraction; + using Engine.Core.Implementation; + using Game.Rendering; + using Game.Rendering.Material; + using Game.Rendering.Native; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + using Color = UnityEngine.Color; + using NativeColor = Core.Primitives.Color; + + public sealed class NativeLightingTests + { + private static LightNode Light(float strength, bool diffuse = true) => new() + { + LightColor = new NativeColor(strength, strength, strength), + UseDiffuse = diffuse, + GameBoxWorldMatrix = new GameBoxMatrix4x4 { Xx = 1, Yy = 1, Zz = 1, Tw = 1, Tz = -100000 }, + }; + + [TestCase(3, 1, 2)] + [TestCase(9, 4, 1)] + [TestCase(38, 19, 1)] + public void EquallyStrongLightsFollowReleasedPartitionAndShortSortOrder(int count, int first, int second) + { + var order = new int[count]; + GameBoxLightOrder.Sort(order, Enumerable.Repeat(.1f, count).ToArray()); + Assert.That(order.Take(2), Is.EqualTo(new[] { first, second })); + } + + [TestCase("Pal3/ToonOpaque")] + [TestCase("Pal3/ToonCutout")] + [TestCase("Pal3/ToonTransparent")] + [TestCase("Pal3/ToonWater")] + [TestCase("Pal3/Opaque")] + [TestCase("Pal3/Transparent")] + [TestCase("Pal3/TransparentOpaquePart")] + public void OriginalShadersRetainSrpBatcherCompatibility(string name) + { + // ShaderUtil's compatibility code needs both an active URP and compiled pass metadata. + using var preview = new ResourceModelPreview(null, false); + preview.Render(32, 32); + Shader shader = Shader.Find(name); + Assert.That(shader, Is.Not.Null); + const BindingFlags methods = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; + MethodInfo compilePass = typeof(UnityEditor.ShaderUtil).GetMethod("CompilePass", methods); + MethodInfo check = typeof(UnityEditor.ShaderUtil).GetMethod("GetSRPBatcherCompatibilityCode", methods); + Assert.That(compilePass, Is.Not.Null, "The installed Unity editor must expose synchronous pass compilation."); + Assert.That(check, Is.Not.Null, "The installed Unity editor must expose its shader compatibility inspection."); + var material = new Material(shader); + try + { + compilePass.Invoke(null, new object[] { material, 0, true }); + Assert.That((int)check.Invoke(null, new object[] { shader, 0 }), Is.Zero, name); + } + finally + { + Object.DestroyImmediate(material); + } + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void NativeSelectionRejectsZeroDiffuseAndExcludesLightmappedGeometry(string variant) + { + using var lighting = new GameBoxNativeLighting(variant); + lighting.SetLights(new LgtFile(new[] { Light(.1f), Light(.8f), Light(.3f), Light(1, false) })); + var root = new GameObject("Native light selection"); + var camera = new GameObject("Native light camera"); + try + { + var renderer = root.AddComponent(); + using IDisposable binding = lighting.Bind(renderer, Vector3.zero, false, false, false, 20); + lighting.Apply(camera.AddComponent()); + var block = new MaterialPropertyBlock(); + renderer.GetPropertyBlock(block); + Assert.That(block.GetFloat("_GbLightCount"), Is.EqualTo(2)); + Assert.That(block.GetVector("_GbLightDiffuse0").x, Is.EqualTo(.8f)); + Assert.That(block.GetVector("_GbLightDiffuse1").x, Is.EqualTo(.3f)); + binding.Dispose(); + using IDisposable mapped = lighting.Bind(renderer, Vector3.zero, true, false, true, 20); + lighting.Apply(camera.GetComponent()); + renderer.GetPropertyBlock(block); + Assert.That(block.GetFloat("_GbLightCount"), Is.Zero); + } + finally + { + Object.DestroyImmediate(root); + Object.DestroyImmediate(camera); + } + } + + [TestCase("PAL3", 1, .01f)] + [TestCase("PAL3A", 2, .8f)] + public void SceneAttachmentUsesThePublishedVariantOrder(string variant, int count, float first) + { + using var lighting = new GameBoxNativeLighting(variant); + lighting.SetLights(new LgtFile(new[] { Light(.8f), Light(.3f) })); + var root = new GameObject("Original scene attachment"); + var camera = new GameObject("Original scene camera"); + try + { + var renderer = root.AddComponent(); + using IDisposable binding = lighting.Bind(renderer, Vector3.zero, false, false, true, 20); + lighting.Apply(camera.AddComponent()); + var block = new MaterialPropertyBlock(); + renderer.GetPropertyBlock(block); + Assert.That(block.GetFloat("_GbLightCount"), Is.EqualTo(count)); + Assert.That(block.GetVector("_GbLightDiffuse0").x, Is.EqualTo(first)); + if (variant == "PAL3") + Assert.That(block.GetVector("_GbLightAmbient0").x, Is.EqualTo(-.25f)); + } + finally + { + Object.DestroyImmediate(root); + Object.DestroyImmediate(camera); + } + } + + [TestCase(false, 1)] + [TestCase(true, 0)] + public void Pal3AUsesFallbackOnlyForAMissingLightFile(bool exists, int expected) + { + using var lighting = new GameBoxNativeLighting("PAL3A"); + lighting.SetLights(exists ? new LgtFile(Array.Empty()) : null); + var root = new GameObject("Empty versus missing LGT"); + var camera = new GameObject("Empty-LGT camera"); + try + { + var renderer = root.AddComponent(); + using IDisposable binding = lighting.Bind(renderer, Vector3.zero, false, false, false, 20); + lighting.Apply(camera.AddComponent()); + var block = new MaterialPropertyBlock(); + renderer.GetPropertyBlock(block); + Assert.That(block.GetFloat("_GbLightCount"), Is.EqualTo(expected)); + } + finally + { + Object.DestroyImmediate(root); + Object.DestroyImmediate(camera); + } + } + + [Test] + public void NativeNormalsAccumulateAcrossMaterialAttributesAndUseOriginalQuantization() + { + Mv3Vert[] vertices = { new(), new() { X = 64 }, new() { Y = 64 }, new() { Z = 640 } }; + Mv3Attribute Part(params ushort[] indices) => new() + { + IndexBuffers = new[] { new Mv3IndexBuffer { TriangleIndex = indices } }, + }; + ushort[] actual = Mv3NativeNormals.Calculate(new[] { new Mv3VertFrame { Vertices = vertices } }, + new[] { Part(0, 1, 2), Part(0, 3, 1) })[0]; + // Released PAL3 ComputeNormal oracle, with a ten-times-larger second face. + Assert.That(actual, Is.EqualTo(new ushort[] { 16191, 16191, 0, 16255 })); + GameBoxVector3 a = Mv3NativeNormals.Decode(actual[0]); + GameBoxVector3 b = Mv3NativeNormals.Decode(actual[2]); + GameBoxVector3 blend = (a + b) * .5f; + Assert.That(GameBoxVector3.Magnitude(blend), Is.LessThan(.98f), "Morph normal interpolation must retain its length."); + } + + [Test] + public void AuthoredDirectionalLightRemainsACameraRelativePointWithMatrixScale() + { + using var lighting = new GameBoxNativeLighting("PAL3A"); + LightNode light = Light(1); + light.LightType = GameBoxLightType.Directional; + light.GameBoxWorldMatrix.Yy = 2; + light.GameBoxWorldMatrix.Ty = 12345; + lighting.SetLights(new LgtFile(new[] { light })); + var root = new GameObject("Scaled directional-light object"); + var camera = new GameObject("Directional-light camera"); + try + { + root.transform.position = new Vector3(10, 20, 30); + camera.transform.position = new Vector3(1, 2, 3); + var renderer = root.AddComponent(); + using IDisposable binding = lighting.Bind(renderer, Vector3.zero, false, false, false, 20); + var view = camera.AddComponent(); + lighting.Apply(view); + var block = new MaterialPropertyBlock(); + renderer.GetPropertyBlock(block); + Vector4 initial = block.GetVector("_GbLightPosition0"); + Assert.That(initial.x, Is.EqualTo(-180).Within(.01)); + Assert.That(initial.y, Is.EqualTo(199640).Within(.01)); + Assert.That(initial.z, Is.EqualTo(-540).Within(.01)); + camera.transform.position += new Vector3(3, 4, 5); + lighting.Apply(view); + renderer.GetPropertyBlock(block); + Vector4 moved = block.GetVector("_GbLightPosition0"); + Assert.That(moved - initial, Is.EqualTo(new Vector4(60, 80, 100, 0))); + } + finally + { + Object.DestroyImmediate(root); + Object.DestroyImmediate(camera); + } + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void OriginalShaderGpuUsesBothMaterialTermsAndBothSelectedLights(string variant) + { + LightNode first = Light(.2f); + first.LightColor = new NativeColor(.2f, .3f, .4f); + LightNode second = Light(.3f); + second.LightColor = new NativeColor(.4f, .3f, .2f); + Color actual = Draw(variant, new[] { first, second }, false, false); + AssertColor(actual, new Color(.38f, .48f, .58f, .8f)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void OriginalShaderGpuKeepsVertexColorsOutsideLighting(string variant) + { + Color actual = Draw(variant, new[] { Light(1) }, true, false); + AssertColor(actual, new Color(.25f, .5f, .75f, .6f)); + } + + [TestCase("PAL3")] + [TestCase("PAL3A")] + public void OriginalShaderGpuMultipliesBothLightmapTexturesAndNativeAlpha(string variant) + { + Color actual = Draw(variant, new[] { Light(1) }, false, true); + AssertColor(actual, new Color(.4f, .36f, .28f, .32f)); + } + + [Test] + public void OriginalShaderGpuUsesAmbientWhenNoDiffuseLightIsEligible() + { + AssertColor(Draw("PAL3A", new[] { Light(1, false) }, false, false), new Color(.04f, .06f, .08f, .8f)); + } + + [Test] + public void OriginalShaderGpuDoesNotCapVertexAttenuationAtSelectionLimit() + { + LightNode light = Light(.001f); + light.GameBoxWorldMatrix.Tz = -.2f; + light.LightDecayType = GameBoxLightDecayType.Distance; + light.DecayRadius = 40; + // A zero vertex-unit fixture gives every shader input the same native + // point while retaining a large, visible rasterized test surface. + AssertColor(Draw("PAL3A", new[] { light }, false, false, 0), new Color(.073333f, .1f, .126667f, .8f)); + } + + [Test] + public void OriginalLightmapAlphaAppliesObjectBlendBeforeTwoTimesSaturation() + { + AssertColor(Draw("PAL3A", new[] { Light(1) }, false, true, saturatedLightmap: true, opacity: .5f), + new Color(.4f, .36f, .28f, .8f)); + } + + [Test] + [Category("ResourceBrowserLocalData")] + public void RealDataOriginalLightingDrawsBothAdditionalMaterialGroupsAndNativeWeaponColors() + { + string variant = ResourceBrowserWindow.Variant; + string dataRoot = Environment.GetEnvironmentVariable(variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(dataRoot)) + Assert.Ignore("Local game data is unavailable."); + using var catalog = ResourceCatalog.OpenBaseData(dataRoot, 936); + string[] models = variant == "PAL3A" ? + new[] { "role\\101\\j21.mv3", "role\\526\\z1.mv3", "weapon\\WPB\\WPB.pol", "weapon\\JQN\\jqn.pol", "weapon\\WXA\\WXA.pol", "cbscene\\M15C\\m15c.pol" } : + new[] { "role\\101\\z01.mv3", "weapon\\JT13\\JT13.pol", "cbscene\\Z04A\\Z04A.pol" }; + ResourceEntry lightEntry = catalog.Entries.First(entry => entry.Extension == ".lgt" && entry.Path.IndexOf("cbscene", StringComparison.OrdinalIgnoreCase) >= 0); + foreach (string path in models) + { + ResourceEntry entry = catalog.Entries.Single(value => value.Path.EndsWith(path, StringComparison.OrdinalIgnoreCase)); + using var lighting = new GameBoxNativeLighting(variant); + lighting.SetLights((LgtFile)ResourceFormats.Read(lightEntry, catalog.Read(lightEntry), catalog.Codepage)); + using var preview = new ResourceModelPreview(catalog, false, lighting); + if (entry.Extension == ".pol") + { + preview.Load(entry, ResourceFormats.Read(entry, catalog.Read(entry), catalog.Codepage)); + if (path.StartsWith("cbscene", StringComparison.OrdinalIgnoreCase)) + preview.SetCamera(new Vector3(15, 18, 30), new Vector3(0, 2, 0), 50); + SaveRealCapture(preview, variant + "-" + path.Replace('\\', '-')); + continue; + } + byte[] bytes = catalog.Read(entry); + var plain = (Mv3File)ResourceFormats.Read(entry, bytes, catalog.Codepage); + var model = (Mv3File)ResourceFormats.Read(entry, bytes, catalog.Codepage, includeMv3NativeNormals: true); + Assert.That(plain.Meshes.SelectMany(mesh => mesh.KeyFrames).All(frame => frame.NativeNormals == null), Is.True); + Assert.That(model.Meshes.SelectMany(mesh => mesh.KeyFrames).All(frame => frame.NativeNormals?.Length == frame.GameBoxVertices.Length), Is.True); + Assert.That(plain.Meshes.Select(mesh => mesh.GameBoxTriangles), Is.EqualTo(model.Meshes.Select(mesh => mesh.GameBoxTriangles))); + GameObject target = preview.CreateObject("Real original-lit actor"); + var renderer = preview.SetVertexModel(target, entry.Path, model); + renderer.SampleAnimation((float)model.TotalGameBoxTicks / 4800 * .37f); + Assert.That(target.GetComponentsInChildren().Sum(filter => filter.sharedMesh.triangles.Length), + Is.EqualTo(model.Meshes.Sum(mesh => mesh.GameBoxTriangles.Length))); + if (path.EndsWith("j21.mv3", StringComparison.OrdinalIgnoreCase)) + Assert.That(model.Meshes.Sum(mesh => mesh.GameBoxTriangles.Length) / 3, Is.EqualTo(1470)); + if (path.Contains("526")) + Assert.That(model.Meshes.Sum(mesh => mesh.GameBoxTriangles.Length) / 3, Is.EqualTo(555)); + preview.Frame(); + SaveRealCapture(preview, variant + "-" + path.Replace('\\', '-')); + } + } + + private static void SaveRealCapture(ResourceModelPreview preview, string name) + { + RenderTexture rendered = preview.Render(512, 512); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(512, 512, TextureFormat.RGB24, false); + try + { + RenderTexture.active = rendered; + image.ReadPixels(new Rect(0, 0, 512, 512), 0, 0); + image.Apply(); + Assert.That(image.GetPixels32().Select(pixel => (pixel.r, pixel.g, pixel.b)).Distinct().Take(100).Count(), Is.GreaterThan(30)); + string output = Environment.GetEnvironmentVariable("PAL3_NATIVE_LIGHTING_QA_ROOT"); + if (!string.IsNullOrEmpty(output)) + { + Directory.CreateDirectory(output); + File.WriteAllBytes(Path.Combine(output, name + ".png"), image.EncodeToPNG()); + } + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + + [Test] + public void BakedNodeScalePreservesOriginalSourceSpaceLightingOnGpu() + { + LightNode light = Light(.8f); + light.GameBoxWorldMatrix.Tx = -20; + light.GameBoxWorldMatrix.Tz = -40; + Color original = Draw("PAL3A", new[] { light }, false, false); + Color baked = Draw("PAL3A", new[] { light }, false, false, bakedNodeScale: new Vector3(3, .5f, 2)); + AssertColor(baked, original); + } + + private static Color Draw(string variant, LightNode[] lights, bool vertexColor, bool lightmapped, + float vertexUnits = 20, bool saturatedLightmap = false, float opacity = 1, Vector3? bakedNodeScale = null) + { + using var lighting = new GameBoxNativeLighting(variant); + lighting.SetLights(new LgtFile(lights)); + using var manager = new GameMaterialManager(new UnityMaterialFactory(), false, lighting); + using var preview = new ResourceModelPreview(null, false, lighting); + var main = new Texture2D(1, 1, TextureFormat.RGBA32, false); + var map = new Texture2D(1, 1, TextureFormat.RGBA32, false); + var image = new Texture2D(1, 1, TextureFormat.RGBA32, false); + main.SetPixel(0, 0, lightmapped ? new Color(.5f, .6f, .7f, saturatedLightmap ? 1 : .8f) : Color.white); + map.SetPixel(0, 0, new Color(.4f, .3f, .2f, saturatedLightmap ? 1 : .25f)); + main.Apply(); + map.Apply(); + IMaterial[] materials = manager.CreateStandardMaterials(RendererType.Pol, + ("main", new UnityTexture2D(main)), lightmapped ? ("lightmap", new UnityTexture2D(map)) : default, + new NativeColor(1, 1, 1, opacity), GameBoxBlendFlag.Opaque, + new GameBoxMaterial { Diffuse = new NativeColor(.5f, .6f, .7f, .8f), Ambient = new NativeColor(.2f, .3f, .4f) }); + try + { + GameObject geometry = preview.CreateObject("Known native-light triangle"); + var mesh = new Mesh + { + vertices = new[] { new Vector3(-1, -1), new Vector3(1, -1), new Vector3(1, 1), new Vector3(-1, 1) }, + triangles = new[] { 0, 2, 1, 0, 3, 2 }, + normals = new[] { Vector3.back, Vector3.back, Vector3.back, Vector3.back }, + uv = new[] { Vector2.zero, Vector2.right, Vector2.one, Vector2.up }, + uv2 = new[] { Vector2.zero, Vector2.right, Vector2.one, Vector2.up }, + colors = new[] { new Color(.25f, .5f, .75f, .6f), new Color(.25f, .5f, .75f, .6f), new Color(.25f, .5f, .75f, .6f), new Color(.25f, .5f, .75f, .6f) }, + }; + geometry.AddComponent().sharedMesh = mesh; + var renderer = geometry.AddComponent(); + renderer.sharedMaterial = materials[0].NativeObject as Material; + Matrix4x4 sourceToRenderer = Matrix4x4.Scale(bakedNodeScale ?? Vector3.one); + if (bakedNodeScale.HasValue) + { + mesh.vertices = mesh.vertices.Select(sourceToRenderer.MultiplyPoint3x4).ToArray(); + Vector3 scale = bakedNodeScale.Value; + geometry.transform.localScale = new Vector3(1 / scale.x, 1 / scale.y, 1 / scale.z); + } + using IDisposable binding = lighting.Bind(renderer, Vector3.zero, lightmapped, vertexColor, false, vertexUnits, + bakedNodeScale.HasValue ? () => sourceToRenderer : null); + preview.SetCamera(new Vector3(0, 0, -5), Vector3.zero, 40); + RenderTexture rendered = preview.Render(128, 128); + RenderTexture previous = RenderTexture.active; + try + { + RenderTexture.active = rendered; + image.ReadPixels(new Rect(64, 64, 1, 1), 0, 0); + image.Apply(); + Assert.That(SystemInfo.graphicsDeviceType, Is.Not.EqualTo(UnityEngine.Rendering.GraphicsDeviceType.Null)); + return image.GetPixel(0, 0); + } + finally { RenderTexture.active = previous; } + } + finally + { + manager.ReturnToPool(materials); + Object.DestroyImmediate(main); + Object.DestroyImmediate(map); + Object.DestroyImmediate(image); + } + } + + private static void AssertColor(Color actual, Color expected) + { + Assert.That(actual.r, Is.EqualTo(expected.r).Within(.015f)); + Assert.That(actual.g, Is.EqualTo(expected.g).Within(.015f)); + Assert.That(actual.b, Is.EqualTo(expected.b).Within(.015f)); + Assert.That(actual.a, Is.EqualTo(expected.a).Within(.015f)); + } + } +} diff --git a/Assets/Tests/ResourceBrowser/Editor/NativeLightingTests.cs.meta b/Assets/Tests/ResourceBrowser/Editor/NativeLightingTests.cs.meta new file mode 100644 index 00000000..1cdfe273 --- /dev/null +++ b/Assets/Tests/ResourceBrowser/Editor/NativeLightingTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 6fb8d961909f47248e590cefb782f867 diff --git a/Assets/Tests/ResourceBrowser/Editor/NativeModelEffectTests.cs b/Assets/Tests/ResourceBrowser/Editor/NativeModelEffectTests.cs new file mode 100644 index 00000000..13901fef --- /dev/null +++ b/Assets/Tests/ResourceBrowser/Editor/NativeModelEffectTests.cs @@ -0,0 +1,323 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.ResourceBrowser.Tests +{ + using System; + using System.IO; + using System.Linq; + using Core.DataReader; + using Core.DataReader.Cvd; + using Core.DataReader.Data; + using Core.DataReader.Lgt; + using Core.DataReader.Pol; + using Core.Primitives; + using Engine.Core.Abstraction; + using Engine.Core.Implementation; + using Engine.Extensions; + using Game.Effect.Runtime; + using Game.Rendering.Material; + using Game.Rendering.Native; + using Game.Rendering.Renderer; + using NUnit.Framework; + using UnityEngine; + using Object = UnityEngine.Object; + + public sealed class NativeModelEffectTests + { + private sealed class WhiteTextures : ITextureResourceProvider + { + public string GetTexturePath(string name) => name; + + public ITexture2D GetTexture(string name) => GetTexture(name, out _); + + public ITexture2D GetTexture(string name, out bool hasAlphaChannel) + { + hasAlphaChannel = false; + return new UnityTexture2D(Texture2D.whiteTexture); + } + } + + private static PolFile ColoredPol(string texture, bool unreferencedVertex = false) + { + GameBoxVector3[] positions = unreferencedVertex ? + new[] { new GameBoxVector3(-20, -20, 0), new GameBoxVector3(20, -20, 0), new GameBoxVector3(20, 20, 0), new GameBoxVector3(-20, 20, 0), new GameBoxVector3(100, 80, 40) } : + new[] { new GameBoxVector3(-20, -20, 0), new GameBoxVector3(20, -20, 0), new GameBoxVector3(20, 20, 0), new GameBoxVector3(-20, 20, 0) }; + return new PolFile(1, new[] { new PolGeometryNode { Name = "Authored quad" } }, + new[] + { + new PolMesh + { + VertexFvfFlag = GameBoxVertexType.XYZ | GameBoxVertexType.Diffuse | GameBoxVertexType.UV0, + VertexInfo = new PolVertexInfo + { + GameBoxPositions = positions, + DiffuseColors = Enumerable.Repeat(new Core.Primitives.Color32(64, 128, 192, 128), positions.Length).ToArray(), + Uvs = new[] { new GameBoxVector2[positions.Length] }, + }, + Textures = new[] + { + new PolTexture + { + BlendFlag = GameBoxBlendFlag.AlphaBlend, + Material = new GameBoxMaterial { TextureFileNames = new[] { texture } }, + GameBoxTriangles = new[] { 0, 2, 1, 0, 3, 2 }, + }, + }, + }, + }, Array.Empty()); + } + + [Test] + public void AuthoredPolKeepsBlendAndCompleteSourceBoundsWithoutWaterSubstitution() + { + using var manager = new GameMaterialManager(new UnityMaterialFactory(), false); + var root = new GameObject("Authored model policy"); + try + { + PolFile model = ColoredPol("w0001.dds", true); + var renderer = root.AddComponent(); + renderer.Render(model, new WhiteTextures(), manager, false, textureFactory: new UnityTextureFactory(), animateWater: false, + modelMode: PolModelMode.Authored); + Material[] materials = root.GetComponentInChildren().sharedMaterials; + Assert.That(materials.Select(material => material.shader.name), Is.EqualTo(new[] { "Pal3/TransparentOpaquePart", "Pal3/Transparent" })); + Mesh mesh = root.GetComponentInChildren().sharedMesh; + Assert.That(mesh.vertexCount, Is.EqualTo(4), "Unused geometry can be omitted without shrinking the authored selection/framing volume."); + var sourceBounds = new Bounds(model.Meshes[0].VertexInfo.GameBoxPositions[0].ToUnityPosition(), Vector3.zero); + foreach (GameBoxVector3 position in model.Meshes[0].VertexInfo.GameBoxPositions) + sourceBounds.Encapsulate(position.ToUnityPosition()); + Assert.That(mesh.bounds, Is.EqualTo(sourceBounds)); + PolMesh source = model.Meshes[0]; + PolTexture section = source.Textures[0]; + section.Material.TextureFileNames = new[] { "white.tga", "" }; + source.Textures[0] = section; + model.Meshes[0] = source; + renderer.Render(model, new WhiteTextures(), manager, false, textureFactory: new UnityTextureFactory(), animateWater: false, + modelMode: PolModelMode.Authored); + Assert.That(root.GetComponentInChildren().sharedMaterial.GetFloat("_HasShadowTex"), Is.Zero, + "An empty second texture slot must preserve the model's single-texture material."); + model = ColoredPol("w0001.dds", true); + renderer.Render(model, new WhiteTextures(), manager, false, textureFactory: new UnityTextureFactory(), animateWater: false); + Assert.That(root.GetComponentInChildren().sharedMaterial.shader.name, Is.EqualTo("Pal3/Water"), + "The default game's water convention must remain intact."); + } + finally { Object.DestroyImmediate(root); } + } + + [Test] + public void AuthoredPolVertexRgbaAndFadeMatchAUniformColorOnGpuWithoutSceneLights() + { + using var manager = new GameMaterialManager(new UnityMaterialFactory(), false); + using var preview = new ResourceModelPreview(null, false); + var renderer = preview.CreateObject("Authored colors").AddComponent(); + renderer.Render(ColoredPol("white.tga"), new WhiteTextures(), manager, false, textureFactory: new UnityTextureFactory(), animateWater: false, + modelMode: PolModelMode.Authored); + preview.SetCamera(new Vector3(0, 0, -5), Vector3.zero, 40); + MeshRenderer meshRenderer = renderer.GetComponentInChildren(); + Material[] materials = meshRenderer.sharedMaterials; + meshRenderer.enabled = false; + UnityEngine.Color background = Center(preview); + meshRenderer.enabled = true; + var reference = new Material(Shader.Find("Pal3/Transparent")) { mainTexture = Texture2D.whiteTexture }; + reference.SetFloat("_Threshold", 2); + var properties = new MaterialPropertyBlock(); + try + { + foreach (float opacity in new[] { 1f, .5f }) + { + meshRenderer.sharedMaterials = materials; + renderer.SetOpacity(opacity); + meshRenderer.GetPropertyBlock(properties); + Assert.That(properties.GetFloat("_GbVertexColor"), Is.EqualTo(1)); + Assert.That(meshRenderer.sharedMaterial.GetFloat("_GbNativeLighting"), Is.Zero); + UnityEngine.Color actual = Center(preview); + properties.SetFloat("_GbVertexColor", 0); + meshRenderer.SetPropertyBlock(properties); + reference.SetColor("_TintColor", new UnityEngine.Color(64f / 255, 128f / 255, 192f / 255, 128f / 255 * opacity)); + meshRenderer.sharedMaterials = new[] { reference }; + UnityEngine.Color expected = Center(preview); + Assert.That(Math.Abs(expected.r - background.r) + Math.Abs(expected.g - background.g) + Math.Abs(expected.b - background.b), + Is.GreaterThan(.05f), "The GPU comparison must contain visible geometry."); + Assert.That(actual.r, Is.EqualTo(expected.r).Within(.015f)); + Assert.That(actual.g, Is.EqualTo(expected.g).Within(.015f)); + Assert.That(actual.b, Is.EqualTo(expected.b).Within(.015f)); + Assert.That(actual.a, Is.EqualTo(expected.a).Within(.015f)); + properties.SetFloat("_GbVertexColor", 1); + meshRenderer.SetPropertyBlock(properties); + } + } + finally + { + meshRenderer.sharedMaterials = materials; + Object.DestroyImmediate(reference); + renderer.Dispose(); + } + } + + private static UnityEngine.Color Center(ResourceModelPreview preview) + { + RenderTexture target = preview.Render(64, 64); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(1, 1, TextureFormat.RGBA32, false); + try + { + RenderTexture.active = target; + image.ReadPixels(new Rect(32, 32, 1, 1), 0, 0); + image.Apply(); + return image.GetPixel(0, 0); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + } + + [Test] + public void NativeCvdKeepsAuthoredCurrentFrameNormalsAndMaterialTerms() + { + CvdVertex[] Frame(GameBoxVector3 normal) => new[] + { + new CvdVertex { GameBoxPosition = new GameBoxVector3(-20, 0, -20), GameBoxNormal = normal }, + new CvdVertex { GameBoxPosition = new GameBoxVector3(20, 0, -20), GameBoxNormal = normal }, + new CvdVertex { GameBoxPosition = new GameBoxVector3(0, 0, 20), GameBoxNormal = normal }, + }; + var source = new GameBoxMaterial + { + Diffuse = new Core.Primitives.Color(.4f, .5f, .6f, .7f), + Ambient = new Core.Primitives.Color(.1f, .2f, .3f), + TextureFileNames = new[] { "white.tga" }, + }; + var node = new CvdGeometryNode + { + IsGeometryNode = true, + Scale = 1, + Children = Array.Empty(), + PositionKeyInfos = new[] { new CvdAnimationPositionKeyFrame { KeyType = CvdAnimationKeyType.Linear } }, + RotationKeyInfos = new[] { new CvdAnimationRotationKeyFrame { KeyType = CvdAnimationKeyType.Linear, GameBoxRotation = new GameBoxQuaternion(0, 0, 0, 1) } }, + ScaleKeyInfos = new[] { new CvdAnimationScaleKeyFrame { KeyType = CvdAnimationKeyType.Linear, GameBoxScale = new GameBoxVector3(3, 2, .5f), GameBoxRotation = new GameBoxQuaternion(0, 0, 0, 1) } }, + Mesh = new CvdMesh + { + AnimationTimeKeys = new[] { 0f, 1f }, + MeshSections = new[] + { + new CvdMeshSection + { + FrameVertices = new[] { Frame(new GameBoxVector3(0, 1, 0)), Frame(new GameBoxVector3(1, 0, 0)) }, + GameBoxTriangles = new[] { 0, 1, 2 }, Material = source, + }, + }, + }, + }; + using var lighting = new GameBoxNativeLighting("PAL3A"); + using var manager = new GameMaterialManager(new UnityMaterialFactory(), false, lighting); + var root = new GameObject("Native CVD regression"); + try + { + var renderer = root.AddComponent(); + renderer.Init(new CvdFile(1, new[] { node }), new WhiteTextures(), manager); + renderer.SetCurrentTime(.5f); + Mesh mesh = root.GetComponentInChildren().sharedMesh; + Assert.That(mesh.normals, Is.EqualTo(Enumerable.Repeat(Vector3.back, 3).ToArray()), "The native IPOL draw does not interpolate authored normals."); + Material material = root.GetComponentInChildren().sharedMaterial; + Assert.That(material.GetFloat("_GbNativeLighting"), Is.EqualTo(1)); + Assert.That(material.GetColor("_GbMaterialDiffuse").a, Is.EqualTo(.7f)); + renderer.SetCurrentTime(1); + Assert.That(mesh.normals, Is.EqualTo(Enumerable.Repeat(Vector3.left, 3).ToArray())); + var animation = renderer.PlayAnimationAsync(1, 1, 1, true); + Assert.That(animation.MoveNext(), Is.True); + var sourceField = typeof(CvdModelRenderer).GetField("_animationCts", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + var cancellation = (System.Threading.CancellationTokenSource)sourceField.GetValue(renderer); + renderer.Dispose(); + Assert.That(root.transform.childCount, Is.Zero); + Assert.That(mesh == null, Is.True); + Assert.Throws(() => cancellation.Token.ToString()); + Assert.That(sourceField.GetValue(renderer), Is.Null); + var cache = (System.Collections.IDictionary)typeof(CvdModelRenderer).GetField("_textureCache", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(renderer); + Assert.That(cache.Count, Is.Zero); + renderer.Dispose(); + renderer.Init(new CvdFile(1, new[] { node }), new WhiteTextures(), manager); + Assert.That(root.transform.childCount, Is.EqualTo(1)); + renderer.Dispose(); + Assert.That(root.transform.childCount, Is.Zero); + } + finally { Object.DestroyImmediate(root); } + } + + [TestCase("POL", false)] + [TestCase("POL", true)] + [TestCase("CVD", true)] + [Category("ResourceBrowserLocalData")] + public void ActualModelEffectsRetainAuthoredVertexDataWithOptionalSceneLighting(string kind, bool native) + { + string variant = ResourceBrowserWindow.Variant; + string dataRoot = Environment.GetEnvironmentVariable(variant + "_TEST_DATA_ROOT"); + if (!Directory.Exists(dataRoot)) + Assert.Ignore("Local game data is unavailable."); + using var catalog = ResourceCatalog.OpenBaseData(dataRoot, 936); + using var resources = new EffectResources(catalog.FileSystem, 936); + using var lighting = native ? new GameBoxNativeLighting(variant) : null; + ResourceEntry lightEntry = catalog.Entries.First(entry => entry.Extension == ".lgt" && entry.Path.IndexOf("cbscene", StringComparison.OrdinalIgnoreCase) >= 0); + lighting?.SetLights((LgtFile)ResourceFormats.Read(lightEntry, catalog.Read(lightEntry), 936)); + using var preview = new ResourceModelPreview(catalog, false, lighting); + EffectDefinition definition = resources.Definitions.EffectDefinitions.First(value => value.IsValid && + EffectClass.Name(value.ClassNameCrc) == "model" && value.TextureName.EndsWith("." + kind, StringComparison.OrdinalIgnoreCase)); + resources.Definitions.Groups[0] = new EffectGroup + { + Objects = new[] + { + new EffectGroupObject { TypeCrc = definition.TypeNameCrc, Tasks = new[] { new EffectTask { IsValid = true, StartTime = -1, Duration = 10, SpeedAlpha = -.5f } } }, + }, + }; + var player = preview.CreateObject("Actual model effect").AddComponent(); + player.AutoAdvance = false; + player.Initialize(resources, 0, nativeLighting: preview.NativeLighting); + Assert.That(player.Error, Is.Null, definition.TextureName); + preview.Rendering += player.Render; + player.AdvanceFrame(.02f); + preview.Render(64, 64); + MeshRenderer[] renderers = preview.Root.GetComponentsInChildren(); + Assert.That(renderers, Is.Not.Empty, definition.TextureName); + Assert.That(renderers.SelectMany(renderer => renderer.sharedMaterials).All(material => material.GetFloat("_GbNativeLighting") == (native ? 1 : 0)), Is.True); + if (kind == "POL") + { + PolFile model = resources.PolModel(definition.TextureName); + if (model.Meshes.Any(mesh => (mesh.VertexFvfFlag & GameBoxVertexType.Diffuse) != 0)) + { + Assert.That(preview.Root.GetComponentsInChildren().All(filter => filter.sharedMesh.colors32.Length == filter.sharedMesh.vertexCount), Is.True, + "The real model effect's vertex colors must reach its mesh."); + var block = new MaterialPropertyBlock(); + foreach (MeshRenderer meshRenderer in renderers) + { + meshRenderer.GetPropertyBlock(block); + Assert.That(block.GetFloat("_GbVertexColor"), Is.EqualTo(1), "The model fade must preserve its vertex-color property."); + } + } + } + else + Assert.That(preview.Root.GetComponentsInChildren().All(filter => filter.sharedMesh.normals.Length == filter.sharedMesh.vertexCount), Is.True); + preview.Frame(); + RenderTexture rendered = preview.Render(128, 128); + RenderTexture previous = RenderTexture.active; + var image = new Texture2D(128, 128, TextureFormat.RGBA32, false); + try + { + RenderTexture.active = rendered; + image.ReadPixels(new Rect(0, 0, 128, 128), 0, 0); + image.Apply(); + Assert.That(image.GetPixels32().Select(pixel => (pixel.r, pixel.g, pixel.b)).Distinct().Take(20).Count(), Is.GreaterThan(10), definition.TextureName); + string output = Environment.GetEnvironmentVariable("PAL3_NATIVE_LIGHTING_QA_ROOT"); + if (!string.IsNullOrEmpty(output)) + File.WriteAllBytes(Path.Combine(output, variant + "-effect-" + kind + (native ? "" : "-standalone") + ".png"), image.EncodeToPNG()); + } + finally + { + RenderTexture.active = previous; + Object.DestroyImmediate(image); + } + Assert.That(player.Error, Is.Null); + } + } +} diff --git a/Assets/Tests/ResourceBrowser/Editor/NativeModelEffectTests.cs.meta b/Assets/Tests/ResourceBrowser/Editor/NativeModelEffectTests.cs.meta new file mode 100644 index 00000000..f88a478e --- /dev/null +++ b/Assets/Tests/ResourceBrowser/Editor/NativeModelEffectTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 0ac8e847d0554b2d9dc79e82a69452ca diff --git a/Assets/Tests/ResourceBrowser/Editor/Pal3.ResourceBrowser.Tests.asmdef b/Assets/Tests/ResourceBrowser/Editor/Pal3.ResourceBrowser.Tests.asmdef index 3def2507..e72f20fd 100644 --- a/Assets/Tests/ResourceBrowser/Editor/Pal3.ResourceBrowser.Tests.asmdef +++ b/Assets/Tests/ResourceBrowser/Editor/Pal3.ResourceBrowser.Tests.asmdef @@ -1,6 +1,6 @@ { "name": "Pal3.ResourceBrowser.Tests", - "references": ["Pal3.ResourceBrowser.Editor", "Pal3.Core", "Pal3.Game", "Engine"], + "references": ["Pal3.Editor.TestSupport", "Pal3.ResourceBrowser.Editor", "Pal3.Core", "Pal3.Game", "Engine"], "includePlatforms": ["Editor"], "optionalUnityReferences": ["TestAssemblies"], "autoReferenced": false, diff --git a/Assets/Tests/ResourceBrowser/Editor/ResourceCatalogTests.cs b/Assets/Tests/ResourceBrowser/Editor/ResourceCatalogTests.cs index c8c17469..96b38782 100644 --- a/Assets/Tests/ResourceBrowser/Editor/ResourceCatalogTests.cs +++ b/Assets/Tests/ResourceBrowser/Editor/ResourceCatalogTests.cs @@ -32,6 +32,67 @@ namespace Pal3.ResourceBrowser.Tests Assert.Throws(() => ResourceCatalog.ExportPath(Application.dataPath, path)); } + [Test] + public void ReportExportAllowsReplacingReportsOutsideTheOriginalDirectory() + { + string output = ReportTestDirectory(); + string source = Path.Combine(output, "original"); + Directory.CreateDirectory(source); + string original = Path.Combine(source, "data.json"); + string report = Path.Combine(output, "report.json"); + File.WriteAllText(original, "original"); + try + { + ResourceCatalog.WriteTextFile(report, "first", source); + ResourceCatalog.WriteTextFile(report, "replacement", source); + Assert.That(File.ReadAllText(report), Is.EqualTo("replacement")); + Assert.Throws(() => ResourceCatalog.WriteTextFile(original, "changed", source)); + Assert.That(File.ReadAllText(original), Is.EqualTo("original")); + } + finally { Directory.Delete(output, true); } + } + + [TestCase("directory")] + [TestCase("file")] + [TestCase("dangling-file")] + public void ReportExportRejectsSymbolicLinksWithoutChangingOriginalData(string kind) + { + if (Application.platform != RuntimePlatform.OSXEditor && Application.platform != RuntimePlatform.LinuxEditor) + Assert.Ignore("Symlink regression uses the Unix ln utility."); + string output = ReportTestDirectory(); + string source = Path.Combine(output, "original"); + Directory.CreateDirectory(source); + string original = Path.Combine(source, "data.json"); + string missing = Path.Combine(source, "missing.json"); + File.WriteAllText(original, "original"); + string alias = Path.Combine(output, "alias"); + var start = new System.Diagnostics.ProcessStartInfo("/bin/ln") { UseShellExecute = false }; + start.ArgumentList.Add("-s"); + start.ArgumentList.Add(kind == "directory" ? source : kind == "file" ? original : missing); + start.ArgumentList.Add(alias); + try + { + using var process = System.Diagnostics.Process.Start(start); + process.WaitForExit(); + Assert.That(process.ExitCode, Is.Zero); + string destination = kind == "directory" ? Path.Combine(alias, "data.json") : alias; + Assert.Throws(() => ResourceCatalog.WriteTextFile(destination, "changed", source)); + Assert.That(File.ReadAllText(original), Is.EqualTo("original")); + Assert.That(File.Exists(missing), Is.False); + } + finally + { + if (kind == "directory") + Directory.Delete(alias); + else + File.Delete(alias); + Directory.Delete(output, true); + } + } + + private static string ReportTestDirectory() => Path.GetFullPath(Path.Combine(Application.dataPath, + "../../workspace/ResourceBrowserQA/report-export", Guid.NewGuid().ToString("N"))); + [Test] public void ImageHeadersAreCheckedBeforeUnsafeTgaDecoding() { diff --git a/Assets/Tests/ResourceBrowser/Editor/ResourceMediaTests.cs b/Assets/Tests/ResourceBrowser/Editor/ResourceMediaTests.cs index 635c8428..698a9eb9 100644 --- a/Assets/Tests/ResourceBrowser/Editor/ResourceMediaTests.cs +++ b/Assets/Tests/ResourceBrowser/Editor/ResourceMediaTests.cs @@ -80,6 +80,8 @@ namespace Pal3.ResourceBrowser.Tests Assert.That(preview.Error, Is.Null, entry.Path); Assert.That(preview.Ready, Is.True); var video = preview.Video; + for (ushort track = 0; track < Math.Min(video.audioTrackCount, video.controlledAudioTrackCount); track++) + video.SetDirectAudioMute(track, true); video.Play(); Assert.That(preview.Tick(), Is.True, "Playing video must repaint."); deadline = EditorApplication.timeSinceStartup + 10; diff --git a/Assets/Tests/ResourceBrowser/Editor/ResourceWindowLifecycleTests.cs b/Assets/Tests/ResourceBrowser/Editor/ResourceWindowLifecycleTests.cs index 2699a4c8..e711d8a1 100644 --- a/Assets/Tests/ResourceBrowser/Editor/ResourceWindowLifecycleTests.cs +++ b/Assets/Tests/ResourceBrowser/Editor/ResourceWindowLifecycleTests.cs @@ -11,8 +11,10 @@ namespace Pal3.ResourceBrowser.Tests using System.IO; using System.Linq; using System.Reflection; + using System.Threading; using System.Threading.Tasks; using NUnit.Framework; + using Pal3.Tests.EditorSupport; using UnityEditor; using UnityEngine; using UnityEngine.TestTools; @@ -23,18 +25,166 @@ namespace Pal3.ResourceBrowser.Tests private const string WindowName = "ResourceBrowserReloadTest"; private const BindingFlags Private = BindingFlags.Instance | BindingFlags.NonPublic; - private sealed class KeyboardFocusProbe : EditorWindow - { - public ResourceBrowserWindow Browser; - public bool FocusList, InputFocused, ListFocused; - public bool DrawList, ExitedGui, ScrollClosedAtExit, ListFocusedAtExit; - public Vector2 MousePosition; - private string _text = "Input"; + private const string EnvironmentKey = WindowName + ".Environment"; - private void OnGUI() + [SetUp] + public void IsolateLifecyclePreferences() + { + // SessionState survives the real reload; instance/static fixture fields do not. + if (SessionState.GetBool(EnvironmentKey, false)) + return; + string pathKey = ResourceBrowserWindow.Variant + ".ResourceBrowser.Path"; + string codepageKey = ResourceBrowserWindow.Variant + ".ResourceBrowser.Codepage"; + string directory = Path.GetFullPath(Path.Combine(Application.dataPath, "../../workspace/ResourceBrowserQA/lifecycle", Guid.NewGuid().ToString("N"))); + Directory.CreateDirectory(directory); + SessionState.SetBool(EnvironmentKey + ".HadPath", EditorPrefs.HasKey(pathKey)); + SessionState.SetString(EnvironmentKey + ".Path", EditorPrefs.GetString(pathKey)); + SessionState.SetBool(EnvironmentKey + ".HadCodepage", EditorPrefs.HasKey(codepageKey)); + SessionState.SetInt(EnvironmentKey + ".Codepage", EditorPrefs.GetInt(codepageKey)); + SessionState.SetString(EnvironmentKey + ".Directory", directory); + SessionState.SetBool(EnvironmentKey, true); + // A missing source is deliberate: draft persistence does not require + // indexing the user's real data or starting a background scan. + EditorPrefs.SetString(pathKey, Path.Combine(directory, "unavailable-source")); + EditorPrefs.SetInt(codepageKey, 936); + } + + [TearDown] + public void RestoreLifecycleEnvironment() + { + string draftId = SessionState.GetString(WindowName + ".DraftId", ""); + try + { + foreach (ResourceBrowserWindow window in Resources.FindObjectsOfTypeAll().Where(value => value.name == WindowName)) + { + window.DiscardChanges(); + Object.DestroyImmediate(window); + } + } + finally + { + try + { + // Recover an orphan too if the reference itself was lost by a regression. + foreach (ResourceTextDraft draft in Resources.FindObjectsOfTypeAll().Where(value => value.GetEntityId().ToString() == draftId)) + { + Undo.ClearUndo(draft); + Object.DestroyImmediate(draft); + } + } + finally + { + try + { + RestorePreferencesAndDirectory(); + } + finally + { + ClearReloadState(); + } + } + } + } + + private static void RestorePreferencesAndDirectory() + { + if (!SessionState.GetBool(EnvironmentKey, false)) + return; + string pathKey = ResourceBrowserWindow.Variant + ".ResourceBrowser.Path"; + string codepageKey = ResourceBrowserWindow.Variant + ".ResourceBrowser.Codepage"; + if (SessionState.GetBool(EnvironmentKey + ".HadPath", false)) + EditorPrefs.SetString(pathKey, SessionState.GetString(EnvironmentKey + ".Path", "")); + else + EditorPrefs.DeleteKey(pathKey); + if (SessionState.GetBool(EnvironmentKey + ".HadCodepage", false)) + EditorPrefs.SetInt(codepageKey, SessionState.GetInt(EnvironmentKey + ".Codepage", 936)); + else + EditorPrefs.DeleteKey(codepageKey); + string directory = SessionState.GetString(EnvironmentKey + ".Directory", ""); + if (Directory.Exists(directory)) + Directory.Delete(directory, true); + } + + private static void ClearReloadState() + { + SessionState.EraseBool(WindowName); + SessionState.EraseString(WindowName + ".WindowId"); + SessionState.EraseString(WindowName + ".DraftId"); + SessionState.EraseBool(EnvironmentKey); + SessionState.EraseBool(EnvironmentKey + ".HadPath"); + SessionState.EraseString(EnvironmentKey + ".Path"); + SessionState.EraseBool(EnvironmentKey + ".HadCodepage"); + SessionState.EraseInt(EnvironmentKey + ".Codepage"); + SessionState.EraseString(EnvironmentKey + ".Directory"); + } + + [Test] + public void DetachedTextEditingStateIsPrivateToEachPanel() + { + bool original = EditorGUIUtility.editingTextField; + bool editingOnReturn = false, otherEditing = true; + var size = new Vector2(200, 100); + using var first = new OffscreenGui(() => + { + if (Event.current.type == EventType.Repaint) + { + editingOnReturn = EditorGUIUtility.editingTextField; + EditorGUIUtility.editingTextField = true; + } + }); + using var second = new OffscreenGui(() => otherEditing = EditorGUIUtility.editingTextField); + first.Paint(size); + Assert.That(EditorGUIUtility.editingTextField, Is.EqualTo(original)); + second.Paint(size); + Assert.That(otherEditing, Is.False); + first.Paint(size); + Assert.That(editingOnReturn, Is.True); + Assert.That(EditorGUIUtility.editingTextField, Is.EqualTo(original)); + } + + [Test] + public void DetachedPointerCaptureStaysWithItsPanelAndReleasesOnMouseUp() + { + int original = GUIUtility.hotControl; + int firstControl = 0, secondControl = -1; + var size = new Vector2(200, 100); + using var first = new OffscreenGui(() => + { + int control = GUIUtility.GetControlID(FocusType.Passive); + if (Event.current.type == EventType.MouseDown) + GUIUtility.hotControl = control; + firstControl = GUIUtility.hotControl; + }); + using var second = new OffscreenGui(() => secondControl = GUIUtility.hotControl); + first.SendEvent(new Event { type = EventType.MouseDown }, size); + Assert.That(firstControl, Is.Not.Zero); + Assert.That(GUIUtility.hotControl, Is.EqualTo(original)); + second.Paint(size); + Assert.That(secondControl, Is.Zero); + first.Paint(size); + Assert.That(firstControl, Is.Not.Zero); + first.SendEvent(new Event { type = EventType.MouseUp }, size); + first.Paint(size); + Assert.That(firstControl, Is.Zero); + Assert.That(GUIUtility.hotControl, Is.EqualTo(original)); + } + + private sealed class KeyboardFocusProbe + { + private readonly ResourceBrowserWindow _window; + private readonly bool _drawList; + private string _text = "Input"; + public bool FocusList, InputFocused, ListFocused; + public bool ExitedGui, ScrollClosedAtExit, ListFocusedAtExit; + + public KeyboardFocusProbe(ResourceBrowserWindow window, bool drawList = false) + { + _window = window; + _drawList = drawList; + } + + public void Draw() { - if (Event.current.type == EventType.MouseMove) - MousePosition = Event.current.mousePosition; int listControl = GUIUtility.GetControlID(FocusType.Keyboard); if (FocusList) { @@ -44,9 +194,9 @@ namespace Pal3.ResourceBrowser.Tests Vector2 origin = GUIUtility.GUIToScreenPoint(Vector2.zero); try { - typeof(ResourceBrowserWindow).GetMethod("HandleListKeys", Private).Invoke(Browser, new object[] { listControl }); - if (DrawList) - typeof(ResourceBrowserWindow).GetMethod("DrawList", Private).Invoke(Browser, new object[] { new Rect(0, 60, 240, 180), listControl }); + typeof(ResourceBrowserWindow).GetMethod("HandleListKeys", Private).Invoke(_window, new object[] { listControl }); + if (_drawList) + typeof(ResourceBrowserWindow).GetMethod("DrawList", Private).Invoke(_window, new object[] { new Rect(0, 60, 240, 180), listControl }); } catch (TargetInvocationException ex) when (ex.InnerException is ExitGUIException) { @@ -55,22 +205,28 @@ namespace Pal3.ResourceBrowser.Tests ListFocusedAtExit = GUIUtility.keyboardControl == listControl; throw ex.InnerException; } - GUI.SetNextControlName("TestInput"); - _text = EditorGUILayout.TextField(_text); - InputFocused = GUI.GetNameOfFocusedControl() == "TestInput"; + if (!_drawList) + { + GUI.SetNextControlName("TestInput"); + _text = EditorGUILayout.TextField(_text); + InputFocused = GUI.GetNameOfFocusedControl() == "TestInput"; + } ListFocused = GUIUtility.keyboardControl == listControl; } } - [UnityTest] - public IEnumerator MouseAndKeyboardSelectionExitTheCurrentGuiPass() + [Test] + [Category("OffscreenGraphics")] + public void MouseAndKeyboardSelectionExitTheCurrentGuiPass() { string output = Path.GetFullPath(Path.Combine(Application.dataPath, "../../workspace/ResourceBrowserQA/test-output", Guid.NewGuid().ToString("N"))); Directory.CreateDirectory(output); var window = ScriptableObject.CreateInstance(); - var probe = ScriptableObject.CreateInstance(); try { + var probe = new KeyboardFocusProbe(window, drawList: true); + using var gui = new OffscreenGui(probe.Draw); + Vector2 canvasSize = new(320, 280); typeof(ResourceBrowserWindow).GetMethod("CancelScan", Private).Invoke(window, null); var catalog = (ResourceCatalog)Activator.CreateInstance(typeof(ResourceCatalog), Private, null, new object[] { output, 936 }, null); typeof(ResourceBrowserWindow).GetField("_catalog", Private).SetValue(window, catalog); @@ -81,72 +237,68 @@ namespace Pal3.ResourceBrowser.Tests File.WriteAllText(text.PhysicalPath, "Selected text"); entries.Add(binary); entries.Add(text); - probe.Browser = window; - probe.DrawList = true; - probe.wantsMouseMove = true; - probe.Show(); - probe.Focus(); - yield return null; foreach (bool mouse in new[] { true, false }) { typeof(ResourceBrowserWindow).GetMethod("Select", Private).Invoke(window, new object[] { binary }); probe.FocusList = true; - probe.SendEvent(new Event { type = EventType.Repaint }); + gui.Paint(canvasSize); probe.ExitedGui = false; var click = new Vector2(20, 108); - probe.SendEvent(new Event { type = EventType.MouseMove, mousePosition = click }); - // SendEvent uses host-view coordinates; account for the window's tab offset. - click += click - probe.MousePosition; - probe.SendEvent(mouse - ? new Event { type = EventType.MouseDown, button = 0, mousePosition = click } - : new Event { type = EventType.KeyDown, keyCode = KeyCode.DownArrow }); + try + { + gui.SendEvent(mouse + ? new Event { type = EventType.MouseDown, button = 0, mousePosition = click } + : new Event { type = EventType.KeyDown, keyCode = KeyCode.DownArrow }, canvasSize); + } + finally + { + if (mouse) + gui.SendEvent(new Event { type = EventType.MouseUp, button = 0, mousePosition = click }, canvasSize); + } Assert.That(probe.ExitedGui, Is.True, mouse ? "Mouse selection" : "Keyboard selection"); Assert.That(probe.ScrollClosedAtExit, Is.True, "The scroll view must close before selection exits OnGUI."); Assert.That(probe.ListFocusedAtExit, Is.True, "Selection must preserve list keyboard focus."); Assert.That(typeof(ResourceBrowserWindow).GetField("_selected", Private).GetValue(window), Is.SameAs(text), mouse ? "Mouse selection" : "Keyboard selection"); var draft = (ResourceTextDraft)typeof(ResourceBrowserWindow).GetField("_textDraft", Private).GetValue(window); Assert.That(draft.Text, Is.EqualTo("Selected text")); - probe.SendEvent(new Event { type = EventType.Repaint }); + gui.Paint(canvasSize); } } finally { - probe.Close(); window.DiscardChanges(); Object.DestroyImmediate(window); Directory.Delete(output, true); } } - [UnityTest] - public IEnumerator ListNavigationDoesNotConsumeArrowsAfterKeyboardFocusMovesToAnInput() + [Test] + [Category("OffscreenGraphics")] + public void ListNavigationDoesNotConsumeArrowsAfterKeyboardFocusMovesToAnInput() { var window = ScriptableObject.CreateInstance(); - var probe = ScriptableObject.CreateInstance(); try { + var probe = new KeyboardFocusProbe(window); + using var gui = new OffscreenGui(probe.Draw); + Vector2 canvasSize = new(320, 280); typeof(ResourceBrowserWindow).GetMethod("CancelScan", Private).Invoke(window, null); var entries = (List)typeof(ResourceBrowserWindow).GetField("_visible", Private).GetValue(window); entries.Add(new ResourceEntry("first.txt")); entries.Add(new ResourceEntry("second.txt")); FieldInfo selection = typeof(ResourceBrowserWindow).GetField("_selected", Private); selection.SetValue(window, entries[0]); - probe.Browser = window; - probe.Show(); - probe.Focus(); - yield return null; probe.FocusList = true; - probe.SendEvent(new Event { type = EventType.Repaint }); + gui.Paint(canvasSize); Assert.That(probe.ListFocused, Is.True); - probe.SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.Tab, character = '\t' }); - probe.SendEvent(new Event { type = EventType.Repaint }); + gui.SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.Tab, character = '\t' }, canvasSize); + gui.Paint(canvasSize); Assert.That(probe.InputFocused, Is.True, "Tab must transfer the list's keyboard focus to the input."); - probe.SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.DownArrow }); + gui.SendEvent(new Event { type = EventType.KeyDown, keyCode = KeyCode.DownArrow }, canvasSize); Assert.That(selection.GetValue(window), Is.SameAs(entries[0])); } finally { - probe.Close(); Object.DestroyImmediate(window); } } @@ -219,17 +371,54 @@ namespace Pal3.ResourceBrowser.Tests } } + [Test] + public void DestroyingTheDiscardedWindowCancelsExportsAndReleasesItsDraft() + { + var window = ScriptableObject.CreateInstance(); + window.name = WindowName; + try + { + var export = new CancellationTokenSource(); + CancellationToken exportToken = export.Token; + typeof(ResourceBrowserWindow).GetField("_exportCancellation", Private).SetValue(window, export); + var draft = ScriptableObject.CreateInstance(); + draft.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave; + draft.SourceRoot = EditorPrefs.GetString(ResourceBrowserWindow.Variant + ".ResourceBrowser.Path"); + draft.SourcePath = "close-test.txt"; + draft.Load(System.Text.Encoding.UTF8.GetBytes("original"), 65001); + draft.Text = "edited text"; + typeof(ResourceBrowserWindow).GetField("_textDraft", Private).SetValue(window, draft); + typeof(ResourceBrowserWindow).GetMethod("UpdateTextDirty", Private).Invoke(window, null); + Assert.That(window.hasUnsavedChanges, Is.True); + window.DiscardChanges(); + Assert.That(window.hasUnsavedChanges, Is.False); + Assert.That(draft.Text, Is.EqualTo("original")); + Object.DestroyImmediate(window); + Assert.That(window == null, Is.True); + Assert.That(exportToken.IsCancellationRequested, Is.True, "OnDisable must cancel pending exports."); + Assert.That(draft == null, Is.True); + } + finally + { + if (window != null) + { + window.DiscardChanges(); + Object.DestroyImmediate(window); + } + } + } + [UnityTest] - public IEnumerator UnsavedTextSurvivesRealAssemblyReloadAndClosesCleanlyAfterDiscard() + public IEnumerator UnsavedTextSurvivesRealAssemblyReloadAndDiscardsCleanly() { if (!SessionState.GetBool(WindowName, false)) { var window = ScriptableObject.CreateInstance(); window.name = WindowName; - window.Show(); + // Keep this state-persistence test detached from desktop input. var draft = ScriptableObject.CreateInstance(); draft.hideFlags = HideFlags.HideInHierarchy | HideFlags.DontSave; - draft.SourceRoot = System.IO.Path.GetFullPath(System.IO.Path.Combine(Application.dataPath, "../../Game Data", ResourceBrowserWindow.Variant)); + draft.SourceRoot = EditorPrefs.GetString(ResourceBrowserWindow.Variant + ".ResourceBrowser.Path"); draft.SourcePath = "reload-test.txt"; draft.Load(System.Text.Encoding.UTF8.GetBytes("original"), 65001); draft.Text = "unsaved text after reload"; @@ -237,35 +426,32 @@ namespace Pal3.ResourceBrowser.Tests serialized.FindProperty("_textDraft").objectReferenceValue = draft; serialized.ApplyModifiedPropertiesWithoutUndo(); typeof(ResourceBrowserWindow).GetMethod("UpdateTextDirty", Private).Invoke(window, null); + SessionState.SetString(WindowName + ".WindowId", window.GetEntityId().ToString()); + SessionState.SetString(WindowName + ".DraftId", draft.GetEntityId().ToString()); SessionState.SetBool(WindowName, true); EditorUtility.RequestScriptReload(); } yield return new WaitForDomainReload(); ResourceBrowserWindow restored = Resources.FindObjectsOfTypeAll().Single(w => w.name == WindowName); - try - { - using var serialized = new SerializedObject(restored); - var draft = (ResourceTextDraft)serialized.FindProperty("_textDraft").objectReferenceValue; - Assert.That(draft, Is.Not.Null); - Assert.That(draft.Text, Is.EqualTo("unsaved text after reload")); - Assert.That(draft.IsDirty, Is.True); - Assert.That(restored.hasUnsavedChanges, Is.True); - var selected = (ResourceEntry)typeof(ResourceBrowserWindow).GetField("_selected", Private).GetValue(restored); - Assert.That(selected.Path, Is.EqualTo(draft.SourcePath)); - restored.DiscardChanges(); - Assert.That(restored.hasUnsavedChanges, Is.False); - restored.Close(); - Assert.That(draft == null, Is.True); - } - finally - { - SessionState.EraseBool(WindowName); - if (restored != null) - { - restored.DiscardChanges(); - restored.Close(); - } - } + using var restoredObject = new SerializedObject(restored); + var restoredDraft = (ResourceTextDraft)restoredObject.FindProperty("_textDraft").objectReferenceValue; + Assert.That(restoredDraft, Is.Not.Null); + Assert.That(restored.GetEntityId().ToString(), Is.EqualTo(SessionState.GetString(WindowName + ".WindowId", "")), "The original native window must survive, not be recreated."); + Assert.That(restoredDraft.GetEntityId().ToString(), Is.EqualTo(SessionState.GetString(WindowName + ".DraftId", "")), "The original native draft must survive, not be reconstructed from the source file."); + Assert.That(typeof(EditorWindow).GetField("m_Parent", Private).GetValue(restored), Is.Null, "Persistence must not attach a desktop GUI host."); + Assert.That(typeof(ResourceBrowserWindow).GetField("_scan", Private).GetValue(restored), Is.Null, "No background index of user data should be started."); + Assert.That(restoredDraft.Text, Is.EqualTo("unsaved text after reload")); + Assert.That(restoredDraft.IsDirty, Is.True); + Assert.That(restored.hasUnsavedChanges, Is.True); + var selected = (ResourceEntry)typeof(ResourceBrowserWindow).GetField("_selected", Private).GetValue(restored); + Assert.That(selected.Path, Is.EqualTo(restoredDraft.SourcePath)); + restored.DiscardChanges(); + Assert.That(restored.hasUnsavedChanges, Is.False); + // EditorWindow.Close requires a GUI parent in this Unity version. + Object.DestroyImmediate(restored); + Assert.That(restored == null, Is.True); + Assert.That(restoredDraft == null, Is.True); + // TearDown owns recovery even if the framework aborts at the yield. } } } diff --git a/README.en-US.md b/README.en-US.md index b7d10b78..aaf692e0 100644 --- a/README.en-US.md +++ b/README.en-US.md @@ -57,6 +57,24 @@ Open the project with the Unity version specified in [ProjectVersion.txt](Projec ``` To extract the original videos, open `Resource Browser`, index the original installation directory, search `ext:bik`, and choose `Original → Export filtered…`. Archive entries larger than 64 MiB require individual confirmation with `Export original…`. The archive directory structure is preserved. +## Battle Editor + +Open `PAL3 / PAL3A → Battle Editor` to test battles in an independent editor +window, without entering Play Mode or loading the story. Select the game data +directory in the canvas, then choose `创建随机战斗` (create a random battle) and +`开始测试` (start test). Playback starts immediately; the toolbar provides pause, +resume and restart controls. Use `Switch Variant` to change games. + +Configure the battlefield, party, enemies, formations, equipment, skills, statuses +and battle inventory. Save presets as `BattleScenarioAsset` assets; editable drafts +remain separate from running snapshots. Both games support original battle rules +and presentation, manual or AI control, settlement, stepping, input replay and JSON +reports. Results do not update story progress or the regular inventory. + +The [battle core](Assets/Scripts/Pal3.Battle/README.md) documents the C# rules +and presenter. The [editor composition guide](Assets/Scripts/Editor/BattleEditor/README.md) +covers the Unity adapter and resource ownership. + ## Editor resource browser Open the dockable window through `PAL3 / PAL3A → Resource Browser`. Choose the data directory containing `basedata/`, select GBK (936) or Big5 (950), and click `Index / Reload`. Use `Switch Variant` to change games. @@ -84,13 +102,13 @@ The version switching is implemented through [Custom scripting symbols](https:// ![PAL3 卡通渲染+光追](Screenshots/PAL3_ToonShading_RayTracing.png?raw=true) ## About VFX and Toon Rendering -Both games default to the original visual style in URP, preserving the original textures, baked lighting, and transparency. Choose **Toon with real-time lighting** under the visual style option in game settings and restart to apply it. Both styles use shaders from this repository and load game data from the player’s local installation. +Both games default to **Toon with real-time lighting** on first launch. To switch to the original visual style in URP, change the visual style in game settings and restart. Both styles use shaders from this repository and load game data from the player’s local installation. The visual effects settings provide independent switches for contact shadows, character lighting, enhanced night fire lighting, and fire shadows. Contact shadows and fire shadows default to enabled on desktop devices. Enhanced fire lighting combines warm lights with a cool ambient tone. Fire shadows also work in dark maze scenes. Desktop defaults to four shadowed fires. Set `Settings.ToonFireShadowBudget` to 0–4 in the debug console. The shadow atlas grows with the budget. Bloom has a separate switch and defaults to enabled only for the original style on desktop. The screenshots above show the previous toon renderer. Supported story and scene effects in both games use the original data: effect groups, tasks, particles, textures, and models loaded from local CPK archives, rendered with this project's URP shaders and Unity components. Open `PAL3 / PAL3A → Effect Editor` in Unity to select a game, play effects, inspect objects, and edit group tasks and legacy particle curves. Save overrides to `Assets/Resources/Effects/PAL3Overrides.asset` or `PAL3AOverrides.asset` for use in the game. The resource browser links effect resources to Effect Editor. Group ID `-1` supports transport points in both games. -The current inventory covers all 56 PAL3 and 93 PAL3A story and scene root groups using original data. Transport points reproduce the original disc, two light cones, and colors selected by scene parameters. SPar keyframes, paths, six controller slots, and material blending are implemented independently; raw SPar fields are read-only in the editor. Unsupported types such as battle directors produce diagnostics and will be added alongside their related systems. +The current inventory covers all 56 PAL3 and 93 PAL3A story and scene root groups using original data. Transport points reproduce the original disc, two light cones, and colors selected by scene parameters. SPar keyframes, paths, six controller slots, and material blending are implemented independently; raw SPar fields are read-only in the editor. Battle-specific types receive context from the independent battle session; missing resources and unsupported inputs produce diagnostics. All implementation code, shaders, and build resources are included in this repository. The game reads the player's local original game data at runtime; that data is not distributed with this project. @@ -100,9 +118,35 @@ All implementation code, shaders, and build resources are included in this repos - Touchscreen: Only enabled on handheld devices with a touch screen, virtual joystick for movement, interaction button for interaction. ## Project State and Roadmap -The story parts of The Legend of Sword and Fairy 3 and The Legend of Sword and Fairy 3 Gaiden: Wenqing Pian are complete. Both games can be played entirely from start to finish to experience the story, and the story selection menu provided in the game can be used to jump to different story points in the game. Most of the switches and puzzles in the mazes in both games have also been implemented, but combat, mini-games, and various systems and features related to supporting the combat system have not been implemented or realized. In addition, the main menu and most of the UI/UX need to be redesigned and implemented as well. +The stories of both games are complete and can be played from start to finish; +the story selection menu also provides shortcuts to preset story points. Most +maze puzzles and story effects have been implemented. The independent Battle +Editor provides battle configuration, execution, original rules and presentation, +and replay testing for both games. Story-triggered battles, the regular inventory, +full equipment management and progress/save writeback still need integration. +Further work on mini-games, the main menu, other interfaces and mobile adaptation +is planned separately. ## How to Contribute? +After changing owned C# sources, use the .NET SDK pinned in `global.json` and run +these commands from the project root: + +```sh +dotnet run --project tools/CodeStyle -- +dotnet run --project tools/CodeStyle -- --check +``` + +The formatter is a .NET tool and needs no Python, Unity installation or game data. +It uses Roslyn, `.editorconfig` and pinned StyleCop layout rules for whitespace, +separate statements and blank lines between members. It checks both PAL3 and +PAL3A conditional branches. By default, it formats changed lines and deletion +boundaries, preserving existing formatting elsewhere; explicit paths or `--all` +check whole files. The `Code style` workflow runs `dotnet test tools/CodeStyle.Tests` +and the same formatting check for pull requests. See the +[tool README](tools/CodeStyle/README.md) for commands and scope. Run the relevant +Unity tests after formatting; ShaderLab/HLSL still needs manual formatting and +rendering validation. + Since the project is still in the early stages, many systems have not yet been implemented, thus I am temporarily not accepting large Pull Requests, especially feature ones. If you have good ideas, suggestions, or have discovered bugs, please feel free to submit an issue. ## Why make this [TL;DR] diff --git a/README.md b/README.md index f52be541..8eb681ef 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,28 @@ CI 仅在 Pull Request 上运行;以下徽章显示各工作流最近一次 PR ffmpeg -i input.mp4 -c:v libvpx -b:v 3M -c:a libvorbis output.webm // vp8 + vorbis ``` +## 战斗编辑器 + +菜单 `PAL3 / PAL3A → Battle Editor` 打开独立窗口,无需进入 Play Mode 或载入剧情。在画布中央选择数据目录,然后点击“创建随机战斗 → 开始测试”。开始测试后即播放,顶部主操作随状态变为暂停、继续或重新测试。切换作品使用现有 `Switch Variant`。 + +随机示例随机选择战场、最多 4 位不同队友及 1–6 位同等级敌人。队友等级比敌方高 3 级(最高 100 级),按各自等级计算成长和装备属性并补满精气神。随机示例和新增队友默认开放各自的全部特技、仙术,熟练度为 4,方便测试;精气神消耗、装备、变身等使用条件继续生效,载入已有预设时保留其技能配置。战斗音乐留空时按原版剧情场景映射自动选择;共享战场缺少唯一剧情来源时使用有诊断说明的编辑器默认曲目,可填写原始曲号覆盖,或填 `NONE` 静音。音乐在 1×播放时输出,暂停、步进及倍速保持静音。 + +可配置场景、阵位、模型、等级、装备、技能、状态及局内物品/金钱/蛊。属性可选显式有效值、基础值加装备,或原版等级成长;当前精气神按最终派生上限校验。预设保存为 `BattleScenarioAsset`,支持 Undo/Redo;编辑草稿与运行快照隔离。右侧“编辑配置”按场景、队伍、物品分组,高级字段折叠收纳;修改、撤销或还原草稿会暂停当前测试,点击“应用并重新开始”建立新快照。文件菜单提供新建、打开、保存、另存与诊断导出;随机创建作为未命名新配置,不覆盖已打开的预设。 + +独立实战覆盖两槽时间条、普攻行列范围、五灵、仙术/特技/物品、装备被动、异常状态、阵法与援护、合击、魔剑技、尸块和专用角色/Boss 机制;外传包含摄灵五灵轮、两种变身及累计损失选项。局内结算包含经验、升级、法术解锁、熟练度、金钱及物品,并配有结果演出。双方可手动操作或使用按发布程序实现的 AI;日志保留请求值、实际变化及随机轨迹。支持暂停、倍速、逻辑单步、下一命中/行动结束、输入重放和 JSON 报告,结果不写回剧情进度或正式背包。 + +新配置默认使用“实时光照 + Toon”,也可在“编辑配置 → 场景 → 音乐、渲染与相机”切换为“原版光影”。原版保留烘焙光影、顶点色及原版角色光照,不创建 Unity 实时灯;Toon 使用实时方向光。普通预览按显示器实际像素密度渲染;启用原版镜头拖影时保留其原生 256×256 缓冲,可关闭拖影检查清晰画面。 + +“诊断工具”集中单步、重放、动作预览、原始资源表、日志与画布设置。受击数字默认保留已核实的原版蓝色 `#3232FF`,画布设置可改为黄色或白色;恢复、气、神及 MISS 颜色保持原版。 + +战斗视图使用原版界面资源,按横屏布局适配 21:9、4:3、2:1、1:1 和安全区,并提供可选的 4:3 预览;“触屏操作”沿用同一套原生界面,适度放大菜单、支持列表滚动/点选与触控命中。目标直接在场景中选择:鼠标悬停时身体闪动并显示原版头顶指针,单击生效;触屏轻触一次即可对有效目标施放,点到无效目标或空白处会回到上一层。AI 与援护也直接点选角色,触屏第一次轻触预览,再点同一角色确认。AI 页先编辑草稿,确认按原版计算时间条成本,取消保留当前设置;调试指令面板独立保留。 + +Battle Editor 的战斗界面支持手柄左摇杆/方向键八向命令盘、A 确认、B 返回、LB/RB 切换分类或额外控件/AI 角色、X 回到普攻焦点(援护页清除援护)、Y 重复、Start 开始/暂停/恢复;结果页也可确认继续。方向盘保留原版九宫位置,魔剑、五灵轮与变身等独立控件通过肩键访问。键盘使用方向键/WASD、Q/E/Z/C 斜向、Enter 确认、Esc 返回、Tab 切换、F/R 普攻/重复。鼠标、键盘、手柄及触屏共用语义输入;原生 Editor 输入流有虚拟手柄回归,实体硬件另行验收。 + +当前采用 20ms 参考步长,按本地两作发布程序核实数值、随机顺序与身体/特效/相机/音频行为;无效快照、缺失资源和不可直接施放的原始描述记录会显示诊断。纯 C# 战斗领域及界面 Presenter 分别独立于 Unity,窗口缩放和投影不参与战斗结算。验证分为无图形逻辑/数据、后台 GPU 离屏、真实桌面 UI 三层;默认后台检查不创建测试窗口,桌面焦点/IMGUI 像素检查需单独执行。最新验证范围与未执行项目见工作区 `docs/battle-system-validation.md`;实体设备与完整原版逐帧视听一致性仍需单独验收。 + +纯 C# 内核见 [Battle core](Assets/Scripts/Pal3.Battle/README.md),Unity 编辑器适配与所有权边界见 [Battle Editor composition](Assets/Scripts/Editor/BattleEditor/README.md)。 + ## 编辑器资源浏览 菜单 `PAL3 / PAL3A → Resource Browser` 打开可停靠的原生编辑器窗口。选择直接包含 `basedata/` 的数据目录与 936(简体)或 950(繁体)编码,再点击 `Index / Reload`。切换作品使用 `Switch Variant`。 @@ -83,13 +105,13 @@ CI 仅在 Pull Request 上运行;以下徽章显示各工作流最近一次 PR ![PAL3 卡通渲染+光追](Screenshots/PAL3_ToonShading_RayTracing.png?raw=true) ## 关于特效和卡通渲染 -两作都默认使用 URP 原版画风,保留原作贴图、烘焙光照和透明混合。可在「游戏设置 → 画风」选择「卡通与实时光影」,重启后生效。两档都使用仓库内的 shader,运行时从玩家本地读取原版游戏资源。 +两作首次运行时默认使用「卡通与实时光影」。可在「游戏设置 → 画风」切换为 URP 原版画风,重启后生效。两档都使用仓库内的 shader,运行时从玩家本地读取原版游戏资源。 「游戏设置 → 画面与特效设置」提供接触阴影、角色光照、增强夜景火光和火光投影四个独立开关,在卡通画风中即时生效。接触阴影和火光投影在桌面设备默认开启,手持设备可按需开启。夜景火光使用暖色灯光与冷色环境底色。火光投影也适用于暗色迷宫,桌面默认四盏,控制台可通过 `Settings.ToonFireShadowBudget` 设置 0–4 盏,阴影图集随预算扩容。泛光可以独立开关,默认仅桌面原版画风开启。 上方截图来自旧版卡通渲染。两作已支持的剧情与场景特效由原版数据驱动,运行时读取本地 CPK 的特效组、任务、粒子、贴图和模型,使用自有 URP shader 与 Unity 原生渲染组件。Unity 菜单 `PAL3 / PAL3A → Effect Editor` 可选择作品、播放、检查对象、修改组任务和旧粒子曲线;覆盖资产分别保存到 `Assets/Resources/Effects/PAL3Overrides.asset` 或 `PAL3AOverrides.asset` 后供游戏读取。资源浏览器的特效视图可直接打开 Effect Editor;组 ID `-1` 支持 PAL3/PAL3A 两作传送点。 -PAL3 已覆盖当前清单中的 56 个剧情/场景根组,PAL3A 已覆盖 93 个,均由原版数据驱动。传送点按原版圆盘、双光锥及场景参数配色播放。SPar 关键帧、路径、六槽控制器和材质混合独立实现,原始 SPar 字段在编辑器中只读。尚未实现的战斗导演等类型会给出诊断,留待对应系统开发时补齐。 +PAL3 已覆盖当前清单中的 56 个剧情/场景根组,PAL3A 已覆盖 93 个,均由原版数据驱动。传送点按原版圆盘、双光锥及场景参数配色播放。SPar 关键帧、路径、六槽控制器和材质混合独立实现,原始 SPar 字段在编辑器中只读。战斗专用类型由独立战斗会话提供上下文;缺失资源或不支持的输入会给出诊断。 实现所需的代码、Shader 和构建资源均随本仓库提供。运行时读取玩家本地的原版游戏数据;原版数据不随项目分发。 @@ -99,17 +121,17 @@ PAL3 已覆盖当前清单中的 56 个剧情/场景根组,PAL3A 已覆盖 9 - 触屏:仅在有触摸屏的手持设备上才会启用,虚拟摇杆控制行走,交互键互动。 ## 项目进度以及路线图 -仙剑奇侠传三以及仙剑奇侠传三外传的剧情部分已经全部完成,两部游戏都可以完整的从头玩到尾体验一遍剧情,也可以使用游戏内提供的剧情选择菜单跳转至预设好的剧情时间点。两部游戏中的迷宫机关也基本全部实现,剧情中出现的大部分特效也已经重新实现。但是战斗,小游戏以及围绕支持战斗系统的各类系统和功能均尚未完成。另外主菜单和大部分界面也需要重新设计和实现(毕竟现在还要做手机端的适配)。 +仙剑奇侠传三以及仙剑奇侠传三外传的剧情部分已经全部完成,两部游戏都可以完整的从头玩到尾体验一遍剧情,也可以使用游戏内提供的剧情选择菜单跳转至预设好的剧情时间点。两部游戏中的迷宫机关也基本全部实现,剧情中出现的大部分特效也已经重新实现。独立 Battle Editor 已提供两作战斗的配置、运行、原版规则与表现及回放测试入口;剧情中的正式接战、背包、完整装备管理和进度写回仍待接入。小游戏、主菜单及其他界面的后续实现与移动端适配另行推进。 ## 如何贡献? 修改自有 C# 代码后,使用 `global.json` 指定的 .NET SDK,在工程根目录执行: ```sh -python3 tools/format-csharp.py -python3 tools/format-csharp.py --check +dotnet run --project tools/CodeStyle -- +dotnet run --project tools/CodeStyle -- --check ``` -工具使用 SDK 自带的 `dotnet format`、`.editorconfig` 和固定版本的 StyleCop 布局规则,检查空格、缩进、函数/成员间空行及多条语句分行。默认只应用改动行及删除边界上的格式修正,保留其他行的既有格式;显式路径或 `--all` 可检查整个文件。工具分别检查 PAL3/PAL3A 条件分支,不需要 Unity 或游戏数据;StyleCop 仅用于开发工具,不进入 Unity 工程。PR 的 `Code style` 工作流执行相同检查。格式检查通过后仍需运行相关 Unity 测试;ShaderLab/HLSL 由人工整理并验证。 +格式工具以纯 .NET 实现,无需 Python、Unity 或游戏数据。它使用 Roslyn、`.editorconfig` 和固定版本的 StyleCop 布局规则,检查空格、缩进、函数/成员间空行及多条语句分行。默认只应用改动行及删除边界上的格式修正,保留其他行的既有格式;显式路径或 `--all` 可检查整个文件。工具分别检查 PAL3/PAL3A 条件分支;StyleCop 仅用于开发工具,不进入 Unity 工程。PR 的 `Code style` 工作流先运行 `dotnet test tools/CodeStyle.Tests`,再执行相同格式检查。更多命令见[工具说明](tools/CodeStyle/README.md)。格式检查通过后仍需运行相关 Unity 测试;ShaderLab/HLSL 由人工整理并验证。 因为项目还处于早期实现过程中,很多系统还没有实现,暂时不接受比较大的Pull request,特别是feature类型,如果您有好的想法,意见或者发现了Bug请欢迎提交issue或者加入交流群与我讨论。 另外您还可以参考这个项目解析视频:https://www.bilibili.com/video/BV1Pr4y167sF diff --git a/tools/Battle.Tests/Domain/Pal3.Battle.csproj b/tools/Battle.Tests/Domain/Pal3.Battle.csproj new file mode 100644 index 00000000..d48af618 --- /dev/null +++ b/tools/Battle.Tests/Domain/Pal3.Battle.csproj @@ -0,0 +1,10 @@ + + + net10.0 + false + + + + + diff --git a/tools/Battle.Tests/Pal3.Battle.Portable.Tests.csproj b/tools/Battle.Tests/Pal3.Battle.Portable.Tests.csproj new file mode 100644 index 00000000..91468dde --- /dev/null +++ b/tools/Battle.Tests/Pal3.Battle.Portable.Tests.csproj @@ -0,0 +1,17 @@ + + + net10.0 + false + true + false + + + + + + + + + + + diff --git a/tools/Battle.Tests/Presentation/Pal3.Battle.Presentation.csproj b/tools/Battle.Tests/Presentation/Pal3.Battle.Presentation.csproj new file mode 100644 index 00000000..ffffbaea --- /dev/null +++ b/tools/Battle.Tests/Presentation/Pal3.Battle.Presentation.csproj @@ -0,0 +1,10 @@ + + + net10.0 + false + + + + + + diff --git a/tools/CodeStyle.Tests/ChangeWriterTests.cs b/tools/CodeStyle.Tests/ChangeWriterTests.cs new file mode 100644 index 00000000..657b0ce7 --- /dev/null +++ b/tools/CodeStyle.Tests/ChangeWriterTests.cs @@ -0,0 +1,153 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle.Tests; + +using System.Text; +using NUnit.Framework; + +public sealed class ChangeWriterTests +{ + private static byte[] Bytes(string value) => Encoding.UTF8.GetBytes(value); + + [TestCase(false)] + [TestCase(true)] + public void ChangedSourceAbortsEntireBatchIncludingUnchangedPlannedFiles(bool secondNeedsFormatting) + { + using var fixture = new RepositoryFixture(); + const string first = "Assets/Scripts/First.cs", second = "Assets/Scripts/Second.cs"; + fixture.Write(first, "class First{int A;}\n"); + fixture.Write(second, "class Second{int A;}\n"); + byte[] firstOriginal = fixture.Read(first), secondOriginal = fixture.Read(second); + FileChange[] changes = + { + new(fixture.PathFor(first), firstOriginal, Bytes("class First\n{\n int A;\n}\n")), + new(fixture.PathFor(second), secondOriginal, secondNeedsFormatting ? Bytes("class Second\n{\n int A;\n}\n") : secondOriginal) + }; + fixture.Write(second, "class Second { int ExternallyChanged; }\n"); + Assert.Throws(() => ChangeWriter.Apply(changes)); + Assert.That(fixture.Read(first), Is.EqualTo(firstOriginal)); + Assert.That(fixture.ReadText(second), Is.EqualTo("class Second { int ExternallyChanged; }\n")); + } + + [Test] + public void MissingSourceFailsBeforeAnyOtherOutputIsWritten() + { + using var fixture = new RepositoryFixture(); + const string source = "Assets/Scripts/First.cs"; + fixture.Write(source, "class First{int A;}\n"); + byte[] original = fixture.Read(source); + FileChange[] changes = + { + new(fixture.PathFor(source), original, Bytes("class First { int A; }\n")), + new(fixture.PathFor("Assets/Scripts/Missing.cs"), Bytes("class Missing {}"), Bytes("class Missing { }")) + }; + Assert.Catch(() => ChangeWriter.Apply(changes)); + Assert.That(fixture.Read(source), Is.EqualTo(original)); + } + + [Test] + public void SuccessfulBatchWritesExactPlannedBytesIncludingBomAndMixedEols() + { + using var fixture = new RepositoryFixture(); + const string source = "Assets/Scripts/Changed.cs", untouched = "Assets/Scripts/Untouched.cs"; + fixture.Write(source, "class Changed{int A;}\n"); + fixture.Write(untouched, "class Untouched {}\n"); + byte[] formatted = new byte[] { 0xef, 0xbb, 0xbf }.Concat(Bytes("class Changed\r\n{\r\n string S = @\"one\ntwo\";\r\n}\r\n")).ToArray(); + byte[] originalUntouched = fixture.Read(untouched); + ChangeWriter.Apply(new FileChange[] + { + new(fixture.PathFor(source), fixture.Read(source), formatted), + new(fixture.PathFor(untouched), originalUntouched, originalUntouched) + }); + Assert.That(fixture.Read(source), Is.EqualTo(formatted)); + Assert.That(fixture.Read(untouched), Is.EqualTo(originalUntouched)); + } + [Test] + public void SourceReplacedByLinkAfterPlanningAbortsAllWritesEvenWhenItsBytesMatch() + { + using var fixture = new RepositoryFixture(); + const string first = "Assets/Scripts/First.cs", second = "Assets/Scripts/Second.cs", target = "Shared/Target.cs"; + fixture.Write(first, "class First{int A;}\n"); + fixture.Write(second, "class Second{int B;}\n"); + byte[] firstOriginal = fixture.Read(first), secondOriginal = fixture.Read(second); + fixture.Write(target, secondOriginal); + FileChange[] changes = + { + new(fixture.PathFor(first), firstOriginal, Bytes("class First { int A; }\n")), + new(fixture.PathFor(second), secondOriginal, secondOriginal) + }; + File.Delete(fixture.PathFor(second)); + fixture.Link(second, target); + string? link = new FileInfo(fixture.PathFor(second)).LinkTarget; + Assert.Throws(() => ChangeWriter.Apply(changes)); + Assert.That(fixture.Read(first), Is.EqualTo(firstOriginal)); + Assert.That(fixture.Read(target), Is.EqualTo(secondOriginal)); + Assert.That(new FileInfo(fixture.PathFor(second)).LinkTarget, Is.EqualTo(link)); + } + + [Test] + public void ReadOnlyInputLeavesTheBatchAndFileAttributesIntact() + { + using var fixture = new RepositoryFixture(); + const string first = "Assets/Scripts/A.cs", second = "Assets/Scripts/B.cs"; + foreach (string name in new[] { first, second }) + fixture.Write(name, "class A{ }"); + string path = fixture.PathFor(second); + FileAttributes attributes = File.GetAttributes(path); + File.SetAttributes(path, attributes | FileAttributes.ReadOnly); + try + { + FileChange[] changes = new[] { first, second } + .Select(name => new FileChange(fixture.PathFor(name), fixture.Read(name), Bytes("class A { }"))).ToArray(); + Assert.Throws(() => ChangeWriter.Apply(changes)); + Assert.That(fixture.ReadText(first), Is.EqualTo("class A{ }")); + Assert.That(fixture.ReadText(second), Is.EqualTo("class A{ }")); + Assert.That(File.GetAttributes(path).HasFlag(FileAttributes.ReadOnly), Is.True); + Assert.That(Directory.GetFiles(fixture.PathFor("Assets/Scripts")), Has.Length.EqualTo(2)); + } + finally + { + File.SetAttributes(path, attributes); + } + } + + [Test] + public void PreCancelledApplyWritesNoSelectedFile() + { + using var fixture = new RepositoryFixture(); + const string source = "Assets/Scripts/First.cs"; + fixture.Write(source, "class First{int A;}\n"); + byte[] original = fixture.Read(source); + FileChange[] changes = { new(fixture.PathFor(source), original, Bytes("class First { int A; }\n")) }; + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + Assert.Throws(() => ChangeWriter.Apply(changes, cancellation.Token)); + Assert.That(fixture.Read(source), Is.EqualTo(original)); + Assert.That(Directory.GetFiles(fixture.PathFor("Assets/Scripts")), Has.Length.EqualTo(1)); + } + + [Test] + public void ParentReplacedByLinkBeforeChangesAreMaterializedCannotRedirectWrites() + { + using var fixture = new RepositoryFixture(); + const string source = "Assets/Scripts/A.cs", target = "Shared/A.cs", moved = "Assets/Moved/A.cs"; + fixture.Write(source, "class A{int Value;}\n"); + byte[] original = fixture.Read(source); + fixture.Write(target, original); + // Program captures originals before awaiting the SDK. Materializing the + // write plan afterward must retain this lexical path and see the link. + Directory.Move(fixture.PathFor("Assets/Scripts"), fixture.PathFor("Assets/Moved")); + fixture.Link("Assets/Scripts", "Shared", directory: true); + Assert.Throws(() => + { + FileChange[] changes = { new(fixture.PathFor(source), original, Bytes("class A { int Value; }\n")) }; + ChangeWriter.Apply(changes); + }); + Assert.That(fixture.Read(target), Is.EqualTo(original)); + Assert.That(fixture.Read(moved), Is.EqualTo(original)); + } + +} diff --git a/tools/CodeStyle.Tests/CliTests.cs b/tools/CodeStyle.Tests/CliTests.cs new file mode 100644 index 00000000..f142df6f --- /dev/null +++ b/tools/CodeStyle.Tests/CliTests.cs @@ -0,0 +1,343 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle.Tests; + +using NUnit.Framework; + +public sealed class CliTests +{ + private const string Source = "Assets/Scripts/效果 layout.cs"; + private const string Good = "internal sealed class Layout\r\n{\r\n#if PAL3\r\n public int AOne() => 1;\r\n\r\n public int ATwo() => 2;\r\n#elif PAL3A\r\n public int BOne() => 1;\r\n\r\n public int BTwo() => 2;\r\n#endif\r\n}\r\n"; + + [Test] + public void CheckIsReadOnlyAndBothVariantsAndBaseModeRepairMemberGaps() + { + using var fixture = new RepositoryFixture(); + fixture.Write(Source, Good); + string baseline = fixture.Commit(); + fixture.Write(Source, Good.Replace(";\r\n\r\n", ";\r\n")); + byte[] original = fixture.Read(Source); + Assert.That(fixture.Format(false, "--check").Output, Does.Contain("Formatting required:")); + Assert.That(fixture.Read(Source), Is.EqualTo(original)); + fixture.Format(); + Assert.That(fixture.ReadText(Source), Is.EqualTo(Good)); + fixture.Format(true, "--check", "--all"); + fixture.Write(Source, Good.Replace("BOne() => 1;\r\n\r\n", "BOne() => 1;\r\n")); + fixture.Format(false, "--check", "--base", baseline); + fixture.Format(); + fixture.Format(true, "--check", "--base", baseline); + } + + [Test] + public void SelectiveFormattingLeavesInheritedViolationsAndExplicitPathsAuditWholeFile() + { + using var fixture = new RepositoryFixture(); + const string source = "Assets/Scripts/Legacy.cs"; + const string baseline = "class Legacy\r\n{\r\n int Untouched;\r\n\r\n int Changed;\r\n}\r\n"; + fixture.Write(source, baseline); + fixture.Commit(); + fixture.Write(source, baseline.Replace("int Changed", "int Changed")); + byte[] original = fixture.Read(source); + fixture.Format(false, "--check"); + Assert.That(fixture.Read(source), Is.EqualTo(original)); + fixture.Format(); + Assert.That(fixture.ReadText(source), Is.EqualTo(baseline)); + fixture.Format(true, "--check"); + fixture.Format(false, "--check", source); + fixture.Format(true, source); + fixture.Format(true, "--check", source); + Assert.That(fixture.ReadText(source), Does.Contain("int Untouched;")); + } + + [Test] + public void IncrementalFormattingAcceptsUnicodeSpacesAndPreservesUntouchedText() + { + using var fixture = new RepositoryFixture(); + const string text = "class Layout\r\n{\r\n int\u00a0First = 1;\r\n int\u3000Second = 2; // 注\u3000释\r\n}\r\n"; + fixture.Write(Source, text); + fixture.Commit(); + fixture.Write(Source, text.Replace("2;", "3;")); + fixture.Format(false, "--check"); + fixture.Format(); + Assert.That(fixture.ReadText(Source), Is.EqualTo(text.Replace("int\u3000Second = 2", "int Second = 3"))); + fixture.Format(true, "--check"); + } + + [Test] + public void NewOwnedFilesAreFormattedWhileThirdPartyGeneratedAndOutsidePathsRemainUntouched() + { + using var fixture = new RepositoryFixture(); + string[] excluded = { "Assets/Plugins/Keep.cs", "Assets/Packages/Keep.cs", "Library/Keep.cs", "Logs/Keep.cs", "obj/Keep.cs", "tools/Keep.cs", "Elsewhere.cs" }; + const string bad = "class Keep{void One(){}void Two(){}}"; + foreach (string path in excluded) + fixture.Write(path, bad); + fixture.Write("Assets/Scripts/Tracked.cs", Good); + fixture.Commit(); + fixture.Write("Assets/Tests/New test.cs", "class NewTest{int A;}\n"); + const string staged = "Assets/Scripts/Staged.cs"; + fixture.Write(staged, "class Staged{int B;}\n"); + fixture.Run("git", "add", "--", staged); + fixture.Format(); + fixture.Format(true, "--check", "--all"); + Assert.That(fixture.ReadText("Assets/Tests/New test.cs"), Does.Contain("int A;")); + Assert.That(fixture.ReadText(staged), Does.Contain("int B;")); + foreach (string path in excluded) + Assert.That(fixture.ReadText(path), Is.EqualTo(bad), path); + } + + [Test] + public void InvalidArgumentCombinationsAndEscapingPathsDoNotWriteSources() + { + using var fixture = new RepositoryFixture(); + const string original = "class Bad{int A;}\n"; + fixture.Write(Source, original); + fixture.Commit(); + foreach (string[] arguments in new[] + { + new[] { "--all", "--base", "HEAD" }, + new[] { "--all", Source }, + new[] { "--base", "HEAD", Source }, + new[] { "../Outside.cs" }, + new[] { "--unknown" } + }) + { + fixture.Format(false, arguments); + Assert.That(fixture.ReadText(Source), Is.EqualTo(original)); + } + } + + [TestCase("")] + [TestCase(" ")] + [TestCase("-b")] + [TestCase("--check")] + public void InvalidBaseValuesFailAsUsageErrors(string value) + { + using var fixture = new RepositoryFixture(); + fixture.Write(Source, Good); + fixture.Commit(); + var result = fixture.Format(false, "--base", value); + Assert.That(result.ExitCode, Is.EqualTo(2)); + Assert.That(result.Output, Does.Contain("--base requires one Git commit.")); + } + + [Test] + public void DivergedBaseUsesTheBranchPointForFileAndLineSelection() + { + using var fixture = new RepositoryFixture(); + const string upstreamOnly = "Assets/Tests/UpstreamOnly.cs"; + string legacy = Good.Replace("int ATwo", "int ATwo"); + fixture.Write(Source, legacy); + fixture.Write(upstreamOnly, "class UpstreamOnly{int A;}\n"); + string fork = fixture.Commit(); + + fixture.Run("git", "checkout", "-q", "-b", "upstream"); + fixture.Write(Source, Good); + fixture.Write(upstreamOnly, "class UpstreamOnly{int A;}\n"); + fixture.Commit(); + + fixture.Run("git", "checkout", "-q", "-b", "topic", fork); + fixture.Write(Source, legacy.Replace("int BTwo", "int BTwo")); + fixture.Commit(); + var result = fixture.Format(true, "--base", "upstream"); + Assert.That(result.Output, Does.Contain("Formatting 1 C# files")); + Assert.That(fixture.ReadText(Source), Is.EqualTo(legacy)); + Assert.That(fixture.ReadText(upstreamOnly), Is.EqualTo("class UpstreamOnly{int A;}\n")); + fixture.Format(true, "--check", "--base", "upstream"); + } + + [Test] + public void ExplicitPathCasingFollowsTheFilesystem() + { + using var fixture = new RepositoryFixture(); + const string source = "Assets/Scripts/Case/One.cs"; + const string alias = "assets/scripts/case/one.cs"; + fixture.Write(source, "class One{int A;}\n"); + fixture.Commit(); + + if (File.Exists(fixture.PathFor(alias))) + { + fixture.Format(false, "--check", alias); + fixture.Format(true, "assets/SCRIPTS/CASE"); + Assert.That(fixture.ReadText(source), Does.Contain("int A;")); + } + else + { + fixture.Write("Assets/Scripts/Case/one.cs", "class Lower{int B;}\n"); + fixture.Format(true, "Assets/Scripts/Case/one.cs"); + Assert.That(fixture.ReadText(source), Is.EqualTo("class One{int A;}\n")); + Assert.That(fixture.ReadText("Assets/Scripts/Case/one.cs"), Does.Contain("int B;")); + } + } + + [Test] + public void EmptyOwnedSelectionExitsSuccessfullyWithoutFormattingExcludedFiles() + { + using var fixture = new RepositoryFixture(); + fixture.Write("Assets/Plugins/Only.cs", "class Only{int A;}"); + fixture.Commit(); + fixture.Format(true, "--check"); + Assert.That(fixture.ReadText("Assets/Plugins/Only.cs"), Is.EqualTo("class Only{int A;}")); + } + [Test] + public void BaseModeIncludesCommittedEditsThatDefaultModeLeavesOutsideSelection() + { + using var fixture = new RepositoryFixture(); + fixture.Write(Source, Good); + string baseline = fixture.Commit(); + fixture.Write(Source, Good.Replace("int ATwo", "int ATwo")); + fixture.Commit(); + fixture.Format(true, "--check"); + fixture.Format(false, "--check", "--base", baseline); + fixture.Format(true, "--base", baseline); + fixture.Format(true, "--check", "--base", baseline); + Assert.That(fixture.ReadText(Source), Is.EqualTo(Good)); + } + + [Test] + public void RenamedFilesPreserveInheritedFormattingAndDeletedFilesStayExcluded() + { + using var fixture = new RepositoryFixture(); + const string original = "Assets/Scripts/Before.cs", renamed = "Assets/Scripts/After [α] #1.cs", deleted = "Assets/Tests/Deleted.cs"; + const string content = "class Renamed\n{\n int Untouched;\n\n int Changed;\n}\n"; + fixture.Write(original, content); + fixture.Write(deleted, "class Deleted{int B;}\n"); + string baseline = fixture.Commit(); + fixture.Run("git", "mv", original, renamed); + fixture.Run("git", "rm", "--quiet", deleted); + fixture.Format(true, "--check"); + fixture.Format(); + Assert.That(fixture.ReadText(renamed), Is.EqualTo(content)); + + fixture.Write(renamed, content.Replace("int Changed", "int Edited")); + fixture.Commit(); + fixture.Format(false, "--check", "--base", baseline); + fixture.Format(true, "--base", baseline); + Assert.That(fixture.ReadText(renamed), Is.EqualTo(content.Replace("int Changed", "int Edited"))); + fixture.Format(true, "--check", "--base", baseline); + Assert.That(File.Exists(fixture.PathFor(original)), Is.False); + Assert.That(File.Exists(fixture.PathFor(deleted)), Is.False); + } + + [Test] + public void DirectorySelectionAcceptsTheTrailingSeparatorAndChecksItsFiles() + { + using var fixture = new RepositoryFixture(); + fixture.Write(Source, Good); + fixture.Commit(); + fixture.Write(Source, Good.Replace(";\r\n\r\n", ";\r\n")); + byte[] original = fixture.Read(Source); + fixture.Format(false, "--check", "Assets/Scripts"); + fixture.Format(false, "--check", "Assets/Scripts/"); + Assert.That(fixture.Read(Source), Is.EqualTo(original)); + fixture.Format(true, "Assets/Scripts/"); + Assert.That(fixture.ReadText(Source), Is.EqualTo(Good)); + } + + [Test] + public void MsBuildReservedCharactersInFileNamesRemainLiteral() + { + using var fixture = new RepositoryFixture(); + fixture.Write("README.txt", "Fixture repository"); + fixture.Commit(); + string[] names = { "A;B.cs", "A$(Missing).cs", "A@(Compile).cs", "A%25.cs", "A'中文.cs" }; + for (int index = 0; index < names.Length; index++) + fixture.Write("Assets/Scripts/" + names[index], "class Punctuation" + index + "{int A;}\n"); + fixture.Format(false, "--check"); + fixture.Format(); + fixture.Format(true, "--check"); + foreach (string name in names) + Assert.That(fixture.ReadText("Assets/Scripts/" + name), Does.Contain("int A;"), name); + } + + [Test] + public void ExplicitPathsResolveFromTheInvokingDirectoryAndAcceptAncestorAliases() + { + using var fixture = new RepositoryFixture(); + fixture.Write(Source, Good.Replace("=> 1;", "=> 1;")); + fixture.Commit(); + fixture.FormatFrom(fixture.PathFor("Assets/Scripts"), true, Path.GetFileName(Source)); + Assert.That(fixture.ReadText(Source), Is.EqualTo(Good)); + fixture.Write(Source, Good.Replace("=> 1;", "=> 1;")); + string alias = fixture.Root + "-parent-alias"; + fixture.Link(alias, Path.GetDirectoryName(fixture.Root)!, directory: true); + try + { + string throughParentAlias = Path.Combine(alias, Path.GetFileName(fixture.Root)); + fixture.Format(true, Path.Combine(throughParentAlias, Source)); + Assert.That(fixture.ReadText(Source), Is.EqualTo(Good)); + fixture.Link("back-to-parent", "..", directory: true); + try + { + var rejected = fixture.Format(false, Path.Combine(throughParentAlias, "back-to-parent", Path.GetFileName(fixture.Root), Source)); + Assert.That(rejected.Output, Does.Contain("Symbolic-link paths are not formatted")); + } + finally + { + Directory.Delete(fixture.PathFor("back-to-parent")); + } + } + finally + { + Directory.Delete(alias); + } + } + + [Test] + public void WholeFileFormattingNormalizesUnicodeLineTerminators() + { + using var fixture = new RepositoryFixture(); + fixture.Write(Source, "internal class Layout { int A;\u0085int B;\u2028int C;\u2029int D; }\n"); + fixture.Commit(); + fixture.Format(true, "--all"); + Assert.That(fixture.ReadText(Source), Does.Not.Contain("\u0085").And.Not.Contain("\u2028").And.Not.Contain("\u2029")); + fixture.Format(true, "--all", "--check"); + } + + [TestCase(false)] + [TestCase(true)] + public void ParentTraversalCannotHideADirectoryLink(bool absolute) + { + using var fixture = new RepositoryFixture(); + const string alias = "Assets/Scripts/Link"; + const string lexicalFile = "Assets/Scripts/Victim.cs"; + const string physicalFile = "Assets/Outside/Victim.cs"; + const string original = "class Victim{int A;}\n"; + fixture.Write(lexicalFile, original); + fixture.Write(physicalFile, original); + Directory.CreateDirectory(fixture.PathFor("Assets/Outside/Nested")); + fixture.Link(alias, "Assets/Outside/Nested", directory: true); + fixture.Commit(); + + string path = alias + "/../Victim.cs"; + var result = fixture.Format(false, absolute ? fixture.PathFor(path) : path); + Assert.That(result.Output, Does.Contain("Symbolic-link paths")); + Assert.That(fixture.ReadText(lexicalFile), Is.EqualTo(original)); + Assert.That(fixture.ReadText(physicalFile), Is.EqualTo(original)); + + fixture.Format(true, "Assets/Scripts/../Scripts/Victim.cs"); + Assert.That(fixture.ReadText(lexicalFile), Is.Not.EqualTo(original)); + } + + [Test] + public void OwnedFileLinksAreSkippedByDefaultAndRejectedExplicitlyWithoutChangingTheirTarget() + { + using var fixture = new RepositoryFixture(); + const string target = "Shared/Target.cs", alias = "Assets/Scripts/Alias.cs"; + const string original = "class SharedTarget{int A;}\n"; + fixture.Write(target, original); + fixture.Link(alias, target); + fixture.Commit(); + string? link = new FileInfo(fixture.PathFor(alias)).LinkTarget; + Assert.That(link, Is.Not.Null); + fixture.Format(true, "--check"); + fixture.Format(true, "--all"); + fixture.Format(false, alias); + Assert.That(fixture.ReadText(target), Is.EqualTo(original)); + Assert.That(new FileInfo(fixture.PathFor(alias)).LinkTarget, Is.EqualTo(link)); + Assert.That(fixture.Run("git", "status", "--porcelain", "--", alias, target).Output, Is.Empty); + } + +} diff --git a/tools/CodeStyle.Tests/CodeStyle.Tests.csproj b/tools/CodeStyle.Tests/CodeStyle.Tests.csproj new file mode 100644 index 00000000..4439711e --- /dev/null +++ b/tools/CodeStyle.Tests/CodeStyle.Tests.csproj @@ -0,0 +1,24 @@ + + + net10.0 + Pal3.Tools.CodeStyle.Tests + Pal3.Tools.CodeStyle.Tests + true + false + enable + enable + false + + + + + + + + + + + + + + diff --git a/tools/CodeStyle.Tests/PayloadTests.cs b/tools/CodeStyle.Tests/PayloadTests.cs new file mode 100644 index 00000000..b0a98e0d --- /dev/null +++ b/tools/CodeStyle.Tests/PayloadTests.cs @@ -0,0 +1,190 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle.Tests; + +using System.Text; +using System.Xml.Linq; +using NUnit.Framework; + +public sealed class PayloadTests +{ + private const string Source = "Assets/Scripts/文字 payload.cs"; + + private const string LiteralSource = """"" +using System; +using System.Text; +internal static class LiteralFixture +{ + static int Factor = 2; +#if PAL3 + static string Branch() => $$""" + 中文 😀 PAL3 + #if NATIVE + #endif + {{Factor}} + """; +#elif PAL3A + static string Branch() => $$""" + 中文 😀 PAL3A + {{Factor + 1}} + """; +#endif + static string Verbatim() => @"one +# two ""quoted"""; + static string Interpolated() => $@"first + {string.Join(" ", new[] { "one", "two" })}"; + static string Raw() => """ + zero + two + """; + public static void Main() => Console.Write(Convert.ToBase64String(Encoding.UTF8.GetBytes(Branch() + Verbatim() + Interpolated() + Raw()))); +} +"""""; + + private const string InterpolationSource = """"" +using System; +using System.Text; +internal static class InterpolationFixture +{ + static int A = 2, B = 3; + static string Plain() => $"sum={A + B} {{ braces }}"; + static string Verbatim() => $@"first +# second {A + B,4:N2}"; + static string Raw() => $$""" + raw text + {{A + B}} + {{string.Join(",", new[] + { + A, B + })}} + """; + static string Formatted() => $"{A + B:D2}"; + static string Nested() => $"outer {$"inner {A + B}"}"; + static string MultilineHole() => $"{A + +B}"; + static string CommentHole() => $"{A + // 中文 😀 +B}"; + static string RawHole() => $$""" +{{A + +B}} +"""; + static string LongDelimiter() => $$$"""" + literal {{braces}} and """ quotes + {{{A + B}}} + """"; + public static void Main() => Console.Write(Convert.ToBase64String(Encoding.UTF8.GetBytes(Plain() + Verbatim() + Raw() + Formatted() + Nested() + MultilineHole() + CommentHole() + RawHole() + LongDelimiter()))); +} +"""""; + + [Test] + public void BomUnicodeAndLiteralSpellingSurviveSelectiveEditsAndRealVariantExecution() + { + using var fixture = new RepositoryFixture(); + fixture.Write(Source, Bom(LiteralSource.ReplaceLineEndings("\n") + "\n")); + fixture.Commit(); + fixture.Write(Source, fixture.ReadText(Source).Replace("Factor = 2;", "Factor = 2;") + .Replace(" two\n \"\"\";", " two\n \"\"\";")); + byte[] before = fixture.Read(Source); + Dictionary payloads = Outputs(fixture); + fixture.Format(false, "--check"); + Assert.That(fixture.Read(Source), Is.EqualTo(before)); + fixture.Format(); + byte[] after = fixture.Read(Source); + Assert.That(after.Take(3), Is.EqualTo(new byte[] { 0xef, 0xbb, 0xbf })); + Assert.That(fixture.ReadText(Source), Does.Contain("Factor = 2;").And.Not.Contain("\r\n")); + foreach (string method in new[] { "Branch", "Verbatim", "Interpolated", "Raw" }) + Assert.That(LiteralBodies(fixture.ReadText(Source), method), Is.EqualTo(LiteralBodies(Encoding.UTF8.GetString(before), method)), method); + fixture.Format(true, "--check"); + Assert.That(Outputs(fixture), Is.EqualTo(payloads)); + } + + [TestCase(false)] + [TestCase(true)] + public void InterpolationExpressionsFormatWhileRawPayloadAndLegacyIndentationRemainExecutable(bool legacyIndentation) + { + using var fixture = new RepositoryFixture(); + fixture.Write(Source, InterpolationSource.ReplaceLineEndings("\n") + .Replace("", " ", StringComparison.Ordinal) + "\n"); + fixture.Format(true, Source); + if (legacyIndentation) + { + string text = fixture.ReadText(Source); + int start = text.IndexOf("$$\"\"\"", StringComparison.Ordinal); + int end = text.IndexOf("\"\"\"", start + 5, StringComparison.Ordinal) + 3; + string[] lines = text[start..end].Split('\n'); + string shifted = lines[0] + "\n" + string.Join("\n", lines.Skip(1).Select(line => " " + line)); + fixture.Write(Source, text[..start] + shifted + text[end..]); + } + string baseline = fixture.Commit(); + fixture.Write(Source, fixture.ReadText(Source).Replace("A + B", "A+B").Replace("A, B", "A, B")); + byte[] original = fixture.Read(Source); + Dictionary payloads = Outputs(fixture); + fixture.Format(false, "--check"); + Assert.That(fixture.Read(Source), Is.EqualTo(original)); + fixture.Format(); + Assert.That(fixture.ReadText(Source), Does.Not.Contain("A+B")); + fixture.Format(true, "--check"); + fixture.Format(true, "--check", "--base", baseline); + if (!legacyIndentation) + fixture.Format(true, "--check", Source); + Assert.That(Outputs(fixture), Is.EqualTo(payloads)); + } + + [Test] + public void CommonInactivePlayerLiteralKeepsLfPayloadInsideBomCrLfCode() + { + using var fixture = new RepositoryFixture(); + const string text = "using System;\nusing System.Text;\ninternal static class InactiveFixture\n{\n static int N = 0;\n#if !UNITY_EDITOR\n static string Value = @\"one\nold\";\n#else\n static string Value = \"editor\";\n#endif\n static void Main() => Console.Write(Convert.ToBase64String(Encoding.UTF8.GetBytes(Value + N)));\n}\n"; + fixture.Write(Source, Bom(text.Replace("\n", "\r\n").Replace("@\"one\r\nold\"", "@\"one\nold\""))); + fixture.Commit(); + fixture.Write(Source, fixture.ReadText(Source).Replace("old", "new").Replace("int N = 0;", "int N = 0;")); + byte[] original = fixture.Read(Source); + Dictionary payloads = Outputs(fixture); + fixture.Format(); + Assert.That(fixture.Read(Source), Is.EqualTo(Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(original).Replace("int N = 0;", "int N = 0;")))); + fixture.Format(true, "--check"); + Assert.That(Outputs(fixture), Is.EqualTo(payloads)); + } + + [TestCase("new")] + [TestCase("--all")] + [TestCase(Source)] + public void WholeFileFormattingPreservesInactiveLiteralBytes(string mode) + { + using var fixture = new RepositoryFixture(); + fixture.Write("README.txt", "Fixture repository"); + fixture.Commit(); + const string payload = "@\"one \ntwo\""; + fixture.Write(Source, "internal class Fixture\r\n{\r\n int n;\r\n#if !UNITY_EDITOR\r\n string Value = " + payload + ";\r\n#endif\r\n}\r\n"); + if (mode == "new") + fixture.Format(); + else + fixture.Format(true, mode); + Assert.That(fixture.ReadText(Source), Does.Contain("int n;").And.Contain(payload)); + } + + private static byte[] Bom(string source) => new byte[] { 0xef, 0xbb, 0xbf }.Concat(Encoding.UTF8.GetBytes(source)).ToArray(); + + private static string[] LiteralBodies(string source, string method) => source.Split(method + "() => ", StringSplitOptions.None) + .Skip(1).Select(part => part.Split(";\n", StringSplitOptions.None)[0]).ToArray(); + + private static Dictionary Outputs(RepositoryFixture fixture) + { + var document = new XDocument(new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement("PropertyGroup", new XElement("TargetFramework", "net10.0"), new XElement("OutputType", "Exe"), + new XElement("EnableDefaultCompileItems", "false"), new XElement("NuGetAudit", "false")), + new XElement("ItemGroup", new XElement("Compile", new XAttribute("Include", Source))))); + fixture.Write("Payload.csproj", document.ToString()); + var result = new Dictionary(); + foreach (string variant in new[] { "PAL3", "PAL3A" }) + { + string destination = fixture.PathFor("compiled/" + variant); + fixture.Run("dotnet", "build", "Payload.csproj", "--verbosity", "quiet", "-p:DefineConstants=" + variant, "-o", destination); + result.Add(variant, fixture.Run("dotnet", Path.Combine(destination, "Payload.dll")).Output); + } + return result; + } +} diff --git a/tools/CodeStyle.Tests/README.md b/tools/CodeStyle.Tests/README.md new file mode 100644 index 00000000..fcefdb34 --- /dev/null +++ b/tools/CodeStyle.Tests/README.md @@ -0,0 +1,17 @@ +# Code style regression tests + +Run the formatter and its tests with the SDK pinned by the repository: + +```sh +dotnet test tools/CodeStyle.Tests +``` + +The suite uses NUnit and the real .NET CLI; Python and Unity are not required. +CLI cases create isolated Git repositories, invoke the built formatter, and +compile and execute literal fixtures for both `PAL3` and `PAL3A`. Unit cases +cover selective whitespace boundaries and the final file-write preflight. + +By default fixtures live in the operating system temporary directory. Set +`PAL3_CODE_STYLE_TEST_ROOT` to place them in a chosen QA directory, and set +`PAL3_CODE_STYLE_KEEP_FIXTURES=1` to retain them for diagnosis. Child processes +receive the fixture as their temporary directory and have a three-minute limit. diff --git a/tools/CodeStyle.Tests/RepositoryFixture.cs b/tools/CodeStyle.Tests/RepositoryFixture.cs new file mode 100644 index 00000000..07b3c703 --- /dev/null +++ b/tools/CodeStyle.Tests/RepositoryFixture.cs @@ -0,0 +1,153 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle.Tests; + +using System.Diagnostics; +using System.Text; +using NUnit.Framework; + +internal sealed class RepositoryFixture : IDisposable +{ + internal static readonly string SourceRoot = FindSourceRoot(); + internal string Root + { + get; + } + + internal RepositoryFixture() + { + string parent = Environment.GetEnvironmentVariable("PAL3_CODE_STYLE_TEST_ROOT") ?? + Path.Combine(Path.GetTempPath(), "Pal3.CodeStyle.Tests"); + Root = Path.Combine(parent, Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Root); + foreach (string name in new[] { ".editorconfig", "global.json" }) + File.Copy(Path.Combine(SourceRoot, name), Path.Combine(Root, name)); + Write(".gitignore", "bin/\nobj/\ncompiled/\n"); + Run("git", "init", "--quiet"); + Run("git", "config", "core.autocrlf", "false"); + Run("git", "config", "core.symlinks", "true"); + Run("git", "config", "core.hooksPath", PathFor(".git/no-hooks")); + // Git canonicalizes system temporary aliases such as /var on macOS. + // Use that stable root before any source snapshots/plans are created. + Root = Run("git", "rev-parse", "--show-toplevel").Output.TrimEnd('\r', '\n'); + } + + internal string PathFor(string relative) => Path.Combine(Root, relative.Replace('/', Path.DirectorySeparatorChar)); + + internal void Write(string relative, string content) => Write(relative, Encoding.UTF8.GetBytes(content)); + + internal void Write(string relative, byte[] content) + { + string path = PathFor(relative); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllBytes(path, content); + } + + internal byte[] Read(string relative) => File.ReadAllBytes(PathFor(relative)); + + internal string ReadText(string relative) => Encoding.UTF8.GetString(Read(relative)); + + internal ProcessResult Format(bool success = true, params string[] arguments) => FormatFrom(Root, success, arguments); + + internal ProcessResult FormatFrom(string directory, bool success, params string[] arguments) + { + string formatter = Path.Combine(AppContext.BaseDirectory, "formatter"); + string configuration = Directory.GetFiles(formatter, "*.runtimeconfig.json").Single(); + string assembly = configuration[..^".runtimeconfig.json".Length] + ".dll"; + return Run("dotnet", new[] { assembly }.Concat(arguments).ToArray(), success, directory); + } + + internal void Link(string relative, string target, bool directory = false) + { + string path = PathFor(relative); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + try + { + string destination = Path.GetRelativePath(Path.GetDirectoryName(path)!, PathFor(target)); + if (directory) + Directory.CreateSymbolicLink(path, destination); + else + File.CreateSymbolicLink(path, destination); + } + catch (Exception exception) when (exception is UnauthorizedAccessException or PlatformNotSupportedException || + OperatingSystem.IsWindows() && exception is IOException && (exception.HResult & 0xffff) == 1314) + { + Assert.Ignore("The current filesystem/user cannot create symbolic links: " + exception.Message); + } + } + + internal string Commit(params string[] paths) + { + Run("git", new[] { "add", "--" }.Concat(paths.Length == 0 ? new[] { "." } : paths).ToArray()); + Run("git", "-c", "user.name=Code style fixture", "-c", "user.email=fixture@localhost", + "-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "Fixture baseline"); + return Run("git", "rev-parse", "HEAD").Output.Trim(); + } + + internal ProcessResult Run(string executable, params string[] arguments) => Run(executable, arguments, true); + + internal ProcessResult Run(string executable, string[] arguments, bool success, string? directory = null) + { + var start = new ProcessStartInfo(executable) + { + WorkingDirectory = directory ?? Root, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }; + foreach (string argument in arguments) + start.ArgumentList.Add(argument); + // A caller's worktree/index overrides must never redirect fixture Git + // commands into an unrelated repository. + foreach (string variable in start.Environment.Keys.Where(name => name.StartsWith("GIT_", StringComparison.Ordinal)).ToArray()) + start.Environment.Remove(variable); + start.Environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1"; + start.Environment["DOTNET_NOLOGO"] = "1"; + // Both Windows and Unix subprocesses keep their temporary files inside + // this fixture, which makes cleanup and failed-test inspection local. + foreach (string variable in new[] { "TMPDIR", "TMP", "TEMP" }) + start.Environment[variable] = Root; + using Process process = Process.Start(start)!; + Task output = process.StandardOutput.ReadToEndAsync(); + Task error = process.StandardError.ReadToEndAsync(); + if (!process.WaitForExit(180000)) + { + process.Kill(entireProcessTree: true); + process.WaitForExit(10000); + Assert.Fail("Command exceeded 180 seconds: " + executable + " " + string.Join(" ", arguments)); + } + string text = output.GetAwaiter().GetResult() + error.GetAwaiter().GetResult(); + Assert.That(process.ExitCode == 0, Is.EqualTo(success), + executable + " " + string.Join(" ", arguments) + Environment.NewLine + text); + return new ProcessResult(process.ExitCode, text); + } + + public void Dispose() + { + // Failed fixtures can be retained for local diagnosis without changing + // the behavior of ordinary dotnet test runs on Windows/macOS/Linux. + if (Environment.GetEnvironmentVariable("PAL3_CODE_STYLE_KEEP_FIXTURES") == "1") + return; + foreach (string file in Directory.EnumerateFiles(Root, "*", SearchOption.AllDirectories)) + { + FileAttributes attributes = File.GetAttributes(file); + if ((attributes & FileAttributes.ReparsePoint) == 0) + File.SetAttributes(file, attributes & ~FileAttributes.ReadOnly); + } + Directory.Delete(Root, recursive: true); + } + + private static string FindSourceRoot() + { + for (DirectoryInfo? directory = new(AppContext.BaseDirectory); directory != null; directory = directory.Parent) + if (File.Exists(Path.Combine(directory.FullName, "global.json")) && + Directory.Exists(Path.Combine(directory.FullName, "tools", "CodeStyle.Tests"))) + return directory.FullName; + throw new DirectoryNotFoundException("The code style tests must run from a repository build output."); + } + + internal readonly record struct ProcessResult(int ExitCode, string Output); +} diff --git a/tools/CodeStyle.Tests/SelectionTests.cs b/tools/CodeStyle.Tests/SelectionTests.cs new file mode 100644 index 00000000..961c9663 --- /dev/null +++ b/tools/CodeStyle.Tests/SelectionTests.cs @@ -0,0 +1,120 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle.Tests; + +using System.Text; +using NUnit.Framework; + +public sealed class SelectionTests +{ + private static byte[] Bytes(string value) => Encoding.UTF8.GetBytes(value); + + private static string Select(string? baseline, string original, string formatted) => + Encoding.UTF8.GetString(SelectiveFormatting.Select(baseline == null ? null : Bytes(baseline), Bytes(original), Bytes(formatted))); + + [TestCase("\r\n")] + [TestCase("\n")] + public void ChangedLinePreservesInheritedSpacingAndEols(string eol) + { + string baseline = "int A;" + eol + eol + "int B;" + eol; + string original = baseline.Replace("int B", "int B"); + string formatted = "int A;\r\n\r\nint B;\r\n"; + Assert.That(Select(baseline, original, formatted), Is.EqualTo(baseline)); + Assert.That(Select(baseline, baseline, formatted), Is.EqualTo(baseline)); + } + + [Test] + public void EditingOneStatementLeavesAdjacentLegacyWhitespaceUntouched() + { + const string baseline = "int before = 0; \nint changed = 1;\n int next = 2;\n int second = 3;\n int third = 4;\n"; + string original = baseline.Replace("changed = 1", "changed = 42"); + const string formatted = "int before = 0;\nint changed = 42;\nint next = 2;\nint second = 3;\nint third = 4;\n"; + Assert.That(Select(baseline, original, formatted), Is.EqualTo(original)); + } + + [Test] + public void RestoringMemberGapPreservesAdjacentIndentationAndFormatsTheEditedMember() + { + const string baseline = "class C\n{\n int A() => 1;\n\n int B() => 2;\n}\n"; + const string formatted = "class C\n{\n int A() => 1;\n\n int B() => 2;\n}\n"; + Assert.That(Select(baseline, baseline.Replace(";\n\n", ";\n"), formatted), Is.EqualTo(baseline)); + string original = baseline.Replace(" int B() => 2", "int B() => 42"); + Assert.That(Select(baseline, original, formatted.Replace("=> 2", "=> 42")), + Is.EqualTo(formatted.Replace("=> 2", "=> 42"))); + } + + [Test] + public void NewFileUsesCompleteFormattingResult() + { + const string formatted = "int A;\r\n\r\nint B;\r\n"; + Assert.That(Select(null, "int A;\nint B;", formatted), Is.EqualTo(formatted)); + } + + [Test] + public void RemovedFinalNewlineAndMemberGapAreRepaired() + { + const string baseline = "int A;\r\n\r\nint B;\r\n"; + const string formatted = "int A;\r\n\r\nint B;\r\n"; + Assert.That(Select(baseline, baseline[..^2], formatted), Is.EqualTo(baseline)); + Assert.That(Select(baseline, baseline.Replace(";\r\n\r\n", ";\r\n"), formatted), Is.EqualTo(baseline)); + Assert.That(Select("class D {}\n\n\n", "class D {}\n\n", "class D {}\n"), Is.EqualTo("class D {}\n")); + } + + [Test] + public void MemberExpansionConvergesWithoutDuplicatingInheritedMembers() + { + const string baseline = "class D\n{\n public int A { get; }\n public int B { get; }\n public int C { get; }\n}\n"; + string original = baseline[..^2] + " public int D { get; }\n}\n"; + string formatted = original.Replace("{ get; }", "\n {\n get;\n }"); + string selected = Select(baseline, original, formatted); + Assert.That(selected.Split("public int B").Length - 1, Is.EqualTo(1)); + Assert.That(new string(selected.Where(character => !char.IsWhiteSpace(character)).ToArray()), + Is.EqualTo(new string(original.Where(character => !char.IsWhiteSpace(character)).ToArray()))); + Assert.That(Select(baseline, selected, formatted), Is.EqualTo(selected)); + string removed = baseline.Replace(" public int A { get; }\n", ""); + string deletion = Select(baseline, removed, removed.Replace("{ get; }", "\n {\n get;\n }")); + Assert.That(deletion, Does.Contain("public int B { get; }")); + } + + [Test] + public void NonWhitespaceRewriteFailsWithoutReturningPartialOutput() + { + Assert.Throws(() => Select("int A;\n", "int A;\n", "int B;\n")); + } + + [Test] + public void MixedEolsAndLiteralOffsetsRemainStableAfterBlankLineDeletion() + { + const string prefix = "class C\r\n{\r\n int A;"; + const string suffix = " string Text = @\"hello\nworld\";\n int B;\n int C;\n int D;\n}\n"; + string baseline = prefix + string.Concat(Enumerable.Repeat("\r\n", 6)) + suffix; + string original = prefix + string.Concat(Enumerable.Repeat("\r\n", 5)) + suffix; + string formatted = prefix + "\r\n\r\n" + suffix.Replace("\n", "\r\n"); + string selected = Select(baseline, original, formatted); + Assert.That(selected, Does.Contain("@\"hello\nworld\"")); + Assert.That(Select(baseline, selected, formatted), Is.EqualTo(selected)); + } + + [Test] + public void LongLfLiteralDoesNotChangeCrLfCodeConvention() + { + string payload = "@\"" + string.Concat(Enumerable.Repeat("world\n", 40)) + "world\""; + string original = "class D\r\n{\r\n string Text = " + payload + ";\r\n int A;\r\n}\r\n"; + string baseline = original.Replace("int A;", "int A;"); + Assert.That(Select(baseline, original, baseline), Is.EqualTo(baseline)); + } + [Test] + public void PreCancelledSelectionDoesNotProduceOutputOrMutateInputs() + { + byte[] baseline = Bytes("class C { int A; }\n"), original = Bytes("class C { int A; }\n"), formatted = Bytes("class C\n{\n int A;\n}\n"); + byte[] before = original.ToArray(); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + Assert.Throws(() => SelectiveFormatting.Select(baseline, original, formatted, cancellation.Token)); + Assert.That(original, Is.EqualTo(before)); + } + +} diff --git a/tools/CodeStyle/ChangeWriter.cs b/tools/CodeStyle/ChangeWriter.cs new file mode 100644 index 00000000..b5fd17af --- /dev/null +++ b/tools/CodeStyle/ChangeWriter.cs @@ -0,0 +1,117 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle; + +internal sealed record FileChange +{ + internal string Path + { + get; + } + + internal byte[] Original + { + get; + } + + internal byte[] Formatted + { + get; + } + + internal FileChange(string path, byte[] original, byte[] formatted) + { + // Repository.Root is canonicalized before reading inputs. Keep its + // lexical child path: resolving a parent again after formatting would + // hide a directory that was replaced with a link while the SDK ran. + Path = System.IO.Path.GetFullPath(path); + Original = original; + Formatted = formatted; + } +} + +internal static class ChangeWriter +{ + internal static void Verify(IReadOnlyList changes) + { + foreach (FileChange change in changes) + if (PathSafety.HasLink(change.Path) || !File.ReadAllBytes(change.Path).AsSpan().SequenceEqual(change.Original)) + throw new IOException($"Source changed while formatting: {change.Path}; no output was applied."); + } + + internal static void Apply(IReadOnlyList changes, CancellationToken cancellation = default) + { + cancellation.ThrowIfCancellationRequested(); + Verify(changes); + var staged = new List<(FileChange Change, string Temporary, string Backup)>(); + var applied = new List<(FileChange Change, string Backup)>(); + var retained = new HashSet(); + try + { + foreach (FileChange change in changes.Where(change => !change.Original.AsSpan().SequenceEqual(change.Formatted))) + { + cancellation.ThrowIfCancellationRequested(); + if ((File.GetAttributes(change.Path) & FileAttributes.ReadOnly) != 0) + throw new UnauthorizedAccessException("Cannot format read-only source: " + change.Path); + string temporary = change.Path + ".pal3-format-" + Guid.NewGuid().ToString("N") + ".tmp"; + string backup = temporary + ".bak"; + staged.Add((change, temporary, backup)); + // Preserve permissions when replacing an existing file. + File.Copy(change.Path, temporary); + File.WriteAllBytes(temporary, change.Formatted); + } + Verify(changes); + foreach (var entry in staged) + { + cancellation.ThrowIfCancellationRequested(); + Verify([entry.Change]); + File.Replace(entry.Temporary, entry.Change.Path, entry.Backup); + applied.Add((entry.Change, entry.Backup)); + } + } + catch + { + foreach (var entry in applied.AsEnumerable().Reverse()) + { + try + { + if (PathSafety.HasLink(entry.Change.Path) || + !File.ReadAllBytes(entry.Change.Path).AsSpan().SequenceEqual(entry.Change.Formatted)) + throw new IOException("Source changed during formatting."); + File.Move(entry.Backup, entry.Change.Path, overwrite: true); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + retained.Add(entry.Backup); + Console.Error.WriteLine($"Could not restore {entry.Change.Path}. Backup path: {entry.Backup}. {error.Message}"); + } + } + throw; + } + finally + { + foreach (var entry in staged) + { + TryDelete(entry.Temporary); + if (!retained.Contains(entry.Backup)) + TryDelete(entry.Backup); + } + } + } + + private static void TryDelete(string path) + { + try + { + if (!PathSafety.HasLink(path)) + File.Delete(path); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + Console.Error.WriteLine($"Could not remove formatter artifact {path}: {error.Message}"); + } + } +} diff --git a/tools/CodeStyle/ChangedLines.cs b/tools/CodeStyle/ChangedLines.cs new file mode 100644 index 00000000..d5923c7f --- /dev/null +++ b/tools/CodeStyle/ChangedLines.cs @@ -0,0 +1,112 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle; + +// Find stable longest contiguous matches (earliest old/new position on ties). +// Recurse only into unmatched intervals, then merge adjacent blocks. This keeps +// repeated blank lines deterministic without marking inherited members dirty. +internal static class ChangedLines +{ + internal readonly record struct Line(string Content, int Start, int End, bool HasNewline); + + private readonly record struct Match(int Old, int Current, int Count); + + internal static Line[] Split(byte[] source) + { + var lines = new List(); + int start = 0; + for (int i = 0; i < source.Length; i++) + { + if (source[i] is not (10 or 13)) + continue; + int contentEnd = i; + if (source[i] == 13 && i + 1 < source.Length && source[i + 1] == 10) + i++; + int end = i + 1; + lines.Add(new(Convert.ToHexString(source.AsSpan(start, contentEnd - start)), start, end, source[end - 1] == 10)); + start = end; + } + if (start < source.Length) + lines.Add(new(Convert.ToHexString(source.AsSpan(start)), start, source.Length, false)); + return lines.ToArray(); + } + + internal static (HashSet Dirty, HashSet Boundaries) Compare(Line[] baseline, Line[] current, CancellationToken cancellation = default) + { + var positions = new Dictionary>(StringComparer.Ordinal); + for (int i = 0; i < current.Length; i++) + { + if (!positions.TryGetValue(current[i].Content, out List? indices)) + positions.Add(current[i].Content, indices = []); + indices.Add(i); + } + var matches = new List(); + var pending = new Stack<(int OldStart, int OldEnd, int Start, int End)>(); + pending.Push((0, baseline.Length, 0, current.Length)); + while (pending.TryPop(out var area)) + { + cancellation.ThrowIfCancellationRequested(); + var best = new Match(area.OldStart, area.Start, 0); + var lengths = new Dictionary(); + for (int old = area.OldStart; old < area.OldEnd; old++) + { + if (old % 64 == 0) + cancellation.ThrowIfCancellationRequested(); + var next = new Dictionary(); + if (positions.TryGetValue(baseline[old].Content, out List? indices)) + { + foreach (int index in indices) + { + if (index < area.Start) + continue; + if (index >= area.End) + break; + int count = lengths.GetValueOrDefault(index - 1) + 1; + next[index] = count; + if (count > best.Count) + best = new(old - count + 1, index - count + 1, count); + } + } + lengths = next; + } + if (best.Count == 0) + continue; + matches.Add(best); + if (best.Old > area.OldStart && best.Current > area.Start) + pending.Push((area.OldStart, best.Old, area.Start, best.Current)); + if (best.Old + best.Count < area.OldEnd && best.Current + best.Count < area.End) + pending.Push((best.Old + best.Count, area.OldEnd, best.Current + best.Count, area.End)); + } + var blocks = new List(); + foreach (Match match in matches.OrderBy(match => match.Old).ThenBy(match => match.Current)) + { + if (blocks.Count > 0 && blocks[^1].Old + blocks[^1].Count == match.Old && blocks[^1].Current + blocks[^1].Count == match.Current) + blocks[^1] = blocks[^1] with + { + Count = blocks[^1].Count + match.Count + }; + else + blocks.Add(match); + } + blocks.Add(new(baseline.Length, current.Length, 0)); + var dirty = new HashSet(); + var boundaries = new HashSet(); + int oldEnd = 0, currentEnd = 0; + foreach (Match match in blocks) + { + for (int line = currentEnd; line < match.Current; line++) + dirty.Add(line); + if (match.Current == currentEnd && match.Old > oldEnd) + boundaries.Add(currentEnd); + for (int line = 0; line < match.Count; line++) + if (baseline[match.Old + line].HasNewline != current[match.Current + line].HasNewline) + dirty.Add(match.Current + line); + oldEnd = match.Old + match.Count; + currentEnd = match.Current + match.Count; + } + return (dirty, boundaries); + } +} diff --git a/tools/CodeStyle/CodeStyle.csproj b/tools/CodeStyle/CodeStyle.csproj new file mode 100644 index 00000000..968df7b6 --- /dev/null +++ b/tools/CodeStyle/CodeStyle.csproj @@ -0,0 +1,20 @@ + + + Exe + net10.0 + Pal3.Tools.CodeStyle + Pal3.Tools.CodeStyle + enable + enable + false + + + + $(MSBuildToolsPath)/Roslyn/bincore/Microsoft.CodeAnalysis.dll + + + $(MSBuildToolsPath)/Roslyn/bincore/Microsoft.CodeAnalysis.CSharp.dll + + + + diff --git a/tools/CodeStyle/FormattingProject.cs b/tools/CodeStyle/FormattingProject.cs new file mode 100644 index 00000000..5316bf0a --- /dev/null +++ b/tools/CodeStyle/FormattingProject.cs @@ -0,0 +1,106 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle; + +using System.Text; +using System.Xml.Linq; + +internal sealed class FormattingProject : IDisposable +{ + private static readonly string[] Rules = ["SA1107", "SA1502", "SA1507", "SA1516"]; + private readonly string _directory; + private readonly string _sources; + private readonly string _project; + private readonly string _root; + + private static string EscapeItem(string path) + { + var escaped = new StringBuilder(); + foreach (char character in path) + if (character is '%' or '$' or '@' or '(' or ')' or ';' or '\'' or '?' or '*') + escaped.Append('%').Append(((int)character).ToString("X2", System.Globalization.CultureInfo.InvariantCulture)); + else + escaped.Append(character); + return escaped.ToString(); + } + + internal FormattingProject(string root, IReadOnlyDictionary originals) + { + _root = root; + string? workspace = Directory.GetParent(root) is { } parent ? Path.Combine(parent.FullName, "workspace") : null; + string temporaryRoot = Directory.Exists(workspace) ? Path.Combine(workspace, "Tooling", "CodeStyle") : Path.GetTempPath(); + _directory = Path.Combine(temporaryRoot, "pal3-format-" + Guid.NewGuid().ToString("N")); + _sources = Path.Combine(_directory, "sources"); + _project = Path.Combine(_directory, "Formatting.csproj"); + try + { + Directory.CreateDirectory(_sources); + File.Copy(Path.Combine(root, ".editorconfig"), Path.Combine(_sources, ".editorconfig")); + foreach (var entry in originals) + { + string path = Path.Combine(_sources, entry.Key); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllBytes(path, entry.Value); + } + var project = new XElement("Project", new XAttribute("Sdk", "Microsoft.NET.Sdk"), + new XElement("PropertyGroup", + new XElement("TargetFramework", "net10.0"), + new XElement("EnableDefaultCompileItems", "false"), + new XElement("GenerateAssemblyInfo", "false"), + new XElement("NuGetAudit", "false"), + new XElement("DefineConstants", "$(PAL3_FORMAT_VARIANT);UNITY_EDITOR")), + new XElement("ItemGroup", + new XElement("PackageReference", new XAttribute("Include", "StyleCop.Analyzers"), + new XAttribute("Version", "1.3.180"), new XAttribute("PrivateAssets", "all")), + originals.Keys.Select(name => new XElement("Compile", new XAttribute("Include", EscapeItem(Path.Combine(_sources, name))))))); + new XDocument(project).Save(_project); + } + catch + { + Dispose(); + throw; + } + } + + internal byte[] Read(string name) => File.ReadAllBytes(Path.Combine(_sources, name)); + + private async Task Run(IEnumerable arguments, CancellationToken cancellation, string? variant = null) + { + ProcessResult result = await Processes.Run("dotnet", arguments, _root, cancellation, + variant == null ? null : new Dictionary { ["PAL3_FORMAT_VARIANT"] = variant }); + Console.Write(Encoding.UTF8.GetString(result.Output)); + Console.Error.Write(result.Error); + return result.ExitCode == 0; + } + + internal async Task Format(bool verbose, CancellationToken cancellation) + { + if (!await Run(["restore", _project, "--verbosity", "quiet"], cancellation)) + throw new IOException("Unable to restore the temporary formatting project."); + bool succeeded = true; + foreach (string variant in new[] { "PAL3", "PAL3A" }) + { + foreach (string command in new[] { "analyzers", "whitespace" }) + { + var arguments = new List { "format", command, _project, "--no-restore", "--verbosity", verbose ? "diagnostic" : "minimal" }; + if (command == "analyzers") + { + arguments.Add("--diagnostics"); + arguments.AddRange(Rules); + } + succeeded &= await Run(arguments, cancellation, variant); + } + } + if (!succeeded) + throw new IOException("The SDK formatter failed; source files were not changed."); + } + + public void Dispose() + { + if (Directory.Exists(_directory)) + Directory.Delete(_directory, recursive: true); + } +} diff --git a/tools/CodeStyle/Options.cs b/tools/CodeStyle/Options.cs new file mode 100644 index 00000000..755ae9b5 --- /dev/null +++ b/tools/CodeStyle/Options.cs @@ -0,0 +1,74 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle; + +internal sealed record Options(bool Check, bool Verbose, bool All, string? Base, string[] Paths, bool Help) +{ + internal const string Usage = """ + Format owned C# changes with the pinned .NET SDK and StyleCop layout rules. + + dotnet run --project tools/CodeStyle -- [--check] [--verbose] [--base REF | --all] [PATH ...] + + --check Report required formatting without changing source files. + --base REF Include changes since the merge base of HEAD and this Git commit. + --all Format all owned C# files. + PATH Format whole files or folders under Assets/Scripts or Assets/Tests. + --verbose Show detailed Roslyn/MSBuild diagnostics. + --help Show this help. + + With no selection flags, format current tracked/untracked C# changes. + Explicit paths cannot be combined with --base or --all. + Both PAL3 and PAL3A branches are formatted. Unity and game data are not required. + """; + + internal static Options Parse(string[] arguments) + { + bool check = false, verbose = false, all = false, help = false, pathsOnly = false; + string? baseline = null; + var paths = new List(); + for (int index = 0; index < arguments.Length; index++) + { + string argument = arguments[index]; + if (pathsOnly) + { + paths.Add(argument); + continue; + } + switch (argument) + { + case "--": + pathsOnly = true; + break; + case "--check": + check = true; + break; + case "--verbose": + verbose = true; + break; + case "--all": + all = true; + break; + case "--help" or "-h": + help = true; + break; + case "--base": + if (baseline != null || ++index >= arguments.Length || + string.IsNullOrWhiteSpace(arguments[index]) || arguments[index].StartsWith('-')) + throw new ArgumentException("--base requires one Git commit."); + baseline = arguments[index]; + break; + default: + if (argument.StartsWith("-", StringComparison.Ordinal)) + throw new ArgumentException("Unknown option: " + argument); + paths.Add(argument); + break; + } + } + if ((all && baseline != null) || (paths.Count > 0 && (all || baseline != null))) + throw new ArgumentException("Explicit paths, --base and --all cannot be combined."); + return new(check, verbose, all, baseline, paths.ToArray(), help); + } +} diff --git a/tools/CodeStyle/PathSafety.cs b/tools/CodeStyle/PathSafety.cs new file mode 100644 index 00000000..c8b5c72b --- /dev/null +++ b/tools/CodeStyle/PathSafety.cs @@ -0,0 +1,50 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle; + +using System.Runtime.InteropServices; + +internal static class PathSafety +{ + // Darwin's _PC_CASE_SENSITIVE reports the volume semantics for this checkout. + private const int MacCaseSensitive = 11; + + [DllImport("libSystem.B.dylib", EntryPoint = "pathconf")] + private static extern nint MacPathConf([MarshalAs(UnmanagedType.LPUTF8Str)] string path, int name); + + internal static StringComparison Comparison(string root) => + OperatingSystem.IsWindows() || (OperatingSystem.IsMacOS() && MacPathConf(root, MacCaseSensitive) == 0) + ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; + + internal static string Physical(string path) + { + string absolute = Path.GetFullPath(path); + string current = Path.GetPathRoot(absolute)!; + foreach (string part in absolute[current.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + current = Path.Combine(current, part); + FileSystemInfo entry = Entry(current); + if (entry.LinkTarget != null) + current = entry.ResolveLinkTarget(returnFinalTarget: true)?.FullName ?? throw new IOException("Unresolved symbolic link: " + current); + } + return Path.TrimEndingDirectorySeparator(current); + } + + internal static bool HasLink(string path) + { + string absolute = Path.GetFullPath(path); + string current = Path.GetPathRoot(absolute)!; + foreach (string part in absolute[current.Length..].Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)) + { + current = Path.Combine(current, part); + if (Entry(current).LinkTarget != null) + return true; + } + return false; + } + + private static FileSystemInfo Entry(string path) => Directory.Exists(path) ? new DirectoryInfo(path) : new FileInfo(path); +} diff --git a/tools/CodeStyle/Processes.cs b/tools/CodeStyle/Processes.cs new file mode 100644 index 00000000..ff2ba595 --- /dev/null +++ b/tools/CodeStyle/Processes.cs @@ -0,0 +1,66 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle; + +using System.Diagnostics; +using System.Text; + +internal readonly record struct ProcessResult(int ExitCode, byte[] Output, string Error); + +internal static class Processes +{ + internal static async Task Run(string executable, IEnumerable arguments, string directory, + CancellationToken cancellation, IReadOnlyDictionary? environment = null) + { + var info = new ProcessStartInfo(executable) + { + WorkingDirectory = directory, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardErrorEncoding = Encoding.UTF8 + }; + foreach (string argument in arguments) + info.ArgumentList.Add(argument); + if (environment != null) + foreach (var entry in environment) + info.Environment[entry.Key] = entry.Value; + using var process = new Process { StartInfo = info }; + process.Start(); + using var output = new MemoryStream(); + Task copy = process.StandardOutput.BaseStream.CopyToAsync(output, cancellation); + Task error = process.StandardError.ReadToEndAsync(cancellation); + try + { + await process.WaitForExitAsync(cancellation); + await copy; + return new(process.ExitCode, output.ToArray(), await error); + } + catch + { + if (!process.HasExited) + process.Kill(entireProcessTree: true); + await process.WaitForExitAsync(CancellationToken.None); + try + { + await Task.WhenAll(copy, error); + } + catch (OperationCanceledException) + { + // Preserve the original cancellation after reaping children. + } + throw; + } + } + + internal static async Task Git(string directory, CancellationToken cancellation, params string[] arguments) + { + ProcessResult result = await Run("git", arguments, directory, cancellation); + if (result.ExitCode != 0) + throw new IOException("Git failed: " + result.Error.Trim()); + return result.Output; + } +} diff --git a/tools/CodeStyle/Program.cs b/tools/CodeStyle/Program.cs new file mode 100644 index 00000000..df8bb8bb --- /dev/null +++ b/tools/CodeStyle/Program.cs @@ -0,0 +1,79 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle; + +using System.ComponentModel; + +internal static class Program +{ + private static async Task Main(string[] arguments) + { + using var cancellation = new CancellationTokenSource(); + ConsoleCancelEventHandler cancel = (_, input) => + { + input.Cancel = true; + cancellation.Cancel(); + }; + Console.CancelKeyPress += cancel; + try + { + Options options = Options.Parse(arguments); + if (options.Help) + { + Console.WriteLine(Options.Usage); + return 0; + } + Repository repository = await Repository.Open(cancellation.Token); + string? reference = options.All || options.Paths.Length > 0 ? null : await repository.ComparisonBase(options.Base); + SourceFile[] files = await repository.Select(options.Paths, reference); + if (files.Length == 0) + { + Console.WriteLine("No owned C# changes to format."); + return 0; + } + var originals = files.ToDictionary(file => file.Name, file => File.ReadAllBytes(repository.FullPath(file.Name)), StringComparer.Ordinal); + using var project = new FormattingProject(repository.Root, originals); + Console.WriteLine($"{(options.Check ? "Checking" : "Formatting")} {files.Length} C# files (PAL3 and PAL3A)."); + await project.Format(options.Verbose, cancellation.Token); + var changes = new List(); + foreach ((string name, string? baselineName) in files) + { + cancellation.Token.ThrowIfCancellationRequested(); + byte[]? baseline = reference == null || baselineName == null ? null : await repository.Baseline(reference, baselineName); + byte[] selected = SelectiveFormatting.Select(baseline, originals[name], project.Read(name), cancellation.Token); + changes.Add(new(repository.FullPath(name), originals[name], selected)); + } + cancellation.Token.ThrowIfCancellationRequested(); + ChangeWriter.Verify(changes); + bool changed = changes.Any(change => !change.Original.AsSpan().SequenceEqual(change.Formatted)); + if (!options.Check) + ChangeWriter.Apply(changes, cancellation.Token); + else + foreach (FileChange change in changes.Where(change => !change.Original.AsSpan().SequenceEqual(change.Formatted))) + Console.WriteLine("Formatting required: " + Path.GetRelativePath(repository.Root, change.Path).Replace(Path.DirectorySeparatorChar, '/')); + return options.Check && changed ? 1 : 0; + } + catch (ArgumentException exception) + { + Console.Error.WriteLine(exception.Message); + return 2; + } + catch (OperationCanceledException) + { + Console.Error.WriteLine("Formatting cancelled."); + return 130; + } + catch (Exception exception) when (exception is IOException or InvalidOperationException or Win32Exception or UnauthorizedAccessException) + { + Console.Error.WriteLine(exception.Message); + return 1; + } + finally + { + Console.CancelKeyPress -= cancel; + } + } +} diff --git a/tools/CodeStyle/ProtectedText.cs b/tools/CodeStyle/ProtectedText.cs new file mode 100644 index 00000000..66cc8aae --- /dev/null +++ b/tools/CodeStyle/ProtectedText.cs @@ -0,0 +1,86 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle; + +using System.Text; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; + +internal readonly record struct ByteRange(int Start, int End); + +internal static class ProtectedText +{ + internal static readonly UTF8Encoding Utf8 = new(false, true); + + internal static IReadOnlyList Capture(byte[] source) + { + string text = Utf8.GetString(source); + var ranges = new List(); + var inactive = new List[2]; + int context = 0; + foreach (string variant in new[] { "PAL3", "PAL3A" }) + { + SyntaxNode root = CSharpSyntaxTree.ParseText(text, + new CSharpParseOptions(LanguageVersion.Preview, preprocessorSymbols: [variant, "UNITY_EDITOR"])).GetRoot(); + inactive[context++] = root.DescendantTrivia(descendIntoTrivia: true) + .Where(trivia => trivia.IsKind(SyntaxKind.DisabledTextTrivia)) + .Select(trivia => new ByteRange(trivia.SpanStart, trivia.Span.End)).ToList(); + foreach (SyntaxNode node in root.DescendantNodes()) + { + switch (node) + { + case InterpolatedStringExpressionSyntax interpolation: + ranges.Add(new(interpolation.StringStartToken.SpanStart, interpolation.StringStartToken.Span.End)); + ranges.Add(new(interpolation.StringEndToken.SpanStart, interpolation.StringEndToken.Span.End)); + break; + case InterpolatedStringTextSyntax part: + ranges.Add(new(part.SpanStart, part.Span.End)); + break; + case InterpolationFormatClauseSyntax format: + ranges.Add(new(format.FormatStringToken.SpanStart, format.FormatStringToken.Span.End)); + break; + } + } + foreach (SyntaxToken token in root.DescendantTokens(descendIntoTrivia: true)) + { + if (token.Kind() is SyntaxKind.StringLiteralToken or SyntaxKind.CharacterLiteralToken or + SyntaxKind.Utf8StringLiteralToken or SyntaxKind.SingleLineRawStringLiteralToken or + SyntaxKind.MultiLineRawStringLiteralToken or SyntaxKind.Utf8SingleLineRawStringLiteralToken or + SyntaxKind.Utf8MultiLineRawStringLiteralToken) + ranges.Add(new(token.SpanStart, token.Span.End)); + } + } + // Text inactive in both formatting contexts is opaque as well: its + // player-only literals must retain their exact original bytes. + for (int left = 0, right = 0; left < inactive[0].Count && right < inactive[1].Count;) + { + ByteRange first = inactive[0][left], second = inactive[1][right]; + int start = Math.Max(first.Start, second.Start), end = Math.Min(first.End, second.End); + if (start < end) + ranges.Add(new(start, end)); + if (first.End <= second.End) + left++; + else + right++; + } + var merged = new List(); + foreach (ByteRange range in ranges.OrderBy(range => range.Start).ThenByDescending(range => range.End)) + { + if (range.Start == range.End) + continue; + if (merged.Count > 0 && range.Start < merged[^1].End) + merged[^1] = merged[^1] with + { + End = Math.Max(merged[^1].End, range.End) + }; + else + merged.Add(range); + } + return merged.Select(range => new ByteRange(Utf8.GetByteCount(text.AsSpan(0, range.Start)), + Utf8.GetByteCount(text.AsSpan(0, range.End)))).ToArray(); + } +} diff --git a/tools/CodeStyle/README.md b/tools/CodeStyle/README.md new file mode 100644 index 00000000..126fb27d --- /dev/null +++ b/tools/CodeStyle/README.md @@ -0,0 +1,81 @@ +# C# code style + +This .NET CLI formats the repository's owned C# sources under `Assets/Scripts/` +and `Assets/Tests/`. It calls the SDK's `dotnet format` with `.editorconfig` and +StyleCop 1.3.180 layout rules SA1107, SA1502, SA1507 and SA1516. Roslyn identifies +the C# text that must be preserved during incremental formatting. It checks both +PAL3 and PAL3A conditional branches without Unity or original game data. The +formatter and its tests need no Python; use the .NET SDK pinned in the +repository's `global.json`. + +Run commands from the repository root. The first run restores the tool's .NET +dependencies. StyleCop is used only by the development tool and is not added to +the Unity project. + +## Commands + +Format current tracked changes and untracked owned C# files, then verify them: + +```sh +dotnet run --project tools/CodeStyle -- +dotnet run --project tools/CodeStyle -- --check +``` + +Check changes since the common ancestor of HEAD and a Git ref, including current +working tree changes, as the pull request workflow does: + +```sh +dotnet run --project tools/CodeStyle -- --check --base origin/main +``` + +Format whole files by selecting explicit repository-relative files or directories: + +```sh +dotnet run --project tools/CodeStyle -- Assets/Scripts/Pal3.Core +``` + +Check every owned C# source, or show detailed formatter diagnostics: + +```sh +dotnet run --project tools/CodeStyle -- --check --all +dotnet run --project tools/CodeStyle -- --check --verbose +``` + +Run the formatter's .NET regression tests: + +```sh +dotnet test tools/CodeStyle.Tests +``` + +After the test command restores both projects, verify their own source whitespace +with the same SDK checks used by CI: + +```sh +dotnet format whitespace tools/CodeStyle --no-restore --verify-no-changes +dotnet format whitespace tools/CodeStyle.Tests --no-restore --verify-no-changes +``` + +## Scope and preservation + +Default and `--base` runs apply formatting only to changed lines and deletion +boundaries. Git-detected renames use the original path for comparison, so a +pure rename preserves the file byte for byte. Newly added and untracked files, +explicit paths and `--all` use whole-file formatting. Third-party +sources outside the owned directories are excluded. `--base` and `--all` are +mutually exclusive, and neither can be combined with explicit paths. + +Files with symbolic links in any component below the repository root are skipped +by default and with `--all`. Explicit paths through symbolic links are rejected. +The tool does not follow links into other source trees or replace links with +ordinary files. + +Check mode formats temporary copies and exits unsuccessfully if formatting is +required; it does not rewrite source files. Formatting preserves each source +file's BOM. Incremental formatting also preserves the existing line ending +convention and protects C# literal contents and inactive conditional text. +Whole-file formatting uses the complete SDK result and the `.editorconfig` +line ending setting. + +These checks cover whitespace and member layout. Run the relevant Unity tests +after formatting to verify compilation and behavior. ShaderLab/HLSL formatting +and rendering checks remain separate. diff --git a/tools/CodeStyle/Repository.cs b/tools/CodeStyle/Repository.cs new file mode 100644 index 00000000..870a8a49 --- /dev/null +++ b/tools/CodeStyle/Repository.cs @@ -0,0 +1,110 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle; + +internal readonly record struct SourceFile(string Name, string? BaselineName); + +internal sealed class Repository(string root, CancellationToken cancellation) +{ + internal string Root { get; } = PathSafety.Physical(root); + + private readonly StringComparison _pathComparison = PathSafety.Comparison(root); + + internal static async Task Open(CancellationToken cancellation) + { + byte[] output = await Processes.Git(Environment.CurrentDirectory, cancellation, "rev-parse", "--show-toplevel"); + return new(Path.GetFullPath(ProtectedText.Utf8.GetString(output).TrimEnd('\r', '\n')), cancellation); + } + + private async Task GitFields(params string[] arguments) + { + byte[] output = await Processes.Git(Root, cancellation, arguments); + return ProtectedText.Utf8.GetString(output).Split('\0', StringSplitOptions.RemoveEmptyEntries); + } + + internal string FullPath(string path) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(path, Root)); + + internal async Task ComparisonBase(string? reference) + { + byte[] output = await Processes.Git(Root, cancellation, "merge-base", "--", "HEAD", reference ?? "HEAD"); + return ProtectedText.Utf8.GetString(output).TrimEnd('\r', '\n'); + } + + private bool AtOrBelow(string path, string directory) + { + string prefix = Path.EndsInDirectorySeparator(directory) ? directory : directory + Path.DirectorySeparatorChar; + return path.Equals(directory, _pathComparison) || path.StartsWith(prefix, _pathComparison); + } + + private string ResolveRequestedPath(string path) + { + string workingDirectory = Environment.CurrentDirectory; + string separators = OperatingSystem.IsWindows() ? "/\\" : "/"; + // An explicit link followed by ".." can resolve to a different file + // on disk. Check the directory being removed before GetFullPath erases it. + foreach (Range segment in path.AsSpan().SplitAny(separators)) + { + if (path.AsSpan()[segment].SequenceEqual("..")) + { + int start = segment.Start.Value; + string directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(start == 0 ? "." : path[..start], workingDirectory)); + if (new DirectoryInfo(directory).LinkTarget != null) + throw new ArgumentException("Symbolic-link paths are not formatted."); + } + } + string absolute = Path.TrimEndingDirectorySeparator(Path.GetFullPath(path, workingDirectory)); + if (AtOrBelow(absolute, Root)) + return absolute; + // Canonicalize an alias above the repository (e.g. macOS /tmp). Leave + // the suffix lexical so the link check below can still reject owned-file links. + var prefixes = new Stack(); + for (DirectoryInfo? prefix = new(absolute); prefix != null; prefix = prefix.Parent) + prefixes.Push(prefix); + foreach (DirectoryInfo prefix in prefixes) + { + if (prefix.Exists && prefix.LinkTarget == null && prefix.Name.Equals(Path.GetFileName(Root), _pathComparison) && + PathSafety.Physical(prefix.FullName).Equals(Root, _pathComparison)) + return FullPath(Path.GetRelativePath(prefix.FullName, absolute)); + } + return absolute; + } + + internal async Task Select(string[] requestedPaths, string? reference) + { + string[] paths = reference == null + ? await GitFields("ls-files", "--cached", "--others", "--exclude-standard", "-z") + : await GitFields("ls-files", "--others", "--exclude-standard", "-z"); + var files = paths.Distinct(StringComparer.Ordinal).Select(path => new SourceFile(path, null)).ToList(); + if (reference != null) + { + string[] fields = await GitFields("diff", "--name-status", "--find-renames", "--diff-filter=ACMR", "-z", reference, "--"); + for (int index = 0; index < fields.Length;) + { + char status = fields[index++][0]; + string firstPath = fields[index++]; + string name = status is 'R' or 'C' ? fields[index++] : firstPath; + string? baselineName = status is 'M' or 'R' ? firstPath : null; + files.Add(new(name, baselineName)); + } + } + string[] requested = requestedPaths.Select(ResolveRequestedPath).ToArray(); + if (requested.Any(path => !AtOrBelow(path, Root))) + throw new ArgumentException("Paths must stay inside the repository."); + if (requested.Any(PathSafety.HasLink)) + throw new ArgumentException("Symbolic-link paths are not formatted."); + return files.Where(file => + { + string name = file.Name; + bool owned = name.StartsWith("Assets/Scripts/", StringComparison.Ordinal) || name.StartsWith("Assets/Tests/", StringComparison.Ordinal); + string path = FullPath(name); + return owned && name.EndsWith(".cs", StringComparison.Ordinal) && File.Exists(path) && !PathSafety.HasLink(path) && + (requested.Length == 0 || requested.Any(request => AtOrBelow(path, request))); + }).OrderBy(file => file.Name, StringComparer.Ordinal).ToArray(); + } + + internal Task Baseline(string reference, string name) => + Processes.Git(Root, cancellation, "show", reference + ":" + name); +} diff --git a/tools/CodeStyle/SelectiveFormatting.cs b/tools/CodeStyle/SelectiveFormatting.cs new file mode 100644 index 00000000..fe1a5058 --- /dev/null +++ b/tools/CodeStyle/SelectiveFormatting.cs @@ -0,0 +1,192 @@ +// ------------------------------------------------------------------------ +// Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. +// See LICENSE file in the project root for license information. +// ------------------------------------------------------------------------ + +namespace Pal3.Tools.CodeStyle; + +using System.Buffers; +using System.Text; + +internal static class SelectiveFormatting +{ + private readonly record struct Token(int Start, int End, string Key, bool Protected); + + internal static byte[] Select(byte[]? baseline, byte[] original, byte[] formatted, CancellationToken cancellation = default) + { + cancellation.ThrowIfCancellationRequested(); + IReadOnlyList sourceRanges = ProtectedText.Capture(original); + IReadOnlyList targetRanges = ProtectedText.Capture(formatted); + Token[] targetTokens = Tokens(formatted, targetRanges); + if (baseline == null) + return SelectOnce(null, original, formatted, sourceRanges, targetTokens, "", cancellation).Item1; + string newline = Newline(original, sourceRanges); + byte[] selected = original; + for (int pass = 0; pass < ChangedLines.Split(original).Length + 2; pass++) + { + cancellation.ThrowIfCancellationRequested(); + (byte[] result, IReadOnlyList nextRanges) = SelectOnce(baseline, selected, formatted, + sourceRanges, targetTokens, newline, cancellation); + if (selected.AsSpan().SequenceEqual(result)) + return result; + selected = result; + sourceRanges = nextRanges; + } + throw new InvalidOperationException("Changed-line formatting did not converge."); + } + + private static (byte[], IReadOnlyList) SelectOnce(byte[]? baseline, byte[] original, byte[] formatted, + IReadOnlyList ranges, Token[] targetTokens, string newline, CancellationToken cancellation) + { + ChangedLines.Line[] lines = ChangedLines.Split(original); + var (dirty, boundaries) = baseline == null ? (new HashSet(), new HashSet()) + : ChangedLines.Compare(ChangedLines.Split(baseline), lines, cancellation); + Token[] sourceTokens = Tokens(original, ranges); + if (!sourceTokens.Select(token => token.Key).SequenceEqual(targetTokens.Select(token => token.Key), StringComparer.Ordinal)) + throw new InvalidOperationException("The formatter changed non-whitespace content; refusing a partial rewrite."); + int[] starts = lines.Select(line => line.Start).Append(original.Length).ToArray(); + var output = new ArrayBufferWriter(); + var nextRanges = new List(); + int sourceEnd = 0, targetEnd = 0; + for (int index = 0; index <= sourceTokens.Length; index++) + { + if (index % 256 == 0) + cancellation.ThrowIfCancellationRequested(); + bool last = index == sourceTokens.Length; + int sourceStart = last ? original.Length : sourceTokens[index].Start; + int targetStart = last ? formatted.Length : targetTokens[index].Start; + ReadOnlySpan gap = original.AsSpan(sourceEnd, sourceStart - sourceEnd); + ReadOnlySpan targetGap = formatted.AsSpan(targetEnd, targetStart - targetEnd); + if (baseline == null) + output.Write(targetGap); + else + { + int firstLine = Math.Min(lines.Length - 1, UpperBound(starts, sourceEnd) - 1); + int lastLine = Math.Min(lines.Length - 1, UpperBound(starts, sourceStart) - 1); + bool changed = boundaries.Any(boundary => sourceEnd <= starts[boundary] && starts[boundary] <= sourceStart); + for (int line = firstLine; line <= lastLine && !changed; line++) + changed = dirty.Contains(line); + if (changed) + WriteChangedGap(output, gap, targetGap, newline, dirty.Contains(firstLine), dirty.Contains(lastLine)); + else + output.Write(gap); + } + if (last) + break; + Token source = sourceTokens[index], target = targetTokens[index]; + if (source.Protected) + nextRanges.Add(new(output.WrittenCount, output.WrittenCount + source.End - source.Start)); + output.Write(original.AsSpan(source.Start, source.End - source.Start)); + sourceEnd = source.End; + targetEnd = target.End; + } + return (output.WrittenSpan.ToArray(), nextRanges); + } + + private static void WriteChangedGap(ArrayBufferWriter output, ReadOnlySpan original, + ReadOnlySpan formatted, string newline, bool firstLineChanged, bool lastLineChanged) + { + string gapNewline = original.Contains((byte)10) ? Newline(original, []) : newline; + int firstBreak = original.IndexOfAny((byte)'\r', (byte)'\n'); + int formattedBreak = formatted.IndexOfAny((byte)'\r', (byte)'\n'); + ReadOnlySpan indentation = []; + if (firstBreak >= 0 && formattedBreak >= 0) + { + // A member gap can change even when the lines on its edges did not. + // Keep trailing whitespace and indentation owned by those lines. + if (!firstLineChanged) + { + output.Write(original[..firstBreak]); + formatted = formatted[formattedBreak..]; + } + if (!lastLineChanged) + { + indentation = original[(original.LastIndexOfAny((byte)'\r', (byte)'\n') + 1)..]; + formatted = formatted[..(formatted.LastIndexOfAny((byte)'\r', (byte)'\n') + 1)]; + } + } + string targetGap = ProtectedText.Utf8.GetString(formatted); + output.Write(ProtectedText.Utf8.GetBytes(targetGap.Replace("\r\n", "\n", StringComparison.Ordinal) + .Replace("\n", gapNewline, StringComparison.Ordinal))); + output.Write(indentation); + } + + private static int UpperBound(int[] sorted, int value) + { + int start = 0, end = sorted.Length; + while (start < end) + { + int middle = start + (end - start) / 2; + if (sorted[middle] <= value) + start = middle + 1; + else + end = middle; + } + return start; + } + + private static string Newline(ReadOnlySpan source, IReadOnlyList protectedRanges) + { + int start = 0, crlf = 0, lf = 0; + foreach (ByteRange range in protectedRanges.Append(new(source.Length, source.Length))) + { + for (int i = start; i < range.Start; i++) + { + if (source[i] != 10) + continue; + lf++; + if (i > start && source[i - 1] == 13) + crlf++; + } + start = range.End; + } + return crlf > lf / 2d ? "\r\n" : "\n"; + } + + private static bool Word(byte value) => value is >= (byte)'a' and <= (byte)'z' or >= (byte)'A' and <= (byte)'Z' or + >= (byte)'0' and <= (byte)'9' or (byte)'_'; + + private static int WhitespaceLength(ReadOnlySpan source) + { + byte first = source[0]; + if (first < 128) + return first is 9 or 10 or 11 or 12 or 13 or 32 ? 1 : 0; + return Rune.DecodeFromUtf8(source, out Rune character, out int length) == OperationStatus.Done && + (character.Value is 0x85 or 0x2028 or 0x2029 || + Rune.GetUnicodeCategory(character) == System.Globalization.UnicodeCategory.SpaceSeparator) ? length : 0; + } + + private static Token[] Tokens(byte[] source, IReadOnlyList ranges) + { + var tokens = new List(); + int cursor = 0; + for (int index = 0; index <= ranges.Count; index++) + { + int end = index < ranges.Count ? ranges[index].Start : source.Length; + if (cursor > end) + throw new InvalidOperationException("Invalid protected text span."); + while (cursor < end) + { + int whitespace = WhitespaceLength(source.AsSpan(cursor, end - cursor)); + if (whitespace > 0) + { + cursor += whitespace; + continue; + } + int start = cursor++; + if (Word(source[start])) + while (cursor < end && Word(source[cursor])) + cursor++; + tokens.Add(new(start, cursor, "code:" + Convert.ToHexString(source.AsSpan(start, cursor - start)), false)); + } + if (index == ranges.Count) + break; + ByteRange range = ranges[index]; + if (range.Start >= range.End || range.End > source.Length) + throw new InvalidOperationException("Invalid protected text span."); + tokens.Add(new(range.Start, range.End, "literal:" + index, true)); + cursor = range.End; + } + return tokens.ToArray(); + } +} diff --git a/tools/format-csharp.py b/tools/format-csharp.py deleted file mode 100644 index 1c7af649..00000000 --- a/tools/format-csharp.py +++ /dev/null @@ -1,176 +0,0 @@ -#!/usr/bin/env python3 -# ------------------------------------------------------------------------ -# Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. -# See LICENSE file in the project root for license information. -# ------------------------------------------------------------------------ - -"""Format owned C# changes with Roslyn and targeted StyleCop layout rules.""" - -import argparse -import difflib -import os -from pathlib import Path -import shutil -import subprocess -import tempfile -import xml.etree.ElementTree as ET - - -ROOT = Path(__file__).resolve().parents[1] -OWNED = ("Assets/Scripts/", "Assets/Tests/") -LAYOUT_RULES = ("SA1107", "SA1502", "SA1507", "SA1516") - - -def git_files(*args): - result = subprocess.check_output(["git", "-C", str(ROOT), *args, "-z"]) - return {os.fsdecode(name) for name in result.split(b"\0") if name} - - -def select_formatting(baseline, original, formatted): - """Keep formatter edits touching changed lines or a deletion boundary.""" - if baseline is None: - return formatted - # Existing files may predate the current CRLF policy. Keep their line-ending - # convention instead of converting the whole file or introducing mixed EOLs. - newline = b"\r\n" if original.count(b"\r\n") > original.count(b"\n") / 2 else b"\n" - formatted = formatted.replace(b"\r\n", b"\n").replace(b"\n", newline) - before = original.splitlines(keepends=True) - after = formatted.splitlines(keepends=True) - content = lambda lines: [line.rstrip(b"\r\n") for line in lines] - old_source = baseline.splitlines(keepends=True) - old_lines = content(old_source) - current_lines = content(before) - dirty = set() - boundaries = set() - for tag, old_start, _, start, end in difflib.SequenceMatcher( - None, old_lines, current_lines, autojunk=False).get_opcodes(): - if tag == "equal": - dirty.update(index for index in range(start, end) - if before[index].endswith(b"\n") != - old_source[old_start + index - start].endswith(b"\n")) - else: - dirty.update(range(start, end)) - if start == end: - boundaries.add(start) - result = [] - # Match surviving lines independently of spacing so an inserted member gap - # does not pull an adjacent, inherited indentation fix into the same edit. - tokens = lambda lines: [b"".join(line.split()) for line in lines] - for tag, start, end, target_start, target_end in difflib.SequenceMatcher( - None, tokens(before), tokens(after), autojunk=False).get_opcodes(): - if tag == "equal": - result.extend(after[target_start + index - start] if index in dirty else before[index] - for index in range(start, end)) - continue - touches_change = any(index in dirty for index in range(start, end)) - touches_change |= any(start <= boundary < end or start == end == boundary - for boundary in boundaries) - if start == end: - touches_change |= start in dirty or start - 1 in dirty - result.extend(after[target_start:target_end] if touches_change else before[start:end]) - return b"".join(result) - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--check", action="store_true", help="Fail instead of modifying files") - parser.add_argument("--verbose", action="store_true", help="Show detailed Roslyn/MSBuild diagnostics") - selection = parser.add_mutually_exclusive_group() - selection.add_argument("--base", help="Include C# changes since this Git ref") - selection.add_argument("--all", action="store_true", help="Include all owned C# sources") - parser.add_argument("paths", nargs="*", help="Format whole files at these repo-relative paths") - args = parser.parse_args() - if args.paths and (args.base or args.all): - parser.error("Explicit paths cannot be combined with --base or --all") - - if args.all or args.paths: - files = git_files("ls-files", "--cached", "--others", "--exclude-standard") - else: - files = git_files("diff", "--name-only", "--diff-filter=ACMR", args.base or "HEAD") - files |= git_files("ls-files", "--others", "--exclude-standard") - files = sorted(name for name in files - if name.startswith(OWNED) and name.endswith(".cs") and (ROOT / name).is_file() - and (ROOT / name).resolve().is_relative_to(ROOT)) - if args.paths: - requested = [(ROOT / path).resolve() for path in args.paths] - if any(not path.is_relative_to(ROOT) for path in requested): - parser.error("Paths must stay inside the repository") - files = [name for name in files if any( - (ROOT / name).resolve() == path or path in (ROOT / name).resolve().parents - for path in requested)] - if not files: - print("No owned C# changes to format.") - return 0 - - originals = {name: (ROOT / name).read_bytes() for name in files} - baselines = {} - if not args.all and not args.paths: - for name in files: - result = subprocess.run(["git", "-C", str(ROOT), "show", f"{args.base or 'HEAD'}:{name}"], - capture_output=True) - baselines[name] = result.stdout if result.returncode == 0 else None - - # A tiny format-only project avoids Unity-generated csproj files and needs - # no Unity install, game data or runtime third-party assemblies. Parsing - # both variants also checks whitespace inside #if PAL3 / #if PAL3A blocks. - workspace = ROOT.parent / "workspace" - temp_root = workspace / "Tooling" / "CodeStyle" if workspace.is_dir() else None - if temp_root is not None: - temp_root.mkdir(parents=True, exist_ok=True) - with tempfile.TemporaryDirectory(prefix="pal3-format-", dir=temp_root) as temporary: - # Format copies so --check is read-only and failures cannot leave partial edits. - source_root = Path(temporary) / "sources" - source_root.mkdir() - shutil.copy2(ROOT / ".editorconfig", source_root / ".editorconfig") - for name, source in originals.items(): - path = source_root / name - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(source) - project = ET.Element("Project", Sdk="Microsoft.NET.Sdk") - properties = ET.SubElement(project, "PropertyGroup") - for name, value in { - "TargetFramework": "net10.0", - "EnableDefaultCompileItems": "false", - "GenerateAssemblyInfo": "false", - "NuGetAudit": "false", - "DefineConstants": "$(PAL3_FORMAT_VARIANT);UNITY_EDITOR", - }.items(): - ET.SubElement(properties, name).text = value - items = ET.SubElement(project, "ItemGroup") - ET.SubElement(items, "PackageReference", Include="StyleCop.Analyzers", Version="1.3.180", PrivateAssets="all") - # The SDK discovers .editorconfig from each source path automatically. - # Adding it explicitly would register it twice in the Roslyn workspace. - for name in files: - ET.SubElement(items, "Compile", Include=str(source_root / name)) - project_path = Path(temporary) / "Formatting.csproj" - ET.ElementTree(project).write(project_path, encoding="utf-8", xml_declaration=True) - print(f"{'Checking' if args.check else 'Formatting'} {len(files)} C# files (PAL3 and PAL3A).", flush=True) - subprocess.run(["dotnet", "restore", str(project_path), "--verbosity", "quiet"], cwd=ROOT, check=True) - failed = False - for variant in ("PAL3", "PAL3A"): - for subcommand, extra in (("analyzers", ["--diagnostics", *LAYOUT_RULES]), ("whitespace", [])): - verbosity = "diagnostic" if args.verbose else "minimal" - command = ["dotnet", "format", subcommand, str(project_path), "--no-restore", "--verbosity", verbosity, *extra] - result = subprocess.run(command, cwd=ROOT, env={**os.environ, "PAL3_FORMAT_VARIANT": variant}) - failed |= result.returncode != 0 - if failed: - return 1 - changed = False - for name, original in originals.items(): - formatted = (source_root / name).read_bytes() - selected = select_formatting(baselines.get(name), original, formatted) - if selected == original: - continue - changed = True - if args.check: - print(f"Formatting required: {name}") - else: - (ROOT / name).write_bytes(selected) - return 1 if args.check and changed else 0 - - -if __name__ == "__main__": - try: - raise SystemExit(main()) - except (OSError, subprocess.CalledProcessError) as error: - raise SystemExit(str(error)) from error diff --git a/tools/tests/test-format-csharp.py b/tools/tests/test-format-csharp.py deleted file mode 100644 index 499c348d..00000000 --- a/tools/tests/test-format-csharp.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/env python3 -# ------------------------------------------------------------------------ -# Copyright (c) 2026, Jiaqi (0x7c13) Liu. All rights reserved. -# See LICENSE file in the project root for license information. -# ------------------------------------------------------------------------ - -"""Exercise layout fixes, change boundaries and read-only checks with Roslyn.""" - -import os -from pathlib import Path -import shutil -import runpy -import subprocess -import sys -import tempfile - - -ROOT = Path(__file__).resolve().parents[2] - - -def run(command, cwd, success=True): - result = subprocess.run(command, cwd=cwd, capture_output=True, text=True, timeout=180, - env={**os.environ, "TMPDIR": str(cwd)}) - if (result.returncode == 0) != success: - raise AssertionError(f"Unexpected exit {result.returncode}: {command}\n{result.stdout}\n{result.stderr}") - return result.stdout + result.stderr - - -def main(): - select = runpy.run_path(str(ROOT / "tools/format-csharp.py"))["select_formatting"] - legacy = b"int A;\r\n\r\nint B;\r\n" - changed = legacy.replace(b"int B", b"int B") - formatted = b"int A;\r\n\r\nint B;\r\n" - assert select(legacy, changed, formatted) == legacy - assert select(legacy, legacy, formatted) == legacy - assert select(None, changed, formatted) == formatted - assert select(legacy.replace(b"\r\n", b"\n"), changed.replace(b"\r\n", b"\n"), formatted) == legacy.replace(b"\r\n", b"\n") - assert select(legacy, legacy[:-2], formatted) == legacy, "Newly removed final newline was missed" - assert select(legacy, legacy.replace(b";\r\n\r\n", b";\r\n"), formatted) == legacy - workspace = ROOT.parent / "workspace" - temporary_root = workspace / "Tooling" / "CodeStyle" if workspace.is_dir() else None - if temporary_root is not None: - temporary_root.mkdir(parents=True, exist_ok=True) - with tempfile.TemporaryDirectory(prefix="pal3-format-test-", dir=temporary_root) as directory: - fixture = Path(directory) - (fixture / "tools").mkdir() - for name in (".editorconfig", "global.json", "tools/format-csharp.py"): - shutil.copy2(ROOT / name, fixture / name) - source = fixture / "Assets/Scripts/Effect layout.cs" - source.parent.mkdir(parents=True) - good = ("internal sealed class Layout\n{\n#if PAL3\n" - " public int AOne() => 1;\n\n public int ATwo() => 2;\n" - "#elif PAL3A\n public int BOne() => 1;\n\n public int BTwo() => 2;\n#endif\n}\n") - source.write_bytes(good.replace("\n", "\r\n").encode()) - plugin = fixture / "Assets/Plugins/Keep.cs" - plugin.parent.mkdir() - plugin.write_bytes(b"class Plugin{void One(){}void Two(){}}") - plugin_before = plugin.read_bytes() - run(["git", "init", "--quiet"], fixture) - run(["git", "add", "."], fixture) - run(["git", "-c", "user.name=Format fixture", "-c", "user.email=fixture@localhost", - "-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "Fixture baseline"], fixture) - base = run(["git", "rev-parse", "HEAD"], fixture).strip() - command = [sys.executable, "tools/format-csharp.py"] - source.write_bytes(good.replace(";\n\n", ";\n").replace("\n", "\r\n").encode()) - before = source.read_bytes() - output = run([*command, "--check"], fixture, success=False) - assert "Formatting required:" in output, output - assert source.read_bytes() == before, "Check mode modified the source" - run(command, fixture) - fixed = source.read_bytes() - assert b"AOne() => 1;\r\n\r\n" in fixed - assert b"BOne() => 1;\r\n\r\n" in fixed - run([*command, "--check", "--all"], fixture) - assert source.read_bytes() == fixed, "Formatting is not stable" - # A violation only in PAL3A must fail the same --base mode as PR CI. - source.write_bytes(fixed.replace(b"BOne() => 1;\r\n\r\n", b"BOne() => 1;\r\n")) - output = run([*command, "--check", "--base", base], fixture, success=False) - assert "Formatting required:" in output, output - run(command, fixture) - # Keep inherited formatting outside the edit, even in the same file. - legacy = fixture / "Assets/Scripts/Legacy.cs" - legacy.write_bytes(b"class Legacy\r\n{\r\n int Untouched;\r\n\r\n int Changed;\r\n}\r\n") - run(["git", "add", "."], fixture) - run(["git", "-c", "user.name=Format fixture", "-c", "user.email=fixture@localhost", - "-c", "commit.gpgsign=false", "commit", "--quiet", "-m", "Legacy baseline"], fixture) - legacy.write_bytes(legacy.read_bytes().replace(b"int Changed", b"int Changed")) - before = legacy.read_bytes() - run([*command, "--check"], fixture, success=False) - assert legacy.read_bytes() == before, "Changed-line check modified the source" - run(command, fixture) - assert b"int Untouched;" in legacy.read_bytes(), "Inherited formatting was changed" - assert b"int Changed;" in legacy.read_bytes(), "Modified line was not formatted" - run([*command, "--check"], fixture) - # Explicit paths still provide an intentional whole-file format/audit. - run([*command, "--check", str(legacy.relative_to(fixture))], fixture, success=False) - assert plugin.read_bytes() == plugin_before, "Third-party source was modified" - print("Passed: both variants fix member gaps, checks are read-only, --base checks PAL3A, inherited formatting and plugins stay untouched, explicit paths audit whole files.") - - -if __name__ == "__main__": - main()