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

@@ -2,15 +2,15 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Code.Game.Entities;
using Code.Game.OfficeGame.BattleMode;
using Code.Game.OfficeGame.Entities;
using Code.Infrastructure.Camera;
using Code.Infrastructure.Particles;
using Code.OfficeGame.BattleMode.Actions;
using Code.OfficeGame.BattleMode.Actions.AI;
using Code.OfficeGame.BattleMode.Actions.Deciders;
using Code.OfficeGame.BattleMode.Effects;
using Code.OfficeGame.BattleMode.Snapshots;
using Code.OfficeGame.BattleMode.Health;
using Code.OfficeGame.BattleMode.HitBoxes;
using Code.OfficeGame.BattleMode.UI;
using Cysharp.Threading.Tasks;
using R3;
@@ -18,40 +18,44 @@ using UnityEngine;
namespace Code.OfficeGame.BattleMode.Timeline
{
public class BattleTimeline
public sealed class BattleTimeline : IDisposable
{
public const int TicksPerSecond = 60;
public const float TickDelta = 1f / TicksPerSecond;
public static bool IsSilentSimulation { get; private set; }
public const int TicksPerSecond = BattleSimulator.TicksPerSecond;
public const float TickDelta = BattleSimulator.FixedTickDelta;
public static float PlaybackSpeed { get; set; } = 1f;
private readonly ReactiveProperty<int> _currentBattleFrame = new(0);
public ReadOnlyReactiveProperty<int> CurrentBattleFrame => _currentBattleFrame;
// Реактивное состояние для UI (ползунок, маркеры, HP-бары)
private readonly ReactiveProperty<int> _displayFrame = new(0);
private readonly ReactiveProperty<int> _committedFrame = new(0);
private readonly ReactiveProperty<int> _maxFrame = new(0);
private readonly ReactiveProperty<TimelineMode> _mode = new(TimelineMode.Idle);
private readonly Subject<BattleTimelineTrack> _onTrackRebaked = new();
private readonly Subject<TimelineEvent> _onRealEvent = new();
public ReadOnlyReactiveProperty<int> DisplayFrame => _displayFrame;
public ReadOnlyReactiveProperty<int> CommittedFrame => _committedFrame;
public ReadOnlyReactiveProperty<int> MaxFrame => _maxFrame;
public ReadOnlyReactiveProperty<TimelineMode> Mode => _mode;
public Observable<BattleTimelineTrack> OnTrackRebaked => _onTrackRebaked;
public Observable<TimelineEvent> OnRealEvent => _onRealEvent;
public BattleTimelineTrack Track { get; } = new();
private readonly BattleTimelinePanel _timelinePanel;
private DisposableBag _battleSubscriptions;
private readonly BattleActionDecisionPanel _decisionPanel;
private readonly HealthPanelsHolder _healthPanelsHolder;
private readonly CameraStateMachine _cameraStateMachine;
private readonly IParticleService _particleService;
private Dictionary<BattleActionType, BattleAction> _battleActions;
private Dictionary<DeciderType, BattleActionDecider> _battleActionDeciders;
private Dictionary<EnemyDeciderTypes, EnemyDecider> _enemyDeciders;
private Dictionary<EntityId, EntityProperties> _entities;
private Dictionary<EntityId, BattleActionData> _battleActionDatas = new();
private Dictionary<EntityId, BattleActionDecisionResult> _actionDecisionResults = new();
private SnapshotUtilityNonStatic _snapshotUtility = new();
private BattleActionDecisionPanel _battleActionDecisionPanel;
private CameraStateMachine _cameraStateMachine;
private SemaphoreSlim _preview = new(1,1);
// Entity, damage
private List<EntityAttackedData> _attackRequests = new();
private List<EntityAttackedData> _predictedAttackRequests = new();
private readonly Dictionary<BattleActionType, BattleAction> _battleActions;
private readonly Dictionary<DeciderType, BattleActionDecider> _battleActionDeciders;
private readonly Dictionary<EnemyDeciderTypes, EnemyDecider> _enemyDeciders;
private readonly BattleSimulator _simulator;
private EntityProperties[] _entities;
private CancellationTokenSource _previewLoopCts;
private bool _previewVisualsEnabled;
public BattleTimeline(
BattleTimelinePanel timelinePanel,
@@ -59,558 +63,436 @@ namespace Code.OfficeGame.BattleMode.Timeline
IEnumerable<BattleActionDecider> battleActionDeciders,
IEnumerable<EnemyDecider> enemyDeciders,
BattleActionDecisionPanel battleActionDecisionPanel,
CameraStateMachine cameraStateMachine)
HealthPanelsHolder healthPanelsHolder,
CameraStateMachine cameraStateMachine,
IParticleService particleService)
{
_cameraStateMachine = cameraStateMachine;
_battleActionDecisionPanel = battleActionDecisionPanel;
_timelinePanel = timelinePanel;
_decisionPanel = battleActionDecisionPanel;
_healthPanelsHolder = healthPanelsHolder;
_cameraStateMachine = cameraStateMachine;
_particleService = particleService;
_battleActions = new();
foreach (var battleAction in battleActions)
{
battleAction.SetBattleTimeline(this);
_battleActions.Add(battleAction.ActionType, battleAction);
}
_battleActions = battleActions.ToDictionary(x => x.ActionType);
_battleActionDeciders = battleActionDeciders.ToDictionary(x => x.DeciderType);
_enemyDeciders = enemyDeciders.ToDictionary(x=>x.EnemyDeciderType);
_enemyDeciders = enemyDeciders.ToDictionary(x => x.EnemyDeciderType);
_simulator = new BattleSimulator(_battleActions);
foreach (var action in _battleActions.Values)
action.SetSimulationContext(_simulator);
}
public int GetSlotIndex(EntityId id) => _simulator.GetSlotIndex(id);
// =================== УПРАВЛЕНИЕ ПОЛЗУНКОМ И ПЛЕЕРОМ ===================
public void ScrubToFrame(int targetFrame)
{
if (_mode.Value == TimelineMode.BattlePlaying || Track.FrameCount == 0)
return;
StopPreviewLoop();
_mode.Value = TimelineMode.Scrubbing;
int clamped = Mathf.Clamp(targetFrame, 0, Track.LastFrame);
ApplyFrame(clamped, playOneShotVfx: false);
}
public void StepFrame(int delta)
{
if (_mode.Value == TimelineMode.BattlePlaying || Track.FrameCount == 0)
return;
ScrubToFrame(_displayFrame.Value + delta);
}
public void TogglePreviewPlayPause()
{
if (_mode.Value == TimelineMode.BattlePlaying || Track.FrameCount == 0)
return;
if (_mode.Value == TimelineMode.PreviewPlaying)
{
StopPreviewLoop();
_mode.Value = TimelineMode.Scrubbing;
}
else if (Track.LastFrame > _committedFrame.Value)
{
StartPreviewLoop(_committedFrame.Value, Track.LastFrame, _battleLoopCt);
}
}
public void ReturnToCommittedFrame()
{
if (_mode.Value == TimelineMode.BattlePlaying || Track.FrameCount == 0)
return;
StopPreviewLoop();
ApplyFrame(_committedFrame.Value, playOneShotVfx: false);
_mode.Value = TimelineMode.Deciding;
}
// =================== ОСНОВНОЙ ЦИКЛ БОЯ ===================
private CancellationToken _battleLoopCt;
public async UniTask RunBattleLoopAsync(List<EntityProperties> entities, CancellationToken ctx)
{
_entities = entities.ToDictionary(x => x.GetEntityId());
_battleLoopCt = ctx;
_entities = entities.ToArray();
_simulator.BindEntities(_entities);
foreach (var (id, entity) in _entities)
{
_battleActionDatas[id] = new NoneBattleActionData() { Finished = true };
_actionDecisionResults[id] = new AsIsBattleActionDeciderResult()
{ ActionType = BattleActionType.None, ResultCode = BattleActionDecisionResultCode.Decided };
}
_currentBattleFrame.Value = 0;
var initialSlots = new EntityActionSlotSnapshot[_entities.Length];
for (int i = 0; i < _entities.Length; i++)
initialSlots[i] = EntityActionSlotSnapshot.CreateNone(0);
_battleSubscriptions = new DisposableBag();
var frameZero = _simulator.CaptureCurrentFrame(
frame: 0,
interruptionStage: 0,
slots: initialSlots,
readySlotsMask: 0UL,
events: Array.Empty<TimelineEvent>(),
hitboxVisuals: Array.Empty<FrameHitboxVisual>());
Track.Initialize(frameZero);
_committedFrame.Value = 0;
_displayFrame.Value = 0;
_maxFrame.Value = 0;
using var uiBinding = _timelinePanel.BindTimeline(this);
using var hpBinding = _healthPanelsHolder.BindToTimeline(this);
using var vfxSub = _onRealEvent.Subscribe(HandleRealEvent);
try
{
_currentBattleFrame
.Subscribe(_timelinePanel.OnFrameTick)
.AddTo(ref _battleSubscriptions);
await DecideActions(_entities.Keys.ToArray(), ctx);
while (!ctx.IsCancellationRequested)
{
EntityId[] entitiesNeedOrders = await PlayTimelineUntilPause(ctx);
var readySlots = Track.GetReadySlotsAt(_committedFrame.Value);
if (readySlots.Count == 0) break;
await DecideActions(entitiesNeedOrders, ctx);
// 1. Собираем приказы для всех освободившихся бойцов
await DecideActionsForSlots(readySlots, ctx);
// 2. Финально запекаем будущее со всеми утверждёнными приказами (без слепков)
_previewVisualsEnabled = false;
HideAllPreviewVisuals();
RebakeFromCommitted(recordGhosts: false);
int nextPauseFrame = Track.FindNextPauseFrame(_committedFrame.Value);
if (nextPauseFrame <= _committedFrame.Value)
{
await UniTask.Yield(PlayerLoopTiming.Update, ctx);
continue;
}
// 3. Плавно проигрываем готовые кадры до ближайшего прерывания
await PlayBakedRangeAsync(_committedFrame.Value + 1, nextPauseFrame, ctx);
// Синхронизируем физику и HP строго на новом CommittedFrame
_simulator.RestoreSimulationToWorld(Track.GetFrame(_committedFrame.Value));
}
}
finally
{
_battleSubscriptions.Dispose();
StopPreviewLoop();
HideAllPreviewVisuals();
HitboxDrawer.Clear();
_mode.Value = TimelineMode.Idle;
}
}
private async UniTask<EntityId[]> PlayTimelineUntilPause(CancellationToken ctx)
private async UniTask PlayBakedRangeAsync(int startFrame, int endFrame, CancellationToken ctx)
{
float accumulator = 0f;
StopPreviewLoop();
_previewVisualsEnabled = false;
HideAllPreviewVisuals();
_mode.Value = TimelineMode.BattlePlaying;
while (!ctx.IsCancellationRequested)
float accumulator = 0f;
int frame = startFrame;
while (frame <= endFrame && !ctx.IsCancellationRequested)
{
await UniTask.Yield(PlayerLoopTiming.Update, ctx);
accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f) * PlaybackSpeed;
while (accumulator >= TickDelta)
while (accumulator >= TickDelta && frame <= endFrame && !ctx.IsCancellationRequested)
{
accumulator -= TickDelta;
_currentBattleFrame.Value++;
var readyEntities = SimulateSingleFrame(_entities);
if (readyEntities.Length > 0)
{
foreach (var entityId in readyEntities)
{
Debug.Log($"Entity {entityId} is real ready");
_battleActions[_actionDecisionResults[entityId].ActionType]
.Finish(
_entities[entityId],
_battleActionDatas[entityId],
_actionDecisionResults[entityId]);
_battleActionDatas.Remove(entityId);
_actionDecisionResults.Remove(entityId);
}
return readyEntities;
}
_committedFrame.Value = frame;
ApplyFrame(frame, playOneShotVfx: true);
frame++;
}
}
return null;
}
// TODO ЗАПУСКАТЬ ДВА ЦИКЛА ПОЛНЫЙ И ДО ПРЕРЫВАНИЯ
private async UniTask PreviewBattleLoopAsync(int frameCount,
Dictionary<EntityId, EntityProperties> entities,
CancellationToken ctx)
{
if (frameCount <= 0)
{
_preview.Release(1);
throw new Exception("FrameCount must be > 0");
}
_snapshotUtility.GetSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
try
{
while (!ctx.IsCancellationRequested)
{
_snapshotUtility.RestoreFromSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
await PlayTimelineForCertainFrames(frameCount, ctx).AttachExternalCancellation(ctx);
}
}
finally
{
_snapshotUtility.RestoreFromSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
foreach (var (_, entity) in entities)
{
entity.EntityPreviewVisuals.HidePreviewState();
}
_preview.Release(1);
}
}
private async UniTask PreviewBattleLoopAsync(EntityId entityId,
Dictionary<EntityId, EntityProperties> entities,
CancellationToken ctx)
private async UniTask DecideActionsForSlots(List<int> readySlots, CancellationToken ctx)
{
_snapshotUtility.GetSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
_mode.Value = TimelineMode.Deciding;
try
// Сначала решения принимают ИИ — игрок сразу увидит их запечённый план на таймлайне
var orderedSlots = readySlots
.OrderBy(slot => _entities[slot].TeamData.Team == EntityTeam.Good ? 1 : 0)
.ToList();
foreach (int slotIndex in orderedSlots)
{
while (!ctx.IsCancellationRequested)
{
_snapshotUtility.RestoreFromSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
_simulator.RestoreSimulationToWorld(Track.GetFrame(_committedFrame.Value));
ApplyFrame(_committedFrame.Value, playOneShotVfx: false);
await PlayTimelineUntilThatSpecific(entityId, ctx).AttachExternalCancellation(ctx);
}
}
finally
{
_snapshotUtility.RestoreFromSnapshots(
entities,
_actionDecisionResults,
_battleActionDatas);
foreach (var (_, entity) in entities)
{
entity.EntityPreviewVisuals.HidePreviewState();
}
EntityActionSlotSnapshot chosenSlot = await DecideForSingleSlot(slotIndex, ctx);
_preview.Release(1);
Track.GetFrame(_committedFrame.Value).Entities[slotIndex].ActionSlot = chosenSlot;
RebakeFromCommitted(recordGhosts: false);
}
}
private async UniTask PlayTimelineForCertainFrames(int frameCount, CancellationToken ctx)
private async UniTask<EntityActionSlotSnapshot> DecideForSingleSlot(int slotIndex, CancellationToken ctx)
{
float accumulator = 0f;
int counter = frameCount;
while (counter > 0 && !ctx.IsCancellationRequested)
var entity = _entities[slotIndex];
if (entity.TeamData.Team == EntityTeam.ChaoticEvil)
{
bool isCanceled = await UniTask.Yield(PlayerLoopTiming.Update, ctx).SuppressCancellationThrow();
if (isCanceled) break;
var (enemyRes, enemyData) = await _enemyDeciders[entity.TeamData.DeciderType]
.DecideEnemy(ctx, entity, _battleActions);
accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f) * PlaybackSpeed;
while (accumulator >= TickDelta && counter > 0 && !ctx.IsCancellationRequested)
return new EntityActionSlotSnapshot
{
// Debug.Log($"Simulating {counter}/{frameCount}");
accumulator -= TickDelta;
counter--;
var readyEntities = SimulateSingleFrame(_entities);
if (readyEntities.Length > 0)
{
foreach (var entityId in readyEntities)
{
var battleActionType = _actionDecisionResults[entityId].ActionType;
Debug.Log($"Entity {entityId} is preview ready {battleActionType}");
_battleActions[battleActionType]
.Finish(
_entities[entityId],
_battleActionDatas[entityId],
_actionDecisionResults[entityId]);
_battleActionDatas.Remove(entityId);
_actionDecisionResults.Remove(entityId);
}
// return;
}
}
ActionType = enemyRes.ActionType,
DecisionResult = enemyRes,
ActionData = enemyData,
LastCompletedActionType = Track.GetFrame(_committedFrame.Value).Entities[slotIndex].ActionSlot.LastCompletedActionType,
ActionStartFrame = _committedFrame.Value,
EstimatedEndFrame = _committedFrame.Value + enemyData.TotalFrames
};
}
if (entity.TeamData.Team == EntityTeam.Good)
return await DecideForPlayerSlot(slotIndex, ctx);
return EntityActionSlotSnapshot.CreateNone(_committedFrame.Value);
}
private async UniTask PlayTimelineUntilThatSpecific(EntityId specificEntityId, CancellationToken ctx)
private async UniTask<EntityActionSlotSnapshot> DecideForPlayerSlot(int slotIndex, CancellationToken ctx)
{
float accumulator = 0f;
var entity = _entities[slotIndex];
var lastCompleted = Track.GetFrame(_committedFrame.Value).Entities[slotIndex].ActionSlot.LastCompletedActionType;
_decisionPanel.SetEntityInfo(entity.battleActionTypes);
_timelinePanel.SetPreviousActionText(lastCompleted.ToString());
// Сразу запекаем прогноз с текущими действиями врагов — ползунок доступен уже в меню выбора!
_previewVisualsEnabled = true;
RebakeFromCommitted(recordGhosts: true);
ApplyFrame(_committedFrame.Value, playOneShotVfx: false);
var cameraBattleState = _cameraStateMachine.CurrentBaseState as CameraBattleModeState;
while (!ctx.IsCancellationRequested)
{
bool isCanceled = await UniTask.Yield(PlayerLoopTiming.Update, ctx).SuppressCancellationThrow();
if (isCanceled) break;
Cursor.lockState = CursorLockMode.Confined;
if (cameraBattleState != null) cameraBattleState.battleDeciding = true;
await _decisionPanel.Open(ctx);
BattleActionType decidedType = await _decisionPanel.GetDecision(ctx);
if (decidedType == BattleActionType.None) continue;
var deciderType = _battleActions[decidedType].DeciderType;
var decider = _battleActionDeciders[deciderType];
StopPreviewLoop();
_simulator.RestoreSimulationToWorld(Track.GetFrame(_committedFrame.Value));
ApplyFrame(_committedFrame.Value, playOneShotVfx: false);
decider.MountDecider(entity);
bool waitingForFirstTarget = true;
try
{
while (!ctx.IsCancellationRequested)
{
// Пока цель ещё не выбрана — курсор залочен под прицеливание камеры.
// Как только цель выбрана (идёт превью) — курсор свободен (Confined),
// чтобы игрок мог двигать ползунок таймлайна (а вращать камеру через ПКМ).
Cursor.lockState = waitingForFirstTarget ? CursorLockMode.Locked : CursorLockMode.Confined;
if (cameraBattleState != null) cameraBattleState.battleDeciding = !waitingForFirstTarget;
await _decisionPanel.Close(ctx);
var decisionResult = await decider.GetDecision();
decisionResult.ActionType = decidedType;
StopPreviewLoop();
_simulator.RestoreSimulationToWorld(Track.GetFrame(_committedFrame.Value));
if (decisionResult.ResultCode == BattleActionDecisionResultCode.CancelDecision)
{
RebakeFromCommitted(recordGhosts: true);
ApplyFrame(_committedFrame.Value, playOneShotVfx: false);
break;
}
var actionData = _battleActions[decidedType].MountAndGetFrames(entity, decisionResult);
var candidateSlot = new EntityActionSlotSnapshot
{
ActionType = decidedType,
DecisionResult = decisionResult,
ActionData = actionData,
LastCompletedActionType = lastCompleted,
ActionStartFrame = _committedFrame.Value,
EstimatedEndFrame = _committedFrame.Value + actionData.TotalFrames
};
if (decisionResult.ResultCode == BattleActionDecisionResultCode.Deciding)
{
waitingForFirstTarget = false;
_previewVisualsEnabled = true;
RebakeFromCommitted(
recordGhosts: true,
overrideSlot: slotIndex,
overrideAction: candidateSlot);
StartPreviewLoop(_committedFrame.Value, Track.LastFrame, ctx);
}
else // BattleActionDecisionResultCode.Decided
{
_previewVisualsEnabled = false;
HideAllPreviewVisuals();
return candidateSlot;
}
}
}
finally
{
StopPreviewLoop();
decider.UnmountDecider();
}
}
return EntityActionSlotSnapshot.CreateNone(_committedFrame.Value, lastCompleted);
}
// =================== ЗАПЕКАНИЕ И ПРИМЕНЕНИЕ КАДРОВ ===================
private void RebakeFromCommitted(
bool recordGhosts,
int overrideSlot = -1,
EntityActionSlotSnapshot? overrideAction = null)
{
_simulator.BakeFrom(Track, _committedFrame.Value, recordGhosts, overrideSlot, overrideAction);
_maxFrame.Value = Track.LastFrame;
_onTrackRebaked.OnNext(Track);
}
private void StartPreviewLoop(int startFrame, int endFrame, CancellationToken battleCtx)
{
StopPreviewLoop();
if (endFrame <= startFrame) return;
_mode.Value = TimelineMode.PreviewPlaying;
_previewLoopCts = CancellationTokenSource.CreateLinkedTokenSource(battleCtx);
RunPreviewPlaybackAsync(startFrame, endFrame, _previewLoopCts.Token).Forget();
}
private async UniTaskVoid RunPreviewPlaybackAsync(int startFrame, int endFrame, CancellationToken ctx)
{
float accumulator = 0f;
int current = startFrame;
while (!ctx.IsCancellationRequested)
{
bool canceled = await UniTask.Yield(PlayerLoopTiming.Update, ctx).SuppressCancellationThrow();
if (canceled) break;
accumulator += Mathf.Min(Time.unscaledDeltaTime, 0.1f) * PlaybackSpeed;
while (accumulator >= TickDelta && !ctx.IsCancellationRequested)
{
accumulator -= TickDelta;
var readyEntities = SimulateSingleFrame(_entities);
current++;
if (current > endFrame) current = startFrame;
if (readyEntities.Length > 0)
{
foreach (var entityId in readyEntities)
{
var battleActionType = _actionDecisionResults[entityId].ActionType;
Debug.Log($"Entity {entityId} is preview ready {battleActionType}");
_battleActions[_actionDecisionResults[entityId].ActionType]
.Finish(
_entities[entityId],
_battleActionDatas[entityId],
_actionDecisionResults[entityId]);
_battleActionDatas.Remove(entityId);
_actionDecisionResults.Remove(entityId);
}
if(readyEntities.Contains(specificEntityId)) return;
}
ApplyFrame(current, playOneShotVfx: false);
}
}
}
public List<EntityAttackedData> PredictSilently(int lookaheadFrames)
private void StopPreviewLoop()
{
// var snapshot = TakeFullBattleSnapshot();
_snapshotUtility.GetSnapshots(
_entities,
_actionDecisionResults,
_battleActionDatas);
_predictedAttackRequests.Clear();
IsSilentSimulation = true;
try
{
for (int i = 0; i < lookaheadFrames; i++)
{
var readyEntities = SimulateSingleFrame(_entities);
if (readyEntities.Length > 0) break; // Останавливаемся, если чей-то ход закончился
}
}
finally
{
IsSilentSimulation = false;
_snapshotUtility.RestoreFromSnapshots(
_entities,
_actionDecisionResults,
_battleActionDatas);
// RestoreFullBattleSnapshot(snapshot);
}
return _predictedAttackRequests;
if (_previewLoopCts == null) return;
_previewLoopCts.Cancel();
_previewLoopCts.Dispose();
_previewLoopCts = null;
}
private EntityId[] SimulateSingleFrame(Dictionary<EntityId, EntityProperties> inEntities)
/// <summary>
/// Единая точка отображения любого кадра (бой, превью и скраббинг ползунком).
/// </summary>
private void ApplyFrame(int frame, bool playOneShotVfx)
{
foreach (var (entityId, entity) in inEntities)
var snapshot = Track.GetFrame(frame);
_simulator.ApplyVisualFrameToWorld(snapshot);
_displayFrame.Value = snapshot.Frame;
// Обновляем многоступенчатые слепки и цвет проекции ТОЛЬКО для кадров будущего (> CommittedFrame)
for (int i = 0; i < _entities.Length; i++)
{
if (!_actionDecisionResults.TryGetValue(entityId, out var actionDecisionResult)
|| !_battleActionDatas.TryGetValue(entityId, out var battleActionData))
continue;
_battleActions[actionDecisionResult.ActionType]
.Tick(
TickDelta,
entity,
actionDecisionResult,
battleActionData);
entity.animator.Update(TickDelta);
_entities[i].EntityPreviewVisuals?.UpdateForTimelineFrame(
viewFrame: snapshot.Frame,
committedFrame: _committedFrame.Value,
interruptionStage: snapshot.InterruptionStage,
showPreviewVisuals: _previewVisualsEnabled);
}
KinematicCharacterController.KinematicCharacterSystem.Simulate(
TickDelta,
KinematicCharacterController.KinematicCharacterSystem.CharacterMotors,
KinematicCharacterController.KinematicCharacterSystem.PhysicsMovers
);
Physics.Simulate(TickDelta);
Physics.SyncTransforms();
ProcessAttackRequests();
var readyEntities = _battleActionDatas
.Where(x => x.Value.Finished)
.Where(x=> !inEntities[x.Key].EntityHealth.IsDead)
.Select(x => x.Key)
.ToArray();
return readyEntities;
}
private async UniTask DecideActions(EntityId[] entities, CancellationToken ctx)
{
foreach (var entityId in entities)
// Хитбоксы текущего кадра не исчезают, даже если ползунок остановлен!
HitboxDrawer.Clear();
var hitboxes = snapshot.HitboxVisuals;
if (hitboxes != null)
{
var (decisionResult, battleActionData) = await DecideAction(ctx, _entities[entityId]);
for (int i = 0; i < hitboxes.Length; i++)
HitboxDrawer.DrawMatrix(hitboxes[i].Matrix, hitboxes[i].Color, duration: 999f);
}
_actionDecisionResults[entityId] = decisionResult;
_battleActionDatas[entityId] = battleActionData;
// События VFX стреляют только в реальном воспроизведении
if (playOneShotVfx && snapshot.Events is { Length: > 0 })
{
for (int i = 0; i < snapshot.Events.Length; i++)
_onRealEvent.OnNext(snapshot.Events[i]);
}
}
private async UniTask<(BattleActionDecisionResult, BattleActionData)> DecideAction(CancellationToken ctx,
EntityProperties entity)
private void HandleRealEvent(TimelineEvent ev)
{
if(entity.TeamData.Team == EntityTeam.Good)
if (ev.EventType == TimelineEventType.HitLanded)
{
var (decisionResult, actionData) = await DecideForPlayer(ctx, entity);
if (decisionResult == null || actionData == null)
throw new ArgumentNullException(nameof(decisionResult));
return (decisionResult, actionData);
_particleService.EmitOneShot(
new ParticlePartitionIDPair(ParticlePartition.HitParticles, 0),
15,
ev.WorldPosition,
Quaternion.identity);
}
if (entity.TeamData.Team == EntityTeam.ChaoticEvil)
{
var (enemyDecisionResult, enemyActionData) =
await _enemyDeciders[entity.TeamData.DeciderType].DecideEnemy(ctx, entity, _battleActions);
if (enemyDecisionResult == null || enemyActionData == null)
throw new ArgumentNullException(nameof(enemyDecisionResult));
return (enemyDecisionResult, enemyActionData);
}
return (new AsIsBattleActionDeciderResult(), new NoneBattleActionData());
}
private async UniTask<(BattleActionDecisionResult decisionResult, BattleActionData actionData)> DecideForPlayer(CancellationToken ctx, EntityProperties entity)
private void HideAllPreviewVisuals()
{
_battleActionDecisionPanel.SetEntityInfo(entity.battleActionTypes);
BattleActionType decidedActionType = BattleActionType.None;
BattleActionDecisionResult decisionResult = null;
BattleActionData actionData = null;
var entityId = entity.GetEntityId();
BattleActionData entityActionDataSnapshot = null;
BattleActionDecisionResult entityResultSnapshot = null;
if (_battleActionDatas.TryGetValue(entityId, out var battleActionData))
entityActionDataSnapshot = battleActionData.GetSnapshot();
if (_actionDecisionResults.TryGetValue(entityId, out var actionDecisionResult))
{
entityResultSnapshot = actionDecisionResult.GetSnapshot();
_timelinePanel.SetPreviousActionText(entityResultSnapshot.ActionType.ToString());
}
while (decidedActionType == BattleActionType.None || ctx.IsCancellationRequested)
{
Cursor.lockState = CursorLockMode.Confined;
((CameraBattleModeState)_cameraStateMachine.CurrentBaseState).battleDeciding = true;
await _battleActionDecisionPanel.Open(ctx);
decidedActionType = await _battleActionDecisionPanel.GetDecision(ctx);
if (decidedActionType == BattleActionType.None) continue;
var deciderType = _battleActions[decidedActionType].DeciderType;
_battleActionDeciders[deciderType].MountDecider(entity);
CancellationTokenSource previewCancellationToken = new();
while (!ctx.IsCancellationRequested)
{
Cursor.lockState = CursorLockMode.Locked;
((CameraBattleModeState)_cameraStateMachine.CurrentBaseState).battleDeciding = false;
await _battleActionDecisionPanel.Close(ctx);
decisionResult = await _battleActionDeciders[deciderType].GetDecision();
decisionResult.ActionType = decidedActionType;
previewCancellationToken.Cancel();
previewCancellationToken.Dispose();
await _preview.WaitAsync(ctx);
_preview.Release();
actionData = _battleActions[decidedActionType].MountAndGetFrames(entity, decisionResult);
if (decisionResult.ResultCode == BattleActionDecisionResultCode.Deciding)
{
_actionDecisionResults[entityId] = decisionResult;
_battleActionDatas[entityId] = actionData;
previewCancellationToken = new();
await _preview.WaitAsync(previewCancellationToken.Token);
PredictSilently(actionData.TotalFrames);
PreviewBattleLoopAsync(entityId, _entities, previewCancellationToken.Token)
.Forget();
}
else if (decisionResult.ResultCode == BattleActionDecisionResultCode.CancelDecision)
{
decidedActionType = BattleActionType.None;
_battleActionDatas.Remove(entityId);
_actionDecisionResults.Remove(entityId);
break;
}
else break;
}
_battleActionDeciders[deciderType].UnmountDecider();
}
_battleActionDatas[entityId] = entityActionDataSnapshot;
_actionDecisionResults[entityId] = entityResultSnapshot;
return (decisionResult, actionData);
if (_entities == null) return;
for (int i = 0; i < _entities.Length; i++)
_entities[i].EntityPreviewVisuals?.HidePreviewState();
}
// public void ForceDecideAction(
// EntityId entityId,
// BattleActionData forcedBattleActionData,
// BattleActionDecisionResult forcedBattleActionDataResult)
// {
// if(_battleActionDatas.TryGetValue(entityId, out var battleActionData)
// && _actionDecisionResults.TryGetValue(entityId, out var actionDecisionResult))
// _battleActions[_actionDecisionResults[entityId].ActionType]
// .Finish(
// _entities[entityId],
// battleActionData,
// actionDecisionResult);
//
// _battleActionDatas[entityId] = forcedBattleActionData;
// _actionDecisionResults[entityId] = forcedBattleActionDataResult;
//
// Debug.Log($"Задано действие {forcedBattleActionDataResult.ActionType} для {entityId} with {forcedBattleActionData.GetType()}");
// }
private void ProcessAttackRequests()
public void Dispose()
{
foreach (var request in _attackRequests)
{
var attacker = request.Attacker;
var defender = request.Defender;
var attackEffects = attacker.Effects.Where(x => x.Type == EffectType.Attack)
.Select(x => (AttackEffect)x);
var damage = request.Damage;
foreach (var effect in attackEffects)
{
effect.Apply(damage);
}
var defendEffects = defender.Effects.Where(x => x.Type == EffectType.Defense)
.Select(x => (DefenseEffect)x);
foreach (var effect in defendEffects)
{
effect.Apply(damage);
}
defender.EntityHealth.GetDamage(damage, request.HitBoxPartType);
var defenderId = request.DefenderId;
if (_battleActionDatas.TryGetValue(defenderId, out var battleActionData)
&& _actionDecisionResults.TryGetValue(defenderId, out var actionDecisionResult))
_battleActions[_actionDecisionResults[defenderId].ActionType]
.Finish(
_entities[defenderId],
battleActionData,
actionDecisionResult);
Debug.Log($"{defender} got {damage} and {defender.EntityHealth.IsDead}");
if (defender.EntityHealth.IsDead)
{
var forcedDeathData = new NoneBattleActionData();
var forcedDeathDecision = new AsIsBattleActionDeciderResult();
_battleActionDatas[defenderId] = forcedDeathData;
_actionDecisionResults[defenderId] = forcedDeathDecision;
}
else
{
_battleActionDatas[defenderId] = request.ForcedActionData;
_actionDecisionResults[defenderId] = request.ForcedDecisionResult;
}
}
_attackRequests.Clear();
}
public void AttackRequest(EntityId attacker, EntityId defender, EntityAttackedData attackedData)
{
if (_attackRequests.Contains(attackedData)) return;
attackedData.AttackerId = attacker;
attackedData.DefenderId = defender;
attackedData.Attacker = _entities[attacker];
attackedData.Defender = _entities[defender];
_attackRequests.Add(attackedData);
}
public void KillEntity(EntityId entityId)
{
StopPreviewLoop();
HitboxDrawer.Clear();
_displayFrame.Dispose();
_committedFrame.Dispose();
_maxFrame.Dispose();
_mode.Dispose();
_onTrackRebaked.Dispose();
_onRealEvent.Dispose();
}
}
}