Exemplo n.º 1
0
        private bool CreateTestSetupMenu()
        {
            var msgBox = new GUIMessageBox(TextManager.Get("EventEditor.TestPromptHeader"), "", new[] { TextManager.Get("Cancel"), TextManager.Get("OK") },
                                           relativeSize: new Vector2(0.2f, 0.3f), minSize: new Point(300, 175));

            var layout = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.5f), msgBox.Content.RectTransform));

            new GUITextBlock(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), TextManager.Get("EventEditor.OutpostGenParams"), font: GUI.SubHeadingFont);
            GUIDropDown paramInput = new GUIDropDown(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), string.Empty, OutpostGenerationParams.Params.Count);

            foreach (OutpostGenerationParams param in OutpostGenerationParams.Params)
            {
                paramInput.AddItem(param.Identifier, param);
            }
            paramInput.OnSelected = (_, param) =>
            {
                lastTestParam = param as OutpostGenerationParams;
                return(true);
            };
            paramInput.SelectItem(lastTestParam ?? OutpostGenerationParams.Params.FirstOrDefault());

            new GUITextBlock(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), TextManager.Get("EventEditor.LocationType"), font: GUI.SubHeadingFont);
            GUIDropDown typeInput = new GUIDropDown(new RectTransform(new Vector2(1, 0.25f), layout.RectTransform), string.Empty, LocationType.List.Count);

            foreach (LocationType type in LocationType.List)
            {
                typeInput.AddItem(type.Identifier, type);
            }
            typeInput.OnSelected = (_, type) =>
            {
                lastTestType = type as LocationType;
                return(true);
            };
            typeInput.SelectItem(lastTestType ?? LocationType.List.FirstOrDefault());

            // Cancel button
            msgBox.Buttons[0].OnClicked = (button, o) =>
            {
                msgBox.Close();
                return(true);
            };

            // Ok button
            msgBox.Buttons[1].OnClicked = (button, o) =>
            {
                TestEvent(lastTestParam, lastTestType);
                msgBox.Close();
                return(true);
            };

            return(true);
        }
Exemplo n.º 2
0
        public void ShowBugReporter()
        {
            if (GUIMessageBox.VisibleBox != null && GUIMessageBox.VisibleBox.UserData as string == "bugreporter")
            {
                return;
            }

            var msgBox = new GUIMessageBox(TextManager.Get("bugreportbutton"), "");

            msgBox.UserData = "bugreporter";
            var linkHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), msgBox.Content.RectTransform))
            {
                Stretch = true, RelativeSpacing = 0.025f
            };

            linkHolder.RectTransform.MaxSize = new Point(int.MaxValue, linkHolder.Rect.Height);

#if !UNSTABLE
            new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), linkHolder.RectTransform), TextManager.Get("bugreportfeedbackform"), style: "MainMenuGUIButton", textAlignment: Alignment.Left)
            {
                UserData  = "https://steamcommunity.com/app/602960/discussions/1/",
                OnClicked = (btn, userdata) =>
                {
                    if (!SteamManager.OverlayCustomURL(userdata as string))
                    {
                        ShowOpenUrlInWebBrowserPrompt(userdata as string);
                    }
                    msgBox.Close();
                    return(true);
                }
            };
#endif

            new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), linkHolder.RectTransform), TextManager.Get("bugreportgithubform"), style: "MainMenuGUIButton", textAlignment: Alignment.Left)
            {
#if UNSTABLE
                UserData = "https://barotraumagame.com/unstable-3rf3w5t4ter/",
#else
                UserData = "https://github.com/Regalis11/Barotrauma/issues/new?template=bug_report.md",
#endif
                OnClicked = (btn, userdata) =>
                {
                    ShowOpenUrlInWebBrowserPrompt(userdata as string);
                    msgBox.Close();
                    return(true);
                }
            };

            msgBox.InnerFrame.RectTransform.MinSize = new Point(0,
                                                                msgBox.InnerFrame.Rect.Height + linkHolder.Rect.Height + msgBox.Content.AbsoluteSpacing * 2 + (int)(50 * GUI.Scale));
        }
Exemplo n.º 3
0
        private bool SaveProjectToFile(GUIButton button, object o)
        {
            string directory = Path.GetFullPath("EventProjects");

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            var        msgBox    = new GUIMessageBox(TextManager.Get("EventEditor.NameFilePrompt"), "", new[] { TextManager.Get("Cancel"), TextManager.Get("Save") }, new Vector2(0.2f, 0.175f), minSize: new Point(300, 175));
            var        layout    = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.25f), msgBox.Content.RectTransform), isHorizontal: true);
            GUITextBox nameInput = new GUITextBox(new RectTransform(Vector2.One, layout.RectTransform))
            {
                Text = projectName
            };

            // Cancel button
            msgBox.Buttons[0].OnClicked = delegate
            {
                msgBox.Close();
                return(true);
            };

            // Ok button
            msgBox.Buttons[1].OnClicked = delegate
            {
                foreach (var illegalChar in Path.GetInvalidFileNameChars())
                {
                    if (!nameInput.Text.Contains(illegalChar))
                    {
                        continue;
                    }

                    GUI.AddMessage(TextManager.GetWithVariable("SubNameIllegalCharsWarning", "[illegalchar]", illegalChar.ToString()), GUI.Style.Red);
                    return(false);
                }

                msgBox.Close();
                projectName = nameInput.Text;
                XElement save     = SaveEvent(projectName);
                string   filePath = System.IO.Path.Combine(directory, $"{projectName}.sevproj");
                File.WriteAllText(Path.Combine(directory, $"{projectName}.sevproj"), save.ToString());
                GUI.AddMessage($"Project saved to {filePath}", GUI.Style.Green);

                AskForConfirmation(TextManager.Get("EventEditor.TestPromptHeader"), TextManager.Get("EventEditor.TestPromptBody"), CreateTestSetupMenu);
                return(true);
            };
            return(true);
        }
Exemplo n.º 4
0
        // ToDo: Move texts/links to localization, when possible.
        public void ShowBugReporter()
        {
            var msgBox     = new GUIMessageBox("", "");
            var linkHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.5f), msgBox.Content.RectTransform))
            {
                Stretch = true, RelativeSpacing = 0.05f
            };

            List <Pair <string, string> > links = new List <Pair <string, string> >()
            {
                new Pair <string, string>("Barotrauma Feedback Form", "https://barotraumagame.com/feedback"),
                new Pair <string, string>("Github Issue Form (Needs account)", "https://github.com/Regalis11/Barotrauma/issues/new?template=bug_report.md")
            };

            foreach (var link in links)
            {
                new GUIButton(new RectTransform(new Vector2(1.0f, 0.2f), linkHolder.RectTransform), link.First, style: "MainMenuGUIButton", textAlignment: Alignment.Left)
                {
                    UserData  = link.Second,
                    OnClicked = (btn, userdata) =>
                    {
                        Process.Start(userdata as string);
                        msgBox.Close();
                        return(true);
                    }
                };
            }
        }
Exemplo n.º 5
0
        // ToDo: Move texts/links to localization, when possible.
        public void ShowBugReporter()
        {
            var msgBox = new GUIMessageBox(TextManager.Get("bugreportbutton"), "");

            msgBox.UserData = "bugreporter";
            var linkHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), msgBox.Content.RectTransform))
            {
                Stretch = true, RelativeSpacing = 0.025f
            };

            linkHolder.RectTransform.MaxSize = new Point(int.MaxValue, linkHolder.Rect.Height);

            List <Pair <string, string> > links = new List <Pair <string, string> >()
            {
                new Pair <string, string>(TextManager.Get("bugreportfeedbackform"), "https://barotraumagame.com/feedback"),
                new Pair <string, string>(TextManager.Get("bugreportgithubform"), "https://github.com/Regalis11/Barotrauma/issues/new?template=bug_report.md")
            };

            foreach (var link in links)
            {
                new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), linkHolder.RectTransform), link.First, style: "MainMenuGUIButton", textAlignment: Alignment.Left)
                {
                    UserData  = link.Second,
                    OnClicked = (btn, userdata) =>
                    {
                        Process.Start(userdata as string);
                        msgBox.Close();
                        return(true);
                    }
                };
            }

            msgBox.InnerFrame.RectTransform.MinSize = new Point(0,
                                                                msgBox.InnerFrame.Rect.Height + linkHolder.Rect.Height + msgBox.Content.AbsoluteSpacing * 2 + (int)(50 * GUI.Scale));
        }
Exemplo n.º 6
0
        public void ShowOpenUrlInWebBrowserPrompt(string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return;
            }
            if (GUIMessageBox.VisibleBox?.UserData as string == "verificationprompt")
            {
                return;
            }

            var msgBox = new GUIMessageBox("", TextManager.GetWithVariable("openlinkinbrowserprompt", "[link]", url),
                                           new string[] { TextManager.Get("Yes"), TextManager.Get("No") })
            {
                UserData = "verificationprompt"
            };

            msgBox.Buttons[0].OnClicked = (btn, userdata) =>
            {
                Process.Start(url);
                msgBox.Close();
                return(true);
            };
            msgBox.Buttons[1].OnClicked = msgBox.Close;
        }
Exemplo n.º 7
0
        private IEnumerable <object> WaitForCampaignSetup()
        {
            GUI.SetCursorWaiting();
            string headerText = TextManager.Get("CampaignStartingPleaseWait");
            var    msgBox     = new GUIMessageBox(headerText, TextManager.Get("CampaignStarting"), new string[] { TextManager.Get("Cancel") });

            msgBox.Buttons[0].OnClicked = (btn, userdata) =>
            {
                GameMain.NetLobbyScreen.HighlightMode(GameMain.NetLobbyScreen.SelectedModeIndex);
                GameMain.NetLobbyScreen.SelectMode(GameMain.NetLobbyScreen.SelectedModeIndex);
                GUI.ClearCursorWait();
                CoroutineManager.StopCoroutines("WaitForCampaignSetup");
                return(true);
            };
            msgBox.Buttons[0].OnClicked += msgBox.Close;

            DateTime timeOut = DateTime.Now + new TimeSpan(0, 0, 10);

            while (GameMain.NetLobbyScreen.CampaignUI == null && DateTime.Now < timeOut)
            {
                msgBox.Header.Text = headerText + new string('.', ((int)Timing.TotalTime % 3 + 1));
                yield return(CoroutineStatus.Running);
            }
            msgBox.Close();
            GUI.ClearCursorWait();
            yield return(CoroutineStatus.Success);
        }
Exemplo n.º 8
0
        private void NotifyPrompt(string header, string body)
        {
            GUIMessageBox msgBox = new GUIMessageBox(header, body, new[] { TextManager.Get("Ok") }, new Vector2(0.2f, 0.175f), minSize: new Point(300, 175));

            msgBox.Buttons[0].OnClicked = delegate
            {
                msgBox.Close();
                return(true);
            };
        }
Exemplo n.º 9
0
        public void CreatePreviewWindow(GUIMessageBox messageBox)
        {
            var background = new GUIButton(new RectTransform(Vector2.One, messageBox.RectTransform), style: "GUIBackgroundBlocker")
            {
                OnClicked = (btn, userdata) => { if (GUI.MouseOn == btn || GUI.MouseOn == btn.TextBlock)
                                                 {
                                                     messageBox.Close();
                                                 }
                                                 return(true); }
            };

            background.RectTransform.SetAsFirstChild();

            new GUITextBlock(new RectTransform(new Vector2(1, 0), messageBox.Content.RectTransform, Anchor.TopCenter), Name, textAlignment: Alignment.Center, font: GUI.LargeFont, wrap: true);

            var upperPart      = new GUIFrame(new RectTransform(new Vector2(1, 0.4f), messageBox.Content.RectTransform, Anchor.Center, Pivot.BottomCenter), color: Color.Transparent);
            var descriptionBox = new GUIListBox(new RectTransform(new Vector2(1, 0.35f), messageBox.Content.RectTransform, Anchor.Center, Pivot.TopCenter));

            if (PreviewImage == null)
            {
                new GUITextBlock(new RectTransform(new Vector2(0.45f, 1), upperPart.RectTransform), TextManager.Get("SubPreviewImageNotFound"));
            }
            else
            {
                new GUIImage(new RectTransform(new Vector2(0.45f, 1), upperPart.RectTransform), PreviewImage);
            }

            Vector2 realWorldDimensions = Dimensions * Physics.DisplayToRealWorldRatio;
            string  dimensionsStr       = realWorldDimensions == Vector2.Zero ?
                                          TextManager.Get("Unknown") :
                                          TextManager.Get("DimensionsFormat").Replace("[width]", ((int)(realWorldDimensions.X)).ToString()).Replace("[height]", ((int)(realWorldDimensions.Y)).ToString());

            var layoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(0.45f, 1), upperPart.RectTransform, Anchor.TopRight));

            new GUITextBlock(new RectTransform(new Vector2(1, 0), layoutGroup.RectTransform),
                             $"{TextManager.Get("Dimensions")}: {dimensionsStr}",
                             font: GUI.SmallFont, wrap: true);

            new GUITextBlock(new RectTransform(new Vector2(1, 0), layoutGroup.RectTransform),
                             $"{TextManager.Get("RecommendedCrewSize")}: {(RecommendedCrewSizeMax == 0 ? TextManager.Get("Unknown") : RecommendedCrewSizeMin + " - " + RecommendedCrewSizeMax)}",
                             font: GUI.SmallFont, wrap: true);

            new GUITextBlock(new RectTransform(new Vector2(1, 0), layoutGroup.RectTransform),
                             $"{TextManager.Get("RecommendedCrewExperience")}: {(string.IsNullOrEmpty(RecommendedCrewExperience) ? TextManager.Get("unknown") : TextManager.Get(RecommendedCrewExperience))}",
                             font: GUI.SmallFont, wrap: true);

            new GUITextBlock(new RectTransform(new Vector2(1, 0), layoutGroup.RectTransform),
                             $"{TextManager.Get("RequiredContentPackages")}: {string.Join(", ", RequiredContentPackages)}",
                             font: GUI.SmallFont, wrap: true);

            new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform, Anchor.TopLeft), Description, font: GUI.SmallFont, wrap: true)
            {
                CanBeFocused = false
            };
        }
Exemplo n.º 10
0
        public static GUIMessageBox AskForConfirmation(string header, string body, Func <bool> onConfirm)
        {
            string[]      buttons = { TextManager.Get("Ok"), TextManager.Get("Cancel") };
            GUIMessageBox msgBox  = new GUIMessageBox(header, body, buttons, new Vector2(0.2f, 0.175f), minSize: new Point(300, 175));

            // Cancel button
            msgBox.Buttons[1].OnClicked = delegate
            {
                msgBox.Close();
                return(true);
            };

            // Ok button
            msgBox.Buttons[0].OnClicked = delegate
            {
                onConfirm.Invoke();
                msgBox.Close();
                return(true);
            };
            return(msgBox);
        }
Exemplo n.º 11
0
        public void CreatePreviewWindow(GUIMessageBox messageBox)
        {
            var background = new GUIButton(new RectTransform(Vector2.One, messageBox.RectTransform), style: "GUIBackgroundBlocker")
            {
                OnClicked = (btn, userdata) => { if (GUI.MouseOn == btn || GUI.MouseOn == btn.TextBlock)
                                                 {
                                                     messageBox.Close();
                                                 }
                                                 return(true); }
            };

            background.RectTransform.SetAsFirstChild();

            var holder = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.85f), messageBox.Content.RectTransform), style: null);

            CreatePreviewWindow(holder);
        }
Exemplo n.º 12
0
        public static void CreateReadyCheck()
        {
            if (lastReadyCheck < DateTime.Now)
            {
#if !DEBUG
                lastReadyCheck = DateTime.Now.AddMinutes(1);
#endif
                IWriteMessage msg = new WriteOnlyMessage();
                msg.Write((byte)ClientPacketHeader.READY_CHECK);
                msg.Write((byte)ReadyCheckState.Start);
                GameMain.Client?.ClientPeer?.Send(msg, DeliveryMethod.Reliable);
                return;
            }

            GUIMessageBox msgBox = new GUIMessageBox(readyCheckHeader, readyCheckPleaseWait((lastReadyCheck - DateTime.Now).Seconds), new[] { closeButton });
            msgBox.Buttons[0].OnClicked = delegate
            {
                msgBox.Close();
                return(true);
            };
        }
Exemplo n.º 13
0
        private bool ExportEventToFile(GUIButton button, object o)
        {
            XElement?save = ExportXML();

            if (save != null)
            {
                try
                {
                    string directory = Path.GetFullPath("EventProjects");
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    string exportPath = Path.Combine(directory, "Exported");
                    if (!Directory.Exists(exportPath))
                    {
                        Directory.CreateDirectory(exportPath);
                    }

                    var        msgBox    = new GUIMessageBox(TextManager.Get("EventEditor.ExportProjectPrompt"), "", new[] { TextManager.Get("Cancel"), TextManager.Get("EventEditor.Export") }, new Vector2(0.2f, 0.175f), minSize: new Point(300, 175));
                    var        layout    = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.25f), msgBox.Content.RectTransform), isHorizontal: true);
                    GUITextBox nameInput = new GUITextBox(new RectTransform(Vector2.One, layout.RectTransform))
                    {
                        Text = projectName
                    };

                    // Cancel button
                    msgBox.Buttons[0].OnClicked = delegate
                    {
                        msgBox.Close();
                        return(true);
                    };

                    // Ok button
                    msgBox.Buttons[1].OnClicked = delegate
                    {
                        foreach (var illegalChar in Path.GetInvalidFileNameChars())
                        {
                            if (!nameInput.Text.Contains(illegalChar))
                            {
                                continue;
                            }

                            GUI.AddMessage(TextManager.GetWithVariable("SubNameIllegalCharsWarning", "[illegalchar]", illegalChar.ToString()), GUI.Style.Red);
                            return(false);
                        }

                        msgBox.Close();
                        string path = Path.Combine(exportPath, $"{nameInput.Text}.xml");
                        File.WriteAllText(path, save.ToString());
                        AskForConfirmation(TextManager.Get("EventEditor.OpenTextHeader"), TextManager.Get("EventEditor.OpenTextBody"), () =>
                        {
                            ToolBox.OpenFileWithShell(path);
                            return(true);
                        });
                        GUI.AddMessage($"XML exported to {path}", GUI.Style.Green);
                        return(true);
                    };
                }
                catch (Exception e)
                {
                    DebugConsole.ThrowError("Failed to export event", e);
                }
            }
            else
            {
                GUI.AddMessage("Unable to export because the project contains errors", GUI.Style.Red);
            }

            return(true);
        }
Exemplo n.º 14
0
        public static void RefreshSavedSubs()
        {
            var contentPackageSubs = ContentPackage.GetFilesOfType(
                GameMain.Config.AllEnabledPackages,
                ContentType.Submarine, ContentType.Outpost, ContentType.OutpostModule,
                ContentType.Wreck, ContentType.BeaconStation);

            for (int i = savedSubmarines.Count - 1; i >= 0; i--)
            {
                if (File.Exists(savedSubmarines[i].FilePath))
                {
                    bool isDownloadedSub      = Path.GetFullPath(Path.GetDirectoryName(savedSubmarines[i].FilePath)) == Path.GetFullPath(SaveUtil.SubmarineDownloadFolder);
                    bool isInSubmarinesFolder = Path.GetFullPath(Path.GetDirectoryName(savedSubmarines[i].FilePath)) == Path.GetFullPath(SavePath);
                    bool isInContentPackage   = contentPackageSubs.Any(fp => Path.GetFullPath(fp.Path).CleanUpPath() == Path.GetFullPath(savedSubmarines[i].FilePath).CleanUpPath());
                    if (isDownloadedSub)
                    {
                        continue;
                    }
                    if (savedSubmarines[i].LastModifiedTime == File.GetLastWriteTime(savedSubmarines[i].FilePath) && (isInSubmarinesFolder || isInContentPackage))
                    {
                        continue;
                    }
                }
                savedSubmarines[i].Dispose();
            }

            if (!Directory.Exists(SavePath))
            {
                try
                {
                    Directory.CreateDirectory(SavePath);
                }
                catch (Exception e)
                {
                    DebugConsole.ThrowError("Directory \"" + SavePath + "\" not found and creating the directory failed.", e);
                    return;
                }
            }

            List <string> filePaths;

            string[] subDirectories;

            try
            {
                filePaths      = Directory.GetFiles(SavePath).ToList();
                subDirectories = Directory.GetDirectories(SavePath).Where(s =>
                {
                    DirectoryInfo dir = new DirectoryInfo(s);
                    return(!dir.Attributes.HasFlag(System.IO.FileAttributes.Hidden) && !dir.Name.StartsWith("."));
                }).ToArray();
            }
            catch (Exception e)
            {
                DebugConsole.ThrowError("Couldn't open directory \"" + SavePath + "\"!", e);
                return;
            }

            foreach (string subDirectory in subDirectories)
            {
                try
                {
                    filePaths.AddRange(Directory.GetFiles(subDirectory).ToList());
                }
                catch (Exception e)
                {
                    DebugConsole.ThrowError("Couldn't open subdirectory \"" + subDirectory + "\"!", e);
                    return;
                }
            }

            foreach (ContentFile subFile in contentPackageSubs)
            {
                if (!filePaths.Any(fp => Path.GetFullPath(fp) == Path.GetFullPath(subFile.Path)))
                {
                    filePaths.Add(subFile.Path);
                }
            }

            filePaths.RemoveAll(p => savedSubmarines.Any(sub => sub.FilePath == p));

            foreach (string path in filePaths)
            {
                var subInfo = new SubmarineInfo(path);
                if (subInfo.IsFileCorrupted)
                {
#if CLIENT
                    if (DebugConsole.IsOpen)
                    {
                        DebugConsole.Toggle();
                    }
                    var deleteSubPrompt = new GUIMessageBox(
                        TextManager.Get("Error"),
                        TextManager.GetWithVariable("SubLoadError", "[subname]", subInfo.Name) + "\n" +
                        TextManager.GetWithVariable("DeleteFileVerification", "[filename]", subInfo.Name),
                        new string[] { TextManager.Get("Yes"), TextManager.Get("No") });

                    string filePath = path;
                    deleteSubPrompt.Buttons[0].OnClicked += (btn, userdata) =>
                    {
                        try
                        {
                            File.Delete(filePath);
                        }
                        catch (Exception e)
                        {
                            DebugConsole.ThrowError($"Failed to delete file \"{filePath}\".", e);
                        }
                        deleteSubPrompt.Close();
                        return(true);
                    };
                    deleteSubPrompt.Buttons[1].OnClicked += deleteSubPrompt.Close;
#endif
                }
                else
                {
                    savedSubmarines.Add(subInfo);
                }
            }
        }
Exemplo n.º 15
0
            public GUIMessageBox Create()
            {
                var box = new GUIMessageBox(TextManager.Get("leveleditor.createlevelobj"), string.Empty,
                                            new string[] { TextManager.Get("cancel"), TextManager.Get("done") }, new Vector2(0.5f, 0.8f));

                box.Content.ChildAnchor     = Anchor.TopCenter;
                box.Content.AbsoluteSpacing = 20;
                int elementSize = 30;
                var listBox     = new GUIListBox(new RectTransform(new Vector2(1, 0.9f), box.Content.RectTransform));

                new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform),
                                 TextManager.Get("leveleditor.levelobjname"))
                {
                    CanBeFocused = false
                };
                var nameBox = new GUITextBox(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform));

                new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform),
                                 TextManager.Get("leveleditor.levelobjtexturepath"))
                {
                    CanBeFocused = false
                };
                var texturePathBox = new GUITextBox(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform));

                foreach (LevelObjectPrefab prefab in LevelObjectPrefab.List)
                {
                    if (prefab.Sprites.FirstOrDefault() == null)
                    {
                        continue;
                    }
                    texturePathBox.Text = Path.GetDirectoryName(prefab.Sprites.FirstOrDefault().FilePath);
                    break;
                }

                newPrefab = new LevelObjectPrefab(null);

                new SerializableEntityEditor(listBox.Content.RectTransform, newPrefab, false, false);

                box.Buttons[0].OnClicked += (b, d) =>
                {
                    box.Close();
                    return(true);
                };
                // Next
                box.Buttons[1].OnClicked += (b, d) =>
                {
                    if (string.IsNullOrEmpty(nameBox.Text))
                    {
                        nameBox.Flash(GUI.Style.Red);
                        GUI.AddMessage(TextManager.Get("leveleditor.levelobjnameempty"), GUI.Style.Red);
                        return(false);
                    }

                    if (LevelObjectPrefab.List.Any(obj => obj.Name.ToLower() == nameBox.Text.ToLower()))
                    {
                        nameBox.Flash(GUI.Style.Red);
                        GUI.AddMessage(TextManager.Get("leveleditor.levelobjnametaken"), GUI.Style.Red);
                        return(false);
                    }

                    if (!File.Exists(texturePathBox.Text))
                    {
                        texturePathBox.Flash(GUI.Style.Red);
                        GUI.AddMessage(TextManager.Get("leveleditor.levelobjtexturenotfound"), GUI.Style.Red);
                        return(false);
                    }

                    newPrefab.Name = nameBox.Text;

                    XmlWriterSettings settings = new XmlWriterSettings {
                        Indent = true
                    };
                    foreach (ContentFile configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelObjectPrefabs))
                    {
                        XDocument doc = XMLExtensions.TryLoadXml(configFile.Path);
                        if (doc == null)
                        {
                            continue;
                        }
                        var newElement = new XElement(newPrefab.Name);
                        newPrefab.Save(newElement);
                        newElement.Add(new XElement("Sprite",
                                                    new XAttribute("texture", texturePathBox.Text),
                                                    new XAttribute("sourcerect", "0,0,100,100"),
                                                    new XAttribute("origin", "0.5,0.5")));

                        doc.Root.Add(newElement);
                        using (var writer = XmlWriter.Create(configFile.Path, settings))
                        {
                            doc.WriteTo(writer);
                            writer.Flush();
                        }
                        // Recreate the prefab so that the sprite loads correctly: TODO: consider a better way to do this
                        newPrefab = new LevelObjectPrefab(newElement);
                        break;
                    }

                    LevelObjectPrefab.List.Add(newPrefab);
                    GameMain.LevelEditorScreen.UpdateLevelObjectsList();

                    box.Close();
                    return(true);
                };
                return(box);
            }
Exemplo n.º 16
0
        private bool SelectTab(GUIButton button, object obj)
        {
            if (obj is Tab)
            {
                if (GameMain.Config.UnsavedSettings)
                {
                    var applyBox = new GUIMessageBox(
                        TextManager.Get("ApplySettingsLabel"),
                        TextManager.Get("ApplySettingsQuestion"),
                        new string[] { TextManager.Get("ApplySettingsYes"), TextManager.Get("ApplySettingsNo") });
                    applyBox.Buttons[0].UserData  = (Tab)obj;
                    applyBox.Buttons[0].OnClicked = (tb, userdata) =>
                    {
                        applyBox.Close(button, userdata);
                        ApplySettings(button, userdata);
                        return(true);
                    };

                    applyBox.Buttons[1].UserData  = (Tab)obj;
                    applyBox.Buttons[1].OnClicked = (tb, userdata) =>
                    {
                        applyBox.Close(button, userdata);
                        DiscardSettings(button, userdata);
                        return(true);
                    };
                    return(false);
                }

                GameMain.Config.ResetSettingsFrame();
                selectedTab = (Tab)obj;

                switch (selectedTab)
                {
                case Tab.NewGame:
                    if (!GameMain.Config.CampaignDisclaimerShown)
                    {
                        selectedTab = 0;
                        GameMain.Instance.ShowCampaignDisclaimer(() => { SelectTab(null, Tab.NewGame); });
                        return(true);
                    }
                    campaignSetupUI.CreateDefaultSaveName();
                    campaignSetupUI.RandomizeSeed();
                    campaignSetupUI.UpdateSubList(Submarine.SavedSubmarines);
                    break;

                case Tab.LoadGame:
                    campaignSetupUI.UpdateLoadMenu();
                    break;

                case Tab.Settings:
                    menuTabs[(int)Tab.Settings].RectTransform.ClearChildren();
                    GameMain.Config.SettingsFrame.RectTransform.Parent       = menuTabs[(int)Tab.Settings].RectTransform;
                    GameMain.Config.SettingsFrame.RectTransform.RelativeSize = Vector2.One;
                    break;

                case Tab.JoinServer:
                    GameMain.ServerListScreen.Select();
                    break;

                case Tab.HostServer:
                    break;

                case Tab.Tutorials:
                    if (!GameMain.Config.CampaignDisclaimerShown)
                    {
                        selectedTab = 0;
                        GameMain.Instance.ShowCampaignDisclaimer(() => { SelectTab(null, Tab.Tutorials); });
                        return(true);
                    }
                    UpdateTutorialList();
                    break;

                case Tab.CharacterEditor:
                    Submarine.MainSub = null;
                    GameMain.CharacterEditorScreen.Select();
                    break;

                case Tab.SubmarineEditor:
                    GameMain.SubEditorScreen.Select();
                    break;

                case Tab.QuickStartDev:
                    QuickStart();
                    break;

                case Tab.SteamWorkshop:
                    if (!Steam.SteamManager.IsInitialized)
                    {
                        return(false);
                    }
                    GameMain.SteamWorkshopScreen.Select();
                    break;
                }
            }
            else
            {
                selectedTab = 0;
            }

            if (button != null)
            {
                button.Selected = true;
            }
            ResetButtonStates(button);

            return(true);
        }
Exemplo n.º 17
0
            public GUIMessageBox Create()
            {
                var box = new GUIMessageBox(TextManager.Get("LevelEditorCreateLevelObj"), string.Empty, 
                    new string[] { TextManager.Get("Cancel"), TextManager.Get("Done") }, GameMain.GraphicsWidth / 2, (int)(GameMain.GraphicsHeight * 0.8f));

                box.Content.ChildAnchor = Anchor.TopCenter;
                box.Content.AbsoluteSpacing = 20;
                int elementSize = 30;
                var listBox = new GUIListBox(new RectTransform(new Vector2(1, 0.9f), box.Content.RectTransform));

                new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform), 
                    TextManager.Get("LevelEditorLevelObjName")) { CanBeFocused = false };
                var nameBox = new GUITextBox(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform));

                new GUITextBlock(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform), 
                    TextManager.Get("LevelEditorLevelObjTexturePath")) { CanBeFocused = false };
                var texturePathBox = new GUITextBox(new RectTransform(new Point(listBox.Content.Rect.Width, elementSize), listBox.Content.RectTransform));
                foreach (LevelObjectPrefab prefab in LevelObjectPrefab.List)
                {
                    if (prefab.Sprite == null) continue;
                    texturePathBox.Text = Path.GetDirectoryName(prefab.Sprite.FilePath);
                    break;
                }

                newPrefab = new LevelObjectPrefab(null);

                new SerializableEntityEditor(listBox.Content.RectTransform, newPrefab, false, false);
                
                box.Buttons[0].OnClicked += (b, d) =>
                {
                    box.Close();
                    return true;
                };
                // Next
                box.Buttons[1].OnClicked += (b, d) =>
                {
                    if (string.IsNullOrEmpty(nameBox.Text))
                    {
                        nameBox.Flash(Color.Red);
                        GUI.AddMessage(TextManager.Get("LevelEditorLevelObjNameEmpty"), Color.Red);
                        return false;
                    }
                    
                    if (LevelObjectPrefab.List.Any(obj => obj.Name.ToLower() == nameBox.Text.ToLower()))
                    {
                        nameBox.Flash(Color.Red);
                        GUI.AddMessage(TextManager.Get("LevelEditorLevelObjNameTaken"), Color.Red);
                        return false;
                    }

                    if (!File.Exists(texturePathBox.Text))
                    {
                        texturePathBox.Flash(Color.Red);
                        GUI.AddMessage(TextManager.Get("LevelEditorLevelObjTextureNotFound"), Color.Red);
                        return false;
                    }

                    newPrefab.Name = nameBox.Text;
                    
                    XmlWriterSettings settings = new XmlWriterSettings { Indent = true };
                    foreach (string configFile in GameMain.Instance.GetFilesOfType(ContentType.LevelObjectPrefabs))
                    {
                        XDocument doc = XMLExtensions.TryLoadXml(configFile);
                        if (doc?.Root == null) continue;
                        var newElement = new XElement(newPrefab.Name);
                        newPrefab.Save(newElement);
                        newElement.Add(new XElement("Sprite", 
                            new XAttribute("texture", texturePathBox.Text), 
                            new XAttribute("sourcerect", "0,0,100,100"),
                            new XAttribute("origin", "0.5,0.5")));

                        doc.Root.Add(newElement);
                        using (var writer = XmlWriter.Create(configFile, settings))
                        {
                            doc.WriteTo(writer);
                            writer.Flush();
                        }
                        break;
                    }

                    LevelObjectPrefab.List.Add(newPrefab);
                    GameMain.LevelEditorScreen.UpdateLevelObjectsList();

                    box.Close();
                    return true;
                };
                return box;
            }
Exemplo n.º 18
0
            void AssignActionsToButtons(List <GUIButton> optionButtons, GUIMessageBox target)
            {
                if (!options.Any())
                {
                    GUIButton closeButton = new GUIButton(new RectTransform(Vector2.One, target.InnerFrame.RectTransform, Anchor.BottomRight, scaleBasis: ScaleBasis.Smallest)
                    {
                        MaxSize        = new Point(GUI.IntScale(24)),
                        MinSize        = new Point(24),
                        AbsoluteOffset = new Point(GUI.IntScale(48), GUI.IntScale(16))
                    }, style: "GUIButtonVerticalArrow")
                    {
                        UserData           = "ContinueButton",
                        IgnoreLayoutGroups = true,
                        Bounce             = true,
                        OnClicked          = (btn, userdata) =>
                        {
                            if (actionInstance != null)
                            {
                                actionInstance.selectedOption = 0;
                            }
                            else if (actionId.HasValue)
                            {
                                SendResponse(actionId.Value, 0);
                            }

                            if (!continueConversation)
                            {
                                target.Close();
                            }
                            else
                            {
                                btn.Frame.FadeOut(0.33f, true);
                            }

                            return(true);
                        }
                    };

                    closeButton.Children.ForEach(child => child.SpriteEffects = SpriteEffects.FlipVertically);
                    closeButton.Frame.FadeIn(0.5f, 0.5f);
                    closeButton.SlideIn(0.5f, 0.33f, 16, SlideDirection.Down);
                }

                for (int i = 0; i < optionButtons.Count; i++)
                {
                    optionButtons[i].UserData   = i;
                    optionButtons[i].OnClicked += (btn, userdata) =>
                    {
                        int selectedOption = (userdata as int?) ?? 0;
                        if (actionInstance != null)
                        {
                            actionInstance.selectedOption = selectedOption;
                            foreach (GUIButton otherButton in optionButtons)
                            {
                                otherButton.CanBeFocused = false;
                                if (otherButton != btn)
                                {
                                    otherButton.TextBlock.OverrideTextColor(Color.DarkGray * 0.8f);
                                }
                            }
                            btn.ExternalHighlight = true;
                            return(true);
                        }

                        if (actionId.HasValue)
                        {
                            SendResponse(actionId.Value, selectedOption);
                            btn.CanBeFocused      = false;
                            btn.ExternalHighlight = true;
                            foreach (GUIButton otherButton in optionButtons)
                            {
                                otherButton.CanBeFocused = false;
                                if (otherButton != btn)
                                {
                                    otherButton.TextBlock.OverrideTextColor(Color.DarkGray * 0.8f);
                                }
                            }
                            return(true);
                        }
                        //should not happen
                        return(false);
                    };

                    if (closingOptions.Contains(i))
                    {
                        optionButtons[i].OnClicked += target.Close;
                    }
                }
            }
Exemplo n.º 19
0
        public void CreateBackgroundColorPicker()
        {
            var msgBox = new GUIMessageBox(TextManager.Get("CharacterEditor.EditBackgroundColor"), "", new[] { TextManager.Get("Reset"), TextManager.Get("OK") }, new Vector2(0.2f, 0.175f), minSize: new Point(300, 175));

            var rgbLayout = new GUILayoutGroup(new RectTransform(new Vector2(1f, 0.25f), msgBox.Content.RectTransform), isHorizontal: true);

            // Generate R,G,B labels and parent elements
            var layoutParents = new GUILayoutGroup[3];

            for (int i = 0; i < 3; i++)
            {
                var colorContainer = new GUILayoutGroup(new RectTransform(new Vector2(0.33f, 1), rgbLayout.RectTransform), isHorizontal: true)
                {
                    Stretch = true
                };
                new GUITextBlock(new RectTransform(new Vector2(0.2f, 1), colorContainer.RectTransform, Anchor.CenterLeft)
                {
                    MinSize = new Point(15, 0)
                }, GUI.colorComponentLabels[i], font: GUI.SmallFont, textAlignment: Alignment.Center);
                layoutParents[i] = colorContainer;
            }

            // attach number inputs to our generated parent elements
            var rInput = new GUINumberInput(new RectTransform(new Vector2(0.7f, 1f), layoutParents[0].RectTransform), GUINumberInput.NumberType.Int)
            {
                IntValue = BackgroundColor.R
            };
            var gInput = new GUINumberInput(new RectTransform(new Vector2(0.7f, 1f), layoutParents[1].RectTransform), GUINumberInput.NumberType.Int)
            {
                IntValue = BackgroundColor.G
            };
            var bInput = new GUINumberInput(new RectTransform(new Vector2(0.7f, 1f), layoutParents[2].RectTransform), GUINumberInput.NumberType.Int)
            {
                IntValue = BackgroundColor.B
            };

            rInput.MinValueInt = gInput.MinValueInt = bInput.MinValueInt = 0;
            rInput.MaxValueInt = gInput.MaxValueInt = bInput.MaxValueInt = 255;

            rInput.OnValueChanged = gInput.OnValueChanged = bInput.OnValueChanged = delegate
            {
                var color = new Color(rInput.IntValue, gInput.IntValue, bInput.IntValue);
                BackgroundColor = color;
                GameSettings.SubEditorBackgroundColor = color;
            };

            // Reset button
            msgBox.Buttons[0].OnClicked = (button, o) =>
            {
                rInput.IntValue = 13;
                gInput.IntValue = 37;
                bInput.IntValue = 69;
                return(true);
            };

            // Ok button
            msgBox.Buttons[1].OnClicked = (button, o) =>
            {
                msgBox.Close();
                GameMain.Config.SaveNewPlayerConfig();
                return(true);
            };
        }
Exemplo n.º 20
0
        public static void StartCampaignSetup()
        {
            var setupBox = new GUIMessageBox("Campaign Setup", "", new string [0], 500, 500);

            setupBox.InnerFrame.Padding = new Vector4(20.0f, 80.0f, 20.0f, 20.0f);

            var newCampaignContainer  = new GUIFrame(new Rectangle(0, 40, 0, 0), null, setupBox.InnerFrame);
            var loadCampaignContainer = new GUIFrame(new Rectangle(0, 40, 0, 0), null, setupBox.InnerFrame);

            var campaignSetupUI = new CampaignSetupUI(true, newCampaignContainer, loadCampaignContainer);

            var newCampaignButton = new GUIButton(new Rectangle(0, 0, 120, 20), "New campaign", "", setupBox.InnerFrame);

            newCampaignButton.OnClicked += (btn, obj) =>
            {
                newCampaignContainer.Visible  = true;
                loadCampaignContainer.Visible = false;
                return(true);
            };

            var loadCampaignButton = new GUIButton(new Rectangle(130, 0, 120, 20), "Load campaign", "", setupBox.InnerFrame);

            loadCampaignButton.OnClicked += (btn, obj) =>
            {
                newCampaignContainer.Visible  = false;
                loadCampaignContainer.Visible = true;
                return(true);
            };

            loadCampaignContainer.Visible = false;

            campaignSetupUI.StartNewGame = (Submarine sub, string saveName, string mapSeed) =>
            {
                GameMain.GameSession = new GameSession(new Submarine(sub.FilePath, ""), saveName, GameModePreset.list.Find(g => g.Name == "Campaign"));
                var campaign = ((MultiplayerCampaign)GameMain.GameSession.GameMode);
                campaign.GenerateMap(mapSeed);
                campaign.SetDelegates();

                setupBox.Close();

                GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                campaign.Map.SelectRandomLocation(true);
                SaveUtil.SaveGame(GameMain.GameSession.SavePath);
                campaign.LastSaveID++;
            };

            campaignSetupUI.LoadGame = (string fileName) =>
            {
                SaveUtil.LoadGame(fileName);
                var campaign = ((MultiplayerCampaign)GameMain.GameSession.GameMode);
                campaign.LastSaveID++;

                setupBox.Close();

                GameMain.NetLobbyScreen.ToggleCampaignMode(true);
                campaign.Map.SelectRandomLocation(true);
            };

            var cancelButton = new GUIButton(new Rectangle(0, 0, 120, 30), "Cancel", Alignment.BottomLeft, "", setupBox.InnerFrame);

            cancelButton.OnClicked += (btn, obj) =>
            {
                setupBox.Close();
                int otherModeIndex = 0;
                for (otherModeIndex = 0; otherModeIndex < GameMain.NetLobbyScreen.ModeList.children.Count; otherModeIndex++)
                {
                    if (GameMain.NetLobbyScreen.ModeList.children[otherModeIndex].UserData is MultiplayerCampaign)
                    {
                        continue;
                    }
                    break;
                }

                GameMain.NetLobbyScreen.SelectMode(otherModeIndex);
                return(true);
            };
        }
Exemplo n.º 21
0
        private static void CreateEditMenu(ValueNode?node, NodeConnection?connection = null)
        {
            object?newValue;
            Type?  type;

            if (node != null)
            {
                newValue = node.Value;
                type     = node.Type;
            }
            else if (connection != null)
            {
                newValue = connection.OverrideValue;
                type     = connection.ValueType;
            }
            else
            {
                return;
            }

            if (connection?.Type == NodeConnectionType.Option)
            {
                newValue = connection.OptionText;
                type     = typeof(string);
            }

            if (type == null)
            {
                return;
            }

            Vector2 size   = type == typeof(string) ? new Vector2(0.2f, 0.3f) : new Vector2(0.2f, 0.175f);
            var     msgBox = new GUIMessageBox(TextManager.Get("EventEditor.Edit"), "", new[] { TextManager.Get("Cancel"), TextManager.Get("OK") }, size, minSize: new Point(300, 175));


            Vector2 layoutSize = type == typeof(string) ? new Vector2(1f, 0.5f) : new Vector2(1f, 0.25f);
            var     layout     = new GUILayoutGroup(new RectTransform(layoutSize, msgBox.Content.RectTransform), isHorizontal: true);

            if (type.IsEnum)
            {
                Array       enums      = Enum.GetValues(type);
                GUIDropDown valueInput = new GUIDropDown(new RectTransform(Vector2.One, layout.RectTransform), newValue?.ToString(), enums.Length);
                foreach (object? @enum in enums)
                {
                    valueInput.AddItem(@enum?.ToString(), @enum);
                }

                valueInput.OnSelected += (component, o) =>
                {
                    newValue = o;
                    return(true);
                };
            }
            else
            {
                if (type == typeof(string))
                {
                    GUIListBox listBox = new GUIListBox(new RectTransform(Vector2.One, layout.RectTransform))
                    {
                        CanBeFocused = false
                    };
                    GUITextBox valueInput = new GUITextBox(new RectTransform(Vector2.One, listBox.Content.RectTransform, Anchor.TopRight), wrap: true, style: "GUITextBoxNoBorder");
                    valueInput.OnTextChanged += (component, o) =>
                    {
                        Vector2 textSize = valueInput.Font.MeasureString(valueInput.WrappedText);
                        valueInput.RectTransform.NonScaledSize = new Point(valueInput.RectTransform.NonScaledSize.X, (int)textSize.Y + 10);
                        listBox.UpdateScrollBarSize();
                        listBox.BarScroll = 1.0f;
                        newValue          = o;
                        return(true);
                    };
                    valueInput.Text = newValue?.ToString() ?? "<type here>";
                }
                else if (type == typeof(float) || type == typeof(int))
                {
                    GUINumberInput valueInput = new GUINumberInput(new RectTransform(Vector2.One, layout.RectTransform), GUINumberInput.NumberType.Float)
                    {
                        FloatValue = (float)(newValue ?? 0.0f)
                    };
                    valueInput.OnValueChanged += component => { newValue = component.FloatValue; };
                }
                else if (type == typeof(bool))
                {
                    GUITickBox valueInput = new GUITickBox(new RectTransform(Vector2.One, layout.RectTransform), "Value")
                    {
                        Selected = (bool)(newValue ?? false)
                    };
                    valueInput.OnSelected += component =>
                    {
                        newValue = component.Selected;
                        return(true);
                    };
                }
            }

            // Cancel button
            msgBox.Buttons[0].OnClicked = (button, o) =>
            {
                msgBox.Close();
                return(true);
            };

            // Ok button
            msgBox.Buttons[1].OnClicked = (button, o) =>
            {
                if (node != null)
                {
                    node.Value = newValue;
                }
                else if (connection != null)
                {
                    if (connection.Type == NodeConnectionType.Option)
                    {
                        connection.OptionText = newValue?.ToString();
                    }
                    else
                    {
                        connection.ClearConnections();
                        connection.OverrideValue = newValue;
                    }
                }

                msgBox.Close();
                return(true);
            };
        }
Exemplo n.º 22
0
            void AssignActionsToButtons(List <GUIButton> optionButtons, GUIMessageBox target)
            {
                if (!options.Any())
                {
                    GUIButton closeButton = new GUIButton(new RectTransform(Vector2.One, target.InnerFrame.RectTransform, Anchor.BottomRight, scaleBasis: ScaleBasis.Smallest)
                    {
                        MaxSize        = new Point(GUI.IntScale(24)),
                        MinSize        = new Point(24),
                        AbsoluteOffset = new Point(GUI.IntScale(48), GUI.IntScale(16))
                    }, style: "GUIButtonVerticalArrow")
                    {
                        UserData           = "ContinueButton",
                        IgnoreLayoutGroups = true,
                        Bounce             = true,
                        OnClicked          = (btn, userdata) =>
                        {
                            if (actionInstance != null)
                            {
                                actionInstance.selectedOption = 0;
                            }
                            else if (actionId.HasValue)
                            {
                                SendResponse(actionId.Value, 0);
                            }

                            if (!continueConversation)
                            {
                                target.Close();
                            }
                            else
                            {
                                btn.Frame.FadeOut(0.33f, true);
                            }

                            return(true);
                        }
                    };

                    double allowCloseTime = Timing.TotalTime + 0.5;
                    closeButton.Children.ForEach(child => child.SpriteEffects = SpriteEffects.FlipVertically);
                    closeButton.Frame.FadeIn(0.5f, 0.5f);
                    closeButton.SlideIn(0.5f, 0.33f, 16, SlideDirection.Down);

                    InputType?closeInput = null;
                    if (GameMain.Config.KeyBind(InputType.Use).MouseButton == MouseButton.None)
                    {
                        closeInput = InputType.Use;
                    }
                    else if (GameMain.Config.KeyBind(InputType.Select).MouseButton == MouseButton.None)
                    {
                        closeInput = InputType.Select;
                    }
                    if (closeInput.HasValue)
                    {
                        closeButton.ToolTip = TextManager.ParseInputTypes($"{TextManager.Get("Close")} ([InputType.{closeInput.Value}])");
                        closeButton.OnAddedToGUIUpdateList += (GUIComponent component) =>
                        {
                            if (Timing.TotalTime > allowCloseTime && PlayerInput.KeyHit(closeInput.Value))
                            {
                                GUIButton btn = component as GUIButton;
                                btn?.OnClicked(btn, btn.UserData);
                                btn?.Flash(GUI.Style.Green);
                            }
                        };
                    }
                }

                for (int i = 0; i < optionButtons.Count; i++)
                {
                    optionButtons[i].UserData   = i;
                    optionButtons[i].OnClicked += (btn, userdata) =>
                    {
                        int selectedOption = (userdata as int?) ?? 0;
                        if (actionInstance != null)
                        {
                            actionInstance.selectedOption = selectedOption;
                            foreach (GUIButton otherButton in optionButtons)
                            {
                                otherButton.CanBeFocused = false;
                                if (otherButton != btn)
                                {
                                    otherButton.TextBlock.OverrideTextColor(Color.DarkGray * 0.8f);
                                }
                            }
                            btn.ExternalHighlight = true;
                            return(true);
                        }

                        if (actionId.HasValue)
                        {
                            SendResponse(actionId.Value, selectedOption);
                            btn.CanBeFocused      = false;
                            btn.ExternalHighlight = true;
                            foreach (GUIButton otherButton in optionButtons)
                            {
                                otherButton.CanBeFocused = false;
                                if (otherButton != btn)
                                {
                                    otherButton.TextBlock.OverrideTextColor(Color.DarkGray * 0.8f);
                                }
                            }
                            return(true);
                        }
                        //should not happen
                        return(false);
                    };

                    if (closingOptions.Contains(i))
                    {
                        optionButtons[i].OnClicked += target.Close;
                    }
                }
            }
Exemplo n.º 23
0
        public void SelectLocation(Location location, LocationConnection connection)
        {
            missionTickBoxes.Clear();
            missionRewardTexts.Clear();
            locationInfoPanel.ClearChildren();
            //don't select the map panel if we're looking at some other tab
            if (selectedTab == CampaignMode.InteractionType.Map)
            {
                SelectTab(CampaignMode.InteractionType.Map);
                locationInfoPanel.Visible = location != null;
            }

            Location prevSelectedLocation  = selectedLocation;
            float    prevMissionListScroll = missionList?.BarScroll ?? 0.0f;

            selectedLocation = location;
            if (location == null)
            {
                return;
            }

            int padding = GUI.IntScale(20);

            var content = new GUILayoutGroup(new RectTransform(locationInfoPanel.Rect.Size - new Point(padding * 2), locationInfoPanel.RectTransform, Anchor.Center), childAnchor: Anchor.TopRight)
            {
                Stretch         = true,
                RelativeSpacing = 0.02f,
            };

            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), location.Name, font: GUI.LargeFont)
            {
                AutoScaleHorizontal = true
            };
            new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), content.RectTransform), location.Type.Name, font: GUI.SubHeadingFont);

            Sprite portrait = location.Type.GetPortrait(location.PortraitId);

            portrait.EnsureLazyLoaded();

            var portraitContainer = new GUICustomComponent(new RectTransform(new Vector2(1.0f, 0.3f), content.RectTransform), onDraw: (sb, customComponent) =>
            {
                portrait.Draw(sb, customComponent.Rect.Center.ToVector2(), Color.Gray, portrait.size / 2, scale: Math.Max(customComponent.Rect.Width / portrait.size.X, customComponent.Rect.Height / portrait.size.Y));
            })
            {
                HideElementsOutsideFrame = true
            };

            var textContent = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), portraitContainer.RectTransform, Anchor.Center))
            {
                RelativeSpacing = 0.05f
            };

            if (connection?.LevelData != null)
            {
                var biomeLabel = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), textContent.RectTransform),
                                                  TextManager.Get("Biome", fallBackTag: "location"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft);
                new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), biomeLabel.RectTransform), connection.Biome.DisplayName, textAlignment: Alignment.CenterRight);

                var difficultyLabel = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), textContent.RectTransform),
                                                       TextManager.Get("LevelDifficulty"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft);
                new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), difficultyLabel.RectTransform), ((int)connection.LevelData.Difficulty) + " %", textAlignment: Alignment.CenterRight);

                if (connection.LevelData.HasBeaconStation)
                {
                    var    beaconStationContent = new GUILayoutGroup(new RectTransform(biomeLabel.RectTransform.NonScaledSize, textContent.RectTransform), isHorizontal: true, childAnchor: Anchor.CenterLeft);
                    string style = connection.LevelData.IsBeaconActive ? "BeaconStationActive" : "BeaconStationInactive";
                    var    icon  = new GUIImage(new RectTransform(new Point((int)(beaconStationContent.Rect.Height * 1.2f)), beaconStationContent.RectTransform),
                                                style, scaleToFit: true)
                    {
                        Color      = MapGenerationParams.Instance.IndicatorColor,
                        HoverColor = Color.Lerp(MapGenerationParams.Instance.IndicatorColor, Color.White, 0.5f),
                        ToolTip    = TextManager.Get(connection.LevelData.IsBeaconActive ? "BeaconStationActiveTooltip" : "BeaconStationInactiveTooltip")
                    };
                    new GUITextBlock(new RectTransform(Vector2.One, beaconStationContent.RectTransform),
                                     TextManager.Get("submarinetype.beaconstation", fallBackTag: "beaconstationsonarlabel"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft)
                    {
                        Padding = Vector4.Zero,
                        ToolTip = icon.ToolTip
                    };
                }
                if (connection.LevelData.HasHuntingGrounds)
                {
                    var huntingGroundsContent = new GUILayoutGroup(new RectTransform(biomeLabel.RectTransform.NonScaledSize, textContent.RectTransform), isHorizontal: true, childAnchor: Anchor.CenterLeft);
                    var icon = new GUIImage(new RectTransform(new Point((int)(huntingGroundsContent.Rect.Height * 1.5f)), huntingGroundsContent.RectTransform),
                                            "HuntingGrounds", scaleToFit: true)
                    {
                        Color      = MapGenerationParams.Instance.IndicatorColor,
                        HoverColor = Color.Lerp(MapGenerationParams.Instance.IndicatorColor, Color.White, 0.5f),
                        ToolTip    = TextManager.Get("HuntingGroundsTooltip")
                    };
                    new GUITextBlock(new RectTransform(Vector2.One, huntingGroundsContent.RectTransform),
                                     TextManager.Get("missionname.huntinggrounds"), font: GUI.SubHeadingFont, textAlignment: Alignment.CenterLeft)
                    {
                        Padding = Vector4.Zero,
                        ToolTip = icon.ToolTip
                    };
                }
            }

            missionList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.4f), content.RectTransform))
            {
                Spacing = (int)(5 * GUI.yScale)
            };
            missionList.OnSelected = (GUIComponent selected, object userdata) =>
            {
                var tickBox = selected.FindChild(c => c is GUITickBox, recursive: true) as GUITickBox;
                if (GUI.MouseOn == tickBox)
                {
                    return(false);
                }
                if (tickBox != null)
                {
                    if (Campaign.AllowedToManageCampaign() && tickBox.Enabled)
                    {
                        tickBox.Selected = !tickBox.Selected;
                    }
                }
                return(true);
            };

            SelectedLevel = connection?.LevelData;
            Location currentDisplayLocation = Campaign.GetCurrentDisplayLocation();

            if (connection != null && connection.Locations.Contains(currentDisplayLocation))
            {
                List <Mission> availableMissions = currentDisplayLocation.GetMissionsInConnection(connection).ToList();
                if (!availableMissions.Contains(null))
                {
                    availableMissions.Insert(0, null);
                }

                missionList.Content.ClearChildren();

                foreach (Mission mission in availableMissions)
                {
                    var missionPanel = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.1f), missionList.Content.RectTransform), style: null)
                    {
                        UserData = mission
                    };
                    var missionTextContent = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), missionPanel.RectTransform, Anchor.Center))
                    {
                        Stretch         = true,
                        CanBeFocused    = true,
                        AbsoluteSpacing = GUI.IntScale(5)
                    };

                    var missionName = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), mission?.Name ?? TextManager.Get("NoMission"), font: GUI.SubHeadingFont, wrap: true);
                    // missionName.RectTransform.MinSize = new Point(0, (int)(missionName.Rect.Height * 1.5f));
                    if (mission != null)
                    {
                        var tickBox = new GUITickBox(new RectTransform(Vector2.One * 0.9f, missionName.RectTransform, anchor: Anchor.CenterLeft, scaleBasis: ScaleBasis.Smallest)
                        {
                            AbsoluteOffset = new Point((int)missionName.Padding.X, 0)
                        }, label: string.Empty)
                        {
                            UserData = mission,
                            Selected = Campaign.Map.CurrentLocation?.SelectedMissions.Contains(mission) ?? false
                        };
                        tickBox.RectTransform.MinSize     = new Point(tickBox.Rect.Height, 0);
                        tickBox.RectTransform.IsFixedSize = true;
                        tickBox.Enabled     = Campaign.AllowedToManageCampaign();
                        tickBox.OnSelected += (GUITickBox tb) =>
                        {
                            if (!Campaign.AllowedToManageCampaign())
                            {
                                return(false);
                            }

                            if (tb.Selected)
                            {
                                Campaign.Map.CurrentLocation.SelectMission(mission);
                            }
                            else
                            {
                                Campaign.Map.CurrentLocation.DeselectMission(mission);
                            }

                            foreach (GUITextBlock rewardText in missionRewardTexts)
                            {
                                Mission otherMission = rewardText.UserData as Mission;
                                rewardText.SetRichText(otherMission.GetMissionRewardText(Submarine.MainSub));
                            }

                            UpdateMaxMissions(connection.OtherLocation(currentDisplayLocation));

                            if ((Campaign is MultiPlayerCampaign multiPlayerCampaign) && !multiPlayerCampaign.SuppressStateSending &&
                                Campaign.AllowedToManageCampaign())
                            {
                                GameMain.Client?.SendCampaignState();
                            }
                            return(true);
                        };
                        missionTickBoxes.Add(tickBox);

                        GUILayoutGroup difficultyIndicatorGroup = null;
                        if (mission.Difficulty.HasValue)
                        {
                            difficultyIndicatorGroup = new GUILayoutGroup(new RectTransform(Vector2.One * 0.9f, missionName.RectTransform, anchor: Anchor.CenterRight, scaleBasis: ScaleBasis.Smallest)
                            {
                                AbsoluteOffset = new Point((int)missionName.Padding.Z, 0)
                            },
                                                                          isHorizontal: true, childAnchor: Anchor.CenterRight)
                            {
                                AbsoluteSpacing = 1,
                                UserData        = "difficulty"
                            };
                            var difficultyColor = mission.GetDifficultyColor();
                            for (int i = 0; i < mission.Difficulty; i++)
                            {
                                new GUIImage(new RectTransform(Vector2.One, difficultyIndicatorGroup.RectTransform, scaleBasis: ScaleBasis.Smallest)
                                {
                                    IsFixedSize = true
                                }, "DifficultyIndicator", scaleToFit: true)
                                {
                                    Color         = difficultyColor,
                                    SelectedColor = difficultyColor,
                                    HoverColor    = difficultyColor
                                };
                            }
                        }

                        float extraPadding  = 0;// 0.8f * tickBox.Rect.Width;
                        float extraZPadding = difficultyIndicatorGroup != null ? mission.Difficulty.Value * (difficultyIndicatorGroup.Children.First().Rect.Width + difficultyIndicatorGroup.AbsoluteSpacing) : 0;
                        missionName.Padding = new Vector4(missionName.Padding.X + tickBox.Rect.Width * 1.2f + extraPadding,
                                                          missionName.Padding.Y,
                                                          missionName.Padding.Z + extraZPadding + extraPadding,
                                                          missionName.Padding.W);
                        missionName.CalculateHeightFromText();

                        //spacing
                        new GUIFrame(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform)
                        {
                            MinSize = new Point(0, GUI.IntScale(10))
                        }, style: null);

                        var rewardText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), mission.GetMissionRewardText(Submarine.MainSub), wrap: true, parseRichText: true)
                        {
                            UserData = mission
                        };
                        missionRewardTexts.Add(rewardText);

                        string reputationText = mission.GetReputationRewardText(mission.Locations[0]);
                        new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), reputationText, wrap: true, parseRichText: true);

                        new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), missionTextContent.RectTransform), mission.Description, wrap: true, parseRichText: true);
                    }
                    missionPanel.RectTransform.MinSize = new Point(0, (int)(missionTextContent.Children.Sum(c => c.Rect.Height + missionTextContent.AbsoluteSpacing) / missionTextContent.RectTransform.RelativeSize.Y) + GUI.IntScale(0));
                    foreach (GUIComponent child in missionTextContent.Children)
                    {
                        if (child is GUITextBlock textBlock)
                        {
                            textBlock.Color             = textBlock.SelectedColor = textBlock.HoverColor = Color.Transparent;
                            textBlock.SelectedTextColor = textBlock.HoverTextColor = textBlock.TextColor;
                        }
                    }
                    missionPanel.OnAddedToGUIUpdateList = (c) =>
                    {
                        missionTextContent.Children.ForEach(child => child.State = c.State);
                        if (missionTextContent.FindChild("difficulty", recursive: true) is GUILayoutGroup group)
                        {
                            group.State = c.State;
                        }
                    };

                    if (mission != availableMissions.Last())
                    {
                        new GUIFrame(new RectTransform(new Vector2(1.0f, 0.01f), missionList.Content.RectTransform), style: "HorizontalLine")
                        {
                            CanBeFocused = false
                        };
                    }
                }
                if (prevSelectedLocation == selectedLocation)
                {
                    missionList.BarScroll = prevMissionListScroll;
                    missionList.UpdateDimensions();
                    missionList.UpdateScrollBarSize();
                }
            }
            var destination = connection.OtherLocation(currentDisplayLocation);

            UpdateMaxMissions(destination);

            var buttonArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.05f), content.RectTransform), isHorizontal: true);

            new GUITextBlock(new RectTransform(new Vector2(0.6f, 1.0f), buttonArea.RectTransform), "", font: GUI.Style.SubHeadingFont)
            {
                TextGetter = () =>
                {
                    return(TextManager.AddPunctuation(':', TextManager.Get("Missions"), $"{Campaign.NumberOfMissionsAtLocation(destination)}/{Campaign.Settings.MaxMissionCount}"));
                }
            };

            StartButton = new GUIButton(new RectTransform(new Vector2(0.4f, 1.0f), buttonArea.RectTransform),
                                        TextManager.Get("StartCampaignButton"), style: "GUIButtonLarge")
            {
                OnClicked = (GUIButton btn, object obj) =>
                {
                    if (missionList.Content.FindChild(c => c is GUITickBox tickBox && tickBox.Selected, recursive: true) == null &&
                        missionList.Content.Children.Any(c => c.UserData is Mission))
                    {
                        var noMissionVerification = new GUIMessageBox(string.Empty, TextManager.Get("nomissionprompt"), new string[] { TextManager.Get("yes"), TextManager.Get("no") });
                        noMissionVerification.Buttons[0].OnClicked = (btn, userdata) =>
                        {
                            StartRound?.Invoke();
                            noMissionVerification.Close();
                            return(true);
                        };
                        noMissionVerification.Buttons[1].OnClicked = noMissionVerification.Close;
                    }
Exemplo n.º 24
0
        private bool SelectTab(GUIButton button, object obj)
        {
            if (obj is Tab)
            {
                if (GameMain.Config.UnsavedSettings)
                {
                    var applyBox = new GUIMessageBox(
                        TextManager.Get("ApplySettingsLabel"),
                        TextManager.Get("ApplySettingsQuestion"),
                        new string[] { TextManager.Get("ApplySettingsYes"), TextManager.Get("ApplySettingsNo") });
                    applyBox.Buttons[0].UserData  = (Tab)obj;
                    applyBox.Buttons[0].OnClicked = (tb, userdata) =>
                    {
                        applyBox.Close(button, userdata);
                        ApplySettings(button, userdata);
                        return(true);
                    };

                    applyBox.Buttons[1].UserData  = (Tab)obj;
                    applyBox.Buttons[1].OnClicked = (tb, userdata) =>
                    {
                        applyBox.Close(button, userdata);
                        DiscardSettings(button, userdata);
                        return(true);
                    };
                    return(false);
                }

                selectedTab = (Tab)obj;

                switch (selectedTab)
                {
                case Tab.NewGame:
                    campaignSetupUI.CreateDefaultSaveName();
                    campaignSetupUI.UpdateTutorialSelection();
                    break;

                case Tab.LoadGame:
                    campaignSetupUI.UpdateLoadMenu();
                    break;

                case Tab.Settings:
                    GameMain.Config.ResetSettingsFrame();
                    menuTabs[(int)Tab.Settings] = GameMain.Config.SettingsFrame;
                    break;

                case Tab.JoinServer:
                    GameMain.ServerListScreen.Select();
                    break;

                case Tab.HostServer:
                    break;

                case Tab.Tutorials:
                    break;

                case Tab.CharacterEditor:
                    Submarine.MainSub = null;
                    GameMain.CharacterEditorScreen.Select();
                    break;

                case Tab.SubmarineEditor:
                    GameMain.SubEditorScreen.Select();
                    break;

                case Tab.QuickStartDev:
                    QuickStart();
                    break;

                case Tab.SteamWorkshop:
                    if (!Steam.SteamManager.IsInitialized)
                    {
                        return(false);
                    }
                    GameMain.SteamWorkshopScreen.Select();
                    break;
                }
            }
            else
            {
                selectedTab = 0;
            }

            if (button != null)
            {
                button.Selected = true;
            }
            ResetButtonStates(button);

            return(true);
        }