Merge branch 'heads/upstream' into OBT/1.2.0(SpringUpdate)

This commit is contained in:
NotAlwaysTrue
2026-04-25 13:08:16 +08:00
420 changed files with 24089 additions and 11191 deletions
@@ -49,6 +49,13 @@ namespace Barotrauma
}
}
/// <summary>
/// A multiplier for the sound range for the purposes of displaying the target on sonar.
/// E.g. a value of 10 would mean the sonar can detect the target from x10 further than monsters.
/// </summary>
public float SoundRangeOnSonarMultiplier { get; private set; } = 1.0f;
public float SightRange
{
get { return sightRange; }
@@ -206,6 +213,7 @@ namespace Barotrauma
MinSoundRange = element.GetAttributeFloat("minsoundrange", 0f);
MaxSightRange = element.GetAttributeFloat("maxsightrange", SightRange);
MaxSoundRange = element.GetAttributeFloat("maxsoundrange", SoundRange);
SoundRangeOnSonarMultiplier = element.GetAttributeFloat(nameof(SoundRangeOnSonarMultiplier), 1.0f);
FadeOutTime = element.GetAttributeFloat("fadeouttime", FadeOutTime);
Static = element.GetAttributeBool("static", Static);
StaticSight = element.GetAttributeBool("staticsight", StaticSight);
@@ -242,16 +242,44 @@ namespace Barotrauma
}
/// <summary>
/// The monster won't try to damage these submarines
/// The monster won't try to damage these submarines. Applies to hulls, structures and static items (items without a physics body) belonging to these submarines. Does not apply to non-static items, e.g. flares or other provocative items.
/// </summary>
public HashSet<Submarine> UnattackableSubmarines
private readonly HashSet<Submarine> unattackableSubmarines = [];
/// <summary>
/// Set the submarine(s) the monster won't attack. Applies to hulls, structures and static items (items without a physics body) belonging to these submarines. Does not apply to non-static items, e.g. flares or other provocative items.
/// </summary>
public void SetUnattackableSubmarines(Submarine submarine, bool includeOwnSub = true, bool includeConnectedSubs = true, bool clearExisting = true)
{
get;
private set;
} = new HashSet<Submarine>();
if (clearExisting)
{
unattackableSubmarines.Clear();
}
if (submarine != null)
{
AddSubs(submarine);
}
if (includeOwnSub && Character.Submarine is Submarine ownSub && ownSub != submarine)
{
AddSubs(ownSub);
}
void AddSubs(Submarine sub)
{
unattackableSubmarines.Add(sub);
if (includeConnectedSubs)
{
foreach (Submarine connectedSub in sub.DockedTo)
{
unattackableSubmarines.Add(connectedSub);
}
}
}
}
public static bool IsTargetBeingChasedBy(Character target, Character character)
=> character?.AIController is EnemyAIController enemyAI && enemyAI.SelectedAiTarget?.Entity == target && enemyAI.State is AIState.Attack or AIState.Aggressive;
public bool IsBeingChasedBy(Character c) => IsTargetBeingChasedBy(Character, c);
private bool IsBeingChased => IsBeingChasedBy(SelectedAiTarget?.Entity as Character);
@@ -539,26 +567,7 @@ namespace Barotrauma
//doesn't do anything usually, but events may sometimes change monsters' (or pets' that use enemy AI) teams
Character.UpdateTeam();
bool ignorePlatforms = Character.AnimController.TargetMovement.Y < -0.5f && (-Character.AnimController.TargetMovement.Y > Math.Abs(Character.AnimController.TargetMovement.X));
if (steeringManager == insideSteering)
{
var currPath = PathSteering.CurrentPath;
if (currPath != null && currPath.CurrentNode != null)
{
if (currPath.CurrentNode.SimPosition.Y < Character.AnimController.GetColliderBottom().Y)
{
// Don't allow to jump from too high.
float allowedJumpHeight = Character.AnimController.ImpactTolerance / 2;
float height = Math.Abs(currPath.CurrentNode.SimPosition.Y - Character.SimPosition.Y);
ignorePlatforms = height < allowedJumpHeight;
}
}
if (Character.IsClimbing && PathSteering.IsNextLadderSameAsCurrent)
{
Character.AnimController.TargetMovement = new Vector2(0.0f, Math.Sign(Character.AnimController.TargetMovement.Y));
}
}
Character.AnimController.IgnorePlatforms = ignorePlatforms;
HandleLaddersAndPlatforms(deltaTime);
if (Math.Abs(Character.AnimController.movement.X) > 0.1f && !Character.AnimController.InWater &&
(GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer || Character.Controlled == Character))
@@ -986,6 +995,69 @@ namespace Barotrauma
}
}
//how often the character can try ragdolling to drop down
private const float MaxDroppingInterval = 5.0f;
//last time the character tried ragdolling to drop down
private double lastDroppingTime;
//how long the character can stay ragdolled to drop down
private const float MaxDroppingTime = 1.0f;
//timer for the duration of the ragdolling
private float droppingTimer;
private void HandleLaddersAndPlatforms(float deltaTime)
{
bool ignorePlatforms = Character.AnimController.TargetMovement.Y < -0.5f && (-Character.AnimController.TargetMovement.Y > Math.Abs(Character.AnimController.TargetMovement.X));
if (steeringManager == insideSteering)
{
var currPath = PathSteering.CurrentPath;
if (currPath is { CurrentNode: WayPoint currentNode })
{
Vector2 colliderBottom = Character.AnimController.GetColliderBottom();
if (Character.Submarine != currentNode.Submarine)
{
colliderBottom = Submarine.GetRelativeSimPosition(colliderBottom, currentNode.Submarine, Character.Submarine);
}
if (currentNode.SimPosition.Y < colliderBottom.Y)
{
// Don't allow to jump from too high.
float allowedJumpHeight = Character.AnimController.ImpactTolerance / 2;
Vector2 diff = currentNode.WorldPosition - Character.WorldPosition;
float height = ConvertUnits.ToSimUnits(Math.Abs(diff.Y));
ignorePlatforms = height < allowedJumpHeight;
//trying to head down ladders, but can't climb -> periodically try ragdolling to get down
//(may be required by large monsters like mudraptors to fit through hatches)
if (ignorePlatforms && !Character.CanClimb && PathSteering.IsCurrentNodeLadder &&
ConvertUnits.ToSimUnits(Math.Abs(diff.X)) < Character.AnimController.Collider.GetMaxExtent())
{
if (lastDroppingTime < Timing.TotalTime - MaxDroppingInterval)
{
Character.IsRagdolled = true;
Character.SetInput(InputType.Ragdoll, hit: false, held: true);
droppingTimer += deltaTime;
if (droppingTimer > MaxDroppingTime)
{
lastDroppingTime = Timing.TotalTime;
}
}
else
{
droppingTimer = 0.0f;
}
}
}
}
if (Character.IsClimbing && PathSteering.IsNextLadderSameAsCurrent)
{
Character.AnimController.TargetMovement = new Vector2(0.0f, Math.Sign(Character.AnimController.TargetMovement.Y));
}
}
Character.AnimController.IgnorePlatforms = ignorePlatforms;
}
#region Idle
private void UpdateIdle(float deltaTime, bool followLastTarget = true)
@@ -1229,6 +1301,8 @@ namespace Barotrauma
return;
}
if (Character.IsAttachedToController()) { return; }
attackWorldPos = SelectedAiTarget.WorldPosition;
attackSimPos = SelectedAiTarget.SimPosition;
@@ -1751,6 +1825,7 @@ namespace Barotrauma
{
SelectTarget(door.Item.AiTarget, currentTargetMemory.Priority);
State = AIState.Attack;
AttackLimb = null;
return;
}
}
@@ -1761,12 +1836,20 @@ namespace Barotrauma
float margin = AttackLimb != null ? Math.Min(AttackLimb.attack.Range * 0.9f, max) : max;
if ((!canAttack || distance > margin) && !IsTryingToSteerThroughGap)
{
bool useManualSteering = false;
// Steer towards the target if in the same room and swimming
// Ruins have walls/pillars inside hulls and therefore we should navigate around them using the path steering.
if (Character.CurrentHull != null &&
Character.Submarine != null && !Character.Submarine.Info.IsRuin &&
(Character.AnimController.InWater || pursue || !Character.AnimController.CanWalk) &&
targetCharacter != null && VisibleHulls.Contains(targetCharacter.CurrentHull))
{
if (CanSeeTarget(targetCharacter))
{
useManualSteering = true;
}
}
if (useManualSteering)
{
Vector2 myPos = Character.AnimController.SimplePhysicsEnabled ? Character.SimPosition : steeringLimb.SimPosition;
SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(attackSimPos - myPos));
@@ -2311,18 +2394,49 @@ namespace Barotrauma
{
float prio = 1 + limb.attack.Priority;
if (Character.AnimController.SimplePhysicsEnabled) { return prio; }
float dist = Vector2.Distance(limb.WorldPosition, attackPos);
float distanceFactor = 1;
float distance = Vector2.Distance(limb.WorldPosition, attackPos);
float maxDistance = Math.Max(limb.attack.Range * 3, 1000);
if (distance > maxDistance)
{
// Far enough to ignore the attack.
return 0;
}
// Not in range, but relatively close. Let's use the distance factor as a multiplier.
float distanceFactor;
if (limb.attack.Ranged)
{
float min = 100;
distanceFactor = MathHelper.Lerp(1, 0, MathUtils.InverseLerp(min, Math.Max(limb.attack.Range / 2, min), dist));
if (distance < min)
{
// Too close -> smoothly but steeply reduce the preference (and prefer other attacks, like melee instead)
float t = MathUtils.InverseLerp(0, min, distance);
distanceFactor = MathHelper.Lerp(0.01f, 1, t * t);
}
else
{
distanceFactor = MathHelper.Lerp(1, 0, MathUtils.InverseLerp(min, maxDistance, distance));
}
}
else
{
// The limb is ignored if the target is not close. Prevents character going in reverse if very far away from it.
// We also need a max value that is more than the actual range.
distanceFactor = MathHelper.Lerp(1, 0, MathUtils.InverseLerp(0, limb.attack.Range * 3, dist));
if (distance <= limb.attack.Range)
{
// In range.
if (!Character.InWater)
{
// On dry land vertical distance works a bit differently, as we can't necessarily reach the target above/below us.
float verticalDistance = Math.Abs(limb.WorldPosition.Y - attackPos.Y);
if (verticalDistance > limb.attack.DamageRange)
{
// Most likely can't reach.
return 0;
}
}
// Highly prefer attacks which we can use to hit immediately.
return prio * 10;
}
float min = limb.attack.Range;
distanceFactor = MathHelper.Lerp(1, 0, MathUtils.InverseLerp(min, maxDistance, distance));
}
return prio * distanceFactor;
}
@@ -2521,6 +2635,7 @@ namespace Barotrauma
{
SelectTarget(aiTarget, GetTargetMemory(SelectedAiTarget, addIfNotFound: true).Priority);
State = AIState.Attack;
AttackLimb = null;
return true;
}
}
@@ -2555,14 +2670,10 @@ namespace Barotrauma
return true;
}
}
if (damageTarget != null)
{
Character.SetInput(item.IsShootable ? InputType.Shoot : InputType.Use, false, true);
item.Use(deltaTime, user: Character);
}
Character.SetInput(item.IsShootable ? InputType.Shoot : InputType.Use, false, true);
item.Use(deltaTime, user: Character);
}
}
if (damageTarget == null) { return true; }
//simulate attack input to get the character to attack client-side
Character.SetInput(InputType.Attack, true, true);
if (!ActiveAttack.IsRunning)
@@ -2609,10 +2720,24 @@ namespace Barotrauma
}
return true;
}
private const float VisibilityCheckStep = 0.2f;
private double lastVisibilityCheckTime;
private bool canSeeTarget;
/// <summary>
/// This method uses <see cref="Character.CanSeeTarget"/> and caches the results.
/// </summary>
private bool CanSeeTarget(ISpatialEntity target)
{
if (Timing.TotalTime > lastVisibilityCheckTime + VisibilityCheckStep)
{
canSeeTarget = Character.CanSeeTarget(target);
lastVisibilityCheckTime = Timing.TotalTime;
}
return canSeeTarget;
}
private float aimTimer;
private float visibilityCheckTimer;
private bool canSeeTarget;
private float sinTime;
private bool Aim(float deltaTime, ISpatialEntity target, Item weapon)
{
@@ -2630,13 +2755,7 @@ namespace Barotrauma
{
Character.CursorPosition -= Character.Submarine.Position;
}
visibilityCheckTimer -= deltaTime;
if (visibilityCheckTimer <= 0.0f)
{
canSeeTarget = Character.CanSeeTarget(target);
visibilityCheckTimer = 0.2f;
}
if (!canSeeTarget)
if (!CanSeeTarget(target))
{
SetAimTimer();
return false;
@@ -2817,7 +2936,10 @@ namespace Barotrauma
}
}
steeringManager.SteeringManual(deltaTime, Vector2.Normalize(limbDiff) * 3);
Character.AnimController.Collider.ApplyForce(limbDiff * mouthLimb.Mass * 50.0f, mouthPos);
if (Character.AnimController.OnGround || Character.InWater)
{
Character.AnimController.Collider.ApplyForce(limbDiff * mouthLimb.Mass * 50.0f, maxVelocity: 10.0f);
}
}
}
else
@@ -2956,12 +3078,18 @@ namespace Barotrauma
}
else
{
// Ignore all structures, items, and hulls inside these subs.
if (aiTarget.Entity.Submarine != null)
if (aiTarget.Entity.Submarine != null)
{
//ignore all items, structures and hulls in wrecks and beacon stations
//(we don't want monsters to be distracted by them during missions,
//nor have monsters inside them attack "their home" rather than the player)
if (aiTarget.Entity.Submarine.Info.IsWreck ||
aiTarget.Entity.Submarine.Info.IsBeacon ||
UnattackableSubmarines.Contains(aiTarget.Entity.Submarine))
aiTarget.Entity.Submarine.Info.IsBeacon)
{
continue;
}
if (aiTarget.Entity is Structure or Hull or Item { body: null } &&
unattackableSubmarines.Contains(aiTarget.Entity.Submarine))
{
continue;
}
@@ -3509,13 +3637,16 @@ namespace Barotrauma
{
if (targetCharacter.Submarine != null)
{
// Target is inside -> reduce the priority
valueModifier *= 0.5f;
if (Character.Submarine != null)
if (Character.Submarine != null && !targetCharacter.Submarine.IsConnectedTo(Character.Submarine))
{
// Both inside different submarines -> can ignore safely
// Both inside different, unconnected submarines -> can ignore safely
continue;
}
else
{
// Target is inside a submarine that we are not -> reduce the priority
valueModifier *= 0.5f;
}
}
else if (Character.CurrentHull != null)
{
@@ -4402,6 +4533,7 @@ namespace Barotrauma
{
SelectTarget(doorAiTarget, CurrentTargetMemory.Priority);
State = AIState.Attack;
AttackLimb = null;
return false;
}
}
@@ -1380,7 +1380,7 @@ namespace Barotrauma
}
else
{
isAttackerInfected = attacker.CharacterHealth.GetAfflictionStrengthByType(AfflictionPrefab.AlienInfectedType) > 0;
isAttackerInfected = attacker.CharacterHealth.GetAfflictionStrengthByType(AfflictionPrefab.AlienInfectionType) > 0;
// Inform other NPCs
if (isAttackerInfected || cumulativeDamage > minorDamageThreshold || totalDamage > minorDamageThreshold)
{
@@ -4,6 +4,7 @@ using Microsoft.Xna.Framework;
using System;
using System.Linq;
using FarseerPhysics;
using System.Diagnostics;
namespace Barotrauma
{
@@ -50,7 +51,7 @@ namespace Barotrauma
}
/// <summary>
/// Returns true if any node in the path is in stairs
/// Returns true if any node in the path is on stairs
/// </summary>
public bool PathHasStairs => currentPath != null && currentPath.Nodes.Any(n => n.Stairs != null);
@@ -285,14 +286,17 @@ namespace Barotrauma
}
}
Vector2 diff = DiffToCurrentNode();
Vector2 diff = GetDiffAndAdvance();
if (diff == Vector2.Zero) { return Vector2.Zero; }
return Vector2.Normalize(diff) * weight;
}
protected override Vector2 DoSteeringSeek(Vector2 target, float weight) => CalculateSteeringSeek(target, weight);
private Vector2 DiffToCurrentNode()
/// <summary>
/// Decides whether and when we should skip to the next node. Returns the difference to the current node (after skipping).
/// </summary>
private Vector2 GetDiffAndAdvance()
{
if (currentPath == null || currentPath.Unreachable)
{
@@ -320,26 +324,37 @@ namespace Barotrauma
Reset();
return Vector2.Zero;
}
Vector2 pos = host.WorldPosition;
Vector2 diff = currentPath.CurrentNode.WorldPosition - pos;
WayPoint currentNode = currentPath.CurrentNode;
WayPoint nextNode = currentPath.NextNode;
Vector2 diff = currentNode.WorldPosition - host.WorldPosition;
float horizontalDistance = Math.Abs(diff.X);
float verticalDistance = Math.Abs(diff.Y);
bool isDiving = character.AnimController.InWater && character.AnimController.HeadInWater;
bool canClimb = character.CanClimb;
Ladder currentLadder = GetCurrentLadder();
Ladder nextLadder = GetNextLadder();
var ladders = currentLadder ?? nextLadder;
Ladder ladders = currentLadder ?? nextLadder;
bool useLadders = canClimb && ladders != null;
var collider = character.AnimController.Collider;
Vector2 colliderSize = collider.GetSize();
Vector2 colliderSize = ConvertUnits.ToDisplayUnits(collider.GetSize());
float colliderHeight = colliderSize.Y;
if (character.AnimController.CurrentAnimationParams is FishGroundedParams fishGrounded)
{
// On monsters, the main collider might be rotated, so we need to take that into account here.
float standAngle = fishGrounded.ColliderStandAngleInRadians * character.AnimController.Dir;
Vector2 transformedColliderSize = PhysicsBody.RotateVector(colliderSize, standAngle);
colliderHeight = Math.Abs(transformedColliderSize.Y);
}
if (useLadders)
{
if (character.IsClimbing && Math.Abs(diff.X) - ConvertUnits.ToDisplayUnits(colliderSize.X) > Math.Abs(diff.Y))
if (character.IsClimbing && Math.Abs(diff.X) - colliderSize.X > Math.Abs(diff.Y))
{
// If the current node is horizontally farther from us than vertically, we don't want to keep climbing the ladders.
useLadders = false;
}
else if (!character.IsClimbing && currentPath.NextNode != null && nextLadder == null)
else if (!character.IsClimbing && nextNode != null && nextLadder == null)
{
Vector2 diffToNextNode = currentPath.NextNode.WorldPosition - pos;
Vector2 diffToNextNode = nextNode.WorldPosition - host.WorldPosition;
if (Math.Abs(diffToNextNode.X) > Math.Abs(diffToNextNode.Y))
{
// If the next node is horizontally farther from us than vertically, we don't want to start climbing.
@@ -356,7 +371,7 @@ namespace Barotrauma
{
if (currentPath.IsAtEndNode && canClimb && ladders != null)
{
// Don't release the ladders when ending a path in ladders.
// Don't release the ladders when ending a path on ladders.
useLadders = true;
}
else
@@ -388,20 +403,18 @@ namespace Barotrauma
if (currentLadder == null && nextLadder != null && character.SelectedSecondaryItem == nextLadder.Item)
{
// Climbing a ladder but the path is still on the node next to the ladder -> Skip the node.
NextNode(!doorsChecked);
return NextNode(!doorsChecked);
}
else
{
bool nextLadderSameAsCurrent = currentLadder == nextLadder;
float colliderHeight = collider.Height / 2 + collider.Radius;
float heightDiff = currentPath.CurrentNode.SimPosition.Y - collider.SimPosition.Y;
float distanceMargin = ConvertUnits.ToDisplayUnits(colliderSize.X);
float distanceMargin = colliderSize.X;
if (currentLadder != null && nextLadder != null)
{
//climbing ladders -> don't move horizontally
diff.X = 0.0f;
}
if (Math.Abs(heightDiff) < colliderHeight * 1.25f)
if (verticalDistance < colliderHeight / 2 * 1.25f)
{
if (nextLadder != null && !nextLadderSameAsCurrent)
{
@@ -410,7 +423,7 @@ namespace Barotrauma
{
if (nextLadder.Item.TryInteract(character, forceSelectKey: true))
{
NextNode(!doorsChecked);
return NextNode(!doorsChecked);
}
}
}
@@ -432,9 +445,9 @@ namespace Barotrauma
}
if (isAboveFloor)
{
if (Math.Abs(diff.Y) < distanceMargin)
if (verticalDistance < distanceMargin)
{
NextNode(!doorsChecked);
return NextNode(!doorsChecked);
}
else if (!currentPath.IsAtEndNode && (nextLadder == null || (currentLadder != null && Math.Abs(currentLadder.Item.WorldPosition.X - nextLadder.Item.WorldPosition.X) > distanceMargin)))
{
@@ -443,14 +456,21 @@ namespace Barotrauma
}
}
}
else if (currentLadder != null && currentPath.NextNode != null)
else if (currentLadder != null && nextNode != null)
{
if (Math.Sign(currentPath.CurrentNode.WorldPosition.Y - character.WorldPosition.Y) != Math.Sign(currentPath.NextNode.WorldPosition.Y - character.WorldPosition.Y))
if (Math.Sign(currentNode.WorldPosition.Y - character.WorldPosition.Y) != Math.Sign(nextNode.WorldPosition.Y - character.WorldPosition.Y))
{
//if the current node is below the character and the next one is above (or vice versa)
//and both are on ladders, we can skip directly to the next one
//e.g. no point in going down to reach the starting point of a path when we could go directly to the one above
NextNode(!doorsChecked);
return NextNode(!doorsChecked);
}
//heading towards a ladder waypoint below the character, but the next waypoint is above it on the same ladder
// -> allow skipping to that waypoint.
// Otherwise the character may get stuck trying to move to a waypoint near the floor at the bottom of the ladder, failing to get close enough because they can't move any lower.
else if (nextLadderSameAsCurrent && diff.Y < 0 && nextNode.WorldPosition.Y > currentNode.WorldPosition.Y)
{
return NextNode(!doorsChecked);
}
}
}
@@ -458,21 +478,20 @@ namespace Barotrauma
else if (character.AnimController.InWater)
{
// Swimming
var door = currentPath.CurrentNode.ConnectedDoor;
var door = currentNode.ConnectedDoor;
if (door == null || door.CanBeTraversed)
{
float margin = MathHelper.Lerp(1, 5, MathHelper.Clamp(collider.LinearVelocity.Length() / 10, 0, 1));
float targetDistance = Math.Max(Math.Max(colliderSize.X, colliderSize.Y) / 2 * margin, 0.5f);
float horizontalDistance = Math.Abs(character.WorldPosition.X - currentPath.CurrentNode.WorldPosition.X);
float verticalDistance = Math.Abs(character.WorldPosition.Y - currentPath.CurrentNode.WorldPosition.Y);
if (character.CurrentHull != currentPath.CurrentNode.CurrentHull)
float distanceMultiplier = MathHelper.Lerp(1, 5, MathHelper.Clamp(collider.LinearVelocity.Length() / 10, 0, 1));
float targetDistance = Math.Max(Math.Max(colliderSize.X, colliderSize.Y) / 2 * distanceMultiplier, 0.5f);
float modifiedVerticalDist = verticalDistance;
if (character.CurrentHull != currentNode.CurrentHull)
{
verticalDistance *= 2;
modifiedVerticalDist *= 2;
}
float distance = horizontalDistance + verticalDistance;
if (ConvertUnits.ToSimUnits(distance) < targetDistance)
float distance = horizontalDistance + modifiedVerticalDist;
if (distance < targetDistance)
{
NextNode(!doorsChecked);
return NextNode(!doorsChecked);
}
}
}
@@ -480,6 +499,10 @@ namespace Barotrauma
{
// Walking horizontally
Vector2 colliderBottom = character.AnimController.GetColliderBottom();
if (character.Submarine != currentNode.Submarine)
{
colliderBottom = Submarine.GetRelativeSimPosition(colliderBottom, currentNode.Submarine, character.Submarine);
}
Vector2 velocity = collider.LinearVelocity;
// If the character is very short, it would fail to use the waypoint nodes because they are always too high.
// If the character is very thin, it would often fail to reach the waypoints, because the horizontal distance is too small.
@@ -487,60 +510,113 @@ namespace Barotrauma
float minHeight = 1.6125001f;
float minWidth = 0.3225f;
// Cannot use the head position, because not all characters have head or it can be below the total height of the character
float characterHeight = Math.Max(colliderSize.Y + character.AnimController.ColliderHeightFromFloor, minHeight);
float horizontalDistance = Math.Abs(collider.SimPosition.X - currentPath.CurrentNode.SimPosition.X);
bool isTargetTooHigh = currentPath.CurrentNode.SimPosition.Y > colliderBottom.Y + characterHeight;
bool isTargetTooLow = currentPath.CurrentNode.SimPosition.Y < colliderBottom.Y;
var door = currentPath.CurrentNode.ConnectedDoor;
float margin = MathHelper.Lerp(1, 10, MathHelper.Clamp(Math.Abs(velocity.X) / 5, 0, 1));
float colliderHeight = collider.Height / 2 + collider.Radius;
if (currentPath.CurrentNode.Stairs == null)
float characterHeight = Math.Max(ConvertUnits.ToSimUnits(colliderHeight) + character.AnimController.ColliderHeightFromFloor, minHeight);
bool isTargetTooHigh = currentNode.SimPosition.Y > colliderBottom.Y + characterHeight;
bool isTargetTooLow = currentNode.SimPosition.Y < colliderBottom.Y;
var door = currentNode.ConnectedDoor;
float targetDistanceMultiplier = MathHelper.Lerp(1, 10, MathHelper.Clamp(Math.Abs(velocity.X) / 5, 0, 1));
if (currentNode.Stairs == null)
{
float heightDiff = currentPath.CurrentNode.SimPosition.Y - collider.SimPosition.Y;
if (heightDiff < colliderHeight)
// Only attempt dropping if the node is below the collider bottom.
// Using the next node position here, because the current node might be on the top of the ladder, which can be at the same level with the character or even above it.
bool isBelowEnough = (nextNode ?? currentNode).WorldPosition.Y < character.WorldPosition.Y - colliderHeight / 2;
bool drop = false;
if (isBelowEnough)
{
// Original comment:
//the waypoint is between the top and bottom of the collider, no need to move vertically.
// Note that the waypoint can be below collider too! This might be incorrect.
if (!canClimb)
{
// Can't climb -> check if we should drop.
Door nextDoor = door ?? nextNode?.ConnectedDoor;
if (nextDoor is Door { IsHorizontal: true, CanBeTraversed: true } openHatch)
{
bool isHatchBelowCharacter = openHatch.LinkedGap.WorldPosition.Y < character.WorldPosition.Y;
if (isHatchBelowCharacter)
{
// Trying to go through an open hatch below us -> drop.
drop = true;
}
}
else if (currentLadder != null && !isTargetTooLow && nextDoor == null)
{
// On ladders -> drop.
drop = true;
}
}
}
if (drop)
{
return NextNode(!doorsChecked);
}
else if (verticalDistance < colliderHeight / 2)
{
// The waypoint is between the top and bottom of the collider, and we don't intend to drop -> no need to move vertically.
diff.Y = 0.0f;
}
}
else
{
// In stairs
bool isNextNodeInSameStairs = currentPath.NextNode?.Stairs == currentPath.CurrentNode.Stairs;
// On stairs
bool isNextNodeInSameStairs = nextNode?.Stairs == currentNode.Stairs;
if (!isNextNodeInSameStairs)
{
margin = 1;
if (currentPath.CurrentNode.SimPosition.Y < colliderBottom.Y + character.AnimController.ColliderHeightFromFloor * 0.25f)
targetDistanceMultiplier = 1;
if (currentNode.SimPosition.Y < colliderBottom.Y + character.AnimController.ColliderHeightFromFloor * 0.25f)
{
isTargetTooLow = true;
}
Structure nextStairs = nextNode?.Stairs;
if (character.AnimController.Stairs != null && nextStairs != null)
{
//currently on stairs, and the next node is not in the same stairs
// -> we must get off the current stairs first before we can skip to the next node, otherwise the character
// would attempt to get "through the stairs" to the next ones
if (character.AnimController.Stairs.StairDirection == Direction.Right)
{
//the direction in which the bot should keep moving depends on the direction of the stairs and whether we're going up or down
diff = nextStairs.WorldPosition.Y > character.AnimController.Stairs.WorldPosition.Y ? Vector2.UnitX : -Vector2.UnitX;
}
else
{
diff = nextStairs.WorldPosition.Y > character.AnimController.Stairs.WorldPosition.Y ? -Vector2.UnitX : Vector2.UnitX;
}
}
}
}
float targetDistance = Math.Max(colliderSize.X / 2 * margin, minWidth / 2);
if (horizontalDistance < targetDistance && !isTargetTooHigh && !isTargetTooLow)
// Walking horizontally, check whether we are close enough to the current node.
float targetDistance = Math.Max(colliderSize.X / 2 * targetDistanceMultiplier, ConvertUnits.ToDisplayUnits(minWidth / 2));
Debug.Assert(targetDistance < 500, "Target distance too large (a character is trying to skip on their path to a waypoint far away), something is probably off here.");
if (!isTargetTooHigh && !isTargetTooLow && horizontalDistance < targetDistance)
{
if (door is not { CanBeTraversed: false } && (currentLadder == null || nextLadder == null))
bool isBlockedByDoor = door is { CanBeTraversed: false };
// If both the current ladder and the next ladder are not null, we are in the middle of ladders and should let the code above handle advancing the nodes.
// However, if either one is null, and we get here, we are probably walking to or from ladders.
bool notOnLadders = currentLadder == null || nextLadder == null;
if (!isBlockedByDoor && notOnLadders)
{
NextNode(!doorsChecked);
return NextNode(!doorsChecked);
}
}
}
if (currentPath.CurrentNode == null)
return ReturnDiff();
Vector2 NextNode(bool checkDoors)
{
return Vector2.Zero;
if (checkDoors)
{
CheckDoorsInPath();
}
currentPath.SkipToNextNode();
return ReturnDiff();
}
return ConvertUnits.ToSimUnits(diff);
}
private void NextNode(bool checkDoors)
{
if (checkDoors)
Vector2 ReturnDiff()
{
CheckDoorsInPath();
if (currentPath.CurrentNode == null)
{
return Vector2.Zero;
}
return ConvertUnits.ToSimUnits(diff);
}
currentPath.SkipToNextNode();
}
public bool CanAccessDoor(Door door, Func<Controller, bool> buttonFilter = null)
@@ -600,8 +676,6 @@ namespace Barotrauma
}
}
private Vector2 GetColliderSize() => ConvertUnits.ToDisplayUnits(character.AnimController.Collider.GetSize());
private float GetColliderLength()
{
Vector2 colliderSize = character.AnimController.Collider.GetSize();
@@ -676,7 +750,7 @@ namespace Barotrauma
if (door.LinkedGap.IsHorizontal)
{
int dir = Math.Sign(nextWaypoint.WorldPosition.X - door.Item.WorldPosition.X);
float size = character.AnimController.InWater ? colliderLength : GetColliderSize().X;
float size = character.AnimController.InWater ? colliderLength : ConvertUnits.ToDisplayUnits(character.AnimController.Collider.GetSize()).X;
shouldBeOpen = (door.Item.WorldPosition.X - character.WorldPosition.X) * dir > -size;
}
else
@@ -794,12 +868,17 @@ namespace Barotrauma
if (character == null) { return 0.0f; }
float? penalty = GetSingleNodePenalty(nextNode);
if (penalty == null) { return null; }
Vector2 nextNodePosition = nextNode.Position;
if (nextNode.Waypoint.Submarine != node.Waypoint.Submarine)
{
nextNodePosition = Submarine.GetRelativeSimPosition(nextNodePosition, node.Waypoint.Submarine, nextNode.Waypoint.Submarine);
}
bool nextNodeAboveWaterLevel = nextNode.Waypoint.CurrentHull != null && nextNode.Waypoint.CurrentHull.Surface < nextNode.Waypoint.Position.Y;
if (!character.CanClimb && node.Waypoint.Stairs == null && nextNode.Waypoint.Stairs == null)
{
if (node.Waypoint.Ladders != null && nextNode.Waypoint.Ladders != null && (!nextNode.Waypoint.Ladders.Item.IsInteractable(character) || character.LockHands) ||
(nextNode.Position.Y - node.Position.Y > 1.0f && //more than one sim unit to climb up
nextNodeAboveWaterLevel)) //upper node not underwater
(nextNodePosition.Y - node.Position.Y > 1.0f && //more than one sim unit to climb up
nextNodeAboveWaterLevel)) //upper node not underwater
{
return null;
}
@@ -830,7 +909,7 @@ namespace Barotrauma
}
}
float yDist = Math.Abs(node.Position.Y - nextNode.Position.Y);
float yDist = Math.Abs(node.Position.Y - nextNodePosition.Y);
if (nextNodeAboveWaterLevel && node.Waypoint.Ladders == null && nextNode.Waypoint.Ladders == null && node.Waypoint.Stairs == null && nextNode.Waypoint.Stairs == null)
{
penalty += yDist * 10.0f;
@@ -898,18 +977,14 @@ namespace Barotrauma
//steer away from edges of the hull
bool wander = false;
bool inWater = character.AnimController.InWater;
Hull currentHull = character.CurrentHull;
// TODO: disabled for now, because seems to cause bots to walk towards walls/doors in some places. In some places it's because how the hulls are defined, but there is probably something else too, is it seems to happen also elsewhere.
// if (!inWater)
// {
// Vector2 colliderBottomPos = ConvertUnits.ToDisplayUnits(character.AnimController.GetColliderBottom());
// if (Hull.FindHull(colliderBottomPos, guess: currentHull, useWorldCoordinates: false) is Hull lowestHull)
// {
// // Use the hull found at the collider bottom, if found.
// // Makes difference in some rooms that have multiple hulls, of which the lowest hull where the feet are might not be the same as where the center position of the main collider is.
// currentHull = lowestHull;
// }
// }
//use the hull the legs are in (if one is found), so the character won't walk against the wall when their torso is in a different hull where there'd be room to walk further
//(e.g. if the character is in a shallow pool-type room, like in ResearchModule_01_Colony)
Hull currentHull =
character.AnimController.GetLimb(LimbType.RightLeg)?.Hull ??
character.AnimController.GetLimb(LimbType.LeftLeg)?.Hull ??
character.CurrentHull;
if (currentHull != null && !inWater)
{
float roomWidth = currentHull.Rect.Width;
@@ -103,9 +103,19 @@ namespace Barotrauma
}
}
// For temporarily forcing walking. Will reset after each priority calculation, so it will need to be kept alive by something.
// The intention of this boolean to allow walking even when the priority is higher than AIObjectiveManager.RunPriority.
public bool ForceWalk { get; set; }
/// <summary>
/// For temporarily forcing walking. Will reset after each priority calculation, so it will need to be kept alive by something.
/// The intention of this boolean to allow walking even when the priority is higher than AIObjectiveManager.RunPriority.
/// </summary>
public bool ForceWalkTemporarily { get; set; }
/// <summary>
/// Forces the character to walk when executing this objective, even if the priority is above <see cref="AIObjectiveManager.RunPriority"/>.
/// Unlike <see cref="ForceWalkTemporarily"/>, this value is not automatically reset.
/// </summary>
public bool ForceWalkPermanently { get; set; }
public bool ForceWalk => ForceWalkTemporarily || ForceWalkPermanently;
public bool IgnoreAtOutpost { get; set; }
@@ -313,7 +323,7 @@ namespace Barotrauma
/// </summary>
public float CalculatePriority()
{
ForceWalk = false;
ForceWalkTemporarily = false;
Priority = GetPriority();
ForceHighestPriority = false;
return Priority;
@@ -40,7 +40,7 @@ namespace Barotrauma
if (subObjectives.All(so => so.SubObjectives.None()))
{
// If none of the subobjectives have subobjectives, no valid container was found. Don't allow running.
ForceWalk = true;
ForceWalkTemporarily = true;
}
return prio;
}
@@ -258,13 +258,14 @@ namespace Barotrauma
protected override bool CheckObjectiveState()
{
if (character.Submarine is { TeamID: CharacterTeamType.FriendlyNPC } && character.Submarine == Enemy.Submarine)
// In a friendly outpost, and the target is still in the outpost
if (character.Submarine is { Info.IsOutpost: true } && character.IsOnFriendlyTeam(character.Submarine.TeamID) &&
character.Submarine == Enemy.Submarine)
{
// Target still in the outpost
// Outpost guards shouldn't lose the target in friendly outposts,
// However, if we are not a guard, let's ensure that we allow the cooldown.
if (character.TeamID == CharacterTeamType.FriendlyNPC && !character.IsSecurity)
{
// Outpost guards shouldn't lose the target in friendly outposts,
// However, if we are not a guard, let's ensure that we allow the cooldown.
allowCooldown = true;
}
}
@@ -286,7 +287,8 @@ namespace Barotrauma
{
allowCooldown = true;
// Target not in the outpost anymore.
if (character.CanSeeTarget(Enemy))
if (character.Submarine.IsConnectedTo(Enemy.Submarine) &&
character.CanSeeTarget(Enemy))
{
allowCooldown = false;
coolDownTimer = DefaultCoolDown;
@@ -389,7 +391,7 @@ namespace Barotrauma
HumanAIController.AutoFaceMovement = false;
if (!gotoObjective.ShouldRun(true))
{
ForceWalk = true;
ForceWalkTemporarily = true;
}
}
}
@@ -468,7 +470,7 @@ namespace Barotrauma
isMoving = true;
if (!IsEnemyClose(MeleeDistance))
{
ForceWalk = true;
ForceWalkTemporarily = true;
}
HumanAIController.FaceTarget(Enemy);
HumanAIController.AutoFaceMovement = false;
@@ -1234,7 +1236,7 @@ namespace Barotrauma
}
if (isAimBlocked)
{
ForceWalk = true;
ForceWalkTemporarily = true;
}
if (!followTargetObjective.IsCloseEnough)
{
@@ -95,7 +95,11 @@ namespace Barotrauma
if (potentialDeconstructor?.InputContainer == null) { continue; }
if (!potentialDeconstructor.InputContainer.Inventory.CanBePut(Item)) { continue; }
if (!potentialDeconstructor.Item.HasAccess(character)) { continue; }
if (Item.Prefab.DeconstructItems.None(it => it.IsValidDeconstructor(otherItem))) { continue; }
if (Item.Prefab.DeconstructItems.Any() &&
Item.Prefab.DeconstructItems.None(it => it.IsValidDeconstructor(otherItem)))
{
continue;
}
float distFactor = GetDistanceFactor(Item.WorldPosition, potentialDeconstructor.Item.WorldPosition, factorAtMaxDistance: 0.2f);
if (distFactor > bestDistFactor)
{
@@ -64,7 +64,11 @@ namespace Barotrauma
if (target == null || target.Removed) { return false; }
//bots can't handle deconstructing items that require another item to deconstruct, let's not try to do that
//in the vanilla game, this means unidentified genetic materials, which we don't want to "deconstruct" anyway
if (target.Prefab.DeconstructItems.All(d => d.RequiredOtherItem.Length > 0)) { return false; }
if (target.Prefab.DeconstructItems.Any() &&
target.Prefab.DeconstructItems.All(d => d.RequiredOtherItem.Length > 0))
{
return false;
}
// If the target was selected as a valid target, we'll have to accept it so that the objective can be completed.
// The validity changes when a character picks the item up.
if (!IsValidTarget(target, character, checkInventory: true))
@@ -148,7 +148,7 @@ namespace Barotrauma
character.Speak(TextManager.GetWithVariable("DialogPutOutFire", "[roomname]", targetHull.DisplayName, FormatCapitals.Yes).Value, null, 0, "putoutfire".ToIdentifier(), 10.0f);
}
// Prevents running into the flames.
objectiveManager.CurrentObjective.ForceWalk = true;
objectiveManager.CurrentObjective.ForceWalkTemporarily = true;
}
if (moveCloser)
{
@@ -11,6 +11,8 @@ namespace Barotrauma
public override Identifier Identifier { get; set; } = "extinguish fires".ToIdentifier();
public override bool ForceRun => true;
protected override bool AllowInAnySub => true;
// Periodically clear the ignore list so that fires abandoned when fumbling with finding an extinguisher, navigating etc get reconsidered
protected override float IgnoreListClearInterval => 30;
public AIObjectiveExtinguishFires(Character character, AIObjectiveManager objectiveManager, float priorityModifier = 1) : base(character, objectiveManager, priorityModifier) { }
@@ -49,6 +49,13 @@ namespace Barotrauma
public const float DefaultReach = 100;
public const float MaxReach = 150;
/// <summary>
/// How long it takes for the objective to be abandoned if no suitable item is found.
/// Intended to be an optimization: if the bots are constantly trying to find some item (like a diving suit),
/// it can easily lead to performance issues when e.g. AIObjectiveFindDivingGear constantly starts up new GetItem objectives.
/// </summary>
private float abandonDelayIfItemNotFound = 5.0f;
/// <summary>
/// Is the goal of this objective to get diving gear (i.e. has it been created by <see cref="AIObjectiveFindDivingGear"/>)?
/// If so, the objective won't attempt to create another objective if the path requires diving gear
@@ -213,7 +220,7 @@ namespace Barotrauma
{
if (isDoneSeeking)
{
HandlePotentialItems();
HandlePotentialItems(deltaTime);
}
if (objectiveManager.CurrentOrder is not AIObjectiveGoTo)
{
@@ -389,6 +396,8 @@ namespace Barotrauma
// If the root container changes, the item is no longer where it was (taken by someone -> need to find another item)
AbortCondition = obj => targetItem == null || (targetItem.GetRootInventoryOwner() is Entity owner && owner != moveToTarget && owner != character),
SpeakIfFails = false,
ForceWalkTemporarily = this.ForceWalkTemporarily,
ForceWalkPermanently = this.ForceWalkPermanently,
endNodeFilter = CreateEndNodeFilter(moveToTarget)
};
},
@@ -598,7 +607,7 @@ namespace Barotrauma
}
}
private void HandlePotentialItems()
private void HandlePotentialItems(float deltaTime)
{
Debug.Assert(isDoneSeeking);
if (itemCandidates.Any())
@@ -652,10 +661,14 @@ namespace Barotrauma
}
else
{
#if DEBUG
DebugConsole.NewMessage($"{character.Name}: Cannot find an item with the following identifier(s) or tag(s): {string.Join(", ", IdentifiersOrTags)}", Color.Yellow);
#endif
Abandon = true;
abandonDelayIfItemNotFound -= deltaTime;
if (abandonDelayIfItemNotFound <= 0.0f)
{
#if DEBUG
DebugConsole.NewMessage($"{character.Name}: Cannot find an item with the following identifier(s) or tag(s): {string.Join(", ", IdentifiersOrTags)}", Color.Yellow);
#endif
Abandon = true;
}
}
}
}
@@ -718,13 +731,15 @@ namespace Barotrauma
private bool CheckItem(Item item)
{
bool matchesIdentifiersOrTags = item.HasIdentifierOrTags(IdentifiersOrTags) || (AllowVariants && !item.Prefab.VariantOf.IsEmpty && IdentifiersOrTags.Contains(item.Prefab.VariantOf));
if (!matchesIdentifiersOrTags) { return false; }
if (!item.HasAccess(character)) { return false; }
if (ignoredItems.Contains(item)) { return false; };
if (ignoredIdentifiersOrTags != null && item.HasIdentifierOrTags(ignoredIdentifiersOrTags)) { return false; }
if (item.Condition < TargetCondition) { return false; }
if (ItemFilter != null && !ItemFilter(item)) { return false; }
if (RequireNonEmpty && item.Components.Any(i => i.IsEmpty(character))) { return false; }
return item.HasIdentifierOrTags(IdentifiersOrTags) || (AllowVariants && !item.Prefab.VariantOf.IsEmpty && IdentifiersOrTags.Contains(item.Prefab.VariantOf));
return true;
}
public override void Reset()
@@ -958,6 +958,7 @@ namespace Barotrauma
public bool ShouldRun(bool run)
{
if (ForceWalk) { return false; }
if (run && objectiveManager.ForcedOrder == this && IsWaitOrder && !character.IsOnPlayerTeam)
{
// NPCs with a wait order don't run.
@@ -267,7 +267,10 @@ namespace Barotrauma
if (node.Waypoint.CurrentHull != character.CurrentHull && HumanAIController.UnsafeHulls.Contains(node.Waypoint.CurrentHull)) { return false; }
return true;
//don't stop at ladders when idling
}, endNodeFilter: node => node.Waypoint.Stairs == null && node.Waypoint.Ladders == null && (!isCurrentHullAllowed || !IsForbidden(node.Waypoint.CurrentHull)));
}, endNodeFilter: node =>
node.Waypoint.Stairs == null && node.Waypoint.CurrentHull == currentTarget && node.Waypoint.Ladders == null &&
(!isCurrentHullAllowed || !IsForbidden(node.Waypoint.CurrentHull)));
if (path.Unreachable)
{
//can't go to this room, remove it from the list and try another room
@@ -78,9 +78,10 @@ namespace Barotrauma
if (item.GetRootInventoryOwner() is Character targetCharacter &&
AIObjectiveFightIntruders.IsValidTarget(targetCharacter, character, targetCharactersInOtherSubs: false))
{
float dist = character.CurrentHull.GetApproximateDistance(character.Position, targetCharacter.Position, targetCharacter.CurrentHull, aiTarget.SoundRange, distanceMultiplierPerClosedDoor: 2);
if (dist * HumanAIController.Hearing > aiTarget.SoundRange) { continue; }
float range = aiTarget.SoundRange * HumanAIController.Hearing;
float dist = character.CurrentHull.GetApproximateDistance(character.Position, targetCharacter.Position, targetCharacter.CurrentHull, range, distanceMultiplierPerClosedDoor: 2);
if (dist > range) { continue; }
character.Speak(TextManager.Get("dialogheardenemy").Value, identifier: "heardenemy".ToIdentifier(), minDurationBetweenSimilar: 30.0f);
if (inspectNoiseObjective != null && subObjectives.Contains(inspectNoiseObjective))
{
@@ -112,7 +112,7 @@ namespace Barotrauma
float prio = objectiveManager.GetOrderPriority(this);
if (subObjectives.All(so => so.SubObjectives.None() || so.Priority <= 0))
{
ForceWalk = true;
ForceWalkTemporarily = true;
}
return prio;
}
@@ -103,10 +103,6 @@ namespace Barotrauma
public void AddObjective<T>(T objective) where T : AIObjective
{
var result = GameMain.LuaCs.Hook.Call<bool?>("AI.addObjective", this, objective);
if (result != null && result.Value) return;
if (objective == null)
{
#if DEBUG
@@ -257,6 +257,7 @@ namespace Barotrauma
{
DialogueIdentifier = AIObjectiveGoTo.DialogCannotReachTarget,
TargetName = target.Item.Name,
ForceWalkPermanently = ForceWalk,
endNodeFilter = EndNodeFilter ?? AIObjectiveGetItem.CreateEndNodeFilter(target.Item)
},
onAbandon: () => Abandon = true,
@@ -29,7 +29,7 @@ namespace Barotrauma
{
if (pump?.Item == null || pump.Item.Removed) { return false; }
if (pump.Item.IgnoreByAI(character)) { return false; }
if (!pump.Item.IsInteractable(character)) { return false; }
if (!pump.Item.IsInteractable(character) || !pump.CanBeSelected) { return false; }
if (pump.IsAutoControlled) { return false; }
if (pump.Item.ConditionPercentage <= 0) { return false; }
if (pump.Item.CurrentHull == null) { return false; }
@@ -136,7 +136,7 @@ namespace Barotrauma
public static bool IsValidTarget(Character target, Character character, out bool ignoredAsMinorWounds)
{
ignoredAsMinorWounds = false;
if (target == null || target.IsDead || target.Removed) { return false; }
if (target == null || target.IsDead || target.Removed || target.InvisibleTimer > 0.0f) { return false; }
if (target.IsInstigator) { return false; }
if (target.IsPet) { return false; }
if (!HumanAIController.IsFriendly(character, target, onlySameTeam: true)) { return false; }
@@ -42,7 +42,9 @@ namespace Barotrauma
{
enemyAi.PetBehavior?.Update(deltaTime);
}
if (IsDead || IsUnconscious || Stun > 0.0f || IsIncapacitated)
if (IsDead || IsUnconscious || IsIncapacitated ||
//only check "real" stuns here, ignoring ragdolling, so the AI can run and decide whether to ragdoll or unragdoll
CharacterHealth.Stun > 0.0f)
{
//don't enable simple physics on dead/incapacitated characters
//the ragdoll controls the movement of incapacitated characters instead of the collider,
@@ -685,7 +685,7 @@ namespace Barotrauma
{
movement = MathUtils.SmoothStep(movement, TargetMovement, 0.2f);
if (Collider.BodyType == BodyType.Dynamic)
if (Collider.BodyType == BodyType.Dynamic && onGround)
{
Collider.LinearVelocity = new Vector2(
movement.X,
@@ -1,5 +1,6 @@
using Barotrauma.Extensions;
using Barotrauma.Items.Components;
using Barotrauma.LuaCs.Events;
using Barotrauma.Networking;
using FarseerPhysics;
using Microsoft.Xna.Framework;
@@ -1305,11 +1306,11 @@ namespace Barotrauma
//increase oxygen and clamp it above zero
// -> the character should be revived if there are no major afflictions in addition to lack of oxygen
target.Oxygen = Math.Max(target.Oxygen + 10.0f, 10.0f);
GameMain.LuaCs.Hook.Call("human.CPRSuccess", this);
LuaCsSetup.Instance.EventService.PublishEvent<IEventHumanCPRSuccess>(x => x.OnCharacterCPRSuccess(this));
}
else
{
GameMain.LuaCs.Hook.Call("human.CPRFailed", this);
LuaCsSetup.Instance.EventService.PublishEvent<IEventHumanCPRFailed>(x => x.OnCharacterCPRFailed(this));
}
}
}
@@ -1,17 +1,18 @@
using Barotrauma.Networking;
using Barotrauma.Extensions;
using Barotrauma.LuaCs.Events;
using Barotrauma.Networking;
using FarseerPhysics;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Contacts;
using FarseerPhysics.Dynamics.Joints;
using Microsoft.Xna.Framework;
using MoonSharp.Interpreter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Barotrauma.Extensions;
using LimbParams = Barotrauma.RagdollParams.LimbParams;
using JointParams = Barotrauma.RagdollParams.JointParams;
using MoonSharp.Interpreter;
using LimbParams = Barotrauma.RagdollParams.LimbParams;
namespace Barotrauma
{
@@ -31,6 +32,7 @@ namespace Barotrauma
{
public Fixture F1, F2;
public Vector2 LocalNormal;
public Vector2 WorldNormal;
public Vector2 Velocity;
public Vector2 ImpactPos;
@@ -40,7 +42,7 @@ namespace Barotrauma
F2 = f2;
Velocity = velocity;
LocalNormal = contact.Manifold.LocalNormal;
contact.GetWorldManifold(out _, out FarseerPhysics.Common.FixedArray2<Vector2> points);
contact.GetWorldManifold(out WorldNormal, out FarseerPhysics.Common.FixedArray2<Vector2> points);
ImpactPos = points[0];
}
}
@@ -827,7 +829,7 @@ namespace Barotrauma
return true;
}
private void ApplyImpact(Fixture f1, Fixture f2, Vector2 localNormal, Vector2 impactPos, Vector2 velocity)
private void ApplyImpact(Fixture f1, Fixture f2, Vector2 worldNormal, Vector2 impactPos, Vector2 velocity)
{
if (character.DisableImpactDamageTimer > 0.0f) { return; }
@@ -839,7 +841,7 @@ namespace Barotrauma
return;
}
Vector2 normal = localNormal;
Vector2 normal = worldNormal;
float impact = Vector2.Dot(velocity, -normal);
if (f1.Body == Collider.FarseerBody || !Collider.Enabled)
{
@@ -857,7 +859,8 @@ namespace Barotrauma
float impactDamage = GetImpactDamage(impact, impactTolerance);
var should = GameMain.LuaCs.Hook.Call<float?>("changeFallDamage", impactDamage, character, impactPos, velocity);
float? should = null;
LuaCsSetup.Instance.EventService.PublishEvent<IEventChangeFallDamage>(x => should = x.OnChangeFallDamage(impactDamage, character, impactPos, velocity) ?? should);
if (should != null)
{
@@ -1077,9 +1080,12 @@ namespace Barotrauma
}
Hull newHull = Hull.FindHull(findPos, currentHull);
if (setInWater && newHull == null)
if (setInWater)
{
inWater = true;
if (newHull == null || findPos.Y < newHull.WorldSurface)
{
inWater = true;
}
}
if (newHull == currentHull) { return; }
@@ -1122,7 +1128,10 @@ namespace Barotrauma
{
//don't teleport out yet if the character is going through a gap
if (Gap.FindAdjacent(Gap.GapList.Where(g => g.Submarine == currentHull.Submarine), findPos, 150.0f, allowRoomToRoom: true) != null) { return; }
if (Limbs.Any(l => Gap.FindAdjacent(currentHull.ConnectedGaps, l.WorldPosition, ConvertUnits.ToDisplayUnits(l.body.GetSize().Combine()), allowRoomToRoom: true) != null)) { return; }
if (Limbs.Any(l => !l.IsSevered && Gap.FindAdjacent(currentHull.ConnectedGaps, l.WorldPosition, ConvertUnits.ToDisplayUnits(l.body.GetSize().Combine()), allowRoomToRoom: true) != null))
{
return;
}
character.MemLocalState?.Clear();
Teleport(ConvertUnits.ToSimUnits(currentHull.Submarine.Position), currentHull.Submarine.Velocity);
}
@@ -1259,6 +1268,9 @@ namespace Barotrauma
private float BodyInRestDelay = 1.0f;
/// <summary>
/// Controls the sleeping state of this character
/// </summary>
public bool BodyInRest
{
get { return bodyInRestTimer > BodyInRestDelay; }
@@ -1282,7 +1294,7 @@ namespace Barotrauma
while (impactQueue.Count > 0)
{
var impact = impactQueue.Dequeue();
ApplyImpact(impact.F1, impact.F2, impact.LocalNormal, impact.ImpactPos, impact.Velocity);
ApplyImpact(impact.F1, impact.F2, impact.WorldNormal, impact.ImpactPos, impact.Velocity);
}
CheckValidity();
@@ -1325,9 +1337,18 @@ namespace Barotrauma
}
float MaxVel = NetConfig.MaxPhysicsBodyVelocity;
Collider.LinearVelocity = new Vector2(
NetConfig.Quantize(Collider.LinearVelocity.X, -MaxVel, MaxVel, 12),
NetConfig.Quantize(Collider.LinearVelocity.Y, -MaxVel, MaxVel, 12));
if (GameMain.NetworkMember != null)
{
Collider.LinearVelocity = new Vector2(
NetConfig.Quantize(Collider.LinearVelocity.X, -MaxVel, MaxVel, 12),
NetConfig.Quantize(Collider.LinearVelocity.Y, -MaxVel, MaxVel, 12));
}
else
{
Collider.LinearVelocity = new Vector2(
MathHelper.Clamp(Collider.LinearVelocity.X, -MaxVel, MaxVel),
MathHelper.Clamp(Collider.LinearVelocity.Y, -MaxVel, MaxVel));
}
if (forceStanding)
{
@@ -1381,9 +1402,19 @@ namespace Barotrauma
UpdateHullFlowForces(deltaTime);
if (currentHull == null ||
bool applyWaterForces =
currentHull == null ||
currentHull.WaterVolume > currentHull.Volume * 0.95f ||
ConvertUnits.ToSimUnits(currentHull.Surface) > Collider.SimPosition.Y)
ConvertUnits.ToSimUnits(currentHull.Surface) > Collider.SimPosition.Y;
#if CLIENT
if (Screen.Selected is CharacterEditor.CharacterEditorScreen &&
this is AnimController animController)
{
applyWaterForces = animController.CurrentAnimationParams is SwimParams;
}
#endif
if (applyWaterForces)
{
Collider.ApplyWaterForces();
}
@@ -1473,10 +1504,10 @@ namespace Barotrauma
else
{
// Falling -> ragdoll briefly if we are not moving at all, because we are probably stuck.
if (Collider.LinearVelocity == Vector2.Zero && !character.IsRemotePlayer)
if (Collider.LinearVelocity == Vector2.Zero && GameMain.NetworkMember is not { IsClient: true })
{
character.IsRagdolled = true;
if (character.IsBot)
if (!character.IsPlayer)
{
// Seems to work without this on player controlled characters -> not sure if we should call it always or just for the bots.
character.SetInput(InputType.Ragdoll, hit: false, held: true);
@@ -1836,7 +1867,13 @@ namespace Barotrauma
{
floorFixture = standOnFloorFixture;
standOnFloorY = rayStart.Y + (rayEnd.Y - rayStart.Y) * standOnFloorFraction;
if (rayStart.Y - standOnFloorY < Collider.Height * 0.5f + Collider.Radius + ColliderHeightFromFloor * 1.2f)
//allow the floor to be just a bit below the bottom of the collider for the character to be "on ground"
//there is some inaccuracy in the physics simulation (and floats), the collider isn't usually precisely ColliderHeightFromFloor above the floor
const float Tolerance = 0.1f;
float standHeight = Collider.Height * 0.5f + Collider.Radius + ColliderHeightFromFloor;
if (rayStart.Y - standOnFloorY <= standHeight + Tolerance)
{
onGround = true;
if (standOnFloorFixture.CollisionCategories == Physics.CollisionStairs)
@@ -190,6 +190,11 @@ namespace Barotrauma
set => Params.Health.DoesBleed = value;
}
/// <summary>
/// Can this character be contained inside a controller?
/// </summary>
public bool IsContainable { get; set; }
public readonly Dictionary<Identifier, SerializableProperty> Properties;
public Dictionary<Identifier, SerializableProperty> SerializableProperties
{
@@ -686,6 +691,11 @@ namespace Barotrauma
get { return AnimController.Mass; }
}
/// <summary>
/// The position the character was at when we previously set the transforms of the items in the character's inventory.
/// </summary>
private Vector2 lastInventoryItemSetTransformPosition;
public CharacterInventory Inventory { get; private set; }
/// <summary>
@@ -791,7 +801,24 @@ namespace Barotrauma
set
{
if (value == selectedCharacter) { return; }
if (selectedCharacter != null) { selectedCharacter.selectedBy = null; }
//deselect the currently selected character
if (selectedCharacter != null)
{
selectedCharacter.selectedBy = null;
//check if some other character has selected the currently selected character too,
//and set selectedBy to that other character (otherwise the currently selected character would be unaware they're still being dragged by someone)
foreach (var otherCharacter in CharacterList)
{
if (otherCharacter != this && otherCharacter.selectedCharacter == selectedCharacter)
{
selectedCharacter.selectedBy = otherCharacter;
break;
}
}
}
CharacterHUD.RecreateHudTextsIfControlling(this);
selectedCharacter = value;
if (selectedCharacter != null) { selectedCharacter.selectedBy = this; }
#if CLIENT
@@ -1433,8 +1460,6 @@ namespace Barotrauma
}
#endif
GameMain.LuaCs.Hook.Call("character.created", new object[] { newCharacter });
return newCharacter;
}
@@ -1648,8 +1673,10 @@ namespace Barotrauma
AnimController.FindHull(setInWater: true);
if (AnimController.CurrentHull != null) { Submarine = AnimController.CurrentHull.Submarine; }
IsContainable = prefab.ConfigElement.GetAttributeBool(nameof(IsContainable), def: Mass <= 30.0f);
CharacterList.Add(this);
Enabled = GameMain.NetworkMember == null;
if (info != null)
@@ -1889,7 +1916,6 @@ namespace Barotrauma
}
}
info.Job?.GiveJobItems(this, isPvPMode, spawnPoint);
GameMain.LuaCs.Hook.Call("character.giveJobItems", this, spawnPoint, isPvPMode);
}
public void GiveIdCardTags(WayPoint spawnPoint, bool createNetworkEvent = false)
@@ -2275,6 +2301,12 @@ namespace Barotrauma
}
}
// Try to detach from the controller if we are currently attached to something that is dangerous for our character
if (aiControlled && Stun <= 0f && !IsKnockedDownOrRagdolled && !LockHands && ShouldAvoidStayingAttachedToController())
{
SelectedItem = null;
}
if (GameMain.NetworkMember != null)
{
if (GameMain.NetworkMember.IsServer)
@@ -2323,7 +2355,7 @@ namespace Barotrauma
{
attackCoolDown -= deltaTime;
}
else if (IsKeyDown(InputType.Attack))
else if (IsKeyDown(InputType.Attack) && !IsAttachedToController())
{
//normally the attack target, where to aim the attack and such is handled by EnemyAIController,
//but in the case of player-controlled monsters, we handle it here
@@ -2850,14 +2882,14 @@ namespace Barotrauma
#if CLIENT
if (Screen.Selected == GameMain.SubEditorScreen) { hidden = false; }
#endif
if (!CanInteract || hidden || !item.IsInteractable(this)) { return false; }
Controller controller = item.GetComponent<Controller>();
if (controller != null && IsAnySelectedItem(item) && controller.IsAttachedUser(this))
{
return true;
}
if (!CanInteract || hidden || !item.IsInteractable(this)) { return false; }
if (item.ParentInventory != null)
{
return CanAccessInventory(item.ParentInventory);
@@ -2979,7 +3011,9 @@ namespace Barotrauma
}
}
if (!item.Prefab.InteractThroughWalls && Screen.Selected != GameMain.SubEditorScreen && !insideTrigger)
//note that the distance to item should be set to 0 above if the character is within the item's bounding box
bool closeEnoughToIgnoreVisibilityCheck = distanceToItem <= 0.1f;
if (!item.Prefab.InteractThroughWalls && Screen.Selected != GameMain.SubEditorScreen && !insideTrigger && !closeEnoughToIgnoreVisibilityCheck)
{
var body = Submarine.CheckVisibility(SimPosition, itemPosition, ignoreLevel: true);
bool itemCenterVisible = CheckBody(body, item);
@@ -3008,7 +3042,6 @@ namespace Barotrauma
{
return itemCenterVisible;
}
}
return true;
@@ -3098,7 +3131,11 @@ namespace Barotrauma
if (!CanInteract)
{
SelectedItem = SelectedSecondaryItem = null;
if (!IsAttachedToController())
{
SelectedItem = null;
}
SelectedSecondaryItem = null;
focusedItem = null;
if (!AllowInput)
{
@@ -3117,8 +3154,16 @@ namespace Barotrauma
{
if (!PlayerInput.PrimaryMouseButtonHeld() || Barotrauma.Inventory.DraggingItemToWorld)
{
FocusedCharacter = CanInteract || CanEat ? FindCharacterAtPosition(mouseSimPos) : null;
if (FocusedCharacter != null && !CanSeeTarget(FocusedCharacter)) { FocusedCharacter = null; }
//don't allow focusing on anyone when the health window is open (avoids accidentally selecting someone when closing the window)
if (CharacterHealth.OpenHealthWindow != null)
{
FocusedCharacter = null;
}
else
{
FocusedCharacter = CanInteract || CanEat ? FindCharacterAtPosition(mouseSimPos) : null;
if (FocusedCharacter != null && !CanSeeTarget(FocusedCharacter)) { FocusedCharacter = null; }
}
float aimAssist = GameSettings.CurrentConfig.AimAssistAmount * (AnimController.InWater ? 1.5f : 1.0f);
if (HeldItems.Any(it => it?.GetComponent<Wire>()?.IsActive ?? false))
{
@@ -3443,7 +3488,7 @@ namespace Barotrauma
obstructVisionAmount = Math.Max(obstructVisionAmount - deltaTime, 0.0f);
if (Inventory != null)
if (Inventory != null && Vector2.DistanceSquared(lastInventoryItemSetTransformPosition, Position) > 0.1f)
{
//do not check for duplicates: this is code is called very frequently, and duplicates don't matter here,
//so it's better just to avoid the relatively expensive duplicate check
@@ -3452,6 +3497,7 @@ namespace Barotrauma
if (item.body == null || item.body.Enabled) { continue; }
item.SetTransform(SimPosition, 0.0f, forceSubmarine: Submarine);
}
lastInventoryItemSetTransformPosition = Position;
}
HideFace = false;
@@ -3578,7 +3624,7 @@ namespace Barotrauma
{
wasRagdolled = IsRagdolled;
IsRagdolled = IsKeyDown(InputType.Ragdoll);
if (IsRagdolled && IsBot && GameMain.NetworkMember is not { IsClient: true })
if (IsRagdolled && !IsPlayer && GameMain.NetworkMember is not { IsClient: true })
{
ClearInput(InputType.Ragdoll);
}
@@ -3630,7 +3676,19 @@ namespace Barotrauma
AnimController.IgnorePlatforms = true;
}
AnimController.ResetPullJoints();
SelectedItem = SelectedSecondaryItem = null;
// Prevent us from detaching from the controller if we are attached to it OR detach if we
// manually ragdoll, in this case it should be similar to us deselecting the controller
if (!IsAttachedToController() ||
(IsKeyDown(InputType.Ragdoll)
// Let only the server do this check since the Ragdoll input for other clients is set to be held
// for stunned characters even if a character isn't manually ragdolling
&& (GameMain.NetworkMember == null || GameMain.NetworkMember is { IsServer: true } )))
{
SelectedItem = null;
}
SelectedSecondaryItem = null;
SelectedCharacter = null;
return;
}
@@ -3659,6 +3717,13 @@ namespace Barotrauma
bool MustDeselect(Item item)
{
if (item == null) { return false; }
// Prevent creatures from deselecting the controller if they are attached to it
if (IsAIControlled && !CanInteract && IsAttachedToController())
{
return false;
}
if (!CanInteractWith(item)) { return true; }
bool hasSelectableComponent = false;
foreach (var component in item.Components)
@@ -4384,6 +4449,41 @@ namespace Barotrauma
}
}
public void ForceSay(LocalizedString messageToSay, bool sayInRadio, bool removeQuotes = false, float delay = 0.0f)
{
if (messageToSay.IsNullOrEmpty() || SpeechImpediment >= 100.0f || IsDead)
{
return;
}
if (removeQuotes)
{
messageToSay = new TrimLString(messageToSay,
TrimLString.Mode.Both, ['"', '”', '“', ' ']);
}
ChatMessageType messageType = ChatMessageType.Default;
bool canUseRadio = ChatMessage.CanUseRadio(this, out WifiComponent radio);
if (canUseRadio && sayInRadio)
{
messageType = ChatMessageType.Radio;
}
CoroutineManager.Invoke(() =>
{
#if SERVER
GameMain.Server?.SendChatMessage(messageToSay.Value, messageType, senderClient: null, this);
#elif CLIENT
// no need to create the message when playing as a client, the server will send it to us
if (GameMain.Client == null)
{
AIChatMessage message = new AIChatMessage(messageToSay.Value, messageType);
SendSinglePlayerMessage(message, canUseRadio, radio);
}
#endif
}, delay);
}
public void SetAllDamage(float damageAmount, float bleedingDamageAmount, float burnDamageAmount)
{
CharacterHealth.SetAllDamage(damageAmount, bleedingDamageAmount, burnDamageAmount);
@@ -4596,12 +4696,6 @@ namespace Barotrauma
public AttackResult DamageLimb(Vector2 worldPosition, Limb hitLimb, IEnumerable<Affliction> afflictions, float stun, bool playSound, Vector2 attackImpulse, Character attacker = null, float damageMultiplier = 1, bool allowStacking = true, float penetration = 0f, bool shouldImplode = false, bool ignoreDamageOverlay = false, bool recalculateVitality = true)
{
if (Removed) { return new AttackResult(); }
AttackResult? retAttackResult = GameMain.LuaCs.Hook.Call<AttackResult?>("character.damageLimb", this, worldPosition, hitLimb, afflictions, stun, playSound, attackImpulse, attacker, damageMultiplier, allowStacking, penetration, shouldImplode);
if (retAttackResult != null)
{
return retAttackResult.Value;
}
SetStun(stun);
@@ -4774,6 +4868,10 @@ namespace Barotrauma
{
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient && !isNetworkMessage) { return; }
if (Screen.Selected != GameMain.GameScreen) { return; }
//don't allow stunning for less than one frame
//fixes monsters/enemies that take some minuscule amount of stun from a weapon still being noticeable affected by the stun,
//because even a one-frame stun briefly disables the animations and makes the character stop
if (newStun < Timing.Step && Stun <= 0.0f) { return; }
if (GodMode)
{
CharacterHealth.Stun = 0;
@@ -4801,7 +4899,12 @@ namespace Barotrauma
CharacterHealth.Stun = newStun;
if (newStun > 0.0f)
{
SelectedItem = SelectedSecondaryItem = null;
if (!IsAttachedToController())
{
SelectedItem = null;
}
SelectedSecondaryItem = null;
if (SelectedCharacter != null) { DeselectCharacter(); }
}
HealthUpdateInterval = 0.0f;
@@ -4990,6 +5093,37 @@ namespace Barotrauma
}
}
public bool IsAttachedToController()
{
if (SelectedItem == null) { return false; }
var controller = SelectedItem.GetComponent<Controller>();
if (controller == null) { return false; }
return controller.IsAttachedUser(this);
}
public bool ShouldAvoidStayingAttachedToController()
{
if (!IsAttachedToController()) { return false; }
var deconstructor = SelectedItem.GetComponent<Deconstructor>();
if (deconstructor != null)
{
return true;
}
// Character is being carried by an enemy!
if (IsHuman &&
SelectedItem.GetRootInventoryOwner() is Character carryingCharacter &&
TeamID != carryingCharacter.TeamID)
{
return true;
}
return false;
}
public void Kill(CauseOfDeathType causeOfDeath, Affliction causeOfDeathAffliction, bool isNetworkMessage = false, bool log = true)
{
if (IsDead || CharacterHealth.Unkillable || GodMode || Removed) { return; }
@@ -5117,7 +5251,6 @@ namespace Barotrauma
AchievementManager.OnCharacterKilled(this, CauseOfDeath);
}
GameMain.LuaCs.Hook.Call("character.death", this, causeOfDeathAffliction);
KillProjSpecific(causeOfDeath, causeOfDeathAffliction, log);
if (info != null)
@@ -5128,7 +5261,7 @@ namespace Barotrauma
AnimController.movement = Vector2.Zero;
AnimController.TargetMovement = Vector2.Zero;
if (!LockHands)
if (!LockHands && causeOfDeath != CauseOfDeathType.Disconnected)
{
foreach (Item heldItem in HeldItems.ToList())
{
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Xna.Framework;
@@ -482,7 +482,6 @@ namespace Barotrauma
{
GrainEffectStrength -= amount;
}
GameMain.LuaCs.Hook.Call("afflictionUpdate", new object[] { this, characterHealth, targetLimb, deltaTime });
}
public void ApplyStatusEffects(ActionType type, float deltaTime, CharacterHealth characterHealth, Limb targetLimb)
@@ -4,6 +4,7 @@ using System.Xml.Linq;
using System;
using Barotrauma.Extensions;
using Microsoft.Xna.Framework;
using Barotrauma.LuaCs.Events;
namespace Barotrauma
{
@@ -337,13 +338,13 @@ namespace Barotrauma
if (Prefab is AfflictionPrefabHusk huskPrefab)
{
if (huskPrefab.ControlHusk || GameMain.LuaCs.Game.enableControlHusk)
if (huskPrefab.ControlHusk || LuaCsSetup.Instance.Game.enableControlHusk)
{
#if SERVER
if (client != null)
{
GameMain.Server.SetClientCharacter(client, husk);
GameMain.LuaCs.Hook.Call("husk.clientControlHusk", new object[] { client, husk });
LuaCsSetup.Instance.EventService.PublishEvent<IEventClientControlHusk>(x => x.OnClientControlHusk(client, husk));
}
#else
if (!character.IsRemotelyControlled && character == Character.Controlled)
@@ -629,7 +629,7 @@ namespace Barotrauma
public static readonly Identifier StunType = "stun".ToIdentifier();
public static readonly Identifier EMPType = "emp".ToIdentifier();
public static readonly Identifier SpaceHerpesType = "spaceherpes".ToIdentifier();
public static readonly Identifier AlienInfectedType = "alieninfected".ToIdentifier();
public static readonly Identifier AlienInfectionType = "alieninfection".ToIdentifier();
public static readonly Identifier InvertControlsType = "invertcontrols".ToIdentifier();
public static readonly Identifier DisguisedAsHuskType = "disguiseashusk".ToIdentifier();
@@ -1,17 +1,19 @@
using Barotrauma.Abilities;
using Barotrauma.Abilities;
using Barotrauma.Extensions;
using Barotrauma.Extensions;
using Barotrauma.LuaCs.Events;
using Barotrauma.Networking;
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using MoonSharp.Interpreter;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Barotrauma.Networking;
using Barotrauma.Extensions;
using System.Globalization;
using MoonSharp.Interpreter;
using Barotrauma.Abilities;
using static OneOf.Types.TrueFalseOrNull;
namespace Barotrauma
{
@@ -657,7 +659,8 @@ namespace Barotrauma
return;
}
var should = GameMain.LuaCs.Hook.Call<bool?>("character.applyDamage", this, attackResult, hitLimb, allowStacking);
bool? should = null;
LuaCsSetup.Instance.EventService.PublishEvent<IEventCharacterApplyDamage>(x => should = x.OnCharacterApplyDamage(this, attackResult, hitLimb, allowStacking) ?? should);
if (should != null && should.Value) { return; }
foreach (Affliction newAffliction in attackResult.Afflictions)
@@ -828,10 +831,9 @@ namespace Barotrauma
if (newAffliction.Prefab.TargetSpecies.Any() && newAffliction.Prefab.TargetSpecies.None(s => s == Character.SpeciesName)) { return; }
if (Character.Params.Health.ImmunityIdentifiers.Contains(newAffliction.Identifier)) { return; }
var should = GameMain.LuaCs.Hook.Call<bool?>("character.applyAffliction", this, limbHealth, newAffliction, allowStacking);
if (should != null && should.Value)
return;
bool? should = null;
LuaCsSetup.Instance.EventService.PublishEvent<IEventCharacterApplyAffliction>(x => should = x.OnCharacterApplyAffliction(this, limbHealth, newAffliction, allowStacking) ?? should);
if (should != null && should.Value) { return; }
Affliction existingAffliction = null;
foreach ((Affliction affliction, LimbHealth value) in afflictions)
@@ -843,9 +845,21 @@ namespace Barotrauma
}
}
float modifiedStrength = newAffliction.Strength * (100.0f / MaxVitality) * (1f - GetResistance(newAffliction.Prefab, limbType));
if (newAffliction.Prefab.AfflictionType == AfflictionPrefab.StunType)
{
//don't allow stunning for less than one frame
//fixes monsters/enemies that take some minuscule amount of stun from a weapon still being noticeable affected by the stun,
//because even a one-frame stun briefly disables the animations and makes the character stop
if (modifiedStrength < Timing.Step && Stun <= 0.0f)
{
return;
}
}
if (existingAffliction != null)
{
float newStrength = newAffliction.Strength * (100.0f / MaxVitality) * (1f - GetResistance(existingAffliction.Prefab, limbType));
float newStrength = modifiedStrength;
if (allowStacking)
{
// Add the existing strength
@@ -867,7 +881,7 @@ namespace Barotrauma
//create a new instance of the affliction to make sure we don't use the same instance for multiple characters
//or modify the affliction instance of an Attack or a StatusEffect
var copyAffliction = newAffliction.Prefab.Instantiate(
Math.Min(newAffliction.Prefab.MaxStrength, newAffliction.Strength * (100.0f / MaxVitality) * (1f - GetResistance(newAffliction.Prefab, limbType))),
Math.Min(newAffliction.Prefab.MaxStrength, modifiedStrength),
newAffliction.Source);
afflictions.Add(copyAffliction, limbHealth);
AchievementManager.OnAfflictionReceived(copyAffliction, Character);
@@ -190,7 +190,7 @@ namespace Barotrauma
idleObjective.PreferredOutpostModuleTypes.Add(moduleType);
}
}
humanAI.ReportRange = Hearing;
humanAI.Hearing = Hearing;
humanAI.ReportRange = ReportRange;
humanAI.FindWeaponsRange = FindWeaponsRange;
humanAI.AimSpeed = AimSpeed;
@@ -1293,7 +1293,7 @@ namespace Barotrauma
if (!statusEffects.TryGetValue(actionType, out var statusEffectList)) { return; }
foreach (StatusEffect statusEffect in statusEffectList)
{
if (statusEffect.ShouldWaitForInterval(character, deltaTime)) { return; }
if (statusEffect.ShouldWaitForInterval(character, deltaTime)) { continue; }
statusEffect.sourceBody = body;
if (statusEffect.type == ActionType.OnDamaged)
@@ -728,7 +728,9 @@ namespace Barotrauma
[Serialize(true, IsPropertySaveable.Yes, description: "Should the character target or ignore walls when it's outside the submarine."), Editable]
public bool TargetOuterWalls { get; private set; }
[Serialize(false, IsPropertySaveable.Yes, description: "If enabled, the character chooses randomly from the available attacks. The priority is used as a weight for weighted random."), Editable]
[Serialize(false, IsPropertySaveable.Yes, description: "If disabled (default), the character selects the limb based on a formula where the parameters are a) the priority of the attack b) the distance to the target, and c) the range of the attack" +
"If enabled, the character chooses randomly from the available attacks. The priority is used as a weight for weighted random. The distance to the target is in this case ignored."
), Editable]
public bool RandomAttack { get; private set; }
[Serialize(false, IsPropertySaveable.Yes, description:"Does the creature know how to open doors (still requires a proper ID card). Humans can always open doors (They don't use this AI definition)."), Editable]