Great timeline system (Age of AI WON)

This commit is contained in:
ThomasCharester committed 2026-11-20 01:36:01 +03:00
1 parent 2ce0391c16
commit e312131725
182 files changed
+380070 -470221

No files matched your search

@@ -1,3 +1,4 @@
using System.Collections.Generic;
using UnityEngine;
namespace Code.OfficeGame.BattleMode.Actions
@@ -6,18 +7,20 @@ namespace Code.OfficeGame.BattleMode.Actions
{
public int CurrentFrame;
public int TransitionFrames;
public Quaternion StartRotation;
public HashSet<EntityId> HitEntities = new();
public override BattleActionData GetSnapshot()
{
var snapshot = new AttackBattleActionData()
return new AttackBattleActionData
{
TotalFrames = TotalFrames,
Finished = Finished,
CurrentFrame = CurrentFrame,
TransitionFrames = TransitionFrames,
StartRotation = StartRotation,
HitEntities = new HashSet<EntityId>(HitEntities)
};
return snapshot;
}
public override void RestoreSnapshot(BattleActionData snapshot)
@@ -28,6 +31,8 @@ namespace Code.OfficeGame.BattleMode.Actions
Finished = neededSnapshot.Finished;
CurrentFrame = neededSnapshot.CurrentFrame;
TransitionFrames = neededSnapshot.TransitionFrames;
StartRotation = neededSnapshot.StartRotation;
HitEntities = new HashSet<EntityId>(neededSnapshot.HitEntities);
}
}
}
@@ -1,6 +1,5 @@
using System.Linq;
using Code.Game.Entities;
using Code.Infrastructure.Particles;
using Code.Infrastructure.Utils;
using Code.OfficeGame.BattleMode.Actions.Deciders;
using Code.OfficeGame.BattleMode.HitBoxes;
@@ -11,21 +10,29 @@ namespace Code.OfficeGame.BattleMode.Actions.Attacks
{
public class BattleActionPlayerAttackMMA : BattleAction
{
private AttackActionConfig _attackData;
private IParticleService _particleService;
public int EntryStateHash => Animator.StringToHash("WalkBlend");
private readonly AttackActionConfig _attackData;
private static readonly int EntryStateHash = Animator.StringToHash("WalkBlend");
public BattleActionPlayerAttackMMA(MultipleConfig<BattleActionParameters> attackData,
IParticleService particleService)
public BattleActionPlayerAttackMMA(MultipleConfig<BattleActionParameters> attackData)
{
_particleService = particleService;
_attackData = (AttackActionConfig)
attackData.Configs.SingleOrDefault(x => x.ActionType == ActionType);
_attackData = (AttackActionConfig)attackData.Configs.SingleOrDefault(x => x.ActionType == ActionType);
}
public override BattleActionType ActionType => BattleActionType.PlayerAttackMMA;
public override DeciderType DeciderType => DeciderType.Rotation;
public override void Tick(float tickDelta,
public override BattleActionData MountAndGetFrames(EntityProperties entity, BattleActionDecisionResult result)
{
return new AttackBattleActionData
{
TotalFrames = _attackData.TotalFrames,
TransitionFrames = _attackData.TransitionFrames,
StartRotation = entity.KinematicCharacterMotor.TransientRotation
};
}
public override void Tick(
float tickDelta,
EntityProperties entity,
BattleActionDecisionResult battleActionDecisionResult,
BattleActionData battleActionData)
@@ -41,42 +48,50 @@ namespace Code.OfficeGame.BattleMode.Actions.Attacks
{
actionData.TransitionFrames = _attackData.TransitionFrames;
actionData.TotalFrames = _attackData.TotalFrames;
actionData.StartRotation = entity.KinematicCharacterMotor.TransientRotation;
actionData.HitEntities.Clear();
entity.SyncRootMotionToMotor();
var entityAnimator = entity.animator;
entityAnimator.applyRootMotion = true;
var transitionTime = actionData.TransitionFrames * BattleTimeline.TickDelta;
entityAnimator.CrossFadeInFixedTime(_attackData.StateHash, transitionTime);
entityAnimator.CrossFadeInFixedTime(_attackData.StateHash, actionData.TransitionFrames * BattleTimeline.TickDelta);
}
else if (actionData.CurrentFrame <= actionData.TransitionFrames
&& actionData.TransitionFrames > 0)
else if (actionData.CurrentFrame <= actionData.TransitionFrames && actionData.TransitionFrames > 0)
{
float t = (float)actionData.CurrentFrame / actionData.TransitionFrames;
Quaternion transientRotation = Quaternion.Lerp(
entity.KinematicCharacterMotor.TransientRotation,
deciderResult.Rotation,
t);
entity.KinematicCharacterMotor.SetRotation(transientRotation);
Quaternion rot = Quaternion.Slerp(actionData.StartRotation, deciderResult.Rotation, t);
entity.KinematicCharacterMotor.SetRotation(rot);
}
actionData.CurrentFrame++;
}
public override void PostPhysicsTick(
EntityProperties entity,
BattleActionDecisionResult battleActionDecisionResult,
BattleActionData battleActionData)
{
if (battleActionData is not AttackBattleActionData actionData) return;
if (actionData.CurrentFrame >= _attackData.HitboxStartFrame
&& actionData.CurrentFrame <= _attackData.HitboxEndFrame)
{
entity.EntityHitBoxes.CheckHitsForCurrentFrame(OnEnemyHit, _attackData.AttackingBodyPart);
entity.EntityHitBoxes.CheckHitsForCurrentFrame(OnEnemyHit, HitBoxPartType.RAnkle);
entity.EntityHitBoxes.CheckHitsForCurrentFrame(
SimContext,
(attackerCol, enemyCol, hitPart) => OnEnemyHit(actionData, attackerCol, enemyCol, hitPart),
_attackData.AttackingBodyPart);
entity.EntityHitBoxes.CheckHitsForCurrentFrame(
SimContext,
(attackerCol, enemyCol, hitPart) => OnEnemyHit(actionData, attackerCol, enemyCol, hitPart),
HitBoxPartType.RAnkle);
}
if (actionData.CurrentFrame >= actionData.TotalFrames)
{
var entityAnimator = entity.animator;
entity.SyncRootMotionToMotor();
entityAnimator.applyRootMotion = false;
entityAnimator.Play(EntryStateHash, 0, 0f);
entityAnimator.Update(0f);
@@ -84,59 +99,55 @@ namespace Code.OfficeGame.BattleMode.Actions.Attacks
}
}
public override DeciderType DeciderType => DeciderType.Rotation;
public override BattleActionData MountAndGetFrames(EntityProperties entity, BattleActionDecisionResult result)
{
return new AttackBattleActionData() { TotalFrames = _attackData.TotalFrames };
}
public override void Finish(EntityProperties entity, BattleActionData actionData, BattleActionDecisionResult result)
{
// var entityAnimator = entity.animator;
//
// entity.SyncRootMotionToMotor();
//
// entityAnimator.Play(EntryStateHash, 0, 0f);
// entityAnimator.Update(0f);
entity.animator.applyRootMotion = false;
}
private void OnEnemyHit(Collider attacker, Collider enemyCollider)
{
var defenderId = enemyCollider.GetComponentInParent<EntityProperties>().GetEntityId();
var attackerId = attacker.GetComponentInParent<EntityProperties>().GetEntityId();
Vector3 attackerDirection = attacker.transform.TransformDirection(_attackData.LocalKnockbackDirection);
attackerDirection.y = 0f;
attackerDirection.Normalize();
var actionData = new StuggerActionData
private void OnEnemyHit(
AttackBattleActionData attackData,
Collider attacker,
Collider enemyCollider,
HitBoxPartType hitPart)
{
var defenderProps = enemyCollider.GetComponentInParent<EntityProperties>();
var attackerProps = attacker.GetComponentInParent<EntityProperties>();
if (defenderProps == null || attackerProps == null) return;
var defenderId = defenderProps.GetEntityId();
var attackerId = attackerProps.GetEntityId();
// Защита от многокадрового урона по одной цели за один удар
if (!attackData.HitEntities.Add(defenderId)) return;
Vector3 knockbackDir = attackerProps.KinematicCharacterMotor.Transform
.TransformDirection(_attackData.LocalKnockbackDirection);
knockbackDir.y = 0f;
if (knockbackDir.sqrMagnitude > 0.0001f) knockbackDir.Normalize();
var forcedActionData = new StuggerActionData
{
TotalFrames = _attackData.StuggerFrames,
CurrentFrame = 0,
KnockbackDirection = attackerDirection,
KnockbackDirection = knockbackDir,
KnockbackSpeed = _attackData.KnockbackSpeed,
KnockbackDistance = _attackData.KnockbackDistance
};
var decisionResult = new AsIsBattleActionDeciderResult { ActionType = BattleActionType.Stugger };
EntityAttackedData attackedData = new()
var forcedDecision = new AsIsBattleActionDeciderResult
{
ForcedActionData = actionData,
ForcedDecisionResult = decisionResult,
ActionType = BattleActionType.Stugger,
ResultCode = BattleActionDecisionResultCode.Decided
};
var attackedData = new EntityAttackedData
{
ForcedActionData = forcedActionData,
ForcedDecisionResult = forcedDecision,
Damage = _attackData.Damage
};
battleTimeline.AttackRequest(attackerId, defenderId, attackedData);
//battleTimeline.ForceDecideAction(originEntityId, actionData, decisionResult);
if(!BattleTimeline.IsSilentSimulation)
_particleService.EmitOneShot(
new ParticlePartitionIDPair(ParticlePartition.HitParticles, 0),
15,
enemyCollider.transform.position,
Quaternion.identity);
SimContext.SubmitAttack(attackerId, defenderId, hitPart, enemyCollider.transform.position, attackedData);
}
}
}
@@ -5,13 +5,21 @@ namespace Code.OfficeGame.BattleMode.Actions
{
public abstract class BattleAction
{
public abstract void Tick(float tickDelta, EntityProperties entity, BattleActionDecisionResult battleActionDecisionResult, BattleActionData battleActionData);
public abstract BattleActionType ActionType { get; }
public abstract DeciderType DeciderType { get; }
public abstract BattleActionData MountAndGetFrames(EntityProperties entity, BattleActionDecisionResult result);
public abstract void Finish(EntityProperties entity, BattleActionData actionData, BattleActionDecisionResult result);
protected BattleTimeline battleTimeline;
public void SetBattleTimeline(BattleTimeline battleTimeline) => this.battleTimeline = battleTimeline;
protected IBattleSimulationContext SimContext { get; private set; }
public void SetSimulationContext(IBattleSimulationContext context) => SimContext = context;
public abstract BattleActionData MountAndGetFrames(EntityProperties entity, BattleActionDecisionResult result);
public abstract void Tick(float tickDelta, EntityProperties entity, BattleActionDecisionResult battleActionDecisionResult, BattleActionData battleActionData);
/// <summary>
/// Вызывается ПОСЛЕ KCC.Simulate, Animator.Update и Physics.SyncTransforms.
/// Здесь проверяются хитбоксы и достижение целевой позиции.
/// </summary>
public virtual void PostPhysicsTick(EntityProperties entity, BattleActionDecisionResult battleActionDecisionResult, BattleActionData battleActionData) { }
public abstract void Finish(EntityProperties entity, BattleActionData actionData, BattleActionDecisionResult result);
}
}
@@ -11,14 +11,14 @@ namespace Code.OfficeGame.BattleMode.Actions
private const float StoppingDistance = 0.15f;
private const float RotateDistance = 1f;
private const float NavMeshSampleRadius = 1.5f;
private const float TurnSpeedDegPerSec = 720f;
private const float TurnSpeedDegPerSec = 720f;
private const int StuckExtraFrames = 90;
private int MoveStateHash => Animator.StringToHash("WalkBlend");
private static readonly int MoveStateHash = Animator.StringToHash("WalkBlend");
public override BattleActionType ActionType => BattleActionType.Move;
public override DeciderType DeciderType => DeciderType.Position;
// Ультра супер мега конструкция для проверки и утверждения точной позиции. Но не работающая.
public override BattleActionData MountAndGetFrames(EntityProperties entity, BattleActionDecisionResult result)
{
MovementBattleActionData data = new();
@@ -29,21 +29,17 @@ namespace Code.OfficeGame.BattleMode.Actions
Vector3 toTargetXZ = targetPos - startPos;
toTargetXZ.y = 0f;
Debug.DrawLine(startPos, targetPos, Color.red, 5f);
float distanceXZ = toTargetXZ.magnitude;
if (distanceXZ <= StoppingDistance)
if (toTargetXZ.magnitude <= StoppingDistance)
{
data.IsRotateOnly = true;
data.Corners = null;
float angle = Quaternion.Angle(entity.KinematicCharacterMotor.TransientRotation, positionDecisionResult.Rotation);
if (angle < 1f)
{
data.TotalFrames = 0;
data.Finished = true;
}
else
{
@@ -60,6 +56,7 @@ namespace Code.OfficeGame.BattleMode.Actions
if (!hasStart || !hasTarget)
{
data.TotalFrames = 0;
data.Finished = true;
return data;
}
@@ -71,13 +68,12 @@ namespace Code.OfficeGame.BattleMode.Actions
data.Corners = new[] { startPos, validTarget };
data.CurrentCornerIndex = 1;
data.TotalFrames = CalculatePathFrames(data.Corners, entity.MovementController);
return data;
}
NavMeshPath path = new();
if (NavMesh.CalculatePath(validStart, validTarget, NavMesh.AllAreas, path)
&& path.status == NavMeshPathStatus.PathComplete
if (NavMesh.CalculatePath(validStart, validTarget, NavMesh.AllAreas, path)
&& path.status == NavMeshPathStatus.PathComplete
&& path.corners.Length > 1)
{
path.corners[0] = startPos;
@@ -90,43 +86,31 @@ namespace Code.OfficeGame.BattleMode.Actions
else
{
data.TotalFrames = 0;
data.Finished = true;
}
return data;
}
public override void Finish(EntityProperties entity, BattleActionData actionData, BattleActionDecisionResult result)
{
entity.KinematicCharacterMotor.BaseVelocity = Vector3.zero;
entity.MovementController.Freeze = true;
entity.MovementController.InternalVelocityAdd = Vector3.zero;
entity.MovementController.MoveInputVector = Vector3.zero;
Debug.Log($"{entity.GetEntityId()} is frozen");
}
public override void Tick(
float tickDelta,
EntityProperties entity,
BattleActionDecisionResult battleActionDecisionResult,
float tickDelta,
EntityProperties entity,
BattleActionDecisionResult battleActionDecisionResult,
BattleActionData battleActionData)
{
if (battleActionData is not MovementBattleActionData movementActionData
|| battleActionDecisionResult is not PositionBattleActionDeciderResult positionDecisionResult)
if (battleActionData is not MovementBattleActionData movementActionData
|| battleActionDecisionResult is not PositionBattleActionDeciderResult positionDecisionResult)
{
battleActionData.Finished = true;
return;
}
var movementController = entity.MovementController;
movementController.Freeze = false;
movementActionData.CurrentFrame++;
if (movementActionData.IsRotateOnly)
{
movementActionData.CurrentFrame++;
float angle = Quaternion.Angle(movementController.Motor.TransientRotation, positionDecisionResult.Rotation);
int framesLeft = Mathf.Max(1, movementActionData.TotalFrames - movementActionData.CurrentFrame + 1);
float stepAngle = angle / framesLeft;
@@ -134,11 +118,10 @@ namespace Code.OfficeGame.BattleMode.Actions
Quaternion nextRot = Quaternion.RotateTowards(
movementController.Motor.TransientRotation,
positionDecisionResult.Rotation,
stepAngle
);
stepAngle);
entity.KinematicCharacterMotor.SetRotation(nextRot);
StopMovementAndFinish(movementController);
StopMovementInputs(movementController);
if (movementActionData.CurrentFrame >= movementActionData.TotalFrames || angle <= 0.5f)
{
@@ -152,7 +135,7 @@ namespace Code.OfficeGame.BattleMode.Actions
if (movementActionData.Corners == null || movementActionData.CurrentCornerIndex >= movementActionData.Corners.Length)
{
entity.KinematicCharacterMotor.SetRotation(positionDecisionResult.Rotation);
StopMovementAndFinish(movementController);
StopMovementInputs(movementController);
battleActionData.Finished = true;
return;
}
@@ -160,28 +143,17 @@ namespace Code.OfficeGame.BattleMode.Actions
if (!movementActionData.WasStarted)
{
movementActionData.WasStarted = true;
float transitionDurationSeconds = 10 * BattleTimeline.TickDelta;
entity.animator.CrossFadeInFixedTime(MoveStateHash, transitionDurationSeconds);
entity.animator.applyRootMotion = false;
entity.animator.CrossFadeInFixedTime(MoveStateHash, 10 * BattleTimeline.TickDelta);
}
Vector3 currentPos = entity.KinematicCharacterMotor.TransientPosition;
while (movementActionData.CurrentCornerIndex < movementActionData.Corners.Length)
{
Vector3 toCorner = movementActionData.Corners[movementActionData.CurrentCornerIndex] - currentPos;
toCorner.y = 0f;
if (toCorner.sqrMagnitude <= StoppingDistance * StoppingDistance)
movementActionData.CurrentCornerIndex++;
else
break;
}
AdvanceCorners(movementActionData, currentPos);
if (movementActionData.CurrentCornerIndex >= movementActionData.Corners.Length)
{
entity.KinematicCharacterMotor.SetRotation(positionDecisionResult.Rotation);
StopMovementAndFinish(movementController);
StopMovementInputs(movementController);
battleActionData.Finished = true;
return;
}
@@ -197,7 +169,6 @@ namespace Code.OfficeGame.BattleMode.Actions
bool preLastPoint = isLastCorner && distance < RotateDistance;
float maxStep = movementController.MaxStableMoveSpeed * tickDelta;
float inputMagnitude = (isLastCorner && distance < maxStep && maxStep > 0f)
? distance / maxStep
: 1f;
@@ -213,22 +184,62 @@ namespace Code.OfficeGame.BattleMode.Actions
MoveVector = moveNormal * inputMagnitude,
Look = lookRotation
};
movementController.SetInputs(ref aiInputs);
}
public override void PostPhysicsTick(
EntityProperties entity,
BattleActionDecisionResult battleActionDecisionResult,
BattleActionData battleActionData)
{
if (battleActionData.Finished
|| battleActionData is not MovementBattleActionData movementActionData
|| battleActionDecisionResult is not PositionBattleActionDeciderResult positionDecisionResult
|| movementActionData.IsRotateOnly
|| movementActionData.Corners == null)
return;
Vector3 postMovePos = entity.KinematicCharacterMotor.TransientPosition;
AdvanceCorners(movementActionData, postMovePos);
Vector3 postMovePos = movementController.Motor.TransientPosition;
Vector3 toFinal = movementActionData.Corners[^1] - postMovePos;
toFinal.y = 0f;
if (isLastCorner && toFinal.sqrMagnitude <= StoppingDistance * StoppingDistance)
bool arrived = movementActionData.CurrentCornerIndex >= movementActionData.Corners.Length
|| toFinal.sqrMagnitude <= StoppingDistance * StoppingDistance;
bool stuckTimeout = movementActionData.CurrentFrame > movementActionData.TotalFrames + StuckExtraFrames;
if (arrived || stuckTimeout)
{
entity.KinematicCharacterMotor.SetRotation(positionDecisionResult.Rotation);
StopMovementAndFinish(movementController);
StopMovementInputs(entity.MovementController);
battleActionData.Finished = true;
}
}
private void StopMovementAndFinish(MovementController movementController)
public override void Finish(EntityProperties entity, BattleActionData actionData, BattleActionDecisionResult result)
{
entity.KinematicCharacterMotor.BaseVelocity = Vector3.zero;
entity.MovementController.Freeze = true;
entity.MovementController.InternalVelocityAdd = Vector3.zero;
entity.MovementController.MoveInputVector = Vector3.zero;
}
private static void AdvanceCorners(MovementBattleActionData data, Vector3 pos)
{
while (data.CurrentCornerIndex < data.Corners.Length)
{
Vector3 toCorner = data.Corners[data.CurrentCornerIndex] - pos;
toCorner.y = 0f;
if (toCorner.sqrMagnitude <= StoppingDistance * StoppingDistance)
data.CurrentCornerIndex++;
else
break;
}
}
private static void StopMovementInputs(MovementController movementController)
{
var emptyInputs = new AICharacterInputs
{
@@ -239,13 +250,11 @@ namespace Code.OfficeGame.BattleMode.Actions
movementController.Motor.BaseVelocity = Vector3.zero;
}
private int CalculatePathFrames(Vector3[] corners, MovementController movementController)
private static int CalculatePathFrames(Vector3[] corners, MovementController movementController)
{
if (corners == null || corners.Length < 2)
return 0;
if (corners == null || corners.Length < 2) return 0;
float totalDistanceXZ = 0f;
for (int i = 1; i < corners.Length; i++)
{
Vector3 segment = corners[i] - corners[i - 1];
@@ -256,10 +265,7 @@ namespace Code.OfficeGame.BattleMode.Actions
float effectiveDistance = Mathf.Max(0f, totalDistanceXZ - StoppingDistance);
float stepPerFrame = movementController.MaxStableMoveSpeed * BattleTimeline.TickDelta;
if (stepPerFrame <= 0.0001f)
return 0;
return Mathf.Max(1, Mathf.CeilToInt(effectiveDistance / stepPerFrame));
return stepPerFrame <= 0.0001f ? 0 : Mathf.Max(1, Mathf.CeilToInt(effectiveDistance / stepPerFrame));
}
}
}
@@ -6,6 +6,7 @@ using Code.OfficeGame.BattleMode.Actions.Player;
using Code.OfficeGame.BattleMode.Marker;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
namespace Code.OfficeGame.BattleMode.Actions.Deciders
@@ -167,6 +168,10 @@ namespace Code.OfficeGame.BattleMode.Actions.Deciders
private void SelectPosition(InputAction.CallbackContext input)
{
// Эта херовина не позволит кликнуть, когда курсор на UI. Случай пока невозможный, но сделаем допущение
if (EventSystem.current != null && EventSystem.current.IsPointerOverGameObject())
return;
_targetPosition = _lastViewedPosition;
_playerLockedDecisionMarker.MoveMarker(_targetPosition);
@@ -6,6 +6,7 @@ using Code.OfficeGame.BattleMode.Actions.Player;
using Code.OfficeGame.BattleMode.Marker;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
namespace Code.OfficeGame.BattleMode.Actions.Deciders
@@ -151,6 +152,10 @@ namespace Code.OfficeGame.BattleMode.Actions.Deciders
private void SelectRotation(InputAction.CallbackContext input)
{
// Эта херовина не позволит кликнуть, когда курсор на UI. Случай пока невозможный, но сделаем допущение
if (EventSystem.current != null && EventSystem.current.IsPointerOverGameObject())
return;
_playerLockedDecisionMarker.MoveMarker(_entityPosition);
_playerLockedDecisionMarker.transform.rotation = _targetRotation;
_playerLockedDecisionMarker.Toggle(true);
@@ -5,178 +5,239 @@ namespace Code.OfficeGame.BattleMode.Actions
{
public class EntityPreviewVisuals : MonoBehaviour
{
[Header("Материалы для MKToon")]
[Tooltip("Полупрозрачный материал для статичного слепка в точке снапшота")]
[SerializeField]
private Material snapshotGhostMaterial;
public const int MaxGhostStages = 5; // 0 = Commit + до 4 прерываний
[Tooltip(
"Опционально: материал для самой движущейся модели во время превью (если null — меняется только Rim/Tint)")]
[SerializeField]
private Material activePreviewMaterial;
[Header("Материалы MKToon")]
[SerializeField] private Material snapshotGhostMaterial;
[SerializeField] private Material activePreviewMaterial;
[Header("Настройки подсветки MKToon (если activePreviewMaterial не задан)")] [SerializeField]
private Color previewAlbedoTint = new Color(0.6f, 0.85f, 1f, 1f);
[Header("Цвета проекции по стадиям прерываний")]
[SerializeField] private Color[] stageProjectionTints =
{
new(0.55f, 0.85f, 1.0f, 1f), // Stage 0: до первого прерывания (голубой)
new(1.0f, 0.85f, 0.35f, 1f), // Stage 1: после 1-го прерывания (жёлтый)
new(1.0f, 0.55f, 0.25f, 1f), // Stage 2: после 2-го прерывания (оранжевый)
new(0.95f, 0.3f, 0.5f, 1f), // Stage 3+: 3+ прерываний (малиновый)
};
[SerializeField, ColorUsage(true, true)]
private Color previewRimColor = new Color(0f, 1.5f, 2f, 1f);
[Header("Цвета статичных слепков")]
[SerializeField] private Color defaultGhostTint = new(0.6f, 0.85f, 1f, 0.35f);
[SerializeField] private Color completedActorGhostColor = new(0.2f, 1f, 0.45f, 0.65f);
private sealed class GhostSlot
{
public GameObject Root;
public Mesh[] BakedMeshes;
public MeshFilter[] Filters;
public MeshRenderer[] Renderers;
public int TriggerFrame = int.MaxValue;
public bool IsActiveInBake;
}
private SkinnedMeshRenderer[] _skinnedRenderers;
private MeshRenderer[] _meshRenderers;
// Кэш оригинальных материалов
private readonly Dictionary<Renderer, Material[]> _originalMaterials = new();
// Пул объектов для статичного слепка (чтобы не делать Instantiate и new Mesh каждый цикл превью)
private GameObject _snapshotGhostRoot;
private readonly List<Mesh> _bakedMeshes = new();
private readonly List<MeshFilter> _ghostMeshFilters = new();
private readonly List<MeshRenderer> _ghostMeshRenderers = new();
private GhostSlot[] _ghostSlots;
private MaterialPropertyBlock _propBlock;
private static readonly int AlbedoColorId = Shader.PropertyToID("_AlbedoColor");
private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor");
private static readonly int RimColorId = Shader.PropertyToID("_RimColor");
private bool _isPreviewLookApplied;
private int _currentAppliedStage = -1;
private void Awake()
{
_propBlock = new MaterialPropertyBlock();
_skinnedRenderers = GetComponentsInChildren<SkinnedMeshRenderer>();
_meshRenderers = GetComponentsInChildren<MeshRenderer>();
// Сохраняем родные материалы MKToon
foreach (var sr in _skinnedRenderers)
_originalMaterials[sr] = sr.sharedMaterials;
foreach (var mr in _meshRenderers)
_originalMaterials[mr] = mr.sharedMaterials;
foreach (var sr in _skinnedRenderers) _originalMaterials[sr] = sr.sharedMaterials;
foreach (var mr in _meshRenderers) _originalMaterials[mr] = mr.sharedMaterials;
InitializeGhostPool();
}
private void InitializeGhostPool()
{
_snapshotGhostRoot = new GameObject($"{gameObject.name}_SnapshotGhost");
_snapshotGhostRoot.SetActive(false);
_ghostSlots = new GhostSlot[MaxGhostStages];
for (int s = 0; s < MaxGhostStages; s++)
{
var root = new GameObject($"{gameObject.name}_GhostStage_{s}");
root.SetActive(false);
int count = _skinnedRenderers.Length;
var slot = new GhostSlot
{
Root = root,
BakedMeshes = new Mesh[count],
Filters = new MeshFilter[count],
Renderers = new MeshRenderer[count]
};
for (int i = 0; i < count; i++)
{
var partGo = new GameObject($"Part_{i}");
partGo.transform.SetParent(root.transform, false);
var mf = partGo.AddComponent<MeshFilter>();
var mr = partGo.AddComponent<MeshRenderer>();
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
var mesh = new Mesh { name = $"BakedGhost_{s}_{i}" };
mf.sharedMesh = mesh;
slot.BakedMeshes[i] = mesh;
slot.Filters[i] = mf;
slot.Renderers[i] = mr;
}
_ghostSlots[s] = slot;
}
}
public void ClearAllGhosts()
{
if (_ghostSlots == null) return;
foreach (var slot in _ghostSlots)
{
slot.IsActiveInBake = false;
slot.TriggerFrame = int.MaxValue;
if (slot.Root != null) slot.Root.SetActive(false);
}
}
/// <summary>
/// Запекает статичный слепок во время BakeFrom (в точке Commit или в точке прерывания).
/// </summary>
public void BakeGhostAtStage(int stageIndex, int triggerFrame, bool isCompletingActor)
{
if (snapshotGhostMaterial == null || stageIndex < 0 || stageIndex >= MaxGhostStages)
return;
var slot = _ghostSlots[stageIndex];
slot.TriggerFrame = triggerFrame;
slot.IsActiveInBake = true;
slot.Root.transform.SetPositionAndRotation(transform.position, transform.rotation);
Color ghostColor = isCompletingActor
? completedActorGhostColor
: GetStageColor(stageIndex, alphaOverride: defaultGhostTint.a);
// Создаём легковесные меш-объекты под каждый SkinnedMeshRenderer персонажа
for (int i = 0; i < _skinnedRenderers.Length; i++)
{
var partGo = new GameObject($"GhostPart_{i}");
partGo.transform.SetParent(_snapshotGhostRoot.transform, false);
var sr = _skinnedRenderers[i];
sr.BakeMesh(slot.BakedMeshes[i]);
var mf = partGo.AddComponent<MeshFilter>();
var mr = partGo.AddComponent<MeshRenderer>();
var ghostTransform = slot.Filters[i].transform;
ghostTransform.SetPositionAndRotation(sr.transform.position, sr.transform.rotation);
// Отключаем тени у призрака для чистоты картинки и производительности
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
int subMeshCount = Mathf.Max(1, slot.BakedMeshes[i].subMeshCount);
var mats = new Material[subMeshCount];
for (int m = 0; m < subMeshCount; m++) mats[m] = snapshotGhostMaterial;
slot.Renderers[i].sharedMaterials = mats;
var bakedMesh = new Mesh { name = $"BakedGhostMesh_{i}" };
mf.sharedMesh = bakedMesh;
_bakedMeshes.Add(bakedMesh);
_ghostMeshFilters.Add(mf);
_ghostMeshRenderers.Add(mr);
slot.Renderers[i].GetPropertyBlock(_propBlock);
_propBlock.SetColor(AlbedoColorId, ghostColor);
_propBlock.SetColor(BaseColorId, ghostColor);
slot.Renderers[i].SetPropertyBlock(_propBlock);
}
slot.Root.SetActive(false);
}
/// <summary>
/// Вызывается перед стартом цикла PreviewBattleLoopAsync (в момент снятия снапшота)
/// Синхронизирует видимость слепков и цвет проекции для текущего кадра ползунка.
/// Для прошлых кадров (viewFrame <= committedFrame) проекция автоматически выключается!
/// </summary>
public void ShowPreviewState(bool spawnStaticSnapshotGhost = true)
public void UpdateForTimelineFrame(int viewFrame, int committedFrame, int interruptionStage, bool showPreviewVisuals)
{
// 1. Запекаем полупрозрачную статую в текущей точке снапшота
if (spawnStaticSnapshotGhost && snapshotGhostMaterial != null)
bool inFuture = showPreviewVisuals && viewFrame > committedFrame;
if (!inFuture)
{
_snapshotGhostRoot.transform.SetPositionAndRotation(transform.position, transform.rotation);
for (int i = 0; i < _skinnedRenderers.Length; i++)
{
var sr = _skinnedRenderers[i];
sr.BakeMesh(_bakedMeshes[i]); // Мгновенный снимок позы скелета!
var ghostTransform = _ghostMeshFilters[i].transform;
ghostTransform.SetPositionAndRotation(sr.transform.position, sr.transform.rotation);
// ghostTransform.localScale = sr.transform.lossyScale;
// Назначаем прозрачный материал на все саб-меши
int subMeshCount = _bakedMeshes[i].subMeshCount;
Material[] ghostMats = new Material[Mathf.Max(1, subMeshCount)];
for (int m = 0; m < ghostMats.Length; m++)
ghostMats[m] = snapshotGhostMaterial;
_ghostMeshRenderers[i].sharedMaterials = ghostMats;
}
_snapshotGhostRoot.SetActive(true);
HidePreviewLook();
for (int s = 0; s < _ghostSlots.Length; s++)
if (_ghostSlots[s].Root.activeSelf) _ghostSlots[s].Root.SetActive(false);
return;
}
// 2. Меняем внешний вид самой модели, которая сейчас побежит в превью
ApplyPreviewLookToMainModel();
ApplyPreviewLook(interruptionStage);
for (int s = 0; s < _ghostSlots.Length; s++)
{
var slot = _ghostSlots[s];
bool shouldShow = slot.IsActiveInBake && viewFrame > slot.TriggerFrame;
if (slot.Root.activeSelf != shouldShow)
slot.Root.SetActive(shouldShow);
}
}
/// <summary>
/// Вызывается в блоке finally в PreviewBattleLoopAsync
/// </summary>
public void HidePreviewState()
{
if (_snapshotGhostRoot != null)
_snapshotGhostRoot.SetActive(false);
RestoreMainModelLook();
ClearAllGhosts();
HidePreviewLook();
}
private void ApplyPreviewLookToMainModel()
private void ApplyPreviewLook(int stage)
{
if (_isPreviewLookApplied && _currentAppliedStage == stage) return;
_isPreviewLookApplied = true;
_currentAppliedStage = stage;
Color tint = GetStageColor(stage);
foreach (var (renderer, origMats) in _originalMaterials)
{
if (renderer == null) continue;
// Способ 1: Если задан отдельный материал для превью — подменяем sharedMaterials
if (activePreviewMaterial != null)
{
Material[] previewMats = new Material[origMats.Length];
for (int i = 0; i < previewMats.Length; i++)
previewMats[i] = activePreviewMaterial;
var previewMats = new Material[origMats.Length];
for (int i = 0; i < previewMats.Length; i++) previewMats[i] = activePreviewMaterial;
renderer.sharedMaterials = previewMats;
}
// Способ 2: Иначе подкрашиваем родной MKToon через MaterialPropertyBlock (без аллокаций)
else
{
renderer.GetPropertyBlock(_propBlock);
_propBlock.SetColor(AlbedoColorId, previewAlbedoTint);
_propBlock.SetColor(RimColorId, previewRimColor);
renderer.SetPropertyBlock(_propBlock);
}
renderer.GetPropertyBlock(_propBlock);
_propBlock.SetColor(AlbedoColorId, tint);
_propBlock.SetColor(RimColorId, tint * 1.5f);
renderer.SetPropertyBlock(_propBlock);
}
}
private void RestoreMainModelLook()
private void HidePreviewLook()
{
if (!_isPreviewLookApplied) return;
_isPreviewLookApplied = false;
_currentAppliedStage = -1;
foreach (var (renderer, origMats) in _originalMaterials)
{
if (renderer == null) continue;
if (activePreviewMaterial != null)
{
renderer.sharedMaterials = origMats;
}
else
{
renderer.SetPropertyBlock(null); // Сбрасывает все переопределения PropertyBlock
}
if (activePreviewMaterial != null) renderer.sharedMaterials = origMats;
renderer.SetPropertyBlock(null);
}
}
private Color GetStageColor(int stage, float? alphaOverride = null)
{
Color c = stageProjectionTints[Mathf.Clamp(stage, 0, stageProjectionTints.Length - 1)];
if (alphaOverride.HasValue) c.a = alphaOverride.Value;
return c;
}
private void OnDestroy()
{
foreach (var mesh in _bakedMeshes)
if (_ghostSlots == null) return;
foreach (var slot in _ghostSlots)
{
if (mesh != null) Destroy(mesh);
if (slot == null) continue;
foreach (var mesh in slot.BakedMeshes)
if (mesh != null) Destroy(mesh);
if (slot.Root != null) Destroy(slot.Root);
}
if (_snapshotGhostRoot != null)
Destroy(_snapshotGhostRoot);
}
}
}
@@ -1,27 +1,66 @@
using Code.OfficeGame.BattleMode.Health;
using KinematicCharacterController;
using UnityEngine;
namespace Code.OfficeGame.BattleMode.Actions
{
public struct BonePoseSnapshot
{
public Vector3[] LocalPositions;
public Quaternion[] LocalRotations;
public static BonePoseSnapshot Capture(Transform[] bones)
{
if (bones == null || bones.Length == 0)
return default;
int count = bones.Length;
var pos = new Vector3[count];
var rot = new Quaternion[count];
for (int i = 0; i < count; i++)
{
pos[i] = bones[i].localPosition;
rot[i] = bones[i].localRotation;
}
return new BonePoseSnapshot
{
LocalPositions = pos,
LocalRotations = rot
};
}
public readonly void ApplyTo(Transform[] bones)
{
if (bones == null || LocalPositions == null) return;
int count = Mathf.Min(bones.Length, LocalPositions.Length);
for (int i = 0; i < count; i++)
{
bones[i].localPosition = LocalPositions[i];
bones[i].localRotation = LocalRotations[i];
}
}
}
public struct EntitySnapshot
{
// 1. KCC Motor
// --- Уровень 1: Визуальный (для O(1) скраббинга ползунком) ---
public Vector3 Position;
public Quaternion Rotation;
public Vector3 BaseVelocity;
public BonePoseSnapshot BonePose;
public HealthData CurrentHealth;
// 2. MovementController
// --- Уровень 2: Полное состояние симуляции (для BakeFrom) ---
public KinematicCharacterMotorState MotorState;
public bool IsFrozen;
public Vector3 MoveInputVector;
public Vector3 LookInputVector;
// 3. Здоровье
public HealthData CurrentHealth;
// 4. Аниматор
public Vector3 InternalVelocityAdd;
public AnimatorSnapshot AnimatorSnapshot;
public static EntitySnapshot GetSnapshot(EntityProperties entity)
public static EntitySnapshot GetSnapshot(EntityProperties entity, Transform[] cachedBones)
{
var motor = entity.KinematicCharacterMotor;
var moveCtrl = entity.MovementController;
@@ -30,49 +69,52 @@ namespace Code.OfficeGame.BattleMode.Actions
{
Position = motor.TransientPosition,
Rotation = motor.TransientRotation,
BaseVelocity = motor.BaseVelocity,
BonePose = BonePoseSnapshot.Capture(cachedBones),
CurrentHealth = entity.EntityHealth != null ? entity.EntityHealth.HealthData.CurrentValue : default,
MotorState = motor.GetState(),
IsFrozen = moveCtrl.Freeze,
// Сохраните текущие входы контроллера (добавьте публичные геттеры в MovementController, если они приватные)
MoveInputVector = moveCtrl.MoveInputVector,
LookInputVector = moveCtrl.LookInputVector,
CurrentHealth = entity.EntityHealth != null ? entity.EntityHealth.HealthData.CurrentValue : default,
InternalVelocityAdd = moveCtrl.InternalVelocityAdd,
AnimatorSnapshot = AnimatorSnapshot.GetSnapshot(entity.animator)
};
}
public static void RestoreSnapshot(EntityProperties entity, EntitySnapshot snapshot)
/// <summary>
/// Мгновенное O(1) восстановление визуала для ползунка и воспроизведения ленты.
/// Не трогает Mecanim и не мутирует EntityHealth.
/// </summary>
public static void ApplyVisualOnly(EntityProperties entity, Transform[] cachedBones, in EntitySnapshot snapshot)
{
entity.KinematicCharacterMotor.SetPositionAndRotation(
snapshot.Position,
snapshot.Rotation,
bypassInterpolation: true);
snapshot.BonePose.ApplyTo(cachedBones);
}
/// <summary>
/// Полное детерминированное восстановление для старта/перезапекания физической симуляции.
/// </summary>
public static void RestoreForSimulation(EntityProperties entity, Transform[] cachedBones, in EntitySnapshot snapshot)
{
var motor = entity.KinematicCharacterMotor;
var moveCtrl = entity.MovementController;
// 1. Восстанавливаем MovementController ДО шага KCC
moveCtrl.Freeze = snapshot.IsFrozen;
var restoredInputs = new Code.Game.Gameplay.Player.AICharacterInputs
{
MoveVector = snapshot.MoveInputVector,
Look = snapshot.LookInputVector.sqrMagnitude > 0.0001f
? Quaternion.LookRotation(snapshot.LookInputVector, motor.CharacterUp)
: snapshot.Rotation
};
moveCtrl.SetInputs(ref restoredInputs);
moveCtrl.MoveInputVector = snapshot.MoveInputVector;
moveCtrl.LookInputVector = snapshot.LookInputVector;
moveCtrl.InternalVelocityAdd = snapshot.InternalVelocityAdd;
// 2. Восстанавливаем капсулу KCC (bypassInterpolation = true сбрасывает внутренние буферы перемещения)
motor.SetPositionAndRotation(snapshot.Position, snapshot.Rotation, bypassInterpolation: true);
motor.BaseVelocity = snapshot.BaseVelocity;
motor.ApplyState(snapshot.MotorState, bypassInterpolation: true);
// 3. Восстанавливаем здоровье (без вызова анимаций смерти)
if (entity.EntityHealth != null)
{
entity.EntityHealth.SetHealthData(snapshot.CurrentHealth);
}
// 4. Восстанавливаем точную позу и фазу перехода Animator
snapshot.AnimatorSnapshot.RestoreTo(entity.animator);
// 5. Мгновенно синхронизируем коллайдеры костей в PhysX
Physics.SyncTransforms();
snapshot.BonePose.ApplyTo(cachedBones);
}
}
@@ -155,8 +197,8 @@ namespace Code.OfficeGame.BattleMode.Actions
layerSnap.NextFullPathHash = nextInfo.fullPathHash;
layerSnap.NextNormalizedTime = nextInfo.normalizedTime;
layerSnap.NextStateLength = Mathf.Max(0.0001f, nextInfo.length);
layerSnap.TotalTransitionDuration = totalTransSeconds;
layerSnap.ElapsedTransitionTime = totalTransSeconds * transInfo.normalizedTime;
layerSnap.TotalTransitionDuration = Mathf.Max(0.0001f, totalTransSeconds);
layerSnap.ElapsedTransitionTime = layerSnap.TotalTransitionDuration * transInfo.normalizedTime;
}
_layers[i] = layerSnap;
@@ -182,7 +224,7 @@ namespace Code.OfficeGame.BattleMode.Actions
}
}
public void RestoreTo(Animator targetAnimator)
public readonly void RestoreTo(Animator targetAnimator)
{
if (targetAnimator == null || _layers == null) return;
@@ -217,29 +259,25 @@ namespace Code.OfficeGame.BattleMode.Actions
if (!layer.IsInTransition || layer.NextFullPathHash == 0)
{
// CrossFadeInFixedTime с длительностью 0f гарантированно убивает любой старый переход без Rebind()!
float timeInSeconds = layer.NormalizedTime * layer.StateLength;
float timeInSeconds = Mathf.Max(0f, layer.NormalizedTime * layer.StateLength);
targetAnimator.CrossFadeInFixedTime(layer.FullPathHash, 0f, i, timeInSeconds);
targetAnimator.Update(0f);
}
else
{
// 1. Отматываем оба стейта к моменту начала перехода (минус ElapsedTransitionTime)
float startSecondsA = (layer.NormalizedTime * layer.StateLength) - layer.ElapsedTransitionTime;
float startSecondsB = (layer.NextNormalizedTime * layer.NextStateLength) - layer.ElapsedTransitionTime;
// Защита от отрицательного времени (фикс бага старого AnimatorSnapshot)
float startSecondsA = Mathf.Max(0f, (layer.NormalizedTime * layer.StateLength) - layer.ElapsedTransitionTime);
float startSecondsB = Mathf.Max(0f, (layer.NextNormalizedTime * layer.NextStateLength) - layer.ElapsedTransitionTime);
targetAnimator.CrossFadeInFixedTime(layer.FullPathHash, 0f, i, startSecondsA);
targetAnimator.Update(0f);
// 2. Запускаем переход с оригинальной полной длительностью
targetAnimator.CrossFadeInFixedTime(
layer.NextFullPathHash,
layer.TotalTransitionDuration,
i,
startSecondsB);
// 3. Прокручиваем аниматор ровно на ElapsedTransitionTime вперед (с выключенным RootMotion),
// чтобы внутренний вес смешивания Mecanim встал ровно в ту же долю процента!
targetAnimator.Update(layer.ElapsedTransitionTime);
}
}