public Stockpile(Faction faction, IEnumerable<Voxel> voxels, RoomData data, ChunkManager chunks) : base(voxels, data, chunks) { Boxes = new List<Body>(); faction.Stockpiles.Add(this); Faction = faction; }
public Deer(string sprites, Vector3 position, ComponentManager manager, ChunkManager chunks, GraphicsDevice graphics, ContentManager content, string name) : base(new CreatureStats { Dexterity = 12, Constitution = 6, Strength = 3, Wisdom = 2, Charisma = 1, Intelligence = 3, Size = 3 }, "Herbivore", PlayState.PlanService, manager.Factions.Factions["Herbivore"], new Physics ( "A Deer", manager.RootComponent, Matrix.CreateTranslation(position), new Vector3(0.3f, 0.3f, 0.3f), new Vector3(0, 0, 0), 1.0f, 1.0f, 0.999f, 0.999f, new Vector3(0, -10, 0) ), chunks, graphics, content, name) { Initialize(new SpriteSheet(sprites)); }
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; }
public Dwarf(CreatureStats stats, string allies, PlanService planService, Faction faction, string name, ChunkManager chunks, GraphicsDevice graphics, ContentManager content, EmployeeClass workerClass, Vector3 position) : base(stats, allies, planService, faction, new Physics( "A Dwarf", PlayState.ComponentManager.RootComponent, Matrix.CreateTranslation(position), new Vector3(0.5f, 0.5f, 0.5f), new Vector3(0.0f, -0.25f, 0.0f), 1.0f, 1.0f, 0.999f, 0.999f, new Vector3(0, -10, 0)), chunks, graphics, content, name) { Initialize(workerClass); }
public VoxelListener(ComponentManager manager, GameComponent parent, ChunkManager chunkManager, Voxel vref) : base("VoxelListener", parent) { Chunk = vref.Chunk; VoxelID = new Point3(vref.GridPosition); Chunk.OnVoxelDestroyed += VoxelListener_OnVoxelDestroyed; ChunkID = Chunk.ID; }
public WaterManager(ChunkManager chunks) { Chunks = chunks; EvaporationLevel = 5; Splashes = new ConcurrentQueue<SplashType>(); Transfers = new ConcurrentQueue<Transfer>(); splashNoiseLimiter["splash2"] = new Timer(0.1f, false); splashNoiseLimiter["flame"] = new Timer(0.1f, false); }
public Room(bool designation, IEnumerable<Voxel> designations, RoomData data, ChunkManager chunks) : base(data.Name + " " + Counter, chunks) { RoomData = data; ReplacementType = VoxelLibrary.GetVoxelType(RoomData.FloorType); Chunks = chunks; Counter++; Designations = designations.ToList(); IsBuilt = false; }
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); } }
public static float GetDistance(Voxel a, Voxel b, Creature.MoveType action, ChunkManager chunks) { if(!b.IsEmpty) { return 100000; } else { float score = (a.Position - b.Position).LengthSquared() * ActionCost(action); return score; } }
public ChunkData(uint chunkSizeX, uint chunkSizeY, uint chunkSizeZ, float invCSX, float invCSY, float invCSZ, Texture2D tilemap, Texture2D illumMap, ChunkManager chunkManager) { ChunkSizeX = chunkSizeX; ChunkSizeY = chunkSizeY; ChunkSizeZ = chunkSizeZ; InvCSX = invCSX; InvCSY = invCSY; InvCSZ = invCSZ; Tilemap = tilemap; IllumMap = illumMap; this.chunkManager = chunkManager; }
public static List<Creature.MoveAction> FindPath(CreatureMovement mover, Voxel start, GoalRegion goal, ChunkManager chunks, int maxExpansions) { List<Creature.MoveAction> p = new List<Creature.MoveAction>(); bool success = Path(mover, start, goal, chunks, maxExpansions, ref p, false); if(success) { return p; } else { return null; } }
public Room(IEnumerable<Voxel> voxels, RoomData data, ChunkManager chunks) : base(data.Name + " " + Counter, chunks) { RoomData = data; ReplacementType = VoxelLibrary.GetVoxelType(RoomData.FloorType); Chunks = chunks; Designations = new List<Voxel>(); Counter++; IsBuilt = true; foreach (Voxel voxel in voxels) { AddVoxel(voxel); } }
// Creature base constructor public Bird(string sprites, Vector3 position, ComponentManager manager, ChunkManager chunks, GraphicsDevice graphics, ContentManager content, string name) : base(// Default stats new CreatureStats { Dexterity = 6, Constitution = 1, Strength = 1, Wisdom = 1, Charisma = 1, Intelligence = 1, Size = 0.25f, CanSleep = false }, // Belongs to herbivore team "Herbivore", // Uses the default plan service PlayState.PlanService, // Belongs to the herbivore team manager.Factions.Factions["Herbivore"], // The physics component this creature belongs to new Physics ( // It is called "bird" "A Bird", // It's attached to the root component of the component manager manager.RootComponent, // It is located at a position passed in as an argument Matrix.CreateTranslation(position), // It has a size of 0.25 blocks new Vector3(0.25f, 0.25f, 0.25f), // Its bounding box is located in its center new Vector3(0.0f, 0.0f, 0.0f), //It has a mass of 1, a moment of intertia of 1, and very small friction/restitution 1.0f, 1.0f, 0.999f, 0.999f, // It has a gravity of 10 blocks per second downward new Vector3(0, -10, 0) ), // All the rest of the arguments are passed in directly chunks, graphics, content, name) { // Called from constructor with appropriate sprite asset as a string Initialize(new SpriteSheet(sprites)); }
public Snake(string sprites, Vector3 position, ComponentManager manager, ChunkManager chunks, GraphicsDevice graphics, ContentManager content, string name) : base(new CreatureStats { Dexterity = 12, Constitution = 6, Strength = 3, Wisdom = 2, Charisma = 1, Intelligence = 3, Size = 3 }, "Herbivore", PlayState.PlanService, manager.Factions.Factions["Herbivore"], new Physics ( "snake", manager.RootComponent, Matrix.CreateTranslation(position), new Vector3(1, .3f, .5f), new Vector3(0, 0, 0), 1.0f, 1.0f, 0.999f, 0.999f, new Vector3(0, -10, 0) ), chunks, graphics, content, name) { Tail = new Physics[5]; for (int i = 0; i < 5; ++i) { Tail[i] = new Physics ( "snaketail", manager.RootComponent, Matrix.CreateTranslation(position), new Vector3(2, 1.5f, .7f), new Vector3(0, 0, 0), 1.0f, 1.0f, 0.995f, 0.999f, new Vector3(0, -10, 0) ); } Initialize(new SpriteSheet(sprites)); }
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; }
new public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { base.Update(gameTime, chunks, camera); if (Instance != null && (HasMoved || firstIter || Instance.Color != Tint)) { Instance.Color = Tint; Instance.Transform = GlobalTransform; Instance.SelectionBufferColor = GetGlobalIDColor(); firstIter = false; } if (checkHeight) { checkHeight = false; } if (IsVisible != instanceVisible) { SetVisible(IsVisible); } }
public void RemoveGameObject(GameComponent GameObject, BoundingBox LastBounds) { var minChunkID = GlobalVoxelCoordinate.FromVector3(LastBounds.Min).GetGlobalChunkCoordinate(); // Todo: Clamp to actual world size. var maxChunkID = GlobalVoxelCoordinate.FromVector3(LastBounds.Max).GetGlobalChunkCoordinate(); for (var x = minChunkID.X; x <= maxChunkID.X; ++x) { for (var y = minChunkID.Y; y <= maxChunkID.Y; ++y) { for (var z = minChunkID.Z; z <= maxChunkID.Z; ++z) { var coord = new GlobalChunkCoordinate(x, y, z); if (ChunkManager.CheckBounds(coord)) { var chunk = ChunkManager.GetChunk(coord); lock (chunk) chunk.Components.Remove(GameObject); } } } } }
public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { if (MathFunctions.HasNan(Position)) { Die(); } IsAboveCullPlane = GlobalTransform.Translation.Y - GetBoundingBox().Extents().Y > (chunks.ChunkData.MaxViewingLevel + 5); if (DrawScreenRect) { Drawer2D.DrawRect(GetScreenRect(camera), Color.Transparent, Color.White, 1); } if (DrawBoundingBox) { Drawer3D.DrawBox(BoundingBox, Color.White, 0.02f); Drawer3D.DrawBox(GetRotatedBoundingBox(), Color.Red, 0.02f); } if (DrawReservation && IsReserved) { Drawer3D.DrawBox(BoundingBox, Color.White, 0.02f); } if (AnimationQueue.Count > 0) { MotionAnimation anim = AnimationQueue[0]; anim.Update(gameTime); LocalTransform = anim.GetTransform(); if (anim.IsDone()) { AnimationQueue.RemoveAt(0); } } base.Update(gameTime, chunks, camera); }
public void AddGameObject(GameComponent GameObject, BoundingBox LastBounds) { var minChunkID = GlobalVoxelCoordinate.FromVector3(LastBounds.Min).GetGlobalChunkCoordinate(); var maxChunkID = GlobalVoxelCoordinate.FromVector3(LastBounds.Max).GetGlobalChunkCoordinate(); for (var x = minChunkID.X; x <= maxChunkID.X; ++x) { for (var y = minChunkID.Y; y <= maxChunkID.Y; ++y) { for (var z = minChunkID.Z; z <= maxChunkID.Z; ++z) { var coord = new GlobalChunkCoordinate(x, y, z); if (ChunkManager.CheckBounds(coord)) { var chunk = ChunkManager.GetChunk(coord); lock (chunk) chunk.Entities.Add(GameObject); } } } } }
override public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { base.Update(gameTime, chunks, camera); if (CachedBiome == null) { var biome = World.Overworld.Map.GetBiomeAt(LocalPosition, chunks.World.Overworld.InstanceSettings.Origin); if (biome != null) { CachedBiome = biome.Name; } } var factor = 1.0f; if (CachedBiome != null) { if (GoodBiomes.Contains(CachedBiome)) { factor = 1.5f; } if (BadBiomes.Contains(CachedBiome)) { factor = 0.5f; } } GrowthTime += gameTime.ElapsedGameTime.TotalMinutes * factor; var scale = (float)(MinSize + (MaxSize - MinSize) * (GrowthTime / GrowthHours)); ReScale(scale); if (GrowthTime >= GrowthHours) { CreateAdult(); } }
public bool CollidesWithChunks(ChunkManager chunks, Vector3 pos, bool applyForce, bool allowInvisible, float size = 0.5f, float height = 2.0f) { var box = new BoundingBox(pos - new Vector3(size, height * 0.5f, size), pos + new Vector3(size, height * 0.5f, size)); bool gotCollision = false; foreach (var v in VoxelHelpers.EnumerateCube(GlobalVoxelCoordinate.FromVector3(pos)) .Select(n => new VoxelHandle(chunks, n))) { if (!v.IsValid) { continue; } if (v.IsEmpty) { continue; } if (!allowInvisible && !v.IsVisible) { continue; } var voxAABB = v.GetBoundingBox(); if (box.Intersects(voxAABB)) { gotCollision = true; if (applyForce) { Collide(v, box, voxAABB); } else { return(true); } } } return(gotCollision); }
public VoxelChunk ToChunk(ChunkManager Manager) { VoxelChunk c = new VoxelChunk(Manager, Origin, ID); for (var i = 0; i < VoxelConstants.ChunkVoxelCount; ++i) { c.Data.Types[i] = Types[i]; if (Types[i] > 0) { c.Data.Health[i] = (byte)VoxelLibrary.GetVoxelType(Types[i]).StartingHealth; // Rebuild the VoxelsPresentInSlice counters c.Data.VoxelsPresentInSlice[(i >> VoxelConstants.ZDivShift) >> VoxelConstants.XDivShift] += 1; } } Explored.CopyTo(c.Data.IsExplored, 0); // Separate loop for cache effeciency for (var i = 0; i < VoxelConstants.ChunkVoxelCount; ++i) { c.Data.Water[i].WaterLevel = Liquid[i]; c.Data.Water[i].Type = (LiquidType)LiquidTypes[i]; // Rebuild the LiquidPresent counters if ((LiquidType)LiquidTypes[i] != LiquidType.None) { c.Data.LiquidPresent[(i >> VoxelConstants.ZDivShift) >> VoxelConstants.XDivShift] += 1; } } GrassType.CopyTo(c.Data.GrassType, 0); GrassDecay.CopyTo(c.Data.GrassDecay, 0); Decals.CopyTo(c.Data.Decals, 0); c.CalculateInitialSunlight(); return(c); }
override public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { base.Update(gameTime, chunks, camera); if (FirstUpdate) { FirstUpdate = false; Faction.Minions.Add(AI); Physics.AllowPhysicsSleep = false; World.AddToSpeciesTracking(Stats.Species); } if (AI == null) { Console.Out.WriteLine("Error: creature {0} {1} has no AI. Deleting it.", Name, GlobalID); GetRoot().Delete(); return; } if (!Active) { return; } UpdateCloak(); Stats.Health.CurrentValue = (Hp - MinHealth) / (MaxHealth - MinHealth); // Todo: MinHealth always 0? UpdateHealthBar(gameTime); CheckNeighborhood(chunks, (float)gameTime.ElapsedGameTime.TotalSeconds); UpdateAnimation(gameTime, chunks, camera); Stats.HandleBuffs(this, gameTime); UpdateMigration(gameTime); UpdateEggs(gameTime); UpdatePregnancy(); MakeNoises(); }
public static void Render( IEnumerable <IRenderableComponent> Renderables, DwarfTime gameTime, ChunkManager chunks, Camera Camera, SpriteBatch spriteBatch, GraphicsDevice graphicsDevice, Shader effect, WaterRenderType waterRenderMode, float waterLevel) { effect.EnableLighting = GameSettings.Default.CursorLightEnabled; graphicsDevice.RasterizerState = RasterizerState.CullNone; if (waterRenderMode == WaterRenderType.Reflective) { foreach (IRenderableComponent bodyToDraw in Renderables) { if (!(bodyToDraw.GetBoundingBox().Min.Y > waterLevel - 2)) { continue; } bodyToDraw.Render(gameTime, chunks, Camera, spriteBatch, graphicsDevice, effect, true); } } else { foreach (IRenderableComponent bodyToDraw in Renderables) { GamePerformance.Instance.StartTrackPerformance("Component Render - " + bodyToDraw.GetType().Name); bodyToDraw.Render(gameTime, chunks, Camera, spriteBatch, graphicsDevice, effect, false); GamePerformance.Instance.StopTrackPerformance("Component Render - " + bodyToDraw.GetType().Name); } } effect.EnableLighting = false; }
new public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { CalculateCurrentOrientation(camera); foreach (string orient in OrientationStrings) { string animationName = currentMode + orient; if (!Animations.ContainsKey(animationName)) { continue; } Animation animation = Animations[animationName]; // Update all the animations! Why? Because we trigger things based on the FORWARD animation frame, // not based on whatever is current. if (animation != CurrentAnimation) { animation.Update(gameTime); } } string s = currentMode + OrientationStrings[(int)CurrentOrientation]; if (Animations.ContainsKey(s)) { var previousAnimation = CurrentAnimation; CurrentAnimation = Animations[s]; if (previousAnimation != null && previousAnimation.Name.StartsWith(currentMode)) { CurrentAnimation.Sychronize(previousAnimation); } SpriteSheet = CurrentAnimation.SpriteSheet; } base.Update(gameTime, chunks, camera); }
public virtual void Update(DwarfTime Time, ChunkManager Chunks, Camera Camera) { if (AnimationQueue.Count > 0) { var anim = AnimationQueue[0]; anim.Update(Time); LocalTransform = anim.GetTransform(); if (anim.IsDone()) { AnimationQueue.RemoveAt(0); } } for (var i = 0; i < Children.Count; ++i) { if (!Children[i].IsFlagSet(Flag.DontUpdate)) { Children[i].Update(Time, Chunks, Camera); } } }
public void LoadFromFile(ChunkManager Manager, SaveGame gameFile, Action <String> SetLoadingMessage) { if (gameFile.ChunkData.Count == 0) { throw new Exception("Game file corrupt. It has no chunk files."); } var maxChunkX = gameFile.ChunkData.Max(c => c.ID.X) + 1; var maxChunkZ = gameFile.ChunkData.Max(c => c.ID.Z) + 1; ChunkMapMinX = gameFile.ChunkData.Min(c => c.ID.X); ChunkMapMinZ = gameFile.ChunkData.Min(c => c.ID.Z); ChunkMapWidth = maxChunkX - ChunkMapMinX; ChunkMapHeight = maxChunkZ - ChunkMapMinZ; ChunkMap = new VoxelChunk[ChunkMapWidth * ChunkMapHeight]; foreach (VoxelChunk chunk in gameFile.ChunkData.Select(file => file.ToChunk(Manager))) { AddChunk(chunk); } Manager.UpdateBounds(); }
override public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { base.Update(gameTime, chunks, camera); if (!LightsWithVoxels) { LightRamp = Color.White; } if (entityLighting && LightsWithVoxels) { var under = new VoxelHandle(chunks, GlobalVoxelCoordinate.FromVector3(Position)); if (under.IsValid) { LightRamp = new Color(under.Sunlight ? 255 : 80, 255, 0); } } else { LightRamp = new Color(200, 255, 0); } }
public override void Update(DwarfTime time, ChunkManager chunks) { if (TrailerCommand != null) { TrailerCommand.Update(World, this); if (!TrailerCommand.Active) { TrailerCommand = null; } } switch (Control) { case ControlType.Overhead: OverheadUpdate(time, chunks); break; case ControlType.Walk: WalkUpdate(time, chunks); break; } base.Update(time, chunks); }
public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { GamePerformance.Instance.StartTrackPerformance("Update Transforms"); if (RootComponent != null) { RootComponent.UpdateTransformsRecursive(null); } GamePerformance.Instance.StopTrackPerformance("Update Transforms"); GamePerformance.Instance.StartTrackPerformance("Factions"); Factions.Update(gameTime); GamePerformance.Instance.StopTrackPerformance("Factions"); GamePerformance.Instance.TrackValueType("Component Count", Components.Count); GamePerformance.Instance.TrackValueType("Updateable Count", UpdateableComponents.Count); GamePerformance.Instance.TrackValueType("Renderable Count", RenderableComponents.Count); GamePerformance.Instance.StartTrackPerformance("Update Components"); foreach (var componentType in UpdateableComponents) { foreach (var component in componentType.Value) { //component.Manager = this; if (component.IsActive) { //GamePerformance.Instance.StartTrackPerformance("Component Update " + component.GetType().Name); component.Update(gameTime, chunks, camera); //GamePerformance.Instance.StopTrackPerformance("Component Update " + component.GetType().Name); } } } GamePerformance.Instance.StopTrackPerformance("Update Components"); HandleAddRemoves(); }
public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { if (!IsActive) { return; } DamageTimer.Update(gameTime); CheckLavaTimer.Update(gameTime); SoundTimer.Update(gameTime); if (CheckLavaTimer.HasTriggered) { CheckForLavaAndWater(gameTime, chunks); } Heat *= 0.999f; if (Heat > Flashpoint) { if (DamageTimer.HasTriggered) { Health.Damage(Damage, Health.DamageType.Fire); } if (SoundTimer.HasTriggered) { SoundManager.PlaySound(ContentPaths.Audio.fire, LocParent.Position, true, 0.5f); } double totalSize = (LocParent.BoundingBox.Max - LocParent.BoundingBox.Min).Length(); int numFlames = (int)(totalSize / 4.0f) + 1; for (int i = 0; i < numFlames; i++) { Vector3 extents = (LocParent.BoundingBox.Max - LocParent.BoundingBox.Min); Vector3 randomPoint = LocParent.BoundingBox.Min + new Vector3(extents.X * MathFunctions.Rand(), extents.Y * MathFunctions.Rand(), extents.Z * MathFunctions.Rand()); Manager.World.ParticleManager.Trigger("flame", randomPoint, Color.White, GetNumTrigger()); } } }
public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) // Todo: Camera redundant { PerformanceMonitor.PushFrame("Component Update"); PerformanceMonitor.SetMetric("COMPONENTS", NumComponents()); var playerPoint = World.Renderer.Camera.Position; // Todo: Make this a sphere? var distanceVec = new Vector3(GameSettings.Current.EntityUpdateDistance, GameSettings.Current.EntityUpdateDistance, GameSettings.Current.EntityUpdateDistance); var updateBox = new BoundingBox(playerPoint - distanceVec, playerPoint + distanceVec); var componentsToUpdate = World.EnumerateIntersectingRootEntitiesLoose(updateBox); var i = 0; foreach (var body in componentsToUpdate) { i += 1; body.Update(gameTime, chunks, camera); body.ProcessTransformChange(); } PerformanceMonitor.SetMetric("ENTITIES UPDATED", i); if (Debugger.Switches.DrawUpdateBox) { foreach (var chunk in World.EnumerateChunksInBounds(updateBox)) { Drawer3D.DrawBox(chunk.GetBoundingBox(), Color.Red, 0.4f, false); } } PerformanceMonitor.PopFrame(); AddRemove(); ReceiveMessage(); }
override public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { base.Update(gameTime, chunks, camera); if (Active && closestCreature != null && !closestCreature.IsDead) { offset = closestCreature.Position - Position; if (offset.Length() > 8) { closestCreature = null; return; } TheAttack.RechargeTimer.Update(gameTime); _targetAngle = (float)Math.Atan2(offset.X, offset.Z); if (TheAttack.RechargeTimer.HasTriggered) { closestCreature.Kill(this); TheAttack.LaunchProjectile(Position + Vector3.Up * 0.5f, closestCreature.Position, closestCreature.Physics); TheAttack.PlayNoise(Position); TheAttack.RechargeTimer.Reset(); if (GetComponent <MagicalObject>().HasValue(out var magicalObject)) { magicalObject.CurrentCharges--; } } } if (Math.Abs(_currentAngle - _targetAngle) > 0.001f) { _currentAngle = 0.9f * _currentAngle + 0.1f * _targetAngle; SetTurretAngle(_currentAngle); } }
public override void Update(DwarfTime Time, ChunkManager Chunks, Camera Camera) { if (Active) { HealTimer.Update(Time); if (HealTimer.HasTriggered) { var objects = World.EnumerateIntersectingObjects(new BoundingBox(-Vector3.One * HealRadius + Position, Vector3.One * HealRadius + Position), CollisionType.Dynamic); foreach (var obj in objects) { var creature = obj.GetRoot().GetComponent <Creature>(); if (creature == null || creature.AI == null || creature.AI.Faction != creature.World.PlayerFaction || creature.Hp == creature.MaxHealth) { continue; } if (MathFunctions.RandEvent(0.5f)) { creature.Heal(HealIncrease); IndicatorManager.DrawIndicator((HealIncrease).ToString() + " HP", creature.Physics.Position, 1.0f, GameSettings.Default.Colors.GetColor("Positive", Microsoft.Xna.Framework.Color.Green)); creature.DrawLifeTimer.Reset(); World.ParticleManager.Trigger("star_particle", obj.Position, Color.Red, 10); World.ParticleManager.TriggerRay("star_particle", Position, obj.Position); SoundManager.PlaySound(ContentPaths.Audio.tinkle, obj.Position, true, 1.0f); GetComponent <MagicalObject>().CurrentCharges--; if (GetComponent <MagicalObject>().CurrentCharges == 0) { return; } } } } } base.Update(Time, Chunks, Camera); }
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 (Alliance.GetRelationship(faction.Value.Name, Faction.Name) != 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); }
override public void Update(DwarfTime Time, ChunkManager Chunks, Camera Camera) { Thoughts.RemoveAll(thought => thought.IsOver(Manager.World.Time.CurrentDate)); Status.Happiness.CurrentValue = 50.0f; foreach (Thought thought in Thoughts) { Status.Happiness.CurrentValue += thought.HappinessModifier; } if (Status.IsAsleep) { AddThought(Thought.ThoughtType.Slept); } else if (Status.Energy.IsDissatisfied()) { AddThought(Thought.ThoughtType.FeltSleepy); } if (Status.Hunger.IsDissatisfied()) { AddThought(Thought.ThoughtType.FeltHungry); } }
public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { if (firstIter) { if (Chunk.Data.Types[Chunk.Data.IndexAt(VoxelID.X, VoxelID.Y, VoxelID.Z)] == 0) { Delete(); } firstIter = false; } if (DestroyOnTimer) { DestroyTimer.Update(gameTime); if (DestroyTimer.HasTriggered) { Die(); Chunk.MakeVoxel(VoxelID.X, VoxelID.Y, VoxelID.Z).Kill(); } } base.Update(gameTime, chunks, camera); }
public static IEnumerable <IRenderableComponent> EnumerateVisibleRenderables( IEnumerable <IRenderableComponent> Renderables, ChunkManager chunks, Camera Camera) { var frustrum = Camera.GetFrustrum(); // Todo: Use an octtree for this. var visibleComponents = Renderables.Where(r => { if (!r.IsVisible) { return(false); } if (chunks.IsAboveCullPlane(r.GetBoundingBox())) { return(false); } if (r.FrustumCull) { if ((r.GlobalTransform.Translation - Camera.Position).LengthSquared() >= chunks.DrawDistanceSquared) { return(false); } if (!r.GetBoundingBox().Intersects(frustrum)) { return(false); } } return(true); }).ToList(); return(visibleComponents); }
public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { UpdateTimer.Update(gameTime); if (UpdateTimer.HasTriggered) { Body p = (Body)Parent; var voxelBelow = new VoxelHandle(chunks.ChunkData, GlobalVoxelCoordinate.FromVector3(p.GlobalTransform.Translation + Vector3.Down * 0.25f)); if (voxelBelow.IsValid) { var shadowTarget = VoxelHelpers.FindFirstVoxelBelow(voxelBelow); if (shadowTarget.IsValid) { var h = shadowTarget.Coordinate.Y + 1; Vector3 pos = p.GlobalTransform.Translation; pos.Y = h; float scaleFactor = GlobalScale / (Math.Max((p.GlobalTransform.Translation.Y - h) * 0.25f, 1)); Matrix newTrans = OriginalTransform; newTrans *= Matrix.CreateScale(scaleFactor); newTrans.Translation = (pos - p.GlobalTransform.Translation) + new Vector3(0.0f, 0.1f, 0.0f); Tint = new Color(Tint.R, Tint.G, Tint.B, (int)(scaleFactor * 255)); Matrix globalRotation = p.GlobalTransform; globalRotation.Translation = Vector3.Zero; LocalTransform = newTrans * Matrix.Invert(globalRotation); } } UpdateTimer.HasTriggered = false; } base.Update(gameTime, chunks, camera); }
override public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { base.Update(gameTime, chunks, camera); if (!Active) { return; } // Never apply physics when animating! if (AnimationQueue.Count > 0) { Velocity = Vector3.Zero; return; } if (gameTime.Speed < 0.01) // This a poor man's IsPaused? Does this even get called if paused? { return; } // How would this get a NaN anyway? if (MathFunctions.HasNan(Velocity)) { Velocity = Vector3.Zero; } if (AllowPhysicsSleep) { bool goingSlow = Velocity.LengthSquared() < 0.05f; // If we're not sleeping and moving very slowly, go to sleep. if (!IsSleeping && goingSlow) { WakeTimer.Reset(); SleepTimer.Update(gameTime); if (SleepTimer.HasTriggered) { WakeTimer.Reset(); Velocity = Vector3.Zero; IsSleeping = true; } } else if (IsSleeping && !goingSlow) { WakeTimer.Update(gameTime); SleepTimer.Reset(); if (WakeTimer.HasTriggered) { IsSleeping = false; } } } // If not sleeping, update physics. if (!IsSleeping || overrideSleepThisFrame) { overrideSleepThisFrame = false; float dt = (float)(gameTime.ElapsedGameTime.TotalSeconds); // Calculate the number of timesteps to apply. int numTimesteps = Math.Min(MaxTimesteps, Math.Max((int)(dt / FixedDT), 1)); float velocityLength = Math.Max(Velocity.Length(), 1.0f); // Prepare expanded world bounds. BoundingBox worldBounds = chunks.Bounds; worldBounds.Max.Y += 50; // For each timestep, move and collide. for (int n = 0; n < numTimesteps * velocityLength; n++) { // Move by a fixed amount. Move(FixedDT / velocityLength); prevVoxel = CurrentVoxel; // Get the current voxel. CurrentVoxel = new VoxelHandle(chunks, GlobalVoxelCoordinate.FromVector3(Position)); if (CurrentVoxel != prevVoxel) { queryNeighborhood = true; } // Collide with the world. if (CollisionType != CollisionType.None) { HandleCollisions(queryNeighborhood, neighborHood, chunks, FixedDT); } queryNeighborhood = false; Matrix transform = LocalTransform; // Avoid leaving the world. if (worldBounds.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 we're outside the world, die if (LocalTransform.Translation.Y < -10 || worldBounds.Contains(GetBoundingBox()) == ContainmentType.Disjoint) { Die(); } // Final check to ensure we're in the world. transform.Translation = ClampToBounds(transform.Translation); LocalTransform = transform; // Assume that if velocity is small, we're standing on ground (lol bad assumption) // Apply friction. if (Math.Abs(Velocity.Y) < 0.1f) { Velocity = new Vector3(Velocity.X * Friction, Velocity.Y, Velocity.Z * Friction); } // Apply gravity. ApplyForce(Gravity, FixedDT / velocityLength); // Damp the velocity. Vector3 dampingForce = -Velocity * (1.0f - LinearDamping); Velocity += dampingForce * FixedDT; AngularVelocity *= AngularDamping; // These will get called next time around anyway... -@blecki // No they won't @blecki, this broke everything!! -@mklingen // Remove check so that it is ALWAYS called when an object moves. Call removed // from component update in ComponentManager. -@blecki if (numTimesteps * velocityLength > 1) { // Assume all physics are attached to the root. if (Parent != null) { globalTransform = LocalTransform * (Parent as GameComponent).GlobalTransform; } else { globalTransform = LocalTransform; } UpdateBoundingBox(); //UpdateTransformsRecursive(Parent as Body); } } if (Orientation != OrientMode.Fixed) { Matrix transform = LocalTransform; if (Velocity.Length() > 0.4f) { if (Orientation == OrientMode.LookAt) { if (Math.Abs(Vector3.Dot(Vector3.Down, Velocity)) < 0.99 * Velocity.Length()) { Matrix newTransform = Matrix.Invert(Matrix.CreateLookAt(LocalPosition, LocalPosition + Velocity, Vector3.Down)); newTransform.Translation = transform.Translation; transform = newTransform; } else { { Matrix newTransform = Matrix.Invert(Matrix.CreateLookAt(LocalPosition, LocalPosition + Velocity, Vector3.Right)); 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; } } LocalTransform = transform; } } CheckLiquids(chunks, (float)gameTime.ElapsedGameTime.TotalSeconds); PreviousVelocity = Velocity; PreviousPosition = Position; }
/// <summary> /// Checks the voxels around the creature and reacts to changes in its immediate environment. /// For example this function determines when the creature is standing on solid ground. /// </summary> public void CheckNeighborhood(ChunkManager chunks, float dt) { var below = new VoxelHandle(chunks, GlobalVoxelCoordinate.FromVector3(Physics.GlobalTransform.Translation - Vector3.UnitY * 0.8f)); var above = new VoxelHandle(chunks, GlobalVoxelCoordinate.FromVector3(Physics.GlobalTransform.Translation + Vector3.UnitY * 0.8f)); if (above.IsValid) { IsHeadClear = above.IsEmpty; } if (below.IsValid && Physics.IsInLiquid) { IsOnGround = false; } else if (below.IsValid) { IsOnGround = !below.IsEmpty; } else { IsOnGround = false; } if (!IsOnGround) { if (CurrentCharacterMode != CharacterMode.Flying) { if (Physics.Velocity.Y > 0.05) { CurrentCharacterMode = CharacterMode.Jumping; } else if (Physics.Velocity.Y < -0.05) { CurrentCharacterMode = CharacterMode.Falling; } } if (Physics.IsInLiquid) { CurrentCharacterMode = CharacterMode.Swimming; } } if (CurrentCharacterMode == CharacterMode.Falling && IsOnGround) { CurrentCharacterMode = CharacterMode.Idle; } if (Stats.IsAsleep) { CurrentCharacterMode = CharacterMode.Sleeping; if (MathFunctions.RandEvent(0.01f)) { NoiseMaker.MakeNoise("Sleep", AI.Position, true); } } else if (CurrentCharacterMode == CharacterMode.Sleeping) { CurrentCharacterMode = CharacterMode.Idle; } if (/*World.Time.IsDay() && */ Stats.IsAsleep && !Stats.Energy.IsDissatisfied() && !Stats.Health.IsCritical()) { Stats.IsAsleep = false; } }
public virtual void Render(DwarfTime gameTime, ChunkManager chunks, Camera camera, SpriteBatch spriteBatch, GraphicsDevice graphicsDevice, Effect effect, bool renderingForWater) { }
public static RoomTile[,] CreateFromRoom(Room room, ChunkManager chunks) { BoundingBox box0 = room.GetBoundingBox(); BoundingBox box = new BoundingBox(box0.Min + Vector3.Up, box0.Max + Vector3.Up); BoundingBox bigBox = new BoundingBox(box0.Min + Vector3.Up + new Vector3(-1, 0, -1), box0.Max + Vector3.Up + new Vector3(1, 0, 1)); int nr = Math.Max((int) (box.Max.X - box.Min.X), 1); int nc = Math.Max((int) (box.Max.Z - box.Min.Z), 1); RoomTile[,] toReturn = new RoomTile[nr + 2, nc + 2]; Dictionary<Point, Voxel> voxelDict = new Dictionary<Point, Voxel>(); List<Voxel> voxelsInRoom = chunks.GetVoxelsIntersecting(bigBox); foreach(Voxel vox in voxelsInRoom) { voxelDict[new Point((int)(vox.Position.X - box.Min.X) + 1, (int)(vox.Position.Z - box.Min.Z) + 1)] = vox; } for(int r = 0; r < nr + 2; r++) { for(int c = 0; c < nc + 2; c++) { toReturn[r, c] = RoomTile.Edge; } } foreach(KeyValuePair<Point, Voxel> voxPair in voxelDict) { Voxel vox = voxPair.Value; Point p = voxPair.Key; if(vox.IsEmpty && p.X > 0 && p.X < nr + 1 && p.Y > 0 && p.Y < nc + 1) { toReturn[p.X, p.Y] = RoomTile.Open; } else if(vox.TypeName != "empty") { toReturn[p.X, p.Y] = RoomTile.Wall; } } return toReturn; }
public VoxelChunk(ChunkManager manager, Vector3 origin, int tileSize, Point3 id, int sizeX, int sizeY, int sizeZ) { FirstWaterIter = true; this.sizeX = sizeX; this.sizeY = sizeY; this.sizeZ = sizeZ; ID = id; Origin = origin; Data = AllocateData(sizeX, sizeY, sizeZ); IsVisible = true; ShouldRebuild = true; this.tileSize = tileSize; HalfLength = new Vector3((float) this.tileSize / 2.0f, (float) this.tileSize / 2.0f, (float) this.tileSize / 2.0f); Primitive = new VoxelListPrimitive(); RenderWireframe = false; Manager = manager; IsActive = true; InitializeStatics(); PrimitiveMutex = new Mutex(); ShouldRecalculateLighting = true; Neighbors = new ConcurrentDictionary<Point3, VoxelChunk>(); DynamicLights = new List<DynamicLight>(); Liquids = new Dictionary<LiquidType, LiquidPrimitive>(); Liquids[LiquidType.Water] = new LiquidPrimitive(LiquidType.Water); Liquids[LiquidType.Lava] = new LiquidPrimitive(LiquidType.Lava); ShouldRebuildWater = true; Springs = new ConcurrentDictionary<Voxel, byte>(); IsRebuilding = false; LightingCalculated = false; RebuildPending = false; RebuildLiquidPending = false; ReconstructRamps = true; }
override public void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { base.Update(gameTime, chunks, camera); if (!Active) { return; } #region Update Status Stat Effects var statAdjustments = Stats.FindAdjustment("status"); Stats.RemoveStatAdjustment("status"); if (statAdjustments == null) { statAdjustments = new StatAdjustment() { Name = "status" } } ; statAdjustments.Reset(); if (!Stats.IsAsleep) { Stats.Hunger.CurrentValue -= (float)gameTime.ElapsedGameTime.TotalSeconds * Stats.HungerGrowth; } else { Hp += (float)gameTime.ElapsedGameTime.TotalSeconds * 0.2f; } Stats.Health.CurrentValue = (Hp - MinHealth) / (MaxHealth - MinHealth); // Todo: MinHealth always 0? if (Stats.Energy.IsDissatisfied()) { DrawIndicator(IndicatorManager.StandardIndicators.Sleepy); statAdjustments.Strength += -2.0f; statAdjustments.Intelligence += -2.0f; statAdjustments.Dexterity += -2.0f; } if (Stats.CanEat && Stats.Hunger.IsDissatisfied() && !Stats.IsAsleep) { DrawIndicator(IndicatorManager.StandardIndicators.Hungry); statAdjustments.Intelligence += -1.0f; statAdjustments.Dexterity += -1.0f; if (Stats.Hunger.CurrentValue <= 1e-12 && (DateTime.Now - LastHungerDamageTime).TotalSeconds > Stats.HungerDamageRate) { Damage(1.0f / (Stats.HungerResistance) * Stats.HungerDamageRate); LastHungerDamageTime = DateTime.Now; } } if (!statAdjustments.IsAllZero) { Stats.AddStatAdjustment(statAdjustments); } #endregion } }
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); } ComponentManager.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; } else if (waterRenderMode == WaterRenderType.Refractive && !RenderRefractive(component, waterLevel)) { continue; } component.Render(gameTime, chunks, camera, spriteBatch, graphicsDevice, effect, renderForWater); } effect.Parameters["xEnableLighting"].SetValue(0); }
public CommonRoom(bool designation, IEnumerable<Voxel> designations, ChunkManager chunks) : base(designation, designations, CommonRoomData, chunks) { }
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); }
public Elf(CreatureStats stats, string allies, PlanService planService, Faction faction, ComponentManager manager, string name, ChunkManager chunks, GraphicsDevice graphics, ContentManager content, Vector3 position) : base(stats, allies, planService, faction, new Physics("elf", manager.RootComponent, Matrix.CreateTranslation(position), new Vector3(0.5f, 0.5f, 0.5f), new Vector3(0.0f, -0.25f, 0.0f), 1.0f, 1.0f, 0.999f, 0.999f, new Vector3(0, -10, 0)), chunks, graphics, content, name) { Initialize(); }
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); } } }
public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { if (ShouldDie) { DeathTimer.Update(gameTime); if (DeathTimer.HasTriggered) { Die(); } } base.Update(gameTime, chunks, camera); }
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); }
public virtual void HandleCollisions(bool queryNeighborHood, VoxelHandle[] neighborHood, ChunkManager chunks, float dt) { if (CollideMode == CollisionMode.None) { return; } int y = (int)Position.Y; if (CurrentVoxel.IsValid && !CurrentVoxel.IsEmpty) { var currentBox = CurrentVoxel.GetBoundingBox(); if (currentBox.Contains(Position) == ContainmentType.Contains) { ResolveTerrainCollisionGradientMethod(); OnTerrainCollision(CurrentVoxel); return; } } if (queryNeighborHood) { int i = 0; foreach (var v in VoxelHelpers.EnumerateManhattanCube(CurrentVoxel.Coordinate).Select(c => new VoxelHandle(chunks, c))) { neighborHood[i] = v; i++; } } foreach (var v in neighborHood) { if (!v.IsValid || v.IsEmpty) { continue; } if (CollideMode == CollisionMode.UpDown && (int)v.Coordinate.Y == y) { continue; } if (CollideMode == CollisionMode.Sides && (int)v.Coordinate.Y != y) { continue; } if (Collide(v.GetBoundingBox(), dt)) { OnTerrainCollision(v); } } }
public CommonRoom(IEnumerable<Voxel> voxels, ChunkManager chunks) : base(voxels, CommonRoomData, chunks) { OnBuilt(); }
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; } } }
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); } } }
public void SetMaxViewingLevel(float level, ChunkManager.SliceMode slice) { Slice = slice; MaxViewingLevel = Math.Max(Math.Min(level, ChunkSizeY), 1); foreach(VoxelChunk c in ChunkMap.Select(chunks => chunks.Value)) { c.ShouldRecalculateLighting = false; c.ShouldRebuild = true; } }
public override void Update(DwarfTime gameTime, ChunkManager chunks, Camera camera) { if(IsActive) { if(CurrentAnimation != null) { CurrentAnimation.Update(gameTime); } } base.Update(gameTime, chunks, camera); }
public virtual void Update(DwarfTime time, ChunkManager chunks) { lastPosition = Position; UpdateViewMatrix(); UpdateProjectionMatrix(); }
public static void CalculateVertexLight(Voxel vox, VoxelVertex face, ChunkManager chunks, List<Voxel> neighbors, ref VertexColorInfo color) { float numHit = 1; float numChecked = 1; int index = vox.Index; color.DynamicColor = 0; color.SunColor += vox.Chunk.Data.SunColors[index]; vox.Chunk.GetNeighborsVertex(face, vox, neighbors); foreach(Voxel v in neighbors) { if(!chunks.ChunkData.ChunkMap.ContainsKey(v.Chunk.ID)) { continue; } VoxelChunk c = chunks.ChunkData.ChunkMap[v.Chunk.ID]; color.SunColor += c.Data.SunColors[v.Index]; if(VoxelLibrary.IsSolid(v)) { if (v.Type.EmitsLight) color.DynamicColor = 255; numHit++; numChecked++; } else { numChecked++; } } float proportionHit = numHit / numChecked; color.AmbientColor = (int) Math.Min((1.0f - proportionHit) * 255.0f, 255); color.SunColor = (int) Math.Min((float) color.SunColor / (float) numChecked, 255); }