#Himalaya: A harmonic composition

No, this page is not turning into a music theory blog. Instead, I’m gonna tell you a little something about the newly introduced component system of the Himalaya game engine.

Remember the original design approach I posted when the framework was still very early in development?

GameElements

My original idea was to have an abstract class as a template for all entities in the game. An entity, such as the player character, would then simply derive from the GameEntity class and implement all the additional functionality that it needs. The “Actor” class was supposed to be a GameEntity that provides additional features for visual representation of the object on the screen. But as the Himalaya engine grew bigger, I realized that this design was good, but not necessarily ideal.

What are you made of?

I came to the conclusion that a component-based approach, similar to the one in the Unity engine, was a much nicer way to describe the functionality of a game entity. What do I mean by “component”? Well…an entity component is basically responsible for handling one specific part of an object in our game. They enable us to easily implement similar behavior in two entities, just by using the same components. An example: For our player character we could create a game entity with one component that handles user input, one that handles collisions, one that renders a sprite on the screen and one that animates said sprite.

Take a look at this chart for clarification:

HimalayaComponents

As you can (hopefully) see, a lot of the classes that I talked about in previous posts have been converted to entity components to conform to the new system. Of course this new design renders the aforementioned “Actor” class obsolete, since it would basically just be a GameEntity with a Sprite and a SpriteAnimator attached to it. Currently, I still keep the Actor class in the library, but I marked it as “obsolete”. It will be removed very soon, though.

Entity Components that need their logic updated each frame implement the IUpdate interface. The GameEntity the component belongs to then makes sure to actually call the update logic regularly. Similarly, components that contain render logic use the IDraw interface and have their draw method called by their entity at the appropriate time.

The Transform component is a special little snowflake, because it is used by every single entity and cannot be removed. I mean, every object needs to be able to be positioned at least, right? Also, some entity components allow only one instance of them to be attached to a game entity. That is the case for our special little friend Transform, but also applies to the CollisionController, the Sprite and the SpriteAnimator for example. With this system, we can easily pick from all the features we need and add them to a specific game entity.

youJustBlewMyMind.gif

How about some code?

Alright, let’s take a look at the EntityComponent class first:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yetibyte.Himalaya.GameElements;

namespace Yetibyte.Himalaya.GameElements {

    public abstract class EntityComponent {

        #region Fields

        protected bool _isActive = true;
        protected GameEntity _gameEntity;

        #endregion

        #region Properties

        public virtual bool AllowMultiple => false;
        public virtual bool IsRemovable => true;

        public GameEntity GameEntity {

            get => _gameEntity;

            set {

                GameEntity futureGameEntity = value;

                if (IsAttached)
                    _gameEntity.RemoveComponent(this);

                futureGameEntity?.AddComponent(this);

                _gameEntity = futureGameEntity;

            }

        }

        /// <summary>
        /// Whether or not this component has been attached to a <see cref="GameElements.GameEntity"/>.
        /// </summary>
        public bool IsAttached => _gameEntity != null;

        /// <summary>
        /// Determines whether or not this component is currently active. This also takes into account the active state of
        /// the <see cref="Yetibyte.Himalaya.GameElements.GameEntity"/> this component is attached to. If the GameEntity is not active, this will return false
        /// regardless of the local active state of this component. A component that is not attached to any GameEntity is always considered inactive.
        /// </summary>
        /// <seealso cref="IsActiveSelf"/>
        public bool IsActive {

            get => _gameEntity != null && _gameEntity.IsActive && this.IsActiveSelf;
            set => this.IsActiveSelf = value;

        }

        /// <summary>
        /// The local active state of this component. This ignores the active state of the <see cref="Yetibyte.Himalaya.GameElements.GameEntity"/> this component is attached to.
        /// Pleae note that, even if this is set to true, the component may still be considered inactive by the <see cref="Scene"/> because the GameEntity is not active or this
        /// component has not been attached to a GameEntity at all.
        /// </summary>
        /// /// <seealso cref="IsActive"/>
        public bool IsActiveSelf { get => _isActive; set => _isActive = value; }

        /// <summary>
        /// Determines the order in which <see cref="EntityComponent"/>s are processed. The processing order goes from
        /// high priority to low priority components. Note: This does not affect the draw order for drawable components.
        /// </summary>
        public int Priority { get; set; }

        #endregion

        #region Methods

        /// <summary>
        /// Sets the <see cref="Yetibyte.Himalaya.GameElements.GameEntity"/> this component is attached to without
        /// the overhead of recalculating relations. Only use this if you know what you're doing!
        /// </summary>
        /// <param name="gameEntity">The new GameEntity.</param>
        internal void SetGameEntityDirectly(GameEntity gameEntity) => _gameEntity = gameEntity;

        /// <summary>
        /// Called when this <see cref="EntityComponent"/> is attached to a <see cref="GameElements.GameEntity"/>.
        /// </summary>
        public virtual void OnAdded() {

        }

        /// <summary>
        /// Called when this <see cref="EntityComponent"/> is removed from a <see cref="GameElements.GameEntity"/>.
        /// </summary>
        /// <param name="gameEntity">The GameEntity this component was removed from.</param>
        public virtual void OnRemoved(GameEntity gameEntity) {

        }

        #endregion

    }
}

Good thing I (almost) always document my code. That saves me some explaining now, if it’s even necessary since this class is pretty short and straight forward and doesn’t do that much on its own. This is simply an abstract class for the different component types to derive from. Entity Components can be set to “inactive” to temporarily prevent them from being processed. The order in which components are updated can be determined via the Priority property. This is useful and even necessary in some cases. For example, it makes sense to first check for keyboard input with the ControlListener component and then after that process the input in a Behavior component.

Speaking of Behavior component. As I mentioned above, the logic and – well – behavior of a game entity is no longer intended to take place directly in a subclass of GameEntity. This is the job of the Behavior component. It has methods for initialization and updating that we can override to describe the behavior of an object such as the player character. It is where we implement all the logic that handles how an entity interacts with its environment.

Components can be added to or removed from a GameEntity with the following simple methods. I added some comments for explanation.

public void AddComponent(EntityComponent component) {

	/* If we passed null for some reason or a component that was already added
	 * to this GameEntity, return without adding anything. */
	if (component == null || HasComponent(component))
		return;

	// Get the type of the component we want to add.
	Type componentType = component.GetType();

	/* If the component does not allow multiple instances of it in one entity and there
	 * is already a component of the same type in this entity, return without adding the component. */
	if (!component.AllowMultiple && HasComponentOfType(componentType))
		return;

	// If the component is currently already attached to another entity, detach it.
	component.GameEntity?.RemoveComponent(component);

	// Add the component to this entity's collection of components.
	_components.Add(component);

	// Set the GameEntity of the component to this one.
	component.SetGameEntityDirectly(this);

	// Call the OnAdded method of the component we just added.
	component.OnAdded();

	// Fire the ComponentAdded event.
	OnRaiseComponentAdded(new ComponentEventArgs(component));

}

public void RemoveComponent(EntityComponent component) {

	/* If we passed null or the component is not attached to this entity
	 * or it is not removable, return. */
	if (component == null || !HasComponent(component) || !component.IsRemovable)
		return;

	// Remove the component from the collection of components in this entity.
	_components.Remove(component);

	// Set the entity of the component to null.
	component.SetGameEntityDirectly(null);

	// Call the OnRemoved method of the component we just removed.
	component.OnRemoved(this);

	// Fire the ComponentRemoved event.
	OnRaiseComponentRemoved(new ComponentEventArgs(component));

}

To retrieve components attached to a GameEntity, we can use one of the following methods:

/// <summary>
/// Returns a collection of all <see cref="EntityComponent"/>s attached to this <see cref="GameEntity"/> that are of or derive from the given Type.
/// </summary>
/// <typeparam name="T">The type to filter the components by.</typeparam>
/// <returns>A collection of all components attached to this entity that derive from the given type.</returns>
public IEnumerable<T> GetComponents<T>() where T : EntityComponent => _components.OfType<T>();

public IEnumerable<T> GetActiveComponents<T>() where T : EntityComponent => _components.OfType<T>().Where(c => c.IsActive);

/// <summary>
/// Returns a collection of all <see cref="EntityComponent"/>s attached to this <see cref="GameEntity"/>'s children that match the given Type or derive from it.
/// </summary>
/// <typeparam name="T">The Type to filter the components by.</typeparam>
/// <param name="includeSelf">Should the root <see cref="GameEntity"/>'s components be included in the collection?</param>
/// <param name="recurse">Should the components attached to grandchildren, great-grandchildren etc. also be included in the collection?</param>
/// <returns>A collection of all components that meet the specified conditions.</returns>
public IEnumerable<T> GetComponentsInChildren<T>(bool includeSelf, bool recurse) where T : EntityComponent {

	IEnumerable<T> ownComponents = includeSelf ? GetComponents<T>() : new T[0];

	if (_childEntities == null) // Just a safety precaution
		return ownComponents.Concat(new T[0]);

	if (!recurse)
		return ownComponents.Concat(_childEntities.SelectMany(e => e.GetComponents<T>()));

	return ownComponents.Concat(_childEntities.SelectMany(e => e.GetComponentsInChildren<T>(true, true)));

}

/// <summary>
/// Returns the first <see cref="EntityComponent"/> attached to this <see cref="GameEntity"/> that matches the given Type or derives from it.
/// </summary>
/// <typeparam name="T">The type of the component to look for.</typeparam>
/// <returns></returns>
public T GetComponent<T>() where T : EntityComponent => GetComponents<T>().FirstOrDefault();

What’s somewhat interesting here is the generic method GetComponentsInChildren that optionally recurses through the entire entity hierarchy and returns all the components of the desired type it can find. By now you should also be able to tell that I’m a big fan of LINQ. 😀

If we wanted to get the Sprite component of a game entity, we would simply do something like: “entity.GetComponent();”

If we know there are multiple components of the same type, let’s say Behavior, and we want to retrieve them all, we’d just go: “entity.GetComponents();”

We’re getting there…

The Himalaya engine is getting richer and richer in features. There’s still a lot to do, but I’m having a lot of fun developing this framework, even though it takes more time than I can afford to spend sometimes. 😀

There are a few more features I haven’t written about yet, but I’ll take care of that shortly. Next time we’ll focus on collision detection and response. I hope you’re looking forward to that.

And as always, let me remind you that the source code of the Himalaya engine can be found in my GitHub repository.

See you around!

Advertisements

#Himalaya: Parenting 101

Unlike what the title might suggest, this post does not offer advice on how to raise your kids. If you were looking for that, I’m sorry. But looking for parenting advice on the internet is probably not a good idea in the first place. Anyway, I digress…

Today I will show you how I implemented a simple parent-child type of hierarchy for game entities in Himalaya. What do I mean by that? Well, I’m glad you ask. Let’s use an example for demonstration. I’m gonna use a few sprites I created for an upcoming project of mine.

Let’s say we have one Game Entity (an Actor to be specific, see my last post) that represents the player:

axeGun1single

We want to equip our player with a gun, which is also a Game Entity:

gunHands1

So, if we combine the two layers we end up with this:

axeGun1singleWithGun

Let’s also make our player drop a shadow to be extra fancy:

axeGun1singleWithGunAndShadow

So now we have three Game Entities in total. And obviously they heavily depend on each other. If the player moves or rotates or something like that, we want this change to also be applied to the gun and the shadow, right? You’ll notice that we kinda need to build ourselves some sort of hierarchy where the player entity is on top and both the gun and the shadow branch off of it. I’m talking about something like this:


PlayerHierarchyExample

Now, this is obviously a very simple hierarchy, but eventually in our game we are very likely to have very complex hierarchies and, therefore, we need to write ourselves some code that helps us create them.

But before I go on any further, let me inform you that there has been a slight change in the design of class relations and dependencies: The “Transformable” class has been renamed “Transform” and is no longer abstract. The Game Entity class now no longer inherits from this class but implements it as a member. You will see that in action in a second.

Let’s do this!

Alright, so in order to actually implement this sort of behavior I added a few properties to the Game Entity class and to what is now the Transform class. Their job is to keep track of what Game Entity our instance is a child of and what instances it is the parent of. Pretty simple and straight-forward. The interesting part is to implement the behavior of when the hierarchy was to change. Let’s take a look at another diagram:


GameEntityHierarchy

So here we have a somewhat more complex hierarchy. We’e got “GameEntityA” with the child entities “GameEntityA_A”, “GameEntityA_B” and “GameEntityA_C” and each of those again have two children. If the position of “GameEntityA” changes, all the child and subchild entities will also move in relation. But what if we were to change the hierarchy at runtime?


GameEntitiyHierarchy2

Of course, we would have to make some recalculations. Changing the parent of “GameEntityA_B_A” obviously also changes the list of child entities inside “GameEntityA_A” and vice versa. Also “GameEntityA_A_C” (formerly “GameEntityA_B_A” needs to be removed from the list of child entities of “GameEntityA_B”. But we don’t want to check specific conditions and write paragraphs of code every time we change our hierarchy. We want to be able to do something as simple as this:

GameEntityA_B_A.Parent = GameEntityA_A;

Or alternatively:

GameEntityA_A.AddChildEntity(GameEntityA_B_A);

The underlying code should then “automagically” change the hierarchy appropriately.

Now, take a look at my implementation. The following code is obviously work in progress and subject to change:

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Linq;

namespace Yetibyte.Himalaya.GameElements {

	public abstract class GameEntity : IUpdate, ITimeScale, IDraw {

        // Fields

        private bool _isActive = true;
		private List<GameEntity> _childEntities = new List<GameEntity>();
        private GameEntity _parentEntity;

		// Properties

        /// <summary>
        /// A <see cref="GameEntity"/> that is inactive will be ignored by the <see cref="Yetibyte.Himalaya.GameElements.Scene"/> and will
        /// therefore not be updated.
        /// </summary>

        public bool IsActive {

            get { return _isActive; }
			set { _isActive = value;}

		}

		public String Name { get; protected set; }

        /// <summary>
        /// The <see cref="Yetibyte.Himalaya.GameElements.Scene"/> this GameEntity lives in.
        /// </summary>

	    public Scene Scene { get; set; } 

		public Game Game {

			get { 

				if(Scene == null)
					return null;

				return Scene.Game;

			}

		}

        /// <summary>
        /// Sets the parent <see cref="GameEntity"/> of this <see cref="GameEntity"/>. Will automatically call AddChildEntity and RemoveChildEntity methods where needed.
        /// That means: When the parent entity changes, this GameEntity will be added to the child entity list of the future parent and removed from the orignal parent's list of child entities
        /// (unless the original parent was null.
        /// </summary>

        public GameEntity ParentEntity {

            get { return _parentEntity; }

            set {

                GameEntity futureParent = value;

                if(this.HasParent) {

                    _parentEntity.RemoveChildEntity(this);

                }

                futureParent?.AddChildEntity(this);

                _parentEntity = futureParent;

            }

        }

        /// <summary>
        /// A list of Game Entities that are children of this <see cref="GameEntity"/>.
        /// </summary>

		public List<GameEntity> ChildEntities {

			get { return _childEntities; }
			protected set { _childEntities = value; }

		}

        public float TimeScale { get; set; } = 1f;

        public bool IsDestroyed { get; protected set; }

        public Transform Transform { get; set; } = new Transform();

        public bool HasParent => _parentEntity != null;

        public int DrawOrder { get; set; }

        // Constructor

        protected GameEntity(string name, Vector2 position) {

			this.Name = name;
			this.Transform.Position = position;

		}

        // Methods

		public virtual void Initialize() {

		}

		public virtual void Update(GameTime gameTime, float globalTimeScale) {

		}

		public virtual void Draw(SpriteBatch spriteBatch, GameTime gameTime) {

		}

        /// <summary>
        /// Destroys this <see cref="GameEntity"/>. It will be removed from the <see cref="Yetibyte.Himalaya.GameElements.Scene"/> it lived in.
        /// </summary>

		public void DestroyEntity() {

			foreach(GameEntity childEntity in ChildEntities)
				childEntity.DestroyEntity();

            if(!IsDestroyed) {

                IsDestroyed = true;
                Scene.RemoveGameEntity(this);

            }

		}

        /// <summary>
        /// Adds the given <see cref="GameEntity"/> to the list of child entities. Also sets the parent entity respectively. The child
        /// Game Entity will also optionally be added to the Scene the parent lives in (if it wasn't already).
        /// </summary>

        /// <param name="childEntity">The child entity to add.</param>
        /// <param name="doAddToScene">Should the child Game Entity be added to the Scene as well? True by default.</param>
        public void AddChildEntity(GameEntity childEntity, bool doAddToScene = true) {

            if (!IsParentOf(childEntity)) {

                ChildEntities.Add(childEntity);
                Transform.AddChild(childEntity.Transform);
                childEntity.ParentEntity = this;

                if(doAddToScene)
                    Scene.AddGameEntity(childEntity);

            }

        }

        /// <summary>
        /// Removes the given  <see cref="GameEntity"/> from the list of child entities. Also sets the parent of the given entity to null.
        /// The child Game Entity will also optionally be removed from the Scene the parent lives in (if it wasn't already).
        /// </summary>

        /// <param name="childEntity">The child entity to remove.</param>
        /// <param name="doRemoveFromScene">Should the child Game Entity be removed from the Scene as well? False by default.</param>
        public void RemoveChildEntity(GameEntity childEntity, bool doRemoveFromScene = false) {

            if (IsParentOf(childEntity)) {

                ChildEntities.Remove(childEntity);
                Transform.RemoveChild(childEntity.Transform);
                childEntity.ParentEntity = null;

                if (doRemoveFromScene)
                    Scene.RemoveGameEntity(childEntity);

            }

        }

        /// <summary>
        /// Checks whether the given <see cref="GameEntity"/> is included in the list of child entities fo this <see cref="GameEntity"/>.
        /// </summary>

        /// <param name="childEntity">The child game entity.</param>
        /// <returns>True if the given entity is a child of this GameEntity.</returns>
        public bool IsParentOf(GameEntity childEntity) => ChildEntities.Contains(childEntity);

    }

}

As you can see, I highlighted the most relevant lines of code for you. Luckily, I already included some XML documentation in the code, so I don’t have to come up with a super lengthy explanation now. 😀

If you study the code a bit, you will notice that there are apparently also methods in the Transform class that handle child-parent relations. This is because I did not want to couple the two classes Transform and GameEntity too tightly. Even though the main purpose of Transform is to implement it in the GameEntity class it may also be used elsewhere. So the Transform hierarchy is responsible only for transferring changes in position, scale and rotation throughout the “family tree”. Changing the hierarchy of Game Entities obviously also changes the hierarchy of their respective Transforms.

For clarification, take a look at the Transform class (also work in progress):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using MonoGame.Framework;

namespace Yetibyte.Himalaya.GameElements {

    /// <summary>
    /// A class that can be used as a component for any object that can be positioned, scaled and rotated.
    /// </summary>

    public class Transform {

        // Fields

        private Transform _parent;
        private Vector2 _position = Vector2.Zero;

        // Properties

        public Transform Parent
        {

            get { return _parent; }

            set
            {

                Transform futureParent = value;

                if (this.HasParent) {

                    _parent.RemoveChild(this);

                }

                futureParent?.AddChild(this);

                _parent = futureParent;

            }

        }

        public List<Transform> Children { get; private set; } = new List<Transform>();

        ///<summary>
        /// The position relative to the parent Transform.
        /// </summary>

        public Vector2 LocalPosition {

            get
            {
                Vector2 relation = Parent != null ? Parent.LocalPosition : Vector2.Zero;
                return Position - relation;
            }

            set
            {
                Vector2 relation = Parent != null ? Parent.Position : Vector2.Zero;
                Position = value + relation;
            }

        }

        /// <summary>
        /// The global scale of this Transform (read-only). Use <see cref="LocalScale"/> to manipulate the scaling value.
        /// </summary>

        public Vector2 Scale
        {

            get
            {
                Vector2 relation = Parent != null ? Parent.Scale : Vector2.One;
                return LocalScale * relation;
            }

        }

        /// <summary>
        /// The global rotation of this Transform in radians (read-only). Use <see cref="LocalRotation"/> to manipulate the rotation value.
        /// </summary>

        public float Rotation
        {

            get
            {
                float relation = Parent != null ? Parent.Rotation : 0f;
                return relation + LocalRotation;
            }

        }

        /// <summary>
        /// The global position. Setting this value will also manipulate the position of all child Transforms.
        /// </summary>

        public Vector2 Position
        {

            get { return _position; }

            set
            {

                Vector2 delta = value - _position;

                foreach (Transform child in Children)
                    child.Position += delta;

                _position = value;

            }

        }
        public Vector2 Origin { get; set; }
        public Vector2 LocalScale { get; set; } = Vector2.One;
        public float LocalRotation { get; set; }

        public bool HasParent => _parent != null;

        // Methods

        public Vector2 Translate(Vector2 offset) {

            Position += offset;
            return Position;

        }

        public Vector2 TranslateLocally(Vector2 offset) {

            LocalPosition += offset;
            return LocalPosition;

        }

        public void AddChild(Transform childTransform) {

            if (IsParentOf(childTransform))
                return;

            Children.Add(childTransform);
            childTransform.Parent = this;

        }

        public void RemoveChild(Transform childTransform) {

            if (!IsParentOf(childTransform))
                return;

            Children.Remove(childTransform);
            childTransform.Parent = null;

        }

        /// <summary>
        /// Checks whether the given <see cref="Transform"/> is included in the list of child entities of this <see cref="Transform"/>.
        /// </summary>

        /// <param name="childTransform">The child transform.</param>
        /// <returns>True if the given Transform is a child of this Transform.</returns>
        public bool IsParentOf(Transform childTransform) => Children.Contains(childTransform);

    }

}

I don’t want to go into too much detail. We got a little bit of recursion going on.  You may have also noticed that I’m a friend of expression bodied members. What you may have noticed as well is that the code handling child-parent relations are very, very similar in both classes. What? We don’t want redundant code, right? Right!

That’s why I created a generic class for cases where we want to implement this sort of hierarchy. Since this can be a reoccurring pattern, an abstract class called “ParentChildHierarchy” can now be found in my utility library:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Yetibyte.Utilities {

    public abstract class ParentChildHierarchy<T> where T : ParentChildHierarchy<T> {

        // Fields

        protected T _parent;

        // Properties

        public T Parent
        {

            get { return _parent; }

            set
            {

                T futureParent = value;

                if (this.HasParent) {

                    _parent.RemoveChild((T)this);

                }

                futureParent?.AddChild((T)this);

                _parent = futureParent;

            }

        }

        public List<T> Children { get; protected set; } = new List<T>();
        public bool HasParent => _parent != null;

        // Methods

        public bool AddChild(T child) {

            if (IsParentOf(child))
                return false;

            Children.Add((T)child);
            child.Parent = (T)this;

            return true;

        }

        public bool RemoveChild(T child) {

            if (!IsParentOf(child))
                return false;

            Children.Remove((T)child);
            child.Parent = null;

            return true;

        }

        public bool IsParentOf(T child) => Children.Contains(child);

        public T GetAncestor() {

            ParentChildHierarchy<T> currentChild = this;

            while (currentChild.Parent != null) {

                currentChild = currentChild.Parent;

            }

            return (T)currentChild;

        }

    }

}

This class will soon be added to the mix to simplify both the Game Entity and the Transform class. Both will then simply inherit from the ParentChildHierarchy class. As you can see this class also has a method for returning the “ancestor”, which is the term I use for the instance that is at the very top of the hierarchy (see the diagrams above).

Thanks for your attention

So, I guess that’s it for today. Take the code in for a moment if you like. Remember, the full source code of the project is available in my GitHub repository:

https://github.com/Yeti47/Yetibyte.Himalaya

himalayaEngineLogoBigger

#Himalaya: Modeling the basic game elements

Okay, so let’s discuss the plan. What does my game engine need? What game components are essential for building a very simple game? Well, in fact most games that need their game and render logic updated regularly share a similar base structure.

Luckily, MonoGame already does most of the low-level stuff for us and provides us with a Game class that has methods for content loading, updating game logic and rendering that are called at the appropriate time. But of course, we don’t want to put all of our game code into this class. That’d be very poor design and – needless to say – it would make our code quite unmanageable. So we want to structure our code and divide our game into reoccurring components, or “Game Elements” as I will be referring to them, since the term “Game Component” is already defined in MonoGame/XNA. As I said, this is handled similarly in most games. We create some sort of scene or game state class that is responsible for managing all of our game objects like the player, enemies, GUI elements, environmental stuff (like a tiled map), basically everything that makes up one particular part or “scene” of our game. Our scene could be a level, it could be a menu, it could be a loading screen… You get the idea. 😀

But before I start trying to draw a picture with words, here’s an actual picture to gaze your eyes upon. This is a (non-standard) UML diagram of what I (and many others before me) came up with.

wp-image-GameElemetsD

Click to enlarge. Created with NClass (http://nclass.sourceforge.net). It’s a cool and handy little tool. Go check it out! I’m serious, go! GO!

 

Of course this is just a first draft and the structure is most likely subject to change a bit. But let me tell you about what you’re seeing real quick.

Scene

As mentioned above, the scene contains all the game objects we currently need in our game and makes sure to update their logic and call their Draw method. We keep track of all game objects that currently live in our scene using a generic List. Also we have two more collections of type Queue. These store the game objects – or “Game Entities” as I refer to them – that are to be added to or removed from the Scene in this update interval. We need those collections because we cannot directly manipulate our List of Game Entities while we are iterating through them in our Update method. Therefore, we keep track of what Entities we want to dynamically add or remove and than do so after all existing entities have been processed.

Game Entity

A Game Entity is basically any object inside our Scene that needs to be updated. This abstract class can be used as a pattern for anything that brings some logic into our messy game world. The basic Game Entity is not intended to have a graphical representation on the screen but it can certainly implement some render logic if the developer (aka me) decides so.

Actor

The Actor class derives from the GameEntity class. The main difference between a simple Game Entity and what I refer to as an “Actor” is that an Actor has a Sprite that makes it visible on the screen. It can also optionally have a Sprite Animator which is used to, well, animate the sprite. More information on Sprites and Sprite Animators are to come… right now.

Sprite

Well, anyone who has ever had something to do with game development knows what a Sprite is. It is basically a certain part of a texture. I feel like explaining it is kind of unnecessary since it is more like a general term. If you really want to know more about sprites and texture atlases… Google is your friend. 😀

boe_tile_set

Here’s an example of a Sprite sheet to give you an idea if you are indeed clueless. Found on: https://de.wikipedia.org/wiki/Sprite_(Computergrafik)

This class is basically my simple implementation of a Sprite. It has a source rectangle which represents the texture coordinates of what part of the texture should be rendered. For reasons of convenience I also implemented the properties Index, Width and Height which are direct links to the source rectangle’s location and size.

I really wasn’t sure if I should also add properties for the Sprite’s position and scale. That way, I could only manipulate those values and used them when the Sprite is drawn to the screen. But eventually I decided against those since the Actor class that is the main user of the Sprite class already has such properties. And since I want the Sprite to sort of graphically represent the Actor, I decided that instead I wanted to pass the Actor’s position and scale to the Sprite’s Draw method. Maybe this will change in the future. I’m not entirely sure. We’ll see.

Sprite Animator and Sprite Animation

The Sprite Animator does exactly what it says. It animates the Sprite that is assigned to it. I. e. according to some predefined data set, it changes the texture coordinates (the index) of the Sprite at a certain interval. This data set can be found in the SpriteAnimation class. The Sprite Animator has methods for playing, pausing and stopping its animation. Originally, I implemented this behavior with a subclass of Sprite called “AnimatedSprite”. However, I quickly found that this was not a good design choice in my case. That is because the Actor class has a property of the type Sprite, remember? I wanted to leave it up to the developer to decide whether the actor should have a Sprite or an Animated Sprite. So far so good, Animated Sprite derives from Sprite, so it wouldn’t have been a problem to assign an instance of AnimatedSprite to the Sprite property of the Actor. The problem however would have been that every time I wanted to use the Sprite as an Animated Sprite, e. g. to update the animation or to play or pause it, I couldn’t have done so easily. Every Animated Sprite is a Sprite, but not every Sprite is an Animated Sprite. I couldn’t just “upcast” the Sprite to an Animated Sprite. So I figured, using an optional Sprite Animator was a better idea.

I created a custom extension for the MonoGame content pipeline that interprets a lua script and creates an instance of the Sprite Animation class from it (see my previous post). I will describe this in more detail in a future post, possibly including a video tutorial on how to create a content pipeline extension, because you wouldn’t believe how poorly documented this subject is. Tutorials about this are very hard to find. So I might possibly create one to fill this gap a bit.

Interfaces

I also use a few interfaces so far and there are most likely more to come. The ITimeScale interface provides a scaling value for all time based operations.  The Scene class implements this interface to provide a global time scaling value, that is passed to all of the Game Entities. I plan to use this to manipulate any calculations that rely on the time that elapsed between the current frame and the previous one (delta time). This way I can easily achieve effects like slow motion or game pause.

The Game Entity class and the Sprite Animator class also implement this interface. This is so that I also have some sort of “local” time scale. In certain cases I might want to slow some entities down while maintaining or increasing the speed of others. That’s what this is for.

There is not much to say about the IDraw and the IUpdate interface. They are used by all the objects that implement the Draw and the Update method the exact same way. I couldn’t name them IDrawable and IUpdatable (to conform to the convention) because, again, those terms are already used by XNA/MonoGame for interfaces with slightly different purposes.

Stick around

That’s it for now. I will be posting about some more details about the Himalaya Game Engine shortly. Remember: The source code of the project, including everything you just read about, can be found in my GitHub repository:

https://github.com/Yeti47/Yetibyte.Himalaya

See ya!

Did you miss me?

Explaining myself

Well, where do I start? After 9 months of silence, my blog returns in a new look and on a different website. What happened? Where the fudge have I been? I’m gonna try and shine some light into my mysterious disappearance.

When I first started blogging on Tumblr, I was unemployed. I guess that already explains a lot, but let me continue with my justification. I don’t want to ramble too much though, so I’ll try to make it short.

I’m the type of guy that needs to be productive in order to be happy. A day without any result or any sort of progress feels empty and wasted to me. That’s one reason why I love coding. And that’s also one of the reasons why I created my blog. But when you’re unemployed, you have so much time that it actually becomes a burden at some point. You get lazy, you start slacking. “Yea, I could do this and that right now… or I could do it in an hour. What’s the difference anyway? I got like millions of those.”

stewieGun

I tried to sort of counter that by not only pursuing my hobbies, but writing about them. That way I was able to fill the huge amount of free time I had at hand a bit better and also actually had proof that this time had not been wasted. Plus, since I always wanted to become a software developer, I thought this was the best possible way to invest my time. At some point, however, it had overcome me. Anyone who knows me personally can confirm that I was going through some tough times back then. I don’t want to go into too much detail here, but let’s just say, updating my blog was not my top-priority in life during that time.

And blah blah blah, yada yada yada, here we are now. Currently, I’m getting trained to become a certified software developer. Less than two years from now I will have a super fancy certificate that proves my coding and software designing abilities. The training is going pretty well. Actually, it could hardly be any better. My grades are on point and I actually get kinda bored evey now and then, because most of the stuff they teach I already know. But unfortunately, in Germany you can have skills as sick as cancer but still won’t get a job because you don’t have some certificate to prove your “haxX0r Sk1llZzZ”. Well, whatever. I’m making a good investment into my future as a developer and for boring moments I always have my laptop with me so I can work on my programming projects.

Speaking of programming projects…

What’s next?

A few weeks ago during said training I started working on a little game just to keep myself busy. At first, I didn’t even know what kind of game I wanted to make. I wanted to keep it really simple and small because I originally intended to only ever work on it every now and then between classes and stuff. Also, my possibilites were kinda limited because I didn’t have a laptop back then. So I only had a portable C# IDE (SharpDevelop, check it out, it’s pretty cool) on a freaking flash drive to work with. I couldn’t use a powerful framework such as MonoGame as I usually would. So I ended up using a C# binding of SFML.

Here’s some material of what that looked like:

Click image to enlarge.

A couple hours into the development of this little project, someone suggested I create a tutorial on game development, and that is how this came to be:

 

I don’t know when I will find the time to continue this series, though. It’s fun, but it’s also very time consuming considering all the editing and other stuff that needs to be done to end up with a halfway decent video. We’ll see about that.

Shortly after that video was made, I got myself a new laptop. That meant no more restrictions when programming on the go. And so I decided to switch to MonoGame. Porting what I had already coded to MonoGame was not a big effort at all. However, I came to the conclusion that I should first build myself a little framework (on top of MonoGame) that is designed particularly for my intentions. So the plan is now to get a basic structure, a simple engine done for future game projects of similarly small scope. And that’s exactly what I’m gonna be working on and blogging about from now on.

I present to you:

himalayaEngineLogo384px

I started this project about two weeks ago and there’s already some code you can check out on GitHub:

Yetibyte.Himalaya on GitHub

And that’s it for now. I stayed up all night. I’m tired. It’s 9 in the morning already. My English is starting to get bad. Stop I will now. You guys later I will see. Buh-buh!

 

 

YTMC DevLog #2: Flooded with Tools

This is part two of my developer log on “Yeti’s Tile Map Creator”, an extension for the Unity game engine.

TL;DR

  • Tile eraser tool is now fully functional
  • Added flood-fill tool that lets you quickly fill an area with a pattern of multiple tiles
  • Created a utility class that can be used to quickly and conveniently add keyboard shortcuts to the Map Creator
  • Added a few keyboard shortcuts

The new tools

Eraser

Let me try to make this sound super exciting: 

Holy sperm whale stuck on a pear tree! With the newly introduced eraser tool all your mistakes will be forgiven! Accidentally misplaced a tile? Unhappy with your creation? Feeling miserable about your recent life choices? Worry no more! YTMC’s eraser tool will wipe out all of your little screw-ups and help you make things right again. And it comes in many different sizes! The future is NOW!

All jokes aside, it lets you delete tiles. That’s about as exciting as it gets. To create this tool, all I had to do basically, was make some minor tweaks to the method responsible for placing tiles. Oh, and the eraser can be resized. Yea…

Flood-fill

I added a tool I honestly wasn’t sure I would when I started developing YTMC. But after a few test drives I realized that a flood-fill/bucket tool was indispensable. 

Since I never had to deal with anything similar to implementing a flood-fill tool for what you could call an image processing software, I consulted the good ol’ internet to get an idea of what an efficient and memory saving algorithm for the job would look like. I quickly found myself on Wikipedia with a pretty straight-forward solution (pseudo-code ahead):

Source: https://en.wikipedia.org/wiki/Flood_fill

I didn’t expect the thing to be too complicated. But I was a little surprised it was going to be THAT simple. 

As always in programming, there are of course plenty of other ways to implement this feature. But I figured this one was the best option to go for.

A lot of other solutions are based on recursion, but I was looking for a way that takes up as little memory as possible. Considering how many recursive method calls the process would make, I didn’t want to take the risk to leave the user with a stack overflow exception when they try to flood-fill a larger area.

My adaptation of the algorithm was implemented really quickly. However, I wanted a tool that can fill an area with not just one tile repeatedly, but with a pattern of multiple tiles. So, I extended the algorithm to meet that requirement.


Being lazy for the lazy

I wanted to accelerate the workflow for the user even more by adding keyboard shortcuts to YTMC. So, I thought about a way of implementing hotkeys without messing with any of the code I had already written.

What I ended up doing was creating a utility class that contains a collection of all the hotkeys available. This way, it’s really easy and convenient for me and future users of the tool to add new keyboard shortcuts that trigger a specific functionality.

Let me give you a brief insight into the code to give you an idea of what I’m talking about. Obviously, the following C# code was simplified for demonstration purposes:

Here’s a rough draft of the Hotkey constructor:

public Hotkey(Modifier m, Key k, Action<MapCreator> a) {
	// some stuff
};

So now we can add hotkeys to the HotkeyList utility class like this:

private Hotkey[] hotkeys = new Hotkey[] {

	new Hotkey(control, escape, (mc) => { mc.DoStuff(); })

};

For the “Modifier” parameter we pass a representation of the modifier key (alt, control, shift etc.) that needs to be held down for the shortcut to be triggered. Knowing that, I reckon you can guess what we pass for the “Key” parameter. 

The fun part is the last parameter. Here we pass an anonymous method that is to be called when the key combination is pressed. In this simplified example, think of “mc” as being the main window of the Map Creator. We can now let our anonymous function use all the public members of the Map Creator window and its components. This way, we don’t have to make any changes to the Map Creator’s code itself. Also, we now have an excuse to make use of lambda expressions to show the world how cool and clever we are. Amirite? 😀

Up next

I guess, my next bigger step will be to add a collision editor to the Map Creator. I’ve planned it to be a visual tool that enables the user to simply add closed polylines to the map that will eventually be converted to Unity colliders. But we’ll see what I’ll end up doing exactly.


The visuals

To conclude this devLog entry, I’m gonna leave you with a few gifs to showcase the progress of YTMC:

Tileset used in these examples made by: Reemax

See: http://opengameart.org/content/lpc-cavern-and-ruin-tiles

var introduction = new BlogEntry();

Well hello, stranger!

I figured I should introduce myself since you happened to stumble upon this blog.

The name my dear mama gave me is Alex, friends also know me as “Yeti”. Lucky Goodrich is a pseudonym I came up with during a really boring internship when I was like 18. I’m a 1990-born programmer and software designer in the making. My native language is German and I live in a German speaking country you might know as “Germany” (I know, crazy, right?). However, I’ve always been more of the cosmopolitan type of guy when it comes to presenting myself on the web (Does that make sense? I’m not as good at using big words as I wish I was).


I spend a lot of time playing video games (mostly Nintendo) and watching cartoons (I will never be too old for Adventure Time – Oh, dear Glob, I love it so much). But the hobby I’m most passionate about is programming, hence this blog. My favorite food is whatever I find in the fridge.

While I do have an educational background in the wonderfully messed up world of computer science, I unfortunately could not yet make the passion I have about it my actual profession.

However, I recently mustered all ambition I could possibly find inside my generic nerd/geek body to refine my abilities and skills and all that good stuff and finally get productive.

image

Off the top of my head, I would name C#, Java, Javascript, Actionscript, PHP and C++ as the languages I’ve worked with over the past few years. But, there is probably more that I can’t remember right now. Every now and then, I’ve found myself experimenting with development tools and stuff. There was a time where I ambitiously created Skyrim Mods for my personal use only (I really should have published them on Steam or something. Stupid me!).

Back in the day, when I was an even more messed up teenager, I used to make games using the good ol’ RPG Maker (ah, the memories, they’re golden) and also Flash. The latter I also created websites with and all that. You know, Flash stuff… One of the tools I recently spend the most time on is – who would’ve thought – Unity3D. (Yes, I have Unity installed on my PC, I’m a professional now :D)


Whatever, I don’t want to make this too long and tell you about my first day at elementary school. Just know, that I set myself the goal to become a professional software/game developer sooner or later. I want to soak in all the knowledge regarding the arts of programming, game design and everything around that. Currently, I am working on an editor extension for Unity that makes it easy for newbies to create tile-based levels. In fact, that one is almost finished (yay!). More about that in future blog entries.

I’m really new to this blogging stuff, so please excuse my noob-esque writing style. There’s probably a lot more I could tell here, but I feel like this should do for now.

Thank you so much for stopping by!


Bonus: Here is a picture of me and Super Mario (well, his voice actor):

image