• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
  • entries
    94
  • comments
    271
  • views
    150217

As promised: Component Binding "BEHIND THE SCENES"

Sign in to follow this  
Followers 0
evanofsky

1869 views

In the wake of this brief description of my component binding system, I was asked to provide more details on its implementation. This article is my best attempt to do so!

This is a tale of intrigue, excitement, and wonder, in which I try to implement a component-entity system in C#, and stumble upon a remarkable paradigm that merges components with data binding.[font="Georgia,"]

Note: If you don't have at least a vague concept of component-entity design, read this article first.

Converting from OO to Component Binding
I started with an orthodox inheritance hierarchy. You've got a GameObject base class with Update and Draw methods. You've got subclasses for each type of object: Player, Camera, Object, Map, etc.

How to convert this hierarchy into components? I figured the one thing almost all the GameObjects had in common was a position, so I set out making a component to store that:
[source lang="csharp"]
class TransformComponent : Component
{
public Vector3 Position;
public Quaternion Orientation;
public Vector3 LinearVelocity;
public Matrix Transform;
public override void Update(float dt)
{
this.Position += this.LinearVelocity * dt;
this.Transform = Matrix.CreateTranslation(this.Position) * Matrix.CreateFromQuaternion(this.Orientation);
}
}
[/source]Next, I created a ModelComponent, that would display a 3D model. This was easy because I already had a separate Model class that was already self-contained. I then wrote a factory to make my first entity: the player. Why a factory? Because it seemed to be the thing to do, and it sounded cool.
[source lang="csharp"]
class PlayerFactory : Factory
{
public Entity Create(Main main)
{
Entity player = new Entity();
player.AddComponent(new TransformComponent());
player.AddComponent(new ModelComponent());
}
}
[/source]Now, how to get the model to show up at the position and orientation specified by the TransformComponent? I wanted the output Matrix from my shiny new TransformComponent to magically "go to" a model component. Or a camera component. Or a shader. Or whatever I wanted! That was the whole point of this disastrous endeavor.

Magic Properties
I needed to create a mystical linkage between two Matrix properties. For that to happen, I would need a way to know when a property changed, so that I could update all the other properties bound to it. And for that to happen, I needed some kind of method that would be called whenever a property changed. So I created a Property object that could be templated to store any kind of object or primitive type. My components now looked like this:
[source lang="csharp"]
class TransformComponent : Component
{
public Property Position = new Property();
public Property Orientation = new Property();
public Property Transform = new Property();
// ...
}
class ModelComponent : Component
{
public Property WorldTransform = new Property();
// ...
}
[/source]To write to one of these properties, I had to do this:
[source lang="csharp"]
this.Transform.Value = ;
[/source]It was a little ugly, but at least I had a property setter where I could put code to update other properties.

With that done, I created a Binding class to link properties together. Upon initialization, the Binding would let both properties know it existed. Both properties would save the Binding to private lists, and whenever their Value setter was called, they would notify all their Bindings, which would synchronize everything between the properties. The player factory method now looked like this:
[source lang="csharp"]
public Entity Create(Main main)
{
Entity player = new Entity();

TransformComponent transform = new TransformComponent();
ModelComponent model = new ModelComponent();

player.AddComponent(transform);
player.AddComponent(model);

new Binding(model.WorldTransform, transform.Transform);
}
[/source]I ended up creating a few different types of Bindings which behaved in different ways. The most basic kind of Binding was one-way between properties of the same type, like the above example. But I quickly found that I needed a way to convert between property types. For example, in the player "state" component I had a Rotation float property that specified the 2D angle the player was facing. I needed to convert that to a Matrix for the Transform component. Through the magic of lambda functions, I ended up with this:
[source lang="csharp"]
// Have the player face the direction he is going
new Binding(
transform.AbsoluteOrientation,
x => Matrix.CreateRotationY(x),
state.Rotation
);
[/source]I created Bindings that compiled values from multiple Properties. I created two-way Bindings. I created Bindings that were automatically re-evaluated every time their Properties were queried, even if nothing seemingly needed updating. They were all pretty trivial and really came in handy later on.

Reaping the benefits: Bindings and declarative code
Bindings are really the strong point of this system. It makes your code declarative rather than procedural. Let's say you want to make a "crouch" ability that lowers the player's height when he's crouching. In standard OOP, you'd get something like this:
[source lang="csharp"]
class CollisionObject : GameObject
{
float width;
float height;
float depth;
public override void Update(float dt)
{
super.Update(dt);

// ... do collision-checking with the width, height, and depth variables
}
}

class Player : CollisionObject
{
public Player()
{
this.width = 1.0f;
this.height = 2.0f;
this.depth = 1.0f;
}
public override void Update(float dt)
{
super.Update(dt);

if (Input.KeyIsPressed(Keys.Crouch))
this.height = 1.0f;
else
this.height = 2.0f;

// ... oodles of other update code...
}
}
[/source]Two years later, when you dig up this project and you want to know how the crouch function works, you'll have to look through the entire Player and CollisionObject code to understand it.

If we tried this with components, we might come up with an InputComponent that handles keyboard input, and a CollisionComponent that handles collision detection. Then in our factory method we might create a binding like this:
[source lang="csharp"]
new Binding(
collisionComponent.Height,
x => (x ? 1.0f : 2.0f),
input.CrouchKeyPressed);
[/source]What changed? Rather than writing a procedure to update the player's height every single frame, we declared a relationship between the crouch key being pressed, and the player's height being decreased. With bindings, you can declare behavior almost like declaring HTML markup.

Still, sometimes you just need to write things procedurally. Don't worry, you can still write procedural code in your individual components. Just be sure to make each component self-contained, and then glue them all together with declarative bindings. Actually, while transitioning to the component system, you can take the "Blob" approach. That is, take all your current procedural code and cram it into a "Blob" component. You can then slowly separate it into more manageable components. Eventually each component will have a nice amount of self-contained procedural code, and you'll have a factory to glue it all together with declarative bindings.

Setters and Getters
One problem I encountered early on was that a lot of my properties had getters and setters, and I didn't want to give up these convenient little methods. A few quick changes to the Property class, and I can do things like this:
[source lang="csharp"]
public class AudioListenerComponent : Component
{
protected AudioListener listener = new AudioListener();
public Property Position = new Property { Editable = false };
public Property Forward = new Property { Editable = false };

public override void InitializeProperties()
{
this.Position.Get =
delegate()
{
return this.listener.Position;
};
this.Position.Set =
delegate(Vector3 value)
{
this.listener.Position = value;
};

this.Forward.Get =
delegate()
{
return this.listener.Forward;
};
this.Forward.Set =
delegate(Vector3 value)
{
this.listener.Forward = value;
};
}
}
[/source]Yes, you can even technically initialize the delegates inline with this really slick syntax:
[source lang="csharp"]
public class AudioListenerComponent : Component
{
protected AudioListener listener = new AudioListener();
public Property Position = new Property
{
Editable = false,
Get = delegate()
{
return this.listener.Position;
},
Set = delegate()
{
this.listener.Position = value;
}
};
public Property Forward = new Property
{
Editable = false,
Get = delegate()
{
return this.listener.Forward;
},
Set = delegate(Vector3 value)
{
this.listener.Forward = value;
}
};
}
[/source]But then for some reason the compiler doesn't let you access the "this" keyword. Bummer.

Commands
I soon realized that the Binding system was somewhat lacking. There was no way to bind events to each other. I wanted a way to say, "when this happens, do that". I followed the MVVM design pattern and used Commands to make this a reality.

The Command class is practically a mirror image of the Property class. But instead of storing a value, it stores a function pointer. Whenever the Command is executed, it calls the function pointer and also executes any Commands that are bound to it with CommandBindings. Easy.
[source lang="csharp"]
public class TimerComponent
{
public Command Command = new Command();

public void Update (float dt)
{
// ...
this.Command.Execute();
}
}
public class SoundComponent
{
public Command Play = new Command();
}
// Factory code...
new CommandBinding(footstepSoundComponent.Play, footstepTimer.Command);
[/source]Adding Commands with one or two parameters was fairly trivial.

Conclusion
This pattern, like all design patterns, is not a silver bullet. I still have too many tight linkages in my code. But it's an improvement, and certainly a step toward self-documenting, maintainable code.

There's a lot more to this system, including how it all works with .NET serialization. I don't have time to cover it all, so for your browsing pleasure, here are the core classes extracted from my project. Hopefully they can be some use to you.

Thanks for reading![/font]

[font="Georgia,"]Mirrored on my blog[/font]

9
Sign in to follow this  
Followers 0


2 Comments


Brilliant. We are proud of you!

Code that views game worlds as a series of interconnections would make things so much cleaner. But if I could ask: how would you handle component bindings in a feedback system without suffering an infinite loop? I was starting to think it was impossible given the ultimately deterministic nature of threads.
2

Share this comment


Link to comment
Thanks!

You mean having two properties bound to each other? Yeah, that was a problem. I ended up having separate internal and external setter functions. The external one used by the client code changes the value and then sends out property change notifications. The binding system uses the internal setter, which doesn't send any notifications.

Once I got the two-way bindings working, I started setting up bindings [i]within[/i] components as well. For example, my TransformComponent soon had separate properties for position, rotation matrix, quaternion, scale, etc. Instead of updating all of them each time the transform changed, I just created two-way bindings between them in the component constructor.
0

Share this comment


Link to comment

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