private void CheckContentPackage() { foreach (ContentPackage contentPackage in Config.SelectedContentPackages) { var exePaths = contentPackage.GetFilesOfType(ContentType.Executable); if (exePaths.Any() && AppDomain.CurrentDomain.FriendlyName != exePaths.First()) { var msgBox = new GUIMessageBox(TextManager.Get("Error"), TextManager.Get("IncorrectExe") .Replace("[selectedpackage]", contentPackage.Name) .Replace("[exename]", exePaths.First()), new string[] { TextManager.Get("Yes"), TextManager.Get("No") }); msgBox.Buttons[0].OnClicked += (_, userdata) => { string fullPath = Path.GetFullPath(exePaths.First()); Process.Start(fullPath); Exit(); return(true); }; msgBox.Buttons[1].OnClicked = msgBox.Close; break; } } }
public CombatMission(MissionPrefab prefab, Location[] locations) : base(prefab, locations) { descriptions = new string[] { TextManager.Get("MissionDescriptionNeutral." + prefab.TextIdentifier, true) ?? prefab.ConfigElement.GetAttributeString("descriptionneutral", ""), TextManager.Get("MissionDescription1." + prefab.TextIdentifier, true) ?? prefab.ConfigElement.GetAttributeString("description1", ""), TextManager.Get("MissionDescription2." + prefab.TextIdentifier, true) ?? prefab.ConfigElement.GetAttributeString("description2", "") }; for (int i = 0; i < descriptions.Length; i++) { for (int n = 0; n < 2; n++) { descriptions[i] = descriptions[i].Replace("[location" + (n + 1) + "]", locations[n].Name); } } teamNames = new string[] { TextManager.Get("MissionTeam1." + prefab.TextIdentifier, true) ?? prefab.ConfigElement.GetAttributeString("teamname1", "Team A"), TextManager.Get("MissionTeam2." + prefab.TextIdentifier, true) ?? prefab.ConfigElement.GetAttributeString("teamname2", "Team B") }; }
public Biome(XElement element) { Identifier = element.GetAttributeString("identifier", ""); OldIdentifier = element.GetAttributeString("oldidentifier", null); if (string.IsNullOrEmpty(Identifier)) { Identifier = element.GetAttributeString("name", ""); DebugConsole.ThrowError("Error in biome \"" + Identifier + "\": identifier missing, using name as the identifier."); } DisplayName = TextManager.Get("biomename." + Identifier, returnNull: true) ?? element.GetAttributeString("name", "Biome") ?? TextManager.Get("biomename." + Identifier); Description = TextManager.Get("biomedescription." + Identifier, returnNull: true) ?? element.GetAttributeString("description", "") ?? TextManager.Get("biomedescription." + Identifier); IsEndBiome = element.GetAttributeBool("endbiome", false); AllowedZones.AddRange(element.GetAttributeIntArray("AllowedZones", new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })); }
public override void Start() { base.Start(); CrewManager.InitSinglePlayerRound(); foreach (Submarine submarine in Submarine.Loaded) { submarine.NeutralizeBallast(); } if (SpawnOutpost) { GenerateOutpost(Submarine.MainSub); } if (TriggeredEvent != null) { scriptedEvent = new List <Event> { TriggeredEvent.CreateInstance() }; GameMain.GameSession.EventManager.PinnedEvent = scriptedEvent.Last(); createEventButton = new GUIButton(new RectTransform(new Point(128, 64), GUI.Canvas, Anchor.TopCenter) { ScreenSpaceOffset = new Point(0, 32) }, TextManager.Get("create")) { OnClicked = delegate { scriptedEvent.Add(TriggeredEvent.CreateInstance()); GameMain.GameSession.EventManager.PinnedEvent = scriptedEvent.Last(); return(true); } }; } }
public IEnumerable <object> DoLoading(IEnumerable <object> loader) { drawn = false; LoadState = null; selectedTip = TextManager.Get("LoadingScreenTip", true); while (!drawn) { yield return(CoroutineStatus.Running); } CoroutineManager.StartCoroutine(loader); yield return(CoroutineStatus.Running); while (CoroutineManager.IsCoroutineRunning(loader.ToString())) { yield return(CoroutineStatus.Running); } LoadState = 100.0f; yield return(CoroutineStatus.Success); }
private void FilterServers() { serverList.RemoveChild(serverList.FindChild("noresults")); foreach (GUIComponent child in serverList.children) { if (!(child.UserData is ServerInfo)) { continue; } ServerInfo serverInfo = (ServerInfo)child.UserData; child.Visible = serverInfo.ServerName.ToLowerInvariant().Contains(searchBox.Text.ToLowerInvariant()) && (!filterPassword.Selected || !serverInfo.HasPassword) && (!filterFull.Selected || serverInfo.PlayerCount < serverInfo.MaxPlayers) && (!filterEmpty.Selected || serverInfo.PlayerCount > 0); } if (serverList.children.All(c => !c.Visible)) { new GUITextBlock(new Rectangle(0, 0, 0, 20), TextManager.Get("NoMatchingServers"), "", serverList).UserData = "noresults"; } }
private void CreateSettingsFrame() { settingsFrame = new GUIFrame(new Rectangle(0, 0, 500, 500), null, Alignment.Center, ""); new GUITextBlock(new Rectangle(0, -30, 0, 30), TextManager.Get("Settings"), "", Alignment.TopCenter, Alignment.TopCenter, settingsFrame, false, GUI.LargeFont); int x = 0, y = 10; new GUITextBlock(new Rectangle(0, y, 20, 20), TextManager.Get("Resolution"), "", Alignment.TopLeft, Alignment.TopLeft, settingsFrame); var resolutionDD = new GUIDropDown(new Rectangle(0, y + 20, 180, 20), "", "", settingsFrame); resolutionDD.OnSelected = SelectResolution; var supportedModes = new List <DisplayMode>(); foreach (DisplayMode mode in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes) { if (supportedModes.FirstOrDefault(m => m.Width == mode.Width && m.Height == mode.Height) != null) { continue; } resolutionDD.AddItem(mode.Width + "x" + mode.Height, mode); supportedModes.Add(mode); if (GraphicsWidth == mode.Width && GraphicsHeight == mode.Height) { resolutionDD.SelectItem(mode); } } if (resolutionDD.SelectedItemData == null) { resolutionDD.SelectItem(GraphicsAdapter.DefaultAdapter.SupportedDisplayModes.Last()); } y += 50; //var fullScreenTick = new GUITickBox(new Rectangle(x, y, 20, 20), "Fullscreen", Alignment.TopLeft, settingsFrame); //fullScreenTick.OnSelected = ToggleFullScreen; //fullScreenTick.Selected = FullScreenEnabled; new GUITextBlock(new Rectangle(x, y, 20, 20), TextManager.Get("DisplayMode"), "", Alignment.TopLeft, Alignment.TopLeft, settingsFrame); var displayModeDD = new GUIDropDown(new Rectangle(x, y + 20, 180, 20), "", "", settingsFrame); displayModeDD.AddItem(TextManager.Get("Fullscreen"), WindowMode.Fullscreen); displayModeDD.AddItem(TextManager.Get("Windowed"), WindowMode.Windowed); displayModeDD.AddItem(TextManager.Get("BorderlessWindowed"), WindowMode.BorderlessWindowed); displayModeDD.SelectItem(GameMain.Config.WindowMode); displayModeDD.OnSelected = (guiComponent, obj) => { UnsavedSettings = true; GameMain.Config.WindowMode = (WindowMode)guiComponent.UserData; return(true); }; y += 70; GUITickBox vsyncTickBox = new GUITickBox(new Rectangle(0, y, 20, 20), TextManager.Get("EnableVSync"), Alignment.CenterY | Alignment.Left, settingsFrame); vsyncTickBox.OnSelected = (GUITickBox box) => { VSyncEnabled = !VSyncEnabled; GameMain.GraphicsDeviceManager.SynchronizeWithVerticalRetrace = VSyncEnabled; GameMain.GraphicsDeviceManager.ApplyChanges(); UnsavedSettings = true; return(true); }; vsyncTickBox.Selected = VSyncEnabled; y += 70; new GUITextBlock(new Rectangle(0, y, 100, 20), TextManager.Get("SoundVolume"), "", settingsFrame); GUIScrollBar soundScrollBar = new GUIScrollBar(new Rectangle(0, y + 20, 150, 20), "", 0.1f, settingsFrame); soundScrollBar.BarScroll = SoundVolume; soundScrollBar.OnMoved = ChangeSoundVolume; soundScrollBar.Step = 0.05f; new GUITextBlock(new Rectangle(0, y + 40, 100, 20), TextManager.Get("MusicVolume"), "", settingsFrame); GUIScrollBar musicScrollBar = new GUIScrollBar(new Rectangle(0, y + 60, 150, 20), "", 0.1f, settingsFrame); musicScrollBar.BarScroll = MusicVolume; musicScrollBar.OnMoved = ChangeMusicVolume; musicScrollBar.Step = 0.05f; x = 200; y = 10; new GUITextBlock(new Rectangle(x, y, 20, 20), TextManager.Get("ContentPackage"), "", Alignment.TopLeft, Alignment.TopLeft, settingsFrame); var contentPackageDD = new GUIDropDown(new Rectangle(x, y + 20, 200, 20), "", "", settingsFrame); contentPackageDD.OnSelected = SelectContentPackage; foreach (ContentPackage contentPackage in ContentPackage.list) { contentPackageDD.AddItem(contentPackage.Name, contentPackage); if (SelectedContentPackage == contentPackage) { contentPackageDD.SelectItem(contentPackage); } } y += 50; new GUITextBlock(new Rectangle(x, y, 100, 20), TextManager.Get("Controls"), "", settingsFrame); y += 30; var inputNames = Enum.GetNames(typeof(InputType)); for (int i = 0; i < inputNames.Length; i++) { new GUITextBlock(new Rectangle(x, y, 100, 18), inputNames[i] + ": ", "", Alignment.TopLeft, Alignment.CenterLeft, settingsFrame); var keyBox = new GUITextBox(new Rectangle(x + 100, y, 120, 18), null, null, Alignment.TopLeft, Alignment.CenterLeft, "", settingsFrame); keyBox.Text = keyMapping[i].ToString(); keyBox.UserData = i; keyBox.OnSelected += KeyBoxSelected; keyBox.SelectedColor = Color.Gold * 0.3f; y += 20; } applyButton = new GUIButton(new Rectangle(0, 0, 100, 20), TextManager.Get("ApplySettingsButton"), Alignment.BottomRight, "", settingsFrame); applyButton.OnClicked = ApplyClicked; }
public void PurchaseUpgrade(UpgradePrefab prefab, UpgradeCategory category) { if (!CanUpgradeSub()) { DebugConsole.ThrowError("Cannot upgrade when switching to another submarine."); return; } int price = prefab.Price.GetBuyprice(GetUpgradeLevel(prefab, category), Campaign.Map?.CurrentLocation); int currentLevel = GetUpgradeLevel(prefab, category); if (currentLevel + 1 > prefab.MaxLevel) { DebugConsole.ThrowError($"Tried to purchase \"{prefab.Name}\" over the max level! ({currentLevel + 1} > {prefab.MaxLevel}). The transaction has been cancelled."); return; } if (price < 0) { Location?location = Campaign.Map?.CurrentLocation; LogError($"Upgrade price is less than 0! ({price})", new Dictionary <string, object?> { { "Level", currentLevel }, { "Saved Level", GetRealUpgradeLevel(prefab, category) }, { "Upgrade", $"{category.Identifier}.{prefab.Identifier}" }, { "Location", location?.Type }, { "Reputation", $"{location?.Reputation?.Value} / {location?.Reputation?.MaxReputation}" }, { "Base Price", prefab.Price.BasePrice } }); } if (Campaign.Money > price) { if (GameMain.NetworkMember == null || GameMain.NetworkMember.IsServer) { // only make the NPC speak if more than 5 minutes have passed since the last purchased service if (lastUpgradeSpeak == DateTime.MinValue || lastUpgradeSpeak.AddMinutes(5) < DateTime.Now) { UpgradeNPCSpeak(TextManager.Get("Dialog.UpgradePurchased"), Campaign.IsSinglePlayer); lastUpgradeSpeak = DateTime.Now; } } Campaign.Money -= price; spentMoney += price; PurchasedUpgrade?upgrade = FindMatchingUpgrade(prefab, category); #if CLIENT DebugLog($"CLIENT: Purchased level {GetUpgradeLevel(prefab, category) + 1} {category.Name}.{prefab.Name} for ${price}", GUI.Style.Orange); #endif if (upgrade == null) { PendingUpgrades.Add(new PurchasedUpgrade(prefab, category)); } else { upgrade.Level++; } #if CLIENT // tell the server that this item is yet to be paid for server side PurchasedUpgrades.Add(new PurchasedUpgrade(prefab, category)); #endif OnUpgradesChanged?.Invoke(); } else { DebugConsole.ThrowError("Tried to purchase an upgrade with insufficient funds, the transaction has not been completed.\n" + $"Upgrade: {prefab.Name}, Cost: {price}, Have: {Campaign.Money}"); } }
public GUIComponent CreateInfoFrame(GUIFrame frame, bool returnParent, Sprite permissionIcon = null) { var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.874f, 0.58f), frame.RectTransform, Anchor.TopCenter) { RelativeOffset = new Vector2(0.0f, 0.05f) }) { RelativeSpacing = 0.05f //Stretch = true }; var headerArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.322f), paddedFrame.RectTransform), isHorizontal: true); new GUICustomComponent(new RectTransform(new Vector2(0.425f, 1.0f), headerArea.RectTransform), onDraw: (sb, component) => DrawInfoFrameCharacterIcon(sb, component.Rect)); ScalableFont font = paddedFrame.Rect.Width < 280 ? GUI.SmallFont : GUI.Font; var headerTextArea = new GUILayoutGroup(new RectTransform(new Vector2(0.575f, 1.0f), headerArea.RectTransform)) { RelativeSpacing = 0.02f, Stretch = true }; Color?nameColor = null; if (Job != null) { nameColor = Job.Prefab.UIColor; } GUITextBlock characterNameBlock = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), headerTextArea.RectTransform), ToolBox.LimitString(Name, GUI.Font, headerTextArea.Rect.Width), textColor: nameColor, font: GUI.Font) { ForceUpperCase = true, Padding = Vector4.Zero }; if (permissionIcon != null) { Point iconSize = permissionIcon.SourceRect.Size; int iconWidth = (int)((float)characterNameBlock.Rect.Height / iconSize.Y * iconSize.X); new GUIImage(new RectTransform(new Point(iconWidth, characterNameBlock.Rect.Height), characterNameBlock.RectTransform) { AbsoluteOffset = new Point(-iconWidth - 2, 0) }, permissionIcon) { IgnoreLayoutGroups = true }; } if (Job != null) { new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), headerTextArea.RectTransform), Job.Name, textColor: Job.Prefab.UIColor, font: font) { Padding = Vector4.Zero }; } if (personalityTrait != null) { new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), headerTextArea.RectTransform), TextManager.AddPunctuation(':', TextManager.Get("PersonalityTrait"), TextManager.Get("personalitytrait." + personalityTrait.Name.Replace(" ", ""))), font: font) { Padding = Vector4.Zero }; } if (Job != null && (Character == null || !Character.IsDead)) { var skillsArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.63f), paddedFrame.RectTransform, Anchor.BottomCenter, Pivot.BottomCenter)) { Stretch = true }; var skills = Job.Skills; skills.Sort((s1, s2) => - s1.Level.CompareTo(s2.Level)); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), skillsArea.RectTransform), TextManager.AddPunctuation(':', TextManager.Get("skills"), string.Empty), font: font) { Padding = Vector4.Zero }; foreach (Skill skill in skills) { Color textColor = Color.White * (0.5f + skill.Level / 200.0f); var skillName = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), skillsArea.RectTransform), TextManager.Get("SkillName." + skill.Identifier), textColor: textColor, font: font) { Padding = Vector4.Zero }; float modifiedSkillLevel = skill.Level; if (Character != null) { modifiedSkillLevel = Character.GetSkillLevel(skill.Identifier); } if (!MathUtils.NearlyEqual(MathF.Round(modifiedSkillLevel), MathF.Round(skill.Level))) { int skillChange = (int)MathF.Round(modifiedSkillLevel - skill.Level); string changeText = $"{(skillChange > 0 ? "+" : "") + skillChange}"; new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), skillName.RectTransform), $"{(int)skill.Level} ({changeText})", textColor: textColor, font: font, textAlignment: Alignment.CenterRight); } else { new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), skillName.RectTransform), ((int)skill.Level).ToString(), textColor: textColor, font: font, textAlignment: Alignment.CenterRight); } } } else if (Character != null && Character.IsDead) { var deadArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.63f), paddedFrame.RectTransform, Anchor.BottomCenter, Pivot.BottomCenter)) { Stretch = true }; string deadDescription = TextManager.AddPunctuation(':', TextManager.Get("deceased") + "\n" + Character.CauseOfDeath.Affliction?.CauseOfDeathDescription ?? TextManager.AddPunctuation(':', TextManager.Get("CauseOfDeath"), TextManager.Get("CauseOfDeath." + Character.CauseOfDeath.Type.ToString()))); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), deadArea.RectTransform), deadDescription, textColor: GUI.Style.Red, font: font, textAlignment: Alignment.TopLeft) { Padding = Vector4.Zero }; } if (returnParent) { return(frame); } else { return(paddedFrame); } }
public void CheckForErrors() { List <string> errorMsgs = new List <string>(); if (!Hull.hullList.Any()) { errorMsgs.Add(TextManager.Get("NoHullsWarning")); } foreach (Item item in Item.ItemList) { if (item.GetComponent <Items.Components.Vent>() == null) { continue; } if (!item.linkedTo.Any()) { errorMsgs.Add(TextManager.Get("DisconnectedVentsWarning")); break; } } if (!WayPoint.WayPointList.Any(wp => wp.ShouldBeSaved && wp.SpawnType == SpawnType.Path)) { errorMsgs.Add(TextManager.Get("NoWaypointsWarning")); } if (WayPoint.WayPointList.Find(wp => wp.SpawnType == SpawnType.Cargo) == null) { errorMsgs.Add(TextManager.Get("NoCargoSpawnpointWarning")); } if (!Item.ItemList.Any(it => it.GetComponent <Items.Components.Pump>() != null && it.HasTag("ballast"))) { errorMsgs.Add(TextManager.Get("NoBallastTagsWarning")); } if (Gap.GapList.Any(g => g.linkedTo.Count == 0)) { errorMsgs.Add(TextManager.Get("NonLinkedGapsWarning")); } if (errorMsgs.Any()) { new GUIMessageBox(TextManager.Get("Warning"), string.Join("\n\n", errorMsgs), new Vector2(0.25f, 0.0f), new Point(400, 200)); } foreach (MapEntity e in MapEntity.mapEntityList) { if (Vector2.Distance(e.Position, HiddenSubPosition) > 20000) { //move disabled items (wires, items inside containers) inside the sub if (e is Item item && item.body != null && !item.body.Enabled) { item.SetTransform(ConvertUnits.ToSimUnits(HiddenSubPosition), 0.0f); } } } foreach (MapEntity e in MapEntity.mapEntityList) { if (Vector2.Distance(e.Position, HiddenSubPosition) > 20000) { var msgBox = new GUIMessageBox( TextManager.Get("Warning"), TextManager.Get("FarAwayEntitiesWarning"), new string[] { TextManager.Get("Yes"), TextManager.Get("No") }); msgBox.Buttons[0].OnClicked += (btn, obj) => { GameMain.SubEditorScreen.Cam.Position = e.WorldPosition; return(true); }; msgBox.Buttons[0].OnClicked += msgBox.Close; msgBox.Buttons[1].OnClicked += msgBox.Close; break; } } }
public AfflictionPrefab(XElement element, string filePath, Type type = null) { FilePath = filePath; typeName = type == null?element.Name.ToString() : type.Name; if (typeName == "InternalDamage" && type == null) { type = typeof(Affliction); } Identifier = element.GetAttributeString("identifier", ""); AfflictionType = element.GetAttributeString("type", ""); Name = TextManager.Get("AfflictionName." + Identifier, true) ?? element.GetAttributeString("name", ""); Description = TextManager.Get("AfflictionDescription." + Identifier, true) ?? element.GetAttributeString("description", ""); IsBuff = element.GetAttributeBool("isbuff", false); LimbSpecific = element.GetAttributeBool("limbspecific", false); if (!LimbSpecific) { string indicatorLimbName = element.GetAttributeString("indicatorlimb", "Torso"); if (!Enum.TryParse(indicatorLimbName, out IndicatorLimb)) { DebugConsole.ThrowError("Error in affliction prefab " + Name + " - limb type \"" + indicatorLimbName + "\" not found."); } } ActivationThreshold = element.GetAttributeFloat("activationthreshold", 0.0f); ShowIconThreshold = element.GetAttributeFloat("showiconthreshold", Math.Max(ActivationThreshold, 0.05f)); MaxStrength = element.GetAttributeFloat("maxstrength", 100.0f); ShowInHealthScannerThreshold = element.GetAttributeFloat("showinhealthscannerthreshold", Math.Max(ActivationThreshold, 0.05f)); DamageOverlayAlpha = element.GetAttributeFloat("damageoverlayalpha", 0.0f); BurnOverlayAlpha = element.GetAttributeFloat("burnoverlayalpha", 0.0f); KarmaChangeOnApplied = element.GetAttributeFloat("karmachangeonapplied", 0.0f); CauseOfDeathDescription = TextManager.Get("AfflictionCauseOfDeath." + Identifier, true) ?? element.GetAttributeString("causeofdeathdescription", ""); SelfCauseOfDeathDescription = TextManager.Get("AfflictionCauseOfDeathSelf." + Identifier, true) ?? element.GetAttributeString("selfcauseofdeathdescription", ""); IconColors = element.GetAttributeColorArray("iconcolors", null); AchievementOnRemoved = element.GetAttributeString("achievementonremoved", ""); foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "icon": Icon = new Sprite(subElement); break; case "effect": effects.Add(new Effect(subElement, Name)); break; } } try { if (type == null) { type = Type.GetType("Barotrauma." + typeName, true, true); if (type == null) { DebugConsole.ThrowError("Could not find an affliction class of the type \"" + typeName + "\"."); return; } } } catch { DebugConsole.ThrowError("Could not find an affliction class of the type \"" + typeName + "\"."); type = typeof(Affliction); } constructor = type.GetConstructor(new[] { typeof(AfflictionPrefab), typeof(float) }); }
private static string readyCheckBody(string name) => string.IsNullOrWhiteSpace(name) ? TextManager.Get("readycheck.serverbody") : TextManager.GetWithVariable("readycheck.body", "[player]", name);
public override void End(string endMessage = "") { isRunning = false; bool success = CrewManager.GetCharacters().Any(c => !c.IsDead); crewDead = false; if (success) { if (subsToLeaveBehind == null || leavingSub == null) { DebugConsole.ThrowError("Leaving submarine not selected -> selecting the closest one"); leavingSub = GetLeavingSub(); subsToLeaveBehind = GetSubsToLeaveBehind(leavingSub); } } GameMain.GameSession.EndRound(""); if (success) { if (leavingSub != Submarine.MainSub && !leavingSub.DockedTo.Contains(Submarine.MainSub)) { Submarine.MainSub = leavingSub; GameMain.GameSession.Submarine = leavingSub; foreach (Submarine sub in subsToLeaveBehind) { MapEntity.mapEntityList.RemoveAll(e => e.Submarine == sub && e is LinkedSubmarine); LinkedSubmarine.CreateDummy(leavingSub, sub); } } if (atEndPosition) { Map.MoveToNextLocation(); } else { Map.SelectLocation(-1); } Map.ProgressWorld(); //save and remove all items that are in someone's inventory foreach (Character c in Character.CharacterList) { if (c.Info == null || c.Inventory == null) { continue; } var inventoryElement = new XElement("inventory"); c.SaveInventory(c.Inventory, inventoryElement); c.Info.InventoryData = inventoryElement; c.Inventory?.DeleteAllItems(); } SaveUtil.SaveGame(GameMain.GameSession.SavePath); } if (!success) { var summaryScreen = GUIMessageBox.VisibleBox; if (summaryScreen != null) { summaryScreen = summaryScreen.Children.First(); var buttonArea = summaryScreen.Children.First().FindChild("buttonarea"); buttonArea.ClearChildren(); summaryScreen.RemoveChild(summaryScreen.Children.FirstOrDefault(c => c is GUIButton)); var okButton = new GUIButton(new RectTransform(new Vector2(0.2f, 1.0f), buttonArea.RectTransform), TextManager.Get("LoadGameButton")) { OnClicked = (GUIButton button, object obj) => { GameMain.GameSession.LoadPrevious(); GameMain.LobbyScreen.Select(); GUIMessageBox.MessageBoxes.Remove(GUIMessageBox.VisibleBox); return(true); } }; var quitButton = new GUIButton(new RectTransform(new Vector2(0.2f, 1.0f), buttonArea.RectTransform), TextManager.Get("QuitButton")); quitButton.OnClicked += GameMain.LobbyScreen.QuitToMainMenu; quitButton.OnClicked += (GUIButton button, object obj) => { GUIMessageBox.MessageBoxes.Remove(GUIMessageBox.VisibleBox); return(true); }; quitButton.OnClicked += (GUIButton button, object obj) => { if (ContextualTutorial.Initialized) { ContextualTutorial.Stop(); } return(true); }; } } CrewManager.EndRound(); for (int i = Character.CharacterList.Count - 1; i >= 0; i--) { Character.CharacterList[i].Remove(); } Submarine.Unload(); GameMain.LobbyScreen.Select(); }
private IEnumerable <object> Load(bool isSeparateThread) { if (GameSettings.VerboseLogging) { DebugConsole.NewMessage("LOADING COROUTINE", Color.Lime); } while (TitleScreen.WaitForLanguageSelection) { yield return(CoroutineStatus.Running); } SoundManager = new Sounds.SoundManager(); SoundManager.SetCategoryGainMultiplier("default", Config.SoundVolume, 0); SoundManager.SetCategoryGainMultiplier("ui", Config.SoundVolume, 0); SoundManager.SetCategoryGainMultiplier("waterambience", Config.SoundVolume, 0); SoundManager.SetCategoryGainMultiplier("music", Config.MusicVolume, 0); SoundManager.SetCategoryGainMultiplier("voip", Math.Min(Config.VoiceChatVolume, 1.0f), 0); if (Config.EnableSplashScreen && !ConsoleArguments.Contains("-skipintro")) { var pendingSplashScreens = TitleScreen.PendingSplashScreens; float baseVolume = MathHelper.Clamp(Config.SoundVolume * 2.0f, 0.0f, 1.0f); pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_UTG.webm", baseVolume * 0.5f)); pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_FF.webm", baseVolume)); pendingSplashScreens?.Enqueue(new LoadingScreen.PendingSplashScreen("Content/SplashScreens/Splash_Daedalic.webm", baseVolume * 0.1f)); } //if not loading in a separate thread, wait for the splash screens to finish before continuing the loading //otherwise the videos will look extremely choppy if (!isSeparateThread) { while (TitleScreen.PlayingSplashScreen || TitleScreen.PendingSplashScreens.Count > 0) { yield return(CoroutineStatus.Running); } } GUI.Init(Window, Config.AllEnabledPackages, GraphicsDevice); DebugConsole.Init(); if (Config.AutoUpdateWorkshopItems) { Config.WaitingForAutoUpdate = true; TaskPool.Add("AutoUpdateWorkshopItemsAsync", SteamManager.AutoUpdateWorkshopItemsAsync(), (task) => { bool result = ((Task <bool>)task).Result; Config.WaitingForAutoUpdate = false; }); while (Config.WaitingForAutoUpdate) { yield return(CoroutineStatus.Running); } } #if DEBUG if (Config.ModBreakerMode) { Config.SelectCorePackage(ContentPackage.CorePackages.GetRandom()); foreach (var regularPackage in ContentPackage.RegularPackages) { if (Rand.Range(0.0, 1.0) <= 0.5) { Config.EnableRegularPackage(regularPackage); } else { Config.DisableRegularPackage(regularPackage); } } ContentPackage.SortContentPackages(p => { return(Rand.Int(int.MaxValue)); }); } #endif if (Config.AllEnabledPackages.None()) { DebugConsole.Log("No content packages selected"); } else { DebugConsole.Log("Selected content packages: " + string.Join(", ", Config.AllEnabledPackages.Select(cp => cp.Name))); } #if DEBUG GameSettings.ShowUserStatisticsPrompt = false; GameSettings.SendUserStatistics = false; #endif InitUserStats(); yield return(CoroutineStatus.Running); Debug.WriteLine("sounds"); int i = 0; foreach (object crObj in SoundPlayer.Init()) { CoroutineStatus status = (CoroutineStatus)crObj; if (status == CoroutineStatus.Success) { break; } i++; TitleScreen.LoadState = SoundPlayer.SoundCount == 0 ? 1.0f : Math.Min(40.0f * i / Math.Max(SoundPlayer.SoundCount, 1), 40.0f); yield return(CoroutineStatus.Running); } TitleScreen.LoadState = 40.0f; yield return(CoroutineStatus.Running); LightManager = new Lights.LightManager(base.GraphicsDevice, Content); TitleScreen.LoadState = 41.0f; yield return(CoroutineStatus.Running); GUI.LoadContent(); TitleScreen.LoadState = 42.0f; yield return(CoroutineStatus.Running); TaskPool.Add("InitRelayNetworkAccess", SteamManager.InitRelayNetworkAccess(), (t) => { }); FactionPrefab.LoadFactions(); NPCSet.LoadSets(); CharacterPrefab.LoadAll(); MissionPrefab.Init(); TraitorMissionPrefab.Init(); MapEntityPrefab.Init(); Tutorials.Tutorial.Init(); MapGenerationParams.Init(); LevelGenerationParams.LoadPresets(); CaveGenerationParams.LoadPresets(); OutpostGenerationParams.LoadPresets(); WreckAIConfig.LoadAll(); EventSet.LoadPrefabs(); ItemPrefab.LoadAll(GetFilesOfType(ContentType.Item)); AfflictionPrefab.LoadAll(GetFilesOfType(ContentType.Afflictions)); SkillSettings.Load(GetFilesOfType(ContentType.SkillSettings)); Order.Init(); EventManagerSettings.Init(); BallastFloraPrefab.LoadAll(GetFilesOfType(ContentType.MapCreature)); HintManager.Init(); TitleScreen.LoadState = 50.0f; yield return(CoroutineStatus.Running); StructurePrefab.LoadAll(GetFilesOfType(ContentType.Structure)); TitleScreen.LoadState = 55.0f; yield return(CoroutineStatus.Running); UpgradePrefab.LoadAll(GetFilesOfType(ContentType.UpgradeModules)); TitleScreen.LoadState = 56.0f; yield return(CoroutineStatus.Running); JobPrefab.LoadAll(GetFilesOfType(ContentType.Jobs)); CorpsePrefab.LoadAll(GetFilesOfType(ContentType.Corpses)); NPCConversation.LoadAll(GetFilesOfType(ContentType.NPCConversations)); ItemAssemblyPrefab.LoadAll(); TitleScreen.LoadState = 60.0f; yield return(CoroutineStatus.Running); GameModePreset.Init(); SaveUtil.DeleteDownloadedSubs(); SubmarineInfo.RefreshSavedSubs(); TitleScreen.LoadState = 65.0f; yield return(CoroutineStatus.Running); GameScreen = new GameScreen(GraphicsDeviceManager.GraphicsDevice, Content); TitleScreen.LoadState = 68.0f; yield return(CoroutineStatus.Running); MainMenuScreen = new MainMenuScreen(this); ServerListScreen = new ServerListScreen(); TitleScreen.LoadState = 70.0f; yield return(CoroutineStatus.Running); #if USE_STEAM SteamWorkshopScreen = new SteamWorkshopScreen(); if (SteamManager.IsInitialized) { Steamworks.SteamFriends.OnGameRichPresenceJoinRequested += OnInvitedToGame; Steamworks.SteamFriends.OnGameLobbyJoinRequested += OnLobbyJoinRequested; } #endif SubEditorScreen = new SubEditorScreen(); TitleScreen.LoadState = 75.0f; yield return(CoroutineStatus.Running); ParticleEditorScreen = new ParticleEditorScreen(); TitleScreen.LoadState = 80.0f; yield return(CoroutineStatus.Running); LevelEditorScreen = new LevelEditorScreen(); SpriteEditorScreen = new SpriteEditorScreen(); EventEditorScreen = new EventEditorScreen(); CharacterEditorScreen = new CharacterEditor.CharacterEditorScreen(); CampaignEndScreen = new CampaignEndScreen(); yield return(CoroutineStatus.Running); TitleScreen.LoadState = 85.0f; ParticleManager = new ParticleManager(GameScreen.Cam); ParticleManager.LoadPrefabs(); TitleScreen.LoadState = 88.0f; LevelObjectPrefab.LoadAll(); TitleScreen.LoadState = 90.0f; yield return(CoroutineStatus.Running); DecalManager = new DecalManager(); LocationType.Init(); MainMenuScreen.Select(); foreach (string steamError in SteamManager.InitializationErrors) { new GUIMessageBox(TextManager.Get("Error"), TextManager.Get(steamError)); } TitleScreen.LoadState = 100.0f; hasLoaded = true; if (GameSettings.VerboseLogging) { DebugConsole.NewMessage("LOADING COROUTINE FINISHED", Color.Lime); } yield return(CoroutineStatus.Success); }
public void ShowEditorDisclaimer() { var msgBox = new GUIMessageBox(TextManager.Get("EditorDisclaimerTitle"), TextManager.Get("EditorDisclaimerText")); var linkHolder = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.25f), 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("EditorDisclaimerWikiLink"), TextManager.Get("EditorDisclaimerWikiUrl")), new Pair <string, string>(TextManager.Get("EditorDisclaimerDiscordLink"), TextManager.Get("EditorDisclaimerDiscordUrl")), new Pair <string, string>(TextManager.Get("EditorDisclaimerForumLink"), TextManager.Get("EditorDisclaimerForumUrl")), }; 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); return(true); } }; } msgBox.InnerFrame.RectTransform.MinSize = new Point(0, msgBox.InnerFrame.Rect.Height + linkHolder.Rect.Height + msgBox.Content.AbsoluteSpacing * 2 + 10); Config.EditorDisclaimerShown = true; Config.SaveNewPlayerConfig(); }
public GUIFrame CreateSummaryFrame(string endMessage) { bool singleplayer = GameMain.NetworkMember == null; bool gameOver = gameSession.CrewManager.GetCharacters().All(c => c.IsDead || c.IsUnconscious); bool progress = Submarine.MainSub.AtEndPosition; if (!singleplayer) { SoundPlayer.OverrideMusicType = gameOver ? "crewdead" : "endround"; SoundPlayer.OverrideMusicDuration = 18.0f; } GUIFrame frame = new GUIFrame(new RectTransform(Vector2.One, GUI.Canvas), style: "GUIBackgroundBlocker"); int width = 760, height = 500; GUIFrame innerFrame = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.5f), frame.RectTransform, Anchor.Center, minSize: new Point(width, height))); var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.9f), innerFrame.RectTransform, Anchor.Center)) { Stretch = true, RelativeSpacing = 0.03f }; GUIListBox infoTextBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.7f), paddedFrame.RectTransform)) { Spacing = (int)(5 * GUI.Scale) }; //spacing new GUIFrame(new RectTransform(new Vector2(1.0f, 0.05f), infoTextBox.Content.RectTransform), style: null); string summaryText = TextManager.GetWithVariables(gameOver ? "RoundSummaryGameOver" : (progress ? "RoundSummaryProgress" : "RoundSummaryReturn"), new string[2] { "[sub]", "[location]" }, new string[2] { Submarine.MainSub.Name, progress ? GameMain.GameSession.EndLocation.Name : GameMain.GameSession.StartLocation.Name }); var infoText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoTextBox.Content.RectTransform), summaryText, wrap: true); GUIComponent endText = null; if (!string.IsNullOrWhiteSpace(endMessage)) { endText = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoTextBox.Content.RectTransform), TextManager.GetServerMessage(endMessage), wrap: true); } //don't show the mission info if the mission was not completed and there's no localized "mission failed" text available if (GameMain.GameSession.Mission != null) { string message = GameMain.GameSession.Mission.Completed ? GameMain.GameSession.Mission.SuccessMessage : GameMain.GameSession.Mission.FailureMessage; if (!string.IsNullOrEmpty(message)) { //spacing var spacingTransform = new RectTransform(new Vector2(1.0f, 0.1f), infoTextBox.Content.RectTransform); new GUIFrame(spacingTransform, style: null); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoTextBox.Content.RectTransform), TextManager.AddPunctuation(':', TextManager.Get("Mission"), GameMain.GameSession.Mission.Name), font: GUI.LargeFont); var missionInfo = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoTextBox.Content.RectTransform), message, wrap: true); if (GameMain.GameSession.Mission.Completed && singleplayer) { var missionReward = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), infoTextBox.Content.RectTransform), TextManager.GetWithVariable("MissionReward", "[reward]", GameMain.GameSession.Mission.Reward.ToString())); } } } new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), TextManager.Get("RoundSummaryCrewStatus"), font: GUI.LargeFont); GUIListBox characterListBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.4f), paddedFrame.RectTransform, minSize: new Point(0, 75)), isHorizontal: true); foreach (CharacterInfo characterInfo in gameSession.CrewManager.GetCharacterInfos()) { if (GameMain.GameSession.Mission is CombatMission && characterInfo.TeamID != GameMain.GameSession.WinningTeam) { continue; } var characterFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.2f, 1.0f), characterListBox.Content.RectTransform, minSize: new Point(170, 0))) { CanBeFocused = false, Stretch = true }; characterInfo.CreateCharacterFrame(characterFrame, characterInfo.Job != null ? (characterInfo.Name + '\n' + "(" + characterInfo.Job.Name + ")") : characterInfo.Name, null); string statusText = TextManager.Get("StatusOK"); Color statusColor = Color.DarkGreen; Character character = characterInfo.Character; if (character == null || character.IsDead) { if (characterInfo.CauseOfDeath == null) { statusText = TextManager.Get("CauseOfDeathDescription.Unknown"); } else if (characterInfo.CauseOfDeath.Type == CauseOfDeathType.Affliction && characterInfo.CauseOfDeath.Affliction == null) { string errorMsg = "Character \"" + character.Name + "\" had an invalid cause of death (the type of the cause of death was Affliction, but affliction was not specified)."; DebugConsole.ThrowError(errorMsg); GameAnalyticsManager.AddErrorEventOnce("RoundSummary:InvalidCauseOfDeath", GameAnalyticsSDK.Net.EGAErrorSeverity.Error, errorMsg); statusText = TextManager.Get("CauseOfDeathDescription.Unknown"); } else { statusText = characterInfo.CauseOfDeath.Type == CauseOfDeathType.Affliction ? characterInfo.CauseOfDeath.Affliction.CauseOfDeathDescription : TextManager.Get("CauseOfDeathDescription." + characterInfo.CauseOfDeath.Type.ToString()); } statusColor = Color.DarkRed; } else { if (character.IsUnconscious) { statusText = TextManager.Get("Unconscious"); statusColor = Color.DarkOrange; } else if (character.Vitality / character.MaxVitality < 0.8f) { statusText = TextManager.Get("Injured"); statusColor = Color.DarkOrange; } } var textHolder = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.2f), characterFrame.RectTransform, Anchor.BottomCenter), style: "InnerGlow", color: statusColor); new GUITextBlock(new RectTransform(Vector2.One, textHolder.RectTransform, Anchor.Center), statusText, Color.White, textAlignment: Alignment.Center, wrap: true, font: GUI.SmallFont, style: null); } new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.1f), paddedFrame.RectTransform), isHorizontal: true, childAnchor: Anchor.BottomRight) { RelativeSpacing = 0.05f, UserData = "buttonarea" }; paddedFrame.Recalculate(); foreach (GUIComponent child in infoTextBox.Content.Children) { child.CanBeFocused = false; if (child is GUITextBlock textBlock) { textBlock.CalculateHeightFromText(); } } return(frame); }
public void SetOrder(Order order, string option, int priority, Character orderGiver, bool speak) { if (character.IsDead) { #if DEBUG DebugConsole.ThrowError("Attempted to set an order for a dead character"); #else return; #endif } ClearIgnored(); if (order == null || order.Identifier == "dismissed") { if (!string.IsNullOrEmpty(option)) { if (CurrentOrders.Any(o => o.MatchesDismissedOrder(option))) { var dismissedOrderInfo = CurrentOrders.First(o => o.MatchesDismissedOrder(option)); CurrentOrders.Remove(dismissedOrderInfo); } } else { CurrentOrders.Clear(); } } // Make sure the order priorities reflect those set by the player for (int i = CurrentOrders.Count - 1; i >= 0; i--) { var currentOrder = CurrentOrders[i]; if (currentOrder.Objective == null || currentOrder.MatchesOrder(order, option)) { CurrentOrders.RemoveAt(i); continue; } var currentOrderInfo = character.GetCurrentOrder(currentOrder.Order, currentOrder.OrderOption); if (currentOrderInfo.HasValue) { int currentPriority = currentOrderInfo.Value.ManualPriority; if (currentOrder.ManualPriority != currentPriority) { CurrentOrders[i] = new OrderInfo(currentOrder, currentPriority); } } else { CurrentOrders.RemoveAt(i); } } var newCurrentOrder = CreateObjective(order, option, orderGiver, isAutonomous: false); if (newCurrentOrder != null) { CurrentOrders.Add(new OrderInfo(order, option, priority, newCurrentOrder)); } if (!HasOrders()) { // Recreate objectives, because some of them may be removed, if impossible to complete (e.g. due to path finding) CreateAutonomousObjectives(); } else { // This should be redundant, because all the objectives are reset when they are selected as active. newCurrentOrder?.Reset(); if (speak && character.IsOnPlayerTeam) { character.Speak(TextManager.Get("DialogAffirmative"), null, 1.0f); //if (speakRoutine != null) //{ // CoroutineManager.StopCoroutines(speakRoutine); //} //speakRoutine = CoroutineManager.InvokeAfter(() => //{ // if (GameMain.GameSession == null || Level.Loaded == null) { return; } // if (newCurrentOrder != null && character.SpeechImpediment < 100.0f) // { // if (newCurrentOrder is AIObjectiveRepairItems repairItems && repairItems.Targets.None()) // { // character.Speak(TextManager.Get("DialogNoRepairTargets"), null, 3.0f, "norepairtargets"); // } // else if (newCurrentOrder is AIObjectiveChargeBatteries chargeBatteries && chargeBatteries.Targets.None()) // { // character.Speak(TextManager.Get("DialogNoBatteries"), null, 3.0f, "nobatteries"); // } // else if (newCurrentOrder is AIObjectiveExtinguishFires extinguishFires && extinguishFires.Targets.None()) // { // character.Speak(TextManager.Get("DialogNoFire"), null, 3.0f, "nofire"); // } // else if (newCurrentOrder is AIObjectiveFixLeaks fixLeaks && fixLeaks.Targets.None()) // { // character.Speak(TextManager.Get("DialogNoLeaks"), null, 3.0f, "noleaks"); // } // else if (newCurrentOrder is AIObjectiveFightIntruders fightIntruders && fightIntruders.Targets.None()) // { // character.Speak(TextManager.Get("DialogNoEnemies"), null, 3.0f, "noenemies"); // } // else if (newCurrentOrder is AIObjectiveRescueAll rescueAll && rescueAll.Targets.None()) // { // character.Speak(TextManager.Get("DialogNoRescueTargets"), null, 3.0f, "norescuetargets"); // } // else if (newCurrentOrder is AIObjectivePumpWater pumpWater && pumpWater.Targets.None()) // { // character.Speak(TextManager.Get("DialogNoPumps"), null, 3.0f, "nopumps"); // } // } //}, 3); } } }
private bool TryEndRound(Submarine leavingSub) { if (leavingSub == null) { return(false); } this.leavingSub = leavingSub; subsToLeaveBehind = GetSubsToLeaveBehind(leavingSub); atEndPosition = leavingSub.AtEndPosition; if (subsToLeaveBehind.Any()) { string msg = TextManager.Get(subsToLeaveBehind.Count == 1 ? "LeaveSubBehind" : "LeaveSubsBehind"); var msgBox = new GUIMessageBox(TextManager.Get("Warning"), msg, new string[] { TextManager.Get("Yes"), TextManager.Get("No") }); msgBox.Buttons[0].OnClicked += (btn, userdata) => { EndRound(leavingSub); return(true); }; msgBox.Buttons[0].OnClicked += msgBox.Close; msgBox.Buttons[0].UserData = Submarine.Loaded.FindAll(s => !subsToLeaveBehind.Contains(s)); msgBox.Buttons[1].OnClicked += msgBox.Close; } else { EndRound(leavingSub); } return(true); }
public override void Update(float deltaTime) { if (isFinished) { return; } isRunning = true; var targets1 = ParentEvent.GetTargets(Target1Tag); if (!targets1.Any()) { return; } foreach (Entity e1 in targets1) { if (DisableInCombat && IsInCombat(e1)) { continue; } if (DisableIfTargetIncapacitated && e1 is Character character1 && (character1.IsDead || character1.IsIncapacitated)) { continue; } if (!string.IsNullOrEmpty(TargetModuleType)) { if (IsCloseEnoughToHull(e1, out Hull hull)) { Trigger(e1, hull); return; } continue; } var targets2 = ParentEvent.GetTargets(Target2Tag); foreach (Entity e2 in targets2) { if (e1 == e2) { continue; } if (DisableInCombat && IsInCombat(e2)) { continue; } if (DisableIfTargetIncapacitated && e2 is Character character2 && (character2.IsDead || character2.IsIncapacitated)) { continue; } if (WaitForInteraction) { Character player = null; Character npc = null; Item item = null; npcOrItem?.TryGet(out npc); npcOrItem?.TryGet(out item); if (e1 is Character char1) { if (char1.IsBot) { npc ??= char1; } else { player = char1; } } else { item ??= e1 as Item; } if (e2 is Character char2) { if (char2.IsBot) { npc ??= char2; } else { player = char2; } } else { item ??= e2 as Item; } if (player != null) { if (npc != null) { if (npc.CampaignInteractionType != CampaignMode.InteractionType.Examine) { npcOrItem = npc; npc.CampaignInteractionType = CampaignMode.InteractionType.Examine; npc.RequireConsciousnessForCustomInteract = false; #if CLIENT npc.SetCustomInteract( (speaker, player) => { if (e1 == speaker) { Trigger(speaker, player); } else { Trigger(player, speaker); } }, TextManager.GetWithVariable("CampaignInteraction.Examine", "[key]", GameMain.Config.KeyBindText(InputType.Use))); #else npc.SetCustomInteract( (speaker, player) => { if (e1 == speaker) { Trigger(speaker, player); } else { Trigger(player, speaker); } }, TextManager.Get("CampaignInteraction.Talk")); GameMain.NetworkMember.CreateEntityEvent(npc, new object[] { NetEntityEvent.Type.AssignCampaignInteraction }); #endif } return; } else if (item != null) { npcOrItem = item; item.CampaignInteractionType = CampaignMode.InteractionType.Examine; if (player.SelectedConstruction == item || player.Inventory != null && player.Inventory.Contains(item) || (player.FocusedItem == item && player.IsKeyHit(InputType.Use))) { Trigger(e1, e2); return; } } } } else { Vector2 pos1 = e1.WorldPosition; Vector2 pos2 = e2.WorldPosition; distance = Vector2.Distance(pos1, pos2); if (((e1 is MapEntity m1) && Submarine.RectContains(m1.WorldRect, pos2)) || ((e2 is MapEntity m2) && Submarine.RectContains(m2.WorldRect, pos1)) || Vector2.DistanceSquared(pos1, pos2) < Radius * Radius) { Trigger(e1, e2); return; } } } } }
private void CreateUI() { Frame.ClearChildren(); leftPanel = new GUIFrame(new RectTransform(new Vector2(0.125f, 1.0f), Frame.RectTransform) { MinSize = new Point(150, 0) }, style: "GUIFrameLeft"); var paddedLeftPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.95f), leftPanel.RectTransform, Anchor.CenterLeft) { RelativeOffset = new Vector2(0.02f, 0.0f) }) { RelativeSpacing = 0.01f, Stretch = true }; rightPanel = new GUIFrame(new RectTransform(new Vector2(0.25f, 1.0f), Frame.RectTransform, Anchor.TopRight) { MinSize = new Point(350, 0) }, style: "GUIFrameRight"); var paddedRightPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.95f), rightPanel.RectTransform, Anchor.Center) { RelativeOffset = new Vector2(0.02f, 0.0f) }) { RelativeSpacing = 0.01f, Stretch = true }; var saveAllButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.03f), paddedRightPanel.RectTransform), TextManager.Get("editor.saveall")) { OnClicked = (btn, obj) => { SerializeAll(); return(true); } }; var serializeToClipBoardButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.03f), paddedRightPanel.RectTransform), TextManager.Get("editor.copytoclipboard")) { OnClicked = (btn, obj) => { SerializeToClipboard(selectedPrefab); return(true); } }; emitter = new Emitter(); var emitterEditorContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.25f), paddedRightPanel.RectTransform), style: null); var emitterEditor = new SerializableEntityEditor(emitterEditorContainer.RectTransform, emitter, false, true, elementHeight: 20, titleFont: GUI.SubHeadingFont); emitterEditor.RectTransform.RelativeSize = Vector2.One; emitterEditorContainer.RectTransform.Resize(new Point(emitterEditorContainer.RectTransform.NonScaledSize.X, emitterEditor.ContentHeight), false); var listBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.6f), paddedRightPanel.RectTransform)); var filterArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.03f), paddedLeftPanel.RectTransform) { MinSize = new Point(0, 20) }, isHorizontal: true) { Stretch = true, UserData = "filterarea" }; filterLabel = new GUITextBlock(new RectTransform(Vector2.One, filterArea.RectTransform), TextManager.Get("serverlog.filter"), font: GUI.Font) { IgnoreLayoutGroups = true }; filterBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), filterArea.RectTransform), font: GUI.Font); filterBox.OnTextChanged += (textBox, text) => { FilterEmitters(text); return(true); }; new GUIButton(new RectTransform(new Vector2(0.05f, 1.0f), filterArea.RectTransform, scaleBasis: ScaleBasis.BothHeight), style: "GUICancelButton") { OnClicked = (btn, userdata) => { FilterEmitters(""); filterBox.Text = ""; filterBox.Flash(Color.White); return(true); } }; prefabList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.8f), paddedLeftPanel.RectTransform)); prefabList.OnSelected += (GUIComponent component, object obj) => { selectedPrefab = obj as ParticlePrefab; listBox.ClearChildren(); new SerializableEntityEditor(listBox.Content.RectTransform, selectedPrefab, false, true, elementHeight: 20, titleFont: GUI.SubHeadingFont); //listBox.Content.RectTransform.NonScaledSize = particlePrefabEditor.RectTransform.NonScaledSize; //listBox.UpdateScrollBarSize(); return(true); }; if (GameMain.ParticleManager != null) { RefreshPrefabList(); } }
public void CreatePreviewWindow(GUIComponent parent) { var upperPart = new GUILayoutGroup(new RectTransform(new Vector2(1, 0.5f), parent.RectTransform, Anchor.Center, Pivot.BottomCenter)); var descriptionBox = new GUIListBox(new RectTransform(new Vector2(1, 0.5f), parent.RectTransform, Anchor.Center, Pivot.TopCenter)) { ScrollBarVisible = true, Spacing = 5 }; if (PreviewImage == null) { new GUITextBlock(new RectTransform(new Vector2(1.0f, 1), upperPart.RectTransform), TextManager.Get(SavedSubmarines.Contains(this) ? "SubPreviewImageNotFound" : "SubNotDownloaded")); } else { var submarinePreviewBackground = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 1.0f), upperPart.RectTransform)) { Color = Color.Black }; new GUIImage(new RectTransform(new Vector2(1.0f, 1.0f), submarinePreviewBackground.RectTransform), PreviewImage, scaleToFit: true); } //space new GUIFrame(new RectTransform(new Vector2(1.0f, 0.03f), descriptionBox.Content.RectTransform), style: null); new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform), Name, font: GUI.LargeFont, wrap: true) { ForceUpperCase = true, CanBeFocused = false }; float leftPanelWidth = 0.6f; float rightPanelWidth = 0.4f / leftPanelWidth; ScalableFont font = descriptionBox.Rect.Width < 350 ? GUI.SmallFont : GUI.Font; Vector2 realWorldDimensions = Dimensions * Physics.DisplayToRealWorldRatio; if (realWorldDimensions != Vector2.Zero) { string dimensionsStr = TextManager.GetWithVariables("DimensionsFormat", new string[2] { "[width]", "[height]" }, new string[2] { ((int)realWorldDimensions.X).ToString(), ((int)realWorldDimensions.Y).ToString() }); var dimensionsText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), descriptionBox.Content.RectTransform), TextManager.Get("Dimensions"), textAlignment: Alignment.TopLeft, font: font, wrap: true) { CanBeFocused = false }; new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), dimensionsText.RectTransform, Anchor.TopRight, Pivot.TopLeft), dimensionsStr, textAlignment: Alignment.TopLeft, font: font, wrap: true) { CanBeFocused = false }; dimensionsText.RectTransform.MinSize = new Point(0, dimensionsText.Children.First().Rect.Height); } if (RecommendedCrewSizeMax > 0) { var crewSizeText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), descriptionBox.Content.RectTransform), TextManager.Get("RecommendedCrewSize"), textAlignment: Alignment.TopLeft, font: font, wrap: true) { CanBeFocused = false }; new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), crewSizeText.RectTransform, Anchor.TopRight, Pivot.TopLeft), RecommendedCrewSizeMin + " - " + RecommendedCrewSizeMax, textAlignment: Alignment.TopLeft, font: font, wrap: true) { CanBeFocused = false }; crewSizeText.RectTransform.MinSize = new Point(0, crewSizeText.Children.First().Rect.Height); } if (!string.IsNullOrEmpty(RecommendedCrewExperience)) { var crewExperienceText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), descriptionBox.Content.RectTransform), TextManager.Get("RecommendedCrewExperience"), textAlignment: Alignment.TopLeft, font: font, wrap: true) { CanBeFocused = false }; new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), crewExperienceText.RectTransform, Anchor.TopRight, Pivot.TopLeft), TextManager.Get(RecommendedCrewExperience), textAlignment: Alignment.TopLeft, font: font, wrap: true) { CanBeFocused = false }; crewExperienceText.RectTransform.MinSize = new Point(0, crewExperienceText.Children.First().Rect.Height); } if (RequiredContentPackages.Any()) { var contentPackagesText = new GUITextBlock(new RectTransform(new Vector2(leftPanelWidth, 0), descriptionBox.Content.RectTransform), TextManager.Get("RequiredContentPackages"), textAlignment: Alignment.TopLeft, font: font) { CanBeFocused = false }; new GUITextBlock(new RectTransform(new Vector2(rightPanelWidth, 0.0f), contentPackagesText.RectTransform, Anchor.TopRight, Pivot.TopLeft), string.Join(", ", RequiredContentPackages), textAlignment: Alignment.TopLeft, font: font, wrap: true) { CanBeFocused = false }; contentPackagesText.RectTransform.MinSize = new Point(0, contentPackagesText.Children.First().Rect.Height); } GUITextBlock.AutoScaleAndNormalize(descriptionBox.Content.Children.Where(c => c is GUITextBlock).Cast <GUITextBlock>()); //space new GUIFrame(new RectTransform(new Vector2(1.0f, 0.05f), descriptionBox.Content.RectTransform), style: null); if (!string.IsNullOrEmpty(Description)) { new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform), TextManager.Get("SaveSubDialogDescription", fallBackTag: "WorkshopItemDescription"), font: GUI.Font, wrap: true) { CanBeFocused = false, ForceUpperCase = true }; } new GUITextBlock(new RectTransform(new Vector2(1, 0), descriptionBox.Content.RectTransform), Description, font: font, wrap: true) { CanBeFocused = false }; }
private GUIComponent CreateEditingHUD(bool inGame = false) { int width = 450, height = 120; int x = GameMain.GraphicsWidth / 2 - width / 2, y = 30; editingHUD = new GUIFrame(new RectTransform(new Point(width, height), GUI.Canvas) { ScreenSpaceOffset = new Point(x, y) }) { UserData = this }; var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.8f), editingHUD.RectTransform, Anchor.Center)) { Stretch = true, RelativeSpacing = 0.05f }; new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), TextManager.Get("LinkedSub"), font: GUI.LargeFont); if (!inGame) { new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), TextManager.Get("LinkLinkedSub"), textColor: Color.Yellow, font: GUI.SmallFont); } var pathContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.2f), paddedFrame.RectTransform), isHorizontal: true); var pathBox = new GUITextBox(new RectTransform(new Vector2(0.8f, 1.0f), pathContainer.RectTransform), filePath, font: GUI.SmallFont); var reloadButton = new GUIButton(new RectTransform(new Vector2(0.2f, 1.0f), pathContainer.RectTransform), TextManager.Get("ReloadLinkedSub")) { OnClicked = Reload, UserData = pathBox, ToolTip = TextManager.Get("ReloadLinkedSubTooltip") }; PositionEditingHUD(); return(editingHUD); }
public GUIFrame CreateInfoFrame(GUIFrame frame) { var paddedFrame = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.7f), frame.RectTransform, Anchor.TopCenter) { RelativeOffset = new Vector2(0.0f, 0.1f) }) { Stretch = true, RelativeSpacing = 0.03f }; var headerArea = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.4f), paddedFrame.RectTransform), isHorizontal: true) { RelativeSpacing = 0.05f, Stretch = true }; new GUICustomComponent(new RectTransform(new Vector2(0.25f, 1.0f), headerArea.RectTransform), onDraw: (sb, component) => DrawIcon(sb, component.Rect.Center.ToVector2(), targetAreaSize: component.Rect.Size.ToVector2())); ScalableFont font = paddedFrame.Rect.Width < 280 ? GUI.SmallFont : GUI.Font; var headerTextArea = new GUILayoutGroup(new RectTransform(new Vector2(0.75f, 1.0f), headerArea.RectTransform)) { RelativeSpacing = 0.05f, Stretch = true }; Color?nameColor = null; if (Job != null) { nameColor = Job.Prefab.UIColor; } new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), headerTextArea.RectTransform), Name, textColor: nameColor, font: GUI.LargeFont) { Padding = Vector4.Zero, AutoScale = true }; if (Job != null) { new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), headerTextArea.RectTransform), Job.Name, textColor: Job.Prefab.UIColor, font: font); } if (personalityTrait != null) { new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), headerTextArea.RectTransform), TextManager.Get("PersonalityTrait") + ": " + personalityTrait.Name, font: font); } //spacing new GUIFrame(new RectTransform(new Vector2(1.0f, 0.05f), paddedFrame.RectTransform), style: null); if (Job != null) { var skills = Job.Skills; skills.Sort((s1, s2) => - s1.Level.CompareTo(s2.Level)); new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), TextManager.Get("Skills") + ":", font: font); foreach (Skill skill in skills) { Color textColor = Color.White * (0.5f + skill.Level / 200.0f); var skillName = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), paddedFrame.RectTransform), TextManager.Get("SkillName." + skill.Identifier), textColor: textColor, font: font); new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), skillName.RectTransform), ((int)skill.Level).ToString(), textColor: textColor, font: font, textAlignment: Alignment.CenterRight); } } return(frame); }
public GUIMessageBox(string headerText, string text, string[] buttons, Vector2?relativeSize = null, Point?minSize = null, Alignment textAlignment = Alignment.TopLeft, Type type = Type.Default, string tag = "", Sprite icon = null, string iconStyle = "", Sprite backgroundIcon = null) : base(new RectTransform(GUI.Canvas.RelativeSize, GUI.Canvas, Anchor.Center), style: GUI.Style.GetComponentStyle("GUIMessageBox." + type) != null ? "GUIMessageBox." + type : "GUIMessageBox") { int width = (int)(DefaultWidth * (type == Type.Default ? 1.0f : 1.5f)), height = 0; if (relativeSize.HasValue) { width = (int)(GameMain.GraphicsWidth * relativeSize.Value.X); height = (int)(GameMain.GraphicsHeight * relativeSize.Value.Y); } if (minSize.HasValue) { width = Math.Max(width, minSize.Value.X); if (height > 0) { height = Math.Max(height, minSize.Value.Y); } } if (backgroundIcon != null) { BackgroundIcon = new GUIImage(new RectTransform(backgroundIcon.size.ToPoint(), RectTransform), backgroundIcon) { IgnoreLayoutGroups = true, Color = Color.Transparent }; } Anchor anchor = type switch { Type.InGame => Anchor.TopCenter, Type.Vote => Anchor.TopRight, _ => Anchor.Center }; InnerFrame = new GUIFrame(new RectTransform(new Point(width, height), RectTransform, anchor) { IsFixedSize = false }, style: null); if (type == Type.Vote) { int offset = GUI.IntScale(64); InnerFrame.RectTransform.ScreenSpaceOffset = new Point(-offset, offset); CanBeFocused = false; } GUI.Style.Apply(InnerFrame, "", this); this.type = type; Tag = tag; if (type == Type.Default || type == Type.Vote) { Content = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.85f), InnerFrame.RectTransform, Anchor.Center)) { AbsoluteSpacing = 5 }; Header = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform), headerText, font: GUI.SubHeadingFont, textAlignment: Alignment.Center, wrap: true); GUI.Style.Apply(Header, "", this); Header.RectTransform.MinSize = new Point(0, Header.Rect.Height); if (!string.IsNullOrWhiteSpace(text)) { Text = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform), text, textAlignment: textAlignment, wrap: true); GUI.Style.Apply(Text, "", this); Text.RectTransform.NonScaledSize = Text.RectTransform.MinSize = Text.RectTransform.MaxSize = new Point(Text.Rect.Width, Text.Rect.Height); Text.RectTransform.IsFixedSize = true; } var buttonContainer = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.15f), Content.RectTransform, Anchor.BottomCenter), childAnchor: Anchor.TopCenter) { AbsoluteSpacing = 5, IgnoreLayoutGroups = true }; int buttonSize = 35; var buttonStyle = GUI.Style.GetComponentStyle("GUIButton"); if (buttonStyle != null && buttonStyle.Height.HasValue) { buttonSize = buttonStyle.Height.Value; } buttonContainer.RectTransform.NonScaledSize = buttonContainer.RectTransform.MinSize = buttonContainer.RectTransform.MaxSize = new Point(buttonContainer.Rect.Width, (int)((buttonSize + 5) * buttons.Length)); buttonContainer.RectTransform.IsFixedSize = true; if (height == 0) { height += Header.Rect.Height + Content.AbsoluteSpacing; height += (Text == null ? 0 : Text.Rect.Height) + Content.AbsoluteSpacing; height += buttonContainer.Rect.Height + 20; if (minSize.HasValue) { height = Math.Max(height, minSize.Value.Y); } InnerFrame.RectTransform.NonScaledSize = new Point(InnerFrame.Rect.Width, (int)Math.Max(height / Content.RectTransform.RelativeSize.Y, height + (int)(50 * GUI.yScale))); Content.RectTransform.NonScaledSize = new Point(Content.Rect.Width, height); } Buttons = new List <GUIButton>(buttons.Length); for (int i = 0; i < buttons.Length; i++) { var button = new GUIButton(new RectTransform(new Vector2(0.6f, 1.0f / buttons.Length), buttonContainer.RectTransform), buttons[i]); Buttons.Add(button); } } else if (type == Type.InGame) { InnerFrame.RectTransform.AbsoluteOffset = new Point(0, GameMain.GraphicsHeight); alwaysVisible = true; CanBeFocused = false; AutoClose = true; GUI.Style.Apply(InnerFrame, "", this); var horizontalLayoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(0.98f, 0.95f), InnerFrame.RectTransform, Anchor.Center), isHorizontal: true, childAnchor: Anchor.CenterLeft) { Stretch = true, RelativeSpacing = 0.02f }; if (icon != null) { Icon = new GUIImage(new RectTransform(new Vector2(0.2f, 0.95f), horizontalLayoutGroup.RectTransform), icon, scaleToFit: true); } else if (iconStyle != string.Empty) { Icon = new GUIImage(new RectTransform(new Vector2(0.2f, 0.95f), horizontalLayoutGroup.RectTransform), iconStyle, scaleToFit: true); } Content = new GUILayoutGroup(new RectTransform(new Vector2(Icon != null ? 0.65f : 0.85f, 1.0f), horizontalLayoutGroup.RectTransform)); var buttonContainer = new GUIFrame(new RectTransform(new Vector2(0.15f, 1.0f), horizontalLayoutGroup.RectTransform), style: null); Buttons = new List <GUIButton>(1) { new GUIButton(new RectTransform(new Vector2(0.3f, 0.5f), buttonContainer.RectTransform, Anchor.Center), style: "UIToggleButton") { OnClicked = Close } }; 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) { Buttons[0].ToolTip = TextManager.ParseInputTypes($"{TextManager.Get("Close")} ([InputType.{closeInput.Value}])"); Buttons[0].OnAddedToGUIUpdateList += (GUIComponent component) => { if (!closing && openState >= 1.0f && PlayerInput.KeyHit(closeInput.Value)) { GUIButton btn = component as GUIButton; btn?.OnClicked(btn, btn.UserData); btn?.Flash(GUI.Style.Green); } }; } Header = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform), headerText, wrap: true); GUI.Style.Apply(Header, "", this); Header.RectTransform.MinSize = new Point(0, Header.Rect.Height); if (!string.IsNullOrWhiteSpace(text)) { Text = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.0f), Content.RectTransform), text, textAlignment: textAlignment, wrap: true); GUI.Style.Apply(Text, "", this); Content.Recalculate(); Text.RectTransform.NonScaledSize = Text.RectTransform.MinSize = Text.RectTransform.MaxSize = new Point(Text.Rect.Width, Text.Rect.Height); Text.RectTransform.IsFixedSize = true; if (string.IsNullOrWhiteSpace(headerText)) { Content.ChildAnchor = Anchor.Center; } } if (height == 0) { height += Header.Rect.Height + Content.AbsoluteSpacing; height += (Text == null ? 0 : Text.Rect.Height) + Content.AbsoluteSpacing; if (minSize.HasValue) { height = Math.Max(height, minSize.Value.Y); } InnerFrame.RectTransform.NonScaledSize = new Point(InnerFrame.Rect.Width, (int)Math.Max(height / Content.RectTransform.RelativeSize.Y, height + (int)(50 * GUI.yScale))); Content.RectTransform.NonScaledSize = new Point(Content.Rect.Width, height); } Buttons[0].RectTransform.MaxSize = new Point((int)(0.4f * Buttons[0].Rect.Y), Buttons[0].Rect.Y); } MessageBoxes.Add(this); }
public void RecreateFrameContents() { var info = CharacterInfo; HeadSelectionList = null; parentComponent.ClearChildren(); ClearSprites(); float contentWidth = HasIcon ? 0.75f : 1.0f; var listBox = new GUIListBox( new RectTransform(new Vector2(contentWidth, 1.0f), parentComponent.RectTransform, Anchor.CenterLeft)) { CanBeFocused = false, CanTakeKeyBoardFocus = false }; var content = listBox.Content; info.LoadHeadAttachments(); if (HasIcon) { info.CreateIcon( new RectTransform(new Vector2(0.25f, 1.0f), parentComponent.RectTransform, Anchor.CenterRight) { RelativeOffset = new Vector2(-0.01f, 0.0f) }); } RectTransform createItemRectTransform(string labelTag, float width = 0.6f) { var layoutGroup = new GUILayoutGroup(new RectTransform(new Vector2(1.0f, 0.166f), content.RectTransform)); var label = new GUITextBlock(new RectTransform(new Vector2(1.0f, 0.5f), layoutGroup.RectTransform), TextManager.Get(labelTag), font: GUI.SubHeadingFont); var bottomItem = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.5f), layoutGroup.RectTransform), style: null); return(new RectTransform(new Vector2(width, 1.0f), bottomItem.RectTransform, Anchor.Center)); } RectTransform genderItemRT = createItemRectTransform("Gender", 1.0f); GUILayoutGroup genderContainer = new GUILayoutGroup(genderItemRT, isHorizontal: true) { Stretch = true, RelativeSpacing = 0.05f }; void createGenderButton(Gender gender) { new GUIButton(new RectTransform(new Vector2(1.0f, 1.0f), genderContainer.RectTransform), TextManager.Get(gender.ToString()), style: "ListBoxElement") { UserData = gender, OnClicked = OpenHeadSelection, Selected = info.Gender == gender }; } createGenderButton(Gender.Male); createGenderButton(Gender.Female); int countAttachmentsOfType(WearableType wearableType) => info.FilterByTypeAndHeadID( info.FilterElementsByGenderAndRace(info.Wearables, info.Head.gender, info.Head.race), wearableType, info.HeadSpriteId).Count(); List <GUIScrollBar> attachmentSliders = new List <GUIScrollBar>(); void createAttachmentSlider(int initialValue, WearableType wearableType) { int attachmentCount = countAttachmentsOfType(wearableType); if (attachmentCount > 0) { var labelTag = wearableType == WearableType.FaceAttachment ? "FaceAttachment.Accessories" : $"FaceAttachment.{wearableType}"; var sliderItemRT = createItemRectTransform(labelTag); var slider = new GUIScrollBar(sliderItemRT, style: "GUISlider") { Range = new Vector2(0, attachmentCount), StepValue = 1, OnMoved = (bar, scroll) => SwitchAttachment(bar, wearableType), OnReleased = OnSliderReleased, BarSize = 1.0f / (float)(attachmentCount + 1) }; slider.BarScrollValue = initialValue; attachmentSliders.Add(slider); } } createAttachmentSlider(info.HairIndex, WearableType.Hair); createAttachmentSlider(info.BeardIndex, WearableType.Beard); createAttachmentSlider(info.MoustacheIndex, WearableType.Moustache); createAttachmentSlider(info.FaceAttachmentIndex, WearableType.FaceAttachment); void createColorSelector(string labelTag, IEnumerable <(Color Color, float Commonness)> options, Func <Color> getter, Action <Color> setter) { var selectorItemRT = createItemRectTransform(labelTag, 0.4f); var dropdown = new GUIDropDown(selectorItemRT) { AllowNonText = true }; var listBoxSize = dropdown.ListBox.RectTransform.RelativeSize; dropdown.ListBox.RectTransform.RelativeSize = new Vector2(listBoxSize.X * 1.75f, listBoxSize.Y); var dropdownButton = dropdown.GetChild <GUIButton>(); var buttonFrame = new GUIFrame( new RectTransform(Vector2.One * 0.7f, dropdownButton.RectTransform, Anchor.CenterLeft) { RelativeOffset = new Vector2(0.05f, 0.0f) }, style: null); Color?previewingColor = null; dropdown.OnSelected = (component, color) => { previewingColor = null; setter((Color)color); buttonFrame.Color = getter(); buttonFrame.HoverColor = getter(); return(true); }; buttonFrame.Color = getter(); buttonFrame.HoverColor = getter(); dropdown.ListBox.UseGridLayout = true; foreach (var option in options) { var optionElement = new GUIFrame( new RectTransform(new Vector2(0.25f, 1.0f / 3.0f), dropdown.ListBox.Content.RectTransform), style: "ListBoxElement") { UserData = option.Color, CanBeFocused = true }; var colorElement = new GUIFrame( new RectTransform(Vector2.One * 0.75f, optionElement.RectTransform, Anchor.Center, scaleBasis: ScaleBasis.Smallest), style: null) { Color = option.Color, HoverColor = option.Color, OutlineColor = Color.Lerp(Color.Black, option.Color, 0.5f), CanBeFocused = false }; } var childToSelect = dropdown.ListBox.Content.FindChild(c => (Color)c.UserData == getter()); dropdown.Select(dropdown.ListBox.Content.GetChildIndex(childToSelect)); //The following exists to track mouseover to preview colors before selecting them new GUICustomComponent(new RectTransform(Vector2.One, buttonFrame.RectTransform), onUpdate: (deltaTime, component) => { if (GUI.MouseOn is GUIFrame { Parent: { } p } hoveredFrame&& dropdown.ListBox.Content.IsParentOf(hoveredFrame)) { previewingColor ??= getter(); Color color = (Color)(dropdown.ListBox.Content.FindChild(c => c == hoveredFrame || c.IsParentOf(hoveredFrame))?.UserData ?? dropdown.SelectedData ?? getter()); setter(color); buttonFrame.Color = getter(); buttonFrame.HoverColor = getter(); }
public ParticleEditorScreen() { cam = new Camera(); leftPanel = new GUIFrame(new RectTransform(new Vector2(0.07f, 1.0f), Frame.RectTransform) { MinSize = new Point(150, 0) }, style: "GUIFrameLeft"); var paddedLeftPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.9f, 0.95f), leftPanel.RectTransform, Anchor.CenterLeft) { RelativeOffset = new Vector2(0.02f, 0.0f) }) { Stretch = true }; rightPanel = new GUIFrame(new RectTransform(new Vector2(0.25f, 1.0f), Frame.RectTransform, Anchor.TopRight) { MinSize = new Point(450, 0) }, style: "GUIFrameRight"); var paddedRightPanel = new GUILayoutGroup(new RectTransform(new Vector2(0.95f, 0.95f), rightPanel.RectTransform, Anchor.Center) { RelativeOffset = new Vector2(0.02f, 0.0f) }) { Stretch = true, RelativeSpacing = 0.01f }; var saveAllButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.03f), paddedRightPanel.RectTransform), TextManager.Get("ParticleEditorSaveAll")) { OnClicked = (btn, obj) => { SerializeAll(); return(true); } }; var serializeToClipBoardButton = new GUIButton(new RectTransform(new Vector2(1.0f, 0.03f), paddedRightPanel.RectTransform), TextManager.Get("ParticleEditorCopyToClipboard")) { OnClicked = (btn, obj) => { SerializeToClipboard(selectedPrefab); return(true); } }; emitter = new Emitter(); var emitterEditorContainer = new GUIFrame(new RectTransform(new Vector2(1.0f, 0.25f), paddedRightPanel.RectTransform), style: null); var emitterEditor = new SerializableEntityEditor(emitterEditorContainer.RectTransform, emitter, false, true, elementHeight: 20); emitterEditor.RectTransform.RelativeSize = Vector2.One; emitterEditorContainer.RectTransform.Resize(new Point(emitterEditorContainer.RectTransform.NonScaledSize.X, emitterEditor.ContentHeight), false); var listBox = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.6f), paddedRightPanel.RectTransform)); prefabList = new GUIListBox(new RectTransform(new Vector2(1.0f, 0.8f), paddedLeftPanel.RectTransform)); prefabList.OnSelected += (GUIComponent component, object obj) => { selectedPrefab = obj as ParticlePrefab; listBox.ClearChildren(); particlePrefabEditor = new SerializableEntityEditor(listBox.Content.RectTransform, selectedPrefab, false, true, elementHeight: 20); //listBox.Content.RectTransform.NonScaledSize = particlePrefabEditor.RectTransform.NonScaledSize; //listBox.UpdateScrollBarSize(); return(true); }; }
private void RefundUpgrades() { DebugConsole.Log($"Refunded {spentMoney} marks in pending upgrades."); if (spentMoney > 0) { #if CLIENT GUIMessageBox msgBox = new GUIMessageBox(TextManager.Get("UpgradeRefundTitle"), TextManager.Get("UpgradeRefundBody"), new[] { TextManager.Get("Ok") }); msgBox.Buttons[0].OnClicked += msgBox.Close; #endif } Campaign.Money += spentMoney; spentMoney = 0; PendingUpgrades.Clear(); PurchasedUpgrades.Clear(); }
protected override void Act(float deltaTime) { if (character.LockHands) { Abandon = true; return; } targetItem = character.Inventory.FindItemByTag(gearTag, true); if (targetItem == null || !character.HasEquippedItem(targetItem)) { TryAddSubObjective(ref getDivingGear, () => { if (targetItem == null) { character.Speak(TextManager.Get("DialogGetDivingGear"), null, 0.0f, "getdivinggear", 30.0f); } return(new AIObjectiveGetItem(character, gearTag, objectiveManager, equip: true) { AllowStealing = true, AllowToFindDivingGear = false, AllowDangerousPressure = true }); }, onAbandon: () => Abandon = true, onCompleted: () => RemoveSubObjective(ref getDivingGear)); } else { if (!EjectEmptyTanks(character, targetItem, out var containedItems)) { #if DEBUG DebugConsole.ThrowError($"{character.Name}: AIObjectiveFindDivingGear failed - the item \"" + targetItem + "\" has no proper inventory"); #endif Abandon = true; return; } if (containedItems.None(it => it != null && it.HasTag(OXYGEN_SOURCE) && it.Condition > MIN_OXYGEN)) { // No valid oxygen source loaded. // Seek oxygen that has min 10% condition left. TryAddSubObjective(ref getOxygen, () => { if (!HumanAIController.HasItem(character, "oxygensource", out _, conditionPercentage: 10)) { character.Speak(TextManager.Get("DialogGetOxygenTank"), null, 0, "getoxygentank", 30.0f); } return(new AIObjectiveContainItem(character, OXYGEN_SOURCE, targetItem.GetComponent <ItemContainer>(), objectiveManager, spawnItemIfNotFound: character.TeamID == CharacterTeamType.FriendlyNPC) { AllowToFindDivingGear = false, AllowDangerousPressure = true, ConditionLevel = MIN_OXYGEN }); }, onAbandon: () => { // Try to seek any oxygen sources. TryAddSubObjective(ref getOxygen, () => { return(new AIObjectiveContainItem(character, OXYGEN_SOURCE, targetItem.GetComponent <ItemContainer>(), objectiveManager, spawnItemIfNotFound: character.TeamID == CharacterTeamType.FriendlyNPC) { AllowToFindDivingGear = false, AllowDangerousPressure = true }); }, onAbandon: () => Abandon = true, onCompleted: () => RemoveSubObjective(ref getOxygen)); }, onCompleted: () => RemoveSubObjective(ref getOxygen)); } } }
private LocationType(XElement element) { Identifier = element.GetAttributeString("identifier", element.Name.ToString()); Name = TextManager.Get("LocationName." + Identifier); nameFormats = TextManager.GetAll("LocationNameFormat." + Identifier); UseInMainMenu = element.GetAttributeBool("useinmainmenu", false); string nameFile = element.GetAttributeString("namefile", "Content/Map/locationNames.txt"); try { names = File.ReadAllLines(nameFile).ToList(); } catch (Exception e) { DebugConsole.ThrowError("Failed to read name file for location type \"" + Identifier + "\"!", e); names = new List <string>() { "Name file not found" }; } string[] commonnessPerZoneStrs = element.GetAttributeStringArray("commonnessperzone", new string[] { "" }); foreach (string commonnessPerZoneStr in commonnessPerZoneStrs) { string[] splitCommonnessPerZone = commonnessPerZoneStr.Split(':'); if (splitCommonnessPerZone.Length != 2 || !int.TryParse(splitCommonnessPerZone[0].Trim(), out int zoneIndex) || !float.TryParse(splitCommonnessPerZone[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out float zoneCommonness)) { DebugConsole.ThrowError("Failed to read commonness values for location type \"" + Identifier + "\" - commonness should be given in the format \"zone0index: zone0commonness, zone1index: zone1commonness\""); break; } CommonnessPerZone[zoneIndex] = zoneCommonness; } hireableJobs = new List <Tuple <JobPrefab, float> >(); foreach (XElement subElement in element.Elements()) { switch (subElement.Name.ToString().ToLowerInvariant()) { case "hireable": string jobIdentifier = subElement.GetAttributeString("identifier", ""); JobPrefab jobPrefab = null; if (jobIdentifier == "") { DebugConsole.ThrowError("Error in location type \"" + Identifier + "\" - hireable jobs should be configured using identifiers instead of names."); jobIdentifier = subElement.GetAttributeString("name", ""); jobPrefab = JobPrefab.List.Find(jp => jp.Name.ToLowerInvariant() == jobIdentifier.ToLowerInvariant()); } else { jobPrefab = JobPrefab.List.Find(jp => jp.Identifier.ToLowerInvariant() == jobIdentifier.ToLowerInvariant()); } if (jobPrefab == null) { DebugConsole.ThrowError("Error in in location type " + Identifier + " - could not find a job with the identifier \"" + jobIdentifier + "\"."); continue; } float jobCommonness = subElement.GetAttributeFloat("commonness", 1.0f); totalHireableWeight += jobCommonness; Tuple <JobPrefab, float> hireableJob = new Tuple <JobPrefab, float>(jobPrefab, jobCommonness); hireableJobs.Add(hireableJob); break; case "symbol": symbolSprite = new Sprite(subElement); SpriteColor = subElement.GetAttributeColor("color", Color.White); break; case "changeto": CanChangeTo.Add(new LocationTypeChange(Identifier, subElement)); break; case "portrait": var portrait = new Sprite(subElement, lazyLoad: true); if (portrait != null) { portraits.Add(portrait); } break; } } }
public GUIComponent CreateEditingHUD(bool inGame = false) { int heightScaled = (int)(20 * GUI.Scale); editingHUD = new GUIFrame(new RectTransform(new Vector2(0.3f, 0.25f), GUI.Canvas, Anchor.CenterRight) { MinSize = new Point(400, 0) }) { UserData = this }; GUIListBox listBox = new GUIListBox(new RectTransform(new Vector2(0.95f, 0.8f), editingHUD.RectTransform, Anchor.Center), style: null) { CanTakeKeyBoardFocus = false }; var editor = new SerializableEntityEditor(listBox.Content.RectTransform, this, inGame, showName: true, titleFont: GUI.LargeFont) { UserData = this }; if (Submarine.MainSub?.Info?.Type == SubmarineType.OutpostModule) { GUITickBox tickBox = new GUITickBox(new RectTransform(new Point(listBox.Content.Rect.Width, 10)), TextManager.Get("sp.structure.removeiflinkedoutpostdoorinuse.name")) { Font = GUI.SmallFont, Selected = RemoveIfLinkedOutpostDoorInUse, ToolTip = TextManager.Get("sp.structure.removeiflinkedoutpostdoorinuse.description"), OnSelected = (tickBox) => { RemoveIfLinkedOutpostDoorInUse = tickBox.Selected; return(true); } }; editor.AddCustomContent(tickBox, 1); } var buttonContainer = new GUILayoutGroup(new RectTransform(new Point(listBox.Content.Rect.Width, heightScaled)), isHorizontal: true) { Stretch = true, RelativeSpacing = 0.01f }; new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("MirrorEntityX")) { ToolTip = TextManager.Get("MirrorEntityXToolTip"), OnClicked = (button, data) => { foreach (MapEntity me in SelectedList) { me.FlipX(relativeToSub: false); } if (!SelectedList.Contains(this)) { FlipX(relativeToSub: false); } return(true); } }; new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("MirrorEntityY")) { ToolTip = TextManager.Get("MirrorEntityYToolTip"), OnClicked = (button, data) => { foreach (MapEntity me in SelectedList) { me.FlipY(relativeToSub: false); } if (!SelectedList.Contains(this)) { FlipY(relativeToSub: false); } return(true); } }; new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("ReloadSprite")) { OnClicked = (button, data) => { Sprite.ReloadXML(); Sprite.ReloadTexture(updateAllSprites: true); return(true); } }; new GUIButton(new RectTransform(new Vector2(0.23f, 1.0f), buttonContainer.RectTransform), TextManager.Get("ResetToPrefab")) { OnClicked = (button, data) => { foreach (MapEntity me in SelectedList) { (me as Item)?.Reset(); (me as Structure)?.Reset(); } if (!SelectedList.Contains(this)) { Reset(); } CreateEditingHUD(); return(true); } }; buttonContainer.RectTransform.Resize(new Point(buttonContainer.Rect.Width, buttonContainer.RectTransform.Children.Max(c => c.MinSize.Y))); buttonContainer.RectTransform.IsFixedSize = true; GUITextBlock.AutoScaleAndNormalize(buttonContainer.Children.Where(c => c is GUIButton).Select(b => ((GUIButton)b).TextBlock)); editor.AddCustomContent(buttonContainer, editor.ContentCount); PositionEditingHUD(); return(editingHUD); }