(61d00a474) v0.9.7.1

This commit is contained in:
Regalis
2020-03-04 13:04:10 +01:00
parent 3c50efa5c9
commit 3c09ebe02f
5086 changed files with 786063 additions and 295871 deletions
@@ -0,0 +1,36 @@
using Microsoft.Xna.Framework;
using Barotrauma.Networking;
using System;
namespace Barotrauma.Items.Components
{
partial class Door
{
partial void SetState(bool open, bool isNetworkMessage, bool sendNetworkMessage, bool forcedOpen)
{
if (IsStuck || isOpen == open)
{
return;
}
isOpen = open;
//opening a partially stuck door makes it less stuck
if (isOpen) stuck = MathHelper.Clamp(stuck - 30.0f, 0.0f, 100.0f);
if (sendNetworkMessage)
{
GameMain.Server.CreateEntityEvent(item, new object[] { NetEntityEvent.Type.ComponentState, item.GetComponentIndex(this), forcedOpen });
}
}
public override void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
base.ServerWrite(msg, c, extraData);
msg.Write(isOpen);
msg.Write(extraData.Length == 3 ? (bool)extraData[2] : false); //forced open
msg.WriteRangedSingle(stuck, 0.0f, 100.0f, 8);
msg.Write(lastUser == null ? (UInt16)0 : lastUser.ID);
}
}
}
@@ -0,0 +1,36 @@
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
namespace Barotrauma.Items.Components
{
partial class Holdable : Pickable, IServerSerializable, IClientSerializable
{
public override void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
base.ServerWrite(msg, c, extraData);
if (!attachable || body == null) { return; }
msg.Write(Attached);
msg.Write(body.SimPosition.X);
msg.Write(body.SimPosition.Y);
}
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
Vector2 simPosition = new Vector2(msg.ReadSingle(), msg.ReadSingle());
if (!item.CanClientAccess(c) || !Attachable || attached || !MathUtils.IsValid(simPosition)) { return; }
Vector2 offset = simPosition - c.Character.SimPosition;
offset = offset.ClampLength(MaxAttachDistance * 1.5f);
simPosition = c.Character.SimPosition + offset;
Drop(false, null);
item.SetTransform(simPosition, 0.0f);
AttachToWall();
item.CreateServerEvent(this);
GameServer.Log(c.Character.LogName + " attached " + item.Name + " to a wall", ServerLog.MessageType.ItemInteraction);
}
}
}
@@ -0,0 +1,14 @@
using Barotrauma.Networking;
namespace Barotrauma.Items.Components
{
partial class LevelResource : ItemComponent, IServerSerializable
{
private float lastSentDeattachTimer;
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
msg.Write(deattachTimer);
}
}
}
@@ -0,0 +1,22 @@
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
partial class ItemComponent : ISerializableEntity
{
private bool LoadElemProjSpecific(XElement subElement)
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "guiframe":
break;
case "sound":
break;
default:
return false; //unknown element
}
return true; //element processed
}
}
}
@@ -0,0 +1,39 @@
using Microsoft.Xna.Framework;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
partial class ItemLabel : ItemComponent, IDrawableComponent
{
[Serialize("", true, description: "The text to display on the label."), Editable(100)]
public string Text
{
get;
set;
}
[Editable, Serialize("0,0,0,255", true, description: "The color of the text displayed on the label.")]
public Color TextColor
{
get;
set;
}
[Editable, Serialize(1.0f, true, description: "The scale of the text displayed on the label.")]
public float TextScale
{
get;
set;
}
public override void Move(Vector2 amount)
{
//do nothing
}
public ItemLabel(Item item, XElement element)
: base(item, element)
{
}
}
}
@@ -0,0 +1,13 @@
using Barotrauma.Networking;
namespace Barotrauma.Items.Components
{
partial class Controller : ItemComponent, IServerSerializable
{
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
msg.Write(state);
msg.Write(user == null ? (ushort)0 : user.ID);
}
}
}
@@ -0,0 +1,27 @@
using Barotrauma.Networking;
using System.Linq;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
partial class Deconstructor : Powered, IServerSerializable, IClientSerializable
{
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
bool active = msg.ReadBoolean();
item.CreateServerEvent(this);
if (item.CanClientAccess(c))
{
SetActive(active, c.Character);
}
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
msg.Write(IsActive);
msg.Write(progressTimer);
}
}
}
@@ -0,0 +1,32 @@
using Barotrauma.Networking;
using System;
namespace Barotrauma.Items.Components
{
partial class Engine : Powered, IServerSerializable, IClientSerializable
{
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
//force can only be adjusted at 10% intervals -> no need for more accuracy than this
msg.WriteRangedInteger((int)(targetForce / 10.0f), -10, 10);
}
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
float newTargetForce = msg.ReadRangedInteger(-10, 10) * 10.0f;
if (item.CanClientAccess(c))
{
if (Math.Abs(newTargetForce - targetForce) > 0.01f)
{
GameServer.Log(c.Character.LogName + " set the force of " + item.Name + " to " + (int)(newTargetForce) + " %", ServerLog.MessageType.ItemInteraction);
}
targetForce = newTargetForce;
}
//notify all clients of the changed state
item.CreateServerEvent(this);
}
}
}
@@ -0,0 +1,42 @@
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
partial class Fabricator : Powered, IServerSerializable, IClientSerializable
{
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
int itemIndex = msg.ReadRangedInteger(-1, fabricationRecipes.Count - 1);
item.CreateServerEvent(this);
if (!item.CanClientAccess(c)) return;
if (itemIndex == -1)
{
CancelFabricating(c.Character);
}
else
{
//if already fabricating the selected item, return
if (fabricatedItem != null && fabricationRecipes.IndexOf(fabricatedItem) == itemIndex) return;
if (itemIndex < 0 || itemIndex >= fabricationRecipes.Count) return;
StartFabricating(fabricationRecipes[itemIndex], c.Character);
}
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
int itemIndex = fabricatedItem == null ? -1 : fabricationRecipes.IndexOf(fabricatedItem);
msg.WriteRangedInteger(itemIndex, -1, fabricationRecipes.Count - 1);
UInt16 userID = fabricatedItem == null || user == null ? (UInt16)0 : user.ID;
msg.Write(userID);
}
}
}
@@ -0,0 +1,42 @@
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System;
using System.Globalization;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
partial class Pump : Powered, IServerSerializable, IClientSerializable
{
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
float newFlowPercentage = msg.ReadRangedInteger(-10, 10) * 10.0f;
bool newIsActive = msg.ReadBoolean();
if (item.CanClientAccess(c))
{
if (newFlowPercentage != FlowPercentage)
{
GameServer.Log(c.Character.LogName + " set the pumping speed of " + item.Name + " to " + (int)(newFlowPercentage) + " %", ServerLog.MessageType.ItemInteraction);
}
if (newIsActive != IsActive)
{
GameServer.Log(c.Character.LogName + (newIsActive ? " turned on " : " turned off ") + item.Name, ServerLog.MessageType.ItemInteraction);
}
FlowPercentage = newFlowPercentage;
IsActive = newIsActive;
}
//notify all clients of the changed state
item.CreateServerEvent(this);
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
//flowpercentage can only be adjusted at 10% intervals -> no need for more accuracy than this
msg.WriteRangedInteger((int)(flowPercentage / 10.0f), -10, 10);
msg.Write(IsActive);
}
}
}
@@ -0,0 +1,54 @@
using Barotrauma.Networking;
using System;
namespace Barotrauma.Items.Components
{
partial class Reactor
{
private Client blameOnBroken;
private float? nextServerLogWriteTime;
private float lastServerLogWriteTime;
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
bool autoTemp = msg.ReadBoolean();
bool powerOn = msg.ReadBoolean();
float fissionRate = msg.ReadRangedSingle(0.0f, 100.0f, 8);
float turbineOutput = msg.ReadRangedSingle(0.0f, 100.0f, 8);
if (!item.CanClientAccess(c)) return;
IsActive = true;
if (!autoTemp && AutoTemp) blameOnBroken = c;
if (turbineOutput < targetTurbineOutput) blameOnBroken = c;
if (fissionRate > targetFissionRate) blameOnBroken = c;
if (!_powerOn && powerOn) blameOnBroken = c;
AutoTemp = autoTemp;
_powerOn = powerOn;
targetFissionRate = fissionRate;
targetTurbineOutput = turbineOutput;
LastUser = c.Character;
if (nextServerLogWriteTime == null)
{
nextServerLogWriteTime = Math.Max(lastServerLogWriteTime + 1.0f, (float)Timing.TotalTime);
}
//need to create a server event to notify all clients of the changed state
unsentChanges = true;
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
msg.Write(autoTemp);
msg.Write(_powerOn);
msg.WriteRangedSingle(temperature, 0.0f, 100.0f, 8);
msg.WriteRangedSingle(targetFissionRate, 0.0f, 100.0f, 8);
msg.WriteRangedSingle(targetTurbineOutput, 0.0f, 100.0f, 8);
msg.WriteRangedSingle(degreeOfSuccess, 0.0f, 1.0f, 8);
}
}
}
@@ -0,0 +1,115 @@
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
namespace Barotrauma.Items.Components
{
partial class Steering : Powered, IServerSerializable, IClientSerializable
{
// TODO: an enumeration would be much cleaner
public bool MaintainPos;
public bool LevelStartSelected;
public bool LevelEndSelected;
public bool UnsentChanges
{
get { return unsentChanges; }
set { unsentChanges = value; }
}
public void ServerRead(ClientNetObject type, IReadMessage msg, Barotrauma.Networking.Client c)
{
bool autoPilot = msg.ReadBoolean();
bool dockingButtonClicked = msg.ReadBoolean();
Vector2 newSteeringInput = targetVelocity;
bool maintainPos = false;
Vector2? newPosToMaintain = null;
bool headingToStart = false;
if (autoPilot)
{
maintainPos = msg.ReadBoolean();
if (maintainPos)
{
newPosToMaintain = new Vector2(
msg.ReadSingle(),
msg.ReadSingle());
}
else
{
headingToStart = msg.ReadBoolean();
}
}
else
{
newSteeringInput = new Vector2(msg.ReadSingle(), msg.ReadSingle());
}
if (!item.CanClientAccess(c)) return;
user = c.Character;
AutoPilot = autoPilot;
if (dockingButtonClicked)
{
item.SendSignal(0, "1", "toggle_docking", sender: null);
GameMain.Server.CreateEntityEvent(item, new object[] { NetEntityEvent.Type.ComponentState, item.GetComponentIndex(this), true });
}
if (!AutoPilot)
{
steeringInput = newSteeringInput;
steeringAdjustSpeed = MathHelper.Lerp(0.2f, 1.0f, c.Character.GetSkillLevel("helm") / 100.0f);
}
else
{
MaintainPos = newPosToMaintain != null;
posToMaintain = newPosToMaintain;
if (posToMaintain == null)
{
LevelStartSelected = headingToStart;
LevelEndSelected = !headingToStart;
UpdatePath();
}
else
{
LevelStartSelected = false;
LevelEndSelected = false;
}
}
//notify all clients of the changed state
unsentChanges = true;
}
public void ServerWrite(IWriteMessage msg, Barotrauma.Networking.Client c, object[] extraData = null)
{
msg.Write(autoPilot);
msg.Write(extraData.Length > 2 && extraData[2] is bool && (bool)extraData[2]);
if (!autoPilot)
{
//no need to write steering info if autopilot is controlling
msg.Write(steeringInput.X);
msg.Write(steeringInput.Y);
msg.Write(targetVelocity.X);
msg.Write(targetVelocity.Y);
msg.Write(steeringAdjustSpeed);
}
else
{
msg.Write(posToMaintain != null);
if (posToMaintain != null)
{
msg.Write(((Vector2)posToMaintain).X);
msg.Write(((Vector2)posToMaintain).Y);
}
else
{
msg.Write(LevelStartSelected);
}
}
}
}
}
@@ -0,0 +1,31 @@
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
partial class PowerContainer : Powered, IDrawableComponent, IServerSerializable, IClientSerializable
{
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
float newRechargeSpeed = msg.ReadRangedInteger(0, 10) / 10.0f * maxRechargeSpeed;
if (item.CanClientAccess(c))
{
RechargeSpeed = newRechargeSpeed;
GameServer.Log(c.Character.LogName + " set the recharge speed of " + item.Name + " to " + (int)((rechargeSpeed / maxRechargeSpeed) * 100.0f) + " %", ServerLog.MessageType.ItemInteraction);
}
item.CreateServerEvent(this);
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
msg.WriteRangedInteger((int)(rechargeSpeed / MaxRechargeSpeed * 10), 0, 10);
float chargeRatio = MathHelper.Clamp(charge / capacity, 0.0f, 1.0f);
msg.WriteRangedSingle(chargeRatio, 0.0f, 1.0f, 8);
}
}
}
@@ -0,0 +1,45 @@
using Barotrauma.Networking;
namespace Barotrauma.Items.Components
{
partial class Repairable : ItemComponent, IServerSerializable, IClientSerializable
{
void InitProjSpecific()
{
//let the clients know the initial deterioration delay
item.CreateServerEvent(this);
}
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
if (c.Character == null) { return; }
var requestedFixAction = (FixActions)msg.ReadRangedInteger(0, 2);
if (requestedFixAction != FixActions.None)
{
if (!c.Character.IsTraitor && requestedFixAction == FixActions.Sabotage)
{
if (GameSettings.VerboseLogging)
{
DebugConsole.Log($"Non traitor \"{c.Character.Name}\" attempted to sabotage item.");
}
requestedFixAction = FixActions.Repair;
}
if (CurrentFixer == null || CurrentFixer == c.Character && requestedFixAction != currentFixerAction)
{
StartRepairing(c.Character, requestedFixAction);
item.CreateServerEvent(this);
}
}
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
msg.Write(deteriorationTimer);
msg.Write(deteriorateAlwaysResetTimer);
msg.Write(DeteriorateAlways);
msg.Write(CurrentFixer == null ? (ushort)0 : CurrentFixer.ID);
msg.WriteRangedInteger((int)currentFixerAction, 0, 2);
}
}
}
@@ -0,0 +1,201 @@
using Barotrauma.Networking;
using FarseerPhysics;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
partial class ConnectionPanel : ItemComponent, IServerSerializable, IClientSerializable
{
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
List<Wire>[] wires = new List<Wire>[Connections.Count];
//read wire IDs for each connection
for (int i = 0; i < Connections.Count; i++)
{
wires[i] = new List<Wire>();
for (int j = 0; j < Connection.MaxLinked; j++)
{
ushort wireId = msg.ReadUInt16();
if (!(Entity.FindEntityByID(wireId) is Item wireItem)) { continue; }
Wire wireComponent = wireItem.GetComponent<Wire>();
if (wireComponent != null)
{
wires[i].Add(wireComponent);
}
}
}
List<Wire> clientSideDisconnectedWires = new List<Wire>();
ushort disconnectedWireCount = msg.ReadUInt16();
for (int i = 0; i < disconnectedWireCount; i++)
{
ushort wireId = msg.ReadUInt16();
if (!(Entity.FindEntityByID(wireId) is Item wireItem)) { continue; }
Wire wireComponent = wireItem.GetComponent<Wire>();
if (wireComponent == null) { continue; }
clientSideDisconnectedWires.Add(wireComponent);
}
//don't allow rewiring locked panels
if (Locked || !GameMain.NetworkMember.ServerSettings.AllowRewiring) { return; }
item.CreateServerEvent(this);
//check if the character can access this connectionpanel
//and all the wires they're trying to connect
if (!item.CanClientAccess(c)) { return; }
for (int i = 0; i < Connections.Count; i++)
{
foreach (Wire wire in wires[i])
{
//wire not found in any of the connections yet (client is trying to connect a new wire)
// -> we need to check if the client has access to it
if (!Connections.Any(connection => connection.Wires.Contains(wire)) && !DisconnectedWires.Contains(wire))
{
if (!wire.Item.CanClientAccess(c)) { return; }
}
}
}
if (!CheckCharacterSuccess(c.Character))
{
GameMain.Server?.CreateEntityEvent(item, new object[] { NetEntityEvent.Type.ApplyStatusEffect, ActionType.OnFailure, this, c.Character.ID });
return;
}
//go through existing wire links
for (int i = 0; i < Connections.Count; i++)
{
int j = -1;
foreach (Wire existingWire in Connections[i].Wires)
{
j++;
if (existingWire == null) { continue; }
//existing wire not in the list of new wires -> disconnect it
if (!wires[i].Contains(existingWire))
{
if (existingWire.Locked)
{
//this should not be possible unless the client is running a modified version of the game
GameServer.Log(c.Character.LogName + " attempted to disconnect a locked wire from " +
Connections[i].Item.Name + " (" + Connections[i].Name + ")", ServerLog.MessageType.Error);
continue;
}
existingWire.RemoveConnection(item);
if (existingWire.Item.ParentInventory == null)
{
item.GetComponent<ConnectionPanel>()?.DisconnectedWires.Add(existingWire);
}
if (!wires.Any(w => w.Contains(existingWire)))
{
GameMain.Server.KarmaManager.OnWireDisconnected(c.Character, existingWire);
}
if (existingWire.Connections[0] == null && existingWire.Connections[1] == null)
{
GameServer.Log(c.Character.LogName + " disconnected a wire from " +
Connections[i].Item.Name + " (" + Connections[i].Name + ")", ServerLog.MessageType.Wiring);
if (existingWire.Item.ParentInventory != null)
{
//in an inventory and not connected to anything -> the wire cannot have any nodes
existingWire.ClearConnections();
}
else if (!clientSideDisconnectedWires.Contains(existingWire))
{
//not in an inventory, not connected to anything, not hanging loose from any panel -> must be dropped
existingWire.Item.Drop(c.Character);
}
}
else if (existingWire.Connections[0] != null)
{
GameServer.Log(c.Character.LogName + " disconnected a wire from " +
Connections[i].Item.Name + " (" + Connections[i].Name + ") to " + existingWire.Connections[0].Item.Name + " (" + existingWire.Connections[0].Name + ")", ServerLog.MessageType.Wiring);
//wires that are not in anyone's inventory (i.e. not currently being rewired)
//can never be connected to only one connection
// -> the client must have dropped the wire from the connection panel
/*if (existingWire.Item.ParentInventory == null && !wires.Any(w => w.Contains(existingWire)))
{
//let other clients know the item was also disconnected from the other connection
existingWire.Connections[0].Item.CreateServerEvent(existingWire.Connections[0].Item.GetComponent<ConnectionPanel>());
existingWire.Item.Drop(c.Character);
}*/
}
else if (existingWire.Connections[1] != null)
{
GameServer.Log(c.Character.LogName + " disconnected a wire from " +
Connections[i].Item.Name + " (" + Connections[i].Name + ") to " + existingWire.Connections[1].Item.Name + " (" + existingWire.Connections[1].Name + ")", ServerLog.MessageType.Wiring);
/*if (existingWire.Item.ParentInventory == null && !wires.Any(w => w.Contains(existingWire)))
{
//let other clients know the item was also disconnected from the other connection
existingWire.Connections[1].Item.CreateServerEvent(existingWire.Connections[1].Item.GetComponent<ConnectionPanel>());
existingWire.Item.Drop(c.Character);
}*/
}
Connections[i].SetWire(j, null);
}
}
}
foreach (Wire disconnectedWire in DisconnectedWires.ToList())
{
if (disconnectedWire.Connections[0] == null &&
disconnectedWire.Connections[1] == null &&
!clientSideDisconnectedWires.Contains(disconnectedWire) &&
disconnectedWire.Item.ParentInventory == null)
{
disconnectedWire.Item.Drop(c.Character);
GameServer.Log(c.Character.LogName + " dropped " + disconnectedWire.Name, ServerLog.MessageType.Inventory);
}
}
//go through new wires
for (int i = 0; i < Connections.Count; i++)
{
foreach (Wire newWire in wires[i])
{
//already connected, no need to do anything
if (Connections[i].Wires.Contains(newWire)) { continue; }
Connections[i].TryAddLink(newWire);
newWire.Connect(Connections[i], true, true);
var otherConnection = newWire.OtherConnection(Connections[i]);
if (otherConnection == null)
{
GameServer.Log(c.Character.LogName + " connected a wire to " +
Connections[i].Item.Name + " (" + Connections[i].Name + ")",
ServerLog.MessageType.Wiring);
}
else
{
GameServer.Log(c.Character.LogName + " connected a wire from " +
Connections[i].Item.Name + " (" + Connections[i].Name + ") to " +
(otherConnection == null ? "none" : otherConnection.Item.Name + " (" + (otherConnection.Name) + ")"),
ServerLog.MessageType.Wiring);
}
}
}
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
msg.Write(user == null ? (ushort)0 : user.ID);
ClientWrite(msg, extraData);
}
}
}
@@ -0,0 +1,62 @@
using Barotrauma.Networking;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
partial class CustomInterface : ItemComponent, IClientSerializable, IServerSerializable
{
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
bool[] elementStates = new bool[customInterfaceElementList.Count];
for (int i = 0; i < customInterfaceElementList.Count; i++)
{
elementStates[i] = msg.ReadBoolean();
}
CustomInterfaceElement clickedButton = null;
if (item.CanClientAccess(c))
{
for (int i = 0; i < customInterfaceElementList.Count; i++)
{
if (customInterfaceElementList[i].ContinuousSignal)
{
TickBoxToggled(customInterfaceElementList[i], elementStates[i]);
}
else if (elementStates[i])
{
clickedButton = customInterfaceElementList[i];
ButtonClicked(customInterfaceElementList[i]);
}
}
}
//notify all clients of the new state
GameMain.Server.CreateEntityEvent(item, new object[]
{
NetEntityEvent.Type.ComponentState,
item.GetComponentIndex(this),
clickedButton
});
item.CreateServerEvent(this);
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
//extradata contains an array of buttons clicked by a client (or nothing if nothing was clicked)
for (int i = 0; i < customInterfaceElementList.Count; i++)
{
if (customInterfaceElementList[i].ContinuousSignal)
{
msg.Write(customInterfaceElementList[i].State);
}
else
{
msg.Write(extraData != null && extraData.Any(d => d as CustomInterfaceElement == customInterfaceElementList[i]));
}
}
}
}
}
@@ -0,0 +1,31 @@
using Barotrauma.Networking;
namespace Barotrauma.Items.Components
{
partial class Terminal : ItemComponent, IClientSerializable, IServerSerializable
{
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
string newOutputValue = msg.ReadString();
if (item.CanClientAccess(c))
{
if (newOutputValue.Length > MaxMessageLength)
{
newOutputValue = newOutputValue.Substring(0, MaxMessageLength);
}
GameServer.Log(c.Character.LogName + " entered \"" + newOutputValue + "\" on " + item.Name,
ServerLog.MessageType.ItemInteraction);
OutputValue = newOutputValue;
item.SendSignal(0, newOutputValue, "signal_out", null);
item.CreateServerEvent(this);
}
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
msg.Write(OutputValue);
}
}
}
@@ -0,0 +1,64 @@
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System;
namespace Barotrauma.Items.Components
{
partial class Wire : ItemComponent, IDrawableComponent, IServerSerializable
{
private void CreateNetworkEvent()
{
if (GameMain.Server == null) return;
//split into multiple events because one might not be enough to fit all the nodes
int eventCount = Math.Max((int)Math.Ceiling(nodes.Count / (float)MaxNodesPerNetworkEvent), 1);
for (int i = 0; i < eventCount; i++)
{
GameMain.Server.CreateEntityEvent(item, new object[] { NetEntityEvent.Type.ComponentState, item.GetComponentIndex(this), i });
}
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
int eventIndex = (int)extraData[2];
int nodeStartIndex = eventIndex * MaxNodesPerNetworkEvent;
int nodeCount = MathHelper.Clamp(nodes.Count - nodeStartIndex, 0, MaxNodesPerNetworkEvent);
msg.WriteRangedInteger(eventIndex, 0, (int)Math.Ceiling(MaxNodeCount / (float)MaxNodesPerNetworkEvent));
msg.WriteRangedInteger(nodeCount, 0, MaxNodesPerNetworkEvent);
for (int i = nodeStartIndex; i < nodeStartIndex + nodeCount; i++)
{
msg.Write(nodes[i].X);
msg.Write(nodes[i].Y);
}
}
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
int nodeCount = msg.ReadByte();
Vector2 lastNodePos = Vector2.Zero;
if (nodeCount > 0)
{
lastNodePos = new Vector2(msg.ReadSingle(), msg.ReadSingle());
}
if (!item.CanClientAccess(c)) { return; }
if (nodes.Count > nodeCount)
{
nodes.RemoveRange(nodeCount, nodes.Count - nodeCount);
}
if (nodeCount > 0)
{
if (nodeCount > nodes.Count)
{
nodes.Add(lastNodePos);
}
else
{
nodes[nodes.Count - 1] = lastNodePos;
}
}
CreateNetworkEvent();
}
}
}
@@ -0,0 +1,149 @@
using Barotrauma.Items.Components;
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma
{
partial class Inventory : IServerSerializable, IClientSerializable
{
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
List<Item> prevItems = new List<Item>(Items);
byte itemCount = msg.ReadByte();
ushort[] newItemIDs = new ushort[itemCount];
for (int i = 0; i < itemCount; i++)
{
newItemIDs[i] = msg.ReadUInt16();
}
if (c == null || c.Character == null) return;
bool accessible = c.Character.CanAccessInventory(this);
if (this is CharacterInventory && accessible)
{
if (Owner == null || !(Owner is Character))
{
accessible = false;
}
else if (!((CharacterInventory)this).AccessibleWhenAlive && !((Character)Owner).IsDead)
{
accessible = false;
}
}
if (!accessible)
{
//create a network event to correct the client's inventory state
//otherwise they may have an item in their inventory they shouldn't have been able to pick up,
//and receiving an event for that inventory later will cause the item to be dropped
CreateNetworkEvent();
for (int i = 0; i < capacity; i++)
{
if (!(Entity.FindEntityByID(newItemIDs[i]) is Item item)) { continue; }
item.PositionUpdateInterval = 0.0f;
if (item.ParentInventory != null && item.ParentInventory != this)
{
item.ParentInventory.CreateNetworkEvent();
}
}
return;
}
List<Inventory> prevItemInventories = new List<Inventory>(Items.Select(i => i?.ParentInventory));
for (int i = 0; i < capacity; i++)
{
Item newItem = newItemIDs[i] == 0 ? null : Entity.FindEntityByID(newItemIDs[i]) as Item;
prevItemInventories.Add(newItem?.ParentInventory);
if (newItemIDs[i] == 0 || (newItem != Items[i]))
{
if (Items[i] != null)
{
Item droppedItem = Items[i];
Entity prevOwner = Owner;
droppedItem.Drop(null);
if (droppedItem.body != null && prevOwner != null)
{
droppedItem.body.SetTransform(prevOwner.SimPosition, 0.0f);
}
}
System.Diagnostics.Debug.Assert(Items[i] == null);
}
}
for (int i = 0; i < capacity; i++)
{
if (newItemIDs[i] > 0)
{
if (!(Entity.FindEntityByID(newItemIDs[i]) is Item item) || item == Items[i]) { continue; }
if (GameMain.Server != null)
{
var holdable = item.GetComponent<Holdable>();
if (holdable != null && !holdable.CanBeDeattached()) { continue; }
if (!prevItems.Contains(item) && !item.CanClientAccess(c))
{
item.PositionUpdateInterval = 0.0f;
continue;
}
}
TryPutItem(item, i, true, true, c.Character, false);
for (int j = 0; j < capacity; j++)
{
if (Items[j] == item && newItemIDs[j] != item.ID)
{
Items[j] = null;
}
}
}
}
CreateNetworkEvent();
foreach (Inventory prevInventory in prevItemInventories.Distinct())
{
if (prevInventory != this) prevInventory?.CreateNetworkEvent();
}
foreach (Item item in Items.Distinct())
{
if (item == null) { continue; }
if (!prevItems.Contains(item))
{
if (Owner == c.Character)
{
GameServer.Log(c.Character.LogName+ " picked up " + item.Name, ServerLog.MessageType.Inventory);
}
else
{
GameServer.Log(c.Character.LogName + " placed " + item.Name + " in " + Owner, ServerLog.MessageType.Inventory);
}
}
}
foreach (Item item in prevItems.Distinct())
{
if (item == null) { continue; }
if (!Items.Contains(item))
{
if (Owner == c.Character)
{
GameServer.Log(c.Character.LogName + " dropped " + item.Name, ServerLog.MessageType.Inventory);
}
else
{
GameServer.Log(c.Character.LogName + " removed " + item.Name + " from " + Owner, ServerLog.MessageType.Inventory);
}
}
}
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
SharedWrite(msg, extraData);
}
}
}
@@ -0,0 +1,376 @@
using Barotrauma.Items.Components;
using Barotrauma.Networking;
using Microsoft.Xna.Framework;
using System;
using System.Linq;
namespace Barotrauma
{
partial class Item : MapEntity, IDamageable, ISerializableEntity, IServerSerializable, IClientSerializable
{
public override Sprite Sprite
{
get { return prefab?.sprite; }
}
public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null)
{
string errorMsg = "";
if (extraData == null || extraData.Length == 0 || !(extraData[0] is NetEntityEvent.Type))
{
if (extraData == null)
{
errorMsg = "Failed to write a network event for the item \"" + Name + "\" - event data was null.";
}
else if (extraData.Length == 0)
{
errorMsg = "Failed to write a network event for the item \"" + Name + "\" - event data was empty.";
}
else
{
errorMsg = "Failed to write a network event for the item \"" + Name + "\" - event type not set.";
}
msg.WriteRangedInteger((int)NetEntityEvent.Type.Invalid, 0, Enum.GetValues(typeof(NetEntityEvent.Type)).Length - 1);
DebugConsole.Log(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("Item.ServerWrite:InvalidData" + Name, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return;
}
int initialWritePos = msg.LengthBits;
NetEntityEvent.Type eventType = (NetEntityEvent.Type)extraData[0];
msg.WriteRangedInteger((int)eventType, 0, Enum.GetValues(typeof(NetEntityEvent.Type)).Length - 1);
switch (eventType)
{
case NetEntityEvent.Type.ComponentState:
if (extraData.Length < 2 || !(extraData[1] is int))
{
errorMsg = "Failed to write a component state event for the item \"" + Name + "\" - component index not given.";
break;
}
int componentIndex = (int)extraData[1];
if (componentIndex < 0 || componentIndex >= components.Count)
{
errorMsg = "Failed to write a component state event for the item \"" + Name + "\" - component index out of range (" + componentIndex + ").";
break;
}
else if (!(components[componentIndex] is IServerSerializable))
{
errorMsg = "Failed to write a component state event for the item \"" + Name + "\" - component \"" + components[componentIndex] + "\" is not server serializable.";
break;
}
msg.WriteRangedInteger(componentIndex, 0, components.Count - 1);
(components[componentIndex] as IServerSerializable).ServerWrite(msg, c, extraData);
break;
case NetEntityEvent.Type.InventoryState:
if (extraData.Length < 2 || !(extraData[1] is int))
{
errorMsg = "Failed to write an inventory state event for the item \"" + Name + "\" - component index not given.";
break;
}
int containerIndex = (int)extraData[1];
if (containerIndex < 0 || containerIndex >= components.Count)
{
errorMsg = "Failed to write an inventory state event for the item \"" + Name + "\" - container index out of range (" + containerIndex + ").";
break;
}
else if (!(components[containerIndex] is ItemContainer))
{
errorMsg = "Failed to write an inventory state event for the item \"" + Name + "\" - component \"" + components[containerIndex] + "\" is not server serializable.";
break;
}
msg.WriteRangedInteger(containerIndex, 0, components.Count - 1);
msg.Write(GameMain.Server.EntityEventManager.Events.Last()?.ID ?? (ushort)0);
(components[containerIndex] as ItemContainer).Inventory.ServerWrite(msg, c);
break;
case NetEntityEvent.Type.Status:
msg.Write(condition);
break;
case NetEntityEvent.Type.Treatment:
{
ItemComponent targetComponent = (ItemComponent)extraData[1];
ActionType actionType = (ActionType)extraData[2];
ushort targetID = (ushort)extraData[3];
Limb targetLimb = (Limb)extraData[4];
Character targetCharacter = FindEntityByID(targetID) as Character;
byte targetLimbIndex = targetLimb != null && targetCharacter != null ? (byte)Array.IndexOf(targetCharacter.AnimController.Limbs, targetLimb) : (byte)255;
msg.Write((byte)components.IndexOf(targetComponent));
msg.WriteRangedInteger((int)actionType, 0, Enum.GetValues(typeof(ActionType)).Length - 1);
msg.Write(targetID);
msg.Write(targetLimbIndex);
}
break;
case NetEntityEvent.Type.ApplyStatusEffect:
{
ActionType actionType = (ActionType)extraData[1];
ItemComponent targetComponent = extraData.Length > 2 ? (ItemComponent)extraData[2] : null;
ushort characterID = extraData.Length > 3 ? (ushort)extraData[3] : (ushort)0;
Limb targetLimb = extraData.Length > 4 ? (Limb)extraData[4] : null;
ushort useTargetID = extraData.Length > 5 ? (ushort)extraData[5] : (ushort)0;
Vector2? worldPosition = null;
if (extraData.Length > 6) { worldPosition = (Vector2)extraData[6]; }
Character targetCharacter = FindEntityByID(characterID) as Character;
byte targetLimbIndex = targetLimb != null && targetCharacter != null ? (byte)Array.IndexOf(targetCharacter.AnimController.Limbs, targetLimb) : (byte)255;
msg.WriteRangedInteger((int)actionType, 0, Enum.GetValues(typeof(ActionType)).Length - 1);
msg.Write((byte)(targetComponent == null ? 255 : components.IndexOf(targetComponent)));
msg.Write(characterID);
msg.Write(targetLimbIndex);
msg.Write(useTargetID);
msg.Write(worldPosition.HasValue);
if (worldPosition.HasValue)
{
msg.Write(worldPosition.Value.X);
msg.Write(worldPosition.Value.Y);
}
}
break;
case NetEntityEvent.Type.ChangeProperty:
try
{
WritePropertyChange(msg, extraData, false);
}
catch (Exception e)
{
errorMsg = "Failed to write a ChangeProperty network event for the item \"" + Name + "\" (" + e.Message + ")";
}
break;
default:
errorMsg = "Failed to write a network event for the item \"" + Name + "\" - \"" + eventType + "\" is not a valid entity event type for items.";
break;
}
if (!string.IsNullOrEmpty(errorMsg))
{
//something went wrong - rewind the write position and write invalid event type to prevent creating an unreadable event
msg.BitPosition = initialWritePos;
msg.LengthBits = initialWritePos;
msg.WriteRangedInteger((int)NetEntityEvent.Type.Invalid, 0, Enum.GetValues(typeof(NetEntityEvent.Type)).Length - 1);
DebugConsole.Log(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("Item.ServerWrite:" + errorMsg, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
}
}
public void ServerRead(ClientNetObject type, IReadMessage msg, Client c)
{
NetEntityEvent.Type eventType =
(NetEntityEvent.Type)msg.ReadRangedInteger(0, Enum.GetValues(typeof(NetEntityEvent.Type)).Length - 1);
c.KickAFKTimer = 0.0f;
switch (eventType)
{
case NetEntityEvent.Type.ComponentState:
int componentIndex = msg.ReadRangedInteger(0, components.Count - 1);
(components[componentIndex] as IClientSerializable).ServerRead(type, msg, c);
break;
case NetEntityEvent.Type.InventoryState:
int containerIndex = msg.ReadRangedInteger(0, components.Count - 1);
(components[containerIndex] as ItemContainer).Inventory.ServerRead(type, msg, c);
break;
case NetEntityEvent.Type.Treatment:
if (c.Character == null || !c.Character.CanInteractWith(this)) return;
UInt16 characterID = msg.ReadUInt16();
byte limbIndex = msg.ReadByte();
Character targetCharacter = FindEntityByID(characterID) as Character;
if (targetCharacter == null) break;
if (targetCharacter != c.Character && c.Character.SelectedCharacter != targetCharacter) break;
Limb targetLimb = limbIndex < targetCharacter.AnimController.Limbs.Length ? targetCharacter.AnimController.Limbs[limbIndex] : null;
if (ContainedItems == null || ContainedItems.All(i => i == null))
{
GameServer.Log(c.Character.LogName + " used item " + Name, ServerLog.MessageType.ItemInteraction);
}
else
{
GameServer.Log(
c.Character.LogName + " used item " + Name + " (contained items: " + string.Join(", ", ContainedItems.Select(i => i.Name)) + ")",
ServerLog.MessageType.ItemInteraction);
}
ApplyTreatment(c.Character, targetCharacter, targetLimb);
break;
case NetEntityEvent.Type.ChangeProperty:
ReadPropertyChange(msg, true, c);
break;
case NetEntityEvent.Type.Combine:
UInt16 combineTargetID = msg.ReadUInt16();
Item combineTarget = FindEntityByID(combineTargetID) as Item;
if (combineTarget == null || !c.Character.CanInteractWith(this) || !c.Character.CanInteractWith(combineTarget))
{
return;
}
Combine(combineTarget, c.Character);
break;
}
}
public void WriteSpawnData(IWriteMessage msg, UInt16 entityID)
{
if (GameMain.Server == null) return;
msg.Write(Prefab.OriginalName);
msg.Write(Prefab.Identifier);
msg.Write(Description != prefab.Description);
if (Description != prefab.Description)
{
msg.Write(Description);
}
msg.Write(entityID);
if (ParentInventory == null || ParentInventory.Owner == null)
{
msg.Write((ushort)0);
msg.Write(Position.X);
msg.Write(Position.Y);
msg.Write(Submarine != null ? Submarine.ID : (ushort)0);
}
else
{
msg.Write(ParentInventory.Owner.ID);
//find the index of the ItemContainer this item is inside to get the item to
//spawn in the correct inventory in multi-inventory items like fabricators
byte containerIndex = 0;
if (Container != null)
{
for (int i = 0; i < Container.components.Count; i++)
{
if (Container.components[i] is ItemContainer container &&
container.Inventory == ParentInventory)
{
containerIndex = (byte)i;
break;
}
}
}
msg.Write(containerIndex);
int slotIndex = ParentInventory.FindIndex(this);
msg.Write(slotIndex < 0 ? (byte)255 : (byte)slotIndex);
}
byte teamID = 0;
foreach (WifiComponent wifiComponent in GetComponents<WifiComponent>())
{
teamID = (byte)wifiComponent.TeamID;
break;
}
msg.Write(teamID);
bool tagsChanged = tags.Count != prefab.Tags.Count || !tags.All(t => prefab.Tags.Contains(t));
msg.Write(tagsChanged);
if (tagsChanged)
{
msg.Write(Tags);
}
}
partial void UpdateNetPosition(float deltaTime)
{
if (parentInventory != null || body == null || !body.Enabled || Removed)
{
PositionUpdateInterval = float.PositiveInfinity;
return;
}
//gradually increase the interval of position updates
PositionUpdateInterval += deltaTime;
float maxInterval = 30.0f;
float velSqr = body.LinearVelocity.LengthSquared();
if (velSqr > 10.0f * 10.0f)
{
//over 10 m/s (projectile, thrown item or similar) -> send updates very frequently
maxInterval = 0.1f;
}
else if (velSqr > 1.0f)
{
//over 1 m/s
maxInterval = 0.25f;
}
else if (velSqr > 0.05f * 0.05f)
{
//over 0.05 m/s
maxInterval = 1.0f;
}
PositionUpdateInterval = Math.Min(PositionUpdateInterval, maxInterval);
}
public float GetPositionUpdateInterval(Client recipient)
{
if (PositionUpdateInterval == float.PositiveInfinity || body == null || parentInventory != null)
{
return float.PositiveInfinity;
}
if (recipient.Character == null || recipient.Character.IsDead)
{
//less frequent updates for clients who aren't controlling a character (max 2 updates/sec)
return Math.Max(PositionUpdateInterval, 0.5f);
}
else
{
float distSqr = Vector2.DistanceSquared(recipient.Character.WorldPosition, WorldPosition);
if (distSqr > 20000.0f * 20000.0f)
{
//don't send position updates at all if >20 000 units away
return float.PositiveInfinity;
}
else if (distSqr > 10000.0f * 10000.0f)
{
//drop the update rate to 10% if too far to see the item
return PositionUpdateInterval * 10;
}
else if (distSqr > 1000.0f * 1000.0f)
{
//halve the update rate if the client is far away (but still close enough to possibly see the item)
return PositionUpdateInterval * 2;
}
return PositionUpdateInterval;
}
}
public void ServerWritePosition(IWriteMessage msg, Client c, object[] extraData = null)
{
msg.Write(ID);
IWriteMessage tempBuffer = new WriteOnlyMessage();
body.ServerWrite(tempBuffer, c, extraData);
msg.WriteVariableUInt32((uint)tempBuffer.LengthBytes);
msg.Write(tempBuffer.Buffer, 0, tempBuffer.LengthBytes);
msg.WritePadBits();
}
public void CreateServerEvent<T>(T ic) where T : ItemComponent, IServerSerializable
{
if (GameMain.Server == null) return;
if (!ItemList.Contains(this))
{
string errorMsg = "Attempted to create a network event for an item (" + Name + ") that hasn't been fully initialized yet.\n" + Environment.StackTrace;
DebugConsole.ThrowError(errorMsg);
GameAnalyticsManager.AddErrorEventOnce("Item.CreateServerEvent:EventForUninitializedItem" + Name + ID, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
return;
}
int index = components.IndexOf(ic);
if (index == -1) return;
GameMain.Server.CreateEntityEvent(this, new object[] { NetEntityEvent.Type.ComponentState, index });
}
}
}