Faction Test 100.4.0.0

This commit is contained in:
Markus Isberg
2022-11-14 18:28:28 +02:00
parent 87426b68b2
commit c772b61fc1
412 changed files with 16984 additions and 5530 deletions
@@ -524,8 +524,8 @@ namespace Barotrauma.Items.Components
System.Diagnostics.Debug.Assert(doorBody == null);
doorBody = GameMain.World.CreateRectangle(
DockingTarget.Door.Body.width,
DockingTarget.Door.Body.height,
DockingTarget.Door.Body.Width,
DockingTarget.Door.Body.Height,
1.0f,
position);
doorBody.UserData = DockingTarget.Door;
@@ -4,9 +4,7 @@ using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using Barotrauma.IO;
using System.Linq;
using System.Xml.Linq;
#if CLIENT
using Barotrauma.Lights;
#endif
@@ -16,6 +14,10 @@ namespace Barotrauma.Items.Components
{
partial class Door : Pickable, IDrawableComponent, IServerSerializable
{
private static readonly HashSet<Door> doorList = new HashSet<Door>();
public static IReadOnlyCollection<Door> DoorList { get { return doorList; } }
private Gap linkedGap;
private bool isOpen;
@@ -92,6 +94,9 @@ namespace Barotrauma.Items.Components
public PhysicsBody Body { get; private set; }
//the fixture that's part of the submarine's collider (= fixture that things outside the sub can collide with if the door is outside hulls)
public Fixture OutsideSubmarineFixture;
private float RepairThreshold
{
get { return item.GetComponent<Repairable>() == null ? 0.0f : item.MaxCondition; }
@@ -165,7 +170,7 @@ namespace Barotrauma.Items.Components
set
{
isOpen = value;
OpenState = (isOpen) ? 1.0f : 0.0f;
OpenState = isOpen ? 1.0f : 0.0f;
}
}
@@ -227,6 +232,7 @@ namespace Barotrauma.Items.Components
}
IsActive = true;
doorList.Add(this);
}
public override void OnItemLoaded()
@@ -366,6 +372,8 @@ namespace Barotrauma.Items.Components
return;
}
bool isClosing = false;
if ((!IsStuck && !IsJammed) || !isOpen)
{
@@ -391,11 +399,20 @@ namespace Barotrauma.Items.Components
if (isClosing)
{
if (OpenState < 0.9f) { PushCharactersAway(); }
if (CheckSubmarinesInDoorWay())
{
PredictedState = null;
isOpen = true;
}
}
else
{
bool wasEnabled = Body.Enabled;
Body.Enabled = Impassable || openState < 1.0f;
if (OutsideSubmarineFixture != null)
{
OutsideSubmarineFixture.CollidesWith = Body.Enabled ? SubmarineBody.CollidesWith : Category.None;
}
if (wasEnabled && !Body.Enabled && IsHorizontal)
{
//when opening a hatch, force characters above it to refresh the floor position
@@ -439,6 +456,10 @@ namespace Barotrauma.Items.Components
}
PushCharactersAway();
}
if (OutsideSubmarineFixture != null && Body.Enabled)
{
OutsideSubmarineFixture.CollidesWith = SubmarineBody.CollidesWith;
}
#if CLIENT
UpdateConvexHulls();
#endif
@@ -459,6 +480,10 @@ namespace Barotrauma.Items.Components
ce = ce.Next;
}
}
if (OutsideSubmarineFixture != null)
{
OutsideSubmarineFixture.CollidesWith = Category.None;
}
linkedGap.Open = 1.0f;
IsOpen = false;
#if CLIENT
@@ -534,6 +559,36 @@ namespace Barotrauma.Items.Components
convexHull?.Remove();
convexHull2?.Remove();
#endif
doorList.Remove(this);
}
private bool CheckSubmarinesInDoorWay()
{
if (linkedGap != null && linkedGap.IsRoomToRoom) { return false; }
Rectangle doorRect = item.WorldRect;
if (IsHorizontal)
{
doorRect.Width = (int)(item.Rect.Width * (1.0f - openState));
}
else
{
doorRect.Height = (int)(item.Rect.Height * (1.0f - openState));
}
foreach (Submarine sub in Submarine.Loaded)
{
if (sub == item.Submarine || sub.DockedTo.Contains(item.Submarine)) { continue; }
Rectangle worldBorders = sub.Borders;
worldBorders.Location += sub.WorldPosition.ToPoint();
if (!Submarine.RectsOverlap(worldBorders, doorRect)) { continue; }
foreach (Hull hull in sub.GetHulls(alsoFromConnectedSubs: false))
{
if (Submarine.RectsOverlap(hull.WorldRect, doorRect)) { return true; }
}
}
return false;
}
bool itemPosErrorShown;
@@ -557,7 +612,6 @@ namespace Barotrauma.Items.Components
Vector2 currSize = IsHorizontal ?
new Vector2(item.Rect.Width * (1.0f - openState), doorSprite.size.Y * item.Scale) :
new Vector2(doorSprite.size.X * item.Scale, item.Rect.Height * (1.0f - openState));
Vector2 simSize = ConvertUnits.ToSimUnits(currSize);
foreach (Character c in Character.CharacterList)
@@ -1,4 +1,5 @@
using Barotrauma.Networking;
using FarseerPhysics;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
@@ -63,6 +64,9 @@ namespace Barotrauma.Items.Components
set;
}
[Serialize(0.0f, IsPropertySaveable.No)]
public float RaycastRange { get; set; }
[Serialize(0.25f, IsPropertySaveable.Yes, description: "The duration of an individual discharge (in seconds)."), Editable(MinValueFloat = 0.0f, MaxValueFloat = 60.0f, ValueStep = 0.1f, DecimalCount = 2)]
public float Duration
{
@@ -70,6 +74,13 @@ namespace Barotrauma.Items.Components
set;
}
[Serialize(0.25f, IsPropertySaveable.Yes), Editable(MinValueFloat = 0.0f, MaxValueFloat = 60.0f, ValueStep = 0.1f, DecimalCount = 2)]
public float Reload
{
get;
set;
}
[Serialize(false, IsPropertySaveable.Yes, "If set to true, the discharge cannot travel inside the submarine nor shock anyone inside."), Editable]
public bool OutdoorsOnly
{
@@ -77,6 +88,13 @@ namespace Barotrauma.Items.Components
set;
}
[Serialize(false, IsPropertySaveable.Yes)]
public bool IgnoreUser
{
get;
set;
}
private readonly List<Node> nodes = new List<Node>();
public IEnumerable<Node> Nodes
{
@@ -91,6 +109,10 @@ namespace Barotrauma.Items.Components
private readonly Attack attack;
private Character user;
private float reloadTimer;
public ElectricalDischarger(Item item, ContentXElement element) :
base(item, element)
{
@@ -125,6 +147,7 @@ namespace Barotrauma.Items.Components
charging = true;
timer = Duration;
IsActive = true;
user = character;
#if SERVER
if (GameMain.Server != null) { item.CreateServerEvent(this); }
#endif
@@ -144,6 +167,11 @@ namespace Barotrauma.Items.Components
if (timer <= 0.0f)
{
if (reloadTimer > 0.0f)
{
reloadTimer -= deltaTime;
return;
}
IsActive = false;
return;
}
@@ -196,6 +224,7 @@ namespace Barotrauma.Items.Components
private void Discharge()
{
reloadTimer = Reload;
ApplyStatusEffects(ActionType.OnUse, 1.0f);
FindNodes(item.WorldPosition, Range);
if (attack != null)
@@ -203,7 +232,7 @@ namespace Barotrauma.Items.Components
foreach ((Character character, Node node) in charactersInRange)
{
if (character == null || character.Removed) { continue; }
character.ApplyAttack(null, node.WorldPosition, attack, MathHelper.Clamp(Voltage, 1.0f, MaxOverVoltageFactor));
character.ApplyAttack(user, node.WorldPosition, attack, MathHelper.Clamp(Voltage, 1.0f, MaxOverVoltageFactor));
}
}
DischargeProjSpecific();
@@ -214,6 +243,18 @@ namespace Barotrauma.Items.Components
public void FindNodes(Vector2 worldPosition, float range)
{
if (RaycastRange > 0.0f)
{
float angle = 0.0f;
float dir = 1;
if (item.body != null)
{
angle += item.body.Rotation;
dir = item.body.Dir;
}
worldPosition += new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)) * RaycastRange * dir;
}
//see which submarines are within range so we can skip structures that are in far-away subs
List<Submarine> submarinesInRange = new List<Submarine>();
foreach (Submarine sub in Submarine.Loaded)
@@ -222,7 +263,7 @@ namespace Barotrauma.Items.Components
{
submarinesInRange.Add(sub);
}
else
else if (sub != null)
{
Rectangle subBorders = new Rectangle(
sub.Borders.X - (int)range, sub.Borders.Y + (int)range,
@@ -263,26 +304,41 @@ namespace Barotrauma.Items.Components
entitiesInRange.Add(structure);
}
nodes.Clear();
if (RaycastRange > 0.0f)
{
nodes.Add(new Node(item.WorldPosition, -1));
int parentNodeIndex = 0;
AddNodesBetweenPoints(item.WorldPosition, worldPosition, 0.5f, ref parentNodeIndex);
}
else
{
nodes.Add(new Node(worldPosition, -1));
}
float totalRange = RaycastRange + range;
foreach (Character character in Character.CharacterList)
{
if (!character.Enabled) continue;
if (OutdoorsOnly && character.Submarine != null) continue;
if (character.Submarine != null && !submarinesInRange.Contains(character.Submarine)) continue;
if (!character.Enabled) { continue; }
if (IgnoreUser && character == user) { continue; }
if (OutdoorsOnly && character.Submarine != null) { continue; }
if (character.Submarine != null && !submarinesInRange.Contains(character.Submarine)) { continue; }
if (Vector2.DistanceSquared(character.WorldPosition, worldPosition) < range * range * RangeMultiplierInWalls)
if (Vector2.DistanceSquared(character.WorldPosition, worldPosition) < totalRange * totalRange * RangeMultiplierInWalls ||
(RaycastRange > 0.0f && MathUtils.LineToPointDistanceSquared(worldPosition, item.WorldPosition, character.WorldPosition) < range * range * RangeMultiplierInWalls))
{
entitiesInRange.Add(character);
charactersInRange.Add((character, nodes[0]));
}
}
nodes.Clear();
nodes.Add(new Node(worldPosition, -1));
FindNodes(entitiesInRange, worldPosition, 0, range);
FindNodes(entitiesInRange, worldPosition, nodes.Count - 1, range);
//construct final nodes (w/ lengths and angles so they don't have to be recalculated when rendering the discharge)
for (int i = 0; i < nodes.Count; i++)
{
if (nodes[i].ParentIndex < 0) continue;
if (nodes[i].ParentIndex < 0) { continue; }
Node parentNode = nodes[nodes[i].ParentIndex];
float length = Vector2.Distance(nodes[i].WorldPosition, parentNode.WorldPosition) * Rand.Range(1.0f, 1.25f);
float angle = MathUtils.VectorToAngle(parentNode.WorldPosition - nodes[i].WorldPosition);
@@ -292,7 +348,7 @@ namespace Barotrauma.Items.Components
private void FindNodes(List<Entity> entitiesInRange, Vector2 currPos, int parentNodeIndex, float currentRange)
{
if (currentRange <= 0.0f || nodes.Count >= MaxNodes) return;
if (currentRange <= 0.0f || nodes.Count >= MaxNodes) { return; }
//find the closest structure
int closestIndex = -1;
@@ -434,20 +490,21 @@ namespace Barotrauma.Items.Components
for (int j = 0; j < entitiesInRange.Count; j++)
{
var otherEntity = entitiesInRange[j];
if (!(otherEntity is Character character)) continue;
if (OutdoorsOnly && character.Submarine != null) continue;
if (otherEntity is not Character character) { continue; }
if (IgnoreUser && character == user) { continue; }
if (OutdoorsOnly && character.Submarine != null) { continue; }
if (targetStructure.IsHorizontal)
{
if (otherEntity.WorldPosition.X < targetStructure.WorldRect.X) continue;
if (otherEntity.WorldPosition.X > targetStructure.WorldRect.Right) continue;
if (Math.Abs(otherEntity.WorldPosition.Y - targetStructure.WorldPosition.Y) > currentRange) continue;
if (otherEntity.WorldPosition.X < targetStructure.WorldRect.X) { continue; }
if (otherEntity.WorldPosition.X > targetStructure.WorldRect.Right) { continue; }
if (Math.Abs(otherEntity.WorldPosition.Y - targetStructure.WorldPosition.Y) > currentRange) { continue; }
}
else
{
if (otherEntity.WorldPosition.Y < targetStructure.WorldRect.Y - targetStructure.Rect.Height) continue;
if (otherEntity.WorldPosition.Y > targetStructure.WorldRect.Y) continue;
if (Math.Abs(otherEntity.WorldPosition.X - targetStructure.WorldPosition.X) > currentRange) continue;
if (otherEntity.WorldPosition.Y < targetStructure.WorldRect.Y - targetStructure.Rect.Height) { continue; }
if (otherEntity.WorldPosition.Y > targetStructure.WorldRect.Y) { continue; }
if (Math.Abs(otherEntity.WorldPosition.X - targetStructure.WorldPosition.X) > currentRange) { continue; }
}
float closestNodeDistSqr = float.MaxValue;
int closestNodeIndex = -1;
@@ -473,7 +530,10 @@ namespace Barotrauma.Items.Components
AddNodesBetweenPoints(currPos, targetPos, 0.25f, ref parentNodeIndex);
nodes.Add(new Node(targetPos, parentNodeIndex));
entitiesInRange.RemoveAt(closestIndex);
charactersInRange.Add((character, nodes[parentNodeIndex]));
if (!charactersInRange.Any(c => c.character == character))
{
charactersInRange.Add((character, nodes[parentNodeIndex]));
}
FindNodes(entitiesInRange, targetPos, nodes.Count - 1, currentRange);
}
}
@@ -483,7 +543,7 @@ namespace Barotrauma.Items.Components
Vector2 diff = targetPos - currPos;
float dist = diff.Length();
Vector2 normal = new Vector2(-diff.Y, diff.X) / dist;
for (float x = MaxNodeDistance; x < dist - MaxNodeDistance; x += MaxNodeDistance * Rand.Range(0.5f, 1.5f))
for (float x = MaxNodeDistance; x < dist - MaxNodeDistance; x += MaxNodeDistance * Rand.Range(0.5f, 1.0f))
{
//0 at the edges, 1 at the center
float normalOffset = (0.5f - Math.Abs(x / dist - 0.5f)) * 2.0f;
@@ -67,11 +67,18 @@ namespace Barotrauma.Items.Components
[Serialize(true, IsPropertySaveable.Yes, "")]
public bool CanSpawn { get; set; } = true;
[Editable, Serialize(false, IsPropertySaveable.Yes, "")]
public bool PreloadCharacter { get; set; }
private float spawnTimer;
private float? spawnTimerGoal;
private int spawnedAmount = 0;
private Character? preloadedCharacter;
private bool preloadInitiated;
public EntitySpawnerComponent(Item item, ContentXElement element) : base(item, element)
{
IsActive = true;
@@ -103,12 +110,21 @@ namespace Barotrauma.Items.Components
}
}
}
base.OnItemLoaded();
}
public override void Update(float deltaTime, Camera cam)
{
if (PreloadCharacter && !Screen.Selected.IsEditor && !preloadInitiated)
{
SpawnCharacter(Vector2.Zero, onSpawn: (Character c) =>
{
preloadedCharacter = c;
c.DisabledByEvent = true;
});
preloadInitiated = true;
return;
}
base.Update(deltaTime, cam);
item.SendSignal(CanSpawn ? "1" : "0", "state_out");
@@ -269,10 +285,18 @@ namespace Barotrauma.Items.Components
{
if (!string.IsNullOrWhiteSpace(SpeciesName))
{
Identifier[] allSpecies = SpeciesName.Split(',').Select(s => s.Trim()).ToIdentifiers().ToArray();
Identifier species = allSpecies.GetRandomUnsynced();
Entity.Spawner?.AddCharacterToSpawnQueue(species, pos);
spawnedAmount++;
if (preloadedCharacter != null)
{
preloadedCharacter.DisabledByEvent = false;
preloadedCharacter.TeleportTo(pos);
preloadedCharacter = null;
spawnedAmount++;
}
else
{
SpawnCharacter(pos);
spawnedAmount++;
}
}
else if (!string.IsNullOrWhiteSpace(ItemIdentifier))
{
@@ -291,5 +315,15 @@ namespace Barotrauma.Items.Components
}
}
}
private void SpawnCharacter(Vector2 pos, Action<Character>? onSpawn = null)
{
if (!string.IsNullOrWhiteSpace(SpeciesName))
{
Identifier[] allSpecies = SpeciesName.Split(',').Select(s => s.Trim()).ToIdentifiers().ToArray();
Identifier species = allSpecies.GetRandomUnsynced();
Entity.Spawner?.AddCharacterToSpawnQueue(species, pos, onSpawn);
}
}
}
}
@@ -127,7 +127,7 @@ namespace Barotrauma.Items.Components
set { attachedByDefault = value; }
}
[Editable, Serialize("0.0,0.0", IsPropertySaveable.No, description: "The position the character holds the item at (in pixels, as an offset from the character's shoulder)."+
[Serialize("0.0,0.0", IsPropertySaveable.No, description: "The position the character holds the item at (in pixels, as an offset from the character's shoulder)."+
" For example, a value of 10,-100 would make the character hold the item 100 pixels below the shoulder and 10 pixels forwards.")]
public Vector2 HoldPos
{
@@ -143,7 +143,11 @@ namespace Barotrauma.Items.Components
set { aimPos = ConvertUnits.ToSimUnits(value); }
}
#if DEBUG
[Editable, Serialize(0.0f, IsPropertySaveable.No, description: "The rotation at which the character holds the item (in degrees, relative to the rotation of the character's hand).")]
#else
[Serialize(0.0f, IsPropertySaveable.No)]
#endif
public float HoldAngle
{
get { return MathHelper.ToDegrees(holdAngle); }
@@ -151,23 +155,50 @@ namespace Barotrauma.Items.Components
}
private Vector2 swingAmount;
#if DEBUG
[Editable, Serialize("0.0,0.0", IsPropertySaveable.No, description: "How much the item swings around when aiming/holding it (in pixels, as an offset from AimPos/HoldPos).")]
#else
[Serialize("0.0,0.0", IsPropertySaveable.No)]
#endif
public Vector2 SwingAmount
{
get { return ConvertUnits.ToDisplayUnits(swingAmount); }
set { swingAmount = ConvertUnits.ToSimUnits(value); }
}
#if DEBUG
[Editable, Serialize(0.0f, IsPropertySaveable.No, description: "How fast the item swings around when aiming/holding it (only valid if SwingAmount is set).")]
#else
[Serialize(0.0f, IsPropertySaveable.No)]
#endif
public float SwingSpeed { get; set; }
#if DEBUG
[Editable, Serialize(false, IsPropertySaveable.No, description: "Should the item swing around when it's being held.")]
#else
[Serialize(false, IsPropertySaveable.No)]
#endif
public bool SwingWhenHolding { get; set; }
#if DEBUG
[Editable, Serialize(false, IsPropertySaveable.No, description: "Should the item swing around when it's being aimed.")]
#else
[Serialize(false, IsPropertySaveable.No)]
#endif
public bool SwingWhenAiming { get; set; }
#if DEBUG
[Editable, Serialize(false, IsPropertySaveable.No, description: "Should the item swing around when it's being used (for example, when firing a weapon or a welding tool).")]
#else
[Serialize(false, IsPropertySaveable.No)]
#endif
public bool SwingWhenUsing { get; set; }
#if DEBUG
[Editable, Serialize(false, IsPropertySaveable.No)]
#else
[Serialize(false, IsPropertySaveable.No)]
#endif
public bool DisableHeadRotation { get; set; }
[ConditionallyEditable(ConditionallyEditable.ConditionType.Attachable, MinValueFloat = 0.0f, MaxValueFloat = 0.999f, DecimalCount = 3), Serialize(0.55f, IsPropertySaveable.No, description: "Sprite depth that's used when the item is NOT attached to a wall.")]
@@ -185,7 +216,7 @@ namespace Barotrauma.Items.Components
Pusher = null;
if (element.GetAttributeBool("blocksplayers", false))
{
Pusher = new PhysicsBody(item.body.width, item.body.height, item.body.radius,
Pusher = new PhysicsBody(item.body.Width, item.body.Height, item.body.Radius,
item.body.Density,
BodyType.Dynamic,
Physics.CollisionItemBlocking,
@@ -386,10 +417,11 @@ namespace Barotrauma.Items.Components
return;
}
//cannot hold and wear an item at the same time
//(unless the slot in which it's held and worn are equal - e.g. a suit with built-in tool or weapon on one hand)
var wearable = item.GetComponent<Wearable>();
if (wearable != null)
if (wearable != null && !wearable.AllowedSlots.SequenceEqual(allowedSlots))
{
//cannot hold and wear an item at the same time
wearable.Unequip(character);
}
@@ -650,11 +682,10 @@ namespace Barotrauma.Items.Components
return false;
}
Vector2 attachPos = GetAttachPosition(character, useWorldCoordinates: true);
Structure attachTarget = Structure.GetAttachTarget(attachPos);
Submarine attachSubmarine = Structure.GetAttachTarget(attachPos)?.Submarine ?? item.Submarine;
int maxAttachableCount = (int)character.Info.GetSavedStatValue(StatTypes.MaxAttachableCount, item.Prefab.Identifier);
int currentlyAttachedCount = Item.ItemList.Count(
i => i.Submarine == attachTarget?.Submarine && i.GetComponent<Holdable>() is Holdable holdable && holdable.Attached && i.Prefab.Identifier == item.Prefab.Identifier);
i => i.Submarine == attachSubmarine && i.GetComponent<Holdable>() is Holdable holdable && holdable.Attached && i.Prefab.Identifier == item.Prefab.Identifier);
if (maxAttachableCount == 0)
{
#if CLIENT
@@ -812,10 +843,18 @@ namespace Barotrauma.Items.Components
public override void Update(float deltaTime, Camera cam)
{
if (item.body == null || !item.body.Enabled) { return; }
Character owner = picker ?? item.GetRootInventoryOwner() as Character;
if (owner != null)
{
ApplyStatusEffects(ActionType.OnActive, deltaTime, owner);
}
if (picker == null || !picker.HasEquippedItem(item))
{
if (Pusher != null) { Pusher.Enabled = false; }
if (attachTargetCell == null) { IsActive = false; }
if (attachTargetCell == null && owner == null) { IsActive = false; }
return;
}
@@ -824,23 +863,7 @@ namespace Barotrauma.Items.Components
Drawable = true;
}
Vector2 swing = Vector2.Zero;
if (swingAmount != Vector2.Zero && !picker.IsUnconscious && picker.Stun <= 0.0f)
{
swingState += deltaTime;
swingState %= 1.0f;
if (SwingWhenHolding ||
(SwingWhenAiming && picker.IsKeyDown(InputType.Aim)) ||
(SwingWhenUsing && picker.IsKeyDown(InputType.Aim) && picker.IsKeyDown(InputType.Shoot)))
{
swing = swingAmount * new Vector2(
PerlinNoise.GetPerlin(swingState * SwingSpeed * 0.1f, swingState * SwingSpeed * 0.1f) - 0.5f,
PerlinNoise.GetPerlin(swingState * SwingSpeed * 0.1f + 0.5f, swingState * SwingSpeed * 0.1f + 0.5f) - 0.5f);
}
}
ApplyStatusEffects(ActionType.OnActive, deltaTime, picker);
UpdateSwingPos(deltaTime, out Vector2 swingPos);
if (item.body.Dir != picker.AnimController.Dir)
{
item.FlipX(relativeToSub: false);
@@ -853,7 +876,7 @@ namespace Barotrauma.Items.Components
scaledHandlePos[0] = handlePos[0] * item.Scale;
scaledHandlePos[1] = handlePos[1] * item.Scale;
bool aim = picker.IsKeyDown(InputType.Aim) && aimPos != Vector2.Zero && picker.CanAim;
picker.AnimController.HoldItem(deltaTime, item, scaledHandlePos, holdPos + swing, aimPos + swing, aim, holdAngle);
picker.AnimController.HoldItem(deltaTime, item, scaledHandlePos, holdPos + swingPos, aimPos + swingPos, aim, holdAngle);
if (!aim)
{
var rope = GetRope();
@@ -890,6 +913,24 @@ namespace Barotrauma.Items.Components
}
}
public void UpdateSwingPos(float deltaTime, out Vector2 swingPos)
{
swingPos = Vector2.Zero;
if (swingAmount != Vector2.Zero && !picker.IsUnconscious && picker.Stun <= 0.0f)
{
swingState += deltaTime;
swingState %= 1.0f;
if (SwingWhenHolding ||
(SwingWhenAiming && picker.IsKeyDown(InputType.Aim)) ||
(SwingWhenUsing && picker.IsKeyDown(InputType.Aim) && picker.IsKeyDown(InputType.Shoot)))
{
swingPos = swingAmount * new Vector2(
PerlinNoise.GetPerlin(swingState * SwingSpeed * 0.1f, swingState * SwingSpeed * 0.1f) - 0.5f,
PerlinNoise.GetPerlin(swingState * SwingSpeed * 0.1f + 0.5f, swingState * SwingSpeed * 0.1f + 0.5f) - 0.5f);
}
}
}
public override void ReceiveSignal(Signal signal, Connection connection)
{
//do nothing
@@ -128,7 +128,7 @@ namespace Barotrauma.Items.Components
if (body != null)
{
trigger = new PhysicsBody(body.width, body.height, body.radius,
trigger = new PhysicsBody(body.Width, body.Height, body.Radius,
body.Density,
BodyType.Static,
Physics.CollisionWall,
@@ -214,8 +214,9 @@ namespace Barotrauma.Items.Components
bool aim = item.RequireAimToUse && picker.AllowInput && picker.IsKeyDown(InputType.Aim) && reloadTimer <= 0 && picker.CanAim;
if (aim)
{
UpdateSwingPos(deltaTime, out Vector2 swingPos);
hitPos = MathUtils.WrapAnglePi(Math.Min(hitPos + deltaTime * 3f, MathHelper.PiOver4));
ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, aim: false, hitPos, holdAngle + hitPos, aimMelee: true);
ac.HoldItem(deltaTime, item, handlePos, aimPos + swingPos, Vector2.Zero, aim: false, hitPos, holdAngle + hitPos, aimMelee: true);
if (ac.InWater)
{
ac.LockFlippingUntil = (float)Timing.TotalTime + Reload;
@@ -392,36 +393,37 @@ namespace Barotrauma.Items.Components
float damageMultiplier = 1 + User.GetStatValue(StatTypes.MeleeAttackMultiplier);
damageMultiplier *= 1.0f + item.GetQualityModifier(Quality.StatType.StrikingPowerMultiplier);
Character user = User;
Limb targetLimb = target.UserData as Limb;
Character targetCharacter = targetLimb?.character ?? target.UserData as Character;
if (Attack != null)
{
Attack.SetUser(User);
Attack.SetUser(user);
Attack.DamageMultiplier = damageMultiplier;
if (targetLimb != null)
{
if (targetLimb.character.Removed) { return; }
targetLimb.character.LastDamageSource = item;
Attack.DoDamageToLimb(User, targetLimb, item.WorldPosition, 1.0f);
Attack.DoDamageToLimb(user, targetLimb, item.WorldPosition, 1.0f);
}
else if (targetCharacter != null)
{
if (targetCharacter.Removed) { return; }
targetCharacter.LastDamageSource = item;
Attack.DoDamage(User, targetCharacter, item.WorldPosition, 1.0f);
Attack.DoDamage(user, targetCharacter, item.WorldPosition, 1.0f);
}
else if ((target.UserData as Structure ?? targetFixture.UserData as Structure) is Structure targetStructure)
{
if (targetStructure.Removed) { return; }
Attack.DoDamage(User, targetStructure, item.WorldPosition, 1.0f);
Attack.DoDamage(user, targetStructure, item.WorldPosition, 1.0f);
}
else if (target.UserData is Item targetItem && targetItem.Prefab.DamagedByMeleeWeapons && targetItem.Condition > 0)
{
if (targetItem.Removed) { return; }
var attackResult = Attack.DoDamage(User, targetItem, item.WorldPosition, 1.0f);
var attackResult = Attack.DoDamage(user, targetItem, item.WorldPosition, 1.0f);
#if CLIENT
if (attackResult.Damage > 0.0f)
if (attackResult.Damage > 0.0f && targetItem.Prefab.ShowHealthBar)
{
Character.Controlled?.UpdateHUDProgressBar(targetItem,
targetItem.WorldPosition,
@@ -435,7 +437,7 @@ namespace Barotrauma.Items.Components
else if (target.UserData is Holdable holdable && holdable.CanPush)
{
if (holdable.Item.Removed) { return; }
Attack.DoDamage(User, holdable.Item, item.WorldPosition, 1.0f);
Attack.DoDamage(user, holdable.Item, item.WorldPosition, 1.0f);
RestoreCollision();
hitting = false;
User = null;
@@ -448,29 +450,32 @@ namespace Barotrauma.Items.Components
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return; }
bool success = Rand.Range(0.0f, 0.5f) < DegreeOfSuccess(User);
#if SERVER
if (GameMain.Server != null && targetCharacter != null) //TODO: Log structure hits
ActionType conditionalActionType = ActionType.OnSuccess;
if (user != null && Rand.Range(0.0f, 0.5f) > DegreeOfSuccess(user))
{
GameMain.Server.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(
success ? ActionType.OnUse : ActionType.OnFailure,
targetItemComponent: null,
targetCharacter, targetLimb));
string logStr = picker?.LogName + " used " + item.Name;
if (item.ContainedItems != null && item.ContainedItems.Any())
{
logStr += " (" + string.Join(", ", item.ContainedItems.Select(i => i?.Name)) + ")";
}
logStr += " on " + targetCharacter.LogName + ".";
Networking.GameServer.Log(logStr, Networking.ServerLog.MessageType.Attack);
conditionalActionType = ActionType.OnFailure;
}
if (GameMain.NetworkMember is { IsServer: true } server && targetCharacter != null)
{
server.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(conditionalActionType, targetItemComponent: null, targetCharacter, targetLimb));
server.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(ActionType.OnUse, targetItemComponent: null, targetCharacter, targetLimb));
#if SERVER
if (GameMain.Server != null) //TODO: Log structure hits
{
string logStr = picker?.LogName + " used " + item.Name;
if (item.ContainedItems != null && item.ContainedItems.Any())
{
logStr += " (" + string.Join(", ", item.ContainedItems.Select(i => i?.Name)) + ")";
}
logStr += " on " + targetCharacter.LogName + ".";
Networking.GameServer.Log(logStr, Networking.ServerLog.MessageType.Attack);
}
#endif
}
#endif
if (targetCharacter != null) //TODO: Allow OnUse to happen on structures too maybe??
{
ApplyStatusEffects(success ? ActionType.OnUse : ActionType.OnFailure, 1.0f, targetCharacter, targetLimb, user: User, afflictionMultiplier: damageMultiplier);
ApplyStatusEffects(conditionalActionType, 1.0f, targetCharacter, targetLimb, user: user, afflictionMultiplier: damageMultiplier);
ApplyStatusEffects(ActionType.OnUse, 1.0f, targetCharacter, targetLimb, user: user, afflictionMultiplier: damageMultiplier);
}
if (DeleteOnUse)
@@ -23,6 +23,8 @@ namespace Barotrauma.Items.Components
[Serialize(0.0f, IsPropertySaveable.No, description: "The force to apply to the user's body."), Editable(MinValueFloat = -1000.0f, MaxValueFloat = 1000.0f)]
public float Force { get; set; }
[Serialize(true, IsPropertySaveable.No, description: "If the item is held in RightHand or LeftHand, apply extra force there")]
public bool ApplyToHands { get; set; }
#if CLIENT
private string particles;
[Serialize("", IsPropertySaveable.No, description: "The name of the particle prefab the item emits when used.")]
@@ -70,13 +72,16 @@ namespace Barotrauma.Items.Components
character.AnimController.Collider.ApplyForce(propulsion);
if (character.Inventory.IsInLimbSlot(item, InvSlotType.RightHand))
{
character.AnimController.GetLimb(LimbType.RightHand)?.body.ApplyForce(propulsion);
}
if (character.Inventory.IsInLimbSlot(item, InvSlotType.LeftHand))
{
character.AnimController.GetLimb(LimbType.LeftHand)?.body.ApplyForce(propulsion);
if (ApplyToHands)
{
if (character.Inventory.IsInLimbSlot(item, InvSlotType.RightHand))
{
character.AnimController.GetLimb(LimbType.RightHand)?.body.ApplyForce(propulsion);
}
if (character.Inventory.IsInLimbSlot(item, InvSlotType.LeftHand))
{
character.AnimController.GetLimb(LimbType.LeftHand)?.body.ApplyForce(propulsion);
}
}
#if CLIENT
@@ -32,6 +32,20 @@ namespace Barotrauma.Items.Components
set { reload = Math.Max(value, 0.0f); }
}
[Serialize(0f, IsPropertySaveable.No, description: "Weapons skill requirement to reload at normal speed.")]
public float ReloadSkillRequirement
{
get;
set;
}
[Serialize(1.0f, IsPropertySaveable.No, description: "Reload time at 0 skill level. Reload time scales with skill level up to the Weapons skill requirement.")]
public float ReloadNoSkill
{
get;
set;
}
[Serialize(false, IsPropertySaveable.No, description: "Tells the AI to hold the trigger down when it uses this weapon")]
public bool HoldTrigger
{
@@ -39,7 +53,7 @@ namespace Barotrauma.Items.Components
set;
}
[Serialize(1, IsPropertySaveable.No, description: "How projectiles the weapon launches when fired once.")]
[Serialize(1, IsPropertySaveable.No, description: "How many projectiles the weapon launches when fired once.")]
public int ProjectileCount
{
get;
@@ -60,6 +74,23 @@ namespace Barotrauma.Items.Components
set;
}
[Serialize(0.0f, IsPropertySaveable.No, description: "The impulse applied to the physics body of the projectile (the higher the impulse, the faster the projectiles are launched). Sum of weapon + projectile.")]
public float LaunchImpulse
{
get;
set;
}
[Serialize(0.0f, IsPropertySaveable.Yes, description: "Percentage of damage mitigation ignored when hitting armored body parts (deflecting limbs). Sum of weapon + projectile."), Editable(MinValueFloat = 0.0f, MaxValueFloat = 1f)]
public float Penetration { get; private set; }
[Serialize(1f, IsPropertySaveable.Yes, description: "Weapon's damage modifier")]
public float WeaponDamageModifier
{
get;
private set;
}
[Serialize(0f, IsPropertySaveable.Yes, description: "The time required for a charge-type turret to charge up before able to fire.")]
public float MaxChargeTime
{
@@ -67,6 +98,9 @@ namespace Barotrauma.Items.Components
private set;
}
private readonly IReadOnlySet<Identifier> suitableProjectiles;
private enum ChargingState
{
Inactive,
@@ -99,6 +133,11 @@ namespace Barotrauma.Items.Components
// TODO: should define this in xml if we have ranged weapons that don't require aim to use
item.RequireAimToUse = true;
characterUsable = true;
suitableProjectiles = element.GetAttributeIdentifierArray(nameof(suitableProjectiles), Array.Empty<Identifier>()).ToHashSet();
if (ReloadSkillRequirement > 0 && ReloadNoSkill <= reload)
{
DebugConsole.AddWarning($"Invalid XML at {item.Name}: ReloadNoSkill is lower or equal than it's reload skill, despite having ReloadSkillRequirement.");
}
InitProjSpecific(element);
}
@@ -167,7 +206,15 @@ namespace Barotrauma.Items.Components
if (currentChargeTime < MaxChargeTime) { return false; }
IsActive = true;
ReloadTimer = reload / (1 + character?.GetStatValue(StatTypes.RangedAttackSpeed) ?? 0f);
float baseReloadTime = reload;
float weaponSkill = character.GetSkillLevel("weapons");
if (ReloadSkillRequirement > 0 && ReloadNoSkill > reload && weaponSkill < ReloadSkillRequirement)
{
//Examples, assuming 40 weapon skill required: 1 - 40/40 = 0 ... 1 - 0/40 = 1 ... 1 - 20 / 40 = 0.5
float reloadFailure = MathHelper.Clamp(1 - (weaponSkill / ReloadSkillRequirement), 0, 1);
baseReloadTime = MathHelper.Lerp(reload, ReloadNoSkill, reloadFailure);
}
ReloadTimer = baseReloadTime / (1 + character?.GetStatValue(StatTypes.RangedAttackSpeed) ?? 0f);
currentChargeTime = 0f;
if (character != null)
@@ -218,9 +265,9 @@ namespace Barotrauma.Items.Components
{
lastProjectile?.Item.GetComponent<Rope>()?.Snap();
}
float damageMultiplier = 1f + item.GetQualityModifier(Quality.StatType.FirepowerMultiplier);
float damageMultiplier = (1f + item.GetQualityModifier(Quality.StatType.FirepowerMultiplier)) * WeaponDamageModifier;
projectile.Launcher = item;
projectile.Shoot(character, character.AnimController.AimSourceSimPos, barrelPos, rotation + spread, ignoredBodies: ignoredBodies.ToList(), createNetworkEvent: false, damageMultiplier);
projectile.Shoot(character, character.AnimController.AimSourceSimPos, barrelPos, rotation + spread, ignoredBodies: ignoredBodies.ToList(), createNetworkEvent: false, damageMultiplier, LaunchImpulse);
projectile.Item.GetComponent<Rope>()?.Attach(Item, projectile.Item);
if (i == 0)
{
@@ -244,39 +291,41 @@ namespace Barotrauma.Items.Components
public Projectile FindProjectile(bool triggerOnUseOnContainers = false)
{
var containedItems = item.OwnInventory?.AllItemsMod;
if (containedItems == null) { return null; }
foreach (Item item in containedItems)
foreach (ItemContainer container in item.GetComponents<ItemContainer>())
{
if (item == null) { continue; }
Projectile projectile = item.GetComponent<Projectile>();
if (projectile != null) { return projectile; }
}
//projectile not found, see if one of the contained items contains projectiles
foreach (Item it in containedItems)
{
if (it == null) { continue; }
var containedSubItems = it.OwnInventory?.AllItemsMod;
if (containedSubItems == null) { continue; }
foreach (Item subItem in containedSubItems)
foreach (Item containedItem in container.Inventory.AllItemsMod)
{
if (subItem == null) { continue; }
Projectile projectile = subItem.GetComponent<Projectile>();
//apply OnUse statuseffects to the container in case it has to react to it somehow
//(play a sound, spawn more projectiles, reduce condition...)
if (triggerOnUseOnContainers && subItem.Condition > 0.0f)
if (containedItem == null) { continue; }
Projectile projectile = containedItem.GetComponent<Projectile>();
if (IsSuitableProjectile(projectile)) { return projectile; }
//projectile not found, see if the contained item contains projectiles
var containedSubItems = containedItem.OwnInventory?.AllItemsMod;
if (containedSubItems == null) { continue; }
foreach (Item subItem in containedSubItems)
{
subItem.GetComponent<ItemContainer>()?.Item.ApplyStatusEffects(ActionType.OnUse, 1.0f);
}
if (projectile != null) { return projectile; }
if (subItem == null) { continue; }
Projectile subProjectile = subItem.GetComponent<Projectile>();
//apply OnUse statuseffects to the container in case it has to react to it somehow
//(play a sound, spawn more projectiles, reduce condition...)
if (triggerOnUseOnContainers && subItem.Condition > 0.0f)
{
subItem.GetComponent<ItemContainer>()?.Item.ApplyStatusEffects(ActionType.OnUse, 1.0f);
}
if (IsSuitableProjectile(subProjectile)) { return subProjectile; }
}
}
}
return null;
}
private bool IsSuitableProjectile(Projectile projectile)
{
if (projectile?.Item == null) { return false; }
if (!suitableProjectiles.Any()) { return true; }
return suitableProjectiles.Any(s => projectile.Item.Prefab.Identifier == s || projectile.Item.HasTag(s));
}
partial void LaunchProjSpecific();
}
class AbilityRangedWeapon : AbilityObject, IAbilityItem
@@ -636,11 +636,14 @@ namespace Barotrauma.Items.Components
float addedDetachTime = deltaTime * (1f + user.GetStatValue(StatTypes.RepairToolDeattachTimeMultiplier)) * (1f + item.GetQualityModifier(Quality.StatType.RepairToolDeattachTimeMultiplier));
levelResource.DeattachTimer += addedDetachTime;
#if CLIENT
Character.Controlled?.UpdateHUDProgressBar(
this,
targetItem.WorldPosition,
levelResource.DeattachTimer / levelResource.DeattachDuration,
GUIStyle.Red, GUIStyle.Green, "progressbar.deattaching");
if (targetItem.Prefab.ShowHealthBar)
{
Character.Controlled?.UpdateHUDProgressBar(
this,
targetItem.WorldPosition,
levelResource.DeattachTimer / levelResource.DeattachDuration,
GUIStyle.Red, GUIStyle.Green, "progressbar.deattaching");
}
#endif
FixItemProjSpecific(user, deltaTime, targetItem, showProgressBar: false);
return true;
@@ -689,7 +692,7 @@ namespace Barotrauma.Items.Components
private float repairTimer;
private Gap previousGap;
private readonly float repairTimeOut = 5;
public override bool AIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
public override bool CrewAIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
{
if (!(objective.OperateTarget is Gap leak))
{
@@ -1,17 +1,26 @@
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System.Linq;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
class Throwable : Holdable
{
private float throwPos;
private bool throwing, throwDone;
enum ThrowState
{
None,
Initiated,
Throwing
}
private const float ThrowAngleStart = -MathHelper.PiOver2, ThrowAngleEnd = MathHelper.PiOver2;
private float throwAngle = ThrowAngleStart;
private bool midAir;
private ThrowState throwState;
//continuous collision detection is used while the item is moving faster than this
const float ContinuousCollisionThreshold = 5.0f;
@@ -27,7 +36,6 @@ namespace Barotrauma.Items.Components
public Throwable(Item item, ContentXElement element)
: base(item, element)
{
//throwForce = ToolBox.GetAttributeFloat(element, "throwforce", 1.0f);
if (aimPos == Vector2.Zero)
{
aimPos = new Vector2(0.6f, 0.1f);
@@ -36,22 +44,21 @@ namespace Barotrauma.Items.Components
public override bool Use(float deltaTime, Character character = null)
{
return characterUsable || character == null; //We do the actual throwing in Aim because Use might be used by chems
//actual throwing logic is handled in Update
return characterUsable || character == null;
}
public override bool SecondaryUse(float deltaTime, Character character = null)
{
if (!throwDone) return false; //This should only be triggered in update
throwDone = false;
return true;
//actual throwing logic is handled in Update - SecondaryUse only triggers when the item is thrown
return false;
}
public override void Drop(Character dropper)
{
base.Drop(dropper);
throwing = false;
throwPos = 0.0f;
throwState = ThrowState.None;
throwAngle = ThrowAngleStart;
}
public override void UpdateBroken(float deltaTime, Camera cam)
@@ -100,13 +107,22 @@ namespace Barotrauma.Items.Components
return;
}
if (picker.IsKeyDown(InputType.Aim) && picker.IsKeyHit(InputType.Shoot)) { throwing = true; }
if (!picker.IsKeyDown(InputType.Aim) && !throwing) { throwPos = 0.0f; }
bool aim = picker.IsKeyDown(InputType.Aim) && picker.CanAim;
if (throwState != ThrowState.Throwing)
{
if (picker.IsKeyDown(InputType.Aim))
{
if (picker.IsKeyDown(InputType.Shoot)) { throwState = ThrowState.Initiated; }
}
else if (throwState != ThrowState.Initiated)
{
throwAngle = ThrowAngleStart;
}
}
bool aim = picker.IsKeyDown(InputType.Aim) && picker.CanAim;
if (picker.IsDead || !picker.AllowInput)
{
throwing = false;
throwState = ThrowState.None;
aim = false;
}
@@ -124,25 +140,29 @@ namespace Barotrauma.Items.Components
item.Submarine = picker.Submarine;
if (!throwing)
if (throwState != ThrowState.Throwing)
{
if (aim)
if (aim || throwState == ThrowState.Initiated)
{
throwPos = MathUtils.WrapAnglePi(System.Math.Min(throwPos + deltaTime * 5.0f, MathHelper.PiOver2));
ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, aim: false, throwPos);
throwAngle = System.Math.Min(throwAngle + deltaTime * 8.0f, ThrowAngleEnd);
ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, aim: false, throwAngle);
if (throwAngle >= ThrowAngleEnd && throwState == ThrowState.Initiated)
{
throwState = ThrowState.Throwing;
}
}
else
{
throwPos = 0;
throwAngle = ThrowAngleStart;
ac.HoldItem(deltaTime, item, handlePos, holdPos, Vector2.Zero, aim: false, holdAngle);
}
}
else
{
throwPos = MathUtils.WrapAnglePi(throwPos - deltaTime * 15.0f);
ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, aim: false, throwPos);
throwAngle = MathUtils.WrapAnglePi(throwAngle - deltaTime * 15.0f);
ac.HoldItem(deltaTime, item, handlePos, aimPos, Vector2.Zero, aim: false, throwAngle);
if (throwPos < 0)
if (throwAngle < 0)
{
Vector2 throwVector = Vector2.Normalize(picker.CursorWorldPosition - picker.WorldPosition);
//throw upwards if cursor is at the position of the character
@@ -180,8 +200,7 @@ namespace Barotrauma.Items.Components
Limb rightHand = ac.GetLimb(LimbType.RightHand);
item.body.AngularVelocity = rightHand.body.AngularVelocity;
throwPos = 0;
throwDone = true;
throwAngle = ThrowAngleStart;
IsActive = true;
if (GameMain.NetworkMember is { IsServer: true })
@@ -193,7 +212,7 @@ namespace Barotrauma.Items.Components
//Stun grenades, flares, etc. all have their throw-related things handled in "onSecondaryUse"
ApplyStatusEffects(ActionType.OnSecondaryUse, deltaTime, CurrentThrower, user: CurrentThrower);
}
throwing = false;
throwState = ThrowState.None;
}
}
}
@@ -111,6 +111,13 @@ namespace Barotrauma.Items.Components
private bool drawable = true;
[Serialize(PropertyConditional.Comparison.And, IsPropertySaveable.No)]
public PropertyConditional.Comparison IsActiveConditionalComparison
{
get;
set;
}
public List<PropertyConditional> IsActiveConditionals;
public bool Drawable
@@ -241,6 +248,11 @@ namespace Barotrauma.Items.Components
[Serialize(0, IsPropertySaveable.Yes, alwaysUseInstanceValues: true)]
public int ManuallySelectedSound { get; private set; }
/// <summary>
/// Can be used by status effects or conditionals to the speed of the item
/// </summary>
public float Speed => item.Speed;
public ItemComponent(Item item, ContentXElement element)
{
this.item = item;
@@ -431,7 +443,7 @@ namespace Barotrauma.Items.Components
public virtual void Drop(Character dropper) { }
/// <returns>true if the operation was completed</returns>
public virtual bool AIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
public virtual bool CrewAIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
{
return false;
}
@@ -814,7 +826,7 @@ namespace Barotrauma.Items.Components
}
}
public void ApplyStatusEffects(ActionType type, float deltaTime, Character character = null, Limb targetLimb = null, Entity useTarget = null, Character user = null, Vector2? worldPosition = null, float afflictionMultiplier = 1.0f, float applyOnUserFraction = 0.0f)
public void ApplyStatusEffects(ActionType type, float deltaTime, Character character = null, Limb targetLimb = null, Entity useTarget = null, Character user = null, Vector2? worldPosition = null, float afflictionMultiplier = 1.0f)
{
if (statusEffectLists == null) { return; }
@@ -828,11 +840,6 @@ namespace Barotrauma.Items.Components
if (user != null) { effect.SetUser(user); }
effect.AfflictionMultiplier = afflictionMultiplier;
item.ApplyStatusEffect(effect, type, deltaTime, character, targetLimb, useTarget, isNetworkEvent: false, checkCondition: false, worldPosition);
if (user != null && applyOnUserFraction > 0.0f && effect.HasTargetType(StatusEffect.TargetType.Character))
{
effect.AfflictionMultiplier = applyOnUserFraction;
item.ApplyStatusEffect(effect, type, deltaTime, user, targetLimb == null ? null : user.AnimController.GetLimb(targetLimb.type), useTarget, false, false, worldPosition);
}
effect.AfflictionMultiplier = 1.0f;
reducesCondition |= effect.ReducesItemCondition();
}
@@ -65,8 +65,16 @@ namespace Barotrauma.Items.Components
public int Capacity
{
get { return capacity; }
set { capacity = Math.Max(value, 0); }
private set
{
capacity = Math.Max(value, 0);
MainContainerCapacity = value;
}
}
/// <summary>
/// The capacity of the main container without taking the sub containers into account. Only differs when there's a sub container defined for the component.
/// </summary>
public int MainContainerCapacity { get; private set; }
//how many items can be contained
private int maxStackSize;
@@ -229,6 +237,9 @@ namespace Barotrauma.Items.Components
public ImmutableHashSet<Identifier> ContainableItemIdentifiers => containableItemIdentifiers;
public List<RelatedItem> ContainableItems { get; }
public List<RelatedItem> AllSubContainableItems { get; }
public readonly bool HasSubContainers;
public ItemContainer(Item item, ContentXElement element)
: base(item, element)
@@ -251,6 +262,7 @@ namespace Barotrauma.Items.Components
break;
case "subcontainer":
totalCapacity += subElement.GetAttributeInt("capacity", 1);
HasSubContainers = true;
break;
}
}
@@ -270,7 +282,7 @@ namespace Barotrauma.Items.Components
int subCapacity = subElement.GetAttributeInt("capacity", 1);
int subMaxStackSize = subElement.GetAttributeInt("maxstacksize", maxStackSize);
List<RelatedItem> subContainableItems = null;
var subContainableItems = new List<RelatedItem>();
foreach (var subSubElement in subElement.Elements())
{
if (subSubElement.Name.ToString().ToLowerInvariant() != "containable") { continue; }
@@ -281,8 +293,9 @@ namespace Barotrauma.Items.Components
DebugConsole.ThrowError("Error in item config \"" + item.ConfigFilePath + "\" - containable with no identifiers.");
continue;
}
subContainableItems ??= new List<RelatedItem>();
subContainableItems.Add(containable);
AllSubContainableItems ??= new List<RelatedItem>();
AllSubContainableItems.Add(containable);
}
for (int i = subContainerIndex; i < subContainerIndex + subCapacity; i++)
@@ -357,6 +370,14 @@ namespace Barotrauma.Items.Components
//no need to Update() if this item has no statuseffects and no physics body
IsActive = activeContainedItems.Count > 0 || Inventory.AllItems.Any(it => it.body != null);
if (IsActive && item.GetRootInventoryOwner() is Character owner &&
owner.HasEquippedItem(item, predicate: slot => slot.HasFlag(InvSlotType.LeftHand) || slot.HasFlag(InvSlotType.RightHand)))
{
// Set the contained items active if there's an item inserted inside the container. Enables e.g. the rifle flashlight when it's attached to the rifle (put inside of it).
SetContainedActive(true);
}
OnContainedItemsChanged.Invoke(this);
}
@@ -409,6 +430,20 @@ namespace Barotrauma.Items.Components
return false;
}
public override void FlipX(bool relativeToSub)
{
base.FlipX(relativeToSub);
if (HideItems) { return; }
if (item.body == null) { return; }
foreach (Item containedItem in Inventory.AllItems)
{
if (containedItem.body != null && containedItem.body.Enabled && containedItem.body.Dir != item.body.Dir)
{
containedItem.FlipX(relativeToSub);
}
}
}
public override void Update(float deltaTime, Camera cam)
{
if (!string.IsNullOrEmpty(SpawnWithId) && !alwaysContainedItemsSpawned)
@@ -477,7 +512,7 @@ namespace Barotrauma.Items.Components
effect.HasTargetType(StatusEffect.TargetType.NearbyCharacters))
{
targets.Clear();
targets.AddRange(effect.GetNearbyTargets(item.WorldPosition, targets));
effect.AddNearbyTargets(item.WorldPosition, targets);
effect.Apply(ActionType.OnActive, deltaTime, item, targets);
}
}
@@ -582,11 +617,53 @@ namespace Barotrauma.Items.Components
public override void Drop(Character dropper)
{
IsActive = true;
SetContainedActive(false);
}
public override void Equip(Character character)
{
IsActive = true;
if (character != null && character.HasEquippedItem(item, predicate: slot => slot.HasFlag(InvSlotType.LeftHand) || slot.HasFlag(InvSlotType.RightHand)))
{
SetContainedActive(true);
}
}
private void SetContainedActive(bool active)
{
foreach (Item containedItem in Inventory.AllItems)
{
RelatedItem containableItem = FindContainableItem(containedItem);
if (containableItem != null && containableItem.SetActive)
{
foreach (var ic in containedItem.Components)
{
ic.IsActive = active;
}
if (containedItem.body != null)
{
containedItem.body.Enabled = active;
if (active)
{
containedItem.body.PhysEnabled = false;
}
}
}
}
if (active)
{
FlipX(false);
}
}
private RelatedItem FindContainableItem(Item item)
{
var relatedItem = ContainableItems?.FirstOrDefault(ci => ci.MatchesItem(item));
if (relatedItem == null && AllSubContainableItems != null)
{
relatedItem = AllSubContainableItems.FirstOrDefault(ci => ci.MatchesItem(item));
}
return relatedItem;
}
public override void ReceiveSignal(Signal signal, Connection connection)
@@ -604,6 +681,7 @@ namespace Barotrauma.Items.Components
}
}
#warning There's some code duplication here and in DrawContainedItems() method, but it's not straightforward to get rid of it, because of slightly different logic and the usage of draw positions vs. positions etc. Should probably be splitted into smaller methods.
public void SetContainedItemPositions()
{
Vector2 transformedItemPos = ItemPos * item.Scale;
@@ -657,29 +735,70 @@ namespace Barotrauma.Items.Components
transformedItemIntervalHorizontal = Vector2.Transform(transformedItemIntervalHorizontal, transform);
transformedItemPos += item.Position;
}
}
float currentRotation = itemRotation;
if (item.body != null)
{
currentRotation *= item.body.Dir;
currentRotation += item.body.Rotation;
}
else
{
currentRotation += -item.RotationRad;
}
int i = 0;
Vector2 currentItemPos = transformedItemPos;
foreach (Item contained in Inventory.AllItems)
{
Vector2 itemPos = currentItemPos;
var relatedItem = FindContainableItem(contained);
if (relatedItem != null)
{
if (relatedItem.Hide.HasValue && relatedItem.Hide.Value) { continue; }
if (relatedItem.ItemPos.HasValue)
{
Vector2 pos = relatedItem.ItemPos.Value;
if (item.body != null)
{
Matrix transform = Matrix.CreateRotationZ(item.body.Rotation);
pos.X *= item.body.Dir;
itemPos = Vector2.Transform(pos, transform) + item.body.Position;
}
else
{
itemPos = pos;
// This code is aped based on above. Not tested.
if (item.FlippedX)
{
itemPos.X = -itemPos.X;
itemPos.X += item.Rect.Width;
}
if (item.FlippedY)
{
itemPos.Y = -itemPos.Y;
itemPos.Y -= item.Rect.Height;
}
itemPos += new Vector2(item.Rect.X, item.Rect.Y);
if (Math.Abs(item.RotationRad) > 0.01f)
{
Matrix transform = Matrix.CreateRotationZ(item.RotationRad);
itemPos = Vector2.Transform(itemPos - item.Position, transform) + item.Position;
}
}
}
}
if (contained.body != null)
{
try
{
Vector2 simPos = ConvertUnits.ToSimUnits(currentItemPos);
contained.body.FarseerBody.SetTransformIgnoreContacts(ref simPos, currentRotation);
Vector2 simPos = ConvertUnits.ToSimUnits(itemPos);
float rotation = itemRotation;
if (relatedItem != null && relatedItem.Rotation != 0)
{
rotation = MathHelper.ToRadians(relatedItem.Rotation);
}
if (item.body != null)
{
rotation *= item.body.Dir;
rotation += item.body.Rotation;
}
else
{
rotation += -item.RotationRad;
}
contained.body.FarseerBody.SetTransformIgnoreContacts(ref simPos, rotation);
contained.body.SetPrevTransform(contained.body.SimPosition, contained.body.Rotation);
contained.body.UpdateDrawPosition();
}
@@ -695,8 +814,8 @@ namespace Barotrauma.Items.Components
contained.Rect =
new Rectangle(
(int)(currentItemPos.X - contained.Rect.Width / 2.0f),
(int)(currentItemPos.Y + contained.Rect.Height / 2.0f),
(int)(itemPos.X - contained.Rect.Width / 2.0f),
(int)(itemPos.Y + contained.Rect.Height / 2.0f),
contained.Rect.Width, contained.Rect.Height);
contained.Submarine = item.Submarine;
@@ -104,12 +104,14 @@ namespace Barotrauma.Items.Components
// doesn't quite work properly, remaining time changes if tinkering stops
float deconstructionSpeedModifier = userDeconstructorSpeedMultiplier * (1f + tinkeringStrength * TinkeringSpeedIncrease);
float deconstructionSpeed = item.StatManager.GetAdjustedValue(ItemTalentStats.DeconstructorSpeed, DeconstructionSpeed);
if (DeconstructItemsSimultaneously)
{
float deconstructTime = 0.0f;
foreach (Item targetItem in inputContainer.Inventory.AllItems)
{
deconstructTime += targetItem.Prefab.DeconstructTime / (DeconstructionSpeed * deconstructionSpeedModifier);
deconstructTime += targetItem.Prefab.DeconstructTime / (deconstructionSpeed * deconstructionSpeedModifier);
}
progressState = Math.Min(progressTimer / deconstructTime, 1.0f);
@@ -139,7 +141,7 @@ namespace Barotrauma.Items.Components
if (targetItem == null) { return; }
var validDeconstructItems = targetItem.Prefab.DeconstructItems.Where(it => it.IsValidDeconstructor(item)).ToList();
float deconstructTime = validDeconstructItems.Any() ? targetItem.Prefab.DeconstructTime / (DeconstructionSpeed * deconstructionSpeedModifier) : 1.0f;
float deconstructTime = validDeconstructItems.Any() ? targetItem.Prefab.DeconstructTime / (deconstructionSpeed * deconstructionSpeedModifier) : 1.0f;
progressState = Math.Min(progressTimer / deconstructTime, 1.0f);
if (progressTimer > deconstructTime)
@@ -218,7 +220,7 @@ namespace Barotrauma.Items.Components
if (percentageHealth < deconstructProduct.MinCondition || percentageHealth > deconstructProduct.MaxCondition) { return; }
if (!(MapEntityPrefab.Find(null, deconstructProduct.ItemIdentifier) is ItemPrefab itemPrefab))
if (MapEntityPrefab.FindByIdentifier(deconstructProduct.ItemIdentifier) is not ItemPrefab itemPrefab)
{
DebugConsole.ThrowError("Tried to deconstruct item \"" + targetItem.Name + "\" but couldn't find item prefab \"" + deconstructProduct.ItemIdentifier + "\"!");
return;
@@ -457,6 +459,12 @@ namespace Barotrauma.Items.Components
progressTimer = 0.0f;
progressState = 0.0f;
}
#if CLIENT
else
{
HintManager.OnStartDeconstructing(user, this);
}
#endif
inputContainer.Inventory.Locked = IsActive;
}
@@ -30,11 +30,8 @@ namespace Barotrauma.Items.Components
Serialize(500.0f, IsPropertySaveable.Yes, description: "The amount of force exerted on the submarine when the engine is operating at full power.")]
public float MaxForce
{
get { return maxForce; }
set
{
maxForce = Math.Max(0.0f, value);
}
get => maxForce;
set => maxForce = Math.Max(0.0f, value);
}
[Editable, Serialize("0.0,0.0", IsPropertySaveable.Yes,
@@ -94,7 +91,7 @@ namespace Barotrauma.Items.Components
}
partial void InitProjSpecific(ContentXElement element);
public override void Update(float deltaTime, Camera cam)
{
UpdateOnActiveEffects(deltaTime);
@@ -129,12 +126,14 @@ namespace Barotrauma.Items.Components
{
forceMultiplier *= MathHelper.Lerp(0.5f, 2.0f, (float)Math.Sqrt(User.GetSkillLevel("helm") / 100));
}
currForce *= maxForce * forceMultiplier;
if (item.GetComponent<Repairable>() is Repairable repairable && repairable.IsTinkering)
currForce *= item.StatManager.GetAdjustedValue(ItemTalentStats.EngineMaxSpeed, MaxForce) * forceMultiplier;
if (item.GetComponent<Repairable>() is { IsTinkering: true } repairable)
{
currForce *= 1f + repairable.TinkeringStrength * TinkeringForceIncrease;
}
currForce = item.StatManager.GetAdjustedValue(ItemTalentStats.EngineSpeed, currForce);
//less effective when in a bad condition
currForce *= MathHelper.Lerp(0.5f, 2.0f, condition);
if (item.Submarine.FlippedX) { currForce *= -1; }
@@ -89,7 +89,7 @@ namespace Barotrauma.Items.Components
{
DebugConsole.ThrowError("Error in item " + item.Name + "! Fabrication recipes should be defined in the craftable item's xml, not in the fabricator.");
break;
}
}
}
var fabricationRecipes = new Dictionary<uint, FabricationRecipe>();
@@ -104,6 +104,18 @@ namespace Barotrauma.Items.Components
continue;
}
}
bool recipeInvalid = false;
foreach (var requiredItem in recipe.RequiredItems)
{
if (requiredItem.ItemPrefabs.None())
{
DebugConsole.ThrowError($"Error in the fabrication recipe for \"{itemPrefab.Name}\". Could not find the ingredient \"{requiredItem}\".");
recipeInvalid = true;
}
}
if (recipeInvalid) { continue; }
fabricationRecipes.Add(recipe.RecipeHash, recipe);
if (recipe.FabricationLimitMax >= 0)
{
@@ -356,9 +368,10 @@ namespace Barotrauma.Items.Components
bool ingredientsStolen = false;
bool ingredientsAllowStealing = true;
if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer)
if (GameMain.NetworkMember is null || GameMain.NetworkMember.IsServer)
{
fabricatedItem.RequiredItems.ForEach(requiredItem =>
List<Item> foundAvailableItems = new List<Item>();
foreach (FabricationRecipe.RequiredItem requiredItem in fabricatedItem.RequiredItems)
{
for (int usedPrefabsAmount = 0; usedPrefabsAmount < requiredItem.Amount; usedPrefabsAmount++)
{
@@ -367,10 +380,7 @@ namespace Barotrauma.Items.Components
if (!availableIngredients.ContainsKey(requiredPrefab.Identifier)) { continue; }
var availableItems = availableIngredients[requiredPrefab.Identifier];
var availableItem = availableItems.FirstOrDefault(potentialPrefab =>
{
return requiredItem.IsConditionSuitable(potentialPrefab.ConditionPercentage);
});
var availableItem = availableItems.FirstOrDefault(potentialPrefab => requiredItem.IsConditionSuitable(potentialPrefab.ConditionPercentage));
if (availableItem == null) { continue; }
@@ -401,13 +411,21 @@ namespace Barotrauma.Items.Components
}
}
foundAvailableItems.Add(availableItem);
availableItems.Remove(availableItem);
Entity.Spawner.AddItemToRemoveQueue(availableItem);
inputContainer.Inventory.RemoveItem(availableItem);
break;
}
}
});
}
var fabricationIngredients = new AbilityFabricationItemIngredients(foundAvailableItems);
user?.CheckTalents(AbilityEffectType.OnItemFabricatedIngredients, fabricationIngredients);
foreach (Item availableItem in fabricationIngredients.Items)
{
Entity.Spawner.AddItemToRemoveQueue(availableItem);
inputContainer.Inventory.RemoveItem(availableItem);
}
int amountFittingContainer = outputContainer.Inventory.HowManyCanBePut(fabricatedItem.TargetItem, fabricatedItem.OutCondition * fabricatedItem.TargetItem.Health);
@@ -535,12 +553,13 @@ namespace Barotrauma.Items.Components
return currPowerConsumption;
}
private int GetFabricatedItemQuality(FabricationRecipe fabricatedItem, Character user)
private static int GetFabricatedItemQuality(FabricationRecipe fabricatedItem, Character user)
{
if (user == null) { return 0; }
if (user?.Info == null) { return 0; }
if (fabricatedItem.TargetItem.ConfigElement.GetChildElement("Quality") == null) { return 0; }
int quality = 0;
float floatQuality = 0.0f;
floatQuality += user.GetStatValue(StatTypes.IncreaseFabricationQuality, includeSaved: false);
foreach (var tag in fabricatedItem.TargetItem.Tags)
{
floatQuality += user.Info.GetSavedStatValue(StatTypes.IncreaseFabricationQuality, tag);
@@ -637,9 +656,14 @@ namespace Barotrauma.Items.Components
//fabricating takes 100 times longer if degree of success is close to 0
//characters with a higher skill than required can fabricate up to 100% faster
return fabricableItem.RequiredTime / FabricationSpeed / MathHelper.Clamp(t, 0.01f, 2.0f);
float time = fabricableItem.RequiredTime / item.StatManager.GetAdjustedValue(ItemTalentStats.FabricationSpeed, FabricationSpeed) / MathHelper.Clamp(t, 0.01f, 2.0f);
if (user is not null && fabricableItem.TargetItem is { } it && it.Tags.Contains("medical"))
{
time *= 1f + user.GetStatValue(StatTypes.FabricateMedicineSpeedMultiplier);
}
return time;
}
public float FabricationDegreeOfSuccess(Character character, ImmutableArray<Skill> skills)
{
if (skills.Length == 0) { return 1.0f; }
@@ -713,7 +737,31 @@ namespace Barotrauma.Items.Components
{
availableIngredients[itemIdentifier] = new List<Item>(itemList.Count);
}
availableIngredients[itemIdentifier].Add(item);
//order by condition (prefer using worst-condition items)
int index = 0;
while (index < availableIngredients[itemIdentifier].Count &&
compare(item, availableIngredients[itemIdentifier][index], inputContainer.Inventory) < 0)
{
index++;
}
static int compare(Item item1, Item item2, Inventory inputInventory)
{
bool item1InInputInventory = item1.ParentInventory == inputInventory;
bool item2InInputInventory = item2.ParentInventory == inputInventory;
//prefer items in the input inventory
if (item1InInputInventory != item2InInputInventory)
{
return item1InInputInventory ? 1 : -1;
}
else
{
//prefer items in worse condition
return Math.Sign(item2.Condition - item1.Condition);
}
}
availableIngredients[itemIdentifier].Insert(index, item);
}
}
@@ -827,5 +875,15 @@ namespace Barotrauma.Items.Components
public float Value { get; set; }
public ItemPrefab ItemPrefab { get; set; }
}
internal sealed class AbilityFabricationItemIngredients : AbilityObject
{
public List<Item> Items { get; set; }
public AbilityFabricationItemIngredients(List<Item> items)
{
Items = items;
}
}
}
}
@@ -15,6 +15,8 @@ namespace Barotrauma.Items.Components
public float? ReceivedOxygenAmount,
ReceivedWaterAmount;
public double LastOxygenDataTime, LastWaterDataTime;
public readonly HashSet<IdCard> Cards = new HashSet<IdCard>();
public bool Distort;
@@ -83,7 +85,7 @@ namespace Barotrauma.Items.Components
public override void Update(float deltaTime, Camera cam)
{
//periodically reset all hull data
//reset data if we haven't received anything in a while
//(so that outdated hull info won't be shown if detectors stop sending signals)
if (DateTime.Now > resetDataTime)
{
@@ -91,8 +93,8 @@ namespace Barotrauma.Items.Components
{
if (!hullData.Distort)
{
hullData.ReceivedOxygenAmount = null;
hullData.ReceivedWaterAmount = null;
if (Timing.TotalTime > hullData.LastOxygenDataTime + 1.0) { hullData.ReceivedOxygenAmount = null; }
if (Timing.TotalTime > hullData.LastWaterDataTime + 1.0) { hullData.ReceivedWaterAmount = null; }
}
}
resetDataTime = DateTime.Now + new TimeSpan(0, 0, 1);
@@ -159,6 +161,7 @@ namespace Barotrauma.Items.Components
//cheating a bit because water detectors don't actually send the water level
bool fromWaterDetector = source.GetComponent<WaterDetector>() != null;
hullData.ReceivedWaterAmount = null;
hullData.LastWaterDataTime = Timing.TotalTime;
if (fromWaterDetector)
{
hullData.ReceivedWaterAmount = WaterDetector.GetWaterPercentage(sourceHull);
@@ -184,9 +187,10 @@ namespace Barotrauma.Items.Components
oxy = Rand.Range(0.0f, 100.0f);
}
hullData.ReceivedOxygenAmount = oxy;
hullData.LastOxygenDataTime = Timing.TotalTime;
foreach (var linked in sourceHull.linkedTo)
{
if (!(linked is Hull linkedHull)) { continue; }
if (linked is not Hull linkedHull) { continue; }
if (!hullDatas.TryGetValue(linkedHull, out HullData linkedHullData))
{
linkedHullData = new HullData();
@@ -57,8 +57,8 @@ namespace Barotrauma.Items.Components
[Editable, Serialize(80.0f, IsPropertySaveable.No, description: "How fast the item pumps water in/out when operating at 100%.", alwaysUseInstanceValues: true)]
public float MaxFlow
{
get { return maxFlow; }
set { maxFlow = value; }
get => maxFlow;
set => maxFlow = value;
}
[Editable, Serialize(true, IsPropertySaveable.Yes, alwaysUseInstanceValues: true)]
@@ -92,13 +92,16 @@ namespace Barotrauma.Items.Components
}
partial void InitProjSpecific(ContentXElement element);
public override void Update(float deltaTime, Camera cam)
{
pumpSpeedLockTimer -= deltaTime;
isActiveLockTimer -= deltaTime;
if (!IsActive) { return; }
if (!IsActive)
{
return;
}
currFlow = 0.0f;
@@ -122,7 +125,10 @@ namespace Barotrauma.Items.Components
FlowPercentage = ((float)TargetLevel - hullPercentage) * 10.0f;
}
if (!HasPower) { return; }
if (!HasPower)
{
return;
}
UpdateProjSpecific(deltaTime);
@@ -132,13 +138,15 @@ namespace Barotrauma.Items.Components
float powerFactor = Math.Min(currPowerConsumption <= 0.0f || MinVoltage <= 0.0f ? 1.0f : Voltage, MaxOverVoltageFactor);
currFlow = flowPercentage / 100.0f * maxFlow * powerFactor;
currFlow = flowPercentage / 100.0f * item.StatManager.GetAdjustedValue(ItemTalentStats.PumpMaxFlow, MaxFlow) * powerFactor;
if (item.GetComponent<Repairable>() is Repairable repairable && repairable.IsTinkering)
if (item.GetComponent<Repairable>() is { IsTinkering: true } repairable)
{
currFlow *= 1f + repairable.TinkeringStrength * TinkeringSpeedIncrease;
}
currFlow = item.StatManager.GetAdjustedValue(ItemTalentStats.PumpSpeed, currFlow);
//less effective when in a bad condition
currFlow *= MathHelper.Lerp(0.5f, 1.0f, item.Condition / item.MaxCondition);
@@ -227,7 +235,7 @@ namespace Barotrauma.Items.Components
}
}
public override bool AIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
public override bool CrewAIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
{
#if CLIENT
if (GameMain.Client != null) { return false; }
@@ -95,15 +95,12 @@ namespace Barotrauma.Items.Components
}
}
}
[Editable(0.0f, float.MaxValue), Serialize(10000.0f, IsPropertySaveable.Yes, description: "How much power (kW) the reactor generates when operating at full capacity.", alwaysUseInstanceValues: true)]
public float MaxPowerOutput
{
get { return maxPowerOutput; }
set
{
maxPowerOutput = Math.Max(0.0f, value);
}
get => maxPowerOutput;
set => maxPowerOutput = Math.Max(0.0f, value);
}
[Editable(0.0f, float.MaxValue), Serialize(120.0f, IsPropertySaveable.Yes, description: "How long the temperature has to stay critical until a meltdown occurs.")]
@@ -152,11 +149,11 @@ namespace Barotrauma.Items.Components
turbineOutput = MathHelper.Clamp(value, 0.0f, 100.0f);
}
}
[Serialize(0.2f, IsPropertySaveable.Yes, description: "How fast the condition of the contained fuel rods deteriorates per second."), Editable(0.0f, 1000.0f, decimals: 3)]
public float FuelConsumptionRate
{
get { return fuelConsumptionRate; }
get => fuelConsumptionRate;
set
{
if (!MathUtils.IsValid(value)) return;
@@ -256,6 +253,8 @@ namespace Barotrauma.Items.Components
}
#endif
float maxPowerOut = GetMaxOutput();
if (signalControlledTargetFissionRate.HasValue && lastReceivedFissionRateSignalTime > Timing.TotalTime - 1)
{
TargetFissionRate = adjustValueWithoutOverShooting(TargetFissionRate, signalControlledTargetFissionRate.Value, deltaTime * 5.0f);
@@ -289,9 +288,9 @@ namespace Barotrauma.Items.Components
//use a smoothed "correct output" instead of the actual correct output based on the load
//so the player doesn't have to keep adjusting the rate impossibly fast when the load fluctuates heavily
if (!MathUtils.NearlyEqual(MaxPowerOutput, 0.0f))
if (!MathUtils.NearlyEqual(maxPowerOut, 0.0f))
{
CorrectTurbineOutput += MathHelper.Clamp((Load / MaxPowerOutput * 100.0f) - CorrectTurbineOutput, -20.0f, 20.0f) * deltaTime;
CorrectTurbineOutput += MathHelper.Clamp((Load / maxPowerOut * 100.0f) - CorrectTurbineOutput, -20.0f, 20.0f) * deltaTime;
}
//calculate tolerances of the meters based on the skills of the user
@@ -350,7 +349,7 @@ namespace Barotrauma.Items.Components
if (!isConnectedToFriendlyOutpost)
{
item.Condition -= fissionRate / 100.0f * fuelConsumptionRate * deltaTime;
item.Condition -= fissionRate / 100.0f * GetFuelConsumption() * deltaTime;
}
}
fuelLeft += item.ConditionPercentage;
@@ -359,10 +358,10 @@ namespace Barotrauma.Items.Components
if (fissionRate > 0.0f)
{
if (item.AiTarget != null && MaxPowerOutput > 0)
if (item.AiTarget != null && maxPowerOut > 0)
{
var aiTarget = item.AiTarget;
float range = Math.Abs(currPowerConsumption) / MaxPowerOutput;
float range = Math.Abs(currPowerConsumption) / maxPowerOut;
aiTarget.SoundRange = MathHelper.Lerp(aiTarget.MinSoundRange, aiTarget.MaxSoundRange, range);
if (item.CurrentHull != null)
{
@@ -433,15 +432,17 @@ namespace Barotrauma.Items.Components
tolerance = 3f;
}
float maxPowerOut = GetMaxOutput();
float temperatureFactor = Math.Min(temperature / 50.0f, 1.0f);
float minOutput = MaxPowerOutput * Math.Clamp(Math.Min((turbineOutput - tolerance) / 100.0f, temperatureFactor), 0, 1);
float maxOutput = MaxPowerOutput * Math.Min((turbineOutput + tolerance) / 100.0f, temperatureFactor);
float minOutput = maxPowerOut * Math.Clamp(Math.Min((turbineOutput - tolerance) / 100.0f, temperatureFactor), 0, 1);
float maxOutput = maxPowerOut * Math.Min((turbineOutput + tolerance) / 100.0f, temperatureFactor);
minUpdatePowerOut = minOutput;
maxUpdatePowerOut = maxOutput;
float reactorMax = PowerOn ? MaxPowerOutput : maxUpdatePowerOut;
float reactorMax = PowerOn ? maxPowerOut : maxUpdatePowerOut;
return new PowerRange(minOutput, maxOutput, reactorMax);
}
@@ -464,11 +465,13 @@ namespace Barotrauma.Items.Components
float output = MathHelper.Clamp(ratio * (maxUpdatePowerOut - minUpdatePowerOut) + minUpdatePowerOut, minUpdatePowerOut, maxUpdatePowerOut);
float newLoad = loadLeft;
float maxOutput = GetMaxOutput();
//Adjust behaviour for multi reactor setup
if (MaxPowerOutput != minMaxPower.ReactorMaxOutput)
if (maxOutput != minMaxPower.ReactorMaxOutput)
{
float idealLoad = MaxPowerOutput / minMaxPower.ReactorMaxOutput * loadLeft;
float loadAdjust = MathHelper.Clamp((ratio - 0.5f) * 25 + idealLoad - (turbineOutput / 100 * MaxPowerOutput), -MaxPowerOutput / 100, MaxPowerOutput / 100);
float idealLoad = maxOutput / minMaxPower.ReactorMaxOutput * loadLeft;
float loadAdjust = MathHelper.Clamp((ratio - 0.5f) * 25 + idealLoad - (turbineOutput / 100 * maxOutput), -maxOutput / 100, maxOutput / 100);
newLoad = MathHelper.Clamp(loadLeft - (expectedPower - output) + loadAdjust, 0, loadLeft);
}
@@ -509,7 +512,7 @@ namespace Barotrauma.Items.Components
//calculate the maximum output if the fission rate is cranked as high as it goes and turbine output is at max
float theoreticalMaxHeat = GetGeneratedHeat(fissionRate: maxFissionRate);
float temperatureFactor = Math.Min(theoreticalMaxHeat / 50.0f, 1.0f);
float theoreticalMaxOutput = Math.Min(maxTurbineOutput / 100.0f, temperatureFactor) * MaxPowerOutput;
float theoreticalMaxOutput = Math.Min(maxTurbineOutput / 100.0f, temperatureFactor) * GetMaxOutput();
//maximum output not enough, we need more fuel
return theoreticalMaxOutput < Load * minimumOutputRatio;
@@ -670,7 +673,7 @@ namespace Barotrauma.Items.Components
return picker != null;
}
public override bool AIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
public override bool CrewAIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
{
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return false; }
character.AIController.SteeringManager.Reset();
@@ -693,7 +696,7 @@ namespace Barotrauma.Items.Components
aiUpdateTimer = AIUpdateInterval;
// load more fuel if the current maximum output is only 50% of the current load
// or if the fuel rod is (almost) deplenished
float minCondition = fuelConsumptionRate * MathUtils.Pow2((degreeOfSuccess - refuelLimit) * 2);
float minCondition = GetFuelConsumption() * MathUtils.Pow2((degreeOfSuccess - refuelLimit) * 2);
if (NeedMoreFuel(minimumOutputRatio: 0.5f, minCondition: minCondition))
{
bool outOfFuel = false;
@@ -871,5 +874,8 @@ namespace Barotrauma.Items.Components
if (GameMain.NetworkMember is { IsServer: true }) { unsentChanges = true; }
}
}
private float GetMaxOutput() => item.StatManager.GetAdjustedValue(ItemTalentStats.ReactorMaxOutput, MaxPowerOutput);
private float GetFuelConsumption() => item.StatManager.GetAdjustedValue(ItemTalentStats.ReactorFuelEfficiency, fuelConsumptionRate);
}
}
@@ -153,13 +153,6 @@ namespace Barotrauma.Items.Components
bool changed = currentMode != value;
currentMode = value;
if (value == Mode.Passive)
{
if (item.AiTarget != null)
{
item.AiTarget.SectorDegrees = 360.0f;
}
}
#if CLIENT
if (changed) { prevPassivePingRadius = float.MaxValue; }
UpdateGUIElements();
@@ -206,13 +199,6 @@ namespace Barotrauma.Items.Components
var activePing = activePings[currentPingIndex];
if (activePing.State > 1.0f)
{
if (item.AiTarget != null)
{
float range = MathUtils.InverseLerp(item.AiTarget.MinSoundRange, item.AiTarget.MaxSoundRange, Range * activePing.State / zoom);
item.AiTarget.SoundRange = MathHelper.Lerp(item.AiTarget.MinSoundRange, item.AiTarget.MaxSoundRange, range);
item.AiTarget.SectorDegrees = activePing.IsDirectional ? DirectionalPingSector : 360.0f;
item.AiTarget.SectorDir = new Vector2(pingDirection.X, -pingDirection.Y);
}
aiPingCheckPending = true;
currentPingIndex = -1;
}
@@ -228,21 +214,27 @@ namespace Barotrauma.Items.Components
activePings[currentPingIndex].Direction = pingDirection;
activePings[currentPingIndex].State = 0.0f;
activePings[currentPingIndex].PrevPingRadius = 0.0f;
if (item.AiTarget != null)
{
item.AiTarget.SectorDegrees = useDirectionalPing ? DirectionalPingSector : 360.0f;
item.AiTarget.SectorDir = new Vector2(pingDirection.X, -pingDirection.Y);
}
item.Use(deltaTime);
}
}
else
{
if (item.AiTarget != null)
{
item.AiTarget.SectorDegrees = 360.0f;
}
aiPingCheckPending = false;
}
}
for (var pingIndex = 0; pingIndex < activePingsCount;)
{
if (item.AiTarget != null)
{
float range = MathUtils.InverseLerp(item.AiTarget.MinSoundRange, item.AiTarget.MaxSoundRange, Range * activePings[pingIndex].State / zoom);
item.AiTarget.SoundRange = Math.Max(item.AiTarget.SoundRange, MathHelper.Lerp(item.AiTarget.MinSoundRange, item.AiTarget.MaxSoundRange, range));
}
if (activePings[pingIndex].State > 1.0f)
{
var lastIndex = --activePingsCount;
@@ -281,7 +273,7 @@ namespace Barotrauma.Items.Components
private static readonly Dictionary<string, List<Character>> targetGroups = new Dictionary<string, List<Character>>();
public override bool AIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
public override bool CrewAIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
{
if (currentMode == Mode.Passive || !aiPingCheckPending) { return false; }
@@ -144,6 +144,11 @@ namespace Barotrauma.Items.Components
}
}
public float TargetVelocityLengthSquared
{
get => TargetVelocity.LengthSquared();
}
public Vector2 SteeringInput
{
get { return steeringInput; }
@@ -715,7 +720,7 @@ namespace Barotrauma.Items.Components
}
}
public override bool AIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
public override bool CrewAIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
{
character.AIController.SteeringManager.Reset();
if (objective.Override)
@@ -808,7 +813,7 @@ namespace Barotrauma.Items.Components
}
}
sonar?.AIOperate(deltaTime, character, objective);
sonar?.CrewAIOperate(deltaTime, character, objective);
if (!MaintainPos && showIceSpireWarning && character.IsOnPlayerTeam)
{
character.Speak(TextManager.Get("dialogicespirespottedsonar").Value, null, 0.0f, "icespirespottedsonar".ToIdentifier(), 60.0f);
@@ -65,7 +65,7 @@ namespace Barotrauma.Items.Components
[Editable, Serialize(10.0f, IsPropertySaveable.Yes, description: "The maximum capacity of the device (kW * min). For example, a value of 1000 means the device can output 100 kilowatts of power for 10 minutes, or 1000 kilowatts for 1 minute.")]
public float Capacity
{
get { return capacity; }
get => capacity;
set { capacity = Math.Max(value, 1.0f); }
}
@@ -89,7 +89,7 @@ namespace Barotrauma.Items.Components
}
}
public float ChargePercentage => MathUtils.Percentage(Charge, Capacity);
public float ChargePercentage => MathUtils.Percentage(Charge, GetCapacity());
[Editable, Serialize(10.0f, IsPropertySaveable.Yes, description: "How fast the device can be recharged. For example, a recharge speed of 100 kW and a capacity of 1000 kW*min would mean it takes 10 minutes to fully charge the device.")]
public float MaxRechargeSpeed
@@ -125,10 +125,19 @@ namespace Barotrauma.Items.Components
set { efficiency = MathHelper.Clamp(value, 0.0f, 1.0f); }
}
private bool flipIndicator;
[Editable, Serialize(false, IsPropertySaveable.Yes, description: "Should the progress bar indicating the charge be flipped to fill from the other side.")]
public bool FlipIndicator
{
get { return flipIndicator; }
set { flipIndicator = value; }
}
public float RechargeRatio => RechargeSpeed / MaxRechargeSpeed;
public const float aiRechargeTargetRatio = 0.5f;
private bool isRunning;
public bool HasBeenTuned { get; private set; }
public PowerContainer(Item item, ContentXElement element)
@@ -146,7 +155,7 @@ namespace Barotrauma.Items.Components
return picker != null;
}
public override void Update(float deltaTime, Camera cam)
public override void Update(float deltaTime, Camera cam)
{
if (item.Connections == null)
{
@@ -283,12 +292,12 @@ namespace Barotrauma.Items.Components
else
{
//Decrease charge based on how much power is leaving the device
Charge = Math.Clamp(Charge - CurrPowerOutput / 60 * UpdateInterval, 0, Capacity);
Charge = Math.Clamp(Charge - CurrPowerOutput / 60 * UpdateInterval, 0, GetCapacity());
prevCharge = Charge;
}
}
public override bool AIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
public override bool CrewAIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
{
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return false; }
@@ -370,5 +379,7 @@ namespace Barotrauma.Items.Components
}
}
}
public float GetCapacity() => item.StatManager.GetAdjustedValue(ItemTalentStats.BatteryCapacity, Capacity);
}
}
@@ -206,7 +206,7 @@ namespace Barotrauma.Items.Components
{
if (!powerOnSoundPlayed && powerOnSound != null)
{
SoundPlayer.PlaySound(powerOnSound.Sound, item.WorldPosition, powerOnSound.Volume, powerOnSound.Range, hullGuess: item.CurrentHull, ignoreMuffling: powerOnSound.IgnoreMuffling);
SoundPlayer.PlaySound(powerOnSound.Sound, item.WorldPosition, powerOnSound.Volume, powerOnSound.Range, hullGuess: item.CurrentHull, ignoreMuffling: powerOnSound.IgnoreMuffling, freqMult: powerOnSound.GetRandomFrequencyMultiplier());
powerOnSoundPlayed = true;
}
}
@@ -279,13 +279,13 @@ namespace Barotrauma.Items.Components
switch (item.body.BodyShape)
{
case PhysicsBody.Shape.Circle:
Attack.DamageRange = item.body.radius;
Attack.DamageRange = item.body.Radius;
break;
case PhysicsBody.Shape.Capsule:
Attack.DamageRange = item.body.height / 2 + item.body.radius;
Attack.DamageRange = item.body.Height / 2 + item.body.Radius;
break;
case PhysicsBody.Shape.Rectangle:
Attack.DamageRange = new Vector2(item.body.width / 2.0f, item.body.height / 2.0f).Length();
Attack.DamageRange = new Vector2(item.body.Width / 2.0f, item.body.Height / 2.0f).Length();
break;
}
Attack.DamageRange = ConvertUnits.ToDisplayUnits(Attack.DamageRange);
@@ -387,11 +387,12 @@ namespace Barotrauma.Items.Components
{
item.body.SetTransform(item.body.SimPosition, launchAngle);
float modifiedLaunchImpulse = (LaunchImpulse + launchImpulseModifier) * (1 + Rand.Range(-ImpulseSpread, ImpulseSpread));
DoLaunch(launchDir * modifiedLaunchImpulse * item.body.Mass);
DoLaunch(launchDir * modifiedLaunchImpulse);
System.Diagnostics.Debug.WriteLine("launch: " + modifiedLaunchImpulse + " - " + item.body.LinearVelocity);
}
}
User = character;
ApplyStatusEffects(ActionType.OnUse, 1.0f, User, user: User);
return true;
}
@@ -412,18 +413,29 @@ namespace Barotrauma.Items.Components
launchPos = item.SimPosition;
item.body.Enabled = true;
item.body.ApplyLinearImpulse(impulse, maxVelocity: NetConfig.MaxPhysicsBodyVelocity * 0.95f);
if (item.body.BodyType == BodyType.Kinematic)
{
item.body.LinearVelocity = impulse;
}
else
{
impulse *= item.body.Mass;
item.body.ApplyLinearImpulse(impulse, maxVelocity: NetConfig.MaxPhysicsBodyVelocity * 0.95f);
}
item.body.FarseerBody.OnCollision += OnProjectileCollision;
item.body.FarseerBody.IsBullet = true;
item.body.CollisionCategories = Physics.CollisionProjectile;
item.body.CollidesWith = Physics.CollisionCharacter | Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionItemBlocking;
if (item.body.CollisionCategories != Category.None)
{
item.body.CollisionCategories = Physics.CollisionProjectile;
item.body.CollidesWith = Physics.CollisionCharacter | Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionItemBlocking;
}
if (item.Prefab.DamagedByProjectiles && !IgnoreProjectilesWhileActive)
{
if (item.body.CollisionCategories == Category.None) { item.body.CollisionCategories = Physics.CollisionCharacter; }
item.body.CollidesWith |= Physics.CollisionProjectile;
}
IsActive = true;
if (stickJoint == null) { return; }
@@ -552,6 +564,7 @@ namespace Barotrauma.Items.Components
return true;
}
if (fixture.Body.UserData is VineTile) { return true; }
if (fixture.CollidesWith == Category.None) { return true; }
if (fixture.Body.UserData is Item item && (item.GetComponent<Door>() == null && !item.Prefab.DamagedByProjectiles || item.Condition <= 0)) { return true; }
if (fixture.Body.UserData as string == "ruinroom" || fixture.Body.UserData is Hull || fixture.UserData is Hull) { return true; }
@@ -592,6 +605,7 @@ namespace Barotrauma.Items.Components
if (fixture.Body.UserData is Item item && (item.GetComponent<Door>() == null && !item.Prefab.DamagedByProjectiles || item.Condition <= 0)) { return -1; }
if (fixture.Body.UserData as string == "ruinroom" || fixture.Body?.UserData is Hull || fixture.UserData is Hull) { return -1; }
if (fixture.CollidesWith == Category.None) { return -1; }
if (!(fixture.Body.UserData is Holdable holdable && holdable.CanPush))
{
//ignore everything else than characters, sub walls and level walls
@@ -731,11 +745,13 @@ namespace Barotrauma.Items.Components
{
if (User != null && User.Removed) { User = null; return false; }
if (IgnoredBodies != null && IgnoredBodies.Contains(target.Body)) { return false; }
if (originalCollisionCategories == Category.None && originalCollisionTargets == Category.None) { return false; }
//ignore character colliders (the projectile only hits limbs)
if (target.CollisionCategories == Physics.CollisionCharacter && target.Body.UserData is Character)
{
return false;
}
if (target.IsSensor) { return false; }
if (hits.Contains(target.Body)) { return false; }
if (target.Body.UserData is Submarine)
{
@@ -772,7 +788,7 @@ namespace Barotrauma.Items.Components
{
item.body.FarseerBody.ResetDynamics();
}
if (hits.Count() >= MaxTargetsToHit || target.Body.UserData is VoronoiCell)
if (hits.Count >= MaxTargetsToHit || target.Body.UserData is VoronoiCell)
{
DisableProjectileCollisions();
return true;
@@ -803,6 +819,13 @@ namespace Barotrauma.Items.Components
}
if (target.Body.UserData is Submarine sub)
{
//hit an item in a different sub -> no need to ignore, we can process the impact with this info
//(if it wasn't, we'll move the projectile to that sub's coordinate space and let it hit what it hits there)
if (Launcher?.Submarine != sub && target.UserData is Item)
{
return false;
}
Vector2 dir = item.body.LinearVelocity.LengthSquared() < 0.001f ?
contact.Manifold.LocalNormal : Vector2.Normalize(item.body.LinearVelocity);
@@ -849,7 +872,7 @@ namespace Barotrauma.Items.Components
AttackResult attackResult = new AttackResult();
Character character = null;
if (target.Body.UserData is Submarine submarine)
if (target.Body.UserData is Submarine submarine && target.UserData is not Barotrauma.Item)
{
item.Move(-submarine.Position);
item.Submarine = submarine;
@@ -874,14 +897,14 @@ namespace Barotrauma.Items.Components
if (Attack != null) { attackResult = Attack.DoDamageToLimb(User ?? Attacker, limb, item.WorldPosition, 1.0f); }
if (limb.character != null) { character = limb.character; }
}
else if ((target.Body.UserData as Item ?? (target.Body.UserData as ItemComponent)?.Item) is Item targetItem)
else if ((target.Body.UserData as Item ?? (target.Body.UserData as ItemComponent)?.Item ?? target.UserData as Item) is Item targetItem)
{
if (targetItem.Removed) { return false; }
if (Attack != null && (targetItem.Prefab.DamagedByProjectiles || DamageDoors && targetItem.GetComponent<Door>() != null) && targetItem.Condition > 0)
{
attackResult = Attack.DoDamage(User ?? Attacker, targetItem, item.WorldPosition, 1.0f);
#if CLIENT
if (attackResult.Damage > 0.0f)
if (attackResult.Damage > 0.0f && targetItem.Prefab.ShowHealthBar)
{
Character.Controlled?.UpdateHUDProgressBar(targetItem,
targetItem.WorldPosition,
@@ -915,23 +938,22 @@ namespace Barotrauma.Items.Components
if (character != null) { character.LastDamageSource = item; }
ActionType actionType = ActionType.OnUse;
if (_user != null && Rand.Range(0.0f, 0.5f) > DegreeOfSuccess(_user))
ActionType conditionalActionType = ActionType.OnSuccess;
if (User != null && Rand.Range(0.0f, 0.5f) > DegreeOfSuccess(User))
{
actionType = ActionType.OnFailure;
conditionalActionType = ActionType.OnFailure;
}
#if CLIENT
PlaySound(actionType, user: _user);
PlaySound(ActionType.OnImpact, user: _user);
PlaySound(conditionalActionType, user: User);
PlaySound(ActionType.OnImpact, user: User);
#endif
if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer)
{
if (target.Body.UserData is Limb targetLimb)
{
ApplyStatusEffects(actionType, 1.0f, character, targetLimb, user: _user);
ApplyStatusEffects(ActionType.OnImpact, 1.0f, character, targetLimb, user: _user);
ApplyStatusEffects(conditionalActionType, 1.0f, character, targetLimb, user: User);
ApplyStatusEffects(ActionType.OnImpact, 1.0f, character, targetLimb, user: User);
var attack = targetLimb.attack;
if (attack != null)
{
@@ -940,8 +962,6 @@ namespace Barotrauma.Items.Components
{
if (effect.type == ActionType.OnImpact)
{
//effect.Apply(effect.type, 1.0f, targetLimb.character, targetLimb.character, targetLimb.WorldPosition);
if (effect.HasTargetType(StatusEffect.TargetType.This))
{
effect.Apply(effect.type, 1.0f, targetLimb.character, targetLimb.character, targetLimb.WorldPosition);
@@ -950,32 +970,27 @@ namespace Barotrauma.Items.Components
effect.HasTargetType(StatusEffect.TargetType.NearbyCharacters))
{
targets.Clear();
targets.AddRange(effect.GetNearbyTargets(targetLimb.WorldPosition, targets));
effect.AddNearbyTargets(targetLimb.WorldPosition, targets);
effect.Apply(ActionType.OnActive, 1.0f, targetLimb.character, targets);
}
}
}
}
#if SERVER
if (GameMain.NetworkMember.IsServer)
if (GameMain.NetworkMember is { IsServer: true } server)
{
GameMain.Server?.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(actionType, this, targetLimb.character, targetLimb, null, item.WorldPosition));
GameMain.Server?.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(ActionType.OnImpact, this, targetLimb.character, targetLimb, null, item.WorldPosition));
server.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(conditionalActionType, this, targetLimb.character, targetLimb, null, item.WorldPosition));
server.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(ActionType.OnImpact, this, targetLimb.character, targetLimb, null, item.WorldPosition));
}
#endif
}
else
{
ApplyStatusEffects(actionType, 1.0f, useTarget: target.Body.UserData as Entity, user: _user);
ApplyStatusEffects(ActionType.OnImpact, 1.0f, useTarget: target.Body.UserData as Entity, user: _user);
#if SERVER
if (GameMain.NetworkMember.IsServer)
ApplyStatusEffects(conditionalActionType, 1.0f, useTarget: target.Body.UserData as Entity, user: User);
ApplyStatusEffects(ActionType.OnImpact, 1.0f, useTarget: target.Body.UserData as Entity, user: User);
if (GameMain.NetworkMember is { IsServer: true } server)
{
GameMain.Server?.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(actionType, this, null, null, target.Body.UserData as Entity, item.WorldPosition));
GameMain.Server?.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(ActionType.OnImpact, this, null, null, target.Body.UserData as Entity, item.WorldPosition));
server.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(conditionalActionType, this, null, null, target.Body.UserData as Entity, item.WorldPosition));
server.CreateEntityEvent(item, new Item.ApplyStatusEffectEventData(ActionType.OnImpact, this, null, null, target.Body.UserData as Entity, item.WorldPosition));
}
#endif
}
}
@@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Barotrauma.Abilities;
namespace Barotrauma.Items.Components
{
@@ -420,7 +421,8 @@ namespace Barotrauma.Items.Components
if (item.ConditionPercentage > MinDeteriorationCondition)
{
item.Condition -= DeteriorationSpeed * deltaTime;
float deteriorationSpeed = item.StatManager.GetAdjustedValue(ItemTalentStats.DetoriationSpeed, DeteriorationSpeed);
item.Condition -= deteriorationSpeed * deltaTime;
}
}
return;
@@ -467,8 +469,14 @@ namespace Barotrauma.Items.Components
wasGoodCondition = true;
}
float talentMultiplier = CurrentFixer.GetStatValue(StatTypes.RepairSpeed);
if (requiredSkills.Any(static skill => skill.Identifier == "mechanical"))
{
talentMultiplier += CurrentFixer.GetStatValue(StatTypes.MechanicalRepairSpeed);
}
float fixDuration = MathHelper.Lerp(FixDurationLowSkill, FixDurationHighSkill, successFactor);
fixDuration /= 1 + CurrentFixer.GetStatValue(StatTypes.RepairSpeed) + currentRepairItem?.Prefab.AddedRepairSpeedMultiplier ?? 0f;
fixDuration /= 1 + talentMultiplier + currentRepairItem?.Prefab.AddedRepairSpeedMultiplier ?? 0f;
fixDuration /= 1 + item.GetQualityModifier(Quality.StatType.RepairSpeed);
item.MaxRepairConditionMultiplier = GetMaxRepairConditionMultiplier(CurrentFixer);
@@ -500,7 +508,7 @@ namespace Barotrauma.Items.Components
SkillSettings.Current.SkillIncreasePerRepair / Math.Max(characterSkillLevel, 1.0f));
}
SteamAchievementManager.OnItemRepaired(item, CurrentFixer);
CurrentFixer.CheckTalents(AbilityEffectType.OnRepairComplete);
CurrentFixer.CheckTalents(AbilityEffectType.OnRepairComplete, new AbilityRepairable(item));
}
if (CurrentFixer?.SelectedItem == item) { CurrentFixer.SelectedItem = null; }
deteriorationTimer = Rand.Range(MinDeteriorationDelay, MaxDeteriorationDelay);
@@ -687,4 +695,14 @@ namespace Barotrauma.Items.Components
//where set_active/set_state signals can disable the component
}
}
internal sealed class AbilityRepairable : AbilityObject, IAbilityItem
{
public Item Item { get; set; }
public AbilityRepairable(Item item)
{
Item = item;
}
}
}
@@ -326,7 +326,7 @@ namespace Barotrauma.Items.Components
}
foreach (StatusEffect effect in btnElement.StatusEffects)
{
item.ApplyStatusEffect(effect, ActionType.OnUse, 1.0f);
item.ApplyStatusEffect(effect, ActionType.OnUse, 1.0f, character: item.ParentInventory?.Owner as Character);
}
}
@@ -289,7 +289,7 @@ namespace Barotrauma.Items.Components
#if CLIENT
Light.ParentSub = item.Submarine;
#endif
if (item.Container != null)
if (item.Container != null && !(item.GetRootInventoryOwner() is Character))
{
SetLightSourceState(false, 0.0f);
return;
@@ -301,7 +301,7 @@ namespace Barotrauma.Items.Components
if (body != null && !body.Enabled)
{
SetLightSourceState(false, 0.0f);
return;
return;
}
//currPowerConsumption = powerConsumption;
@@ -30,7 +30,7 @@ namespace Barotrauma.Items.Components
private const int MaxMessages = 60;
private List<TerminalMessage> messageHistory = new List<TerminalMessage>(MaxMessages);
private readonly List<TerminalMessage> messageHistory = new List<TerminalMessage>(MaxMessages);
public LocalizedString DisplayedWelcomeMessage
{
@@ -67,6 +67,12 @@ namespace Barotrauma.Items.Components
[Editable, Serialize(false, IsPropertySaveable.Yes, description: "The terminal will use a monospace font if this box is ticked.", alwaysUseInstanceValues: true)]
public bool UseMonospaceFont { get; set; }
[Serialize(false, IsPropertySaveable.No)]
public bool AutoHideScrollbar { get; set; }
[Serialize(false, IsPropertySaveable.Yes, alwaysUseInstanceValues: true)]
public bool WelcomeMessageDisplayed { get; set; }
private Color textColor = Color.LimeGreen;
[Editable, Serialize("50,205,50,255", IsPropertySaveable.Yes, description: "Color of the terminal text.", alwaysUseInstanceValues: true)]
@@ -85,6 +91,15 @@ namespace Barotrauma.Items.Components
}
}
[Editable, Serialize("> ", IsPropertySaveable.Yes)]
public string LineStartSymbol { get; set; }
[Editable, Serialize(false, IsPropertySaveable.No)]
public bool Readonly { get; set; }
[Serialize(true, IsPropertySaveable.No)]
public bool AutoScrollToBottom { get; set; }
private string OutputValue { get; set; }
private string prevColorSignal;
@@ -143,14 +158,14 @@ namespace Barotrauma.Items.Components
#endif
base.OnItemLoaded();
if (!DisplayedWelcomeMessage.IsNullOrEmpty())
if (!DisplayedWelcomeMessage.IsNullOrEmpty() && !WelcomeMessageDisplayed)
{
ShowOnDisplay(DisplayedWelcomeMessage.Value, addToHistory: !isSubEditor, TextColor);
DisplayedWelcomeMessage = "";
//remove welcome message if a game session is running so it doesn't reappear on successive rounds
//disable welcome message if a game session is running so it doesn't reappear on successive rounds
if (GameMain.GameSession != null && !isSubEditor)
{
welcomeMessage = null;
WelcomeMessageDisplayed = true;
}
}
}
@@ -74,7 +74,13 @@ namespace Barotrauma.Items.Components
return 0.0f;
}
}
}
}
[Serialize(false, IsPropertySaveable.Yes, alwaysUseInstanceValues: true)]
public bool ApplyEffectsToCharactersInsideSub { get; set; }
[Serialize(false, IsPropertySaveable.Yes, alwaysUseInstanceValues: true)]
public bool MoveOutsideSub { get; set; }
private readonly LevelTrigger.TriggererType triggeredBy;
private readonly HashSet<Entity> triggerers = new HashSet<Entity>();
@@ -131,7 +137,7 @@ namespace Barotrauma.Items.Components
PhysicsBody.FarseerBody.SetIsSensor(true);
PhysicsBody.FarseerBody.OnCollision += OnCollision;
PhysicsBody.FarseerBody.OnSeparation += OnSeparation;
RadiusInDisplayUnits = ConvertUnits.ToDisplayUnits(PhysicsBody.radius);
RadiusInDisplayUnits = ConvertUnits.ToDisplayUnits(PhysicsBody.Radius);
}
public override void OnMapLoaded()
@@ -144,7 +150,7 @@ namespace Barotrauma.Items.Components
private bool OnCollision(Fixture sender, Fixture other, Contact contact)
{
if (!(LevelTrigger.GetEntity(other) is Entity entity)) { return false; }
if (!LevelTrigger.IsTriggeredByEntity(entity, triggeredBy, mustBeOnSpecificSub: (true, item.Submarine))) { return false; }
if (!LevelTrigger.IsTriggeredByEntity(entity, triggeredBy, mustBeOnSpecificSub: (!MoveOutsideSub, item.Submarine))) { return false; }
triggerers.Add(entity);
return true;
}
@@ -169,6 +175,15 @@ namespace Barotrauma.Items.Components
public override void Update(float deltaTime, Camera cam)
{
if (item.Submarine != null && MoveOutsideSub)
{
item.SetTransform(ConvertUnits.ToSimUnits(item.WorldPosition), item.Rotation);
item.CurrentHull = null;
item.Submarine = null;
PhysicsBody.SetTransformIgnoreContacts(item.SimPosition, 0.0f);
PhysicsBody.Submarine = item.Submarine;
}
LevelTrigger.RemoveInActiveTriggerers(PhysicsBody, triggerers);
if (triggerOnce)
@@ -208,6 +223,13 @@ namespace Barotrauma.Items.Components
else if (triggerer is Submarine submarine)
{
LevelTrigger.ApplyAttacks(attacks, item.WorldPosition, deltaTime);
foreach (Character c2 in Character.CharacterList)
{
if (c2.Submarine == submarine)
{
LevelTrigger.ApplyAttacks(attacks, c2, item.WorldPosition, deltaTime);
}
}
}
if (Math.Abs(Force) < 0.01f)
@@ -317,6 +317,39 @@ namespace Barotrauma.Items.Components
private set;
}
[Serialize(false, IsPropertySaveable.Yes, description:"Should the turret operate automatically using AI targeting? Comes with some optional random movement that can be adjusted below."), Editable]
public bool AutoOperate { get; set; }
[Serialize(0f, IsPropertySaveable.Yes, description: "[Auto Operate] How much the turret should adjust the aim off the target randomly instead of tracking the target perfectly?"), Editable]
public float RandomAimAmount { get; private set; }
[Serialize(0f, IsPropertySaveable.Yes, description: "[Auto Operate] How often the turret should adjust the aim randomly instead of tracking the target perfectly?"), Editable]
public float RandomAimMinTime { get; private set; }
[Serialize(0f, IsPropertySaveable.Yes, description: "[Auto Operate] How often the turret should adjust the aim randomly instead of tracking the target perfectly?"), Editable]
public float RandomAimMaxTime { get; private set; }
[Serialize(false, IsPropertySaveable.Yes, description: "[Auto Operate] Should the turret move randomly while idle?"), Editable]
public bool RandomMovement { get; set; }
[Serialize(false, IsPropertySaveable.Yes, description: "[Auto Operate] Should the turret always aim at targets without delay?"), Editable]
public bool IgnoreAimDelay { get; set; }
[Serialize(true, IsPropertySaveable.Yes, description: "[Auto Operate] Should the turret target characters?"), Editable]
public bool TargetCharacters { get; set; }
[Serialize(true, IsPropertySaveable.Yes, description: "[Auto Operate] Should the turret target monsters?"), Editable]
public bool TargetMonsters { get; set; }
[Serialize(true, IsPropertySaveable.Yes, description: "[Auto Operate] Should the turret target humans (or pets)"), Editable]
public bool TargetHumans { get; set; }
[Serialize(true, IsPropertySaveable.Yes, description: "[Auto Operate] Should the turret target other submarines?"), Editable]
public bool TargetSubmarines { get; set; }
[Serialize("", IsPropertySaveable.Yes, description: "[Auto Operate] Group or SpeciesName that the AI ignores when the turret is operated automatically."), Editable]
public Identifier FriendlyTag { get; private set; }
public Turret(Item item, ContentXElement element)
: base(item, element)
{
@@ -558,6 +591,11 @@ namespace Barotrauma.Items.Components
}
UpdateLightComponents();
if (AutoOperate)
{
UpdateAutoOperate(deltaTime);
}
}
public void UpdateLightComponents()
@@ -656,13 +694,20 @@ namespace Barotrauma.Items.Components
loaderBroken = true;
continue;
}
ItemContainer projectileContainer = linkedItem.GetComponent<ItemContainer>();
if (tryUseProjectileContainer(linkedItem)) { break; }
}
tryUseProjectileContainer(item);
bool tryUseProjectileContainer(Item containerItem)
{
ItemContainer projectileContainer = containerItem.GetComponent<ItemContainer>();
if (projectileContainer != null)
{
linkedItem.Use(deltaTime, null);
containerItem.Use(deltaTime, null);
projectiles = GetLoadedProjectiles();
if (projectiles.Any()) { break; }
if (projectiles.Any()) { return true; }
}
return false;
}
}
if (projectiles.Count == 0 && !LaunchWithoutProjectile)
@@ -898,12 +943,20 @@ namespace Barotrauma.Items.Components
private float prevTargetRotation;
private float updateTimer;
private bool updatePending;
public void ThalamusOperate(WreckAI ai, float deltaTime, bool targetHumans, bool targetOtherCreatures, bool targetSubmarines, bool ignoreDelay)
{
if (ai == null) { return; }
public void UpdateAutoOperate(float deltaTime, Identifier friendlyTag = default)
{
IsActive = true;
bool targetCharacters = TargetCharacters || TargetHumans || TargetMonsters;
bool targetHumans = TargetCharacters && TargetHumans;
bool targetMonsters = TargetCharacters && TargetMonsters;
if (friendlyTag.IsEmpty)
{
friendlyTag = FriendlyTag;
}
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
{
return;
@@ -922,7 +975,7 @@ namespace Barotrauma.Items.Components
updateTimer -= deltaTime;
}
if (!ignoreDelay && waitTimer > 0)
if (!IgnoreAimDelay && waitTimer > 0)
{
waitTimer -= deltaTime;
return;
@@ -932,12 +985,12 @@ namespace Barotrauma.Items.Components
float shootDistance = AIRange;
ISpatialEntity target = null;
float closestDist = shootDistance * shootDistance;
if (targetHumans || targetOtherCreatures)
if (targetCharacters)
{
foreach (var character in Character.CharacterList)
{
if (character == null || character.Removed || character.IsDead) { continue; }
if (character.Params.Group == ai.Config.Entity) { continue; }
if (!friendlyTag.IsEmpty && (character.SpeciesName.Equals(friendlyTag) || character.Group.Equals(friendlyTag))) { continue; }
bool isHuman = character.IsHuman || character.Params.Group == CharacterPrefab.HumanSpeciesName;
if (isHuman)
{
@@ -947,7 +1000,7 @@ namespace Barotrauma.Items.Components
continue;
}
}
else if (!targetOtherCreatures)
else if (!targetMonsters)
{
// Don't target other creatures if not defined to.
continue;
@@ -958,7 +1011,7 @@ namespace Barotrauma.Items.Components
closestDist = dist;
}
}
if (targetSubmarines)
if (TargetSubmarines)
{
if (target == null || target.Submarine != null)
{
@@ -966,6 +1019,7 @@ namespace Barotrauma.Items.Components
foreach (Submarine sub in Submarine.Loaded)
{
if (sub.Info.Type != SubmarineType.Player) { continue; }
if (sub == Item.Submarine) { continue; }
float dist = Vector2.DistanceSquared(sub.WorldPosition, item.WorldPosition);
if (dist > closestDist) { continue; }
closestSub = sub;
@@ -985,28 +1039,33 @@ namespace Barotrauma.Items.Components
}
}
}
if (!ignoreDelay)
if (target == null && RandomMovement)
{
if (target == null)
// Random movement while there's no target
waitTimer = Rand.Value(Rand.RandSync.Unsynced) < 0.98f ? 0f : Rand.Range(5f, 20f);
targetRotation = Rand.Range(minRotation, maxRotation);
updatePending = true;
return;
}
if (!IgnoreAimDelay)
{
if (RandomAimAmount > 0)
{
// Random movement
waitTimer = Rand.Value(Rand.RandSync.Unsynced) < 0.98f ? 0f : Rand.Range(5f, 20f);
targetRotation = Rand.Range(minRotation, maxRotation);
updatePending = true;
return;
}
if (disorderTimer < 0)
{
// Random disorder
disorderTimer = Rand.Range(0f, 3f);
waitTimer = Rand.Range(0.25f, 1f);
targetRotation = MathUtils.WrapAngleTwoPi(targetRotation += Rand.Range(-1f, 1f));
updatePending = true;
return;
}
else
{
disorderTimer -= deltaTime;
if (disorderTimer < 0)
{
// Random disorder
disorderTimer = Rand.Range(RandomAimMinTime, RandomAimMaxTime);
waitTimer = Rand.Range(0.25f, 1f);
targetRotation = MathUtils.WrapAngleTwoPi(targetRotation += Rand.Range(-RandomAimAmount, RandomAimAmount));
updatePending = true;
return;
}
else
{
disorderTimer -= deltaTime;
}
}
}
if (target == null) { return; }
@@ -1041,11 +1100,11 @@ namespace Barotrauma.Items.Components
start -= target.Submarine.SimPosition;
end -= target.Submarine.SimPosition;
Body transformedTarget = CheckLineOfSight(start, end);
shoot = CanShoot(transformedTarget, user: null, ai, targetSubmarines) && (worldTarget == null || CanShoot(worldTarget, user: null, ai, targetSubmarines));
shoot = CanShoot(transformedTarget, user: null, friendlyTag, TargetSubmarines) && (worldTarget == null || CanShoot(worldTarget, user: null, friendlyTag, TargetSubmarines));
}
else
{
shoot = CanShoot(worldTarget, user: null, ai, targetSubmarines);
shoot = CanShoot(worldTarget, user: null, friendlyTag, TargetSubmarines);
}
if (shoot)
{
@@ -1053,7 +1112,7 @@ namespace Barotrauma.Items.Components
}
}
public override bool AIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
public override bool CrewAIOperate(float deltaTime, Character character, AIObjectiveOperateItem objective)
{
if (character.AIController.SelectedAiTarget?.Entity is Character previousTarget && previousTarget.IsDead)
{
@@ -1438,7 +1497,7 @@ namespace Barotrauma.Items.Components
return 0;
}
private bool CanShoot(Body targetBody, Character user = null, WreckAI ai = null, bool targetSubmarines = true)
private bool CanShoot(Body targetBody, Character user = null, Identifier friendlyTag = default, bool targetSubmarines = true)
{
if (targetBody == null) { return false; }
Character targetCharacter = null;
@@ -1459,9 +1518,9 @@ namespace Barotrauma.Items.Components
return false;
}
}
if (ai != null)
if (!friendlyTag.IsEmpty)
{
if (targetCharacter.Params.Group == ai.Config.Entity)
if (targetCharacter.SpeciesName.Equals(friendlyTag) || targetCharacter.Group.Equals(friendlyTag))
{
return false;
}
@@ -270,6 +270,9 @@ namespace Barotrauma.Items.Components
public bool AutoEquipWhenFull { get; private set; }
public bool DisplayContainedStatus { get; private set; }
[Serialize(false, IsPropertySaveable.No, description: "Can the item be used (assuming it has components that are usable in some way) when worn."), Editable(MinValueFloat = -1000.0f, MaxValueFloat = 1000.0f)]
public bool AllowUseWhenWorn { get; set; }
public readonly int Variants;
private int variant;
@@ -512,8 +515,11 @@ namespace Barotrauma.Items.Components
return;
}
item.SetTransform(picker.SimPosition, 0.0f);
//if the item is also being held, let the Holdable component control the position
if (item.GetComponent<Holdable>() is not { IsActive: true })
{
item.SetTransform(picker.SimPosition, 0.0f);
}
item.ApplyStatusEffects(ActionType.OnWearing, deltaTime, picker);
#if CLIENT