public MainMenuState(DwarfGame game, GameStateManager stateManager) : base(game, "MainMenuState", stateManager) { ResourceLibrary library = new ResourceLibrary(); IsGameRunning = false; MaintainState = false; }
public LoseState(DwarfGame game, GameStateManager stateManager, PlayState play) : base(game, "EconomyState", stateManager) { Input = new InputManager(); PlayState = play; EnableScreensaver = false; }
public WorldGeneratorState(DwarfGame game, GameStateManager stateManager) : base(game, "WorldGeneratorState", stateManager) { GenerationComplete = false; ImageMutex = new Mutex(); Input = new InputManager(); Settings = new WorldSettings(); }
public GameLoaderState(DwarfGame game, GameStateManager stateManager) : base(game, "GameLoaderState", stateManager) { IsInitialized = false; Games = new List<GameLoadDescriptor>(); ExitThreads = false; Threads = new List<Thread>(); }
public EconomyState(DwarfGame game, GameStateManager stateManager, PlayState play) : base(game, "EconomyState", stateManager) { EdgePadding = 32; Input = new InputManager(); PlayState = play; EnableScreensaver = false; InputManager.KeyReleasedCallback += InputManager_KeyReleasedCallback; }
public GameState(DwarfGame game, string name, GameStateManager stateManager) { EnableScreensaver = true; Game = game; Name = name; StateManager = stateManager; IsInitialized = false; TransitionValue = 0.0f; Transitioning = TransitionMode.Entering; RenderUnderneath = false; IsActiveState = false; }
public CompanyMakerState(DwarfGame game, GameStateManager stateManager) : base(game, "CompanyMakerState", stateManager) { CompanyName = DefaultName; CompanyMotto = DefaultMotto; CompanyLogo = DefaultLogo; CompanyColor = DefaultColor; EdgePadding = 32; Input = new InputManager(); Drawer = new Drawer2D(Game.Content, Game.GraphicsDevice); TextGenerator = new TextGenerator(); }
public OptionsState(DwarfGame game, GameStateManager stateManager) : base(game, "OptionsState", stateManager) { EdgePadding = 32; Input = new InputManager(); Categories = new Dictionary<string, GroupBox>(); DisplayModes = new Dictionary<string, DisplayMode>(); AAModes = new Dictionary<string, int>(); AAModes["None"] = 0; AAModes["FXAA"] = -1; AAModes["2x MSAA"] = 2; AAModes["4x MSAA"] = 4; AAModes["16x MSAA"] = 16; }
public static void PopState(bool enterNext = true) { lock (_mutex) { if (StateStack.Count > 0) { DwarfGame.LogSentryBreadcrumb("GameState", String.Format("Leaving state {0}", StateStack[0].GetType().FullName)); StateStack[0].OnPopped(); StateStack.RemoveAt(0); } if (StateStack.Count > 0 && enterNext) { var state = StateStack.ElementAt(0); NextState = state; NextState.OnEnter(); // Split into OnEnter and OnExposed } } }
/// <summary> /// The main entry point for the application. /// </summary> private static void Main(string[] args) { #if CREATE_CRASH_LOGS try #endif { using (DwarfGame game = new DwarfGame()) { game.Run(); } Program.SignalShutdown(); } #if CREATE_CRASH_LOGS catch (Exception exception) { ProgramData.WriteExceptionLog(exception); } #endif }
public static void Update() { SteamAPI.RunCallbacks(); foreach (var transaction in PendingTransactions) { transaction.Update(); } PendingTransactions.RemoveAll(t => t.Complete); var console = DwarfGame.GetConsoleTile("STEAM"); console.Lines.Clear(); console.Lines.Add("STEAM TRANSACTIONS"); foreach (var transaction in PendingTransactions) { console.Lines.Add(transaction.Transaction.ToString() + " " + transaction.Transaction.Message + "\n"); } console.Invalidate(); }
/// <summary> /// Helper for drawing a texture into the current rendertarget, /// using a custom shader to apply postprocessing effects. /// </summary> private void DrawFullscreenQuad(Texture2D texture, int width, int height, Effect effect, IntermediateBuffer currentBuffer) { // If the user has selected one of the show intermediate buffer options, // we still draw the quad to make sure the image will end up on the screen, // but might need to skip applying the custom pixel shader. if (showBuffer < currentBuffer) { effect = null; } try { DwarfGame.SafeSpriteBatchBegin(0, BlendState.Opaque, null, null, null, effect, Matrix.Identity); DwarfGame.SpriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White); } catch (InvalidOperationException operationException) { Console.Error.WriteLine(operationException.ToString()); return; } DwarfGame.SpriteBatch.End(); }
public WorldGeneratorState(DwarfGame Game, GameStateManager StateManager, WorldGenerationSettings Settings, bool AutoGenerate) : base(Game, "NewWorldGeneratorState", StateManager) { this.AutoGenerate = AutoGenerate; this.Settings = Settings; if (this.Settings == null) { this.Settings = new WorldGenerationSettings() { Width = 512, Height = 512, Name = TextGenerator.GenerateRandom(TextGenerator.GetAtoms(ContentPaths.Text.Templates.worlds)), NumCivilizations = 5, NumFaults = 3, NumRains = 1000, NumVolcanoes = 3, RainfallScale = 1.0f, SeaLevel = 0.17f, TemperatureScale = 1.0f } } ; }
public static void Update(DwarfTime time) { lock (_mutex) { if (NextState != null && NextState.IsInitialized) { if (CurrentState != null) { CurrentState.OnCovered(); } CurrentState = NextState; NextState = null; } if (CurrentState != null && CurrentState.IsInitialized) { CurrentState.Update(time); } if (DwarfGame.IsConsoleVisible) { PerformanceMonitor.SetMetric("MEMORY", BytesToString(System.GC.GetTotalMemory(false))); var statsDisplay = DwarfGame.GetConsoleTile("STATS"); statsDisplay.Lines.Clear(); statsDisplay.Lines.Add("** STATISTICS **"); foreach (var metric in PerformanceMonitor.EnumerateMetrics()) { statsDisplay.Lines.Add(String.Format("{0} {1}", metric.Value.ToString(), metric.Key)); } statsDisplay.Invalidate(); } } }
public override void Update(DwarfGame game, DwarfTime time) { if (World.UserInterface.IsCameraRotationModeActive()) { World.UserInterface.VoxSelector.Enabled = false; World.UserInterface.SetMouse(null); World.UserInterface.BodySelector.Enabled = false; return; } World.UserInterface.VoxSelector.Enabled = true; World.UserInterface.BodySelector.Enabled = false; World.UserInterface.VoxSelector.DrawBox = false; World.UserInterface.VoxSelector.DrawVoxel = true; World.UserInterface.VoxSelector.SelectionType = VoxelSelectionType.SelectEmpty; if (World.UserInterface.IsMouseOverGui) { World.UserInterface.SetMouse(World.UserInterface.MousePointer); } else { World.UserInterface.SetMouse(new Gui.MousePointer("mouse", 1, 4)); } // Don't attempt any camera control if the user is trying to type intoa focus item. if (World.UserInterface.Gui.FocusItem != null && !World.UserInterface.Gui.FocusItem.IsAnyParentTransparent() && !World.UserInterface.Gui.FocusItem.IsAnyParentHidden()) { return; } KeyboardState state = Keyboard.GetState(); bool leftKey = state.IsKeyDown(ControlSettings.Mappings.RotateObjectLeft); bool rightKey = state.IsKeyDown(ControlSettings.Mappings.RotateObjectRight); if (LeftPressed && !leftKey) { if (PathVoxels.Count > 1) { var matched = false; var firstDelta = CompassOrientationHelper.GetVoxelDelta(PathVoxels[0], PathVoxels[1]); var firstConnection = new CompassConnection(OverrideStartingOrientation ? StartingOppositeOrientation : CompassOrientationHelper.Opposite(firstDelta), firstDelta); var orientationDelta = 1; for (; orientationDelta < 8 && !matched; ++orientationDelta) { firstConnection.A = CompassOrientationHelper.Rotate(firstConnection.A, 1); foreach (var piece in Library.EnumerateRailPieces().Where(p => p.CompassConnections.Count != 0)) { for (int j = 0; j < 4 && !matched; ++j) { foreach (var compassConnection in piece.CompassConnections) { if (compassConnection.RotateToPiece((PieceOrientation)j) == firstConnection) { matched = true; } } } if (matched) { break; } } } if (matched) { StartingOppositeOrientation = firstConnection.A; } OverrideStartingOrientation = true; } } if (RightPressed && !rightKey) { if (PathVoxels.Count > 1) { var matched = false; var lastDelta = CompassOrientationHelper.GetVoxelDelta(PathVoxels[PathVoxels.Count - 1], PathVoxels[PathVoxels.Count - 2]); var lastConnection = new CompassConnection(lastDelta, OverrideEndingOrientation ? EndingOppositeOrientation : CompassOrientationHelper.Opposite(lastDelta)); var orientationDelta = 1; for (; orientationDelta < 8 && !matched; ++orientationDelta) { lastConnection.B = CompassOrientationHelper.Rotate(lastConnection.B, 1); foreach (var piece in Library.EnumerateRailPieces().Where(p => p.CompassConnections.Count != 0)) { for (int j = 0; j < 4 && !matched; ++j) { foreach (var compassConnection in piece.CompassConnections) { if (compassConnection.RotateToPiece((PieceOrientation)j) == lastConnection) { matched = true; } } } if (matched) { break; } } } if (matched) { EndingOppositeOrientation = lastConnection.B; } OverrideEndingOrientation = true; } } LeftPressed = leftKey; RightPressed = rightKey; var tint = Color.White; if (!Dragging) { } else { var voxelUnderMouse = World.UserInterface.VoxSelector.VoxelUnderMouse; if (voxelUnderMouse == DragStartVoxel) { // Create single straight preview piece } else { var destinationPoint = voxelUnderMouse.Coordinate; // Prevent path finding from attempting slopes - not supported yet. destinationPoint = new GlobalVoxelCoordinate(destinationPoint.X, DragStartVoxel.Coordinate.Y, destinationPoint.Z); var currentVoxel = DragStartVoxel.Coordinate; PathVoxels.Clear(); PathVoxels.Add(currentVoxel); while (true) { var closestDirection = 0; float closestDistance = float.PositiveInfinity; for (var i = 0; i < 8; ++i) { var offsetPos = currentVoxel + CompassOrientationHelper.GetOffset((CompassOrientation)i); var distance = (destinationPoint.ToVector3() - offsetPos.ToVector3()).LengthSquared(); if (distance < closestDistance) { closestDistance = distance; closestDirection = i; } } var nextCoordinate = currentVoxel + CompassOrientationHelper.GetOffset((CompassOrientation)closestDirection); PathVoxels.Add(nextCoordinate); if (PathVoxels.Count >= 100) { break; } if (nextCoordinate == destinationPoint) { break; } currentVoxel = nextCoordinate; } // Iterate PathVoxels, determining deltas and using them to decide which piece to create. var pathCompassConnections = new List <CompassConnection>(); if (PathVoxels.Count > 1) { var firstDelta = CompassOrientationHelper.GetVoxelDelta(PathVoxels[0], PathVoxels[1]); pathCompassConnections.Add(new CompassConnection(OverrideStartingOrientation ? StartingOppositeOrientation : CompassOrientationHelper.Opposite(firstDelta), firstDelta)); for (var i = 1; i < PathVoxels.Count - 1; ++i) { pathCompassConnections.Add(new CompassConnection( CompassOrientationHelper.GetVoxelDelta(PathVoxels[i], PathVoxels[i - 1]), CompassOrientationHelper.GetVoxelDelta(PathVoxels[i], PathVoxels[i + 1]))); } var lastDelta = CompassOrientationHelper.GetVoxelDelta(PathVoxels[PathVoxels.Count - 1], PathVoxels[PathVoxels.Count - 2]); pathCompassConnections.Add(new CompassConnection(lastDelta, OverrideEndingOrientation ? EndingOppositeOrientation : CompassOrientationHelper.Opposite(lastDelta))); } var bodyCounter = 0; var previousPieceAddedTrailingDiagonals = false; for (var i = 0; i < pathCompassConnections.Count; ++i) { var pieceAdded = false; foreach (var piece in Library.EnumerateRailPieces().Where(p => p.CompassConnections.Count != 0)) { var matchedOrientation = PieceOrientation.North; CompassConnection matchedConnection = new CompassConnection(); bool matched = false; for (int j = 0; j < 4 && !matched; ++j) { foreach (var compassConnection in piece.CompassConnections) { var rotated = compassConnection.RotateToPiece((PieceOrientation)j); if (rotated == pathCompassConnections[i]) { matched = true; matchedOrientation = (PieceOrientation)j; matchedConnection = pathCompassConnections[i]; break; } } } if (matched) { var newPiece = new JunctionPiece { Offset = new Point(PathVoxels[i].X - DragStartVoxel.Coordinate.X, PathVoxels[i].Z - DragStartVoxel.Coordinate.Z), RailPiece = piece.Name, Orientation = matchedOrientation }; if (PreviewBodies.Count <= bodyCounter) { PreviewBodies.Add(RailHelper.CreatePreviewBody(World.ComponentManager, DragStartVoxel, newPiece)); } else { PreviewBodies[bodyCounter].UpdatePiece(newPiece, DragStartVoxel); } bodyCounter += 1; pieceAdded = true; if (!previousPieceAddedTrailingDiagonals && (matchedConnection.A == CompassOrientation.Northeast || matchedConnection.A == CompassOrientation.Southeast || matchedConnection.A == CompassOrientation.Southwest || matchedConnection.A == CompassOrientation.Northwest)) { bodyCounter = AddDiagonal(bodyCounter, matchedConnection.A, newPiece, 7, 5); bodyCounter = AddDiagonal(bodyCounter, matchedConnection.A, newPiece, 1, 1); } if (matchedConnection.B == CompassOrientation.Northeast || matchedConnection.B == CompassOrientation.Southeast || matchedConnection.B == CompassOrientation.Southwest || matchedConnection.B == CompassOrientation.Northwest) { previousPieceAddedTrailingDiagonals = true; bodyCounter = AddDiagonal(bodyCounter, matchedConnection.B, newPiece, 7, 5); bodyCounter = AddDiagonal(bodyCounter, matchedConnection.B, newPiece, 1, 1); } else { previousPieceAddedTrailingDiagonals = false; } break; } } if (!pieceAdded) { break; } } // Clean up any excess preview entities. var lineSize = bodyCounter; while (bodyCounter < PreviewBodies.Count) { PreviewBodies[bodyCounter].GetRoot().Delete(); bodyCounter += 1; } PreviewBodies = PreviewBodies.Take(lineSize).ToList(); } } CanPlace = RailHelper.CanPlace(World, PreviewBodies); if (CanPlace) { tint = GameSettings.Default.Colors.GetColor("Positive", Color.Green); } else { tint = GameSettings.Default.Colors.GetColor("Negative", Color.Red); } foreach (var body in PreviewBodies) { body.SetVertexColorRecursive(tint); } }
public GuiStateTemplate(DwarfGame Game, GameStateManager StateManager) : base(Game, "GuiStateTemplate", StateManager) { }
public override void Render(DwarfGame game, DwarfTime time) { }
public WaitState(DwarfGame game, string name, GameStateManager stateManager, Thread waitThread, DwarfGUI gui) : base(game, name, stateManager) { WaitThread = waitThread; GUI = gui; OnFinished = () => { }; Done = false; }
public IntroState(DwarfGame game, GameStateManager stateManager) : base(game, "IntroState", stateManager) { ResourceLibrary library = new ResourceLibrary(); }
public void LoadWorlds() { ExitThreads = false; try { System.IO.DirectoryInfo worldDirectory = System.IO.Directory.CreateDirectory(DwarfGame.GetGameDirectory() + ProgramData.DirChar + OverworldDirectory); foreach (System.IO.DirectoryInfo file in worldDirectory.EnumerateDirectories()) { WorldLoadDescriptor descriptor = new WorldLoadDescriptor { DirectoryName = file.FullName, WorldName = file.FullName.Split(ProgramData.DirChar).Last(), ScreenshotName = file.FullName + ProgramData.DirChar + "screenshot.png", FileName = file.FullName + ProgramData.DirChar + "world." + OverworldFile.CompressedExtension, }; Worlds.Add(descriptor); } } catch (System.IO.IOException exception) { Console.Error.WriteLine(exception.Message); Dialog.Popup(GUI, "Error.", "Error loading worlds:\n" + exception.Message, Dialog.ButtonType.OK); } }
public override void Construct() { Padding = new Margin(2, 2, 0, 0); StartButton = AddChild(new Gui.Widget { Text = "Start Game", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockBottom, OnClick = (sender, args) => { var saveName = DwarfGame.GetWorldDirectory() + Path.DirectorySeparatorChar + Settings.Name + Path.DirectorySeparatorChar + String.Format("{0}-{1}", (int)Settings.InstanceSettings.Origin.X, (int)Settings.InstanceSettings.Origin.Y); var saveGame = SaveGame.LoadMetaFromDirectory(saveName); if (saveGame != null) { DwarfGame.LogSentryBreadcrumb("WorldGenerator", "User is loading a saved game."); Settings.InstanceSettings.ExistingFile = saveName; Settings.InstanceSettings.LoadType = LoadType.LoadFromFile; GameStateManager.ClearState(); GameStateManager.PushState(new LoadState(Game, Settings, LoadTypes.UseExistingOverworld)); } else { DwarfGame.LogSentryBreadcrumb("WorldGenerator", string.Format("User is starting a game with a {0} x {1} world.", Settings.Width, Settings.Height)); Settings.InstanceSettings.ExistingFile = null; Settings.InstanceSettings.LoadType = LoadType.CreateNew; var message = ""; var valid = InstanceSettings.ValidateEmbarkment(Settings, out message); if (valid == InstanceSettings.ValidationResult.Pass) { LaunchNewGame(); } else if (valid == InstanceSettings.ValidationResult.Query) { var popup = new Gui.Widgets.Confirm() { Text = message, OnClose = (_sender) => { if ((_sender as Gui.Widgets.Confirm).DialogResult == Gui.Widgets.Confirm.Result.OKAY) { LaunchNewGame(); } } }; Root.ShowModalPopup(popup); } else if (valid == InstanceSettings.ValidationResult.Reject) { var popup = new Gui.Widgets.Confirm() { Text = message, CancelText = "" }; Root.ShowModalPopup(popup); } } } }); CellInfo = AddChild(new Widget { AutoLayout = AutoLayout.DockFill, TextColor = new Vector4(0, 0, 0, 1), Font = "font10" }); ZoomedPreview = AddChild(new Gui.Widget { AutoLayout = Gui.AutoLayout.DockBottom, OnLayout = (sender) => { sender.Rect.Height = StartButton.Rect.Width; sender.Rect.Width = StartButton.Rect.Width; sender.Rect.Y = StartButton.Rect.Top - StartButton.Rect.Width - 2; sender.Rect.X = StartButton.Rect.X; } }); UpdateCellInfo(); this.Layout(); base.Construct(); }
public WorldGeneratorState(DwarfGame Game, Overworld Settings, PanelStates StartingState) : base(Game) { this.PanelState = StartingState; this.Settings = Settings; }
public CompanyMakerState(DwarfGame game, GameStateManager stateManager) : base(game, "CompanyMakerState", stateManager) { CompanyInformation = new CompanyInformation(); }
public override void OnEnter() { // Clear the input queue... cause other states aren't using it and it's been filling up. DwarfGame.GumInputMapper.GetInputQueue(); GuiRoot = new Gui.Root(DwarfGame.GuiSkin); GuiRoot.MousePointer = new MousePointer("mouse", 15.0f, 16, 17, 18, 19, 20, 21, 22, 23); var mainPanel = GuiRoot.RootItem.AddChild(new Gui.Widget { Rect = GuiRoot.RenderData.VirtualScreen, Border = "border-fancy", Text = Settings.Name, Font = "font16", TextColor = new Vector4(0, 0, 0, 1), Padding = new Gui.Margin(4, 4, 4, 4), InteriorMargin = new Gui.Margin(24, 0, 0, 0), }); var rightPanel = mainPanel.AddChild(new Gui.Widget { AutoLayout = Gui.AutoLayout.DockRight, MinimumSize = new Point(256, 0), Padding = new Gui.Margin(2, 2, 2, 2) }); rightPanel.AddChild(new Gui.Widget { Text = "Regenerate", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, OnClick = (sender, args) => { Settings = new WorldGenerationSettings(); RestartGeneration(); } }); rightPanel.AddChild(new Gui.Widget { Text = "Save World", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, OnClick = (sender, args) => { if (Generator.CurrentState != WorldGenerator.GenerationState.Finished) { GuiRoot.ShowTooltip(GuiRoot.MousePosition, "Generator is not finished."); } else { System.IO.DirectoryInfo worldDirectory = System.IO.Directory.CreateDirectory(DwarfGame.GetWorldDirectory() + System.IO.Path.DirectorySeparatorChar + Settings.Name); NewOverworldFile file = new NewOverworldFile(Game.GraphicsDevice, Overworld.Map, Settings.Name, Settings.SeaLevel); file.WriteFile(worldDirectory.FullName); file.SaveScreenshot(worldDirectory.FullName + System.IO.Path.DirectorySeparatorChar + "screenshot.png"); GuiRoot.ShowModalPopup(GuiRoot.ConstructWidget(new Gui.Widgets.Popup { Text = "File saved." })); } } }); rightPanel.AddChild(new Gui.Widget { Text = "Advanced", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, OnClick = (sender, args) => { var advancedSettingsEditor = GuiRoot.ConstructWidget(new Gui.Widgets.WorldGenerationSettingsDialog { Settings = Settings, OnClose = (s) => { if ((s as Gui.Widgets.WorldGenerationSettingsDialog).Result == Gui.Widgets.WorldGenerationSettingsDialog.DialogResult.Okay) { RestartGeneration(); } } }); GuiRoot.ShowModalPopup(advancedSettingsEditor); } }); rightPanel.AddChild(new Gui.Widget { Text = "Back", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, OnClick = (sender, args) => { Generator.Abort(); StateManager.PopState(); } }); StartButton = rightPanel.AddChild(new Gui.Widget { Text = "Start Game", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockBottom, OnClick = (sender, args) => { if (Generator.CurrentState != WorldGenerator.GenerationState.Finished) { GuiRoot.ShowTooltip(GuiRoot.MousePosition, "World generation is not finished."); } else { Overworld.Name = Settings.Name; Settings.ExistingFile = null; Settings.WorldOrigin = Settings.WorldGenerationOrigin; Settings.SpawnRect = Generator.GetSpawnRectangle(); if (Settings.Natives == null || Settings.Natives.Count == 0) { Settings.Natives = Generator.NativeCivilizations; } //Settings.StartUnderground = StartUnderground.CheckState; //Settings.RevealSurface = RevealSurface.CheckState; foreach (var faction in Settings.Natives) { Vector2 center = new Vector2(faction.Center.X, faction.Center.Y); Vector2 spawn = new Vector2(Generator.GetSpawnRectangle().Center.X, Generator.GetSpawnRectangle().Center.Y); faction.DistanceToCapital = (center - spawn).Length(); faction.ClaimsColony = false; } foreach (var faction in Generator.GetFactionsInSpawn()) { faction.ClaimsColony = true; } StateManager.ClearState(); StateManager.PushState(new LoadState(Game, StateManager, Settings)); } } }); rightPanel.AddChild(new Gui.Widget { Text = "Territory size", AutoLayout = Gui.AutoLayout.DockTop, Font = "font8", TextColor = new Vector4(0, 0, 0, 1), }); var colonySizeCombo = rightPanel.AddChild(new Gui.Widgets.ComboBox { AutoLayout = Gui.AutoLayout.DockTop, Items = new List <string>(new string[] { "Small", "Medium", "Large" }), Font = "font8", TextColor = new Vector4(0, 0, 0, 1), OnSelectedIndexChanged = (sender) => { switch ((sender as Gui.Widgets.ComboBox).SelectedItem) { case "Small": Settings.ColonySize = new Point3(4, 1, 4); break; case "Medium": Settings.ColonySize = new Point3(8, 1, 8); break; case "Large": Settings.ColonySize = new Point3(10, 1, 10); break; } var worldSize = Settings.ColonySize.ToVector3() * VoxelConstants.ChunkSizeX / Settings.WorldScale; float w = worldSize.X; float h = worldSize.Z; float clickX = System.Math.Max(System.Math.Min(Settings.WorldGenerationOrigin.X, Settings.Width - w), 0); float clickY = System.Math.Max(System.Math.Min(Settings.WorldGenerationOrigin.Y, Settings.Height - h), 0); Settings.WorldGenerationOrigin = new Vector2((int)(clickX), (int)(clickY)); } }) as Gui.Widgets.ComboBox; rightPanel.AddChild(new Gui.Widget { Text = "Difficulty", AutoLayout = Gui.AutoLayout.DockTop, Font = "font8", TextColor = new Vector4(0, 0, 0, 1) }); var difficultySelectorCombo = rightPanel.AddChild(new Gui.Widgets.ComboBox { AutoLayout = Gui.AutoLayout.DockTop, Items = EmbarkmentLibrary.Embarkments.Select(e => e.Key).ToList(), TextColor = new Vector4(0, 0, 0, 1), Font = "font8", OnSelectedIndexChanged = (sender) => { Settings.InitalEmbarkment = EmbarkmentLibrary.Embarkments[(sender as Gui.Widgets.ComboBox).SelectedItem]; } }) as Gui.Widgets.ComboBox; /* * StartUnderground = rightPanel.AddChild(new Gui.Widgets.CheckBox * { * AutoLayout = Gui.AutoLayout.DockTop, * Font = "font8", * Text = "@world-generation-start-underground" * }) as Gui.Widgets.CheckBox; * * RevealSurface = rightPanel.AddChild(new Gui.Widgets.CheckBox * { * AutoLayout = Gui.AutoLayout.DockTop, * Font = "font8", * Text = "@world-generation-reveal-surface", * CheckState = true * }) as Gui.Widgets.CheckBox; */ rightPanel.AddChild(new Gui.Widget { Text = "Cave Layers", AutoLayout = Gui.AutoLayout.DockTop, Font = "font8", TextColor = new Vector4(0, 0, 0, 1), }); var layerSetting = rightPanel.AddChild(new Gui.Widgets.ComboBox { AutoLayout = AutoLayout.DockTop, Items = new List <string>(new string[] { "Barely any", "Few", "Normal", "Lots", "Way too many" }), Font = "font8", TextColor = new Vector4(0, 0, 0, 1), OnSelectedIndexChanged = (sender) => { switch ((sender as Gui.Widgets.ComboBox).SelectedItem) { case "Barely any": Settings.NumCaveLayers = 2; break; case "Few": Settings.NumCaveLayers = 3; break; case "Normal": Settings.NumCaveLayers = 4; break; case "Lots": Settings.NumCaveLayers = 6; break; case "Way too many": Settings.NumCaveLayers = 9; break; } } }) as Gui.Widgets.ComboBox; ZoomedPreview = rightPanel.AddChild(new Gui.Widget { AutoLayout = Gui.AutoLayout.DockBottom, OnLayout = (sender) => { var space = System.Math.Min( layerSetting.Rect.Width, StartButton.Rect.Top - layerSetting.Rect.Bottom - 4); sender.Rect.Height = space; sender.Rect.Width = space; sender.Rect.Y = layerSetting.Rect.Bottom + 2; sender.Rect.X = layerSetting.Rect.X + ((layerSetting.Rect.Width - space) / 2); } }); GenerationProgress = mainPanel.AddChild(new Gui.Widgets.ProgressBar { AutoLayout = Gui.AutoLayout.DockBottom, TextHorizontalAlign = Gui.HorizontalAlign.Center, TextVerticalAlign = Gui.VerticalAlign.Center, Font = "font10", TextColor = new Vector4(1, 1, 1, 1) }) as Gui.Widgets.ProgressBar; Preview = mainPanel.AddChild(new WorldGeneratorPreview(Game.GraphicsDevice) { Border = "border-thin", AutoLayout = Gui.AutoLayout.DockFill }) as WorldGeneratorPreview; GuiRoot.RootItem.Layout(); difficultySelectorCombo.SelectedIndex = difficultySelectorCombo.Items.IndexOf("Normal"); colonySizeCombo.SelectedIndex = colonySizeCombo.Items.IndexOf("Medium"); layerSetting.SelectedIndex = layerSetting.Items.IndexOf("Normal"); IsInitialized = true; if (AutoGenerate) { RestartGeneration(); } else // Setup a dummy generator for now. { Generator = new WorldGenerator(Settings); Generator.LoadDummy( new Color[Overworld.Map.GetLength(0) * Overworld.Map.GetLength(1)], Game.GraphicsDevice); Preview.SetGenerator(Generator); } base.OnEnter(); }
public PlayFactionViewState(DwarfGame Game, WorldManager World) : base(Game, World.Overworld) { this.World = World; }
public void LoadWorlds() { ExitThreads = false; try { System.IO.DirectoryInfo savedirectory = System.IO.Directory.CreateDirectory(DwarfGame.GetGameDirectory() + ProgramData.DirChar + SaveDirectory); foreach (System.IO.DirectoryInfo file in savedirectory.EnumerateDirectories()) { GameLoadDescriptor descriptor = new GameLoadDescriptor { FileName = file.FullName }; Games.Add(descriptor); } } catch (System.IO.IOException exception) { Console.Error.WriteLine(exception.Message); } }
public MainMenuState(DwarfGame game) : base(game) { }
public GUITest(DwarfGame game, GameStateManager stateManager) : base(game, "GUITest", stateManager) { EdgePadding = 32; Input = new InputManager(); }
public void MakeMenu(DirectoryInfo GameToContinue) { var frame = CreateMenu(Library.GetString("main-menu-title")); if (GameToContinue != null && NewOverworldFile.CheckCompatibility(GameToContinue.FullName)) { CreateMenuItem(frame, "Continue", NewOverworldFile.GetOverworldName(GameToContinue.FullName), (sender, args) => { var file = NewOverworldFile.Load(GameToContinue.FullName); GameStateManager.PopState(); var overworldSettings = file.CreateSettings(); overworldSettings.InstanceSettings.LoadType = LoadType.LoadFromFile; GameStateManager.PushState(new LoadState(Game, overworldSettings, LoadTypes.UseExistingOverworld)); }); } CreateMenuItem(frame, Library.GetString("new-game"), Library.GetString("new-game-tooltip"), (sender, args) => GameStateManager.PushState(new WorldGeneratorState(Game, Overworld.Create(), WorldGeneratorState.PanelStates.Generate))); CreateMenuItem(frame, Library.GetString("load-game"), Library.GetString("load-game-tooltip"), (sender, args) => GameStateManager.PushState(new WorldLoaderState(Game))); CreateMenuItem(frame, Library.GetString("options"), Library.GetString("options-tooltip"), (sender, args) => GameStateManager.PushState(new OptionsState(Game))); CreateMenuItem(frame, Library.GetString("manage-mods"), Library.GetString("manage-mods-tooltip"), (sender, args) => GameStateManager.PushState(new ModManagement.ManageModsState(Game))); CreateMenuItem(frame, Library.GetString("credits"), Library.GetString("credits-tooltip"), (sender, args) => GameStateManager.PushState(new CreditsState(GameState.Game))); CreateMenuItem(frame, "QUICKPLAY", "", (sender, args) => { DwarfGame.LogSentryBreadcrumb("Menu", "User generating a random world."); var overworldSettings = Overworld.Create(); overworldSettings.InstanceSettings.InitalEmbarkment = new Embarkment(overworldSettings); overworldSettings.InstanceSettings.InitalEmbarkment.Funds = 1000u; overworldSettings.InstanceSettings.InitalEmbarkment.Employees.Add(Applicant.Random("Crafter", overworldSettings.Company)); overworldSettings.InstanceSettings.InitalEmbarkment.Employees.Add(Applicant.Random("Manager", overworldSettings.Company)); overworldSettings.InstanceSettings.InitalEmbarkment.Employees.Add(Applicant.Random("Miner", overworldSettings.Company)); overworldSettings.InstanceSettings.InitalEmbarkment.Employees.Add(Applicant.Random("Wizard", overworldSettings.Company)); overworldSettings.InstanceSettings.InitalEmbarkment.Employees.Add(Applicant.Random("Soldier", overworldSettings.Company)); overworldSettings.InstanceSettings.InitalEmbarkment.Employees.Add(Applicant.Random("Musketeer", overworldSettings.Company)); GameStateManager.PushState(new LoadState(Game, overworldSettings, LoadTypes.GenerateOverworld)); }); CreateMenuItem(frame, "GIANT QUICKPLAY", "", (sender, args) => { GameStateManager.PushState(new CheckMegaWorldState(Game)); }); CreateMenuItem(frame, "Dwarf Designer", "Open the dwarf designer.", (sender, args) => { GameStateManager.PushState(new Debug.DwarfDesignerState(GameState.Game)); }); #if DEBUG CreateMenuItem(frame, "Yarn test", "", (sender, args) => { GameStateManager.PushState(new YarnState(null, "test.conv", "Start", new Yarn.MemoryVariableStore())); }); CreateMenuItem(frame, "Debug GUI", "", (sender, args) => { GameStateManager.PushState(new Debug.GuiDebugState(GameState.Game)); }); #endif CreateMenuItem(frame, Library.GetString("quit"), Library.GetString("quit-tooltip"), (sender, args) => Game.Exit()); FinishMenu(); }
public GuiDebugState(DwarfGame game) : base(game) { }
public void PreRender(SpriteBatch sprites) { if (sprites.IsDisposed || sprites.GraphicsDevice.IsDisposed) { return; } try { if (DrawShader != null && (DrawShader.IsDisposed || DrawShader.GraphicsDevice.IsDisposed)) { DrawShader = new BasicEffect(World.GraphicsDevice); } if (RenderTarget.IsDisposed || RenderTarget.IsContentLost) { World.ChunkManager.NeedsMinimapUpdate = true; RenderTarget = new RenderTarget2D(GameState.Game.GraphicsDevice, RenderWidth, RenderHeight, false, SurfaceFormat.Color, DepthFormat.Depth24); return; } if (!HomeSet) { if (World.EnumerateZones().Any()) { HomePosition = World.EnumerateZones().First().GetBoundingBox().Center(); } HomeSet = true; } ReDrawChunks(); World.GraphicsDevice.SetRenderTarget(RenderTarget); World.GraphicsDevice.Clear(Color.Black); Camera.Target = World.Renderer.Camera.Target; Vector3 cameraToTarget = World.Renderer.Camera.Target - World.Renderer.Camera.Position; cameraToTarget.Normalize(); Camera.Position = World.Renderer.Camera.Target + Vector3.Up * 50 - cameraToTarget * 4; Camera.UpdateViewMatrix(); Camera.UpdateProjectionMatrix(); World.Renderer.DefaultShader.View = Camera.ViewMatrix; World.Renderer.DefaultShader.Projection = Camera.ProjectionMatrix; var bounds = World.ChunkManager.Bounds; DrawShader.TextureEnabled = true; DrawShader.LightingEnabled = false; DrawShader.Projection = Camera.ProjectionMatrix; DrawShader.View = Camera.ViewMatrix; DrawShader.World = Matrix.Identity; DrawShader.VertexColorEnabled = false; DrawShader.Alpha = 1.0f; foreach (var cell in Cells) { DrawShader.Texture = cell.Value.Texture; DrawShader.World = Matrix.CreateTranslation(cell.Key.X * VoxelConstants.ChunkSizeX, 0.0f, cell.Key.Z * VoxelConstants.ChunkSizeZ); foreach (var pass in DrawShader.CurrentTechnique.Passes) { pass.Apply(); World.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, quad2, 0, 2); } } World.Renderer.DefaultShader.EnbleFog = true; try { DwarfGame.SafeSpriteBatchBegin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Drawer2D.PointMagLinearMin, null, RasterizerState.CullNone, null, Matrix.Identity); var viewPort = new Viewport(RenderTarget.Bounds); foreach (var icon in World.ComponentManager.GetMinimapIcons()) { if (!icon.Parent.IsVisible) { continue; } var screenPos = viewPort.Project(icon.GlobalTransform.Translation, Camera.ProjectionMatrix, Camera.ViewMatrix, Matrix.Identity); if (RenderTarget.Bounds.Contains((int)screenPos.X, (int)screenPos.Y)) { var parentBody = icon.Parent; if (icon.Parent != null) { if (icon.Parent.Position.Y > World.Renderer.PersistentSettings.MaxViewingLevel + 1) { continue; } var firstVisible = VoxelHelpers.FindFirstVisibleVoxelOnRay(World.ChunkManager, parentBody.Position, parentBody.Position + Vector3.Up * World.WorldSizeInVoxels.Y); if (firstVisible.IsValid) { continue; } } DwarfGame.SpriteBatch.Draw(icon.Icon.SafeGetImage(), new Vector2(screenPos.X, screenPos.Y), icon.Icon.SourceRect, Color.White, 0.0f, new Vector2(icon.Icon.SourceRect.Width / 2.0f, icon.Icon.SourceRect.Height / 2.0f), icon.IconScale, SpriteEffects.None, 0); } } } finally { sprites.End(); } World.GraphicsDevice.BlendState = BlendState.NonPremultiplied; World.GraphicsDevice.DepthStencilState = DepthStencilState.Default; World.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; World.GraphicsDevice.SamplerStates[0] = Drawer2D.PointMagLinearMin; World.GraphicsDevice.SetRenderTarget(null); } catch (Exception exception) { Console.Out.WriteLine(exception); } }
public void UpdateCellInfo() { if (Settings.InstanceSettings.Origin.X < 0 || Settings.InstanceSettings.Origin.X >= Settings.Width || Settings.InstanceSettings.Origin.Y < 0 || Settings.InstanceSettings.Origin.Y >= Settings.Height) { StartButton.Hidden = true; CellInfo.Text = "\nSelect a spawn cell to continue"; SaveName = ""; } else { SaveName = DwarfGame.GetWorldDirectory() + Path.DirectorySeparatorChar + Settings.Name + Path.DirectorySeparatorChar + String.Format("{0}-{1}", (int)Settings.InstanceSettings.Origin.X, (int)Settings.InstanceSettings.Origin.Y); var saveGame = SaveGame.LoadMetaFromDirectory(SaveName); if (saveGame != null) { StartButton.Text = "Load"; CellInfo.Clear(); CellInfo.Text = "\n" + saveGame.Metadata.DescriptionString; StartButton.Hidden = false; CellInfo.Layout(); } else { StartButton.Hidden = false; StartButton.Text = "Create"; CellInfo.Clear(); CellInfo.Text = ""; var cellInfoText = Root.ConstructWidget(new Widget { AutoLayout = AutoLayout.DockFill }); CellInfo.AddChild(new Gui.Widget { Text = "Edit Embarkment", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, MinimumSize = new Point(0, 32), OnClick = (sender, args) => { DwarfGame.LogSentryBreadcrumb("Game Launcher", "User is modifying embarkment."); var embarkmentEditor = Root.ConstructWidget(new EmbarkmentEditor(Settings) { OnClose = (s) => { SetCreateCellInfoText(cellInfoText); } }); Root.ShowModalPopup(embarkmentEditor); } }); CellInfo.AddChild(cellInfoText); SetCreateCellInfoText(cellInfoText); CellInfo.Layout(); } } }
public TutorialViewState(DwarfGame game, GameStateManager stateManager, WorldManager world) : base(game, "TutorialViewState", stateManager) { World = world; }
public InstanceSettings InstanceSettings; // These are only saved because it makes the selector default to the last launched branch. public String GetInstancePath() { return(DwarfGame.GetWorldDirectory() + System.IO.Path.DirectorySeparatorChar + Name + System.IO.Path.DirectorySeparatorChar + String.Format("{0}-{1}", (int)InstanceSettings.Origin.X, (int)InstanceSettings.Origin.Y)); }
/// <summary> /// Creates a new play state /// </summary> /// <param name="game">The program currently running</param> /// <param name="stateManager">The game state manager this state will belong to</param> public PlayState(DwarfGame game, GameStateManager stateManager) : base(game, "PlayState", stateManager) { ShouldReset = true; Paused = false; Content = Game.Content; GraphicsDevice = Game.GraphicsDevice; Seed = Random.Next(); RenderUnderneath = true; WorldOrigin = new Vector2(WorldWidth / 2, WorldHeight / 2); PreSimulateTimer = new Timer(3, false); Time = new WorldTime(); }
public DwarfDesignerState(DwarfGame game, GameStateManager stateManager) : base(game, "GuiDebugState", stateManager) { }
public FactionViewState(DwarfGame game, GameStateManager stateManager, WorldManager world) : base(game, "FactionViewState", stateManager) { World = world; }
public NewGameCreateDebugWorldState(DwarfGame game, GameStateManager stateManager) : base(game, "MainMenuState", stateManager) { }
public IntroState(DwarfGame game, GameStateManager stateManager) : base(game, "IntroState", stateManager) { }
public void PreRender(DwarfTime time, SpriteBatch sprites) { if (!HomeSet) { HomePosition = World.Camera.Position; HomeSet = true; } //Camera.Update(time, World.ChunkManager); Camera.Target = World.Camera.Target; Vector3 cameraToTarget = World.Camera.Target - World.Camera.Position; cameraToTarget.Normalize(); Camera.Position = World.Camera.Target + Vector3.Up * 50 - cameraToTarget * 4; Camera.UpdateViewMatrix(); Camera.UpdateProjectionMatrix(); World.GraphicsDevice.SetRenderTarget(RenderTarget); World.GraphicsDevice.Clear(ClearOptions.Target, Color.Black, 0, 0); World.DefaultShader.View = Camera.ViewMatrix; World.DefaultShader.EnbleFog = false; World.DefaultShader.Projection = Camera.ProjectionMatrix; World.DefaultShader.CurrentTechnique = World.DefaultShader.Techniques[Shader.Technique.TexturedWithColorScale]; World.GraphicsDevice.BlendState = BlendState.NonPremultiplied; World.GraphicsDevice.DepthStencilState = DepthStencilState.Default; World.ChunkRenderer.RenderAll(Camera, time, World.GraphicsDevice, World.DefaultShader, Matrix.Identity, ColorMap); World.WaterRenderer.DrawWaterFlat(World.GraphicsDevice, Camera.ViewMatrix, Camera.ProjectionMatrix, World.DefaultShader, World.ChunkManager); World.GraphicsDevice.Textures[0] = null; World.GraphicsDevice.Indices = null; World.GraphicsDevice.SetVertexBuffer(null); World.DefaultShader.EnbleFog = true; try { DwarfGame.SafeSpriteBatchBegin(SpriteSortMode.Immediate, BlendState.NonPremultiplied, Drawer2D.PointMagLinearMin, null, RasterizerState.CullNone, null, Matrix.Identity); Viewport viewPort = new Viewport(RenderTarget.Bounds); foreach (var icon in World.ComponentManager.GetMinimapIcons()) { if (!icon.Parent.IsVisible) { continue; } Vector3 screenPos = viewPort.Project(icon.GlobalTransform.Translation, Camera.ProjectionMatrix, Camera.ViewMatrix, Matrix.Identity); if (RenderTarget.Bounds.Contains((int)screenPos.X, (int)screenPos.Y)) { DwarfGame.SpriteBatch.Draw(icon.Icon.Image, new Vector2(screenPos.X, screenPos.Y), icon.Icon.SourceRect, Color.White, 0.0f, new Vector2(icon.Icon.SourceRect.Width / 2.0f, icon.Icon.SourceRect.Height / 2.0f), icon.IconScale, SpriteEffects.None, 0); } } } finally { DwarfGame.SpriteBatch.End(); } World.GraphicsDevice.BlendState = BlendState.NonPremultiplied; World.GraphicsDevice.DepthStencilState = DepthStencilState.Default; World.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise; World.GraphicsDevice.SamplerStates[0] = Drawer2D.PointMagLinearMin; World.GraphicsDevice.SetRenderTarget(null); }
public MainMenuState(DwarfGame game, GameStateManager stateManager) : base(game, "MainMenuState", stateManager) { }
public override void Update(DwarfGame game, DwarfTime time) { if (Player.IsCameraRotationModeActive()) { Player.VoxSelector.Enabled = false; Player.World.SetMouse(null); Player.BodySelector.Enabled = false; return; } Player.VoxSelector.Enabled = true; Player.BodySelector.Enabled = false; Player.VoxSelector.DrawBox = false; Player.VoxSelector.DrawVoxel = false; Player.VoxSelector.SelectionType = VoxelSelectionType.SelectEmpty; if (Player.World.IsMouseOverGui) { Player.World.SetMouse(Player.World.MousePointer); } else { Player.World.SetMouse(new Gui.MousePointer("mouse", 1, 4)); } // Don't attempt any control if the user is trying to type into a focus item. if (Player.World.Gui.FocusItem != null && !Player.World.Gui.FocusItem.IsAnyParentTransparent() && !Player.World.Gui.FocusItem.IsAnyParentHidden()) { return; } KeyboardState state = Keyboard.GetState(); bool leftKey = state.IsKeyDown(ControlSettings.Mappings.RotateObjectLeft); bool rightKey = state.IsKeyDown(ControlSettings.Mappings.RotateObjectRight); if (LeftPressed && !leftKey) { Pattern = Pattern.Rotate(Rail.PieceOrientation.East); } if (RightPressed && !rightKey) { Pattern = Pattern.Rotate(Rail.PieceOrientation.West); } LeftPressed = leftKey; RightPressed = rightKey; var tint = Color.White; for (var i = 0; i < PreviewBodies.Count && i < Pattern.Pieces.Count; ++i) { PreviewBodies[i].UpdatePiece(Pattern.Pieces[i], Player.VoxSelector.VoxelUnderMouse); } if (RailHelper.CanPlace(Player, PreviewBodies)) { tint = GameSettings.Default.Colors.GetColor("Positive", Color.Green); } else { tint = GameSettings.Default.Colors.GetColor("Negative", Color.Red); } foreach (var body in PreviewBodies) { body.SetVertexColorRecursive(tint); } }
public GUITest(DwarfGame game, GameStateManager stateManager) : base(game, "GUITest", stateManager) { EdgePadding = 32; Input = new InputManager(); }