コード例 #1
0
ファイル: GameSession.cs プロジェクト: akosipc/Barotrauma
        public void EndRound(string endMessage)
        {
            if (Mission != null)
            {
                Mission.End();
            }
            GameAnalyticsManager.AddProgressionEvent(
                (Mission == null || Mission.Completed)  ? GameAnalyticsSDK.Net.EGAProgressionStatus.Complete : GameAnalyticsSDK.Net.EGAProgressionStatus.Fail,
                GameMode.Preset.Identifier,
                (Mission == null ? "None" : Mission.GetType().ToString()));

#if CLIENT
            if (roundSummary != null)
            {
                GUIFrame summaryFrame = roundSummary.CreateSummaryFrame(endMessage);
                GUIMessageBox.MessageBoxes.Add(summaryFrame);
                var okButton = new GUIButton(new RectTransform(new Vector2(0.2f, 1.0f), summaryFrame.Children.First().Children.First().FindChild("buttonarea").RectTransform),
                                             TextManager.Get("OK"))
                {
                    OnClicked = (GUIButton button, object obj) => { GUIMessageBox.MessageBoxes.Remove(summaryFrame); return(true); }
                };
            }
#endif

            EventManager.EndRound();
            SteamAchievementManager.OnRoundEnded(this);

            Mission = null;

            StatusEffect.StopAll();
        }
コード例 #2
0
ファイル: Structure.cs プロジェクト: Leonidas-ai/Barotrauma
        public void ClientRead(ServerNetObject type, IReadMessage msg, float sendingTime)
        {
            byte sectionCount = msg.ReadByte();

            bool invalidMessage = false;

            if (type != ServerNetObject.ENTITY_EVENT && type != ServerNetObject.ENTITY_EVENT_INITIAL)
            {
                DebugConsole.NewMessage($"Error while reading a network event for the structure \"{Name} ({ID})\". Invalid event type ({type}).", Color.Red);
                return;
            }
            else if (sectionCount != Sections.Length)
            {
                invalidMessage = true;
                string errorMsg = $"Error while reading a network event for the structure \"{Name} ({ID})\". Section count does not match (server: {sectionCount} client: {Sections.Length})";
                DebugConsole.NewMessage(errorMsg, Color.Red);
                GameAnalyticsManager.AddErrorEventOnce("Structure.ClientRead:SectionCountMismatch", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
            }

            for (int i = 0; i < sectionCount; i++)
            {
                float damage = msg.ReadRangedSingle(0.0f, 1.0f, 8) * MaxHealth;
                if (!invalidMessage && i < Sections.Length)
                {
                    SetDamage(i, damage);
                }
            }
        }
コード例 #3
0
ファイル: Hull.cs プロジェクト: DoctorJPrototype/Barotrauma
        public override XElement Save(XElement parentElement)
        {
            if (Submarine == null)
            {
                string errorMsg = "Error - tried to save a hull that's not a part of any submarine.\n" + Environment.StackTrace;
                DebugConsole.ThrowError(errorMsg);
                GameAnalyticsManager.AddErrorEventOnce("Hull.Save:WorldHull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                return(null);
            }

            XElement element = new XElement("Hull");

            element.Add
            (
                new XAttribute("ID", ID),
                new XAttribute("rect",
                               (int)(rect.X - Submarine.HiddenSubPosition.X) + "," +
                               (int)(rect.Y - Submarine.HiddenSubPosition.Y) + "," +
                               rect.Width + "," + rect.Height),
                new XAttribute("water", waterVolume)
            );

            if (linkedTo != null && linkedTo.Count > 0)
            {
                var saveableLinked = linkedTo.Where(l => l.ShouldBeSaved).ToList();
                element.Add(new XAttribute("linked", string.Join(",", saveableLinked.Select(l => l.ID.ToString()))));
            }
            SerializableProperty.SerializeProperties(this, element);
            parentElement.Add(element);
            return(element);
        }
コード例 #4
0
 private void InitUserStats()
 {
     if (GameSettings.ShowUserStatisticsPrompt)
     {
         var userStatsPrompt = new GUIMessageBox(
             "Do you want to help us make Barotrauma better?",
             "Do you allow Barotrauma to send usage statistics and error reports to the developers? The data is anonymous, " +
             "does not contain any personal information and is only used to help us diagnose issues and improve Barotrauma.",
             new string[] { "Yes", "No" });
         userStatsPrompt.Buttons[0].OnClicked += (btn, userdata) =>
         {
             GameSettings.ShowUserStatisticsPrompt = false;
             GameSettings.SendUserStatistics       = true;
             GameAnalyticsManager.Init();
             return(true);
         };
         userStatsPrompt.Buttons[0].OnClicked += userStatsPrompt.Close;
         userStatsPrompt.Buttons[1].OnClicked += (btn, userdata) =>
         {
             GameSettings.ShowUserStatisticsPrompt = false;
             GameSettings.SendUserStatistics       = false;
             return(true);
         };
         userStatsPrompt.Buttons[1].OnClicked += userStatsPrompt.Close;
     }
     else if (GameSettings.SendUserStatistics)
     {
         GameAnalyticsManager.Init();
     }
 }
コード例 #5
0
        partial void InitProjectSpecific()
        {
            string previewImageData = SubmarineElement.GetAttributeString("previewimage", "");

            if (!string.IsNullOrEmpty(previewImageData))
            {
                try
                {
                    using (System.IO.MemoryStream mem = new System.IO.MemoryStream(Convert.FromBase64String(previewImageData)))
                    {
                        var texture = TextureLoader.FromStream(mem, path: FilePath, compress: false);
                        if (texture == null)
                        {
                            throw new Exception("PreviewImage texture returned null");
                        }
                        PreviewImage = new Sprite(texture, null, null);
                    }
                }
                catch (Exception e)
                {
                    DebugConsole.ThrowError("Loading the preview image of the submarine \"" + Name + "\" failed. The file may be corrupted.", e);
                    GameAnalyticsManager.AddErrorEventOnce("Submarine..ctor:PreviewImageLoadingFailed", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                                                           "Loading the preview image of the submarine \"" + Name + "\" failed. The file may be corrupted.");
                    PreviewImage = null;
                }
            }
        }
コード例 #6
0
        private bool IsValidValue(Vector2 value, string valueName, float minValue = float.MinValue, float maxValue = float.MaxValue)
        {
            if (!MathUtils.IsValid(value) ||
                (value.X < minValue || value.Y < minValue) ||
                (value.X > maxValue || value.Y > maxValue))
            {
                string userData = UserData == null ? "null" : UserData.ToString();
                string errorMsg =
                    "Attempted to apply invalid " + valueName +
                    " to a physics body (userdata: " + userData +
                    "), value: " + value;
                if (GameMain.NetworkMember != null)
                {
                    errorMsg += GameMain.NetworkMember.IsClient ? " Playing as a client." : " Hosting a server.";
                }
                errorMsg += "\n" + Environment.StackTrace.CleanupStackTrace();

                if (GameSettings.VerboseLogging)
                {
                    DebugConsole.ThrowError(errorMsg);
                }
                GameAnalyticsManager.AddErrorEventOnce(
                    "PhysicsBody.SetPosition:InvalidPosition" + userData,
                    GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                    errorMsg);
                return(false);
            }
            return(true);
        }
コード例 #7
0
ファイル: GameMain.cs プロジェクト: sylvinite/Barotrauma
        public GameMain()
        {
            Instance = this;

            World = new World(new Vector2(0, -9.82f));
            FarseerPhysics.Settings.AllowSleep         = true;
            FarseerPhysics.Settings.ContinuousPhysics  = false;
            FarseerPhysics.Settings.VelocityIterations = 1;
            FarseerPhysics.Settings.PositionIterations = 1;

            Config = new GameSettings("config.xml");
            if (Config.WasGameUpdated)
            {
                UpdaterUtil.CleanOldFiles();
                Config.WasGameUpdated = false;
                Config.Save("config.xml");
            }

            if (GameSettings.SendUserStatistics)
            {
                GameAnalyticsManager.Init();
            }

            GameScreen = new GameScreen();
        }
コード例 #8
0
        public override void Select()
        {
            base.Select();

            if (GameMain.Client != null)
            {
                GameMain.Client.Disconnect();
                GameMain.Client = null;
            }

            Submarine.Unload();

            ResetButtonStates(null);

            GameAnalyticsManager.SetCustomDimension01("");

            #if OSX
            // Hack for adjusting the viewport properly after splash screens on older Macs
            if (firstLoadOnMac)
            {
                firstLoadOnMac = false;

                menuTabs[(int)Tab.Empty] = new GUIFrame(new RectTransform(new Vector2(1f, 1f), GUI.Canvas), "", Color.Transparent)
                {
                    CanBeFocused = false
                };
                var emptyList = new GUIListBox(new RectTransform(new Vector2(0.0f, 0.0f), menuTabs[(int)Tab.Empty].RectTransform))
                {
                    CanBeFocused = false
                };

                SelectTab(null, Tab.Empty);
            }
            #endif
        }
コード例 #9
0
        public void EndRound(string endMessage)
        {
            if (Mission != null)
            {
                Mission.End();
            }

            GameAnalyticsManager.AddProgressionEvent(
                (Mission == null || Mission.Completed) ? GameAnalyticsSDK.Net.EGAProgressionStatus.Complete : GameAnalyticsSDK.Net.EGAProgressionStatus.Fail,
                GameMode.Name,
                (Mission == null ? "None" : Mission.GetType().ToString()));

#if CLIENT
            if (roundSummary != null)
            {
                GUIFrame summaryFrame = roundSummary.CreateSummaryFrame(endMessage);
                GUIMessageBox.MessageBoxes.Add(summaryFrame);
                var okButton = new GUIButton(new Rectangle(0, 20, 100, 30), "Ok", Alignment.BottomRight, "", summaryFrame.children[0]);
                okButton.OnClicked = (GUIButton button, object obj) => { GUIMessageBox.MessageBoxes.Remove(summaryFrame); return(true); };
            }
#endif

            EventManager.EndRound();

            currentMission = null;

            StatusEffect.StopAll();
        }
コード例 #10
0
ファイル: Item.cs プロジェクト: parhelia512/Barotrauma
        public void CreateServerEvent <T>(T ic, object[] extraData) where T : ItemComponent, IServerSerializable
        {
            if (GameMain.Server == null)
            {
                return;
            }

            if (!ItemList.Contains(this))
            {
                string errorMsg = "Attempted to create a network event for an item (" + Name + ") that hasn't been fully initialized yet.\n" + Environment.StackTrace.CleanupStackTrace();
                DebugConsole.ThrowError(errorMsg);
                GameAnalyticsManager.AddErrorEventOnce("Item.CreateServerEvent:EventForUninitializedItem" + Name + ID, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                return;
            }

            int index = components.IndexOf(ic);

            if (index == -1)
            {
                return;
            }

            object[] data = new object[] { NetEntityEvent.Type.ComponentState, index }.Concat(extraData).ToArray();
            GameMain.Server.CreateEntityEvent(this, data);
        }
コード例 #11
0
        public static Color GradientLerp(float t, params Color[] gradient)
        {
            if (!MathUtils.IsValid(t))
            {
                return(Color.Purple);
            }
            System.Diagnostics.Debug.Assert(gradient.Length > 0, "Empty color array passed to the GradientLerp method");
            if (gradient.Length == 0)
            {
#if DEBUG
                DebugConsole.ThrowError("Empty color array passed to the GradientLerp method.\n" + Environment.StackTrace.CleanupStackTrace());
#endif
                GameAnalyticsManager.AddErrorEventOnce("ToolBox.GradientLerp:EmptyColorArray", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                                                       "Empty color array passed to the GradientLerp method.\n" + Environment.StackTrace.CleanupStackTrace());
                return(Color.Black);
            }

            if (t <= 0.0f || !MathUtils.IsValid(t))
            {
                return(gradient[0]);
            }
            if (t >= 1.0f)
            {
                return(gradient[gradient.Length - 1]);
            }

            float scaledT = t * (gradient.Length - 1);

            return(Color.Lerp(gradient[(int)scaledT], gradient[(int)Math.Min(scaledT + 1, gradient.Length - 1)], (scaledT - (int)scaledT)));
        }
コード例 #12
0
ファイル: TextManager.cs プロジェクト: yweber/Barotrauma
        public static string GetFormatted(string textTag, bool returnNull = false, params object[] args)
        {
            string text = Get(textTag, returnNull);

            if (text == null || text.Length == 0)
            {
                if (returnNull)
                {
                    return(null);
                }
                else
                {
                    DebugConsole.ThrowError("Text \"" + textTag + "\" not found.");
                    return(textTag);
                }
            }

            try
            {
                return(string.Format(text, args));
            }
            catch (FormatException)
            {
                string errorMsg = "Failed to format text \"" + text + "\", args: " + string.Join(", ", args);
                GameAnalyticsManager.AddErrorEventOnce("TextManager.GetFormatted:FormatException", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                return(text);
            }
        }
コード例 #13
0
        /// <summary>
        /// Removes the entity from the entity dictionary and frees up the ID it was using.
        /// </summary>
        public void FreeID()
        {
            DebugConsole.Log("Removing entity " + ToString() + " (" + ID + ") from entity dictionary.");
            if (!dictionary.TryGetValue(ID, out Entity existingEntity))
            {
                DebugConsole.Log("Entity " + ToString() + " (" + ID + ") not present in entity dictionary.");
                GameAnalyticsManager.AddErrorEventOnce(
                    "Entity.FreeID:EntityNotFound" + ID,
                    GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                    "Entity " + ToString() + " (" + ID + ") not present in entity dictionary.\n" + Environment.StackTrace);
            }
            else if (existingEntity != this)
            {
                DebugConsole.Log("Entity ID mismatch in entity dictionary. Entity " + existingEntity + " had the ID " + ID + " (expecting " + ToString() + ")");
                GameAnalyticsManager.AddErrorEventOnce("Entity.FreeID:EntityMismatch" + ID,
                                                       GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                                                       "Entity ID mismatch in entity dictionary. Entity " + existingEntity + " had the ID " + ID + " (expecting " + ToString() + ")");

                foreach (var keyValuePair in dictionary.Where(kvp => kvp.Value == this).ToList())
                {
                    dictionary.Remove(keyValuePair.Key);
                }
            }

            dictionary.Remove(ID);
            idFreed = true;
        }
コード例 #14
0
        public GameMain(string[] args)
        {
            Instance = this;

            CommandLineArgs = args;

            World = new World(new Vector2(0, -9.82f));
            FarseerPhysics.Settings.AllowSleep         = true;
            FarseerPhysics.Settings.ContinuousPhysics  = false;
            FarseerPhysics.Settings.VelocityIterations = 1;
            FarseerPhysics.Settings.PositionIterations = 1;

            Console.WriteLine("Loading game settings");
            Config = new GameSettings();

            Console.WriteLine("Loading MD5 hash cache");
            Md5Hash.LoadCache();

            Console.WriteLine("Initializing SteamManager");
            SteamManager.Initialize();
            Console.WriteLine("Initializing GameAnalytics");
            if (GameSettings.SendUserStatistics)
            {
                GameAnalyticsManager.Init();
            }

            Console.WriteLine("Initializing GameScreen");
            GameScreen = new GameScreen();
        }
コード例 #15
0
        private IEnumerable <object> CreateAIHusk()
        {
            character.Enabled = false;
            Entity.Spawner.AddToRemoveQueue(character);

            string          huskedSpeciesName = GetHuskedSpeciesName(character.SpeciesName, Prefab as AfflictionPrefabHusk);
            CharacterPrefab prefab            = CharacterPrefab.FindBySpeciesName(huskedSpeciesName);

            if (prefab == null)
            {
                DebugConsole.ThrowError("Failed to turn character \"" + character.Name + "\" into a husk - husk config file not found.");
                yield return(CoroutineStatus.Success);
            }
            var husk = Character.Create(huskedSpeciesName, character.WorldPosition, ToolBox.RandomSeed(8), character.Info, isRemotePlayer: false, hasAi: true);

            foreach (Limb limb in husk.AnimController.Limbs)
            {
                if (limb.type == LimbType.None)
                {
                    limb.body.SetTransform(character.SimPosition, 0.0f);
                    continue;
                }

                var matchingLimb = character.AnimController.GetLimb(limb.type);
                if (matchingLimb?.body != null)
                {
                    limb.body.SetTransform(matchingLimb.SimPosition, matchingLimb.Rotation);
                    limb.body.LinearVelocity  = matchingLimb.LinearVelocity;
                    limb.body.AngularVelocity = matchingLimb.body.AngularVelocity;
                }
            }

            if (character.Inventory != null && husk.Inventory != null)
            {
                if (character.Inventory.Items.Length != husk.Inventory.Items.Length)
                {
                    string errorMsg = "Failed to move items from the source character's inventory into a husk's inventory (inventory sizes don't match)";
                    DebugConsole.ThrowError(errorMsg);
                    GameAnalyticsManager.AddErrorEventOnce("AfflictionHusk.CreateAIHusk:InventoryMismatch", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                    yield return(CoroutineStatus.Success);
                }
                for (int i = 0; i < character.Inventory.Items.Length && i < husk.Inventory.Items.Length; i++)
                {
                    if (character.Inventory.Items[i] == null)
                    {
                        continue;
                    }
                    husk.Inventory.TryPutItem(character.Inventory.Items[i], i, true, false, null);
                }
            }

            husk.SetStun(5);
            yield return(new WaitForSeconds(5, false));

#if CLIENT
            husk.PlaySound(CharacterSound.SoundType.Idle);
#endif
            yield return(CoroutineStatus.Success);
        }
コード例 #16
0
        private void ReadStatus(IReadMessage msg)
        {
            bool isDead = msg.ReadBoolean();

            if (isDead)
            {
                CauseOfDeathType causeOfDeathType       = (CauseOfDeathType)msg.ReadRangedInteger(0, Enum.GetValues(typeof(CauseOfDeathType)).Length - 1);
                AfflictionPrefab causeOfDeathAffliction = null;
                if (causeOfDeathType == CauseOfDeathType.Affliction)
                {
                    string afflictionName = msg.ReadString();
                    if (!AfflictionPrefab.Prefabs.ContainsKey(afflictionName))
                    {
                        string errorMsg = $"Error in CharacterNetworking.ReadStatus: affliction not found ({afflictionName})";
                        causeOfDeathType = CauseOfDeathType.Unknown;
                        GameAnalyticsManager.AddErrorEventOnce("CharacterNetworking.ReadStatus:AfflictionIndexOutOfBounts", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                    }
                    else
                    {
                        causeOfDeathAffliction = AfflictionPrefab.Prefabs[afflictionName];
                    }
                }

                byte severedLimbCount = msg.ReadByte();
                if (!IsDead)
                {
                    if (causeOfDeathType == CauseOfDeathType.Pressure)
                    {
                        Implode(true);
                    }
                    else
                    {
                        Kill(causeOfDeathType, causeOfDeathAffliction?.Instantiate(1.0f), true);
                    }
                }

                for (int i = 0; i < severedLimbCount; i++)
                {
                    int severedJointIndex = msg.ReadByte();
                    if (severedJointIndex < 0 || severedJointIndex >= AnimController.LimbJoints.Length)
                    {
                        string errorMsg = $"Error in CharacterNetworking.ReadStatus: severed joint index out of bounds (index: {severedJointIndex}, joint count: {AnimController.LimbJoints.Length})";
                        GameAnalyticsManager.AddErrorEventOnce("CharacterNetworking.ReadStatus:JointIndexOutOfBounts", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                    }
                    else
                    {
                        AnimController.SeverLimbJoint(AnimController.LimbJoints[severedJointIndex]);
                    }
                }
            }
            else
            {
                if (IsDead)
                {
                    Revive();
                }
                CharacterHealth.ClientRead(msg);
            }
        }
コード例 #17
0
        void UpdateDying(float deltaTime)
        {
            if (deathAnimDuration <= 0.0f)
            {
                return;
            }

            float animStrength = (1.0f - deathAnimTimer / deathAnimDuration);

            Limb head = GetLimb(LimbType.Head);
            Limb tail = GetLimb(LimbType.Tail);

            if (head != null && !head.IsSevered)
            {
                head.body.ApplyTorque((float)(Math.Sqrt(head.Mass) * Dir * Math.Sin(WalkPos)) * 30.0f * animStrength);
            }
            if (tail != null && !tail.IsSevered)
            {
                tail.body.ApplyTorque((float)(Math.Sqrt(tail.Mass) * -Dir * Math.Sin(WalkPos)) * 30.0f * animStrength);
            }

            WalkPos += deltaTime * 10.0f * animStrength;

            Vector2 centerOfMass = GetCenterOfMass();

            foreach (Limb limb in Limbs)
            {
#if CLIENT
                if (limb.LightSource != null)
                {
                    limb.LightSource.Color = Color.Lerp(limb.InitialLightSourceColor, Color.TransparentBlack, deathAnimTimer / deathAnimDuration);
                }
#endif
                if (limb.type == LimbType.Head || limb.type == LimbType.Tail || limb.IsSevered || !limb.body.Enabled)
                {
                    continue;
                }
                if (limb.Mass <= 0.0f)
                {
                    string errorMsg = "Creature death animation error: invalid limb mass on character \"" + character.SpeciesName + "\" (type: " + limb.type + ", mass: " + limb.Mass + ")";
                    DebugConsole.ThrowError(errorMsg);
                    GameAnalyticsManager.AddErrorEventOnce("FishAnimController.UpdateDying:InvalidMass" + character.ID, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                    deathAnimTimer = deathAnimDuration;
                    return;
                }

                Vector2 diff = (centerOfMass - limb.SimPosition);
                if (!MathUtils.IsValid(diff))
                {
                    string errorMsg = "Creature death animation error: invalid diff (center of mass: " + centerOfMass + ", limb position: " + limb.SimPosition + ")";
                    DebugConsole.ThrowError(errorMsg);
                    GameAnalyticsManager.AddErrorEventOnce("FishAnimController.UpdateDying:InvalidDiff" + character.ID, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                    deathAnimTimer = deathAnimDuration;
                    return;
                }

                limb.body.ApplyForce(diff * (float)(Math.Sin(WalkPos) * Math.Sqrt(limb.Mass)) * 30.0f * animStrength);
            }
        }
コード例 #18
0
        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", "");
            }

            if (string.IsNullOrEmpty(filename))
            {
                string errorMsg = "Error when loading round sound (" + element + ") - file path not set";
                DebugConsole.ThrowError(errorMsg);
                GameAnalyticsManager.AddErrorEventOnce("Submarine.LoadRoundSound:FilePathEmpty" + element.ToString(), GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg + "\n" + Environment.StackTrace);
                return(null);
            }

            filename = Path.GetFullPath(filename.CleanUpPath()).CleanUpPath();
            Sound existingSound = null;

            if (roundSounds == null)
            {
                roundSounds = new List <RoundSound>();
            }
            else
            {
                existingSound = roundSounds.Find(s => s.Filename == filename && s.Stream == stream)?.Sound;
            }

            if (existingSound == null)
            {
                try
                {
                    existingSound = GameMain.SoundManager.LoadSound(filename, stream);
                    if (existingSound == null)
                    {
                        return(null);
                    }
                }
                catch (System.IO.FileNotFoundException e)
                {
                    string errorMsg = "Failed to load sound file \"" + filename + "\".";
                    DebugConsole.ThrowError(errorMsg, e);
                    GameAnalyticsManager.AddErrorEventOnce("Submarine.LoadRoundSound:FileNotFound" + filename, GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg + "\n" + Environment.StackTrace);
                    return(null);
                }
            }

            RoundSound newSound = new RoundSound(element, existingSound);

            roundSounds.Add(newSound);
            return(newSound);
        }
コード例 #19
0
ファイル: PhysicsBody.cs プロジェクト: yweber/Barotrauma
        public PosInfo ClientRead(ServerNetObject type, IReadMessage msg, float sendingTime, string parentDebugName)
        {
            float MaxVel        = NetConfig.MaxPhysicsBodyVelocity;
            float MaxAngularVel = NetConfig.MaxPhysicsBodyAngularVelocity;

            Vector2 newPosition        = SimPosition;
            float?  newRotation        = null;
            bool    awake              = FarseerBody.Awake;
            Vector2 newVelocity        = LinearVelocity;
            float?  newAngularVelocity = null;

            newPosition = new Vector2(
                msg.ReadSingle(),
                msg.ReadSingle());

            awake = msg.ReadBoolean();
            bool fixedRotation = msg.ReadBoolean();

            if (!fixedRotation)
            {
                newRotation = msg.ReadRangedSingle(0.0f, MathHelper.TwoPi, 8);
            }
            if (awake)
            {
                newVelocity = new Vector2(
                    msg.ReadRangedSingle(-MaxVel, MaxVel, 12),
                    msg.ReadRangedSingle(-MaxVel, MaxVel, 12));
                newVelocity = NetConfig.Quantize(newVelocity, -MaxVel, MaxVel, 12);

                if (!fixedRotation)
                {
                    newAngularVelocity = msg.ReadRangedSingle(-MaxAngularVel, MaxAngularVel, 8);
                    newAngularVelocity = NetConfig.Quantize(newAngularVelocity.Value, -MaxAngularVel, MaxAngularVel, 8);
                }
            }
            msg.ReadPadBits();

            if (!MathUtils.IsValid(newPosition) ||
                !MathUtils.IsValid(newVelocity) ||
                (newRotation.HasValue && !MathUtils.IsValid(newRotation.Value)) ||
                (newAngularVelocity.HasValue && !MathUtils.IsValid(newAngularVelocity.Value)))
            {
                string errorMsg = "Received invalid position data for \"" + parentDebugName
                                  + "\" (position: " + newPosition + ", rotation: " + (newRotation ?? 0) + ", velocity: " + newVelocity + ", angular velocity: " + (newAngularVelocity ?? 0) + ")";
#if DEBUG
                DebugConsole.ThrowError(errorMsg);
#endif
                GameAnalyticsManager.AddErrorEventOnce("PhysicsBody.ClientRead:InvalidData" + parentDebugName,
                                                       GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                                                       errorMsg);
                return(null);
            }

            return(lastProcessedNetworkState > sendingTime ?
                   null :
                   new PosInfo(newPosition, newRotation, newVelocity, newAngularVelocity, sendingTime));
        }
コード例 #20
0
        public virtual bool TryPutItem(Item item, int i, bool allowSwapping, bool allowCombine, Character user, bool createNetworkEvent = true)
        {
            if (i < 0 || i >= slots.Length)
            {
                string errorMsg = "Inventory.TryPutItem failed: index was out of range(" + i + ").\n" + Environment.StackTrace.CleanupStackTrace();
                GameAnalyticsManager.AddErrorEventOnce("Inventory.TryPutItem:IndexOutOfRange", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                return(false);
            }

            if (Owner == null)
            {
                return(false);
            }
            //there's already an item in the slot
            if (slots[i].Any() && allowCombine)
            {
                if (slots[i].First().Combine(item, user))
                {
                    //item in the slot removed as a result of combining -> put this item in the now free slot
                    if (!slots[i].Any())
                    {
                        return(TryPutItem(item, i, allowSwapping, allowCombine, user, createNetworkEvent));
                    }
                    return(true);
                }
            }
            if (CanBePut(item, i))
            {
                PutItem(item, i, user, true, createNetworkEvent);
                return(true);
            }
            else if (slots[i].Any() && item.ParentInventory != null && allowSwapping)
            {
                var itemInSlot = slots[i].First();
                if (itemInSlot.OwnInventory != null &&
                    !itemInSlot.OwnInventory.Contains(item) &&
                    (itemInSlot.GetComponent <ItemContainer>()?.MaxStackSize ?? 0) == 1 &&
                    itemInSlot.OwnInventory.TrySwapping(0, item, user, createNetworkEvent, swapWholeStack: false))
                {
                    return(true);
                }
                return
                    (TrySwapping(i, item, user, createNetworkEvent, swapWholeStack: true) ||
                     TrySwapping(i, item, user, createNetworkEvent, swapWholeStack: false));
            }
            else
            {
#if CLIENT
                if (visualSlots != null && createNetworkEvent)
                {
                    visualSlots[i].ShowBorderHighlight(GUI.Style.Red, 0.1f, 0.9f);
                }
#endif
                return(false);
            }
        }
コード例 #21
0
        public void PingServer(ServerInfo serverInfo, int timeOut)
        {
            if (string.IsNullOrWhiteSpace(serverInfo?.IP))
            {
                serverInfo.PingChecked = true;
                serverInfo.Ping        = -1;
                return;
            }

            long      rtt     = -1;
            IPAddress address = null;

            IPAddress.TryParse(serverInfo.IP, out address);
            if (address != null)
            {
                //don't attempt to ping if the address is IPv6 and it's not supported
                if (address.AddressFamily != AddressFamily.InterNetworkV6 || Socket.OSSupportsIPv6)
                {
                    Ping   ping   = new Ping();
                    byte[] buffer = new byte[32];
                    try
                    {
                        PingReply pingReply = ping.Send(address, timeOut, buffer, new PingOptions(128, true));

                        if (pingReply != null)
                        {
                            switch (pingReply.Status)
                            {
                            case IPStatus.Success:
                                rtt = pingReply.RoundtripTime;
                                break;

                            default:
                                rtt = -1;
                                break;
                            }
                        }
                    }
                    catch (PingException ex)
                    {
                        string errorMsg = "Failed to ping a server (" + serverInfo.ServerName + ", " + serverInfo.IP + ") - " + (ex?.InnerException?.Message ?? ex.Message);
                        GameAnalyticsManager.AddErrorEventOnce("ServerListScreen.PingServer:PingException" + serverInfo.IP, GameAnalyticsSDK.Net.EGAErrorSeverity.Warning, errorMsg);
#if DEBUG
                        DebugConsole.NewMessage(errorMsg, Color.Red);
#endif
                    }
                }
            }

            serverInfo.PingChecked = true;
            serverInfo.Ping        = (int)rtt;
        }
コード例 #22
0
        private IEnumerable <object> CreateAIHusk(Character character)
        {
            character.Enabled = false;
            Entity.Spawner.AddToRemoveQueue(character);

            string speciesName = GetHuskedSpeciesName(character.SpeciesName, Prefab as AfflictionPrefabHusk);
            string configFile  = Character.GetConfigFilePath(speciesName);

            if (string.IsNullOrEmpty(configFile))
            {
                DebugConsole.ThrowError("Failed to turn character \"" + character.Name + "\" into a husk - husk config file not found.");
                yield return(CoroutineStatus.Success);
            }

            var husk = Character.Create(configFile, character.WorldPosition, character.Info.Name, character.Info, isRemotePlayer: false, hasAi: true, ragdoll: character.AnimController.RagdollParams);

            foreach (Limb limb in husk.AnimController.Limbs)
            {
                if (limb.type == LimbType.None)
                {
                    limb.body.SetTransform(character.SimPosition, 0.0f);
                    continue;
                }

                var matchingLimb = character.AnimController.GetLimb(limb.type);
                if (matchingLimb?.body != null)
                {
                    limb.body.SetTransform(matchingLimb.SimPosition, matchingLimb.Rotation);
                    limb.body.LinearVelocity  = matchingLimb.LinearVelocity;
                    limb.body.AngularVelocity = matchingLimb.body.AngularVelocity;
                }
            }

            if (character.Inventory.Items.Length != husk.Inventory.Items.Length)
            {
                string errorMsg = "Failed to move items from the source character's inventory into a husk's inventory (inventory sizes don't match)";
                DebugConsole.ThrowError(errorMsg);
                GameAnalyticsManager.AddErrorEventOnce("AfflictionHusk.CreateAIHusk:InventoryMismatch", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                yield return(CoroutineStatus.Success);
            }

            for (int i = 0; i < character.Inventory.Items.Length && i < husk.Inventory.Items.Length; i++)
            {
                if (character.Inventory.Items[i] == null)
                {
                    continue;
                }
                husk.Inventory.TryPutItem(character.Inventory.Items[i], i, true, false, null);
            }

            yield return(CoroutineStatus.Success);
        }
コード例 #23
0
 public AIObjectiveRescue(Character character, Character targetCharacter, AIObjectiveManager objectiveManager, float priorityModifier = 1)
     : base(character, objectiveManager, priorityModifier)
 {
     if (targetCharacter == null)
     {
         string errorMsg = $"{character.Name}: Attempted to create a Rescue objective with no target!\n" + Environment.StackTrace.CleanupStackTrace();
         DebugConsole.ThrowError(errorMsg);
         GameAnalyticsManager.AddErrorEventOnce("AIObjectiveRescue:ctor:targetnull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
         Abandon = true;
         return;
     }
     this.targetCharacter = targetCharacter;
 }
コード例 #24
0
        private static void UpdateWaterAmbience(float ambienceVolume)
        {
            //how fast the sub is moving, scaled to 0.0 -> 1.0
            float movementSoundVolume = 0.0f;

            foreach (Submarine sub in Submarine.Loaded)
            {
                float movementFactor = (sub.Velocity == Vector2.Zero) ? 0.0f : sub.Velocity.Length() / 10.0f;
                movementFactor = MathHelper.Clamp(movementFactor, 0.0f, 1.0f);

                if (Character.Controlled == null || Character.Controlled.Submarine != sub)
                {
                    float dist = Vector2.Distance(GameMain.GameScreen.Cam.WorldViewCenter, sub.WorldPosition);
                    movementFactor = movementFactor / Math.Max(dist / 1000.0f, 1.0f);
                }

                movementSoundVolume = Math.Max(movementSoundVolume, movementFactor);
                if (!MathUtils.IsValid(movementSoundVolume))
                {
                    string errorMsg = "Failed to update water ambience volume - submarine's movement value invalid (" + movementSoundVolume + ", sub velocity: " + sub.Velocity + ")";
                    DebugConsole.Log(errorMsg);
                    GameAnalyticsManager.AddErrorEventOnce("SoundPlayer.UpdateWaterAmbience:InvalidVolume", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                    movementSoundVolume = 0.0f;
                }
            }

            if (waterAmbiences.Count > 1)
            {
                if (waterAmbienceChannels[0] == null || !waterAmbienceChannels[0].IsPlaying)
                {
                    waterAmbienceChannels[0] = waterAmbiences[0].Play(ambienceVolume * (1.0f - movementSoundVolume), "waterambience");
                    //waterAmbiences[0].Loop(waterAmbienceIndexes[0], ambienceVolume * (1.0f - movementSoundVolume));
                    waterAmbienceChannels[0].Looping = true;
                }
                else
                {
                    waterAmbienceChannels[0].Gain = ambienceVolume * (1.0f - movementSoundVolume);
                }

                if (waterAmbienceChannels[1] == null || !waterAmbienceChannels[1].IsPlaying)
                {
                    waterAmbienceChannels[1] = waterAmbiences[1].Play(ambienceVolume * movementSoundVolume, "waterambience");
                    //waterAmbienceIndexes[1] = waterAmbiences[1].Loop(waterAmbienceIndexes[1], ambienceVolume * movementSoundVolume);
                    waterAmbienceChannels[1].Looping = true;
                }
                else
                {
                    waterAmbienceChannels[1].Gain = ambienceVolume * movementSoundVolume;
                }
            }
        }
コード例 #25
0
        private void StartGame(Submarine selectedSub, string saveName, string mapSeed)
        {
            if (string.IsNullOrEmpty(saveName))
            {
                return;
            }

            string[] existingSaveFiles = SaveUtil.GetSaveFiles(SaveUtil.SaveType.Singleplayer);

            if (Array.Find(existingSaveFiles, s => s == saveName) != null)
            {
                new GUIMessageBox("Save name already in use", "Please choose another name for the save file");
                return;
            }

            if (selectedSub == null)
            {
                new GUIMessageBox(TextManager.Get("SubNotSelected"), TextManager.Get("SelectSubRequest"));
                return;
            }

            if (!Directory.Exists(SaveUtil.TempPath))
            {
                Directory.CreateDirectory(SaveUtil.TempPath);
            }

            try
            {
                File.Copy(selectedSub.FilePath, Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"), true);
            }
            catch (IOException e)
            {
                DebugConsole.ThrowError("Copying the file \"" + selectedSub.FilePath + "\" failed. The file may have been deleted or in use by another process. Try again or select another submarine.", e);
                GameAnalyticsManager.AddErrorEventOnce(
                    "MainMenuScreen.StartGame:IOException" + selectedSub.Name,
                    GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                    "Copying the file \"" + selectedSub.FilePath + "\" failed.\n" + e.Message + "\n" + Environment.StackTrace);
                return;
            }

            selectedSub = new Submarine(Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"), "");

            GameMain.GameSession = new GameSession(selectedSub, saveName, GameModePreset.list.Find(gm => gm.Name == "Single Player"));
            (GameMain.GameSession.GameMode as CampaignMode).GenerateMap(mapSeed);

            GameSession.inGameInfo.Initialize();

            GameMain.NilMod.GameInitialize(true);

            GameMain.LobbyScreen.Select();
        }
コード例 #26
0
        public void SelectLocation(Location location)
        {
            if (!Locations.Contains(location))
            {
                string errorMsg = "Failed to select a location. " + (location?.Name ?? "null") + " not found in the map.";
                DebugConsole.ThrowError(errorMsg);
                GameAnalyticsManager.AddErrorEventOnce("Map.SelectLocation:LocationNotFound", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                return;
            }

            SelectedLocation   = location;
            SelectedConnection = connections.Find(c => c.Locations.Contains(CurrentLocation) && c.Locations.Contains(SelectedLocation));
            OnLocationSelected?.Invoke(SelectedLocation, SelectedConnection);
        }
コード例 #27
0
        protected virtual void PutItem(Item item, int i, Character user, bool removeItem = true, bool createNetworkEvent = true)
        {
            if (i < 0 || i >= Items.Length)
            {
                string errorMsg = "Inventory.PutItem failed: index was out of range(" + i + ").\n" + Environment.StackTrace;
                GameAnalyticsManager.AddErrorEventOnce("Inventory.PutItem:IndexOutOfRange", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
                return;
            }

            if (Owner == null)
            {
                return;
            }

            Inventory prevInventory = item.ParentInventory;

            if (createNetworkEvent)
            {
                CreateNetworkEvent();
                //also delay syncing the inventory the item was inside
                if (prevInventory != null && prevInventory != this)
                {
                    prevInventory.syncItemsDelay = 1.0f;
                }
            }

            if (removeItem)
            {
                item.Drop(user);
                if (item.ParentInventory != null)
                {
                    item.ParentInventory.RemoveItem(item);
                }
            }

            Items[i]             = item;
            item.ParentInventory = this;

#if CLIENT
            if (slots != null)
            {
                slots[i].ShowBorderHighlight(Color.White, 0.1f, 0.4f);
            }
#endif

            if (item.body != null)
            {
                item.body.Enabled = false;
            }
        }
コード例 #28
0
        private void FetchRemoteContent(RectTransform parent)
        {
            if (string.IsNullOrEmpty(GameMain.Config.RemoteContentUrl))
            {
                return;
            }
            try
            {
                var client  = new RestClient(GameMain.Config.RemoteContentUrl);
                var request = new RestRequest("MenuContent.xml", Method.GET);

                IRestResponse response = client.Execute(request);
                if (response.ResponseStatus != ResponseStatus.Completed)
                {
                    return;
                }
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return;
                }

                string xml   = response.Content;
                int    index = xml.IndexOf('<');
                if (index > 0)
                {
                    xml = xml.Substring(index, xml.Length - index);
                }
                if (string.IsNullOrWhiteSpace(xml))
                {
                    return;
                }

                XElement element = XDocument.Parse(xml)?.Root;
                foreach (XElement subElement in element.Elements())
                {
                    GUIComponent.FromXML(subElement, parent);
                }
            }

            catch (Exception e)
            {
#if DEBUG
                DebugConsole.ThrowError("Fetching remote content to the main menu failed.", e);
#endif
                GameAnalyticsManager.AddErrorEventOnce("MainMenuScreen.FetchRemoteContent:Exception", GameAnalyticsSDK.Net.EGAErrorSeverity.Error,
                                                       "Fetching remote content to the main menu failed. " + e.Message);
                return;
            }
        }
コード例 #29
0
 public void AddToSpawnQueue(string speciesName, Vector2 position, Submarine sub, Action <Character> onSpawn = null)
 {
     if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
     {
         return;
     }
     if (string.IsNullOrEmpty(speciesName))
     {
         string errorMsg = "Attempted to add an empty/null species name to entity spawn queue.\n" + Environment.StackTrace;
         DebugConsole.ThrowError(errorMsg);
         GameAnalyticsManager.AddErrorEventOnce("EntitySpawner.AddToSpawnQueue5:SpeciesNameNullOrEmpty", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
         return;
     }
     spawnQueue.Enqueue(new CharacterSpawnInfo(speciesName, position, sub, onSpawn));
 }
コード例 #30
0
 public void AddToSpawnQueue(ItemPrefab itemPrefab, Inventory inventory, float?condition = null)
 {
     if (GameMain.NetworkMember != null && GameMain.NetworkMember.IsClient)
     {
         return;
     }
     if (itemPrefab == null)
     {
         string errorMsg = "Attempted to add a null item to entity spawn queue.\n" + Environment.StackTrace;
         DebugConsole.ThrowError(errorMsg);
         GameAnalyticsManager.AddErrorEventOnce("EntitySpawner.AddToSpawnQueue3:ItemPrefabNull", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg);
         return;
     }
     spawnQueue.Enqueue(new ItemSpawnInfo(itemPrefab, inventory, condition));
 }