Unstable 0.1500.2.0 (Rokvach's dog edition)

This commit is contained in:
Markus Isberg
2021-09-10 04:52:34 +09:00
parent e7b7c1a748
commit 1231170fce
126 changed files with 2424 additions and 1083 deletions
@@ -1,5 +1,6 @@
using Barotrauma.Items.Components;
using Barotrauma.Networking;
using FarseerPhysics;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
@@ -95,14 +96,26 @@ namespace Barotrauma
}
}
protected bool HasValidPath(bool requireNonDirty = false) =>
steeringManager is IndoorsSteeringManager pathSteering && pathSteering.CurrentPath != null && !pathSteering.CurrentPath.Finished && !pathSteering.CurrentPath.Unreachable && (!requireNonDirty || !pathSteering.IsPathDirty);
public bool HasValidPath(bool requireNonDirty = false, bool requireUnfinished = true) =>
steeringManager is IndoorsSteeringManager pathSteering &&
pathSteering.CurrentPath != null &&
(!requireUnfinished || !pathSteering.CurrentPath.Finished) &&
!pathSteering.CurrentPath.Unreachable &&
(!requireNonDirty || !pathSteering.IsPathDirty);
protected readonly float colliderWidth;
protected readonly float colliderLength;
protected readonly float avoidLookAheadDistance;
public AIController (Character c)
{
Character = c;
hullVisibilityTimer = Rand.Range(0f, hullVisibilityTimer);
Enabled = true;
var size = Character.AnimController.Collider.GetSize();
colliderWidth = size.X;
colliderLength = size.Y;
avoidLookAheadDistance = Math.Max(Math.Max(colliderWidth, colliderLength) * 3, 1.5f);
}
public virtual void OnAttacked(Character attacker, AttackResult attackResult) { }
@@ -327,6 +340,119 @@ namespace Barotrauma
unequippedItems.Clear();
}
#region Escape
public abstract void Escape(float deltaTime);
public Gap EscapeTarget { get; private set; }
private readonly float escapeTargetSeekInterval = 2;
private float escapeTimer;
protected bool allGapsSearched;
protected readonly HashSet<Gap> unreachableGaps = new HashSet<Gap>();
protected bool UpdateEscape(float deltaTime, bool canAttackDoors)
{
IndoorsSteeringManager pathSteering = SteeringManager as IndoorsSteeringManager;
if (allGapsSearched)
{
escapeTimer -= deltaTime;
if (escapeTimer <= 0)
{
allGapsSearched = false;
}
}
if (Character.CurrentHull != null && pathSteering != null)
{
// Seek exit if inside
if (!allGapsSearched)
{
float closestDistance = 0;
foreach (Gap gap in Gap.GapList)
{
if (gap == null || gap.Removed) { continue; }
if (EscapeTarget == gap) { continue; }
if (unreachableGaps.Contains(gap)) { continue; }
if (gap.Submarine != Character.Submarine) { continue; }
if (gap.IsRoomToRoom) { continue; }
float multiplier = 1;
var door = gap.ConnectedDoor;
if (door != null)
{
if (!door.CanBeTraversed)
{
if (!door.HasAccess(Character))
{
if (!canAttackDoors) { continue; }
// Treat doors that don't have access to like they were farther, because it will take time to break them.
multiplier = 5;
}
}
}
else
{
if (gap.Open < 1) { continue; }
bool canGetThrough = ConvertUnits.ToDisplayUnits(colliderWidth) < gap.Size;
if (!canGetThrough) { continue; }
}
if (gap.FlowTargetHull == Character.CurrentHull)
{
// If the gap is in the same room, it's close enough.
EscapeTarget = gap;
break;
}
float distance = Vector2.DistanceSquared(Character.WorldPosition, gap.WorldPosition) * multiplier;
if (EscapeTarget == null || distance < closestDistance)
{
EscapeTarget = gap;
closestDistance = distance;
}
}
allGapsSearched = true;
escapeTimer = escapeTargetSeekInterval;
}
else if (EscapeTarget != null && EscapeTarget.FlowTargetHull != Character.CurrentHull)
{
if (pathSteering.CurrentPath != null && !pathSteering.IsPathDirty && pathSteering.CurrentPath.Unreachable)
{
unreachableGaps.Add(EscapeTarget);
EscapeTarget = null;
allGapsSearched = false;
}
}
}
if (EscapeTarget != null)
{
SteeringManager.SteeringSeek(EscapeTarget.SimPosition, 10);
float sqrDist = Vector2.DistanceSquared(Character.SimPosition, EscapeTarget.SimPosition);
if (sqrDist < 0.5f || Character.CurrentHull == null || HasValidPath(requireNonDirty: true, requireUnfinished: false) && pathSteering.CurrentPath.Finished)
{
// Very close to the target, outside, or at the end of the path -> just steer towards it manually without using the path
SteeringManager.Reset();
SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(EscapeTarget.WorldPosition - Character.WorldPosition));
if (sqrDist < 4)
{
return true;
}
}
}
else
{
// Can't find the target
EscapeTarget = null;
allGapsSearched = false;
unreachableGaps.Clear();
}
return false;
}
public void ResetEscape()
{
EscapeTarget = null;
allGapsSearched = false;
unreachableGaps.Clear();
}
#endregion
protected virtual void OnStateChanged(AIState from, AIState to) { }
protected virtual void OnTargetChanged(AITarget previousTarget, AITarget newTarget) { }
@@ -60,8 +60,6 @@ namespace Barotrauma
// Min priority for the memorized targets. The actual value fades gradually, unless kept fresh by selecting the target.
private const float minPriority = 10;
private readonly float avoidLookAheadDistance;
private IndoorsSteeringManager PathSteering => insideSteering as IndoorsSteeringManager;
private SteeringManager outsideSteering, insideSteering;
@@ -113,20 +111,21 @@ namespace Barotrauma
lastAttackUpdateTime = Timing.TotalTime;
}
}
public AITargetMemory SelectedTargetMemory => selectedTargetMemory;
private AITargetMemory selectedTargetMemory;
private float targetValue;
private CharacterParams.TargetParams selectedTargetingParams;
private Dictionary<AITarget, AITargetMemory> targetMemories;
private readonly float colliderWidth;
private readonly float colliderLength;
private readonly int requiredHoleCount;
private bool canAttackWalls;
public bool CanAttackDoors => canAttackDoors;
private bool canAttackDoors;
private bool canAttackCharacters;
public float PriorityFearIncrement => priorityFearIncreasement;
private readonly float priorityFearIncreasement = 2;
private readonly float memoryFadeTime = 0.5f;
@@ -299,12 +298,8 @@ namespace Barotrauma
steeringManager = outsideSteering;
State = AIState.Idle;
var size = Character.AnimController.Collider.GetSize();
colliderWidth = size.X;
colliderLength = size.Y;
requiredHoleCount = (int)Math.Ceiling(ConvertUnits.ToDisplayUnits(colliderWidth) / Structure.WallSectionSize);
avoidLookAheadDistance = Math.Max(Math.Max(colliderWidth, colliderLength) * 3, 1.5f);
myBodies = Character.AnimController.Limbs.Select(l => l.body.FarseerBody);
}
@@ -440,9 +435,9 @@ namespace Barotrauma
if (Math.Abs(Character.AnimController.movement.X) > 0.1f && !Character.AnimController.InWater &&
(GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer || Character.Controlled == Character))
{
if (SelectedAiTarget?.Entity != null || escapeTarget != null)
if (SelectedAiTarget?.Entity != null || EscapeTarget != null)
{
Entity t = SelectedAiTarget?.Entity ?? escapeTarget;
Entity t = SelectedAiTarget?.Entity ?? EscapeTarget;
float referencePos = Vector2.DistanceSquared(Character.WorldPosition, t.WorldPosition) > 100 * 100 && HasValidPath(true) ? PathSteering.CurrentPath.CurrentNode.WorldPosition.X : t.WorldPosition.X;
Character.AnimController.TargetDir = Character.WorldPosition.X < referencePos ? Direction.Right : Direction.Left;
}
@@ -585,7 +580,7 @@ namespace Barotrauma
case AIState.Escape:
case AIState.Flee:
run = true;
UpdateEscape(deltaTime);
Escape(deltaTime);
break;
case AIState.Avoid:
case AIState.PassiveAggressive:
@@ -602,7 +597,7 @@ namespace Barotrauma
run = true;
if (State == AIState.Avoid)
{
UpdateEscape(deltaTime);
Escape(deltaTime);
}
else
{
@@ -827,142 +822,6 @@ namespace Barotrauma
#endregion
#region Escape
private readonly float escapeTargetSeekInterval = 2;
private float escapeTimer;
private Gap escapeTarget;
private bool allGapsSearched;
private readonly HashSet<Gap> unreachableGaps = new HashSet<Gap>();
private void UpdateEscape(float deltaTime)
{
if (SelectedAiTarget != null && (SelectedAiTarget.Entity == null || SelectedAiTarget.Entity.Removed))
{
State = AIState.Idle;
return;
}
else if (selectedTargetMemory != null && SelectedAiTarget?.Entity is Character)
{
selectedTargetMemory.Priority += deltaTime * priorityFearIncreasement;
}
IndoorsSteeringManager pathSteering = SteeringManager as IndoorsSteeringManager;
bool hasValidPath = pathSteering?.CurrentPath != null && !pathSteering.IsPathDirty && !pathSteering.CurrentPath.Unreachable;
if (allGapsSearched)
{
escapeTimer -= deltaTime;
if (escapeTimer <= 0)
{
allGapsSearched = false;
}
}
if (Character.CurrentHull != null && pathSteering != null)
{
// Seek exit if inside
if (!allGapsSearched)
{
float closestDistance = 0;
foreach (Gap gap in Gap.GapList)
{
if (gap == null || gap.Removed) { continue; }
if (escapeTarget == gap) { continue; }
if (unreachableGaps.Contains(gap)) { continue; }
if (gap.Submarine != Character.Submarine) { continue; }
if (gap.IsRoomToRoom) { continue; }
float multiplier = 1;
var door = gap.ConnectedDoor;
if (door != null)
{
if (!door.CanBeTraversed)
{
if (!door.HasAccess(Character))
{
if (!canAttackDoors) { continue; }
// Treat doors that don't have access to like they were farther, because it will take time to break them.
multiplier = 5;
}
}
}
else
{
if (gap.Open < 1) { continue; }
bool canGetThrough = ConvertUnits.ToDisplayUnits(colliderWidth) < gap.Size;
if (!canGetThrough) { continue; }
}
if (gap.FlowTargetHull == Character.CurrentHull)
{
// If the gap is in the same room, it's close enough.
escapeTarget = gap;
break;
}
float distance = Vector2.DistanceSquared(Character.WorldPosition, gap.WorldPosition) * multiplier;
if (escapeTarget == null || distance < closestDistance)
{
escapeTarget = gap;
closestDistance = distance;
}
}
allGapsSearched = true;
escapeTimer = escapeTargetSeekInterval;
}
else if (escapeTarget != null && escapeTarget.FlowTargetHull != Character.CurrentHull)
{
if (pathSteering.CurrentPath != null && !pathSteering.IsPathDirty && pathSteering.CurrentPath.Unreachable)
{
unreachableGaps.Add(escapeTarget);
escapeTarget = null;
allGapsSearched = false;
}
}
}
if (escapeTarget != null && Character.CurrentHull != null && Vector2.DistanceSquared(Character.SimPosition, escapeTarget.SimPosition) > 0.5f)
{
if (hasValidPath && pathSteering.CurrentPath.Finished)
{
// Steer manually towards the gap
SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(escapeTarget.WorldPosition - Character.WorldPosition));
}
else if (SelectedAiTarget?.Entity is Character targetCharacter && targetCharacter.CurrentHull == Character.CurrentHull)
{
// Steer away from the target if in the same room
Vector2 escapeDir = Vector2.Normalize(SelectedAiTarget != null ? WorldPosition - SelectedAiTarget.WorldPosition : Character.AnimController.TargetMovement);
if (!MathUtils.IsValid(escapeDir)) { escapeDir = Vector2.UnitY; }
SteeringManager.SteeringManual(deltaTime, escapeDir);
return;
}
else if (pathSteering != null)
{
if (hasValidPath && canAttackDoors)
{
var door = pathSteering.CurrentPath.CurrentNode?.ConnectedDoor ?? pathSteering.CurrentPath.NextNode?.ConnectedDoor;
if (door != null && !door.CanBeTraversed && !door.HasAccess(Character))
{
if (SelectedAiTarget != door.Item.AiTarget || State != AIState.Attack)
{
SelectTarget(door.Item.AiTarget, selectedTargetMemory.Priority);
State = AIState.Attack;
return;
}
}
}
}
SteeringManager.SteeringSeek(escapeTarget.SimPosition, 10);
}
else
{
escapeTarget = null;
allGapsSearched = false;
Vector2 escapeDir = Vector2.Normalize(SelectedAiTarget != null ? WorldPosition - SelectedAiTarget.WorldPosition : Character.AnimController.TargetMovement);
if (!MathUtils.IsValid(escapeDir)) escapeDir = Vector2.UnitY;
SteeringManager.SteeringManual(deltaTime, escapeDir);
if (Character.CurrentHull == null)
{
SteeringManager.SteeringWander();
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: avoidLookAheadDistance, weight: 5);
}
}
}
#endregion
#region Attack
private Vector2 attackWorldPos;
@@ -3129,11 +2988,9 @@ namespace Barotrauma
{
LatchOntoAI?.DeattachFromBody(reset: true);
Character.AnimController.ReleaseStuckLimbs();
escapeTarget = null;
AttackingLimb = null;
movementMargin = 0;
allGapsSearched = false;
unreachableGaps.Clear();
ResetEscape();
if (isStateChanged && to == AIState.Idle && from != to)
{
SetStateResetTimer();
@@ -3283,6 +3140,71 @@ namespace Barotrauma
public bool CanPassThroughHole(Structure wall, int sectionIndex) => CanPassThroughHole(wall, sectionIndex, requiredHoleCount);
public override void Escape(float deltaTime)
{
if (SelectedAiTarget != null && (SelectedAiTarget.Entity == null || SelectedAiTarget.Entity.Removed))
{
State = AIState.Idle;
return;
}
else if (SelectedTargetMemory is AITargetMemory targetMemory && SelectedAiTarget?.Entity is Character)
{
targetMemory.Priority += deltaTime * PriorityFearIncrement;
}
bool isSteeringThroughGap = UpdateEscape(deltaTime, canAttackDoors);
if (!isSteeringThroughGap)
{
if (SelectedAiTarget?.Entity is Character targetCharacter && targetCharacter.CurrentHull == Character.CurrentHull)
{
SteerAwayFromTheEnemy();
}
else if (canAttackDoors && HasValidPath(requireNonDirty: true, requireUnfinished: true))
{
var door = PathSteering.CurrentPath.CurrentNode?.ConnectedDoor ?? PathSteering.CurrentPath.NextNode?.ConnectedDoor;
if (door != null && !door.CanBeTraversed && !door.HasAccess(Character))
{
if (SelectedAiTarget != door.Item.AiTarget || State != AIState.Attack)
{
SelectTarget(door.Item.AiTarget, SelectedTargetMemory.Priority);
State = AIState.Attack;
}
}
}
}
if (EscapeTarget == null)
{
if (SelectedAiTarget?.Entity is Character)
{
SteerAwayFromTheEnemy();
}
else
{
SteeringManager.SteeringWander();
if (Character.CurrentHull == null)
{
SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: avoidLookAheadDistance, weight: 5);
}
}
}
void SteerAwayFromTheEnemy()
{
if (SelectedAiTarget == null) { return; }
Vector2 escapeDir = Vector2.Normalize(WorldPosition - SelectedAiTarget.WorldPosition);
if (Character.CurrentHull != null && !Character.AnimController.InWater)
{
// Inside
escapeDir = new Vector2(Math.Sign(escapeDir.X), 0);
}
if (!MathUtils.IsValid(escapeDir))
{
escapeDir = Vector2.UnitY;
}
SteeringManager.Reset();
SteeringManager.SteeringManual(deltaTime, escapeDir);
}
}
private readonly List<Limb> targetLimbs = new List<Limb>();
public Limb GetTargetLimb(Limb attackLimb, Character target, LimbType targetLimbType = LimbType.None)
{
@@ -20,6 +20,11 @@ namespace Barotrauma
private float reactTimer;
private float unreachableClearTimer;
private bool shouldCrouch;
public bool IsInsideCave { get; private set; }
/// <summary>
/// Resets each frame
/// </summary>
public bool AutoFaceMovement = true;
const float reactionTime = 0.3f;
const float crouchRaycastInterval = 1;
@@ -52,7 +57,7 @@ namespace Barotrauma
private readonly float steeringBufferIncreaseSpeed = 100;
private float steeringBuffer;
private readonly float obstacleRaycastInterval = 1;
private readonly float obstacleRaycastIntervalShort = 1, obstacleRaycastIntervalLong = 5;
private float obstacleRaycastTimer;
private readonly float enemyCheckInterval = 0.2f;
@@ -86,6 +91,8 @@ namespace Barotrauma
private readonly SteeringManager outsideSteering, insideSteering;
public bool UseIndoorSteeringOutside { get; set; } = false;
public IndoorsSteeringManager PathSteering => insideSteering as IndoorsSteeringManager;
public HumanoidAnimController AnimController => Character.AnimController as HumanoidAnimController;
@@ -207,33 +214,78 @@ namespace Barotrauma
IgnoredItems.Clear();
}
bool IsCloseEnoughToTargetSub(float threshold) => SelectedAiTarget?.Entity?.Submarine is Submarine sub && sub != null && Vector2.DistanceSquared(Character.WorldPosition, sub.WorldPosition) < MathUtils.Pow(Math.Max(sub.Borders.Size.X, sub.Borders.Size.Y) / 2 + threshold, 2);
bool IsCloseEnoughToTarget(float threshold, bool useTargetSub = true)
{
Entity target = SelectedAiTarget?.Entity;
if (target == null)
{
return false;
}
if (useTargetSub)
{
if (target.Submarine is Submarine sub)
{
target = sub;
threshold += Math.Max(sub.Borders.Size.X, sub.Borders.Size.Y) / 2;
}
else
{
return false;
}
}
return Vector2.DistanceSquared(Character.WorldPosition, target.WorldPosition) < MathUtils.Pow(threshold, 2);
}
bool hasValidPath = HasValidPath();
if (Character.Submarine == null)
{
if (hasValidPath)
// When the character is outside, far enough from the target, and the direct route is blocked,
// use the indoor steering with the main and side path waypoints to help avoid getting stuck in level walls
if (SelectedAiTarget?.Entity != null && !IsCloseEnoughToTarget(2000, useTargetSub: false))
{
obstacleRaycastTimer -= deltaTime;
if (obstacleRaycastTimer <= 0)
{
obstacleRaycastTimer = obstacleRaycastInterval;
// Swimming outside and using the path finder -> check that the path is not blocked with anything (the path finder doesn't know about other subs).
foreach (var connectedSub in Submarine.MainSub.GetConnectedSubs())
obstacleRaycastTimer = obstacleRaycastIntervalLong;
Vector2 rayEnd = SelectedAiTarget.Entity.SimPosition;
if (SelectedAiTarget.Entity.Submarine != null)
{
if (connectedSub == Submarine.MainSub) { continue; }
Vector2 rayStart = SimPosition - connectedSub.SimPosition;
Vector2 dir = PathSteering.CurrentPath.CurrentNode.WorldPosition - WorldPosition;
Vector2 rayEnd = rayStart + dir.ClampLength(Character.AnimController.Collider.GetLocalFront().Length() * 5);
if (Submarine.CheckVisibility(rayStart, rayEnd, ignoreSubs: true) != null)
rayEnd += SelectedAiTarget.Entity.Submarine.SimPosition;
}
UseIndoorSteeringOutside = Submarine.PickBody(SimPosition, rayEnd, collisionCategory: Physics.CollisionLevel) != null;
}
}
else
{
UseIndoorSteeringOutside = false;
if (hasValidPath)
{
obstacleRaycastTimer -= deltaTime;
if (obstacleRaycastTimer <= 0)
{
obstacleRaycastTimer = obstacleRaycastIntervalShort;
// Swimming outside and using the path finder -> check that the path is not blocked with anything (the path finder doesn't know about other subs).
foreach (var connectedSub in Submarine.MainSub.GetConnectedSubs())
{
PathSteering.CurrentPath.Unreachable = true;
break;
if (connectedSub == Submarine.MainSub) { continue; }
Vector2 rayStart = SimPosition - connectedSub.SimPosition;
Vector2 dir = PathSteering.CurrentPath.CurrentNode.WorldPosition - WorldPosition;
Vector2 rayEnd = rayStart + dir.ClampLength(Character.AnimController.Collider.GetLocalFront().Length() * 5);
if (Submarine.CheckVisibility(rayStart, rayEnd, ignoreSubs: true) != null)
{
PathSteering.CurrentPath.Unreachable = true;
break;
}
}
}
}
}
}
else
{
UseIndoorSteeringOutside = false;
}
if (Character.Submarine == null || !IsOnFriendlyTeam(Character.TeamID, Character.Submarine.TeamID) && !Character.IsEscorted)
{
@@ -273,13 +325,31 @@ namespace Barotrauma
}
}
}
if (Character.Submarine != null || hasValidPath && IsCloseEnoughToTargetSub(maxSteeringBuffer) || IsCloseEnoughToTargetSub(steeringBuffer))
// Check whether the character is inside a cave
if (IsInsideCave)
{
// If the character was inside a cave, require them to move a bit further from the area to set the field back to false
// This is to avoid any twitchy behavior with the steering managers
IsInsideCave = Character.CurrentHull == null && Level.Loaded?.Caves.FirstOrDefault(c =>
{
var area = c.Area;
area.Inflate(new Vector2(100));
return area.Contains(Character.WorldPosition);
}) is Level.Cave;
}
else
{
IsInsideCave = Character.CurrentHull == null && Level.Loaded?.Caves.FirstOrDefault(c => c.Area.Contains(Character.WorldPosition)) is Level.Cave;
}
if (UseIndoorSteeringOutside || IsInsideCave || Character.Submarine != null || hasValidPath && IsCloseEnoughToTarget(maxSteeringBuffer) || IsCloseEnoughToTarget(steeringBuffer))
{
if (steeringManager != insideSteering)
{
insideSteering.Reset();
steeringManager = insideSteering;
}
steeringManager = insideSteering;
steeringBuffer += steeringBufferIncreaseSpeed * deltaTime;
}
else
@@ -287,8 +357,8 @@ namespace Barotrauma
if (steeringManager != outsideSteering)
{
outsideSteering.Reset();
steeringManager = outsideSteering;
}
steeringManager = outsideSteering;
steeringBuffer = minSteeringBuffer;
}
steeringBuffer = Math.Clamp(steeringBuffer, minSteeringBuffer, maxSteeringBuffer);
@@ -419,7 +489,7 @@ namespace Barotrauma
Character.SelectedConstruction.SecondaryUse(deltaTime, Character);
}
}
else if (Math.Abs(Character.AnimController.TargetMovement.X) > 0.1f && !Character.AnimController.InWater)
else if (AutoFaceMovement && Math.Abs(Character.AnimController.TargetMovement.X) > 0.1f && !Character.AnimController.InWater)
{
newDir = Character.AnimController.TargetMovement.X > 0.0f ? Direction.Right : Direction.Left;
}
@@ -429,6 +499,7 @@ namespace Barotrauma
flipTimer = FlipInterval;
}
}
AutoFaceMovement = true;
MentalStateManager?.Update(deltaTime);
ShipCommandManager?.Update(deltaTime);
@@ -1240,10 +1311,7 @@ namespace Barotrauma
{
var objective = new AIObjectiveCombat(Character, target, mode, objectiveManager)
{
HoldPosition =
Character.Info?.Job?.Prefab.Identifier == "watchman" ||
Character.CurrentHull == null ||
Character.IsOnPlayerTeam && !target.IsPlayer && ObjectiveManager.GetActiveObjective<AIObjectiveGoTo>()?.Target is Character followTarget && followTarget.IsPlayer,
HoldPosition = Character.Info?.Job?.Prefab.Identifier == "watchman",
AbortCondition = abortCondition,
allowHoldFire = allowHoldFire,
};
@@ -1293,6 +1361,11 @@ namespace Barotrauma
ObjectiveManager.WaitTimer = waitDuration;
}
public override void Escape(float deltaTime)
{
UpdateEscape(deltaTime, canAttackDoors: false);
}
private void CheckCrouching(float deltaTime)
{
crouchRaycastTimer -= deltaTime;
@@ -78,7 +78,7 @@ namespace Barotrauma
public IndoorsSteeringManager(ISteerable host, bool canOpenDoors, bool canBreakDoors) : base(host)
{
pathFinder = new PathFinder(WayPoint.WayPointList.FindAll(wp => wp.SpawnType == SpawnType.Path), indoorsSteering: true);
pathFinder = new PathFinder(WayPoint.WayPointList.FindAll(wp => wp.SpawnType == SpawnType.Path), true);
pathFinder.GetNodePenalty = GetNodePenalty;
this.canOpenDoors = canOpenDoors;
@@ -160,26 +160,34 @@ namespace Barotrauma
private Vector2 CalculateSteeringSeek(Vector2 target, float weight, Func<PathNode, bool> startNodeFilter = null, Func<PathNode, bool> endNodeFilter = null, Func<PathNode, bool> nodeFilter = null, bool checkVisibility = true)
{
Vector2 targetDiff = target - currentTarget;
if (currentPath != null && currentPath.Nodes.Any() && character.Submarine != null)
bool needsNewPath = currentPath == null || currentPath.Unreachable;
if (!needsNewPath && character.Submarine != null && character.Params.PathFinderPriority > 0.5f)
{
//target in a different sub than where the character is now
//take that into account when calculating if the target has moved
Submarine currentPathSub = currentPath?.CurrentNode?.Submarine;
if (currentPathSub == character.Submarine) { currentPathSub = currentPath?.Nodes.LastOrDefault()?.Submarine; }
if (currentPathSub != character.Submarine && targetDiff.LengthSquared() > 1 && currentPathSub != null)
Vector2 targetDiff = target - currentTarget;
if (currentPath != null && currentPath.Nodes.Any() && character.Submarine != null)
{
Vector2 subDiff = character.Submarine.SimPosition - currentPathSub.SimPosition;
targetDiff += subDiff;
//target in a different sub than where the character is now
//take that into account when calculating if the target has moved
Submarine currentPathSub = currentPath?.CurrentNode?.Submarine;
if (currentPathSub == character.Submarine) { currentPathSub = currentPath?.Nodes.LastOrDefault()?.Submarine; }
if (currentPathSub != character.Submarine && targetDiff.LengthSquared() > 1 && currentPathSub != null)
{
Vector2 subDiff = character.Submarine.SimPosition - currentPathSub.SimPosition;
targetDiff += subDiff;
}
}
if (targetDiff.LengthSquared() > 1)
{
needsNewPath = true;
}
}
bool needsNewPath = character.Params.PathFinderPriority > 0.5f && (currentPath == null || currentPath.Unreachable || targetDiff.LengthSquared() > 1);
//find a new path if one hasn't been found yet or the target is different from the current target
if (needsNewPath || findPathTimer < -1.0f)
{
IsPathDirty = true;
if (findPathTimer < 0)
{
SkipCurrentPathNodes();
currentTarget = target;
Vector2 currentPos = host.SimPosition;
if (character != null && character.Submarine == null)
@@ -193,7 +201,7 @@ namespace Barotrauma
pathFinder.InsideSubmarine = character.Submarine != null;
pathFinder.ApplyPenaltyToOutsideNodes = character.PressureProtection <= 0;
var newPath = pathFinder.FindPath(currentPos, target, character.Submarine, "(Character: " + character.Name + ")", startNodeFilter, endNodeFilter, nodeFilter, checkVisibility: checkVisibility);
bool useNewPath = needsNewPath || currentPath == null || currentPath.CurrentNode == null || findPathTimer < -1 && Math.Abs(character.AnimController.TargetMovement.X) <= 0;
bool useNewPath = needsNewPath || currentPath == null || currentPath.CurrentNode == null || character.Submarine != null && findPathTimer < -1 && Math.Abs(character.AnimController.TargetMovement.X) <= 0;
if (!useNewPath && currentPath != null && currentPath.CurrentNode != null && newPath.Nodes.Any() && !newPath.Unreachable)
{
// Check if the new path is the same as the old, in which case we just ignore it and continue using the old path (or the progress would reset).
@@ -206,7 +214,7 @@ namespace Barotrauma
// Use the new path if it has significantly lower cost (don't change the path if it has marginally smaller cost. This reduces navigating backwards due to new path that is calculated from the node just behind us).
float t = (float)currentPath.CurrentIndex / (currentPath.Nodes.Count - 1);
useNewPath = newPath.Cost < currentPath.Cost * MathHelper.Lerp(0.95f, 0, t);
if (!useNewPath)
if (!useNewPath && character.Submarine != null)
{
// It's possible that the current path was calculated from a start point that is no longer valid.
// Therefore, let's accept also paths with a greater cost than the current, if the current node is much farther than the new start node.
@@ -239,6 +247,32 @@ namespace Barotrauma
findPathTimer = priority * Rand.Range(1.0f, 1.2f);
IsPathDirty = false;
return DiffToCurrentNode();
void SkipCurrentPathNodes()
{
if (!character.AnimController.InWater || character.Submarine != null) { return; }
if (CurrentPath == null || CurrentPath.Unreachable || CurrentPath.Finished) { return; }
if (CurrentPath.CurrentIndex < 0 || CurrentPath.CurrentIndex >= CurrentPath.Nodes.Count - 1) { return; }
// Check if we could skip ahead to NextNode when the character is swimming and using waypoints outside.
// Do this to optimize the old path before creating and evaluating a new path.
// In general, this is to avoid behavior where:
// a) the character goes back to first reach CurrentNode when the second node would be closer; or
// b) the character moves along the path when they could cut through open space to reduce the total distance.
float pathDistance = Vector2.Distance(character.WorldPosition, CurrentPath.CurrentNode.WorldPosition);
pathDistance += CurrentPath.GetLength(startIndex: CurrentPath.CurrentIndex);
for (int i = CurrentPath.Nodes.Count - 1; i > CurrentPath.CurrentIndex + 1; i--)
{
var waypoint = CurrentPath.Nodes[i];
float directDistance = Vector2.DistanceSquared(character.WorldPosition, waypoint.WorldPosition);
if (directDistance > (pathDistance * pathDistance) || Submarine.PickBody(host.SimPosition, waypoint.SimPosition, collisionCategory: Physics.CollisionLevel) != null)
{
pathDistance -= CurrentPath.GetLength(startIndex: i - 1, endIndex: i);
continue;
}
CurrentPath.SkipToNode(i);
break;
}
}
}
}
@@ -278,18 +312,15 @@ namespace Barotrauma
CheckDoorsInPath();
}
Vector2 pos = host.SimPosition;
if (character != null && currentPath.CurrentNode != null)
if (character != null && CurrentPath.CurrentNode?.Submarine != null)
{
if (CurrentPath.CurrentNode.Submarine != null)
if (character.Submarine == null)
{
if (character.Submarine == null)
{
pos -= CurrentPath.CurrentNode.Submarine.SimPosition;
}
else if (character.Submarine != currentPath.CurrentNode.Submarine)
{
pos -= ConvertUnits.ToSimUnits(currentPath.CurrentNode.Submarine.Position - character.Submarine.Position);
}
pos -= CurrentPath.CurrentNode.Submarine.SimPosition;
}
else if (character.Submarine != currentPath.CurrentNode.Submarine)
{
pos -= ConvertUnits.ToSimUnits(currentPath.CurrentNode.Submarine.Position - character.Submarine.Position);
}
}
bool isDiving = character.AnimController.InWater && character.AnimController.HeadInWater;
@@ -94,7 +94,7 @@ namespace Barotrauma
if (_abandon)
{
#if DEBUG
if (HumanAIController.debugai && objectiveManager.IsOrder(this) && !objectiveManager.IsCurrentOrder<AIObjectiveGoTo>())
if (HumanAIController.debugai && objectiveManager.IsOrder(this) && !objectiveManager.IsCurrentOrder<AIObjectiveGoTo>() && !objectiveManager.IsCurrentOrder<AIObjectiveReturn>())
{
throw new Exception("Order abandoned!");
}
@@ -83,12 +83,13 @@ namespace Barotrauma
if (suitableContainer != null)
{
bool equip = item.GetComponent<Holdable>() != null ||
item.AllowedSlots.None(s =>
s == InvSlotType.Card ||
s == InvSlotType.Head ||
s == InvSlotType.Headset ||
s == InvSlotType.InnerClothes ||
s == InvSlotType.OuterClothes);
item.AllowedSlots.Any(s => s != InvSlotType.Any) &&
item.AllowedSlots.None(s =>
s == InvSlotType.Card ||
s == InvSlotType.Head ||
s == InvSlotType.Headset ||
s == InvSlotType.InnerClothes ||
s == InvSlotType.OuterClothes);
TryAddSubObjective(ref decontainObjective, () => new AIObjectiveDecontainItem(character, item, objectiveManager, targetContainer: suitableContainer.GetComponent<ItemContainer>())
{
@@ -252,9 +252,40 @@ namespace Barotrauma
{
case CombatMode.Offensive:
case CombatMode.Arrest:
Engage();
Engage(deltaTime);
break;
case CombatMode.Defensive:
if (character.IsOnPlayerTeam && !Enemy.IsPlayer && objectiveManager.IsCurrentOrder<AIObjectiveGoTo>())
{
if ((character.CurrentHull == null || character.CurrentHull == Enemy.CurrentHull) && sqrDistance < 200 * 200)
{
Engage(deltaTime);
}
else
{
// Keep following the goto target
var gotoObjective = objectiveManager.GetOrder<AIObjectiveGoTo>();
if (gotoObjective != null)
{
gotoObjective.ForceAct(deltaTime);
if (!character.AnimController.InWater)
{
HumanAIController.FaceTarget(Enemy);
ForceWalk = true;
HumanAIController.AutoFaceMovement = false;
}
}
else
{
SteeringManager.Reset();
}
}
}
else
{
Retreat(deltaTime);
}
break;
case CombatMode.Retreat:
Retreat(deltaTime);
break;
@@ -671,6 +702,14 @@ namespace Barotrauma
{
RemoveSubObjective(ref retreatObjective);
}
if (character.Submarine == null && sqrDistance < MathUtils.Pow2(maxDistance))
{
// Swim away
SteeringManager.Reset();
SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(character.WorldPosition - Enemy.WorldPosition));
SteeringManager.SteeringAvoid(deltaTime, 5, weight: 2);
return;
}
if (retreatTarget == null || (retreatObjective != null && !retreatObjective.CanBeCompleted))
{
if (findHullTimer > 0)
@@ -704,7 +743,7 @@ namespace Barotrauma
}
}
private void Engage()
private void Engage(float deltaTime)
{
if (WeaponComponent == null)
{
@@ -722,6 +761,21 @@ namespace Barotrauma
RemoveSubObjective(ref retreatObjective);
RemoveSubObjective(ref seekAmmunitionObjective);
RemoveSubObjective(ref seekWeaponObjective);
if (character.Submarine == null && WeaponComponent is MeleeWeapon meleeWeapon)
{
if (sqrDistance > MathUtils.Pow2(meleeWeapon.Range))
{
// Swim towards the target
SteeringManager.Reset();
SteeringManager.SteeringSeek(character.GetRelativeSimPosition(Enemy), weight: 10);
SteeringManager.SteeringAvoid(deltaTime, 5, weight: 15);
}
else
{
SteeringManager.Reset();
}
return;
}
if (followTargetObjective != null && followTargetObjective.Target != Enemy)
{
RemoveFollowTarget();
@@ -46,7 +46,10 @@ namespace Barotrauma
}
if (character.CurrentHull == null)
{
Priority = (objectiveManager.IsCurrentOrder<AIObjectiveGoTo>() || objectiveManager.HasActiveObjective<AIObjectiveCombat>()) && HumanAIController.HasDivingSuit(character) ? 0 : 100;
Priority = (objectiveManager.IsCurrentOrder<AIObjectiveGoTo>() ||
objectiveManager.IsCurrentOrder<AIObjectiveReturn>() ||
objectiveManager.Objectives.Any(o => o.Priority > 0 && o is AIObjectiveCombat))
&& HumanAIController.HasDivingSuit(character) ? 0 : 100;
}
else
{
@@ -57,9 +60,11 @@ namespace Barotrauma
{
Priority = 100;
}
else if (objectiveManager.IsCurrentOrder<AIObjectiveGoTo>() && character.Submarine != null && !HumanAIController.IsOnFriendlyTeam(character.TeamID, character.Submarine.TeamID))
else if ((objectiveManager.IsCurrentOrder<AIObjectiveGoTo>() || objectiveManager.IsCurrentOrder<AIObjectiveReturn>()) &&
character.Submarine != null && !HumanAIController.IsOnFriendlyTeam(character.TeamID, character.Submarine.TeamID))
{
// Ordered to follow/hold position inside a hostile sub -> ignore find safety unless we need to find a diving gear
// Ordered to follow, hold position, or return back to main sub inside a hostile sub
// -> ignore find safety unless we need to find a diving gear
Priority = 0;
}
Priority = MathHelper.Clamp(Priority, 0, 100);
@@ -298,6 +303,7 @@ namespace Barotrauma
Hull bestHull = null;
float bestValue = 0;
bool bestIsAirlock = false;
foreach (Hull hull in Hull.hullList.OrderByDescending(h => EstimateHullSuitability(h)))
{
if (hull.Submarine == null) { continue; }
@@ -306,9 +312,10 @@ namespace Barotrauma
if (ignoredHulls != null && ignoredHulls.Contains(hull)) { continue; }
if (HumanAIController.UnreachableHulls.Contains(hull)) { continue; }
float hullSafety = 0;
if (character.CurrentHull != null && character.Submarine != null)
bool hullIsAirlock = false;
bool isCharacterInside = character.CurrentHull != null && character.Submarine != null;
if (isCharacterInside)
{
// Inside
if (!character.Submarine.IsConnectedTo(hull.Submarine)) { continue; }
hullSafety = HumanAIController.GetHullSafety(hull, hull.GetConnectedHulls(true, 1), character);
float yDist = Math.Abs(character.WorldPosition.Y - hull.WorldPosition.Y);
@@ -343,24 +350,16 @@ namespace Barotrauma
}
else
{
// Outside
if (hull.RoomName != null && hull.RoomName.Contains("airlock", StringComparison.OrdinalIgnoreCase))
// TODO: could also target gaps that get us inside?
if (hull.IsTaggedAirlock())
{
hullSafety = 100;
hullIsAirlock = true;
}
else if(!bestIsAirlock && hull.LeadsOutside(character))
{
hullSafety = 100;
}
else
{
// TODO: could also target gaps that get us inside?
foreach (Item item in Item.ItemList)
{
if (item.CurrentHull != hull && item.HasTag("airlock"))
{
hullSafety = 100;
break;
}
}
}
// TODO: could we get a closest door to the outside and target the flowing hull if no airlock is found?
// Huge preference for closer targets
float distance = Vector2.DistanceSquared(character.WorldPosition, hull.WorldPosition);
float distanceFactor = MathHelper.Lerp(1, 0.2f, MathUtils.InverseLerp(0, MathUtils.Pow(100000, 2), distance));
@@ -372,10 +371,11 @@ namespace Barotrauma
hullSafety /= 10;
}
}
if (hullSafety > bestValue)
if (hullSafety > bestValue || (!isCharacterInside && hullIsAirlock && !bestIsAirlock))
{
bestHull = hull;
bestValue = hullSafety;
bestIsAirlock = hullIsAirlock;
}
}
return bestHull;
@@ -159,6 +159,8 @@ namespace Barotrauma
}
}
public void ForceAct(float deltaTime) => Act(deltaTime);
protected override void Act(float deltaTime)
{
if (followControlledCharacter)
@@ -240,7 +242,7 @@ namespace Barotrauma
if (getDivingGearIfNeeded && !character.LockHands)
{
Character followTarget = Target as Character;
bool needsDivingSuit = targetIsOutside;
bool needsDivingSuit = !isInside || targetIsOutside;
bool needsDivingGear = needsDivingSuit || HumanAIController.NeedsDivingGear(targetHull, out needsDivingSuit);
if (mimic)
{
@@ -444,13 +446,22 @@ namespace Barotrauma
}
if (SteeringManager == PathSteering)
{
Vector2 targetPos = character.GetRelativeSimPosition(Target);
Func<PathNode, bool> nodeFilter = null;
if (isInside && !AllowGoingOutside)
{
nodeFilter = n => n.Waypoint.CurrentHull != null;
}
else if (!isInside && HumanAIController.UseIndoorSteeringOutside)
{
if (character.Submarine == null && Target.Submarine != null)
{
targetPos += Target.Submarine.SimPosition;
}
nodeFilter = n => n.Waypoint.Tunnel != null;
}
PathSteering.SteeringSeek(character.GetRelativeSimPosition(Target), 1,
PathSteering.SteeringSeek(targetPos, 1,
startNodeFilter: n => (n.Waypoint.CurrentHull == null) == (character.CurrentHull == null),
endNodeFilter,
nodeFilter,
@@ -233,11 +233,7 @@ namespace Barotrauma
if (orderObjective == null) { return; }
#if DEBUG
// Note: don't automatically remove orders here. Removing orders needs to be done via dismissing.
if (orderObjective.IsCompleted)
{
DebugConsole.NewMessage($"{character.Name}: ORDER {orderObjective.DebugTag} IS COMPLETED. CURRENTLY ALL ORDERS SHOULD BE LOOPING.", Color.Red);
}
else if (!orderObjective.CanBeCompleted)
if (!orderObjective.CanBeCompleted)
{
DebugConsole.NewMessage($"{character.Name}: ORDER {orderObjective.DebugTag}, CANNOT BE COMPLETED.", Color.Red);
}
@@ -281,9 +277,9 @@ namespace Barotrauma
ForcedOrder?.CalculatePriority();
AIObjective orderWithHighestPriority = null;
float highestPriority = 0;
foreach (var currentOrder in CurrentOrders)
for (int i = CurrentOrders.Count - 1; i >= 0; i--)
{
var orderObjective = currentOrder.Objective;
var orderObjective = CurrentOrders[i].Objective;
if (orderObjective == null) { continue; }
orderObjective.CalculatePriority();
if (orderWithHighestPriority == null || orderObjective.Priority > highestPriority)
@@ -467,6 +463,11 @@ namespace Barotrauma
AllowGoingOutside = character.Submarine == null || (order.TargetSpatialEntity != null && character.Submarine != order.TargetSpatialEntity.Submarine)
};
break;
case "return":
newObjective = new AIObjectiveReturn(character, this, priorityModifier: priorityModifier);
newObjective.Abandoned += () => DismissSelf(order, option);
newObjective.Completed += () => DismissSelf(order, option);
break;
case "fixleaks":
newObjective = new AIObjectiveFixLeaks(character, this, priorityModifier: priorityModifier, prioritizedHull: order.TargetEntity as Hull);
break;
@@ -586,6 +587,27 @@ namespace Barotrauma
return newObjective;
}
private void DismissSelf(Order order, string option)
{
var currentOrder = CurrentOrders.FirstOrDefault(oi => oi.MatchesOrder(order, option));
if (currentOrder.Order == null)
{
#if DEBUG
DebugConsole.ThrowError("Tried to self-dismiss an order, but no matching current order was found");
#endif
return;
}
#if CLIENT
if (GameMain.GameSession?.CrewManager != null && GameMain.GameSession.CrewManager.IsSinglePlayer)
{
GameMain.GameSession?.CrewManager?.SetCharacterOrder(character, Order.GetPrefab("dismissed"), Order.GetDismissOrderOption(currentOrder), currentOrder.ManualPriority, character);
}
#else
GameMain.Server?.SendOrderChatMessage(new OrderChatMessage(Order.GetPrefab("dismissed"), Order.GetDismissOrderOption(currentOrder), currentOrder.ManualPriority, currentOrder.Order?.TargetSpatialEntity, character, character));
#endif
}
private bool IsAllowedToWait()
{
if (!character.IsOnPlayerTeam) { return false; }
@@ -606,6 +628,8 @@ namespace Barotrauma
public bool IsActiveObjective<T>() where T : AIObjective => GetActiveObjective() is T;
public AIObjective GetActiveObjective() => CurrentObjective?.GetActiveObjective();
public T GetOrder<T>() where T : AIObjective => CurrentOrders.FirstOrDefault(o => o.Objective is T).Objective as T;
/// <summary>
/// Returns the last active objective of the specific type.
/// </summary>
@@ -0,0 +1,243 @@
using Barotrauma.Extensions;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma
{
class AIObjectiveReturn : AIObjective
{
public override string Identifier { get; set; } = "return";
private AIObjectiveGoTo moveInsideObjective, moveInCaveObjective, moveOutsideObjective;
private bool usingEscapeBehavior;
public Submarine ReturnTarget { get; }
public AIObjectiveReturn(Character character, AIObjectiveManager objectiveManager, float priorityModifier = 1.0f) : base(character, objectiveManager, priorityModifier)
{
ReturnTarget = GetReturnTarget(Submarine.MainSubs) ?? GetReturnTarget(Submarine.Loaded);
if (ReturnTarget == null)
{
DebugConsole.ThrowError("Error with a Return objective: no suitable return target found");
Abandon = true;
}
Submarine GetReturnTarget(IEnumerable<Submarine> subs)
{
Submarine returnTarget = null;
foreach (var sub in subs)
{
if (sub?.TeamID != character.TeamID) { continue; }
returnTarget = sub;
break;
}
return returnTarget;
}
}
protected override float GetPriority()
{
if (!Abandon && !IsCompleted && objectiveManager.IsOrder(this))
{
Priority = objectiveManager.GetOrderPriority(this);
}
else
{
// TODO: Consider if this needs to be addressed
Priority = 0;
}
return Priority;
}
protected override void Act(float deltaTime)
{
if (ReturnTarget == null)
{
Abandon = true;
return;
}
bool shouldUseEscapeBehavior = false;
if (character.CurrentHull != null)
{
if (character.Submarine == null || !character.Submarine.IsConnectedTo(ReturnTarget))
{
// Character is on another sub that is not connected to the target sub, use the escape behavior to get them out
shouldUseEscapeBehavior = true;
if (!usingEscapeBehavior)
{
HumanAIController.ResetEscape();
}
HumanAIController.Escape(deltaTime);
if (HumanAIController.EscapeTarget == null || !HumanAIController.HasValidPath(requireNonDirty: true, requireUnfinished: false))
{
Abandon = true;
}
}
else if (character.Submarine != ReturnTarget)
{
// Character is on another sub that is connected to the target sub, create a Go To objective to reach the target sub
if (moveInsideObjective == null)
{
Hull targetHull = null;
foreach (var d in ReturnTarget.ConnectedDockingPorts.Values)
{
if (!d.Docked) { continue; }
if (d.DockingTarget == null) { continue; }
if (d.DockingTarget.Item.Submarine != character.Submarine) { continue; }
targetHull = d.Item.CurrentHull;
break;
}
if (targetHull != null)
{
RemoveSubObjective(ref moveInCaveObjective);
RemoveSubObjective(ref moveOutsideObjective);
// TODO: Check 'repeat' and 'onAbandon' parameters
TryAddSubObjective(ref moveInsideObjective,
constructor: () => new AIObjectiveGoTo(targetHull, character, objectiveManager),
onCompleted: () => moveInsideObjective = null);
}
else
{
DebugConsole.ThrowError("Error with a Return objective: no suitable target for 'moveInsideObjective'");
}
}
}
else
{
// Character is on the target sub, the objective is completed
IsCompleted = true;
}
}
else if (moveInCaveObjective == null && moveOutsideObjective == null)
{
if (HumanAIController.IsInsideCave)
{
WayPoint closestOutsideWaypoint = null;
float closestDistance = float.MaxValue;
foreach (var w in WayPoint.WayPointList)
{
if (w.Tunnel == null) { continue; }
if (w.Tunnel.Type == Level.TunnelType.Cave) { continue; }
if (w.linkedTo.None(l => l is WayPoint linkedWaypoint && linkedWaypoint.Tunnel?.Type == Level.TunnelType.Cave)) { continue; }
float distance = Vector2.DistanceSquared(character.WorldPosition, w.WorldPosition);
if (closestOutsideWaypoint == null || distance < closestDistance)
{
closestOutsideWaypoint = w;
closestDistance = distance;
}
}
if (closestOutsideWaypoint != null)
{
RemoveSubObjective(ref moveInsideObjective);
RemoveSubObjective(ref moveOutsideObjective);
// TODO: Check 'repeat' and 'onAbandon' parameters
TryAddSubObjective(ref moveInCaveObjective,
constructor: () => new AIObjectiveGoTo(closestOutsideWaypoint, character, objectiveManager)
{
endNodeFilter = n => n.Waypoint == closestOutsideWaypoint
},
onCompleted: () => moveInCaveObjective = null);
}
else
{
DebugConsole.ThrowError("Error with a Return objective: no suitable main or side path node target found for 'moveOutsideObjective'");
}
}
else
{
Hull targetHull = null;
float targetDistanceSquared = float.MaxValue;
bool targetIsAirlock = false;
foreach (var hull in ReturnTarget.GetHulls(false))
{
bool hullIsAirlock = hull.IsTaggedAirlock();
if(hullIsAirlock || (!targetIsAirlock && hull.LeadsOutside(character)))
{
float distanceSquared = Vector2.DistanceSquared(character.WorldPosition, hull.WorldPosition);
if (targetHull == null || distanceSquared < targetDistanceSquared)
{
targetHull = hull;
targetDistanceSquared = distanceSquared;
targetIsAirlock = hullIsAirlock;
}
}
}
if (targetHull != null)
{
RemoveSubObjective(ref moveInsideObjective);
RemoveSubObjective(ref moveInCaveObjective);
// TODO: Check 'repeat' and 'onAbandon' parameters
TryAddSubObjective(ref moveOutsideObjective,
constructor: () => new AIObjectiveGoTo(targetHull, character, objectiveManager),
onCompleted: () => moveOutsideObjective = null);
}
else
{
DebugConsole.ThrowError("Error with a Return objective: no suitable target for 'moveOutsideObjective'");
}
}
}
else
{
if (HumanAIController.IsInsideCave)
{
if (moveOutsideObjective != null)
{
RemoveSubObjective(ref moveOutsideObjective);
moveOutsideObjective = null;
}
}
else
{
if (moveInCaveObjective != null)
{
RemoveSubObjective(ref moveInCaveObjective);
moveInCaveObjective = null;
}
}
}
usingEscapeBehavior = shouldUseEscapeBehavior;
}
protected override bool CheckObjectiveSpecific()
{
if (IsCompleted)
{
return true;
}
if (ReturnTarget == null)
{
Abandon = true;
return false;
}
if (character.Submarine == ReturnTarget)
{
IsCompleted = true;
}
return IsCompleted;
}
public override void Reset()
{
base.Reset();
moveInsideObjective = null;
moveInCaveObjective = null;
moveOutsideObjective = null;
usingEscapeBehavior = false;
HumanAIController.ResetEscape();
}
protected override void OnAbandon()
{
base.OnAbandon();
SteeringManager.Reset();
if (character.IsOnPlayerTeam && objectiveManager.CurrentOrder == objectiveManager.CurrentObjective)
{
string msg = TextManager.Get("dialogcannotreturn", returnNull: true);
if (msg != null)
{
character.Speak(msg, identifier: "dialogcannotreturn", minDurationBetweenSimilar: 5.0f);
}
}
}
}
}
@@ -1,4 +1,5 @@
using Microsoft.Xna.Framework;
using Barotrauma.Extensions;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -23,6 +24,8 @@ namespace Barotrauma
public readonly Vector2 Position;
public readonly int WayPointID;
public bool blocked;
public override string ToString()
{
return $"PathNode {WayPointID}";
@@ -86,21 +89,19 @@ namespace Barotrauma
public GetNodePenaltyHandler GetNodePenalty;
private readonly List<PathNode> nodes;
public readonly bool IndoorsSteering;
private readonly bool isCharacter;
public bool InsideSubmarine { get; set; }
public bool ApplyPenaltyToOutsideNodes { get; set; }
public PathFinder(List<WayPoint> wayPoints, bool indoorsSteering = false)
public PathFinder(List<WayPoint> wayPoints, bool isCharacter)
{
nodes = PathNode.GenerateNodes(wayPoints.FindAll(w => w.Submarine != null == indoorsSteering), removeOrphans: true);
nodes = PathNode.GenerateNodes(wayPoints.FindAll(w => (w.Submarine != null == isCharacter) || (isCharacter && w.Tunnel != null)), removeOrphans: true);
foreach (WayPoint wp in wayPoints)
{
wp.OnLinksChanged += WaypointLinksChanged;
}
IndoorsSteering = indoorsSteering;
this.isCharacter = isCharacter;
}
void WaypointLinksChanged(WayPoint wp)
@@ -145,6 +146,8 @@ namespace Barotrauma
public SteeringPath FindPath(Vector2 start, Vector2 end, Submarine hostSub = null, string errorMsgStr = null, Func<PathNode, bool> startNodeFilter = null, Func<PathNode, bool> endNodeFilter = null, Func<PathNode, bool> nodeFilter = null, bool checkVisibility = true)
{
UpdateBlockedNodes();
//sort nodes roughly according to distance
sortedNodes.Clear();
foreach (PathNode node in nodes)
@@ -152,7 +155,9 @@ namespace Barotrauma
node.TempPosition = node.Position;
if (hostSub != null)
{
Vector2 diff = hostSub.SimPosition - node.Waypoint.Submarine.SimPosition;
Vector2 diff = node.Waypoint.Submarine != null ?
hostSub.SimPosition - node.Waypoint.Submarine.SimPosition :
hostSub.SimPosition - node.Waypoint.SimPosition;
node.TempPosition -= diff;
}
float xDiff = Math.Abs(start.X - node.TempPosition.X);
@@ -174,29 +179,34 @@ namespace Barotrauma
sortedNodes.Insert(i, node);
}
bool IsWaypointVisible(PathNode node, Vector2 rayStart, bool checkVisibility = true)
{
//if searching for a path inside the sub, make sure the waypoint is visible
if (checkVisibility && isCharacter)
{
if (node.Waypoint.isObstructed) { return false; }
var body = Submarine.PickBody(rayStart, node.TempPosition,
collisionCategory: Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionStairs);
if (body != null)
{
if (body.UserData is Structure s && !s.IsPlatform) { return false; }
if (body.UserData is Item && body.FixtureList[0].CollisionCategories.HasFlag(Physics.CollisionWall)) { return false; }
}
}
return true;
}
//find the most suitable start node, starting from the ones that are the closest
PathNode startNode = null;
foreach (PathNode node in sortedNodes)
{
if (startNode == null || node.TempDistance < startNode.TempDistance)
{
if (node.blocked) { continue; }
if (nodeFilter != null && !nodeFilter(node)) { continue; }
if (startNodeFilter != null && !startNodeFilter(node)) { continue; }
//if searching for a path inside the sub, make sure the waypoint is visible
if (IndoorsSteering)
{
if (node.Waypoint.isObstructed) { continue; }
// Always check the visibility for the start node
var body = Submarine.PickBody(
start, node.TempPosition, null,
Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionStairs);
if (body != null)
{
if (body.UserData is Structure && !((Structure)body.UserData).IsPlatform) { continue; }
if (body.UserData is Item && body.FixtureList[0].CollisionCategories.HasFlag(Physics.CollisionWall)) { continue; }
}
}
// Always check the visibility for the start node
if (!IsWaypointVisible(node, start)) { continue; }
startNode = node;
}
}
@@ -241,24 +251,11 @@ namespace Barotrauma
{
if (endNode == null || node.TempDistance < endNode.TempDistance)
{
if (node.blocked) { continue; }
if (nodeFilter != null && !nodeFilter(node)) { continue; }
if (endNodeFilter != null && !endNodeFilter(node)) { continue; }
if (IndoorsSteering)
{
if (node.Waypoint.isObstructed) { continue; }
//if searching for a path inside the sub, make sure the waypoint is visible
if (checkVisibility)
{
// Only check the visibility for the end node when allowed (fix leaks)
var body = Submarine.PickBody(end, node.TempPosition, null,
Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionStairs);
if (body != null)
{
if (body.UserData is Structure && !((Structure)body.UserData).IsPlatform) { continue; }
if (body.UserData is Item && body.FixtureList[0].CollisionCategories.HasFlag(Physics.CollisionWall)) { continue; }
}
}
}
// Only check the visibility for the end node when allowed (fix leaks)
if (!IsWaypointVisible(node, end, checkVisibility: checkVisibility)) { continue; }
endNode = node;
}
}
@@ -330,7 +327,8 @@ namespace Barotrauma
foreach (PathNode node in nodes)
{
if (node.state != 1) { continue; }
if (IndoorsSteering && node.Waypoint.isObstructed) { continue; }
if (isCharacter && node.Waypoint.isObstructed) { continue; }
if (node.blocked) { continue; }
if (filter != null && !filter(node)) { continue; }
if (node.F < dist)
{
@@ -438,6 +436,25 @@ namespace Barotrauma
return path;
}
private void UpdateBlockedNodes()
{
if (!isCharacter) { return; }
foreach (var n in nodes)
{
n.blocked = false;
if (n.Waypoint.Submarine != null) { continue; }
if (n.Waypoint.Tunnel?.Type != Level.TunnelType.Cave) { continue; }
foreach (var w in Level.Loaded.ExtraWalls)
{
if (!(w is DestructibleLevelWall d)) { continue; }
if (d.Destroyed) { continue; }
if (!d.IsPointInside(n.Waypoint.Position)) { continue; }
n.blocked = true;
break;
}
}
}
}
}
@@ -1,4 +1,5 @@
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
namespace Barotrauma
@@ -24,16 +25,47 @@ namespace Barotrauma
if (Unreachable) { return float.PositiveInfinity; }
if (!totalLength.HasValue)
{
totalLength = 0.0f;
for (int i = 0; i < nodes.Count - 1; i++)
{
totalLength += Vector2.Distance(nodes[i].WorldPosition, nodes[i + 1].WorldPosition);
}
CalculateTotalLength();
}
return totalLength.Value;
}
}
public float GetLength(int? startIndex = null, int? endIndex = null)
{
if (Unreachable) { return float.PositiveInfinity; }
startIndex ??= 0;
endIndex ??= Nodes.Count - 1;
if (startIndex == 0 && endIndex == Nodes.Count - 1)
{
return TotalLength;
}
if (!totalLength.HasValue)
{
CalculateTotalLength();
}
float length = 0.0f;
for (int i = startIndex.Value; i < endIndex.Value; i++)
{
length += nodeDistances[i];
}
return length;
}
private void CalculateTotalLength()
{
totalLength = 0.0f;
nodeDistances.Clear();
for (int i = 0; i < nodes.Count - 1; i++)
{
float distance = Vector2.Distance(nodes[i].WorldPosition, nodes[i + 1].WorldPosition);
totalLength += distance;
nodeDistances.Add(distance);
}
}
private readonly List<float> nodeDistances = new List<float>();
public SteeringPath(bool unreachable = false)
{
nodes = new List<WayPoint>();
@@ -107,6 +139,11 @@ namespace Barotrauma
currentIndex++;
}
public void SkipToNode(int nodeIndex)
{
currentIndex = nodeIndex;
}
public WayPoint CheckProgress(Vector2 simPosition, float minSimDistance = 0.1f)
{
if (nodes.Count == 0 || currentIndex > nodes.Count - 1) { return null; }
@@ -1130,7 +1130,7 @@ namespace Barotrauma
{
nonHuskedSpeciesName = AfflictionHusk.GetNonHuskedSpeciesName(speciesName, matchingAffliction);
}
if (ragdollParams == null)
if (ragdollParams == null && prefab.VariantOf == null)
{
string name = Params.UseHuskAppendage ? nonHuskedSpeciesName : speciesName;
ragdollParams = IsHumanoid ? RagdollParams.GetDefaultRagdollParams<HumanRagdollParams>(name) : RagdollParams.GetDefaultRagdollParams<FishRagdollParams>(name) as RagdollParams;
@@ -3078,30 +3078,47 @@ namespace Barotrauma
//set the character order only if the character is close enough to hear the message
if (!force && orderGiver != null && !CanHearCharacter(orderGiver)) { return; }
if (order.OrderGiver != orderGiver)
if (order != null && order.OrderGiver != orderGiver)
{
order.OrderGiver = orderGiver;
}
// If there's another character operating the same device, make them dismiss themself
if (order != null && order.Category == OrderCategory.Operate && order.TargetEntity != null)
switch (order?.Category)
{
foreach (var character in CharacterList)
{
if (character == this) { continue; }
if (character.TeamID != TeamID) { continue; }
if (!(character.AIController is HumanAIController)) { continue; }
if (!HumanAIController.IsActive(character)) { continue; }
foreach (var currentOrder in character.CurrentOrders)
case OrderCategory.Operate when order?.TargetEntity != null:
// If there's another character operating the same device, make them dismiss themself
foreach (var character in CharacterList)
{
if (character == this) { continue; }
if (character.TeamID != TeamID) { continue; }
if (!(character.AIController is HumanAIController)) { continue; }
if (!HumanAIController.IsActive(character)) { continue; }
foreach (var currentOrder in character.CurrentOrders)
{
if (currentOrder.Order == null) { continue; }
if (currentOrder.Order.Category != OrderCategory.Operate) { continue; }
if (currentOrder.Order.Identifier != order.Identifier) { continue; }
if (currentOrder.Order.TargetEntity != order.TargetEntity) { continue; }
character.SetOrder(Order.GetPrefab("dismissed"), Order.GetDismissOrderOption(currentOrder), currentOrder.ManualPriority, character, speak: speak, force: force);
break;
}
}
break;
case OrderCategory.Movement:
// If there character has another movement order, dismiss that order
OrderInfo? orderToReplace = null;
foreach (var currentOrder in CurrentOrders)
{
if (currentOrder.Order == null) { continue; }
if (currentOrder.Order.Category != OrderCategory.Operate) { continue; }
if (currentOrder.Order.Identifier != order.Identifier) { continue; }
if (currentOrder.Order.TargetEntity != order.TargetEntity) { continue; }
character.SetOrder(Order.GetPrefab("dismissed"), Order.GetDismissOrderOption(currentOrder), currentOrder.ManualPriority, character, speak: speak, force: force);
if (currentOrder.Order.Category != OrderCategory.Movement) { continue; }
orderToReplace = currentOrder;
break;
}
}
if (orderToReplace.HasValue)
{
SetOrder(Order.GetPrefab("dismissed"), Order.GetDismissOrderOption(orderToReplace.Value), orderToReplace.Value.ManualPriority, this, speak: speak, force: force);
}
break;
}
// Prevent adding duplicate orders
@@ -3112,7 +3129,8 @@ namespace Barotrauma
if (orderGiver != null)
{
orderGiver.CheckTalents(AbilityEffectType.OnGiveOrder, this);
var abilityOrderedCharacter = new AbilityCharacter(this);
orderGiver.CheckTalents(AbilityEffectType.OnGiveOrder, abilityOrderedCharacter);
}
if (AIController is HumanAIController humanAI)
@@ -3504,11 +3522,12 @@ namespace Barotrauma
public void RecordKill(Character target)
{
var abilityCharacter = new AbilityCharacter(target);
foreach (Character attackerCrewmember in GetFriendlyCrew(this))
{
attackerCrewmember.CheckTalents(AbilityEffectType.OnCrewKillCharacter, target);
attackerCrewmember.CheckTalents(AbilityEffectType.OnCrewKillCharacter, abilityCharacter);
}
CheckTalents(AbilityEffectType.OnKillCharacter, target);
CheckTalents(AbilityEffectType.OnKillCharacter, abilityCharacter);
if (!IsOnPlayerTeam) { return; }
if (GameMain.Config.KilledCreatures.Any(name => name.Equals(target.SpeciesName, StringComparison.OrdinalIgnoreCase))) { return; }
@@ -3604,8 +3623,11 @@ namespace Barotrauma
ApplyStatusEffects(ActionType.OnDamaged, 1.0f);
hitLimb.ApplyStatusEffects(ActionType.OnDamaged, 1.0f);
}
attacker?.CheckTalents(AbilityEffectType.OnAttackResult, attackResult);
if (attacker != null)
{
var abilityAttackResult = new AbilityAttackResult(attackResult);
attacker.CheckTalents(AbilityEffectType.OnAttackResult, abilityAttackResult);
}
return attackResult;
}
@@ -3828,7 +3850,8 @@ namespace Barotrauma
causeOfDeathAffliction?.Source ?? LastAttacker, LastDamageSource);
OnDeath?.Invoke(this, CauseOfDeath);
CheckTalents(AbilityEffectType.OnDieToCharacter, CauseOfDeath.Killer);
var abilityKiller = new AbilityCharacter(CauseOfDeath.Killer);
CheckTalents(AbilityEffectType.OnDieToCharacter, abilityKiller);
if (GameMain.GameSession != null && Screen.Selected == GameMain.GameScreen)
{
@@ -4347,11 +4370,16 @@ namespace Barotrauma
return CharacterList.Where(c => HumanAIController.IsFriendly(character, c, onlySameTeam: true) && !c.IsDead);
}
public void CheckTalents(AbilityEffectType abilityEffectType, object abilityData)
public bool HasTalents()
{
return characterTalents.Any();
}
public void CheckTalents(AbilityEffectType abilityEffectType, AbilityObject abilityObject)
{
foreach (var characterTalent in characterTalents)
{
characterTalent.CheckTalent(abilityEffectType, abilityData);
characterTalent.CheckTalent(abilityEffectType, abilityObject);
}
}
@@ -4359,7 +4387,7 @@ namespace Barotrauma
{
foreach (var characterTalent in characterTalents)
{
characterTalent.CheckTalent(abilityEffectType, (object)null);
characterTalent.CheckTalent(abilityEffectType, null);
}
}
@@ -4421,7 +4449,8 @@ namespace Barotrauma
//replace by updating the character wearable stat values when equipping or unequipping wearables
for (int i = 0; i < Inventory.Capacity; i++)
{
if (Inventory.SlotTypes[i] != InvSlotType.Any && Inventory.GetItemAt(i)?.GetComponent<Wearable>() is Wearable wearable)
if (Inventory.SlotTypes[i] != InvSlotType.Any && Inventory.SlotTypes[i] != InvSlotType.LeftHand && Inventory.SlotTypes[i] != InvSlotType.RightHand
&& Inventory.GetItemAt(i)?.GetComponent<Wearable>() is Wearable wearable)
{
if (wearable.WearableStatValues.TryGetValue(statType, out float wearableValue))
{
@@ -220,7 +220,7 @@ namespace Barotrauma
public HashSet<string> UnlockedTalents { get; private set; } = new HashSet<string>();
public int AdditionalTalentPoints { get; private set; }
public int AdditionalTalentPoints { get; set; }
private Sprite headSprite;
public Sprite HeadSprite
@@ -541,6 +541,7 @@ namespace Barotrauma
Salary = infoElement.GetAttributeInt("salary", 1000);
ExperiencePoints = infoElement.GetAttributeInt("experiencepoints", 0);
UnlockedTalents = new HashSet<string>(infoElement.GetAttributeStringArray("unlockedtalents", new string[0], convertToLowerInvariant: true));
AdditionalTalentPoints = infoElement.GetAttributeInt("additionaltalentpoints", 0);
Enum.TryParse(infoElement.GetAttributeString("race", "White"), true, out Race race);
Enum.TryParse(infoElement.GetAttributeString("gender", "None"), true, out Gender gender);
_speciesName = infoElement.GetAttributeString("speciesname", null);
@@ -984,12 +985,14 @@ namespace Barotrauma
float newLevel = Job.GetSkillLevel(skillIdentifier);
if ((int)newLevel > (int)prevLevel)
{
Character.CheckTalents(AbilityEffectType.OnGainSkillPoint, skillIdentifier);
{
// assume we are getting at least 1 point in skill, since this logic only runs in such cases
float increaseSinceLastSkillPoint = MathHelper.Max(increase, 1f);
var abilitySkillGain = new AbilityValueStringCharacter(increaseSinceLastSkillPoint, skillIdentifier, Character);
Character.CheckTalents(AbilityEffectType.OnGainSkillPoint, abilitySkillGain);
foreach (Character character in Character.GetFriendlyCrew(Character))
{
var abilityStringCharacter = new AbilityStringCharacter(skillIdentifier, Character);
character.CheckTalents(AbilityEffectType.OnAllyGainSkillPoint, abilityStringCharacter);
character.CheckTalents(AbilityEffectType.OnAllyGainSkillPoint, abilitySkillGain);
}
}
@@ -1138,6 +1141,7 @@ namespace Barotrauma
new XAttribute("salary", Salary),
new XAttribute("experiencepoints", ExperiencePoints),
new XAttribute("unlockedtalents", string.Join(",", UnlockedTalents)),
new XAttribute("additionaltalentpoints", AdditionalTalentPoints),
new XAttribute("headspriteid", HeadSpriteId),
new XAttribute("hairindex", HairIndex),
new XAttribute("beardindex", BeardIndex),
@@ -176,6 +176,21 @@ namespace Barotrauma
(Strength - currentEffect.MinStrength) / (currentEffect.MaxStrength - currentEffect.MinStrength)) * GetScreenEffectFluctuation(currentEffect);
}
public float GetAfflictionOverlayMultiplier()
{
//If the overlay's alpha progresses linearly, then don't worry about affliction effects.
if (Prefab.AfflictionOverlayAlphaIsLinear) { return (Strength / Prefab.MaxStrength); }
if (Strength < Prefab.ActivationThreshold) { return 0.0f; }
AfflictionPrefab.Effect currentEffect = GetActiveEffect();
if (currentEffect == null) { return 0.0f; }
if (currentEffect.MaxAfflictionOverlayAlphaMultiplier - currentEffect.MinAfflictionOverlayAlphaMultiplier < 0.0f) { return 0.0f; }
return MathHelper.Lerp(
currentEffect.MinAfflictionOverlayAlphaMultiplier,
currentEffect.MaxAfflictionOverlayAlphaMultiplier,
(Strength - currentEffect.MinStrength) / (currentEffect.MaxStrength - currentEffect.MinStrength));
}
public float GetScreenBlurStrength()
{
if (Strength < Prefab.ActivationThreshold) { return 0.0f; }
@@ -344,6 +359,8 @@ namespace Barotrauma
private readonly List<ISerializableEntity> targets = new List<ISerializableEntity>();
public void ApplyStatusEffect(ActionType type, StatusEffect statusEffect, float deltaTime, CharacterHealth characterHealth, Limb targetLimb)
{
if (type == ActionType.OnDamaged && !statusEffect.HasRequiredAfflictions(characterHealth.Character.LastDamage)) { return; }
statusEffect.SetUser(Source);
if (statusEffect.HasTargetType(StatusEffect.TargetType.Character))
{
@@ -21,6 +21,8 @@ namespace Barotrauma
private Character character;
private bool stun = true;
private readonly List<Affliction> huskInfection = new List<Affliction>();
[Serialize(0f, true), Editable]
@@ -34,6 +36,7 @@ namespace Barotrauma
float threshold = _strength > ActiveThreshold ? ActiveThreshold + 1 : DormantThreshold - 1;
float max = Math.Max(threshold, previousValue);
_strength = Math.Clamp(value, 0, max);
stun = GameMain.GameSession?.IsRunning ?? true;
if (previousValue > 0.0f && value <= 0.0f)
{
DeactivateHusk();
@@ -60,6 +63,8 @@ namespace Barotrauma
private float TransitionThreshold => (Prefab as AfflictionPrefabHusk)?.TransitionThreshold ?? Prefab.MaxStrength * 0.75f;
private float TransformThresholdOnDeath => (Prefab as AfflictionPrefabHusk)?.TransformThresholdOnDeath ?? ActiveThreshold;
public AfflictionHusk(AfflictionPrefab prefab, float strength) : base(prefab, strength) { }
public override void Update(CharacterHealth characterHealth, Limb targetLimb, float deltaTime)
@@ -91,7 +96,7 @@ namespace Barotrauma
}
else if (Strength < TransitionThreshold)
{
if (State != InfectionState.Active)
if (State != InfectionState.Active && stun)
{
character.SetStun(Rand.Range(2, 4));
}
@@ -167,7 +172,7 @@ namespace Barotrauma
private void CharacterDead(Character character, CauseOfDeath causeOfDeath)
{
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return; }
if (Strength < ActiveThreshold || character.Removed)
if (Strength < TransformThresholdOnDeath || character.Removed)
{
UnsubscribeFromDeathEvent();
return;
@@ -101,6 +101,7 @@ namespace Barotrauma
DormantThreshold = element.GetAttributeFloat("dormantthreshold", MaxStrength * 0.5f);
ActiveThreshold = element.GetAttributeFloat("activethreshold", MaxStrength * 0.75f);
TransitionThreshold = element.GetAttributeFloat("transitionthreshold", MaxStrength);
TransformThresholdOnDeath = element.GetAttributeFloat("transformthresholdondeath", ActiveThreshold);
}
// Use any of these to define which limb the appendage is attached to.
@@ -110,6 +111,7 @@ namespace Barotrauma
public readonly LimbType AttachLimbType;
public float ActiveThreshold, DormantThreshold, TransitionThreshold;
public float TransformThresholdOnDeath;
public readonly string HuskedSpeciesName;
public readonly string[] TargetSpecies;
@@ -182,6 +184,12 @@ namespace Barotrauma
[Serialize(0.0f, false)]
public float ScreenEffectFluctuationFrequency { get; private set; }
[Serialize(1.0f, false)]
public float MinAfflictionOverlayAlphaMultiplier { get; private set; }
[Serialize(1.0f, false)]
public float MaxAfflictionOverlayAlphaMultiplier { get; private set; }
[Serialize(1.0f, false)]
public float MinBuffMultiplier { get; private set; }
@@ -358,6 +366,9 @@ namespace Barotrauma
public readonly Sprite Icon;
public readonly Color[] IconColors;
public readonly Sprite AfflictionOverlay;
public readonly bool AfflictionOverlayAlphaIsLinear;
private readonly List<Effect> effects = new List<Effect>();
private readonly List<PeriodicEffect> periodicEffects = new List<PeriodicEffect>();
@@ -645,6 +656,7 @@ namespace Barotrauma
SelfCauseOfDeathDescription = TextManager.Get("AfflictionCauseOfDeathSelf." + translationId, true) ?? element.GetAttributeString("selfcauseofdeathdescription", "");
IconColors = element.GetAttributeColorArray("iconcolors", null);
AfflictionOverlayAlphaIsLinear = element.GetAttributeBool("afflictionoverlayalphaislinear", false);
AchievementOnRemoved = element.GetAttributeString("achievementonremoved", "");
foreach (XElement subElement in element.Elements())
@@ -654,6 +666,9 @@ namespace Barotrauma
case "icon":
Icon = new Sprite(subElement);
break;
case "afflictionoverlay":
AfflictionOverlay = new Sprite(subElement);
break;
}
}
@@ -6,6 +6,7 @@ using System.Xml.Linq;
using Barotrauma.Networking;
using Barotrauma.Extensions;
using System.Globalization;
using Barotrauma.Abilities;
namespace Barotrauma
{
@@ -483,9 +484,12 @@ namespace Barotrauma
{
var matchingAffliction = matchingAfflictions[i];
// kind of bad to create a tuple every time, but I can't think of another way to easily do this
var afflictionReduction = (matchingAffliction, reduceAmount);
Character.CheckTalents(AbilityEffectType.OnReduceAffliction, afflictionReduction);
// this logic runs very often, so culling unnecessary object creation and talent checking with this method
if (Character.HasTalents())
{
var afflictionReduction = new AbilityValueAffliction(reduceAmount, matchingAffliction);
Character.CheckTalents(AbilityEffectType.OnReduceAffliction, afflictionReduction);
}
if (matchingAffliction.Strength < reduceAmount)
{
@@ -11,6 +11,7 @@ using System.Xml.Linq;
using Barotrauma.Networking;
using LimbParams = Barotrauma.RagdollParams.LimbParams;
using JointParams = Barotrauma.RagdollParams.JointParams;
using Barotrauma.Abilities;
namespace Barotrauma
{
@@ -741,7 +742,11 @@ namespace Barotrauma
{
newAffliction.SetStrength(affliction.NonClampedStrength);
}
attacker?.CheckTalents(AbilityEffectType.OnAddDamageAffliction, newAffliction);
if (attacker != null)
{
var abilityAffliction = new AbilityAffliction(newAffliction);
attacker.CheckTalents(AbilityEffectType.OnAddDamageAffliction, abilityAffliction);
}
if (applyAffliction)
{
afflictionsCopy.Add(newAffliction);
@@ -20,7 +20,7 @@ namespace Barotrauma.Abilities
character = characterTalent.Character;
invert = conditionElement.GetAttributeBool("invert", false);
}
public abstract bool MatchesCondition(object abilityData);
public abstract bool MatchesCondition(AbilityObject abilityObject);
public abstract bool MatchesCondition();
@@ -31,9 +31,9 @@ namespace Barotrauma.Abilities
}
}
protected override bool MatchesConditionSpecific(object abilityData)
protected override bool MatchesConditionSpecific(AbilityObject abilityObject)
{
if (abilityData is AbilityAttackData attackData)
if (abilityObject is AbilityAttackData attackData)
{
Item item = attackData?.SourceAttack?.SourceItem;
@@ -71,7 +71,7 @@ namespace Barotrauma.Abilities
}
else
{
LogAbilityConditionError(abilityData, typeof(AbilityAttackData));
LogAbilityConditionError(abilityObject, typeof(AbilityAttackData));
return false;
}
}
@@ -15,9 +15,9 @@ namespace Barotrauma.Abilities
afflictions = conditionElement.GetAttributeStringArray("afflictions", new string[0], convertToLowerInvariant: true);
}
protected override bool MatchesConditionSpecific(object abilityData)
protected override bool MatchesConditionSpecific(AbilityObject abilityObject)
{
if (abilityData is AttackResult attackResult)
if ((abilityObject as IAbilityAttackResult)?.AttackResult is AttackResult attackResult)
{
if (!IsViableTarget(targetTypes, attackResult.HitLimb?.character)) { return false; }
@@ -30,7 +30,7 @@ namespace Barotrauma.Abilities
}
else
{
LogAbilityConditionError(abilityData, typeof(AbilityAttackData));
LogAbilityConditionError(abilityObject, typeof(IAbilityAttackResult));
return false;
}
}
@@ -12,9 +12,9 @@ namespace Barotrauma.Abilities
targetTypes = ParseTargetTypes(conditionElement.GetAttributeStringArray("targettypes", new string[0], convertToLowerInvariant: true));
}
protected override bool MatchesConditionSpecific(object abilityData)
protected override bool MatchesConditionSpecific(AbilityObject abilityObject)
{
if (abilityData is Character character)
if ((abilityObject as IAbilityCharacter)?.Character is Character character)
{
if (!IsViableTarget(targetTypes, character)) { return false; }
@@ -22,7 +22,7 @@ namespace Barotrauma.Abilities
}
else
{
LogAbilityConditionError(abilityData, typeof(Character));
LogAbilityConditionError(abilityObject, typeof(IAbilityCharacter));
return false;
}
}
@@ -16,21 +16,21 @@ namespace Barotrauma.Abilities
/// </summary>
public AbilityConditionData(CharacterTalent characterTalent, XElement conditionElement) : base(characterTalent, conditionElement) { }
protected void LogAbilityConditionError<T>(T abilityData, Type expectedData)
protected void LogAbilityConditionError(AbilityObject abilityObject, Type expectedData)
{
DebugConsole.ThrowError($"Used data-reliant ability condition when data is incompatible! Expected {expectedData}, but received {abilityData}");
DebugConsole.ThrowError($"Used data-reliant ability condition when data is incompatible! Expected {expectedData}, but received {abilityObject}");
}
protected abstract bool MatchesConditionSpecific(object abilityData);
protected abstract bool MatchesConditionSpecific(AbilityObject abilityObject);
public override bool MatchesCondition()
{
DebugConsole.ThrowError("Used data-reliant ability condition in a state-based ability! This is not allowed.");
return false;
}
public override bool MatchesCondition(object abilityData)
public override bool MatchesCondition(AbilityObject abilityObject)
{
if (abilityData is null) { return invert; }
return invert ? !MatchesConditionSpecific(abilityData) : MatchesConditionSpecific(abilityData);
if (abilityObject is null) { return invert; }
return invert ? !MatchesConditionSpecific(abilityObject) : MatchesConditionSpecific(abilityObject);
}
}
}
@@ -6,15 +6,15 @@ namespace Barotrauma.Abilities
{
public AbilityConditionEvasiveManeuvers(CharacterTalent characterTalent, XElement conditionElement) : base(characterTalent, conditionElement) { }
protected override bool MatchesConditionSpecific(object abilityData)
protected override bool MatchesConditionSpecific(AbilityObject abilityObject)
{
if (abilityData is Submarine submarine)
if ((abilityObject as IAbilitySubmarine)?.Submarine is Submarine submarine && (abilityObject as IAbilityCharacter)?.Character is Character attackingCharacter)
{
return submarine.TeamID == character.TeamID && character.Submarine == submarine;
return submarine.TeamID == character.TeamID && character.Submarine == submarine && attackingCharacter.TeamID != character.TeamID;
}
else
{
LogAbilityConditionError(abilityData, typeof(Submarine));
LogAbilityConditionError(abilityObject, typeof(IAbilitySubmarine));
return false;
}
}
@@ -15,33 +15,33 @@ namespace Barotrauma.Abilities
tags = conditionElement.GetAttributeStringArray("tags", Array.Empty<string>(), convertToLowerInvariant: true);
}
protected override bool MatchesConditionSpecific(object abilityData)
protected override bool MatchesConditionSpecific(AbilityObject abilityObject)
{
ItemPrefab item = null;
if (abilityData is Item tempItem)
ItemPrefab itemPrefab = null;
if ((abilityObject as IAbilityItemPrefab)?.ItemPrefab is ItemPrefab abilityItemPrefab)
{
item = tempItem.Prefab;
itemPrefab = abilityItemPrefab;
}
else if (abilityData is IAbilityItemPrefab abilityItemPrefab)
else if ((abilityObject as IAbilityItem)?.Item is Item abilityItem)
{
item = abilityItemPrefab.ItemPrefab;
itemPrefab = abilityItem.Prefab;
}
if (item != null)
if (itemPrefab != null)
{
if (!string.IsNullOrEmpty(identifier))
{
if (item.Identifier != identifier)
if (itemPrefab.Identifier != identifier)
{
return false;
}
}
return tags.Any(t => item.Tags.Any(p => t == p));
return tags.Any(t => itemPrefab.Tags.Any(p => t == p));
}
else
{
LogAbilityConditionError(abilityData, typeof(Item));
LogAbilityConditionError(abilityObject, typeof(IAbilityItemPrefab));
return false;
}
}
@@ -13,19 +13,19 @@ namespace Barotrauma.Abilities
identifier = conditionElement.GetAttributeString("identifier", "");
}
protected override bool MatchesConditionSpecific(object abilityData)
protected override bool MatchesConditionSpecific(AbilityObject abilityObject)
{
if (abilityData is IAbilityAffliction abilityAffliction)
if ((abilityObject as IAbilityAffliction)?.Affliction is Affliction affliction)
{
if (allowedTypes.Find(c => c == abilityAffliction.Affliction.Prefab.AfflictionType) == null) { return false; }
if (allowedTypes.Find(c => c == affliction.Prefab.AfflictionType) == null) { return false; }
if (!string.IsNullOrEmpty(identifier) && abilityAffliction.Affliction.Prefab.Identifier != identifier) { return false; }
if (!string.IsNullOrEmpty(identifier) && affliction.Prefab.Identifier != identifier) { return false; }
return true;
}
else
{
LogAbilityConditionError(abilityData, typeof(IAbilityAffliction));
LogAbilityConditionError(abilityObject, typeof(IAbilityAffliction));
return false;
}
}
@@ -4,17 +4,18 @@ namespace Barotrauma.Abilities
{
class AbilityConditionScavenger : AbilityConditionData
{
public AbilityConditionScavenger(CharacterTalent characterTalent, XElement conditionElement) : base(characterTalent, conditionElement) { }
protected override bool MatchesConditionSpecific(object abilityData)
protected override bool MatchesConditionSpecific(AbilityObject abilityObject)
{
if (abilityData is Item item)
if ((abilityObject as IAbilityItem)?.Item is Item item)
{
return item.Submarine != character.Submarine;
return item.Submarine == null || item.Submarine.TeamID != character.Info.TeamID;
}
else
{
LogAbilityConditionError(abilityData, typeof(Item));
LogAbilityConditionError(abilityObject, typeof(IAbilityItem));
return false;
}
}
@@ -0,0 +1,23 @@
using System.Xml.Linq;
namespace Barotrauma.Abilities
{
class AbilityConditionScrounger : AbilityConditionData
{
public AbilityConditionScrounger(CharacterTalent characterTalent, XElement conditionElement) : base(characterTalent, conditionElement) { }
protected override bool MatchesConditionSpecific(AbilityObject abilityObject)
{
if ((abilityObject as IAbilityItem)?.Item is Item item)
{
return item.Submarine?.Info?.IsWreck ?? false;
}
else
{
LogAbilityConditionError(abilityObject, typeof(IAbilityItem));
return false;
}
}
}
}
@@ -16,15 +16,15 @@ namespace Barotrauma.Abilities
return this.skillIdentifier == skillIdentifier;
}
protected override bool MatchesConditionSpecific(object abilityData)
protected override bool MatchesConditionSpecific(AbilityObject abilityObject)
{
if ((abilityData as string ?? (abilityData as IAbilityString)?.String) is string skillIdentifier)
if ((abilityObject as IAbilityString)?.String is string skillIdentifier)
{
return MatchesConditionSpecific(skillIdentifier);
}
else
{
LogAbilityConditionError(abilityData, typeof(string));
LogAbilityConditionError(abilityObject, typeof(IAbilityString));
return false;
}
}
@@ -12,7 +12,7 @@ namespace Barotrauma.Abilities
return invert ? !MatchesConditionSpecific() : MatchesConditionSpecific();
}
public override bool MatchesCondition(object abilityData)
public override bool MatchesCondition(AbilityObject abilityObject)
{
return invert ? !MatchesConditionSpecific() : MatchesConditionSpecific();
}
@@ -22,15 +22,15 @@ namespace Barotrauma.Abilities
}
}
protected override bool MatchesConditionSpecific(object abilityData)
protected override bool MatchesConditionSpecific(AbilityObject abilityObject)
{
if (abilityData is IAbilityMission abilityMission)
if ((abilityObject as IAbilityMission)?.Mission is Mission mission)
{
return abilityMission.Mission.Prefab.Type == missionType;
return mission.Prefab.Type == missionType;
}
else
{
LogAbilityConditionError(abilityData, typeof(IAbilityMission));
LogAbilityConditionError(abilityObject, typeof(IAbilityMission));
return false;
}
}
@@ -5,6 +5,11 @@
public ItemPrefab ItemPrefab { get; set; }
}
interface IAbilityItem
{
public Item Item { get; set; }
}
interface IAbilityValue
{
public float Value { get; set; }
@@ -29,4 +34,14 @@
{
public Affliction Affliction { get; set; }
}
interface IAbilityAttackResult
{
public AttackResult AttackResult { get; set; }
}
interface IAbilitySubmarine
{
public Submarine Submarine { get; set; }
}
}
@@ -2,8 +2,30 @@
namespace Barotrauma.Abilities
{
class AbilityObject
{
// kept as blank for now, as we are using a composition and only using this object to enforce parameter types
}
class AbilityValue : IAbilityValue
class AbilityCharacter : AbilityObject, IAbilityCharacter
{
public AbilityCharacter(Character character)
{
Character = character;
}
public Character Character { get; set; }
}
class AbilityItem : AbilityObject, IAbilityItem
{
public AbilityItem(Item item)
{
Item = item;
}
public Item Item { get; set; }
}
class AbilityValue : AbilityObject, IAbilityValue
{
public AbilityValue(float value)
{
@@ -12,7 +34,16 @@ namespace Barotrauma.Abilities
public float Value { get; set; }
}
class AbilityValueItem : IAbilityValue, IAbilityItemPrefab
class AbilityAffliction : AbilityObject, IAbilityAffliction
{
public AbilityAffliction(Affliction affliction)
{
Affliction = affliction;
}
public Affliction Affliction { get; set; }
}
class AbilityValueItem : AbilityObject, IAbilityValue, IAbilityItemPrefab
{
public AbilityValueItem(float value, ItemPrefab itemPrefab)
{
@@ -23,7 +54,7 @@ namespace Barotrauma.Abilities
public ItemPrefab ItemPrefab { get; set; }
}
class AbilityValueString : IAbilityValue, IAbilityString
class AbilityValueString : AbilityObject, IAbilityValue, IAbilityString
{
public AbilityValueString(float value, string abilityString)
{
@@ -34,7 +65,20 @@ namespace Barotrauma.Abilities
public string String { get; set; }
}
class AbilityStringCharacter : IAbilityCharacter, IAbilityString
class AbilityValueStringCharacter : AbilityObject, IAbilityValue, IAbilityString
{
public AbilityValueStringCharacter(float value, string abilityString, Character character)
{
Value = value;
String = abilityString;
Character = character;
}
public Character Character { get; set; }
public float Value { get; set; }
public string String { get; set; }
}
class AbilityStringCharacter : AbilityObject, IAbilityCharacter, IAbilityString
{
public AbilityStringCharacter(string abilityString, Character character)
{
@@ -45,7 +89,7 @@ namespace Barotrauma.Abilities
public string String { get; set; }
}
class AbilityValueAffliction : IAbilityValue, IAbilityAffliction
class AbilityValueAffliction : AbilityObject, IAbilityValue, IAbilityAffliction
{
public AbilityValueAffliction(float value, Affliction affliction)
{
@@ -56,7 +100,7 @@ namespace Barotrauma.Abilities
public Affliction Affliction { get; set; }
}
class AbilityValueMission : IAbilityValue, IAbilityMission
class AbilityValueMission : AbilityObject, IAbilityValue, IAbilityMission
{
public AbilityValueMission(float value, Mission mission)
{
@@ -67,7 +111,8 @@ namespace Barotrauma.Abilities
public Mission Mission { get; set; }
}
class AbilityAttackData : IAbilityCharacter
// this is an exception class that should only be passed in this form, so classes that use it should cast into it directly
class AbilityAttackData : AbilityObject, IAbilityCharacter
{
public float DamageMultiplier { get; set; } = 1f;
public float AddedPenetration { get; set; } = 0f;
@@ -82,4 +127,26 @@ namespace Barotrauma.Abilities
Character = character;
}
}
class AbilityAttackResult : AbilityObject, IAbilityAttackResult
{
public AttackResult AttackResult { get; set; }
public AbilityAttackResult(AttackResult attackResult)
{
AttackResult = attackResult;
}
}
class AbilityCharacterSubmarine : AbilityObject, IAbilityCharacter, IAbilitySubmarine
{
public AbilityCharacterSubmarine(Character character, Submarine submarine)
{
Character = character;
Submarine = submarine;
}
public Character Character { get; set; }
public Submarine Submarine { get; set; }
}
}
@@ -65,15 +65,15 @@ namespace Barotrauma.Abilities
DebugConsole.ThrowError($"Ability {this} does not have an implementation for VerifyState! This ability does not work in interval ability groups.");
}
public void ApplyAbilityEffect(object abilityData)
public void ApplyAbilityEffect(AbilityObject abilityObject)
{
if (abilityData is null)
if (abilityObject is null)
{
ApplyEffect();
}
else
{
ApplyEffect(abilityData);
ApplyEffect(abilityObject);
}
}
@@ -82,12 +82,12 @@ namespace Barotrauma.Abilities
DebugConsole.AddWarning($"Ability {this} used improperly! This ability does not have a definition for ApplyEffect");
}
protected virtual void ApplyEffect(object abilityData)
protected virtual void ApplyEffect(AbilityObject abilityObject)
{
DebugConsole.AddWarning($"Ability {this} used improperly! This ability does not take a parameter for ApplyEffect");
}
protected void LogAbilityDataMismatch()
protected void LogabilityObjectMismatch()
{
DebugConsole.ThrowError($"Incompatible ability! Ability {this} is incompatitible with this type of ability effect type.");
}
@@ -34,32 +34,33 @@ namespace Barotrauma.Abilities
{
targets.Clear();
targets.AddRange(statusEffect.GetNearbyTargets(targetCharacter.WorldPosition, targets));
statusEffect.SetUser(Character);
statusEffect.Apply(ActionType.OnAbility, EffectDeltaTime, targetCharacter, targets);
}
else if (statusEffect.HasTargetType(StatusEffect.TargetType.This))
else if (statusEffect.HasTargetType(StatusEffect.TargetType.Character))
{
statusEffect.SetUser(Character);
statusEffect.Apply(ActionType.OnAbility, EffectDeltaTime, Character, targetCharacter);
}
else
{
statusEffect.SetUser(Character);
statusEffect.Apply(ActionType.OnAbility, EffectDeltaTime, Character, Character);
}
else
{
statusEffect.Apply(ActionType.OnAbility, EffectDeltaTime, Character, targetCharacter);
}
}
}
protected override void ApplyEffect()
{
ApplyEffectSpecific(Character);
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (applyToSelected && Character.SelectedCharacter is Character selectedCharacter)
{
ApplyEffectSpecific(selectedCharacter);
}
else if ((abilityData as Character ?? (abilityData as IAbilityCharacter)?.Character) is Character targetCharacter)
else if ((abilityObject as IAbilityCharacter)?.Character is Character targetCharacter)
{
ApplyEffectSpecific(targetCharacter);
}
@@ -9,9 +9,9 @@ namespace Barotrauma.Abilities
{
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if ((abilityData as AbilityAttackData)?.Attacker is Character attacker)
if ((abilityObject as AbilityAttackData)?.Attacker is Character attacker)
{
ApplyEffectSpecific(attacker);
}
@@ -0,0 +1,27 @@
using Microsoft.Xna.Framework;
using System.Xml.Linq;
namespace Barotrauma.Abilities
{
class CharacterAbilityGainSimultaneousSkill : CharacterAbility
{
private string skillIdentifier;
public CharacterAbilityGainSimultaneousSkill(CharacterAbilityGroup characterAbilityGroup, XElement abilityElement) : base(characterAbilityGroup, abilityElement)
{
skillIdentifier = abilityElement.GetAttributeString("skillidentifier", "").ToLowerInvariant();
}
protected override void ApplyEffect(AbilityObject abilityObject)
{
if ((abilityObject as IAbilityValue)?.Value is float skillIncrease)
{
Character.Info?.IncreaseSkillLevel(skillIdentifier, skillIncrease, Character.Position + Vector2.UnitY * 175.0f);
}
else
{
LogabilityObjectMismatch();
}
}
}
}
@@ -27,9 +27,9 @@ namespace Barotrauma.Abilities
targetCharacter.GiveMoney((int)(multiplier * amount));
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if ((abilityData as Character ?? (abilityData as IAbilityCharacter)?.Character) is Character targetCharacter)
if ((abilityObject as IAbilityCharacter)?.Character is Character targetCharacter)
{
ApplyEffectSpecific(targetCharacter);
}
@@ -12,6 +12,8 @@ namespace Barotrauma.Abilities
private readonly bool targetAllies;
private readonly bool removeOnDeath;
private readonly bool removeAfterRound;
private readonly bool giveOnAddingFirstTime;
//private readonly float maximumValue;
public override bool AppliesEffectOnIntervalUpdate => true;
@@ -25,10 +27,19 @@ namespace Barotrauma.Abilities
targetAllies = abilityElement.GetAttributeBool("targetallies", false);
removeOnDeath = abilityElement.GetAttributeBool("removeondeath", true);
removeAfterRound = abilityElement.GetAttributeBool("removeafterround", false);
giveOnAddingFirstTime = abilityElement.GetAttributeBool("giveonaddingfirsttime", false);
//maximumValue = abilityElement.GetAttributeFloat("maximumvalue", float.MaxValue);
}
protected override void ApplyEffect(object abilityData)
public override void InitializeAbility(bool addingFirstTime)
{
if (giveOnAddingFirstTime && addingFirstTime)
{
ApplyEffectSpecific();
}
}
protected override void ApplyEffect(AbilityObject abilityObject)
{
ApplyEffectSpecific();
}
@@ -0,0 +1,23 @@
using Barotrauma.Extensions;
using System.Xml.Linq;
namespace Barotrauma.Abilities
{
class CharacterAbilityGiveTalentPoints : CharacterAbility
{
private readonly int amount;
public CharacterAbilityGiveTalentPoints(CharacterAbilityGroup characterAbilityGroup, XElement abilityElement) : base(characterAbilityGroup, abilityElement)
{
amount = abilityElement.GetAttributeInt("amount", 0);
}
public override void InitializeAbility(bool addingFirstTime)
{
if (addingFirstTime && Character.Info != null)
{
Character.Info.AdditionalTalentPoints += amount;
}
}
}
}
@@ -21,9 +21,9 @@ namespace Barotrauma.Abilities
ApplyEffectSpecific(Character);
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is Character character)
if ((abilityObject as IAbilityCharacter)?.Character is Character character)
{
ApplyEffectSpecific(character);
}
@@ -15,9 +15,9 @@ namespace Barotrauma.Abilities
addedMultiplier = abilityElement.GetAttributeFloat("addedmultiplier", 0f);
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is Affliction affliction)
if ((abilityObject as IAbilityAffliction)?.Affliction is Affliction affliction)
{
foreach (string afflictionIdentifier in afflictionIdentifiers)
{
@@ -29,7 +29,7 @@ namespace Barotrauma.Abilities
}
else
{
LogAbilityDataMismatch();
LogabilityObjectMismatch();
}
}
}
@@ -22,9 +22,9 @@ namespace Barotrauma.Abilities
implode = abilityElement.GetAttributeBool("implode", false);
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is AbilityAttackData attackData)
if (abilityObject is AbilityAttackData attackData)
{
if (attackData.Afflictions == null)
{
@@ -46,7 +46,7 @@ namespace Barotrauma.Abilities
}
else
{
LogAbilityDataMismatch();
LogabilityObjectMismatch();
}
}
}
@@ -12,15 +12,15 @@ namespace Barotrauma.Abilities
addedAmountMultiplier = abilityElement.GetAttributeFloat("addedamountmultiplier", 0f);
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is (Affliction affliction, float reduceAmount))
if (abilityObject is AbilityValueAffliction afflictionReduceAmount)
{
affliction.Strength -= addedAmountMultiplier * reduceAmount;
afflictionReduceAmount.Affliction.Strength -= addedAmountMultiplier * afflictionReduceAmount.Value;
}
else
{
LogAbilityDataMismatch();
LogabilityObjectMismatch();
}
}
}
@@ -13,9 +13,9 @@ namespace Barotrauma.Abilities
multiplyValue = abilityElement.GetAttributeFloat("multiplyvalue", 1f);
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is IAbilityValue abilityValue)
if (abilityObject is IAbilityValue abilityValue)
{
abilityValue.Value += addedValue;
abilityValue.Value *= multiplyValue;
@@ -11,7 +11,7 @@ namespace Barotrauma.Abilities
{
statIdentifier = abilityElement.GetAttributeString("statidentifier", "").ToLowerInvariant();
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
ApplyEffectSpecific();
}
@@ -21,7 +21,7 @@ namespace Barotrauma.Abilities
ApplyEffectSpecific();
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
ApplyEffectSpecific();
}
@@ -0,0 +1,39 @@
using System.Collections.Generic;
using System.Xml.Linq;
namespace Barotrauma.Abilities
{
class CharacterAbilitySpawnItemsToContainer : CharacterAbility
{
// currently used only for spawning items to containers
private readonly List<StatusEffect> statusEffects;
private readonly List<Item> openedContainers = new List<Item>();
private readonly float randomChance;
public CharacterAbilitySpawnItemsToContainer(CharacterAbilityGroup characterAbilityGroup, XElement abilityElement) : base(characterAbilityGroup, abilityElement)
{
statusEffects = CharacterAbilityGroup.ParseStatusEffects(CharacterTalent, abilityElement.GetChildElement("statuseffects"));
randomChance = abilityElement.GetAttributeFloat("randomchance", 1f);
}
protected override void ApplyEffect(AbilityObject abilityObject)
{
if ((abilityObject as IAbilityItem)?.Item is Item item)
{
if (openedContainers.Contains(item)) { return; }
openedContainers.Add(item);
if (randomChance < Rand.Range(0f, 1f, Rand.RandSync.Unsynced)) { return; }
foreach (var statusEffect in statusEffects)
{
statusEffect.Apply(ActionType.OnAbility, EffectDeltaTime, item, item);
}
}
else
{
LogabilityObjectMismatch();
}
}
}
}
@@ -18,9 +18,9 @@ namespace Barotrauma.Abilities
tags = abilityElement.GetAttributeStringArray("tags", Array.Empty<string>(), convertToLowerInvariant: true);
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is AbilityAttackData attackData)
if (abilityObject is AbilityAttackData attackData)
{
float totalAddedDamageMultiplier = 0f;
foreach (Item item in Character.Inventory.AllItems)
@@ -34,7 +34,7 @@ namespace Barotrauma.Abilities
}
else
{
LogAbilityDataMismatch();
LogabilityObjectMismatch();
}
}
}
@@ -10,11 +10,11 @@ namespace Barotrauma.Abilities
{
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is AbilityStringCharacter abilityStringCharacter && abilityStringCharacter.Character != Character)
if ((abilityObject as IAbilityString)?.String is string skillIdentifier && (abilityObject as IAbilityCharacter)?.Character is Character character)
{
Character.Info?.IncreaseSkillLevel(abilityStringCharacter.String, 1.0f, abilityStringCharacter.Character.Position + Vector2.UnitY * 175.0f);
Character.Info?.IncreaseSkillLevel(skillIdentifier, 1.0f, character.Position + Vector2.UnitY * 175.0f);
}
}
}
@@ -12,9 +12,9 @@ namespace Barotrauma.Abilities
vitalityPercentage = abilityElement.GetAttributeFloat("vitalitypercentage", 0f);
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is Character character)
if ((abilityObject as IAbilityCharacter)?.Character is Character character)
{
Character.GiveMoney((int)(vitalityPercentage * character.MaxVitality));
}
@@ -11,9 +11,9 @@ namespace Barotrauma.Abilities
{
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is string skillIdentifier)
if ((abilityObject as IAbilityString)?.String is string skillIdentifier)
{
if (skillIdentifier != lastSkillIdentifier)
{
@@ -8,19 +8,26 @@ namespace Barotrauma.Abilities
{
class CharacterAbilityRegenerateLoot : CharacterAbility
{
// separate random chance used for the ability itself to prevent the player
// from opening/reopening a container until it spawns loot
private readonly float randomChance;
// not maintained through death, so it's possible for players to respawn and re-loot chests
// seems like a minor issue for now
List<Item> openedContainers = new List<Item>();
private readonly List<Item> openedContainers = new List<Item>();
public CharacterAbilityRegenerateLoot(CharacterAbilityGroup characterAbilityGroup, XElement abilityElement) : base(characterAbilityGroup, abilityElement)
{
randomChance = abilityElement.GetAttributeFloat("randomchance", 1f);
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is Item item && !openedContainers.Contains(item))
if ((abilityObject as IAbilityItem)?.Item is Item item)
{
if (openedContainers.Contains(item)) { return; }
openedContainers.Add(item);
if (randomChance < Rand.Range(0f, 1f, Rand.RandSync.Unsynced)) { return; }
if (item.GetComponent<ItemContainer>() is ItemContainer itemContainer)
{
@@ -16,9 +16,9 @@ namespace Barotrauma.Abilities
statusEffectsRemove = CharacterAbilityGroup.ParseStatusEffects(CharacterTalent, abilityElement.GetChildElement("statuseffectsremove"));
}
protected override void ApplyEffect(object abilityData)
protected override void ApplyEffect(AbilityObject abilityObject)
{
if (abilityData is Character targetCharacter)
if ((abilityObject as IAbilityCharacter)?.Character is Character targetCharacter)
{
if (targetCharacter == Character) { return; }
@@ -10,25 +10,25 @@ namespace Barotrauma.Abilities
{
public CharacterAbilityGroupEffect(CharacterTalent characterTalent, XElement abilityElementGroup) : base(characterTalent, abilityElementGroup) { }
public void CheckAbilityGroup(object abilityData)
public void CheckAbilityGroup(AbilityObject abilityObject)
{
if (!IsActive) { return; }
if (IsApplicable(abilityData))
if (IsApplicable(abilityObject))
{
foreach (var characterAbility in characterAbilities)
{
if (characterAbility.IsViable())
{
characterAbility.ApplyAbilityEffect(abilityData);
characterAbility.ApplyAbilityEffect(abilityObject);
}
}
}
}
private bool IsApplicable(object abilityData)
private bool IsApplicable(AbilityObject abilityObject)
{
if (timesTriggered >= maxTriggerCount) { return false; }
return abilityConditions.All(c => c.MatchesCondition(abilityData));
return abilityConditions.All(c => c.MatchesCondition(abilityObject));
}
}
}
@@ -60,13 +60,13 @@ namespace Barotrauma
}
}
public void CheckTalent(AbilityEffectType abilityEffectType, object abilityData)
public void CheckTalent(AbilityEffectType abilityEffectType, AbilityObject abilityObject)
{
if (characterAbilityGroupEffectDictionary.TryGetValue(abilityEffectType, out var characterAbilityGroups))
{
foreach (var characterAbilityGroup in characterAbilityGroups)
{
characterAbilityGroup.CheckAbilityGroup(abilityData);
characterAbilityGroup.CheckAbilityGroup(abilityObject);
}
}
}
@@ -420,7 +420,9 @@ namespace Barotrauma
default:
try
{
XDocument.Load(file.Path);
using FileStream stream = File.Open(file.Path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
using var reader = XMLExtensions.CreateReader(stream);
XDocument.Load(reader);
}
catch (Exception e)
{
@@ -57,6 +57,7 @@
OnGainMissionMoney,
OnItemDeconstructed,
OnItemDeconstructedMaterial,
OnStopTinkering,
AfterSubmarineAttacked,
}
@@ -89,6 +90,7 @@
// Utility
RepairSpeed,
DeconstructorSpeedMultiplier,
TinkeringDuration,
// Misc
ReputationGainMultiplier,
MissionMoneyGainMultiplier,
@@ -108,6 +110,8 @@
IgnoredByEnemyAI,
MoveNormallyWhileDragging,
CanTinker,
CanTinkerFabricatorsAndDeconstructors,
TinkeringPowersDevices,
GainSkillPastMaximum,
RetainExperienceForNewCharacter
}
@@ -122,7 +122,7 @@ namespace Barotrauma
{
npcOrItem = npc;
npc.CampaignInteractionType = CampaignMode.InteractionType.Examine;
npc.RequireConsciousnessForCustomInteract = false;
npc.RequireConsciousnessForCustomInteract = DisableIfTargetIncapacitated;
#if CLIENT
npc.SetCustomInteract(
(speaker, player) => { if (e1 == speaker) { Trigger(speaker, player); } else { Trigger(player, speaker); } },
@@ -103,7 +103,7 @@ namespace Barotrauma
selectedEvents.Clear();
activeEvents.Clear();
pathFinder = new PathFinder(WayPoint.WayPointList, indoorsSteering: false);
pathFinder = new PathFinder(WayPoint.WayPointList, false);
totalPathLength = 0.0f;
if (level != null)
{
@@ -140,6 +140,12 @@ namespace Barotrauma
public override int GetReward(Submarine sub)
{
// If we are not at the location of the mission, skip the calculation of the reward
if (GameMain.GameSession?.StartLocation != Locations[0])
{
return calculatedReward;
}
bool missionsChanged = false;
if (GameMain.GameSession?.StartLocation?.SelectedMissions != null)
{
@@ -1,5 +1,5 @@
using System.Collections.Generic;
using System.IO;
using Barotrauma.IO;
using System.Linq;
namespace Barotrauma
@@ -16,7 +16,7 @@ namespace Barotrauma
{
forbiddenWords = File.ReadAllLines(fileListPath).Select(s => s.ToLowerInvariant()).ToHashSet();
}
catch (IOException e)
catch (System.IO.IOException e)
{
DebugConsole.ThrowError($"Failed to load the list of forbidden words from {fileListPath}.", e);
}
@@ -1,12 +1,11 @@
using Barotrauma.Items.Components;
using Barotrauma.Networking;
using FarseerPhysics;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Barotrauma.Networking;
using Barotrauma.Extensions;
namespace Barotrauma
{
@@ -17,11 +16,17 @@ namespace Barotrauma
// Anything that uses this field I wasn't sure if actually needed the proper campaign settings to be passed down
public static CampaignSettings Unsure = Empty;
public bool RadiationEnabled { get; set; }
public int MaxMissionCount { get; set; }
public int AddedMissionCount { get; set; }
public int TotalMaxMissionCount => MaxMissionCount + AddedMissionCount;
private int maxMissionCount;
public int MaxMissionCount
{
get { return maxMissionCount; }
set { maxMissionCount = MathHelper.Clamp(value, MinMissionCountLimit, MaxMissionCountLimit); }
}
public const int DefaultMaxMissionCount = 2;
public const int MaxMissionCountLimit = 10;
@@ -29,16 +34,18 @@ namespace Barotrauma
public CampaignSettings(IReadMessage inc)
{
maxMissionCount = DefaultMaxMissionCount;
RadiationEnabled = inc.ReadBoolean();
MaxMissionCount = inc.ReadInt32();
AddedMissionCount = inc.ReadInt32();
MaxMissionCount = inc.ReadInt32();
}
public CampaignSettings(XElement element)
{
maxMissionCount = DefaultMaxMissionCount;
RadiationEnabled = element.GetAttributeBool(nameof(RadiationEnabled).ToLowerInvariant(), true);
MaxMissionCount = element.GetAttributeInt(nameof(MaxMissionCount).ToLowerInvariant(), DefaultMaxMissionCount);
AddedMissionCount = element.GetAttributeInt(nameof(AddedMissionCount).ToLowerInvariant(), 0);
MaxMissionCount = element.GetAttributeInt(nameof(MaxMissionCount).ToLowerInvariant(), DefaultMaxMissionCount);
}
public void Serialize(IWriteMessage msg)
@@ -659,9 +659,9 @@ namespace Barotrauma
public static IEnumerable<Character> GetSessionCrewCharacters()
{
#if SERVER
return GameMain.Server.ConnectedClients.Select(c => c.Character).Where(c => c.Info != null);
return GameMain.Server.ConnectedClients.Select(c => c.Character).Where(c => c?.Info != null);
#else
return GameMain.GameSession.CrewManager.GetCharacters().Where(c => c.Info != null);
return GameMain.GameSession.CrewManager.GetCharacters().Where(c => c?.Info != null);
#endif
}
@@ -291,11 +291,25 @@ namespace Barotrauma
{
currentSlot = i;
if (allowedSlots.Any(a => a.HasFlag(SlotTypes[i])))
inSuitableSlot = true;
{
if ((SlotTypes[i] == InvSlotType.RightHand || SlotTypes[i] == InvSlotType.LeftHand) && !allowedSlots.Contains(SlotTypes[i]))
{
//allowed slot = InvSlotType.RightHand | InvSlotType.LeftHand
// -> make sure the item is in both hand slots
inSuitableSlot = IsInLimbSlot(item, InvSlotType.RightHand) && IsInLimbSlot(item, InvSlotType.LeftHand);
}
else
{
inSuitableSlot = true;
}
}
else if (!allowedSlots.Any(a => a.HasFlag(SlotTypes[i])))
{
inWrongSlot = true;
}
}
}
//all good
if (inSuitableSlot && !inWrongSlot) { return true; }
@@ -67,7 +67,7 @@ namespace Barotrauma.Items.Components
private bool isBroken;
public bool CanBeTraversed => (IsOpen || IsBroken) && !IsJammed && !IsStuck;
public bool CanBeTraversed => (IsOpen || IsBroken) && !IsJammed && !IsStuck && !Impassable;
public bool IsBroken
{
@@ -116,7 +116,11 @@ namespace Barotrauma.Items.Components
#if SERVER
item.CreateServerEvent(this);
#endif
}
}
foreach (Item containedItem in item.ContainedItems)
{
containedItem.GetComponent<GeneticMaterial>()?.Equip(character);
}
}
public override void Update(float deltaTime, Camera cam)
@@ -124,12 +128,16 @@ namespace Barotrauma.Items.Components
base.Update(deltaTime, cam);
if (targetCharacter != null)
{
var rootContainer = item.GetRootContainer();
if (!targetCharacter.HasEquippedItem(item) &&
(item.Container == null || !targetCharacter.HasEquippedItem(item.Container) || !(item.Container.GetComponent<ItemContainer>()?.AutoInject ?? false)))
(rootContainer == null || !targetCharacter.HasEquippedItem(rootContainer) || !targetCharacter.Inventory.IsInLimbSlot(rootContainer, InvSlotType.HealthInterface)))
{
item.ApplyStatusEffects(ActionType.OnSevered, 1.0f, targetCharacter);
var currentEffect = tainted ? selectedTaintedEffect : selectedEffect;
targetCharacter.CharacterHealth.ReduceAffliction(null, currentEffect.Identifier, currentEffect.MaxStrength);
targetCharacter.CharacterHealth.ReduceAffliction(null, selectedEffect.Identifier, selectedEffect.MaxStrength);
if (tainted)
{
targetCharacter.CharacterHealth.ReduceAffliction(null, selectedTaintedEffect.Identifier, selectedTaintedEffect.MaxStrength);
}
targetCharacter = null;
IsActive = false;
}
@@ -1,4 +1,5 @@
using Barotrauma.Networking;
using Barotrauma.Abilities;
using Barotrauma.Networking;
using FarseerPhysics;
using FarseerPhysics.Collision;
using FarseerPhysics.Dynamics;
@@ -158,10 +159,14 @@ namespace Barotrauma.Items.Components
if (currentChargeTime < MaxChargeTime) { return false; }
IsActive = true;
ReloadTimer = reload / (1 + character.GetStatValue(StatTypes.RangedAttackSpeed));
ReloadTimer = reload / (1 + character?.GetStatValue(StatTypes.RangedAttackSpeed) ?? 0f);
currentChargeTime = 0f;
character.CheckTalents(AbilityEffectType.OnUseRangedWeapon, item);
if (character != null)
{
var abilityItem = new AbilityItem(item);
character.CheckTalents(AbilityEffectType.OnUseRangedWeapon, abilityItem);
}
if (item.AiTarget != null)
{
@@ -6,6 +6,7 @@ using System.Xml.Linq;
using Barotrauma.Extensions;
using FarseerPhysics;
using System.Collections.Immutable;
using Barotrauma.Abilities;
namespace Barotrauma.Items.Components
{
@@ -114,6 +115,13 @@ namespace Barotrauma.Items.Components
set;
}
[Serialize(true, false)]
public bool AllowSwappingContainedItems
{
get;
set;
}
[Serialize(false, false, description: "If set to true, interacting with this item will make the character interact with the contained item(s), automatically picking them up if they can be picked up.")]
public bool AutoInteractWithContained
{
@@ -414,7 +422,8 @@ namespace Barotrauma.Items.Components
}
}
}
character.CheckTalents(AbilityEffectType.OnOpenItemContainer, item);
var abilityItem = new AbilityItem(item);
character.CheckTalents(AbilityEffectType.OnOpenItemContainer, abilityItem);
return base.Select(character);
}
@@ -588,6 +597,7 @@ namespace Barotrauma.Items.Components
public override void OnItemLoaded()
{
Inventory.AllowSwappingContainedItems = AllowSwappingContainedItems;
containableItemIdentifiers = slotRestrictions.SelectMany(s => s.ContainableItems?.SelectMany(ri => ri.Identifiers) ?? Enumerable.Empty<string>()).ToImmutableHashSet();
if (item.Submarine == null || !item.Submarine.Loading)
{
@@ -616,7 +626,21 @@ namespace Barotrauma.Items.Components
}
itemIds = null;
}
SpawnAlwaysContainedItems();
//outpost and ruins are loaded in multiple stages (each module is loaded separately)
//spawning items at this point during the generation will cause ID overlaps with the entities in the modules loaded afterwards
//so let's not spawn them at this point, but in the 1st Update()
if (item.Submarine?.Info != null && (item.Submarine.Info.IsOutpost || item.Submarine.Info.IsRuin))
{
if (SpawnWithId.Length > 0)
{
IsActive = true;
}
}
else
{
SpawnAlwaysContainedItems();
}
}
private void SpawnAlwaysContainedItems()
@@ -106,7 +106,7 @@ namespace Barotrauma.Items.Components
if ((Entity.Spawner?.IsInRemoveQueue(targetItem) ?? false) || !inputContainer.Inventory.AllItems.Contains(targetItem)) { continue; }
var validDeconstructItems = targetItem.Prefab.DeconstructItems.FindAll(it =>
(it.RequiredDeconstructor.Length == 0 || it.RequiredDeconstructor.Any(r => item.HasTag(r) || item.Prefab.Identifier.Equals(r, StringComparison.OrdinalIgnoreCase))) &&
(it.RequiredOtherItem.Length == 0 || it.RequiredOtherItem.Any(r => items.Any(it => it.HasTag(r) || it.Prefab.Identifier.Equals(r, StringComparison.OrdinalIgnoreCase)))));
(it.RequiredOtherItem.Length == 0 || it.RequiredOtherItem.Any(r => items.Any(it => it != targetItem && (it.HasTag(r) || it.Prefab.Identifier.Equals(r, StringComparison.OrdinalIgnoreCase))))));
ProcessItem(targetItem, items, validDeconstructItems, allowRemove: validDeconstructItems.Any() || !targetItem.Prefab.DeconstructItems.Any());
}
@@ -148,6 +148,12 @@ namespace Barotrauma.Items.Components
// In multiplayer, the server handles the deconstruction into new items
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return; }
if (user != null && !user.Removed)
{
var abilityTargetItem = new AbilityItem(targetItem);
user.CheckTalents(AbilityEffectType.OnItemDeconstructed, abilityTargetItem);
}
if (targetItem.Prefab.RandomDeconstructionOutput)
{
int amount = targetItem.Prefab.RandomDeconstructionOutputAmount;
@@ -169,8 +175,6 @@ namespace Barotrauma.Items.Components
commonness.RemoveAt(removeIndex);
}
user.CheckTalents(AbilityEffectType.OnItemDeconstructed, targetItem);
foreach (DeconstructItem deconstructProduct in products)
{
CreateDeconstructProduct(deconstructProduct, inputItems);
@@ -225,10 +229,15 @@ namespace Barotrauma.Items.Components
}
}
}
var itemsCreated = new AbilityValue(1f);
user.CheckTalents(AbilityEffectType.OnItemDeconstructedMaterial, (targetItem.Prefab, itemsCreated));
int amount = (int)itemsCreated.Value;
int amount = 1;
if (user != null && !user.Removed)
{
var itemsCreated = new AbilityValueItem(1f, targetItem.Prefab);
user.CheckTalents(AbilityEffectType.OnItemDeconstructedMaterial, itemsCreated);
amount = (int)itemsCreated.Value;
}
for (int i = 0; i < amount; i++)
{
@@ -113,37 +113,35 @@ namespace Barotrauma.Items.Components
Force = MathHelper.Lerp(force, (Voltage < MinVoltage) ? 0.0f : targetForce, 0.1f);
if (Math.Abs(Force) > 1.0f)
{
float voltageFactor = MinVoltage <= 0.0f ? 1.0f : Math.Min(Voltage, 1.0f);
float currForce = force * voltageFactor;
float condition = item.Condition / item.MaxCondition;
// Broken engine makes more noise.
float noise = Math.Abs(currForce) * MathHelper.Lerp(1.5f, 1f, condition);
UpdateAITargets(noise);
//arbitrary multiplier that was added to changes in submarine mass without having to readjust all engines
float forceMultiplier = 0.1f;
if (User != null)
{
forceMultiplier *= MathHelper.Lerp(0.5f, 2.0f, (float)Math.Sqrt(User.GetSkillLevel("helm") / 100));
}
float voltageFactor = MinVoltage <= 0.0f ? 1.0f : Math.Min(Voltage, 1.0f);
Vector2 currForce = new Vector2(force * maxForce * forceMultiplier * voltageFactor, 0.0f);
if (item.GetComponent<Repairable>()?.IsTinkering ?? false)
currForce *= maxForce * forceMultiplier;
if (item.GetComponent<Repairable>() is Repairable repairable && repairable.IsTinkering)
{
currForce *= 2.5f;
}
//less effective when in a bad condition
currForce *= MathHelper.Lerp(0.5f, 2.0f, item.Condition / item.MaxCondition);
currForce *= MathHelper.Lerp(0.5f, 2.0f, condition);
if (item.Submarine.FlippedX) { currForce *= -1; }
item.Submarine.ApplyForce(currForce);
Vector2 forceVector = new Vector2(currForce, 0);
item.Submarine.ApplyForce(forceVector);
UpdatePropellerDamage(deltaTime);
float maxChangeSpeed = 0.5f;
float modifier = 2;
float noise = MathUtils.NearlyEqual(0.0f, maxForce) ? 0.0f : currForce.Length() * forceMultiplier * modifier / maxForce;
float min = Math.Max(1 - maxChangeSpeed, 0);
float max = 1 + maxChangeSpeed;
UpdateAITargets(Math.Clamp(noise, min, max), deltaTime);
#if CLIENT
particleTimer -= deltaTime;
if (particleTimer <= 0.0f)
{
Vector2 particleVel = -currForce.ClampLength(5000.0f) / 5.0f;
Vector2 particleVel = -forceVector.ClampLength(5000.0f) / 5.0f;
GameMain.ParticleManager.CreateParticle("bubbles", item.WorldPosition + PropellerPos * item.Scale,
particleVel * Rand.Range(0.9f, 1.1f),
0.0f, item.CurrentHull);
@@ -153,14 +151,14 @@ namespace Barotrauma.Items.Components
}
}
private void UpdateAITargets(float increaseSpeed, float deltaTime)
private void UpdateAITargets(float noise)
{
if (item.AiTarget != null)
{
item.AiTarget.IncreaseSoundRange(deltaTime, increaseSpeed);
item.AiTarget.SoundRange = MathHelper.Lerp(item.AiTarget.MinSoundRange, item.AiTarget.MaxSoundRange, noise / 100);
if (item.CurrentHull != null && item.CurrentHull.AiTarget != null)
{
// It's possible that some othe item increases the hull's soundrange more than the engine.
// It's possible that some other item increases the hull's soundrange more than the engine.
item.CurrentHull.AiTarget.SoundRange = Math.Max(item.CurrentHull.AiTarget.SoundRange, item.AiTarget.SoundRange);
}
}
@@ -327,6 +327,7 @@ namespace Barotrauma.Items.Components
int amountFittingContainer = outputContainer.Inventory.HowManyCanBePut(fabricatedItem.TargetItem, fabricatedItem.OutCondition * fabricatedItem.TargetItem.Health);
var fabricationValueItem = new AbilityValueItem(fabricatedItem.Amount, fabricatedItem.TargetItem);
if (user != null)
{
foreach (Character character in Character.CharacterList.Where(c => c.TeamID == user.TeamID))
@@ -369,10 +370,11 @@ namespace Barotrauma.Items.Components
float addedSkill = skill.Level * SkillSettings.Current.SkillIncreasePerFabricatorRequiredSkill / Math.Max(userSkill, 1.0f);
var addedSkillValue = new AbilityValueString(0f, skill.Identifier);
user.CheckTalents(AbilityEffectType.OnItemFabricationSkillGain, addedSkillValue);
addedSkill += addedSkillValue.Value;
user.Info.IncreaseSkillLevel(
skill.Identifier,
addedSkill + addedSkillValue.Value,
addedSkill,
user.Position + Vector2.UnitY * 150.0f);
}
}
@@ -106,7 +106,7 @@ namespace Barotrauma.Items.Components
currFlow = flowPercentage / 100.0f * maxFlow * powerFactor;
if (item.GetComponent<Repairable>()?.IsTinkering ?? false)
if (item.GetComponent<Repairable>() is Repairable repairable && repairable.IsTinkering)
{
currFlow *= 2.5f;
}
@@ -367,23 +367,19 @@ namespace Barotrauma.Items.Components
item.Condition -= fissionRate / 100.0f * fuelConsumptionRate * deltaTime;
}
}
if (item.CurrentHull != null)
{
var aiTarget = item.CurrentHull.AiTarget;
if (aiTarget != null && MaxPowerOutput > 0)
{
float range = Math.Abs(currPowerConsumption) / MaxPowerOutput;
float noise = MathHelper.Lerp(aiTarget.MinSoundRange, aiTarget.MaxSoundRange, range);
aiTarget.SoundRange = Math.Max(aiTarget.SoundRange, noise);
}
}
if (item.AiTarget != null && MaxPowerOutput > 0)
{
var aiTarget = item.AiTarget;
float range = Math.Abs(currPowerConsumption) / MaxPowerOutput;
aiTarget.SoundRange = MathHelper.Lerp(aiTarget.MinSoundRange, aiTarget.MaxSoundRange, range);
if (item.CurrentHull != null)
{
var hullAITarget = item.CurrentHull.AiTarget;
if (hullAITarget != null)
{
hullAITarget.SoundRange = Math.Max(hullAITarget.SoundRange, aiTarget.SoundRange);
}
}
}
}
@@ -85,10 +85,10 @@ namespace Barotrauma.Items.Components
}
private float skillRequirementMultiplier;
[Serialize(1.0f, true)]
public float SkillRequirementMultiplier
{
public float SkillRequirementMultiplier
{
get { return skillRequirementMultiplier; }
set
{
@@ -100,7 +100,7 @@ namespace Barotrauma.Items.Components
RecreateGUI();
}
#endif
}
}
}
public bool IsTinkering { get; private set; } = false;
@@ -113,6 +113,8 @@ namespace Barotrauma.Items.Components
public Character CurrentFixer { get; private set; }
private Item currentRepairItem;
private float tinkeringDuration;
public enum FixActions : int
{
None = 0,
@@ -135,13 +137,13 @@ namespace Barotrauma.Items.Components
canBeSelected = true;
this.item = item;
header =
header =
TextManager.Get(element.GetAttributeString("header", ""), returnNull: true) ??
TextManager.Get(item.Prefab.ConfigElement.GetAttributeString("header", ""), returnNull: true) ??
element.GetAttributeString("name", "");
//backwards compatibility
var repairThresholdAttribute =
var repairThresholdAttribute =
element.Attributes().FirstOrDefault(a => a.Name.ToString().Equals("showrepairuithreshold", StringComparison.OrdinalIgnoreCase)) ??
element.Attributes().FirstOrDefault(a => a.Name.ToString().Equals("airepairthreshold", StringComparison.OrdinalIgnoreCase));
if (repairThresholdAttribute != null)
@@ -197,7 +199,7 @@ namespace Barotrauma.Items.Components
return ((average + 100.0f) / 2.0f) / 100.0f;
}
public bool StartRepairing(Character character, FixActions action)
{
if (character == null || character.IsDead || action == FixActions.None)
@@ -227,6 +229,18 @@ namespace Barotrauma.Items.Components
CurrentFixer = character;
currentRepairItem = bestRepairItem;
CurrentFixerAction = action;
if (action == FixActions.Tinker)
{
if (character.HasAbilityFlag(AbilityFlags.CanTinkerFabricatorsAndDeconstructors) && item.GetComponent<Deconstructor>() != null || item.GetComponent<Fabricator>() != null)
{
// fabricators and deconstructors can be tinkered indefinitely (more or less)
tinkeringDuration = float.MaxValue;
}
else
{
tinkeringDuration = CurrentFixer.GetStatValue(StatTypes.TinkeringDuration);
}
}
return true;
Item GetBestRepairItem(Character character)
@@ -254,13 +268,17 @@ namespace Barotrauma.Items.Components
ic.ApplyStatusEffects(ActionType.OnSuccess, 1.0f, character);
}
}
if (CurrentFixerAction == FixActions.Tinker)
{
CurrentFixer.CheckTalents(AbilityEffectType.OnStopTinkering);
}
CurrentFixer.AnimController.Anim = AnimController.Animation.None;
CurrentFixer = null;
currentRepairItem = null;
currentFixerAction = FixActions.None;
#if CLIENT
repairSoundChannel?.FadeOutAndDispose();
repairSoundChannel = null;
repairSoundChannel = null;
#endif
return true;
}
@@ -290,6 +308,8 @@ namespace Barotrauma.Items.Components
UpdateProjSpecific(deltaTime);
IsTinkering = false;
item.SendSignal($"{(int) item.ConditionPercentage}", "condition_out");
if (CurrentFixer == null)
{
if (deteriorateAlwaysResetTimer > 0.0f)
@@ -339,8 +359,9 @@ namespace Barotrauma.Items.Components
if (currentFixerAction == FixActions.Tinker)
{
tinkeringDuration -= deltaTime;
// not great to interject it here, should be less reliant on returning
if (!CanTinker(CurrentFixer))
if (!CanTinker(CurrentFixer) || tinkeringDuration <= 0f)
{
StopRepairing(CurrentFixer);
}
@@ -396,7 +417,7 @@ namespace Barotrauma.Items.Components
CurrentFixer.CheckTalents(AbilityEffectType.OnRepairComplete);
}
deteriorationTimer = Rand.Range(MinDeteriorationDelay, MaxDeteriorationDelay);
wasBroken = false;
wasBroken = false;
StopRepairing(CurrentFixer);
}
}
@@ -439,9 +460,27 @@ namespace Barotrauma.Items.Components
}
}
private bool CanTinker(Character character)
private bool IsTinkerable(Character character)
{
if (!character.HasAbilityFlag(AbilityFlags.CanTinker)) { return false; }
if (item.GetComponent<Engine>() != null) { return true; }
if (item.GetComponent<Turret>() != null) { return true; }
if (item.GetComponent<Pump>() != null) { return true; }
if (!character.HasAbilityFlag(AbilityFlags.CanTinkerFabricatorsAndDeconstructors)) { return false; }
if (item.GetComponent<Fabricator>() != null) { return true; }
if (item.GetComponent<Deconstructor>() != null) { return true; }
return false;
}
private Affliction GetTinkerExhaustion(Character character)
{
return character.CharacterHealth.GetAffliction("tinkerexhaustion");
}
private bool CanTinker(Character character)
{
if (!IsTinkerable(character)) { return false; }
if (GetTinkerExhaustion(character) is Affliction tinkerExhaustion && tinkerExhaustion.Strength <= tinkerExhaustion.Prefab.MaxStrength) { return false; }
return true;
}
@@ -469,7 +508,7 @@ namespace Barotrauma.Items.Components
}
else if (ic is PowerTransfer pt)
{
//power transfer items (junction boxes, relays) don't deteriorate if they're no carrying any power
//power transfer items (junction boxes, relays) don't deteriorate if they're no carrying any power
if (Math.Abs(pt.CurrPowerConsumption) > 0.1f) { return true; }
}
else if (ic is Engine engine)
@@ -530,7 +569,7 @@ namespace Barotrauma.Items.Components
public override void ReceiveSignal(Signal signal, Connection connection)
{
//do nothing
//Repairables should always stay active, so we don't want to use the default behavior
//Repairables should always stay active, so we don't want to use the default behavior
//where set_active/set_state signals can disable the component
}
}
@@ -233,6 +233,8 @@ namespace Barotrauma.Items.Components
}
UpdateOnActiveEffects(deltaTime);
if (powerIn == null && powerConsumption > 0.0f) { Voltage -= deltaTime; }
#if CLIENT
Light.ParentSub = item.Submarine;
#endif
@@ -293,8 +295,6 @@ namespace Barotrauma.Items.Components
}
SetLightSourceState(true, lightBrightness);
if (powerIn == null && powerConsumption > 0.0f) { Voltage -= deltaTime; }
}
public override void UpdateBroken(float deltaTime, Camera cam)
@@ -742,10 +742,10 @@ namespace Barotrauma.Items.Components
Projectile projectileComponent = projectile.GetComponent<Projectile>();
if (projectileComponent != null)
{
projectileComponent.Attacker = user;
projectileComponent.Attacker = projectileComponent.User = user;
if (isTinkering)
{
projectileComponent.Attack.DamageMultiplier *= 1.25f;
projectileComponent.Attack.DamageMultiplier = 1.25f;
}
projectileComponent.Use();
projectile.GetComponent<Rope>()?.Attach(item, projectile);
@@ -258,6 +258,8 @@ namespace Barotrauma
get { return capacity; }
}
public bool AllowSwappingContainedItems = true;
public Inventory(Entity owner, int capacity, int slotsPerRow = 5)
{
this.capacity = capacity;
@@ -623,6 +625,8 @@ namespace Barotrauma
protected bool TrySwapping(int index, Item item, Character user, bool createNetworkEvent, bool swapWholeStack)
{
if (item?.ParentInventory == null || !slots[index].Any()) { return false; }
if (slots[index].Items.Any(it => !it.IsInteractable(user))) { return false; }
if (!AllowSwappingContainedItems) { return false; }
//swap to InvSlotType.Any if possible
Inventory otherInventory = item.ParentInventory;
@@ -230,8 +230,7 @@ namespace Barotrauma
public bool IsInteractable(Character character)
{
if (character != null && character.IsOnPlayerTeam)
{
{
return IsPlayerTeamInteractable;
}
else
@@ -41,6 +41,11 @@ namespace Barotrauma
get { return type; }
}
/// <summary>
/// Index of the slot the target must be in when targeting a Contained item
/// </summary>
public int TargetSlot = -1;
public string JoinedIdentifiers
{
get { return string.Join(",", Identifiers); }
@@ -147,7 +152,9 @@ namespace Barotrauma
foreach (Item contained in parentItem.ContainedItems)
{
if (TargetSlot > -1 && parentItem.OwnInventory.FindIndex(contained) != TargetSlot) { continue; }
if ((!ExcludeBroken || contained.Condition > 0.0f) && MatchesItem(contained)) { return true; }
if (CheckContained(contained)) { return true; }
}
return false;
@@ -271,6 +278,8 @@ namespace Barotrauma
ri.IsOptional = element.GetAttributeBool("optional", false);
ri.IgnoreInEditor = element.GetAttributeBool("ignoreineditor", false);
ri.MatchOnEmpty = element.GetAttributeBool("matchonempty", false);
ri.TargetSlot = element.GetAttributeInt("targetslot", -1);
return ri;
}
}
@@ -471,9 +471,8 @@ namespace Barotrauma
{
aiTarget = new AITarget(this)
{
MinSightRange = 2000,
MinSightRange = 1000,
MaxSightRange = 5000,
MaxSoundRange = 5000,
SoundRange = 0
};
}
@@ -787,7 +786,7 @@ namespace Barotrauma
if (aiTarget != null)
{
aiTarget.SightRange = Submarine == null ? aiTarget.MinSightRange : Submarine.Velocity.Length() / 2 * aiTarget.MaxSightRange;
aiTarget.SightRange = Submarine == null ? aiTarget.MinSightRange : MathHelper.Lerp(aiTarget.MinSightRange, aiTarget.MaxSightRange, Submarine.Velocity.Length() / 10);
aiTarget.SoundRange -= deltaTime * 1000.0f;
}
@@ -1244,6 +1243,44 @@ namespace Barotrauma
return "RoomName.Sub" + roomPos.ToString();
}
/// <summary>
/// Is this hull or any of the items inside it tagged as "airlock"?
/// </summary>
public bool IsTaggedAirlock()
{
if (RoomName != null && RoomName.Contains("airlock", StringComparison.OrdinalIgnoreCase))
{
return true;
}
else
{
foreach (Item item in Item.ItemList)
{
if (item.CurrentHull != this && item.HasTag("airlock"))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Does this hull have any doors leading outside?
/// </summary>
/// <param name="character">Used to check if this character has access to the door leading outside</param>
public bool LeadsOutside(Character character)
{
foreach (var gap in ConnectedGaps)
{
if (gap.ConnectedDoor == null) { continue; }
if (gap.IsRoomToRoom) { continue; }
if (!gap.ConnectedDoor.CanBeTraversed && (character == null || !gap.ConnectedDoor.HasAccess(character))) { continue; }
return true;
}
return false;
}
#region BackgroundSections
private void CreateBackgroundSections()
{
@@ -415,14 +415,13 @@ namespace Barotrauma
//connect clone wires to the clone items and refresh links between doors and gaps
for (int i = 0; i < clones.Count; i++)
{
var cloneItem = clones[i] as Item;
if (cloneItem == null) { continue; }
if (!(clones[i] is Item cloneItem)) { continue; }
var door = cloneItem.GetComponent<Door>();
door?.RefreshLinkedGap();
var cloneWire = cloneItem.GetComponent<Wire>();
if (cloneWire == null) continue;
if (cloneWire == null) { continue; }
var originalWire = ((Item)entitiesToClone[i]).GetComponent<Wire>();
@@ -430,10 +429,23 @@ namespace Barotrauma
for (int n = 0; n < 2; n++)
{
if (originalWire.Connections[n] == null) { continue; }
if (originalWire.Connections[n] == null)
{
var disconnectedFrom = entitiesToClone.Find(e => e is Item item && (item.GetComponent<ConnectionPanel>()?.DisconnectedWires.Contains(originalWire) ?? false));
if (disconnectedFrom == null) { continue; }
int disconnectedFromIndex = entitiesToClone.IndexOf(disconnectedFrom);
var disconnectedFromClone = (clones[disconnectedFromIndex] as Item)?.GetComponent<ConnectionPanel>();
if (disconnectedFromClone == null) { continue; }
disconnectedFromClone.DisconnectedWires.Add(cloneWire);
if (cloneWire.Item.body != null) { cloneWire.Item.body.Enabled = false; }
cloneWire.IsActive = false;
continue;
}
var connectedItem = originalWire.Connections[n].Item;
if (connectedItem == null) continue;
if (connectedItem == null) { continue; }
//index of the item the wire is connected to
int itemIndex = entitiesToClone.IndexOf(connectedItem);
@@ -8,6 +8,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Barotrauma.Abilities;
#if CLIENT
using Microsoft.Xna.Framework.Graphics;
#endif
@@ -437,8 +438,8 @@ namespace Barotrauma
{
aiTarget = new AITarget(this)
{
MinSightRange = 2000,
MaxSightRange = 5000,
MinSightRange = 1000,
MaxSightRange = 4000,
MaxSoundRange = 0
};
}
@@ -956,11 +957,12 @@ namespace Barotrauma
}
#endif
if (Submarine != null && damageAmount > 0)
if (Submarine != null && damageAmount > 0 && attacker != null)
{
var abilityAttackerSubmarine = new AbilityCharacterSubmarine(attacker, Submarine);
foreach (Character character in Character.CharacterList)
{
character.CheckTalents(AbilityEffectType.AfterSubmarineAttacked, Submarine);
character.CheckTalents(AbilityEffectType.AfterSubmarineAttacked, abilityAttackerSubmarine);
}
}
@@ -1462,7 +1464,7 @@ namespace Barotrauma
{
if (aiTarget != null)
{
aiTarget.SightRange = Submarine == null ? aiTarget.MinSightRange : Submarine.Velocity.Length() / 2 * aiTarget.MaxSightRange;
aiTarget.SightRange = Submarine == null ? aiTarget.MinSightRange : MathHelper.Lerp(aiTarget.MinSightRange, aiTarget.MaxSightRange, Submarine.Velocity.Length() / 10);
}
}
}
@@ -96,6 +96,9 @@ namespace Barotrauma
public OutpostModuleInfo OutpostModuleInfo { get; set; }
public bool IsOutpost => Type == SubmarineType.Outpost || Type == SubmarineType.OutpostModule;
//TODO: replace when the ruin branch is merged
public bool IsRuin => false;
public bool IsWreck => Type == SubmarineType.Wreck;
public bool IsBeacon => Type == SubmarineType.BeaconStation;
public bool IsPlayer => Type == SubmarineType.Player;
@@ -743,7 +746,10 @@ namespace Barotrauma
try
{
stream.Position = 0;
doc = XDocument.Load(stream); //ToolBox.TryLoadXml(file);
using (var reader = XMLExtensions.CreateReader(stream))
{
doc = XDocument.Load(reader);
}
stream.Close();
stream.Dispose();
}
@@ -760,9 +766,10 @@ namespace Barotrauma
try
{
ToolBox.IsProperFilenameCase(file);
doc = XDocument.Load(file, LoadOptions.SetBaseUri);
using var stream = File.Open(file, System.IO.FileMode.Open, System.IO.FileAccess.Read);
using var reader = XMLExtensions.CreateReader(stream);
doc = XDocument.Load(reader);
}
catch (Exception e)
{
exception = e;
@@ -892,8 +892,15 @@ namespace Barotrauma.Networking
get;
set;
}
// we do not serialize this value because it relies on a default setting
public int MaxMissionCount { get; set; } = CampaignSettings.DefaultMaxMissionCount;
private int maxMissionCount = CampaignSettings.DefaultMaxMissionCount;
[Serialize(CampaignSettings.DefaultMaxMissionCount, true)]
public int MaxMissionCount
{
get { return maxMissionCount; }
set { maxMissionCount = MathHelper.Clamp(value, CampaignSettings.MinMissionCountLimit, CampaignSettings.MaxMissionCountLimit); }
}
public void SetPassword(string password)
{
@@ -73,19 +73,7 @@ namespace Barotrauma
public int GetMaxMissionCount()
{
#if CLIENT
// this seems rather silly, but it matches the radiation enabled check structurally. is this right?
if (maxMissionCountText != null && Int32.TryParse(maxMissionCountText.Text, out int result))
{
return result;
}
else
{
return 0;
}
#elif SERVER
return GameMain.Server.ServerSettings.MaxMissionCount;
#endif
return GameMain.NetworkMember?.ServerSettings?.MaxMissionCount ?? 0;
}
public void ToggleTraitorsEnabled(int dir)
@@ -1,5 +1,4 @@
using System;
using Barotrauma.IO;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
@@ -7,20 +6,54 @@ using System.Text;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Xna.Framework;
using File = Barotrauma.IO.File;
using FileStream = Barotrauma.IO.FileStream;
namespace Barotrauma
{
public static class XMLExtensions
{
public static string ParseContentPathFromUri(this XObject element) => Path.GetRelativePath(Environment.CurrentDirectory, element.BaseUri);
public static string ParseContentPathFromUri(this XObject element) => System.IO.Path.GetRelativePath(Environment.CurrentDirectory, element.BaseUri);
public static readonly XmlReaderSettings ReaderSettings = new XmlReaderSettings
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null
};
public static XmlReader CreateReader(System.IO.Stream stream)
=> XmlReader.Create(stream, ReaderSettings);
public static XDocument TryLoadXml(System.IO.Stream stream)
{
XDocument doc;
try
{
using XmlReader reader = CreateReader(stream);
doc = XDocument.Load(reader);
}
catch (Exception e)
{
DebugConsole.ThrowError($"Couldn't load xml document from stream!", e);
return null;
}
if (doc?.Root == null)
{
DebugConsole.ThrowError("XML could not be loaded from stream: Document or the root element is invalid!");
return null;
}
return doc;
}
public static XDocument TryLoadXml(string filePath)
{
XDocument doc;
try
{
ToolBox.IsProperFilenameCase(filePath);
doc = XDocument.Load(filePath, LoadOptions.SetBaseUri);
using FileStream stream = File.Open(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
using XmlReader reader = CreateReader(stream);
doc = XDocument.Load(reader);
}
catch (Exception e)
{
@@ -45,7 +78,9 @@ namespace Barotrauma
{
try
{
doc = XDocument.Load(filePath, LoadOptions.SetBaseUri);
using FileStream stream = File.Open(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
using XmlReader reader = CreateReader(stream);
doc = XDocument.Load(reader);
}
catch
{
@@ -137,6 +137,7 @@ namespace Barotrauma
public readonly ItemPrefab ItemPrefab;
public readonly SpawnPositionType SpawnPosition;
public readonly bool SpawnIfInventoryFull;
public readonly float Speed;
public readonly float Rotation;
public readonly int Count;
@@ -173,6 +174,7 @@ namespace Barotrauma
}
}
SpawnIfInventoryFull = element.GetAttributeBool("spawnifinventoryfull", false);
Speed = element.GetAttributeFloat("speed", 0.0f);
Rotation = element.GetAttributeFloat("rotation", 0.0f);
@@ -312,6 +314,8 @@ namespace Barotrauma
private set;
}
private bool modifyAfflictionsByMaxVitality;
public IEnumerable<CharacterSpawnInfo> SpawnCharacters
{
get { return spawnCharacters; }
@@ -373,6 +377,7 @@ namespace Barotrauma
ReduceAffliction = new List<(string affliction, float amount)>();
giveExperiences = new List<int>();
giveSkills = new List<(string, float)>();
modifyAfflictionsByMaxVitality = element.GetAttributeBool("multiplyafflictionsbymaxvitality", false);
tags = new HashSet<string>(element.GetAttributeString("tags", "").Split(','));
OnlyInside = element.GetAttributeBool("onlyinside", false);
@@ -695,7 +700,7 @@ namespace Barotrauma
{
if (requiredAfflictions == null) { return true; }
if (attackResult.Afflictions == null) { return false; }
if (attackResult.Afflictions.None(a => requiredAfflictions.Any(a2 => a.Strength >= a2.strength && a.Identifier == a2.affliction || a.Prefab.AfflictionType == a2.affliction)))
if (attackResult.Afflictions.None(a => requiredAfflictions.Any(a2 => a.Strength >= a2.strength && (a.Identifier == a2.affliction || a.Prefab.AfflictionType == a2.affliction))))
{
return false;
}
@@ -1151,7 +1156,7 @@ namespace Barotrauma
if (target is Character character)
{
if (character.Removed) { continue; }
newAffliction = GetMultipliedAffliction(affliction, entity, character, deltaTime);
newAffliction = GetMultipliedAffliction(affliction, entity, character, deltaTime, modifyAfflictionsByMaxVitality);
character.LastDamageSource = entity;
foreach (Limb limb in character.AnimController.Limbs)
{
@@ -1169,7 +1174,7 @@ namespace Barotrauma
{
if (limb.IsSevered) { continue; }
if (limb.character.Removed || limb.Removed) { continue; }
newAffliction = GetMultipliedAffliction(affliction, entity, limb.character, deltaTime);
newAffliction = GetMultipliedAffliction(affliction, entity, limb.character, deltaTime, modifyAfflictionsByMaxVitality);
AttackResult result = limb.character.DamageLimb(position, limb, newAffliction.ToEnumerable(), stun: 0.0f, playSound: false, attackImpulse: 0.0f, attacker: affliction.Source, allowStacking: !setValue);
limb.character.TrySeverLimbJoints(limb, SeverLimbsProbability, disableDeltaTime ? result.Damage : result.Damage / deltaTime, allowBeheading: true);
RegisterTreatmentResults(entity, limb, affliction, result);
@@ -1417,9 +1422,9 @@ namespace Barotrauma
{
inventory = item?.GetComponent<ItemContainer>()?.Inventory;
}
if (inventory != null && inventory.CanBePut(chosenItemSpawnInfo.ItemPrefab))
if (inventory != null && (inventory.CanBePut(chosenItemSpawnInfo.ItemPrefab) || chosenItemSpawnInfo.SpawnIfInventoryFull))
{
Entity.Spawner.AddToSpawnQueue(chosenItemSpawnInfo.ItemPrefab, inventory, spawnIfInventoryFull: false);
Entity.Spawner.AddToSpawnQueue(chosenItemSpawnInfo.ItemPrefab, inventory, spawnIfInventoryFull: chosenItemSpawnInfo.SpawnIfInventoryFull);
}
}
break;
@@ -1439,9 +1444,9 @@ namespace Barotrauma
foreach (Item item in thisInventory.AllItems)
{
Inventory containedInventory = item.GetComponent<ItemContainer>()?.Inventory;
if (containedInventory != null && containedInventory.CanBePut(chosenItemSpawnInfo.ItemPrefab))
if (containedInventory != null && (containedInventory.CanBePut(chosenItemSpawnInfo.ItemPrefab) || chosenItemSpawnInfo.SpawnIfInventoryFull))
{
Entity.Spawner.AddToSpawnQueue(chosenItemSpawnInfo.ItemPrefab, containedInventory, spawnIfInventoryFull: false);
Entity.Spawner.AddToSpawnQueue(chosenItemSpawnInfo.ItemPrefab, containedInventory, spawnIfInventoryFull: chosenItemSpawnInfo.SpawnIfInventoryFull);
}
break;
}
@@ -1543,14 +1548,14 @@ namespace Barotrauma
if (target is Character character)
{
if (character.Removed) { continue; }
newAffliction = element.Parent.GetMultipliedAffliction(affliction, element.Entity, character, deltaTime);
newAffliction = element.Parent.GetMultipliedAffliction(affliction, element.Entity, character, deltaTime, element.Parent.modifyAfflictionsByMaxVitality);
var result = character.AddDamage(character.WorldPosition, newAffliction.ToEnumerable(), stun: 0.0f, playSound: false, attacker: element.User);
element.Parent.RegisterTreatmentResults(element.Entity, result.HitLimb, affliction, result);
}
else if (target is Limb limb)
{
if (limb.character.Removed || limb.Removed) { continue; }
newAffliction = element.Parent.GetMultipliedAffliction(affliction, element.Entity, limb.character, deltaTime);
newAffliction = element.Parent.GetMultipliedAffliction(affliction, element.Entity, limb.character, deltaTime, element.Parent.modifyAfflictionsByMaxVitality);
var result = limb.character.DamageLimb(limb.WorldPosition, limb, newAffliction.ToEnumerable(), stun: 0.0f, playSound: false, attackImpulse: 0.0f, attacker: element.User);
element.Parent.RegisterTreatmentResults(element.Entity, limb, affliction, result);
}
@@ -1614,9 +1619,14 @@ namespace Barotrauma
return multiplier;
}
private Affliction GetMultipliedAffliction(Affliction affliction, Entity entity, Character targetCharacter, float deltaTime)
private Affliction GetMultipliedAffliction(Affliction affliction, Entity entity, Character targetCharacter, float deltaTime, bool modifyByMaxVitality)
{
float afflictionMultiplier = GetAfflictionMultiplier(entity, targetCharacter, deltaTime);
if (modifyByMaxVitality)
{
afflictionMultiplier *= targetCharacter.MaxVitality / 100f;
}
if (!MathUtils.NearlyEqual(afflictionMultiplier, 1.0f))
{
return affliction.CreateMultiplied(afflictionMultiplier);
@@ -49,7 +49,7 @@ namespace Barotrauma
Reactor reactor = item.GetComponent<Reactor>();
if (reactor != null) { roundData.Reactors.Add(reactor); }
}
pathFinder = new PathFinder(WayPoint.WayPointList, indoorsSteering: false);
pathFinder = new PathFinder(WayPoint.WayPointList, false);
cachedDistances.Clear();
}
@@ -192,7 +192,7 @@ namespace Barotrauma
static CachedDistance CalculateNewCachedDistance(Character c)
{
pathFinder ??= new PathFinder(WayPoint.WayPointList, indoorsSteering: false);
pathFinder ??= new PathFinder(WayPoint.WayPointList, false);
var path = pathFinder.FindPath(ConvertUnits.ToSimUnits(c.WorldPosition), ConvertUnits.ToSimUnits(Submarine.MainSub.WorldPosition));
if (path.Unreachable) { return null; }
return new CachedDistance(c.WorldPosition, Submarine.MainSub.WorldPosition, path.TotalLength, Timing.TotalTime + Rand.Range(1.0f, 5.0f));
@@ -1,21 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma.IO
{
static class Validation
{
static readonly string[] unwritableDirs = new string[] { "Content", "Data/ContentPackages" };
private static readonly string[] unwritableDirs = new string[] { "Content", "Data/ContentPackages" };
private static readonly string[] unwritableExtensions = new string[]
{
".pdb", ".com", ".scr", ".dylib", ".so", ".a", ".app", //executables and libraries (.exe and .dll handled separately in CanWrite)
".bat", ".sh", //shell scripts
".json" //deps.json
};
/// <summary>
/// When set to true, the game is allowed to modify the vanilla content in debug builds. Has no effect in non-debug builds.
/// </summary>
public static bool SkipValidationInDebugBuilds;
public static bool CanWrite(string path)
public static bool CanWrite(string path, bool isDirectory)
{
path = System.IO.Path.GetFullPath(path).CleanUpPath();
string extension = System.IO.Path.GetExtension(path).Replace(" ", "");
if (unwritableExtensions.Any(e => e.Equals(extension, StringComparison.OrdinalIgnoreCase)))
{
return false;
}
if (!path.StartsWith(System.IO.Path.GetFullPath("Mods/").CleanUpPath(), StringComparison.OrdinalIgnoreCase)
&& (extension.Equals(".dll", StringComparison.OrdinalIgnoreCase)
|| extension.Equals(".exe", StringComparison.OrdinalIgnoreCase)))
{
return false;
}
foreach (string unwritableDir in unwritableDirs)
{
string dir = System.IO.Path.GetFullPath(unwritableDir).CleanUpPath();
@@ -38,9 +58,9 @@ namespace Barotrauma.IO
{
public static void SaveSafe(this System.Xml.Linq.XDocument doc, string path)
{
if (!Validation.CanWrite(path))
if (!Validation.CanWrite(path, false))
{
DebugConsole.ThrowError($"Cannot save XML document to \"{path}\": modifying the files in the folder is not allowed.");
DebugConsole.ThrowError($"Cannot save XML document to \"{path}\": modifying the files in this folder/with this extension is not allowed.");
return;
}
doc.Save(path);
@@ -48,9 +68,9 @@ namespace Barotrauma.IO
public static void SaveSafe(this System.Xml.Linq.XElement element, string path)
{
if (!Validation.CanWrite(path))
if (!Validation.CanWrite(path, false))
{
DebugConsole.ThrowError($"Cannot save XML element to \"{path}\": modifying the files in the folder is not allowed.");
DebugConsole.ThrowError($"Cannot save XML element to \"{path}\": modifying the files in this folder/with this extension is not allowed.");
return;
}
element.Save(path);
@@ -73,9 +93,9 @@ namespace Barotrauma.IO
public XmlWriter(string path, System.Xml.XmlWriterSettings settings)
{
if (!Validation.CanWrite(path))
if (!Validation.CanWrite(path, false))
{
DebugConsole.ThrowError($"Cannot write XML document to \"{path}\": modifying the files in the folder is not allowed.");
DebugConsole.ThrowError($"Cannot write XML document to \"{path}\": modifying the files in this folder/with this extension is not allowed.");
Writer = null;
return;
}
@@ -228,9 +248,9 @@ namespace Barotrauma.IO
public static System.IO.DirectoryInfo CreateDirectory(string path)
{
if (!Validation.CanWrite(path))
if (!Validation.CanWrite(path, true))
{
DebugConsole.ThrowError($"Cannot create directory \"{path}\": modifying the contents of the folder is not allowed.");
DebugConsole.ThrowError($"Cannot create directory \"{path}\": modifying the contents of this folder/using this extension is not allowed.");
return null;
}
return System.IO.Directory.CreateDirectory(path);
@@ -238,9 +258,9 @@ namespace Barotrauma.IO
public static void Delete(string path, bool recursive=true)
{
if (!Validation.CanWrite(path))
if (!Validation.CanWrite(path, true))
{
DebugConsole.ThrowError($"Cannot delete directory \"{path}\": modifying the contents of the folder is not allowed.");
DebugConsole.ThrowError($"Cannot delete directory \"{path}\": modifying the contents of this folder/using this extension is not allowed.");
return;
}
//TODO: validate recursion?
@@ -257,9 +277,9 @@ namespace Barotrauma.IO
public static void Copy(string src, string dest, bool overwrite=false)
{
if (!Validation.CanWrite(dest))
if (!Validation.CanWrite(dest, false))
{
DebugConsole.ThrowError($"Cannot copy \"{src}\" to \"{dest}\": modifying the contents of the folder is not allowed.");
DebugConsole.ThrowError($"Cannot copy \"{src}\" to \"{dest}\": modifying the contents of this folder/using this extension is not allowed.");
return;
}
System.IO.File.Copy(src, dest, overwrite);
@@ -267,12 +287,12 @@ namespace Barotrauma.IO
public static void Move(string src, string dest)
{
if (!Validation.CanWrite(src))
if (!Validation.CanWrite(src, false))
{
DebugConsole.ThrowError($"Cannot move \"{src}\" to \"{dest}\": modifying the contents of the source folder is not allowed.");
return;
}
if (!Validation.CanWrite(dest))
if (!Validation.CanWrite(dest, false))
{
DebugConsole.ThrowError($"Cannot move \"{src}\" to \"{dest}\": modifying the contents of the destination folder is not allowed");
return;
@@ -282,9 +302,9 @@ namespace Barotrauma.IO
public static void Delete(string path)
{
if (!Validation.CanWrite(path))
if (!Validation.CanWrite(path, false))
{
DebugConsole.ThrowError($"Cannot delete file \"{path}\": modifying the contents of the folder is not allowed.");
DebugConsole.ThrowError($"Cannot delete file \"{path}\": modifying the contents of this folder/using this extension is not allowed.");
return;
}
System.IO.File.Delete(path);
@@ -304,15 +324,15 @@ namespace Barotrauma.IO
case System.IO.FileMode.OpenOrCreate:
case System.IO.FileMode.Append:
case System.IO.FileMode.Truncate:
if (!Validation.CanWrite(path))
if (!Validation.CanWrite(path, false))
{
DebugConsole.ThrowError($"Cannot open \"{path}\" in {mode} mode: modifying the contents of the folder is not allowed.");
DebugConsole.ThrowError($"Cannot open \"{path}\" in {mode} mode: modifying the contents of this folder/using this extension is not allowed.");
return null;
}
break;
}
return new FileStream(path, System.IO.File.Open(path, mode,
!Validation.CanWrite(path) ?
!Validation.CanWrite(path, false) ?
System.IO.FileAccess.Read :
access));
}
@@ -334,9 +354,9 @@ namespace Barotrauma.IO
public static void WriteAllBytes(string path, byte[] contents)
{
if (!Validation.CanWrite(path))
if (!Validation.CanWrite(path, false))
{
DebugConsole.ThrowError($"Cannot write all bytes to \"{path}\": modifying the files in the folder is not allowed.");
DebugConsole.ThrowError($"Cannot write all bytes to \"{path}\": modifying the files in this folder/with this extension is not allowed.");
return;
}
System.IO.File.WriteAllBytes(path, contents);
@@ -344,9 +364,9 @@ namespace Barotrauma.IO
public static void WriteAllText(string path, string contents, System.Text.Encoding? encoding = null)
{
if (!Validation.CanWrite(path))
if (!Validation.CanWrite(path, false))
{
DebugConsole.ThrowError($"Cannot write all text to \"{path}\": modifying the files in the folder is not allowed.");
DebugConsole.ThrowError($"Cannot write all text to \"{path}\": modifying the files in this folder/with this extension is not allowed.");
return;
}
System.IO.File.WriteAllText(path, contents, encoding ?? System.Text.Encoding.UTF8);
@@ -354,9 +374,9 @@ namespace Barotrauma.IO
public static void WriteAllLines(string path, IEnumerable<string> contents, System.Text.Encoding? encoding = null)
{
if (!Validation.CanWrite(path))
if (!Validation.CanWrite(path, false))
{
DebugConsole.ThrowError($"Cannot write all lines to \"{path}\": modifying the files in the folder is not allowed.");
DebugConsole.ThrowError($"Cannot write all lines to \"{path}\": modifying the files in this folder/with this extension is not allowed.");
return;
}
System.IO.File.WriteAllLines(path, contents, encoding ?? System.Text.Encoding.UTF8);
@@ -396,7 +416,7 @@ namespace Barotrauma.IO
{
get
{
if (!Validation.CanWrite(fileName)) { return false; }
if (!Validation.CanWrite(fileName, false)) { return false; }
return innerStream.CanWrite;
}
}
@@ -422,13 +442,13 @@ namespace Barotrauma.IO
public override void Write(byte[] buffer, int offset, int count)
{
if (Validation.CanWrite(fileName))
if (Validation.CanWrite(fileName, false))
{
innerStream.Write(buffer, offset, count);
}
else
{
DebugConsole.ThrowError($"Cannot write to file \"{fileName}\": modifying the files in the folder is not allowed.");
DebugConsole.ThrowError($"Cannot write to file \"{fileName}\": modifying the files in this folder/with this extension is not allowed.");
}
}
@@ -493,9 +513,9 @@ namespace Barotrauma.IO
public void Delete()
{
if (!Validation.CanWrite(innerInfo.FullName))
if (!Validation.CanWrite(innerInfo.FullName, false))
{
DebugConsole.ThrowError($"Cannot delete directory \"{Name}\": modifying the contents of the folder is not allowed.");
DebugConsole.ThrowError($"Cannot delete directory \"{Name}\": modifying the contents of this folder/using this extension is not allowed.");
return;
}
innerInfo.Delete();
@@ -529,9 +549,9 @@ namespace Barotrauma.IO
}
set
{
if (!Validation.CanWrite(innerInfo.FullName))
if (!Validation.CanWrite(innerInfo.FullName, false))
{
DebugConsole.ThrowError($"Cannot set read-only to {value} for \"{Name}\": modifying the files in the folder is not allowed.");
DebugConsole.ThrowError($"Cannot set read-only to {value} for \"{Name}\": modifying the files in this folder/with this extension is not allowed.");
return;
}
innerInfo.IsReadOnly = value;
@@ -540,7 +560,7 @@ namespace Barotrauma.IO
public void CopyTo(string dest, bool overwriteExisting = false)
{
if (!Validation.CanWrite(dest))
if (!Validation.CanWrite(dest, false))
{
DebugConsole.ThrowError($"Cannot copy \"{Name}\" to \"{dest}\": modifying the contents of the destination folder is not allowed.");
return;
@@ -550,9 +570,9 @@ namespace Barotrauma.IO
public void Delete()
{
if (!Validation.CanWrite(innerInfo.FullName))
if (!Validation.CanWrite(innerInfo.FullName, false))
{
DebugConsole.ThrowError($"Cannot delete file \"{Name}\": modifying the files in the folder is not allowed.");
DebugConsole.ThrowError($"Cannot delete file \"{Name}\": modifying the files in this folder/with this extension is not allowed.");
return;
}
innerInfo.Delete();
@@ -1,4 +1,5 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Barotrauma.IO;
using System.IO.Compression;
@@ -352,8 +353,10 @@ namespace Barotrauma
}
}
public static bool DecompressFile(string sDir, GZipStream zipStream, ProgressDelegate progress)
private static bool DecompressFile(bool writeFile, string sDir, GZipStream zipStream, ProgressDelegate progress, out string fileName)
{
fileName = null;
//Decompress file name
byte[] bytes = new byte[sizeof(int)];
int Readed = zipStream.Read(bytes, 0, sizeof(int));
@@ -375,6 +378,8 @@ namespace Barotrauma
sb.Append(c);
}
string sFileName = sb.ToString();
fileName = sFileName;
progress?.Invoke(sFileName);
//Decompress file content
@@ -387,6 +392,17 @@ namespace Barotrauma
string sFilePath = Path.Combine(sDir, sFileName);
string sFinalDir = Path.GetDirectoryName(sFilePath);
string sDirFull = (string.IsNullOrEmpty(sDir) ? Directory.GetCurrentDirectory() : Path.GetFullPath(sDir)).CleanUpPathCrossPlatform(correctFilenameCase: false);
string sFinalDirFull = (string.IsNullOrEmpty(sFinalDir) ? Directory.GetCurrentDirectory() : Path.GetFullPath(sFinalDir)).CleanUpPathCrossPlatform(correctFilenameCase: false);
if (!sFinalDirFull.StartsWith(sDirFull, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
$"Error extracting \"{sFileName}\": cannot be extracted to parent directory");
}
if (!writeFile) { return true; }
if (!Directory.Exists(sFinalDir))
Directory.CreateDirectory(sFinalDir);
@@ -421,7 +437,7 @@ namespace Barotrauma
{
using (FileStream inFile = File.Open(sCompressedFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
using (GZipStream zipStream = new GZipStream(inFile, CompressionMode.Decompress, true))
while (DecompressFile(sDir, zipStream, progress)) { };
while (DecompressFile(true, sDir, zipStream, progress, out _)) { };
break;
}
@@ -434,6 +450,35 @@ namespace Barotrauma
}
}
public static IEnumerable<string> EnumerateContainedFiles(string sCompressedFile)
{
int maxRetries = 4;
HashSet<string> paths = new HashSet<string>();
for (int i = 0; i <= maxRetries; i++)
{
try
{
using FileStream inFile = File.Open(sCompressedFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
using GZipStream zipStream = new GZipStream(inFile, CompressionMode.Decompress, true);
while (DecompressFile(false, "", zipStream, null, out string fileName))
{
paths.Add(fileName);
}
}
catch (System.IO.IOException e)
{
if (i >= maxRetries || !File.Exists(sCompressedFile)) { throw; }
DebugConsole.NewMessage(
$"Failed to decompress file \"{sCompressedFile}\" for enumeration {{{e.Message}}}, retrying in 250 ms...",
Color.Red);
Thread.Sleep(250);
}
}
return paths;
}
public static void CopyFolder(string sourceDirName, string destDirName, bool copySubDirs, bool overwriteExisting = false)
{
// Get the subdirectories for the specified directory.