Thursday, 12 December 2013

Exam Review: What I learned from Engine design

This post will be very different from my previous Game Engine Design posts. Rather than focusing on a particular topic, this will actually focus on various different topics and how I applied them. However, because we did not apply every concept taught in class to my teams game, Iron Heart, I'll focus on how I would have applied those full with coding samples and everything. This post is both exam review, and a final development blog for the semester. Let's get started.

What is a game engine?

A question my professor asked at the start of the semester that made me think for a second. As a gamer, we constantly reference the word "engine" but never really describe what it is, or know exactly how to define it. What I learned this year is that a game engine can be many, many things. It really all depends on the needs of developers. It could be a physics engine, wrapped with a rendering engine, like Iron Heart. Or it could be something meant to handle large number of on scene objects with physics, like Natural Motions Euphoria engine. You also want to be careful not to pick an engine you don't need. Just because you have the Frostbite physics engine, doesn't mean you need it to make a Mario platformer.

But at its core, the engine is what makes the game run and simply work. It is a SDK/API, with code and tools available to the developers to take full advantage of. So for what is a game engine, I like to look at it as a way of getting your game moving and working.

Components of a Game Engine

Game engines all have components. While some commercial engines may not have some systems that another engine has, does not mean it is bad per say. Here is a general list of some components of a game engine, and what I learned about them.

Graphics Subsystem

A graphics subsystem converts internal model representation into pixels on screen. It can be many things however. It could have a shader based pipeline with special effects such as transparency and particles. Some examples of these could be OpenGL or DirectX. In class, we used Ogre3D which is a rendering engine. It is important for your graphics system and physics system to communicate between each other, primarily because of collision detection. For Iron Heart, we utilized Ogre3D in such a way that whenever there is a collision between a tank and a cannon ball, the graphics subsystem stops drawing the hit model. We could also utilize Ogre3D's particle system, but we currently have no particle effects.

Physics Subsystem

The physics subsystem focuses on moving objects. This includes physics calculations for velocity, acceleration, force, drag, friction, inertia, and so much more. The physics subsystem is also related to collision, animation, and AI system. For Iron Heart we took full advantage of the physics engine Havok. We use Havok physics to move out objects, give them physics stats (how high the restitution, how much friction, etc). We also determine what kind of rigid body they are and what kind of collision detection they use (hull, box, mesh, etc). This way, we apply forces to our objects and the engine does the rest for us. What is great about this, because out physics system and our graphics system will be communicating data between each other, as we move and object, the graphics system draws them at their new position.

Collision ensures the objects do what they need to do when they collide with another object. Whether it be they stop and provide functionary for the user, or pass right through, or do some kind of specific event call back, collision can be used for many things. It works hand in hand with the graphics engine because when a certain kind of collision happens, the rendering and physics system can then do some particular action (like a particle effect followed by a bounce back).

Animation Subsystem

The animation deals with model skinning, character animations, kinematics (forward and inverse), as well as key frame animation, interpolation, and spline controls. It is related to the Physics and AI components of the engine. This system can communicate data to the physics/collision system so that when some kind of action happens to a particular part of the rig, we can cause an animation on the model. (IE. Getting shot and having the model move backwards)

While Iron Heart really only has a locomotion system, and not an animation system, we will have to provide one next semester. Now, because we are animating a tank, it will be a little more interesting to animate. The tank will require some kind of rig to move the wheels (if any, some of our tanks have no wheels), and the turret. We'll have to rig it, then import that rig into the game engine. Then, we'll have to create a system for importing the rig (or a third party library, if I can find a good free one). After which, we can apply it to the tank and then use in the game. This will require the use of quaternian math, a scene graph, and a lot of testing to get right. If we do however get it right, we can then have a fully animated tank that looks good.

Scripting

Scripting components of a game engine are absolutely critical for development. What I learned mostly about scripting is how the can reduce development time, increase integration between programmers and designers, and reduce debugging. They can also be used intensely for initialization of data. Scripts are generally divided into component scripts, system scripts, and data scripts.

Component scripts can act as a glue between different components of your game where we can transfer data between them with a lot of ease. System scripts are divided into boids which the system can easily access. Data scripts can save out the state of the script, drive the system with data, and define the structure for both.

Scripting generally deals with game logic, and while scripts are generally slower then actual C++ code, what they are truly great for is reducing development time. From one of my earlier blogs, I described how James Everett, a designer at Ubisoft who was working on Splinter Cell: Blacklist was having a problem understanding the code for weapon balance. So a programmer created a system that utilized scripts so he could easily make changes to all the weapons and test them live. It sped up production greatly and was relatively bug free.

Networking

Networking computers together to create a multi-player experience is the key for so many engines today. While I have not looked into how to do this yet, it is a requirement for next semester. What this requires is the transmission of data between two computers so that both can understand and see what is going on in the current world, and how to update it. However, what is important to consider for networking are what exactly are your requirements? Doing a local LAN game is much different from something complex like Eve.

Sounds

Sounds are another important part component of game engines because of how reliant they are on triggers from the collision system. Whether it be from a particular input, walking on a certain ground, punching that bad guy, or a change in the ambient noise, sounds rely on triggers from the game engine. Because of this, we can put our sound calls in our specific trigger calls.

What is a module

If you think of a game engine as like an inventory for a character in a game with a bunch of slots, a module would be something you can place into those inventory slots. It is a component which has its own interface which you use to interact with the rest of the system. Physics, Audio, Graphics are all examples of Modules.

What is the open/close principles:

Open principle means that the module is OPEN to be modified and added upon. Closed means the module is available for use by other modules like a .lib. Good modules are both Open and Closed allowing it to be used for other things as well as still able to be added on.

How is polymorphism useful?

When looking at Havok code, I was surprised how much polymorphism was used. I knew it was a useful tool and I have used it before, but seeing how much polymorphism was being used now, I never imagined.
What makes polymorphism such a great tool is how you can use it make every much more simply, structure your code efficiently, and make excellent use of abstract classes.

Example AI state manager that uses polymorphism for the child classes

For example, Iron Heart has an abstract class called Tank, and this class has a function called update. We have another class called Iron Duke. Now, we also also have an abstract class called Level_Handler that has a Spawner object in it. We also have yet another abstract class called AI_Handler and the Tank class has an object called currentAIState. The Game State Manager has an object of Level_Handler called *currentLevel. Because of polymorhpism, in the primary update loop, all I need to do is this to update all of the active enemies.

currentLevel->activeEnemies.at(i)->currentAIState->update(currentLevel->activeEnemies.at(i)->tankRB, Player1->playerTank->tankRB);

So as you can see from the function above, that is about as abstract as it gets. This kind of abstraction greatly reduces the amount of lines of code I need to write and helps minimize debugging as all of the different cpp files are isolates and easy to read. What is great is that the activeEnemies vertex buffer can also have any number of different types of tanks. All the activeEnemies vertex buffer cares about is updating their AI.

So what I learned from polymorphism is this: it is amazing for reducing code, increasing abstraction and decreasing debugging, and excellent for organizing your data.

Design Patterns

Design patterns are fun to play with. While a lot of developers shy away from them, they are excellent in many cases. Iron Heart takes advantage of the design patterns taught in class, although some more then others. However, design patterns are not a must because they can limit how a programmer may lay out their code and approach problems, which can limit creativity. However, I find the benefits of design patterns outweigh the negative. They can help reduce debugging, increase the readability and reuse-ability of code, and speed up development. Four design patterns were primarily taught in class:
  • Singleton
  • Facade
  • State Manager
  • Factory
Singletons

Singletons are one of my favorites. They allow for a programmer to create one instance of an object that can act as a manager of sorts. Several game engines make excellent use of singleton managers, like the Ogre rendering engine and the Naughty Dog engine, they use singletons as managers to control how they initialize their data. Normally, these singletons are not initialized by a constructor, but instead that is left blank and they are given an initalize function. C++ can sometimes construct classes in strange orders, so by controlling your initializing of classes, you can create a stack in which you can init certain singletons in such an order where if a particular singleton needed data from another singleton, it will get it. This also means the programmers can control the method of deconstruction. Because it is a stack, the top layer will get destroyed first, and so on.

For Iron Heart, I really only needed one singleton, and this was a Gameplay manager. This manager contained a large set of data that was all relevant to the gameplay. It included two state managers, one for AI and the other for levels. However, because of the nature of the TwoLoc, it creates a Game State Manager for us. We can create other managers, like a shaders manager. All of our data can then flow straight through this manager. This makes it easy to manage, read, and debug.



Facade

Facade's were not used in Iron Heart, but they could still potentially be useful. A facade is also a manager class, but it provides a single interface to a large collection of related classed (often a set of singletons). This makes communication between subsystems easier because it can manage access to other systems. 

The reason we do not need them is because Iron Heart simply isn't big enough yet. We don't need an entire set of managers communicating data. Currently, having game play related classes communicating necessary data between each other suits our current needs and we do not need a solution to a problem we simply don't have. 

State Manager


Iron Heart makes excellent use of state managers for AI and level handing. State managers are an excellent choice for managing these because of how they are easy to write, understand, and describe visually. They also help reduce debugging and isolate code to smaller cpp files. While these are great, I would say the best advantage is how they take full advantage of polymorphism. 

We can create an abstract AI handler classes with child classes that define the virtual functions. Then, we can create an object of those handlers in some other class, say, an AI object currentAIState in a Tank class. We also need another abstract level handler class, with a vertex buffer of all active enemies. Because the enemies have an object of currentAIState, all that is left to do at this point is call the update function for the Tank object and we have a running AI state manager. With this, we have a simplistic way of updating all of our enemies, updating their AI, and keeping the flow of data steady.

mMainHkWorld->markForWrite();
{
             
currentLevel->update(mMainHkWorld);

for(int i = 0; i < currentLevel->activeEnemies.size(); i++)
       {
       currentLevel->activeEnemies.at(i)->currentAIState->update(currentLevel->activeEnemies.at(i)->tankRB, Player1->playerTank->tankRB);
}
}

// Other code

}
Once again, my AI state manager.
So what I learned from state managers is that you can take a really complicated problem like, how am I going to update my AI, and turn it into a simple, data efficient solution.

Factories

Factories are interesting because they allow for a programmer to deal with the creation of a large quantity of objects fairly easily. They allow you to create instances of objects and all you have to do is pass in an ID and have the factory create the object for you. We can use a case switch where the input ID is simply an int, and if the int is equivalent to a particular number, return that object. Then we can perform an init of the object and bam, we have a new object. Now depending what the object is, we can store it in a vertex buffer, or some other form of storage.

For Iron Heart, we did not use a factory as exactly taught in class, but we still took the essential theory behind one and implemented it. Rather then have some kind of abstract function that has a case switch that can create multiple tanks, we simply implemented a setTank feature where it instances an input tank. We can call this as many times as we like, and it will take care of all the work for us. In the future, we can set it so it will create which tank we want, but for now, it works for as is. 

Data Oriented Design

Data oriented design provides solutions to problems that I didn't knew yet existed. We're trying to solve the problem of constant cache misses and random memory access patterns in later game development. This is happening because of the increasing gap between processing speed and memory. The idea behind data oriented design is to try to organize your data into vectors or arrays, rather than having a large quantity of objects. By organizing our data into vectors, we can keep track of their sizes and try to limit the amount of cache misses. This means data will be isolated, self contained, interchangeable pieces of code.

This way, we no longer have individual objects with data attached to them, but a manager of sorts with implicit objects. This manager can then update all of the implicit objects as a chunk of data, rather then individual objects. The advantage of this is how we can reduce cache misses and make use of linked lists.

For example:

class OOPball{
vec3 position;
vec3 direction;
float speed;

void Update(float deltaT);
}

class DODball{
vec3 position[4];
vec3 direction[4];
float speed[4];

void Update(float deltaT);
}

As you can see, the Data-oriented ball class is acting as a manager. It simply has a group of instanced ball objects in which we can update. The object oriented one will rely on creating 4 objects. Now, the OOPball class has its own update, and a manager. This manager will call the update function of the OOPball class like this.

void OOPballManager::Update(deltaT)
{
for (int i = 0; i < m_BallTotal; i++)
{
m_Balls[i]->Update(deltaT);
}
}

And the OOP update will look like this.

void OOPball::Update(float deltaT)
{
position += direction * speed * deltaT;
}

The DOD version will look like this:

void DODball::Update(float deltaT)
{
for (int i = 0; i < m_BallData.filled; i++)
{
mBallData.position[i] += mBallData.direction[i] * mBallData.speed[i] * deltaT;
}
}

What is so significant about this? Because the advantages are not clear, try to think of this as a factory where data goes in, some operation is performed, and data comes out. By instancing implicit objects this way, we can reduce cache misses and potentially improve our performance. Because DOD is not fully popularized yet, it has a lot of potential of influencing currently design methods for programming.

Version Control

Version control is extremely important for group assignments, and game development in general. (If you disagree, ask the guys at Runescape when you had to roll back to a 2007 version of the game to keep their fanbase happy). More or less version control is all about keeping older versions of your build by uploading them to some cloud or other storage system. You can use things like bitbucket, Perforce, or even a removable hard drive.

If it is uploaded to a cloud, then it becomes easy for everyone (yes that includes artists and designers) to download the latest version and check out the code. It could also mean modify it, implement new things, etc. Then, when all changes are done, that person can check the code back into the repository, with a README file detailing everything they did, and any potential bugs. This also stores the user ID so everyone will know where to direct questions to (or blame). This will create a new version of the build so if there are major problems, they can simply roll back and ignore.

Another advantage of this is that is allows for two or more programmers to work on the same code. When one programmer then uploads the code to the repository, the other team members are informed by the repository and then have to fix any potential conflicts. When everyone uploads, we have a single version with all of the new implementations.

Version control has to be one of my favorite things learned this year. The ability to easily control versions without a messy dropbox folder makes it so much easier.

Data structures for Game Engines

There are a lot of different data structures for game engines. Here are some of the ones I learned over the course of the semester.

Stacks

Stacks are interesting because they can help control the initialization and destruction of data in the game. In some game engines like the Naughty Dog engine, they utilize a stack method when initializing their singletons because some managers may require data that another has. When the game closes and they commence deconstruction, the deconstruct in the reverse order of construction. This makes it very easy to under how to initialize your data.

// Example Stack Method

// Construction
mGlobalManager.Init();
mGameplayerManager.Init();
mGraphicsManager.Init();
mAnimationManager.Init();
...... // More construction
// Deconstruction
mGlobalManager.Destroy();
mGameplayerManager.Destroy();
mGraphicsManager.Destroy();
mAnimationManager.Destroy();
...... // More Deconstruction

Queues

Queues are similar but different to stacks. Rather then implementing a first in last out method, queues are first in first out. This is good for when you have data you need to use in a sequential order, and you don't want to mess it up.

Linked Lists

Linked lists are excellent for memory management and reducing cache misses. Normally linked lists for memory management are arrays that have a point to the next link in the list. Then what happens is that data of predetermined sizes are stored into the link, normally the amount of data will be the same as the size of the array. This helps reduce cache misses greatly because if we know we have 100 items each at 64 bytes, the we can use 100 arrays on a linked list each of size 64. This way, we never have a cache miss and our memory is used to its greatest efficiency.

Vectors

Vectors, or vertex buffers, are all purpose arrays that are insanely useful for storing any kinds of data. In Iron Heart, we use these extensively to store active and inactive tanks. This way, we can dynamically increase or decrease the size of the vector without problem, and using the polymorphic methods shown earlier, we can simply update the vector based on the size.

Scene Graphs

Scene graphs are an implementation of the tree data structure. This spatially defines objects relative to their parents. This kind of structure makes it easy to position entities and have them interact how you wish. However, this can cause cache problems when we are trying to perform operations on all the nodes of the tree. More so if these are done on a per frame basis.

Scene Graphs are better a redundant structure. This makes it useful for debugging purposes, as well as setting up a scene. All of the operations involving the attached objects should be the job of their components.

// Example Scene Graph from Iron Heart
[File Scene Graph]
- ironDukeRT_ROOT
-- ironDuke
--- ironDukeGUNLoc
--- ironDukeDirNode
--- ironDuke_Entity

God of War Camera's (and camera's in general)

The God of War series has a camera system that is almost mind boggling (in a good way). I learned a great deal not only about their camera system in general, but also their techniques which will allow me to implement them in my own projects in the future. Let's get started with the GoW camera system.

Selection

Zones: Selection involves the process of understanding zones. These zones are based on walk-able areas that trigger which camera is in use.

Combat: Whether it is combat, or a specific combat maneuver, we have to to be able to select whether we are using a dynamic camera or a fixed one for combat. These camera's could also have specific animations associated with them, but those are more scripted cameras.

Scripting: There are pre-defined camera sequences that are used to highlight important objects or events. This includes a level puzzle, a key, or showing off a series of enemies before the battle.

Dynamics

Animated Camera: An animated camera is a camera that a predefined animation along a spline. This plays during a specific trigger event and can be used to showcase important information that the player may need. We can use look at locators to determine where the camera should look, or we can have it look at a locator on a rail so it will always follow that locator.

Dynamic Camera:


Dynamic camera's have more properties then a regular camera. 

The viewing screen is represented by a grid, where the center is (0,0). Within this grid, there is an area called the safe zone where Kratos will always be. 


In order to keep Kratos in the safe zone, we do an every-frame calculation by converting the screen coords into spherical angle ranges, then we update the angle offsets for the current target position. This is called framing. 

The dynamic camera has several properties. There is the dolly, which is origin point of the boom. The dolly can either be at a fixed point in space, or animate along a spline. The position of the dolly depends on the zone Kratos is in, and when he is in a zone, how his movement affects the angle constraints and the average weighting value currently. Another important component is the boom and the boom ratio. 

The boom is a directional vector which goes from the origin of the dolly and points to Kratos. The boom ratio which is a value between 0-1 which represents the camera position along the boom. We calculate the boom ratio two ways. It has a constraint to dolly and constraint to target, which sets two constraints that the camera cannot pass. The boom also has two offsets known as angular constraints so the camera can angle itself between two set angular constraint vectors.

Combat Camera:

Combat camera's have what is called a rig. For regular gameplay, a rig is made up of three joints. The base joint exists at the base of the player, the camera which is placed above and behind the player, and the target, which is in front of Kratos. Sometimes we lock this to prevent issues because of the level geometry.


Targeting:

When trying to determine where the boom target will be (where the camera is facing) we have to take into account the weight value of each character. This could be Kratos, enemies, or large trolls or important objects. 


The above example deominstartes how to determine the boom target. As you can see, Kratos is surrounded by a large red sphere, and the creature has a smaller red sphere. This is the weight influence of both characters on screen. So what we do is take the average weight and place the look at here. This way, the camera will follow Kratos and keep enemies in sight. However, we introduce concepts like distance from the hero and activation/deactivation fade to ensure that Kratos will stay on screen. 

Distance weighting simply ensures that the hero is is the primary weight, assuming we have a large number of bad guys in the background. This ensures he does not get lost in the crowd or Kratos walks off screen. Activation/Deactivation fade is when enemies die or spawn and we slowly introduce their weighting to avoid strong camera movements (snap movements).

Lastly, we can apply priority weighting to ensure that Kratos for sure will never go off screen. Because we have the concept of the safe zone, and we want to keep Kratos on screen, if we make him a priority weight, then the camera will always take his weighting into consideration. It will prioritize on getting Kratos into the screen. We do this by first centering the frame on the hero. We then calculate the extents of the lowest level priority and move the frame the smallest amount required to get as much of the action as possible. We then repeat at the next highest priority level until done. When this is all done we have the amount the frame has moved and we apply that delta to the azumith & elevation parameters, we get our new boom target. 

Enemies behind the camera:

A big problem was when enemies would move behind the camera. However, this was solved through a method of priority framing. What the programmers did is applied a minimum distance to target constraint. This essentially forces the camera behind the camera based on the distance to target constraint discussed before. It fixes the problem and still keeps Kratos in the safe zone.


Conclusion

Unfortunately, due to exams and other circumstances, I was not able to include everything I learned over the course of the year. However this class has really been a learning experience. I learned a great deal from it and there is so much I can now apply to my own projects.

Thank you for reading!

Works Cited

http://twvideo01.ubm-us.net/o1/vault/gdc2011/slides/Phil_Wilkins_IteratingDynamicCamera.pdf

Gregory, Jason. Game Engine Architecture. Wellesley, MA: K Peters, 2009. Print.

1 comment: