Jump to content
  • Advertisement
  • 10/07/17 10:02 AM

    Game Architecture: Migrating to a Basic Entity Component System

    General and Gameplay Programming

    tgobbens

    Introduction 

    The architecture of software design is a much-debated subject. Every developer has his own opinion about what is good software design and what is not. Most developers agree on what is bad design, on what is good design there are a wide variety of opinions. Unfortunately, due to the nature of software development, there is no silver bullet; there is no one design strategy that always works.

    There are a couple of strategies that have proofed to be successful. These strategies have known strengths and weaknesses. The advantage of using such a strategy is allowing you to focus on building your game, instead of worrying if your codebase will implode after someone decided the game should function a bit different than how the code was originally written.

    Architecture

    In game development, the entity-component-system is an architectural pattern that is used successfully in small, medium and large games. The main strength of this strategy is the usage of the composition over inheritance pattern. This pattern prevents the build-up of complex object inheritance tree’s, that will make your code impossible to refactor without a lot of side-effects.

    So how does this pattern work, at its core, there are three elements; entity, components, and systems guess you didn’t see that coming. ;) Let’s describe these one by one, I’m starting with the smallest and most simple one the “component”:

    Component

     The component represents a single attribute of an entity. Some examples of entities can be:

    • Position
    • Rotation
    • Scale
    • Physics body
    • Texture
    • Health

    Entity

     Entities are the “game-object” some examples:

    • Ball
    • Camera
    • Player
    • Enemy
    • Bullet

    An entity can have multiple components, for example, a ball entity can have the following components: position, rotation, scale, texture and physics body. A camera entity might only have a position. Usually, all entities have a unique-id for fast access, but there can also be other ways of accessing entities.

    System

    The system is responsible for one aspect of the game, a simple game has can, for example, have the following systems:

    • Rendering
    • Physics
    • GUI
    • Sound
    • AI

    What a system does is iterating over all entities that have components of the types defined by the system. For example, the physics system will act only on entities with a physics-component and a position-component. The rendering system will only act on entities that have a position and texture component. 

    For example, if a ball entity has a position and physics and texture component. The physics system will pick up the ball entity, as it has a physics and position component. The physics-system control a physics-engine, that will do its magic and calculate a new position for the ball. The physics system will set this new position on the position component.

    The rendering-system will also pick up the ball entity, as it acts on all entities that have a position and a texture component. The rendering system can render the ball using the texture and the position found with the ball entity (yes, the same component that was just updated by the physics-system).

    Now imagine you spend some time implementing the architecture described above, and you after, running it, realize the ball is not really moving very realistic. That might be because you forgot to take rotation into account.

    To fix it you now only have to create a rotation-component and add it to the ball entity. Now add in the physics system a check if the entity has a rotation component and if so just set the rotation on this component. In the rendering-system also add some code to check if there is a rotation component and if so render with this rotation.

    This is where the power of this architecture emerges, imagine you have not one ball entity but have a lot of entities like the ball, wall, player, ground, etc. and you forgot about the rotation. You only have to modify the rendering system and the physics system. Then by simple adding a rotation component to the entities you want to have rotation on, magically all those objects have a rotation. Now adding rotation seems like a trivial thing to do, but what does this architecture enforces is the separation of concerns (e.g. rendering and physics) while still allows adding new functionality. And important; It does this without the usage of inheritance but rather by composition.

    Possible features

    The architecture described above is in itself quite powerful. But there are some more interesting possibilities with this architecture. I will describe some of them below.

    Game-mechanic tweaking

    Creating a generic mechanic-tuning-utilities; as there are a limit number of component types, you can create a (developer) GUI-overlay that allows you to modify the values of a component. This will allow you to in real-time modify the values, e.g. the position, size, texture, acceleration, the weight of a certain entity his components. This will help you tremendously in fine-tuning game mechanics without the need to keep recompiling and reloading your game.

    Level-editor

    Taking this even a step further you could use the above system to load all entities and relevant components from a file, e.g. XML. This will also help you decrease compile and loading time, letting you focus more one tuning game mechanics. This could then be a very good start for creating a level-editor, letting a none technical team member (game-designers) tweak game mechanics.

    Dynamic loading

    Something else that can be managed using this system, is implementing an entity loading/unloading mechanism. You can define an interface with functions like initializing, loading, starting, stopping, unloading, destructing. Now you can implement a loading mechanism that guarantees the loading and initializing always happen asynchronously. This will allow you to load and unload entities in a uniform and controlled manner. You could also choose to run all the systems in a different thread you need to take some more care about modifying components, but this could allow you to do a lot of performance enhancements, as for example, the AI needs less frequent updates then a renderer.

    Real-world example

    Note this implementation is done in Java, as I’m using libGDX as the platform, but the architecture is certainly not limited to Java and can also be implemented in other languages like C++.

    Enough of the theory, now for a real implementation. As a hobby project, I have been creating a small iOS/Android game, my first implementation of this game was naïve, with one source file containing all logic. No need to explain this is a bad implementation, but this did allow me to check if my idea was fun and create a quick prototype and do some fast iterations from there.

    For reference, the “bad” implementation can still be found here:  https://github.com/tgobbens/fluffybalance/blob/master/core/src/com/balanceball/Balanceball.java  

    After I created this implementation I decided I wanted to implement the same game using a better manageable implementation.

    The “main” entry file can be found here: https://github.com/tgobbens/fluffybalance/blob/master/core/src/com/balanceball/BalanceBallSec.java.

    So, I’ve created my own entity-component-system. If you want to create your own game using an entity-component-system, and want the game to be ready as soon as possible then I wouldn’t recommend writing one yourself. However, if you want to learn about programming or just create something for fun, implementing such a system is easy, and you will learn a lot from doing this. Another reason to implement this yourself is you get a lot of freedom allowing you to add specific tricks and features that can help you improve your codebase.

    The entity component system can be found under https://github.com/tgobbens/fluffybalance/tree/master/core/src/com/sec and yes there are some optimisation and improvements opportunities in this code base. But it does show an easy to understand implementation. When trying to understand make sure you know what Java generic types are. It’s quite common you need to find a certain entity to update or get some info from. As there are a lot of components you know there will be only one instance from. I’ve added a method to get the first entity of a certain type. For example, give me the camera entity, or give me the first “game-world” entity. But there are also helper functions to get all entities of a certain type. The same trick is used for getting components of an entity.

    You will also find a basic type called “engine”, used for binding everything together. This will trigger the updates and holding references to all systems and entities. If you look for a “starting” point for the architecture this is where to start looking.



      Report Article


    User Feedback


    There are no comments to display.



    Create an account or sign in to comment

    You need to be a member in order to leave a comment

    Create an account

    Sign up for a new account in our community. It's easy!

    Register a new account

    Sign in

    Already have an account? Sign in here.

    Sign In Now

  • Advertisement
  • Advertisement
  • intellogo.png

    Are you ready to promote your game?

    Submit your game for Intel® certification by December 21, 2018 and you could win big! 

    Click here to learn more.

  • Latest Featured Articles

  • Featured Blogs

  • Advertisement
  • Popular Now

  • Similar Content

    • By dj180
      For some gamers out there, platformer games can be the main deciding factor when considering which console to buy (when buying all of them is not a realistic option). Personally, I have been playing Playstation consoles my entire life, dabbling in other consoles and portable gaming platforms, yet I always seem to return to Playstation because of the exclusive games only available through their platforms. The Last of Us is an award-winning 3D action platformer game available only on Playstation consoles. 
      The single player campaign opens in the midst of a zombie virus outbreak among the entire world. The narrative follows two characters Joel, a father to a recently deceased daughter due to the outbreak, and Ellie a teenager who is believed to hold the cure to the virus in her immune system. Joel encounters a militia group, known as the Fireflies, that formed after the outbreak and is quickly tasked with the mission of delivering Ellie to other members of the militia outside the quarantined zone. Due to the initial conflict set up by the narrative and the undercover nature of the main mission, the suggested way to play the game is by remaining out of sight as much as possible and engaging enemies in a sly manner. However, games are places people flock to when looking for an escape from reality, a place with no rules or direction in some cases. For this reason, gamers approach games from different perspectives, causing them to play the game using different strategies. 

      Some player types such as the Killer player type defined by the Bartle player dichotomy the would prefer to take tactical approach to the task at hand, rather than a strategic one. For these type players, the combat they seek would include more face-to-face and traditional battles. For a strategic player, playing the game as if they themselves were in the shoes of the character, it is more appealing to remain as hidden as possible. The Last of Us also does a nice job of including both perspectives in specific instances. Players do not have to actively seek out or play intentionally with a certain strategy, the elements that Killers and Achievers enjoy most are built into the narrative at some main turning points, whereas most minor engagements are left up to the choice of the player. 

      In addition to the two polarizing player types mentioned previously, The Last of Us elegantly includes elements favored by the scavenger and artisan player types as well. Above the main mission of transporting Ellie to the Fireflies, there is obviously a larger responsibility to remain alive. There are several mechanics contained within the game that players can use to increase their chances of survival. Some of these mechanics include looting and crafting. It is possible to “loot” in virtually every scene of the game, although it is entirely the player’s choice whether to spend time looting or continue on with the main story line. Looted items can be used to craft items to boost health, melee weapons, and throwable items such as Molotov cocktails and nail bombs. These items are crafted with smaller parts players find by looting abandoned place and of course, classic to most Naughty Dog games, some of the better items require more exploring. Although all players must use items and crafting to some degree in order to play through the game successfully, the game will reward players more who spend more time searching for these items. This is also a positive feedback mechanism because players who are excelling in the game will be given opportunities to make the game easier through the use of the items they are able to craft. Crafting can also allow players to make improvements to Joel’s abilities and, at certain work benches found throughout the story, his firearms.  Dylan Richmond 

      The craft-able items also introduce a variety of combat techniques that appeal to the wide array of player types. Certain enemies require some sort of tactic or craft-able item in order to defeat. A “clicker” is a type of enemy players encounter who uses its sense of hearing to detect players, making it easier for players to sneak around in plain sight, however players cannot engage this enemy without a weapon of some sort, or they will instantly die. This encourages players to come up with a clever and stealthy way to defeat this type of enemy. One option is to sneak up behind a clicker and use a craft-able item called a shiv in order to defeat the enemy. This is designed for rational players because this technique requires a great deal of thought and concentration in order to prevent the clicker from noticing the player. Aggressive players might ignore the clicker’s abilities of enhanced hearing and strength and face the clicker straight on with a gun or a melee weapon, such as a crowbar. Casual players may attempt to defeat the enemy from afar with one of the easiest methods, a Molotov cocktail. This item will attract the clicker to its flames and if the clicker has been standing in the flames for long enough, it will be defeated. This method is also best for defeating large hoards of zombies or clickers and might be chosen by a strategic or tactical player. 

      People have all sorts of play styles, approaches, and ways of enjoying video games, many beyond the scope of merely one game. Including these alternative pathways throughout video games increase their appeal to a greater number of people, which is ultimately the goal in creating a video game, yet having these various routes also increases the overall enjoyment of the game for everyone. For any player type, it is reassuring to know that if one of the options are situationally unavailable, another option is always at hand. The Last of Us artfully combines its narrative and combat mechanics with a multitude of viable player types. It’s the cross between elements and approaches from these player types that keeps The Last of Us fresh with every new engagement. Keeping a single consistent play style throughout the entire game is not an easy task for most, often times players must use a combination of strategies, abilities, and interact with various features in order to successfully complete The Last of Us. 
        
    • By GameDev.net
      Originally published on NotesonGameDev.net October 27, 2008
      Jenova Chen, creator behind the multi award-winning student game Cloud and flOw, co-founder of thatgamecompany, is dedicated to expanding the emotional spectrum of video games and making them available for a much wider audience. And how did Jenova "make it" as an independent developer? With a lot of support and a drive for innovation.
      Can you tell us a little bit about your interest in game development and where it all started?
      When I was 10 years old, my Dad, who worked in the software industry, took me to a special Computer Programming school for kids hoping I'd become Bill Gate's one day. However, I had no interest in learning programming; instead I got to play my very first computer game at the school. And from that point on, video games were pretty much my obsession.
      My first attempt in making video games happened when I was 12, and my enthusiasm quickly faded due to a bad 5 inch floppy disk which carried a week's worth of my work. When I went to college around 1999, I was pretty much bored with the math and programming, and I started to put all my spare time on digital animation and 3D graphics.
      At the time, there were no domestic video game development studios in China and video game education was also a vacuum. And by accident, I met some very enthusiastic students in the college who wanted to make video games. It seemed like a good place where I could put my digital art skill to use. Once the training started, the adventure and joy from game development has never stopped.
      Speaking of college... What was your role in Cloud and how did it come to be?
      My first big student team project in the grad school at USC Interactive Media Division was not Cloud but Dyadin (IGF 2005), where my role was lead artist. It was the first video game made by student team in our division. The big success brought a lot of attention to the school, therefore the school started a grant to encourage students to team up and make more innovative games. The grant was open to the entire university.
      As one of the applicants I came up the rough idea of making a game about clouds and rallied around students and faculties. Once the cloud game idea won the grant and got funded by the school, we put a team together. My role was team lead. As a result I worked with the team on many aspects of the game: gameplay prototyping, game design, story and all the visual arts.
      What do you think made Cloud the 2006 IGF Student Showcase Winner?
      Being one of a kind--a fresh emotional experience that's different from anything on the mainstream market.
      Following Cloud, you went right on to working on flOw. How did Cloud's success influence you?
      It's not the success part of Cloud influenced me but the failure of Cloud. So many people downloaded our game, including people who never played games. I guess they were lured to the childhood fantasy. As a result, their lack of game knowledge prevented them from enjoying the relaxing experience---instead, their frustration of learning how to control the game ruined the experience.
      I learned from Cloud that there is a huge market for games that evoke a different emotional experience. However, new markets mean new audience. In order to search for a design methodology that enables a game to satisfy both experienced gamers and not so experienced ones, I started the flOw project.
      Interesting concept to work with! How was flOw conceptualized and developed?
      As part of my master degree thesis at USC, flOw, the original web game, was made for the sole purpose of testing whether the design methodology I developed based on Flow theory works. In the academia, there was a lot of many research about how to use an A.I. to read player's performance and alter the gaming experience. However, through playing those games myself, I feel there are so many cases where the A.I. can't assess player's true feeling based on rigid formulas.
      As a side effect, the false reaction of the A.I. broke my "sense of control", a key condition to enter the Flow state. Therefore, through learning successful video games with mass appeal, I came up a different approach to adjust the difficulties of the game. I call it Active Dynamic Difficulty Adjustment, which uses player's choice to change the difficulty of the gaming experience.
      The trick is to embed the difficulty adjustment choices in the core gameplay mechanics so that when player makes those choices, he won't feel interrupted from the core gameplay. In flOw, player's only action is swimming and eating, and the way the player engages different content with different difficulties is also through swimming and eating. And the result of the testing was amazing
      flOw is now available on PS3, something that indie developers aspire to. How did you make the leap to console?
      My business partner Kellee Santiago and I were very lucky to have studied at the USC Interactive Media Division where we took a class called business of interactive entertainment. It's that class that opened our eyes that starting up a company and chasing your dream is not a fairy tale; instead it's something totally possible for normal people like us who had no money, but a passion.
      We had a sneak peek at the great potential and promising future of video games through Cloud. And we really hope the maturing of video games as an interactive medium could happen faster. We want to push the boundary of video games and allow more people around the world to see games like Cloud, to awaken the dormant market so that more people can join us to further expand video games' emotional range and meet various needs from the public. Not just things made for excitement and leisure but also things that are thought evoking and deeply emotional. With that goal, we started to pitch the grand idea of Cloud, the commercial version to almost all the publishers in North America.
      Quickly, we realized that based on the experience we had fresh out of school and the ridiculous budget we asked, there was simply no one who would take the risk with us. It had to be the timing and pure luck that we encountered the opportunity of making games for the digital distribution platform for next generation console like Wii and PS3. Both of Sony and Nintendo were going to launch their new gaming consoles, and they were both dying for new content on their digital distribution channel.
      The fact that flOw was a rather complete game concept made with two students in three months helped us to convince Sony that they could trust us for a much smaller game than Cloud. And then the leap was made.
      Well that's great! What are you working on now?
      We are finishing up our second title for Sony's Playstation Network, Flower. A game that is a sister piece after Cloud and flOw. Our version of a video game poem dealing with our inner desires towards the wild nature and urban life.
      What would you say is the biggest challenge you've faced so far as an indie?
      The biggest challenge is to grow up, to become experienced from inexperience. We made so many mistakes in running a startup company and in game development. Though we've overcome all the challenges, the taste is still yummy pain.
      Heh heh. What about your biggest triumph then?
      Thatgamecompany is still up and running. And we are making games that we believe will push the boundary of what video games can communicate.
      What advice do you have out there for those aspiring to join game industry as an indie?
      Really consider indie game developer within our industry. Just look around at what's happened in the past two years. How many of your favorite indie games have shown up on the commercial platforms? How many highly reviewed video games are from independent studios? This is the golden time of independent video games. We see so many talented new faces coming out of school and even veterans who left the big studios to form their company and chase their dreams. The renaissance of video games is already happening.
    • By blesseddisciple
      So I have a decent amount of JavaScript experience now and decided I was gonna lower my head and start cranking out some 2d games, partly to learn, partly to have fun. Afterall, HTML5 canvas is such an easy and enticing medium. I love the JavaScript implementation of it. But after literally struggling for a week to get basic game functionality working I have had enough of the little stupid bugs that pop up with JavaScript. Don't get me wrong, I still love the language for scripting. I'm just not going to spend 20 mins coding and 5 hours debugging just because the language is crap.
      I've decided to return to my previous endeavor, Java. I like Java a lot and the only reason I haven't pursued more in the way of game development is just for the fact that Java is limited to mobile or PC apps that may never see the light of day unless it's hosted on some obscure Java game hosting website that is populated with 2,000 half developed games that no one will ever care about. BUT, still, I enjoy hand coding and I know C# but don't feel like using Visual studio and I really don't wanna hand code C# on the .Net or whatever. I use Visual Studio for business apps (ASP.NET) but I don't wanna build a game with it.
      So, does anyone have any points to share about why moving to Java for game development is not smart? Besides the whole, "Java is slow" thing. I mean things that might make it harder in JAva to make games vs. in other languages. Please share your thoughts. 
    • By Lauren Tuccy
      So my only coding experience is with writing Interactive Fiction games with Inform, so I get the logic and stuff, but, I'm so used to starting with a program with libraries and assets already built in, that I have no idea how to build something from scratch. 
      I'm would like to make this simulation game where the player is a student in a [magic] school, and I've got stats for the students, their personality types, and ideas on how that should effect their performance in class, and experience rates, and all this data in a google spreadsheet, but I have NO idea how to start creating this game on a code level. So, I'm just struggling on finding out how to get started. Can anybody give me some advice?
    • By MiniDarkOF
      Hello Again,
      I'm trying to create a "sound expansion"

      The Example:
      a nuclear explosion sound has 1000ft of audible sound area
      players who is next to the explosion hear it first
      players who is far to the explosion will hear after some seconds
      when the sound reaches its area limit, it ends with a "fade-out"

      The Point:
      i already know how to create fade-out sound effect in Unity
      know i want to know how i can create this "sound expansion" effect
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!