public void Update(WorldManager world, OrbitCamera camera)
        {
            float dt = (float)DwarfTime.LastTime.ElapsedRealTime.TotalSeconds;

            Duration.Update(DwarfTime.LastTime);
            Vector3 forward = (camera.Target - camera.Position);

            forward.Normalize();
            Vector3 right = Vector3.Cross(forward, camera.UpVector);
            Vector3 up    = Vector3.Cross(right, forward);

            right.Normalize();
            up.Normalize();
            Vector3 vel = Velocity.X * right + Velocity.Y * up - Velocity.Z * forward;
            float   l   = vel.Length();

            vel.Y = 0;

            if (vel.Length() > 0.001f)
            {
                vel.Normalize();
                vel *= l;
            }
            camera.Position += vel * dt;
            camera.Target   += vel * dt;
            camera.OverheadUpdate(DwarfTime.LastTime, world.ChunkManager, 0.0f, Spin * dt, Zoom * dt);

            if (Duration.HasTriggered)
            {
                Deactivate(world, camera);
            }
        }
Esempio n. 2
0
        public static void Render(
            GraphicsDevice Device,
            Shader Effect,
            OrbitCamera Camera,
            DesignationSet Designations,
            WorldManager World)
        {
            lock (renderLock)
            {
                Drawer3D.Effect = Effect;
                Drawer3D.Camera = Camera;

                var colorModulation = Math.Abs(Math.Sin(DwarfTime.LastTime.TotalGameTime.TotalSeconds * 2.0f));

                DrawEntityDesignations(World, Designations);

                foreach (var box in Boxes)
                {
                    _addBox(box.RealBox.Min, box.RealBox.Max - box.RealBox.Min, box.Color, box.Thickness, box.Warp);
                }

                foreach (var segment in Segments)
                {
                    _addLineSegment(segment.A, segment.B, segment.Color, segment.Thickness, false);
                }

                _flush();

                Boxes.Clear();
                Segments.Clear();
            }
        }
Esempio n. 3
0
        void ISaveableObject.LoadFromNugget(Loader SaveSystem, Nugget From)
        {
            var nug = From as PlayDataNugget;

            Camera = SaveSystem.LoadObject(nug.Camera) as OrbitCamera;
            /* Etc */
            throw new NotImplementedException();
        }
Esempio n. 4
0
        public static void Render(
            GraphicsDevice Device,
            Shader Effect,
            OrbitCamera Camera,
            DesignationDrawer DesignationDrawer,
            DesignationSet Designations,
            WorldManager World)
        {
            lock (renderLock)
            {
                Drawer3D.Effect = Effect;
                Drawer3D.Camera = Camera;

                var colorModulation = Math.Abs(Math.Sin(DwarfTime.LastTime.TotalGameTime.TotalSeconds * 2.0f));

                DesignationDrawer.DrawHilites(
                    World,
                    Designations,
                    _addBox,
                    (pos, type) =>
                {
                    Effect.MainTexture = AssetManager.GetContentTexture(ContentPaths.Terrain.terrain_tiles);
                    Effect.LightRamp   = Color.White;
                    // Todo: Alpha pulse
                    Effect.VertexColorTint  = new Color(0.1f, 0.9f, 1.0f, 1.0f);
                    var prevTechnique       = Effect.CurrentTechnique;
                    Effect.CurrentTechnique = Effect.Techniques[Shader.Technique.Stipple];
                    var pos_distorted       = pos + Vector3.Up * 0.15f + VertexNoise.GetNoiseVectorFromRepeatingTexture(pos + Vector3.One * 0.5f);
                    Effect.World            = Matrix.CreateTranslation(pos_distorted);

                    foreach (EffectPass pass in Effect.CurrentTechnique.Passes)
                    {
                        pass.Apply();
                        VoxelLibrary.GetPrimitive(type).Render(Device);
                    }

                    Effect.LightRamp        = Color.White;
                    Effect.VertexColorTint  = Color.White;
                    Effect.World            = Matrix.Identity;
                    Effect.CurrentTechnique = prevTechnique;
                });

                foreach (var box in Boxes)
                {
                    _addBox(box.RealBox.Min, box.RealBox.Max - box.RealBox.Min, box.Color, box.Thickness, box.Warp);
                }

                foreach (var segment in Segments)
                {
                    _addLineSegment(segment.A, segment.B, segment.Color, segment.Thickness, false);
                }

                _flush();

                Boxes.Clear();
                Segments.Clear();
            }
        }
 public void Deactivate(WorldManager world, OrbitCamera camera)
 {
     Active = false;
     GameSettings.Current.CursorLightEnabled = _lightActive;
     world.UserInterface.Gui.RootItem.Hidden = false;
     world.UserInterface.Gui.RootItem.Invalidate();
     camera.Control       = OrbitCamera.ControlType.Overhead;
     camera.EnableControl = true;
 }
Esempio n. 6
0
 public static void Cleanup()
 {
     Verticies   = new VertexPositionColor[MaxTriangles * 3];
     VertexCount = 0;
     Effect      = null;
     Camera      = null;
     Boxes.Clear();
     Segments.Clear();
 }
Esempio n. 7
0
        public void GenerateInitialChunks(OrbitCamera camera, Point3 origin, ref string message)
        {
            float origBuildRadius = GenerateDistance;

            GenerateDistance = origBuildRadius * 2.0f;

            int i     = 0;
            int iters = WorldSize.X * WorldSize.Y * WorldSize.Z;

            for (int dx = origin.X - WorldSize.X / 2 + 1; dx < origin.X + WorldSize.X / 2; dx++)
            {
                for (int dy = origin.Y - WorldSize.Y / 2; dy <= origin.Y + WorldSize.Y / 2; dy++)
                {
                    for (int dz = origin.Z - WorldSize.Z / 2 + 1; dz < origin.Z + WorldSize.Z / 2; dz++)
                    {
                        message = "Generating : " + (i + 1) + "/" + iters;
                        i++;

                        Point3 box = new Point3(dx, dy, dz);

                        if (!ChunkData.ChunkMap.ContainsKey(box))
                        {
                            Vector3    worldPos = new Vector3(box.X * ChunkData.ChunkSizeX, box.Y * ChunkData.ChunkSizeY, box.Z * ChunkData.ChunkSizeZ);
                            VoxelChunk chunk    = ChunkGen.GenerateChunk(worldPos, (int)ChunkData.ChunkSizeX, (int)ChunkData.ChunkSizeY, (int)ChunkData.ChunkSizeZ, Components, Content, Graphics);
                            chunk.ShouldRebuild             = true;
                            chunk.ShouldRecalculateLighting = true;
                            chunk.IsVisible = true;
                            chunk.ResetSunlight(0);
                            GeneratedChunks.Enqueue(chunk);
                            foreach (VoxelChunk chunk2 in GeneratedChunks)
                            {
                                if (!ChunkData.ChunkMap.ContainsKey(chunk2.ID))
                                {
                                    ChunkData.AddChunk(chunk2);
                                    RecalculateBounds();
                                }
                            }
                        }
                    }
                }
            }

            UpdateRebuildList();
            GenerateDistance = origBuildRadius;

            while (GeneratedChunks.Count > 0)
            {
                VoxelChunk gen = null;
                if (!GeneratedChunks.TryDequeue(out gen))
                {
                    break;
                }
            }

            ChunkData.ChunkManager.CreateGraphics(ref message, ChunkData);
        }
Esempio n. 8
0
        public Minimap(DwarfGUI gui, GUIComponent parent, int width, int height, PlayState playState, Texture2D colormap, Texture2D frame) :
            base(gui, parent, new ImageFrame())
        {
            Frame         = frame;
            SuppressClick = false;
            ColorMap      = colormap;

            RenderWidth      = width;
            RenderHeight     = height;
            RenderTarget     = new RenderTarget2D(GameState.Game.GraphicsDevice, RenderWidth, RenderHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
            Image.Image      = RenderTarget;
            Image.SourceRect = new Rectangle(0, 0, RenderWidth, RenderHeight);
            PlayState        = playState;

            ConstrainSize = true;

            Camera = new OrbitCamera(0, 0, 0.01f, new Vector3(0, 0, 0), new Vector3(0, 0, 0), 2.5f, 1.0f, 0.1f, 1000.0f)
            {
                Projection = global::DwarfCorp.Camera.ProjectionMode.Orthographic
            };

            ZoomInButton = new Button(GUI, this, "", GUI.SmallFont, Button.ButtonMode.ImageButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.ZoomIn))
            {
                LocalBounds = new Rectangle(1, 1, 32, 32),
                ToolTip     = "Zoom in"
            };

            ZoomInButton.OnClicked += zoomInButton_OnClicked;

            ZoomOutButton = new Button(GUI, this, "", GUI.SmallFont, Button.ButtonMode.ImageButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.ZoomOut))
            {
                LocalBounds = new Rectangle(33, 1, 32, 32),
                ToolTip     = "Zoom out"
            };

            ZoomOutButton.OnClicked += zoomOutButton_OnClicked;


            ZoomHomeButton = new Button(GUI, this, "", GUI.SmallFont, Button.ButtonMode.ImageButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.ZoomHome))
            {
                LocalBounds = new Rectangle(65, 1, 32, 32),
                ToolTip     = "Home camera"
            };

            ZoomHomeButton.OnClicked += ZoomHomeButton_OnClicked;

            MinimizeButton = new Button(GUI, this, "", GUI.SmallFont, Button.ButtonMode.ImageButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.SmallArrowDown))
            {
                LocalBounds = new Rectangle(width - 32, 0, 32, 32),
                ToolTip     = "Show/Hide Map"
            };

            MinimizeButton.OnClicked += MinimizeButton_OnClicked;

            OnClicked += Minimap_OnClicked;
        }
Esempio n. 9
0
        public void Activate(WorldManager world, OrbitCamera camera)
        {
            Active       = true;
            _lightActive = GameSettings.Default.CursorLightEnabled;
            GameSettings.Default.CursorLightEnabled = false;
            world.Gui.RootItem.Hidden = true;
            world.Gui.RootItem.Invalidate();

            camera.Control       = OrbitCamera.ControlType.Overhead;
            camera.EnableControl = false;
        }
Esempio n. 10
0
        public void Initialize(DwarfGame game, ComponentManager components, ChunkManager chunks, OrbitCamera camera, GraphicsDevice graphics)
        {
            CameraController = camera;
            VoxSelector      = new VoxelSelector(World);
            BodySelector     = new BodySelector(CameraController, GameState.Game.GraphicsDevice, components);
            SelectedMinions  = new List <CreatureAI>();

            CreateTools();

            //InputManager.KeyReleasedCallback += OnKeyReleased;
            //InputManager.KeyPressedCallback += OnKeyPressed;
        }
Esempio n. 11
0
        public static bool RotationEnabled(OrbitCamera camera)
        {
            KeyboardState keys         = Keyboard.GetState();
            bool          shiftPressed = keys.IsKeyDown(ControlSettings.Mappings.CameraMode) ||
                                         keys.IsKeyDown(Keys.RightShift) || Mouse.GetState().MiddleButton == ButtonState.Pressed;

            if (camera.Control == OrbitCamera.ControlType.Walk)
            {
                return(!camera.IsMouseActiveInWalk());
            }
            else
            {
                return(shiftPressed);
            }
        }
Esempio n. 12
0
        public void Initialize(DwarfGame game, ComponentManager components, ChunkManager chunks, OrbitCamera camera, GraphicsDevice graphics)
        {
            RoomLibrary.InitializeStatics();

            CameraController = camera;
            VoxSelector      = new VoxelSelector(World, CameraController, GameState.Game.GraphicsDevice, chunks);
            BodySelector     = new BodySelector(CameraController, GameState.Game.GraphicsDevice, components);
            SelectedMinions  = new List <CreatureAI>();

            if (Spells == null)
            {
                Spells = SpellLibrary.CreateSpellTree(components.World);
            }
            CreateTools();

            //InputManager.KeyReleasedCallback += OnKeyReleased;
            //InputManager.KeyPressedCallback += OnKeyPressed;
        }
Esempio n. 13
0
        private void LoadThreaded()
        {
            DwarfGame.ExitGame = false;
            // Ensure we're using the invariant culture.
            Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
            LoadStatus = LoadingStatus.Loading;
            SetLoadingMessage("Initializing ...");

            while (GraphicsDevice == null)
            {
                Thread.Sleep(100);
            }
            Thread.Sleep(1000);

#if !DEBUG
            try
            {
#endif
            bool fileExists = !string.IsNullOrEmpty(ExistingFile);

            SetLoadingMessage("Creating Sky...");

            Sky = new SkyRenderer();

            #region Reading game file

            if (fileExists)
            {
                SetLoadingMessage("Loading " + ExistingFile);

                gameFile = SaveGame.CreateFromDirectory(ExistingFile);
                if (gameFile == null)
                {
                    throw new InvalidOperationException("Game File does not exist.");
                }

                // Todo: REMOVE THIS WHEN THE NEW SAVE SYSTEM IS COMPLETE.
                if (gameFile.Metadata.Version != Program.Version && !Program.CompatibleVersions.Contains(gameFile.Metadata.Version))
                {
                    throw new InvalidOperationException(String.Format("Game file is from version {0}. Compatible versions are {1}.", gameFile.Metadata.Version,
                                                                      TextGenerator.GetListString(Program.CompatibleVersions)));
                }

                Sky.TimeOfDay = gameFile.Metadata.TimeOfDay;
                Time          = gameFile.Metadata.Time;
                WorldOrigin   = gameFile.Metadata.WorldOrigin;
                WorldScale    = gameFile.Metadata.WorldScale;
                WorldSize     = gameFile.Metadata.NumChunks;
                GameID        = gameFile.Metadata.GameID;

                if (gameFile.Metadata.OverworldFile != null && gameFile.Metadata.OverworldFile != "flat")
                {
                    SetLoadingMessage("Loading world " + gameFile.Metadata.OverworldFile);
                    Overworld.Name = gameFile.Metadata.OverworldFile;
                    DirectoryInfo worldDirectory =
                        Directory.CreateDirectory(DwarfGame.GetWorldDirectory() +
                                                  Path.DirectorySeparatorChar + Overworld.Name);
                    var overWorldFile = new NewOverworldFile(worldDirectory.FullName);
                    Overworld.Map  = overWorldFile.Data.Data;
                    Overworld.Name = overWorldFile.Data.Name;
                }
                else
                {
                    SetLoadingMessage("Generating flat world..");
                    Overworld.CreateUniformLand(GraphicsDevice);
                }
            }

            #endregion

            #region Initialize static data

            {
                Vector3 origin  = new Vector3(0, 0, 0);
                Vector3 extents = new Vector3(1500, 1500, 1500);
                OctTree = new OctTreeNode <Body>(origin - extents, origin + extents);

                PrimitiveLibrary.Initialize(GraphicsDevice, Content);

                InstanceRenderer = new InstanceRenderer(GraphicsDevice, Content);

                Color[] white = new Color[1];
                white[0] = Color.White;
                pixel    = new Texture2D(GraphicsDevice, 1, 1);
                pixel.SetData(white);

                Tilesheet                  = AssetManager.GetContentTexture(ContentPaths.Terrain.terrain_tiles);
                AspectRatio                = GraphicsDevice.Viewport.AspectRatio;
                DefaultShader              = new Shader(Content.Load <Effect>(ContentPaths.Shaders.TexturedShaders), true);
                DefaultShader.ScreenWidth  = GraphicsDevice.Viewport.Width;
                DefaultShader.ScreenHeight = GraphicsDevice.Viewport.Height;
                CraftLibrary.InitializeDefaultLibrary();
                PotionLibrary.Initialize();
                VoxelLibrary.InitializeDefaultLibrary(GraphicsDevice);
                GrassLibrary.InitializeDefaultLibrary();
                DecalLibrary.InitializeDefaultLibrary();

                bloom = new BloomComponent(Game)
                {
                    Settings = BloomSettings.PresetSettings[5]
                };
                bloom.Initialize();

                SoundManager.Content = Content;
                if (PlanService != null)
                {
                    PlanService.Restart();
                }

                JobLibrary.Initialize();
                MonsterSpawner = new MonsterSpawner(this);
                EntityFactory.Initialize(this);
            }

            #endregion


            SetLoadingMessage("Creating Planner ...");
            PlanService = new PlanService();

            SetLoadingMessage("Creating Shadows...");
            Shadows = new ShadowRenderer(GraphicsDevice, 1024, 1024);

            SetLoadingMessage("Creating Liquids ...");

            #region liquids

            WaterRenderer = new WaterRenderer(GraphicsDevice);

            #endregion

            SetLoadingMessage("Generating Initial Terrain Chunks ...");

            if (!fileExists)
            {
                GameID = MathFunctions.Random.Next(0, 1024);
            }

            ChunkGenerator = new ChunkGenerator(VoxelLibrary, Seed, 0.02f)
            {
                SeaLevel = SeaLevel
            };


            #region Load Components

            if (fileExists)
            {
                ChunkManager = new ChunkManager(Content, this,
                                                ChunkGenerator, WorldSize.X, WorldSize.Y, WorldSize.Z);
                Splasher = new Splasher(ChunkManager);


                ChunkRenderer = new ChunkRenderer(ChunkManager.ChunkData);

                SetLoadingMessage("Loading Terrain...");
                gameFile.ReadChunks(ExistingFile);
                ChunkManager.ChunkData.LoadFromFile(ChunkManager, gameFile, SetLoadingMessage);

                SetLoadingMessage("Loading Entities...");
                gameFile.LoadPlayData(ExistingFile, this);
                Camera            = gameFile.PlayData.Camera;
                DesignationDrawer = gameFile.PlayData.Designations;

                Vector3 origin  = new Vector3(WorldOrigin.X, 0, WorldOrigin.Y);
                Vector3 extents = new Vector3(1500, 1500, 1500);
                if (gameFile.PlayData.Stats != null)
                {
                    Stats = gameFile.PlayData.Stats;
                }
                if (gameFile.PlayData.Resources != null)
                {
                    foreach (var resource in gameFile.PlayData.Resources)
                    {
                        if (!ResourceLibrary.Resources.ContainsKey(resource.Key))
                        {
                            ResourceLibrary.Add(resource.Value);
                        }
                    }
                }
                ComponentManager = new ComponentManager(gameFile.PlayData.Components, this);

                foreach (var component in gameFile.PlayData.Components.SaveableComponents)
                {
                    if (!ComponentManager.HasComponent(component.GlobalID) &&
                        ComponentManager.HasComponent(component.Parent.GlobalID))
                    {
                        // Logically impossible.
                        throw new InvalidOperationException("Component exists in save data but not in manager.");
                    }
                }

                ConversationMemory = gameFile.PlayData.ConversationMemory;

                Factions = gameFile.PlayData.Factions;
                ComponentManager.World = this;

                Sky.TimeOfDay = gameFile.Metadata.TimeOfDay;
                Time          = gameFile.Metadata.Time;
                WorldOrigin   = gameFile.Metadata.WorldOrigin;
                WorldScale    = gameFile.Metadata.WorldScale;

                // Restore native factions from deserialized data.
                Natives = new List <Faction>();

                foreach (Faction faction in Factions.Factions.Values)
                {
                    if (faction.Race.IsNative && faction.Race.IsIntelligent && !faction.IsRaceFaction)
                    {
                        Natives.Add(faction);
                    }
                }

                Diplomacy = gameFile.PlayData.Diplomacy;

                GoalManager = new Goals.GoalManager();
                GoalManager.Initialize(new List <Goals.Goal>());// gameFile.PlayData.Goals);

                TutorialManager = new Tutorial.TutorialManager();
                TutorialManager.SetFromSaveData(gameFile.PlayData.TutorialSaveData);
            }
            else
            {
                Time = new WorldTime();

                Camera = new OrbitCamera(this,
                                         new Vector3(VoxelConstants.ChunkSizeX,
                                                     VoxelConstants.ChunkSizeY - 1.0f,
                                                     VoxelConstants.ChunkSizeZ),
                                         new Vector3(VoxelConstants.ChunkSizeY, VoxelConstants.ChunkSizeY - 1.0f,
                                                     VoxelConstants.ChunkSizeZ) +
                                         Vector3.Up * 10.0f + Vector3.Backward * 10,
                                         MathHelper.PiOver4, AspectRatio, 0.1f,
                                         GameSettings.Default.VertexCullDistance);

                ChunkManager = new ChunkManager(Content, this,
                                                ChunkGenerator, WorldSize.X, WorldSize.Y, WorldSize.Z);
                Splasher = new Splasher(ChunkManager);


                ChunkRenderer = new ChunkRenderer(ChunkManager.ChunkData);

                Camera.Position = new Vector3(0, 10, 0) + new Vector3(WorldSize.X * VoxelConstants.ChunkSizeX, 0, WorldSize.Z * VoxelConstants.ChunkSizeZ) * 0.5f;
                Camera.Target   = new Vector3(0, 10, 1) + new Vector3(WorldSize.X * VoxelConstants.ChunkSizeX, 0, WorldSize.Z * VoxelConstants.ChunkSizeZ) * 0.5f;


                ComponentManager = new ComponentManager(this);
                ComponentManager.SetRootComponent(new Body(ComponentManager, "root", Matrix.Identity, Vector3.Zero, Vector3.Zero));

                if (Natives == null) // Todo: Always true??
                {
                    FactionLibrary library = new FactionLibrary();
                    library.Initialize(this, CompanyMakerState.CompanyInformation);
                    Natives = new List <Faction>();
                    for (int i = 0; i < 10; i++)
                    {
                        Natives.Add(library.GenerateFaction(this, i, 10));
                    }
                }

                #region Prepare Factions

                foreach (Faction faction in Natives)
                {
                    faction.World = this;

                    if (faction.RoomBuilder == null)
                    {
                        faction.RoomBuilder = new RoomBuilder(faction, this);
                    }
                }

                Factions = new FactionLibrary();
                if (Natives != null && Natives.Count > 0)
                {
                    Factions.AddFactions(this, Natives);
                }

                Factions.Initialize(this, CompanyMakerState.CompanyInformation);
                Point playerOrigin = new Point((int)(WorldOrigin.X), (int)(WorldOrigin.Y));

                Factions.Factions["Player"].Center         = playerOrigin;
                Factions.Factions["The Motherland"].Center = new Point(playerOrigin.X + 50, playerOrigin.Y + 50);

                #endregion

                Diplomacy = new Diplomacy(this);
                Diplomacy.Initialize(Time.CurrentDate);

                // Initialize goal manager here.
                GoalManager = new Goals.GoalManager();
                GoalManager.Initialize(new List <Goals.Goal>());

                TutorialManager = new Tutorial.TutorialManager();
                TutorialManager.TutorialEnabled = !GameSettings.Default.TutorialDisabledGlobally;
                Tutorial("new game start");

                foreach (var item in CraftLibrary.EnumerateCraftables())
                {
                    if (!String.IsNullOrEmpty(item.Tutorial))
                    {
                        TutorialManager.AddTutorial(item.Name, item.Tutorial, item.Icon);
                    }
                }
            }

            Camera.World = this;
            //Drawer3D.Camera = Camera;


            #endregion

            SetLoadingMessage("Creating Particles ...");
            ParticleManager = new ParticleManager(ComponentManager);

            SetLoadingMessage("Creating GameMaster ...");
            Master = new GameMaster(Factions.Factions["Player"], Game, ComponentManager, ChunkManager,
                                    Camera, GraphicsDevice);

            // If there's no file, we have to initialize the first chunk coordinate
            if (gameFile == null)
            {
                ChunkManager.GenerateInitialChunks(SpawnRect,
                                                   new GlobalChunkCoordinate(0, 0, 0),
                                                   SetLoadingMessage);
            }

            if (gameFile != null)
            {
                if (gameFile.PlayData.Tasks != null)
                {
                    Master.NewArrivals         = gameFile.PlayData.NewArrivals ?? new List <GameMaster.ApplicantArrival>();
                    Master.TaskManager         = gameFile.PlayData.Tasks;
                    Master.TaskManager.Faction = Master.Faction;
                }
                if (gameFile.PlayData.InitialEmbark != null)
                {
                    InitialEmbark = gameFile.PlayData.InitialEmbark;
                }
                ChunkManager.World.Master.SetMaxViewingLevel(gameFile.Metadata.Slice > 0
                ? gameFile.Metadata.Slice
                : ChunkManager.World.Master.MaxViewingLevel);
            }

            if (Master.Faction.Economy.Company.Information == null)
            {
                Master.Faction.Economy.Company.Information = new CompanyInformation();
            }

            CreateInitialEmbarkment();
            foreach (var chunk in ChunkManager.ChunkData.ChunkMap)
            {
                chunk.CalculateInitialSunlight();
            }

            if (RevealSurface)
            {
                VoxelHelpers.InitialReveal(ChunkManager, ChunkManager.ChunkData, new VoxelHandle(
                                               ChunkManager.ChunkData.GetChunkEnumerator().FirstOrDefault(), new LocalVoxelCoordinate(0, VoxelConstants.ChunkSizeY - 1, 0)));
            }

            foreach (var chunk in ChunkManager.ChunkData.ChunkMap)
            {
                ChunkManager.InvalidateChunk(chunk);
            }

            SetLoadingMessage("Creating Geometry...");
            ChunkManager.GenerateAllGeometry();

            ChunkManager.StartThreads();
            SetLoadingMessage("Presimulating ...");
            ShowingWorld = false;
            OnLoadedEvent();
            Thread.Sleep(1000);

            ShowingWorld = true;

            SetLoadingMessage("Complete.");

            // GameFile is no longer needed.
            gameFile   = null;
            LoadStatus = LoadingStatus.Success;
#if !DEBUG
        }

        catch (Exception exception)
        {
            Game.CaptureException(exception);
            LoadingException = exception;
            LoadStatus       = LoadingStatus.Failure;
            ProgramData.WriteExceptionLog(exception);
        }
#endif
        }
Esempio n. 14
0
        public GameMaster(Faction faction, DwarfGame game, ComponentManager components, ChunkManager chunks, OrbitCamera camera, GraphicsDevice graphics)
        {
            TaskManager         = new TaskManager();
            TaskManager.Faction = faction;

            World   = components.World;
            Faction = faction;
            Initialize(game, components, chunks, camera, graphics);
            VoxSelector.Selected   += OnSelected;
            VoxSelector.Dragged    += OnDrag;
            BodySelector.Selected  += OnBodiesSelected;
            BodySelector.MouseOver += OnMouseOver;
            World.Master            = this;
            World.Time.NewDay      += Time_NewDay;
        }
Esempio n. 15
0
        public void GenerateInitialChunks(OrbitCamera camera, Point3 origin, ref string message)
        {
            float origBuildRadius = GenerateDistance;
            GenerateDistance = origBuildRadius * 2.0f;

            int i = 0;
            int iters = WorldSize.X * WorldSize.Y * WorldSize.Z;
            for (int dx = origin.X - WorldSize.X/2 + 1; dx < origin.X + WorldSize.X/2; dx++)
            {
                for (int dy = origin.Y - WorldSize.Y/2; dy <= origin.Y + WorldSize.Y/2; dy++)
                {
                    for (int dz = origin.Z - WorldSize.Z/2 + 1; dz < origin.Z + WorldSize.Z/2; dz++)
                    {
                        message = "Generating : " + (i + 1) + "/" + iters;
                        i++;

                        Point3 box = new Point3(dx, dy, dz);

                        if (!ChunkData.ChunkMap.ContainsKey(box))
                        {
                            Vector3 worldPos = new Vector3(box.X * ChunkData.ChunkSizeX, box.Y * ChunkData.ChunkSizeY, box.Z * ChunkData.ChunkSizeZ);
                            VoxelChunk chunk = ChunkGen.GenerateChunk(worldPos, (int)ChunkData.ChunkSizeX, (int)ChunkData.ChunkSizeY, (int)ChunkData.ChunkSizeZ, Components, Content, Graphics);
                            chunk.ShouldRebuild = true;
                            chunk.ShouldRecalculateLighting = true;
                            chunk.IsVisible = true;
                            chunk.ResetSunlight(0);
                            GeneratedChunks.Enqueue(chunk);
                            foreach (VoxelChunk chunk2 in GeneratedChunks)
                            {
                                if (!ChunkData.ChunkMap.ContainsKey(chunk2.ID))
                                {
                                    ChunkData.AddChunk(chunk2);
                                    RecalculateBounds();
                                }
                            }
                        }
                    }
                }
            }

            UpdateRebuildList();
            GenerateDistance = origBuildRadius;

            while(GeneratedChunks.Count > 0)
            {
                VoxelChunk gen = null;
                if(!GeneratedChunks.TryDequeue(out gen))
                {
                    break;
                }
            }

            ChunkData.ChunkManager.CreateGraphics(ref message, ChunkData);
        }
Esempio n. 16
0
        private void LoadThreaded()
        {
            // Ensure we're using the invariant culture.
            Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
            LoadStatus = LoadingStatus.Loading;
            SetLoadingMessage("Initializing ...");

            while (GraphicsDevice == null)
            {
                Thread.Sleep(100);
            }
            Thread.Sleep(1000);

#if CREATE_CRASH_LOGS
            try
#endif
#if !DEBUG
            try
            {
#endif
            bool fileExists = !string.IsNullOrEmpty(ExistingFile);

            SetLoadingMessage("Creating Sky...");

            Sky = new SkyRenderer(
                TextureManager.GetTexture(ContentPaths.Sky.moon),
                TextureManager.GetTexture(ContentPaths.Sky.sun),
                Content.Load <TextureCube>(ContentPaths.Sky.day_sky),
                Content.Load <TextureCube>(ContentPaths.Sky.night_sky),
                TextureManager.GetTexture(ContentPaths.Gradients.skygradient),
                Content.Load <Model>(ContentPaths.Models.sphereLowPoly),
                Content.Load <Effect>(ContentPaths.Shaders.SkySphere),
                Content.Load <Effect>(ContentPaths.Shaders.Background));

            #region Reading game file

            if (fileExists)
            {
                SetLoadingMessage("Loading " + ExistingFile);

                gameFile = SaveGame.CreateFromDirectory(ExistingFile);
                if (gameFile == null)
                {
                    throw new InvalidOperationException("Game File does not exist.");
                }

                // Todo: REMOVE THIS WHEN THE NEW SAVE SYSTEM IS COMPLETE.
                if (gameFile.Metadata.Version != Program.Version && !Program.CompatibleVersions.Contains(gameFile.Metadata.Version))
                {
                    throw new InvalidOperationException(String.Format("Game file is from version {0}. Compatible versions are {1}.", gameFile.Metadata.Version,
                                                                      TextGenerator.GetListString(Program.CompatibleVersions)));
                }
                Sky.TimeOfDay = gameFile.Metadata.TimeOfDay;
                Time          = gameFile.Metadata.Time;
                WorldOrigin   = gameFile.Metadata.WorldOrigin;
                WorldScale    = gameFile.Metadata.WorldScale;
                WorldSize     = gameFile.Metadata.NumChunks;
                GameID        = gameFile.Metadata.GameID;

                if (gameFile.Metadata.OverworldFile != null && gameFile.Metadata.OverworldFile != "flat")
                {
                    SetLoadingMessage("Loading world " + gameFile.Metadata.OverworldFile);
                    Overworld.Name = gameFile.Metadata.OverworldFile;
                    DirectoryInfo worldDirectory =
                        Directory.CreateDirectory(DwarfGame.GetWorldDirectory() +
                                                  ProgramData.DirChar + Overworld.Name);
                    var overWorldFile = new NewOverworldFile(worldDirectory.FullName);
                    Overworld.Map  = overWorldFile.Data.Data;
                    Overworld.Name = overWorldFile.Data.Name;
                }
                else
                {
                    SetLoadingMessage("Generating flat world..");
                    Overworld.CreateUniformLand(GraphicsDevice);
                }
            }

            #endregion

            #region Initialize static data

            {
                Vector3 origin  = new Vector3(WorldOrigin.X, 0, WorldOrigin.Y);
                Vector3 extents = new Vector3(1500, 1500, 1500);
                CollisionManager = new CollisionManager(new BoundingBox(origin - extents, origin + extents));

                CraftLibrary = new CraftLibrary();

                new PrimitiveLibrary(GraphicsDevice, Content);
                NewInstanceManager = new NewInstanceManager(GraphicsDevice, new BoundingBox(origin - extents, origin + extents),
                                                            Content);

                Color[] white = new Color[1];
                white[0] = Color.White;
                pixel    = new Texture2D(GraphicsDevice, 1, 1);
                pixel.SetData(white);

                Tilesheet                  = TextureManager.GetTexture(ContentPaths.Terrain.terrain_tiles);
                AspectRatio                = GraphicsDevice.Viewport.AspectRatio;
                DefaultShader              = new Shader(Content.Load <Effect>(ContentPaths.Shaders.TexturedShaders), true);
                DefaultShader.ScreenWidth  = GraphicsDevice.Viewport.Width;
                DefaultShader.ScreenHeight = GraphicsDevice.Viewport.Height;
                VoxelLibrary.InitializeDefaultLibrary(GraphicsDevice, Tilesheet);
                GrassLibrary.InitializeDefaultLibrary();
                DecalLibrary.InitializeDefaultLibrary();

                bloom = new BloomComponent(Game)
                {
                    Settings = BloomSettings.PresetSettings[5]
                };
                bloom.Initialize();


                fxaa = new FXAA();
                fxaa.Initialize();

                SoundManager.Content = Content;
                if (PlanService != null)
                {
                    PlanService.Restart();
                }

                JobLibrary.Initialize();
                MonsterSpawner = new MonsterSpawner(this);
                EntityFactory.Initialize(this);
            }

            #endregion


            SetLoadingMessage("Creating Planner ...");
            PlanService = new PlanService();

            SetLoadingMessage("Creating Shadows...");
            Shadows = new ShadowRenderer(GraphicsDevice, 1024, 1024);

            SetLoadingMessage("Creating Liquids ...");

            #region liquids

            WaterRenderer = new WaterRenderer(GraphicsDevice);

            LiquidAsset waterAsset = new LiquidAsset
            {
                Type        = LiquidType.Water,
                Opactiy     = 0.8f,
                Reflection  = 1.0f,
                WaveHeight  = 0.1f,
                WaveLength  = 0.05f,
                WindForce   = 0.001f,
                BumpTexture = TextureManager.GetTexture(ContentPaths.Terrain.water_normal),
                BaseTexture = TextureManager.GetTexture(ContentPaths.Terrain.cartoon_water),
                MinOpacity  = 0.4f,
                RippleColor = new Vector4(0.6f, 0.6f, 0.6f, 0.0f),
                FlatColor   = new Vector4(0.3f, 0.3f, 0.9f, 1.0f)
            };
            WaterRenderer.AddLiquidAsset(waterAsset);


            LiquidAsset lavaAsset = new LiquidAsset
            {
                Type        = LiquidType.Lava,
                Opactiy     = 0.95f,
                Reflection  = 0.0f,
                WaveHeight  = 0.1f,
                WaveLength  = 0.05f,
                WindForce   = 0.001f,
                MinOpacity  = 0.8f,
                BumpTexture = TextureManager.GetTexture(ContentPaths.Terrain.water_normal),
                BaseTexture = TextureManager.GetTexture(ContentPaths.Terrain.lava),
                RippleColor = new Vector4(0.5f, 0.4f, 0.04f, 0.0f),
                FlatColor   = new Vector4(0.9f, 0.7f, 0.2f, 1.0f)
            };

            WaterRenderer.AddLiquidAsset(lavaAsset);

            #endregion

            SetLoadingMessage("Generating Initial Terrain Chunks ...");

            if (!fileExists)
            {
                GameID = MathFunctions.Random.Next(0, 1024);
            }

            ChunkGenerator = new ChunkGenerator(VoxelLibrary, Seed, 0.02f, this.WorldScale)
            {
                SeaLevel = SeaLevel
            };


            #region Load Components

            if (fileExists)
            {
                ChunkManager = new ChunkManager(Content, this, Camera,
                                                GraphicsDevice,
                                                ChunkGenerator, WorldSize.X, WorldSize.Y, WorldSize.Z);

                ChunkRenderer = new ChunkRenderer(this, Camera, GraphicsDevice, ChunkManager.ChunkData);

                SetLoadingMessage("Loading Terrain...");
                gameFile.ReadChunks(ExistingFile);
                ChunkManager.ChunkData.LoadFromFile(gameFile, SetLoadingMessage);

                ChunkManager.ChunkData.SetMaxViewingLevel(gameFile.Metadata.Slice > 0
                        ? gameFile.Metadata.Slice
                        : ChunkManager.ChunkData.MaxViewingLevel, ChunkManager.SliceMode.Y);

                SetLoadingMessage("Loading Entities...");
                gameFile.LoadPlayData(ExistingFile, this);
                Camera = gameFile.PlayData.Camera;
                ChunkManager.camera  = Camera;
                ChunkRenderer.camera = Camera;
                DesignationDrawer    = gameFile.PlayData.Designations;

                Vector3 origin  = new Vector3(WorldOrigin.X, 0, WorldOrigin.Y);
                Vector3 extents = new Vector3(1500, 1500, 1500);
                CollisionManager = new CollisionManager(new BoundingBox(origin - extents, origin + extents));

                if (gameFile.PlayData.Resources != null)
                {
                    foreach (var resource in gameFile.PlayData.Resources)
                    {
                        if (!ResourceLibrary.Resources.ContainsKey(resource.Key))
                        {
                            ResourceLibrary.Add(resource.Value);
                        }
                    }
                }
                ComponentManager = new ComponentManager(gameFile.PlayData.Components, this);

                foreach (var component in gameFile.PlayData.Components.SaveableComponents)
                {
                    if (!ComponentManager.HasComponent(component.GlobalID) &&
                        ComponentManager.HasComponent(component.Parent.GlobalID))
                    {
                        // Logically impossible.
                        throw new InvalidOperationException("Component exists in save data but not in manager.");
                    }
                }

                Factions = gameFile.PlayData.Factions;
                ComponentManager.World = this;

                Sky.TimeOfDay = gameFile.Metadata.TimeOfDay;
                Time          = gameFile.Metadata.Time;
                WorldOrigin   = gameFile.Metadata.WorldOrigin;
                WorldScale    = gameFile.Metadata.WorldScale;

                // Restore native factions from deserialized data.
                Natives = new List <Faction>();
                foreach (Faction faction in Factions.Factions.Values)
                {
                    if (faction.Race.IsNative && faction.Race.IsIntelligent && !faction.IsRaceFaction)
                    {
                        Natives.Add(faction);
                    }
                }

                Diplomacy = gameFile.PlayData.Diplomacy;

                GoalManager = new Goals.GoalManager();
                GoalManager.Initialize(gameFile.PlayData.Goals);

                TutorialManager = new Tutorial.TutorialManager(Program.CreatePath("Content", "tutorial.txt"));
                TutorialManager.SetFromSaveData(gameFile.PlayData.TutorialSaveData);
            }
            else
            {
                Time = new WorldTime();
                // WorldOrigin is in "map" units. Convert to voxels
                var globalOffset = new Vector3(WorldOrigin.X, 0, WorldOrigin.Y) * WorldScale;

                Camera = new OrbitCamera(this,
                                         new Vector3(VoxelConstants.ChunkSizeX,
                                                     VoxelConstants.ChunkSizeY - 1.0f,
                                                     VoxelConstants.ChunkSizeZ) + new Vector3(WorldOrigin.X, 0, WorldOrigin.Y) * WorldScale,
                                         new Vector3(VoxelConstants.ChunkSizeY, VoxelConstants.ChunkSizeY - 1.0f,
                                                     VoxelConstants.ChunkSizeZ) + new Vector3(WorldOrigin.X, 0, WorldOrigin.Y) * WorldScale +
                                         Vector3.Up * 10.0f + Vector3.Backward * 10,
                                         MathHelper.PiOver4, AspectRatio, 0.1f,
                                         GameSettings.Default.VertexCullDistance);

                ChunkManager = new ChunkManager(Content, this, Camera,
                                                GraphicsDevice,
                                                ChunkGenerator, WorldSize.X, WorldSize.Y, WorldSize.Z);

                ChunkRenderer = new ChunkRenderer(this, Camera, GraphicsDevice, ChunkManager.ChunkData);


                var chunkOffset = GlobalVoxelCoordinate.FromVector3(globalOffset).GetGlobalChunkCoordinate();
                //var chunkOffset = ChunkManager.ChunkData.RoundToChunkCoords(globalOffset);
                //globalOffset.X = chunkOffset.X * VoxelConstants.ChunkSizeX;
                //globalOffset.Y = chunkOffset.Y * VoxelConstants.ChunkSizeY;
                //globalOffset.Z = chunkOffset.Z * VoxelConstants.ChunkSizeZ;

                WorldOrigin     = new Vector2(globalOffset.X, globalOffset.Z);
                Camera.Position = new Vector3(0, 10, 0) + globalOffset;
                Camera.Target   = new Vector3(0, 10, 1) + globalOffset;

                // If there's no file, we have to initialize the first chunk coordinate
                if (gameFile == null)     // Todo: Always true?
                {
                    ChunkManager.GenerateInitialChunks(
                        GlobalVoxelCoordinate.FromVector3(globalOffset).GetGlobalChunkCoordinate(),
                        SetLoadingMessage);
                }

                ComponentManager = new ComponentManager(this);
                ComponentManager.SetRootComponent(new Body(ComponentManager, "root", Matrix.Identity,
                                                           Vector3.Zero, Vector3.Zero, false));

                if (Natives == null)     // Todo: Always true??
                {
                    FactionLibrary library = new FactionLibrary();
                    library.Initialize(this, CompanyMakerState.CompanyInformation);
                    Natives = new List <Faction>();
                    for (int i = 0; i < 10; i++)
                    {
                        Natives.Add(library.GenerateFaction(this, i, 10));
                    }
                }

                #region Prepare Factions

                foreach (Faction faction in Natives)
                {
                    faction.World = this;

                    if (faction.RoomBuilder == null)
                    {
                        faction.RoomBuilder = new RoomBuilder(faction, this);
                    }

                    if (faction.CraftBuilder == null)
                    {
                        faction.CraftBuilder = new CraftBuilder(faction, this);
                    }
                }

                Factions = new FactionLibrary();
                if (Natives != null && Natives.Count > 0)
                {
                    Factions.AddFactions(this, Natives);
                }

                Factions.Initialize(this, CompanyMakerState.CompanyInformation);
                Point playerOrigin = new Point((int)(WorldOrigin.X), (int)(WorldOrigin.Y));

                Factions.Factions["Player"].Center         = playerOrigin;
                Factions.Factions["The Motherland"].Center = new Point(playerOrigin.X + 50, playerOrigin.Y + 50);

                #endregion

                Diplomacy = new Diplomacy(this);
                Diplomacy.Initialize(Time.CurrentDate);

                // Initialize goal manager here.
                GoalManager = new Goals.GoalManager();
                GoalManager.Initialize(new List <Goals.Goal>());

                TutorialManager = new Tutorial.TutorialManager(Program.CreatePath("Content", "tutorial.txt"));
                TutorialManager.TutorialEnabled = !GameSettings.Default.TutorialDisabledGlobally;
                Tutorial("new game start");
            }

            Camera.World = this;
            //Drawer3D.Camera = Camera;


            #endregion

            ChunkManager.camera = Camera;

            SetLoadingMessage("Creating Particles ...");
            ParticleManager = new ParticleManager(GraphicsDevice, ComponentManager);

            SetLoadingMessage("Creating GameMaster ...");
            Master = new GameMaster(Factions.Factions["Player"], Game, ComponentManager, ChunkManager,
                                    Camera, GraphicsDevice);

            if (gameFile != null)
            {
                if (gameFile.PlayData.Spells != null)
                {
                    Master.Spells = gameFile.PlayData.Spells;
                }
                if (gameFile.PlayData.Tasks != null)
                {
                    Master.TaskManager = gameFile.PlayData.Tasks;
                }
            }

            if (Master.Faction.Economy.Company.Information == null)
            {
                Master.Faction.Economy.Company.Information = new CompanyInformation();
            }

            CreateInitialEmbarkment();
            foreach (var chunk in ChunkManager.ChunkData.ChunkMap)
            {
                chunk.CalculateInitialSunlight();
            }
            VoxelHelpers.InitialReveal(ChunkManager.ChunkData, new VoxelHandle(
                                           ChunkManager.ChunkData.GetChunkEnumerator().FirstOrDefault(), new LocalVoxelCoordinate(0, VoxelConstants.ChunkSizeY - 1, 0)));

            foreach (var chunk in ChunkManager.ChunkData.ChunkMap)
            {
                ChunkManager.InvalidateChunk(chunk);
            }

            ChunkManager.StartThreads();
            SetLoadingMessage("Presimulating ...");
            ShowingWorld = false;
            OnLoadedEvent();

            Thread.Sleep(1000);
            ShowingWorld = true;

            SetLoadingMessage("Complete.");

            // GameFile is no longer needed.
            gameFile   = null;
            LoadStatus = LoadingStatus.Success;
#if !DEBUG
        }

        catch (Exception exception)
        {
            Game.CaptureException(exception);
            LoadingException = exception;
            LoadStatus       = LoadingStatus.Failure;
        }
#endif
        }
Esempio n. 17
0
        public Minimap(DwarfGUI gui, GUIComponent parent, int width, int height, PlayState playState, Texture2D colormap, Texture2D frame)
            : base(gui, parent, new ImageFrame())
        {
            Frame = frame;
            SuppressClick = false;
            ColorMap = colormap;

            RenderWidth = width;
            RenderHeight = height;
            RenderTarget = new RenderTarget2D(GameState.Game.GraphicsDevice, RenderWidth, RenderHeight, false, SurfaceFormat.Color, DepthFormat.Depth24);
            Image.Image = RenderTarget;
            Image.SourceRect = new Rectangle(0, 0, RenderWidth, RenderHeight);
            PlayState = playState;

            ConstrainSize = true;

            Camera = new OrbitCamera(0, 0, 0.01f, new Vector3(0, 0, 0), new Vector3(0, 0, 0),  2.5f, 1.0f, 0.1f, 1000.0f)
            {
                Projection = global::DwarfCorp.Camera.ProjectionMode.Orthographic
            };

            ZoomInButton = new Button(GUI, this, "", GUI.SmallFont, Button.ButtonMode.ImageButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.ZoomIn))
            {
                LocalBounds = new Rectangle(1, 1, 32, 32),
                ToolTip =  "Zoom in"
            };

            ZoomInButton.OnClicked += zoomInButton_OnClicked;

            ZoomOutButton = new Button(GUI, this, "", GUI.SmallFont, Button.ButtonMode.ImageButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.ZoomOut))
            {
                LocalBounds = new Rectangle(33, 1, 32, 32),
                ToolTip =  "Zoom out"
            };

            ZoomOutButton.OnClicked += zoomOutButton_OnClicked;

            ZoomHomeButton = new Button(GUI, this, "", GUI.SmallFont, Button.ButtonMode.ImageButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.ZoomHome))
            {
                LocalBounds = new Rectangle(65, 1, 32, 32),
                ToolTip =  "Home camera"
            };

            ZoomHomeButton.OnClicked +=ZoomHomeButton_OnClicked;

            MinimizeButton = new Button(GUI, this, "", GUI.SmallFont, Button.ButtonMode.ImageButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.SmallArrowDown))
            {
                LocalBounds = new Rectangle(width - 32, 0, 32, 32),
                ToolTip = "Show/Hide Map"
            };

            MinimizeButton.OnClicked += MinimizeButton_OnClicked;

            OnClicked += Minimap_OnClicked;
        }