Files
Hasebe/Assets/Code/OfficeGame/BattleMode/Timeline/BattleSimulator.cs
T

443 lines
18 KiB
C#

using System;
using System.Collections.Generic;
using Code.Game.Entities;
using Code.OfficeGame.BattleMode.Actions;
using Code.OfficeGame.BattleMode.Effects;
using Code.OfficeGame.BattleMode.HitBoxes;
using KinematicCharacterController;
using UnityEngine;
namespace Code.OfficeGame.BattleMode.Timeline
{
public interface IBattleSimulationContext
{
float TickDelta { get; }
int CurrentSimFrame { get; }
int GetSlotIndex(EntityId entityId);
void SubmitAttack(
EntityId attackerId,
EntityId defenderId,
HitBoxPartType hitPart,
Vector3 hitWorldPosition,
EntityAttackedData attackedData);
void RecordHitboxVisual(BoxCollider box, Color color);
}
public sealed class BattleSimulator : IBattleSimulationContext
{
public const int TicksPerSecond = 60;
public const float FixedTickDelta = 1f / TicksPerSecond;
public const int MaxBakeFramesPerStep = 360; // 6 секунд предохранитель
private static readonly int VelocityForwardHash = Animator.StringToHash("VelocityForward");
private static readonly int VelocityRightHash = Animator.StringToHash("VelocityRight");
public float TickDelta => FixedTickDelta;
public int CurrentSimFrame { get; private set; }
public bool IsBaking { get; private set; }
private readonly Dictionary<BattleActionType, BattleAction> _actions;
private readonly List<EntityAttackedData> _pendingAttacks = new(8);
private readonly List<TimelineEvent> _frameEvents = new(8);
private readonly List<FrameHitboxVisual> _frameHitboxes = new(8);
private EntityProperties[] _entities;
private Transform[][] _entityBones;
private Dictionary<EntityId, int> _idToSlot;
private EntityActionSlotSnapshot[] _workingSlots;
public BattleSimulator(Dictionary<BattleActionType, BattleAction> actions)
{
_actions = actions;
}
public void BindEntities(EntityProperties[] entities)
{
_entities = entities;
_entityBones = new Transform[entities.Length][];
_idToSlot = new Dictionary<EntityId, int>(entities.Length);
_workingSlots = new EntityActionSlotSnapshot[entities.Length];
for (int i = 0; i < entities.Length; i++)
{
_idToSlot[entities[i].GetEntityId()] = i;
_entityBones[i] = CollectSkeletonTransforms(entities[i]);
}
}
private static Transform[] CollectSkeletonTransforms(EntityProperties properties)
{
if (properties.animator == null) return Array.Empty<Transform>();
var unique = new HashSet<Transform>();
var list = new List<Transform>(64);
foreach (var t in properties.animator.transform.GetComponentsInChildren<Transform>(includeInactive: true))
{
if (unique.Add(t)) list.Add(t);
}
return list.ToArray();
}
public int GetSlotIndex(EntityId entityId) =>
_idToSlot != null && _idToSlot.TryGetValue(entityId, out int slot) ? slot : -1;
public void SubmitAttack(
EntityId attackerId,
EntityId defenderId,
HitBoxPartType hitPart,
Vector3 hitWorldPosition,
EntityAttackedData attackedData)
{
int attackerSlot = GetSlotIndex(attackerId);
int defenderSlot = GetSlotIndex(defenderId);
if (attackerSlot < 0 || defenderSlot < 0) return;
// Заполняем ключи ДО проверки дубликатов
attackedData.AttackerId = attackerId;
attackedData.DefenderId = defenderId;
attackedData.HitBoxPartType = hitPart;
attackedData.HitWorldPosition = hitWorldPosition;
attackedData.Attacker = _entities[attackerSlot];
attackedData.Defender = _entities[defenderSlot];
for (int i = 0; i < _pendingAttacks.Count; i++)
{
if (_pendingAttacks[i].Equals(attackedData))
return;
}
_pendingAttacks.Add(attackedData);
}
public void RecordHitboxVisual(BoxCollider box, Color color)
{
if (box == null) return;
Transform t = box.transform;
Vector3 worldCenter = t.TransformPoint(box.center);
Vector3 worldSize = Vector3.Scale(box.size, t.lossyScale);
_frameHitboxes.Add(new FrameHitboxVisual
{
Matrix = Matrix4x4.TRS(worldCenter, t.rotation, worldSize),
Color = color
});
}
public BattleFrameSnapshot CaptureCurrentFrame(
int frame,
int interruptionStage,
EntityActionSlotSnapshot[] slots,
ulong readySlotsMask,
TimelineEvent[] events,
FrameHitboxVisual[] hitboxVisuals)
{
var entitySnaps = new EntityFrameSnapshot[_entities.Length];
for (int i = 0; i < _entities.Length; i++)
{
entitySnaps[i] = new EntityFrameSnapshot
{
EntityId = _entities[i].GetEntityId(),
PhysicsAndVisuals = EntitySnapshot.GetSnapshot(_entities[i], _entityBones[i]),
ActionSlot = slots[i].Clone()
};
}
return new BattleFrameSnapshot
{
Frame = frame,
InterruptionStage = interruptionStage,
Entities = entitySnaps,
ReadySlotsMask = readySlotsMask,
Events = events,
HitboxVisuals = hitboxVisuals
};
}
/// <summary>
/// Быстрое O(1) применение позы и позиции (для ползунка и воспроизведения).
/// </summary>
public void ApplyVisualFrameToWorld(BattleFrameSnapshot snapshot)
{
for (int i = 0; i < _entities.Length; i++)
{
EntitySnapshot.ApplyVisualOnly(_entities[i], _entityBones[i], snapshot.Entities[i].PhysicsAndVisuals);
}
Physics.SyncTransforms();
}
/// <summary>
/// Полное восстановление KCC + Mecanim + HP (для начала симуляции и перед Decider).
/// </summary>
public void RestoreSimulationToWorld(BattleFrameSnapshot snapshot)
{
for (int i = 0; i < _entities.Length; i++)
{
EntitySnapshot.RestoreForSimulation(_entities[i], _entityBones[i], snapshot.Entities[i].PhysicsAndVisuals);
}
Physics.SyncTransforms();
}
/// <summary>
/// Запекает будущее начиная со startFrame до завершения ВСЕХ активных действий.
/// При recordGhosts == true запекает слепки на старте (Stage 0) и на каждом кадре прерывания.
/// </summary>
public void BakeFrom(
BattleTimelineTrack track,
int startFrame,
bool recordGhosts,
int overrideSlot = -1,
EntityActionSlotSnapshot? overrideAction = null)
{
IsBaking = true;
try
{
track.TruncateAfter(startFrame);
var baseSnapshot = track.GetFrame(startFrame);
RestoreSimulationToWorld(baseSnapshot);
for (int i = 0; i < _entities.Length; i++)
{
_workingSlots[i] = (i == overrideSlot && overrideAction.HasValue)
? overrideAction.Value.Clone()
: baseSnapshot.Entities[i].ActionSlot.Clone();
_entities[i].EntityPreviewVisuals?.ClearAllGhosts();
}
// Stage 0: статичный слепок исходной точки (CommittedFrame)
if (recordGhosts)
{
for (int i = 0; i < _entities.Length; i++)
_entities[i].EntityPreviewVisuals?.BakeGhostAtStage(0, startFrame, isCompletingActor: false);
}
int currentStage = 0;
int steps = 0;
while (HasAnyActiveAction() && steps < MaxBakeFramesPerStep)
{
steps++;
CurrentSimFrame = startFrame + steps;
var nextFrameSnap = StepSingleFrame(CurrentSimFrame, ref currentStage, recordGhosts);
track.AppendFrame(nextFrameSnap);
}
}
finally
{
IsBaking = false;
RestoreSimulationToWorld(track.GetFrame(startFrame));
}
}
private bool HasAnyActiveAction()
{
for (int i = 0; i < _entities.Length; i++)
{
if (_entities[i].EntityHealth.IsDead) continue;
var slot = _workingSlots[i];
if (slot.ActionType != BattleActionType.None && slot.ActionData != null && !slot.ActionData.Finished)
return true;
}
return false;
}
private BattleFrameSnapshot StepSingleFrame(int frame, ref int currentStage, bool recordGhosts)
{
_pendingAttacks.Clear();
_frameEvents.Clear();
_frameHitboxes.Clear();
// ФАЗА 1: Логика тика действий (установка входов KCC, CrossFade, повороты)
for (int i = 0; i < _entities.Length; i++)
{
var entity = _entities[i];
if (entity.EntityHealth.IsDead) continue;
var slot = _workingSlots[i];
if (slot.ActionType == BattleActionType.None) continue;
_actions[slot.ActionType].Tick(FixedTickDelta, entity, slot.DecisionResult, slot.ActionData);
}
// ФАЗА 2: Единый шаг KCC для всех моторов одновременно
KinematicCharacterSystem.Simulate(
FixedTickDelta,
KinematicCharacterSystem.CharacterMotors,
KinematicCharacterSystem.PhysicsMovers);
// ФАЗА 3: Параметры BlendTree ходьбы + шаг аниматоров + RootMotion синхронизация каждый тик
for (int i = 0; i < _entities.Length; i++)
{
var entity = _entities[i];
UpdateAnimatorLocomotionParams(entity);
entity.animator.Update(FixedTickDelta);
if (entity.animator.applyRootMotion)
entity.SyncRootMotionToMotor();
}
// ФАЗА 4: Единый шаг PhysX и синхронизация костей/хитбоксов ДО проверок
Physics.Simulate(FixedTickDelta);
Physics.SyncTransforms();
// ФАЗА 5: Пост-проверка (хитбоксы и достижение точки уже по актуальным позициям!)
for (int i = 0; i < _entities.Length; i++)
{
var entity = _entities[i];
if (entity.EntityHealth.IsDead) continue;
var slot = _workingSlots[i];
if (slot.ActionType == BattleActionType.None) continue;
_actions[slot.ActionType].PostPhysicsTick(entity, slot.DecisionResult, slot.ActionData);
}
// ФАЗА 6: Одновременное разрешение всех попаданий кадра (честный Clash)
ResolvePendingAttacks(frame, currentStage);
// ФАЗА 7: Завершение окончившихся действий, смена стадии прерываний и запекание слепков
ulong readyMask = 0UL;
for (int i = 0; i < _entities.Length; i++)
{
var entity = _entities[i];
if (entity.EntityHealth.IsDead) continue;
var slot = _workingSlots[i];
if (slot.ActionType != BattleActionType.None && slot.ActionData.Finished)
{
BattleActionType completedType = slot.ActionType;
_actions[completedType].Finish(entity, slot.ActionData, slot.DecisionResult);
_workingSlots[i] = EntityActionSlotSnapshot.CreateNone(frame, completedType);
readyMask |= 1UL << i;
}
}
if (readyMask != 0UL)
{
currentStage++;
for (int i = 0; i < _entities.Length; i++)
{
bool isCompleting = (readyMask & (1UL << i)) != 0UL;
if (isCompleting)
{
_frameEvents.Add(new TimelineEvent(
frame,
i,
_entities[i].GetEntityId(),
TimelineEventType.ActionCompleted,
currentStage,
_entities[i].KinematicCharacterMotor.TransientPosition));
}
// Запекаем слепки ВСЕХ сущностей на кадре прерывания (завершивший — отдельным цветом)
if (recordGhosts && currentStage < EntityPreviewVisuals.MaxGhostStages)
{
_entities[i].EntityPreviewVisuals?.BakeGhostAtStage(
currentStage,
frame,
isCompleting);
}
}
}
return CaptureCurrentFrame(
frame,
currentStage,
_workingSlots,
readyMask,
_frameEvents.Count > 0 ? _frameEvents.ToArray() : Array.Empty<TimelineEvent>(),
_frameHitboxes.Count > 0 ? _frameHitboxes.ToArray() : Array.Empty<FrameHitboxVisual>());
}
private static void UpdateAnimatorLocomotionParams(EntityProperties entity)
{
if (entity.animator == null || entity.KinematicCharacterMotor == null) return;
var vel = entity.KinematicCharacterMotor.Velocity;
var t = entity.KinematicCharacterMotor.Transform;
entity.animator.SetFloat(VelocityForwardHash, Vector3.Project(vel, t.right).magnitude);
entity.animator.SetFloat(VelocityRightHash, Vector3.Project(vel, t.forward).magnitude);
}
private void ResolvePendingAttacks(int frame, int currentStage)
{
if (_pendingAttacks.Count == 0) return;
for (int i = 0; i < _pendingAttacks.Count; i++)
{
var request = _pendingAttacks[i];
int defenderSlot = GetSlotIndex(request.DefenderId);
if (defenderSlot < 0) continue;
var attacker = request.Attacker;
var defender = request.Defender;
if (defender.EntityHealth.IsDead) continue;
int damage = request.Damage;
foreach (var effect in attacker.Effects)
if (effect is AttackEffect atk) atk.Apply(ref damage);
foreach (var effect in defender.Effects)
if (effect is DefenseEffect def) def.Apply(ref damage);
defender.EntityHealth.GetDamage(damage, request.HitBoxPartType);
_frameEvents.Add(new TimelineEvent(
frame,
defenderSlot,
request.DefenderId,
TimelineEventType.HitLanded,
currentStage,
request.HitWorldPosition,
request.HitBoxPartType,
damage));
var oldSlot = _workingSlots[defenderSlot];
if (oldSlot.ActionType != BattleActionType.None)
{
_actions[oldSlot.ActionType].Finish(defender, oldSlot.ActionData, oldSlot.DecisionResult);
}
if (defender.EntityHealth.IsDead)
{
_workingSlots[defenderSlot] = EntityActionSlotSnapshot.CreateNone(frame, oldSlot.LastCompletedActionType);
_frameEvents.Add(new TimelineEvent(
frame,
defenderSlot,
request.DefenderId,
TimelineEventType.EntityDied,
currentStage,
defender.KinematicCharacterMotor.TransientPosition));
}
else
{
_workingSlots[defenderSlot] = new EntityActionSlotSnapshot
{
ActionType = request.ForcedDecisionResult.ActionType,
DecisionResult = request.ForcedDecisionResult,
ActionData = request.ForcedActionData,
LastCompletedActionType = oldSlot.LastCompletedActionType,
ActionStartFrame = frame,
EstimatedEndFrame = frame + request.ForcedActionData.TotalFrames
};
_frameEvents.Add(new TimelineEvent(
frame,
defenderSlot,
request.DefenderId,
TimelineEventType.Staggered,
currentStage,
defender.KinematicCharacterMotor.TransientPosition));
}
}
_pendingAttacks.Clear();
}
}
}