Project_WL/Assets/WL/Combat/AttackRootMotion.cs

146 lines
7.3 KiB
C#

// ─────────────────────────────────────────────────────────────────────────────
// AttackRootMotion.cs — 공격 클립의 이동을 액터 이동으로 재현 (PD #789 · #791 · 2026-09-07)
//
// 모드(WLCombatMotionSettings.attackMoveMode):
// · FrameTable(기본 · #791): 클립별 "프레임 → 전진(cm)" 표(발 접지 실측으로 도출)를 클립 정규화 시간으로 재생.
// 발이 땅에 붙어 있는 구간엔 0, 발이 공중에 있거나 내딛는 구간에만 전진 → 발 슬라이딩이 없다.
// 힘민지 원본 `Interpolation` 이벤트(프레임 목록 + 프레임당 값)와 같은 개념을 WL 설정 SO 로 옮긴 것(FBX 이벤트 무수정).
// · ClipRootMotion(#789): animator.deltaPosition(RootT) 재생. Knight 클립은 상체 러닝(hips 33 cm 전후)이 루트에 섞여
// 접지 발이 30 cm 미끄러진다(2026-09-07 실측) → 기본에서 제외, 비교용으로 보존.
// · FixedStep(#762): AttackStepDriver + 원본 Set_Move.
// 적용: 공격 상태에서만 · NavMeshAgent.Move · 대상 stopDistance 관통 방지 · 조이스틱 입력 시 중단 없음(공격 중엔 입력 무시가 원본 동작).
// ─────────────────────────────────────────────────────────────────────────────
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
namespace WL.Combat
{
[DisallowMultipleComponent]
public sealed class AttackRootMotion : MonoBehaviour
{
private PCActor _pc;
private Animator _anim;
private NavMeshAgent _agent;
private WLCombatMotionSettings _cfg;
// FrameTable 상태
private int _tableClipHash; // 현재 재생 중인 표의 클립(상태) 식별
private int _tableLastFrame = -1; // 마지막으로 처리한 프레임 인덱스
private float _tableLastNorm = -1f;
// ── 검증용 정적 카운터 ──
public static int EntryCount, ApplyCount;
public static float LastFrameDelta, SwingAccum, RawAccum;
public static string LastInfo = "";
public static bool HandlesAttackMove(PCActor pc)
{
var cfg = WLCombatMotionSettings.Instance;
return pc != null && cfg != null && cfg.attackMoveMode != AttackMoveMode.FixedStep;
}
public static void Ensure(PCActor pc)
{
if (pc == null || pc.m_animation == null) return;
var cfg = WLCombatMotionSettings.Instance;
if (cfg == null) return;
var host = pc.m_animation.gameObject;
var rm = host.GetComponent<AttackRootMotion>();
if (rm == null) rm = host.AddComponent<AttackRootMotion>();
rm._pc = pc; rm._anim = pc.m_animation; rm._agent = pc.Get_Agent(); rm._cfg = cfg;
rm._anim.applyRootMotion = cfg.attackMoveMode == AttackMoveMode.ClipRootMotion;
}
private void OnDisable() { if (_anim != null) _anim.applyRootMotion = false; }
private void OnAnimatorMove()
{
EntryCount++;
if (_pc == null || _anim == null) return;
var cfg = _cfg != null ? _cfg : WLCombatMotionSettings.Instance;
if (cfg == null) return;
if (cfg.attackMoveMode != AttackMoveMode.ClipRootMotion)
{
if (_anim.applyRootMotion) _anim.applyRootMotion = false;
return;
}
if (!_anim.applyRootMotion) _anim.applyRootMotion = true;
if (!Gate(cfg)) return;
Vector3 d = _anim.deltaPosition; d.y = 0f;
RawAccum += d.magnitude;
if (d.sqrMagnitude < 1e-12f) return;
Apply(d * Mathf.Max(cfg.rootMotionScale, 0f), cfg, true);
}
private void LateUpdate()
{
if (_pc == null || _anim == null) return;
var cfg = _cfg != null ? _cfg : WLCombatMotionSettings.Instance;
if (cfg == null || cfg.attackMoveMode != AttackMoveMode.FrameTable) return;
if (!Gate(cfg)) { _tableLastFrame = -1; _tableClipHash = 0; return; }
var st = _anim.GetCurrentAnimatorStateInfo(0);
var ci = _anim.GetCurrentAnimatorClipInfo(0);
if (ci.Length == 0 || ci[0].clip == null) return;
var clip = ci[0].clip;
var table = cfg.FindFrameTable(clip.name);
if (table == null) return;
float norm = st.normalizedTime - Mathf.Floor(st.normalizedTime);
int totalFrames = Mathf.Max(1, Mathf.RoundToInt(clip.frameRate * clip.length));
int frame = Mathf.Clamp((int)(norm * totalFrames), 0, totalFrames);
int hash = st.fullPathHash;
if (hash != _tableClipHash || norm < _tableLastNorm - 0.5f) { _tableClipHash = hash; _tableLastFrame = frame - 1; }
_tableLastNorm = norm;
if (frame <= _tableLastFrame) return;
// 놓친 프레임까지 합산(프레임 드랍 보정 · 원본 Co_Interpolation 과 같은 규약)
float cm = 0f;
for (int f = _tableLastFrame + 1; f <= frame; f++) cm += table.ValueAt(f);
_tableLastFrame = frame;
if (cm <= 0f) return;
Vector3 fwd = _pc.transform.forward; fwd.y = 0f;
if (fwd.sqrMagnitude < 1e-6f) return;
Apply(fwd.normalized * (cm * 0.01f * Mathf.Max(cfg.frameTableScale, 0f)), cfg, false);
}
private bool Gate(WLCombatMotionSettings cfg)
{
if (_agent == null || !_agent.enabled || !_agent.isOnNavMesh) return false;
if (!_pc.WL_CanAttackStep()) return false;
if (DashDriver.IsDashingNow(_pc)) return false;
return true;
}
private void Apply(Vector3 d, WLCombatMotionSettings cfg, bool clampSpeed)
{
if (clampSpeed)
{
float maxStep = Mathf.Max(cfg.rootMotionMaxSpeed, 0.1f) * Mathf.Max(Time.deltaTime, 1e-4f);
if (d.magnitude > maxStep) d = d.normalized * maxStep;
}
if (!cfg.rootMotionAllowBackward)
{
Vector3 f = _pc.transform.forward; f.y = 0f;
if (f.sqrMagnitude > 1e-6f) { f.Normalize(); float along = Vector3.Dot(d, f); if (along < 0f) d -= f * along; }
}
var target = _pc.Get_Target();
if (target != null && !target.IsDead() && cfg.attackStepStopDistance > 0f)
{
Vector3 to = target.Get_position() - _pc.transform.position; to.y = 0f;
float dist = to.magnitude;
if (dist > 1e-4f)
{
Vector3 n = to / dist; float along = Vector3.Dot(d, n);
if (along > 0f && dist - along < cfg.attackStepStopDistance)
{ float allowed = Mathf.Max(dist - cfg.attackStepStopDistance, 0f); d -= n * (along - allowed); }
}
}
if (d.sqrMagnitude < 1e-12f) return;
_agent.Move(d);
ApplyCount++; LastFrameDelta = d.magnitude; SwingAccum += d.magnitude;
}
}
}