This commit is contained in:
Evil Factory
2022-04-28 12:36:24 -03:00
91 changed files with 1140 additions and 491 deletions
@@ -838,7 +838,7 @@ namespace Barotrauma
if (container == null) { return 0; }
if (!container.Inventory.CanBePut(containableItem)) { return 0; }
var rootContainer = container.Item.GetRootContainer();
if (rootContainer?.GetComponent<Fabricator>() != null || rootContainer?.GetComponent<Fabricator>() != null) { return 0; }
if (rootContainer?.GetComponent<Fabricator>() != null || rootContainer?.GetComponent<Deconstructor>() != null) { return 0; }
if (container.ShouldBeContained(containableItem, out bool isRestrictionsDefined))
{
if (isRestrictionsDefined)
@@ -57,8 +57,6 @@ namespace Barotrauma
private readonly int speakerIndex;
private readonly ImmutableHashSet<Identifier> allowedSpeakerTags;
private readonly bool requireNextLine;
// used primarily for team1 characters interacting with escorted personnel (TODO: not used anywhere)
private readonly bool requireSight;
public NPCConversation(XElement element)
{
@@ -75,7 +73,6 @@ namespace Barotrauma
Responses = element.Elements().Select(s => new NPCConversation(s)).ToImmutableArray();
requireNextLine = element.GetAttributeBool("requirenextline", false);
requireSight = element.GetAttributeBool("requiresight", false);
}
private static List<Identifier> GetCurrentFlags(Character speaker)
@@ -162,23 +159,38 @@ namespace Barotrauma
return currentFlags;
}
private static List<NPCConversation> previousConversations = new List<NPCConversation>();
private static readonly List<NPCConversation> previousConversations = new List<NPCConversation>();
public static List<Pair<Character, string>> CreateRandom(List<Character> availableSpeakers)
public static List<(Character speaker, string line)> CreateRandom(List<Character> availableSpeakers)
{
Dictionary<int, Character> assignedSpeakers = new Dictionary<int, Character>();
List<Pair<Character, string>> lines = new List<Pair<Character, string>>();
List<(Character speaker, string line)> lines = new List<(Character speaker, string line)>();
var language = GameSettings.CurrentConfig.Language;
if (language != TextManager.DefaultLanguage && !NPCConversationCollection.Collections.ContainsKey(language))
{
DebugConsole.AddWarning($"Could not find NPC conversations for the language \"{language}\". Using \"{TextManager.DefaultLanguage}\" instead..");
language = TextManager.DefaultLanguage;
}
CreateConversation(availableSpeakers, assignedSpeakers, null, lines,
availableConversations: NPCConversationCollection.Collections[GameSettings.CurrentConfig.Language].SelectMany(cc => cc.Conversations).ToList());
availableConversations: NPCConversationCollection.Collections[language].SelectMany(cc => cc.Conversations).ToList());
return lines;
}
public static List<Pair<Character, string>> CreateRandom(List<Character> availableSpeakers, IEnumerable<Identifier> requiredFlags)
public static List<(Character speaker, string line)> CreateRandom(List<Character> availableSpeakers, IEnumerable<Identifier> requiredFlags)
{
Dictionary<int, Character> assignedSpeakers = new Dictionary<int, Character>();
List<Pair<Character, string>> lines = new List<Pair<Character, string>>();
var availableConversations = NPCConversationCollection.Collections[GameSettings.CurrentConfig.Language]
List<(Character speaker, string line)> lines = new List<(Character speaker, string line)>();
var language = GameSettings.CurrentConfig.Language;
if (language != TextManager.DefaultLanguage && !NPCConversationCollection.Collections.ContainsKey(language))
{
DebugConsole.AddWarning($"Could not find NPC conversations for the language \"{language}\". Using \"{TextManager.DefaultLanguage}\" instead..");
language = TextManager.DefaultLanguage;
}
var availableConversations = NPCConversationCollection.Collections[language]
.SelectMany(cc => cc.Conversations.Where(c => requiredFlags.All(f => c.Flags.Contains(f)))).ToList();
if (availableConversations.Count > 0)
{
@@ -191,7 +203,7 @@ namespace Barotrauma
List<Character> availableSpeakers,
Dictionary<int, Character> assignedSpeakers,
NPCConversation baseConversation,
IList<Pair<Character, string>> lineList,
IList<(Character speaker, string line)> lineList,
IList<NPCConversation> availableConversations,
bool ignoreFlags = false)
{
@@ -271,7 +283,7 @@ namespace Barotrauma
previousConversations.Insert(0, selectedConversation);
if (previousConversations.Count > MaxPreviousConversations) previousConversations.RemoveAt(MaxPreviousConversations);
}
lineList.Add(new Pair<Character, string>(speaker, selectedConversation.Line));
lineList.Add((speaker, selectedConversation.Line));
CreateConversation(availableSpeakers, assignedSpeakers, selectedConversation, lineList, availableConversations);
}
@@ -2749,12 +2749,15 @@ namespace Barotrauma
if (!Enabled) { return; }
if (Level.Loaded != null && WorldPosition.Y < Level.MaxEntityDepth ||
(Submarine != null && Submarine.WorldPosition.Y < Level.MaxEntityDepth))
if (Level.Loaded != null)
{
Enabled = false;
Kill(CauseOfDeathType.Pressure, null);
return;
if (WorldPosition.Y < Level.MaxEntityDepth ||
(Submarine != null && Submarine.WorldPosition.Y < Level.MaxEntityDepth))
{
Enabled = false;
Kill(CauseOfDeathType.Pressure, null);
return;
}
}
ApplyStatusEffects(ActionType.Always, deltaTime);
@@ -130,15 +130,15 @@ namespace Barotrauma
head = value;
HeadSprite = null;
AttachmentSprites = null;
IsMale = value.Preset?.TagSet?.Contains("Male".ToIdentifier()) ?? false;
IsFemale = value.Preset?.TagSet?.Contains("Female".ToIdentifier()) ?? false;
}
}
}
public bool IsMale { get; private set; }
private readonly Identifier maleIdentifier = "Male".ToIdentifier();
private readonly Identifier femaleIdentifier = "Female".ToIdentifier();
public bool IsFemale { get; private set; }
public bool IsMale { get { return head?.Preset?.TagSet?.Contains(maleIdentifier) ?? false; } }
public bool IsFemale { get { return head?.Preset?.TagSet?.Contains(femaleIdentifier) ?? false; } }
public CharacterInfoPrefab Prefab => CharacterPrefab.Prefabs[SpeciesName].CharacterInfoPrefab;
public class HeadPreset : ISerializableEntity
@@ -1033,7 +1033,7 @@ namespace Barotrauma
if (Name == null || Job == null) { return 0; }
int salary = 0;
foreach (Skill skill in Job.Skills)
foreach (Skill skill in Job.GetSkills())
{
salary += (int)(skill.Level * skill.PriceMultiplier);
}
@@ -1076,10 +1076,10 @@ namespace Barotrauma
{
if (Job == null) { return; }
var skill = Job.Skills.Find(s => s.Identifier == skillIdentifier);
var skill = Job.GetSkill(skillIdentifier);
if (skill == null)
{
Job.Skills.Add(new Skill(skillIdentifier, level));
Job.IncreaseSkillLevel(skillIdentifier, level, increasePastMax: false);
OnSkillChanged(skillIdentifier, 0.0f, level);
}
else
@@ -384,7 +384,7 @@ namespace Barotrauma
foreach (var itemPrefab in ItemPrefab.Prefabs)
{
float suitability = Math.Max(itemPrefab.GetTreatmentSuitability(Identifier), itemPrefab.GetTreatmentSuitability(AfflictionType));
if (suitability > 0.0f)
if (!MathUtils.NearlyEqual(suitability, 0.0f))
{
yield return new KeyValuePair<Identifier, float>(itemPrefab.Identifier, suitability);
}
@@ -154,10 +154,14 @@ namespace Barotrauma
public void GiveItems(Character character, Submarine submarine, Rand.RandSync randSync = Rand.RandSync.Unsynced, bool createNetworkEvents = true)
{
if (ItemSets == null || !ItemSets.Any()) { return; }
var spawnItems = ToolBox.SelectWeightedRandom(ItemSets.Keys.ToList(), ItemSets.Values.ToList(), randSync);
foreach (XElement itemElement in spawnItems.GetChildElements("item"))
if (spawnItems != null)
{
InitializeItem(character, itemElement, submarine, this, createNetworkEvents: createNetworkEvents);
foreach (XElement itemElement in spawnItems.GetChildElements("item"))
{
InitializeItem(character, itemElement, submarine, this, createNetworkEvents: createNetworkEvents);
}
}
}
@@ -17,8 +17,6 @@ namespace Barotrauma
public JobPrefab Prefab => prefab;
public List<Skill> Skills => skills.Values.ToList();
public int Variant;
public Skill PrimarySkill { get; }
@@ -80,7 +78,12 @@ namespace Barotrauma
var prefab = JobPrefab.Random(randSync);
var variant = Rand.Range(0, prefab.Variants, randSync);
return new Job(prefab, randSync, variant);
}
}
public IEnumerable<Skill> GetSkills()
{
return skills.Values;
}
public float GetSkillLevel(Identifier skillIdentifier)
{
@@ -89,6 +92,22 @@ namespace Barotrauma
return skill?.Level ?? 0.0f;
}
public Skill GetSkill(Identifier skillIdentifier)
{
if (skillIdentifier.IsEmpty) { return null; }
skills.TryGetValue(skillIdentifier, out Skill skill);
return skill;
}
public void OverrideSkills(Dictionary<Identifier, float> newSkills)
{
skills.Clear();
foreach (var newSkill in newSkills)
{
skills.Add(newSkill.Key, new Skill(newSkill.Key, newSkill.Value));
}
}
public void IncreaseSkillLevel(Identifier skillIdentifier, float increase, bool increasePastMax)
{
if (skills.TryGetValue(skillIdentifier, out Skill skill))
@@ -171,7 +190,7 @@ namespace Barotrauma
character.Inventory.TryPutItem(item, null, item.AllowedSlots);
}
Wearable wearable = ((List<ItemComponent>)item.Components)?.Find(c => c is Wearable) as Wearable;
Wearable wearable = item.GetComponent<Wearable>();
if (wearable != null)
{
if (Variant > 0 && Variant <= wearable.Variants)
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Barotrauma
@@ -12,7 +11,7 @@ namespace Barotrauma
public readonly List<string> AllowedDialogTags;
private float commonness;
private readonly float commonness;
public float Commonness
{
get { return commonness; }
@@ -20,12 +19,22 @@ namespace Barotrauma
public static IEnumerable<NPCPersonalityTrait> GetAll(LanguageIdentifier language)
{
if (language != TextManager.DefaultLanguage && !NPCConversationCollection.Collections.ContainsKey(language))
{
DebugConsole.AddWarning($"Could not find NPC personality traits for the language \"{language}\". Using \"{TextManager.DefaultLanguage}\" instead..");
language = TextManager.DefaultLanguage;
}
return NPCConversationCollection.Collections[language]
.SelectMany(cc => cc.PersonalityTraits.Values);
}
public static NPCPersonalityTrait Get(LanguageIdentifier language, Identifier traitName)
{
if (language != TextManager.DefaultLanguage && !NPCConversationCollection.Collections.ContainsKey(language))
{
DebugConsole.AddWarning($"Could not find NPC personality traits for the language \"{language}\". Using \"{TextManager.DefaultLanguage}\" instead..");
language = TextManager.DefaultLanguage;
}
return NPCConversationCollection.Collections[language]
.FirstOrDefault(cc => cc.PersonalityTraits.ContainsKey(traitName))
.PersonalityTraits[traitName];
@@ -293,6 +293,10 @@ namespace Barotrauma
{
return Create<HumanSwimFastParams>(fullPath, speciesName, animationType);
}
if (type == typeof(HumanCrouchParams))
{
return Create<HumanCrouchParams>(fullPath, speciesName, animationType);
}
if (type == typeof(FishWalkParams))
{
return Create<FishWalkParams>(fullPath, speciesName, animationType);
@@ -47,7 +47,7 @@ namespace Barotrauma.Abilities
{
if (skillIdentifier == "random")
{
var skill = character.Info?.Job?.Skills?.GetRandomUnsynced();
var skill = character.Info?.Job?.GetSkills()?.GetRandomUnsynced();
if (skill == null) { return; }
character.Info?.IncreaseSkillLevel(skill.Identifier, skillIncrease, gainedFromAbility: true);
}
@@ -30,11 +30,12 @@ namespace Barotrauma.Abilities
if (useAll && Character.Info?.Job != null)
{
foreach (Skill skill in Character.Info.Job.Skills)
var skills = Character.Info.Job.GetSkills();
foreach (Skill skill in skills)
{
skillTotal += Character.GetSkillLevel(skill.Identifier);
}
skillTotal /= Character.Info.Job.Skills.Count;
skillTotal /= skills.Count();
}
else
{
@@ -825,7 +825,7 @@ namespace Barotrauma
if (isMax) { level = 100; }
if (skillIdentifier == "all")
{
foreach (Skill skill in character.Info.Job.Skills)
foreach (Skill skill in character.Info.Job.GetSkills())
{
character.Info.SetSkillLevel(skill.Identifier, level);
}
@@ -845,7 +845,7 @@ namespace Barotrauma
{
return new[]
{
Character.Controlled?.Info?.Job?.Skills?.Select(skill => skill.Identifier.Value).ToArray() ?? Array.Empty<string>(),
Character.Controlled?.Info?.Job?.GetSkills()?.Select(skill => skill.Identifier.Value).ToArray() ?? Array.Empty<string>(),
new[]{ "max" },
Character.CharacterList.Select(c => c.Name).Distinct().OrderBy(n => n).ToArray(),
};
@@ -1747,20 +1747,12 @@ namespace Barotrauma
ThrowError(args[1] + " is not a valid latency value.");
return;
}
#if CLIENT
if (GameMain.Client != null)
if (GameMain.NetworkMember != null)
{
GameMain.Client.SimulatedMinimumLatency = minimumLatency;
GameMain.Client.SimulatedRandomLatency = randomLatency;
GameMain.NetworkMember.SimulatedMinimumLatency = minimumLatency;
GameMain.NetworkMember.SimulatedRandomLatency = randomLatency;
}
#elif SERVER
if (GameMain.Server != null)
{
GameMain.Server.SimulatedMinimumLatency = minimumLatency;
GameMain.Server.SimulatedRandomLatency = randomLatency;
}
#endif
NewMessage("Set simulated minimum latency to " + minimumLatency + " and random latency to " + randomLatency + ".", Color.White);
NewMessage("Set simulated minimum latency to " + minimumLatency.ToString(CultureInfo.InvariantCulture) + " and random latency to " + randomLatency.ToString(CultureInfo.InvariantCulture) + ".", Color.White);
}));
commands.Add(new Command("simulatedloss", "simulatedloss [lossratio]: applies simulated packet loss to network messages. For example, a value of 0.1 would mean 10% of the packets are dropped. Useful for simulating real network conditions when testing the multiplayer locally.", (string[] args) =>
@@ -1771,17 +1763,10 @@ namespace Barotrauma
ThrowError(args[0] + " is not a valid loss ratio.");
return;
}
#if CLIENT
if (GameMain.Client != null)
if (GameMain.NetworkMember != null)
{
GameMain.Client.SimulatedLoss = loss;
GameMain.NetworkMember.SimulatedLoss = loss;
}
#elif SERVER
if (GameMain.Server != null)
{
GameMain.Server.SimulatedLoss = loss;
}
#endif
NewMessage("Set simulated packet loss to " + (int)(loss * 100) + "%.", Color.White);
}));
commands.Add(new Command("simulatedduplicateschance", "simulatedduplicateschance [duplicateratio]: simulates packet duplication in network messages. For example, a value of 0.1 would mean there's a 10% chance a packet gets sent twice. Useful for simulating real network conditions when testing the multiplayer locally.", (string[] args) =>
@@ -1792,21 +1777,27 @@ namespace Barotrauma
ThrowError(args[0] + " is not a valid duplicate ratio.");
return;
}
#if CLIENT
if (GameMain.Client != null)
if (GameMain.NetworkMember != null)
{
GameMain.Client.SimulatedDuplicatesChance = duplicates;
GameMain.NetworkMember.SimulatedDuplicatesChance = duplicates;
}
#elif SERVER
if (GameMain.Server != null)
{
GameMain.Server.SimulatedDuplicatesChance = duplicates;
}
#endif
NewMessage("Set packet duplication to " + (int)(duplicates * 100) + "%.", Color.White);
}));
#if DEBUG
commands.Add(new Command("simulatedlongloadingtime", "simulatedlongloadingtime [minimum loading time]: forces loading a round to take at least the specified amount of seconds.", (string[] args) =>
{
if (args.Count() < 1 || (GameMain.NetworkMember == null)) return;
if (!float.TryParse(args[0], NumberStyles.Any, CultureInfo.InvariantCulture, out float time))
{
ThrowError(args[0] + " is not a valid duration ratio.");
return;
}
GameSession.MinimumLoadingTime = time;
NewMessage("Set minimum loading time to " + time + " seconds.", Color.White);
}));
commands.Add(new Command("storeinfo", "", (string[] args) =>
{
if (GameMain.GameSession?.Map?.CurrentLocation is Location location)
@@ -316,7 +316,7 @@ namespace Barotrauma
}
// Exchange money
int itemValue = item.Quantity * buyValues[item.ItemPrefab];
campaign.GetWallet(client).TryDeduct(itemValue);
campaign.TryPurchase(client, itemValue);
GameAnalyticsManager.AddMoneySpentEvent(itemValue, GameAnalyticsManager.MoneySink.Store, item.ItemPrefab.Identifier.Value);
store.Balance += itemValue;
if (removeFromCrate)
@@ -13,7 +13,7 @@ namespace Barotrauma
const float ConversationIntervalMax = 180.0f;
const float ConversationIntervalMultiplierMultiplayer = 5.0f;
private float conversationTimer, conversationLineTimer;
private readonly List<Pair<Character, string>> pendingConversationLines = new List<Pair<Character, string>>();
private readonly List<(Character speaker, string line)> pendingConversationLines = new List<(Character speaker, string line)>();
public const int MaxCrewSize = 16;
@@ -339,7 +339,7 @@ namespace Barotrauma
#region Dialog
public void AddConversation(List<Pair<Character, string>> conversationLines)
public void AddConversation(List<(Character speaker, string line)> conversationLines)
{
if (conversationLines == null || conversationLines.Count == 0) { return; }
pendingConversationLines.AddRange(conversationLines);
@@ -428,16 +428,16 @@ namespace Barotrauma
if (conversationLineTimer <= 0.0f)
{
//speaker of the next line can't speak, interrupt the conversation
if (pendingConversationLines[0].First.SpeechImpediment >= 100.0f)
if (pendingConversationLines[0].speaker.SpeechImpediment >= 100.0f)
{
pendingConversationLines.Clear();
return;
}
pendingConversationLines[0].First.Speak(pendingConversationLines[0].Second, null);
pendingConversationLines[0].speaker.Speak(pendingConversationLines[0].line, null);
if (pendingConversationLines.Count > 1)
{
conversationLineTimer = MathHelper.Clamp(pendingConversationLines[0].Second.Length * 0.1f, 1.0f, 5.0f);
conversationLineTimer = MathHelper.Clamp(pendingConversationLines[0].line.Length * 0.1f, 1.0f, 5.0f);
}
pendingConversationLines.RemoveAt(0);
}
@@ -227,6 +227,21 @@ namespace Barotrauma
return Bank;
}
public virtual bool TryPurchase(Client client, int price)
{
return GetWallet(client).TryDeduct(price);
}
public virtual int GetBalance(Client client = null)
{
return GetWallet(client).Balance;
}
public bool CanAfford(int cost, Client client = null)
{
return GetBalance(client) >= cost;
}
/// <summary>
/// The location that's displayed as the "current one" in the map screen. Normally the current outpost or the location at the start of the level,
/// but when selecting the next destination at the end of the level at an uninhabited location we use the location at the end
@@ -766,7 +781,7 @@ namespace Barotrauma
public bool TryHireCharacter(Location location, CharacterInfo characterInfo, Client client = null)
{
if (characterInfo == null) { return false; }
if (!GetWallet(client).TryDeduct(characterInfo.Salary)) { return false; }
if (!TryPurchase(client, characterInfo.Salary)) { return false; }
characterInfo.IsNewHire = true;
location.RemoveHireableCharacter(characterInfo);
CrewManager.AddCharacterInfo(characterInfo);
@@ -14,6 +14,10 @@ namespace Barotrauma
{
partial class GameSession
{
#if DEBUG
public static float MinimumLoadingTime;
#endif
public enum InfoFrameTab { Crew, Mission, MyCharacter, Traitor };
public readonly EventManager EventManager;
@@ -292,7 +296,7 @@ namespace Barotrauma
if ((GameMain.NetworkMember is null || GameMain.NetworkMember is { IsServer: true }) && cost > 0)
{
Campaign!.GetWallet(client).TryDeduct(cost);
Campaign!.TryPurchase(client, cost);
}
GameAnalyticsManager.AddMoneySpentEvent(cost, GameAnalyticsManager.MoneySink.SubmarineSwitch, newSubmarine.Name);
Campaign!.PendingSubmarineSwitch = newSubmarine;
@@ -303,7 +307,7 @@ namespace Barotrauma
public void PurchaseSubmarine(SubmarineInfo newSubmarine, Client? client = null)
{
if (Campaign is null) { return; }
if ((GameMain.NetworkMember is null || GameMain.NetworkMember is { IsServer: true }) && !Campaign.GetWallet(client).TryDeduct(newSubmarine.Price)) { return; }
if ((GameMain.NetworkMember is null || GameMain.NetworkMember is { IsServer: true }) && !Campaign.TryPurchase(client, newSubmarine.Price)) { return; }
if (!OwnedSubmarines.Any(s => s.Name == newSubmarine.Name))
{
GameAnalyticsManager.AddMoneySpentEvent(newSubmarine.Price, GameAnalyticsManager.MoneySink.SubmarinePurchase, newSubmarine.Name);
@@ -355,6 +359,9 @@ namespace Barotrauma
public void StartRound(LevelData? levelData, bool mirrorLevel = false, SubmarineInfo? startOutpost = null, SubmarineInfo? endOutpost = null)
{
#if DEBUG
DateTime startTime = DateTime.Now;
#endif
AfflictionPrefab.LoadAllEffects();
MirrorLevel = mirrorLevel;
@@ -485,6 +492,15 @@ namespace Barotrauma
}
}
#if DEBUG
double startDuration = (DateTime.Now - startTime).TotalSeconds;
if (startDuration < MinimumLoadingTime)
{
int sleepTime = (int)((MinimumLoadingTime - startDuration) * 1000);
DebugConsole.NewMessage($"Stalling round start by {sleepTime / 1000.0f} s (minimum loading time set to {MinimumLoadingTime})...", Color.Magenta);
System.Threading.Thread.Sleep(sleepTime);
}
#endif
#if CLIENT
if (GameMode is CampaignMode && levelData != null) { SteamAchievementManager.OnBiomeDiscovered(levelData.Biome); }
@@ -213,7 +213,7 @@ namespace Barotrauma
if (!force)
{
if (IsOutpostInCombat()) { return HealRequestResult.Refused; }
if (!GetWallet(client).TryDeduct(totalCost)) { return HealRequestResult.InsufficientFunds; }
if (!(campaign?.TryPurchase(client, totalCost) ?? false)) { return HealRequestResult.InsufficientFunds; }
}
ImmutableArray<CharacterInfo> crew = GetCrewCharacters();
@@ -314,10 +314,7 @@ namespace Barotrauma
private int GetAdjustedPrice(int price) => campaign?.Map?.CurrentLocation is { Type: { HasOutpost: true } } currentLocation ? currentLocation.GetAdjustedHealCost(price) : int.MaxValue;
public Wallet GetWallet(Client? c = null)
{
return campaign?.GetWallet(c) ?? Wallet.Invalid;
}
public int GetBalance() => campaign?.GetBalance() ?? 0;
public static ImmutableArray<CharacterInfo> GetCrewCharacters()
{
@@ -216,7 +216,7 @@ namespace Barotrauma
price = 0;
}
if (Campaign.GetWallet(client).TryDeduct(price))
if (Campaign.TryPurchase(client, price))
{
if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer)
{
@@ -313,7 +313,7 @@ namespace Barotrauma
price = 0;
}
if (Campaign.GetWallet(client).TryDeduct(price))
if (Campaign.TryPurchase(client, price))
{
PurchasedItemSwaps.RemoveAll(p => linkedItems.Contains(p.ItemToRemove));
if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer)
@@ -3,7 +3,6 @@ using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
@@ -18,6 +17,8 @@ namespace Barotrauma.Items.Components
const int MaxNodes = 100;
const float MaxNodeDistance = 150.0f;
private bool waitForVoltageRecalculation;
public struct Node
{
public Vector2 WorldPosition;
@@ -120,6 +121,7 @@ namespace Barotrauma.Items.Components
CurrPowerConsumption = powerConsumption;
Voltage = 0.0f;
waitForVoltageRecalculation = true;
charging = true;
timer = Duration;
IsActive = true;
@@ -134,6 +136,12 @@ namespace Barotrauma.Items.Components
#if CLIENT
frameOffset = Rand.Int(electricitySprite.FrameCount);
#endif
if (waitForVoltageRecalculation)
{
waitForVoltageRecalculation = false;
return;
}
if (timer <= 0.0f)
{
IsActive = false;
@@ -33,9 +33,6 @@ namespace Barotrauma.Items.Components
set;
}
private JobPrefab cachedJobPrefab;
private string cachedName;
public ImmutableHashSet<Identifier> OwnerTagSet { get; set; }
[Serialize("", IsPropertySaveable.Yes, alwaysUseInstanceValues: true)]
@@ -98,6 +95,7 @@ namespace Barotrauma.Items.Components
OwnerName = info.Name;
OwnerJobId = info.Job?.Prefab.Identifier ?? Identifier.Empty;
item.AddTag($"jobid:{OwnerJobId}");
OwnerTagSet = info.Head.Preset.TagSet;
OwnerHairIndex = head.HairIndex;
OwnerBeardIndex = head.BeardIndex;
@@ -315,6 +315,15 @@ namespace Barotrauma.Items.Components
}
}
private Client GetUsingClient()
{
#if SERVER
return GameMain.Server.ConnectedClients.Find(c => c.Character == user);
#elif CLIENT
return null;
#endif
}
private void Fabricate()
{
RefreshAvailableIngredients();
@@ -327,9 +336,20 @@ namespace Barotrauma.Items.Components
if (fabricatedItem.RequiredMoney > 0)
{
if (user == null) { return; }
if (GameMain.GameSession?.GameMode is MultiPlayerCampaign)
if (GameMain.GameSession?.GameMode is MultiPlayerCampaign mpCampaign)
{
user.Wallet.Deduct(fabricatedItem.RequiredMoney);
#if CLIENT
mpCampaign.TryPurchase(null, fabricatedItem.RequiredMoney);
#elif SERVER
if (GetUsingClient() is { } client)
{
mpCampaign.TryPurchase(client, fabricatedItem.RequiredMoney);
}
else
{
user.Wallet.Deduct(fabricatedItem.RequiredMoney);
}
#endif
}
else if (GameMain.GameSession?.GameMode is CampaignMode campaign)
{
@@ -530,6 +550,10 @@ namespace Barotrauma.Items.Components
{
floatQuality += user.Info.GetSavedStatValue(StatTypes.IncreaseFabricationQuality, tag);
}
if (!fabricatedItem.TargetItem.Tags.Contains(fabricatedItem.TargetItem.Identifier))
{
floatQuality += user.Info.GetSavedStatValue(StatTypes.IncreaseFabricationQuality, fabricatedItem.TargetItem.Identifier);
}
quality = (int)floatQuality;
const int MaxCraftingSkill = 100;
@@ -548,17 +572,22 @@ namespace Barotrauma.Items.Components
if (fabricableItem.RequiredMoney > 0)
{
if (GameMain.GameSession?.GameMode is MultiPlayerCampaign)
switch (GameMain.GameSession?.GameMode)
{
if (character?.Wallet == null || character.Wallet.Balance < fabricableItem.RequiredMoney) { return false; }
}
else if (GameMain.GameSession?.GameMode is CampaignMode campaign)
{
if (campaign.Bank.Balance < fabricableItem.RequiredMoney) { return false; }
}
else
{
return false;
case MultiPlayerCampaign mpCampaign:
{
if (!mpCampaign.CanAfford(fabricableItem.RequiredMoney, GetUsingClient())) { return false; }
break;
}
case CampaignMode campaign:
{
if (campaign.Bank.Balance < fabricableItem.RequiredMoney) { return false; }
break;
}
default:
return false;
}
}
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Xml.Linq;
namespace Barotrauma.Items.Components
{
@@ -565,16 +565,20 @@ namespace Barotrauma.Items.Components
//Iterate through all connections in the group to get their minmax power and sum them
foreach (Connection c in scrGroup.Connections)
{
Powered device = c.Item.GetComponent<Powered>();
scrGroup.MinMaxPower += device.MinMaxPowerOut(c, grid.Load);
foreach (var device in c.Item.GetComponents<Powered>())
{
scrGroup.MinMaxPower += device.MinMaxPowerOut(c, grid.Load);
}
}
//Iterate through all connections to get their final power out provided the min max information
float addedPower = 0;
foreach (Connection c in scrGroup.Connections)
{
Powered device = c.Item.GetComponent<Powered>();
addedPower += device.GetConnectionPowerOut(c, grid.Power, scrGroup.MinMaxPower, grid.Load);
foreach (var device in c.Item.GetComponents<Powered>())
{
addedPower += device.GetConnectionPowerOut(c, grid.Power, scrGroup.MinMaxPower, grid.Load);
}
}
//Add the power to the grid
@@ -591,10 +595,12 @@ namespace Barotrauma.Items.Components
grid.Voltage = newVoltage;
//Iterate through all connections on that grid and run their gridResolved function
foreach (Connection con in grid.Connections)
foreach (Connection c in grid.Connections)
{
Powered device = con.Item.GetComponent<Powered>();
device?.GridResolved(con);
foreach (var device in c.Item.GetComponents<Powered>())
{
device?.GridResolved(c);
}
}
}
@@ -671,21 +677,18 @@ namespace Barotrauma.Items.Components
/// </summary>
protected float GetAvailableInstantaneousBatteryPower()
{
if (item.Connections == null) { return 0.0f; }
if (item.Connections == null || powerIn == null) { return 0.0f; }
float availablePower = 0.0f;
foreach (Connection c in item.Connections)
var recipients = powerIn.Recipients;
foreach (Connection recipient in recipients)
{
var recipients = c.Recipients;
foreach (Connection recipient in recipients)
{
if (!recipient.IsPower || !recipient.IsOutput) { continue; }
var battery = recipient.Item?.GetComponent<PowerContainer>();
if (battery == null) { continue; }
float maxOutputPerFrame = battery.MaxOutPut / 60.0f;
float framesPerMinute = 3600.0f;
availablePower += Math.Min(battery.Charge * framesPerMinute, maxOutputPerFrame);
}
}
if (!recipient.IsPower || !recipient.IsOutput) { continue; }
var battery = recipient.Item?.GetComponent<PowerContainer>();
if (battery == null || battery.Item.Condition <= 0.0f) { continue; }
float maxOutputPerFrame = battery.MaxOutPut / 60.0f;
float framesPerMinute = 3600.0f;
availablePower += Math.Min(battery.Charge * framesPerMinute, maxOutputPerFrame);
}
return availablePower;
}
@@ -597,7 +597,7 @@ namespace Barotrauma.Items.Components
else if (ic is PowerTransfer pt)
{
//power transfer items (junction boxes, relays) don't deteriorate if they're no carrying any power
if (Math.Abs(pt.CurrPowerConsumption) > 0.1f) { return true; }
if (pt.Voltage > 0.1f) { return true; }
}
else if (ic is PowerContainer pc)
{
@@ -768,8 +768,11 @@ namespace Barotrauma
{
for (int j = 0; j < capacity; j++)
{
if (slots[j].Contains(item)) { visualSlots[j].ShowBorderHighlight(GUIStyle.Green, 0.1f, 0.9f); }
if (slots[j].Contains(item)) { visualSlots[j].ShowBorderHighlight(GUIStyle.Green, 0.1f, 0.9f); }
}
}
if (otherInventory.visualSlots != null)
{
for (int j = 0; j < otherInventory.capacity; j++)
{
if (otherInventory.slots[j].Contains(existingItems.FirstOrDefault())) { otherInventory.visualSlots[j].ShowBorderHighlight(GUIStyle.Green, 0.1f, 0.9f); }
@@ -1792,7 +1792,7 @@ namespace Barotrauma
if (Math.Abs(body.LinearVelocity.X) > 0.01f || Math.Abs(body.LinearVelocity.Y) > 0.01f || transformDirty)
{
UpdateTransform();
if (CurrentHull == null && body.SimPosition.Y < ConvertUnits.ToSimUnits(Level.MaxEntityDepth))
if (CurrentHull == null && Level.Loaded != null && body.SimPosition.Y < ConvertUnits.ToSimUnits(Level.MaxEntityDepth))
{
Spawner?.AddItemToRemoveQueue(this);
return;
@@ -51,11 +51,26 @@ namespace Barotrauma.MapCreatures.Behavior
private bool inflate;
private float pulseDelay = Rand.Range(0f, 3f);
public readonly BallastFloraBranch? ParentBranch;
private BallastFloraBranch? parentBranch;
public BallastFloraBranch? ParentBranch
{
get { return parentBranch; }
set
{
if (value != parentBranch)
{
parentBranch = value;
if (parentBranch != null)
{
BranchDepth = parentBranch.BranchDepth + 1;
}
}
}
}
/// <summary>
/// How far from the root this branch is
/// </summary>
public readonly int BranchDepth;
public int BranchDepth { get; private set; }
public float AccumulatedDamage;
public float DamageVisualizationTimer;
@@ -71,10 +86,6 @@ namespace Barotrauma.MapCreatures.Behavior
{
ParentBranch = parentBranch;
ParentBallastFlora = parent;
if (parentBranch != null)
{
BranchDepth = parentBranch.BranchDepth + 1;
}
}
public void UpdateHealth()
@@ -319,6 +330,7 @@ namespace Barotrauma.MapCreatures.Behavior
foreach (BallastFloraBranch branch in Branches)
{
SetHull(branch);
if (branch.ClaimedItemId > -1)
{
if (Entity.FindEntityByID((ushort)branch.ClaimedItemId) is Item item)
@@ -422,6 +434,7 @@ namespace Barotrauma.MapCreatures.Behavior
public void LoadSave(XElement element, IdRemap idRemap)
{
List<(BallastFloraBranch branch, int parentBranchId)> branches = new List<(BallastFloraBranch branch, int parentBranchId)>();
SerializableProperties = SerializableProperty.DeserializeProperties(this, element);
Offset = element.GetAttributeVector2("offset", Vector2.Zero);
foreach (var subElement in element.Elements())
@@ -442,6 +455,14 @@ namespace Barotrauma.MapCreatures.Behavior
}
}
foreach ((BallastFloraBranch branch, int parentBranchId) in branches)
{
if (parentBranchId > -1 && parentBranchId < Branches.Count)
{
branch.ParentBranch = Branches[parentBranchId];
}
}
void LoadBranch(XElement branchElement, IdRemap idRemap)
{
Vector2 pos = branchElement.GetAttributeVector2("pos", Vector2.Zero);
@@ -456,13 +477,7 @@ namespace Barotrauma.MapCreatures.Behavior
int claimedId = branchElement.GetAttributeInt("claimed", -1);
int parentBranchId = branchElement.GetAttributeInt("parentbranch", -1);
BallastFloraBranch? parentBranch = null;
if (parentBranchId > -1)
{
parentBranch = Branches[parentBranchId];
}
BallastFloraBranch newBranch = new BallastFloraBranch(this, parentBranch, pos, VineTileType.CrossJunction, FoliageConfig.Deserialize(flowerConfig), FoliageConfig.Deserialize(leafconfig))
BallastFloraBranch newBranch = new BallastFloraBranch(this, null, pos, VineTileType.CrossJunction, FoliageConfig.Deserialize(flowerConfig), FoliageConfig.Deserialize(leafconfig))
{
ID = id,
Health = health,
@@ -471,6 +486,8 @@ namespace Barotrauma.MapCreatures.Behavior
BlockedSides = (TileSide) blockedSides,
IsRoot = isRoot
};
branches.Add((newBranch, parentBranchId));
if (newBranch.IsRoot) { root = newBranch; }
if (claimedId > -1)
@@ -731,7 +748,7 @@ namespace Barotrauma.MapCreatures.Behavior
}
// could probably be moved to the branch constructor
private void SetHull(BallastFloraBranch branch)
public void SetHull(BallastFloraBranch branch)
{
branch.CurrentHull = Hull.FindHull(GetWorldPosition() + branch.Position, Parent, true);
}
@@ -1204,7 +1221,7 @@ namespace Barotrauma.MapCreatures.Behavior
_entityList.Remove(this);
#if SERVER
CreateNetworkMessage(new KillEventData());
CreateNetworkMessage(new RemoveEventData());
#endif
}
@@ -19,6 +19,11 @@ namespace Barotrauma.MapCreatures.Behavior
public NetworkHeader NetworkHeader => NetworkHeader.Kill;
}
private readonly struct RemoveEventData : IEventData
{
public NetworkHeader NetworkHeader => NetworkHeader.Remove;
}
private readonly struct BranchCreateEventData : IEventData
{
public NetworkHeader NetworkHeader => NetworkHeader.BranchCreate;
@@ -8,10 +8,7 @@ using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Barotrauma.IO;
using Voronoi2;
namespace Barotrauma
@@ -25,7 +22,7 @@ namespace Barotrauma
}
//all entities are disabled after they reach this depth
public const int MaxEntityDepth = -300000;
public const int MaxEntityDepth = -1000000;
public const float ShaftHeight = 1000.0f;
/// <summary>
/// The level generator won't try to adjust the width of the main path above this limit.
@@ -164,18 +164,14 @@ namespace Barotrauma.Networking
}
public bool HasSpawned; //has the client spawned as a character during the current round
private List<Client> kickVoters;
private readonly List<Client> kickVoters;
public HashSet<Identifier> GivenAchievements = new HashSet<Identifier>();
public ClientPermissions Permissions = ClientPermissions.None;
public List<DebugConsole.Command> PermittedConsoleCommands
{
get;
private set;
}
public readonly HashSet<DebugConsole.Command> PermittedConsoleCommands = new HashSet<DebugConsole.Command>();
private object[] votes;
private readonly object[] votes;
public int KickVoteCount
{
@@ -195,7 +191,6 @@ namespace Barotrauma.Networking
this.Name = name;
this.ID = ID;
PermittedConsoleCommands = new List<DebugConsole.Command>();
kickVoters = new List<Client>();
votes = new object[Enum.GetNames(typeof(VoteType)).Length];
@@ -37,7 +37,7 @@ namespace Barotrauma.Networking
public readonly LocalizedString Name;
public readonly LocalizedString Description;
public readonly ClientPermissions Permissions;
public readonly List<DebugConsole.Command> PermittedCommands;
public readonly HashSet<DebugConsole.Command> PermittedCommands;
public PermissionPreset(XElement element)
{
@@ -51,7 +51,7 @@ namespace Barotrauma.Networking
DebugConsole.ThrowError("Error in permission preset \"" + Name + "\" - " + permissionsStr + " is not a valid permission!");
}
PermittedCommands = new List<DebugConsole.Command>();
PermittedCommands = new HashSet<DebugConsole.Command>();
if (Permissions.HasFlag(ClientPermissions.ConsoleCommands))
{
foreach (var subElement in element.Elements())
@@ -87,7 +87,7 @@ namespace Barotrauma.Networking
}
}
public bool MatchesPermissions(ClientPermissions permissions, List<DebugConsole.Command> permittedConsoleCommands)
public bool MatchesPermissions(ClientPermissions permissions, HashSet<DebugConsole.Command> permittedConsoleCommands)
{
return permissions == this.Permissions && PermittedCommands.SequenceEqual(permittedConsoleCommands);
}
@@ -443,6 +443,9 @@ namespace Barotrauma
{
removeQueue.Clear();
spawnQueue.Clear();
#if CLIENT
receivedEvents.Clear();
#endif
}
}
}
@@ -72,18 +72,18 @@ namespace Barotrauma.Networking
public readonly string EndPoint;
public readonly ulong SteamID;
public readonly string Name;
public List<DebugConsole.Command> PermittedCommands;
public HashSet<DebugConsole.Command> PermittedCommands;
public ClientPermissions Permissions;
public SavedClientPermission(string name, string endpoint, ClientPermissions permissions, List<DebugConsole.Command> permittedCommands)
public SavedClientPermission(string name, string endpoint, ClientPermissions permissions, HashSet<DebugConsole.Command> permittedCommands)
{
this.Name = name;
this.EndPoint = endpoint;
this.Permissions = permissions;
this.PermittedCommands = permittedCommands;
}
public SavedClientPermission(string name, ulong steamID, ClientPermissions permissions, List<DebugConsole.Command> permittedCommands)
public SavedClientPermission(string name, ulong steamID, ClientPermissions permissions, HashSet<DebugConsole.Command> permittedCommands)
{
this.Name = name;
this.SteamID = steamID;
@@ -43,7 +43,7 @@ namespace Barotrauma
{
Config config = new Config
{
Language = LanguageIdentifier.None,
Language = TextManager.DefaultLanguage,
SubEditorUndoBuffer = 32,
MaxAutoSaves = 8,
AutoSaveIntervalSeconds = 300,
@@ -99,6 +99,10 @@ namespace Barotrauma
Config retVal = fallback ?? GetDefault();
retVal.DeserializeElement(element);
if (retVal.Language == LanguageIdentifier.None)
{
retVal.Language = TextManager.DefaultLanguage;
}
retVal.Graphics = GraphicsSettings.FromElements(element.GetChildElements("graphicsmode", "graphicssettings"), retVal.Graphics);
retVal.Audio = AudioSettings.FromElements(element.GetChildElements("audio"), retVal.Audio);
@@ -1485,7 +1485,7 @@ namespace Barotrauma
Identifier GetRandomSkill()
{
return targetCharacter.Info?.Job?.Skills.Select(s => s.Identifier).GetRandomUnsynced() ?? Identifier.Empty;
return targetCharacter.Info?.Job?.GetSkills().GetRandomUnsynced()?.Identifier ?? Identifier.Empty;
}
}
}
@@ -1,3 +1,4 @@
using Steamworks.Data;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -74,6 +75,24 @@ namespace Barotrauma.Steam
return Steamworks.SteamClient.Name;
}
public static uint GetNumSubscribedItems()
{
if (!IsInitialized || !Steamworks.SteamClient.IsValid)
{
return 0;
}
return Steamworks.SteamUGC.NumSubscribedItems;
}
public static PublishedFileId[] GetSubscribedItems()
{
if (!IsInitialized || !Steamworks.SteamClient.IsValid)
{
return new PublishedFileId[0];
}
return Steamworks.SteamUGC.GetSubscribedItems();
}
public static bool UnlockAchievement(string achievementIdentifier) =>
UnlockAchievement(achievementIdentifier.ToIdentifier());
@@ -250,12 +250,15 @@ namespace Barotrauma.Steam
public static void DeleteFailedCopies()
{
foreach (var dir in Directory.EnumerateDirectories(ContentPackage.WorkshopModsDir, "**"))
if (Directory.Exists(ContentPackage.WorkshopModsDir))
{
string copyingIndicatorPath = Path.Combine(dir, ContentPackageManager.CopyIndicatorFileName);
if (File.Exists(copyingIndicatorPath))
foreach (var dir in Directory.EnumerateDirectories(ContentPackage.WorkshopModsDir, "**"))
{
Directory.Delete(dir, recursive: true);
string copyingIndicatorPath = Path.Combine(dir, ContentPackageManager.CopyIndicatorFileName);
if (File.Exists(copyingIndicatorPath))
{
Directory.Delete(dir, recursive: true);
}
}
}
}
@@ -80,7 +80,7 @@ namespace Barotrauma
#if DEBUG
if (!lStr.IsNullOrEmpty() && lStr.Contains("‖"))
{
if (Debugger.IsAttached) { Debugger.Break(); }
//if (Debugger.IsAttached) { Debugger.Break(); }
}
#endif
return Plain(lStr ?? string.Empty);