Exemple #1
0
 public GameMaster(Faction faction, DwarfGame game, ComponentManager components, ChunkManager chunks, Camera camera, GraphicsDevice graphics, DwarfGUI gui)
 {
     Faction = faction;
     Initialize(game, components, chunks, camera, graphics, gui);
     VoxSelector.Selected += OnSelected;
     BodySelector.Selected += OnBodiesSelected;
     PlayState.Time.NewDay += Time_NewDay;
 }
Exemple #2
0
        public override void Render(DwarfTime gameTime, ChunkManager chunks, Camera camera, SpriteBatch spriteBatch, GraphicsDevice graphicsDevice, Effect effect, bool renderingForWater)
        {
            base.Render(gameTime, chunks, camera, spriteBatch, graphicsDevice, effect, renderingForWater);
            effect.Parameters["xTexture"].SetValue(Texture);
            effect.Parameters["xWorld"].SetValue(GlobalTransform);

            foreach(EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                Primitive.Render(graphicsDevice);
            }
        }
Exemple #3
0
 public BodySelector(Camera camera, GraphicsDevice graphics, ComponentManager components)
 {
     AllowRightClickSelection = true;
     SelectionColor = Color.White;
     SelectionWidth = 0.1f;
     CurrentWidth = 0.08f;
     CurrentColor = Color.White;
     CameraController = camera;
     Graphics = graphics;
     Components = components;
     SelectionBuffer = new List<Body>();
     LeftReleased = LeftReleasedCallback;
     RightReleased = RightReleasedCallback;
     Selected += SelectedCallback;
     Enabled = true;
     DeleteColor = Color.Red;
     BoxYOffset = 0;
     LastMouseWheel = 0;
     SelectionRectangle = new Rectangle(0, 0, 0, 0);
 }
Exemple #4
0
 public VoxelSelector(Camera camera, GraphicsDevice graphics, ChunkManager chunks)
 {
     SelectionType = VoxelSelectionType.SelectEmpty;
     SelectionColor = Color.White;
     SelectionWidth = 0.1f;
     CurrentWidth = 0.08f;
     CurrentColor = Color.White;
     CameraController = camera;
     Graphics = graphics;
     Chunks = chunks;
     SelectionBuffer =
      new List<Voxel>();
     LeftPressed = LeftPressedCallback;
     RightPressed = RightPressedCallback;
     LeftReleased = LeftReleasedCallback;
     RightReleased = RightReleasedCallback;
     Selected = SelectedCallback;
     Enabled = true;
     DeleteColor = Color.Red;
     BoxYOffset = 0;
     LastMouseWheel = 0;
 }
Exemple #5
0
        public void Update(DwarfTime gameTime, Camera camera, GraphicsDevice g)
        {
            UpdateRenderList(camera);

            if (waterUpdateTimer.Update(gameTime))
            {
                WaterUpdateEvent.Set();
            }

            UpdateRebuildList();

            generateChunksTimer.Update(gameTime);
            if(generateChunksTimer.HasTriggered)
            {
                if(ToGenerate.Count > 0)
                {
                    NeedsGenerationEvent.Set();
                    ChunkData.RecomputeNeighbors();
                }

                foreach(VoxelChunk chunk in GeneratedChunks)
                {
                    if(!ChunkData.ChunkMap.ContainsKey(chunk.ID))
                    {
                        ChunkData.AddChunk(chunk);
                        ChunkGen.GenerateVegetation(chunk, Components, Content, Graphics);
                        ChunkGen.GenerateFauna(chunk, Components, Content, Graphics, PlayState.ComponentManager.Factions);
                        List<VoxelChunk> adjacents = ChunkData.GetAdjacentChunks(chunk);
                        foreach(VoxelChunk c in adjacents)
                        {
                            c.ShouldRecalculateLighting = true;
                            c.ShouldRebuild = true;
                        }
                        RecalculateBounds();
                    }
                }

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

            visibilityChunksTimer.Update(gameTime);
            if(visibilityChunksTimer.HasTriggered)
            {
                visibleSet.Clear();
                GetChunksIntersecting(camera.GetFrustrum(), visibleSet);
                //RemoveDistantBlocks(camera);
            }

            foreach(VoxelChunk chunk in ChunkData.ChunkMap.Values)
            {
                chunk.Update(gameTime);
            }

            Water.Splash(gameTime);
            Water.HandleTransfers(gameTime);

            HashSet<VoxelChunk> affectedChunks = new HashSet<VoxelChunk>();
            foreach (Voxel voxel in KilledVoxels)
            {
                affectedChunks.Add(voxel.Chunk);
                voxel.Chunk.NotifyDestroyed(new Point3(voxel.GridPosition));
                if (!voxel.IsInterior)
                {
                    foreach (KeyValuePair<Point3, VoxelChunk> n in voxel.Chunk.Neighbors)
                    {
                        affectedChunks.Add(n.Value);
                    }
                }
            }

            lock (RebuildList)
            {
                foreach (VoxelChunk affected in affectedChunks)
                {
                    affected.NotifyTotalRebuild(false);
                }
            }
            KilledVoxels.Clear();
        }
Exemple #6
0
        public void Update(DwarfTime gameTime, Camera camera, GraphicsDevice g)
        {
            UpdateRenderList(camera);

            if (waterUpdateTimer.Update(gameTime))
            {
                WaterUpdateEvent.Set();
            }

            UpdateRebuildList();

            generateChunksTimer.Update(gameTime);
            if(generateChunksTimer.HasTriggered)
            {
                if(ToGenerate.Count > 0)
                {
                    NeedsGenerationEvent.Set();
                    ChunkData.RecomputeNeighbors();
                }

                foreach(VoxelChunk chunk in GeneratedChunks)
                {
                    if(!ChunkData.ChunkMap.ContainsKey(chunk.ID))
                    {
                        ChunkData.AddChunk(chunk);
                        ChunkGen.GenerateVegetation(chunk, Components, Content, Graphics);
                        ChunkGen.GenerateFauna(chunk, Components, Content, Graphics, PlayState.ComponentManager.Factions);
                        List<VoxelChunk> adjacents = ChunkData.GetAdjacentChunks(chunk);
                        foreach(VoxelChunk c in adjacents)
                        {
                            c.ShouldRecalculateLighting = true;
                            c.ShouldRebuild = true;
                        }
                        RecalculateBounds();
                    }
                }

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


            visibilityChunksTimer.Update(gameTime);
            if(visibilityChunksTimer.HasTriggered)
            {
                visibleSet.Clear();
                GetChunksIntersecting(camera.GetFrustrum(), visibleSet);
                //RemoveDistantBlocks(camera);
            }


            foreach(VoxelChunk chunk in ChunkData.ChunkMap.Values)
            {
                chunk.Update(gameTime);
            }

            Water.Splash(gameTime);
            Water.HandleTransfers(gameTime);

            HashSet<VoxelChunk> affectedChunks = new HashSet<VoxelChunk>();
            
            foreach (Voxel voxel in KilledVoxels)
            {
                affectedChunks.Add(voxel.Chunk);
                voxel.Chunk.NotifyDestroyed(new Point3(voxel.GridPosition));
                if (!voxel.IsInterior)
                {
                    foreach (KeyValuePair<Point3, VoxelChunk> n in voxel.Chunk.Neighbors)
                    {
                        affectedChunks.Add(n.Value);
                    }
                }
            }

            if (GameSettings.Default.FogofWar)
            {
                ChunkData.Reveal(KilledVoxels);
            }

            lock (RebuildList)
            {
                foreach (VoxelChunk affected in affectedChunks)
                {
                    affected.NotifyTotalRebuild(false);
                }
            }
            KilledVoxels.Clear();
        }
        public override void Render(SpriteBatch batch, Camera camera, Viewport viewport)
        {
            if(Points.Count <= 1)
            {
                return;
            }

            for(int i = 0; i < Points.Count - 1; i++)
            {
                Drawer2D.DrawLine(batch, Points[i], Points[i + 1], LineColor, LineWidth);
            }

            if(IsClosed && Points.Count > 2)
            {
                Drawer2D.DrawLine(batch, Points.Last(), Points.First(), LineColor, LineWidth);
            }
        }
        public List <Body> FrustrumCullLocatableComponents(Camera camera)
        {
            List <Body> visible = CollisionManager.GetVisibleObjects <Body>(camera.GetFrustrum(), CollisionManager.CollisionType.Dynamic | CollisionManager.CollisionType.Static);

            return(visible);
        }
Exemple #9
0
        public Voxel GetFirstVisibleBlockHitByScreenCoord(int x, int y, Camera camera, Viewport viewPort, float dist, bool draw = false, bool selectEmpty = false)
        {
            Vector3 pos1 = viewPort.Unproject(new Vector3(x, y, 0), camera.ProjectionMatrix, camera.ViewMatrix, Matrix.Identity);
            Vector3 pos2 = viewPort.Unproject(new Vector3(x, y, 1), camera.ProjectionMatrix, camera.ViewMatrix, Matrix.Identity);
            Vector3 dir = Vector3.Normalize(pos2 - pos1);
            Voxel vox = GetFirstVisibleBlockHitByRay(pos1, pos1 + dir * dist, draw, selectEmpty);

            return vox;
        }
Exemple #10
0
        public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            bool got = false;
            foreach (var faction in Manager.Factions.Factions)
            {
                if (faction.Value.Name == Faction.Name) continue;
                else if (PlayState.Diplomacy.GetPolitics(Faction, faction.Value).GetCurrentRelationship() != Relationship.Loves)
                {
                    foreach (CreatureAI creature in faction.Value.Minions)
                    {
                        if ((creature.Position - Position).LengthSquared() < DamageRadius)
                        {
                            creature.Creature.Damage(Damage.Amount, Damage.DamageType);
                            got = true;
                            break;
                        }
                    }
                }

                if (got) break;
            }

            if (got)
            {
                Die();
            }

            base.Update(gameTime, chunks, camera);
        }
Exemple #11
0
        public void DrawWater(GraphicsDevice device,
            float time,
            Effect effect,
            Matrix viewMatrix,
            Matrix reflectionViewMatrix,
            Matrix projectionMatrix,
            Vector3 windDirection,
            Camera camera,
            ChunkManager chunks)
        {
            effect.CurrentTechnique = effect.Techniques["Water"];
            Matrix worldMatrix = Matrix.Identity;
            effect.Parameters["xWorld"].SetValue(worldMatrix);
            effect.Parameters["xView"].SetValue(viewMatrix);
            effect.Parameters["xReflectionView"].SetValue(reflectionViewMatrix);
            effect.Parameters["xProjection"].SetValue(projectionMatrix);
            effect.Parameters["xReflectionMap"].SetValue(ReflectionMap);
            effect.Parameters["xRefractionMap"].SetValue(RefractionMap);
            effect.Parameters["xTime"].SetValue(time);
            effect.Parameters["xWindDirection"].SetValue(windDirection);
            effect.Parameters["xCamPos"].SetValue(camera.Position);

            foreach (KeyValuePair<LiquidType, LiquidAsset> asset in LiquidAssets)
            {
                effect.Parameters["xWaveLength"].SetValue(asset.Value.WaveLength);
                effect.Parameters["xWaveHeight"].SetValue(asset.Value.WaveHeight);
                effect.Parameters["xWindForce"].SetValue(asset.Value.WindForce);
                effect.Parameters["xWaterBumpMap"].SetValue(asset.Value.BumpTexture);
                effect.Parameters["xTexture"].SetValue(asset.Value.BaseTexture);
                effect.Parameters["xTexture1"].SetValue(asset.Value.FoamTexture);
                effect.Parameters["xWaterOpacity"].SetValue(asset.Value.Opactiy);
                effect.Parameters["xWaterMinOpacity"].SetValue(asset.Value.MinOpacity);
                effect.Parameters["xWaterSloshOpacity"].SetValue(asset.Value.SloshOpacity);
                effect.Parameters["xRippleColor"].SetValue(asset.Value.RippleColor);

                foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    foreach (KeyValuePair<Point3, VoxelChunk> chunkpair in chunks.ChunkData.ChunkMap)
                    {
                        VoxelChunk chunk = chunkpair.Value;
                        if (chunk.IsVisible)
                        {
                            //chunk.PrimitiveMutex.WaitOne();
                            chunk.Liquids[asset.Key].Render(device);
                            //chunk.PrimitiveMutex.ReleaseMutex();
                        }
                    }
                }
            }
        }
Exemple #12
0
        public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            BoundingBox bounds = chunks.Bounds;
            bounds.Max.Y += 50;

            if (!IsSleeping && (Velocity).Length() < 0.15f)
            {
                SleepTimer.Update(gameTime);
                if (SleepTimer.HasTriggered)
                {
                    applyGravityThisFrame = false;
                    Velocity *= 0.0f;
                    IsSleeping = true;
                }

            }
            else
            {
                SleepTimer.Reset();
                IsSleeping = false;
            }

            if(!IsSleeping || overrideSleepThisFrame)
            {
                if(overrideSleepThisFrame)
                {
                    overrideSleepThisFrame = false;
                }

                float dt = (float)(gameTime.ElapsedGameTime.TotalSeconds);

                if (MathFunctions.HasNan(Velocity))
                {
                    Velocity = Vector3.Zero;
                }

                MoveY(dt);
                MoveX(dt);
                MoveZ(dt);
                HandleCollisions(chunks, dt);

                Matrix transform = LocalTransform;
                if (bounds.Contains(LocalTransform.Translation + Velocity*dt) != ContainmentType.Contains)
                {
                    transform.Translation = LocalTransform.Translation - 0.1f * Velocity * dt;
                    Velocity = new Vector3(Velocity.X * -0.9f, Velocity.Y, Velocity.Z * -0.9f);
                }

                if (LocalTransform.Translation.Z < -10 || bounds.Contains(GetBoundingBox()) == ContainmentType.Disjoint)
                {
                    Die();
                }

                if(Orientation == OrientMode.Physics)
                {
                    Matrix dA = Matrix.Identity;
                    dA *= Matrix.CreateRotationX(AngularVelocity.X * dt);
                    dA *= Matrix.CreateRotationY(AngularVelocity.Y * dt);
                    dA *= Matrix.CreateRotationZ(AngularVelocity.Z * dt);

                    transform = dA * transform;
                }
                else if(Orientation != OrientMode.Fixed)
                {
                    if(Velocity.Length() > 0.4f)
                    {
                        if (Orientation == OrientMode.LookAt)
                        {
                            Matrix newTransform =
                                Matrix.Invert(Matrix.CreateLookAt(Position, Position + Velocity, Vector3.Down));
                            newTransform.Translation = transform.Translation;
                            transform = newTransform;
                        }
                        else if (Orientation == OrientMode.RotateY)
                        {

                            Rotation = (float) Math.Atan2(Velocity.X, -Velocity.Z);
                            Quaternion newRotation = Quaternion.CreateFromRotationMatrix(Matrix.CreateRotationY(Rotation));
                            Quaternion oldRotation = Quaternion.CreateFromRotationMatrix(LocalTransform);
                            Quaternion finalRot = Quaternion.Slerp(oldRotation, newRotation, 0.1f);
                            finalRot.Normalize();
                            Matrix newTransform = Matrix.CreateFromQuaternion(finalRot);
                            newTransform.Translation = transform.Translation;
                            newTransform.Right.Normalize();
                            newTransform.Up.Normalize();
                            newTransform.Forward.Normalize();
                            newTransform.M14 = 0;
                            newTransform.M24 = 0;
                            newTransform.M34 = 0;
                            newTransform.M44 = 1;
                            transform = newTransform;
                        }
                    }
                }

                transform.Translation = ClampToBounds(transform.Translation);
                LocalTransform = transform;

                if(Math.Abs(Velocity.Y) < 0.1f)
                {
                    Velocity = new Vector3(Velocity.X * Friction, Velocity.Y, Velocity.Z * Friction);
                }

                if (applyGravityThisFrame)
                {
                    ApplyForce(Gravity, dt);
                }
                else
                {
                    applyGravityThisFrame = true;
                }

                Velocity *= LinearDamping;
                AngularVelocity *= AngularDamping;
                UpdateBoundingBox();
            }
            CheckLiquids(chunks, (float)gameTime.ElapsedGameTime.TotalSeconds);
            Velocity = (PreviousVelocity * 0.1f + Velocity * 0.9f);
            PreviousVelocity = Velocity;
            PreviousPosition = Position;
            base.Update(gameTime, chunks, camera);
        }
Exemple #13
0
 public override void Render(SpriteBatch batch, Camera camera, Viewport viewport)
 {
     Drawer2D.FillRect(batch, Bounds, FillColor);
     Drawer2D.DrawRect(batch, Bounds, StrokeColor, StrokeWeight);
 }
Exemple #14
0
 public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
 {
     base.Update(gameTime, chunks, camera);
     Physics prev, next;
     prev = null;
     next = Physics;
     for (int i = 0; i < 5; i++)
     {
         prev = next;
         next = Tail[i];
         Vector3 prevT, nextT, distance;
         prevT = prev.GlobalTransform.Translation;
         nextT = next.GlobalTransform.Translation;
         distance = prevT - nextT;
         if (distance.LengthSquared() < .2f)
         {
             prev.ApplyForce(distance * 1f, 1);
             next.ApplyForce(distance * -1f, 1);
         }
         else
         {
             prev.ApplyForce(distance * -1f, 1);
             next.ApplyForce(distance * 1f, 1);
         }
     }
 }
Exemple #15
0
        public override void Render(DwarfTime gameTime, ChunkManager chunks, Camera camera, Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch, Microsoft.Xna.Framework.Graphics.GraphicsDevice graphicsDevice, Microsoft.Xna.Framework.Graphics.Effect effect, bool renderingForWater)
        {
            if (GUIObject != null)
            {
                if (Enabled && IsVisible && camera.IsInView(GetBoundingBox()))
                {
                    Vector3 screenPos = camera.Project(GlobalTransform.Translation);
                    GUIObject.LocalBounds = new Rectangle((int) screenPos.X - GUIObject.LocalBounds.Width/2,
                        (int) screenPos.Y - GUIObject.LocalBounds.Height/2, GUIObject.LocalBounds.Width,
                        GUIObject.LocalBounds.Height);

                    GUIObject.IsVisible = true;
                }
                else
                {
                    GUIObject.IsVisible = false;
                }
            }
            base.Render(gameTime, chunks, camera, spriteBatch, graphicsDevice, effect, renderingForWater);
        }
Exemple #16
0
        public bool IsVisibleToCamera(Body component, Camera camera)
        {
            BoundingFrustum frustrum = new BoundingFrustum(camera.ViewMatrix * camera.ProjectionMatrix);

            return(component.Intersects(frustrum));
        }
Exemple #17
0
        public void Render(DwarfTime gameTime,
                           ChunkManager chunks,
                           Camera camera,
                           SpriteBatch spriteBatch,
                           GraphicsDevice graphicsDevice,
                           Effect effect,
                           WaterRenderType waterRenderMode, float waterLevel)
        {
            bool renderForWater = (waterRenderMode != WaterRenderType.None);

            if (!renderForWater)
            {
                visibleComponents.Clear();
                componentsToDraw.Clear();


                List <Body> list = FrustrumCullLocatableComponents(camera);
                foreach (Body component in list)
                {
                    visibleComponents.Add(component);
                }


                Camera = camera;
                foreach (GameComponent component in Components.Values)
                {
                    bool isLocatable = component is Body;

                    if (isLocatable)
                    {
                        Body loc = (Body)component;


                        if (((loc.GlobalTransform.Translation - camera.Position).LengthSquared() < chunks.DrawDistanceSquared &&
                             visibleComponents.Contains(loc) || !(loc.FrustrumCull) || !(loc.WasAddedToOctree) && !loc.IsAboveCullPlane)
                            )
                        {
                            componentsToDraw.Add(component);
                        }
                    }
                    else
                    {
                        componentsToDraw.Add(component);
                    }
                }
            }


            effect.Parameters["xEnableLighting"].SetValue(GameSettings.Default.CursorLightEnabled ? 1 : 0);
            graphicsDevice.RasterizerState = RasterizerState.CullNone;

            foreach (GameComponent component in componentsToDraw)
            {
                if (waterRenderMode == WaterRenderType.Reflective && !RenderReflective(component, waterLevel))
                {
                    continue;
                }
                component.Render(gameTime, chunks, camera, spriteBatch, graphicsDevice, effect, renderForWater);
            }

            effect.Parameters["xEnableLighting"].SetValue(0);
        }
Exemple #18
0
        public ChunkManager(ContentManager content, 
            uint chunkSizeX, uint chunkSizeY, uint chunkSizeZ,
            Camera camera, GraphicsDevice graphics, Texture2D tilemap,
            Texture2D illumMap, Texture2D sunMap, Texture2D ambientMap,
            Texture2D torchMap, ChunkGenerator chunkGen, int maxChunksX, int maxChunksY, int maxChunksZ)
        {
            KilledVoxels = new List<Voxel>();
            ExitThreads = false;
            drawDistSq = DrawDistance * DrawDistance;
            Content = content;

            chunkData = new ChunkData(chunkSizeX, chunkSizeY, chunkSizeZ, 1.0f / chunkSizeX, 1.0f / chunkSizeY, 1.0f / chunkSizeZ, tilemap, illumMap, this);
            ChunkData.ChunkMap = new ConcurrentDictionary<Point3, VoxelChunk>();
            RenderList = new ConcurrentQueue<VoxelChunk>();
            RebuildList = new ConcurrentQueue<VoxelChunk>();
            RebuildLiquidsList = new ConcurrentQueue<VoxelChunk>();
            ChunkGen = chunkGen;

            GeneratedChunks = new ConcurrentQueue<VoxelChunk>();
            GeneratorThread = new Thread(GenerateThread);

            RebuildThread = new Thread(RebuildVoxelsThread);
            RebuildLiquidThread = new Thread(RebuildLiquidsThread);

            WaterThread = new Thread(UpdateWaterThread);

            ToGenerate = new List<Point3>();
            Graphics = graphics;

            chunkGen.Manager = this;

            ChunkData.MaxViewingLevel = chunkSizeY;

            GameSettings.Default.ChunkGenerateTime = 0.5f;
            generateChunksTimer = new Timer(GameSettings.Default.ChunkGenerateTime, false, Timer.TimerMode.Real);
            GameSettings.Default.ChunkRebuildTime = 0.1f;
            Timer rebuildChunksTimer = new Timer(GameSettings.Default.ChunkRebuildTime, false, Timer.TimerMode.Real);
            GameSettings.Default.VisibilityUpdateTime = 0.05f;
            visibilityChunksTimer = new Timer(GameSettings.Default.VisibilityUpdateTime, false, Timer.TimerMode.Real);
            generateChunksTimer.HasTriggered = true;
            rebuildChunksTimer.HasTriggered = true;
            visibilityChunksTimer.HasTriggered = true;
            this.camera = camera;

            Water = new WaterManager(this);

            ChunkData.SunMap = sunMap;
            ChunkData.AmbientMap = ambientMap;
            ChunkData.TorchMap = torchMap;

            DynamicLights = new List<DynamicLight>();

            ChunkData.Slice = SliceMode.Y;
            PauseThreads = false;

            WorldSize = new Point3(maxChunksX, maxChunksY, maxChunksZ);

            Vector3 maxBounds = new Vector3(maxChunksX * chunkSizeX * 0.5f, maxChunksY * chunkSizeY * 0.5f, maxChunksZ * chunkSizeZ * 0.5f);
            Vector3 minBounds = -maxBounds;
            Bounds = new BoundingBox(minBounds, maxBounds);
        }
Exemple #19
0
 public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
 {
     base.Update(gameTime, chunks, camera);
 }
Exemple #20
0
        public void UpdateRenderList(Camera camera)
        {
            while(RenderList.Count > 0)
            {
                VoxelChunk result;
                if(!RenderList.TryDequeue(out result))
                {
                    break;
                }
            }

            foreach(VoxelChunk chunk in visibleSet)
            {
                BoundingBox box = chunk.GetBoundingBox();

                if((camera.Position - (box.Min + box.Max) * 0.5f).Length() < DrawDistance)
                {
                    chunk.IsVisible = true;
                    RenderList.Enqueue(chunk);
                }
                else
                {
                    chunk.IsVisible = false;
                }
            }
        }
Exemple #21
0
 public override void Render(DwarfTime gameTime, ChunkManager chunks, Camera camera, SpriteBatch spriteBatch,
     GraphicsDevice graphicsDevice, Effect effect, bool renderingForWater)
 {
     if (!isBlinking)
     {
         base.Render(gameTime, chunks, camera, spriteBatch, graphicsDevice, effect, renderingForWater);
     }
     else
     {
         if (blinkTimer.CurrentTimeSeconds < 0.5f*blinkTimer.TargetTimeSeconds)
         {
             base.Render(gameTime, chunks, camera, spriteBatch, graphicsDevice, effect, renderingForWater);
         }
     }
 }
Exemple #22
0
        public float GetVisibleWaterHeight(ChunkManager chunkManager, Camera camera, Viewport port, float defaultHeight)
        {
            Voxel vox = chunkManager.ChunkData.GetFirstVisibleBlockHitByScreenCoord(port.Width / 2, port.Height / 2, camera, port, 100.0f);

            if(vox != null)
            {
                float h = vox.Chunk.GetTotalWaterHeightCells(vox) - 0.75f;
                if(h < 0.01f)
                {
                    return defaultHeight;
                }

                return (h + vox.Position.Y + defaultHeight) / 2.0f + 0.5f;
            }
            else
            {
                return defaultHeight;
            }
        }
Exemple #23
0
        public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            if (ShouldDie)
            {
                DeathTimer.Update(gameTime);

                if (DeathTimer.HasTriggered)
                {
                    Die();
                }
            }
            base.Update(gameTime, chunks, camera);
        }
Exemple #24
0
 public Voxel GetFirstVisibleBlockHitByMouse(MouseState mouse, Camera camera, Viewport viewPort, bool selectEmpty = false)
 {
     Voxel vox = GetFirstVisibleBlockHitByScreenCoord(mouse.X, mouse.Y, camera, viewPort, 150.0f, false, selectEmpty);
     return vox;
 }
Exemple #25
0
        public override void Render(DwarfTime gameTime,
            ChunkManager chunks,
            Camera camera,
            SpriteBatch spriteBatch,
            GraphicsDevice graphicsDevice,
            Effect effect,
            bool renderingForWater)
        {
            base.Render(gameTime, chunks, camera, spriteBatch, graphicsDevice, effect, renderingForWater);

            if(!IsVisible)
            {
                return;
            }

            if (CurrentAnimation != null && CurrentAnimation.CurrentFrame >= 0 && CurrentAnimation.CurrentFrame < CurrentAnimation.Primitives.Count)
            {
                CurrentAnimation.PreRender();
                SpriteSheet = CurrentAnimation.SpriteSheet;
                effect.Parameters["xTexture"].SetValue(SpriteSheet.GetTexture());

                if(OrientationType != OrientMode.Fixed)
                {
                    if(camera.Projection == Camera.ProjectionMode.Perspective)
                    {
                        if(OrientationType == OrientMode.Spherical)
                        {
                            float xscale = GlobalTransform.Left.Length();
                            float yscale = GlobalTransform.Up.Length();
                            float zscale = GlobalTransform.Forward.Length();
                            Matrix rot = Matrix.CreateRotationZ(BillboardRotation);
                            Matrix bill = Matrix.CreateBillboard(GlobalTransform.Translation, camera.Position, camera.UpVector, null);
                            Matrix noTransBill = bill;
                            noTransBill.Translation = Vector3.Zero;

                            Matrix worldRot = Matrix.CreateScale(new Vector3(xscale, yscale, zscale)) * rot * noTransBill;
                            worldRot.Translation = bill.Translation;
                            effect.Parameters["xWorld"].SetValue(worldRot);
                        }
                        else
                        {
                            Vector3 axis = Vector3.Zero;

                            switch(OrientationType)
                            {
                                case OrientMode.XAxis:
                                    axis = Vector3.UnitX;
                                    break;
                                case OrientMode.YAxis:
                                    axis = Vector3.UnitY;
                                    break;
                                case OrientMode.ZAxis:
                                    axis = Vector3.UnitZ;
                                    break;
                            }

                            Matrix worldRot = Matrix.CreateConstrainedBillboard(GlobalTransform.Translation, camera.Position, axis, null, null);
                            effect.Parameters["xWorld"].SetValue(worldRot);
                        }
                    }
                    else
                    {
                        Matrix rotation = Matrix.CreateRotationY(-(float) Math.PI * 0.25f) * Matrix.CreateTranslation(GlobalTransform.Translation);
                        effect.Parameters["xWorld"].SetValue(rotation);
                    }
                }
                else
                {
                    effect.Parameters["xWorld"].SetValue(GlobalTransform);
                }

                foreach(EffectPass pass in effect.CurrentTechnique.Passes)
                {
                    pass.Apply();
                    CurrentAnimation.Primitives[CurrentAnimation.CurrentFrame].Render(graphicsDevice);
                }
            }
        }
Exemple #26
0
        public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            Vector3 targetVelocity = TargetPosition - Body.GlobalTransform.Translation;

            if(targetVelocity.LengthSquared() > 0.0001f)
            {
                targetVelocity.Normalize();
                targetVelocity *= MaxVelocity;
            }

            Matrix m = Body.LocalTransform;
            m.Translation += targetVelocity * (float)gameTime.ElapsedGameTime.TotalSeconds;
            Body.LocalTransform = m;

            Body.HasMoved = true;

            switch(State)
            {
                case BalloonState.DeliveringGoods:
                    VoxelChunk chunk = chunks.ChunkData.GetVoxelChunkAtWorldLocation(Body.GlobalTransform.Translation);

                    if(chunk != null)
                    {
                        Vector3 gridPos = chunk.WorldToGrid(Body.GlobalTransform.Translation);
                        float height = chunk.GetFilledVoxelGridHeightAt((int) gridPos.X, (int) gridPos.Y, (int) gridPos.Z) + chunk.Origin.Y;
                        TargetPosition = new Vector3(Body.GlobalTransform.Translation.X, height + 5, Body.GlobalTransform.Translation.Z);

                        Vector3 diff = Body.GlobalTransform.Translation - TargetPosition;

                        if(diff.LengthSquared() < 2)
                        {
                            State = BalloonState.Waiting;
                        }
                    }
                    else
                    {
                        State = BalloonState.Leaving;
                    }

                    break;
                case BalloonState.Leaving:
                    TargetPosition = Vector3.UnitY * 100 + Body.GlobalTransform.Translation;

                    if(Body.GlobalTransform.Translation.Y > 300)
                    {
                        Die();
                    }

                    break;
                case BalloonState.Waiting:
                    TargetPosition = Body.GlobalTransform.Translation;

                    if(!shipmentGiven)
                    {

                        shipmentGiven = true;
                    }
                    else
                    {
                        State = BalloonState.Leaving;
                    }

                    break;
            }

            base.Update(gameTime, chunks, camera);
        }
Exemple #27
0
        public void GetBodiesVisibleToCamera(Camera camera, List <Body> components)
        {
            BoundingFrustum frustrum = new BoundingFrustum(camera.ViewMatrix * camera.ProjectionMatrix);

            GetBodiesIntersecting(frustrum, components, CollisionManager.CollisionType.Dynamic | CollisionManager.CollisionType.Static);
        }
Exemple #28
0
        public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            if(isBlinking)
            {
                blinkTrigger.Update(gameTime);

                if(blinkTrigger.HasTriggered)
                {
                    isBlinking = false;
                    isCoolingDown = true;
                }
            }

            if(isCoolingDown)
            {
                coolDownTimer.Update(gameTime);

                if(coolDownTimer.HasTriggered)
                {
                    isCoolingDown = false;
                }
            }

            blinkTimer.Update(gameTime);

            base.Update(gameTime, chunks, camera);
        }
Exemple #29
0
        public void CalculateCurrentOrientation(Camera camera)
        {
            float xComponent = Vector3.Dot(camera.ViewMatrix.Forward, GlobalTransform.Left);
            float yComponent = Vector3.Dot(camera.ViewMatrix.Forward, GlobalTransform.Forward);

            float angle = (float) Math.Atan2(yComponent, xComponent);

            if(angle > -MathHelper.PiOver4 && angle < MathHelper.PiOver4)
            {
                CurrentOrientation = Orientation.Left;
            }
            else if(angle > MathHelper.PiOver4 && angle < 3.0f * MathHelper.PiOver4)
            {
                CurrentOrientation = Orientation.Backward;
            }
            else if((angle > 3.0f * MathHelper.PiOver4 || angle < -3.0f * MathHelper.PiOver4))
            {
                CurrentOrientation = Orientation.Right;
            }
            else
            {
                CurrentOrientation = Orientation.Forward;
            }
        }
Exemple #30
0
        public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            SenseTimer.Update(gameTime);

            if (SenseTimer.HasTriggered)
            {
                Sense();
            }
            Enemies.RemoveAll(ai => ai.IsDead);
            base.Update(gameTime, chunks, camera);
        }
Exemple #31
0
        public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            CalculateCurrentOrientation(camera);

            string s = currentMode + OrientationStrings[(int) CurrentOrientation];
            if(Animations.ContainsKey(s))
            {
                CurrentAnimation = Animations[s];
                CurrentAnimation.Play();

                SpriteSheet = CurrentAnimation.SpriteSheet;
            }

            base.Update(gameTime, chunks, camera);
        }
Exemple #32
0
        public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            if(IsActive)
            {
                if(CurrentAnimation != null)
                {
                    CurrentAnimation.Update(gameTime);
                }
            }

            base.Update(gameTime, chunks, camera);
        }
Exemple #33
0
        public void Render(Camera renderCamera, DwarfTime gameTime, GraphicsDevice graphicsDevice, Effect effect, Matrix worldMatrix)
        {
            effect.Parameters["xIllumination"].SetValue(ChunkData.IllumMap);
            effect.Parameters["xTexture"].SetValue(ChunkData.Tilemap);
            effect.Parameters["xSunGradient"].SetValue(ChunkData.SunMap);
            effect.Parameters["xAmbientGradient"].SetValue(ChunkData.AmbientMap);
            effect.Parameters["xTorchGradient"].SetValue(ChunkData.TorchMap);
            effect.Parameters["xTint"].SetValue(new Vector4(1.0f, 1.0f, 1.0f, 1.0f));
            effect.Parameters["SelfIllumination"].SetValue(1);

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                foreach(VoxelChunk chunk in RenderList)
                {
                    chunk.Render(ChunkData.Tilemap, ChunkData.IllumMap, ChunkData.SunMap, ChunkData.AmbientMap, ChunkData.TorchMap, graphicsDevice, effect, worldMatrix);
                }
            }
            effect.Parameters["SelfIllumination"].SetValue(0);
        }
Exemple #34
0
        public void Update(Creature creature, DwarfTime gameTime, ChunkManager chunks, Camera camera)
        {
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
            Hunger.CurrentValue -= dt * creature.Stats.HungerGrowth;

            Health.CurrentValue = (creature.Hp - creature.MinHealth) / (creature.MaxHealth - creature.MinHealth);

            if(creature.Stats.CanSleep)
                Energy.CurrentValue = (float) (100*Math.Sin(PlayState.Time.GetTotalHours()*Math.PI / 24.0f));
            else
            {
                Energy.CurrentValue = 100.0f;
            }

            if(Energy.IsUnhappy())
            {
                creature.DrawIndicator(IndicatorManager.StandardIndicators.Sleepy);
            }

            if(creature.Stats.CanEat && Hunger.IsUnhappy())
            {
                creature.DrawIndicator(IndicatorManager.StandardIndicators.Hungry);

                if(Hunger.CurrentValue <= 1e-12 && (DateTime.Now - LastHungerDamageTime).TotalSeconds > HungerDamageRate)
                {
                    creature.Damage(1.0f / (creature.Stats.HungerResistance) * HungerDamageRate);
                    LastHungerDamageTime = DateTime.Now;
                }
            }
        }
Exemple #35
0
        public void RenderAll(Camera renderCamera, DwarfTime gameTime, GraphicsDevice graphicsDevice, Effect effect, Matrix worldMatrix, Texture2D tilemap)
        {
            effect.Parameters["xIllumination"].SetValue(ChunkData.IllumMap);
            effect.Parameters["xTexture"].SetValue(tilemap);
            effect.Parameters["xSunGradient"].SetValue(ChunkData.SunMap);
            effect.Parameters["xAmbientGradient"].SetValue(ChunkData.AmbientMap);
            effect.Parameters["xTorchGradient"].SetValue(ChunkData.TorchMap);
            effect.Parameters["xTint"].SetValue(new Vector4(1.0f, 1.0f, 1.0f, 1.0f));
            effect.Parameters["SelfIllumination"].SetValue(1);

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                foreach (KeyValuePair<Point3, VoxelChunk> chunk in ChunkData.ChunkMap)
                {
                    if (renderCamera.GetFrustrum().Intersects(chunk.Value.GetBoundingBox()))
                    {
                        chunk.Value.Render(tilemap, ChunkData.IllumMap, ChunkData.SunMap, ChunkData.AmbientMap,
                            ChunkData.TorchMap, graphicsDevice, effect, worldMatrix);
                    }
                }
            }
            effect.Parameters["SelfIllumination"].SetValue(0);
        }