Unstable 0.1300.1.11

This commit is contained in:
Markus Isberg
2021-04-26 21:07:23 +03:00
parent 841d755394
commit 2c750282ec
76 changed files with 671 additions and 396 deletions
@@ -21,6 +21,11 @@ namespace Barotrauma
throw new System.Exception("Error in CargoMission.ClientReadInitial: item count does not match the server count (" + itemCount + " != " + items.Count + ", mission: " + Prefab.Identifier + ")");
}
if (requiredDeliveryAmount == 0) { requiredDeliveryAmount = items.Count; }
if (requiredDeliveryAmount > items.Count)
{
DebugConsole.AddWarning($"Error in mission \"{Prefab.Identifier}\". Required delivery amount is {requiredDeliveryAmount} but there's only {items.Count} items to deliver.");
requiredDeliveryAmount = items.Count;
}
}
}
}
@@ -1274,6 +1274,7 @@ namespace Barotrauma
private static void UpdateSavingIndicator(float deltaTime)
{
if (Style.SavingIndicator == null) { return; }
lock (mutex)
{
if (timeUntilSavingIndicatorDisabled.HasValue)
@@ -1651,7 +1652,7 @@ namespace Barotrauma
private static void DrawSavingIndicator(SpriteBatch spriteBatch)
{
if (!IsSavingIndicatorVisible) { return; }
if (!IsSavingIndicatorVisible || Style.SavingIndicator == null) { return; }
var sheet = Style.SavingIndicator;
Vector2 pos = new Vector2(GameMain.GraphicsWidth, GameMain.GraphicsHeight) - new Vector2(HUDLayoutSettings.Padding) - 2 * Scale * sheet.FrameSize.ToVector2();
sheet.Draw(spriteBatch, (int)Math.Floor(savingIndicatorSpriteIndex), pos, savingIndicatorColor, origin: Vector2.Zero, rotate: 0.0f, scale: new Vector2(Scale));
@@ -1319,17 +1319,26 @@ namespace Barotrauma
// When using Deselect to close the interface, make sure it's not a seconday mouse button click on a node
// That should be reserved for opening manual assignment
var hitDeselect = PlayerInput.KeyHit(InputType.Deselect) && (!PlayerInput.SecondaryMouseButtonClicked() ||
(optionNodes.None(n => GUI.IsMouseOn(n.Item1)) && shortcutNodes.None(n => GUI.IsMouseOn(n))));
bool isMouseOnOptionNode = optionNodes.Any(n => GUI.IsMouseOn(n.Item1));
bool isMouseOnShortcutNode = !isMouseOnOptionNode && shortcutNodes.Any(n => GUI.IsMouseOn(n));
bool hitDeselect = PlayerInput.KeyHit(InputType.Deselect) &&
(!PlayerInput.SecondaryMouseButtonClicked() || (!isMouseOnOptionNode && !isMouseOnShortcutNode));
bool isBoundToPrimaryMouse = GameMain.Config.KeyBind(InputType.Command).MouseButton is MouseButton mouseButton &&
(mouseButton == MouseButton.PrimaryMouse || mouseButton == (PlayerInput.MouseButtonsSwapped() ? MouseButton.RightMouse : MouseButton.LeftMouse));
bool canToggleInterface = !isBoundToPrimaryMouse ||
(!isMouseOnOptionNode && !isMouseOnShortcutNode && extraOptionNodes.None(n => GUI.IsMouseOn(n)) && !GUI.IsMouseOn(returnNode));
// TODO: Consider using HUD.CloseHUD() instead of KeyHit(Escape), the former method is also used for health UI
if (hitDeselect || PlayerInput.KeyHit(Keys.Escape) || !CanIssueOrders ||
(PlayerInput.KeyHit(InputType.Command) && selectedNode == null && !clicklessSelectionActive))
(canToggleInterface && PlayerInput.KeyHit(InputType.Command) && selectedNode == null && !clicklessSelectionActive))
{
DisableCommandUI();
}
else if (PlayerInput.KeyUp(InputType.Command))
{
if (!isOpeningClick && clicklessSelectionActive && timeSelected < 0.15f)
// Clickless selection behavior
if (canToggleInterface && !isOpeningClick && clicklessSelectionActive && timeSelected < 0.15f)
{
DisableCommandUI();
}
@@ -1344,6 +1353,7 @@ namespace Barotrauma
}
else if (PlayerInput.KeyDown(InputType.Command) && (targetFrame == null || !targetFrame.Visible))
{
// Clickless selection behavior
if (!GUI.IsMouseOn(centerNode))
{
clicklessSelectionActive = true;
@@ -1914,6 +1924,7 @@ namespace Barotrauma
private bool NavigateForward(GUIButton node, object userData)
{
if (commandFrame == null) { return false; }
if (!(optionNodes.Find(n => n.Item1 == node) is Tuple<GUIComponent, Keys> optionNode) || !optionNodes.Remove(optionNode))
{
shortcutNodes.Remove(node);
@@ -1953,6 +1964,7 @@ namespace Barotrauma
private bool NavigateBackward(GUIButton node, object userData)
{
if (commandFrame == null) { return false; }
RemoveOptionNodes();
if (targetFrame != null) { targetFrame.Visible = false; }
// TODO: Center node could move to option node instead of being removed
@@ -474,8 +474,7 @@ namespace Barotrauma
public override void Update(float deltaTime, Camera cam, bool isSubInventory = false)
{
// Need to update the infiltrator's inventory because they use id cards to access the sub. TODO: We don't probably need to update everything.
if (!AccessibleWhenAlive && !character.IsDead && (character.Params.AI == null || !character.Params.AI.Infiltrate))
if (!AccessibleWhenAlive && !character.IsDead)
{
syncItemsDelay = Math.Max(syncItemsDelay - deltaTime, 0.0f);
return;
@@ -898,6 +898,22 @@ namespace Barotrauma.Items.Components
signalWarningText.Visible = false;
}
foreach (AITarget aiTarget in AITarget.List)
{
if (!aiTarget.Enabled) { continue; }
if (string.IsNullOrEmpty(aiTarget.SonarLabel) || aiTarget.SoundRange <= 0.0f) { continue; }
if (Vector2.DistanceSquared(aiTarget.WorldPosition, transducerCenter) < aiTarget.SoundRange * aiTarget.SoundRange)
{
DrawMarker(spriteBatch,
aiTarget.SonarLabel,
aiTarget.SonarIconIdentifier,
aiTarget,
aiTarget.WorldPosition, transducerCenter,
displayScale, center, DisplayRadius * 0.975f);
}
}
if (GameMain.GameSession == null || Level.Loaded == null) { return; }
if (Level.Loaded.StartLocation != null)
@@ -931,23 +947,7 @@ namespace Barotrauma.Items.Components
cave.StartPos.ToVector2(), transducerCenter,
displayScale, center, DisplayRadius);
}
foreach (AITarget aiTarget in AITarget.List)
{
if (!aiTarget.Enabled) { continue; }
if (string.IsNullOrEmpty(aiTarget.SonarLabel) || aiTarget.SoundRange <= 0.0f) { continue; }
if (Vector2.DistanceSquared(aiTarget.WorldPosition, transducerCenter) < aiTarget.SoundRange * aiTarget.SoundRange)
{
DrawMarker(spriteBatch,
aiTarget.SonarLabel,
aiTarget.SonarIconIdentifier,
aiTarget,
aiTarget.WorldPosition, transducerCenter,
displayScale, center, DisplayRadius * 0.975f);
}
}
foreach (Mission mission in GameMain.GameSession.Missions)
{
if (!string.IsNullOrWhiteSpace(mission.SonarLabel))
@@ -220,6 +220,8 @@ namespace Barotrauma
public int tooltipDisplayedCondition;
public bool ForceTooltipRefresh;
public SlotReference(Inventory parentInventory, VisualSlot slot, int slotIndex, bool isSubSlot, Inventory subInventory = null)
{
ParentInventory = parentInventory;
@@ -234,12 +236,14 @@ namespace Barotrauma
public bool TooltipNeedsRefresh()
{
if (ForceTooltipRefresh) { return true; }
if (Item == null) { return false; }
return (int)Item.ConditionPercentage != tooltipDisplayedCondition;
}
public void RefreshTooltip()
{
ForceTooltipRefresh = false;
if (Item == null) { return; }
IEnumerable<Item> itemsInSlot = null;
if (ParentInventory != null && Item != null)
@@ -160,17 +160,6 @@ namespace Barotrauma
public void Update(float deltaTime)
{
if (ParticleEmitters != null)
{
for (int i = 0; i < ParticleEmitters.Length; i++)
{
if (ParticleEmitterTriggers[i] != null && !ParticleEmitterTriggers[i].IsTriggered) continue;
Vector2 emitterPos = LocalToWorld(Prefab.EmitterPositions[i]);
ParticleEmitters[i].Emit(deltaTime, emitterPos, hullGuess: null,
angle: ParticleEmitters[i].Prefab.CopyEntityAngle ? Rotation : 0.0f);
}
}
CurrentRotation = Rotation;
if (ActivePrefab.SwingFrequency > 0.0f)
{
@@ -214,6 +203,17 @@ namespace Barotrauma
UpdateDeformations(deltaTime);
}
if (ParticleEmitters != null)
{
for (int i = 0; i < ParticleEmitters.Length; i++)
{
if (ParticleEmitterTriggers[i] != null && !ParticleEmitterTriggers[i].IsTriggered) { continue; }
Vector2 emitterPos = LocalToWorld(Prefab.EmitterPositions[i]);
ParticleEmitters[i].Emit(deltaTime, emitterPos, hullGuess: null,
angle: ParticleEmitters[i].Prefab.CopyEntityAngle ? -CurrentRotation + MathHelper.PiOver2 : 0.0f);
}
}
for (int i = 0; i < Sounds.Length; i++)
{
if (Sounds[i] == null) { continue; }
@@ -573,7 +573,7 @@ namespace Barotrauma
if (!spriteRecorder.ReadyToRender)
{
string waitText = !loadTask.IsCompleted ?
"Generating preview..." :
TextManager.Get("generatingsubmarinepreview", fallBackTag: "loading") :
(loadTask.Exception?.ToString() ?? "Task completed without marking as ready to render");
Vector2 origin = (GUI.Font.MeasureString(waitText) * 0.5f);
origin.X = MathF.Round(origin.X);
@@ -12,9 +12,10 @@ namespace Barotrauma.Networking
{
protected class ServerContentPackage
{
public string Name;
public string Hash;
public UInt64 WorkshopId;
public readonly string Name;
public readonly string Hash;
public readonly UInt64 WorkshopId;
public readonly DateTime InstallTime;
public ContentPackage RegularPackage
{
@@ -32,11 +33,12 @@ namespace Barotrauma.Networking
}
}
public ServerContentPackage(string name, string hash, UInt64 workshopId)
public ServerContentPackage(string name, string hash, UInt64 workshopId, DateTime installTime)
{
Name = name;
Hash = hash;
WorkshopId = workshopId;
InstallTime = installTime;
}
}
@@ -129,7 +131,10 @@ namespace Barotrauma.Networking
string name = inc.ReadString();
string hash = inc.ReadString();
UInt64 workshopId = inc.ReadUInt64();
var pkg = new ServerContentPackage(name, hash, workshopId);
UInt32 installTimeDiffSeconds = inc.ReadUInt32();
DateTime installTime = DateTime.UtcNow + TimeSpan.FromSeconds(installTimeDiffSeconds);
var pkg = new ServerContentPackage(name, hash, workshopId, installTime);
if (pkg.CorePackage != null)
{
corePackage = pkg;
@@ -147,16 +152,24 @@ namespace Barotrauma.Networking
if (missingPackages.Count > 0)
{
var nonDownloadable = missingPackages.Where(p => p.WorkshopId == 0);
var mismatchedButDownloaded = missingPackages.Where(p =>
var mismatchedButDownloaded = missingPackages.Where(remote =>
{
var localMatching = ContentPackage.RegularPackages.Find(l => l.SteamWorkshopId != 0 && p.WorkshopId == l.SteamWorkshopId);
localMatching ??= ContentPackage.CorePackages.Find(l => l.SteamWorkshopId != 0 && p.WorkshopId == l.SteamWorkshopId);
return localMatching != null;
return ContentPackage.AllPackages.Any(local =>
local.SteamWorkshopId != 0 && /* is a Workshop item */
remote.WorkshopId == local.SteamWorkshopId /* ids match */);
});
if (GameMain.ServerListScreen.LastAutoConnectEndpoint != ServerConnection.EndPointString)
{
mismatchedButDownloaded = mismatchedButDownloaded.Where(remote =>
{
return ContentPackage.AllPackages.Any(local =>
remote.InstallTime < local.InstallTime/* remote is older than local */);
});
}
if (mismatchedButDownloaded.Any())
{
GameMain.ServerListScreen.LastAutoConnectEndpoint = null;
string disconnectMsg;
if (mismatchedButDownloaded.Count() == 1)
{
@@ -1,4 +1,5 @@
using Barotrauma.IO;
using Barotrauma.Extensions;
using Barotrauma.IO;
using Barotrauma.Networking;
using RestSharp;
using System;
@@ -921,10 +922,6 @@ namespace Barotrauma.Steam
return null;
}
#if DEBUG
item = item?.WithPrivateVisibility();
#endif
contentPackage.GameVersion = GameMain.Version;
contentPackage.Save(contentPackage.Path);
@@ -969,6 +966,9 @@ namespace Barotrauma.Steam
}
else
{
//nuke the existing steamworks cache for the item we just published
ForceRedownload(task.Result.FileId);
workshopPublishStatus.Success = true;
workshopPublishStatus.Result = task.Result;
DebugConsole.NewMessage("Published workshop item " + item?.Title + " successfully.", Microsoft.Xna.Framework.Color.LightGreen);
@@ -986,41 +986,61 @@ namespace Barotrauma.Steam
yield return CoroutineStatus.Success;
}
/// <summary>
/// Forces a Workshop item to redownload.
/// </summary>
public static void ForceRedownload(Steamworks.Data.PublishedFileId itemId, Action onDownloadFinished = null)
{
Steamworks.Ugc.Item itemToNuke = new Steamworks.Ugc.Item(itemId);
string directory = itemToNuke.Directory;
if (Directory.Exists(directory))
{
try
{
Directory.Delete(directory, true);
}
catch (Exception e) { DebugConsole.ThrowError("Failed to delete Workshop item cache", e); }
}
itemToNuke.Download(onDownloadFinished, highPriority: true);
}
/// <summary>
/// Installs a workshop item by moving it to the game folder.
/// </summary>
public static bool InstallWorkshopItem(Steamworks.Ugc.Item? item, out string errorMsg, bool enableContentPackage = false, bool suppressInstallNotif = false)
public static bool InstallWorkshopItem(Steamworks.Ugc.Item? itemOrNull, out string errorMsg, bool enableContentPackage = false, bool suppressInstallNotif = false)
{
if (!(item?.IsInstalled ?? false))
errorMsg = "Item is null";
if (!itemOrNull.TryGetValue(out Steamworks.Ugc.Item item)) { return false; }
if (!item.IsInstalled)
{
errorMsg = TextManager.GetWithVariable("WorkshopErrorInstallRequiredToEnable", "[itemname]", item?.Title ?? "[NULL]");
errorMsg = TextManager.GetWithVariable("WorkshopErrorInstallRequiredToEnable", "[itemname]", item.Title);
DebugConsole.NewMessage(errorMsg, Color.Red);
return false;
}
string metaDataFilePath = Path.Combine(item?.Directory, MetadataFileName);
string metaDataFilePath = Path.Combine(item.Directory, MetadataFileName);
if (!File.Exists(metaDataFilePath))
{
errorMsg = TextManager.GetWithVariable("WorkshopErrorInstallRequiredToEnable", "[itemname]", item?.Title);
errorMsg = TextManager.GetWithVariable("WorkshopErrorInstallRequiredToEnable", "[itemname]", item.Title);
DebugConsole.ThrowError(errorMsg);
return false;
}
ContentPackage contentPackage = new ContentPackage(metaDataFilePath)
{
SteamWorkshopId = item?.Id ?? 0
SteamWorkshopId = item.Id
};
string newContentPackagePath = GetWorkshopItemContentPackagePath(contentPackage);
List<ContentPackage> existingPackages = ContentPackage.AllPackages.Where(cp => cp.Path.CleanUpPath() == newContentPackagePath.CleanUpPath()).ToList();
if (existingPackages.Any())
{
if (item?.Owner.Id != Steamworks.SteamClient.SteamId)
if (item.Owner.Id != Steamworks.SteamClient.SteamId)
{
errorMsg = TextManager.GetWithVariables("WorkshopErrorSamePathInstalled",
new string[] { "[itemname]", "[itempath]" },
new string[] { item?.Title, Path.GetDirectoryName(newContentPackagePath) });
new string[] { item.Title, Path.GetDirectoryName(newContentPackagePath) });
return false;
}
else
@@ -1041,12 +1061,12 @@ namespace Barotrauma.Steam
lock (modCopiesInProgress)
{
if (modCopiesInProgress.ContainsKey(item.Value.Id))
if (modCopiesInProgress.ContainsKey(item.Id))
{
errorMsg = ""; return true;
}
newTask = CopyWorkShopItemAsync(item, contentPackage, newContentPackagePath, metaDataFilePath);
modCopiesInProgress.Add(item.Value.Id, newTask);
modCopiesInProgress.Add(item.Id, newTask);
}
TaskPool.Add("CopyWorkShopItemAsync",
@@ -1058,14 +1078,14 @@ namespace Barotrauma.Steam
{
if (task.IsFaulted || task.IsCanceled)
{
DebugConsole.ThrowError($"Failed to copy \"{item?.Title}\"", task.Exception);
DebugConsole.ThrowError($"Failed to copy \"{item.Title}\"", task.Exception);
GameMain.SteamWorkshopScreen?.SetReinstallButtonStatus(item, true, GUI.Style.Red);
return;
}
string errorMsg = ((Task<string>)task).Result;
if (!string.IsNullOrWhiteSpace(errorMsg))
{
DebugConsole.ThrowError($"Failed to copy \"{item?.Title}\": {errorMsg}");
DebugConsole.ThrowError($"Failed to copy \"{item.Title}\": {errorMsg}");
GameMain.SteamWorkshopScreen?.SetReinstallButtonStatus(item, true, GUI.Style.Red);
return;
}
@@ -1074,8 +1094,8 @@ namespace Barotrauma.Steam
var newPackage = new ContentPackage(cp.Path, newContentPackagePath)
{
SteamWorkshopId = item?.Id ?? 0,
InstallTime = item?.Updated > item?.Created ? item?.Updated : item?.Created
SteamWorkshopId = item.Id,
InstallTime = item.Updated > item.Created ? item.Updated : item.Created
};
foreach (ContentFile contentFile in newPackage.Files)
@@ -1124,7 +1144,6 @@ namespace Barotrauma.Steam
GameMain.Config.SuppressModFolderWatcher = false;
GameMain.SteamWorkshopScreen?.SetReinstallButtonStatus(item, true, GUI.Style.Green);
}
catch
{
@@ -1132,7 +1151,7 @@ namespace Barotrauma.Steam
}
finally
{
modCopiesInProgress.Remove(item.Value.Id);
modCopiesInProgress.Remove(item.Id);
}
});
@@ -1144,9 +1163,27 @@ namespace Barotrauma.Steam
/// Asynchronously copies a Workshop item into the Mods folder.
/// </summary>
/// <returns>Returns an empty string on success, otherwise returns an error message.</returns>
private async static Task<string> CopyWorkShopItemAsync(Steamworks.Ugc.Item? item, ContentPackage contentPackage, string newContentPackagePath, string metaDataFilePath)
private async static Task<string> CopyWorkShopItemAsync(Steamworks.Ugc.Item? itemOrNull, ContentPackage contentPackage, string newContentPackagePath, string metaDataFilePath)
{
await Task.Yield();
if (!itemOrNull.TryGetValue(out Steamworks.Ugc.Item item)) { return "Item is null"; }
if (item.NeedsUpdate)
{
item.Download(highPriority: true);
await Task.Delay(1000);
}
while (item.NeedsUpdate && !item.IsDownloading && !item.IsDownloadPending && !item.IsInstalled)
{
if (!item.IsDownloading && !item.IsDownloadPending)
{
if (!item.Download())
{
return TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item.Title);
}
}
await Task.Delay(1000);
}
string targetPath = Path.GetDirectoryName(GetWorkshopItemContentPackagePath(contentPackage));
string copyingPath = Path.Combine(targetPath, CopyIndicatorFileName);
@@ -1157,18 +1194,18 @@ namespace Barotrauma.Steam
Directory.CreateDirectory(targetPath);
File.WriteAllText(copyingPath, "TEMPORARY FILE");
SaveUtil.CopyFolder(item?.Directory, targetPath, copySubDirs: true, overwriteExisting: false);
SaveUtil.CopyFolder(item.Directory, targetPath, copySubDirs: true, overwriteExisting: false);
File.Delete(copyingPath);
return "";
}
var allPackageFiles = Directory.GetFiles(item?.Directory, "*", System.IO.SearchOption.AllDirectories);
var allPackageFiles = Directory.GetFiles(item.Directory, "*", System.IO.SearchOption.AllDirectories);
List<string> nonContentFiles = new List<string>();
foreach (string file in allPackageFiles)
{
if (file == metaDataFilePath) { continue; }
string relativePath = UpdaterUtil.GetRelativePath(file, item?.Directory);
string relativePath = UpdaterUtil.GetRelativePath(file, item.Directory);
string fullPath = Path.GetFullPath(relativePath);
if (contentPackage.Files.Any(f => { string fp = Path.GetFullPath(f.Path); return fp == fullPath; })) { continue; }
nonContentFiles.Add(relativePath);
@@ -1198,14 +1235,14 @@ namespace Barotrauma.Steam
foreach (ContentFile contentFile in contentPackage.Files)
{
contentFile.Path = contentFile.Path.CleanUpPathCrossPlatform(correctFilenameCase: true, item?.Directory);
string sourceFile = Path.Combine(item?.Directory, contentFile.Path);
contentFile.Path = contentFile.Path.CleanUpPathCrossPlatform(correctFilenameCase: true, item.Directory);
string sourceFile = Path.Combine(item.Directory, contentFile.Path);
if (!File.Exists(sourceFile))
{
string[] splitPath = contentFile.Path.Split('/');
if (splitPath.Length >= 2 && splitPath[0] == "Mods")
{
sourceFile = Path.Combine(item?.Directory, string.Join("/", splitPath.Skip(2)));
sourceFile = Path.Combine(item.Directory, string.Join("/", splitPath.Skip(2)));
}
}
@@ -1225,7 +1262,7 @@ namespace Barotrauma.Steam
//if the external file doesn't exist, we cannot enable the package
else if (!File.Exists(contentFile.Path))
{
errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item?.Title) + " " + TextManager.GetWithVariable("WorkshopFileNotFound", "[path]", "\"" + contentFile.Path + "\"");
errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item.Title) + " " + TextManager.GetWithVariable("WorkshopFileNotFound", "[path]", "\"" + contentFile.Path + "\"");
return errorMsg;
}
continue;
@@ -1240,7 +1277,7 @@ namespace Barotrauma.Steam
else
{
//file not present in either the mod or the game folder -> cannot enable the package
errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item?.Title) + " " + TextManager.GetWithVariable("WorkshopFileNotFound", "[path]", "\"" + contentFile.Path + "\"");
errorMsg = TextManager.GetWithVariable("WorkshopErrorEnableFailed", "[itemname]", item.Title) + " " + TextManager.GetWithVariable("WorkshopFileNotFound", "[path]", "\"" + contentFile.Path + "\"");
return errorMsg;
}
}
@@ -1252,7 +1289,7 @@ namespace Barotrauma.Steam
foreach (string nonContentFile in nonContentFiles)
{
string sourceFile = Path.Combine(item?.Directory, nonContentFile);
string sourceFile = Path.Combine(item.Directory, nonContentFile);
if (!File.Exists(sourceFile)) { continue; }
string destinationPath = CorrectContentFilePath(nonContentFile, ContentType.None, contentPackage, false);
Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
@@ -1351,43 +1388,50 @@ namespace Barotrauma.Steam
string metaDataPath = Path.Combine(item?.Directory, MetadataFileName);
if (!File.Exists(metaDataPath))
{
throw new System.IO.FileNotFoundException("Metadata file for the Workshop item \"" + item?.Title + "\" not found. The file may be corrupted.");
DebugConsole.ThrowError("Metadata file for the Workshop item \"" + item?.Title + "\" not found. The file may be corrupted.", appendStackTrace: true);
return null;
}
ContentPackage contentPackage = new ContentPackage(metaDataPath);
return contentPackage.IsCompatible();
}
public static bool CheckWorkshopItemInstalled(Steamworks.Ugc.Item? item)
public static bool CheckWorkshopItemInstalled(Steamworks.Ugc.Item? itemOrNull)
{
if (!(item?.IsInstalled ?? false)) { return false; }
if (!itemOrNull.TryGetValue(out Steamworks.Ugc.Item item)) { return false; }
if (!item.IsInstalled) { return false; }
lock (modCopiesInProgress)
{
if (modCopiesInProgress.ContainsKey(item.Value.Id))
if (modCopiesInProgress.ContainsKey(item.Id))
{
return true;
}
}
if (!Directory.Exists(item?.Directory))
if (item.NeedsUpdate && !item.IsDownloading && !item.IsDownloadPending)
{
DebugConsole.ThrowError("Workshop item \"" + item?.Title + "\" has been installed but the install directory cannot be found. Attempting to redownload...");
item?.Download();
return false;
item.Download();
return false;
}
if (!Directory.Exists(item.Directory))
{
DebugConsole.ThrowError("Workshop item \"" + item.Title + "\" has been installed but the install directory cannot be found. Attempting to redownload...");
item.Download();
return false;
}
string metaDataPath = "";
try
{
metaDataPath = Path.Combine(item?.Directory, MetadataFileName);
metaDataPath = Path.Combine(item.Directory, MetadataFileName);
}
catch (ArgumentException)
{
string errorMessage = "Metadata file for the Workshop item \"" + item?.Title +
"\" not found. Could not combine path (" + (item?.Directory ?? "directory name empty") + ").";
string errorMessage = "Metadata file for the Workshop item \"" + item.Title +
"\" not found. Could not combine path (" + (item.Directory ?? "directory name empty") + ").";
DebugConsole.ThrowError(errorMessage);
GameAnalyticsManager.AddErrorEventOnce("SteamManager.CheckWorkshopItemInstalled:PathCombineException" + item?.Title,
GameAnalyticsManager.AddErrorEventOnce("SteamManager.CheckWorkshopItemInstalled:PathCombineException" + item.Title,
GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
errorMessage);
return false;
@@ -1395,13 +1439,13 @@ namespace Barotrauma.Steam
if (!File.Exists(metaDataPath))
{
DebugConsole.ThrowError("Metadata file for the Workshop item \"" + item?.Title + "\" not found. The file may be corrupted.");
DebugConsole.ThrowError("Metadata file for the Workshop item \"" + item.Title + "\" not found. The file may be corrupted.");
return false;
}
ContentPackage contentPackage = new ContentPackage(metaDataPath)
{
SteamWorkshopId = item?.Id ?? 0
SteamWorkshopId = item.Id
};
//make sure the contentpackage file is present
if (!File.Exists(GetWorkshopItemContentPackagePath(contentPackage)) ||
@@ -1414,20 +1458,21 @@ namespace Barotrauma.Steam
return true;
}
public static bool CheckWorkshopItemUpToDate(Steamworks.Ugc.Item? item)
public static bool CheckWorkshopItemUpToDate(Steamworks.Ugc.Item? itemOrNull)
{
if (!(item?.IsInstalled ?? false)) return false;
if (!itemOrNull.TryGetValue(out Steamworks.Ugc.Item item)) { return false; }
if (!item.IsInstalled || item.NeedsUpdate || item.IsDownloading || item.IsDownloadPending) { return false; }
string metaDataPath = Path.Combine(item?.Directory, MetadataFileName);
string metaDataPath = Path.Combine(item.Directory, MetadataFileName);
if (!File.Exists(metaDataPath))
{
DebugConsole.ThrowError("Metadata file for the Workshop item \"" + item?.Title + "\" not found. The file may be corrupted.");
DebugConsole.ThrowError("Metadata file for the Workshop item \"" + item.Title + "\" not found. The file may be corrupted.");
return false;
}
ContentPackage steamPackage = new ContentPackage(metaDataPath)
{
SteamWorkshopId = item?.Id ?? 0
SteamWorkshopId = item.Id
};
ContentPackage myPackage = ContentPackage.AllPackages.FirstOrDefault(cp => cp.SteamWorkshopId == steamPackage.SteamWorkshopId);
@@ -1435,7 +1480,7 @@ namespace Barotrauma.Steam
{
return false;
}
DateTime latestTime = item.Value.Updated > item.Value.Created ? item.Value.Updated : item.Value.Created;
DateTime latestTime = item.Updated > item.Created ? item.Updated : item.Created;
bool upToDate = latestTime <= myPackage.InstallTime.Value;
return upToDate;
}
@@ -1,4 +1,5 @@
using Barotrauma.Sounds;
using Concentus.Structs;
using Microsoft.Xna.Framework;
using OpenAL;
using System;
@@ -23,6 +24,8 @@ namespace Barotrauma.Networking
private bool capturing;
private OpusEncoder encoder;
public double LastdB
{
get;
@@ -79,7 +82,7 @@ namespace Barotrauma.Networking
{
Disconnected = false;
VoipConfig.SetupEncoding();
encoder = VoipConfig.CreateEncoder();
//set up capture device
captureDevice = Alc.CaptureOpenDevice(deviceName, VoipConfig.FREQUENCY, Al.FormatMono16, VoipConfig.BUFFER_SIZE * 5);
@@ -265,10 +268,10 @@ namespace Barotrauma.Networking
{
if (!prevCaptured) //enqueue the previous buffer if not sent to avoid cutoff
{
int compressedCountPrev = VoipConfig.Encoder.Encode(prevUncompressedBuffer, 0, VoipConfig.BUFFER_SIZE, BufferToQueue, 0, VoipConfig.MAX_COMPRESSED_SIZE);
int compressedCountPrev = encoder.Encode(prevUncompressedBuffer, 0, VoipConfig.BUFFER_SIZE, BufferToQueue, 0, VoipConfig.MAX_COMPRESSED_SIZE);
EnqueueBuffer(compressedCountPrev);
}
int compressedCount = VoipConfig.Encoder.Encode(uncompressedBuffer, 0, VoipConfig.BUFFER_SIZE, BufferToQueue, 0, VoipConfig.MAX_COMPRESSED_SIZE);
int compressedCount = encoder.Encode(uncompressedBuffer, 0, VoipConfig.BUFFER_SIZE, BufferToQueue, 0, VoipConfig.MAX_COMPRESSED_SIZE);
EnqueueBuffer(compressedCount);
}
captureTimer -= (VoipConfig.BUFFER_SIZE * 1000) / VoipConfig.FREQUENCY;
@@ -10,35 +10,22 @@ namespace Barotrauma.Networking
{
static partial class VoipConfig
{
public static bool Ready = false;
public const int FREQUENCY = 48000; //48Khz
public const int BITRATE = 16000; //16Kbps
public const int BUFFER_SIZE = (8 * MAX_COMPRESSED_SIZE * FREQUENCY) / BITRATE; //20ms window
public const int FREQUENCY = 48000;
public const int BUFFER_SIZE = 960; //20ms window
public static OpusEncoder CreateEncoder()
{
var encoder = new OpusEncoder(FREQUENCY, 1, OpusApplication.OPUS_APPLICATION_VOIP);
encoder.Bandwidth = OpusBandwidth.OPUS_BANDWIDTH_AUTO;
encoder.Bitrate = BITRATE;
encoder.SignalType = OpusSignal.OPUS_SIGNAL_VOICE;
return encoder;
}
public static OpusEncoder Encoder
public static OpusDecoder CreateDecoder()
{
get;
private set;
}
public static OpusDecoder Decoder
{
get;
private set;
}
public static void SetupEncoding()
{
if (!Ready)
{
Encoder = new OpusEncoder(FREQUENCY, 1, OpusApplication.OPUS_APPLICATION_VOIP);
Encoder.Bandwidth = OpusBandwidth.OPUS_BANDWIDTH_AUTO;
Encoder.Bitrate = 8 * MAX_COMPRESSED_SIZE * FREQUENCY / BUFFER_SIZE;
Encoder.SignalType = OpusSignal.OPUS_SIGNAL_VOICE;
Decoder = new OpusDecoder(FREQUENCY, 1);
Ready = true;
}
return new OpusDecoder(FREQUENCY, 1);
}
}
}
@@ -407,7 +407,7 @@ namespace Barotrauma
ToolTip = TextManager.Get(connection.LevelData.IsBeaconActive ? "BeaconStationActiveTooltip" : "BeaconStationInactiveTooltip")
};
new GUITextBlock(new RectTransform(Vector2.One, beaconStationContent.RectTransform),
TextManager.Get("submarinetype.beaconstation"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft)
TextManager.Get("submarinetype.beaconstation", fallBackTag: "beaconstationsonarlabel"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft)
{
Padding = Vector4.Zero,
ToolTip = icon.ToolTip
@@ -78,7 +78,7 @@ namespace Barotrauma
private readonly GUIFrame playerInfoContainer;
private GUILayoutGroup infoContainer;
private GUITextBlock changesPendingText;
private GUIComponent changesPendingText;
public GUIButton PlayerFrame;
private readonly GUIComponent subPreviewContainer;
@@ -417,7 +417,7 @@ namespace Barotrauma
{
if (!(FileTransferFrame.UserData is FileReceiver.FileTransferIn transfer)) { return false; }
GameMain.Client?.CancelFileTransfer(transfer);
GameMain.Client.FileReceiver.StopTransfer(transfer);
GameMain.Client?.FileReceiver.StopTransfer(transfer);
return true;
}
};
@@ -1632,9 +1632,17 @@ namespace Barotrauma
private void CreateChangesPendingText()
{
if (changesPendingText != null || infoContainer == null) return;
changesPendingText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.065f), infoContainer.Parent.RectTransform, Anchor.BottomCenter, Pivot.TopCenter) { RelativeOffset = new Vector2(0f, -0.065f) },
TextManager.Get("tabmenu.characterchangespending"), textColor: GUI.Style.Orange, textAlignment: Alignment.Center, style: null) { IgnoreLayoutGroups = true };
if (changesPendingText != null || infoContainer == null) { return; }
changesPendingText = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.065f), infoContainer.Parent.Parent.RectTransform, Anchor.BottomCenter, Pivot.TopCenter) { RelativeOffset = new Vector2(0f, -0.03f) },
style: "OuterGlow")
{
Color = Color.Black,
IgnoreLayoutGroups = true
};
var text = new GUITextBlock(new RectTransform(Vector2.One, changesPendingText.RectTransform, Anchor.Center),
TextManager.Get("tabmenu.characterchangespending"), textColor: GUI.Style.Orange, textAlignment: Alignment.Center, style: null);
changesPendingText.RectTransform.MinSize = new Point((int)(text.TextSize.X * 1.2f), (int)(text.TextSize.Y * 2.0f));
}
private void CreateJobVariantTooltip(JobPrefab jobPrefab, int variant, GUIComponent parentSlot)
@@ -189,7 +189,7 @@ namespace Barotrauma
var particlePrefabs = GameMain.ParticleManager.GetPrefabList();
foreach (ParticlePrefab particlePrefab in particlePrefabs)
{
var prefabText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), prefabList.Content.RectTransform) { MinSize = new Point(0, 20) },
new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.05f), prefabList.Content.RectTransform) { MinSize = new Point(0, 20) },
particlePrefab.DisplayName)
{
Padding = Vector4.Zero,
@@ -231,6 +231,7 @@ namespace Barotrauma
private void SerializeAll()
{
Barotrauma.IO.Validation.SkipValidationInDebugBuilds = true;
foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.Particles))
{
XDocument doc = XMLExtensions.TryLoadXml(configFile.Path);
@@ -259,6 +260,7 @@ namespace Barotrauma
writer.Flush();
}
}
Barotrauma.IO.Validation.SkipValidationInDebugBuilds = false;
}
private void SerializeToClipboard(ParticlePrefab prefab)
@@ -41,7 +41,9 @@ namespace Barotrauma
private GUIFrame workshopDownloadsFrame = null;
private Steamworks.Ugc.Item? currentlyDownloadingWorkshopItem = null;
private Dictionary<ulong, Steamworks.Ugc.Item?> pendingWorkshopDownloads = null;
private string autoConnectName; private string autoConnectEndpoint;
private string autoConnectName;
public string AutoConnectEndpoint { get; private set; }
public string LastAutoConnectEndpoint;
private enum TernaryOption
{
@@ -1037,7 +1039,7 @@ namespace Barotrauma
}
}
if (currentlyDownloadingWorkshopItem?.IsInstalled ?? true)
if (currentlyDownloadingWorkshopItem == null)
{
if (pendingWorkshopDownloads?.Any() ?? false)
{
@@ -1046,15 +1048,19 @@ namespace Barotrauma
{
ulong itemId = item.Value.Id;
currentlyDownloadingWorkshopItem = item;
SteamManager.SubscribeToWorkshopItem(itemId, () =>
SteamManager.ForceRedownload(item.Value.Id, () =>
{
if (!(item?.IsSubscribed ?? false))
{
TaskPool.Add("SubscribeToServerMod", item?.Subscribe(), (t) => { });
}
pendingWorkshopDownloads.Remove(itemId);
currentlyDownloadingWorkshopItem = null;
if (SteamManager.CheckWorkshopItemInstalled(item))
{
SteamManager.UninstallWorkshopItem(item, false, out _);
}
if (SteamManager.InstallWorkshopItem(item, out string errorMsg, enableContentPackage: false, suppressInstallNotif: true))
{
workshopDownloadsFrame?.FindChild((c) => c.UserData is ulong l && l == itemId, true)?.Flash(GUI.Style.Green);
@@ -1067,10 +1073,11 @@ namespace Barotrauma
});
}
}
else if (!string.IsNullOrEmpty(autoConnectEndpoint))
else if (!string.IsNullOrEmpty(AutoConnectEndpoint))
{
JoinServer(autoConnectEndpoint, autoConnectName);
autoConnectEndpoint = null;
LastAutoConnectEndpoint = AutoConnectEndpoint;
JoinServer(AutoConnectEndpoint, autoConnectName);
AutoConnectEndpoint = null;
}
}
}
@@ -2132,9 +2139,10 @@ namespace Barotrauma
if (workshopDownloadsFrame != null) { return; }
int rowCount = ids.Count() + 2;
autoConnectName = serverName; autoConnectEndpoint = endPointString;
autoConnectName = serverName; AutoConnectEndpoint = endPointString;
workshopDownloadsFrame = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas), null, Color.Black * 0.5f);
currentlyDownloadingWorkshopItem = null;
pendingWorkshopDownloads = new Dictionary<ulong, Steamworks.Ugc.Item?>();
var innerFrame = new GUIFrame(new RectTransform(new Vector2(0.5f, 0.1f + 0.03f * rowCount), workshopDownloadsFrame.RectTransform, Anchor.Center, Pivot.Center));
@@ -2191,9 +2199,11 @@ namespace Barotrauma
{
OnClicked = (btn, obj) =>
{
autoConnectEndpoint = null;
AutoConnectEndpoint = null;
LastAutoConnectEndpoint = null;
autoConnectName = null;
pendingWorkshopDownloads.Clear();
currentlyDownloadingWorkshopItem = null;
workshopDownloadsFrame = null;
return true;
}
@@ -682,12 +682,21 @@ namespace Barotrauma
try
{
bool reselect = GameMain.Config.AllEnabledPackages.Any(cp => cp.SteamWorkshopId != 0 && cp.SteamWorkshopId == item?.Id);
if (!SteamManager.UninstallWorkshopItem(item, false, out string errorMsg) ||
!SteamManager.InstallWorkshopItem(item, out errorMsg, reselect, true))
if (!SteamManager.UninstallWorkshopItem(item, false, out string errorMsg))
{
DebugConsole.ThrowError($"Failed to reinstall \"{item?.Title}\": {errorMsg}", null, true);
elem.Flash(GUI.Style.Red);
return true;
}
SteamManager.ForceRedownload(item?.Id ?? 0, () =>
{
if (!SteamManager.InstallWorkshopItem(item, out string errorMsg, reselect, true))
{
DebugConsole.ThrowError($"Failed to reinstall \"{item?.Title}\": {errorMsg}", null, true);
elem.Flash(GUI.Style.Red);
}
});
}
catch (Exception e)
{
@@ -2815,13 +2815,17 @@ namespace Barotrauma
foreach (GUIComponent child in categorizedEntityList.Content.Children)
{
child.Visible = !entityCategory.HasValue || (MapEntityCategory)child.UserData == entityCategory;
if (child.Visible && dummyCharacter?.SelectedConstruction?.OwnInventory != null)
var innerList = child.GetChild<GUIListBox>();
foreach (GUIComponent grandChild in innerList.Content.Children)
{
child.Visible = child.UserData is MapEntityPrefab item && IsItemPrefab(item);
grandChild.Visible = true;
}
}
if (!string.IsNullOrEmpty(entityFilterBox.Text)) { FilterEntities(entityFilterBox.Text); }
if (!string.IsNullOrEmpty(entityFilterBox.Text) || dummyCharacter?.SelectedConstruction?.OwnInventory != null)
{
FilterEntities(entityFilterBox.Text);
}
categorizedEntityList.UpdateScrollBarSize();
categorizedEntityList.BarScroll = 0.0f;
@@ -2831,7 +2835,7 @@ namespace Barotrauma
private void FilterEntities(string filter)
{
if (string.IsNullOrWhiteSpace(filter))
if (string.IsNullOrWhiteSpace(filter) && dummyCharacter?.SelectedConstruction?.OwnInventory == null)
{
allEntityList.Visible = false;
categorizedEntityList.Visible = true;
@@ -2844,10 +2848,6 @@ namespace Barotrauma
foreach (GUIComponent grandChild in innerList.Content.Children)
{
grandChild.Visible = ((MapEntityPrefab)grandChild.UserData).Name.ToLower().Contains(filter);
if (grandChild.Visible && dummyCharacter?.SelectedConstruction?.OwnInventory != null)
{
grandChild.Visible = grandChild.UserData is MapEntityPrefab item && IsItemPrefab(item);
}
}
};
categorizedEntityList.UpdateScrollBarSize();
@@ -1,5 +1,6 @@
using Barotrauma.IO;
using Barotrauma.Networking;
using Concentus.Structs;
using Microsoft.Xna.Framework;
using OpenAL;
using System;
@@ -30,6 +31,8 @@ namespace Barotrauma.Sounds
private SoundChannel soundChannel;
private OpusDecoder decoder;
public bool UseRadioFilter;
public bool UseMuffleFilter;
@@ -65,7 +68,7 @@ namespace Barotrauma.Sounds
public VoipSound(string name, SoundManager owner, VoipQueue q) : base(owner, $"VoIP ({name})", true, true, getFullPath: false)
{
VoipConfig.SetupEncoding();
decoder = VoipConfig.CreateDecoder();
ALFormat = Al.FormatMono16;
SampleRate = VoipConfig.FREQUENCY;
@@ -152,7 +155,7 @@ namespace Barotrauma.Sounds
{
if (compressedSize > 0)
{
VoipConfig.Decoder.Decode(compressedBuffer, 0, compressedSize, buffer, 0, VoipConfig.BUFFER_SIZE);
decoder.Decode(compressedBuffer, 0, compressedSize, buffer, 0, VoipConfig.BUFFER_SIZE);
bufferID++;
return VoipConfig.BUFFER_SIZE;
}
@@ -5,6 +5,7 @@ using Barotrauma.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using System.Globalization;
namespace Barotrauma
{
@@ -217,7 +218,7 @@ namespace Barotrauma
$"<PersonalityTrait " +
$"{GetVariable("name", split[1])}" +
$"{GetVariable("alloweddialogtags", string.Join(",", NPCPersonalityTrait.List[i].AllowedDialogTags))}" +
$"{GetVariable("commonness", NPCPersonalityTrait.List[i].Commonness.ToString())}/>");
$"{GetVariable("commonness", NPCPersonalityTrait.List[i].Commonness.ToString(CultureInfo.InvariantCulture))}/>");
}
xmlContent.Add(string.Empty);