WiP movement prediction.

This commit is contained in:
Pieter-Jan Briers
2020-06-24 02:21:20 +02:00
parent 822436bb81
commit da45a52325
48 changed files with 1101 additions and 540 deletions

View File

@@ -0,0 +1,71 @@
using System;
using Content.Shared.GameObjects.Components.Movement;
using Content.Shared.GameObjects.EntitySystems;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
namespace Content.Shared.GameObjects.Components.Mobs
{
public abstract class SharedStunnableComponent : Component, IMoveSpeedModifier, IActionBlocker
{
public sealed override string Name => "Stunnable";
public override uint? NetID => ContentNetIDs.STUNNABLE;
[ViewVariables] protected float WalkModifierOverride = 0f;
[ViewVariables] protected float RunModifierOverride = 0f;
[ViewVariables] public abstract bool Stunned { get; }
[ViewVariables] public abstract bool KnockedDown { get; }
[ViewVariables] public abstract bool SlowedDown { get; }
#region ActionBlockers
public bool CanMove() => (!Stunned);
public bool CanInteract() => (!Stunned);
public bool CanUse() => (!Stunned);
public bool CanThrow() => (!Stunned);
public bool CanSpeak() => true;
public bool CanDrop() => (!Stunned);
public bool CanPickup() => (!Stunned);
public bool CanEmote() => true;
public bool CanAttack() => (!Stunned);
public bool CanEquip() => (!Stunned);
public bool CanUnequip() => (!Stunned);
public bool CanChangeDirection() => true;
#endregion
[ViewVariables]
public float WalkSpeedModifier => (SlowedDown ? (WalkModifierOverride <= 0f ? 0.5f : WalkModifierOverride) : 1f);
[ViewVariables]
public float SprintSpeedModifier => (SlowedDown ? (RunModifierOverride <= 0f ? 0.5f : RunModifierOverride) : 1f);
[Serializable, NetSerializable]
protected sealed class StunnableComponentState : ComponentState
{
public bool Stunned { get; }
public bool KnockedDown { get; }
public bool SlowedDown { get; }
public float WalkModifierOverride { get; }
public float RunModifierOverride { get; }
public StunnableComponentState(bool stunned, bool knockedDown, bool slowedDown, float walkModifierOverride, float runModifierOverride) : base(ContentNetIDs.STUNNABLE)
{
Stunned = stunned;
KnockedDown = knockedDown;
SlowedDown = slowedDown;
WalkModifierOverride = walkModifierOverride;
RunModifierOverride = runModifierOverride;
}
}
}
}

View File

@@ -0,0 +1,59 @@
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Map;
using Robust.Shared.Maths;
namespace Content.Shared.GameObjects.Components.Movement
{
// Does nothing except ensure uniqueness between mover components.
// There can only be one.
public interface IMoverComponent : IComponent
{
/// <summary>
/// Movement speed (m/s) that the entity walks.
/// </summary>
float CurrentWalkSpeed { get; }
/// <summary>
/// Movement speed (m/s) that the entity sprints.
/// </summary>
float CurrentSprintSpeed { get; }
/// <summary>
/// The movement speed (m/s) of the entity when it pushes off of a solid object in zero gravity.
/// </summary>
float CurrentPushSpeed { get; }
/// <summary>
/// How far an entity can reach (in meters) to grab hold of a solid object in zero gravity.
/// </summary>
float GrabRange { get; }
/// <summary>
/// Is the entity Sprinting (running)?
/// </summary>
bool Sprinting { get; }
/// <summary>
/// Calculated linear velocity direction of the entity.
/// </summary>
(Vector2 walking, Vector2 sprinting) VelocityDir { get; }
GridCoordinates LastPosition { get; set; }
float StepSoundDistance { get; set; }
/// <summary>
/// Toggles one of the four cardinal directions. Each of the four directions are
/// composed into a single direction vector, <see cref="PlayerInputMoverComponent.VelocityDir"/>. Enabling
/// opposite directions will cancel each other out, resulting in no direction.
/// </summary>
/// <param name="direction">Direction to toggle.</param>
/// <param name="subTick"></param>
/// <param name="enabled">If the direction is active.</param>
void SetVelocityDirection(Direction direction, ushort subTick, bool enabled);
void SetSprinting(ushort subTick, bool enabled);
}
}

View File

@@ -0,0 +1,9 @@
using Robust.Shared.Players;
namespace Content.Shared.GameObjects.Components.Movement
{
public interface IRelayMoveInput
{
void MoveInputPressed(ICommonSession session);
}
}

View File

@@ -0,0 +1,92 @@
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
namespace Content.Shared.GameObjects.Components.Movement
{
[RegisterComponent]
public class MovementSpeedModifierComponent : Component
{
public const float DefaultBaseWalkSpeed = 4.0f;
public const float DefaultBaseSprintSpeed = 7.0f;
public override string Name => "MovementSpeedModifier";
private float _cachedWalkSpeedModifier = 1.0f;
[ViewVariables]
public float WalkSpeedModifier
{
get
{
RecalculateMovementSpeedModifiers();
return _cachedWalkSpeedModifier;
}
}
private float _cachedSprintSpeedModifier;
[ViewVariables]
public float SprintSpeedModifier
{
get
{
RecalculateMovementSpeedModifiers();
return _cachedSprintSpeedModifier;
}
}
[ViewVariables(VVAccess.ReadWrite)]
public float BaseWalkSpeed { get; set; }
[ViewVariables(VVAccess.ReadWrite)]
public float BaseSprintSpeed { get; set; }
[ViewVariables]
public float CurrentWalkSpeed => WalkSpeedModifier * BaseWalkSpeed;
[ViewVariables]
public float CurrentSprintSpeed => SprintSpeedModifier * BaseSprintSpeed;
/// <summary>
/// set to warn us that a component's movespeed modifier has changed
/// </summary>
private bool _movespeedModifiersNeedRefresh = true;
public void RefreshMovementSpeedModifiers()
{
_movespeedModifiersNeedRefresh = true;
}
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(this, p => p.BaseWalkSpeed, "baseWalkSpeed", 4);
serializer.DataField(this, p => p.BaseSprintSpeed, "baseSprintSpeed", 7);
}
/// <summary>
/// Recalculate movement speed with current modifiers, or return early if no change
/// </summary>
private void RecalculateMovementSpeedModifiers()
{
{
if (!_movespeedModifiersNeedRefresh)
return;
var movespeedModifiers = Owner.GetAllComponents<IMoveSpeedModifier>();
float walkSpeedModifier = 1.0f;
float sprintSpeedModifier = 1.0f;
foreach (var component in movespeedModifiers)
{
walkSpeedModifier *= component.WalkSpeedModifier;
sprintSpeedModifier *= component.SprintSpeedModifier;
}
_cachedWalkSpeedModifier = walkSpeedModifier;
_cachedSprintSpeedModifier = sprintSpeedModifier;
}
_movespeedModifiersNeedRefresh = false;
}
}
public interface IMoveSpeedModifier
{
float WalkSpeedModifier { get; }
float SprintSpeedModifier { get; }
}
}

View File

@@ -0,0 +1,287 @@
using System;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.Configuration;
using Robust.Shared.Interfaces.Timing;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Map;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Serialization;
using Robust.Shared.Timing;
using Robust.Shared.ViewVariables;
#nullable enable
namespace Content.Shared.GameObjects.Components.Movement
{
public abstract class SharedPlayerInputMoverComponent : Component, IMoverComponent
{
// This class has to be able to handle server TPS being lower than client FPS.
// While still having perfectly responsive movement client side.
// We do this by keeping track of the exact sub-tick values that inputs are pressed on the client,
// and then building a total movement vector based on those sub-tick steps.
//
// We keep track of the last sub-tick a movement input came in,
// Then when a new input comes in, we calculate the fraction of the tick the LAST input was active for
// (new sub-tick - last sub-tick)
// and then add to the total-this-tick movement vector
// by multiplying that fraction by the movement direction for the last input.
// This allows us to incrementally build the movement vector for the current tick,
// without having to keep track of some kind of list of inputs and calculating it later.
//
// We have to keep track of a separate movement vector for walking and sprinting,
// since we don't actually know our current movement speed while processing inputs.
// We change which vector we write into based on whether we were sprinting after the previous input.
// (well maybe we do but the code is designed such that MoverSystem applies movement speed)
// (and I'm not changing that)
[Dependency] private readonly IConfigurationManager _configurationManager = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
public sealed override string Name => "PlayerInputMover";
public sealed override uint? NetID => ContentNetIDs.PLAYER_INPUT_MOVER;
private GameTick _lastInputTick;
private ushort _lastInputSubTick;
private Vector2 _curTickWalkMovement;
private Vector2 _curTickSprintMovement;
private MoveButtons _heldMoveButtons = MoveButtons.None;
public float CurrentWalkSpeed
{
get
{
if (Owner.TryGetComponent(out MovementSpeedModifierComponent component))
{
return component.CurrentWalkSpeed;
}
return MovementSpeedModifierComponent.DefaultBaseWalkSpeed;
}
}
public float CurrentSprintSpeed
{
get
{
if (Owner.TryGetComponent(out MovementSpeedModifierComponent component))
{
return component.CurrentSprintSpeed;
}
return MovementSpeedModifierComponent.DefaultBaseSprintSpeed;
}
}
public float CurrentPushSpeed => 5;
public float GrabRange => 0.2f;
public bool Sprinting => !_heldMoveButtons.HasFlag(MoveButtons.Sprint);
/// <summary>
/// Calculated linear velocity direction of the entity.
/// </summary>
[ViewVariables]
public (Vector2 walking, Vector2 sprinting) VelocityDir
{
get
{
if (!_gameTiming.InSimulation)
{
// Outside of simulation we'll be running client predicted movement per-frame.
// So return a full-length vector as if it's a full tick.
// Physics system will have the correct time step anyways.
var immediateDir = DirVecForButtons(_heldMoveButtons);
return Sprinting ? (Vector2.Zero, immediateDir) : (immediateDir, Vector2.Zero);
}
Vector2 walk;
Vector2 sprint;
float remainingFraction;
if (_gameTiming.CurTick > _lastInputTick)
{
walk = Vector2.Zero;
sprint = Vector2.Zero;
remainingFraction = 1;
}
else
{
walk = _curTickWalkMovement;
sprint = _curTickSprintMovement;
remainingFraction = (ushort.MaxValue - _lastInputSubTick) / (float) ushort.MaxValue;
}
var curDir = DirVecForButtons(_heldMoveButtons) * remainingFraction;
if (Sprinting)
{
sprint += curDir;
}
else
{
walk += curDir;
}
// Logger.Info($"{curDir}{walk}{sprint}");
return (walk, sprint);
}
}
public abstract GridCoordinates LastPosition { get; set; }
public abstract float StepSoundDistance { get; set; }
/// <summary>
/// Whether or not the player can move diagonally.
/// </summary>
[ViewVariables]
public bool DiagonalMovementEnabled => _configurationManager.GetCVar<bool>("game.diagonalmovement");
/// <inheritdoc />
public override void OnAdd()
{
// This component requires that the entity has a PhysicsComponent.
if (!Owner.HasComponent<SharedPhysicsComponent>())
Logger.Error(
$"[ECS] {Owner.Prototype?.Name} - {nameof(SharedPlayerInputMoverComponent)} requires" +
$" {nameof(SharedPhysicsComponent)}. ");
base.OnAdd();
}
/// <summary>
/// Toggles one of the four cardinal directions. Each of the four directions are
/// composed into a single direction vector, <see cref="VelocityDir"/>. Enabling
/// opposite directions will cancel each other out, resulting in no direction.
/// </summary>
/// <param name="direction">Direction to toggle.</param>
/// <param name="subTick"></param>
/// <param name="enabled">If the direction is active.</param>
public void SetVelocityDirection(Direction direction, ushort subTick, bool enabled)
{
// Logger.Info($"[{_gameTiming.CurTick}/{subTick}] {direction}: {enabled}");
var bit = direction switch
{
Direction.East => MoveButtons.Right,
Direction.North => MoveButtons.Up,
Direction.West => MoveButtons.Left,
Direction.South => MoveButtons.Down,
_ => throw new ArgumentException(nameof(direction))
};
SetMoveInput(subTick, enabled, bit);
}
private void SetMoveInput(ushort subTick, bool enabled, MoveButtons bit)
{
// Modifies held state of a movement button at a certain sub tick and updates current tick movement vectors.
if (_gameTiming.CurTick > _lastInputTick)
{
_curTickWalkMovement = Vector2.Zero;
_curTickSprintMovement = Vector2.Zero;
_lastInputTick = _gameTiming.CurTick;
_lastInputSubTick = 0;
}
var fraction = (subTick - _lastInputSubTick) / (float) ushort.MaxValue;
ref var lastMoveAmount = ref Sprinting ? ref _curTickSprintMovement : ref _curTickWalkMovement;
lastMoveAmount += DirVecForButtons(_heldMoveButtons) * fraction;
if (enabled)
{
_heldMoveButtons |= bit;
}
else
{
_heldMoveButtons &= ~bit;
}
_lastInputSubTick = subTick;
Dirty();
}
public void SetSprinting(ushort subTick, bool enabled)
{
// Logger.Info($"[{_gameTiming.CurTick}/{subTick}] Sprint: {enabled}");
SetMoveInput(subTick, enabled, MoveButtons.Sprint);
}
public override void HandleComponentState(ComponentState? curState, ComponentState? nextState)
{
if (curState is MoverComponentState state)
{
_heldMoveButtons = state.Buttons;
_lastInputTick = GameTick.Zero;
_lastInputSubTick = 0;
}
}
public override ComponentState GetComponentState()
{
return new MoverComponentState(_heldMoveButtons);
}
/// <summary>
/// Retrieves the normalized direction vector for a specified combination of movement keys.
/// </summary>
private Vector2 DirVecForButtons(MoveButtons buttons)
{
// key directions are in screen coordinates
// _moveDir is in world coordinates
// if the camera is moved, this needs to be changed
var x = 0;
x -= buttons.HasFlag(MoveButtons.Left) ? 1 : 0;
x += buttons.HasFlag(MoveButtons.Right) ? 1 : 0;
var y = 0;
if (DiagonalMovementEnabled || x == 0)
{
y -= buttons.HasFlag(MoveButtons.Down) ? 1 : 0;
y += buttons.HasFlag(MoveButtons.Up) ? 1 : 0;
}
var vec = new Vector2(x, y);
// can't normalize zero length vector
if (vec.LengthSquared > 1.0e-6)
{
// Normalize so that diagonals aren't faster or something.
vec = vec.Normalized;
}
return vec;
}
[Serializable, NetSerializable]
private sealed class MoverComponentState : ComponentState
{
public MoveButtons Buttons { get; }
public MoverComponentState(MoveButtons buttons) : base(ContentNetIDs
.PLAYER_INPUT_MOVER)
{
Buttons = buttons;
}
}
[Flags]
private enum MoveButtons : byte
{
None = 0,
Up = 1,
Down = 2,
Left = 4,
Right = 8,
Sprint = 16,
}
}
}

View File

@@ -0,0 +1,60 @@
using System;
using Content.Shared.GameObjects.Components.Movement;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
namespace Content.Shared.GameObjects.Components.Nutrition
{
public abstract class SharedHungerComponent : Component, IMoveSpeedModifier
{
public sealed override string Name => "Hunger";
public sealed override uint? NetID => ContentNetIDs.HUNGER;
public abstract HungerThreshold CurrentHungerThreshold { get; }
float IMoveSpeedModifier.WalkSpeedModifier
{
get
{
if (CurrentHungerThreshold == HungerThreshold.Starving)
{
return 0.5f;
}
return 1.0f;
}
}
float IMoveSpeedModifier.SprintSpeedModifier
{
get
{
if (CurrentHungerThreshold == HungerThreshold.Starving)
{
return 0.5f;
}
return 1.0f;
}
}
[Serializable, NetSerializable]
protected sealed class HungerComponentState : ComponentState
{
public HungerThreshold CurrentThreshold { get; }
public HungerComponentState(HungerThreshold currentThreshold) : base(ContentNetIDs.HUNGER)
{
CurrentThreshold = currentThreshold;
}
}
}
public enum HungerThreshold : byte
{
Overfed,
Okay,
Peckish,
Starving,
Dead,
}
}

View File

@@ -0,0 +1,61 @@
using System;
using Content.Shared.GameObjects.Components.Movement;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
namespace Content.Shared.GameObjects.Components.Nutrition
{
public abstract class SharedThirstComponent : Component, IMoveSpeedModifier
{
public sealed override string Name => "Thirst";
public sealed override uint? NetID => ContentNetIDs.THIRST;
public abstract ThirstThreshold CurrentThirstThreshold { get; }
float IMoveSpeedModifier.SprintSpeedModifier
{
get
{
if (CurrentThirstThreshold == ThirstThreshold.Parched)
{
return 0.25f;
}
return 1.0f;
}
}
float IMoveSpeedModifier.WalkSpeedModifier
{
get
{
if (CurrentThirstThreshold == ThirstThreshold.Parched)
{
return 0.5f;
}
return 1.0f;
}
}
[Serializable, NetSerializable]
protected sealed class ThirstComponentState : ComponentState
{
public ThirstThreshold CurrentThreshold { get; }
public ThirstComponentState(ThirstThreshold currentThreshold) : base(ContentNetIDs.THIRST)
{
CurrentThreshold = currentThreshold;
}
}
}
public enum ThirstThreshold : byte
{
// Hydrohomies
OverHydrated,
Okay,
Thirsty,
Parched,
Dead,
}
}

View File

@@ -1,13 +1,22 @@
using System;
using Content.Shared.GameObjects.EntitySystems;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization;
namespace Content.Shared.GameObjects.Components.Observer
{
public class SharedGhostComponent : Component
public class SharedGhostComponent : Component, IActionBlocker
{
public override string Name => "Ghost";
public override uint? NetID => ContentNetIDs.GHOST;
public bool CanInteract() => false;
public bool CanUse() => false;
public bool CanThrow() => false;
public bool CanDrop() => false;
public bool CanPickup() => false;
public bool CanEmote() => false;
public bool CanAttack() => false;
}
[Serializable, NetSerializable]

View File

@@ -50,6 +50,10 @@
public const uint PDA = 1044;
public const uint PATHFINDER_DEBUG = 1045;
public const uint AI_DEBUG = 1046;
public const uint PLAYER_INPUT_MOVER = 1047;
public const uint STUNNABLE = 1048;
public const uint HUNGER = 1049;
public const uint THIRST = 1050;
// Net IDs for integration tests.
public const uint PREDICTION_TEST = 10001;

View File

@@ -0,0 +1,162 @@
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.GameObjects;
namespace Content.Shared.GameObjects.EntitySystems
{
public interface IActionBlocker
{
bool CanMove() => true;
bool CanInteract() => true;
bool CanUse() => true;
bool CanThrow() => true;
bool CanSpeak() => true;
bool CanDrop() => true;
bool CanPickup() => true;
bool CanEmote() => true;
bool CanAttack() => true;
bool CanEquip() => true;
bool CanUnequip() => true;
bool CanChangeDirection() => true;
}
public class ActionBlockerSystem : EntitySystem
{
public static bool CanMove(IEntity entity)
{
bool canmove = true;
foreach(var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
canmove &= actionblockercomponents.CanMove(); //sets var to false if false
}
return canmove;
}
public static bool CanInteract(IEntity entity)
{
bool caninteract = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
caninteract &= actionblockercomponents.CanInteract();
}
return caninteract;
}
public static bool CanUse(IEntity entity)
{
bool canuse = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
canuse &= actionblockercomponents.CanUse();
}
return canuse;
}
public static bool CanThrow(IEntity entity)
{
bool canthrow = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
canthrow &= actionblockercomponents.CanThrow();
}
return canthrow;
}
public static bool CanSpeak(IEntity entity)
{
bool canspeak = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
canspeak &= actionblockercomponents.CanSpeak();
}
return canspeak;
}
public static bool CanDrop(IEntity entity)
{
bool candrop = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
candrop &= actionblockercomponents.CanDrop();
}
return candrop;
}
public static bool CanPickup(IEntity entity)
{
bool canpickup = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
canpickup &= actionblockercomponents.CanPickup();
}
return canpickup;
}
public static bool CanEmote(IEntity entity)
{
bool canemote = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
canemote &= actionblockercomponents.CanEmote();
}
return canemote;
}
public static bool CanAttack(IEntity entity)
{
bool canattack = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
canattack &= actionblockercomponents.CanAttack();
}
return canattack;
}
public static bool CanEquip(IEntity entity)
{
bool canequip = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
canequip &= actionblockercomponents.CanEquip();
}
return canequip;
}
public static bool CanUnequip(IEntity entity)
{
bool canunequip = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
canunequip &= actionblockercomponents.CanUnequip();
}
return canunequip;
}
public static bool CanChangeDirection(IEntity entity)
{
bool canchangedirection = true;
foreach (var actionblockercomponents in entity.GetAllComponents<IActionBlocker>())
{
canchangedirection &= actionblockercomponents.CanChangeDirection();
}
return canchangedirection;
}
}
}

View File

@@ -0,0 +1,235 @@
using System.Diagnostics.CodeAnalysis;
using Content.Shared.GameObjects.Components.Movement;
using Content.Shared.Physics;
using Robust.Shared.Configuration;
using Robust.Shared.GameObjects;
using Robust.Shared.GameObjects.Components;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Input;
using Robust.Shared.Input.Binding;
using Robust.Shared.Interfaces.Configuration;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.GameObjects.Components;
using Robust.Shared.Interfaces.Map;
using Robust.Shared.Interfaces.Physics;
using Robust.Shared.Interfaces.Random;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
using Robust.Shared.Players;
using Robust.Shared.Prototypes;
#nullable enable
namespace Content.Shared.GameObjects.EntitySystems
{
public abstract class SharedMoverSystem : EntitySystem
{
// [Dependency] private readonly IPauseManager _pauseManager;
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly ITileDefinitionManager _tileDefinitionManager = default!;
[Dependency] private readonly IMapManager _mapManager = default!;
[Dependency] private readonly IRobustRandom _robustRandom = default!;
[Dependency] private readonly IEntityManager _entityManager = default!;
[Dependency] private readonly IPhysicsManager _physicsManager = default!;
[Dependency] private readonly IConfigurationManager _configurationManager = default!;
public override void Initialize()
{
base.Initialize();
EntityQuery = new TypeEntityQuery(typeof(IMoverComponent));
var moveUpCmdHandler = new MoverDirInputCmdHandler(Direction.North);
var moveLeftCmdHandler = new MoverDirInputCmdHandler(Direction.West);
var moveRightCmdHandler = new MoverDirInputCmdHandler(Direction.East);
var moveDownCmdHandler = new MoverDirInputCmdHandler(Direction.South);
CommandBinds.Builder
.Bind(EngineKeyFunctions.MoveUp, moveUpCmdHandler)
.Bind(EngineKeyFunctions.MoveLeft, moveLeftCmdHandler)
.Bind(EngineKeyFunctions.MoveRight, moveRightCmdHandler)
.Bind(EngineKeyFunctions.MoveDown, moveDownCmdHandler)
.Bind(EngineKeyFunctions.Run, new SprintInputCmdHandler())
.Register<SharedMoverSystem>();
_configurationManager.RegisterCVar("game.diagonalmovement", true, CVar.ARCHIVE);
}
/// <inheritdoc />
public override void Shutdown()
{
CommandBinds.Unregister<SharedMoverSystem>();
base.Shutdown();
}
protected void UpdateKinematics(ITransformComponent transform, IMoverComponent mover, SharedPhysicsComponent physics,
CollidableComponent? collider = null)
{
if (physics.Controller == null)
{
// Set up controller
SetController(physics);
}
var weightless = !transform.Owner.HasComponent<MovementIgnoreGravityComponent>() &&
_physicsManager.IsWeightless(transform.GridPosition);
if (weightless && collider != null)
{
// No gravity: is our entity touching anything?
var touching = IsAroundCollider(transform, mover, collider);
if (!touching)
{
return;
}
}
// TODO: movement check.
var (walkDir, sprintDir) = mover.VelocityDir;
var combined = walkDir + sprintDir;
if (combined.LengthSquared < 0.001 || !ActionBlockerSystem.CanMove(mover.Owner) && !weightless)
{
(physics.Controller as MoverController)?.StopMoving();
}
else
{
//Console.WriteLine($"{IoCManager.Resolve<IGameTiming>().TickStamp}: {combined}");
if (weightless)
{
(physics.Controller as MoverController)?.Push(combined, mover.CurrentPushSpeed);
transform.LocalRotation = walkDir.GetDir().ToAngle();
return;
}
var total = walkDir * mover.CurrentWalkSpeed + sprintDir * mover.CurrentSprintSpeed;
//Console.WriteLine($"{walkDir} ({mover.CurrentWalkSpeed}) + {sprintDir} ({mover.CurrentSprintSpeed}): {total}");
(physics.Controller as MoverController)?.Move(total, 1);
transform.LocalRotation = total.GetDir().ToAngle();
HandleFootsteps(mover);
}
}
protected virtual void HandleFootsteps(IMoverComponent mover)
{
}
protected abstract void SetController(SharedPhysicsComponent physics);
private bool IsAroundCollider(ITransformComponent transform, IMoverComponent mover,
CollidableComponent collider)
{
foreach (var entity in _entityManager.GetEntitiesInRange(transform.Owner, mover.GrabRange, true))
{
if (entity == transform.Owner)
{
continue; // Don't try to push off of yourself!
}
if (!entity.TryGetComponent<CollidableComponent>(out var otherCollider))
{
continue;
}
// TODO: Item check.
var touching = ((collider.CollisionMask & otherCollider.CollisionLayer) != 0x0
|| (otherCollider.CollisionMask & collider.CollisionLayer) != 0x0) // Ensure collision
&& true; // !entity.HasComponent<ItemComponent>(); // This can't be an item
if (touching)
{
return true;
}
}
return false;
}
private static void HandleDirChange(ICommonSession? session, Direction dir, ushort subTick, bool state)
{
if (!TryGetAttachedComponent<IMoverComponent>(session, out var moverComp))
return;
var owner = session?.AttachedEntity;
if (owner != null)
{
foreach (var comp in owner.GetAllComponents<IRelayMoveInput>())
{
comp.MoveInputPressed(session);
}
}
moverComp.SetVelocityDirection(dir, subTick, state);
}
private static void HandleRunChange(ICommonSession? session, ushort subTick, bool running)
{
if (!TryGetAttachedComponent<IMoverComponent>(session, out var moverComp))
{
return;
}
moverComp.SetSprinting(subTick, running);
}
private static bool TryGetAttachedComponent<T>(ICommonSession? session, [MaybeNullWhen(false)] out T component)
where T : IComponent
{
component = default;
var ent = session?.AttachedEntity;
if (ent == null || !ent.IsValid())
return false;
if (!ent.TryGetComponent(out T comp))
return false;
component = comp;
return true;
}
private sealed class MoverDirInputCmdHandler : InputCmdHandler
{
private readonly Direction _dir;
public MoverDirInputCmdHandler(Direction dir)
{
_dir = dir;
}
public override bool HandleCmdMessage(ICommonSession? session, InputCmdMessage message)
{
if (!(message is FullInputCmdMessage full))
{
return false;
}
HandleDirChange(session, _dir, message.SubTick, full.State == BoundKeyState.Down);
return false;
}
}
private sealed class SprintInputCmdHandler : InputCmdHandler
{
public override bool HandleCmdMessage(ICommonSession? session, InputCmdMessage message)
{
if (!(message is FullInputCmdMessage full))
{
return false;
}
HandleRunChange(session, full.SubTick, full.State == BoundKeyState.Down);
return false;
}
}
}
}

View File

@@ -30,7 +30,7 @@ namespace Content.Shared.Physics
public void Move(Vector2 velocityDirection, float speed)
{
if (!_component.Owner.HasComponent<MovementIgnoreGravityComponent>() && IoCManager
.Resolve<IPhysicsManager>().IsWeightless(_component.Owner.Transform.GridPosition)) return;
.Resolve<IPhysicsManager>().IsWeightless(_component.Owner.Transform.GridPosition) && false) return;
Push(velocityDirection, speed);
}