diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 6a035c1c7..342e85237 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,6 +1,9 @@ --- name: Bug report about: Found a bug? Help us squash it by making a bug report! +title: '' +labels: '' +assignees: '' --- @@ -13,8 +16,7 @@ A clear and concise description of what the bug is. If possible, describe how the developers can reproduce the issue. It is often extremely hard to fix a bug if we don't know how to make it happen. **Version** -Which version of the game did the bug happen in. You can see the version number at the bottom left corner of the main menu, and in a file called "Version.txt" inside the game folder. -Also, please include the operating system you're using (Windows/Linux/Mac). +Which version of the game did the bug happen in. Also, please include the operating system you're using (Windows/Linux/Mac). **Additional information** Add any other context about the problem here. diff --git a/Barotrauma/BarotraumaClient/ClientSource/Camera.cs b/Barotrauma/BarotraumaClient/ClientSource/Camera.cs index 48648f15b..1afe18bd0 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Camera.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Camera.cs @@ -335,8 +335,7 @@ namespace Barotrauma //an ad-hoc way of allowing the players to have roughly the same maximum view distance regardless of the resolution, //while still keeping the zoom around 1.0 when not looking further away (because otherwise we'd always be downsampling //on lower resolutions, which doesn't look that good) - float newZoom = MathHelper.Lerp(unscaledZoom, scaledZoom, - (GameMain.Config == null || GameMain.Config.EnableMouseLook) ? (float)Math.Sqrt(zoomOutAmount) : 0.3f); + float newZoom = MathHelper.Lerp(unscaledZoom, scaledZoom, (float)Math.Sqrt(zoomOutAmount)); Zoom += (newZoom - zoom) / ZoomSmoothness; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/AITarget.cs b/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/AITarget.cs index bf6555d5d..a237a6a1e 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/AITarget.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/AITarget.cs @@ -9,7 +9,7 @@ namespace Barotrauma public void Draw(SpriteBatch spriteBatch) { - if (!ShowAITargets) { return; } + if (!ShowAITargets) return; var pos = new Vector2(WorldPosition.X, -WorldPosition.Y); if (soundRange > 0.0f) { @@ -43,7 +43,7 @@ namespace Barotrauma } else { - //color = Color.WhiteSmoke; + color = Color.WhiteSmoke; // disable the indicators for structures, because they clutter the debug view return; } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/EnemyAIController.cs b/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/EnemyAIController.cs index a9ff967ca..d33b41d27 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/EnemyAIController.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/EnemyAIController.cs @@ -17,7 +17,7 @@ namespace Barotrauma if (State == AIState.Idle && PreviousState == AIState.Attack) { var target = _selectedAiTarget ?? _lastAiTarget; - if (target != null && target.Entity != null) + if (target != null) { var memory = GetTargetMemory(target); Vector2 targetPos = memory.Location; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/HumanAIController.cs b/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/HumanAIController.cs index fdf426063..726985bb1 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/HumanAIController.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Characters/AI/HumanAIController.cs @@ -16,6 +16,11 @@ namespace Barotrauma }*/ } + partial void SetOrderProjSpecific(Order order, string option) + { + GameMain.GameSession.CrewManager.DisplayCharacterOrder(Character, order, option); + } + public override void DebugDraw(Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch) { Vector2 pos = Character.WorldPosition; @@ -35,7 +40,7 @@ namespace Barotrauma var currentOrder = ObjectiveManager.CurrentOrder; if (currentOrder != null) { - GUI.DrawString(spriteBatch, pos + textOffset + new Vector2(0, 20), $"ORDER: {currentOrder.DebugTag} ({currentOrder.Priority.FormatZeroDecimal()})", Color.White, Color.Black); + GUI.DrawString(spriteBatch, pos + textOffset + new Vector2(0, 20), $"ORDER: {currentOrder.DebugTag} ({currentOrder.GetPriority().FormatZeroDecimal()})", Color.White, Color.Black); } else if (ObjectiveManager.WaitTimer > 0) { @@ -46,17 +51,17 @@ namespace Barotrauma { if (currentOrder == null) { - GUI.DrawString(spriteBatch, pos + textOffset + new Vector2(0, 20), $"MAIN OBJECTIVE: {currentObjective.DebugTag} ({currentObjective.Priority.FormatZeroDecimal()})", Color.White, Color.Black); + GUI.DrawString(spriteBatch, pos + textOffset + new Vector2(0, 20), $"MAIN OBJECTIVE: {currentObjective.DebugTag} ({currentObjective.GetPriority().FormatZeroDecimal()})", Color.White, Color.Black); } - var subObjective = currentObjective.CurrentSubObjective; + var subObjective = currentObjective.SubObjectives.FirstOrDefault(); if (subObjective != null) { - GUI.DrawString(spriteBatch, pos + textOffset + new Vector2(0, 40), $"SUBOBJECTIVE: {subObjective.DebugTag} ({subObjective.Priority.FormatZeroDecimal()})", Color.White, Color.Black); + GUI.DrawString(spriteBatch, pos + textOffset + new Vector2(0, 40), $"SUBOBJECTIVE: {subObjective.DebugTag} ({subObjective.GetPriority().FormatZeroDecimal()})", Color.White, Color.Black); } var activeObjective = ObjectiveManager.GetActiveObjective(); if (activeObjective != null) { - GUI.DrawString(spriteBatch, pos + textOffset + new Vector2(0, 60), $"ACTIVE OBJECTIVE: {activeObjective.DebugTag} ({activeObjective.Priority.FormatZeroDecimal()})", Color.White, Color.Black); + GUI.DrawString(spriteBatch, pos + textOffset + new Vector2(0, 60), $"ACTIVE OBJECTIVE: {activeObjective.DebugTag} ({activeObjective.GetPriority().FormatZeroDecimal()})", Color.White, Color.Black); } } } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Characters/Character.cs b/Barotrauma/BarotraumaClient/ClientSource/Characters/Character.cs index e7ed22d8b..a2e3ff53f 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Characters/Character.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Characters/Character.cs @@ -603,11 +603,6 @@ namespace Barotrauma } } - partial void SetOrderProjSpecific(Order order, string orderOption) - { - GameMain.GameSession?.CrewManager?.DisplayCharacterOrder(this, order, orderOption); - } - public static void AddAllToGUIUpdateList() { for (int i = 0; i < CharacterList.Count; i++) @@ -643,7 +638,8 @@ namespace Barotrauma public void Draw(SpriteBatch spriteBatch, Camera cam) { - if (!Enabled) { return; } + if (!Enabled) return; + AnimController.Draw(spriteBatch, cam); } @@ -660,6 +656,8 @@ namespace Barotrauma if (GameMain.DebugDraw) { AnimController.DebugDraw(spriteBatch); + + if (aiTarget != null) aiTarget.Draw(spriteBatch); } if (GUI.DisableHUD) return; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterHUD.cs b/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterHUD.cs index f337e8296..2f2b23ece 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterHUD.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterHUD.cs @@ -92,7 +92,7 @@ namespace Barotrauma if (!character.IsUnconscious && character.Stun <= 0.0f) { - if (character.Info != null && !character.ShouldLockHud() && character.SelectedCharacter == null) + if (character.Info != null && !character.ShouldLockHud()) { bool mouseOnPortrait = HUDLayoutSettings.BottomRightInfoArea.Contains(PlayerInput.MousePosition) && GUI.MouseOn == null; if (mouseOnPortrait && PlayerInput.PrimaryMouseButtonClicked()) @@ -309,7 +309,7 @@ namespace Barotrauma (int)(HUDLayoutSettings.BottomRightInfoArea.Y + HUDLayoutSettings.BottomRightInfoArea.Height * 0.1f), (int)(HUDLayoutSettings.BottomRightInfoArea.Width / 2), (int)(HUDLayoutSettings.BottomRightInfoArea.Height * 0.7f))); - character.Info.DrawPortrait(spriteBatch, HUDLayoutSettings.PortraitArea.Location.ToVector2(), new Vector2(-12 * GUI.Scale, 4 * GUI.Scale), targetWidth: HUDLayoutSettings.PortraitArea.Width, true); + character.Info.DrawPortrait(spriteBatch, HUDLayoutSettings.PortraitArea.Location.ToVector2(), new Vector2((int)(-4 * GUI.Scale), (int)(2 * GUI.Scale)), targetWidth: HUDLayoutSettings.PortraitArea.Width, true); } mouseOnPortrait = HUDLayoutSettings.BottomRightInfoArea.Contains(PlayerInput.MousePosition) && !character.ShouldLockHud(); if (mouseOnPortrait) diff --git a/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterInfo.cs b/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterInfo.cs index 4a93fc785..9758686d7 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterInfo.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterInfo.cs @@ -10,12 +10,12 @@ namespace Barotrauma { partial class CharacterInfo { + public const float BgScale = 1.2f; private static Sprite infoAreaPortraitBG; public static void Init() { - infoAreaPortraitBG = GUI.Style.GetComponentStyle("InfoAreaPortraitBG")?.Sprites[GUIComponent.ComponentState.None][0].Sprite; - new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(833, 298, 142, 98), null, 0); + infoAreaPortraitBG = new Sprite("Content/UI/InventoryUIAtlas.png", new Rectangle(833, 298, 142, 98), null, 0); } @@ -171,7 +171,6 @@ namespace Barotrauma public void DrawBackground(SpriteBatch spriteBatch) { - if (infoAreaPortraitBG == null) { return; } infoAreaPortraitBG.Draw(spriteBatch, HUDLayoutSettings.BottomRightInfoArea.Location.ToVector2(), Color.White, Vector2.Zero, 0.0f, scale: new Vector2( HUDLayoutSettings.BottomRightInfoArea.Width / (float)infoAreaPortraitBG.SourceRect.Width, diff --git a/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterNetworking.cs b/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterNetworking.cs index 5726215f5..28ca04741 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterNetworking.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterNetworking.cs @@ -1,5 +1,4 @@ -using Barotrauma.Extensions; -using Barotrauma.Networking; +using Barotrauma.Networking; using Microsoft.Xna.Framework; using System; using System.Linq; @@ -385,37 +384,6 @@ namespace Barotrauma character = Create(speciesName, position, seed, info, GameMain.Client.ID != ownerId, hasAi); character.ID = id; character.TeamID = (TeamType)teamID; - - // Check if the character has a current order - if (inc.ReadBoolean()) - { - int orderPrefabIndex = inc.ReadByte(); - Entity targetEntity = FindEntityByID(inc.ReadUInt16()); - Character orderGiver = inc.ReadBoolean() ? FindEntityByID(inc.ReadUInt16()) as Character : null; - int orderOptionIndex = inc.ReadByte(); - - if (orderPrefabIndex >= 0 && orderPrefabIndex < Order.PrefabList.Count) - { - var orderPrefab = Order.PrefabList[orderPrefabIndex]; - if ((orderPrefab.ItemComponentType == null && orderPrefab.ItemIdentifiers.None()) || - (targetEntity != null && (targetEntity as Item).Components.Any(c => c?.GetType() == orderPrefab.ItemComponentType))) - { - character.SetOrder( - new Order(orderPrefab, targetEntity, (targetEntity as Item)?.Components.FirstOrDefault(c => c?.GetType() == orderPrefab.ItemComponentType), orderGiver: orderGiver), - orderOptionIndex >= 0 && orderOptionIndex < orderPrefab.Options.Length ? orderPrefab.Options[orderOptionIndex] : null, - orderGiver, speak: false); - } - else - { - DebugConsole.ThrowError("Could not set order \"" + orderPrefab.Identifier + "\" for character \"" + character.Name + "\" because required target entity was not found."); - } - } - else - { - DebugConsole.ThrowError("Invalid order prefab index - index (" + orderPrefabIndex + ") out of bounds."); - } - } - bool containsStatusData = inc.ReadBoolean(); if (containsStatusData) { diff --git a/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterSound.cs b/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterSound.cs index e93c6e2b8..a096c3cc9 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterSound.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Characters/CharacterSound.cs @@ -14,8 +14,8 @@ namespace Barotrauma public SoundType Type => Params.State; public Gender Gender => Params.Gender; - public float Volume => roundSound == null ? 0.0f : roundSound.Volume; - public float Range => roundSound == null ? 0.0f : roundSound.Range; + public float Volume => roundSound.Volume; + public float Range => roundSound.Range; public Sound Sound => roundSound?.Sound; public CharacterSound(CharacterParams.SoundParams soundParams) diff --git a/Barotrauma/BarotraumaClient/ClientSource/Characters/Health/CharacterHealth.cs b/Barotrauma/BarotraumaClient/ClientSource/Characters/Health/CharacterHealth.cs index 823d018cb..360e81399 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Characters/Health/CharacterHealth.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Characters/Health/CharacterHealth.cs @@ -246,13 +246,11 @@ namespace Barotrauma } private GUIFrame healthBarHolder; - private Point healthBarOffset { get { - // 0.38775510204f = percentage of offset before reaching the healthbar portion of the graphic going from bottom upwards - return new Point(2, (int)(HUDLayoutSettings.HealthBarArea.Size.Y * 0.38775510204f)); + return new Point(5 - (int)Math.Ceiling(1 - 1 * GUI.Scale), (int)Math.Min(Math.Ceiling(17 * GUI.Scale), 20)); } } @@ -260,7 +258,7 @@ namespace Barotrauma { get { - return new Point((int)Math.Ceiling(HUDLayoutSettings.HealthBarArea.Size.X - 45 * GUI.Scale), (int)(healthBarHolder.Rect.Height - Math.Min(23 * GUI.Scale, 25)) / 2); + return new Point(healthBarHolder.Rect.Width - (int)Math.Ceiling(Math.Min(46 * GUI.Scale, 53)), (int)(healthBarHolder.Rect.Height - Math.Min(23 * GUI.Scale, 25)) / 2); } } @@ -305,7 +303,7 @@ namespace Barotrauma healthShadowSize = 1.0f; healthBar = new GUIProgressBar(new RectTransform(healthBarSize, healthBarHolder.RectTransform, Anchor.BottomRight), - barSize: 1.0f, color: GUI.Style.HealthBarColorHigh, style: horizontal ? "CharacterHealthBarSlider" : "GUIProgressBarVertical", showFrame: false) + barSize: 1.0f, color: GUIColorSettings.HealthBarColorHigh, style: horizontal ? "CharacterHealthBarSlider" : "GUIProgressBarVertical", showFrame: false) { HoverCursor = CursorState.Hand, Enabled = true, @@ -522,10 +520,8 @@ namespace Barotrauma UpdateAlignment(); - suicideButton = new GUIButton(new RectTransform(new Vector2(0.1f, 0.02f), GUI.Canvas, Anchor.TopCenter) - { - MinSize = new Point(150, 20), RelativeOffset = new Vector2(0.0f, 0.01f) - }, + suicideButton = new GUIButton(new RectTransform(new Vector2(0.06f, 0.02f), GUI.Canvas, Anchor.TopCenter) + { MinSize = new Point(150, 20), RelativeOffset = new Vector2(0.0f, 0.01f) }, TextManager.Get("GiveInButton"), style: "GUIButtonLarge") { ToolTip = TextManager.Get(GameMain.NetworkMember == null ? "GiveInHelpSingleplayer" : "GiveInHelpMultiplayer"), @@ -820,7 +816,9 @@ namespace Barotrauma if (highlightedLimbIndex < 0 && selectedLimbIndex < 0) { // If no limb is selected or highlighted, select the one with the most critical afflictions. - var affliction = SortAfflictionsBySeverity(GetAllAfflictions(a => a.Prefab.IndicatorLimb != LimbType.None)).FirstOrDefault(); + var affliction = GetAllAfflictions(a => a.Prefab.IndicatorLimb != LimbType.None) + .OrderByDescending(a => a.DamagePerSecond) + .ThenByDescending(a => a.Strength).FirstOrDefault(); if (affliction.DamagePerSecond > 0 || affliction.Strength > 0) { var limbHealth = GetMatchingLimbHealth(affliction); @@ -851,7 +849,7 @@ namespace Barotrauma } else { - healthBar.Color = healthWindowHealthBar.Color = ToolBox.GradientLerp(DisplayedVitality / MaxVitality, GUI.Style.HealthBarColorLow, GUI.Style.HealthBarColorMedium, GUI.Style.HealthBarColorHigh); + healthBar.Color = healthWindowHealthBar.Color = ToolBox.GradientLerp(DisplayedVitality / MaxVitality, GUIColorSettings.HealthBarColorLow, GUIColorSettings.HealthBarColorMedium, GUIColorSettings.HealthBarColorHigh); healthBar.HoverColor = healthWindowHealthBar.HoverColor = healthBar.Color * 2.0f; healthBar.BarSize = healthWindowHealthBar.BarSize = (DisplayedVitality > 0.0f) ? @@ -1136,11 +1134,11 @@ namespace Barotrauma { if (prefab.IsBuff) { - return ToolBox.GradientLerp(affliction.Strength / prefab.MaxStrength, GUI.Style.BuffColorLow, GUI.Style.BuffColorMedium, GUI.Style.BuffColorHigh); + return ToolBox.GradientLerp(affliction.Strength / prefab.MaxStrength, GUIColorSettings.BuffColorLow, GUIColorSettings.BuffColorMedium, GUIColorSettings.BuffColorHigh); } else { - return ToolBox.GradientLerp(affliction.Strength / prefab.MaxStrength, GUI.Style.DebuffColorLow, GUI.Style.DebuffColorMedium, GUI.Style.DebuffColorHigh); + return ToolBox.GradientLerp(affliction.Strength / prefab.MaxStrength, GUIColorSettings.DebuffColorLow, GUIColorSettings.DebuffColorMedium, GUIColorSettings.DebuffColorHigh); } } else @@ -1187,8 +1185,7 @@ namespace Barotrauma Dictionary treatmentSuitability = new Dictionary(); GetSuitableTreatments(treatmentSuitability, normalize: true, randomization: randomVariance); - //Affliction mostSevereAffliction = afflictions.FirstOrDefault(a => !a.Prefab.IsBuff && !afflictions.Any(a2 => !a2.Prefab.IsBuff && a2.Strength > a.Strength)) ?? afflictions.FirstOrDefault(); - Affliction mostSevereAffliction = SortAfflictionsBySeverity(afflictions).FirstOrDefault(); + Affliction mostSevereAffliction = afflictions.FirstOrDefault(a => !a.Prefab.IsBuff && !afflictions.Any(a2 => !a2.Prefab.IsBuff && a2.Strength > a.Strength)) ?? afflictions.FirstOrDefault(); GUIButton buttonToSelect = null; foreach (Affliction affliction in afflictions) @@ -1814,8 +1811,8 @@ namespace Barotrauma float iconScale = 0.25f * scale; Vector2 iconPos = highlightArea.Center.ToVector2(); - //Affliction mostSevereAffliction = thisAfflictions.FirstOrDefault(a => !a.Prefab.IsBuff && !thisAfflictions.Any(a2 => !a2.Prefab.IsBuff && a2.Strength > a.Strength)) ?? thisAfflictions.FirstOrDefault(); - Affliction mostSevereAffliction = SortAfflictionsBySeverity(thisAfflictions).FirstOrDefault(); + Affliction mostSevereAffliction = thisAfflictions.FirstOrDefault(a => !a.Prefab.IsBuff && !thisAfflictions.Any(a2 => !a2.Prefab.IsBuff && a2.Strength > a.Strength)) ?? thisAfflictions.FirstOrDefault(); + if (mostSevereAffliction != null) { DrawLimbAfflictionIcon(spriteBatch, mostSevereAffliction, iconScale, ref iconPos); } if (thisAfflictions.Count() > 1) diff --git a/Barotrauma/BarotraumaClient/ClientSource/DebugConsole.cs b/Barotrauma/BarotraumaClient/ClientSource/DebugConsole.cs index 723afcee0..70b15fe92 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/DebugConsole.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/DebugConsole.cs @@ -440,7 +440,6 @@ namespace Barotrauma AssignRelayToServer("ban", false); AssignRelayToServer("banid", false); AssignRelayToServer("dumpids", false); - AssignRelayToServer("dumptofile", false); AssignRelayToServer("findentityids", false); AssignRelayToServer("campaigninfo", false); AssignRelayToServer("help", false); @@ -1058,69 +1057,23 @@ namespace Barotrauma if (args.Length != 2 || Screen.Selected != GameMain.SubEditorScreen) { return; } foreach (MapEntity me in MapEntity.SelectedList) { - bool propertyFound = false; - if (!(me is ISerializableEntity serializableEntity)) { continue; } - if (serializableEntity.SerializableProperties == null) { continue; } - - if (serializableEntity.SerializableProperties.TryGetValue(args[0].ToLowerInvariant(), out SerializableProperty property)) + if (me is ISerializableEntity serializableEntity) { - propertyFound = true; - object prevValue = property.GetValue(me); - if (property.TrySetValue(me, args[1])) + if (serializableEntity.SerializableProperties == null) { - NewMessage($"Changed the value \"{args[0]}\" from {(prevValue?.ToString() ?? null)} to {args[1]} on entity \"{me.ToString()}\".", Color.LightGreen); + continue; } - else + if (!serializableEntity.SerializableProperties.TryGetValue(args[0].ToLowerInvariant(), out SerializableProperty property)) { - NewMessage($"Failed to set the value of \"{args[0]}\" to \"{args[1]}\" on the entity \"{me.ToString()}\".", Color.Orange); + NewMessage("Property \"" + args[0] + "\" not found in the entity \"" + me.ToString() + "\".", Color.Orange); + continue; } - } - if (me is Item item) - { - foreach (ItemComponent ic in item.Components) + if (!property.TrySetValue(me, args[1])) { - ic.SerializableProperties.TryGetValue(args[0].ToLowerInvariant(), out SerializableProperty componentProperty); - if (componentProperty == null) { continue; } - propertyFound = true; - object prevValue = componentProperty.GetValue(ic); - if (componentProperty.TrySetValue(ic, args[1])) - { - NewMessage($"Changed the value \"{args[0]}\" from {prevValue} to {args[1]} on item \"{me.ToString()}\", component \"{ic.GetType().Name}\".", Color.LightGreen); - } - else - { - NewMessage($"Failed to set the value of \"{args[0]}\" to \"{args[1]}\" on the item \"{me.ToString()}\", component \"{ic.GetType().Name}\".", Color.Orange); - } - } - } - if (!propertyFound) - { - NewMessage($"Property \"{args[0]}\" not found in the entity \"{me.ToString()}\".", Color.Orange); - } - } - }, - () => - { - List propertyList = new List(); - foreach (MapEntity me in MapEntity.SelectedList) - { - if (!(me is ISerializableEntity serializableEntity)) { continue; } - if (serializableEntity.SerializableProperties == null) { continue; } - propertyList.AddRange(serializableEntity.SerializableProperties.Select(p => p.Key)); - if (me is Item item) - { - foreach (ItemComponent ic in item.Components) - { - propertyList.AddRange(ic.SerializableProperties.Select(p => p.Key)); + NewMessage("Failed to set the value of \"" + args[0] + "\" to \"" + args[1] + "\" on the entity \"" + me.ToString() + "\".", Color.Orange); } } } - - return new string[][] - { - propertyList.Distinct().ToArray(), - new string[0] - }; })); commands.Add(new Command("checkmissingloca", "", (string[] args) => @@ -2360,7 +2313,7 @@ namespace Barotrauma switch (firstArg) { case "name": - var sprites = Sprite.LoadedSprites.Where(s => s.Name != null && s.Name.Equals(secondArg, StringComparison.OrdinalIgnoreCase)); + var sprites = Sprite.LoadedSprites.Where(s => s.Name?.ToLowerInvariant() == secondArg.ToLowerInvariant()); if (sprites.Any()) { foreach (var s in sprites) @@ -2376,7 +2329,7 @@ namespace Barotrauma } case "identifier": case "id": - sprites = Sprite.LoadedSprites.Where(s => s.EntityID != null && s.EntityID.Equals(secondArg, StringComparison.OrdinalIgnoreCase)); + sprites = Sprite.LoadedSprites.Where(s => s.EntityID?.ToLowerInvariant() == secondArg.ToLowerInvariant()); if (sprites.Any()) { foreach (var s in sprites) diff --git a/Barotrauma/BarotraumaClient/ClientSource/Events/Missions/MissionPrefab.cs b/Barotrauma/BarotraumaClient/ClientSource/Events/Missions/MissionPrefab.cs index 878c814b7..58d480b8a 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Events/Missions/MissionPrefab.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Events/Missions/MissionPrefab.cs @@ -24,7 +24,7 @@ namespace Barotrauma { foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("icon", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "icon") { continue; } Icon = new Sprite(subElement); IconColor = subElement.GetAttributeColor("color", Color.White); } diff --git a/Barotrauma/BarotraumaClient/ClientSource/GUI/ChatBox.cs b/Barotrauma/BarotraumaClient/ClientSource/GUI/ChatBox.cs index ce3fb6ce4..d3e45860b 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GUI/ChatBox.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GUI/ChatBox.cs @@ -252,29 +252,21 @@ namespace Barotrauma Visible = false, CanBeFocused = false }; - var content = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), popupMsg.RectTransform, Anchor.Center)); - Vector2 senderTextSize = Vector2.Zero; - if (!string.IsNullOrEmpty(senderName)) - { - var senderText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), - senderName, textColor: senderColor, style: null, font: GUI.SmallFont) - { - CanBeFocused = false - }; - senderTextSize = senderText.Font.MeasureString(senderText.WrappedText); - senderText.RectTransform.MinSize = new Point(0, senderText.Rect.Height); - } - var msgPopupText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), - displayedText, textColor: message.Color, font: GUI.SmallFont, textAlignment: Alignment.BottomLeft, style: null, wrap: true) + var senderText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), popupMsg.RectTransform, Anchor.TopRight), + senderName, textColor: senderColor, font: GUI.SmallFont, textAlignment: Alignment.TopRight) { CanBeFocused = false }; - msgPopupText.RectTransform.MinSize = new Point(0, msgPopupText.Rect.Height); - Vector2 msgSize = msgPopupText.Font.MeasureString(msgPopupText.WrappedText); - int textWidth = (int)Math.Max(msgSize.X + msgPopupText.Padding.X + msgPopupText.Padding.Z, senderTextSize.X) + 10; - popupMsg.RectTransform.Resize(new Point((int)(textWidth / content.RectTransform.RelativeSize.X) , (int)((senderTextSize.Y + msgSize.Y) / content.RectTransform.RelativeSize.Y)), resizeChildren: true); - popupMsg.RectTransform.IsFixedSize = true; - content.Recalculate(); + var msgPopupText = new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.0f), popupMsg.RectTransform, Anchor.TopRight) + { AbsoluteOffset = new Point(0, senderText.Rect.Height) }, + displayedText, textColor: message.Color, font: GUI.SmallFont, textAlignment: Alignment.TopRight, style: null, wrap: true) + { + CanBeFocused = false + }; + int textWidth = (int)Math.Max( + msgPopupText.Font.MeasureString(msgPopupText.WrappedText).X, + senderText.Font.MeasureString(senderText.WrappedText).X); + popupMsg.RectTransform.Resize(new Point(textWidth + 20, msgPopupText.Rect.Bottom - senderText.Rect.Y), resizeChildren: false); popupMessages.Enqueue(popupMsg); } diff --git a/Barotrauma/BarotraumaClient/ClientSource/GUI/ComponentStyle.cs b/Barotrauma/BarotraumaClient/ClientSource/GUI/ComponentStyle.cs index 106072e13..ec39f671c 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GUI/ComponentStyle.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GUI/ComponentStyle.cs @@ -159,7 +159,7 @@ namespace Barotrauma Point size = new Point(0, 0); foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("size", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "size") { continue; } Point maxResolution = subElement.GetAttributePoint("maxresolution", new Point(int.MaxValue, int.MaxValue)); if (GameMain.GraphicsWidth <= maxResolution.X && GameMain.GraphicsHeight <= maxResolution.Y) { diff --git a/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIColorSettings.cs b/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIColorSettings.cs new file mode 100644 index 000000000..7b402000f --- /dev/null +++ b/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIColorSettings.cs @@ -0,0 +1,24 @@ +using Microsoft.Xna.Framework; + +namespace Barotrauma +{ + public class GUIColorSettings + { + // Inventory + public static Color EquipmentSlotIconColor = new Color(99, 70, 64); + + // Health HUD + public static Color BuffColorLow = Color.LightGreen; + public static Color BuffColorMedium = Color.Green; + public static Color BuffColorHigh = Color.DarkGreen; + + public static Color DebuffColorLow = Color.DarkSalmon; + public static Color DebuffColorMedium = Color.Red; + public static Color DebuffColorHigh = Color.DarkRed; + + public static Color HealthBarColorLow = Color.Red; + public static Color HealthBarColorMedium = Color.Orange; + public static Color HealthBarColorHigh = new Color(78, 114, 88); + + } +} diff --git a/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIComponent.cs b/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIComponent.cs index 82bbf672b..77bb51dc1 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIComponent.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIComponent.cs @@ -801,7 +801,8 @@ namespace Barotrauma foreach (XElement subElement in element.Elements()) { - if (subElement.Name.ToString().Equals("conditional", StringComparison.OrdinalIgnoreCase) && !CheckConditional(subElement)) + if (subElement.Name.ToString().ToLowerInvariant() == "conditional" && + !CheckConditional(subElement)) { return null; } @@ -850,7 +851,7 @@ namespace Barotrauma { foreach (XElement subElement in element.Elements()) { - if (subElement.Name.ToString().Equals("conditional", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() == "conditional") { continue; } FromXML(subElement, component is GUIListBox listBox ? listBox.Content.RectTransform : component.RectTransform); } @@ -1018,7 +1019,7 @@ namespace Barotrauma private static GUIFrame LoadGUIFrame(XElement element, RectTransform parent) { - string style = element.GetAttributeString("style", element.Name.ToString().Equals("spacing", StringComparison.OrdinalIgnoreCase) ? null : ""); + string style = element.GetAttributeString("style", element.Name.ToString().ToLowerInvariant() == "spacing" ? null : ""); if (style == "null") { style = null; } return new GUIFrame(RectTransform.Load(element, parent), style: style); } diff --git a/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIStyle.cs b/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIStyle.cs index 01e36a545..96191e3be 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIStyle.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GUI/GUIStyle.cs @@ -59,36 +59,11 @@ namespace Barotrauma /// public Color Blue { get; private set; } = Color.Blue; - public Color ColorInventoryEmpty { get; private set; } = Color.Red; - public Color ColorInventoryHalf { get; private set; } = Color.Orange; - public Color ColorInventoryFull { get; private set; } = Color.LightGreen; - public Color ColorInventoryBackground { get; private set; } = Color.Gray; - public Color TextColor { get; private set; } = Color.White * 0.8f; public Color TextColorBright { get; private set; } = Color.White * 0.9f; public Color TextColorDark { get; private set; } = Color.Black * 0.9f; public Color TextColorDim { get; private set; } = Color.White * 0.6f; - // Inventory - public Color EquipmentSlotIconColor { get; private set; } = new Color(99, 70, 64); - - // Health HUD - public Color BuffColorLow { get; private set; } = Color.LightGreen; - public Color BuffColorMedium { get; private set; } = Color.Green; - public Color BuffColorHigh { get; private set; } = Color.DarkGreen; - - public Color DebuffColorLow { get; private set; } = Color.DarkSalmon; - public Color DebuffColorMedium { get; private set; } = Color.Red; - public Color DebuffColorHigh { get; private set; } = Color.DarkRed; - - public Color HealthBarColorLow { get; private set; } = Color.Red; - public Color HealthBarColorMedium { get; private set; } = Color.Orange; - public Color HealthBarColorHigh { get; private set; } = new Color(78, 114, 88); - - public Color EquipmentIndicatorNotEquipped { get; private set; } = Color.Gray; - public Color EquipmentIndicatorEquipped { get; private set; } = new Color(105, 202, 125); - public Color EquipmentIndicatorRunningOut { get; private set; } = new Color(202, 105, 105); - public static Point ItemFrameMargin => new Point(50, 56).Multiply(GUI.SlicedSpriteScale); public static Point ItemFrameOffset => new Point(0, 3).Multiply(GUI.SlicedSpriteScale); @@ -128,22 +103,10 @@ namespace Barotrauma case "blue": Blue = subElement.GetAttributeColor("color", Blue); break; - case "colorinventoryempty": - ColorInventoryEmpty = subElement.GetAttributeColor("color", ColorInventoryEmpty); - break; - case "colorinventoryhalf": - ColorInventoryHalf = subElement.GetAttributeColor("color", ColorInventoryHalf); - break; - case "colorinventoryfull": - ColorInventoryFull = subElement.GetAttributeColor("color", ColorInventoryFull); - break; - case "colorinventorybackground": - ColorInventoryBackground = subElement.GetAttributeColor("color", ColorInventoryBackground); - break; case "textcolordark": TextColorDark = subElement.GetAttributeColor("color", TextColorDark); break; - case "textcolorbright": + case "TextColorBright": TextColorBright = subElement.GetAttributeColor("color", TextColorBright); break; case "textcolordim": @@ -153,45 +116,6 @@ namespace Barotrauma case "textcolor": TextColor = subElement.GetAttributeColor("color", TextColor); break; - case "equipmentsloticoncolor": - EquipmentSlotIconColor = subElement.GetAttributeColor("color", EquipmentSlotIconColor); - break; - case "buffcolorlow": - BuffColorLow = subElement.GetAttributeColor("color", BuffColorLow); - break; - case "buffcolormedium": - BuffColorMedium = subElement.GetAttributeColor("color", BuffColorMedium); - break; - case "buffcolorhigh": - BuffColorHigh = subElement.GetAttributeColor("color", BuffColorHigh); - break; - case "debuffcolorlow": - DebuffColorLow = subElement.GetAttributeColor("color", DebuffColorLow); - break; - case "debuffcolormedium": - DebuffColorMedium = subElement.GetAttributeColor("color", DebuffColorMedium); - break; - case "debuffcolorhigh": - DebuffColorHigh = subElement.GetAttributeColor("color", DebuffColorHigh); - break; - case "healthbarcolorlow": - HealthBarColorLow = subElement.GetAttributeColor("color", HealthBarColorLow); - break; - case "healthbarcolormedium": - HealthBarColorMedium = subElement.GetAttributeColor("color", HealthBarColorMedium); - break; - case "healthbarcolorhigh": - HealthBarColorHigh = subElement.GetAttributeColor("color", HealthBarColorHigh); - break; - case "equipmentindicatornotequipped": - EquipmentIndicatorNotEquipped = subElement.GetAttributeColor("color", EquipmentIndicatorNotEquipped); - break; - case "equipmentindicatorequipped": - EquipmentIndicatorEquipped = subElement.GetAttributeColor("color", EquipmentIndicatorEquipped); - break; - case "equipmentindicatorrunningout": - EquipmentIndicatorRunningOut = subElement.GetAttributeColor("color", EquipmentIndicatorRunningOut); - break; case "uiglow": UIGlow = new UISprite(subElement); break; @@ -326,8 +250,9 @@ namespace Barotrauma //check if any of the language override fonts want to override the font size as well foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("override", StringComparison.OrdinalIgnoreCase)) { continue; } - if (GameMain.Config.Language.Equals(subElement.GetAttributeString("language", ""), StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() != "override") { continue; } + string language = subElement.GetAttributeString("language", "").ToLowerInvariant(); + if (GameMain.Config.Language.ToLowerInvariant() == language) { uint overrideFontSize = GetFontSize(subElement, 0); if (overrideFontSize > 0) { return overrideFontSize; } @@ -336,7 +261,7 @@ namespace Barotrauma foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("size", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "size") { continue; } Point maxResolution = subElement.GetAttributePoint("maxresolution", new Point(int.MaxValue, int.MaxValue)); if (GameMain.GraphicsWidth <= maxResolution.X && GameMain.GraphicsHeight <= maxResolution.Y) { @@ -350,8 +275,9 @@ namespace Barotrauma { foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("override", StringComparison.OrdinalIgnoreCase)) { continue; } - if (GameMain.Config.Language.Equals(subElement.GetAttributeString("language", ""), StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() != "override") { continue; } + string language = subElement.GetAttributeString("language", "").ToLowerInvariant(); + if (GameMain.Config.Language.ToLowerInvariant() == language) { return subElement.GetAttributeString("file", ""); } @@ -363,8 +289,9 @@ namespace Barotrauma { foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("override", StringComparison.OrdinalIgnoreCase)) { continue; } - if (GameMain.Config.Language.Equals(subElement.GetAttributeString("language", ""), StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() != "override") { continue; } + string language = subElement.GetAttributeString("language", "").ToLowerInvariant(); + if (GameMain.Config.Language.ToLowerInvariant() == language) { return subElement.GetAttributeBool("dynamicloading", false); } @@ -376,8 +303,9 @@ namespace Barotrauma { foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("override", StringComparison.OrdinalIgnoreCase)) { continue; } - if (GameMain.Config.Language.Equals(subElement.GetAttributeString("language", ""), StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() != "override") { continue; } + string language = subElement.GetAttributeString("language", "").ToLowerInvariant(); + if (GameMain.Config.Language.ToLowerInvariant() == language) { return subElement.GetAttributeBool("iscjk", false); } diff --git a/Barotrauma/BarotraumaClient/ClientSource/GUI/GUITextBlock.cs b/Barotrauma/BarotraumaClient/ClientSource/GUI/GUITextBlock.cs index 5ce433044..37fd18873 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GUI/GUITextBlock.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GUI/GUITextBlock.cs @@ -328,7 +328,11 @@ namespace Barotrauma { if (text == null) { return; } - censoredText = string.IsNullOrEmpty(text) ? "" : new string('\u2022', text.Length); + censoredText = ""; + for (int i = 0; i < text.Length; i++) + { + censoredText += "\u2022"; + } var rect = Rect; diff --git a/Barotrauma/BarotraumaClient/ClientSource/GUI/HUDLayoutSettings.cs b/Barotrauma/BarotraumaClient/ClientSource/GUI/HUDLayoutSettings.cs index 8df88614e..a67480d28 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GUI/HUDLayoutSettings.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GUI/HUDLayoutSettings.cs @@ -112,16 +112,16 @@ namespace Barotrauma //slice from the top of the screen for misc buttons (info, end round, server controls) ButtonAreaTop = new Rectangle(Padding, Padding, GameMain.GraphicsWidth - Padding * 2, (int)(50 * GUI.Scale)); - int infoAreaWidth = (int)(142 * GUI.Scale); - int infoAreaHeight = (int)(98 * GUI.Scale); - int portraitSize = (int)(infoAreaHeight * 0.95f); + int infoAreaWidth = (int)(142 * GUI.Scale * CharacterInfo.BgScale); + int infoAreaHeight = (int)(98 * GUI.Scale * CharacterInfo.BgScale); + int portraitSize = (int)(125 * GUI.Scale); BottomRightInfoArea = new Rectangle(GameMain.GraphicsWidth - Padding * 2 - infoAreaWidth, GameMain.GraphicsHeight - Padding * 2 - infoAreaHeight, infoAreaWidth, infoAreaHeight); - PortraitArea = new Rectangle(GameMain.GraphicsWidth - portraitSize, BottomRightInfoArea.Bottom - portraitSize + Padding / 2, portraitSize, portraitSize); + PortraitArea = new Rectangle(GameMain.GraphicsWidth - Padding - portraitSize, GameMain.GraphicsHeight - Padding - portraitSize, portraitSize, portraitSize); //horizontal slices at the corners of the screen for health bar and affliction icons int afflictionAreaHeight = (int)(50 * GUI.Scale); - int healthBarWidth = BottomRightInfoArea.Width + CharacterInventory.SlotSize.X + CharacterInventory.Spacing * 2 + CharacterInventory.HideButtonWidth; - int healthBarHeight = (int)(50f * GUI.Scale); + int healthBarWidth = (int)((BottomRightInfoArea.Width + CharacterInventory.SlotSize.X + CharacterInventory.Spacing) * 1.1f); + int healthBarHeight = (int)Math.Max(50f * GUI.Scale, 25f); HealthBarArea = new Rectangle(BottomRightInfoArea.X - (healthBarWidth - BottomRightInfoArea.Width) + (int)(2 * GUI.Scale), BottomRightInfoArea.Y - healthBarHeight + (int)(10 * GUI.Scale), healthBarWidth, healthBarHeight); AfflictionAreaLeft = new Rectangle(HealthBarArea.X, HealthBarArea.Y - Padding - afflictionAreaHeight, HealthBarArea.Width, afflictionAreaHeight); diff --git a/Barotrauma/BarotraumaClient/ClientSource/GameMain.cs b/Barotrauma/BarotraumaClient/ClientSource/GameMain.cs index 9c130c74e..8d86b74b2 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GameMain.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GameMain.cs @@ -66,7 +66,7 @@ namespace Barotrauma if (vanillaContent == null) { // TODO: Dynamic method for defining and finding the vanilla content package. - vanillaContent = ContentPackage.List.SingleOrDefault(cp => Path.GetFileName(cp.Path).Equals("vanilla 0.9.xml", StringComparison.OrdinalIgnoreCase)); + vanillaContent = ContentPackage.List.SingleOrDefault(cp => Path.GetFileName(cp.Path).ToLowerInvariant() == "vanilla 0.9.xml"); } return vanillaContent; } @@ -397,7 +397,7 @@ namespace Barotrauma SoundManager.SetCategoryGainMultiplier("ui", Config.SoundVolume, 0); SoundManager.SetCategoryGainMultiplier("waterambience", Config.SoundVolume, 0); SoundManager.SetCategoryGainMultiplier("music", Config.MusicVolume, 0); - SoundManager.SetCategoryGainMultiplier("voip", Config.VoiceChatVolume, 0); + SoundManager.SetCategoryGainMultiplier("voip", Config.VoiceChatVolume * 20.0f, 0); if (Config.EnableSplashScreen && !ConsoleArguments.Contains("-skipintro")) { @@ -421,27 +421,17 @@ namespace Barotrauma GUI.Init(Window, Config.SelectedContentPackages, GraphicsDevice); DebugConsole.Init(); - if (Config.AutoUpdateWorkshopItems) + CrossThread.RequestExecutionOnMainThread(() => { - bool waitingForWorkshopUpdates = true; - bool result = false; - TaskPool.Add(SteamManager.AutoUpdateWorkshopItems(), (task) => + if (Config.AutoUpdateWorkshopItems) { - result = task.Result; - waitingForWorkshopUpdates = false; - }); - - while (waitingForWorkshopUpdates) { yield return CoroutineStatus.Running; } - - if (result) - { - CrossThread.RequestExecutionOnMainThread(() => + if (SteamManager.AutoUpdateWorkshopItems()) { ContentPackage.LoadAll(); Config.ReloadContentPackages(); - }); + } } - } + }); if (SelectedPackages.None()) @@ -1096,10 +1086,7 @@ namespace Barotrauma UserData = "https://steamcommunity.com/app/602960/discussions/1/", OnClicked = (btn, userdata) => { - if (!SteamManager.OverlayCustomURL(userdata as string)) - { - ShowOpenUrlInWebBrowserPrompt(userdata as string); - } + SteamManager.OverlayCustomURL(userdata as string); msgBox.Close(); return true; } diff --git a/Barotrauma/BarotraumaClient/ClientSource/GameSession/CrewManager.cs b/Barotrauma/BarotraumaClient/ClientSource/GameSession/CrewManager.cs index c63edc24b..9e87390d5 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GameSession/CrewManager.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GameSession/CrewManager.cs @@ -51,6 +51,7 @@ namespace Barotrauma { if (toggleCrewListOpen == value) { return; } toggleCrewListOpen = GameMain.Config.CrewMenuOpen = value; + toggleCrewButton.Children.ForEach(c => c.SpriteEffects = toggleCrewListOpen ? SpriteEffects.None : SpriteEffects.FlipHorizontally); } } @@ -69,13 +70,13 @@ namespace Barotrauma { foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("character", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "character") continue; var characterInfo = new CharacterInfo(subElement); characterInfos.Add(characterInfo); foreach (XElement invElement in subElement.Elements()) { - if (!invElement.Name.ToString().Equals("inventory", StringComparison.OrdinalIgnoreCase)) { continue; } + if (invElement.Name.ToString().ToLowerInvariant() != "inventory") continue; characterInfo.InventoryData = invElement; break; } @@ -97,13 +98,11 @@ namespace Barotrauma CanBeFocused = false }; - var commandButtonHeight = (int)(GUI.Scale * 40); - var buttonSize = new Point((int)(182f / 99f * commandButtonHeight), commandButtonHeight); - var crewListToggleButtonHeight = (int)(64f * buttonSize.X / 175f); + var buttonHeight = (int)(GUI.Scale * 40); crewArea = new GUIFrame( new RectTransform( - new Point(crewAreaWithButtons.Rect.Width, crewAreaWithButtons.Rect.Height - commandButtonHeight - crewListToggleButtonHeight - 2 * HUDLayoutSettings.Padding), + new Point(crewAreaWithButtons.Rect.Width, crewAreaWithButtons.Rect.Height - (int)(1.5f * buttonHeight) - 2 * HUDLayoutSettings.Padding), crewAreaWithButtons.RectTransform, Anchor.BottomLeft), style: null, @@ -112,6 +111,7 @@ namespace Barotrauma CanBeFocused = false }; + var buttonSize = new Point((int)(182.0f / 99.0f * buttonHeight), buttonHeight); commandButton = new GUIButton( new RectTransform(buttonSize, parent: crewAreaWithButtons.RectTransform), style: "CommandButton") @@ -139,13 +139,14 @@ namespace Barotrauma Spacing = (int)(GUI.Scale * 10) }; - buttonSize.Y = crewListToggleButtonHeight; toggleCrewButton = new GUIButton( - new RectTransform(buttonSize, parent: crewAreaWithButtons.RectTransform) + new RectTransform( + new Point(buttonSize.X, (int)(0.5f * buttonHeight)), + parent: crewAreaWithButtons.RectTransform) { - AbsoluteOffset = new Point(0, commandButtonHeight + HUDLayoutSettings.Padding) + AbsoluteOffset = new Point(0, buttonHeight + HUDLayoutSettings.Padding) }, - style: "CrewListToggleButton") + style: "UIToggleButton") { OnClicked = (GUIButton btn, object userdata) => { @@ -211,7 +212,7 @@ namespace Barotrauma var chatBox = ChatBox ?? GameMain.Client?.ChatBox; if (chatBox != null) { - chatBox.ToggleButton = new GUIButton(new RectTransform(new Point((int)(182f * GUI.Scale * 0.4f), (int)(99f * GUI.Scale * 0.4f)), chatBox.GUIFrame.Parent.RectTransform), style: "ChatToggleButton"); + chatBox.ToggleButton = new GUIButton(new RectTransform(new Point((int)(182f * GUI.Scale * 0.4f), (int)(99f * GUI.Scale * 0.4f)), guiFrame.RectTransform), style: "ChatToggleButton"); chatBox.ToggleButton.RectTransform.AbsoluteOffset = new Point(0, HUDLayoutSettings.ChatBoxArea.Height - chatBox.ToggleButton.Rect.Height); chatBox.ToggleButton.OnClicked += (GUIButton btn, object userdata) => { @@ -329,7 +330,17 @@ namespace Barotrauma } AddCharacterToCrewList(character); - DisplayCharacterOrder(character, character.CurrentOrder, character.CurrentOrderOption); + + if (character is AICharacter) + { + var ai = character.AIController as HumanAIController; + if (ai == null) + { + DebugConsole.ThrowError("Error in crewmanager - attempted to give orders to a character with no HumanAIController"); + return; + } + character.SetOrder(ai.CurrentOrder, "", null, false); + } } public void AddCharacterInfo(CharacterInfo characterInfo) @@ -777,11 +788,11 @@ namespace Barotrauma characterFrame.SetAsFirstChild(); } - private void DisplayPreviousCharacterOrder(Character character, GUILayoutGroup characterComponent, OrderInfo orderInfo) + private void DisplayPreviousCharacterOrder(Character character, GUILayoutGroup characterComponent, OrderInfo currentOrderInfo) { - if (orderInfo.Order == null || orderInfo.Order.Identifier == dismissedOrderPrefab.Identifier) { return; } + if (currentOrderInfo.Order == null || currentOrderInfo.Order.Identifier == dismissedOrderPrefab.Identifier) { return; } - var previousOrderInfo = new OrderInfo(orderInfo); + var previousOrderInfo = new OrderInfo(currentOrderInfo); var prevOrderFrame = new GUIButton( new RectTransform( characterComponent.GetChildByUserData("job").RectTransform.RelativeSize, @@ -824,12 +835,12 @@ namespace Barotrauma private GUIComponent GetCurrentOrderComponent(GUILayoutGroup characterComponent) { - return characterComponent?.FindChild(c => c?.UserData is OrderInfo orderInfo && orderInfo.ComponentIdentifier == "currentorder"); + return characterComponent.FindChild(c => c.UserData is OrderInfo orderInfo && orderInfo.ComponentIdentifier == "currentorder"); } private GUIComponent GetPreviousOrderComponent(GUILayoutGroup characterComponent) { - return characterComponent?.FindChild(c => c?.UserData is OrderInfo orderInfo && orderInfo.ComponentIdentifier == "previousorder"); + return characterComponent.FindChild(c => c.UserData is OrderInfo orderInfo && orderInfo.ComponentIdentifier == "previousorder"); } private struct OrderInfo @@ -899,11 +910,7 @@ namespace Barotrauma { if (!(c.UserData is Character character) || character.IsDead || character.Removed) { continue; } AddCharacter(character); - if (GetPreviousOrderComponent(c.GetChild())?.UserData is OrderInfo prevInfo && - crewList.Content.Children.FirstOrDefault(c => c?.UserData == character)?.GetChild() is GUILayoutGroup newLayoutGroup) - { - DisplayPreviousCharacterOrder(character, newLayoutGroup, prevInfo); - } + DisplayCharacterOrder(character, character.CurrentOrder, (character.AIController as HumanAIController)?.CurrentOrderOption); } } @@ -1286,21 +1293,13 @@ namespace Barotrauma { get { -#if DEBUG - return Character.Controlled == null || Character.Controlled.Info != null && Character.Controlled.SpeechImpediment < 100.0f; -#else return Character.Controlled != null && Character.Controlled.SpeechImpediment < 100.0f; -#endif } } private bool CanSomeoneHearCharacter() { -#if DEBUG - return true; -#else return Character.Controlled != null && characters.Any(c => c != Character.Controlled && c.CanHearCharacter(Character.Controlled)); -#endif } private void CreateCommandUI(Character characterContext = null) @@ -1506,7 +1505,17 @@ namespace Barotrauma shortcutCenterNode = null; } CreateNodes(userData); - CreateReturnNodeHotkey(); + if (returnNode != null && returnNode.Visible) + { + var hotkey = optionNodes.Count + 1; + if (expandNode != null && expandNode.Visible) { hotkey += 1; } + CreateHotkeyIcon(returnNode.RectTransform, hotkey % 10, true); + returnNodeHotkey = Keys.D0 + hotkey % 10; + } + else + { + returnNodeHotkey = Keys.None; + } return true; } @@ -1530,20 +1539,10 @@ namespace Barotrauma returnNode = null; } CreateNodes(userData); - CreateReturnNodeHotkey(); - return true; - } - - private void CreateReturnNodeHotkey() - { if (returnNode != null && returnNode.Visible) { - var hotkey = 1; - if (targetFrame == null || !targetFrame.Visible) - { - hotkey = optionNodes.Count + 1; - if (expandNode != null && expandNode.Visible) { hotkey += 1; } - } + var hotkey = optionNodes.Count + 1; + if (expandNode != null && expandNode.Visible) { hotkey += 1; } CreateHotkeyIcon(returnNode.RectTransform, hotkey % 10, true); returnNodeHotkey = Keys.D0 + hotkey % 10; } @@ -1551,6 +1550,7 @@ namespace Barotrauma { returnNodeHotkey = Keys.None; } + return true; } private void SetCenterNode(GUIButton node) @@ -2148,11 +2148,7 @@ namespace Barotrauma ToolTip = character.Info.DisplayName + " (" + character.Info.Job.Name + ")" }; -#if DEBUG - bool canHear = true; -#else bool canHear = character.CanHearCharacter(Character.Controlled); -#endif if (!canHear) { node.CanBeFocused = icon.CanBeFocused = false; @@ -2275,10 +2271,8 @@ namespace Barotrauma private Character GetBestCharacterForOrder(Order order) { -#if !DEBUG if (Character.Controlled == null) { return null; } -#endif - return characters.FindAll(c => Character.Controlled == null || (c != Character.Controlled && c.TeamID == Character.Controlled.TeamID)) + return characters.FindAll(c => c != Character.Controlled && c.TeamID == Character.Controlled.TeamID) .OrderByDescending(c => c.CurrentOrder == null || c.CurrentOrder.Identifier == dismissedOrderPrefab.Identifier) .ThenByDescending(c => order.HasAppropriateJob(c)) .ThenBy(c => c.CurrentOrder?.Weight) @@ -2287,18 +2281,16 @@ namespace Barotrauma private List GetCharactersSortedForOrder(Order order) { -#if !DEBUG if (Character.Controlled == null) { return new List(); } -#endif if (order.Identifier == "follow") { - return characters.FindAll(c => Character.Controlled == null || (c != Character.Controlled && c.TeamID == Character.Controlled.TeamID)) + return characters.FindAll(c => c != Character.Controlled && c.TeamID == Character.Controlled.TeamID) .OrderByDescending(c => c.CurrentOrder == null || c.CurrentOrder.Identifier == dismissedOrderPrefab.Identifier) .ToList(); } else { - return characters.FindAll(c => Character.Controlled == null || c.TeamID == Character.Controlled.TeamID) + return characters.FindAll(c => c.TeamID == Character.Controlled.TeamID) .OrderByDescending(c => c.CurrentOrder == null || c.CurrentOrder.Identifier == dismissedOrderPrefab.Identifier) .ThenByDescending(c => order.HasAppropriateJob(c)) .ThenBy(c => c.CurrentOrder?.Weight) diff --git a/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameModes/SinglePlayerCampaign.cs b/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameModes/SinglePlayerCampaign.cs index 06dca83df..833b5693b 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameModes/SinglePlayerCampaign.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameModes/SinglePlayerCampaign.cs @@ -91,7 +91,7 @@ namespace Barotrauma if (Character.Controlled.Submarine != outpost) { return null; } //if there's a sub docked to the outpost, we can leave the level - if (outpost.DockedTo.Any()) + if (outpost.DockedTo.Count > 0) { var dockedSub = outpost.DockedTo.FirstOrDefault(); return dockedSub.DockedTo.Contains(Submarine.MainSub) ? Submarine.MainSub : dockedSub; diff --git a/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameModes/Tutorials/CaptainTutorial.cs b/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameModes/Tutorials/CaptainTutorial.cs index 89c5fbf6c..711b190ac 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameModes/Tutorials/CaptainTutorial.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameModes/Tutorials/CaptainTutorial.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using System.Linq; using System.Xml.Linq; using Barotrauma.Items.Components; using Barotrauma.Networking; @@ -222,7 +221,7 @@ namespace Barotrauma.Tutorials { //captain_navConsoleCustomInterface.HighlightElement(0, uiHighlightColor, duration: 1.0f, pulsateAmount: 0.0f); yield return new WaitForSeconds(1.0f, false); - } while (Submarine.MainSub.DockedTo.Any()); + } while (Submarine.MainSub.DockedTo.Count > 0); RemoveCompletedObjective(segments[4]); yield return new WaitForSeconds(2f, false); TriggerTutorialSegment(5); // Navigate to destination @@ -246,7 +245,7 @@ namespace Barotrauma.Tutorials { //captain_navConsoleCustomInterface.HighlightElement(0, uiHighlightColor, duration: 1.0f, pulsateAmount: 0.0f); yield return new WaitForSeconds(1.0f, false); - } while (!Submarine.MainSub.AtEndPosition || Submarine.MainSub.DockedTo.Any()); + } while (!Submarine.MainSub.AtEndPosition || Submarine.MainSub.DockedTo.Count == 0); RemoveCompletedObjective(segments[6]); yield return new WaitForSeconds(3f, false); GameMain.GameSession?.CrewManager.AddSinglePlayerChatMessage(radioSpeakerName, TextManager.GetWithVariable("Captain.Radio.Complete", "[OUTPOSTNAME]", GameMain.GameSession.EndLocation.Name), ChatMessageType.Radio, null); diff --git a/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameSession.cs b/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameSession.cs index 903f55d0f..aab3afeef 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameSession.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GameSession/GameSession.cs @@ -13,7 +13,6 @@ namespace Barotrauma private GUIFrame infoFrameContent; public RoundSummary RoundSummary { get; private set; } - public static bool IsInfoFrameOpen => GameMain.GameSession?.infoFrame != null; private bool ToggleInfoFrame() { diff --git a/Barotrauma/BarotraumaClient/ClientSource/GameSettings.cs b/Barotrauma/BarotraumaClient/ClientSource/GameSettings.cs index 7344da554..8c16da963 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/GameSettings.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/GameSettings.cs @@ -1182,7 +1182,7 @@ namespace Barotrauma { RelativeOffset = new Vector2(0.02f, 0.02f) }) { RelativeSpacing = 0.01f }; - var automaticQuickStartTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, debugTickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), "Automatic quickstart enabled", style: "GUITickBox"); + var automaticQuickStartTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, debugTickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), "Enable automatic quickstart", style: "GUITickBox"); automaticQuickStartTickBox.Selected = AutomaticQuickStartEnabled; automaticQuickStartTickBox.ToolTip = "Will the game automatically move on to Quickstart when the game is launched"; automaticQuickStartTickBox.OnSelected = (tickBox) => @@ -1192,7 +1192,7 @@ namespace Barotrauma return true; }; - var showSplashScreenTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, debugTickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), "Splash screen enabled", style: "GUITickBox"); + var showSplashScreenTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, debugTickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), "Show splash screen", style: "GUITickBox"); showSplashScreenTickBox.Selected = EnableSplashScreen; showSplashScreenTickBox.ToolTip = "Are the splash screens shown when the game is launched"; showSplashScreenTickBox.OnSelected = (tickBox) => @@ -1202,7 +1202,7 @@ namespace Barotrauma return true; }; - var verboseLoggingTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, debugTickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), "Verbose logging enabled", style: "GUITickBox"); + var verboseLoggingTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, debugTickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), "Enable verbose logging", style: "GUITickBox"); verboseLoggingTickBox.Selected = VerboseLogging; verboseLoggingTickBox.ToolTip = "Should verbose logging be used"; verboseLoggingTickBox.OnSelected = (tickBox) => @@ -1211,16 +1211,6 @@ namespace Barotrauma UnsavedSettings = true; return true; }; - - var textManagerDebugModeTickBox = new GUITickBox(new RectTransform(tickBoxScale / 0.18f, debugTickBoxes.RectTransform, scaleBasis: ScaleBasis.BothHeight), "TextManager debug mode enabled", style: "GUITickBox"); - textManagerDebugModeTickBox.Selected = TextManagerDebugModeEnabled; - textManagerDebugModeTickBox.ToolTip = "Does the TextManager return the text tags for debug purposes?"; - textManagerDebugModeTickBox.OnSelected = (tickBox) => - { - TextManagerDebugModeEnabled = tickBox.Selected; - UnsavedSettings = true; - return true; - }; #endif UnsavedSettings = false; // Reset unsaved settings to false once the UI has been created @@ -1289,7 +1279,7 @@ namespace Barotrauma string[] prefixes = { "OpenAL Soft on " }; foreach (string prefix in prefixes) { - if (name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + if (name.StartsWith(prefix, StringComparison.InvariantCulture)) { return name.Remove(0, prefix.Length); } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Items/CharacterInventory.cs b/Barotrauma/BarotraumaClient/ClientSource/Items/CharacterInventory.cs index 42de38bdd..a910bbb99 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Items/CharacterInventory.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Items/CharacterInventory.cs @@ -43,7 +43,6 @@ namespace Barotrauma public Vector2[] SlotPositions; public static Point SlotSize; public static int Spacing; - public static int HideButtonWidth; private Layout layout; public Layout CurrentLayout @@ -72,44 +71,22 @@ namespace Barotrauma { get { return personalSlotArea; } } - - private GUIImage[] indicators = new GUIImage[5]; - private int[] indicatorIndexes = new int[5]; - private Vector2 indicatorSpriteSize; - private GUILayoutGroup indicatorGroup; - + partial void InitProjSpecific(XElement element) { Hidden = true; - hideButton = new GUIButton(new RectTransform(new Point((int)(31f * (HUDLayoutSettings.BottomRightInfoArea.Height / 100f)), HUDLayoutSettings.BottomRightInfoArea.Height), GUI.Canvas) + hideButton = new GUIButton(new RectTransform(new Point((int)(30 * GUI.Scale), (int)(60 * GUI.Scale)), GUI.Canvas) { AbsoluteOffset = HUDLayoutSettings.CrewArea.Location }, - "", style: "EquipmentToggleButton"); - - indicatorGroup = new GUILayoutGroup(new RectTransform(Point.Zero, hideButton.RectTransform)) { IsHorizontal = false }; - indicatorGroup.ChildAnchor = Anchor.TopCenter; - indicatorSpriteSize = GUI.Style.GetComponentStyle("EquipmentIndicatorDivingSuit").Sprites[GUIComponent.ComponentState.None][0].Sprite.size; - - indicators[0] = new GUIImage(new RectTransform(Point.Zero, indicatorGroup.RectTransform), "EquipmentIndicatorDivingSuit"); - indicators[1] = new GUIImage(new RectTransform(Point.Zero, indicatorGroup.RectTransform), "EquipmentIndicatorID"); - indicators[2] = new GUIImage(new RectTransform(Point.Zero, indicatorGroup.RectTransform), "EquipmentIndicatorOutfit"); - indicators[3] = new GUIImage(new RectTransform(Point.Zero, indicatorGroup.RectTransform), "EquipmentIndicatorHeadwear"); - indicators[4] = new GUIImage(new RectTransform(Point.Zero, indicatorGroup.RectTransform), "EquipmentIndicatorHeadphones"); - - indicatorIndexes[0] = FindLimbSlot(InvSlotType.OuterClothes); - indicatorIndexes[1] = FindLimbSlot(InvSlotType.Card); - indicatorIndexes[2] = FindLimbSlot(InvSlotType.InnerClothes); - indicatorIndexes[3] = FindLimbSlot(InvSlotType.Head); - indicatorIndexes[4] = FindLimbSlot(InvSlotType.Headset); - - for (int i = 0; i < indicators.Length; i++) - { - indicators[i].CanBeFocused = false; - } - + "", style: "UIToggleButton"); + hideButton.Children.ForEach(c => c.SpriteEffects = SpriteEffects.FlipHorizontally); hideButton.OnClicked += (GUIButton btn, object userdata) => { hidePersonalSlots = !hidePersonalSlots; + foreach (GUIComponent child in btn.Children) + { + child.SpriteEffects = hidePersonalSlots ? SpriteEffects.None : SpriteEffects.FlipHorizontally; + } return true; }; @@ -268,26 +245,6 @@ namespace Barotrauma return false; } - - private void SetIndicatorSizes() - { - indicatorGroup.RectTransform.AbsoluteOffset = new Point((int)Math.Round(4 * GUI.Scale), (int)Math.Round(7 * GUI.Scale)); - indicatorGroup.RectTransform.NonScaledSize = new Point(hideButton.Rect.Width - indicatorGroup.RectTransform.AbsoluteOffset.X * 2, hideButton.Rect.Height - indicatorGroup.RectTransform.AbsoluteOffset.Y * 2); - indicatorGroup.AbsoluteSpacing = (int)Math.Ceiling(2 * GUI.Scale); - - int indicatorHeight = (indicatorGroup.RectTransform.NonScaledSize.Y - indicatorGroup.AbsoluteSpacing * (indicators.Length - 1)) / indicators.Length; - int indicatorWidth = (int)(indicatorSpriteSize.X / (indicatorSpriteSize.Y / indicatorHeight)); - - if (HideButtonWidth % 2 != indicatorWidth % 2) indicatorWidth++; - - Point indicatorSize = new Point(indicatorWidth, indicatorHeight); - - for (int i = 0; i < indicators.Length; i++) - { - indicators[i].RectTransform.NonScaledSize = indicatorSize; - } - } - private void SetSlotPositions(Layout layout) { bool isFourByThree = GUI.IsFourByThree(); @@ -300,8 +257,6 @@ namespace Barotrauma Spacing = (int)(8 * UIScale); } - HideButtonWidth = (int)(31f * (HUDLayoutSettings.BottomRightInfoArea.Height / 100f)); - SlotSize = !isFourByThree ? (SlotSpriteSmall.size * UIScale).ToPoint() : (SlotSpriteSmall.size * UIScale * .925f).ToPoint(); int bottomOffset = SlotSize.Y + Spacing * 2 + ContainedIndicatorHeight; @@ -317,7 +272,8 @@ namespace Barotrauma int normalSlotCount = SlotTypes.Count(s => !PersonalSlots.HasFlag(s)); int x = GameMain.GraphicsWidth / 2 - normalSlotCount * (SlotSize.X + Spacing) / 2; - int upperX = HUDLayoutSettings.BottomRightInfoArea.X - SlotSize.X - Spacing * 4 - HideButtonWidth; + int upperX = HUDLayoutSettings.BottomRightInfoArea.X - Spacing * 2 - SlotSize.X - SlotSize.X / 2; + //int upperX = GameMain.GraphicsWidth - personalSlotCount * (slotSize.X + spacing) + (int)(11 * GUI.Scale) + spacing; //make sure the rightmost normal slot doesn't overlap with the personal slots x -= Math.Max((x + normalSlotCount * (SlotSize.X + Spacing)) - (upperX - personalSlotCount * (SlotSize.X + Spacing)), 0); @@ -344,13 +300,11 @@ namespace Barotrauma if (hideButtonSlotIndex > -1) { hideButton.RectTransform.SetPosition(Anchor.TopLeft, Pivot.TopLeft); - hideButton.RectTransform.NonScaledSize = new Point(HideButtonWidth, HUDLayoutSettings.BottomRightInfoArea.Height); + hideButton.RectTransform.NonScaledSize = new Point(SlotSize.X / 2, HUDLayoutSettings.BottomRightInfoArea.Height); hideButton.RectTransform.AbsoluteOffset = new Point( - personalSlotArea.Right + Spacing * 2, + personalSlotArea.Right + Spacing, HUDLayoutSettings.BottomRightInfoArea.Y); hideButton.Visible = true; - - SetIndicatorSizes(); } } break; @@ -503,8 +457,7 @@ namespace Barotrauma hidePersonalSlotsState = hidePersonalSlots ? Math.Min(hidePersonalSlotsState + deltaTime * 5.0f, 1.0f) : Math.Max(hidePersonalSlotsState - deltaTime * 5.0f, 0.0f); - - bool personalSlotsMoving = hidePersonalSlotsState > 0 && hidePersonalSlotsState < 1f; + for (int i = 0; i < slots.Length; i++) { if (!PersonalSlots.HasFlag(SlotTypes[i])) { continue; } @@ -513,7 +466,6 @@ namespace Barotrauma if (selectedSlot?.Slot == slots[i]) { selectedSlot = null; } highlightedSubInventorySlots.RemoveWhere(s => s.Slot == slots[i]); } - slots[i].IsMoving = personalSlotsMoving; slots[i].DrawOffset = Vector2.Lerp(Vector2.Zero, new Vector2(personalSlotArea.Width, 0.0f), hidePersonalSlotsState); } } @@ -599,8 +551,6 @@ namespace Barotrauma if (character == Character.Controlled && character.SelectedCharacter == null) // Permanently open subinventories only available when the default UI layout is in use -> not when grabbing characters { - UpdateEquipmentIndicators(); - //remove the highlighted slots of other characters' inventories when not grabbing anyone highlightedSubInventorySlots.RemoveWhere(s => s.ParentInventory != this && s.ParentInventory?.Owner is Character); @@ -701,39 +651,6 @@ namespace Barotrauma } } } - - private void UpdateEquipmentIndicators() - { - for (int i = 0; i < indicators.Length; i++) - { - Item item = Items[indicatorIndexes[i]]; - if (item != null) - { - Wearable wearable = item.GetComponent(); - if (wearable != null && wearable.DisplayContainedStatus) - { - float conditionPercentage = item.GetContainedItemConditionPercentage(); - - if (conditionPercentage != -1) - { - indicators[i].Color = ToolBox.GradientLerp(conditionPercentage, GUI.Style.EquipmentIndicatorRunningOut, GUI.Style.EquipmentIndicatorEquipped); - } - else - { - indicators[i].Color = GUI.Style.EquipmentIndicatorRunningOut; - } - } - else - { - indicators[i].Color = GUI.Style.EquipmentIndicatorEquipped; - } - } - else - { - indicators[i].Color = GUI.Style.EquipmentIndicatorNotEquipped; - } - } - } private void ShowSubInventory(SlotReference slotRef, float deltaTime, Camera cam, List hideSubInventories, bool isEquippedSubInventory) { @@ -1047,7 +964,7 @@ namespace Barotrauma if (limbSlotIcons.ContainsKey(SlotTypes[i])) { var icon = limbSlotIcons[SlotTypes[i]]; - icon.Draw(spriteBatch, slots[i].Rect.Center.ToVector2() + slots[i].DrawOffset, GUI.Style.EquipmentSlotIconColor, origin: icon.size / 2, scale: slots[i].Rect.Width / icon.size.X); + icon.Draw(spriteBatch, slots[i].Rect.Center.ToVector2() + slots[i].DrawOffset, GUIColorSettings.EquipmentSlotIconColor, origin: icon.size / 2, scale: slots[i].Rect.Width / icon.size.X); } continue; } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Fabricator.cs b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Fabricator.cs index 159bbb2a4..10240011e 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Fabricator.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Fabricator.cs @@ -140,11 +140,11 @@ namespace Barotrauma.Items.Components var inputArea = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 1f), bottomFrame.RectTransform, Anchor.BottomCenter), isHorizontal: true, childAnchor: Anchor.BottomLeft); // === INPUT SLOTS === // - inputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(0.7f, 1f), inputArea.RectTransform), style: null); + inputInventoryHolder = new GUIFrame(new RectTransform(new Vector2(0.8f, 1f), inputArea.RectTransform), style: null); new GUICustomComponent(new RectTransform(Vector2.One, inputInventoryHolder.RectTransform), DrawInputOverLay) { CanBeFocused = false }; // === ACTIVATE BUTTON === // - var buttonFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.3f, 0.8f), inputArea.RectTransform), childAnchor: Anchor.CenterRight); + var buttonFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.2f, 0.8f), inputArea.RectTransform), childAnchor: Anchor.CenterRight); activateButton = new GUIButton(new RectTransform(new Vector2(1f, 0.6f), buttonFrame.RectTransform), TextManager.Get("FabricatorCreate"), style: "DeviceButton") { @@ -154,7 +154,7 @@ namespace Barotrauma.Items.Components }; // === POWER WARNING === // inSufficientPowerWarning = new GUITextBlock(new RectTransform(Vector2.One, activateButton.RectTransform), - TextManager.Get("FabricatorNoPower"), textColor: GUI.Style.Orange, textAlignment: Alignment.Center, color: Color.Black, style: "OuterGlow", wrap: true) + TextManager.Get("FabricatorNoPower"), textColor: GUI.Style.Orange, textAlignment: Alignment.Center, color: Color.Black, style: "OuterGlow") { HoverColor = Color.Black, IgnoreLayoutGroups = true, @@ -356,8 +356,6 @@ namespace Barotrauma.Items.Components private void DrawOutputOverLay(SpriteBatch spriteBatch, GUICustomComponent overlayComponent) { overlayComponent.RectTransform.SetAsLastChild(); - - if (outputContainer.Inventory.Items.First() != null) { return; } FabricationRecipe targetItem = fabricatedItem ?? selectedItem; if (targetItem != null) diff --git a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Sonar.cs b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Sonar.cs index d1f5e4439..ffc0fc194 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Sonar.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Sonar.cs @@ -490,7 +490,7 @@ namespace Barotrauma.Items.Components disruptedDirections.Clear(); foreach (AITarget t in AITarget.List) { - if (t.SoundRange <= 0.0f || float.IsNaN(t.SoundRange) || float.IsInfinity(t.SoundRange)) { continue; } + if (t.SoundRange <= 0.0f || !t.Enabled || float.IsNaN(t.SoundRange) || float.IsInfinity(t.SoundRange)) { continue; } float distSqr = Vector2.DistanceSquared(t.WorldPosition, transducerCenter); if (distSqr > t.SoundRange * t.SoundRange * 2) { continue; } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Steering.cs b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Steering.cs index 07bd0f3d9..4254f0534 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Steering.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Machines/Steering.cs @@ -665,7 +665,7 @@ namespace Barotrauma.Items.Components if (Vector2.DistanceSquared(PlayerInput.MousePosition, steerArea.Rect.Center.ToVector2()) < steerRadius * steerRadius) { - if (PlayerInput.PrimaryMouseButtonHeld() && !CrewManager.IsCommandInterfaceOpen && !GameSession.IsInfoFrameOpen) + if (PlayerInput.PrimaryMouseButtonHeld() && !CrewManager.IsCommandInterfaceOpen) { Vector2 displaySubPos = (-sonar.DisplayOffset * sonar.Zoom) / sonar.Range * sonar.DisplayRadius * sonar.Zoom; displaySubPos.Y = -displaySubPos.Y; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Repairable.cs b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Repairable.cs index 998db3672..8caf52a49 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Repairable.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Repairable.cs @@ -236,7 +236,15 @@ namespace Barotrauma.Items.Components DeteriorateAlways = msg.ReadBoolean(); ushort currentFixerID = msg.ReadUInt16(); currentFixerAction = (FixActions)msg.ReadRangedInteger(0, 2); - CurrentFixer = currentFixerID != 0 ? Entity.FindEntityByID(currentFixerID) as Character : null; + + if (currentFixerID == 0) + { + CurrentFixer = null; + } + else + { + CurrentFixer = Entity.FindEntityByID(currentFixerID) as Character; + } } public void ClientWrite(IWriteMessage msg, object[] extraData = null) diff --git a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Signal/Wire.cs b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Signal/Wire.cs index fda7187df..7deb2705e 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Signal/Wire.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/Signal/Wire.cs @@ -72,7 +72,7 @@ namespace Barotrauma.Items.Components foreach (XElement subElement in element.Elements()) { - if (subElement.Name.ToString().Equals("wiresprite", StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() == "wiresprite") { overrideSprite = new Sprite(subElement); break; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/StatusHUD.cs b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/StatusHUD.cs index d61908320..c2371bcb7 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Items/Components/StatusHUD.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Items/Components/StatusHUD.cs @@ -142,7 +142,7 @@ namespace Barotrauma.Items.Components private void DrawCharacterInfo(SpriteBatch spriteBatch, Character target, float alpha = 1.0f) { - Vector2 hudPos = GameMain.GameScreen.Cam.WorldToScreen(target.DrawPosition); + Vector2 hudPos = GameMain.GameScreen.Cam.WorldToScreen(target.WorldPosition); hudPos += Vector2.UnitX * 50.0f; List texts = new List(); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Items/DockingPort.cs b/Barotrauma/BarotraumaClient/ClientSource/Items/DockingPort.cs index b789b4381..93249475c 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Items/DockingPort.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Items/DockingPort.cs @@ -152,7 +152,7 @@ namespace Barotrauma.Items.Components string errorMsg = "Error while reading a docking port network event (Dock method did not create a joint between the ports)." + " Submarine: " + (item.Submarine?.Name ?? "null") + ", target submarine: " + (DockingTarget.item.Submarine?.Name ?? "null"); - if (item.Submarine?.ConnectedDockingPorts.ContainsKey(DockingTarget.item.Submarine) ?? false) + if (item.Submarine?.DockedTo.Contains(DockingTarget.item.Submarine) ?? false) { errorMsg += "\nAlready docked."; } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Items/Inventory.cs b/Barotrauma/BarotraumaClient/ClientSource/Items/Inventory.cs index 370dde2e6..b7b4eb4d5 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Items/Inventory.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Items/Inventory.cs @@ -45,17 +45,12 @@ namespace Barotrauma public float QuickUseTimer; public string QuickUseButtonToolTip; - public bool IsMoving = false; - private static Rectangle offScreenRect = new Rectangle(new Point(-1000, 0), Point.Zero); public GUIComponent.ComponentState EquipButtonState; public Rectangle EquipButtonRect { get { - // Returns a point off-screen, Rectangle.Empty places buttons in the top left of the screen - if (IsMoving) return offScreenRect; - int buttonDir = Math.Sign(SubInventoryDir); float sizeY = Inventory.UnequippedIndicator.size.Y * Inventory.UIScale * Inventory.IndicatorScaleAdjustment; @@ -289,7 +284,6 @@ namespace Barotrauma } protected static HashSet highlightedSubInventorySlots = new HashSet(); - private static List subInventorySlotsToDraw = new List(); protected static SlotReference selectedSlot; @@ -1054,14 +1048,11 @@ namespace Barotrauma return hoverArea; } - public static void DrawFront(SpriteBatch spriteBatch) { - if (GUI.PauseMenuOpen || GUI.SettingsMenuOpen) { return; } + if (GUI.PauseMenuOpen || GUI.SettingsMenuOpen) return; - subInventorySlotsToDraw.Clear(); - subInventorySlotsToDraw.AddRange(highlightedSubInventorySlots); - foreach (var slot in subInventorySlotsToDraw) + foreach (var slot in highlightedSubInventorySlots) { int slotIndex = Array.IndexOf(slot.ParentInventory.slots, slot.Slot); if (slotIndex > -1 && slotIndex < slot.ParentInventory.slots.Length) @@ -1145,11 +1136,11 @@ namespace Barotrauma /*if (inventory != null && (CharacterInventory.PersonalSlots.HasFlag(type) || (inventory.isSubInventory && (inventory.Owner as Item) != null && (inventory.Owner as Item).AllowedSlots.Any(a => CharacterInventory.PersonalSlots.HasFlag(a))))) { - slotColor = slot.IsHighlighted ? GUI.Style.EquipmentSlotColor : GUI.Style.EquipmentSlotColor * 0.8f; + slotColor = slot.IsHighlighted ? GUIColorSettings.EquipmentSlotColor : GUIColorSettings.EquipmentSlotColor * 0.8f; } else { - slotColor = slot.IsHighlighted ? GUI.Style.InventorySlotColor : GUI.Style.InventorySlotColor * 0.8f; + slotColor = slot.IsHighlighted ? GUIColorSettings.InventorySlotColor : GUIColorSettings.InventorySlotColor * 0.8f; }*/ if (inventory != null && inventory.Locked) { slotColor = Color.Gray * 0.5f; } @@ -1208,15 +1199,13 @@ namespace Barotrauma dir < 0 ? rect.Bottom + HUDLayoutSettings.Padding / 2 : rect.Y - HUDLayoutSettings.Padding / 2 - ContainedIndicatorHeight, rect.Width, ContainedIndicatorHeight); containedIndicatorArea.Inflate(-4, 0); - Color backgroundColor = GUI.Style.ColorInventoryBackground; - if (itemContainer.ContainedStateIndicator?.Texture == null) { containedIndicatorArea.Inflate(0, -2); - GUI.DrawRectangle(spriteBatch, containedIndicatorArea, backgroundColor, true); + GUI.DrawRectangle(spriteBatch, containedIndicatorArea, Color.Gray * 0.9f, true); GUI.DrawRectangle(spriteBatch, new Rectangle(containedIndicatorArea.X, containedIndicatorArea.Y, (int)(containedIndicatorArea.Width * containedState), containedIndicatorArea.Height), - ToolBox.GradientLerp(containedState, GUI.Style.ColorInventoryEmpty, GUI.Style.ColorInventoryHalf, GUI.Style.ColorInventoryFull) * 0.8f, true); + ToolBox.GradientLerp(containedState, Color.Red, Color.Orange, Color.LightGreen) * 0.8f, true); GUI.DrawLine(spriteBatch, new Vector2(containedIndicatorArea.X + (int)(containedIndicatorArea.Width * containedState), containedIndicatorArea.Y), new Vector2(containedIndicatorArea.X + (int)(containedIndicatorArea.Width * containedState), containedIndicatorArea.Bottom), @@ -1235,12 +1224,12 @@ namespace Barotrauma } indicatorSprite.Draw(spriteBatch, containedIndicatorArea.Center.ToVector2(), - (inventory != null && inventory.Locked) ? backgroundColor * 0.5f : backgroundColor, + (inventory != null && inventory.Locked) ? Color.Gray * 0.5f : Color.Gray * 0.9f, origin: indicatorSprite.size / 2, rotate: 0.0f, scale: indicatorScale); - Color indicatorColor = ToolBox.GradientLerp(containedState, GUI.Style.ColorInventoryEmpty, GUI.Style.ColorInventoryHalf, GUI.Style.ColorInventoryFull); + Color indicatorColor = ToolBox.GradientLerp(containedState, Color.Red, Color.Orange, Color.LightGreen); if (inventory != null && inventory.Locked) { indicatorColor *= 0.5f; } spriteBatch.Draw(indicatorSprite.Texture, containedIndicatorArea.Center.ToVector2(), diff --git a/Barotrauma/BarotraumaClient/ClientSource/Items/Item.cs b/Barotrauma/BarotraumaClient/ClientSource/Items/Item.cs index 755769bd2..d4ded9f01 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Items/Item.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Items/Item.cs @@ -333,6 +333,15 @@ namespace Barotrauma if (GameMain.DebugDraw) { + aiTarget?.Draw(spriteBatch); + var containedItems = ContainedItems; + if (containedItems != null) + { + foreach (Item item in containedItems) + { + item.AiTarget?.Draw(spriteBatch); + } + } if (body != null) { body.DebugDraw(spriteBatch, Color.White); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Map/Hull.cs b/Barotrauma/BarotraumaClient/ClientSource/Map/Hull.cs index d817f8eb9..baf8124c6 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Map/Hull.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Map/Hull.cs @@ -248,6 +248,8 @@ namespace Barotrauma if (!editing && !GameMain.DebugDraw) return; + if (aiTarget != null) aiTarget.Draw(spriteBatch); + Rectangle drawRect = Submarine == null ? rect : new Rectangle((int)(Submarine.DrawPosition.X + rect.X), (int)(Submarine.DrawPosition.Y + rect.Y), rect.Width, rect.Height); @@ -269,8 +271,7 @@ namespace Barotrauma GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.Center.X, -drawRect.Y + drawRect.Height / 2, 10, (int)(100 * Math.Min(waterVolume / Volume, 1.0f))), Color.Cyan, true); if (WaterVolume > Volume) { - float maxExcessWater = Volume * MaxCompress; - GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.Center.X, -drawRect.Y + drawRect.Height / 2, 10, (int)(100 * (waterVolume - Volume) / maxExcessWater)), GUI.Style.Red, true); + GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.Center.X, -drawRect.Y + drawRect.Height / 2, 10, (int)(100 * (waterVolume - Volume) / MaxCompress)), GUI.Style.Red, true); } GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.Center.X, -drawRect.Y + drawRect.Height / 2, 10, 100), Color.Black); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/BackgroundCreatures/BackgroundCreaturePrefab.cs b/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/BackgroundCreatures/BackgroundCreaturePrefab.cs index 94501138a..72d5db102 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/BackgroundCreatures/BackgroundCreaturePrefab.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/BackgroundCreatures/BackgroundCreaturePrefab.cs @@ -39,7 +39,7 @@ namespace Barotrauma foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("sprite", System.StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "sprite") continue; Sprite = new Sprite(subElement, lazyLoad: true); break; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/LevelObjects/LevelObject.cs b/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/LevelObjects/LevelObject.cs index fdc5a0afe..e8ca4f341 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/LevelObjects/LevelObject.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/LevelObjects/LevelObject.cs @@ -126,7 +126,7 @@ namespace Barotrauma int j = 0; foreach (XElement subElement in Prefab.Config.Elements()) { - if (!subElement.Name.ToString().Equals("deformablesprite", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "deformablesprite") continue; foreach (XElement animationElement in subElement.Elements()) { var newDeformation = SpriteDeformation.Load(animationElement, Prefab.Name); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/LevelObjects/LevelObjectPrefab.cs b/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/LevelObjects/LevelObjectPrefab.cs index dd66c27c5..b961d85be 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/LevelObjects/LevelObjectPrefab.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Map/Levels/LevelObjects/LevelObjectPrefab.cs @@ -4,7 +4,6 @@ using Barotrauma.SpriteDeformations; using Microsoft.Xna.Framework; using System.Collections.Generic; using System.Globalization; -using System.Linq; using System.Xml.Linq; namespace Barotrauma @@ -121,7 +120,7 @@ namespace Barotrauma SerializableProperty.SerializeProperties(this, element); - foreach (XElement subElement in element.Elements().ToList()) + foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { @@ -140,7 +139,7 @@ namespace Barotrauma break; } } - + foreach (LightSourceParams lightSourceParams in LightSourceParams) { var lightElement = new XElement("LightSource"); @@ -161,7 +160,7 @@ namespace Barotrauma bool elementFound = false; foreach (XElement subElement in element.Elements()) { - if (subElement.Name.ToString().Equals("overridecommonness", System.StringComparison.OrdinalIgnoreCase) + if (subElement.Name.ToString().ToLowerInvariant() == "overridecommonness" && subElement.GetAttributeString("leveltype", "") == overrideCommonness.Key) { subElement.Attribute("commonness").Value = overrideCommonness.Value.ToString("G", CultureInfo.InvariantCulture); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Map/MapEntity.cs b/Barotrauma/BarotraumaClient/ClientSource/Map/MapEntity.cs index 2842f811f..f485e4d9c 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Map/MapEntity.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Map/MapEntity.cs @@ -589,14 +589,6 @@ namespace Barotrauma if (structure.FlippedX && structure.Prefab.CanSpriteFlipX) spriteEffects ^= SpriteEffects.FlipHorizontally; if (structure.flippedY && structure.Prefab.CanSpriteFlipY) spriteEffects ^= SpriteEffects.FlipVertically; } - else if (e is WayPoint wayPoint) - { - Vector2 drawPos = e.WorldPosition; - drawPos.Y = -drawPos.Y; - drawPos += moveAmount; - wayPoint.Draw(spriteBatch, drawPos); - continue; - } e.prefab?.DrawPlacing(spriteBatch, new Rectangle(e.WorldRect.Location + new Point((int)moveAmount.X, (int)-moveAmount.Y), e.WorldRect.Size), e.Scale, spriteEffects); GUI.DrawRectangle(spriteBatch, diff --git a/Barotrauma/BarotraumaClient/ClientSource/Map/Structure.cs b/Barotrauma/BarotraumaClient/ClientSource/Map/Structure.cs index 5ebf33375..121bad258 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Map/Structure.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Map/Structure.cs @@ -254,7 +254,7 @@ namespace Barotrauma spriteBatch, new Vector2(rect.X + drawOffset.X, -(rect.Y + drawOffset.Y)), new Vector2(rect.Width, rect.Height), - color: Prefab.BackgroundSpriteColor, + color: color, textureScale: TextureScale * Scale, startOffset: backGroundOffset, depth: Math.Max(Prefab.BackgroundSprite.Depth + (ID % 255) * 0.000001f, depth + 0.000001f)); @@ -350,6 +350,8 @@ namespace Barotrauma } } } + + AiTarget?.Draw(spriteBatch); } } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Map/StructurePrefab.cs b/Barotrauma/BarotraumaClient/ClientSource/Map/StructurePrefab.cs index 51376edb9..34b5a4d12 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Map/StructurePrefab.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Map/StructurePrefab.cs @@ -6,12 +6,6 @@ namespace Barotrauma { partial class StructurePrefab : MapEntityPrefab { - public Color BackgroundSpriteColor - { - get; - private set; - } - public override void UpdatePlacing(Camera cam) { Vector2 position = Submarine.MouseToWorldGrid(cam, Submarine.MainSub); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Map/Submarine.cs b/Barotrauma/BarotraumaClient/ClientSource/Map/Submarine.cs index 03082d4c1..c29f8c331 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Map/Submarine.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Map/Submarine.cs @@ -56,8 +56,6 @@ namespace Barotrauma private static List roundSounds = null; public static RoundSound LoadRoundSound(XElement element, bool stream = false) { - if (GameMain.SoundManager?.Disabled ?? true) { return null; } - string filename = element.GetAttributeString("file", ""); if (string.IsNullOrEmpty(filename)) filename = element.GetAttributeString("sound", ""); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Map/WayPoint.cs b/Barotrauma/BarotraumaClient/ClientSource/Map/WayPoint.cs index 58e0aef36..195cb57a4 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Map/WayPoint.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Map/WayPoint.cs @@ -9,8 +9,9 @@ namespace Barotrauma { partial class WayPoint : MapEntity { - private static Dictionary iconSprites; - private const int WaypointSize = 12, SpawnPointSize = 32; + private static Texture2D iconTexture; + private const int IconSize = 32; + private static int[] iconIndices = { 3, 0, 1, 2 }; public override bool IsVisible(Rectangle worldView) { @@ -22,58 +23,58 @@ namespace Barotrauma get { return !IsHidden(); } } - public override void Draw(SpriteBatch spriteBatch, bool editing, bool back = true) { if (!editing && !GameMain.DebugDraw) { return; } + if (IsHidden()) { return; } + //Rectangle drawRect = + // Submarine == null ? rect : new Rectangle((int)(Submarine.DrawPosition.X + rect.X), (int)(Submarine.DrawPosition.Y + rect.Y), rect.Width, rect.Height); + Vector2 drawPos = Position; - if (Submarine != null) { drawPos += Submarine.DrawPosition; } + if (Submarine != null) drawPos += Submarine.DrawPosition; drawPos.Y = -drawPos.Y; - Draw(spriteBatch, drawPos); - } - - public void Draw(SpriteBatch spriteBatch, Vector2 drawPos) - { - Color clr = currentHull == null ? Color.CadetBlue : GUI.Style.Green; - if (spawnType != SpawnType.Path) { clr = Color.Gray; } + Color clr = currentHull == null ? Color.Blue : Color.White; if (isObstructed) { clr = Color.Black; } - if (IsHighlighted || IsHighlighted) { clr = Color.Lerp(clr, Color.White, 0.8f); } + if (IsSelected) clr = GUI.Style.Red; + if (IsHighlighted) clr = Color.DarkRed; - int iconSize = spawnType == SpawnType.Path ? WaypointSize : SpawnPointSize; - if (ConnectedGap != null || Ladders != null || Stairs != null || SpawnType != SpawnType.Path) { iconSize = (int)(iconSize * 1.5f); } + int iconX = iconIndices[(int)spawnType] * IconSize % iconTexture.Width; + int iconY = (int)(Math.Floor(iconIndices[(int)spawnType] * IconSize / (float)iconTexture.Width)) * IconSize; - if (IsSelected || IsHighlighted) + int iconSize = IconSize; + if (ConnectedGap != null) { - int glowSize = (int)(iconSize * 1.5f); - GUI.Style.UIGlowCircular.Draw(spriteBatch, - new Rectangle((int)(drawPos.X - glowSize / 2), (int)(drawPos.Y - glowSize / 2), glowSize, glowSize), - Color.White); + iconSize = (int)(iconSize * 1.5f); + } + if (Ladders != null) + { + iconSize = (int)(iconSize * 1.5f); + } + if (Stairs != null) + { + iconSize = (int)(iconSize * 1.5f); } - Sprite sprite = iconSprites[SpawnType]; - if (spawnType == SpawnType.Human && AssignedJob?.Icon != null) - { - sprite = iconSprites[SpawnType.Path]; - } - sprite.Draw(spriteBatch, drawPos, clr, scale: iconSize / (float)sprite.SourceRect.Width, depth: 0.001f); - sprite.RelativeOrigin = Vector2.One * 0.5f; - if (spawnType == SpawnType.Human && AssignedJob?.Icon != null) - { - AssignedJob.Icon.Draw(spriteBatch, drawPos, AssignedJob.UIColor, scale: iconSize / (float)AssignedJob.Icon.SourceRect.Width * 0.8f, depth: 0.0f); - } + spriteBatch.Draw(iconTexture, + new Rectangle((int)(drawPos.X - iconSize / 2), (int)(drawPos.Y - iconSize / 2), iconSize, iconSize), + new Rectangle(iconX, iconY, IconSize, IconSize), clr); + + //GUI.DrawRectangle(spriteBatch, new Rectangle(drawRect.X, -drawRect.Y, rect.Width, rect.Height), clr, true); + + //GUI.SmallFont.DrawString(spriteBatch, Position.ToString(), new Vector2(Position.X, -Position.Y), Color.White); foreach (MapEntity e in linkedTo) { GUI.DrawLine(spriteBatch, drawPos, new Vector2(e.DrawPosition.X, -e.DrawPosition.Y), - (isObstructed ? Color.Gray : GUI.Style.Green) * 0.7f, width: 5, depth: 0.002f); + isObstructed ? Color.Gray : GUI.Style.Green, width: 5); } GUI.SmallFont.DrawString(spriteBatch, @@ -82,14 +83,6 @@ namespace Barotrauma Color.WhiteSmoke); } - public override bool IsMouseOn(Vector2 position) - { - if (IsHidden()) { return false; } - float dist = Vector2.DistanceSquared(position, WorldPosition); - float radius = (SpawnType == SpawnType.Path ? WaypointSize : SpawnPointSize) * 0.6f; - return dist < radius * radius; - } - private bool IsHidden() { if (spawnType == SpawnType.Path) diff --git a/Barotrauma/BarotraumaClient/ClientSource/Networking/Client.cs b/Barotrauma/BarotraumaClient/ClientSource/Networking/Client.cs index b16791516..ae9a597bc 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Networking/Client.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Networking/Client.cs @@ -71,8 +71,7 @@ namespace Barotrauma.Networking else { VoipSound.SetPosition(null); - VoipSound.Gain = 1.0f; - } + } } partial void InitProjSpecific() diff --git a/Barotrauma/BarotraumaClient/ClientSource/Networking/GameClient.cs b/Barotrauma/BarotraumaClient/ClientSource/Networking/GameClient.cs index a99dfeb7c..47ff63bfb 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Networking/GameClient.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Networking/GameClient.cs @@ -8,7 +8,6 @@ using System.IO.Compression; using System.Linq; using System.Text; using System.Threading; -using System.Threading.Tasks; namespace Barotrauma.Networking { @@ -61,18 +60,6 @@ namespace Barotrauma.Networking private bool connected; - private enum RoundInitStatus - { - NotStarted, - Starting, - Started, - TimedOut, - Error, - Interrupted - } - - private RoundInitStatus roundInitStatus = RoundInitStatus.NotStarted; - private byte myID; private List otherClients; @@ -161,8 +148,6 @@ namespace Barotrauma.Networking this.ownerKey = ownerKey; this.steamP2POwner = steamP2POwner; - roundInitStatus = RoundInitStatus.NotStarted; - allowReconnect = true; netStats = new NetStats(); @@ -487,17 +472,13 @@ namespace Barotrauma.Networking var msgBox = new GUIMessageBox(pwMsg, "", new string[] { TextManager.Get("OK"), TextManager.Get("Cancel") }, relativeSize: new Vector2(0.25f, 0.1f), minSize: new Point(400, 170)); - var passwordHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), msgBox.Content.RectTransform), childAnchor: Anchor.TopCenter); - var passwordBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1f), passwordHolder.RectTransform) { MinSize = new Point(0, 20) }) + var passwordHolder = new GUILayoutGroup(new RectTransform(Vector2.One, msgBox.Content.RectTransform), childAnchor: Anchor.TopCenter); + var passwordBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1f) , passwordHolder.RectTransform) { MinSize = new Point(0, 20) }) { UserData = "password", Censor = true }; - msgBox.Content.Recalculate(); - msgBox.Content.RectTransform.MinSize = new Point(0, msgBox.Content.RectTransform.Children.Sum(c => c.Rect.Height)); - msgBox.Content.Parent.RectTransform.MinSize = new Point(0, (int)(msgBox.Content.RectTransform.MinSize.Y / msgBox.Content.RectTransform.RelativeSize.Y)); - var okButton = msgBox.Buttons[0]; var cancelButton = msgBox.Buttons[1]; @@ -543,7 +524,6 @@ namespace Barotrauma.Networking foreach (Client c in ConnectedClients) { - if (c.Character != null && c.Character.Removed) { c.Character = null; } c.UpdateSoundPosition(); } @@ -578,13 +558,6 @@ namespace Barotrauma.Networking try { - incomingMessagesToProcess.Clear(); - incomingMessagesToProcess.AddRange(pendingIncomingMessages); - foreach (var inc in incomingMessagesToProcess) - { - ReadDataMessage(inc); - } - pendingIncomingMessages.Clear(); clientPeer?.Update(deltaTime); } catch (Exception e) @@ -659,23 +632,11 @@ namespace Barotrauma.Networking } } - private bool waitingForStartRoundFinalize = false; - - private readonly List pendingIncomingMessages = new List(); - private readonly List incomingMessagesToProcess = new List(); + private CoroutineHandle startGameCoroutine; private void ReadDataMessage(IReadMessage inc) { ServerPacketHeader header = (ServerPacketHeader)inc.ReadByte(); - - if (header != ServerPacketHeader.STARTGAMEFINALIZE && - header != ServerPacketHeader.ENDGAME && - waitingForStartRoundFinalize) - { - pendingIncomingMessages.Add(inc); - return; - } - switch (header) { case ServerPacketHeader.UPDATE_LOBBY: @@ -753,10 +714,7 @@ namespace Barotrauma.Networking } break; case ServerPacketHeader.STARTGAME: - GameMain.Instance.ShowLoading(StartGame(inc), false); - break; - case ServerPacketHeader.STARTGAMEFINALIZE: - ReadStartGameFinalize(inc); + startGameCoroutine = GameMain.Instance.ShowLoading(StartGame(inc), false); break; case ServerPacketHeader.ENDGAME: string endMessage = inc.ReadString(); @@ -767,8 +725,6 @@ namespace Barotrauma.Networking GameMain.GameSession.WinningTeam = winningTeam; GameMain.GameSession.Mission.Completed = true; } - - roundInitStatus = RoundInitStatus.Interrupted; CoroutineManager.StartCoroutine(EndGame(endMessage), "EndGame"); break; case ServerPacketHeader.CAMPAIGN_SETUP_INFO: @@ -819,37 +775,7 @@ namespace Barotrauma.Networking break; } } - - private void ReadStartGameFinalize(IReadMessage inc) - { - ushort contentToPreloadCount = inc.ReadUInt16(); - List contentToPreload = new List(); - for (int i = 0; i < contentToPreloadCount; i++) - { - ContentType contentType = (ContentType)inc.ReadByte(); - string filePath = inc.ReadString(); - contentToPreload.Add(new ContentFile(filePath, contentType)); - } - - GameMain.GameSession.EventManager.PreloadContent(contentToPreload); - - int levelEqualityCheckVal = inc.ReadInt32(); - - if (Level.Loaded.EqualityCheckVal != levelEqualityCheckVal) - { - string errorMsg = "Level equality check failed. The level generated at your end doesn't match the level generated by the server (seed: " + Level.Loaded.Seed + - ", sub: " + Submarine.MainSub.Name + " (" + Submarine.MainSub.MD5Hash.ShortHash + ")" + - ", mirrored: " + Level.Loaded.Mirrored + ")."; - GameAnalyticsManager.AddErrorEventOnce("GameClient.StartGame:LevelsDontMatch" + Level.Loaded.Seed, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg); - throw new Exception(errorMsg); - } - - GameMain.GameSession.Mission?.ClientReadInitial(inc); - - roundInitStatus = RoundInitStatus.Started; - } - - + private void OnDisconnect() { if (SteamManager.IsInitialized) @@ -958,7 +884,6 @@ namespace Barotrauma.Networking } else { - connected = false; connectCancelled = true; string msg = ""; @@ -1183,8 +1108,6 @@ namespace Barotrauma.Networking if (Character != null) Character.Remove(); HasSpawned = false; eventErrorWritten = false; - waitingForStartRoundFinalize = false; - GameMain.NetLobbyScreen.StopWaitingForStartRound(); while (CoroutineManager.IsCoroutineRunning("EndGame")) { @@ -1203,11 +1126,9 @@ namespace Barotrauma.Networking EndVoteTickBox.Selected = false; - roundInitStatus = RoundInitStatus.Starting; - int seed = inc.ReadInt32(); string levelSeed = inc.ReadString(); - //int levelEqualityCheckVal = inc.ReadInt32(); + int levelEqualityCheckVal = inc.ReadInt32(); float levelDifficulty = inc.ReadSingle(); byte losMode = inc.ReadByte(); @@ -1225,15 +1146,23 @@ namespace Barotrauma.Networking int missionIndex = inc.ReadInt16(); bool respawnAllowed = inc.ReadBoolean(); + bool loadSecondSub = inc.ReadBoolean(); bool disguisesAllowed = inc.ReadBoolean(); bool rewiringAllowed = inc.ReadBoolean(); bool allowRagdollButton = inc.ReadBoolean(); - serverSettings.ReadMonsterEnabled(inc); + ushort contentToPreloadCount = inc.ReadUInt16(); + List contentToPreload = new List(); + for (int i = 0; i < contentToPreloadCount; i++) + { + ContentType contentType = (ContentType)inc.ReadByte(); + string filePath = inc.ReadString(); + contentToPreload.Add(new ContentFile(filePath, contentType)); + } - bool includesFinalize = inc.ReadBoolean(); inc.ReadPadBits(); + serverSettings.ReadMonsterEnabled(inc); GameModePreset gameMode = GameModePreset.List.Find(gm => gm.Identifier == modeIdentifier); MultiPlayerCampaign campaign = @@ -1269,8 +1198,6 @@ namespace Barotrauma.Networking Rand.SetSyncedSeed(seed); - Task startRoundTask; - if (campaign == null) { //this shouldn't happen, TrySelectSub should stop the coroutine if the correct sub/shuttle cannot be found @@ -1310,132 +1237,21 @@ namespace Barotrauma.Networking yield return CoroutineStatus.Failure; } - MissionPrefab missionPrefab = missionIndex < 0 ? null : MissionPrefab.List[missionIndex]; - GameMain.GameSession = missionIndex < 0 ? new GameSession(GameMain.NetLobbyScreen.SelectedSub, "", gameMode, MissionType.None) : - new GameSession(GameMain.NetLobbyScreen.SelectedSub, "", gameMode, missionPrefab); - - //startRoundTask = Task.Run(async () => { await Task.Yield(); GameMain.GameSession.StartRound(levelSeed, levelDifficulty); }); - GameMain.GameSession.StartRound(levelSeed, levelDifficulty); + new GameSession(GameMain.NetLobbyScreen.SelectedSub, "", gameMode, MissionPrefab.List[missionIndex]); + GameMain.GameSession.StartRound(levelSeed, levelDifficulty, loadSecondSub); } else { if (GameMain.GameSession?.CrewManager != null) GameMain.GameSession.CrewManager.Reset(); - /*startRoundTask = Task.Run(async () => - { - await Task.Yield(); - GameMain.GameSession.StartRound(campaign.Map.SelectedConnection.Level, - reloadSub: true, - mirrorLevel: campaign.Map.CurrentLocation != campaign.Map.SelectedConnection.Locations[0]); - });*/ GameMain.GameSession.StartRound(campaign.Map.SelectedConnection.Level, - reloadSub: true, - mirrorLevel: campaign.Map.CurrentLocation != campaign.Map.SelectedConnection.Locations[0]); + reloadSub: true, + loadSecondSub: false, + mirrorLevel: campaign.Map.CurrentLocation != campaign.Map.SelectedConnection.Locations[0]); } - waitingForStartRoundFinalize = true; - - DateTime? timeOut = null; - - while (true) - { - try - { - if (timeOut.HasValue) - { - if (DateTime.Now > timeOut) - { - DebugConsole.ThrowError("Error while starting the round (did not receive STARTROUNDFINALIZE message from the server). Stopping the round..."); - roundInitStatus = RoundInitStatus.TimedOut; - break; - } - } - else - { - if (includesFinalize) - { - ReadStartGameFinalize(inc); - } - else - { - IWriteMessage msg = new WriteOnlyMessage(); - msg.Write((byte)ClientPacketHeader.REQUEST_STARTGAMEFINALIZE); - clientPeer.Send(msg, DeliveryMethod.Reliable); - } - - //wait for up to 30 seconds for the server to send the STARTGAMEFINALIZE message - timeOut = DateTime.Now + new TimeSpan(0, 0, seconds: 30); - /*if (startRoundTask.Status == TaskStatus.RanToCompletion) - { - if (includesFinalize) - { - ReadStartGameFinalize(inc); - } - else - { - IWriteMessage msg = new WriteOnlyMessage(); - msg.Write((byte)ClientPacketHeader.REQUEST_STARTGAMEFINALIZE); - clientPeer.Send(msg, DeliveryMethod.Reliable); - } - - //wait for up to 30 seconds for the server to send the STARTGAMEFINALIZE message - timeOut = DateTime.Now + new TimeSpan(0, 0, seconds: 30); - } - else if (startRoundTask.Status == TaskStatus.Faulted) - { - DebugConsole.ThrowError("There was an error initializing the round: startRoundTask failed.", startRoundTask.Exception.InnerExceptions[0]); - roundInitStatus = RoundInitStatus.Error; - break; - } - else if (startRoundTask.Status == TaskStatus.Canceled) - { - DebugConsole.ThrowError("There was an error initializing the round: startRoundTask was canceled."); - roundInitStatus = RoundInitStatus.Error; - break; - }*/ - } - - if (!connected) - { - roundInitStatus = RoundInitStatus.Interrupted; - break; - } - - if (roundInitStatus != RoundInitStatus.Starting) - { - break; - } - - clientPeer.Update((float)Timing.Step); - } - catch (Exception e) - { - DebugConsole.ThrowError("There was an error initializing the round.", e, true); - roundInitStatus = RoundInitStatus.Error; - //startRoundTask?.Wait(); - break; - } - - //waiting for a STARTGAMEFINALIZE message - yield return CoroutineStatus.Running; - } - - waitingForStartRoundFinalize = false; - - if (roundInitStatus != RoundInitStatus.Started) - { - if (roundInitStatus != RoundInitStatus.Interrupted) - { - DebugConsole.ThrowError(roundInitStatus.ToString()); - CoroutineManager.StartCoroutine(EndGame("")); - yield return CoroutineStatus.Failure; - } - else - { - yield return CoroutineStatus.Success; - } - } + GameMain.GameSession.Mission?.ClientReadInitial(inc); if (GameMain.GameSession.Submarine.IsFileCorrupted) { @@ -1445,7 +1261,7 @@ namespace Barotrauma.Networking for (int i = 0; i < Submarine.MainSubs.Length; i++) { - if (Submarine.MainSubs[i] == null) { break; } + if (!loadSecondSub && i > 0) { break; } var teamID = i == 0 ? Character.TeamType.Team1 : Character.TeamType.Team2; Submarine.MainSubs[i].TeamID = teamID; @@ -1455,10 +1271,23 @@ namespace Barotrauma.Networking } } + if (Level.Loaded.EqualityCheckVal != levelEqualityCheckVal) + { + string errorMsg = "Level equality check failed. The level generated at your end doesn't match the level generated by the server (seed: " + Level.Loaded.Seed + + ", sub: " + Submarine.MainSub.Name + " (" + Submarine.MainSub.MD5Hash.ShortHash + ")" + + ", mirrored: " + Level.Loaded.Mirrored + ")."; + DebugConsole.ThrowError(errorMsg, createMessageBox: true); + GameAnalyticsManager.AddErrorEventOnce("GameClient.StartGame:LevelsDontMatch" + levelSeed, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg); + CoroutineManager.StartCoroutine(EndGame("")); + yield return CoroutineStatus.Failure; + } + if (respawnAllowed) { respawnManager = new RespawnManager(this, GameMain.NetLobbyScreen.UsingShuttle ? GameMain.NetLobbyScreen.SelectedShuttle : null); } - gameStarted = true; + GameMain.GameSession.EventManager.PreloadContent(contentToPreload); + ServerSettings.ServerDetailsChanged = true; + gameStarted = true; GameMain.GameScreen.Select(); @@ -1606,7 +1435,7 @@ namespace Barotrauma.Networking existingClient.Muted = tc.Muted; existingClient.AllowKicking = tc.AllowKicking; GameMain.NetLobbyScreen.SetPlayerNameAndJobPreference(existingClient); - if (Screen.Selected != GameMain.NetLobbyScreen && tc.CharacterID > 0) + if (tc.CharacterID > 0) { existingClient.Character = Entity.FindEntityByID(tc.CharacterID) as Character; if (existingClient.Character == null) @@ -2150,7 +1979,8 @@ namespace Barotrauma.Networking { if (!permissions.HasFlag(ClientPermissions.ConsoleCommands)) { return false; } - if (permittedConsoleCommands.Any(c => c.Equals(commandName, StringComparison.OrdinalIgnoreCase))) { return true; } + commandName = commandName.ToLowerInvariant(); + if (permittedConsoleCommands.Any(c => c.ToLowerInvariant() == commandName)) { return true; } //check aliases foreach (DebugConsole.Command command in DebugConsole.Commands) @@ -2668,7 +2498,6 @@ namespace Barotrauma.Networking { var transfer = fileReceiver.ActiveTransfers.First(); GameMain.NetLobbyScreen.FileTransferFrame.Visible = true; - GameMain.NetLobbyScreen.FileTransferFrame.UserData = transfer; GameMain.NetLobbyScreen.FileTransferTitle.Text = ToolBox.LimitString( TextManager.GetWithVariable("DownloadingFile", "[filename]", transfer.FileName), @@ -2982,8 +2811,8 @@ namespace Barotrauma.Networking errorLines.Add(" " + DebugConsole.Messages[i].Time + " - " + DebugConsole.Messages[i].Text); } - string filePath = "event_error_log_client_" + Name + "_" + DateTime.UtcNow.ToShortTimeString() + ".log"; - filePath = Path.Combine(ServerLog.SavePath, ToolBox.RemoveInvalidFileNameChars(filePath)); + string filePath = "event_error_log_client_" + Name + "_" + ToolBox.RemoveInvalidFileNameChars(DateTime.UtcNow.ToShortTimeString() + ".log"); + filePath = Path.Combine(ServerLog.SavePath, filePath); if (!Directory.Exists(ServerLog.SavePath)) { diff --git a/Barotrauma/BarotraumaClient/ClientSource/Networking/Primitives/Peers/LidgrenClientPeer.cs b/Barotrauma/BarotraumaClient/ClientSource/Networking/Primitives/Peers/LidgrenClientPeer.cs index 41f8f65af..d315062c3 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Networking/Primitives/Peers/LidgrenClientPeer.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Networking/Primitives/Peers/LidgrenClientPeer.cs @@ -91,7 +91,6 @@ namespace Barotrauma.Networking return; } - incomingLidgrenMessages.Clear(); netClient.ReadMessages(incomingLidgrenMessages); foreach (NetIncomingMessage inc in incomingLidgrenMessages) @@ -108,6 +107,8 @@ namespace Barotrauma.Networking break; } } + + incomingLidgrenMessages.Clear(); } private void HandleDataMessage(NetIncomingMessage inc) diff --git a/Barotrauma/BarotraumaClient/ClientSource/Networking/SteamManager.cs b/Barotrauma/BarotraumaClient/ClientSource/Networking/SteamManager.cs index 873c79530..6b2f569db 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Networking/SteamManager.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Networking/SteamManager.cs @@ -1314,69 +1314,79 @@ namespace Barotrauma.Steam return upToDate; } - public static async Task AutoUpdateWorkshopItems() + public static bool AutoUpdateWorkshopItems() { if (!isInitialized) { return false; } var query = new Steamworks.Ugc.Query(Steamworks.UgcType.All) .WhereUserSubscribed() .WithLongDescription(); - - DateTime startTime = DateTime.Now; - DateTime endTime = startTime + new TimeSpan(0, 0, 30); - - int processedResults = 0; int pageIndex = 1; - Steamworks.Ugc.ResultPage? resultPage = await query.GetPageAsync(pageIndex); - - while (resultPage.HasValue && resultPage?.ResultCount > 0) + //ugcResultPageTasks ??= new List(); + //ugcResultPageTasks.Add(); + CancellationTokenSource cancelTokenSource = new CancellationTokenSource(); + CancellationToken cancelToken = cancelTokenSource.Token; + Task task = Task.Factory.StartNew(async () => { - if (DateTime.Now > endTime) + int processedResults = 0; int pageIndex = 1; + Steamworks.Ugc.ResultPage? resultPage = await query.GetPageAsync(pageIndex); + + while (resultPage.HasValue && resultPage?.ResultCount > 0) { - return false; - } - foreach (var item in resultPage.Value.Entries) - { - try + foreach (var item in resultPage.Value.Entries) { - if (!item.IsInstalled || !CheckWorkshopItemEnabled(item) || CheckWorkshopItemUpToDate(item)) { continue; } - if (!UpdateWorkshopItem(item, out string errorMsg)) + if (cancelToken.IsCancellationRequested) + { + cancelToken.ThrowIfCancellationRequested(); + } + try + { + if (!item.IsInstalled || !CheckWorkshopItemEnabled(item) || CheckWorkshopItemUpToDate(item)) { continue; } + if (!UpdateWorkshopItem(item, out string errorMsg)) + { + DebugConsole.ThrowError(errorMsg); + new GUIMessageBox( + TextManager.Get("Error"), + TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { item.Title, errorMsg })); + } + else + { + //TODO: potential race condition + new GUIMessageBox("", TextManager.GetWithVariable("WorkshopItemUpdated", "[itemname]", item.Title)); + } + } + catch (Exception e) { - DebugConsole.ThrowError(errorMsg); new GUIMessageBox( TextManager.Get("Error"), - TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { item.Title, errorMsg })); - } - else - { - //TODO: potential race condition - new GUIMessageBox("", TextManager.GetWithVariable("WorkshopItemUpdated", "[itemname]", item.Title)); + TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { item.Title, e.Message + ", " + e.TargetSite })); + GameAnalyticsManager.AddErrorEventOnce( + "SteamManager.AutoUpdateWorkshopItems:" + e.Message, + GameAnalyticsSDK.Net.EGAErrorSeverity.Error, + "Failed to autoupdate workshop item \"" + item.Title + "\". " + e.Message + "\n" + e.StackTrace); } } - catch (Exception e) - { - new GUIMessageBox( - TextManager.Get("Error"), - TextManager.GetWithVariables("WorkshopItemUpdateFailed", new string[2] { "[itemname]", "[errormessage]" }, new string[2] { item.Title, e.Message + ", " + e.TargetSite })); - GameAnalyticsManager.AddErrorEventOnce( - "SteamManager.AutoUpdateWorkshopItems:" + e.Message, - GameAnalyticsSDK.Net.EGAErrorSeverity.Error, - "Failed to autoupdate workshop item \"" + item.Title + "\". " + e.Message + "\n" + e.StackTrace); - } - } - processedResults += resultPage.Value.ResultCount; - pageIndex++; - if (processedResults < resultPage?.TotalCount) - { - resultPage = await query.GetPageAsync(pageIndex); + processedResults += resultPage.Value.ResultCount; + pageIndex++; + if (processedResults < resultPage?.TotalCount) + { + resultPage = await query.GetPageAsync(pageIndex); + } + else + { + resultPage = null; + } } - else - { - resultPage = null; - } - } + }, cancelToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); - return true; + task.Wait(10000); + if (!task.IsCompleted) + { + cancelTokenSource.Cancel(); + task.Wait(); + } + + return task.Status == TaskStatus.RanToCompletion; } public static bool UpdateWorkshopItem(Steamworks.Ugc.Item? item, out string errorMsg) @@ -1421,7 +1431,7 @@ namespace Barotrauma.Steam private static void CorrectContentFileCopy(ContentPackage package, string src, string dest, bool overwrite) { - if (Path.GetExtension(src).Equals(".xml", StringComparison.OrdinalIgnoreCase)) + if (Path.GetExtension(src).ToLowerInvariant() == ".xml") { XDocument doc = XMLExtensions.TryLoadXml(src); if (doc != null) @@ -1471,7 +1481,7 @@ namespace Barotrauma.Steam { if (checkIfFileExists) { - ContentPackage otherContentPackage = ContentPackage.List.Find(cp => cp.Name.Equals(splitPath[1], StringComparison.OrdinalIgnoreCase)); + ContentPackage otherContentPackage = ContentPackage.List.Find(cp => cp.Name.ToLowerInvariant() == splitPath[1].ToLowerInvariant()); if (otherContentPackage != null) { string otherPackageName = Path.GetDirectoryName(otherContentPackage.Path); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Networking/Voip/VoipClient.cs b/Barotrauma/BarotraumaClient/ClientSource/Networking/Voip/VoipClient.cs index 574dffcb2..59db1c580 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Networking/Voip/VoipClient.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Networking/Voip/VoipClient.cs @@ -93,7 +93,7 @@ namespace Barotrauma.Networking if (client.VoipSound == null) { DebugConsole.Log("Recreating voipsound " + queueId); - client.VoipSound = new VoipSound(client.Name, GameMain.SoundManager, client.VoipQueue); + client.VoipSound = new VoipSound(GameMain.SoundManager, client.VoipQueue); } if (client.Character != null && !client.Character.IsDead && !client.Character.Removed && client.Character.SpeechImpediment <= 100.0f) @@ -119,7 +119,7 @@ namespace Barotrauma.Networking GameMain.NetLobbyScreen?.SetPlayerSpeaking(client); GameMain.GameSession?.CrewManager?.SetClientSpeaking(client); - if ((client.VoipSound.CurrentAmplitude * client.VoipSound.Gain * GameMain.SoundManager.GetCategoryGainMultiplier("voip")) > 0.1f) //TODO: might need to tweak + if (client.VoipSound.CurrentAmplitude > 0.1f) //TODO: might need to tweak { if (client.Character != null && !client.Character.Removed) { diff --git a/Barotrauma/BarotraumaClient/ClientSource/Particles/DecalPrefab.cs b/Barotrauma/BarotraumaClient/ClientSource/Particles/DecalPrefab.cs index da75fd497..d4c179ae1 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Particles/DecalPrefab.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Particles/DecalPrefab.cs @@ -11,18 +11,7 @@ namespace Barotrauma.Particles public string OriginalName { get { return Name; } } - private string _identifier; - public string Identifier - { - get - { - if (_identifier == null) - { - _identifier = Name.ToLowerInvariant(); - } - return _identifier; - } - } + public string Identifier { get { return Name.ToLowerInvariant(); } } public string FilePath { get; private set; } @@ -57,7 +46,7 @@ namespace Barotrauma.Particles foreach (XElement subElement in element.Elements()) { - if (subElement.Name.ToString().Equals("sprite", StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() == "sprite") { Sprites.Add(new Sprite(subElement)); } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Particles/ParticleEmitter.cs b/Barotrauma/BarotraumaClient/ClientSource/Particles/ParticleEmitter.cs index e23e05d2f..f7471bda7 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Particles/ParticleEmitter.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Particles/ParticleEmitter.cs @@ -150,12 +150,6 @@ namespace Barotrauma.Particles { DistanceMin = DistanceMax = element.GetAttributeFloat("distance", 0.0f); } - if (DistanceMax < DistanceMin) - { - var temp = DistanceMin; - DistanceMin = DistanceMax; - DistanceMax = temp; - } if (element.Attribute("velocity") == null) { @@ -166,12 +160,6 @@ namespace Barotrauma.Particles { VelocityMin = VelocityMax = element.GetAttributeFloat("velocity", 0.0f); } - if (VelocityMax < VelocityMin) - { - var temp = VelocityMin; - VelocityMin = VelocityMax; - VelocityMax = temp; - } EmitInterval = element.GetAttributeFloat("emitinterval", 0.0f); ParticlesPerSecond = element.GetAttributeInt("particlespersecond", 0); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/CharacterEditor/CharacterEditorScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/CharacterEditor/CharacterEditorScreen.cs index c1b1f58ab..1ff4d6a40 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/CharacterEditor/CharacterEditorScreen.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/CharacterEditor/CharacterEditorScreen.cs @@ -3347,7 +3347,6 @@ namespace Barotrauma.CharacterEditor void CreateCloseButton(SerializableEntityEditor editor, Action onButtonClicked, float size = 1) { - if (editor == null) { return; } int height = 30; var parent = new GUIFrame(new RectTransform(new Point(editor.Rect.Width, (int)(height * size * GUI.yScale)), editor.RectTransform, isFixedSize: true), style: null) { @@ -3367,7 +3366,6 @@ namespace Barotrauma.CharacterEditor void CreateAddButtonAtLast(ParamsEditor editor, Action onButtonClicked, string text) { - if (editor == null) { return; } var parentFrame = new GUIFrame(new RectTransform(new Point(editor.EditorBox.Rect.Width, (int)(50 * GUI.yScale)), editor.EditorBox.Content.RectTransform), style: null, color: ParamsEditor.Color) { CanBeFocused = false @@ -3385,7 +3383,6 @@ namespace Barotrauma.CharacterEditor void CreateAddButton(SerializableEntityEditor editor, Action onButtonClicked, string text) { - if (editor == null) { return; } var parent = new GUIFrame(new RectTransform(new Point(editor.Rect.Width, (int)(60 * GUI.yScale)), editor.RectTransform), style: null) { CanBeFocused = false diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/CharacterEditor/Wizard.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/CharacterEditor/Wizard.cs index 8f6eb15ce..ba788163d 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/CharacterEditor/Wizard.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/CharacterEditor/Wizard.cs @@ -394,7 +394,7 @@ namespace Barotrauma.CharacterEditor return false; } var path = Path.GetFileName(TexturePath); - if (!path.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) + if (!path.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase)) { GUI.AddMessage(TextManager.Get("WrongFileType"), GUI.Style.Red); texturePathElement.Flash(GUI.Style.Red); @@ -724,8 +724,8 @@ namespace Barotrauma.CharacterEditor { ParseLimbsFromGUIElements(); ParseJointsFromGUIElements(); - var main = LimbXElements.Values.Select(xe => xe.Attribute("type")).Where(a => a.Value.Equals("torso", StringComparison.OrdinalIgnoreCase)).FirstOrDefault() ?? - LimbXElements.Values.Select(xe => xe.Attribute("type")).Where(a => a.Value.Equals("head", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + var main = LimbXElements.Values.Select(xe => xe.Attribute("type")).Where(a => a.Value.ToLowerInvariant() == "torso").FirstOrDefault() ?? + LimbXElements.Values.Select(xe => xe.Attribute("type")).Where(a => a.Value.ToLowerInvariant() == "head").FirstOrDefault(); if (main == null) { GUI.AddMessage(GetCharacterEditorTranslation("MissingTorsoOrHead"), GUI.Style.Red); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/GameScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/GameScreen.cs index 3a0e2d267..3eeb3be8a 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/GameScreen.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/GameScreen.cs @@ -91,13 +91,7 @@ namespace Barotrauma c.DoVisibilityCheck(cam); if (c.IsVisible != wasVisible) { - c.AnimController.Limbs.ForEach(l => - { - if (l.LightSource != null) - { - l.LightSource.Enabled = c.IsVisible; - } - }); + c.AnimController.Limbs.ForEach(l => { if (l.LightSource != null) l.LightSource.Enabled = c.IsVisible; }); } } @@ -288,23 +282,14 @@ namespace Barotrauma } spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.LinearWrap, DepthStencilState.None, null, null, cam.Transform); - foreach (Character c in Character.CharacterList) + foreach (Character c in Character.CharacterList) c.DrawFront(spriteBatch, cam); + + if (Level.Loaded != null) Level.Loaded.DrawFront(spriteBatch, cam); + if (GameMain.DebugDraw && GameMain.GameSession?.EventManager != null) { - c.DrawFront(spriteBatch, cam); - } - if (Level.Loaded != null) - { - Level.Loaded.DrawFront(spriteBatch, cam); - } - if (GameMain.DebugDraw) - { - MapEntity.mapEntityList.ForEach(me => me.AiTarget?.Draw(spriteBatch)); - Character.CharacterList.ForEach(c => c.AiTarget?.Draw(spriteBatch)); - if (GameMain.GameSession?.EventManager != null) - { - GameMain.GameSession.EventManager.DebugDraw(spriteBatch); - } + GameMain.GameSession.EventManager.DebugDraw(spriteBatch); } + spriteBatch.End(); if (GameMain.LightManager.LosEnabled && GameMain.LightManager.LosMode != LosMode.None && Character.Controlled != null) diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/LevelEditorScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/LevelEditorScreen.cs index a81d9c9e3..7ef7322d3 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/LevelEditorScreen.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/LevelEditorScreen.cs @@ -517,21 +517,8 @@ namespace Barotrauma { foreach (XElement element in doc.Root.Elements()) { - XElement levelParamElement = element; - if (element.IsOverride()) - { - foreach (XElement subElement in element.Elements()) - { - if (subElement.Name.ToString().Equals(genParams.Name, StringComparison.OrdinalIgnoreCase)) - { - SerializableProperty.SerializeProperties(genParams, subElement, true); - } - } - } - else if (element.Name.ToString().Equals(genParams.Name, StringComparison.OrdinalIgnoreCase)) - { - SerializableProperty.SerializeProperties(genParams, element, true); - } + if (element.Name.ToString().ToLowerInvariant() != genParams.Name.ToLowerInvariant()) continue; + SerializableProperty.SerializeProperties(genParams, element, true); break; } } @@ -552,7 +539,7 @@ namespace Barotrauma { foreach (XElement element in doc.Root.Elements()) { - if (!element.Name.ToString().Equals(levelObjPrefab.Name, StringComparison.OrdinalIgnoreCase)) { continue; } + if (element.Name.ToString().ToLowerInvariant() != levelObjPrefab.Name.ToLowerInvariant()) continue; levelObjPrefab.Save(element); break; } @@ -577,7 +564,7 @@ namespace Barotrauma bool elementFound = false; foreach (XElement element in doc.Root.Elements()) { - if (!element.Name.ToString().Equals(genParams.Name, StringComparison.OrdinalIgnoreCase)) { continue; } + if (element.Name.ToString().ToLowerInvariant() != genParams.Name.ToLowerInvariant()) continue; SerializableProperty.SerializeProperties(genParams, element, true); elementFound = true; } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/LobbyScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/LobbyScreen.cs index da10f626d..7a3818d74 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/LobbyScreen.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/LobbyScreen.cs @@ -79,7 +79,8 @@ namespace Barotrauma private IEnumerable LoadRound() { GameMain.GameSession.StartRound(campaignUI.SelectedLevel, - reloadSub: true, + reloadSub: true, + loadSecondSub: false, mirrorLevel: GameMain.GameSession.Map.CurrentLocation != GameMain.GameSession.Map.SelectedConnection.Locations[0]); GameMain.GameScreen.Select(); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/NetLobbyScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/NetLobbyScreen.cs index 1cd489054..d49a95eda 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/NetLobbyScreen.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/NetLobbyScreen.cs @@ -443,7 +443,7 @@ namespace Barotrauma { OnClicked = (btn, userdata) => { - if (!(FileTransferFrame.UserData is FileReceiver.FileTransferIn transfer)) { return false; } + if (!(userdata is FileReceiver.FileTransferIn transfer)) { return false; } GameMain.Client?.CancelFileTransfer(transfer); GameMain.Client.FileReceiver.StopTransfer(transfer); return true; @@ -658,7 +658,7 @@ namespace Barotrauma OnClicked = (btn, obj) => { GameMain.Client.RequestStartRound(); - CoroutineManager.StartCoroutine(WaitForStartRound(StartButton, allowCancel: false), "WaitForStartRound"); + CoroutineManager.StartCoroutine(WaitForStartRound(StartButton, allowCancel: true), "WaitForStartRound"); return true; } }; @@ -1147,22 +1147,6 @@ namespace Barotrauma clientDisabledElements.AddRange(botSpawnModeButtons); } - public void StopWaitingForStartRound() - { - CoroutineManager.StopCoroutines("WaitForStartRound"); - - GUIMessageBox.CloseAll(); - if (StartButton != null) - { - StartButton.Enabled = true; - } - if (campaignUI?.StartButton != null) - { - campaignUI.StartButton.Enabled = true; - } - GUI.ClearCursorWait(); - } - public IEnumerable WaitForStartRound(GUIButton startButton, bool allowCancel) { GUI.SetCursorWaiting(); @@ -1189,8 +1173,7 @@ namespace Barotrauma } DateTime timeOut = DateTime.Now + new TimeSpan(0, 0, 10); - while (Selected == GameMain.NetLobbyScreen && - DateTime.Now < timeOut) + while (Selected == GameMain.NetLobbyScreen && DateTime.Now < timeOut) { msgBox.Header.Text = headerText + new string('.', ((int)Timing.TotalTime % 3 + 1)); yield return CoroutineStatus.Running; @@ -1339,8 +1322,6 @@ namespace Barotrauma if (GameMain.Client == null) return; spectateButton.Visible = true; spectateButton.Enabled = true; - - StartButton.Visible = false; } public void SetCampaignCharacterInfo(CharacterInfo newCampaignCharacterInfo) @@ -1780,7 +1761,7 @@ namespace Barotrauma } GameMain.Client.RequestSelectMode(component.Parent.GetChildIndex(component)); HighlightMode(SelectedModeIndex); - return !presetName.Equals("multiplayercampaign", StringComparison.OrdinalIgnoreCase); + return (presetName.ToLowerInvariant() != "multiplayercampaign"); } return false; } @@ -2260,7 +2241,7 @@ namespace Barotrauma targetMicStyle = "GUIMicrophoneDisabled"; } - if (!targetMicStyle.Equals(currMicStyle, StringComparison.OrdinalIgnoreCase)) + if (targetMicStyle.ToLowerInvariant() != currMicStyle.ToLowerInvariant()) { GUI.Style.Apply(micIcon, targetMicStyle); } @@ -2616,7 +2597,7 @@ namespace Barotrauma GUILayoutGroup row = null; int itemsInRow = 0; - XElement headElement = info.Ragdoll.MainElement.Elements().FirstOrDefault(e => e.GetAttributeString("type", "").Equals("head", StringComparison.OrdinalIgnoreCase)); + XElement headElement = info.Ragdoll.MainElement.Elements().FirstOrDefault(e => e.GetAttributeString("type", "").ToLowerInvariant() == "head"); XElement headSpriteElement = headElement.Element("sprite"); string spritePathWithTags = headSpriteElement.Attribute("texture").Value; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/ParticleEditorScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/ParticleEditorScreen.cs index d37df90f9..922e24e57 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/ParticleEditorScreen.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/ParticleEditorScreen.cs @@ -237,7 +237,7 @@ namespace Barotrauma { foreach (XElement element in doc.Root.Elements()) { - if (!element.Name.ToString().Equals(prefab.Name, StringComparison.OrdinalIgnoreCase)) { continue; } + if (element.Name.ToString().ToLowerInvariant() != prefab.Name.ToLowerInvariant()) continue; SerializableProperty.SerializeProperties(prefab, element, true); } } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/ServerListScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/ServerListScreen.cs index f22122b03..7bd320d68 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/ServerListScreen.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/ServerListScreen.cs @@ -965,7 +965,7 @@ namespace Barotrauma child.Visible = serverInfo.OwnerVerified && - serverInfo.ServerName.Contains(searchBox.Text, StringComparison.OrdinalIgnoreCase) && + serverInfo.ServerName.ToLowerInvariant().Contains(searchBox.Text.ToLowerInvariant()) && (!filterSameVersion.Selected || (remoteVersion != null && NetworkMember.IsCompatible(remoteVersion, GameMain.Version))) && (!filterPassword.Selected || !serverInfo.HasPassword) && (!filterIncompatible.Selected || !incompatible) && @@ -996,7 +996,7 @@ namespace Barotrauma foreach (GUITickBox tickBox in gameModeTickBoxes) { var gameMode = (string)tickBox.UserData; - if (!tickBox.Selected && serverInfo.GameMode.Equals(gameMode, StringComparison.OrdinalIgnoreCase)) + if (!tickBox.Selected && (serverInfo.GameMode == gameMode.ToLowerInvariant() || serverInfo.GameMode == gameMode)) { child.Visible = false; break; @@ -1512,7 +1512,7 @@ namespace Barotrauma { serverList.ClearChildren(); - if (masterServerData.Substring(0, 5).Equals("error", StringComparison.OrdinalIgnoreCase)) + if (masterServerData.Substring(0, 5).ToLowerInvariant() == "error") { DebugConsole.ThrowError("Error while connecting to master server (" + masterServerData + ")!"); return; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/SteamWorkshopScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/SteamWorkshopScreen.cs index c55149c95..59ef3ab77 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/SteamWorkshopScreen.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/SteamWorkshopScreen.cs @@ -1097,7 +1097,7 @@ namespace Barotrauma var tagBtn = new GUIButton(new RectTransform(new Vector2(0.25f, 1.0f), tagHolder.Content.RectTransform, anchor: Anchor.CenterLeft), tag.CapitaliseFirstInvariant(), style: "GUIButtonRound"); tagBtn.TextBlock.AutoScaleHorizontal = true; - tagBtn.Selected = itemEditor?.Tags?.Any(t => t.Equals(tag, StringComparison.OrdinalIgnoreCase)) ?? false; + tagBtn.Selected = itemEditor?.Tags?.Any(t => t.ToLowerInvariant() == tag) ?? false; tagBtn.OnClicked = (btn, userdata) => { @@ -1108,7 +1108,7 @@ namespace Barotrauma } else { - itemEditor?.Tags?.RemoveAll(t => t.Equals(tagBtn.Text, StringComparison.OrdinalIgnoreCase)); + itemEditor?.Tags?.RemoveAll(t => t.ToLowerInvariant() == tagBtn.Text.ToLowerInvariant()); tagBtn.Selected = false; } return true; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Screens/SubEditorScreen.cs b/Barotrauma/BarotraumaClient/ClientSource/Screens/SubEditorScreen.cs index fc8fbab2f..f8e71d755 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Screens/SubEditorScreen.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Screens/SubEditorScreen.cs @@ -7,8 +7,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Linq; -using EventInput; -using Microsoft.Xna.Framework.Input; namespace Barotrauma { @@ -90,9 +88,6 @@ namespace Barotrauma private GUITextBlock submarineDescriptionCharacterCount; private Mode mode; - - // Prevent the mode from changing - private bool lockMode; public override Camera Cam { @@ -238,21 +233,15 @@ namespace Barotrauma return true; }; - var spacing = new GUIFrame(new RectTransform(new Vector2(0.02f, 1.0f), paddedTopPanel.RectTransform), style: null); - new GUIFrame(new RectTransform(new Vector2(0.1f, 0.9f), spacing.RectTransform, Anchor.Center), style: "VerticalLine"); + new GUIFrame(new RectTransform(new Vector2(0.01f, 0.9f), paddedTopPanel.RectTransform), style: "VerticalLine"); defaultModeTickBox = new GUITickBox(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "EditSubButton") { ToolTip = TextManager.Get("SubEditorEditingMode"), OnSelected = (GUITickBox tBox) => { - if (!lockMode) - { - if (tBox.Selected) { SetMode(Mode.Default); } - - return true; - } - else { return false; } + if (tBox.Selected) { SetMode(Mode.Default); } + return true; } }; @@ -261,12 +250,8 @@ namespace Barotrauma ToolTip = TextManager.Get("CharacterModeButton") + '\n' + TextManager.Get("CharacterModeToolTip"), OnSelected = (GUITickBox tBox) => { - if (!lockMode) - { - SetMode(tBox.Selected ? Mode.Character : Mode.Default); - return true; - } - else { return false; } + SetMode(tBox.Selected ? Mode.Character : Mode.Default); + return true; } }; @@ -275,17 +260,20 @@ namespace Barotrauma ToolTip = TextManager.Get("WiringModeButton") + '\n' + TextManager.Get("WiringModeToolTip"), OnSelected = (GUITickBox tBox) => { - if (!lockMode) - { - SetMode(tBox.Selected ? Mode.Wiring : Mode.Default); - return true; - } - else { return false; } + SetMode(tBox.Selected ? Mode.Wiring : Mode.Default); + return true; } }; - spacing = new GUIFrame(new RectTransform(new Vector2(0.02f, 1.0f), paddedTopPanel.RectTransform), style: null); - new GUIFrame(new RectTransform(new Vector2(0.1f, 0.9f), spacing.RectTransform, Anchor.Center), style: "VerticalLine"); + new GUIFrame(new RectTransform(new Vector2(0.01f, 0.9f), paddedTopPanel.RectTransform), style: "VerticalLine"); + + new GUIButton(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "GenerateWaypointsButton") + { + ToolTip = TextManager.Get("GenerateWaypointsButton") + '\n' + TextManager.Get("GenerateWaypointsToolTip"), + OnClicked = GenerateWaypoints + }; + + new GUIFrame(new RectTransform(new Vector2(0.01f, 0.9f), paddedTopPanel.RectTransform), style: "VerticalLine"); var visibilityButton = new GUIButton(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "SetupVisibilityButton") { @@ -311,42 +299,6 @@ namespace Barotrauma } }; - spacing = new GUIFrame(new RectTransform(new Vector2(0.02f, 1.0f), paddedTopPanel.RectTransform), style: null); - new GUIFrame(new RectTransform(new Vector2(0.1f, 0.9f), spacing.RectTransform, Anchor.Center), style: "VerticalLine"); - - new GUIButton(new RectTransform(new Vector2(0.9f, 0.9f), paddedTopPanel.RectTransform, scaleBasis: ScaleBasis.BothHeight), "", style: "GenerateWaypointsButton") - { - ToolTip = TextManager.Get("GenerateWaypointsButton") + '\n' + TextManager.Get("GenerateWaypointsToolTip"), - OnClicked = (btn, userdata) => - { - if (WayPoint.WayPointList.Any()) - { - var generateWaypointsVerification = new GUIMessageBox("", TextManager.Get("generatewaypointsverification"), new string[] { TextManager.Get("ok"), TextManager.Get("cancel") }); - generateWaypointsVerification.Buttons[0].OnClicked = (btn, userdata) => - { - if (GenerateWaypoints()) - { - GUI.AddMessage(TextManager.Get("waypointsgeneratedsuccesfully"), GUI.Style.Green); - } - WayPoint.ShowWayPoints = true; - generateWaypointsVerification.Close(); - return true; - }; - generateWaypointsVerification.Buttons[1].OnClicked = generateWaypointsVerification.Close; - } - else - { - if (GenerateWaypoints()) - { - GUI.AddMessage(TextManager.Get("waypointsgeneratedsuccesfully"), GUI.Style.Green); - } - WayPoint.ShowWayPoints = true; - - } - return true; - } - }; - var disclaimerBtn = new GUIButton(new RectTransform(new Vector2(0.1f, 1.0f), paddedTopPanel.RectTransform, Anchor.CenterRight), style: "GUINotificationButton") { IgnoreLayoutGroups = true, @@ -1035,27 +987,18 @@ namespace Barotrauma nameBox.Flash(); return false; } - var result = SaveSubToFile(nameBox.Text); - saveFrame = null; - return result; - } - - private bool SaveSubToFile(string name) - { - if (string.IsNullOrWhiteSpace(name)) + + foreach (char illegalChar in Path.GetInvalidFileNameChars()) { - GUI.AddMessage(TextManager.Get("SubNameMissingWarning"), GUI.Style.Red); - return false; + if (nameBox.Text.Contains(illegalChar)) + { + GUI.AddMessage(TextManager.GetWithVariable("SubNameIllegalCharsWarning", "[illegalchar]", illegalChar.ToString()), GUI.Style.Red); + nameBox.Flash(); + return false; + } } - foreach (var illegalChar in Path.GetInvalidFileNameChars()) - { - if (!name.Contains(illegalChar)) continue; - GUI.AddMessage(TextManager.GetWithVariable("SubNameIllegalCharsWarning", "[illegalchar]", illegalChar.ToString()), GUI.Style.Red); - return false; - } - - string savePath = name + ".sub"; + string savePath = nameBox.Text + ".sub"; string prevSavePath = null; if (Submarine.MainSub != null) { @@ -1072,8 +1015,8 @@ namespace Barotrauma if (vanilla != null) { var vanillaSubs = vanilla.GetFilesOfType(ContentType.Submarine); - string pathToCompare = savePath.Replace(@"\", @"/"); - if (vanillaSubs.Any(sub => sub.Replace(@"\", @"/").Equals(pathToCompare, StringComparison.OrdinalIgnoreCase))) + string pathToCompare = savePath.Replace(@"\", @"/").ToLowerInvariant(); + if (vanillaSubs.Any(sub => sub.Replace(@"\", @"/").ToLowerInvariant() == pathToCompare)) { GUI.AddMessage(TextManager.Get("CannotEditVanillaSubs"), GUI.Style.Red, font: GUI.LargeFont); return false; @@ -1081,7 +1024,7 @@ namespace Barotrauma } #endif - if (previewImage?.Sprite?.Texture != null) + if (previewImage.Sprite?.Texture != null) { using (MemoryStream imgStream = new MemoryStream()) { @@ -1093,7 +1036,7 @@ namespace Barotrauma { Submarine.SaveCurrent(savePath); } - Submarine.MainSub?.CheckForErrors(); + Submarine.MainSub.CheckForErrors(); GUI.AddMessage(TextManager.GetWithVariable("SubSavedNotification", "[filepath]", Submarine.MainSub.FilePath), GUI.Style.Green); @@ -1111,6 +1054,8 @@ namespace Barotrauma subNameLabel.Text = ToolBox.LimitString(Submarine.MainSub.Name, subNameLabel.Font, subNameLabel.Rect.Width); + saveFrame = null; + return false; } @@ -1679,10 +1624,7 @@ namespace Barotrauma foreach (Item item in Item.ItemList) { var lightComponent = item.GetComponent(); - if (lightComponent != null) - { - lightComponent.Light.Enabled = item.ParentInventory == null; - } + if (lightComponent != null) lightComponent.Light.Enabled = item.ParentInventory == null; } if (selectedSub.GameVersion < new Version("0.8.9.0")) @@ -1812,20 +1754,18 @@ namespace Barotrauma return true; } - public void SetMode(Mode newMode) + public void SetMode(Mode mode) { - if (newMode == mode) { return; } - mode = newMode; + if (mode == this.mode) { return; } + this.mode = mode; - lockMode = true; - defaultModeTickBox.Selected = newMode == Mode.Default; + defaultModeTickBox.Selected = mode == Mode.Default; defaultModeTickBox.CanBeFocused = !defaultModeTickBox.Selected; - characterModeTickBox.Selected = newMode == Mode.Character; - wiringModeTickBox.Selected = newMode == Mode.Wiring; - lockMode = false; - - switch (newMode) + characterModeTickBox.Selected = mode == Mode.Character; + wiringModeTickBox.Selected = mode == Mode.Wiring; + + switch (mode) { case Mode.Character: CreateDummyCharacter(); @@ -1850,7 +1790,6 @@ namespace Barotrauma } MapEntity.DeselectAll(); - MapEntity.FilteredSelectedList.Clear(); } private void RemoveDummyCharacter() @@ -2065,10 +2004,12 @@ namespace Barotrauma return false; } - private bool GenerateWaypoints() + private bool GenerateWaypoints(GUIButton button, object obj) { - if (Submarine.MainSub == null) { return false; } - return WayPoint.GenerateSubWaypoints(Submarine.MainSub); + if (Submarine.MainSub == null) return false; + + WayPoint.GenerateSubWaypoints(Submarine.MainSub); + return true; } private void AddPreviouslyUsed(MapEntityPrefab mapEntityPrefab) @@ -2465,53 +2406,12 @@ namespace Barotrauma hullVolumeFrame.Visible = MapEntity.SelectedList.Any(s => s is Hull); saveAssemblyFrame.Visible = MapEntity.SelectedList.Count > 0; - if (GUI.KeyboardDispatcher.Subscriber == null) + if (PlayerInput.KeyHit(Microsoft.Xna.Framework.Input.Keys.Tab)) { - // TODO adjust when the new inventory stuff rolls in - if (PlayerInput.KeyHit(Keys.Q) && mode == Mode.Default) - { - toggleEntityMenuButton.OnClicked?.Invoke(toggleEntityMenuButton, toggleEntityMenuButton.UserData); - } - - if (PlayerInput.KeyHit(Keys.Tab)) - { - entityFilterBox.Select(); - } - - if (PlayerInput.KeyDown(Keys.LeftControl)) - { - // Save menu - if (PlayerInput.KeyHit(Keys.S)) - { - if (PlayerInput.KeyDown(Keys.LeftShift)) - { - // Save the sub without a menu - if (subNameLabel != null) - { - SaveSubToFile(subNameLabel.Text); - } - } - else - { - // Save menu - if (saveFrame == null) - { - CreateSaveScreen(); - } - } - } - - // 1-3 keys on the keyboard for switching modes - if (PlayerInput.KeyHit(Keys.D1)) { SetMode(Mode.Default); } - if (PlayerInput.KeyHit(Keys.D2)) { SetMode(Mode.Character); } - if (PlayerInput.KeyHit(Keys.D3)) { SetMode(Mode.Wiring); } - } - else - { - cam.MoveCamera((float) deltaTime, true); - } + entityFilterBox.Select(); } - + + cam.MoveCamera((float)deltaTime, true); if (PlayerInput.MidButtonHeld()) { Vector2 moveSpeed = PlayerInput.MouseSpeed * (float)deltaTime * 100.0f / cam.Zoom; diff --git a/Barotrauma/BarotraumaClient/ClientSource/Sounds/SoundChannel.cs b/Barotrauma/BarotraumaClient/ClientSource/Sounds/SoundChannel.cs index f1b73d220..cb28e241c 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Sounds/SoundChannel.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Sounds/SoundChannel.cs @@ -97,32 +97,6 @@ namespace Barotrauma.Sounds if (position != null) { - if (float.IsNaN(position.Value.X)) - { - throw new Exception("Failed to set source's position: " + debugName + ", position.X is NaN"); - } - if (float.IsNaN(position.Value.Y)) - { - throw new Exception("Failed to set source's position: " + debugName + ", position.Y is NaN"); - } - if (float.IsNaN(position.Value.Z)) - { - throw new Exception("Failed to set source's position: " + debugName + ", position.Z is NaN"); - } - - if (float.IsInfinity(position.Value.X)) - { - throw new Exception("Failed to set source's position: " + debugName + ", position.X is Infinity"); - } - if (float.IsInfinity(position.Value.Y)) - { - throw new Exception("Failed to set source's position: " + debugName + ", position.Y is Infinity"); - } - if (float.IsInfinity(position.Value.Z)) - { - throw new Exception("Failed to set source's position: " + debugName + ", position.Z is Infinity"); - } - uint alSource = Sound.Owner.GetSourceFromIndex(Sound.SourcePoolIndex, ALSourceIndex); Al.Sourcei(alSource, Al.SourceRelative, Al.False); int alError = Al.GetError(); @@ -404,12 +378,12 @@ namespace Barotrauma.Sounds uint alSource = Sound.Owner.GetSourceFromIndex(Sound.SourcePoolIndex, ALSourceIndex); if (!Al.IsSource(alSource)) return false; Al.GetSourcei(alSource, Al.SourceState, out state); + bool playing = state == Al.Playing; int alError = Al.GetError(); if (alError != Al.NoError) { throw new Exception("Failed to determine playing state from source: " + debugName + ", " + Al.GetErrorString(alError)); } - bool playing = state == Al.Playing; return playing; } } @@ -641,7 +615,7 @@ namespace Barotrauma.Sounds uint alSource = Sound.Owner.GetSourceFromIndex(Sound.SourcePoolIndex, ALSourceIndex); int state; - Al.GetSourcei(alSource, Al.SourceState, out state); + Al.GetSourcei(Sound.Owner.GetSourceFromIndex(Sound.SourcePoolIndex, ALSourceIndex), Al.SourceState, out state); bool playing = state == Al.Playing; int alError = Al.GetError(); if (alError != Al.NoError) @@ -656,7 +630,7 @@ namespace Barotrauma.Sounds { throw new Exception("Failed to determine processed buffers from streamed source: " + debugName + ", " + Al.GetErrorString(alError)); } - + Al.SourceUnqueueBuffers(alSource, unqueuedBufferCount, unqueuedBuffers); alError = Al.GetError(); if (alError != Al.NoError) @@ -753,20 +727,9 @@ namespace Barotrauma.Sounds streamAmplitude = streamBufferAmplitudes[queueStartIndex]; Al.GetSourcei(alSource, Al.SourceState, out state); - alError = Al.GetError(); - if (alError != Al.NoError) - { - throw new Exception("Failed to retrieve stream source state: " + debugName + ", " + Al.GetErrorString(alError)); - } - if (state != Al.Playing) { Al.SourcePlay(alSource); - alError = Al.GetError(); - if (alError != Al.NoError) - { - throw new Exception("Failed to start stream playback: " + debugName + ", " + Al.GetErrorString(alError)); - } } } @@ -775,10 +738,6 @@ namespace Barotrauma.Sounds streamAmplitude = 0.0f; } } - catch (Exception e) - { - DebugConsole.ThrowError($"An exception was thrown when updating a sound stream ({debugName})", e); - } finally { Monitor.Exit(mutex); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Sounds/SoundPlayer.cs b/Barotrauma/BarotraumaClient/ClientSource/Sounds/SoundPlayer.cs index 3db4a6cf3..51ccff9aa 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Sounds/SoundPlayer.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Sounds/SoundPlayer.cs @@ -123,7 +123,7 @@ namespace Barotrauma string filePathB = b.GetAttributeString("file", "").CleanUpPath(); float baseGainB = b.GetAttributeFloat("volume", 1.0f); float rangeB = b.GetAttributeFloat("range", 1000.0f); - return a.Name.ToString().Equals(b.Name.ToString(), StringComparison.OrdinalIgnoreCase) && + return a.Name.ToString().ToLowerInvariant() == b.Name.ToString().ToLowerInvariant() && filePathA == filePathB && MathUtils.NearlyEqual(baseGainA, baseGainB) && MathUtils.NearlyEqual(rangeA, rangeB); } @@ -151,7 +151,7 @@ namespace Barotrauma SoundCount = 1 + soundElements.Count(); - var startUpSoundElement = soundElements.Find(e => e.Name.ToString().Equals("startupsound", StringComparison.OrdinalIgnoreCase)); + var startUpSoundElement = soundElements.Find(e => e.Name.ToString().ToLowerInvariant() == "startupsound"); if (startUpSoundElement != null) { startUpSound = GameMain.SoundManager.LoadSound(startUpSoundElement, false); @@ -182,7 +182,7 @@ namespace Barotrauma musicClips.AddIfNotNull(newMusicClip); if (loadedSoundElements != null) { - if (newMusicClip.Type.Equals("menu", StringComparison.OrdinalIgnoreCase)) + if (newMusicClip.Type.ToLowerInvariant() == "menu") { targetMusic[0] = newMusicClip; } diff --git a/Barotrauma/BarotraumaClient/ClientSource/Sounds/VoipSound.cs b/Barotrauma/BarotraumaClient/ClientSource/Sounds/VoipSound.cs index 974a67cdd..bd137b800 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Sounds/VoipSound.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Sounds/VoipSound.cs @@ -59,10 +59,8 @@ namespace Barotrauma.Sounds get { return soundChannel?.CurrentAmplitude ?? 0.0f; } } - public VoipSound(string name, SoundManager owner, VoipQueue q) : base(owner, "voip", true, true) + public VoipSound(SoundManager owner, VoipQueue q) : base(owner, "voip", true, true) { - Filename = $"VoIP ({name})"; - VoipConfig.SetupEncoding(); ALFormat = Al.FormatMono16; @@ -95,28 +93,9 @@ namespace Barotrauma.Sounds public void ApplyFilters(short[] buffer, int readSamples) { - for (int i = 0; i < readSamples; i++) - { - float fVal = ShortToFloat(buffer[i]); - if (UseMuffleFilter) - { - foreach (var filter in muffleFilters) - { - fVal = filter.Process(fVal); - } - } - if (UseRadioFilter) - { - foreach (var filter in radioFilters) - { - fVal = filter.Process(fVal); - } - } - buffer[i] = FloatToShort(fVal); - } if (UseMuffleFilter) { - ApplyFilters(muffleFilters, buffer, readSamples); + ApplyFilters(radioFilters, buffer, readSamples); } if (UseRadioFilter) @@ -127,6 +106,15 @@ namespace Barotrauma.Sounds private void ApplyFilters(IEnumerable filters, short[] buffer, int readSamples) { + for (int i = 0; i < readSamples; i++) + { + float fVal = ShortToFloat(buffer[i]); + foreach (var filter in filters) + { + fVal = filter.Process(fVal); + } + buffer[i] = FloatToShort(fVal); + } } public override SoundChannel Play(float gain, float range, Vector2 position, bool muffle = false) diff --git a/Barotrauma/BarotraumaClient/ClientSource/StatusEffects/StatusEffect.cs b/Barotrauma/BarotraumaClient/ClientSource/StatusEffects/StatusEffect.cs index 2d058ee32..c1fab4f3a 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/StatusEffects/StatusEffect.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/StatusEffects/StatusEffect.cs @@ -52,7 +52,7 @@ namespace Barotrauma } } - partial void ApplyProjSpecific(float deltaTime, Entity entity, IEnumerable targets, Hull hull, Vector2 worldPosition) + partial void ApplyProjSpecific(float deltaTime, Entity entity, List targets, Hull hull, Vector2 worldPosition) { if (entity == null) { return; } @@ -116,13 +116,13 @@ namespace Barotrauma { if (entity is Item item && item.body != null) { - angle = -item.body.Rotation; - if (item.body.Dir < 0.0f) { angle += MathHelper.Pi; } + angle = item.body.Rotation + ((item.body.Dir > 0.0f) ? 0.0f : MathHelper.Pi); } } - emitter.Emit(deltaTime, worldPosition, hull, angle: angle, particleRotation: angle); - } + emitter.Emit(deltaTime, worldPosition, hull, angle); + } + } static partial void UpdateAllProjSpecific(float deltaTime) diff --git a/Barotrauma/BarotraumaClient/ClientSource/Traitors/TraitorMissionPrefab.cs b/Barotrauma/BarotraumaClient/ClientSource/Traitors/TraitorMissionPrefab.cs index 42d8d7f84..9a900cf4c 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Traitors/TraitorMissionPrefab.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Traitors/TraitorMissionPrefab.cs @@ -35,7 +35,7 @@ namespace Barotrauma Identifier = element.GetAttributeString("identifier", ""); foreach (XElement subElement in element.Elements()) { - if (subElement.Name.ToString().Equals("icon", StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() == "icon") { Icon = new Sprite(subElement); IconColor = subElement.GetAttributeColor("color", Color.White); diff --git a/Barotrauma/BarotraumaClient/ClientSource/Utils/ToolBox.cs b/Barotrauma/BarotraumaClient/ClientSource/Utils/ToolBox.cs index c04d65ed9..ad2518771 100644 --- a/Barotrauma/BarotraumaClient/ClientSource/Utils/ToolBox.cs +++ b/Barotrauma/BarotraumaClient/ClientSource/Utils/ToolBox.cs @@ -240,13 +240,13 @@ namespace Barotrauma name = null; endpoint = null; lobbyId = 0; if (args == null || args.Length < 2) { return; } - if (args[0].Equals("-connect", StringComparison.OrdinalIgnoreCase)) + if (args[0].Equals("-connect", StringComparison.InvariantCultureIgnoreCase)) { if (args.Length < 3) { return; } name = args[1]; endpoint = args[2]; } - else if (args[0].Equals("+connect_lobby", StringComparison.OrdinalIgnoreCase)) + else if (args[0].Equals("+connect_lobby", StringComparison.InvariantCultureIgnoreCase)) { UInt64.TryParse(args[1], out lobbyId); } diff --git a/Barotrauma/BarotraumaClient/LinuxClient.csproj b/Barotrauma/BarotraumaClient/LinuxClient.csproj index 0d22d7edc..b5fd4f6d5 100644 --- a/Barotrauma/BarotraumaClient/LinuxClient.csproj +++ b/Barotrauma/BarotraumaClient/LinuxClient.csproj @@ -1,186 +1,186 @@ - - - - WinExe - netcoreapp3.0 - Barotrauma - FakeFish, Undertow Games - Barotrauma - 0.9.7.0 - Copyright © FakeFish 2018-2020 - AnyCPU;x64 - Barotrauma - ..\BarotraumaShared\Icon.ico - Debug;Release;Unstable - - - - DEBUG;TRACE;CLIENT;LINUX;USE_STEAM - x64 - ..\bin\$(Configuration)Linux\ - - - - TRACE;DEBUG;CLIENT;LINUX;X64;USE_STEAM - x64 - ..\bin\$(Configuration)Linux\ - - - - TRACE;CLIENT;LINUX;USE_STEAM - x64 - ..\bin\$(Configuration)Linux\ - - - - TRACE;CLIENT;LINUX;USE_STEAM;UNSTABLE - x64 - ..\bin\$(Configuration)Linux\ - - - - TRACE;CLIENT;LINUX;X64;USE_STEAM - x64 - ..\bin\$(Configuration)Linux\ - - - - TRACE;CLIENT;LINUX;X64;USE_STEAM;UNSTABLE - x64 - ..\bin\$(Configuration)Linux\ - - - - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - PreserveNewest - - - - Icon.bmp - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(IntermediateOutputPath)gitver - $(IntermediateOutputPath)gitbranch - - - - - - - - - - - - - - - - - - @(GitVersion) - - - - - - - - - @(GitBranch) - - - - - - - $(IntermediateOutputPath)CustomAssemblyInfo.cs - - - - - - - - - <_Parameter1>GitRevision - <_Parameter2>$(BuildHash) - - - <_Parameter1>GitBranch - <_Parameter2>$(BuildBranch) - - - - - - + + + + WinExe + netcoreapp3.0 + Barotrauma + FakeFish, Undertow Games + Barotrauma + 0.9.7.1 + Copyright © FakeFish 2018-2020 + AnyCPU;x64 + Barotrauma + ..\BarotraumaShared\Icon.ico + Debug;Release;Unstable + + + + DEBUG;TRACE;CLIENT;LINUX;USE_STEAM + x64 + ..\bin\$(Configuration)Linux\ + + + + TRACE;DEBUG;CLIENT;LINUX;X64;USE_STEAM + x64 + ..\bin\$(Configuration)Linux\ + + + + TRACE;CLIENT;LINUX;USE_STEAM + x64 + ..\bin\$(Configuration)Linux\ + + + + TRACE;CLIENT;LINUX;USE_STEAM;UNSTABLE + x64 + ..\bin\$(Configuration)Linux\ + + + + TRACE;CLIENT;LINUX;X64;USE_STEAM + x64 + ..\bin\$(Configuration)Linux\ + + + + TRACE;CLIENT;LINUX;X64;USE_STEAM;UNSTABLE + x64 + ..\bin\$(Configuration)Linux\ + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + PreserveNewest + + + + Icon.bmp + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + $(IntermediateOutputPath)gitver + $(IntermediateOutputPath)gitbranch + + + + + + + + + + + + + + + + + + @(GitVersion) + + + + + + + + + @(GitBranch) + + + + + + + $(IntermediateOutputPath)CustomAssemblyInfo.cs + + + + + + + + + <_Parameter1>GitRevision + <_Parameter2>$(BuildHash) + + + <_Parameter1>GitBranch + <_Parameter2>$(BuildBranch) + + + + + + \ No newline at end of file diff --git a/Barotrauma/BarotraumaClient/MacClient.csproj b/Barotrauma/BarotraumaClient/MacClient.csproj index af0cf1908..de068fa67 100644 --- a/Barotrauma/BarotraumaClient/MacClient.csproj +++ b/Barotrauma/BarotraumaClient/MacClient.csproj @@ -1,188 +1,188 @@ - - - - WinExe - netcoreapp3.0 - Barotrauma - FakeFish, Undertow Games - Barotrauma - 0.9.7.0 - Copyright © FakeFish 2018-2020 - AnyCPU;x64 - Barotrauma - ..\BarotraumaShared\Icon.ico - 0.9.703.0 - Debug;Release;Unstable - - - - TRACE;CLIENT;OSX;USE_STEAM;DEBUG;NETCOREAPP;NETCOREAPP3_0 - x64 - ..\bin\$(Configuration)Mac - - - - TRACE;DEBUG;CLIENT;OSX;X64;USE_STEAM - x64 - ..\bin\$(Configuration)Mac\ - - - - TRACE;CLIENT;OSX;USE_STEAM;RELEASE;NETCOREAPP;NETCOREAPP3_0 - x64 - - ..\bin\$(Configuration)Mac - - - - TRACE;CLIENT;OSX;USE_STEAM;RELEASE;NETCOREAPP;NETCOREAPP3_0;UNSTABLE - x64 - - ..\bin\$(Configuration)Mac - - - - TRACE;CLIENT;OSX;X64;USE_STEAM - x64 - ..\bin\$(Configuration)Mac\ - - - - TRACE;CLIENT;OSX;X64;USE_STEAM;UNSTABLE - x64 - ..\bin\$(Configuration)Mac\ - - - - - - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - Icon.bmp - - - - - - - - - - - - - - - - - - - - - - - - - - - libsteam_api64.dylib - PreserveNewest - - - - - PreserveNewest - - - - - - $(IntermediateOutputPath)gitver - $(IntermediateOutputPath)gitbranch - - - - - - - - - - - - - - - - - - @(GitVersion) - - - - - - - - - @(GitBranch) - - - - - - - $(IntermediateOutputPath)CustomAssemblyInfo.cs - - - - - - - - - <_Parameter1>GitRevision - <_Parameter2>$(BuildHash) - - - <_Parameter1>GitBranch - <_Parameter2>$(BuildBranch) - - - - - - + + + + WinExe + netcoreapp3.0 + Barotrauma + FakeFish, Undertow Games + Barotrauma + 0.9.7.1 + Copyright © FakeFish 2018-2020 + AnyCPU;x64 + Barotrauma + ..\BarotraumaShared\Icon.ico + 0.9.703.0 + Debug;Release;Unstable + + + + TRACE;CLIENT;OSX;USE_STEAM;DEBUG;NETCOREAPP;NETCOREAPP3_0 + x64 + ..\bin\$(Configuration)Mac + + + + TRACE;DEBUG;CLIENT;OSX;X64;USE_STEAM + x64 + ..\bin\$(Configuration)Mac\ + + + + TRACE;CLIENT;OSX;USE_STEAM;RELEASE;NETCOREAPP;NETCOREAPP3_0 + x64 + + ..\bin\$(Configuration)Mac + + + + TRACE;CLIENT;OSX;USE_STEAM;RELEASE;NETCOREAPP;NETCOREAPP3_0;UNSTABLE + x64 + + ..\bin\$(Configuration)Mac + + + + TRACE;CLIENT;OSX;X64;USE_STEAM + x64 + ..\bin\$(Configuration)Mac\ + + + + TRACE;CLIENT;OSX;X64;USE_STEAM;UNSTABLE + x64 + ..\bin\$(Configuration)Mac\ + + + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + Icon.bmp + + + + + + + + + + + + + + + + + + + + + + + + + + + libsteam_api64.dylib + PreserveNewest + + + + + PreserveNewest + + + + + + $(IntermediateOutputPath)gitver + $(IntermediateOutputPath)gitbranch + + + + + + + + + + + + + + + + + + @(GitVersion) + + + + + + + + + @(GitBranch) + + + + + + + $(IntermediateOutputPath)CustomAssemblyInfo.cs + + + + + + + + + <_Parameter1>GitRevision + <_Parameter2>$(BuildHash) + + + <_Parameter1>GitBranch + <_Parameter2>$(BuildBranch) + + + + + + \ No newline at end of file diff --git a/Barotrauma/BarotraumaClient/WindowsClient.csproj b/Barotrauma/BarotraumaClient/WindowsClient.csproj index 8b2899f4e..6db530ef8 100644 --- a/Barotrauma/BarotraumaClient/WindowsClient.csproj +++ b/Barotrauma/BarotraumaClient/WindowsClient.csproj @@ -1,210 +1,209 @@ - - - - WinExe - netcoreapp3.0 - Barotrauma - FakeFish, Undertow Games - Barotrauma - 0.9.7.0 - Copyright © FakeFish 2018-2020 - AnyCPU;x64 - Barotrauma - ..\BarotraumaShared\Icon.ico - Debug;Release;Unstable - app.manifest - - - - DEBUG;TRACE;CLIENT;WINDOWS;USE_STEAM - x64 - ..\bin\$(Configuration)Windows\ - - - - TRACE;DEBUG;CLIENT;WINDOWS;X64;USE_STEAM - x64 - ..\bin\$(Configuration)Windows\ - - - - TRACE;CLIENT;WINDOWS;USE_STEAM - x64 - ..\bin\$(Configuration)Windows\ - - - - TRACE;CLIENT;WINDOWS;USE_STEAM - x64 - ..\bin\$(Configuration)Windows\ - - - - TRACE;CLIENT;WINDOWS;X64;USE_STEAM - x64 - ..\bin\$(Configuration)Windows\ - - - - TRACE;CLIENT;WINDOWS;X64;USE_STEAM - x64 - ..\bin\$(Configuration)Windows\ - - - - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - - PreserveNewest - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - - - - - - $(IntermediateOutputPath)gitver - $(IntermediateOutputPath)gitbranch - - - - - - - - - - - - - - - - - - @(GitVersion) - - - - - - - - - @(GitBranch) - - - - - - - $(IntermediateOutputPath)CustomAssemblyInfo.cs - - - - - - - - - <_Parameter1>GitRevision - <_Parameter2>$(BuildHash) - - - <_Parameter1>GitBranch - <_Parameter2>$(BuildBranch) - - - - - - + + + + WinExe + netcoreapp3.0 + Barotrauma + FakeFish, Undertow Games + Barotrauma + 0.9.7.1 + Copyright © FakeFish 2018-2020 + AnyCPU;x64 + Barotrauma + ..\BarotraumaShared\Icon.ico + Debug;Release;Unstable + + + + DEBUG;TRACE;CLIENT;WINDOWS;USE_STEAM + x64 + ..\bin\$(Configuration)Windows\ + + + + TRACE;DEBUG;CLIENT;WINDOWS;X64;USE_STEAM + x64 + ..\bin\$(Configuration)Windows\ + + + + TRACE;CLIENT;WINDOWS;USE_STEAM + x64 + ..\bin\$(Configuration)Windows\ + + + + TRACE;CLIENT;WINDOWS;USE_STEAM + x64 + ..\bin\$(Configuration)Windows\ + + + + TRACE;CLIENT;WINDOWS;X64;USE_STEAM + x64 + ..\bin\$(Configuration)Windows\ + + + + TRACE;CLIENT;WINDOWS;X64;USE_STEAM + x64 + ..\bin\$(Configuration)Windows\ + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + PreserveNewest + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Never + + + Never + + + Never + + + Never + + + Never + + + Never + + + Never + + + Never + + + + + + + + $(IntermediateOutputPath)gitver + $(IntermediateOutputPath)gitbranch + + + + + + + + + + + + + + + + + + @(GitVersion) + + + + + + + + + @(GitBranch) + + + + + + + $(IntermediateOutputPath)CustomAssemblyInfo.cs + + + + + + + + + <_Parameter1>GitRevision + <_Parameter2>$(BuildHash) + + + <_Parameter1>GitBranch + <_Parameter2>$(BuildBranch) + + + + + + \ No newline at end of file diff --git a/Barotrauma/BarotraumaServer/LinuxServer.csproj b/Barotrauma/BarotraumaServer/LinuxServer.csproj index ea1c07d7d..55665f547 100644 --- a/Barotrauma/BarotraumaServer/LinuxServer.csproj +++ b/Barotrauma/BarotraumaServer/LinuxServer.csproj @@ -6,7 +6,7 @@ Barotrauma FakeFish, Undertow Games Barotrauma Dedicated Server - 0.9.7.0 + 0.9.7.1 Copyright © FakeFish 2018-2020 AnyCPU;x64 DedicatedServer diff --git a/Barotrauma/BarotraumaServer/MacServer.csproj b/Barotrauma/BarotraumaServer/MacServer.csproj index 2aba5ac45..94e78064c 100644 --- a/Barotrauma/BarotraumaServer/MacServer.csproj +++ b/Barotrauma/BarotraumaServer/MacServer.csproj @@ -6,7 +6,7 @@ Barotrauma FakeFish, Undertow Games Barotrauma Dedicated Server - 0.9.7.0 + 0.9.7.1 Copyright © FakeFish 2018-2020 AnyCPU;x64 DedicatedServer diff --git a/Barotrauma/BarotraumaServer/ServerSource/Characters/CharacterNetworking.cs b/Barotrauma/BarotraumaServer/ServerSource/Characters/CharacterNetworking.cs index a2b32e735..e537f50db 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Characters/CharacterNetworking.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Characters/CharacterNetworking.cs @@ -333,14 +333,6 @@ namespace Barotrauma attack = dequeuedInput.HasFlag(InputNetFlags.Attack); shoot = dequeuedInput.HasFlag(InputNetFlags.Shoot); } - else if (keys != null) - { - aiming = keys[(int)InputType.Aim].GetHeldQueue; - use = keys[(int)InputType.Use].GetHeldQueue; - attack = keys[(int)InputType.Attack].GetHeldQueue; - shoot = keys[(int)InputType.Shoot].GetHeldQueue; - networkUpdateSent = true; - } tempBuffer.Write(aiming); tempBuffer.Write(shoot); @@ -497,31 +489,6 @@ namespace Barotrauma msg.Write(this is AICharacter); msg.Write(info.SpeciesName); info.ServerWrite(msg); - - // Current order - if (info.CurrentOrder != null) - { - msg.Write(true); - msg.Write((byte)Order.PrefabList.IndexOf(info.CurrentOrder.Prefab)); - msg.Write(info.CurrentOrder.TargetEntity == null ? (UInt16)0 : - info.CurrentOrder.TargetEntity.ID); - if (info.CurrentOrder.OrderGiver != null) - { - msg.Write(true); - msg.Write(info.CurrentOrder.OrderGiver.ID); - } - else - { - msg.Write(false); - } - msg.Write((byte)(string.IsNullOrWhiteSpace(info.CurrentOrderOption) ? 0 : - Array.IndexOf(info.CurrentOrder.Prefab.Options, info.CurrentOrderOption))); - } - else - { - msg.Write(false); - } - TryWriteStatus(msg); void TryWriteStatus(IWriteMessage msg) diff --git a/Barotrauma/BarotraumaServer/ServerSource/DebugConsole.cs b/Barotrauma/BarotraumaServer/ServerSource/DebugConsole.cs index 4236b0d3a..b4ed048c7 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/DebugConsole.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/DebugConsole.cs @@ -558,7 +558,7 @@ namespace Barotrauma ShowQuestionPrompt("Rank to grant to \"" + client.Name + "\"?", (rank) => { - PermissionPreset preset = PermissionPreset.List.Find(p => p.Name.Equals(rank, StringComparison.OrdinalIgnoreCase)); + PermissionPreset preset = PermissionPreset.List.Find(p => p.Name.ToLowerInvariant() == rank.ToLowerInvariant()); if (preset == null) { ThrowError("Rank \"" + rank + "\" not found."); @@ -1165,7 +1165,7 @@ namespace Barotrauma else { string modeName = string.Join(" ", args); - if (modeName.Equals("campaign", StringComparison.OrdinalIgnoreCase)) + if (modeName.ToLowerInvariant() == "campaign") { MultiPlayerCampaign.StartCampaignSetup(); } @@ -1493,7 +1493,7 @@ namespace Barotrauma { if (args.Length < 2) return; - AfflictionPrefab afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(a => a.Name.Equals(args[0], StringComparison.OrdinalIgnoreCase)); + AfflictionPrefab afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(a => a.Name.ToLowerInvariant() == args[0].ToLowerInvariant()); if (afflictionPrefab == null) { GameMain.Server.SendConsoleMessage("Affliction \"" + args[0] + "\" not found.", client); @@ -1718,7 +1718,7 @@ namespace Barotrauma } string rank = string.Join("", args.Skip(1)); - PermissionPreset preset = PermissionPreset.List.Find(p => p.Name.Equals(rank, StringComparison.OrdinalIgnoreCase)); + PermissionPreset preset = PermissionPreset.List.Find(p => p.Name.ToLowerInvariant() == rank.ToLowerInvariant()); if (preset == null) { GameMain.Server.SendConsoleMessage("Rank \"" + rank + "\" not found.", senderClient); diff --git a/Barotrauma/BarotraumaServer/ServerSource/Events/Missions/CombatMission.cs b/Barotrauma/BarotraumaServer/ServerSource/Events/Missions/CombatMission.cs index 5c4f447f0..92697eac9 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Events/Missions/CombatMission.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Events/Missions/CombatMission.cs @@ -21,7 +21,7 @@ namespace Barotrauma } } - public override void AssignTeamIDs(List clients) + public override bool AssignTeamIDs(List clients) { List randList = new List(clients); for (int i = 0; i < randList.Count; i++) @@ -44,6 +44,7 @@ namespace Barotrauma randList[i].TeamID = Character.TeamType.Team2; } } + return true; } public override void Update(float deltaTime) diff --git a/Barotrauma/BarotraumaServer/ServerSource/GameMain.cs b/Barotrauma/BarotraumaServer/ServerSource/GameMain.cs index 5d3840b57..fe6bc2504 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/GameMain.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/GameMain.cs @@ -61,7 +61,7 @@ namespace Barotrauma if (vanillaContent == null) { // TODO: Dynamic method for defining and finding the vanilla content package. - vanillaContent = ContentPackage.List.SingleOrDefault(cp => Path.GetFileName(cp.Path).Equals("vanilla 0.9.xml", StringComparison.OrdinalIgnoreCase)); + vanillaContent = ContentPackage.List.SingleOrDefault(cp => Path.GetFileName(cp.Path).ToLowerInvariant() == "vanilla 0.9.xml"); } return vanillaContent; } diff --git a/Barotrauma/BarotraumaServer/ServerSource/GameSession/GameModes/MultiPlayerCampaign.cs b/Barotrauma/BarotraumaServer/ServerSource/GameSession/GameModes/MultiPlayerCampaign.cs index 0b51ae6d3..caff80bd3 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/GameSession/GameModes/MultiPlayerCampaign.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/GameSession/GameModes/MultiPlayerCampaign.cs @@ -46,7 +46,7 @@ namespace Barotrauma DebugConsole.NewMessage("********* CAMPAIGN SETUP *********", Color.White); DebugConsole.ShowQuestionPrompt("Do you want to start a new campaign? Y/N", (string arg) => { - if (arg.Equals("y", StringComparison.OrdinalIgnoreCase) || arg.Equals("yes", StringComparison.OrdinalIgnoreCase)) + if (arg.ToLowerInvariant() == "y" || arg.ToLowerInvariant() == "yes") { DebugConsole.ShowQuestionPrompt("Enter a save name for the campaign:", (string saveName) => { diff --git a/Barotrauma/BarotraumaServer/ServerSource/Items/Components/Repairable.cs b/Barotrauma/BarotraumaServer/ServerSource/Items/Components/Repairable.cs index 3cf56ec69..43b056872 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Items/Components/Repairable.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Items/Components/Repairable.cs @@ -12,7 +12,7 @@ namespace Barotrauma.Items.Components public void ServerRead(ClientNetObject type, IReadMessage msg, Client c) { - if (c.Character == null) { return; } + if (c.Character == null) return; var requestedFixAction = (FixActions)msg.ReadRangedInteger(0, 2); if (requestedFixAction != FixActions.None) { diff --git a/Barotrauma/BarotraumaServer/ServerSource/Items/Components/Signal/Terminal.cs b/Barotrauma/BarotraumaServer/ServerSource/Items/Components/Signal/Terminal.cs index 7bd88be3d..c7653ef60 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Items/Components/Signal/Terminal.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Items/Components/Signal/Terminal.cs @@ -17,10 +17,9 @@ namespace Barotrauma.Items.Components GameServer.Log(c.Character.LogName + " entered \"" + newOutputValue + "\" on " + item.Name, ServerLog.MessageType.ItemInteraction); OutputValue = newOutputValue; - item.SendSignal(0, newOutputValue, "signal_out", null); - item.CreateServerEvent(this); } + item.CreateServerEvent(this); } public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null) diff --git a/Barotrauma/BarotraumaServer/ServerSource/Items/Item.cs b/Barotrauma/BarotraumaServer/ServerSource/Items/Item.cs index 9545c41b6..8f1a873a2 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Items/Item.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Items/Item.cs @@ -8,11 +8,6 @@ namespace Barotrauma { partial class Item : MapEntity, IDamageable, ISerializableEntity, IServerSerializable, IClientSerializable { - public override Sprite Sprite - { - get { return prefab?.sprite; } - } - public void ServerWrite(IWriteMessage msg, Client c, object[] extraData = null) { string errorMsg = ""; diff --git a/Barotrauma/BarotraumaServer/ServerSource/Networking/GameServer.cs b/Barotrauma/BarotraumaServer/ServerSource/Networking/GameServer.cs index 3328d59c2..d3df8d576 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Networking/GameServer.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Networking/GameServer.cs @@ -627,16 +627,10 @@ namespace Barotrauma.Networking //game already started -> send start message immediately if (gameStarted) { - SendStartMessage(roundStartSeed, GameMain.GameSession.Level.Seed, GameMain.GameSession, connectedClient, true); + SendStartMessage(roundStartSeed, Submarine.MainSub, GameMain.GameSession.GameMode.Preset, connectedClient); } } break; - case ClientPacketHeader.REQUEST_STARTGAMEFINALIZE: - if (gameStarted && connectedClient != null) - { - SendRoundStartFinalize(connectedClient); - } - break; case ClientPacketHeader.UPDATE_LOBBY: ClientReadLobby(inc); break; @@ -784,8 +778,8 @@ namespace Barotrauma.Networking Directory.CreateDirectory(ServerLog.SavePath); } - string filePath = "event_error_log_server_" + client.Name + "_" + DateTime.UtcNow.ToShortTimeString() + ".log"; - filePath = Path.Combine(ServerLog.SavePath, ToolBox.RemoveInvalidFileNameChars(filePath)); + string filePath = "event_error_log_server_" + client.Name + "_" + ToolBox.RemoveInvalidFileNameChars(DateTime.UtcNow.ToShortTimeString() + ".log"); + filePath = Path.Combine(ServerLog.SavePath, filePath); if (File.Exists(filePath)) { return; } List errorLines = new List @@ -1078,7 +1072,7 @@ namespace Barotrauma.Networking case ClientPermissions.Kick: string kickedName = inc.ReadString().ToLowerInvariant(); string kickReason = inc.ReadString(); - var kickedClient = connectedClients.Find(cl => cl != sender && cl.Name.Equals(kickedName, StringComparison.OrdinalIgnoreCase) && cl.Connection != OwnerConnection); + var kickedClient = connectedClients.Find(cl => cl != sender && cl.Name.ToLowerInvariant() == kickedName && cl.Connection != OwnerConnection); if (kickedClient != null) { Log("Client \"" + sender.Name + "\" kicked \"" + kickedClient.Name + "\".", ServerLog.MessageType.ServerMessage); @@ -1095,7 +1089,7 @@ namespace Barotrauma.Networking bool range = inc.ReadBoolean(); double durationSeconds = inc.ReadDouble(); - var bannedClient = connectedClients.Find(cl => cl != sender && cl.Name.Equals(bannedName, StringComparison.OrdinalIgnoreCase) && cl.Connection != OwnerConnection); + var bannedClient = connectedClients.Find(cl => cl != sender && cl.Name.ToLowerInvariant() == bannedName && cl.Connection != OwnerConnection); if (bannedClient != null) { Log("Client \"" + sender.Name + "\" banned \"" + bannedClient.Name + "\".", ServerLog.MessageType.ServerMessage); @@ -1154,7 +1148,7 @@ namespace Barotrauma.Networking break; case ClientPermissions.SelectMode: UInt16 modeIndex = inc.ReadUInt16(); - if (GameMain.NetLobbyScreen.GameModes[modeIndex].Identifier.Equals("multiplayercampaign", StringComparison.OrdinalIgnoreCase)) + if (GameMain.NetLobbyScreen.GameModes[modeIndex].Identifier.ToLowerInvariant() == "multiplayercampaign") { string[] saveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Multiplayer).ToArray(); for (int i = 0; i < saveFiles.Length; i++) @@ -1779,10 +1773,10 @@ namespace Barotrauma.Networking //always allow the server owner to spectate even if it's disallowed in server settings playingClients.RemoveAll(c => c.Connection == OwnerConnection && c.SpectateOnly); - if (GameMain.GameSession.GameMode.Mission != null) + if (GameMain.GameSession.GameMode.Mission != null && + GameMain.GameSession.GameMode.Mission.AssignTeamIDs(playingClients)) { - GameMain.GameSession.GameMode.Mission.AssignTeamIDs(playingClients); - teamCount = GameMain.GameSession.GameMode.Mission.TeamCount; + teamCount = 2; } else { @@ -1802,10 +1796,9 @@ namespace Barotrauma.Networking campaign.Map.SelectRandomLocation(preferUndiscovered: true); } - SendStartMessage(roundStartSeed, campaign.Map.SelectedConnection.Level.Seed, GameMain.GameSession, connectedClients, false); - GameMain.GameSession.StartRound(campaign.Map.SelectedConnection.Level, reloadSub: true, + loadSecondSub: teamCount > 1, mirrorLevel: campaign.Map.CurrentLocation != campaign.Map.SelectedConnection.Locations[0]); campaign.AssignClientCharacterInfos(connectedClients); @@ -1815,9 +1808,7 @@ namespace Barotrauma.Networking } else { - SendStartMessage(roundStartSeed, GameMain.NetLobbyScreen.LevelSeed, GameMain.GameSession, connectedClients, false); - - GameMain.GameSession.StartRound(GameMain.NetLobbyScreen.LevelSeed, serverSettings.SelectedLevelDifficulty); + GameMain.GameSession.StartRound(GameMain.NetLobbyScreen.LevelSeed, serverSettings.SelectedLevelDifficulty, teamCount > 1); Log("Game mode: " + selectedMode.Name, ServerLog.MessageType.ServerMessage); Log("Submarine: " + selectedSub.Name, ServerLog.MessageType.ServerMessage); Log("Level seed: " + GameMain.NetLobbyScreen.LevelSeed, ServerLog.MessageType.ServerMessage); @@ -1955,6 +1946,8 @@ namespace Barotrauma.Networking GameAnalyticsManager.AddDesignEvent("Traitors:" + (TraitorManager == null ? "Disabled" : "Enabled")); + SendStartMessage(roundStartSeed, Submarine.MainSub, GameMain.GameSession.GameMode.Preset, connectedClients); + yield return CoroutineStatus.Running; GameMain.GameScreen.Select(); @@ -1972,34 +1965,35 @@ namespace Barotrauma.Networking yield return CoroutineStatus.Success; } - private void SendStartMessage(int seed, string levelSeed, GameSession gameSession, List clients, bool includesFinalize) + private void SendStartMessage(int seed, Submarine selectedSub, GameModePreset selectedMode, List clients) { foreach (Client client in clients) { - SendStartMessage(seed, levelSeed, gameSession, client, includesFinalize); + SendStartMessage(seed, selectedSub, selectedMode, client); } } - private void SendStartMessage(int seed, string levelSeed, GameSession gameSession, Client client, bool includesFinalize) + private void SendStartMessage(int seed, Submarine selectedSub, GameModePreset selectedMode, Client client) { IWriteMessage msg = new WriteOnlyMessage(); msg.Write((byte)ServerPacketHeader.STARTGAME); msg.Write(seed); - msg.Write(levelSeed); + msg.Write(GameMain.GameSession.Level.Seed); + msg.Write(GameMain.GameSession.Level.EqualityCheckVal); msg.Write(serverSettings.SelectedLevelDifficulty); msg.Write((byte)GameMain.Config.LosMode); msg.Write((byte)GameMain.NetLobbyScreen.MissionType); - msg.Write(gameSession.Submarine.Name); - msg.Write(gameSession.Submarine.MD5Hash.Hash); + msg.Write(selectedSub.Name); + msg.Write(selectedSub.MD5Hash.Hash); msg.Write(serverSettings.UseRespawnShuttle); msg.Write(GameMain.NetLobbyScreen.SelectedShuttle.Name); msg.Write(GameMain.NetLobbyScreen.SelectedShuttle.MD5Hash.Hash); - msg.Write(gameSession.GameMode.Preset.Identifier); + msg.Write(selectedMode.Identifier); msg.Write((short)(GameMain.GameSession.GameMode?.Mission == null ? -1 : MissionPrefab.List.IndexOf(GameMain.GameSession.GameMode.Mission.Prefab))); @@ -2008,43 +2002,13 @@ namespace Barotrauma.Networking MissionMode missionMode = GameMain.GameSession.GameMode as MissionMode; bool missionAllowRespawn = campaign == null && (missionMode?.Mission == null || missionMode.Mission.AllowRespawn); msg.Write(serverSettings.AllowRespawn && missionAllowRespawn); + msg.Write(Submarine.MainSubs[1] != null); //loadSecondSub msg.Write(serverSettings.AllowDisguises); msg.Write(serverSettings.AllowRewiring); msg.Write(serverSettings.AllowRagdollButton); - serverSettings.WriteMonsterEnabled(msg); - - msg.Write(includesFinalize); msg.WritePadBits(); - if (includesFinalize) - { - WriteRoundStartFinalize(msg, client); - } - - serverPeer.Send(msg, client.Connection, DeliveryMethod.Reliable); - } - - private void SendRoundStartFinalize(List clients) - { - foreach (Client client in clients) - { - SendRoundStartFinalize(client); - } - } - - private void SendRoundStartFinalize(Client client) - { - IWriteMessage msg = new WriteOnlyMessage(); - msg.Write((byte)ServerPacketHeader.STARTGAMEFINALIZE); - - WriteRoundStartFinalize(msg, client); - - serverPeer.Send(msg, client.Connection, DeliveryMethod.Reliable); - } - - private void WriteRoundStartFinalize(IWriteMessage msg, Client client) - { //tell the client what content files they should preload var contentToPreload = GameMain.GameSession.EventManager.GetFilesToPreload(); msg.Write((ushort)contentToPreload.Count()); @@ -2054,8 +2018,11 @@ namespace Barotrauma.Networking msg.Write(contentFile.Path); } - msg.Write(GameMain.GameSession.Level.EqualityCheckVal); + serverSettings.WriteMonsterEnabled(msg); + GameMain.GameSession.Mission?.ServerWriteInitial(msg, client); + + serverPeer.Send(msg, client.Connection, DeliveryMethod.Reliable); } public void EndGame() @@ -2203,9 +2170,11 @@ namespace Barotrauma.Networking public override void KickPlayer(string playerName, string reason) { + playerName = playerName.ToLowerInvariant(); + Client client = connectedClients.Find(c => - c.Name.Equals(playerName, StringComparison.OrdinalIgnoreCase) || - (c.Character != null && c.Character.Name.Equals(playerName, StringComparison.OrdinalIgnoreCase))); + c.Name.ToLowerInvariant() == playerName || + (c.Character != null && c.Character.Name.ToLowerInvariant() == playerName)); KickClient(client, reason); } @@ -2239,9 +2208,11 @@ namespace Barotrauma.Networking public override void BanPlayer(string playerName, string reason, bool range = false, TimeSpan? duration = null) { + playerName = playerName.ToLowerInvariant(); + Client client = connectedClients.Find(c => - c.Name.Equals(playerName, StringComparison.OrdinalIgnoreCase) || - (c.Character != null && c.Character.Name.Equals(playerName, StringComparison.OrdinalIgnoreCase))); + c.Name.ToLowerInvariant() == playerName || + (c.Character != null && c.Character.Name.ToLowerInvariant() == playerName)); if (client == null) { diff --git a/Barotrauma/BarotraumaServer/ServerSource/Networking/RespawnManager.cs b/Barotrauma/BarotraumaServer/ServerSource/Networking/RespawnManager.cs index 8a12853f7..d1a158d2e 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Networking/RespawnManager.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Networking/RespawnManager.cs @@ -258,9 +258,6 @@ namespace Barotrauma.Networking { bool bot = i >= clients.Count; - characterInfos[i].CurrentOrder = null; - characterInfos[i].CurrentOrderOption = null; - var character = Character.Create(characterInfos[i], shuttleSpawnPoints[i].WorldPosition, characterInfos[i].Name, !bot, bot); character.TeamID = Character.TeamType.Team1; diff --git a/Barotrauma/BarotraumaServer/ServerSource/Networking/ServerSettings.cs b/Barotrauma/BarotraumaServer/ServerSource/Networking/ServerSettings.cs index b92cc8ea1..77b9c4c1e 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Networking/ServerSettings.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Networking/ServerSettings.cs @@ -367,7 +367,7 @@ namespace Barotrauma.Networking if (clientElement.Attribute("preset") == null) { string permissionsStr = clientElement.GetAttributeString("permissions", ""); - if (permissionsStr.Equals("all", StringComparison.OrdinalIgnoreCase)) + if (permissionsStr.ToLowerInvariant() == "all") { foreach (ClientPermissions permission in Enum.GetValues(typeof(ClientPermissions))) { @@ -384,7 +384,7 @@ namespace Barotrauma.Networking { foreach (XElement commandElement in clientElement.Elements()) { - if (!commandElement.Name.ToString().Equals("command", StringComparison.OrdinalIgnoreCase)) { continue; } + if (commandElement.Name.ToString().ToLowerInvariant() != "command") continue; string commandName = commandElement.GetAttributeString("name", ""); DebugConsole.Command command = DebugConsole.FindCommand(commandName); diff --git a/Barotrauma/BarotraumaServer/ServerSource/Traitors/Goals/GoalEntityTransformation.cs b/Barotrauma/BarotraumaServer/ServerSource/Traitors/Goals/GoalEntityTransformation.cs index 5bfff56a5..2472d685f 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Traitors/Goals/GoalEntityTransformation.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Traitors/Goals/GoalEntityTransformation.cs @@ -67,7 +67,7 @@ namespace Barotrauma { continue; } - if (character.SpeciesName.Equals(entities[activeEntityIndex], StringComparison.OrdinalIgnoreCase) && Vector2.Distance(activeEntitySavedPosition, character.WorldPosition) < graceDistance) + if (character.SpeciesName.ToLowerInvariant() == entities[activeEntityIndex] && Vector2.Distance(activeEntitySavedPosition, character.WorldPosition) < graceDistance) { activeEntity = character; transformationTime = 0.0; @@ -117,7 +117,7 @@ namespace Barotrauma { continue; } - if (character.SpeciesName.Equals(entities[activeEntityIndex], StringComparison.OrdinalIgnoreCase)) + if (character.SpeciesName.ToLowerInvariant() == entities[activeEntityIndex].ToLowerInvariant()) { activeEntity = character; break; @@ -131,7 +131,7 @@ namespace Barotrauma { continue; } - if (item.prefab.Identifier.Equals(entities[0], StringComparison.OrdinalIgnoreCase)) + if (item.prefab.Identifier.ToLowerInvariant() == entities[0].ToLowerInvariant()) { activeEntity = item; break; diff --git a/Barotrauma/BarotraumaServer/ServerSource/Traitors/Goals/GoalKeepTransformedAlive.cs b/Barotrauma/BarotraumaServer/ServerSource/Traitors/Goals/GoalKeepTransformedAlive.cs index 8d4500fa8..6e40f2681 100644 --- a/Barotrauma/BarotraumaServer/ServerSource/Traitors/Goals/GoalKeepTransformedAlive.cs +++ b/Barotrauma/BarotraumaServer/ServerSource/Traitors/Goals/GoalKeepTransformedAlive.cs @@ -52,7 +52,7 @@ namespace Barotrauma { continue; } - if (character.SpeciesName.Equals(speciesId, StringComparison.OrdinalIgnoreCase)) + if (character.SpeciesName.ToLowerInvariant() == speciesId) { targetCharacter = character; break; diff --git a/Barotrauma/BarotraumaServer/WindowsServer.csproj b/Barotrauma/BarotraumaServer/WindowsServer.csproj index e798bf5cf..53ebc9350 100644 --- a/Barotrauma/BarotraumaServer/WindowsServer.csproj +++ b/Barotrauma/BarotraumaServer/WindowsServer.csproj @@ -6,7 +6,7 @@ Barotrauma FakeFish, Undertow Games Barotrauma Dedicated Server - 0.9.7.0 + 0.9.7.1 Copyright © FakeFish 2018-2020 AnyCPU;x64 DedicatedServer diff --git a/Barotrauma/BarotraumaShared/.gitignore b/Barotrauma/BarotraumaShared/.gitignore new file mode 100644 index 000000000..a2c944923 --- /dev/null +++ b/Barotrauma/BarotraumaShared/.gitignore @@ -0,0 +1 @@ +Content/* diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/AITarget.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/AITarget.cs index ae2b245fe..4f25f046e 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/AITarget.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/AITarget.cs @@ -25,7 +25,7 @@ namespace Barotrauma /// /// How long does it take for the ai target to fade out if not kept alive. /// - public float FadeOutTime { get; private set; } = 2; + public float FadeOutTime { get; private set; } = 1; public bool Static { get; private set; } public bool StaticSound { get; private set; } @@ -92,7 +92,7 @@ namespace Barotrauma public string SonarLabel; public string SonarIconIdentifier; - public bool Enabled => SoundRange > 0 || SightRange > 0; + public bool Enabled = true; public float MinSoundRange, MinSightRange; public float MaxSoundRange = 100000, MaxSightRange = 100000; @@ -195,7 +195,7 @@ namespace Barotrauma public void Update(float deltaTime) { - if (Enabled && !Static && FadeOutTime > 0) + if (!Static && FadeOutTime > 0) { // The aitarget goes silent/invisible if the components don't keep it active if (!StaticSight) diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/EnemyAIController.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/EnemyAIController.cs index 2a39dee6d..44bfc5ad5 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/EnemyAIController.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/EnemyAIController.cs @@ -1017,63 +1017,58 @@ namespace Barotrauma return; } - if (AttackingLimb != null && AttackingLimb.attack.Retreat) + Vector2 offset = Character.SimPosition - steeringLimb.SimPosition; + // Offset so that we don't overshoot the movement + Vector2 steerPos = attackSimPos + offset; + + if (SteeringManager is IndoorsSteeringManager pathSteering) { - UpdateFallBack(attackWorldPos, deltaTime, false); - } - else - { - Vector2 offset = Character.SimPosition - steeringLimb.SimPosition; - // Offset so that we don't overshoot the movement - Vector2 steerPos = attackSimPos + offset; - if (SteeringManager is IndoorsSteeringManager pathSteering) + if (pathSteering.CurrentPath != null) { - if (pathSteering.CurrentPath != null) + // Attack doors + if (canAttackSub) { - // Attack doors - if (canAttackSub) + // If the target is in the same hull, there shouldn't be any doors blocking the path + if (targetCharacter == null || targetCharacter.CurrentHull != Character.CurrentHull) { - // If the target is in the same hull, there shouldn't be any doors blocking the path - if (targetCharacter == null || targetCharacter.CurrentHull != Character.CurrentHull) + var door = pathSteering.CurrentPath.CurrentNode?.ConnectedDoor ?? pathSteering.CurrentPath.NextNode?.ConnectedDoor; + if (door != null && !door.IsOpen) { - var door = pathSteering.CurrentPath.CurrentNode?.ConnectedDoor ?? pathSteering.CurrentPath.NextNode?.ConnectedDoor; - if (door != null && !door.IsOpen) + if (door.Item.AiTarget != null && SelectedAiTarget != door.Item.AiTarget) { - if (door.Item.AiTarget != null && SelectedAiTarget != door.Item.AiTarget) - { - SelectTarget(door.Item.AiTarget, selectedTargetMemory.Priority); - return; - } + SelectTarget(door.Item.AiTarget, selectedTargetMemory.Priority); + return; } } } - // Steer towards the target if in the same room and swimming - if ((Character.AnimController.InWater || pursue) && targetCharacter != null && VisibleHulls.Contains(targetCharacter.CurrentHull)) - { - SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(attackSimPos - steeringLimb.SimPosition)); - } - else - { - SteeringManager.SteeringSeek(steerPos, 2); - // Switch to Idle when cannot reach the target and if cannot damage the walls - if ((!canAttackSub || wallTarget == null) && !pathSteering.IsPathDirty && pathSteering.CurrentPath.Unreachable) - { - State = AIState.Idle; - return; - } - } + } + // Steer towards the target if in the same room and swimming + if ((Character.AnimController.InWater || pursue) && targetCharacter != null && VisibleHulls.Contains(targetCharacter.CurrentHull)) + { + SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(attackSimPos - steeringLimb.SimPosition)); } else { - SteeringManager.SteeringSeek(steerPos, 5); + SteeringManager.SteeringSeek(steerPos, 2); + // Switch to Idle when cannot reach the target and if cannot damage the walls + if ((!canAttackSub || wallTarget == null) && !pathSteering.IsPathDirty && pathSteering.CurrentPath.Unreachable) + { + State = AIState.Idle; + return; + } } } else { - SteeringManager.SteeringSeek(steerPos, 10); - SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: avoidLookAheadDistance, weight: 15); + SteeringManager.SteeringSeek(steerPos, 5); } } + else + { + SteeringManager.SteeringSeek(steerPos, 10); + SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: avoidLookAheadDistance, weight: 15); + } + if (canAttack) { if (!UpdateLimbAttack(deltaTime, AttackingLimb, attackSimPos, distance, attackTargetLimb)) @@ -1277,9 +1272,12 @@ namespace Barotrauma if (attackResult.Damage > 0.0f) { bool canAttack = attacker.Submarine == Character.Submarine && canAttackCharacters || attacker.Submarine != null && canAttackSub; - if (Character.Params.AI.AttackWhenProvoked && canAttack) + if (Character.Params.AI.AttackWhenProvoked) { - ChangeTargetState(attacker, AIState.Attack, 100); + if (canAttack) + { + ChangeTargetState(attacker, AIState.Attack, 100); + } } else if (!AIParams.HasTag(attacker.SpeciesName)) { @@ -1289,14 +1287,14 @@ namespace Barotrauma { if (!AIParams.HasTag("stronger")) { - ChangeTargetState(attacker, canAttack ? AIState.PassiveAggressive : AIState.Escape, 100); + ChangeTargetState(attacker, AIState.Escape, 100); } } else if (enemyAI.CombatStrength < CombatStrength) { if (!AIParams.HasTag("weaker")) { - ChangeTargetState(attacker, canAttack ? AIState.PassiveAggressive : AIState.Escape, 100); + ChangeTargetState(attacker, canAttack ? AIState.Attack : AIState.Escape, 100); } } else @@ -1307,7 +1305,7 @@ namespace Barotrauma } else { - ChangeTargetState(attacker, canAttack ? AIState.PassiveAggressive : AIState.Escape, 100); + ChangeTargetState(attacker, AIState.Escape, 100); } } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/HumanAIController.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/HumanAIController.cs index 1d168f138..0d685c7cc 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/HumanAIController.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/HumanAIController.cs @@ -323,7 +323,7 @@ namespace Barotrauma || ObjectiveManager.IsCurrentObjective() || ObjectiveManager.CurrentObjective.GetSubObjectivesRecursive(true).Any(o => o.KeepDivingGearOn); bool removeDivingSuit = !Character.AnimController.HeadInWater && oxygenLow; - AIObjectiveGoTo gotoObjective = ObjectiveManager.GetActiveObjective(); + AIObjectiveGoTo gotoObjective = ObjectiveManager.CurrentOrder as AIObjectiveGoTo; if (!removeDivingSuit) { bool targetHasNoSuit = gotoObjective != null && gotoObjective.mimic && !HasDivingSuit(gotoObjective.Target as Character); @@ -536,16 +536,14 @@ namespace Barotrauma Hull targetHull = null; if (Character.CurrentHull != null) { - bool isFighting = ObjectiveManager.HasActiveObjective(); - bool isFleeing = ObjectiveManager.HasActiveObjective(); foreach (var hull in VisibleHulls) { - foreach (Character target in Character.CharacterList) + foreach (Character c in Character.CharacterList) { - if (target.CurrentHull != hull || !target.Enabled) { continue; } - if (AIObjectiveFightIntruders.IsValidTarget(target, Character)) + if (c.CurrentHull != hull || !c.Enabled) { continue; } + if (AIObjectiveFightIntruders.IsValidTarget(c, Character)) { - if (AddTargets(Character, target) && newOrder == null) + if (AddTargets(Character, c) && newOrder == null) { var orderPrefab = Order.GetPrefab("reportintruders"); newOrder = new Order(orderPrefab, hull, null, orderGiver: Character); @@ -562,48 +560,42 @@ namespace Barotrauma targetHull = hull; } } - if (!isFighting) + foreach (Character c in Character.CharacterList) { - foreach (var gap in hull.ConnectedGaps) + if (c.CurrentHull != hull) { continue; } + if (AIObjectiveRescueAll.IsValidTarget(c, Character)) { - if (AIObjectiveFixLeaks.IsValidTarget(gap, Character)) + if (AddTargets(c, Character) && newOrder == null && !ObjectiveManager.HasActiveObjective()) { - if (AddTargets(Character, gap) && newOrder == null && !gap.IsRoomToRoom) - { - var orderPrefab = Order.GetPrefab("reportbreach"); - newOrder = new Order(orderPrefab, hull, null, orderGiver: Character); - targetHull = hull; - } + var orderPrefab = Order.GetPrefab("requestfirstaid"); + newOrder = new Order(orderPrefab, hull, null, orderGiver: Character); + targetHull = hull; } } - if (!isFleeing) + } + foreach (var gap in hull.ConnectedGaps) + { + if (AIObjectiveFixLeaks.IsValidTarget(gap, Character)) { - foreach (Character target in Character.CharacterList) + if (AddTargets(Character, gap) && newOrder == null && !gap.IsRoomToRoom) { - if (target.CurrentHull != hull) { continue; } - if (AIObjectiveRescueAll.IsValidTarget(target, Character)) - { - if (AddTargets(Character, target) && newOrder == null && !ObjectiveManager.HasActiveObjective()) - { - var orderPrefab = Order.GetPrefab("requestfirstaid"); - newOrder = new Order(orderPrefab, hull, null, orderGiver: Character); - targetHull = hull; - } - } + var orderPrefab = Order.GetPrefab("reportbreach"); + newOrder = new Order(orderPrefab, hull, null, orderGiver: Character); + targetHull = hull; } - foreach (Item item in Item.ItemList) + } + } + foreach (Item item in Item.ItemList) + { + if (item.CurrentHull != hull) { continue; } + if (AIObjectiveRepairItems.IsValidTarget(item, Character)) + { + if (item.Repairables.All(r => item.ConditionPercentage > r.AIRepairThreshold)) { continue; } + if (AddTargets(Character, item) && newOrder == null && !ObjectiveManager.HasActiveObjective()) { - if (item.CurrentHull != hull) { continue; } - if (AIObjectiveRepairItems.IsValidTarget(item, Character)) - { - if (item.Repairables.All(r => item.ConditionPercentage > r.AIRepairThreshold)) { continue; } - if (AddTargets(Character, item) && newOrder == null && !ObjectiveManager.HasActiveObjective()) - { - var orderPrefab = Order.GetPrefab("reportbrokendevices"); - newOrder = new Order(orderPrefab, hull, item.Repairables?.FirstOrDefault(), orderGiver: Character); - targetHull = hull; - } - } + var orderPrefab = Order.GetPrefab("reportbrokendevices"); + newOrder = new Order(orderPrefab, hull, item.Repairables?.FirstOrDefault(), orderGiver: Character); + targetHull = hull; } } } @@ -658,7 +650,7 @@ namespace Barotrauma // Should not cancel any existing ai objectives (so that if the character attacked you and then helped, we still would want to retaliate). return; } - if (!attacker.IsPlayer && attacker.AIController != null && attacker.AIController.Enabled) + if (!attacker.IsRemotePlayer && Character.Controlled != attacker && attacker.AIController != null && attacker.AIController.Enabled) { // Don't retaliate on damage done by friendly ai, because we know that it's accidental AddCombatObjective(AIObjectiveCombat.CombatMode.Retreat, Rand.Range(0.5f, 1f, Rand.RandSync.Unsynced)); @@ -672,8 +664,9 @@ namespace Barotrauma } else { - float dmgPercentage = MathUtils.Percentage(damage, Character.CharacterHealth.Vitality); - if (dmgPercentage < 10) + float currentVitality = Character.CharacterHealth.Vitality; + float dmgPercentage = damage / currentVitality * 100; + if (dmgPercentage < currentVitality / 10) { // Don't retaliate on minor (accidental) dmg done by characters that are in the same team AddCombatObjective(AIObjectiveCombat.CombatMode.Retreat, Rand.Range(0.5f, 1f, Rand.RandSync.Unsynced)); @@ -718,6 +711,7 @@ namespace Barotrauma public void SetOrder(Order order, string option, Character orderGiver, bool speak = true) { + SetOrderProjSpecific(order, option); CurrentOrderOption = option; CurrentOrder = order; objectiveManager.SetOrder(order, option, orderGiver); @@ -758,6 +752,8 @@ namespace Barotrauma } } + partial void SetOrderProjSpecific(Order order, string option); + public override void SelectTarget(AITarget target) { SelectedAiTarget = target; @@ -810,11 +806,11 @@ namespace Barotrauma /// public static bool HasDivingMask(Character character, float conditionPercentage = 0) => HasItem(character, "divingmask", "oxygensource", conditionPercentage); - public static bool HasItem(Character character, string tagOrIdentifier, string containedTag = null, float conditionPercentage = 0) + public static bool HasItem(Character character, string identifier, string containedTag, float conditionPercentage = 0) { if (character == null) { return false; } if (character.Inventory == null) { return false; } - var item = character.Inventory.FindItemByIdentifier(tagOrIdentifier) ?? character.Inventory.FindItemByTag(tagOrIdentifier); + var item = character.Inventory.FindItemByIdentifier(identifier) ?? character.Inventory.FindItemByTag(identifier); return item != null && item.ConditionPercentage > conditionPercentage && character.HasEquippedItem(item) && @@ -938,7 +934,7 @@ namespace Barotrauma visibleHulls = VisibleHulls; } // TODO: should we calculate the visible hulls for each hull? -> could be a bit heavy. - bool ignoreFire = objectiveManager.HasActiveObjective(); + bool ignoreFire = ObjectiveManager.IsCurrentObjective() || objectiveManager.HasActiveObjective(); bool ignoreWater = HasDivingSuit(character); bool ignoreOxygen = ignoreWater || HasDivingMask(character); bool ignoreEnemies = ObjectiveManager.IsCurrentObjective(); @@ -1026,23 +1022,15 @@ namespace Barotrauma return false; } - public static int CountCrew(Character character, Func predicate = null, bool onlyActive = true, bool onlyBots = false) + public static int CountCrew(Character character, Func predicate = null) { if (character == null) { return 0; } int count = 0; - foreach (var other in Character.CharacterList) + foreach (var c in Character.CharacterList) { - if (onlyActive && !IsActive(other)) + if (FilterCrewMember(character, c)) { - continue; - } - if (onlyBots && other.IsPlayer) - { - continue; - } - if (FilterCrewMember(character, other)) - { - if (predicate == null || predicate(other.AIController as HumanAIController)) + if (predicate == null || predicate(c.AIController as HumanAIController)) { count++; } @@ -1070,7 +1058,7 @@ namespace Barotrauma public void DoForEachCrewMember(Action action) => DoForEachCrewMember(Character, action); public bool IsTrueForAnyCrewMember(Func predicate) => IsTrueForAnyCrewMember(Character, predicate); public bool IsTrueForAllCrewMembers(Func predicate) => IsTrueForAllCrewMembers(Character, predicate); - public int CountCrew(Func predicate = null, bool onlyActive = true, bool onlyBots = false) => CountCrew(Character, predicate, onlyActive, onlyBots); + public int CountCrew(Func predicate = null) => CountCrew(Character, predicate); #endregion } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/IndoorsSteeringManager.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/IndoorsSteeringManager.cs index 661c4b76c..e0cd0198f 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/IndoorsSteeringManager.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/IndoorsSteeringManager.cs @@ -56,7 +56,7 @@ namespace Barotrauma /// /// Returns true if any node in the path is in stairs /// - public bool PathHasStairs => currentPath != null && currentPath.Nodes.Any(n => n.Stairs != null); + public bool InStairs => currentPath != null && currentPath.Nodes.Any(n => n.Stairs != null); public bool IsNextNodeLadder => GetNextLadder() != null; @@ -134,7 +134,7 @@ namespace Barotrauma private Vector2 CalculateSteeringSeek(Vector2 target, float weight, Func startNodeFilter = null, Func endNodeFilter = null, Func nodeFilter = null) { - bool needsNewPath = character.Params.PathFinderPriority > 0.5f && (currentPath == null || currentPath.Unreachable || currentPath.Finished || Vector2.DistanceSquared(target, currentTarget) > 1); + bool needsNewPath = character.Params.PathFinderPriority > 0.5f && (currentPath == null || currentPath.Unreachable || currentPath.NextNode == null || Vector2.DistanceSquared(target, currentTarget) > 1); //find a new path if one hasn't been found yet or the target is different from the current target if (needsNewPath || findPathTimer < -1.0f) { @@ -308,7 +308,7 @@ namespace Barotrauma currentPath.SkipToNextNode(); } } - else if (!IsNextLadderSameAsCurrent) + else { Vector2 colliderBottom = character.AnimController.GetColliderBottom(); Vector2 colliderSize = collider.GetSize(); @@ -530,6 +530,7 @@ namespace Barotrauma if (node.Waypoint != null && node.Waypoint.CurrentHull != null) { var hull = node.Waypoint.CurrentHull; + if (hull.FireSources.Count > 0) { foreach (FireSource fs in hull.FireSources) @@ -537,14 +538,9 @@ namespace Barotrauma penalty += fs.Size.X * 10.0f; } } - if (character.NeedsAir && hull.WaterVolume / hull.Rect.Width > 100.0f) - { - penalty += 500.0f; - } - if (character.PressureProtection < 10.0f && hull.WaterVolume > hull.Volume) - { - penalty += 1000.0f; - } + + if (character.NeedsAir && hull.WaterVolume / hull.Rect.Width > 100.0f) penalty += 500.0f; + if (character.PressureProtection < 10.0f && hull.WaterVolume > hull.Volume) penalty += 1000.0f; } return penalty; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/NPCConversation.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/NPCConversation.cs index c5ab0ea33..ece8f6cf3 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/NPCConversation.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/NPCConversation.cs @@ -136,10 +136,9 @@ namespace Barotrauma string allowedJobsStr = element.GetAttributeString("allowedjobs", ""); foreach (string allowedJobIdentifier in allowedJobsStr.Split(',')) { - string key = allowedJobIdentifier.ToLowerInvariant(); - if (JobPrefab.Prefabs.ContainsKey(key)) + if (JobPrefab.Prefabs.ContainsKey(allowedJobIdentifier.ToLowerInvariant())) { - AllowedJobs.Add(JobPrefab.Prefabs[key]); + AllowedJobs.Add(JobPrefab.Prefabs[allowedJobIdentifier.ToLowerInvariant()]); } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjective.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjective.cs index 581ef4f49..c71d9043d 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjective.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjective.cs @@ -32,18 +32,6 @@ namespace Barotrauma public virtual bool UnequipItems => false; protected readonly List subObjectives = new List(); - private float _cumulatedDevotion; - protected float CumulatedDevotion - { - get { return _cumulatedDevotion; } - set { _cumulatedDevotion = MathHelper.Clamp(value, 0, MaxDevotion); } - } - - protected virtual float MaxDevotion => 10; - - /// - /// Final priority value after all calculations. - /// public float Priority { get; set; } public float PriorityModifier { get; private set; } = 1; public readonly Character character; @@ -71,7 +59,6 @@ namespace Barotrauma /// public virtual bool IsLoop { get; set; } public IEnumerable SubObjectives => subObjectives; - public AIObjective CurrentSubObjective => subObjectives.FirstOrDefault(); private readonly List all = new List(); public IEnumerable GetSubObjectivesRecursive(bool includingSelf = false) @@ -99,7 +86,7 @@ namespace Barotrauma public AIObjective GetActiveObjective() { - var subObjective = CurrentSubObjective; + var subObjective = SubObjectives.FirstOrDefault(); return subObjective == null ? this : subObjective.GetActiveObjective(); } @@ -170,8 +157,7 @@ namespace Barotrauma { if (!AllowSubObjectiveSorting) { return; } if (subObjectives.None()) { return; } - subObjectives.ForEach(so => so.GetPriority()); - subObjectives.Sort((x, y) => y.Priority.CompareTo(x.Priority)); + subObjectives.Sort((x, y) => y.GetPriority().CompareTo(x.GetPriority())); if (ConcurrentObjectives) { subObjectives.ForEach(so => so.SortSubObjectives()); @@ -182,23 +168,7 @@ namespace Barotrauma } } - /// - /// Call this only when the priority needs to be recalculated. Use the cached Priority property when you don't need to recalculate. - /// - public virtual float GetPriority() - { - Priority = CumulatedDevotion * PriorityModifier; - return Priority; - } - - private void UpdateDevotion(float deltaTime) - { - var currentObjective = objectiveManager.CurrentObjective; - if (currentObjective != null && (currentObjective == this || currentObjective.subObjectives.Any(so => so == this))) - { - CumulatedDevotion += Devotion * PriorityModifier * deltaTime; - } - } + public virtual float GetPriority() => Priority * PriorityModifier; public virtual bool IsDuplicate(T otherObjective) where T : AIObjective => otherObjective.Option == Option; @@ -210,7 +180,14 @@ namespace Barotrauma } else if (objectiveManager.WaitTimer <= 0) { - UpdateDevotion(deltaTime); + if (objectiveManager.CurrentObjective != null) + { + if (objectiveManager.CurrentObjective == this || objectiveManager.CurrentObjective.subObjectives.Any(so => so == this)) + { + Priority += Devotion * PriorityModifier * deltaTime; + } + } + Priority = MathHelper.Clamp(Priority, 0, 100); } subObjectives.ForEach(so => so.Update(deltaTime)); } @@ -287,7 +264,6 @@ namespace Barotrauma public virtual void OnDeselected() { - CumulatedDevotion = 0; Deselected?.Invoke(); } @@ -306,7 +282,6 @@ namespace Barotrauma isCompleted = false; hasBeenChecked = false; _abandon = false; - CumulatedDevotion = 0; } protected abstract void Act(float deltaTime); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveCombat.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveCombat.cs index 82b80055c..aff1bf4b7 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveCombat.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveCombat.cs @@ -100,11 +100,7 @@ namespace Barotrauma } } - public override float GetPriority() - { - Priority = (Enemy != null && (Enemy.Removed || Enemy.IsDead)) ? 0 : Math.Min(100 * PriorityModifier, 100); - return Priority; - } + public override float GetPriority() => (Enemy != null && (Enemy.Removed || Enemy.IsDead)) ? 0 : Math.Min(100 * PriorityModifier, 100); public override void Update(float deltaTime) { @@ -143,7 +139,7 @@ namespace Barotrauma } if (seekAmmunition == null) { - if (Mode != CombatMode.Retreat && TryArm() && Enemy != null && !Enemy.Removed) + if (TryArm() && Enemy != null && !Enemy.Removed) { OperateWeapon(deltaTime); } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveContainItem.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveContainItem.cs index a77455b67..15959d86f 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveContainItem.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveContainItem.cs @@ -74,6 +74,15 @@ namespace Barotrauma } } + public override float GetPriority() + { + if (objectiveManager.CurrentOrder == this) + { + return AIObjectiveManager.OrderPriority; + } + return 1.0f; + } + private bool CheckItem(Item i) => itemIdentifiers.Any(id => i.Prefab.Identifier == id || i.HasTag(id)) && i.ConditionPercentage > ConditionLevel; protected override void Act(float deltaTime) diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveDecontainItem.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveDecontainItem.cs index f13e6e548..63a86fea7 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveDecontainItem.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveDecontainItem.cs @@ -54,6 +54,15 @@ namespace Barotrauma protected override bool Check() => IsCompleted; + public override float GetPriority() + { + if (objectiveManager.CurrentOrder == this) + { + return AIObjectiveManager.OrderPriority; + } + return 1.0f; + } + protected override void Act(float deltaTime) { Item itemToDecontain = targetItem ?? sourceContainer.Inventory.FindItem(i => itemIdentifiers.Any(id => i.Prefab.Identifier == id || i.HasTag(id)), recursive: false); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveExtinguishFire.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveExtinguishFire.cs index 8ccdf33c8..9dcb5c3a6 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveExtinguishFire.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveExtinguishFire.cs @@ -1,4 +1,5 @@ using Barotrauma.Items.Components; +using FarseerPhysics; using Microsoft.Xna.Framework; using System; using System.Linq; @@ -28,44 +29,32 @@ namespace Barotrauma public override float GetPriority() { if (!objectiveManager.IsCurrentOrder() - && Character.CharacterList.Any(c => c.CurrentHull == targetHull && !HumanAIController.IsFriendly(c) && HumanAIController.IsActive(c))) + && Character.CharacterList.Any(c => c.CurrentHull == targetHull && !HumanAIController.IsFriendly(c) && HumanAIController.IsActive(c))) { return 0; } + float yDist = Math.Abs(character.WorldPosition.Y - targetHull.WorldPosition.Y); + yDist = yDist > 100 ? yDist * 3 : 0; + float dist = Math.Abs(character.WorldPosition.X - targetHull.WorldPosition.X) + yDist; + float distanceFactor = MathHelper.Lerp(1, 0.1f, MathUtils.InverseLerp(0, 5000, dist)); + if (targetHull == character.CurrentHull) { - Priority = 0; + distanceFactor = 1; } - else - { - float yDist = Math.Abs(character.WorldPosition.Y - targetHull.WorldPosition.Y); - yDist = yDist > 100 ? yDist * 3 : 0; - float dist = Math.Abs(character.WorldPosition.X - targetHull.WorldPosition.X) + yDist; - float distanceFactor = MathHelper.Lerp(1, 0.1f, MathUtils.InverseLerp(0, 5000, dist)); - if (targetHull == character.CurrentHull) - { - distanceFactor = 1; - } - float severity = AIObjectiveExtinguishFires.GetFireSeverity(targetHull); - float severityFactor = MathHelper.Lerp(0, 1, severity / 100); - float devotion = CumulatedDevotion / 100; - Priority = MathHelper.Lerp(0, 100, MathHelper.Clamp(devotion + (severityFactor * distanceFactor * PriorityModifier), 0, 1)); - } - return Priority; + float severity = AIObjectiveExtinguishFires.GetFireSeverity(targetHull); + float severityFactor = MathHelper.Lerp(0, 1, severity / 100); + float devotion = Math.Min(Priority, 10) / 100; + return MathHelper.Lerp(0, 100, MathHelper.Clamp(devotion + severityFactor * distanceFactor, 0, 1)); } protected override bool Check() => targetHull.FireSources.None(); - private float sinTime; protected override void Act(float deltaTime) { - var extinguisherItem = character.Inventory.FindItemByIdentifier("fireextinguisher") ?? character.Inventory.FindItemByTag("fireextinguisher"); + var extinguisherItem = character.Inventory.FindItemByIdentifier("extinguisher") ?? character.Inventory.FindItemByTag("extinguisher"); if (extinguisherItem == null || extinguisherItem.Condition <= 0.0f || !character.HasEquippedItem(extinguisherItem)) { TryAddSubObjective(ref getExtinguisherObjective, () => { character.Speak(TextManager.Get("DialogFindExtinguisher"), null, 2.0f, "findextinguisher", 30.0f); - return new AIObjectiveGetItem(character, "fireextinguisher", objectiveManager, equip: true) - { - // If the item is inside an unsafe hull, decrease the priority - GetItemPriority = i => HumanAIController.UnsafeHulls.Contains(i.CurrentHull) ? 0.1f : 1 - }; + return new AIObjectiveGetItem(character, "extinguisher", objectiveManager, equip: true); }); } else @@ -90,12 +79,8 @@ namespace Barotrauma { useExtinquisherTimer = 0.0f; } - // Aim character.CursorPosition = fs.Position; - Vector2 fromCharacterToFireSource = fs.WorldPosition - character.WorldPosition; - float dist = fromCharacterToFireSource.Length(); - character.CursorPosition += VectorExtensions.Forward(extinguisherItem.body.TransformedRotation + (float)Math.Sin(sinTime) / 2, dist / 2); - if (extinguisherItem.RequireAimToUse) + if (extinguisher.Item.RequireAimToUse) { bool isOperatingButtons = false; if (SteeringManager == PathSteering) @@ -110,9 +95,8 @@ namespace Barotrauma { character.SetInput(InputType.Aim, false, true); } - sinTime += deltaTime * 10; } - character.SetInput(extinguisherItem.IsShootable ? InputType.Shoot : InputType.Use, false, true); + character.SetInput(extinguisher.Item.IsShootable ? InputType.Shoot : InputType.Use, false, true); extinguisher.Use(deltaTime, character); if (!targetHull.FireSources.Contains(fs)) { @@ -126,7 +110,7 @@ namespace Barotrauma if (move) { //go to the first firesource - TryAddSubObjective(ref gotoObjective, () => new AIObjectiveGoTo(fs, character, objectiveManager, closeEnough: extinguisher.Range / 2) + TryAddSubObjective(ref gotoObjective, () => new AIObjectiveGoTo(fs, character, objectiveManager) { DialogueIdentifier = "dialogcannotreachfire", TargetName = fs.Hull.DisplayName diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveExtinguishFires.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveExtinguishFires.cs index fd6bc49ce..f5142278c 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveExtinguishFires.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveExtinguishFires.cs @@ -9,6 +9,7 @@ namespace Barotrauma { public override string DebugTag => "extinguish fires"; public override bool ForceRun => true; + public override bool IgnoreUnsafeHulls => true; public AIObjectiveExtinguishFires(Character character, AIObjectiveManager objectiveManager, float priorityModifier = 1) : base(character, objectiveManager, priorityModifier) { } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFindDivingGear.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFindDivingGear.cs index 9b851aefb..c41580047 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFindDivingGear.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFindDivingGear.cs @@ -9,6 +9,7 @@ namespace Barotrauma public override string DebugTag => $"find diving gear ({gearTag})"; public override bool ForceRun => true; public override bool KeepDivingGearOn => true; + public override bool IgnoreUnsafeHulls => true; private readonly string gearTag; private readonly string fallbackTag; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFindSafety.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFindSafety.cs index 63eb1372b..1676bffc4 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFindSafety.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFindSafety.cs @@ -33,8 +33,6 @@ namespace Barotrauma private bool resetPriority; - public override float GetPriority() => Priority; - public override void Update(float deltaTime) { if (resetPriority) @@ -254,7 +252,7 @@ namespace Barotrauma else { // Outside - if (hull.RoomName != null && hull.RoomName.Contains("airlock", StringComparison.OrdinalIgnoreCase)) + if (hull.RoomName != null && hull.RoomName.ToLowerInvariant().Contains("airlock")) { hullSafety = 100; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFixLeak.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFixLeak.cs index 4121ccdce..9467b940c 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFixLeak.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFixLeak.cs @@ -29,23 +29,16 @@ namespace Barotrauma public override float GetPriority() { - if (Leak.Removed || Leak.Open <= 0) - { - Priority = 0; - } - else - { - float xDist = Math.Abs(character.WorldPosition.X - Leak.WorldPosition.X); - float yDist = Math.Abs(character.WorldPosition.Y - Leak.WorldPosition.Y); - // Vertical distance matters more than horizontal (climbing up/down is harder than moving horizontally). - // If the target is close, ignore the distance factor alltogether so that we keep fixing the leaks that are nearby. - float distanceFactor = xDist < 200 && yDist < 100 ? 1 : MathHelper.Lerp(1, 0.1f, MathUtils.InverseLerp(0, 5000, xDist + yDist * 3.0f)); - float severity = AIObjectiveFixLeaks.GetLeakSeverity(Leak) / 100; - float max = Math.Min((AIObjectiveManager.OrderPriority - 1), 90); - float devotion = CumulatedDevotion / 100; - Priority = MathHelper.Lerp(0, max, MathHelper.Clamp(devotion + (severity * distanceFactor * PriorityModifier), 0, 1)); - } - return Priority; + if (Leak.Removed || Leak.Open <= 0) { return 0; } + float xDist = Math.Abs(character.WorldPosition.X - Leak.WorldPosition.X); + float yDist = Math.Abs(character.WorldPosition.Y - Leak.WorldPosition.Y); + // Vertical distance matters more than horizontal (climbing up/down is harder than moving horizontally). + // If the target is close, ignore the distance factor alltogether so that we keep fixing the leaks that are nearby. + float distanceFactor = xDist < 200 && yDist < 100 ? 1 : MathHelper.Lerp(1, 0.1f, MathUtils.InverseLerp(0, 5000, xDist + yDist * 3.0f)); + float severity = AIObjectiveFixLeaks.GetLeakSeverity(Leak) / 100; + float max = Math.Min((AIObjectiveManager.OrderPriority - 1), 90); + float devotion = Math.Min(Priority, 10) / 100; + return MathHelper.Lerp(0, max, MathHelper.Clamp(devotion + severity * distanceFactor * PriorityModifier, 0, 1)); } protected override void Act(float deltaTime) diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFixLeaks.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFixLeaks.cs index 659958632..5e35d9135 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFixLeaks.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveFixLeaks.cs @@ -11,6 +11,7 @@ namespace Barotrauma public override string DebugTag => "fix leaks"; public override bool ForceRun => true; public override bool KeepDivingGearOn => true; + public override bool IgnoreUnsafeHulls => true; public AIObjectiveFixLeaks(Character character, AIObjectiveManager objectiveManager, float priorityModifier = 1) : base(character, objectiveManager, priorityModifier) { } @@ -35,7 +36,7 @@ namespace Barotrauma protected override float TargetEvaluation() { - int otherFixers = HumanAIController.CountCrew(c => c != HumanAIController && c.ObjectiveManager.IsCurrentObjective(), onlyBots: true); + int otherFixers = HumanAIController.CountCrew(c => c != HumanAIController && c.ObjectiveManager.IsCurrentObjective()); int totalLeaks = Targets.Count(); if (totalLeaks == 0) { return 0; } int secondaryLeaks = Targets.Count(l => l.IsRoomToRoom); @@ -43,13 +44,13 @@ namespace Barotrauma bool anyFixers = otherFixers > 0; if (objectiveManager.CurrentOrder == this) { - float ratio = anyFixers ? totalLeaks / (float)otherFixers : 1; + float ratio = anyFixers ? totalLeaks / otherFixers : 1; return Targets.Sum(t => GetLeakSeverity(t)) * ratio; } else { float ratio = leaks == 0 ? 1 : anyFixers ? leaks / otherFixers : 1; - if (anyFixers && (ratio <= 1 || otherFixers > 5 || otherFixers / (float)HumanAIController.CountCrew(onlyBots: true) > 0.75f)) + if (anyFixers && (ratio <= 1 || otherFixers > 5 || otherFixers / HumanAIController.CountCrew() > 0.75f)) { // Enough fixers return 0; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveGetItem.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveGetItem.cs index 626c49064..27950b88d 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveGetItem.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveGetItem.cs @@ -31,6 +31,15 @@ namespace Barotrauma public bool AllowToFindDivingGear { get; set; } = true; + public override float GetPriority() + { + if (objectiveManager.CurrentOrder == this) + { + return AIObjectiveManager.OrderPriority; + } + return 1.0f; + } + public AIObjectiveGetItem(Character character, Item targetItem, AIObjectiveManager objectiveManager, bool equip = true, float priorityModifier = 1) : base(character, objectiveManager, priorityModifier) { diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveGoTo.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveGoTo.cs index aa0ad824f..f76dbdd71 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveGoTo.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveGoTo.cs @@ -51,19 +51,14 @@ namespace Barotrauma public override float GetPriority() { - if (followControlledCharacter && Character.Controlled == null) + if (followControlledCharacter && Character.Controlled == null) { return 0.0f; } + if (Target is Entity e && e.Removed) { return 0.0f; } + if (IgnoreIfTargetDead && Target is Character character && character.IsDead) { return 0.0f; } + if (objectiveManager.CurrentOrder == this) { - Priority = 0; + return AIObjectiveManager.OrderPriority; } - if (Target is Entity e && e.Removed) - { - Priority = 0; - } - if (IgnoreIfTargetDead && Target is Character character && character.IsDead) - { - Priority = 0; - } - return objectiveManager.CurrentOrder == this ? AIObjectiveManager.OrderPriority : Priority; + return 1.0f; } public AIObjectiveGoTo(ISpatialEntity target, Character character, AIObjectiveManager objectiveManager, bool repeat = false, bool getDivingGearIfNeeded = true, float priorityModifier = 1, float closeEnough = 0) @@ -223,7 +218,7 @@ namespace Barotrauma if (n.Waypoint.isObstructed) { return false; } return (n.Waypoint.CurrentHull == null) == (character.CurrentHull == null); }, endNodeFilter, nodeFilter); - if (!isInside && (PathSteering.CurrentPath == null || PathSteering.IsPathDirty || PathSteering.CurrentPath.Unreachable)) + if (!isInside && PathSteering.CurrentPath == null || PathSteering.IsPathDirty || PathSteering.CurrentPath.Unreachable) { SteeringManager.SteeringManual(deltaTime, Vector2.Normalize(Target.WorldPosition - character.WorldPosition)); SteeringManager.SteeringAvoid(deltaTime, lookAheadDistance: 5, weight: 15); @@ -270,11 +265,14 @@ namespace Barotrauma { get { - if (character.IsClimbing && SteeringManager == PathSteering && PathSteering.CurrentPath != null && !PathSteering.CurrentPath.Finished) + if (SteeringManager == PathSteering && PathSteering.CurrentPath?.CurrentNode?.Ladders != null) { - // Still in ladders and the path is not finished -> don't release - return false; + //don't consider the character to be close enough to the target while climbing ladders, + //UNLESS the last node in the path has been reached + //otherwise characters can let go of the ladders too soon once they're close enough to the target + if (PathSteering.CurrentPath.NextNode != null) { return false; } } + bool closeEnough = Vector2.DistanceSquared(Target.WorldPosition, character.WorldPosition) < CloseEnough * CloseEnough; if (closeEnough) { diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveIdle.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveIdle.cs index 0d9a61f81..998691f95 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveIdle.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveIdle.cs @@ -45,17 +45,20 @@ namespace Barotrauma private float randomUpdateInterval = 5; public float Random { get; private set; } - public void CalculatePriority() + public void SetRandom() { Random = Rand.Range(0.5f, 1.5f); randomTimer = randomUpdateInterval; + } + + public override float GetPriority() + { float max = Math.Min(Math.Min(AIObjectiveManager.RunPriority, AIObjectiveManager.OrderPriority) - 1, 100); float initiative = character.GetSkillLevel("initiative"); Priority = MathHelper.Lerp(1, max, MathUtils.InverseLerp(100, 0, initiative * Random)); + return Priority; } - public override float GetPriority() => Priority; - public override void Update(float deltaTime) { if (objectiveManager.CurrentObjective == this) @@ -66,7 +69,7 @@ namespace Barotrauma } else { - CalculatePriority(); + SetRandom(); } } } @@ -179,7 +182,7 @@ namespace Barotrauma if (!character.IsClimbing) { if (SteeringManager != PathSteering || (PathSteering.CurrentPath != null && - (PathSteering.CurrentPath.Finished || PathSteering.CurrentPath.Unreachable || PathSteering.CurrentPath.HasOutdoorsNodes))) + (PathSteering.CurrentPath.NextNode == null || PathSteering.CurrentPath.Unreachable || PathSteering.CurrentPath.HasOutdoorsNodes))) { Wander(deltaTime); return; @@ -261,9 +264,9 @@ namespace Barotrauma public static bool IsForbidden(Hull hull) { if (hull == null) { return true; } - string hullName = hull.RoomName; + string hullName = hull.RoomName?.ToLowerInvariant(); if (hullName == null) { return false; } - return hullName.Contains("ballast", StringComparison.OrdinalIgnoreCase) || hullName.Contains("airlock", StringComparison.OrdinalIgnoreCase); + return hullName.Contains("ballast") || hullName.Contains("airlock"); } } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveLoop.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveLoop.cs index 8c2a4b340..61ce5ef6a 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveLoop.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveLoop.cs @@ -45,7 +45,6 @@ namespace Barotrauma public override bool CanBeCompleted => true; public override bool AbandonWhenCannotCompleteSubjectives => false; public override bool AllowSubObjectiveSorting => true; - public virtual bool InverseTargetEvaluation => false; public override bool IsLoop { get => true; set => throw new System.Exception("Trying to set the value for IsLoop from: " + System.Environment.StackTrace); } @@ -108,46 +107,21 @@ namespace Barotrauma public override float GetPriority() { - if (character.LockHands || character.Submarine == null || Targets.None()) + if (character.LockHands) { return 0; } + if (character.Submarine == null) { return 0; } + if (Targets.None()) { return 0; } + // Allow the target value to be more than 100. + float targetValue = TargetEvaluation(); + // If the target value is less than 1% of the max value, let's just treat it as zero. + if (targetValue < 1) { return 0; } + if (objectiveManager.CurrentOrder == this) { - Priority = 0; + return AIObjectiveManager.OrderPriority; } - else - { - // Allow the target value to be more than 100. - float targetValue = TargetEvaluation(); - if (InverseTargetEvaluation) - { - targetValue = 100 - targetValue; - } - var currentSubObjective = CurrentSubObjective; - if (currentSubObjective != null && currentSubObjective.Priority > targetValue) - { - // If the priority is higher than the target value, let's just use it. - // The priority calculation is more precise, but it takes into account things like distances, - // so it's better not to use it if it's lower than the rougher targetValue. - targetValue = Priority; - } - // If the target value is less than 1% of the max value, let's just treat it as zero. - if (targetValue < 1) - { - Priority = 0; - } - else - { - if (objectiveManager.CurrentOrder == this) - { - Priority = AIObjectiveManager.OrderPriority; - } - else - { - float max = MathHelper.Min(AIObjectiveManager.OrderPriority - 1, 90); - float value = MathHelper.Clamp((CumulatedDevotion + (targetValue * PriorityModifier)) / 100, 0, 1); - Priority = MathHelper.Lerp(0, max, value); - } - } - } - return Priority; + float max = MathHelper.Min(AIObjectiveManager.OrderPriority - 1, 90); + float devotion = MathHelper.Min(10, Priority); + float value = MathHelper.Clamp((devotion + targetValue * PriorityModifier) / 100, 0, 1); + return MathHelper.Lerp(0, max, value); } protected void UpdateTargets() diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveManager.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveManager.cs index abe0f4052..cdf43f230 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveManager.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveManager.cs @@ -41,15 +41,6 @@ namespace Barotrauma public bool IsActiveObjective() where T : AIObjective => GetActiveObjective() is T; public AIObjective GetActiveObjective() => CurrentObjective?.GetActiveObjective(); - /// - /// Returns the last active objective of the specific type. - /// - public T GetActiveObjective() where T : AIObjective => CurrentObjective?.GetSubObjectivesRecursive(includingSelf: true).LastOrDefault(so => so is T) as T; - - /// - /// Returns all active objectives of the specific type. Creates a new collection -> don't use too frequently. - /// - public IEnumerable GetActiveObjectives() where T : AIObjective => CurrentObjective?.GetSubObjectivesRecursive(includingSelf: true).Where(so => so is T).Select(so => so as T); public bool HasActiveObjective() where T : AIObjective => CurrentObjective is T || CurrentObjective != null && CurrentObjective.GetSubObjectivesRecursive().Any(so => so is T); @@ -155,7 +146,7 @@ namespace Barotrauma { var previousObjective = CurrentObjective; var firstObjective = Objectives.FirstOrDefault(); - if (CurrentOrder != null && firstObjective != null && CurrentOrder.Priority > firstObjective.Priority) + if (CurrentOrder != null && firstObjective != null && CurrentOrder.GetPriority() > firstObjective.GetPriority()) { CurrentObjective = CurrentOrder; } @@ -167,14 +158,14 @@ namespace Barotrauma { previousObjective?.OnDeselected(); CurrentObjective?.OnSelected(); - GetObjective().CalculatePriority(); + GetObjective().SetRandom(); } return CurrentObjective; } public float GetCurrentPriority() { - return CurrentObjective == null ? 0.0f : CurrentObjective.Priority; + return CurrentObjective == null ? 0.0f : CurrentObjective.GetPriority(); } public void UpdateObjectives(float deltaTime) @@ -214,8 +205,7 @@ namespace Barotrauma { if (Objectives.Any()) { - Objectives.ForEach(o => o.GetPriority()); - Objectives.Sort((x, y) => y.Priority.CompareTo(x.Priority)); + Objectives.Sort((x, y) => y.GetPriority().CompareTo(x.GetPriority())); } GetCurrentObjective()?.SortSubObjectives(); } @@ -307,7 +297,7 @@ namespace Barotrauma { IsLoop = true, // Don't override unless it's an order by a player - Override = orderGiver != null && orderGiver.IsPlayer + Override = orderGiver != null && (orderGiver == Character.Controlled || orderGiver.IsRemotePlayer) }; break; default: @@ -316,7 +306,7 @@ namespace Barotrauma { IsLoop = true, // Don't override unless it's an order by a player - Override = orderGiver != null && orderGiver.IsPlayer + Override = orderGiver != null && (orderGiver == Character.Controlled || orderGiver.IsRemotePlayer) }; break; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveOperateItem.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveOperateItem.cs index 5c58fdb29..a726858d3 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveOperateItem.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveOperateItem.cs @@ -3,7 +3,6 @@ using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; -using Barotrauma.Extensions; namespace Barotrauma { @@ -32,32 +31,19 @@ namespace Barotrauma public override float GetPriority() { - if (component.Item.ConditionPercentage <= 0) + if (component.Item.ConditionPercentage <= 0) { return 0; } + if (objectiveManager.CurrentOrder == this) { - Priority = 0; + return AIObjectiveManager.OrderPriority; } - else - { - if (objectiveManager.CurrentOrder == this) - { - Priority = AIObjectiveManager.OrderPriority; - } - if (component.Item.CurrentHull == null || component.Item.CurrentHull.FireSources.None() || IsOperatedByAnother(GetTarget())) - { - Priority = 0; - } - else if (Character.CharacterList.Any(c => c.CurrentHull == component.Item.CurrentHull && !HumanAIController.IsFriendly(c) && HumanAIController.IsActive(c))) - { - Priority = 0; - } - else - { - float value = CumulatedDevotion + (AIObjectiveManager.OrderPriority * PriorityModifier); - float max = MathHelper.Min((AIObjectiveManager.OrderPriority - 1), 90); - Priority = MathHelper.Clamp(value, 0, max); - } - } - return Priority; + if (component.Item.CurrentHull == null) { return 0; } + if (component.Item.CurrentHull.FireSources.Count > 0) { return 0; } + if (IsOperatedByAnother(GetTarget())) { return 0; } + if (Character.CharacterList.Any(c => c.CurrentHull == component.Item.CurrentHull && !HumanAIController.IsFriendly(c) && HumanAIController.IsActive(c))) { return 0; } + float devotion = MathHelper.Min(10, Priority); + float value = devotion + AIObjectiveManager.OrderPriority * PriorityModifier; + float max = MathHelper.Min((AIObjectiveManager.OrderPriority - 1), 90); + return MathHelper.Clamp(value, 0, max); } public AIObjectiveOperateItem(ItemComponent item, Character character, AIObjectiveManager objectiveManager, string option, bool requireEquip, Entity operateTarget = null, bool useController = false, float priorityModifier = 1) diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectivePumpWater.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectivePumpWater.cs index 0921dc1ff..9d5b1058c 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectivePumpWater.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectivePumpWater.cs @@ -12,6 +12,7 @@ namespace Barotrauma public override string DebugTag => "pump water"; public override bool KeepDivingGearOn => true; public override bool UnequipItems => true; + public override bool IgnoreUnsafeHulls => true; private IEnumerable pumpList; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRepairItem.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRepairItem.cs index 1e5971576..20a892037 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRepairItem.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRepairItem.cs @@ -30,28 +30,21 @@ namespace Barotrauma { // TODO: priority list? // Ignore items that are being repaired by someone else. - if (Item.Repairables.Any(r => r.CurrentFixer != null && r.CurrentFixer != character)) + if (Item.Repairables.Any(r => r.CurrentFixer != null && r.CurrentFixer != character)) { return 0; } + float yDist = Math.Abs(character.WorldPosition.Y - Item.WorldPosition.Y); + yDist = yDist > 100 ? yDist * 5 : 0; + float dist = Math.Abs(character.WorldPosition.X - Item.WorldPosition.X) + yDist; + float distanceFactor = MathHelper.Lerp(1, 0.25f, MathUtils.InverseLerp(0, 5000, dist)); + if (Item.CurrentHull == character.CurrentHull) { - Priority = 0; + distanceFactor = 1; } - else - { - float yDist = Math.Abs(character.WorldPosition.Y - Item.WorldPosition.Y); - yDist = yDist > 100 ? yDist * 5 : 0; - float dist = Math.Abs(character.WorldPosition.X - Item.WorldPosition.X) + yDist; - float distanceFactor = MathHelper.Lerp(1, 0.25f, MathUtils.InverseLerp(0, 5000, dist)); - if (Item.CurrentHull == character.CurrentHull) - { - distanceFactor = 1; - } - float damagePriority = MathHelper.Lerp(1, 0, Item.Condition / Item.MaxCondition); - float successFactor = MathHelper.Lerp(0, 1, Item.Repairables.Average(r => r.DegreeOfSuccess(character))); - float isSelected = IsRepairing ? 50 : 0; - float devotion = (CumulatedDevotion + isSelected) / 100; - float max = MathHelper.Min(AIObjectiveManager.OrderPriority - 1, 90); - Priority = MathHelper.Lerp(0, max, MathHelper.Clamp(devotion + (damagePriority * distanceFactor * successFactor * PriorityModifier), 0, 1)); - } - return Priority; + float damagePriority = MathHelper.Lerp(1, 0, Item.Condition / Item.MaxCondition); + float successFactor = MathHelper.Lerp(0, 1, Item.Repairables.Average(r => r.DegreeOfSuccess(character))); + float isSelected = IsRepairing ? 50 : 0; + float devotion = (Math.Min(Priority, 10) + isSelected) / 100; + float max = MathHelper.Min(AIObjectiveManager.OrderPriority - 1, 90); + return MathHelper.Lerp(0, max, MathHelper.Clamp(devotion + damagePriority * distanceFactor * successFactor * PriorityModifier, 0, 1)); } protected override bool Check() @@ -165,7 +158,7 @@ namespace Barotrauma } repairable.StopRepairing(character); } - else if (repairable.CurrentFixer != character) + else { repairable.StartRepairing(character, Repairable.FixActions.Repair); } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRepairItems.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRepairItems.cs index f6df24810..28183a43c 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRepairItems.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRepairItems.cs @@ -81,17 +81,18 @@ namespace Barotrauma // Don't stop fixing until done return 100; } - int otherFixers = HumanAIController.CountCrew(c => c != HumanAIController && c.ObjectiveManager.IsCurrentObjective(), onlyBots: true); + int otherFixers = HumanAIController.CountCrew(c => c != HumanAIController && c.ObjectiveManager.IsCurrentObjective()); int items = Targets.Count; bool anyFixers = otherFixers > 0; - float ratio = anyFixers ? items / (float)otherFixers : 1; + float ratio = anyFixers ? items / otherFixers : 1; + var result = ratio; if (objectiveManager.CurrentOrder == this) { return Targets.Sum(t => 100 - t.ConditionPercentage) * ratio; } else { - if (anyFixers && (ratio <= 1 || otherFixers > 5 || otherFixers / (float)HumanAIController.CountCrew(onlyBots: true) > 0.75f)) + if (anyFixers && (ratio <= 1 || otherFixers > 5 || otherFixers / HumanAIController.CountCrew() > 0.75f)) { // Enough fixers return 0; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRescue.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRescue.cs index 57cea1a9f..2a8b6c756 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRescue.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRescue.cs @@ -14,7 +14,7 @@ namespace Barotrauma const float TreatmentDelay = 0.5f; - const float CloseEnoughToTreat = 100.0f; + const float CloseEnoughToTreat = 150.0f; private readonly Character targetCharacter; @@ -44,15 +44,6 @@ namespace Barotrauma Abandon = true; return; } - if (targetCharacter.SelectedBy != null && targetCharacter.SelectedBy != character) - { - var otherCharacter = character.SelectedBy; - if (otherCharacter != null) - { - // Someone else is rescuing/holding the target. - Abandon = otherCharacter.IsPlayer || character.GetSkillLevel("medical") < otherCharacter.GetSkillLevel("medical"); - } - } if (targetCharacter != character) { @@ -76,11 +67,7 @@ namespace Barotrauma TargetName = targetCharacter.DisplayName }, onCompleted: () => RemoveSubObjective(ref goToObjective), - onAbandon: () => - { - RemoveSubObjective(ref goToObjective); - Abandon = true; - }); + onAbandon: () => RemoveSubObjective(ref goToObjective)); } else { @@ -99,11 +86,7 @@ namespace Barotrauma RemoveSubObjective(ref goToObjective); TryAddSubObjective(ref goToObjective, () => new AIObjectiveGoTo(safeHull, character, objectiveManager), onCompleted: () => RemoveSubObjective(ref goToObjective), - onAbandon: () => - { - RemoveSubObjective(ref goToObjective); - safeHull = character.CurrentHull; - }); + onAbandon: () => RemoveSubObjective(ref goToObjective)); } } } @@ -122,11 +105,7 @@ namespace Barotrauma TargetName = targetCharacter.DisplayName }, onCompleted: () => RemoveSubObjective(ref goToObjective), - onAbandon: () => - { - RemoveSubObjective(ref goToObjective); - Abandon = true; - }); + onAbandon: () => RemoveSubObjective(ref goToObjective)); } else { @@ -148,11 +127,6 @@ namespace Barotrauma private Dictionary currentTreatmentSuitabilities = new Dictionary(); private void GiveTreatment(float deltaTime) { - if (!targetCharacter.IsPlayer) - { - // If the target is a bot, don't let it move - targetCharacter.AIController.SteeringManager.Reset(); - } if (treatmentTimer > 0.0f) { treatmentTimer -= deltaTime; @@ -163,8 +137,9 @@ namespace Barotrauma //find which treatments are the most suitable to treat the character's current condition targetCharacter.CharacterHealth.GetSuitableTreatments(currentTreatmentSuitabilities, normalize: false); + var allAfflictions = GetVitalityReducingAfflictions(targetCharacter).OrderByDescending(a => a.GetVitalityDecrease(targetCharacter.CharacterHealth)); //check if we already have a suitable treatment for any of the afflictions - foreach (Affliction affliction in GetSortedAfflictions(targetCharacter)) + foreach (Affliction affliction in allAfflictions) { foreach (KeyValuePair treatmentSuitability in affliction.Prefab.TreatmentSuitability) { @@ -225,12 +200,10 @@ namespace Barotrauma onAbandon: () => RemoveSubObjective(ref getItemObjective)); } } - if (character != targetCharacter) - { - character.AnimController.Anim = AnimController.Animation.CPR; - } + character.AnimController.Anim = AnimController.Animation.CPR; } + private void ApplyTreatment(Affliction affliction, Item item) { var targetLimb = targetCharacter.CharacterHealth.GetAfflictionLimb(affliction); @@ -267,7 +240,7 @@ namespace Barotrauma Abandon = true; return false; } - bool isCompleted = AIObjectiveRescueAll.GetVitalityFactor(targetCharacter) >= AIObjectiveRescueAll.GetVitalityThreshold(objectiveManager, character, targetCharacter); + bool isCompleted = AIObjectiveRescueAll.GetVitalityFactor(targetCharacter) > AIObjectiveRescueAll.GetVitalityThreshold(objectiveManager); if (isCompleted && targetCharacter != character) { character.Speak(TextManager.GetWithVariable("DialogTargetHealed", "[targetname]", targetCharacter.Name), @@ -280,24 +253,20 @@ namespace Barotrauma { if (targetCharacter == null || targetCharacter.CurrentHull == null || targetCharacter.Removed || targetCharacter.IsDead) { - Priority = 0; + return 0; } - else + // Vertical distance matters more than horizontal (climbing up/down is harder than moving horizontally) + float dist = Math.Abs(character.WorldPosition.X - targetCharacter.WorldPosition.X) + Math.Abs(character.WorldPosition.Y - targetCharacter.WorldPosition.Y) * 2.0f; + float distanceFactor = MathHelper.Lerp(1, 0.1f, MathUtils.InverseLerp(0, 5000, dist)); + if (targetCharacter.CurrentHull == character.CurrentHull) { - // Vertical distance matters more than horizontal (climbing up/down is harder than moving horizontally) - float dist = Math.Abs(character.WorldPosition.X - targetCharacter.WorldPosition.X) + Math.Abs(character.WorldPosition.Y - targetCharacter.WorldPosition.Y) * 2.0f; - float distanceFactor = MathHelper.Lerp(1, 0.1f, MathUtils.InverseLerp(0, 5000, dist)); - if (targetCharacter.CurrentHull == character.CurrentHull) - { - distanceFactor = 1; - } - float vitalityFactor = 1 - AIObjectiveRescueAll.GetVitalityFactor(targetCharacter) / 100; - float devotion = CumulatedDevotion / 100; - Priority = MathHelper.Lerp(0, 100, MathHelper.Clamp(devotion + (vitalityFactor * distanceFactor * PriorityModifier), 0, 1)); + distanceFactor = 1; } - return Priority; + float vitalityFactor = AIObjectiveRescueAll.GetVitalityFactor(targetCharacter); + float devotion = Math.Min(Priority, 10) / 100; + return MathHelper.Lerp(0, 100, MathHelper.Clamp(devotion + vitalityFactor * distanceFactor, 0, 1)); } - public static IEnumerable GetSortedAfflictions(Character character) => CharacterHealth.SortAfflictionsBySeverity(character.CharacterHealth.GetAllAfflictions()); + public static IEnumerable GetVitalityReducingAfflictions(Character character) => character.CharacterHealth.GetAllAfflictions(a => a.GetVitalityDecrease(character.CharacterHealth) > 0); } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRescueAll.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRescueAll.cs index d3d9adfed..6cc31471c 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRescueAll.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Objectives/AIObjectiveRescueAll.cs @@ -8,11 +8,11 @@ namespace Barotrauma { public override string DebugTag => "rescue all"; public override bool ForceRun => true; - public override bool InverseTargetEvaluation => true; + public override bool IgnoreUnsafeHulls => true; private const float vitalityThreshold = 80; - private const float vitalityThresholdForOrders = 100; - public static float GetVitalityThreshold(AIObjectiveManager manager, Character character, Character target) + private const float vitalityThresholdForOrders = 95; + public static float GetVitalityThreshold(AIObjectiveManager manager) { if (manager == null) { @@ -20,7 +20,7 @@ namespace Barotrauma } else { - return character == target || manager.CurrentOrder is AIObjectiveRescueAll ? vitalityThresholdForOrders : vitalityThreshold; + return manager.CurrentOrder is AIObjectiveRescueAll ? vitalityThresholdForOrders : vitalityThreshold; } } @@ -31,50 +31,9 @@ namespace Barotrauma protected override IEnumerable GetList() => Character.CharacterList; - protected override float TargetEvaluation() - { - int otherRescuers = HumanAIController.CountCrew(c => c != HumanAIController && c.ObjectiveManager.IsCurrentObjective(), onlyBots: true); - int targetCount = Targets.Count; - bool anyRescuers = otherRescuers > 0; - float ratio = anyRescuers ? targetCount / (float)otherRescuers : 1; - if (objectiveManager.CurrentOrder == this) - { - return Targets.Min(t => GetVitalityFactor(t)) / ratio; - } - else - { - float multiplier = 1; - if (anyRescuers) - { - float mySkill = character.GetSkillLevel("medical"); - int betterRescuers = HumanAIController.CountCrew(c => c != HumanAIController && c.Character.Info.Job.GetSkillLevel("medical") >= mySkill, onlyBots: true); - if (targetCount / (float)betterRescuers <= 1) - { - // Enough rescuers - return 100; - } - else - { - bool foundOtherMedics = HumanAIController.IsTrueForAnyCrewMember(c => c != HumanAIController && c.Character.Info.Job.Prefab.Identifier == "medicaldoctor"); - if (foundOtherMedics) - { - if (character.Info.Job.Prefab.Identifier != "medicaldoctor") - { - // Double the vitality factor -> less likely to take action - multiplier = 2; - } - } - } - } - return Targets.Min(t => GetVitalityFactor(t)) / ratio * multiplier; - } - } + protected override float TargetEvaluation() => Targets.Max(t => GetVitalityFactor(t)); - public static float GetVitalityFactor(Character character) - { - float vitality = character.HealthPercentage - character.Bleeding - character.Bloodloss + Math.Min(character.Oxygen, 0); - return Math.Clamp(vitality, 0, 100); - } + public static float GetVitalityFactor(Character character) => Math.Min(character.HealthPercentage - character.Bleeding - character.Bloodloss - Math.Min(character.Oxygen, 0), 100); protected override AIObjective ObjectiveConstructor(Character target) => new AIObjectiveRescue(character, target, objectiveManager, PriorityModifier); @@ -88,34 +47,16 @@ namespace Barotrauma if (!HumanAIController.IsFriendly(character, target)) { return false; } if (character.AIController is HumanAIController humanAI) { - if (GetVitalityFactor(target) >= GetVitalityThreshold(humanAI.ObjectiveManager, character, target)) { return false; } - if (!humanAI.ObjectiveManager.IsCurrentOrder()) - { - // Ignore unsafe hulls, unless ordered - if (humanAI.UnsafeHulls.Contains(target.CurrentHull)) - { - return false; - } - } + if (GetVitalityFactor(target) > GetVitalityThreshold(humanAI.ObjectiveManager)) { return false; } } else { - if (GetVitalityFactor(target) >= vitalityThreshold) { return false; } + if (GetVitalityFactor(target) > vitalityThreshold) { return false; } } if (target.Submarine == null || character.Submarine == null) { return false; } if (target.Submarine.TeamID != character.Submarine.TeamID) { return false; } if (target.CurrentHull == null) { return false; } if (character.Submarine != null && !character.Submarine.IsEntityFoundOnThisSub(target.CurrentHull, true)) { return false; } - if (!target.IsPlayer && HumanAIController.IsActive(target) && target.AIController is HumanAIController targetAI) - { - // Ignore all concious targets that are currently fighting, fleeing or treating characters - if (targetAI.ObjectiveManager.HasActiveObjective() || - targetAI.ObjectiveManager.HasActiveObjective() || - targetAI.ObjectiveManager.HasActiveObjective()) - { - return false; - } - } // Don't go into rooms that have enemies if (Character.CharacterList.Any(c => c.CurrentHull == target.CurrentHull && !HumanAIController.IsFriendly(character, c) && HumanAIController.IsActive(c))) { return false; } return true; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Order.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Order.cs index 53e1b4ac6..16ba0c9ea 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Order.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/AI/Order.cs @@ -291,7 +291,7 @@ namespace Barotrauma } for (int i = 0; i < AppropriateJobs.Length; i++) { - if (character.Info.Job.Prefab.Identifier.Equals(AppropriateJobs[i], StringComparison.OrdinalIgnoreCase)) { return true; } + if (character.Info.Job.Prefab.Identifier.ToLowerInvariant() == AppropriateJobs[i].ToLowerInvariant()) { return true; } } return false; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/Ragdoll.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/Ragdoll.cs index a5925403b..6490858b9 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/Ragdoll.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Animation/Ragdoll.cs @@ -732,20 +732,14 @@ namespace Barotrauma limbJoint.IsSevered = true; limbJoint.Enabled = false; - Vector2 limbDiff = limbJoint.LimbA.SimPosition - limbJoint.LimbB.SimPosition; - if (limbDiff.LengthSquared() < 0.0001f) { limbDiff = Rand.Vector(1.0f); } - limbDiff = Vector2.Normalize(limbDiff); - float mass = limbJoint.BodyA.Mass + limbJoint.BodyB.Mass; - limbJoint.LimbA.body.ApplyLinearImpulse(limbDiff * mass, (limbJoint.LimbA.SimPosition + limbJoint.LimbB.SimPosition) / 2.0f); - limbJoint.LimbB.body.ApplyLinearImpulse(-limbDiff * mass, (limbJoint.LimbA.SimPosition + limbJoint.LimbB.SimPosition) / 2.0f); - List connectedLimbs = new List(); List checkedJoints = new List(); GetConnectedLimbs(connectedLimbs, checkedJoints, MainLimb); foreach (Limb limb in Limbs) { - if (connectedLimbs.Contains(limb)) { continue; } + if (connectedLimbs.Contains(limb)) continue; + limb.IsSevered = true; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Attack.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Attack.cs index b77288654..a3b3a9ea2 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Attack.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Attack.cs @@ -78,7 +78,7 @@ namespace Barotrauma [Serialize(AttackTarget.Any, true, description: "Does the attack target only specific targets?"), Editable] public AttackTarget TargetType { get; private set; } - [Serialize(LimbType.None, true, description: "To which limb is the attack aimed at? If not defined or set to none, the closest limb is used (default)."), Editable] + [Serialize(LimbType.None, true, description: "If not defined or set to none, the closest limb is used (default)."), Editable] public LimbType TargetLimbType { get; private set; } [Serialize(HitDetection.Distance, true, description: "Collision detection is more accurate, but it only affects targets that are in contact with the limb."), Editable] @@ -87,12 +87,9 @@ namespace Barotrauma [Serialize(AIBehaviorAfterAttack.FallBack, true, description: "The preferred AI behavior after the attack."), Editable] public AIBehaviorAfterAttack AfterAttack { get; set; } - [Serialize(false, true, description: "Should the AI try to turn around when aiming with this attack?"), Editable] + [Serialize(false, true, description: "Should the AI try to reverse when aiming with this attack?"), Editable] public bool Reverse { get; private set; } - [Serialize(false, true, description: "Should the AI try to steer away from the target when aiming with this attack? Best combined with PassiveAggressive behavior."), Editable] - public bool Retreat { get; private set; } - [Serialize(0.0f, true, description: "The min distance from the attack limb to the target before the AI tries to attack."), Editable(MinValueFloat = 0.0f, MaxValueFloat = 2000.0f)] public float Range { get; set; } @@ -282,7 +279,7 @@ namespace Barotrauma { DebugConsole.ThrowError("Error in Attack (" + parentDebugName + ") - define afflictions using identifiers instead of names."); string afflictionName = subElement.GetAttributeString("name", "").ToLowerInvariant(); - afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(ap => ap.Name.Equals(afflictionName, System.StringComparison.OrdinalIgnoreCase)); + afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(ap => ap.Name.ToLowerInvariant() == afflictionName); if (afflictionPrefab == null) { DebugConsole.ThrowError("Error in Attack (" + parentDebugName + ") - Affliction prefab \"" + afflictionName + "\" not found."); @@ -292,7 +289,7 @@ namespace Barotrauma else { string afflictionIdentifier = subElement.GetAttributeString("identifier", "").ToLowerInvariant(); - afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(ap => ap.Identifier.Equals(afflictionIdentifier, System.StringComparison.OrdinalIgnoreCase)); + afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(ap => ap.Identifier.ToLowerInvariant() == afflictionIdentifier); if (afflictionPrefab == null) { DebugConsole.ThrowError("Error in Attack (" + parentDebugName + ") - Affliction prefab \"" + afflictionIdentifier + "\" not found."); @@ -327,7 +324,7 @@ namespace Barotrauma AfflictionPrefab afflictionPrefab; Affliction affliction; string afflictionIdentifier = subElement.GetAttributeString("identifier", "").ToLowerInvariant(); - afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(ap => ap.Identifier.Equals(afflictionIdentifier, System.StringComparison.OrdinalIgnoreCase)); + afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(ap => ap.Identifier.ToLowerInvariant() == afflictionIdentifier); if (afflictionPrefab != null) { float afflictionStrength = subElement.GetAttributeFloat(1.0f, "amount", "strength"); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Character.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Character.cs index 02c4901de..c88604bcc 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Character.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Character.cs @@ -57,9 +57,6 @@ namespace Barotrauma public Hull CurrentHull = null; public bool IsRemotePlayer; - - public bool IsPlayer => Controlled == this || IsRemotePlayer; - public readonly Dictionary Properties; public Dictionary SerializableProperties { @@ -131,40 +128,13 @@ namespace Barotrauma set => Params.Noise = value; } - public float Visibility - { - get => Params.Visibility; - set => Params.Visibility = value; - } - public bool IsTraitor; public string TraitorCurrentObjective = ""; public bool IsHuman => SpeciesName.Equals(CharacterPrefab.HumanSpeciesName, StringComparison.OrdinalIgnoreCase); private float attackCoolDown; - public Order CurrentOrder - { - get - { - return Info?.CurrentOrder; - } - private set - { - if (Info != null) { Info.CurrentOrder = value; } - } - } - public string CurrentOrderOption - { - get - { - return Info?.CurrentOrderOption; - } - private set - { - if (Info != null) { Info.CurrentOrderOption = value; } - } - } + public Order CurrentOrder { get; private set; } private readonly List statusEffects = new List(); private readonly List speedMultipliers = new List(); @@ -788,7 +758,7 @@ namespace Barotrauma var matchingAffliction = AfflictionPrefab.List .Where(p => p.AfflictionType == "huskinfection") .Select(p => p as AfflictionPrefabHusk) - .FirstOrDefault(p => p.TargetSpecies.Any(t => t.Equals(AfflictionHusk.GetNonHuskedSpeciesName(speciesName, p), StringComparison.OrdinalIgnoreCase))); + .FirstOrDefault(p => p.TargetSpecies.Any(t => t.Equals(AfflictionHusk.GetNonHuskedSpeciesName(speciesName, p), StringComparison.InvariantCultureIgnoreCase))); string nonHuskedSpeciesName = string.Empty; if (matchingAffliction == null) { @@ -2042,8 +2012,8 @@ namespace Barotrauma HideFace = false; - UpdateSightRange(deltaTime); - UpdateSoundRange(deltaTime); + UpdateSightRange(); + UpdateSoundRange(); if (IsDead) { return; } @@ -2192,8 +2162,6 @@ namespace Barotrauma partial void UpdateProjSpecific(float deltaTime, Camera cam); - partial void SetOrderProjSpecific(Order order, string orderOption); - private void UpdateOxygen(float deltaTime) { PressureProtection -= deltaTime * 100.0f; @@ -2296,12 +2264,7 @@ namespace Barotrauma if (itemContainer == null) { return; } foreach (Item inventoryItem in Inventory.Items) { - if (inventoryItem == null) { continue; } - if (!itemContainer.Inventory.TryPutItem(inventoryItem, user: null)) - { - //if the item couldn't be put inside the despawn container, just drop it - inventoryItem.Drop(dropper: this); - } + itemContainer.Inventory.TryPutItem(inventoryItem, user: null); } } } @@ -2327,39 +2290,18 @@ namespace Barotrauma } } - private readonly float maxAIRange = 10000; - private readonly float aiTargetChangeSpeed = 5; - - private void UpdateSightRange(float deltaTime) + private void UpdateSightRange() { if (aiTarget == null) { return; } - float minRange = Math.Clamp((float)Math.Sqrt(Mass) * Visibility, 250, 1000); - float massFactor = (float)Math.Sqrt(Mass / 20); - float targetRange = Math.Min(minRange + massFactor * AnimController.Collider.LinearVelocity.Length() * 2 * Visibility, maxAIRange); - float newRange = MathHelper.SmoothStep(aiTarget.SightRange, targetRange, deltaTime * aiTargetChangeSpeed); - if (!float.IsNaN(newRange)) - { - aiTarget.SightRange = newRange; - } + float range = (float)Math.Sqrt(Mass) * 250 + AnimController.Collider.LinearVelocity.Length() * 500; + aiTarget.SightRange = MathHelper.Clamp(range, 0, 10000); } - private void UpdateSoundRange(float deltaTime) + private void UpdateSoundRange() { if (aiTarget == null) { return; } - if (IsDead) - { - aiTarget.SoundRange = 0; - } - else - { - float massFactor = (float)Math.Sqrt(Mass / 10); - float targetRange = Math.Min(massFactor * AnimController.Collider.LinearVelocity.Length() * 2 * Noise, maxAIRange); - float newRange = MathHelper.SmoothStep(aiTarget.SoundRange, targetRange, deltaTime * aiTargetChangeSpeed); - if (!float.IsNaN(newRange)) - { - aiTarget.SoundRange = newRange; - } - } + float range = ((float)Math.Sqrt(Mass) / 3) * (AnimController.TargetMovement.Length() * 2) * Noise; + aiTarget.SoundRange = MathHelper.Clamp(range, 0, 10000); } public bool CanHearCharacter(Character speaker) @@ -2374,17 +2316,24 @@ namespace Barotrauma public void SetOrder(Order order, string orderOption, Character orderGiver, bool speak = true) { - //set the character order only if the character is close enough to hear the message - if (orderGiver != null && !CanHearCharacter(orderGiver)) { return; } + if (orderGiver != null) + { + //set the character order only if the character is close enough to hear the message + if (!CanHearCharacter(orderGiver)) { return; } + } if (AIController is HumanAIController humanAI) { humanAI.SetOrder(order, orderOption, orderGiver, speak); } +#if CLIENT + else + { + GameMain.GameSession?.CrewManager?.DisplayCharacterOrder(this, order, orderOption); + } +#endif - SetOrderProjSpecific(order, orderOption); CurrentOrder = order; - CurrentOrderOption = orderOption; } private readonly List aiChatMessageQueue = new List(); @@ -2653,7 +2602,6 @@ namespace Barotrauma mainLimb.body.ApplyLinearImpulse(impulse, hitPos, maxVelocity: NetConfig.MaxPhysicsBodyVelocity); } } - bool wasDead = IsDead; Vector2 simPos = hitLimb.SimPosition + ConvertUnits.ToSimUnits(dir); AttackResult attackResult = hitLimb.AddDamage(simPos, afflictions, playSound); CharacterHealth.ApplyDamage(hitLimb, attackResult); @@ -2661,10 +2609,6 @@ namespace Barotrauma { OnAttacked?.Invoke(attacker, attackResult); OnAttackedProjSpecific(attacker, attackResult); - if (!wasDead) - { - TryAdjustAttackerSkill(attacker, -attackResult.Damage); - } }; if (attacker != null && attackResult.Damage > 0.0f) @@ -2677,30 +2621,6 @@ namespace Barotrauma partial void OnAttackedProjSpecific(Character attacker, AttackResult attackResult); - public void TryAdjustAttackerSkill(Character attacker, float healthChange) - { - if (attacker == null) { return; } - - bool isEnemy = AIController is EnemyAIController || TeamID != attacker.TeamID; - if (isEnemy) - { - if (healthChange < 0.0f) - { - float attackerSkillLevel = attacker.GetSkillLevel("weapons"); - attacker.Info?.IncreaseSkillLevel("weapons", - -healthChange * SkillSettings.Current.SkillIncreasePerHostileDamage / Math.Max(attackerSkillLevel, 1.0f), - attacker.WorldPosition + Vector2.UnitY * 100.0f); - } - } - else if (healthChange > 0.0f) - { - float attackerSkillLevel = attacker.GetSkillLevel("medical"); - attacker.Info?.IncreaseSkillLevel("medical", - healthChange * SkillSettings.Current.SkillIncreasePerFriendlyHealed / Math.Max(attackerSkillLevel, 1.0f), - attacker.WorldPosition + Vector2.UnitY * 100.0f); - } - } - public void SetStun(float newStun, bool allowStunDecrease = false, bool isNetworkMessage = false) { if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient && !isNetworkMessage) { return; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/CharacterInfo.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/CharacterInfo.cs index e1b4fe019..37d41d47e 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/CharacterInfo.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/CharacterInfo.cs @@ -293,9 +293,6 @@ namespace Barotrauma private NPCPersonalityTrait personalityTrait; - public Order CurrentOrder { get; set;} - public string CurrentOrderOption { get; set; } - //unique ID given to character infos in MP //used by clients to identify which infos are the same to prevent duplicate characters in round summary public ushort ID; @@ -527,11 +524,9 @@ namespace Barotrauma } foreach (XElement subElement in infoElement.Elements()) { - if (subElement.Name.ToString().Equals("job", StringComparison.OrdinalIgnoreCase)) - { - Job = new Job(subElement); - break; - } + if (subElement.Name.ToString().ToLowerInvariant() != "job") continue; + Job = new Job(subElement); + break; } LoadHeadAttachments(); } @@ -666,7 +661,7 @@ namespace Barotrauma { foreach (XElement limbElement in Ragdoll.MainElement.Elements()) { - if (!limbElement.GetAttributeString("type", "").Equals("head", StringComparison.OrdinalIgnoreCase)) { continue; } + if (limbElement.GetAttributeString("type", "").ToLowerInvariant() != "head") { continue; } XElement spriteElement = limbElement.Element("sprite"); if (spriteElement == null) { continue; } @@ -682,7 +677,7 @@ namespace Barotrauma //go through the files in the directory to find a matching sprite foreach (string file in Directory.GetFiles(Path.GetDirectoryName(spritePath))) { - if (!file.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) + if (!file.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase)) { continue; } @@ -833,11 +828,6 @@ namespace Barotrauma { if (Job == null || (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) || Character == null) { return; } - if (Job.Prefab.Identifier == "assistant") - { - increase *= SkillSettings.Current.AssistantSkillIncreaseMultiplier; - } - float prevLevel = Job.GetSkillLevel(skillIdentifier); Job.IncreaseSkillLevel(skillIdentifier, increase); @@ -965,7 +955,7 @@ namespace Barotrauma foreach (XElement childInvElement in itemElement.Elements()) { if (itemContainerIndex >= itemContainers.Count) break; - if (!childInvElement.Name.ToString().Equals("inventory", StringComparison.OrdinalIgnoreCase)) { continue; } + if (childInvElement.Name.ToString().ToLowerInvariant() != "inventory") continue; SpawnInventoryItemsRecursive(itemContainers[itemContainerIndex].Inventory, childInvElement); itemContainerIndex++; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/AfflictionHusk.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/AfflictionHusk.cs index 000eadc87..445b65755 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/AfflictionHusk.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/Afflictions/AfflictionHusk.cs @@ -220,7 +220,7 @@ namespace Barotrauma var element = appendageDefinition; if (element == null) { - element = mainElement.GetChildElements("huskappendage").FirstOrDefault(e => e.GetAttributeString("affliction", string.Empty).Equals(afflictionIdentifier, System.StringComparison.OrdinalIgnoreCase)); + element = mainElement.GetChildElements("huskappendage").FirstOrDefault(e => e.GetAttributeString("affliction", string.Empty).Equals(afflictionIdentifier)); } if (element == null) { diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/CharacterHealth.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/CharacterHealth.cs index 3f1876376..1b0dd640d 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/CharacterHealth.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Health/CharacterHealth.cs @@ -216,7 +216,7 @@ namespace Barotrauma limbHealths.Clear(); foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("limb", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "limb") continue; limbHealths.Add(new LimbHealth(subElement, this)); } if (limbHealths.Count == 0) @@ -408,10 +408,11 @@ namespace Barotrauma return resistance; } - private List matchingAfflictions = new List(); public void ReduceAffliction(Limb targetLimb, string affliction, float amount) { - matchingAfflictions.Clear(); + affliction = affliction.ToLowerInvariant(); + + List matchingAfflictions = new List(afflictions); if (targetLimb != null) { @@ -425,8 +426,8 @@ namespace Barotrauma } } matchingAfflictions.RemoveAll(a => - !a.Prefab.Identifier.Equals(affliction, StringComparison.OrdinalIgnoreCase) && - !a.Prefab.AfflictionType.Equals(affliction, StringComparison.OrdinalIgnoreCase)); + a.Prefab.Identifier.ToLowerInvariant() != affliction && + a.Prefab.AfflictionType.ToLowerInvariant() != affliction); if (matchingAfflictions.Count == 0) return; @@ -690,15 +691,13 @@ namespace Barotrauma foreach (Affliction affliction in limbHealth.Afflictions) { float vitalityDecrease = affliction.GetVitalityDecrease(this); - string identifier = affliction.Prefab.Identifier.ToLowerInvariant(); - string type = affliction.Prefab.AfflictionType.ToLowerInvariant(); - if (limbHealth.VitalityMultipliers.ContainsKey(identifier)) + if (limbHealth.VitalityMultipliers.ContainsKey(affliction.Prefab.Identifier.ToLowerInvariant())) { - vitalityDecrease *= limbHealth.VitalityMultipliers[identifier]; + vitalityDecrease *= limbHealth.VitalityMultipliers[affliction.Prefab.Identifier.ToLowerInvariant()]; } - if (limbHealth.VitalityTypeMultipliers.ContainsKey(type)) + if (limbHealth.VitalityTypeMultipliers.ContainsKey(affliction.Prefab.AfflictionType.ToLowerInvariant())) { - vitalityDecrease *= limbHealth.VitalityTypeMultipliers[type]; + vitalityDecrease *= limbHealth.VitalityTypeMultipliers[affliction.Prefab.AfflictionType.ToLowerInvariant()]; } vitalityDecrease *= damageResistanceMultiplier; Vitality -= vitalityDecrease; @@ -792,7 +791,8 @@ namespace Barotrauma /// /// A dictionary where the key is the identifier of the item and the value the suitability /// If true, the suitability values are normalized between 0 and 1. If not, they're arbitrary values defined in the medical item XML, where negative values are unsuitable, and positive ones suitable. - /// Amount of randomization to apply to the values (0 = the values are accurate, 1 = the values are completely random) + /// Amount of randomization to apply to the values (0 = the values are accurate, 1 = the values are completely random) + public void GetSuitableTreatments(Dictionary treatmentSuitability, bool normalize, float randomization = 0.0f) { //key = item identifier @@ -873,11 +873,5 @@ namespace Barotrauma } partial void RemoveProjSpecific(); - - /// - /// Automatically filters out buffs. - /// - public static IEnumerable SortAfflictionsBySeverity(IEnumerable afflictions) => - afflictions.Where(a => !a.Prefab.IsBuff).OrderByDescending(a => a.DamagePerSecond).ThenByDescending(a => a.Strength); } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Jobs/Job.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Jobs/Job.cs index 68a0cf326..85bb5925c 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Jobs/Job.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Jobs/Job.cs @@ -62,7 +62,7 @@ namespace Barotrauma skills = new Dictionary(); foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("skill", System.StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "skill") { continue; } string skillIdentifier = subElement.GetAttributeString("identifier", ""); if (string.IsNullOrEmpty(skillIdentifier)) { continue; } skills.Add( diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Jobs/JobPrefab.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Jobs/JobPrefab.cs index 89b414110..b6ffe5ed0 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Jobs/JobPrefab.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Jobs/JobPrefab.cs @@ -262,7 +262,7 @@ namespace Barotrauma } foreach (XElement element in mainElement.Elements()) { - if (element.Name.ToString().Equals("nojob", StringComparison.OrdinalIgnoreCase)) { continue; } + if (element.Name.ToString().ToLowerInvariant() == "nojob") { continue; } if (element.IsOverride()) { var job = new JobPrefab(element.FirstElement(), file.Path) diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/Animation/AnimationParams.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/Animation/AnimationParams.cs index 9f97ec0be..91c4e209d 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/Animation/AnimationParams.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/Animation/AnimationParams.cs @@ -125,7 +125,7 @@ namespace Barotrauma public static string GetFolder(XDocument doc, string filePath) { var folder = doc.Root?.Element("animations")?.GetAttributeString("folder", string.Empty); - if (string.IsNullOrEmpty(folder) || folder.Equals("default", StringComparison.OrdinalIgnoreCase)) + if (string.IsNullOrEmpty(folder) || folder.ToLowerInvariant() == "default") { folder = Path.Combine(Path.GetDirectoryName(filePath), "Animations"); } @@ -198,7 +198,7 @@ namespace Barotrauma } else { - selectedFile = filteredFiles.FirstOrDefault(f => Path.GetFileNameWithoutExtension(f).Equals(fileName, StringComparison.OrdinalIgnoreCase)); + selectedFile = filteredFiles.FirstOrDefault(f => Path.GetFileNameWithoutExtension(f).ToLowerInvariant() == fileName.ToLowerInvariant()); if (selectedFile == null) { DebugConsole.ThrowError($"[AnimationParams] Could not find an animation file that matches the name {fileName} and the animation type {animType}. Using the default animations."); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/CharacterParams.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/CharacterParams.cs index 09db026cf..8e3333721 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/CharacterParams.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/CharacterParams.cs @@ -40,9 +40,6 @@ namespace Barotrauma [Serialize(100f, true, description: "How much noise the character makes when moving?"), Editable(minValue: 0f, maxValue: 1000f)] public float Noise { get; set; } - [Serialize(100f, true, description: "How visible the character is?"), Editable(minValue: 0f, maxValue: 1000f)] - public float Visibility { get; set; } - [Serialize("blood", true), Editable] public string BloodDecal { get; private set; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/Ragdoll/RagdollParams.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/Ragdoll/RagdollParams.cs index 3dcf84652..f9e20691e 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/Ragdoll/RagdollParams.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/Params/Ragdoll/RagdollParams.cs @@ -94,7 +94,8 @@ namespace Barotrauma public static string GetFolder(string speciesName, ContentPackage contentPackage = null) { - CharacterPrefab prefab = CharacterPrefab.Find(p => p.Identifier.Equals(speciesName, StringComparison.OrdinalIgnoreCase) && (contentPackage == null || p.ContentPackage == contentPackage)); + CharacterPrefab prefab = CharacterPrefab.Find(p => p.Identifier.ToLowerInvariant()==speciesName.ToLowerInvariant() && + (contentPackage==null || p.ContentPackage == contentPackage)); if (prefab?.XDocument == null) { DebugConsole.ThrowError($"Failed to find config file for '{speciesName}' (content package {contentPackage?.Name ?? "null"})"); @@ -106,7 +107,7 @@ namespace Barotrauma public static string GetFolder(XDocument doc, string filePath) { var folder = doc.Root?.Element("ragdolls")?.GetAttributeString("folder", string.Empty); - if (string.IsNullOrEmpty(folder) || folder.Equals("default", StringComparison.OrdinalIgnoreCase)) + if (string.IsNullOrEmpty(folder) || folder.ToLowerInvariant() == "default") { folder = Path.Combine(Path.GetDirectoryName(filePath), "Ragdolls") + Path.DirectorySeparatorChar; } @@ -149,7 +150,7 @@ namespace Barotrauma } else { - selectedFile = files.FirstOrDefault(f => Path.GetFileNameWithoutExtension(f).Equals(fileName, StringComparison.OrdinalIgnoreCase)); + selectedFile = files.FirstOrDefault(f => Path.GetFileNameWithoutExtension(f).ToLowerInvariant() == fileName.ToLowerInvariant()); if (selectedFile == null) { DebugConsole.ThrowError($"[RagdollParams] Could not find a ragdoll file that matches the name {fileName}. Using the default ragdoll."); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Characters/SkillSettings.cs b/Barotrauma/BarotraumaShared/SharedSource/Characters/SkillSettings.cs index abe6aab58..f0814daed 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Characters/SkillSettings.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Characters/SkillSettings.cs @@ -65,37 +65,6 @@ namespace Barotrauma set { skillIncreasePerFabricatorRequiredSkill = value; } } - private float skillIncreasePerHostileDamage; - [Serialize(0.01f, true)] - public float SkillIncreasePerHostileDamage - { - get { return skillIncreasePerHostileDamage * GetCurrentSkillGainMultiplier(); } - set { skillIncreasePerHostileDamage = value; } - } - - private float skillIncreasePerSecondWhenOperatingTurret; - [Serialize(0.001f, true)] - public float SkillIncreasePerSecondWhenOperatingTurret - { - get { return skillIncreasePerSecondWhenOperatingTurret * GetCurrentSkillGainMultiplier(); } - set { skillIncreasePerSecondWhenOperatingTurret = value; } - } - - private float skillIncreasePerFriendlyHealed; - [Serialize(0.001f, true)] - public float SkillIncreasePerFriendlyHealed - { - get { return skillIncreasePerFriendlyHealed * GetCurrentSkillGainMultiplier(); } - set { skillIncreasePerFriendlyHealed = value; } - } - - [Serialize(1.1f, true)] - public float AssistantSkillIncreaseMultiplier - { - get; - set; - } - private SkillSettings(XElement element) { SerializableProperties = SerializableProperty.DeserializeProperties(this, element); diff --git a/Barotrauma/BarotraumaShared/SharedSource/ContentPackage.cs b/Barotrauma/BarotraumaShared/SharedSource/ContentPackage.cs index 84f727001..7087bfb5b 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/ContentPackage.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/ContentPackage.cs @@ -460,12 +460,12 @@ namespace Barotrauma XDocument doc = XMLExtensions.TryLoadXml(file.Path); var rootElement = doc.Root; var element = rootElement.IsOverride() ? rootElement.FirstElement() : rootElement; - var ragdollFolder = RagdollParams.GetFolder(doc, file.Path).CleanUpPathCrossPlatform(true); + var ragdollFolder = RagdollParams.GetFolder(doc, file.Path); if (Directory.Exists(ragdollFolder)) { Directory.GetFiles(ragdollFolder, "*.xml").ForEach(f => filePaths.Add(f)); } - var animationFolder = AnimationParams.GetFolder(doc, file.Path).CleanUpPathCrossPlatform(true); + var animationFolder = AnimationParams.GetFolder(doc, file.Path); if (Directory.Exists(animationFolder)) { Directory.GetFiles(animationFolder, "*.xml").ForEach(f => filePaths.Add(f)); diff --git a/Barotrauma/BarotraumaShared/SharedSource/CoroutineManager.cs b/Barotrauma/BarotraumaShared/SharedSource/CoroutineManager.cs index 6ef497afd..47b732af0 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/CoroutineManager.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/CoroutineManager.cs @@ -186,7 +186,6 @@ namespace Barotrauma #endif if (handle.Thread == null) { - if (handle.AbortRequested) { return true; } if (handle.Coroutine.Current != null) { WaitForSeconds wfs = handle.Coroutine.Current as WaitForSeconds; diff --git a/Barotrauma/BarotraumaShared/SharedSource/DebugConsole.cs b/Barotrauma/BarotraumaShared/SharedSource/DebugConsole.cs index a49104da3..455ebca33 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/DebugConsole.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/DebugConsole.cs @@ -531,17 +531,18 @@ namespace Barotrauma commands.Add(new Command("findentityids", "findentityids [entityname]", (string[] args) => { - if (args.Length == 0) { return; } + if (args.Length == 0) return; + args[0] = args[0].ToLowerInvariant(); foreach (MapEntity mapEntity in MapEntity.mapEntityList) { - if (mapEntity.Name.Equals(args[0], StringComparison.OrdinalIgnoreCase)) + if (mapEntity.Name.ToLowerInvariant() == args[0]) { ThrowError(mapEntity.ID + ": " + mapEntity.Name.ToString()); } } foreach (Character character in Character.CharacterList) { - if (character.Name.Equals(args[0], StringComparison.OrdinalIgnoreCase) || character.SpeciesName.Equals(args[0], StringComparison.OrdinalIgnoreCase)) + if (character.Name.ToLowerInvariant() == args[0] || character.SpeciesName.ToLowerInvariant() == args[0]) { ThrowError(character.ID + ": " + character.Name.ToString()); } @@ -553,8 +554,8 @@ namespace Barotrauma if (args.Length < 2) return; AfflictionPrefab afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(a => - a.Name.Equals(args[0], StringComparison.OrdinalIgnoreCase) || - a.Identifier.Equals(args[0], StringComparison.OrdinalIgnoreCase)); + a.Name.ToLowerInvariant() == args[0].ToLowerInvariant() || + a.Identifier.ToLowerInvariant() == args[0].ToLowerInvariant()); if (afflictionPrefab == null) { ThrowError("Affliction \"" + args[0] + "\" not found."); @@ -705,7 +706,7 @@ namespace Barotrauma { if (Submarine.MainSub == null || Level.Loaded == null) return; - if (args.Length > 0 && args[0].Equals("start", StringComparison.OrdinalIgnoreCase)) + if (args.Length > 0 && args[0].ToLowerInvariant() == "start") { Submarine.MainSub.SetPosition(Level.Loaded.StartPosition - Vector2.UnitY * Submarine.MainSub.Borders.Height); } @@ -1219,17 +1220,15 @@ namespace Barotrauma return; } - string firstCommand = splitCommand[0].ToLowerInvariant(); - - if (!firstCommand.Equals("admin", StringComparison.OrdinalIgnoreCase)) + if (!splitCommand[0].ToLowerInvariant().Equals("admin")) { NewMessage(command, Color.White, true); } - + #if CLIENT if (GameMain.Client != null) { - Command matchingCommand = commands.Find(c => c.names.Contains(firstCommand)); + Command matchingCommand = commands.Find(c => c.names.Contains(splitCommand[0].ToLowerInvariant())); if (matchingCommand == null) { //if the command is not defined client-side, we'll relay it anyway because it may be a custom command at the server's side @@ -1237,7 +1236,7 @@ namespace Barotrauma NewMessage("Server command: " + command, Color.Cyan); return; } - else if (GameMain.Client.HasConsoleCommandPermission(firstCommand)) + else if (GameMain.Client.HasConsoleCommandPermission(splitCommand[0].ToLowerInvariant())) { if (matchingCommand.RelayToServer) { @@ -1256,7 +1255,7 @@ namespace Barotrauma bool commandFound = false; foreach (Command c in commands) { - if (!c.names.Contains(firstCommand)) { continue; } + if (!c.names.Contains(splitCommand[0].ToLowerInvariant())) continue; c.Execute(splitCommand.Skip(1).ToArray()); commandFound = true; break; @@ -1284,7 +1283,7 @@ namespace Barotrauma } var matchingCharacters = Character.CharacterList.FindAll(c => - c.Name.Equals(characterName, StringComparison.OrdinalIgnoreCase) && + c.Name.ToLowerInvariant() == characterName && (!c.IsRemotePlayer || !ignoreRemotePlayers || allowedRemotePlayer?.Character == c)); if (!matchingCharacters.Any()) @@ -1330,7 +1329,7 @@ namespace Barotrauma JobPrefab job = null; if (!JobPrefab.Prefabs.ContainsKey(characterLowerCase)) { - job = JobPrefab.Prefabs.Find(jp => jp.Name != null && jp.Name.Equals(characterLowerCase, StringComparison.OrdinalIgnoreCase)); + job = JobPrefab.Prefabs.Find(jp => jp.Name?.ToLowerInvariant() == characterLowerCase); } else { @@ -1588,7 +1587,12 @@ namespace Barotrauma return true; } - public static Command FindCommand(string commandName) => commands.Find(c => c.names.Any(n => n.Equals(commandName, StringComparison.OrdinalIgnoreCase))); + public static Command FindCommand(string commandName) + { + commandName = commandName.ToLowerInvariant(); + return commands.Find(c => c.names.Any(n => n.ToLowerInvariant() == commandName)); + } + public static void Log(string message) { @@ -1606,24 +1610,8 @@ namespace Barotrauma } } System.Diagnostics.Debug.WriteLine(error); + NewMessage(error, Color.Red); #if CLIENT - var textContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), listBox.Content.RectTransform), - style: "InnerFrame", color: Color.White) - { - CanBeFocused = false - }; - var textBlock = new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width - 5, 0), textContainer.RectTransform, Anchor.TopLeft) { AbsoluteOffset = new Point(2, 2) }, - error, textAlignment: Alignment.TopLeft, font: GUI.SmallFont, wrap: true) - { - CanBeFocused = false, - TextColor = Color.Red - }; - textContainer.RectTransform.NonScaledSize = new Point(textContainer.RectTransform.NonScaledSize.X, textBlock.RectTransform.NonScaledSize.Y + 5); - textBlock.SetTextPos(); - - listBox.UpdateScrollBarSize(); - listBox.BarScroll = 1.0f; - if (createMessageBox) { CoroutineManager.StartCoroutine(CreateMessageBox(error)); @@ -1632,8 +1620,6 @@ namespace Barotrauma { isOpen = true; } -#else - NewMessage(error, Color.Red); #endif } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Events/EventManager.cs b/Barotrauma/BarotraumaShared/SharedSource/Events/EventManager.cs index 9f148181a..01dd3c557 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Events/EventManager.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Events/EventManager.cs @@ -219,40 +219,13 @@ namespace Barotrauma private void CreateEvents(ScriptedEventSet eventSet) { - int applyCount = 1; - if (eventSet.PerRuin) + if (eventSet.ChooseRandom) { - applyCount = Level.Loaded.Ruins.Count(); - } - for (int i = 0; i < applyCount; i++) - { - if (eventSet.ChooseRandom) + if (eventSet.EventPrefabs.Count > 0) { - if (eventSet.EventPrefabs.Count > 0) - { - MTRandom rand = new MTRandom(ToolBox.StringToInt(level.Seed)); - var eventPrefab = ToolBox.SelectWeightedRandom(eventSet.EventPrefabs, eventSet.EventPrefabs.Select(e => e.Commonness).ToList(), rand); - if (eventPrefab != null) - { - var newEvent = eventPrefab.CreateInstance(); - newEvent.Init(true); - DebugConsole.Log("Initialized event " + newEvent.ToString()); - if (!selectedEvents.ContainsKey(eventSet)) - { - selectedEvents.Add(eventSet, new List()); - } - selectedEvents[eventSet].Add(newEvent); - } - } - if (eventSet.ChildSets.Count > 0) - { - var newEventSet = SelectRandomEvents(eventSet.ChildSets); - if (newEventSet != null) { CreateEvents(newEventSet); } - } - } - else - { - foreach (ScriptedEventPrefab eventPrefab in eventSet.EventPrefabs) + MTRandom rand = new MTRandom(ToolBox.StringToInt(level.Seed)); + var eventPrefab = ToolBox.SelectWeightedRandom(eventSet.EventPrefabs, eventSet.EventPrefabs.Select(e => e.Commonness).ToList(), rand); + if (eventPrefab != null) { var newEvent = eventPrefab.CreateInstance(); newEvent.Init(true); @@ -263,11 +236,30 @@ namespace Barotrauma } selectedEvents[eventSet].Add(newEvent); } - - foreach (ScriptedEventSet childEventSet in eventSet.ChildSets) + } + if (eventSet.ChildSets.Count > 0) + { + var newEventSet = SelectRandomEvents(eventSet.ChildSets); + if (newEventSet != null) { CreateEvents(newEventSet); } + } + } + else + { + foreach (ScriptedEventPrefab eventPrefab in eventSet.EventPrefabs) + { + var newEvent = eventPrefab.CreateInstance(); + newEvent.Init(true); + DebugConsole.Log("Initialized event " + newEvent.ToString()); + if (!selectedEvents.ContainsKey(eventSet)) { - CreateEvents(childEventSet); + selectedEvents.Add(eventSet, new List()); } + selectedEvents[eventSet].Add(newEvent); + } + + foreach (ScriptedEventSet childEventSet in eventSet.ChildSets) + { + CreateEvents(childEventSet); } } } @@ -304,14 +296,11 @@ namespace Barotrauma 0.0f, 1.0f); //don't create new events if within 50 meters of the start/end of the level - if (!eventSet.AllowAtStart) + if (distanceTraveled <= 0.0f || + distFromStart * Physics.DisplayToRealWorldRatio < 50.0f || + distFromEnd * Physics.DisplayToRealWorldRatio < 50.0f) { - if (distanceTraveled <= 0.0f || - distFromStart * Physics.DisplayToRealWorldRatio < 50.0f || - distFromEnd * Physics.DisplayToRealWorldRatio < 50.0f) - { - return false; - } + return false; } if ((Submarine.MainSub == null || distanceTraveled < eventSet.MinDistanceTraveled) && diff --git a/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/CombatMission.cs b/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/CombatMission.cs index 20c2dafd9..6e5da3bf8 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/CombatMission.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/CombatMission.cs @@ -44,11 +44,6 @@ namespace Barotrauma } } - public override int TeamCount - { - get { return 2; } - } - public CombatMission(MissionPrefab prefab, Location[] locations) : base(prefab, locations) { @@ -118,7 +113,7 @@ namespace Barotrauma { for (int i = 0; i < 2; i++) { - if (wifiComponent.Item.Submarine == subs[i] || subs[i].ConnectedDockingPorts.ContainsKey(wifiComponent.Item.Submarine)) + if (wifiComponent.Item.Submarine == subs[i] || subs[i].DockedTo.Contains(wifiComponent.Item.Submarine)) { wifiComponent.TeamID = subs[i].TeamID; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/Mission.cs b/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/Mission.cs index 7b9ddacd4..3386a00ec 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/Mission.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/Mission.cs @@ -74,11 +74,6 @@ namespace Barotrauma get { return true; } } - public virtual int TeamCount - { - get { return 1; } - } - public virtual IEnumerable SonarPositions { get { return Enumerable.Empty(); } @@ -141,7 +136,7 @@ namespace Barotrauma } else { - allowedMissions.AddRange(MissionPrefab.List.Where(m => ((int)(missionType & m.Type)) != 0)); + allowedMissions.AddRange(MissionPrefab.List.Where(m => ((int)(missionType & m.type)) != 0)); } allowedMissions.RemoveAll(m => isSinglePlayer ? m.MultiplayerOnly : m.SingleplayerOnly); @@ -173,9 +168,10 @@ namespace Barotrauma public virtual void Update(float deltaTime) { } - public virtual void AssignTeamIDs(List clients) + public virtual bool AssignTeamIDs(List clients) { clients.ForEach(c => c.TeamID = Character.TeamType.Team1); + return false; } protected void ShowMessage(int missionState) diff --git a/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/MissionPrefab.cs b/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/MissionPrefab.cs index a354e7972..aa0092485 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/MissionPrefab.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Events/Missions/MissionPrefab.cs @@ -31,7 +31,7 @@ namespace Barotrauma private readonly ConstructorInfo constructor; - public readonly MissionType Type; + public readonly MissionType type; public readonly bool MultiplayerOnly, SingleplayerOnly; @@ -154,18 +154,18 @@ namespace Barotrauma } string missionTypeName = element.GetAttributeString("type", ""); - if (!Enum.TryParse(missionTypeName, out Type)) + if (!Enum.TryParse(missionTypeName, out type)) { DebugConsole.ThrowError("Error in mission prefab \"" + Name + "\" - \"" + missionTypeName + "\" is not a valid mission type."); return; } - if (Type == MissionType.None) + if (type == MissionType.None) { DebugConsole.ThrowError("Error in mission prefab \"" + Name + "\" - mission type cannot be none."); return; } - constructor = missionClasses[Type].GetConstructor(new[] { typeof(MissionPrefab), typeof(Location[]) }); + constructor = missionClasses[type].GetConstructor(new[] { typeof(MissionPrefab), typeof(Location[]) }); InitProjSpecific(element); } @@ -176,11 +176,11 @@ namespace Barotrauma { foreach (Pair allowedLocationType in AllowedLocationTypes) { - if (allowedLocationType.First.Equals("any", StringComparison.OrdinalIgnoreCase) || - allowedLocationType.First.Equals(from.Type.Identifier, StringComparison.OrdinalIgnoreCase)) + if (allowedLocationType.First.ToLowerInvariant() == "any" || + allowedLocationType.First.ToLowerInvariant() == from.Type.Identifier.ToLowerInvariant()) { - if (allowedLocationType.Second.Equals("any", StringComparison.OrdinalIgnoreCase) || - allowedLocationType.Second.Equals(to.Type.Identifier, StringComparison.OrdinalIgnoreCase)) + if (allowedLocationType.Second.ToLowerInvariant() == "any" || + allowedLocationType.Second.ToLowerInvariant() == to.Type.Identifier.ToLowerInvariant()) { return true; } @@ -189,7 +189,7 @@ namespace Barotrauma return false; } - + public Mission Instantiate(Location[] locations) { return constructor?.Invoke(new object[] { this, locations }) as Mission; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Events/MonsterEvent.cs b/Barotrauma/BarotraumaShared/SharedSource/Events/MonsterEvent.cs index 4b23b9235..df5c497b1 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Events/MonsterEvent.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Events/MonsterEvent.cs @@ -9,38 +9,42 @@ namespace Barotrauma { class MonsterEvent : ScriptedEvent { - private readonly string speciesName; - private readonly int minAmount, maxAmount; + private string speciesName; + + private int minAmount, maxAmount; + private List monsters; - private readonly bool spawnDeep; + private bool spawnDeep; private Vector2? spawnPos; - private readonly bool disallowed; - - private readonly Level.PositionType spawnPosType; + private bool disallowed; + + private Level.PositionType spawnPosType; private bool spawnPending; + private string characterFileName; + public override Vector2 DebugDrawPos { - get { return spawnPos ?? Vector2.Zero; } + get { return spawnPos.HasValue ? spawnPos.Value : Vector2.Zero; } } - + public override string ToString() { if (maxAmount <= 1) { - return "MonsterEvent (" + speciesName + ")"; + return "MonsterEvent (" + characterFileName + ")"; } else if (minAmount < maxAmount) { - return "MonsterEvent (" + speciesName + " x" + minAmount + "-" + maxAmount + ")"; + return "MonsterEvent (" + characterFileName + " x" + minAmount + "-" + maxAmount + ")"; } else { - return "MonsterEvent (" + speciesName + " x" + maxAmount + ")"; + return "MonsterEvent (" + characterFileName + " x" + maxAmount + ")"; } } @@ -72,6 +76,7 @@ namespace Barotrauma } spawnDeep = prefab.ConfigElement.GetAttributeBool("spawndeep", false); + characterFileName = Path.GetFileName(Path.GetDirectoryName(speciesName)).ToLower(); if (GameMain.NetworkMember != null) { @@ -240,37 +245,7 @@ namespace Barotrauma { if (submarine.IsOutpost) { continue; } float minDist = GetMinDistanceToSub(submarine); - if (Vector2.DistanceSquared(submarine.WorldPosition, spawnPos.Value) < minDist * minDist) { return; } - } - - //if spawning in a ruin/cave, wait for someone to be close to it to spawning - //unnecessary monsters in places the players might never visit during the round - if (spawnPosType == Level.PositionType.Ruin || - spawnPosType == Level.PositionType.Cave) - { - bool someoneNearby = false; - float minDist = Items.Components.Sonar.DefaultSonarRange * 0.8f; - foreach (Submarine submarine in Submarine.Loaded) - { - if (submarine.IsOutpost) { continue; } - if (Vector2.DistanceSquared(submarine.WorldPosition, spawnPos.Value) < minDist * minDist) - { - someoneNearby = true; - break; - } - } - foreach (Character c in Character.CharacterList) - { - if (c == Character.Controlled || c.IsRemotePlayer) - { - if (Vector2.DistanceSquared(c.WorldPosition, spawnPos.Value) < minDist * minDist) - { - someoneNearby = true; - break; - } - } - } - if (!someoneNearby) { return; } + if (Vector2.DistanceSquared(submarine.WorldPosition, spawnPos.Value) < minDist * minDist) return; } spawnPending = false; @@ -305,7 +280,7 @@ namespace Barotrauma Entity targetEntity = Submarine.FindClosest(GameMain.GameScreen.Cam.WorldViewCenter); #if CLIENT - if (Character.Controlled != null) { targetEntity = Character.Controlled; } + if (Character.Controlled != null) targetEntity = (Entity)Character.Controlled; #endif bool monstersDead = true; @@ -322,7 +297,7 @@ namespace Barotrauma } } - if (monstersDead) { Finished(); } + if (monstersDead) Finished(); } } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Events/ScriptedEventSet.cs b/Barotrauma/BarotraumaShared/SharedSource/Events/ScriptedEventSet.cs index 190a1a28b..333974395 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Events/ScriptedEventSet.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Events/ScriptedEventSet.cs @@ -25,10 +25,6 @@ namespace Barotrauma //the events in this set are delayed if the current EventManager intensity is not between these values public readonly float MinIntensity, MaxIntensity; - public readonly bool AllowAtStart; - - public readonly bool PerRuin; - public readonly Dictionary Commonness; public readonly List EventPrefabs; @@ -58,9 +54,6 @@ namespace Barotrauma MinDistanceTraveled = element.GetAttributeFloat("mindistancetraveled", 0.0f); MinMissionTime = element.GetAttributeFloat("minmissiontime", 0.0f); - AllowAtStart = element.GetAttributeBool("allowatstart", false); - PerRuin = element.GetAttributeBool("perruin", false); - Commonness[""] = 1.0f; foreach (XElement subElement in element.Elements()) { @@ -70,7 +63,7 @@ namespace Barotrauma Commonness[""] = subElement.GetAttributeFloat("commonness", 0.0f); foreach (XElement overrideElement in subElement.Elements()) { - if (overrideElement.Name.ToString().Equals("override", StringComparison.OrdinalIgnoreCase)) + if (overrideElement.Name.ToString().ToLowerInvariant() == "override") { string levelType = overrideElement.GetAttributeString("leveltype", ""); if (!Commonness.ContainsKey(levelType)) @@ -123,7 +116,7 @@ namespace Barotrauma int i = 0; foreach (XElement element in doc.Root.Elements()) { - if (!element.Name.ToString().Equals("eventset", StringComparison.OrdinalIgnoreCase)) { continue; } + if (element.Name.ToString().ToLowerInvariant() != "eventset") { continue; } List.Add(new ScriptedEventSet(element, i.ToString())); i++; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Extensions/IEnumerableExtensions.cs b/Barotrauma/BarotraumaShared/SharedSource/Extensions/IEnumerableExtensions.cs index b2dfb78c1..a769afa54 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Extensions/IEnumerableExtensions.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Extensions/IEnumerableExtensions.cs @@ -7,23 +7,24 @@ namespace Barotrauma.Extensions public static class IEnumerableExtensions { /// - /// Randomizes the collection (using OrderBy) and returns it. + /// Randomizes the collection and returns it. /// - public static IOrderedEnumerable Randomize(this IEnumerable source, Rand.RandSync randSync = Rand.RandSync.Unsynced) + public static IOrderedEnumerable Randomize(this IEnumerable source) { - return source.OrderBy(i => Rand.Value(randSync)); + return source.OrderBy(i => Rand.Value()); } /// - /// Randomizes the list in place without creating a new collection, using a Fisher-Yates-based algorithm. + /// Randomizes the list in place. /// - public static void Shuffle(this IList list, Rand.RandSync randSync = Rand.RandSync.Unsynced) + public static void RandomizeList(this List list) { + //Fisher-Yates shuffle int n = list.Count; while (n > 1) { n--; - int k = Rand.Int(n + 1, randSync); + int k = Rand.Int(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; @@ -89,11 +90,6 @@ namespace Barotrauma.Extensions return source.Count(predicate) > 1; } } - - public static IEnumerable ToEnumerable(this T item) - { - yield return item; - } // source: https://stackoverflow.com/questions/19237868/get-all-children-to-one-list-recursive-c-sharp public static IEnumerable SelectManyRecursive(this IEnumerable source, Func> selector) diff --git a/Barotrauma/BarotraumaShared/SharedSource/GameSession/AutoItemPlacer.cs b/Barotrauma/BarotraumaShared/SharedSource/GameSession/AutoItemPlacer.cs index 3c0a12681..b77825408 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/GameSession/AutoItemPlacer.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/GameSession/AutoItemPlacer.cs @@ -66,7 +66,7 @@ namespace Barotrauma spawnedItems.Clear(); var validContainers = new Dictionary(); - prefabsWithContainer.Shuffle(); + prefabsWithContainer.RandomizeList(); // Spawn items that have an ItemContainer component first so we can fill them up with items if needed (oxygen tanks inside the spawned diving masks, etc) for (int i = 0; i < prefabsWithContainer.Count; i++) { @@ -82,7 +82,7 @@ namespace Barotrauma // Another pass for items with containers because also they can spawn inside other items (like smg magazine) prefabsWithContainer.ForEach(i => SpawnItems(i)); // Spawn items that don't have containers last - prefabsWithoutContainer.Shuffle(); + prefabsWithoutContainer.RandomizeList(); prefabsWithoutContainer.ForEach(i => SpawnItems(i)); if (OutputDebugInfo) diff --git a/Barotrauma/BarotraumaShared/SharedSource/GameSession/GameSession.cs b/Barotrauma/BarotraumaShared/SharedSource/GameSession/GameSession.cs index ac4f1fa65..3964464a1 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/GameSession/GameSession.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/GameSession/GameSession.cs @@ -150,14 +150,14 @@ namespace Barotrauma SaveUtil.LoadGame(SavePath); } - public void StartRound(string levelSeed, float? difficulty = null) + public void StartRound(string levelSeed, float? difficulty = null, bool loadSecondSub = false) { Level randomLevel = Level.CreateRandom(levelSeed, difficulty); - StartRound(randomLevel, true); + StartRound(randomLevel, true, loadSecondSub); } - public void StartRound(Level level, bool reloadSub = true, bool mirrorLevel = false) + public void StartRound(Level level, bool reloadSub = true, bool loadSecondSub = false, bool mirrorLevel = false) { //make sure no status effects have been carried on from the next round //(they should be stopped in EndRound, this is a safeguard against cases where the round is ended ungracefully) @@ -177,7 +177,7 @@ namespace Barotrauma if (reloadSub || Submarine.MainSub != Submarine) { Submarine.Load(true); } Submarine.MainSub = Submarine; - if (GameMode.Mission != null && GameMode.Mission.TeamCount > 1) + if (loadSecondSub) { if (Submarine.MainSubs[1] == null) { @@ -231,7 +231,7 @@ namespace Barotrauma if (port.Item.WorldPosition.Y < Submarine.WorldPosition.Y) { continue; } float dist = Vector2.DistanceSquared(port.Item.WorldPosition, level.StartOutpost.WorldPosition); - if (myPort == null || dist < closestDistance || (port.MainDockingPort && !myPort.MainDockingPort)) + if (myPort == null || dist < closestDistance) { myPort = port; closestDistance = dist; diff --git a/Barotrauma/BarotraumaShared/SharedSource/GameSettings.cs b/Barotrauma/BarotraumaShared/SharedSource/GameSettings.cs index 51d1695d9..11424d818 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/GameSettings.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/GameSettings.cs @@ -198,7 +198,7 @@ namespace Barotrauma { voiceChatVolume = MathHelper.Clamp(value, 0.0f, 1.0f); #if CLIENT - GameMain.SoundManager?.SetCategoryGainMultiplier("voip", voiceChatVolume, 0); + GameMain.SoundManager?.SetCategoryGainMultiplier("voip", voiceChatVolume * 30.0f, 0); #endif } } @@ -236,7 +236,6 @@ namespace Barotrauma #if DEBUG public bool AutomaticQuickStartEnabled { get; set; } - public bool TextManagerDebugModeEnabled { get; set; } #endif private FileSystemWatcher modsFolderWatcher; @@ -1203,7 +1202,6 @@ namespace Barotrauma new XAttribute("tutorialskipwarning", ShowTutorialSkipWarning) #if DEBUG , new XAttribute("automaticquickstartenabled", AutomaticQuickStartEnabled) - , new XAttribute("textmanagerdebugmodeenabled", TextManagerDebugModeEnabled) #endif ); @@ -1389,7 +1387,6 @@ namespace Barotrauma ShowTutorialSkipWarning = doc.Root.GetAttributeBool("tutorialskipwarning", true); #if DEBUG AutomaticQuickStartEnabled = doc.Root.GetAttributeBool("automaticquickstartenabled", AutomaticQuickStartEnabled); - TextManagerDebugModeEnabled = doc.Root.GetAttributeBool("textmanagerdebugmodeenabled", TextManagerDebugModeEnabled); #endif XElement gameplayElement = doc.Root.Element("gameplay"); jobPreferences = new List>(); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/CharacterInventory.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/CharacterInventory.cs index e962781f8..c6cc4d6d8 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/CharacterInventory.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/CharacterInventory.cs @@ -73,7 +73,7 @@ namespace Barotrauma foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("item", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "item") continue; string itemIdentifier = subElement.GetAttributeString("identifier", ""); ItemPrefab itemPrefab = MapEntityPrefab.Find(null, itemIdentifier) as ItemPrefab; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/DockingPort.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/DockingPort.cs index ec9e72a82..d958b9eb3 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/DockingPort.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/DockingPort.cs @@ -58,13 +58,6 @@ namespace Barotrauma.Items.Components set; } - [Serialize(false, false, description: "If set to true, this docking port is used when spawning the submarine docked to an outpost (if possible).")] - public bool MainDockingPort - { - get; - set; - } - public DockingPort DockingTarget { get; private set; } public bool Docked @@ -180,8 +173,8 @@ namespace Barotrauma.Items.Components if (!item.linkedTo.Contains(target.item)) item.linkedTo.Add(target.item); if (!target.item.linkedTo.Contains(item)) target.item.linkedTo.Add(item); - if (!target.item.Submarine.DockedTo.Contains(item.Submarine)) target.item.Submarine.ConnectedDockingPorts.Add(item.Submarine, target); - if (!item.Submarine.DockedTo.Contains(target.item.Submarine)) item.Submarine.ConnectedDockingPorts.Add(target.item.Submarine, this); + if (!target.item.Submarine.DockedTo.Contains(item.Submarine)) target.item.Submarine.DockedTo.Add(item.Submarine); + if (!item.Submarine.DockedTo.Contains(target.item.Submarine)) item.Submarine.DockedTo.Add(target.item.Submarine); DockingTarget = target; DockingTarget.DockingTarget = this; @@ -710,8 +703,8 @@ namespace Barotrauma.Items.Components ApplyStatusEffects(ActionType.OnSecondaryUse, 1.0f); - DockingTarget.item.Submarine.ConnectedDockingPorts.Remove(item.Submarine); - item.Submarine.ConnectedDockingPorts.Remove(DockingTarget.item.Submarine); + DockingTarget.item.Submarine.DockedTo.Remove(item.Submarine); + item.Submarine.DockedTo.Remove(DockingTarget.item.Submarine); if (door != null && DockingTarget.door != null) { diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Door.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Door.cs index 45d565f4c..7a9b760b7 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Door.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Door.cs @@ -287,21 +287,24 @@ namespace Barotrauma.Items.Components public override bool Select(Character character) { - if (isBroken) { return true; } - bool hasRequiredItems = HasRequiredItems(character, false); - if (HasAccess(character)) + if (!isBroken) { - float originalPickingTime = PickingTime; - PickingTime = 0; - ToggleState(ActionType.OnUse, character); - PickingTime = originalPickingTime; - } + bool hasRequiredItems = HasRequiredItems(character, false); + if (HasAccess(character)) + { + float originalPickingTime = PickingTime; + PickingTime = 0; + ToggleState(ActionType.OnUse, character); + PickingTime = originalPickingTime; + } #if CLIENT - else if (hasRequiredItems && character != null && character == Character.Controlled) - { - GUI.AddMessage(accessDeniedTxt, GUI.Style.Red); - } + else if (hasRequiredItems && character != null && character == Character.Controlled) + { + GUI.AddMessage(accessDeniedTxt, GUI.Style.Red); + + } #endif + } return false; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/MeleeWeapon.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/MeleeWeapon.cs index 0f575f5d1..f2a6bf1f6 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/MeleeWeapon.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/MeleeWeapon.cs @@ -54,7 +54,7 @@ namespace Barotrauma.Items.Components { foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("attack", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "attack") { continue; } attack = new Attack(subElement, item.Name + ", MeleeWeapon"); } item.IsShootable = true; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/RangedWeapon.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/RangedWeapon.cs index 4366bdcaa..94f4d3e38 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/RangedWeapon.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/RangedWeapon.cs @@ -29,13 +29,6 @@ namespace Barotrauma.Items.Components set { reload = Math.Max(value, 0.0f); } } - [Serialize(1, false, description: "How projectiles the weapon launches when fired once.")] - public int ProjectileCount - { - get; - set; - } - [Serialize(0.0f, false, description: "Random spread applied to the firing angle of the projectiles when used by a character with sufficient skills to use the weapon (in degrees).")] public float Spread { @@ -117,61 +110,55 @@ namespace Barotrauma.Items.Components ApplyStatusEffects(ActionType.OnFailure, 1.0f, character); } - for (int i = 0; i < ProjectileCount; i++) + Projectile projectile = FindProjectile(triggerOnUseOnContainers: true); + if (projectile == null) { return true; } + + float spread = GetSpread(character); + float rotation = (item.body.Dir == 1.0f) ? item.body.Rotation : item.body.Rotation - MathHelper.Pi; + rotation += spread * Rand.Range(-0.5f, 0.5f); + + projectile.User = character; + //add the limbs of the shooter to the list of bodies to be ignored + //so that the player can't shoot himself + projectile.IgnoredBodies = new List(limbBodies); + + Vector2 projectilePos = item.SimPosition; + Vector2 sourcePos = character?.AnimController == null ? item.SimPosition : character.AnimController.AimSourceSimPos; + Vector2 barrelPos = TransformedBarrelPos + item.body.SimPosition; + //make sure there's no obstacles between the base of the weapon (or the shoulder of the character) and the end of the barrel + if (Submarine.PickBody(sourcePos, barrelPos, projectile.IgnoredBodies, Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionItemBlocking) == null) { - Projectile projectile = FindProjectile(triggerOnUseOnContainers: true); - if (projectile == null) { return true; } - - float spread = GetSpread(character); - float rotation = (item.body.Dir == 1.0f) ? item.body.Rotation : item.body.Rotation - MathHelper.Pi; - rotation += spread * Rand.Range(-0.5f, 0.5f); - - projectile.User = character; - //add the limbs of the shooter to the list of bodies to be ignored - //so that the player can't shoot himself - projectile.IgnoredBodies = new List(limbBodies); - - Vector2 projectilePos = item.SimPosition; - Vector2 sourcePos = character?.AnimController == null ? item.SimPosition : character.AnimController.AimSourceSimPos; - Vector2 barrelPos = TransformedBarrelPos + item.body.SimPosition; - //make sure there's no obstacles between the base of the weapon (or the shoulder of the character) and the end of the barrel - if (Submarine.PickBody(sourcePos, barrelPos, projectile.IgnoredBodies, Physics.CollisionWall | Physics.CollisionLevel | Physics.CollisionItemBlocking) == null) - { - //no obstacles -> we can spawn the projectile at the barrel - projectilePos = barrelPos; - } - else if ((sourcePos - barrelPos).LengthSquared() > 0.0001f) - { - //spawn the projectile body.GetMaxExtent() away from the position where the raycast hit the obstacle - projectilePos = sourcePos - Vector2.Normalize(barrelPos - projectilePos) * Math.Max(projectile.Item.body.GetMaxExtent(), 0.1f); - } - - projectile.Item.body.ResetDynamics(); - projectile.Item.SetTransform(projectilePos, rotation); - - projectile.Use(deltaTime); - if (projectile.Item.Removed) { continue; } - projectile.User = character; - - projectile.Item.body.ApplyTorque(projectile.Item.body.Mass * degreeOfFailure * Rand.Range(-10.0f, 10.0f)); - - //set the rotation of the projectile again because dropping the projectile resets the rotation - projectile.Item.SetTransform(projectilePos, - rotation + (projectile.Item.body.Dir * projectile.LaunchRotationRadians)); - - item.RemoveContained(projectile.Item); - - if (i == 0) - { - //recoil - item.body.ApplyLinearImpulse( - new Vector2((float)Math.Cos(projectile.Item.body.Rotation), (float)Math.Sin(projectile.Item.body.Rotation)) * item.body.Mass * -50.0f, - maxVelocity: NetConfig.MaxPhysicsBodyVelocity); - } + //no obstacles -> we can spawn the projectile at the barrel + projectilePos = barrelPos; } + else if ((sourcePos - barrelPos).LengthSquared() > 0.0001f) + { + //spawn the projectile body.GetMaxExtent() away from the position where the raycast hit the obstacle + projectilePos = sourcePos - Vector2.Normalize(barrelPos - projectilePos) * Math.Max(projectile.Item.body.GetMaxExtent(), 0.1f); + } + + projectile.Item.body.ResetDynamics(); + projectile.Item.SetTransform(projectilePos, rotation); + + projectile.Use(deltaTime); + if (projectile.Item.Removed) { return true; } + projectile.User = character; + + projectile.Item.body.ApplyTorque(projectile.Item.body.Mass * degreeOfFailure * Rand.Range(-10.0f, 10.0f)); + + //set the rotation of the projectile again because dropping the projectile resets the rotation + projectile.Item.SetTransform(projectilePos, + rotation + (projectile.Item.body.Dir * projectile.LaunchRotationRadians)); + + //recoil + item.body.ApplyLinearImpulse( + new Vector2((float)Math.Cos(projectile.Item.body.Rotation), (float)Math.Sin(projectile.Item.body.Rotation)) * item.body.Mass * -50.0f, + maxVelocity: NetConfig.MaxPhysicsBodyVelocity); LaunchProjSpecific(); + item.RemoveContained(projectile.Item); + return true; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/RepairTool.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/RepairTool.cs index 7d7638c33..31b47c057 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/RepairTool.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Holdable/RepairTool.cs @@ -578,7 +578,13 @@ namespace Barotrauma.Items.Components { character.SetInput(InputType.Aim, false, true); } - sinTime += deltaTime * 5; + bool isAiming = false; + var holdable = item.GetComponent(); + if (holdable != null) + { + isAiming = holdable.ControlPose; + } + sinTime = isAiming ? sinTime + deltaTime * 5 : 0; } // Press the trigger only when the tool is approximately facing the target. Vector2 fromItemToLeak = leak.WorldPosition - item.WorldPosition; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/ItemComponent.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/ItemComponent.cs index 5687f6ddb..73e3baad9 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/ItemComponent.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/ItemComponent.cs @@ -741,7 +741,7 @@ namespace Barotrauma.Items.Components { foreach (XAttribute attribute in componentElement.Attributes()) { - if (!SerializableProperties.TryGetValue(attribute.Name.ToString().ToLowerInvariant(), out SerializableProperty property)) { continue; } + if (!SerializableProperties.TryGetValue(attribute.Name.ToString().ToLowerInvariant(), out SerializableProperty property)) continue; property.TrySetValue(this, attribute.Value); } ParseMsg(); @@ -870,7 +870,6 @@ namespace Barotrauma.Items.Components switch (subElement.Name.ToString().ToLowerInvariant()) { case "requireditem": - case "requireditems": RelatedItem newRequiredItem = RelatedItem.Load(subElement, returnEmptyRequirements, item.Name); if (newRequiredItem == null) continue; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Fabricator.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Fabricator.cs index bf975c14e..7bdd7bfdc 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Fabricator.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Fabricator.cs @@ -39,7 +39,7 @@ namespace Barotrauma.Items.Components { foreach (XElement subElement in element.Elements()) { - if (subElement.Name.ToString().Equals("fabricableitem", StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() == "fabricableitem") { DebugConsole.ThrowError("Error in item " + item.Name + "! Fabrication recipes should be defined in the craftable item's xml, not in the fabricator."); break; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Pump.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Pump.cs index cc0b63766..520b0b0a3 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Pump.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Pump.cs @@ -144,7 +144,7 @@ namespace Barotrauma.Items.Components if (GameMain.Client != null) { return false; } #endif - if (objective.Option.Equals("stoppumping", StringComparison.OrdinalIgnoreCase)) + if (objective.Option.ToLowerInvariant() == "stoppumping") { #if SERVER if (FlowPercentage > 0.0f) diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Reactor.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Reactor.cs index 82f3f24f6..68d569275 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Reactor.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Machines/Reactor.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Barotrauma.Extensions; -using System.Globalization; namespace Barotrauma.Items.Components { @@ -652,20 +651,6 @@ namespace Barotrauma.Items.Components unsentChanges = true; } break; - case "set_fissionrate": - if (float.TryParse(signal, NumberStyles.Float, CultureInfo.InvariantCulture, out float newFissionRate)) - { - FissionRate = newFissionRate; - unsentChanges = true; - } - break; - case "set_turbineoutput": - if (float.TryParse(signal, NumberStyles.Float, CultureInfo.InvariantCulture, out float newTurbineOutput)) - { - TurbineOutput = newTurbineOutput; - unsentChanges = true; - } - break; } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Power/PowerContainer.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Power/PowerContainer.cs index 755391dc9..f2d9706b1 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Power/PowerContainer.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Power/PowerContainer.cs @@ -213,7 +213,7 @@ namespace Barotrauma.Items.Components } if (HasBeenTuned) { return true; } - if (string.IsNullOrEmpty(objective.Option) || objective.Option.Equals("charge", StringComparison.OrdinalIgnoreCase)) + if (string.IsNullOrEmpty(objective.Option) || objective.Option.ToLowerInvariant() == "charge") { if (Math.Abs(rechargeSpeed - maxRechargeSpeed * aiRechargeTargetRatio) > 0.05f) { diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Projectile.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Projectile.cs index cc4219912..27e46c46d 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Projectile.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Projectile.cs @@ -53,9 +53,7 @@ namespace Barotrauma.Items.Components private PrismaticJoint stickJoint; private Body stickTarget; - private readonly Attack attack; - - private Vector2 launchPos; + private Attack attack; public List IgnoredBodies; @@ -159,7 +157,7 @@ namespace Barotrauma.Items.Components foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("attack", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "attack") continue; attack = new Attack(subElement, item.Name + ", Projectile"); } } @@ -222,8 +220,6 @@ namespace Barotrauma.Items.Components item.Drop(null); - launchPos = item.SimPosition; - item.body.Enabled = true; item.body.ApplyLinearImpulse(impulse, maxVelocity: NetConfig.MaxPhysicsBodyVelocity); @@ -419,9 +415,7 @@ namespace Barotrauma.Items.Components item.body.SimPosition - ConvertUnits.ToSimUnits(sub.Position) - dir, item.body.SimPosition - ConvertUnits.ToSimUnits(sub.Position) + dir, collisionCategory: Physics.CollisionWall); - if (wallBody?.FixtureList?.First() != null && wallBody.UserData is Structure structure && - //ignore the hit if it's behind the position the item was launched from, and the projectile is travelling in the opposite direction - Vector2.Dot(item.body.SimPosition - launchPos, dir) > 0) + if (wallBody?.FixtureList?.First() != null && wallBody.UserData is Structure structure) { target = wallBody.FixtureList.First(); } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Repairable.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Repairable.cs index 457ae0617..4544bd612 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Repairable.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Repairable.cs @@ -1,5 +1,4 @@ -using Barotrauma.Extensions; -using Barotrauma.Networking; +using Barotrauma.Networking; using Microsoft.Xna.Framework; using System; using System.Globalization; @@ -112,7 +111,7 @@ namespace Barotrauma.Items.Components element.GetAttributeString("name", ""); //backwards compatibility - var showRepairUIAttribute = element.Attributes().FirstOrDefault(a => a.Name.ToString().Equals("showrepairuithreshold", StringComparison.OrdinalIgnoreCase)); + var showRepairUIAttribute = element.Attributes().FirstOrDefault(a => a.Name.ToString().ToLowerInvariant() == "showrepairuithreshold"); if (showRepairUIAttribute != null) { float repairThreshold; @@ -131,26 +130,7 @@ namespace Barotrauma.Items.Components } partial void InitProjSpecific(XElement element); - - /// - /// Check if the character manages to succesfully repair the item - /// - public bool CheckCharacterSuccess(Character character) - { - if (character == null) { return false; } - - // Only check for success when repairing electrical devices - if (requiredSkills.None(s => s != null && s.Identifier.Equals("electrical", StringComparison.OrdinalIgnoreCase))) { return true; } - - //unpowered items can be repaired without a risk of electrical shock - if (item.GetComponent() is Powered powered && powered.Voltage < 0.1f) { return true; } - - if (Rand.Range(0.0f, 0.5f) < DegreeOfSuccess(character)) { return true; } - - item.ApplyStatusEffects(ActionType.OnFailure, 1.0f, character); - return false; - } - + public bool StartRepairing(Character character, FixActions action) { if (character == null || character.IsDead || action == FixActions.None) @@ -163,15 +143,8 @@ namespace Barotrauma.Items.Components #if SERVER if (CurrentFixer != character || currentFixerAction != action) { - if (!CheckCharacterSuccess(character)) - { - GameMain.Server?.CreateEntityEvent(item, new object[] { NetEntityEvent.Type.ApplyStatusEffect, ActionType.OnFailure, this, character.ID }); - return false; - } item.CreateServerEvent(this); } -#else - if (GameMain.Client == null && (CurrentFixer != character || currentFixerAction != action) && !CheckCharacterSuccess(character)) { return false; } #endif CurrentFixer = character; CurrentFixerAction = action; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/Connection.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/Connection.cs index edbfddcdd..ada7e145b 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/Connection.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/Connection.cs @@ -88,7 +88,7 @@ namespace Barotrauma.Items.Components { foreach (XElement subElement in item.Prefab.ConfigElement.Elements()) { - if (!subElement.Name.ToString().Equals("connectionpanel", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "connectionpanel") { continue; } foreach (XElement connectionElement in subElement.Elements()) { diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/CustomInterface.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/CustomInterface.cs index 92115c571..6f0ca45b8 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/CustomInterface.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/CustomInterface.cs @@ -32,7 +32,7 @@ namespace Barotrauma.Items.Components foreach (XElement subElement in element.Elements()) { - if (subElement.Name.ToString().Equals("statuseffect", System.StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() == "statuseffect") { StatusEffects.Add(StatusEffect.Load(subElement, parentDebugName: "custom interface element (label " + Label + ")")); } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/LightComponent.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/LightComponent.cs index 67c7e815b..7a150d53f 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/LightComponent.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/LightComponent.cs @@ -272,12 +272,13 @@ namespace Barotrauma.Items.Components private void UpdateAITarget(AITarget target) { + target.Enabled = IsActive; if (!IsActive) { return; } if (target.MaxSightRange <= 0) { target.MaxSightRange = Range * 5; } - target.SightRange = Math.Max(target.SightRange, target.MaxSightRange * lightBrightness); + target.SightRange = target.MaxSightRange * lightBrightness; } partial void SetLightSourceState(bool enabled, float brightness); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/WifiComponent.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/WifiComponent.cs index 5513e315e..a1da8e1d1 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/WifiComponent.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Signal/WifiComponent.cs @@ -39,14 +39,6 @@ namespace Barotrauma.Items.Components } } - - [Serialize(false, false, description: "Can the component communicate with wifi components in another team's submarine (e.g. enemy sub in Combat missions, respawn shuttle). Needs to be enabled on both the component transmitting the signal and the component receiving it.")] - public bool AllowCrossTeamCommunication - { - get; - set; - } - [Editable, Serialize(false, false, description: "If enabled, any signals received from another chat-linked wifi component are displayed " + "as chat messages in the chatbox of the player holding the item.")] public bool LinkToChat @@ -92,7 +84,7 @@ namespace Barotrauma.Items.Components { if (sender == null || sender.channel != channel) { return false; } - if (sender.TeamID != TeamID && !AllowCrossTeamCommunication) + if (sender.TeamID != TeamID) { return false; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Turret.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Turret.cs index 00eeec4d8..5879e6be8 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Turret.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Turret.cs @@ -72,13 +72,6 @@ namespace Barotrauma.Items.Components set { reloadTime = value; } } - [Serialize(1, false, description: "How projectiles the weapon launches when fired once.")] - public int ProjectileCount - { - get; - set; - } - [Editable, Serialize("0.0,0.0", true, description: "The range at which the barrel can rotate. TODO")] public Vector2 RotationLimits { @@ -220,13 +213,13 @@ namespace Barotrauma.Items.Components { this.cam = cam; - if (reload > 0.0f) { reload -= deltaTime; } + if (reload > 0.0f) reload -= deltaTime; ApplyStatusEffects(ActionType.OnActive, deltaTime, null); UpdateProjSpecific(deltaTime); - if (minRotation == maxRotation) { return; } + if (minRotation == maxRotation) return; float targetMidDiff = MathHelper.WrapAngle(targetRotation - (minRotation + maxRotation) / 2.0f); @@ -237,19 +230,12 @@ namespace Barotrauma.Items.Components targetRotation = (targetMidDiff < 0.0f) ? minRotation : maxRotation; } - float degreeOfSuccess = user == null ? 0.5f : DegreeOfSuccess(user); - if (degreeOfSuccess < 0.5f) { degreeOfSuccess *= degreeOfSuccess; } //the ease of aiming drops quickly with insufficient skill levels + float degreeOfSuccess = user == null ? 0.5f : DegreeOfSuccess(user); + if (degreeOfSuccess < 0.5f) degreeOfSuccess *= degreeOfSuccess; //the ease of aiming drops quickly with insufficient skill levels float springStiffness = MathHelper.Lerp(SpringStiffnessLowSkill, SpringStiffnessHighSkill, degreeOfSuccess); float springDamping = MathHelper.Lerp(SpringDampingLowSkill, SpringDampingHighSkill, degreeOfSuccess); float rotationSpeed = MathHelper.Lerp(RotationSpeedLowSkill, RotationSpeedHighSkill, degreeOfSuccess); - if (user?.Info != null) - { - user.Info.IncreaseSkillLevel("weapons", - SkillSettings.Current.SkillIncreasePerSecondWhenOperatingTurret * deltaTime / Math.Max(user.GetSkillLevel("weapons"), 1.0f), - user.WorldPosition + Vector2.UnitY * 150.0f); - } - angularVelocity += (MathHelper.WrapAngle(targetRotation - rotation) * springStiffness - angularVelocity * springDamping) * deltaTime; angularVelocity = MathHelper.Clamp(angularVelocity, -rotationSpeed, rotationSpeed); @@ -279,16 +265,18 @@ namespace Barotrauma.Items.Components public override bool Use(float deltaTime, Character character = null) { - if (!characterUsable && character != null) { return false; } + if (!characterUsable && character != null) return false; return TryLaunch(deltaTime, character); } private bool TryLaunch(float deltaTime, Character character = null) { - if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient) { return false; } +#if CLIENT + if (GameMain.Client != null) return false; +#endif + + if (reload > 0.0f) return false; - if (reload > 0.0f) { return false; } - if (GetAvailableBatteryPower() < powerConsumption) { #if CLIENT @@ -300,77 +288,72 @@ namespace Barotrauma.Items.Components #endif return false; } - - Projectile launchedProjectile = null; - for (int i = 0; i < ProjectileCount; i++) + + foreach (MapEntity e in item.linkedTo) { - foreach (MapEntity e in item.linkedTo) + //use linked projectile containers in case they have to react to the turret being launched somehow + //(play a sound, spawn more projectiles) + if (!(e is Item linkedItem)) continue; + ItemContainer projectileContainer = linkedItem.GetComponent(); + if (projectileContainer != null) { - //use linked projectile containers in case they have to react to the turret being launched somehow - //(play a sound, spawn more projectiles) - if (!(e is Item linkedItem)) { continue; } - ItemContainer projectileContainer = linkedItem.GetComponent(); - if (projectileContainer != null) + linkedItem.Use(deltaTime, null); + var repairable = linkedItem.GetComponent(); + if (repairable != null) { - linkedItem.Use(deltaTime, null); - var repairable = linkedItem.GetComponent(); - if (repairable != null) - { - repairable.LastActiveTime = (float)Timing.TotalTime + 1.0f; - } + repairable.LastActiveTime = (float)Timing.TotalTime + 1.0f; } } - - var projectiles = GetLoadedProjectiles(true); - if (projectiles.Count == 0) - { - //coilguns spawns ammo in the ammo boxes with the OnUse statuseffect when the turret is launched, - //causing a one frame delay before the gun can be launched (or more in multiplayer where there may be a longer delay) - // -> attempt to launch the gun multiple times before showing the "no ammo" flash - failedLaunchAttempts++; -#if CLIENT - if (!flashNoAmmo && character != null && character == Character.Controlled && failedLaunchAttempts > 20) - { - flashNoAmmo = true; - failedLaunchAttempts = 0; - GUI.PlayUISound(GUISoundType.PickItemFail); - } -#endif - return false; - } - - failedLaunchAttempts = 0; - - var batteries = item.GetConnectedComponents(); - float neededPower = powerConsumption; - - while (neededPower > 0.0001f && batteries.Count > 0) - { - batteries.RemoveAll(b => b.Charge <= 0.0001f || b.MaxOutPut <= 0.0001f); - float takePower = neededPower / batteries.Count; - takePower = Math.Min(takePower, batteries.Min(b => Math.Min(b.Charge * 3600.0f, b.MaxOutPut))); - foreach (PowerContainer battery in batteries) - { - neededPower -= takePower; - battery.Charge -= takePower / 3600.0f; -#if SERVER - if (GameMain.Server != null) - { - battery.Item.CreateServerEvent(battery); - } -#endif - } - } - - launchedProjectile = projectiles[0]; - Launch(projectiles[0].Item, character); } -#if SERVER - if (character != null && launchedProjectile != null) + var projectiles = GetLoadedProjectiles(true); + if (projectiles.Count == 0) { - string msg = character.LogName + " launched " + item.Name + " (projectile: " + launchedProjectile.Item.Name; - var containedItems = launchedProjectile.Item.ContainedItems; + //coilguns spawns ammo in the ammo boxes with the OnUse statuseffect when the turret is launched, + //causing a one frame delay before the gun can be launched (or more in multiplayer where there may be a longer delay) + // -> attempt to launch the gun multiple times before showing the "no ammo" flash + failedLaunchAttempts++; +#if CLIENT + if (!flashNoAmmo && character != null && character == Character.Controlled && failedLaunchAttempts > 20) + { + flashNoAmmo = true; + failedLaunchAttempts = 0; + GUI.PlayUISound(GUISoundType.PickItemFail); + } +#endif + return false; + } + + failedLaunchAttempts = 0; + + var batteries = item.GetConnectedComponents(); + float neededPower = powerConsumption; + + while (neededPower > 0.0001f && batteries.Count > 0) + { + batteries.RemoveAll(b => b.Charge <= 0.0001f || b.MaxOutPut <= 0.0001f); + float takePower = neededPower / batteries.Count; + takePower = Math.Min(takePower, batteries.Min(b => Math.Min(b.Charge * 3600.0f, b.MaxOutPut))); + foreach (PowerContainer battery in batteries) + { + neededPower -= takePower; + battery.Charge -= takePower / 3600.0f; +#if SERVER + if (GameMain.Server != null) + { + battery.Item.CreateServerEvent(battery); + } +#endif + } + } + + Launch(projectiles[0].Item, character); + +#if SERVER + if (character != null) + { + string msg = character.LogName + " launched " + item.Name + " (projectile: " + projectiles[0].Item.Name; + var containedItems = projectiles[0].Item.ContainedItems; if (containedItems == null || !containedItems.Any()) { msg += ")"; @@ -564,7 +547,7 @@ namespace Barotrauma.Items.Components return false; } - if (objective.Option.Equals("fireatwill", StringComparison.OrdinalIgnoreCase)) + if (objective.Option.ToLowerInvariant() == "fireatwill") { character?.Speak(TextManager.GetWithVariable("DialogFireTurret", "[itemname]", item.Name, true), null, 0.0f, "fireturret", 5.0f); character.SetInput(InputType.Shoot, true, true); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Wearable.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Wearable.cs index c95adedb1..df34a4c9a 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Wearable.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Components/Wearable.cs @@ -211,7 +211,6 @@ namespace Barotrauma.Items.Components } public bool AutoEquipWhenFull { get; private set; } - public bool DisplayContainedStatus { get; private set; } public readonly int Variants; @@ -265,7 +264,6 @@ namespace Barotrauma.Items.Components limbType = new LimbType[spriteCount]; limb = new Limb[spriteCount]; AutoEquipWhenFull = element.GetAttributeBool("autoequipwhenfull", true); - DisplayContainedStatus = element.GetAttributeBool("displaycontainedstatus", false); int i = 0; foreach (XElement subElement in element.Elements()) { @@ -286,7 +284,7 @@ namespace Barotrauma.Items.Components foreach (XElement lightElement in subElement.Elements()) { - if (!lightElement.Name.ToString().Equals("lightcomponent", StringComparison.OrdinalIgnoreCase)) { continue; } + if (lightElement.Name.ToString().ToLowerInvariant() != "lightcomponent") continue; wearableSprites[i].LightComponent = new LightComponent(item, lightElement) { Parent = this diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/Item.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/Item.cs index 9f5c0ae56..2310af049 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/Item.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/Item.cs @@ -1839,30 +1839,6 @@ namespace Barotrauma return true; } - public float GetContainedItemConditionPercentage() - { - var containedItems = ContainedItems; - - if (containedItems != null) - { - float condition = 0f; - float maxCondition = 0f; - - foreach (Item item in containedItems) - { - condition += item.condition; - maxCondition += item.MaxCondition; - } - - if (maxCondition > 0.0f) - { - return condition / maxCondition; - } - } - - return -1; - } - public void Use(float deltaTime, Character character = null, Limb targetLimb = null) { if (RequireAimToUse && (character == null || !character.IsKeyDown(InputType.Aim))) diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/ItemPrefab.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/ItemPrefab.cs index 358b6f708..041b021ad 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/ItemPrefab.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/ItemPrefab.cs @@ -810,7 +810,7 @@ namespace Barotrauma public PriceInfo GetPrice(Location location) { - if (prices == null || !prices.ContainsKey(location.Type.Identifier.ToLowerInvariant())) { return null; } + if (prices == null || !prices.ContainsKey(location.Type.Identifier.ToLowerInvariant())) return null; return prices[location.Type.Identifier.ToLowerInvariant()]; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Items/RelatedItem.cs b/Barotrauma/BarotraumaShared/SharedSource/Items/RelatedItem.cs index 4cc0bc78c..d21bb00a2 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Items/RelatedItem.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Items/RelatedItem.cs @@ -152,7 +152,7 @@ namespace Barotrauma public void Save(XElement element) { element.Add( - new XAttribute("items", JoinedIdentifiers), + new XAttribute("identifiers", JoinedIdentifiers), new XAttribute("type", type.ToString()), new XAttribute("optional", IsOptional), new XAttribute("ignoreineditor", IgnoreInEditor)); @@ -219,10 +219,7 @@ namespace Barotrauma string typeStr = element.GetAttributeString("type", ""); if (string.IsNullOrEmpty(typeStr)) { - if (element.Name.ToString().Equals("containable", StringComparison.OrdinalIgnoreCase)) - { - typeStr = "Contained"; - } + if (element.Name.ToString().ToLowerInvariant() == "containable") typeStr = "Contained"; } if (!Enum.TryParse(typeStr, true, out ri.type)) { @@ -249,7 +246,7 @@ namespace Barotrauma foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("statuseffect", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "statuseffect") continue; ri.statusEffects.Add(StatusEffect.Load(subElement, parentDebugName)); } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/FireSource.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/FireSource.cs index 08feb0f1c..50f3b9554 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/FireSource.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/FireSource.cs @@ -14,7 +14,7 @@ namespace Barotrauma partial class FireSource : ISpatialEntity { const float OxygenConsumption = 50.0f; - const float GrowSpeed = 20.0f; + const float GrowSpeed = 5.0f; protected Hull hull; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/Gap.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/Gap.cs index 4a91880e8..454068b5e 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/Gap.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/Gap.cs @@ -378,7 +378,7 @@ namespace Barotrauma delta = Math.Min(((hull2.Pressure + subOffset.Y) - hull1.Pressure) * 5.0f * sizeModifier, Math.Min(hull2.WaterVolume, hull2.Volume)); //make sure not to place more water to the target room than it can hold - delta = Math.Min(delta, hull1.Volume * Hull.MaxCompress - (hull1.WaterVolume)); + delta = Math.Min(delta, hull1.Volume + Hull.MaxCompress - (hull1.WaterVolume)); hull1.WaterVolume += delta; hull2.WaterVolume -= delta; if (hull1.WaterVolume > hull1.Volume) @@ -399,7 +399,7 @@ namespace Barotrauma delta = Math.Min((hull1.Pressure - (hull2.Pressure + subOffset.Y)) * 5.0f * sizeModifier, Math.Min(hull1.WaterVolume, hull1.Volume)); //make sure not to place more water to the target room than it can hold - delta = Math.Min(delta, hull2.Volume * Hull.MaxCompress - (hull2.WaterVolume)); + delta = Math.Min(delta, hull2.Volume + Hull.MaxCompress - (hull2.WaterVolume)); hull1.WaterVolume -= delta; hull2.WaterVolume += delta; if (hull2.WaterVolume > hull2.Volume) @@ -414,14 +414,14 @@ namespace Barotrauma { float avg = (hull1.Surface + hull2.Surface) / 2.0f; - if (hull1.WaterVolume < hull1.Volume / Hull.MaxCompress && + if (hull1.WaterVolume < hull1.Volume - Hull.MaxCompress && hull1.Surface + hull1.WaveY[hull1.WaveY.Length - 1] < rect.Y) { hull1.WaveVel[hull1.WaveY.Length - 1] = (avg - (hull1.Surface + hull1.WaveY[hull1.WaveY.Length - 1])) * 0.1f; hull1.WaveVel[hull1.WaveY.Length - 2] = hull1.WaveVel[hull1.WaveY.Length - 1]; } - if (hull2.WaterVolume < hull2.Volume / Hull.MaxCompress && + if (hull2.WaterVolume < hull2.Volume - Hull.MaxCompress && hull2.Surface + hull2.WaveY[0] < rect.Y) { hull2.WaveVel[0] = (avg - (hull2.Surface + hull2.WaveY[0])) * 0.1f; @@ -436,12 +436,12 @@ namespace Barotrauma //lower room is full of water if (hull2.Pressure + subOffset.Y > hull1.Pressure && hull2.WaterVolume > 0.0f) { - float delta = Math.Min(hull2.WaterVolume - hull2.Volume + (hull2.Volume * Hull.MaxCompress), deltaTime * 8000.0f * sizeModifier); + float delta = Math.Min(hull2.WaterVolume - hull2.Volume + Hull.MaxCompress, deltaTime * 8000.0f * sizeModifier); //make sure not to place more water to the target room than it can hold - if (hull1.WaterVolume + delta > hull1.Volume * Hull.MaxCompress) + if (hull1.WaterVolume + delta > hull1.Volume + Hull.MaxCompress) { - delta -= (hull1.WaterVolume + delta) - (hull1.Volume * Hull.MaxCompress); + delta -= (hull1.WaterVolume + delta) - (hull1.Volume + Hull.MaxCompress); } delta = Math.Max(delta, 0.0f); @@ -469,9 +469,9 @@ namespace Barotrauma float delta = Math.Min(hull1.WaterVolume, deltaTime * 25000f * sizeModifier); //make sure not to place more water to the target room than it can hold - if (hull2.WaterVolume + delta > hull2.Volume * Hull.MaxCompress) + if (hull2.WaterVolume + delta > hull2.Volume + Hull.MaxCompress) { - delta -= (hull2.WaterVolume + delta) - (hull2.Volume * Hull.MaxCompress); + delta -= (hull2.WaterVolume + delta) - (hull2.Volume + Hull.MaxCompress); } hull1.WaterVolume -= delta; hull2.WaterVolume += delta; @@ -489,7 +489,7 @@ namespace Barotrauma if (open > 0.0f) { - if (hull1.WaterVolume > hull1.Volume / Hull.MaxCompress && hull2.WaterVolume > hull2.Volume / Hull.MaxCompress) + if (hull1.WaterVolume > hull1.Volume - Hull.MaxCompress && hull2.WaterVolume > hull2.Volume - Hull.MaxCompress) { float avgLethality = (hull1.LethalPressure + hull2.LethalPressure) / 2.0f; hull1.LethalPressure = avgLethality; @@ -515,10 +515,10 @@ namespace Barotrauma //the larger the gap is, the faster the water flows float sizeModifier = size * open * open; - float delta = hull1.Volume * Hull.MaxCompress * sizeModifier * deltaTime; + float delta = Hull.MaxCompress * sizeModifier * deltaTime; //make sure not to place more water to the target room than it can hold - delta = Math.Min(delta, hull1.Volume * Hull.MaxCompress - hull1.WaterVolume); + delta = Math.Min(delta, hull1.Volume + Hull.MaxCompress - hull1.WaterVolume); hull1.WaterVolume += delta; if (hull1.WaterVolume > hull1.Volume) hull1.Pressure += 0.5f; @@ -541,7 +541,7 @@ namespace Barotrauma higherSurface = hull1.Surface; lowerSurface = rect.Y; - if (hull1.WaterVolume < hull1.Volume / Hull.MaxCompress && + if (hull1.WaterVolume < hull1.Volume - Hull.MaxCompress && hull1.Surface < rect.Y) { if (rect.X > hull1.Rect.X + hull1.Rect.Width / 2.0f) @@ -576,7 +576,7 @@ namespace Barotrauma { flowForce = new Vector2(0.0f, delta); } - if (hull1.WaterVolume >= hull1.Volume / Hull.MaxCompress) + if (hull1.WaterVolume >= hull1.Volume - Hull.MaxCompress) { hull1.LethalPressure += (Submarine != null && Submarine.AtDamageDepth) ? 100.0f * deltaTime : 10.0f * deltaTime; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/Hull.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/Hull.cs index 1c3294421..06ff02e92 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/Hull.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/Hull.cs @@ -26,9 +26,8 @@ namespace Barotrauma public static float WaveSpread = 0.05f; public static float WaveDampening = 0.05f; - //how much excess water the room can contain, relative to the volume of the room. - //needed to make it possible for pressure to "push" water up through U-shaped hull configurations - public const float MaxCompress = 1.05f; + //how much excess water the room can contain (= more than the volume of the room) + public const float MaxCompress = 10000f; public readonly Dictionary properties; public Dictionary SerializableProperties @@ -155,7 +154,7 @@ namespace Barotrauma set { if (!MathUtils.IsValid(value)) return; - waterVolume = MathHelper.Clamp(value, 0.0f, Volume * MaxCompress); + waterVolume = MathHelper.Clamp(value, 0.0f, Volume + MaxCompress); if (waterVolume < Volume) Pressure = rect.Y - rect.Height + waterVolume / rect.Width; if (waterVolume > 0.0f) update = true; } @@ -322,7 +321,6 @@ namespace Barotrauma CeilingHeight = ConvertUnits.ToDisplayUnits(upperPickedPos.Y - lowerPickedPos.Y); } } - Pressure = rect.Y - rect.Height + waterVolume / rect.Width; } public void AddToGrid(Submarine submarine) @@ -875,7 +873,7 @@ namespace Barotrauma var hull = new Hull(MapEntityPrefab.Find(null, "hull"), rect, submarine) { - WaterVolume = element.GetAttributeFloat("pressure", 0.0f), + waterVolume = element.GetAttributeFloat("pressure", 0.0f), ID = (ushort)int.Parse(element.Attribute("ID").Value) }; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Level.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Level.cs index ae5740cec..412298f03 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Level.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Level.cs @@ -310,7 +310,6 @@ namespace Barotrauma if (Submarine.MainSub != null) { Rectangle dockedSubBorders = Submarine.MainSub.GetDockedBorders(); - dockedSubBorders.Inflate(dockedSubBorders.Size.ToVector2() * 0.05f); minWidth = Math.Max(minWidth, Math.Max(dockedSubBorders.Width, dockedSubBorders.Height)); minWidth = Math.Min(minWidth, maxWidth); } @@ -1623,7 +1622,7 @@ namespace Barotrauma EndOutpost = outpost; if (GameMain.GameSession?.EndLocation != null) { outpost.Name = GameMain.GameSession.EndLocation.Name; } } - } + } } private bool IsModeStartOutpostCompatible() diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/LevelGenerationParams.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/LevelGenerationParams.cs index 29a84d566..463db19dc 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/LevelGenerationParams.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/LevelGenerationParams.cs @@ -415,10 +415,10 @@ namespace Barotrauma string biomeName = biomeNames[i].Trim().ToLowerInvariant(); if (biomeName == "none") { continue; } - Biome matchingBiome = biomes.Find(b => b.Identifier.Equals(biomeName, StringComparison.OrdinalIgnoreCase)); + Biome matchingBiome = biomes.Find(b => b.Identifier.ToLowerInvariant() == biomeName); if (matchingBiome == null) { - matchingBiome = biomes.Find(b => b.DisplayName.Equals(biomeName, StringComparison.OrdinalIgnoreCase)); + matchingBiome = biomes.Find(b => b.DisplayName.ToLowerInvariant() == biomeName); if (matchingBiome == null) { DebugConsole.ThrowError("Error in level generation parameters: biome \"" + biomeName + "\" not found."); @@ -487,7 +487,7 @@ namespace Barotrauma mainElement = doc.Root.FirstElement(); biomeElements.Clear(); levelParamElements.Clear(); - DebugConsole.NewMessage($"Overriding the level generation parameters and biomes with '{file.Path}'", Color.Yellow); + DebugConsole.NewMessage($"Overriding the level generation parameters with '{file.Path}'", Color.Yellow); } else if (biomeElements.Any() || levelParamElements.Any()) { @@ -497,22 +497,7 @@ namespace Barotrauma foreach (XElement element in mainElement.Elements()) { - if (element.IsOverride()) - { - if (element.FirstElement().Name.ToString().Equals("biomes", StringComparison.OrdinalIgnoreCase)) - { - biomeElements.Clear(); - biomeElements.AddRange(element.FirstElement().Elements()); - DebugConsole.NewMessage($"Overriding biomes with '{file.Path}'", Color.Yellow); - } - else - { - levelParamElements.Clear(); - DebugConsole.NewMessage($"Overriding the level generation parameters with '{file.Path}'", Color.Yellow); - levelParamElements.AddRange(element.Elements()); - } - } - else if (element.Name.ToString().Equals("biomes", StringComparison.OrdinalIgnoreCase)) + if (element.Name.ToString().ToLowerInvariant() == "biomes") { biomeElements.AddRange(element.Elements()); } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Ruins/RuinGenerationParams.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Ruins/RuinGenerationParams.cs index 4eb5b637f..14c5f9d6a 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Ruins/RuinGenerationParams.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Ruins/RuinGenerationParams.cs @@ -277,7 +277,7 @@ namespace Barotrauma.RuinGeneration { foreach (XElement subElement in element2.Elements()) { - if (subElement.Name.ToString().Equals("chooseone", StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() == "chooseone") { groupIndex++; LoadEntities(subElement, ref groupIndex); @@ -390,7 +390,7 @@ namespace Barotrauma.RuinGeneration SourceEntityIdentifier = element.GetAttributeString("sourceentity", ""); foreach (XElement subElement in element.Elements()) { - if (subElement.Name.ToString().Equals("wire", StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() == "wire") { WireConnection = new Pair( subElement.GetAttributeString("from", ""), diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Ruins/RuinGenerator.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Ruins/RuinGenerator.cs index 2a96202f1..1d29696e7 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Ruins/RuinGenerator.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/Levels/Ruins/RuinGenerator.cs @@ -721,10 +721,8 @@ namespace Barotrauma.RuinGeneration //doors create their own gaps, don't create an additional one if there's a door at this bool doorFound = false; - foreach (Item item in Item.ItemList) + foreach (Door door in doors) { - var door = item.GetComponent(); - if (door == null) { continue; } if (Math.Abs(door.Item.WorldPosition.X - gapRect.Value.Center.X) < 5 && Math.Abs(door.Item.WorldPosition.Y - gapRect.Value.Center.Y) < 5) { diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/Map/Map.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/Map/Map.cs index d1b5bff03..1bca7d130 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/Map/Map.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/Map/Map.cs @@ -284,7 +284,7 @@ namespace Barotrauma foreach (LocationConnection connection in connections) { float centerDist = Vector2.Distance(connection.CenterPos, mapCenter); - connection.Difficulty = MathHelper.Clamp(((1.0f - centerDist / mapRadius) * 100) + Rand.Range(-10.0f, 0.0f, Rand.RandSync.Server), 0, 100); + connection.Difficulty = MathHelper.Clamp(((1.0f - centerDist / mapRadius) * 100) + Rand.Range(-10.0f, 10.0f, Rand.RandSync.Server), 0, 100); } AssignBiomes(); @@ -463,7 +463,7 @@ namespace Barotrauma bool disallowedFound = false; foreach (string disallowedLocationName in typeChange.DisallowedAdjacentLocations) { - if (location.Connections.Any(c => c.OtherLocation(location).Type.Identifier.Equals(disallowedLocationName, StringComparison.OrdinalIgnoreCase))) + if (location.Connections.Any(c => c.OtherLocation(location).Type.Identifier.ToLowerInvariant() == disallowedLocationName.ToLowerInvariant())) { disallowedFound = true; break; @@ -475,7 +475,7 @@ namespace Barotrauma bool requiredFound = false; foreach (string requiredLocationName in typeChange.RequiredAdjacentLocations) { - if (location.Connections.Any(c => c.OtherLocation(location).Type.Identifier.Equals(requiredLocationName, StringComparison.OrdinalIgnoreCase))) + if (location.Connections.Any(c => c.OtherLocation(location).Type.Identifier.ToLowerInvariant() == requiredLocationName.ToLowerInvariant())) { requiredFound = true; break; @@ -499,7 +499,7 @@ namespace Barotrauma if (selectedTypeChange != null) { string prevName = location.Name; - location.ChangeType(LocationType.List.Find(lt => lt.Identifier.Equals(selectedTypeChange.ChangeToType, StringComparison.OrdinalIgnoreCase))); + location.ChangeType(LocationType.List.Find(lt => lt.Identifier.ToLowerInvariant() == selectedTypeChange.ChangeToType.ToLowerInvariant())); ChangeLocationType(location, prevName, selectedTypeChange); location.TypeChangeTimer = -1; break; @@ -553,12 +553,13 @@ namespace Barotrauma string prevLocationName = location.Name; LocationType prevLocationType = location.Type; location.Discovered = true; - location.ChangeType(LocationType.List.Find(lt => lt.Identifier.Equals(locationType, StringComparison.OrdinalIgnoreCase))); + location.ChangeType(LocationType.List.Find(lt => lt.Identifier.ToLowerInvariant() == locationType.ToLowerInvariant())); location.TypeChangeTimer = typeChangeTimer; location.MissionsCompleted = missionsCompleted; if (showNotifications && prevLocationType != location.Type) { - var change = prevLocationType.CanChangeTo.Find(c => c.ChangeToType.Equals(location.Type.Identifier, StringComparison.OrdinalIgnoreCase)); + var change = prevLocationType.CanChangeTo.Find(c => + c.ChangeToType.ToLowerInvariant() == location.Type.Identifier.ToLowerInvariant()); if (change != null) { ChangeLocationType(location, prevLocationName, change); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/MapEntityPrefab.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/MapEntityPrefab.cs index 5c7ecbeb3..3d5aade29 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/MapEntityPrefab.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/MapEntityPrefab.cs @@ -43,6 +43,7 @@ namespace Barotrauma protected string originalName; protected string identifier; + protected ContentPackage contentPackage; public Sprite sprite; @@ -242,10 +243,7 @@ namespace Barotrauma /// The identifier of the item (if null, the identifier is ignored and the search is done only based on the name) public static MapEntityPrefab Find(string name, string identifier = null, bool showErrorMessages = true) { - if (name != null) - { - name = name.ToLowerInvariant(); - } + if (name != null) name = name.ToLowerInvariant(); foreach (MapEntityPrefab prefab in List) { if (identifier != null) @@ -256,17 +254,12 @@ namespace Barotrauma } else { - if (string.IsNullOrEmpty(name)) { return prefab; } + if (string.IsNullOrEmpty(name)) return prefab; } } if (!string.IsNullOrEmpty(name)) { - if (prefab.Name.Equals(name, StringComparison.OrdinalIgnoreCase) || - prefab.originalName.Equals(name, StringComparison.OrdinalIgnoreCase) || - (prefab.Aliases != null && prefab.Aliases.Any(a => a.Equals(name, StringComparison.OrdinalIgnoreCase)))) - { - return prefab; - } + if (prefab.Name.ToLowerInvariant() == name || prefab.originalName.ToLowerInvariant() == name || (prefab.Aliases != null && prefab.Aliases.Any(a => a.ToLowerInvariant() == name))) return prefab; } } @@ -289,9 +282,27 @@ namespace Barotrauma /// /// Check if the name or any of the aliases of this prefab match the given name. /// - public bool NameMatches(string name, StringComparison comparisonType) => originalName.Equals(name, comparisonType) || (Aliases != null && Aliases.Any(a => a.Equals(name, comparisonType))); + public bool NameMatches(string name, bool caseSensitive = false) + { + if (caseSensitive) + { + return this.originalName == name || (Aliases != null && Aliases.Any(a => a == name)); + } + else + { + name = name.ToLowerInvariant(); + return this.originalName.ToLowerInvariant() == name || (Aliases != null && Aliases.Any(a => a.ToLowerInvariant() == name)); + } + } - public bool NameMatches(IEnumerable allowedNames, StringComparison comparisonType) => allowedNames.Any(n => NameMatches(n, comparisonType)); + public bool NameMatches(IEnumerable allowedNames, bool caseSensitive = false) + { + foreach (string name in allowedNames) + { + if (NameMatches(name, caseSensitive)) return true; + } + return false; + } public bool IsLinkAllowed(MapEntityPrefab target) { diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/StructurePrefab.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/StructurePrefab.cs index 5a3b0b2ea..ef8076b81 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/StructurePrefab.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/StructurePrefab.cs @@ -260,15 +260,15 @@ namespace Barotrauma } #if CLIENT - if (subElement.GetAttributeBool("fliphorizontal", false)) + if (subElement.GetAttributeBool("fliphorizontal", false)) sp.sprite.effects = SpriteEffects.FlipHorizontally; - if (subElement.GetAttributeBool("flipvertical", false)) + if (subElement.GetAttributeBool("flipvertical", false)) sp.sprite.effects = SpriteEffects.FlipVertically; #endif - + sp.canSpriteFlipX = subElement.GetAttributeBool("canflipx", true); sp.canSpriteFlipY = subElement.GetAttributeBool("canflipy", true); - + if (subElement.Attribute("name") == null && !string.IsNullOrWhiteSpace(sp.Name)) { sp.sprite.Name = sp.Name; @@ -286,10 +286,12 @@ namespace Barotrauma sp.BackgroundSprite.RelativeOrigin = subElement.GetAttributeVector2("origin", new Vector2(0.5f, 0.5f)); } #if CLIENT - if (subElement.GetAttributeBool("fliphorizontal", false)) { sp.BackgroundSprite.effects = SpriteEffects.FlipHorizontally; } - if (subElement.GetAttributeBool("flipvertical", false)) { sp.BackgroundSprite.effects = SpriteEffects.FlipVertically; } - sp.BackgroundSpriteColor = subElement.GetAttributeColor("color", Color.White); + if (subElement.GetAttributeBool("fliphorizontal", false)) + sp.BackgroundSprite.effects = SpriteEffects.FlipHorizontally; + if (subElement.GetAttributeBool("flipvertical", false)) + sp.BackgroundSprite.effects = SpriteEffects.FlipVertically; #endif + break; } } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/Submarine.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/Submarine.cs index 0b8b69742..d30787186 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/Submarine.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/Submarine.cs @@ -77,18 +77,7 @@ namespace Barotrauma private SubmarineBody subBody; - public readonly Dictionary ConnectedDockingPorts; - public IEnumerable DockedTo - { - get - { - if (ConnectedDockingPorts == null) { yield break; } - foreach (Submarine sub in ConnectedDockingPorts.Keys) - { - yield return sub; - } - } - } + public readonly List DockedTo; private static Vector2 lastPickedPosition; private static float lastPickedFraction; @@ -453,7 +442,7 @@ namespace Barotrauma } } - ConnectedDockingPorts = new Dictionary(); + DockedTo = new List(); FreeID(); } @@ -511,7 +500,7 @@ namespace Barotrauma LeftBehindSubDockingPortOccupied = false; foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("linkedsubmarine")) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "linkedsubmarine") { continue; } if (subElement.Attribute("location") == null) { continue; } subsLeftBehind = true; @@ -572,32 +561,27 @@ namespace Barotrauma /// /// Returns a rect that contains the borders of this sub and all subs docked to it /// - public Rectangle GetDockedBorders(List checkd=null) + public Rectangle GetDockedBorders() { - if (checkd == null) { checkd = new List(); } - checkd.Add(this); - Rectangle dockedBorders = Borders; + dockedBorders.Y -= dockedBorders.Height; - var connectedSubs = DockedTo.Where(s => !checkd.Contains(s) && !s.IsOutpost).ToList(); + var connectedSubs = GetConnectedSubs(); foreach (Submarine dockedSub in connectedSubs) { - //use docking ports instead of world position to determine - //borders, as world position will not necessarily match where - //the subs are supposed to go - Vector2? expectedLocation = CalculateDockOffset(this, dockedSub); - if (expectedLocation == null) { continue; } + if (dockedSub == this) continue; - Rectangle dockedSubBorders = dockedSub.GetDockedBorders(checkd); - dockedSubBorders.Location += MathUtils.ToPoint(expectedLocation.Value); + Vector2 diff = dockedSub.Submarine == this ? dockedSub.WorldPosition : dockedSub.WorldPosition - WorldPosition; + + Rectangle dockedSubBorders = dockedSub.Borders; + dockedSubBorders.Y -= dockedSubBorders.Height; + dockedSubBorders.Location += MathUtils.ToPoint(diff); - dockedBorders.Y = -dockedBorders.Y; - dockedSubBorders.Y = -dockedSubBorders.Y; dockedBorders = Rectangle.Union(dockedBorders, dockedSubBorders); - dockedBorders.Y = -dockedBorders.Y; } + dockedBorders.Y += dockedBorders.Height; return dockedBorders; } @@ -1147,37 +1131,25 @@ namespace Barotrauma prevPosition = position; } - public void SetPosition(Vector2 position, List checkd=null) + public void SetPosition(Vector2 position) { if (!MathUtils.IsValid(position)) return; - - if (checkd == null) { checkd = new List(); } - if (checkd.Contains(this)) { return; } - - checkd.Add(this); - + subBody.SetPosition(position); - foreach (Submarine dockedSub in DockedTo) + foreach (Submarine sub in loaded) { - Vector2? expectedLocation = CalculateDockOffset(this, dockedSub); - if (expectedLocation == null) { continue; } + if (sub != this && sub.Submarine == this) + { + sub.SetPosition(position + sub.WorldPosition); + sub.Submarine = null; + } - dockedSub.SetPosition(position + expectedLocation.Value, checkd); } //Level.Loaded.SetPosition(-position); //prevPosition = position; } - public static Vector2? CalculateDockOffset(Submarine sub, Submarine dockedSub) - { - Item myPort = sub.ConnectedDockingPorts.ContainsKey(dockedSub) ? sub.ConnectedDockingPorts[dockedSub].Item : null; - if (myPort == null) { return null; } - Item theirPort = dockedSub.ConnectedDockingPorts.ContainsKey(sub) ? dockedSub.ConnectedDockingPorts[sub].Item : null; - if (theirPort == null) { return null; } - return (myPort.Position - sub.HiddenSubPosition) - (theirPort.Position - dockedSub.HiddenSubPosition); - } - public void Translate(Vector2 amount) { if (amount == Vector2.Zero || !MathUtils.IsValid(amount)) return; @@ -1264,17 +1236,9 @@ namespace Barotrauma { if (Path.GetFullPath(savedSubmarines[i].filePath) == fullPath) { - if (savedSubmarines[i] == MainSub) - { - savedSubmarines.Remove(savedSubmarines[i]); - } - else - { - savedSubmarines[i].Dispose(); - } + savedSubmarines[i].Dispose(); } } - if (File.Exists(filePath)) { var sub = new Submarine(filePath); @@ -1592,7 +1556,7 @@ namespace Barotrauma foreach (Hull hull in matchingHulls) { - if (string.IsNullOrEmpty(hull.RoomName) || !hull.RoomName.Contains("roomname.", StringComparison.OrdinalIgnoreCase)) + if (string.IsNullOrEmpty(hull.RoomName) || !hull.RoomName.ToLowerInvariant().Contains("roomname.")) { hull.RoomName = hull.CreateRoomName(); } @@ -1769,7 +1733,7 @@ namespace Barotrauma if (MainSub == this) MainSub = null; if (MainSubs[1] == this) MainSubs[1] = null; - ConnectedDockingPorts?.Clear(); + DockedTo?.Clear(); } public void Dispose() diff --git a/Barotrauma/BarotraumaShared/SharedSource/Map/WayPoint.cs b/Barotrauma/BarotraumaShared/SharedSource/Map/WayPoint.cs index 0c557c183..c8a2b2291 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Map/WayPoint.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Map/WayPoint.cs @@ -121,15 +121,9 @@ namespace Barotrauma idCardTags = new string[0]; #if CLIENT - if (iconSprites == null) + if (iconTexture == null) { - iconSprites = new Dictionary() - { - { SpawnType.Path, new Sprite("Content/UI/MainIconsAtlas.png", new Rectangle(0,0,128,128)) }, - { SpawnType.Human, new Sprite("Content/UI/MainIconsAtlas.png", new Rectangle(128,0,128,128)) }, - { SpawnType.Enemy, new Sprite("Content/UI/MainIconsAtlas.png", new Rectangle(256,0,128,128)) }, - { SpawnType.Cargo, new Sprite("Content/UI/MainIconsAtlas.png", new Rectangle(384,0,128,128)) } - }; + iconTexture = Sprite.LoadTexture("Content/Map/waypointIcons.png"); } #endif @@ -154,12 +148,21 @@ namespace Barotrauma return clone; } - public static bool GenerateSubWaypoints(Submarine submarine) + public override bool IsMouseOn(Vector2 position) + { +#if CLIENT + if (IsHidden()) return false; +#endif + + return base.IsMouseOn(position); + } + + public static void GenerateSubWaypoints(Submarine submarine) { if (!Hull.hullList.Any()) { DebugConsole.ThrowError("Couldn't generate waypoints: no hulls found."); - return false; + return; } List existingWaypoints = WayPointList.FindAll(wp => wp.spawnType == SpawnType.Path); @@ -462,8 +465,6 @@ namespace Barotrauma { door.Body.Enabled = false; } - - return true; } private WayPoint FindClosest(int dir, bool horizontalSearch, Vector2 tolerance, Body ignoredBody = null) @@ -653,7 +654,7 @@ namespace Barotrauma { w.assignedJob = JobPrefab.Get(jobIdentifier) ?? - JobPrefab.Prefabs.Find(jp => jp.Name.Equals(jobIdentifier, StringComparison.OrdinalIgnoreCase)); + JobPrefab.Prefabs.Find(jp => jp.Name.ToLowerInvariant() == jobIdentifier); } w.ladderId = (ushort)element.GetAttributeInt("ladders", 0); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Networking/ClientPermissions.cs b/Barotrauma/BarotraumaShared/SharedSource/Networking/ClientPermissions.cs index f84dc043a..c1fbc3ac3 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Networking/ClientPermissions.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Networking/ClientPermissions.cs @@ -51,7 +51,7 @@ namespace Barotrauma.Networking { foreach (XElement subElement in element.Elements()) { - if (!subElement.Name.ToString().Equals("command", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "command") continue; string commandName = subElement.GetAttributeString("name", ""); DebugConsole.Command command = DebugConsole.FindCommand(commandName); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Networking/NetworkMember.cs b/Barotrauma/BarotraumaShared/SharedSource/Networking/NetworkMember.cs index 5858d7f55..ed54d4672 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Networking/NetworkMember.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Networking/NetworkMember.cs @@ -22,8 +22,6 @@ namespace Barotrauma.Networking RESPONSE_STARTGAME, //tell the server whether you're ready to start SERVER_COMMAND, //tell the server to end a round or kick/ban someone (special permissions required) - REQUEST_STARTGAMEFINALIZE, //tell the server you're ready to finalize round initialization - ERROR //tell the server that an error occurred } enum ClientNetObject @@ -62,7 +60,6 @@ namespace Barotrauma.Networking QUERY_STARTGAME, //ask the clients whether they're ready to start STARTGAME, //start a new round - STARTGAMEFINALIZE, //finalize round initialization ENDGAME, TRAITOR_MESSAGE, diff --git a/Barotrauma/BarotraumaShared/SharedSource/Networking/ServerSettings.cs b/Barotrauma/BarotraumaShared/SharedSource/Networking/ServerSettings.cs index 567d6ac39..aecaf8011 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Networking/ServerSettings.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Networking/ServerSettings.cs @@ -138,7 +138,7 @@ namespace Barotrauma.Networking { return (a == null) == (b == null); } - return a.ToString().Equals(b.ToString(), StringComparison.OrdinalIgnoreCase); + return a.ToString().Equals(b.ToString(), StringComparison.InvariantCulture); } } @@ -759,7 +759,7 @@ namespace Barotrauma.Networking private set; } - [Serialize(600.0f, true)] + [Serialize(120.0f, true)] public float KickAFKTime { get; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Networking/SteamManager.cs b/Barotrauma/BarotraumaShared/SharedSource/Networking/SteamManager.cs index 4c5fae069..9a5eada0c 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Networking/SteamManager.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Networking/SteamManager.cs @@ -70,15 +70,14 @@ namespace Barotrauma.Steam return Steamworks.SteamClient.Name; } - public static bool OverlayCustomURL(string url) + public static void OverlayCustomURL(string url) { if (!isInitialized || !Steamworks.SteamClient.IsValid) { - return false; + return; } Steamworks.SteamFriends.OpenWebOverlay(url); - return true; } public static bool UnlockAchievement(string achievementName) diff --git a/Barotrauma/BarotraumaShared/SharedSource/Serialization/SerializableProperty.cs b/Barotrauma/BarotraumaShared/SharedSource/Serialization/SerializableProperty.cs index 37b24658a..2526e7f8c 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Serialization/SerializableProperty.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Serialization/SerializableProperty.cs @@ -679,7 +679,7 @@ namespace Barotrauma { foreach (XElement subElement in configElement.Elements()) { - if (!subElement.Name.ToString().Equals("upgrade", StringComparison.OrdinalIgnoreCase)) { continue; } + if (subElement.Name.ToString().ToLowerInvariant() != "upgrade") { continue; } var upgradeVersion = new Version(subElement.GetAttributeString("gameversion", "0.0.0.0")); if (savedVersion >= upgradeVersion) { continue; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/Serialization/XMLExtensions.cs b/Barotrauma/BarotraumaShared/SharedSource/Serialization/XMLExtensions.cs index 3c3f636d2..8daa9feef 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Serialization/XMLExtensions.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Serialization/XMLExtensions.cs @@ -570,7 +570,7 @@ namespace Barotrauma { bool hexFailed = true; stringColor = stringColor.Trim(); - if (stringColor.Length > 0 && stringColor[0] == '#') + if (stringColor[0]=='#') { stringColor = stringColor.Substring(1); diff --git a/Barotrauma/BarotraumaShared/SharedSource/Sprite/Sprite.cs b/Barotrauma/BarotraumaShared/SharedSource/Sprite/Sprite.cs index e494349c4..cc3e4649d 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Sprite/Sprite.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Sprite/Sprite.cs @@ -329,10 +329,10 @@ namespace Barotrauma { foreach (XElement subElement in SourceElement.Elements()) { - if (subElement.Name.ToString().Equals("override", StringComparison.OrdinalIgnoreCase)) + if (subElement.Name.ToString().ToLowerInvariant() == "override") { string language = subElement.GetAttributeString("language", ""); - if (TextManager.Language.Equals(language, StringComparison.InvariantCultureIgnoreCase)) + if (TextManager.Language.ToLower() == language.ToLower()) { return subElement; } diff --git a/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/DelayedEffect.cs b/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/DelayedEffect.cs index ae67f66f2..cddc9c97d 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/DelayedEffect.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/DelayedEffect.cs @@ -1,27 +1,17 @@ using System.Collections.Generic; using System.Linq; using System.Xml.Linq; -using Barotrauma.Extensions; using Microsoft.Xna.Framework; namespace Barotrauma { class DelayedListElement { - public readonly DelayedEffect Parent; - public readonly Entity Entity; - public readonly Vector2? WorldPosition; - public readonly List Targets; + public DelayedEffect Parent; + public Entity Entity; + public Vector2? WorldPosition; + public List Targets; public float StartTimer; - - public DelayedListElement(DelayedEffect parentEffect, Entity parentEntity, IEnumerable targets, float delay, Vector2? worldPosition) - { - Parent = parentEffect; - Entity = parentEntity; - Targets = new List(targets); - StartTimer = delay; - WorldPosition = worldPosition; - } } class DelayedEffect : StatusEffect { @@ -37,18 +27,28 @@ namespace Barotrauma public override void Apply(ActionType type, float deltaTime, Entity entity, ISerializableEntity target, Vector2? worldPosition = null) { - if (this.type != type || !HasRequiredItems(entity)) { return; } - if (!Stackable && DelayList.Any(d => d.Parent == this && d.Targets.FirstOrDefault() == target)) { return; } - if (targetIdentifiers != null && !IsValidTarget(target)) { return; } - if (!HasRequiredConditions(target.ToEnumerable())) { return; } + if (this.type != type || !HasRequiredItems(entity)) return; + if (!Stackable && DelayList.Any(d => d.Parent == this && d.Targets.FirstOrDefault() == target)) return; + + if (targetIdentifiers != null && !IsValidTarget(target)) return; + if (!HasRequiredConditions(new List() { target })) return; - DelayList.Add(new DelayedListElement(this, entity, target.ToEnumerable(), delay, worldPosition)); + DelayedListElement element = new DelayedListElement + { + Parent = this, + StartTimer = delay, + Entity = entity, + WorldPosition = worldPosition, + Targets = new List() { target } + }; + + DelayList.Add(element); } public override void Apply(ActionType type, float deltaTime, Entity entity, IEnumerable targets, Vector2? worldPosition = null) { - if (this.type != type || !HasRequiredItems(entity)) { return; } - if (!Stackable && DelayList.Any(d => d.Parent == this && d.Targets.SequenceEqual(targets))) { return; } + if (this.type != type || !HasRequiredItems(entity)) return; + if (!Stackable && DelayList.Any(d => d.Parent == this && d.Targets.SequenceEqual(targets))) return; currentTargets.Clear(); foreach (ISerializableEntity target in targets) @@ -61,9 +61,18 @@ namespace Barotrauma currentTargets.Add(target); } - if (!HasRequiredConditions(currentTargets)) { return; } + if (!HasRequiredConditions(currentTargets)) return; - DelayList.Add(new DelayedListElement(this, entity, currentTargets, delay, worldPosition)); + DelayedListElement element = new DelayedListElement + { + Parent = this, + StartTimer = delay, + Entity = entity, + WorldPosition = worldPosition, + Targets = currentTargets + }; + + DelayList.Add(element); } public static void Update(float deltaTime) @@ -79,7 +88,7 @@ namespace Barotrauma element.StartTimer -= deltaTime; - if (element.StartTimer > 0.0f) { continue; } + if (element.StartTimer > 0.0f) continue; element.Parent.Apply(1.0f, element.Entity, element.Targets, element.WorldPosition); DelayList.Remove(element); diff --git a/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/PropertyConditional.cs b/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/PropertyConditional.cs index 80a50f2fc..aeeea37c0 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/PropertyConditional.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/PropertyConditional.cs @@ -51,8 +51,7 @@ namespace Barotrauma // Only used by attacks public readonly bool TargetSelf; - // Only used by conditionals targeting an item (makes the conditional check the item/character whose inventory this item is inside) - public readonly bool TargetContainer; + private readonly string[] afflictionNames = new string[] { "internaldamage", "bleeding", "burn", "oxygenlow", "bloodloss", "pressure", "stun", "husk", "afflictionhusk", "huskinfection" }; private readonly int cancelStatusEffect; @@ -63,7 +62,6 @@ namespace Barotrauma { case "targetitemcomponent": case "targetself": - case "targetcontainer": return false; default: return true; @@ -134,7 +132,6 @@ namespace Barotrauma } TargetItemComponentName = attribute.Parent.GetAttributeString("targetitemcomponent", ""); - TargetContainer = attribute.Parent.GetAttributeBool("targetcontainer", false); TargetSelf = attribute.Parent.GetAttributeBool("targetself", false); foreach (XElement subElement in attribute.Parent.Elements()) @@ -153,9 +150,13 @@ namespace Barotrauma if (!Enum.TryParse(AttributeName, true, out Type)) { - if (AfflictionPrefab.Prefabs.Any(p => p.Identifier.Equals(AttributeName, StringComparison.OrdinalIgnoreCase))) + if (afflictionNames.Any(n => n == AttributeName)) { Type = ConditionType.Affliction; + if (AttributeName == "husk" || AttributeName == "huskaffliction") + { + AttributeName = "huskinfection"; + } } else { @@ -172,7 +173,8 @@ namespace Barotrauma public bool Matches(ISerializableEntity target) { - string valStr = AttributeValue.ToString(); + string valStr = AttributeValue.ToString(); + switch (Type) { case ConditionType.PropertyValue: diff --git a/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/StatusEffect.cs b/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/StatusEffect.cs index 278558a3e..cee21264e 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/StatusEffect.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/StatusEffects/StatusEffect.cs @@ -1,5 +1,4 @@ -using Barotrauma.Extensions; -using Barotrauma.Items.Components; +using Barotrauma.Items.Components; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; @@ -10,27 +9,11 @@ namespace Barotrauma { class DurationListElement { - public readonly StatusEffect Parent; - public readonly Entity Entity; - public readonly List Targets; - public Character User { get; private set; } - + public StatusEffect Parent; + public Entity Entity; + public List Targets; public float Timer; - - public DurationListElement(StatusEffect parentEffect, Entity parentEntity, IEnumerable targets, float duration, Character user) - { - Parent = parentEffect; - Entity = parentEntity; - Targets = new List(targets); - Timer = duration; - User = user; - } - - public void Reset(float duration, Character newUser) - { - Timer = duration; - User = newUser; - } + public Character User; } partial class StatusEffect @@ -71,7 +54,7 @@ namespace Barotrauma //backwards compatibility DebugConsole.ThrowError("Error in StatusEffect config (" + element.ToString() + ") - use item identifier instead of the name."); string itemPrefabName = element.GetAttributeString("name", ""); - ItemPrefab = ItemPrefab.Prefabs.Find(m => m.NameMatches(itemPrefabName, StringComparison.OrdinalIgnoreCase) || m.Tags.Contains(itemPrefabName)); + ItemPrefab = ItemPrefab.Prefabs.Find(m => m.NameMatches(itemPrefabName) || m.Tags.Contains(itemPrefabName)); if (ItemPrefab == null) { DebugConsole.ThrowError("Error in StatusEffect \""+ parentDebugName + "\" - item prefab \"" + itemPrefabName + "\" not found."); @@ -374,7 +357,7 @@ namespace Barotrauma { DebugConsole.ThrowError("Error in StatusEffect (" + parentDebugName + ") - define afflictions using identifiers instead of names."); string afflictionName = subElement.GetAttributeString("name", "").ToLowerInvariant(); - afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(ap => ap.Name.Equals(afflictionName, StringComparison.OrdinalIgnoreCase)); + afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(ap => ap.Name.ToLowerInvariant() == afflictionName); if (afflictionPrefab == null) { DebugConsole.ThrowError("Error in StatusEffect (" + parentDebugName + ") - Affliction prefab \"" + afflictionName + "\" not found."); @@ -384,7 +367,7 @@ namespace Barotrauma else { string afflictionIdentifier = subElement.GetAttributeString("identifier", "").ToLowerInvariant(); - afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(ap => ap.Identifier.Equals(afflictionIdentifier, StringComparison.OrdinalIgnoreCase)); + afflictionPrefab = AfflictionPrefab.List.FirstOrDefault(ap => ap.Identifier.ToLowerInvariant() == afflictionIdentifier); if (afflictionPrefab == null) { DebugConsole.ThrowError("Error in StatusEffect (" + parentDebugName + ") - Affliction prefab with the identifier \"" + afflictionIdentifier + "\" not found."); @@ -493,68 +476,41 @@ namespace Barotrauma } } - public bool HasRequiredConditions(IEnumerable targets) - { - return HasRequiredConditions(targets, targetingContainer: false); - } - - private bool HasRequiredConditions(IEnumerable targets, bool targetingContainer) + public virtual bool HasRequiredConditions(List targets) { if (!propertyConditionals.Any()) { return true; } - if (requiredItems.Any() && requiredItems.All(ri => ri.MatchOnEmpty) && !targets.Any()) { return true; } + if (requiredItems.Any() && requiredItems.All(ri => ri.MatchOnEmpty) && targets.Count == 0) { return true; } switch (conditionalComparison) { case PropertyConditional.Comparison.Or: - foreach (PropertyConditional pc in propertyConditionals) + foreach (ISerializableEntity target in targets) { - if (pc.TargetContainer && !targetingContainer) + foreach (PropertyConditional pc in propertyConditionals) { - var target = targets.FirstOrDefault(t => t is Item || t is ItemComponent); - var targetItem = target as Item ?? (target as ItemComponent)?.Item; - if (targetItem?.ParentInventory == null) { continue; } - if (targetItem.ParentInventory.Owner is Item container && HasRequiredConditions(container.AllPropertyObjects, targetingContainer: true)) { return true; } - if (targetItem.ParentInventory.Owner is Character character && HasRequiredConditions(character.ToEnumerable(), targetingContainer: true)) { return true; } - } - else - { - foreach (ISerializableEntity target in targets) + if (!string.IsNullOrEmpty(pc.TargetItemComponentName)) { - if (!string.IsNullOrEmpty(pc.TargetItemComponentName)) + if (!(target is ItemComponent ic) || ic.Name != pc.TargetItemComponentName) { - if (!(target is ItemComponent ic) || ic.Name != pc.TargetItemComponentName) - { - continue; - } + continue; } - if (pc.Matches(target)) { return true; } } + if (pc.Matches(target)) { return true; } } } return false; case PropertyConditional.Comparison.And: - foreach (PropertyConditional pc in propertyConditionals) + foreach (ISerializableEntity target in targets) { - if (pc.TargetContainer && !targetingContainer) + foreach (PropertyConditional pc in propertyConditionals) { - var target = targets.FirstOrDefault(t => t is Item || t is ItemComponent); - var targetItem = target as Item ?? (target as ItemComponent)?.Item; - if (targetItem?.ParentInventory == null) { return false; } - if (targetItem.ParentInventory.Owner is Item container && !HasRequiredConditions(container.AllPropertyObjects, targetingContainer: true)) { return false; } - if (targetItem.ParentInventory.Owner is Character character && !HasRequiredConditions(character.ToEnumerable(), targetingContainer: true)) { return false; } - } - else - { - foreach (ISerializableEntity target in targets) + if (!string.IsNullOrEmpty(pc.TargetItemComponentName)) { - if (!string.IsNullOrEmpty(pc.TargetItemComponentName)) + if (!(target is ItemComponent ic) || ic.Name != pc.TargetItemComponentName) { - if (!(target is ItemComponent ic) || ic.Name != pc.TargetItemComponentName) - { - continue; - } + continue; } - if (!pc.Matches(target)) { return false; } } + if (!pc.Matches(target)) { return false; } } } return true; @@ -604,26 +560,33 @@ namespace Barotrauma public virtual void Apply(ActionType type, float deltaTime, Entity entity, ISerializableEntity target, Vector2? worldPosition = null) { - if (this.type != type || !HasRequiredItems(entity)) { return; } + if (this.type != type || !HasRequiredItems(entity)) return; - if (targetIdentifiers != null && !IsValidTarget(target)) { return; } + if (targetIdentifiers != null && !IsValidTarget(target)) return; if (duration > 0.0f && !Stackable) { //ignore if not stackable and there's already an identical statuseffect DurationListElement existingEffect = DurationList.Find(d => d.Parent == this && d.Targets.FirstOrDefault() == target); - existingEffect?.Reset(Math.Max(existingEffect.Timer, duration), user); - return; + if (existingEffect != null) + { + existingEffect.Timer = Math.Max(existingEffect.Timer, duration); + existingEffect.User = user; + return; + } } - if (!HasRequiredConditions(target.ToEnumerable())) { return; } - Apply(deltaTime, entity, target.ToEnumerable(), worldPosition); + List targets = new List { target }; + + if (!HasRequiredConditions(targets)) return; + + Apply(deltaTime, entity, targets, worldPosition); } protected readonly List currentTargets = new List(); public virtual void Apply(ActionType type, float deltaTime, Entity entity, IEnumerable targets, Vector2? worldPosition = null) { - if (this.type != type) { return; } + if (this.type != type) return; currentTargets.Clear(); foreach (ISerializableEntity target in targets) @@ -638,20 +601,24 @@ namespace Barotrauma if (targetIdentifiers != null && currentTargets.Count == 0) { return; } - if (!HasRequiredItems(entity) || !HasRequiredConditions(currentTargets)) { return; } + if (!HasRequiredItems(entity) || !HasRequiredConditions(currentTargets)) return; if (duration > 0.0f && !Stackable) { //ignore if not stackable and there's already an identical statuseffect DurationListElement existingEffect = DurationList.Find(d => d.Parent == this && d.Targets.SequenceEqual(currentTargets)); - existingEffect?.Reset(Math.Max(existingEffect.Timer, duration), user); - return; + if (existingEffect != null) + { + existingEffect.Timer = Math.Max(existingEffect.Timer, duration); + existingEffect.User = user; + return; + } } Apply(deltaTime, entity, currentTargets, worldPosition); } - protected void Apply(float deltaTime, Entity entity, IEnumerable targets, Vector2? worldPosition = null) + protected void Apply(float deltaTime, Entity entity, List targets, Vector2? worldPosition = null) { if (lifeTime > 0) { @@ -718,7 +685,16 @@ namespace Barotrauma if (duration > 0.0f) { - DurationList.Add(new DurationListElement(this, entity, targets, duration, user)); + DurationListElement element = new DurationListElement + { + Parent = this, + Timer = duration, + Entity = entity, + Targets = targets, + User = user + }; + + DurationList.Add(element); } else { @@ -756,7 +732,7 @@ namespace Barotrauma character.LastDamageSource = entity; foreach (Limb limb in character.AnimController.Limbs) { - limb.character.DamageLimb(position, limb, multipliedAffliction.ToEnumerable(), stun: 0.0f, playSound: false, attackImpulse: 0.0f, attacker: affliction.Source); + limb.character.DamageLimb(position, limb, new List() { multipliedAffliction }, stun: 0.0f, playSound: false, attackImpulse: 0.0f, attacker: affliction.Source); limb.character.TrySeverLimbJoints(limb, SeverLimbsProbability); //only apply non-limb-specific afflictions to the first limb if (!affliction.Prefab.LimbSpecific) { break; } @@ -765,7 +741,7 @@ namespace Barotrauma else if (target is Limb limb) { if (limb.character.Removed || limb.Removed) { continue; } - limb.character.DamageLimb(position, limb, multipliedAffliction.ToEnumerable(), stun: 0.0f, playSound: false, attackImpulse: 0.0f, attacker: affliction.Source); + limb.character.DamageLimb(position, limb, new List() { multipliedAffliction }, stun: 0.0f, playSound: false, attackImpulse: 0.0f, attacker: affliction.Source); limb.character.TrySeverLimbJoints(limb, SeverLimbsProbability); } } @@ -788,7 +764,6 @@ namespace Barotrauma { float prevVitality = targetCharacter.Vitality; targetCharacter.CharacterHealth.ReduceAffliction(targetLimb, reduceAffliction.First, reduceAmount); - targetCharacter.TryAdjustAttackerSkill(user, targetCharacter.Vitality - prevVitality); #if SERVER GameMain.Server.KarmaManager.OnCharacterHealthChanged(targetCharacter, user, prevVitality - targetCharacter.Vitality); #endif @@ -878,7 +853,7 @@ namespace Barotrauma ApplyProjSpecific(deltaTime, entity, targets, hull, position); } - partial void ApplyProjSpecific(float deltaTime, Entity entity, IEnumerable targets, Hull currentHull, Vector2 worldPosition); + partial void ApplyProjSpecific(float deltaTime, Entity entity, List targets, Hull currentHull, Vector2 worldPosition); private void ApplyToProperty(ISerializableEntity target, SerializableProperty property, object value, float deltaTime) { @@ -959,12 +934,12 @@ namespace Barotrauma if (target is Character character) { if (character.Removed) { continue; } - character.AddDamage(character.WorldPosition, multipliedAffliction.ToEnumerable(), stun: 0.0f, playSound: false, attacker: element.User); + character.AddDamage(character.WorldPosition, new List() { multipliedAffliction }, stun: 0.0f, playSound: false, attacker: element.User); } else if (target is Limb limb) { if (limb.character.Removed || limb.Removed) { continue; } - limb.character.DamageLimb(limb.WorldPosition, limb, multipliedAffliction.ToEnumerable(), stun: 0.0f, playSound: false, attackImpulse: 0.0f, attacker: element.User); + limb.character.DamageLimb(limb.WorldPosition, limb, new List() { multipliedAffliction }, stun: 0.0f, playSound: false, attackImpulse: 0.0f, attacker: element.User); } } @@ -985,7 +960,6 @@ namespace Barotrauma { float prevVitality = targetCharacter.Vitality; targetCharacter.CharacterHealth.ReduceAffliction(targetLimb, reduceAffliction.First, reduceAffliction.Second * deltaTime); - targetCharacter.TryAdjustAttackerSkill(element.User, targetCharacter.Vitality - prevVitality); #if SERVER GameMain.Server.KarmaManager.OnCharacterHealthChanged(targetCharacter, element.User, prevVitality - targetCharacter.Vitality); #endif diff --git a/Barotrauma/BarotraumaShared/SharedSource/TextManager.cs b/Barotrauma/BarotraumaShared/SharedSource/TextManager.cs index 4be9d38ad..23b4288c2 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/TextManager.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/TextManager.cs @@ -216,13 +216,6 @@ namespace Barotrauma } } -#if DEBUG - if (GameMain.Config != null && GameMain.Config.TextManagerDebugModeEnabled) - { - return textTag; - } -#endif - foreach (TextPack textPack in textPacks[Language]) { string text = textPack.Get(textTag); diff --git a/Barotrauma/BarotraumaShared/SharedSource/TextPack.cs b/Barotrauma/BarotraumaShared/SharedSource/TextPack.cs index 26ad16718..ff7efc692 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/TextPack.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/TextPack.cs @@ -30,7 +30,7 @@ namespace Barotrauma { doc = XMLExtensions.TryLoadXml(filePath); if (doc != null) { break; } - if (filePath.Equals("content/texts/englishvanilla.xml", StringComparison.OrdinalIgnoreCase)) + if (filePath.ToLowerInvariant() == "content/texts/englishvanilla.xml") { //try fixing legacy EnglishVanilla path string newPath = "Content/Texts/English/EnglishVanilla.xml"; diff --git a/Barotrauma/BarotraumaShared/SharedSource/Utils/ToolBox.cs b/Barotrauma/BarotraumaShared/SharedSource/Utils/ToolBox.cs index 1fe670106..6f31de524 100644 --- a/Barotrauma/BarotraumaShared/SharedSource/Utils/ToolBox.cs +++ b/Barotrauma/BarotraumaShared/SharedSource/Utils/ToolBox.cs @@ -118,10 +118,6 @@ namespace Barotrauma for (int i = 0; i < subDirs.Length; i++) { - if (i == subDirs.Length - 1 && string.IsNullOrEmpty(subDirs[i])) - { - break; - } string enumPath = string.IsNullOrEmpty(filename) ? "./" : filename; List filePaths = Directory.GetFileSystemEntries(enumPath).Select(s => Path.GetFileName(s)).ToList(); if (filePaths.Any(s => s.Equals(subDirs[i], StringComparison.Ordinal))) @@ -151,7 +147,7 @@ namespace Barotrauma public static string RemoveInvalidFileNameChars(string fileName) { - var invalidChars = Path.GetInvalidFileNameChars().Concat(new char[] {':', ';'}); + var invalidChars = Path.GetInvalidFileNameChars(); foreach (char invalidChar in invalidChars) { fileName = fileName.Replace(invalidChar.ToString(), ""); diff --git a/Barotrauma/BarotraumaShared/Submarines/Berilia.sub b/Barotrauma/BarotraumaShared/Submarines/Berilia.sub index 4b5d06bfc..4968e0976 100644 Binary files a/Barotrauma/BarotraumaShared/Submarines/Berilia.sub and b/Barotrauma/BarotraumaShared/Submarines/Berilia.sub differ diff --git a/Barotrauma/BarotraumaShared/Submarines/Humpback.sub b/Barotrauma/BarotraumaShared/Submarines/Humpback.sub index 20e29f6cd..950e13ff9 100644 Binary files a/Barotrauma/BarotraumaShared/Submarines/Humpback.sub and b/Barotrauma/BarotraumaShared/Submarines/Humpback.sub differ diff --git a/Barotrauma/BarotraumaShared/Submarines/Kastrull.sub b/Barotrauma/BarotraumaShared/Submarines/Kastrull.sub index 81e94e034..0fefa6c94 100644 Binary files a/Barotrauma/BarotraumaShared/Submarines/Kastrull.sub and b/Barotrauma/BarotraumaShared/Submarines/Kastrull.sub differ diff --git a/Barotrauma/BarotraumaShared/Submarines/KastrullDrone.sub b/Barotrauma/BarotraumaShared/Submarines/KastrullDrone.sub index 7ffd2212b..7524f6b98 100644 Binary files a/Barotrauma/BarotraumaShared/Submarines/KastrullDrone.sub and b/Barotrauma/BarotraumaShared/Submarines/KastrullDrone.sub differ diff --git a/Barotrauma/BarotraumaShared/Submarines/Remora.sub b/Barotrauma/BarotraumaShared/Submarines/Remora.sub index dddef7978..9a91693e5 100644 Binary files a/Barotrauma/BarotraumaShared/Submarines/Remora.sub and b/Barotrauma/BarotraumaShared/Submarines/Remora.sub differ diff --git a/Barotrauma/BarotraumaShared/Submarines/Typhon2.sub b/Barotrauma/BarotraumaShared/Submarines/Typhon2.sub index 45aa395d7..2925bd7cb 100644 Binary files a/Barotrauma/BarotraumaShared/Submarines/Typhon2.sub and b/Barotrauma/BarotraumaShared/Submarines/Typhon2.sub differ diff --git a/Barotrauma/BarotraumaShared/changelog.txt b/Barotrauma/BarotraumaShared/changelog.txt index 09bdaea9e..4ab81f579 100644 --- a/Barotrauma/BarotraumaShared/changelog.txt +++ b/Barotrauma/BarotraumaShared/changelog.txt @@ -1,3 +1,9 @@ +--------------------------------------------------------------------------------------------------------- +v0.9.7.1 +--------------------------------------------------------------------------------------------------------- + +- Fixed crashing when attempting to publish Workshop items. + --------------------------------------------------------------------------------------------------------- v0.9.7.0 --------------------------------------------------------------------------------------------------------- diff --git a/Barotrauma/BarotraumaShared/serversettings.xml b/Barotrauma/BarotraumaShared/serversettings.xml index fb58fd6df..4960cd465 100644 --- a/Barotrauma/BarotraumaShared/serversettings.xml +++ b/Barotrauma/BarotraumaShared/serversettings.xml @@ -43,7 +43,7 @@ endvoterequiredratio="0.6" kickvoterequiredratio="0.6" killdisconnectedtime="120" - kickafktime="600" + kickafktime="120" traitoruseratio="True" traitorratio="0.2" karmaenabled="False" diff --git a/Deploy/Linux/DeployLinux.sh b/Deploy/Linux/DeployLinux.sh index c9f7e721b..822bdb7f8 100644 --- a/Deploy/Linux/DeployLinux.sh +++ b/Deploy/Linux/DeployLinux.sh @@ -3,8 +3,8 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish LinuxClient.csproj -c Release -clp:"ErrorsOnly;Summary" --self-contained -r linux-x64 \/p:Platform="x64" +dotnet publish LinuxClient.csproj -c Release --self-contained -r linux-x64 \/p:Platform="x64" cd .. cd BarotraumaServer -dotnet publish LinuxServer.csproj -c Release -clp:"ErrorsOnly;Summary" --self-contained -r linux-x64 \/p:Platform="x64" +dotnet publish LinuxServer.csproj -c Release --self-contained -r linux-x64 \/p:Platform="x64" diff --git a/Deploy/Linux/DeployLinuxServer.sh b/Deploy/Linux/DeployLinuxServer.sh new file mode 100644 index 000000000..4d05a7814 --- /dev/null +++ b/Deploy/Linux/DeployLinuxServer.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +cd ../../Barotrauma/BarotraumaServer +dotnet publish LinuxServer.csproj -c Release --self-contained -r linux-x64 \/p:Platform="x64" diff --git a/Deploy/Linux/DeployLinuxUnstable.sh b/Deploy/Linux/DeployLinuxUnstable.sh index e38a25d8d..7362f9057 100644 --- a/Deploy/Linux/DeployLinuxUnstable.sh +++ b/Deploy/Linux/DeployLinuxUnstable.sh @@ -3,8 +3,8 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish LinuxClient.csproj -c Unstable -clp:"ErrorsOnly;Summary" --self-contained -r linux-x64 \/p:Platform="x64" +dotnet publish LinuxClient.csproj -c Unstable --self-contained -r linux-x64 \/p:Platform="x64" cd .. cd BarotraumaServer -dotnet publish LinuxServer.csproj -c Unstable -clp:ErrorsOnly;Summary" --self-contained -r linux-x64 \/p:Platform="x64" +dotnet publish LinuxServer.csproj -c Unstable --self-contained -r linux-x64 \/p:Platform="x64" diff --git a/Deploy/Linux/DeployMac.sh b/Deploy/Linux/DeployMac.sh index 0bde38073..7a0c51c02 100644 --- a/Deploy/Linux/DeployMac.sh +++ b/Deploy/Linux/DeployMac.sh @@ -3,8 +3,8 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish MacClient.csproj -c Release -clp:"ErrorsOnly;Summary" --self-contained -r osx-x64 \/p:Platform="x64" +dotnet publish MacClient.csproj -c Release --self-contained -r osx-x64 \/p:Platform="x64" cd .. cd BarotraumaServer -dotnet publish MacServer.csproj -c Release -clp:"ErrorsOnly;Summary" --self-contained -r osx-x64 \/p:Platform="x64" +dotnet publish MacServer.csproj -c Release --self-contained -r osx-x64 \/p:Platform="x64" diff --git a/Deploy/Linux/DeployMacUnstable.sh b/Deploy/Linux/DeployMacUnstable.sh index ecccfe3fc..683ad7973 100644 --- a/Deploy/Linux/DeployMacUnstable.sh +++ b/Deploy/Linux/DeployMacUnstable.sh @@ -3,8 +3,8 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish MacClient.csproj -c Unstable -clp:"ErrorsOnly;Summary" --self-contained -r osx-x64 \/p:Platform="x64" +dotnet publish MacClient.csproj -c Unstable --self-contained -r osx-x64 \/p:Platform="x64" cd .. cd BarotraumaServer -dotnet publish MacServer.csproj -c Unstable -clp:"ErrorsOnly;Summary" --self-contained -r osx-x64 \/p:Platform="x64" +dotnet publish MacServer.csproj -c Unstable --self-contained -r osx-x64 \/p:Platform="x64" diff --git a/Deploy/Linux/DeployWindows.sh b/Deploy/Linux/DeployWindows.sh index 527841ed4..8adb6aab6 100644 --- a/Deploy/Linux/DeployWindows.sh +++ b/Deploy/Linux/DeployWindows.sh @@ -3,8 +3,8 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish WindowsClient.csproj -c Release -clp:"ErrorsOnly;Summary" --self-contained -r win-x64 \/p:Platform="x64" +dotnet publish WindowsClient.csproj -c Release --self-contained -r win-x64 \/p:Platform="x64" cd .. cd BarotraumaServer -dotnet publish WindowsServer.csproj -c Release -clp:"ErrorsOnly;Summary" --self-contained -r win-x64 \/p:Platform="x64" +dotnet publish WindowsServer.csproj -c Release --self-contained -r win-x64 \/p:Platform="x64" diff --git a/Deploy/Linux/DeployWindowsUnstable.sh b/Deploy/Linux/DeployWindowsUnstable.sh index ccabb7aee..e37eb630c 100644 --- a/Deploy/Linux/DeployWindowsUnstable.sh +++ b/Deploy/Linux/DeployWindowsUnstable.sh @@ -3,8 +3,8 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish WindowsClient.csproj -c Unstable -clp:"ErrorsOnly;Summary" --self-contained -r win-x64 \/p:Platform="x64" +dotnet publish WindowsClient.csproj -c Unstable --self-contained -r win-x64 \/p:Platform="x64" cd .. cd BarotraumaServer -dotnet publish WindowsServer.csproj -c Unstable -clp:"ErrorsOnly;Summary" --self-contained -r win-x64 \/p:Platform="x64" +dotnet publish WindowsServer.csproj -c Unstable --self-contained -r win-x64 \/p:Platform="x64" diff --git a/Deploy/Windows/DeployLinux.bat b/Deploy/Windows/DeployLinux.bat index 13cebab0c..337966b26 100644 --- a/Deploy/Windows/DeployLinux.bat +++ b/Deploy/Windows/DeployLinux.bat @@ -3,10 +3,10 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish LinuxClient.csproj -c Release -clp:ErrorsOnly;Summary --self-contained -r linux-x64 /p:Platform=x64 +dotnet publish LinuxClient.csproj -c Release --self-contained -r linux-x64 /p:Platform=x64 cd .. cd BarotraumaServer -dotnet publish LinuxServer.csproj -c Release -clp:ErrorsOnly;Summary --self-contained -r linux-x64 /p:Platform=x64 +dotnet publish LinuxServer.csproj -c Release --self-contained -r linux-x64 /p:Platform=x64 PAUSE diff --git a/Deploy/Windows/DeployLinuxUnstable.bat b/Deploy/Windows/DeployLinuxUnstable.bat index ce7c60bc5..eb3279e76 100644 --- a/Deploy/Windows/DeployLinuxUnstable.bat +++ b/Deploy/Windows/DeployLinuxUnstable.bat @@ -3,10 +3,10 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish LinuxClient.csproj -c Unstable -clp:ErrorsOnly;Summary --self-contained -r linux-x64 /p:Platform=x64 +dotnet publish LinuxClient.csproj -c Unstable --self-contained -r linux-x64 /p:Platform=x64 cd .. cd BarotraumaServer -dotnet publish LinuxServer.csproj -c Unstable -clp:ErrorsOnly;Summary --self-contained -r linux-x64 /p:Platform=x64 +dotnet publish LinuxServer.csproj -c Unstable --self-contained -r linux-x64 /p:Platform=x64 PAUSE diff --git a/Deploy/Windows/DeployMac.bat b/Deploy/Windows/DeployMac.bat index c1488f7a3..6b4b8ade6 100644 --- a/Deploy/Windows/DeployMac.bat +++ b/Deploy/Windows/DeployMac.bat @@ -3,10 +3,10 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish MacClient.csproj -c Release -clp:ErrorsOnly;Summary --self-contained -r osx-x64 /p:Platform=x64 +dotnet publish MacClient.csproj -c Release --self-contained -r osx-x64 /p:Platform=x64 cd .. cd BarotraumaServer -dotnet publish MacServer.csproj -c Release -clp:ErrorsOnly;Summary --self-contained -r osx-x64 /p:Platform=x64 +dotnet publish MacServer.csproj -c Release --self-contained -r osx-x64 /p:Platform=x64 PAUSE diff --git a/Deploy/Windows/DeployMacUnstable.bat b/Deploy/Windows/DeployMacUnstable.bat index 771f83526..321211736 100644 --- a/Deploy/Windows/DeployMacUnstable.bat +++ b/Deploy/Windows/DeployMacUnstable.bat @@ -3,10 +3,10 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish MacClient.csproj -c Unstable -clp:ErrorsOnly;Summary --self-contained -r osx-x64 /p:Platform=x64 +dotnet publish MacClient.csproj -c Unstable --self-contained -r osx-x64 /p:Platform=x64 cd .. cd BarotraumaServer -dotnet publish MacServer.csproj -c Unstable -clp:ErrorsOnly;Summary --self-contained -r osx-x64 /p:Platform=x64 +dotnet publish MacServer.csproj -c Unstable --self-contained -r osx-x64 /p:Platform=x64 PAUSE diff --git a/Deploy/Windows/DeployWindows.bat b/Deploy/Windows/DeployWindows.bat index cdd63185f..93331e334 100644 --- a/Deploy/Windows/DeployWindows.bat +++ b/Deploy/Windows/DeployWindows.bat @@ -3,10 +3,10 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish WindowsClient.csproj -c Release -clp:ErrorsOnly;Summary --self-contained -r win-x64 /p:Platform=x64 +dotnet publish WindowsClient.csproj -c Release --self-contained -r win-x64 /p:Platform=x64 cd .. cd BarotraumaServer -dotnet publish WindowsServer.csproj -c Release -clp:ErrorsOnly;Summary --self-contained -r win-x64 /p:Platform=x64 +dotnet publish WindowsServer.csproj -c Release --self-contained -r win-x64 /p:Platform=x64 PAUSE diff --git a/Deploy/Windows/DeployWindowsServer.bat b/Deploy/Windows/DeployWindowsServer.bat new file mode 100644 index 000000000..865d61d03 --- /dev/null +++ b/Deploy/Windows/DeployWindowsServer.bat @@ -0,0 +1,6 @@ +@ECHO OFF + +cd ../../Barotrauma/BarotraumaServer +dotnet publish WindowsServer.csproj -c Release --self-contained -r win-x64 /p:Platform=x64 + +PAUSE diff --git a/Deploy/Windows/DeployWindowsUnstable.bat b/Deploy/Windows/DeployWindowsUnstable.bat index d8d4b4f7e..99847a16c 100644 --- a/Deploy/Windows/DeployWindowsUnstable.bat +++ b/Deploy/Windows/DeployWindowsUnstable.bat @@ -3,10 +3,10 @@ cd ../../Barotrauma cd BarotraumaClient -dotnet publish WindowsClient.csproj -c Unstable -clp:ErrorsOnly;Summary --self-contained -r win-x64 /p:Platform=x64 +dotnet publish WindowsClient.csproj -c Unstable --self-contained -r win-x64 /p:Platform=x64 cd .. cd BarotraumaServer -dotnet publish WindowsServer.csproj -c Unstable -clp:ErrorsOnly;Summary --self-contained -r win-x64 /p:Platform=x64 +dotnet publish WindowsServer.csproj -c Unstable --self-contained -r win-x64 /p:Platform=x64 PAUSE diff --git a/Libraries/Lidgren.Network/NetBuffer.cs b/Libraries/Lidgren.Network/NetBuffer.cs index 15903bb73..34c783fde 100644 --- a/Libraries/Lidgren.Network/NetBuffer.cs +++ b/Libraries/Lidgren.Network/NetBuffer.cs @@ -76,7 +76,7 @@ namespace Lidgren.Network MethodInfo[] methods = typeof(NetIncomingMessage).GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (MethodInfo mi in methods) { - if (mi.GetParameters().Length == 0 && mi.Name.StartsWith("Read", StringComparison.OrdinalIgnoreCase) && mi.Name.Substring(4) == mi.ReturnType.Name) + if (mi.GetParameters().Length == 0 && mi.Name.StartsWith("Read", StringComparison.InvariantCulture) && mi.Name.Substring(4) == mi.ReturnType.Name) { s_readMethods[mi.ReturnType] = mi; } @@ -86,7 +86,7 @@ namespace Lidgren.Network methods = typeof(NetOutgoingMessage).GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (MethodInfo mi in methods) { - if (mi.Name.Equals("Write", StringComparison.OrdinalIgnoreCase)) + if (mi.Name.Equals("Write", StringComparison.InvariantCulture)) { ParameterInfo[] pis = mi.GetParameters(); if (pis.Length == 1) diff --git a/Libraries/Lidgren.Network/NetUtility.cs b/Libraries/Lidgren.Network/NetUtility.cs index 0c437ce7f..349d1150b 100644 --- a/Libraries/Lidgren.Network/NetUtility.cs +++ b/Libraries/Lidgren.Network/NetUtility.cs @@ -401,7 +401,7 @@ namespace Lidgren.Network { if (j >= h) { - if (string.Compare(list[j - h].Name, tmp.Name, StringComparison.OrdinalIgnoreCase) > 0) + if (string.Compare(list[j - h].Name, tmp.Name, StringComparison.InvariantCulture) > 0) { list[j] = list[j - h]; j -= h; diff --git a/Libraries/XNATypes/Rectangle.cs b/Libraries/XNATypes/Rectangle.cs index c9c7b77a2..f8a73be11 100644 --- a/Libraries/XNATypes/Rectangle.cs +++ b/Libraries/XNATypes/Rectangle.cs @@ -375,15 +375,6 @@ namespace Microsoft.Xna.Framework Height += (int)verticalAmount * 2; } - /// - /// Adjusts the edges of this by specified horizontal and vertical amounts. - /// - /// Value to adjust the edges. - public void Inflate(Vector2 amount) - { - Inflate(amount.X, amount.Y); - } - /// /// Gets whether or not the other intersects with this rectangle. ///