Unstable 0.1400.0.0

This commit is contained in:
Markus Isberg
2021-05-11 15:47:47 +03:00
parent 3f324b14e8
commit 92f0264af2
247 changed files with 8238 additions and 1911 deletions
@@ -1,4 +1,5 @@
using Microsoft.Xna.Framework;
using Barotrauma.Extensions;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -30,6 +31,8 @@ namespace Barotrauma
public ReadyCheck ActiveReadyCheck;
public XElement ActiveOrdersElement { get; set; }
public CrewManager(bool isSinglePlayer)
{
IsSinglePlayer = isSinglePlayer;
@@ -111,6 +114,9 @@ namespace Barotrauma
case "health":
characterInfo.HealthData = subElement;
break;
case "orders":
characterInfo.OrderData = subElement;
break;
}
}
}
@@ -189,7 +195,7 @@ namespace Barotrauma
spawnWaypoints = WayPoint.WayPointList.FindAll(wp =>
wp.SpawnType == SpawnType.Human &&
wp.Submarine == Level.Loaded.StartOutpost &&
wp.CurrentHull?.OutpostModuleTags != null &&
wp.CurrentHull != null &&
wp.CurrentHull.OutpostModuleTags.Contains("airlock"));
while (spawnWaypoints.Count > characterInfos.Count)
{
@@ -229,10 +235,14 @@ namespace Barotrauma
}
if (character.Info.HealthData != null)
{
character.Info.ApplyHealthData(character, character.Info.HealthData);
CharacterInfo.ApplyHealthData(character, character.Info.HealthData);
}
character.GiveIdCardTags(spawnWaypoints[i]);
character.Info.StartItemsGiven = true;
if (character.Info.OrderData != null)
{
character.Info.ApplyOrderData();
}
}
AddCharacter(character);
@@ -265,6 +275,14 @@ namespace Barotrauma
RemoveCharacterInfo(characterInfo);
}
public void ClearCurrentOrders()
{
foreach (var characterInfo in characterInfos)
{
characterInfo?.ClearCurrentOrders();
}
}
public void Update(float deltaTime)
{
foreach (Pair<Order, float?> order in ActiveOrders)
@@ -392,6 +410,88 @@ namespace Barotrauma
#endregion
public static Character GetCharacterForQuickAssignment(Order order, Character controlledCharacter, IEnumerable<Character> characters, bool includeSelf = false)
{
var controllingCharacter = controlledCharacter != null;
#if !DEBUG
if (!controllingCharacter) { return null; }
#endif
if (order.Category == OrderCategory.Operate && HumanAIController.IsItemOperatedByAnother(null, order.TargetItemComponent, out Character operatingCharacter) &&
(!controllingCharacter || operatingCharacter.CanHearCharacter(controlledCharacter)))
{
return operatingCharacter;
}
return GetCharactersSortedForOrder(order, characters, controlledCharacter, includeSelf).FirstOrDefault(c => !controllingCharacter || c.CanHearCharacter(controlledCharacter)) ?? controlledCharacter;
}
public static IEnumerable<Character> GetCharactersSortedForOrder(Order order, IEnumerable<Character> characters, Character controlledCharacter, bool includeSelf, IEnumerable<Character> extraCharacters = null)
{
var filteredCharacters = characters.Where(c => controlledCharacter == null || ((includeSelf || c != controlledCharacter) && c.TeamID == controlledCharacter.TeamID));
if (extraCharacters != null)
{
filteredCharacters = filteredCharacters.Union(extraCharacters);
}
return filteredCharacters
// 1. Prioritize those who are on the same submarine than the controlled character
.OrderByDescending(c => Character.Controlled == null || c.Submarine == Character.Controlled.Submarine)
// 2. Prioritize those who have been given the same maintenance or operate order as now issued
.ThenByDescending(c => c.CurrentOrders.Any(o =>
o.Order != null && o.Order.Identifier == order.Identifier &&
(order.Category == OrderCategory.Maintenance || order.Category == OrderCategory.Operate)))
// 3. Prioritize those with the appropriate job for the order
.ThenByDescending(c => order.HasAppropriateJob(c))
// 4. Prioritize bots over player controlled characters
.ThenByDescending(c => c.IsBot)
// 5. Use the priority value of the current objective
.ThenBy(c => c.AIController is HumanAIController humanAI ? humanAI.ObjectiveManager.CurrentObjective?.Priority : 0)
// 6. Prioritize those with the best skill for the order
.ThenByDescending(c => c.GetSkillLevel(order.AppropriateSkill));
}
partial void UpdateProjectSpecific(float deltaTime);
private void SaveActiveOrders(XElement parentElement)
{
ActiveOrdersElement = new XElement("activeorders");
// Only save orders with no fade out time (e.g. ignore orders)
var ordersToSave = new List<OrderInfo>();
foreach (var activeOrder in ActiveOrders)
{
var order = activeOrder?.First;
if (order == null || activeOrder.Second.HasValue) { continue; }
ordersToSave.Add(new OrderInfo(order, null, CharacterInfo.HighestManualOrderPriority));
}
CharacterInfo.SaveOrders(ActiveOrdersElement, ordersToSave.ToArray());
parentElement?.Add(ActiveOrdersElement);
}
public void LoadActiveOrders()
{
if (ActiveOrdersElement == null) { return; }
foreach (var orderInfo in CharacterInfo.LoadOrders(ActiveOrdersElement))
{
IIgnorable ignoreTarget = null;
if (orderInfo.Order.IsIgnoreOrder)
{
switch (orderInfo.Order.TargetType)
{
case Order.OrderTargetType.Entity:
ignoreTarget = orderInfo.Order.TargetEntity as IIgnorable;
break;
case Order.OrderTargetType.WallSection when orderInfo.Order.TargetEntity is Structure s && orderInfo.Order.WallSectionIndex.HasValue:
ignoreTarget = s.GetSection(orderInfo.Order.WallSectionIndex.Value) as IIgnorable;
break;
default:
DebugConsole.ThrowError("Error loading an ignore order - can't find a proper ignore target");
continue;
}
}
if (ignoreTarget != null)
{
ignoreTarget.OrderedToBeIgnored = true;
}
AddOrder(orderInfo.Order, null);
}
}
}
}
@@ -51,7 +51,7 @@ namespace Barotrauma
//there can be no events before this time has passed during the 1st campaign round
const float FirstRoundEventDelay = 30.0f;
public enum InteractionType { None, Talk, Map, Crew, Store, Repair, Upgrade, PurchaseSub }
public enum InteractionType { None, Talk, Examine, Map, Crew, Store, Repair, Upgrade, PurchaseSub }
public readonly CargoManager CargoManager;
public UpgradeManager UpgradeManager;
@@ -169,7 +169,7 @@ namespace Barotrauma
return Submarine.Loaded.FindAll(sub =>
sub != leavingSub &&
!leavingSub.DockedTo.Contains(sub) &&
sub.Info.Type == SubmarineType.Player &&
sub.Info.Type == SubmarineType.Player && sub.TeamID == CharacterTeamType.Team1 && // pirate subs are currently tagged as player subs as well
sub != GameMain.NetworkMember?.RespawnManager?.RespawnShuttle &&
(sub.AtEndExit != leavingSub.AtEndExit || sub.AtStartExit != leavingSub.AtStartExit));
}
@@ -268,7 +268,7 @@ namespace Barotrauma
var beaconMissionPrefab = ToolBox.SelectWeightedRandom(beaconMissionPrefabs, beaconMissionPrefabs.Select(p => (float)p.Commonness).ToList(), rand);
if (!Missions.Any(m => m.Prefab.Type == beaconMissionPrefab.Type))
{
extraMissions.Add(beaconMissionPrefab.Instantiate(Map.SelectedConnection.Locations));
extraMissions.Add(beaconMissionPrefab.Instantiate(Map.SelectedConnection.Locations, Submarine.MainSub));
}
}
}
@@ -285,7 +285,7 @@ namespace Barotrauma
var huntingGroundsMissionPrefab = ToolBox.SelectWeightedRandom(huntingGroundsMissionPrefabs, huntingGroundsMissionPrefabs.Select(p => (float)p.Commonness).ToList(), rand);
if (!Missions.Any(m => m.Prefab.Tags.Any(t => t.Equals("huntinggrounds", StringComparison.OrdinalIgnoreCase))))
{
extraMissions.Add(huntingGroundsMissionPrefab.Instantiate(Map.SelectedConnection.Locations));
extraMissions.Add(huntingGroundsMissionPrefab.Instantiate(Map.SelectedConnection.Locations, Submarine.MainSub));
}
}
}
@@ -595,7 +595,6 @@ namespace Barotrauma
{
CrewManager.RemoveCharacterInfo(ci);
}
ci?.ClearCurrentOrders();
}
foreach (DockingPort port in DockingPort.List)
@@ -637,6 +636,7 @@ namespace Barotrauma
location.CreateStore(force: true);
location.ClearMissions();
location.Discovered = false;
location.LevelData?.EventHistory?.Clear();
}
Map.SetLocation(Map.Locations.IndexOf(Map.StartLocation));
Map.SelectLocation(-1);
@@ -26,6 +26,7 @@ namespace Barotrauma
private XElement itemData;
private XElement healthData;
public XElement OrderData { get; private set; }
partial void InitProjSpecific(Client client);
public CharacterCampaignData(Client client)
@@ -38,8 +39,10 @@ namespace Barotrauma
if (client.Character.Inventory != null)
{
itemData = new XElement("inventory");
client.Character.SaveInventory(client.Character.Inventory, itemData);
Character.SaveInventory(client.Character.Inventory, itemData);
}
OrderData = new XElement("orders");
CharacterInfo.SaveOrderData(client.Character.Info, OrderData);
}
public CharacterCampaignData(XElement element)
@@ -67,6 +70,9 @@ namespace Barotrauma
case "health":
healthData = subElement;
break;
case "orders":
OrderData = subElement;
break;
}
}
}
@@ -78,8 +84,10 @@ namespace Barotrauma
if (character.Inventory != null)
{
itemData = new XElement("inventory");
character.SaveInventory(character.Inventory, itemData);
Character.SaveInventory(character.Inventory, itemData);
}
OrderData = new XElement("orders");
CharacterInfo.SaveOrderData(character.Info, OrderData);
}
public XElement Save()
@@ -92,6 +100,7 @@ namespace Barotrauma
CharacterInfo?.Save(element);
if (itemData != null) { element.Add(itemData); }
if (healthData != null) { element.Add(healthData); }
if (OrderData != null) { element.Add(OrderData); }
return element;
}
@@ -21,7 +21,7 @@ namespace Barotrauma
Location[] locations = { GameMain.GameSession.StartLocation, GameMain.GameSession.EndLocation };
foreach (MissionPrefab missionPrefab in missionPrefabs)
{
missions.Add(missionPrefab.Instantiate(locations));
missions.Add(missionPrefab.Instantiate(locations, Submarine.MainSub));
}
}
@@ -149,12 +149,14 @@ namespace Barotrauma
case "metadata":
CampaignMetadata = new CampaignMetadata(this, subElement);
break;
case "upgrademanager":
case "pendingupgrades":
UpgradeManager = new UpgradeManager(this, subElement, isSingleplayer: false);
break;
case "bots" when GameMain.NetworkMember != null && GameMain.NetworkMember.IsServer:
CrewManager.HasBots = subElement.GetAttributeBool("hasbots", false);
CrewManager.AddCharacterElements(subElement);
CrewManager.ActiveOrdersElement = subElement.GetChildElement("activeorders");
break;
case "cargo":
CargoManager?.LoadPurchasedItems(subElement);
@@ -353,9 +353,14 @@ namespace Barotrauma
}
}
}
if (GameMode is PvPMode && Submarine.MainSubs[1] == null)
if (Submarine.MainSubs[1] == null)
{
Submarine.MainSubs[1] = new Submarine(SubmarineInfo, true);
var enemySubmarineInfo = GameMode is PvPMode ? SubmarineInfo : GameMode.Missions.FirstOrDefault(m => m.EnemySubmarineInfo != null)?.EnemySubmarineInfo;
if (enemySubmarineInfo != null)
{
Submarine.MainSubs[1] = new Submarine(enemySubmarineInfo, true);
}
}
if (GameMain.NetworkMember?.ServerSettings?.LockAllDefaultWires ?? false)
@@ -28,6 +28,18 @@ namespace Barotrauma
}
}
internal class PurchasedItemSwap
{
public readonly Item ItemToRemove;
public readonly ItemPrefab ItemToInstall;
public PurchasedItemSwap(Item itemToRemove, ItemPrefab itemToInstall)
{
ItemToRemove = itemToRemove;
ItemToInstall = itemToInstall;
}
}
/// <summary>
/// This class handles all upgrade logic.
/// Storing, applying, checking and validation of upgrades.
@@ -75,6 +87,8 @@ namespace Barotrauma
public readonly List<PurchasedUpgrade> PendingUpgrades = new List<PurchasedUpgrade>();
public readonly List<PurchasedItemSwap> PurchasedItemSwaps = new List<PurchasedItemSwap>();
private CampaignMetadata Metadata => Campaign.CampaignMetadata;
private readonly CampaignMode Campaign;
private int spentMoney;
@@ -90,7 +104,67 @@ namespace Barotrauma
public UpgradeManager(CampaignMode campaign, XElement element, bool isSingleplayer) : this(campaign)
{
DebugConsole.Log($"Restored upgrade manager from save file, ({element.Elements().Count()} pending upgrades).");
LoadPendingUpgrades(element, isSingleplayer);
//backwards compatibility:
//upgrades used to be saved to a <pendingupgrades> element, now upgrades and item swaps are saved separately under a <upgrademanager> element
if (element.Name.LocalName.Equals("pendingupgrades", StringComparison.OrdinalIgnoreCase))
{
LoadPendingUpgrades(element, isSingleplayer);
}
else
{
foreach (XElement subElement in element.Elements())
{
switch (subElement.Name.ToString().ToLowerInvariant())
{
case "pendingupgrades":
LoadPendingUpgrades(subElement, isSingleplayer);
break;
}
}
}
}
public int DetermineItemSwapCost(Item item, ItemPrefab replacement)
{
if (replacement == null)
{
replacement = ItemPrefab.Find("", item.Prefab.SwappableItem.ReplacementOnUninstall);
if (replacement == null)
{
DebugConsole.ThrowError("Failed to determine swap cost for item \"{}\". Trying to uninstall the item but no replacement item found.");
return 0;
}
}
int price = 0;
if (replacement == item.Prefab)
{
if (item.PendingItemSwap != null)
{
//refund the pending swap
price -= item.PendingItemSwap.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
//buy back the current item
price += item.Prefab.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
}
}
else
{
price = replacement.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
if (item.PendingItemSwap != null)
{
//refund the pending swap
price -= item.PendingItemSwap.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
//buy back the current item
price += item.Prefab.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
}
//refund the current item
if (replacement != item.prefab)
{
price -= item.Prefab.SwappableItem.GetPrice(Campaign?.Map?.CurrentLocation);
}
}
return price;
}
private DateTime lastUpgradeSpeak, lastErrorSpeak;
@@ -102,9 +176,6 @@ namespace Barotrauma
/// Purchased upgrades are temporarily stored in <see cref="PendingUpgrades"/> and they are applied
/// after the next round starts similarly how items are spawned in the stowage room after the round starts.
/// </remarks>
/// <param name="prefab"></param>
/// <param name="category"></param>
/// <param name="force"></param>
public void PurchaseUpgrade(UpgradePrefab prefab, UpgradeCategory category, bool force = false)
{
if (!CanUpgradeSub())
@@ -142,7 +213,7 @@ namespace Barotrauma
price = 0;
}
if (Campaign.Money > price)
if (Campaign.Money >= price)
{
if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer)
{
@@ -184,6 +255,151 @@ namespace Barotrauma
}
}
/// <summary>
/// Purchases an item swap and handles logic for deducting the credit.
/// </summary>
public void PurchaseItemSwap(Item itemToRemove, ItemPrefab itemToInstall, bool force = false)
{
if (!CanUpgradeSub())
{
DebugConsole.ThrowError("Cannot swap items when switching to another submarine.");
return;
}
if (itemToRemove == null)
{
DebugConsole.ThrowError($"Cannot swap null item!");
return;
}
if (!UpgradeCategory.Categories.Any(c => c.ItemTags.Any(t => itemToRemove.HasTag(t)) && c.ItemTags.Any(t => itemToInstall.Tags.Contains(t))))
{
DebugConsole.ThrowError($"Failed to swap item \"{itemToRemove.Name}\" with \"{itemToInstall.Name}\" (not in the same upgrade category).");
return;
}
/*if (itemToRemove.PendingItemSwap != null)
{
CancelItemSwap(itemToRemove);
}
else */
if (itemToRemove.prefab == itemToInstall)
{
DebugConsole.ThrowError($"Failed to swap item \"{itemToRemove.Name}\" (trying to swap with the same item!).");
return;
}
SwappableItem? swappableItem = itemToRemove.Prefab.SwappableItem;
if (swappableItem == null)
{
DebugConsole.ThrowError($"Failed to swap item \"{itemToRemove.Name}\" (not configured as a swappable item).");
return;
}
int price = 0;
if (!itemToRemove.AvailableSwaps.Contains(itemToInstall))
{
price = itemToInstall.SwappableItem.GetPrice(Campaign.Map?.CurrentLocation);
}
if (force)
{
price = 0;
}
if (Campaign.Money >= price)
{
PurchasedItemSwaps.RemoveAll(p => p.ItemToRemove == itemToRemove);
if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer)
{
// only make the NPC speak if more than 5 minutes have passed since the last purchased service
if (lastUpgradeSpeak == DateTime.MinValue || lastUpgradeSpeak.AddMinutes(5) < DateTime.Now)
{
UpgradeNPCSpeak(TextManager.Get("Dialog.UpgradePurchased"), Campaign.IsSinglePlayer);
lastUpgradeSpeak = DateTime.Now;
}
}
Campaign.Money -= price;
spentMoney += price;
itemToRemove.AvailableSwaps.Add(itemToRemove.Prefab);
if (itemToInstall != null) { itemToRemove.AvailableSwaps.Add(itemToInstall); }
if (itemToRemove.Prefab != itemToInstall && itemToInstall != null)
{
itemToRemove.PendingItemSwap = itemToInstall;
PurchasedItemSwaps.Add(new PurchasedItemSwap(itemToRemove, itemToInstall));
DebugLog($"CLIENT: Swapped item \"{itemToRemove.Name}\" with \"{itemToInstall.Name}\".", Color.Orange);
}
else
{
DebugLog($"CLIENT: Cancelled swapping the item \"{itemToRemove.Name}\" with \"{(itemToRemove.PendingItemSwap?.Name ?? null)}\".", Color.Orange);
}
OnUpgradesChanged?.Invoke();
}
else
{
DebugConsole.ThrowError("Tried to swap an item with insufficient funds, the transaction has not been completed.\n" +
$"Item to remove: {itemToRemove.Name}, Item to install: {itemToInstall.Name}, Cost: {price}, Have: {Campaign.Money}");
}
}
/// <summary>
/// Cancels the currently pending item swap, or uninstalls the item if there's no swap pending
/// </summary>
public void CancelItemSwap(Item itemToRemove, bool force = false)
{
if (!CanUpgradeSub())
{
DebugConsole.ThrowError("Cannot swap items when switching to another submarine.");
return;
}
if (itemToRemove?.PendingItemSwap == null && string.IsNullOrEmpty(itemToRemove?.Prefab.SwappableItem?.ReplacementOnUninstall))
{
DebugConsole.ThrowError($"Cannot uninstall item \"{itemToRemove?.Name}\" (no replacement item configured).");
return;
}
SwappableItem? swappableItem = itemToRemove.Prefab.SwappableItem;
if (swappableItem == null)
{
DebugConsole.ThrowError($"Failed to uninstall item \"{itemToRemove.Name}\" (not configured as a swappable item).");
return;
}
if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer)
{
// only make the NPC speak if more than 5 minutes have passed since the last purchased service
if (lastUpgradeSpeak == DateTime.MinValue || lastUpgradeSpeak.AddMinutes(5) < DateTime.Now)
{
UpgradeNPCSpeak(TextManager.Get("Dialog.UpgradePurchased"), Campaign.IsSinglePlayer);
lastUpgradeSpeak = DateTime.Now;
}
}
if (itemToRemove.PendingItemSwap == null)
{
var replacement = MapEntityPrefab.Find("", swappableItem.ReplacementOnUninstall) as ItemPrefab;
if (replacement == null)
{
DebugConsole.ThrowError($"Failed to uninstall item \"{itemToRemove.Name}\". Could not find the replacement item \"{swappableItem.ReplacementOnUninstall}\".");
return;
}
PurchasedItemSwaps.RemoveAll(p => p.ItemToRemove == itemToRemove);
PurchasedItemSwaps.Add(new PurchasedItemSwap(itemToRemove, replacement));
DebugLog($"Uninstalled item item \"{itemToRemove.Name}\".", Color.Orange);
itemToRemove.PendingItemSwap = replacement;
}
else
{
PurchasedItemSwaps.RemoveAll(p => p.ItemToRemove == itemToRemove);
DebugLog($"Cancelled swapping the item \"{itemToRemove.Name}\" with \"{itemToRemove.PendingItemSwap.Name}\".", Color.Orange);
itemToRemove.PendingItemSwap = null;
}
#if CLIENT
OnUpgradesChanged?.Invoke();
#endif
}
/// <summary>
/// Applies all our pending upgrades to the submarine.
/// </summary>
@@ -201,24 +417,17 @@ namespace Barotrauma
public void ApplyUpgrades()
{
PurchasedUpgrades.Clear();
PurchasedItemSwaps.Clear();
if (Submarine.MainSub == null) { return; }
List<PurchasedUpgrade> pendingUpgrades = PendingUpgrades;
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
{
if (Level.Loaded?.Type != LevelData.LevelType.Outpost)
if (loadedUpgrades != null)
{
if (loadedUpgrades != null)
{
// client receives pending upgrades from the save file
pendingUpgrades = loadedUpgrades;
}
}
else
{
// prevent the client from applying pending upgrades at an outpost when joining mid round
return;
// client receives pending upgrades from the save file
pendingUpgrades = loadedUpgrades;
}
}
@@ -592,7 +801,17 @@ namespace Barotrauma
OnUpgradesChanged?.Invoke();
}
public void SavePendingUpgrades(XElement? parent, List<PurchasedUpgrade> upgrades)
public void Save(XElement? parent)
{
if (parent == null) { return; }
var upgradeManagerElement = new XElement("upgrademanager");
parent.Add(upgradeManagerElement);
SavePendingUpgrades(upgradeManagerElement, PendingUpgrades);
}
private void SavePendingUpgrades(XElement? parent, List<PurchasedUpgrade> upgrades)
{
if (parent == null) { return; }
@@ -647,7 +866,7 @@ namespace Barotrauma
#endif
}
public static void LogError(string text, Dictionary<string, object?> data, Exception e = null)
public static void LogError(string text, Dictionary<string, object?> data, Exception? e = null)
{
string error = $"{text}\n";
foreach (var (label, value) in data)