Why Robotlegs For Games?

Why Robotlegs for Games?

The following covers why you would utilize the Robotlegs MVC architecture in a lightweight, Lua game for Corona. I’ll discuss the refactoring reasoning, the common problems you run across in game architecture, and their solutions with their pro’s and con’s discussed. Finally, I conclude on how Robotlegs helps solve these common issues, specifically in a Lua & Corona context.

I’ve started the port of Robotlegs to Lua to work in Corona if you’re interested in learning more.

Refactor First

In learning Lua & Corona, I quickly ran into 2 problems with the game I’m working on. The main code controller became way too large to manage. It wasn’t quite a God object (yes, the anti-pattern) because a lot of the View’s themselves handled some of the necessary messaging & logic. Regardless, time to refactor.

The first thing was to start using classes. Lua doesn’t have classes. There are a bunch of resources out there that explain how to do them in various incarnations. I went with a version that Darren Osadchuk, creator of the Corona bundle for TextMate.

The second thing was to start using packages. Lua doesn’t have packages. There are various ways of implementing them which are all confusing as hell. The easiest way is to just put your code in a folder and use that path in the require function, but you can’t utilize folders for Android in the latest build of Corona at the time of this writing.

These are the low hanging fruit of re-factoring, and has made a huge difference in code readability & maintainability.

Burdens of Encapsulation

The downside of OOP is that it’s encapsulated. While making something a black box with internally managed state & implied reusability is good on the surface, it pushes the burden of managing communication between those encapsulated objects to someone ones.

You have 3 options: globals, messaging dependencies, or mediation.

Global Variables: The Good

Most people agree global variables are bad… in larger software development. In smaller scoped software gaming, not so much. Let’s explore their benefits.

In a lot of languages, globals are part of the language design, irrespective of how the runtime and tools/IDE’s handle them. Some languages make them first class citizens with mechanisms and rules around how they’re often used. This makes them formalized, accepted, AND useful. This is important to understand.

If it’s formalized, it means the language designers deem their usage acceptable, AND expected.

If it’s accepted, it means others will use them, incorporate them into their projects, libraries, and training & writing materials. This also means it’s then promoted amongst the community, solutions and coding strategies/solutions are built around it. This doesn’t make it inherently “good”, just accepted in that particular community.

If it’s useful, the majority of people will use it if their job is using that language as opposed to hobbyists, or those who continue to explore the language and try different ways to solve similar problems with it off of their employer’s clock.

In Lua, globals are all 3. Formalized via _G, very similar to ActionScript 1’s _global, accepted in that people do in fact use them (unknowingly a lot I’d wager), and useful since the syntax to utilize globals is terse; a Lua hallmark. Notice both have the preceding underscore to ensure they don’t interfere with the developer’s potential to create a variable called G or global. While ActionScript 1 has some security implementations to prevent certain loaded SWF’s from writing/modifying existing definitions, they had the same mechinism with strorage, first via _level’s on a per SWF basis, and later a formalized _global. Lua takes it a step farther with a series of facilities to change “which” globals your using, etc. It’s also used in package naming strategies, OOP, etc.

As a globally accessible table, access to _G is fast. Fast is good in game development. You want to be part of the solution, not part of the problem.

Global Variables: The Bad

This differs from traditional software development. If you come from any formal software development, globals are considered extremely bad practice. There is a common strategy to use the Singleton design pattern to “get away with it”. Even those are considered bad practice when over used. In fact, Singletons are often created merely because the language doesn’t offer a formalized way of doing global variables (like ActionScript 3 vs. ActionScript 1).

Why? The 3 main reasons are application state coupling, access control, and preventing testability.

Application State Coupling

Application State Coupling refers to the state of your application being dependent on usually a series of global variables. I won’t get into the why’s, but MVC and it’s MVP derivatives (Passive View, Supervising Controller, Presentation Model) have solved most of the state problems. They keep visual state in the View’s (or anything that’s a GUI that you can see), and application logic & state in the Model layer somewhere. Your application is no longer coupled to a single variable being a specific value for your application to run, to exhibit a certain bug, etc. Each piece can (usually, hehe) be run independently, and if there is a problem, you know where to look, or at least where NOT to look.

An example is if your player is dying too quickly, you know the problem isn’t in the player code, or the controller code, but rather somewhere in the model where his life state is being access/set/updated. If you used a global, it’d probably be set in player itself, or perhaps by an enemy bullet that hit him, etc. No clue where to look.

Another side effect is adding new global variables. This leads to certain parts of your application expecting the globals to be a certain value at certain times. If they aren’t, things don’t work. Because they are many different places, it becomes extremely time consuming for you to debug and track down because you don’t necessarily know who is expecting what to be set to what, and why. This is more caused by access control, however…

Access Control

Access Control refers to who can access your data, and how. In Flash & Flex apps that are smaller, we’ll usually use the server as access control. Meaning, while we provide a GUI to allow people to create, edit, and delete users from a database for example, the actual PHP/Ruby/Python/Java on the server is the access control. No matter what we do in the Flex/Flash, we can be assured the server (usually… *sigh*) will ensure we don’t delete people we’re not allowed to, delete users en-masse, put illegal characters into their name, etc. Basically anything that would corrupt the data and screw the up the GUI.

In Flex/Flash apps, and nowadays in larger JavaScript web applications, you have a notion of “application logic” or “application state”. This is because this state is no longer on the server. It used to be with some web applications, usually in the session. When you go add something to your cart on Amazon.com, it’s not stored on the page that much beyond to show you a slight graphical change. Once you change pages, that JavaScript & HTML page state is now gone and replaced with a new one… but it remembers what you added. It does this because the state is saved on the server since the client needs to be stateless if the user refreshes the page to go to another one.

We don’t have that problem as much in Flash/Flex apps. We don’t go to pages insomuch as new “Views”. These views, or graphical representations of a GUI that have internal state, are still in the same SWF embedded in the same page in a browser that doesn’t go anywhere (same thing for an AIR app on the desktop or on a mobile device). Therefore, someone has to be responsible for holding the data in a variable or series of variables, and updating it when the server gives you new data.

These are usually classes called “Models”, and they’ll usually mirror their server-side equivalents in terms of CRUD operations: create, read, update, and delete. Where they differ is how much of the server-side provided data is parsed, error handling, data access control, and how that server-side data is set internally.

Suffice to say, good Model classes are encapsulated, ensure application logic is accessed by a public API that ensures security, doesn’t allow the internal data to be corrupted, and does all this within reason. An example is our Player’s health. If every enemy collision and bullet out there has access to the player’s health, we have no easy way to track down who may be potentially doing the math wrong on calculating the new hit-points and setting them to invalid values, or thinking the player is dead when she’s not, etc. If you have a PlayerModel, you can ensure your problem’s regarding hit-points and letting the world know about player death is in one place, and problems with said state (how much health does the player currently have) starts in that class and those who access him. Access control in this case refers to ensuring the PlayerModel only exposes methods to increment/decrement the Player’s hit-points vs. allowing them to be set to -16, or NaN/Nil, etc. You don’t even have to worry about this; you just don’t allow it to happen.

Thus, the burden on accessing and setting hit-points correctly is pushed to someone else; those who access PlayerModel. THIS is where you look for bugs, but again, you need to ensure only a set few have access to the data access layer (PlayerModel).

In short, Models centralize data access, ensure it’s correct, testable, and DRY and prevent incorrect access errors, (i.e. global.playerHitPoints = “dude, pimp!”).

Preventing Testability

This third problem isn’t necessarily around unit-testing and TDD (Test Driven Development), but more around just ripping the class out, putting in a simple main.lua, and seeing if it works. If it has dependencies, they get dragged with it… and you have to instantiate and setup those guys. Suddenly quickly confirming some class or method works or not becomes a time consuming process that’s painful. If you can’t test something in isolation, you’ll have huge problems down the road isolating problems in a timely fashion.

Globals by their very nature are’t testable because they’re variables, not encapsulated classes. While Lua has some neat mechanisms to encapsulate globals in certain contexts, somewhere, someone is setting a global to some value in their own way. If a class depends on this global, that global must be set the same way before you test the class that relies on the global. Since you may not know who set the global a certain way, that global may not be the same in your test environment vs. in the game proper.

Global Conclusions

While globals in Lua are fast, formalized, and accepted, you must be aware of the rules so you can break them with confidence. First, keep in mind if you want to get something done, premature optimization is the root of all evil. With that in mind, ask yourself the quick question: Does creating a data access control class/layer around your globals to ensure it’s DRY and secure add so much overhead that the speed makes your game un-playable?

I’ve found this not to be the case in my implementations in Lua and ActionScript. They run fine, are encapsulated, and succeed in good access control. Thus, while globals are accepted in Lua, implementing a good coding practice via a data access layer does not adversely affect my performance while increasing my productivity in DRY’er code that’s easier to test with good encapsulation.

Messaging Dependencies

We’ve seen how globals can work to allow multiple View’s to talk to each other directly or indirectly via variables they all reference, or even methods/tables. We’ve also see how this leads to bad things like harder to find bugs and spaghetti code (you change 1 thing that adversely affects something else seemingly unrelated) as well as making refactoring more challenging than it needs to be.

One way to allow encapsulated objects to communicate is through messaging systems, also know as notifications or events (we’ll just call them events because that’s what ActionScript and Corona use). When something happens inside the object, such as a user clicking something, or some internal property changes, it’ll emit an event. There are 3 types of events we’re concerned with: local, global, and event context.

A local event is an event issued from an object/table. In ActionScript, anything that extends EventDispatcher, including DisplayObjects (things you can see), can emit events. In Lua, only DisplayObjects can; you have to build your own for regular tables as Lua doesn’t have an event system. So, if I create a wrapper table in Lua, I can then register for events from that table, and later when it emits them, I’ll hear them. Those are local events; events dispatched from an object/table directly. Although event objects/tables have the target property on them so I know where they come from, USUALLY event responders are not that encapsulated, and make the assumption that the event is coming from a specific object/table.

A global event is one that’s received, but we have no clue where it came from. At this point, we’re inspecting the event object itself to find context. If it’s a collision, then who collided with who? If it’s a touch event, then what was touched, and how? Global messaging systems are used for higher-level events and concerns. While you usually won’t have global events for touches because your mainly concerned with handling the touch event locally, a pause event for example could of been issued from anywhere, and while you don’t care who issued it, you’re more than capable of handling it (stopping your game loop, pausing your player’s movement, etc).

To properly handle an event, we need context. Context is basically the data the event, or message, has stored internally so when the handler gets it, he knows how to handle it. If the event is a touch event, cool, start moving. If it’s a touch release event, cool, stop moving. If it’s a collision, is it a bullet? If so, take less damage than say a missile hitting. Is the bullet’s velocity higher? If so, take more damage than usual. This context is what allows the encapsulation to happen. You issue a message, provide context, and whoever gets it doesn’t necessarily HAVE to know where it came from; they’ll have enough information to know how to handle it.

For Corona DisplayObjects, this is easy. You just use dispatch an event. But for Model/data access objects, not so much. You don’t want the overhead of a DisplayObject to just to send messages, so you build your own. This implies another class/table with the capability of sending/receiving messages. This means your classes will have a dependency on this object. For example, if I want to test my Model class in a brand new main.lua, it’ll bring along/require the messaging class. This is a dependency. One of the threads (just like OOP, encapsulation, keeping things DRY, don’t optimize too early, etc) you want to keep in the back of your head is to keep the dependencies low. You don’t want a class to have too many dependencies. Like globals, dependencies can cause spaghetti code, hard to test & debug situations, and overall just hard to manage code.

Corona makes the event dispatching dependency invisible with DisplayObjects because it’s built in. Not so for regular tables. Somehow, you have to put this dependency in every class. You can either create a public setter for it, and pass in an instance, or just reference a class globally in a base class. Both are a dependency, the latter just requires a lot less work and code.

Downside? It’s a dependency. You also force this implementation on everyone who wishes to utilize your class. If you make the messaging system events, 2 things happen. First, people using Corona get it because it’s the exact same API and functionality (excluding bubbling) that developers are used to. Secondly, it’s interchangeable and works with Corona DisplayObjects. The best solution would be to do Dependency Injection/Inversion of Control… but I haven’t figured out how to do this in Lua yet, and I’m not sure Lua supports metadata annotations. Considering it’s dynamic, you CAN inject things like this at runtime, but someone, somewhere has to do so. Why do so when every object requiring messaging needs the same mechanism? Thus, the pragmatic thing is to build it in.

Also, more importantly, DOES this messaging system add more performance overhead than using simple globals? To make the question harder to answer, can you make tighter coupling of your code and still get things done?

It’s been my experience, if you make things easier to use with less coupling, you’re more productive in the last 10% of your project. While coupling makes things easy in the beginning, it’s a farce; it has more than an exponential cost at the end.

Besides, you can always increase coupling easily; it’s removing coupling later that’s hard. If you need to optimize, great, you can. If not, great, no more work to do; you can instead focus on features. Usually, though, you’ll know pretty quick if you do iterative builds if a messaging system is making a huge performance impact on your game on not. The only surprises you’ll get is you spend days on something without a build. Do a small test, see if there is a noticeable difference. Sometimes you’ll have n-problems you won’t find till your game gets to a specific size which are unfortunate. An example is a charting component that works great building up to 5000 data points, but suddenly DRASTICALLY slows down beyond that.

These problems aren’t the fault of the API. If you take a step back, the “30,000ft view”, usually it’s the implementation that’s at fault, not the code itself.

For example, a little history lesson. Back when ActionScript 1 development was increasing in scope, we went through 4 different messaging systems. The first was the built-in one for Mouse and Keyboard, etc. It was only partially available; there wasn’t a MovieClip one. So, we used ASBroadcaster; an undocumented one inside of Flash Player. It had a known bug with removing a listener during a dispatch, and other things. Then Bokel released a version on top of that fixed it. Then Adobe created EventDispatcher, mirroring the ECMA one. They then built this into the Flash Player for Flash Player 9’s new virtual machine.

There were others that came out after ActionScript 3 was born. PureMVC had notifications in it for an easier port to other platforms & languages. Robert Penner created Signals for a light-weight, object poolable, quick to develop in C#-esque messaging system.

As you can see, why the bottleneck for most larger Flash & Flex 1.x applications at the time was EventDispatcher, even when they built it into the runtime in C, developers opt-ed for a slower system built by themselves to solve different problems.

So why the continuous talk about performance questions in this section when I rail against premature optimization? Because messaging is the core of any app, or game. The choice you make is the largest impact on what you’re building, both from performance and from a development perspective. Yes, you can just use direct access to objects, or callbacks, but that’s not very encapsulated, nor DRY, and is a pain to re-factor later if you need. Messages via Events are more encapsulated, and less coupled, but have a performance impact. Additionally, only DisplayObjects use the internal C implementation; your own uses interpreted Lua with whatever JIT’ing/machine/voodoo conversion Corona does.

Traditionally, it’s easy to switch to events from callbacks, but not the other way around. While the performance impact isn’t that large to utilize a DisplayObject and use the built-in event messaging, based on some benchmarks, this isn’t a good idea to build upon.

Mediation

The third option is using the Mediator pattern. Once you have 2 encapsulated objects that need to talk to each other, you utilize a class that handles the communication. It takes the message from ViewA and sends that to ViewB. When ViewB wishes to talk to ViewA, it sends the message and the Mediator relays it.

All the MVC/MVP articles go over A LOT about the different things a View should/should not do, particularly with it’s needs for data and how to show it. Regardless of the implementation, it’s generally understood that someone such as a Mediator or a Presenter handels the responses from a View. If it’s a Presenter, it’s a dependency in the View, and the View calls methods on it. This allows the actual logic behind both responding to View user gestures (like when I touch a button on the phone) to not muddy up the View (muddy up means TONS of code that has nothing to do with displaying graphics, putting into groups, setting up Sprite Sheets, etc), and allows you to test the behavior in isolation.

Mediator’s are similar, although, the View has no idea he/she has a Mediator, and the Mediator has the View reference passed into it by someone else. Again, more encapsulation, yet SOMEONE has to have the burden of setting up this relationship. In ActionScript this is easy; Robotlegs just listens for the Event.ADDED_TO_STAGE/REMOVED_FROM_STAGE events and creates/destroys based on an internal hash/table. In Lua, you don’t have any DisplayObjects events, so you have to manually do it.

Either way, if you DON’T Mediate your View’s, you’ll eventually have a lot of code in there that has to “know” about other objects. This’ll be either a global reference, or a dependency… and we’ve already talked about why those things are bad to do. Additionally, tons of code in general is bad; having a View just focus on graphical things and emitting events people outside would care about while the logic can be put elsewhere makes it easier to manage. When you open a View class; you know pretty quickly what you’re looking at is just GUI specific code.

There’s another more important aspect of Mediation that is similar to messaging and that is system events that affect Application Logic.

For example, many things in a game care about a Player’s health.

  • the Sprite that represents the player; it needs to show different graphics for how much health it has
  • a health bar at the top right of the screen that fills up with green the more health the player has
  • sounds that play when the player loses and gains health

If you use globals, you’d have all 3 handled by the actual Player sprite class. It’d update it’s internal health and update the global variables. Those who have references to the globals would be informed when that value changes. Additionally, you’ve now wired them together if you do this. If you change one, you’ll break the other.

Using a Mediator allows:

  • the player and the health bar both the capability to react to the change in the hit points in an encapsulated way. If you change how the Player and HealthBar look/work, the actual logic on how yo do that is centralized to either them, or their Mediators… and usually Mediators are like 1 line of actual code to change.
  • The application logic of how hit points are updated and changed to be done in 1 place. As your game grows and different enemies need to do different types of damage to your player, and sometimes react differently depending on how much health the player has, this is all done and updated in 1 place. It’s DRY, and easy to find where the logic bugs are.
  • A side effect of this is… the Mediator pattern (lolz). You can have View’s the capability of talking to each other without having tight coupling.

The most important feature is solving the classic race condition of is the data ready for a View when he’s created, or is it null and he has to wait. Using Medaitors, you don’t have this problem. In the onRegister, you just set it if you have it on whatever Model(s) you need, else just wait for the Model(s) to be updated and inform the view.

…I wouldn’t say totally solved; handling “null” or “nil” is still a challenge for developers even in simple View’s. Those are good problems to have, though vs. race conditions.

If you enter the optimization phase of your game and want to remove events, use callbacks, and have hard-wired references, that’s fine if benchmarks truly identify that you need the performance gains. Usually, though, Mediator communication isn’t your bottle neck, it’s collisions, lack of object-pooling, and how messages are handled.

Quickie on Commands

Commands are just formalized Controller logic. In fact, in other frameworks, they’re simply Controller classes with methods. They’re called “Commands” because they do 1 thing… and can potentially undo it. If you’ve ever used an Adobe Product, a few of them like Dreamweaver, Fireworks, Flash, and Photoshop will have a Command list, also called “History Panel”. In Flash and Fireworks, you can even get the code for these Commands. The line blurs here once you lump them all together, but in my experience, good Controllers have 2 things in common:

  1. They contain the only code in the application that updates the Models (update/delete in CRUD for internal data)
  2. They contain all application logic… or at least share the burden with the Models.

For #1, this is important in tracking down bugs and keeping your code DRY. You always know who’s changing your Player’s hit points, who’s actually applying your level up rewards, etc. If you can test your Models in isolation, and they’re good… then you know who to blame. This is good because again, they tend to often start by being 1 line functions with the potential to grow to 30 to 60… not a bad way to start life, nor grow. Small, readable code.

For #2, whether you have a Controller class function, or a Command, SOMEONE in your application needs to “load the level data” from your level editor. SOMEONE needs to handle the fact that your player just drank a health potion, but he’s also wearing a Ring of Health Boost + 2, and this positively affects the effects of the health potions she drinks. SOMEONE needs to handle calling the loadSaveGame service, ensuring it worked, and updating all the Models with their relevant Memento data.

This orchestrator of pulling everyone together, to read multiple Models and “make decisions”, they’re the brains of your application. For performance reasons, a lot of Controller logic is often done directly in game views, even if it just references a Controller class for ensuring logic is somewhat DRY.

There’s a lot of loathing in the community by those with a more pragmatic bent, or just on smaller code bases with shorter deadlines. The overhead associated with them completely negates their perceived value when you can just call a centralized Controller logic function via… a function call vs. some event that magically spawns some other class that has 1 function with a bunch of injected dependencies. Just depends in you read that last sentence and go “Makes sense to me, don’t see what the issue with it is… ” or “w…t…f… why!?”.

Conclusions

Remember, the above is all complete bs. If you or your team have a way of building games that works for you, great. This is just helpful tool I’ve found in Flash & Flex application development, and it seems to help me in Corona games, specifically around the GUI/HUD portions. I still have globals in my collision routines for speed purposes, hehe.

Additionally, it’s a great teaching tool, too. Joel Hooks got some similar schlack like I did in using PureMVC when he was first starting out in Objective C for iPhone. Providing a comfortable & familiar framework of development really helped him learn and have context how the new language & platform work with certain concerns; it’s how he shipped his first app on the app store. Same with me in Corona… and game development.

Finally, this isn’t an all or nothing approach. You can just use it on the parts you need, or perhaps just to learn. I find its helped me learn a lot about Lua and Corona, as well as having the flexibly to change the API of my Player and Enemies without affecting how the GUI itself around the game works. In true spirit of total disclosure, I’ll report on any adverse overhead if I find it.

7 Replies to “Why Robotlegs For Games?”

  1. First, the Mediator Pattern and Mediators in Robotlegs are two entirely different patterns (@see http://johnlindquist.com/2010/10/13/patterncraft-mediator-pattern-vs-framework-mediators/). Semantics, I know, but important to avoid confusion with your discussion on its benefits.

    Second, I think the only proper way to respond to this post (since you’ve already put so much effort into developing it) is to refactor your github sample with the way I would approach it (which I’ll try to get around to this week).

    Third, thanks for sharing. These are definitely discussions worth having.

    1. Of course they are, but you and I both know even with scientific definitions + studies behind patterns, no one implements them the same. I’ve seen people treat Mediators in Robotlegs like Mediators (who’d a thunk?). Others used them in conjunction with PassiveView’s, yet gave them their own Presenters… still others who used them as SupervisingControllers… and Robotlegs Mediators. OOP Soup, yo.

      Regardless, thanks for keeping me straight.

      Wow, John, that’d be great! I’m sure the community would totally A) dig another example and B) appreciate another perspective that holds weight. Corroboration is one thing in inspiring confidence, and a different approach is WAY more inviting for those who wish to learn. Poor Joel had a lot of responsibility on his shoulders to do everything, sounds like I’ll get off easy. If you need check-in access or whatever let me know how to do that on Github.

      Regarding third… if you say so. My initial suggestions on this were met with a ton of disdain and repulsiveness… which basically made me want to do it more.

      You rock as usual!

      1. Well, I never said I agreed with your approach ;)

        Too many people like to point out what’s “wrong” with other peoples’ code to try to validate themselves. They should be discussing what’s “right” with it to take the good ideas and make something better.

        Anywho, the “traditional” Mediator enables viewview communication (instead of viewapp) which I believe is a great pattern for character interactivity where things update every “tick”. Then you can simply have the Mediator send off commands to update UI, models, etc (you never know when you’re going to need a command history) for things that update less often and need looser coupling (I guess most to least performant would be Visitor/Observer, Mediator, then Messaging. That gives me some ideas for a blog post…).

        Anywho #2, I’ll let my example do the talking when I get around to it ;)

Comments are closed.