Build 0.18.0.0

This commit is contained in:
Markus Isberg
2022-05-13 00:55:52 +09:00
parent 15d18e6ff6
commit 7547a9b78a
218 changed files with 3881 additions and 2192 deletions
@@ -3,36 +3,32 @@ using System;
using System.Collections.Generic;
using System.Linq;
using Barotrauma.Extensions;
using Microsoft.Xna.Framework;
namespace Barotrauma
{
#warning TODO: This class needs some changes:
// - We shouldn't be iterating over MapEntityPrefab.List. It has no guarantee of any sort of order and becomes entirely unpredictable once you start adding mods.
// - Note: iterating over ItemPrefab.Prefabs would also be incorrect. Sorting by UintIdentifier is necessary for determinism.
// - SpawnItems and SpawnItem are named incorrectly.
static class AutoItemPlacer
{
public static bool OutputDebugInfo = false;
/// <summary>
/// If we are spawning in an area where difficulty should not be a factor, assume difficulty is at the exact "middle"
/// </summary>
public const float DefaultDifficultyModifier = 0f;
public static void PlaceIfNeeded()
public static void SpawnItems()
{
if (GameMain.NetworkMember != null && !GameMain.NetworkMember.IsServer) { return; }
for (int i = 0; i < Submarine.MainSubs.Length; i++)
bool skipMainSubs = GameMain.GameSession.GameMode is CampaignMode { IsFirstRound: false };
if (!skipMainSubs)
{
if (Submarine.MainSubs[i] == null || Submarine.MainSubs[i].Info.InitialSuppliesSpawned) { continue; }
List<Submarine> subs = new List<Submarine>() { Submarine.MainSubs[i] };
subs.AddRange(Submarine.MainSubs[i].DockedTo.Where(d => !d.Info.IsOutpost));
Place(subs);
subs.ForEach(s => s.Info.InitialSuppliesSpawned = true);
for (int i = 0; i < Submarine.MainSubs.Length; i++)
{
var sub = Submarine.MainSubs[i];
if (sub == null || sub.Info.InitialSuppliesSpawned) { continue; }
SpawnStartItems(sub);
var subs = sub.GetConnectedSubs().Where(s => s.TeamID == sub.TeamID);
CreateAndPlace(subs);
subs.ForEach(s => s.Info.InitialSuppliesSpawned = true);
}
}
float difficultyModifier = GetLevelDifficultyModifier();
foreach (var sub in Submarine.Loaded)
{
if (sub.Info.Type == SubmarineType.Player ||
@@ -42,33 +38,93 @@ namespace Barotrauma
{
continue;
}
Place(sub.ToEnumerable(), difficultyModifier: difficultyModifier);
if (sub.Info.InitialSuppliesSpawned) { continue; }
CreateAndPlace(sub.ToEnumerable());
sub.Info.InitialSuppliesSpawned = true;
}
if (Level.Loaded?.StartOutpost != null && Level.Loaded.Type == LevelData.LevelType.Outpost)
{
Rand.SetSyncedSeed(ToolBox.StringToInt(Level.Loaded.StartOutpost.Info.Name));
Place(Level.Loaded.StartOutpost.ToEnumerable());
var sub = Level.Loaded.StartOutpost;
if (!sub.Info.InitialSuppliesSpawned)
{
Rand.SetSyncedSeed(ToolBox.StringToInt(sub.Info.Name));
CreateAndPlace(sub.ToEnumerable());
sub.Info.InitialSuppliesSpawned = true;
}
}
}
private const float MaxDifficultyModifier = 0.2f;
/// <summary>
/// Spawn probability of loot is modified by difficulty, -20% less loot at 0% difficulty and +20% loot at 100% difficulty.
/// </summary>
private static float GetLevelDifficultyModifier()
{
return Math.Clamp(Level.Loaded?.Difficulty is float difficulty ? (difficulty / 100f) * (MaxDifficultyModifier * 2) - MaxDifficultyModifier : DefaultDifficultyModifier, -MaxDifficultyModifier, MaxDifficultyModifier);
}
public static void RegenerateLoot(Submarine sub, ItemContainer regeneratedContainer)
{
// Level difficulty currently doesn't affect regenerated loot for the sake of simplicity
Place(sub.ToEnumerable(), regeneratedContainer: regeneratedContainer);
CreateAndPlace(sub.ToEnumerable(), regeneratedContainer: regeneratedContainer);
}
private static void Place(IEnumerable<Submarine> subs, ItemContainer regeneratedContainer = null, float difficultyModifier = DefaultDifficultyModifier)
public static Identifier StartItemSet = new Identifier("normal");
private static void SpawnStartItems(Submarine sub)
{
if (!Barotrauma.StartItemSet.Sets.TryGet(StartItemSet, out StartItemSet itemSet))
{
DebugConsole.AddWarning($"Couldn't find a start item set matching the identifier \"{StartItemSet}\"!");
return;
}
WayPoint wp = WayPoint.GetRandom(SpawnType.Cargo, null, sub);
ISpatialEntity initialSpawnPos;
if (wp?.CurrentHull == null)
{
var spawnHull = Hull.HullList.Where(h => h.Submarine == sub && !h.IsWetRoom).GetRandomUnsynced();
if (spawnHull == null)
{
DebugConsole.AddWarning($"Failed to spawn start items in the sub. No cargo waypoint or dry hulls found to spawn the items in.");
return;
}
initialSpawnPos = spawnHull;
}
else
{
initialSpawnPos = wp;
}
var newItems = new List<Item>();
foreach (var startItem in itemSet.Items)
{
if (!ItemPrefab.Prefabs.TryGet(startItem.Item, out ItemPrefab itemPrefab))
{
DebugConsole.AddWarning($"Cannot find a start item with with the identifier \"{startItem.Item}\"");
continue;
}
for (int i = 0; i < startItem.Amount; i++)
{
var item = new Item(itemPrefab, initialSpawnPos.Position, sub, callOnItemLoaded: false);
// Is this necessary?
foreach (WifiComponent wifiComponent in item.GetComponents<WifiComponent>())
{
wifiComponent.TeamID = sub.TeamID;
}
newItems.Add(item);
}
}
var cargoContainers = new List<ItemContainer>();
foreach (var item in newItems)
{
#if SERVER
Entity.Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(item));
#endif
foreach (ItemComponent ic in item.Components)
{
ic.OnItemLoaded();
}
var container = sub.FindContainerFor(item, onlyPrimary: true);
if (container == null)
{
var cargoContainer = CargoManager.GetOrCreateCargoContainerFor(item.Prefab, initialSpawnPos, ref cargoContainers);
container = cargoContainer?.Item;
}
container?.OwnInventory.TryPutItem(item, user: null);
}
}
private static void CreateAndPlace(IEnumerable<Submarine> subs, ItemContainer regeneratedContainer = null)
{
if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
{
@@ -76,7 +132,7 @@ namespace Barotrauma
return;
}
List<Item> spawnedItems = new List<Item>(100);
List<Item> itemsToSpawn = new List<Item>(100);
int itemCountApprox = MapEntityPrefab.List.Count() / 3;
var containers = new List<ItemContainer>(70 + 30 * subs.Count());
@@ -100,11 +156,11 @@ namespace Barotrauma
containers.Shuffle(Rand.RandSync.ServerAndClient);
}
foreach (ItemPrefab ip in ItemPrefab.Prefabs)
var itemPrefabs = ItemPrefab.Prefabs.OrderBy(p => p.UintIdentifier);
foreach (ItemPrefab ip in itemPrefabs)
{
if (!ip.PreferredContainers.Any()) { continue; }
if (ip.ConfigElement.Elements().Any(e => string.Equals(e.Name.ToString(), typeof(ItemContainer).Name.ToString(), StringComparison.OrdinalIgnoreCase)) &&
ItemPrefab.Prefabs.Any(ip2 => CanSpawnIn(ip2, ip)))
if (ip.ConfigElement.Elements().Any(e => string.Equals(e.Name.ToString(), typeof(ItemContainer).Name.ToString(), StringComparison.OrdinalIgnoreCase)) && itemPrefabs.Any(ip2 => CanSpawnIn(ip2, ip)))
{
prefabsItemsCanSpawnIn.Add(ip);
}
@@ -141,9 +197,9 @@ namespace Barotrauma
{
var subNames = subs.Select(s => s.Info.Name).ToList();
DebugConsole.NewMessage($"Automatically placed items in { string.Join(", ", subNames) }:");
foreach (string itemName in spawnedItems.Select(it => it.Name).Distinct())
foreach (string itemName in itemsToSpawn.Select(it => it.Name).Distinct())
{
DebugConsole.NewMessage(" - " + itemName + " x" + spawnedItems.Count(it => it.Name == itemName));
DebugConsole.NewMessage(" - " + itemName + " x" + itemsToSpawn.Count(it => it.Name == itemName));
}
}
@@ -153,24 +209,28 @@ namespace Barotrauma
{
foreach (Location.TakenItem takenItem in GameMain.GameSession.StartLocation.TakenItems)
{
var matchingItem = spawnedItems.Find(it => takenItem.Matches(it));
var matchingItem = itemsToSpawn.Find(it => takenItem.Matches(it));
if (matchingItem == null) { continue; }
var containedItems = spawnedItems.FindAll(it => it.ParentInventory?.Owner == matchingItem);
if (OutputDebugInfo)
{
DebugConsole.NewMessage($"Removing the stolen item: {matchingItem.Prefab.Identifier} ({matchingItem.ID})");
}
var containedItems = itemsToSpawn.FindAll(it => it.ParentInventory?.Owner == matchingItem);
matchingItem.Remove();
spawnedItems.Remove(matchingItem);
itemsToSpawn.Remove(matchingItem);
foreach (Item containedItem in containedItems)
{
containedItem.Remove();
spawnedItems.Remove(containedItem);
itemsToSpawn.Remove(containedItem);
}
}
}
foreach (Item spawnedItem in spawnedItems)
foreach (Item item in itemsToSpawn)
{
#if SERVER
Entity.Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(spawnedItem));
Entity.Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(item));
#endif
foreach (ItemComponent ic in spawnedItem.Components)
foreach (ItemComponent ic in item.Components)
{
ic.OnItemLoaded();
}
@@ -186,9 +246,12 @@ namespace Barotrauma
return false;
}
bool success = false;
bool isCampaign = GameMain.GameSession?.GameMode is CampaignMode;
foreach (PreferredContainer preferredContainer in itemPrefab.PreferredContainers)
{
if (preferredContainer.SpawnProbability <= 0.0f || preferredContainer.MaxAmount <= 0) { continue; }
if (preferredContainer.CampaignOnly && !isCampaign) { continue; }
if (preferredContainer.NotCampaign && isCampaign) { continue; }
if (preferredContainer.SpawnProbability <= 0.0f || preferredContainer.MaxAmount <= 0 && preferredContainer.Amount <= 0) { continue; }
validContainers = GetValidContainers(preferredContainer, containers, validContainers, primary: true);
if (validContainers.None())
{
@@ -196,10 +259,10 @@ namespace Barotrauma
}
foreach (var validContainer in validContainers)
{
var newItems = SpawnItem(itemPrefab, containers, validContainer, difficultyModifier);
var newItems = CreateItems(itemPrefab, containers, validContainer);
if (newItems.Any())
{
spawnedItems.AddRange(newItems);
itemsToSpawn.AddRange(newItems);
success = true;
}
}
@@ -238,16 +301,20 @@ namespace Barotrauma
(3, 0.0f),
};
private static List<Item> SpawnItem(ItemPrefab itemPrefab, List<ItemContainer> containers, KeyValuePair<ItemContainer, PreferredContainer> validContainer, float difficultyModifier)
private static List<Item> CreateItems(ItemPrefab itemPrefab, List<ItemContainer> containers, KeyValuePair<ItemContainer, PreferredContainer> validContainer)
{
List<Item> spawnedItems = new List<Item>();
if (Rand.Value(Rand.RandSync.ServerAndClient) > validContainer.Value.SpawnProbability * (1f + difficultyModifier)) { return spawnedItems; }
List<Item> newItems = new List<Item>();
if (Rand.Value(Rand.RandSync.ServerAndClient) > validContainer.Value.SpawnProbability) { return newItems; }
// Don't add dangerously reactive materials in thalamus wrecks
if (validContainer.Key.Item.Submarine.WreckAI != null && itemPrefab.Tags.Contains("explodesinwater"))
{
return spawnedItems;
return newItems;
}
int amount = validContainer.Value.Amount;
if (amount == 0)
{
amount = Rand.Range(validContainer.Value.MinAmount, validContainer.Value.MaxAmount + 1, Rand.RandSync.ServerAndClient);
}
int amount = Rand.Range(validContainer.Value.MinAmount, validContainer.Value.MaxAmount + 1, Rand.RandSync.ServerAndClient);
for (int i = 0; i < amount; i++)
{
if (validContainer.Key.Inventory.IsFull(takeStacksIntoAccount: true))
@@ -255,14 +322,12 @@ namespace Barotrauma
containers.Remove(validContainer.Key);
break;
}
var existingItem = validContainer.Key.Inventory.AllItems.FirstOrDefault(it => it.Prefab == itemPrefab);
int quality =
existingItem?.Quality ??
ToolBox.SelectWeightedRandom(
qualityCommonnesses.Select(q => q.quality).ToList(),
qualityCommonnesses.Select(q => q.commonness).ToList(),
Rand.RandSync.ServerAndClient);
qualityCommonnesses.Select(q => q.commonness).ToList(), Rand.RandSync.ServerAndClient);
if (!validContainer.Key.Inventory.CanBePut(itemPrefab, quality: quality)) { break; }
var item = new Item(itemPrefab, validContainer.Key.Item.Position, validContainer.Key.Item.Submarine, callOnItemLoaded: false)
{
@@ -277,11 +342,11 @@ namespace Barotrauma
{
wifiComponent.TeamID = validContainer.Key.Item.Submarine.TeamID;
}
spawnedItems.Add(item);
newItems.Add(item);
validContainer.Key.Inventory.TryPutItem(item, null, createNetworkEvent: false);
containers.AddRange(item.GetComponents<ItemContainer>());
}
return spawnedItems;
return newItems;
}
}
}
@@ -22,14 +22,14 @@ namespace Barotrauma
public int Quantity { get; set; }
public bool? IsStoreComponentEnabled { get; set; }
public readonly int BuyerCharacterInfoId;
public readonly int BuyerCharacterInfoIdentifier;
public PurchasedItem(ItemPrefab itemPrefab, int quantity, int buyerCharacterInfoId)
{
ItemPrefabIdentifier = itemPrefab.Identifier;
Quantity = quantity;
IsStoreComponentEnabled = null;
BuyerCharacterInfoId = buyerCharacterInfoId;
BuyerCharacterInfoIdentifier = buyerCharacterInfoId;
}
#if CLIENT
@@ -44,7 +44,7 @@ namespace Barotrauma
ItemPrefabIdentifier = itemPrefabId;
Quantity = quantity;
IsStoreComponentEnabled = null;
BuyerCharacterInfoId = buyer?.Character?.Info?.ID ?? Character.Controlled?.Info?.ID ?? 0;
BuyerCharacterInfoIdentifier = buyer?.Character?.Info?.GetIdentifier() ?? Character.Controlled?.Info?.GetIdentifier() ?? 0;
}
public override string ToString()
@@ -284,11 +284,10 @@ namespace Barotrauma
foreach (PurchasedItem item in newItems)
{
int itemValue = item.Quantity * buyValues[item.ItemPrefab];
GameAnalyticsManager.AddMoneySpentEvent(itemValue, GameAnalyticsManager.MoneySink.Store, item.ItemPrefab.Identifier.Value);
sb.Append($"\n - {item.ItemPrefab.Name} x{item.Quantity}");
price += itemValue;
}
GameServer.Log($"{NetworkMember.ClientLogName(client, client?.Name ?? "Unknown")} purchased {newItems.Count} item(s) for {TextManager.FormatCurrency(price)}{sb.ToString()}", ServerLog.MessageType.Money);
}
#endif
@@ -317,7 +316,10 @@ namespace Barotrauma
// Exchange money
int itemValue = item.Quantity * buyValues[item.ItemPrefab];
campaign.TryPurchase(client, itemValue);
GameAnalyticsManager.AddMoneySpentEvent(itemValue, GameAnalyticsManager.MoneySink.Store, item.ItemPrefab.Identifier.Value);
if (GameMain.IsSingleplayer)
{
GameAnalyticsManager.AddMoneySpentEvent(itemValue, GameAnalyticsManager.MoneySink.Store, item.ItemPrefab.Identifier.Value);
}
store.Balance += itemValue;
if (removeFromCrate)
{
@@ -368,12 +370,13 @@ namespace Barotrauma
public void CreatePurchasedItems()
{
purchasedIDCards.Clear();
var items = new List<PurchasedItem>();
foreach (var storeSpecificItems in PurchasedItems)
{
items.AddRange(storeSpecificItems.Value);
}
CreateItems(items, Submarine.MainSub);
CreateItems(items, Submarine.MainSub, this);
PurchasedItems.Clear();
OnPurchasedItemsChanged?.Invoke();
}
@@ -407,7 +410,7 @@ namespace Barotrauma
if (!item.Components.All(c => !(c is Holdable h) || !h.Attachable || !h.Attached)) { return false; }
if (!item.Components.All(c => !(c is Wire w) || w.Connections.All(c => c == null))) { return false; }
if (!ItemAndAllContainersInteractable(item)) { return false; }
if (item.GetRootContainer() is Item rootContainer && rootContainer.HasTag("donttakeitems")) { return false; }
if (item.GetRootContainer() is Item rootContainer && rootContainer.HasTag("dontsellitems")) { return false; }
return true;
}).Distinct();
@@ -428,7 +431,7 @@ namespace Barotrauma
if (!item.Prefab.CanBeSold) { return false; }
if (item.SpawnedInCurrentOutpost) { return false; }
if (!item.Prefab.AllowSellingWhenBroken && item.ConditionPercentage < 90.0f) { return false; }
if (confirmedItems.Any(ci => ci.Item == item)) { return false; }
if (confirmedItems != null && confirmedItems.Any(ci => ci.Item == item)) { return false; }
if (UndeterminedSoldEntities.TryGetValue(item.Prefab, out int count))
{
int newCount = count - 1;
@@ -448,13 +451,58 @@ namespace Barotrauma
if (containedItems.None()) { return true; }
// Allow selling the item if contained items are unsellable and set to be removed on deconstruct
if (itemContainer.RemoveContainedItemsOnDeconstruct && containedItems.All(it => !it.Prefab.CanBeSold)) { return true; }
// Otherwise there must be no contained items or the contained items must be confirmed as sold
if (!containedItems.All(it => confirmedItems.Any(ci => ci.Item == it))) { return false; }
if (confirmedItems != null)
{
// Otherwise there must be no contained items or the contained items must be confirmed as sold
if (!containedItems.All(it => confirmedItems.Any(ci => ci.Item == it))) { return false; }
}
}
return true;
}
public static void CreateItems(List<PurchasedItem> itemsToSpawn, Submarine sub)
public static ItemContainer GetOrCreateCargoContainerFor(ItemPrefab item, ISpatialEntity cargoRoomOrSpawnPoint, ref List<ItemContainer> availableContainers)
{
ItemContainer itemContainer = null;
if (!string.IsNullOrEmpty(item.CargoContainerIdentifier))
{
itemContainer = availableContainers.Find(ac =>
ac.Inventory.CanBePut(item) &&
(ac.Item.Prefab.Identifier == item.CargoContainerIdentifier ||
ac.Item.Prefab.Tags.Contains(item.CargoContainerIdentifier)));
if (itemContainer == null)
{
ItemPrefab containerPrefab = ItemPrefab.Prefabs.Find(ep =>
ep.Identifier == item.CargoContainerIdentifier ||
(ep.Tags != null && ep.Tags.Contains(item.CargoContainerIdentifier)));
if (containerPrefab == null)
{
DebugConsole.AddWarning($"CargoManager: could not find the item prefab for container {item.CargoContainerIdentifier}!");
return null;
}
Vector2 containerPosition = cargoRoomOrSpawnPoint is Hull cargoRoom ? GetCargoPos(cargoRoom, containerPrefab) : cargoRoomOrSpawnPoint.Position;
Item containerItem = new Item(containerPrefab, containerPosition, cargoRoomOrSpawnPoint.Submarine);
itemContainer = containerItem.GetComponent<ItemContainer>();
if (itemContainer == null)
{
DebugConsole.AddWarning($"CargoManager: No ItemContainer component found in {containerItem.Prefab.Identifier}!");
return null;
}
availableContainers.Add(itemContainer);
#if SERVER
if (GameMain.Server != null)
{
Entity.Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(itemContainer.Item));
}
#endif
}
}
return itemContainer;
}
public static void CreateItems(List<PurchasedItem> itemsToSpawn, Submarine sub, CargoManager cargoManager)
{
if (itemsToSpawn.Count == 0) { return; }
@@ -496,60 +544,26 @@ namespace Barotrauma
}
List<ItemContainer> availableContainers = new List<ItemContainer>();
ItemPrefab containerPrefab = null;
foreach (PurchasedItem pi in itemsToSpawn)
{
Vector2 position = GetCargoPos(cargoRoom, pi.ItemPrefab);
for (int i = 0; i < pi.Quantity; i++)
{
ItemContainer itemContainer = null;
if (!string.IsNullOrEmpty(pi.ItemPrefab.CargoContainerIdentifier))
{
itemContainer = availableContainers.Find(ac =>
ac.Inventory.CanBePut(pi.ItemPrefab) &&
(ac.Item.Prefab.Identifier == pi.ItemPrefab.CargoContainerIdentifier ||
ac.Item.Prefab.Tags.Contains(pi.ItemPrefab.CargoContainerIdentifier.ToLowerInvariant())));
if (itemContainer == null)
{
containerPrefab = ItemPrefab.Prefabs.Find(ep =>
ep.Identifier == pi.ItemPrefab.CargoContainerIdentifier ||
(ep.Tags != null && ep.Tags.Contains(pi.ItemPrefab.CargoContainerIdentifier.ToLowerInvariant())));
if (containerPrefab == null)
{
DebugConsole.ThrowError("Cargo spawning failed - could not find the item prefab for container \"" + pi.ItemPrefab.CargoContainerIdentifier + "\"!");
continue;
}
Vector2 containerPosition = GetCargoPos(cargoRoom, containerPrefab);
Item containerItem = new Item(containerPrefab, containerPosition, wp.Submarine);
itemContainer = containerItem.GetComponent<ItemContainer>();
if (itemContainer == null)
{
DebugConsole.ThrowError("Cargo spawning failed - container \"" + containerItem.Name + "\" does not have an ItemContainer component!");
continue;
}
availableContainers.Add(itemContainer);
#if SERVER
if (GameMain.Server != null)
{
Entity.Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(itemContainer.Item));
}
#endif
}
}
var item = new Item(pi.ItemPrefab, position, wp.Submarine);
itemContainer?.Inventory.TryPutItem(item, null);
itemSpawned(item);
var itemContainer = GetOrCreateCargoContainerFor(pi.ItemPrefab, cargoRoom, ref availableContainers);
itemContainer?.Inventory.TryPutItem(item, null);
var idCard = item.GetComponent<IdCard>();
if (cargoManager != null && idCard != null && pi.BuyerCharacterInfoIdentifier != 0)
{
cargoManager.purchasedIDCards.Add((pi, idCard));
}
itemSpawned(pi, item);
#if SERVER
Entity.Spawner?.CreateNetworkEvent(new EntitySpawner.SpawnEntity(item));
#endif
(itemContainer?.Item ?? item).CampaignInteractionType = CampaignMode.InteractionType.Cargo;
static void itemSpawned(Item item)
static void itemSpawned(PurchasedItem purchased, Item item)
{
Submarine sub = item.Submarine ?? item.GetRootContainer()?.Submarine;
if (sub != null)
@@ -565,6 +579,23 @@ namespace Barotrauma
itemsToSpawn.Clear();
}
private readonly List<(PurchasedItem purchaseInfo, IdCard idCard)> purchasedIDCards = new List<(PurchasedItem purchaseInfo, IdCard idCard)>();
public void InitPurchasedIDCards()
{
foreach ((PurchasedItem purchased, IdCard idCard) in purchasedIDCards)
{
if (idCard != null && purchased.BuyerCharacterInfoIdentifier != 0)
{
var owner = Character.CharacterList.Find(c => c.Info?.GetIdentifier() == purchased.BuyerCharacterInfoIdentifier);
if (owner?.Info != null)
{
var mainSubSpawnPoints = WayPoint.SelectCrewSpawnPoints(new List<CharacterInfo>() { owner.Info }, Submarine.MainSub);
idCard.Initialize(mainSubSpawnPoints.FirstOrDefault(), owner);
}
}
}
}
public static Vector2 GetCargoPos(Hull hull, ItemPrefab itemPrefab)
{
float floorPos = hull.Rect.Y - hull.Rect.Height;
@@ -603,7 +634,7 @@ namespace Barotrauma
new XAttribute("id", item.ItemPrefab.Identifier),
new XAttribute("qty", item.Quantity),
new XAttribute("storeid", storeSpecificItems.Key),
new XAttribute("buyer", item.BuyerCharacterInfoId)));
new XAttribute("buyer", item.BuyerCharacterInfoIdentifier)));
}
}
parentElement.Add(itemsElement);
@@ -51,8 +51,6 @@ namespace Barotrauma
public ReadyCheck ActiveReadyCheck;
public XElement ActiveOrdersElement { get; set; }
public CrewManager(bool isSinglePlayer)
{
IsSinglePlayer = isSinglePlayer;
@@ -493,9 +491,8 @@ namespace Barotrauma
partial void UpdateProjectSpecific(float deltaTime);
private void SaveActiveOrders(XElement parentElement)
public void SaveActiveOrders(XElement element)
{
ActiveOrdersElement = new XElement("activeorders");
// Only save orders with no fade out time (e.g. ignore orders)
var ordersToSave = new List<Order>();
foreach (var activeOrder in ActiveOrders)
@@ -504,14 +501,13 @@ namespace Barotrauma
if (order == null || activeOrder.FadeOutTime.HasValue) { continue; }
ordersToSave.Add(order.WithManualPriority(CharacterInfo.HighestManualOrderPriority));
}
CharacterInfo.SaveOrders(ActiveOrdersElement, ordersToSave.ToArray());
parentElement?.Add(ActiveOrdersElement);
CharacterInfo.SaveOrders(element, ordersToSave.ToArray());
}
public void LoadActiveOrders()
public void LoadActiveOrders(XElement element)
{
if (ActiveOrdersElement == null) { return; }
foreach (var orderInfo in CharacterInfo.LoadOrders(ActiveOrdersElement))
if (element == null) { return; }
foreach (var orderInfo in CharacterInfo.LoadOrders(element))
{
IIgnorable ignoreTarget = null;
if (orderInfo.IsIgnoreOrder)
@@ -1,4 +1,5 @@
using Barotrauma.Items.Components;
using Barotrauma.Extensions;
using Barotrauma.Items.Components;
using Barotrauma.Networking;
using FarseerPhysics;
using Microsoft.Xna.Framework;
@@ -107,6 +108,8 @@ namespace Barotrauma
protected XElement petsElement;
protected XElement ActiveOrdersElement { get; set; }
public CampaignSettings Settings;
private readonly List<Mission> extraMissions = new List<Mission>();
@@ -739,8 +742,10 @@ namespace Barotrauma
foreach (LocationConnection connection in Map.Connections)
{
connection.Difficulty = MathHelper.Lerp(connection.Difficulty, 100.0f, 0.25f);
connection.LevelData.Difficulty = connection.Difficulty;
connection.LevelData.IsBeaconActive = false;
connection.LevelData = new LevelData(connection)
{
IsBeaconActive = false
};
connection.LevelData.HasHuntingGrounds = connection.LevelData.OriginallyHadHuntingGrounds;
}
foreach (Location location in Map.Locations)
@@ -1032,5 +1037,184 @@ namespace Barotrauma
}
}
protected void LeaveUnconnectedSubs(Submarine leavingSub)
{
if (leavingSub != Submarine.MainSub && !leavingSub.DockedTo.Contains(Submarine.MainSub))
{
Submarine.MainSub = leavingSub;
GameMain.GameSession.Submarine = leavingSub;
GameMain.GameSession.SubmarineInfo = leavingSub.Info;
leavingSub.Info.FilePath = System.IO.Path.Combine(SaveUtil.TempPath, leavingSub.Info.Name + ".sub");
var subsToLeaveBehind = GetSubsToLeaveBehind(leavingSub);
GameMain.GameSession.OwnedSubmarines.Add(leavingSub.Info);
foreach (Submarine sub in subsToLeaveBehind)
{
GameMain.GameSession.OwnedSubmarines.RemoveAll(s => s != leavingSub.Info && s.Name == sub.Info.Name);
MapEntity.mapEntityList.RemoveAll(e => e.Submarine == sub && e is LinkedSubmarine);
LinkedSubmarine.CreateDummy(leavingSub, sub);
}
}
}
public SubmarineInfo SwitchSubs()
{
TransferItemsBetweenSubs();
RefreshOwnedSubmarines();
PendingSubmarineSwitch = null;
return GameMain.GameSession.SubmarineInfo;
}
/// <summary>
/// Also serializes the current sub.
/// </summary>
protected void TransferItemsBetweenSubs()
{
Submarine currentSub = GameMain.GameSession.Submarine;
if (currentSub == null || currentSub.Removed)
{
DebugConsole.ThrowError("Cannot transfer items between subs, because the current sub is null or removed!");
return;
}
var itemsToTransfer = new List<(Item item, Item container)>();
if (PendingSubmarineSwitch != null)
{
// Remove items from the old sub
foreach (Item item in Item.ItemList)
{
if (item.Removed) { continue; }
if (item.NonInteractable) { continue; }
if (item.HiddenInGame) { continue; }
if (item.Submarine != currentSub) { continue; }
if (item.Prefab.DontTransferBetweenSubs) { continue; }
if (item.GetRootInventoryOwner() is Character) { continue; }
if (item.GetComponent<Holdable>() == null && item.GetComponent<Wearable>() == null && item.GetComponent<Projectile>() == null) { continue; }
if (item.Components.Any(c => c is Holdable h && h.Attached)) { continue; }
if (item.Components.Any(c => c is Wire w && w.Connections.Any(c => c != null))) { continue; }
itemsToTransfer.Add((item, item.Container));
item.Submarine = null;
}
foreach (var (item, container) in itemsToTransfer)
{
if (container?.Submarine != null)
{
// Drop the item if it's not inside another item set to be transferred.
item.Drop(null, createNetworkEvent: false, setTransform: false);
}
}
}
// Serialize the current sub
GameMain.GameSession.SubmarineInfo = new SubmarineInfo(currentSub);
if (PendingSubmarineSwitch != null && itemsToTransfer.Any())
{
// Load the new sub
var newSub = new Submarine(PendingSubmarineSwitch);
// Move the transferred items
List<ItemContainer> availableContainers = Item.ItemList
.Where(it => it.Submarine == newSub && it.HasTag("crate") && !it.NonInteractable && !it.HiddenInGame && !it.Removed)
.Select(it => it.GetComponent<ItemContainer>())
.Where(c => c != null)
.ToList();
foreach (var (item, oldContainer) in itemsToTransfer)
{
Item newContainer = null;
item.Submarine = newSub;
if (item.Container == null)
{
newContainer = newSub.FindContainerFor(item, onlyPrimary: true, checkTransferConditions: true);
}
if (item.Container == null && (newContainer == null || !newContainer.OwnInventory.TryPutItem(item, user: null, createNetworkEvent: false)))
{
WayPoint wp = WayPoint.GetRandom(SpawnType.Cargo, null, newSub);
Hull spawnHull = wp?.CurrentHull ?? Hull.HullList.Where(h => h.Submarine == newSub && !h.IsWetRoom).GetRandomUnsynced();
if (spawnHull == null)
{
DebugConsole.AddWarning($"Failed to transfer items between subs. No cargo waypoint or dry hulls found in the new sub.");
return;
}
if (spawnHull != null)
{
var cargoContainer = CargoManager.GetOrCreateCargoContainerFor(item.Prefab, spawnHull, ref availableContainers);
if (cargoContainer == null || !cargoContainer.Inventory.TryPutItem(item, user: null, createNetworkEvent: false))
{
item.SetTransform(wp.SimPosition, 0.0f, findNewHull: false, setPrevTransform: false);
}
}
else
{
DebugConsole.AddWarning($"Failed to transfer item {item.Prefab.Identifier} ({item.ID}), because no cargo spawn point could be found!");
}
}
string newContainerName = newContainer == null ? "(null)" : $"{newContainer.Prefab.Identifier} ({newContainer.Tags})";
string msg = "Item transfer log error.";
if (oldContainer != null)
{
if (newContainer == null && oldContainer == item.Container)
{
msg = $"Transferred {item.Prefab.Identifier} ({item.ID}) contained inside {oldContainer.Prefab.Identifier} ({oldContainer.ID})";
}
else
{
msg = $"Transferred {item.Prefab.Identifier} ({item.ID}) from {oldContainer.Prefab.Identifier} ({oldContainer.Tags}) to {newContainerName}";
}
}
else
{
msg = $"Transferred {item.Prefab.Identifier} ({item.ID}) to {newContainerName}";
}
#if DEBUG
DebugConsole.NewMessage(msg);
#else
DebugConsole.Log(msg);
#endif
}
// Serialize the new sub
PendingSubmarineSwitch = new SubmarineInfo(newSub);
}
}
protected void RefreshOwnedSubmarines()
{
if (PendingSubmarineSwitch != null)
{
SubmarineInfo previousSub = GameMain.GameSession.SubmarineInfo;
GameMain.GameSession.SubmarineInfo = PendingSubmarineSwitch;
for (int i = 0; i < GameMain.GameSession.OwnedSubmarines.Count; i++)
{
if (GameMain.GameSession.OwnedSubmarines[i].Name == previousSub.Name)
{
GameMain.GameSession.OwnedSubmarines[i] = previousSub;
break;
}
}
}
}
public void SavePets(XElement parentElement = null)
{
petsElement = new XElement("pets");
PetBehavior.SavePets(petsElement);
parentElement?.Add(petsElement);
}
public void LoadPets()
{
if (petsElement != null)
{
PetBehavior.LoadPets(petsElement);
}
}
public void SaveActiveOrders(XElement parentElement = null)
{
ActiveOrdersElement = new XElement("activeorders");
CrewManager?.SaveActiveOrders(ActiveOrdersElement);
parentElement?.Add(ActiveOrdersElement);
}
public void LoadActiveOrders()
{
CrewManager?.LoadActiveOrders(ActiveOrdersElement);
}
}
}
@@ -155,7 +155,7 @@ namespace Barotrauma
case "bots" when GameMain.NetworkMember != null && GameMain.NetworkMember.IsServer:
CrewManager.HasBots = subElement.GetAttributeBool("hasbots", false);
CrewManager.AddCharacterElements(subElement);
CrewManager.ActiveOrdersElement = subElement.GetChildElement("activeorders");
ActiveOrdersElement = subElement.GetChildElement("activeorders");
break;
case "cargo":
CargoManager?.LoadPurchasedItems(subElement);
@@ -275,7 +275,7 @@ namespace Barotrauma
/// <summary>
/// Switch to another submarine. The sub is loaded when the next round starts.
/// </summary>
public SubmarineInfo SwitchSubmarine(SubmarineInfo newSubmarine, int cost, Client? client = null)
public void SwitchSubmarine(SubmarineInfo newSubmarine, int cost, Client? client = null)
{
if (!OwnedSubmarines.Any(s => s.Name == newSubmarine.Name))
{
@@ -293,15 +293,12 @@ namespace Barotrauma
}
}
}
if ((GameMain.NetworkMember is null || GameMain.NetworkMember is { IsServer: true }) && cost > 0)
{
Campaign!.TryPurchase(client, cost);
}
GameAnalyticsManager.AddMoneySpentEvent(cost, GameAnalyticsManager.MoneySink.SubmarineSwitch, newSubmarine.Name);
Campaign!.PendingSubmarineSwitch = newSubmarine;
return newSubmarine;
}
public void PurchaseSubmarine(SubmarineInfo newSubmarine, Client? client = null)
@@ -600,10 +597,13 @@ namespace Barotrauma
{
//only place items and corpses here in single player
//the server does this after loading the respawn shuttle
Level?.SpawnNPCs();
Level?.SpawnCorpses();
Level?.PrepareBeaconStation();
AutoItemPlacer.PlaceIfNeeded();
if (Level != null)
{
Level.SpawnNPCs();
Level.SpawnCorpses();
Level.PrepareBeaconStation();
}
AutoItemPlacer.SpawnItems();
}
if (GameMode is MultiPlayerCampaign mpCampaign)
{
@@ -836,6 +836,11 @@ namespace Barotrauma
{
GUI.TogglePauseMenu();
}
if (IsTabMenuOpen)
{
ToggleTabMenu();
}
GUI.PreventPauseMenuToggle = true;
if (!(GameMode is TestGameMode) && Screen.Selected == GameMain.GameScreen && RoundSummary != null)
@@ -1072,8 +1077,21 @@ namespace Barotrauma
rootElement.Add(new XAttribute("savetime", ToolBox.Epoch.NowLocal));
rootElement.Add(new XAttribute("version", GameMain.Version));
var submarineInfo = Campaign?.PendingSubmarineSwitch ?? SubmarineInfo;
rootElement.Add(new XAttribute("submarine", submarineInfo == null ? "" : submarineInfo.Name));
if (Submarine?.Info != null && !Submarine.Removed && Campaign != null)
{
bool hasNewPendingSub = Campaign.PendingSubmarineSwitch != null &&
Campaign.PendingSubmarineSwitch.MD5Hash.StringRepresentation != Submarine.Info.MD5Hash.StringRepresentation;
if (hasNewPendingSub)
{
Campaign.SwitchSubs();
}
else
{
SubmarineInfo = new SubmarineInfo(Submarine);
}
}
rootElement.Add(new XAttribute("submarine", SubmarineInfo == null ? "" : SubmarineInfo.Name));
if (OwnedSubmarines != null)
{
List<string> ownedSubmarineNames = new List<string>();