Alternative to context objects

Started by
3 comments, last by AzureBlaze 11 years, 3 months ago
Hi,

I have a "Stage" class which act sort of like a context object and contains every service and module that will be used in the same level. Most services live and die with the stage, but some are reference to upper services in the game. The stage also contains a list of entities who will use the services.

Entities come in vast varieties and each uses different services, so I pass the Stage object in their constructor and let them decide what to use.

Some entities need to load a sprite, which will be cached for later use in the same stage:
stage->getResourceManager()->getSprite(...);

Some entities need to check for map collisions:
stage->getMap()->testCollision(...);

Some entities need to override camera control:
stage->getCameraController()->setPosition(...);

This works, but every time I add a new service to Stage, every entity needs to be recompiled as they all depend on Stage, which is somehow annoying.

I also have a factory which maintains a map of every entity and its "Key", so I can read and create entities from a file. The factory have to call functions with same signatures, such as
Entity *Create(Stage *stage);
so passing individual service a certain entity need to its constructor don't seems feasible.

I have written several games, and they all end up having a huge class containing everything anyone might need. Is there a better solution to this?

I have looked into the service locator pattern but I'm not sure it is the right solution like this:
static_cast<ResourceManager*>(stage->getService("ResourceManager"))->getSprite(...);

Singletons won't work because there might be more than one Stage (split screen 2P, etc...)
Advertisement
1) Instead of calling functions send messages. Kind of ugly, but would work

2) Use Components

3) Use mixins

I prefer components myself.
Have a scene class, which contains a list of game objects.
A game object is a transform, a name, a layer and one or more components.
The component class is a generic interface, it has abstract functions to init, update, render, etc...
Subclass the component into things like: script component, camera component, sprite component, renderer component
So, you have a game object and you attach a sprite component to it. The sprite component does whatever needs to be done to load in a sprite (texutre, uv coords, etc...) It will however not render anything. For that you attach a render component.
Each frame you loop trough your cameras, each camera determines which objects are visible to it, then uses the render component to render the visible objects.
Delegate each specific responsibility into it's own component, and if you can have a script component to script your game.

Unity3D's script component lifecycle:
http://www.richardfine.co.uk/junk/unity%20lifetime.png
I agree that this issue can be addressed with component based design.

I currently favor a design in which components are those parts of entities which are associated with specific engine systems ("services"). They're created (and processed) by the engine systems themselves. And entities are collections of components.

The components generally need to know about a couple of other requisite components types, and often don't even need to know about their own engine system, since the system knows about them.

Note that this still leaves us with entity constructors which know about components, and the engine systems which create them.

This can be resolved by designing an entity factory, with which each engine system registers itself (rather than one which already knows about them), that does data driven entity construction (is given a list of component type IDs and uses the registered systems to generate an entity containing instances of those components).

That should eliminate the need to recompile code for non-dependent entity types when adding new systems. Although I must admit, I'm not sure how much this saves you in terms of re-compiling. On the one hand, there will still be some high level code (AI) which will need to know about a lot of the systems/component types. And on the other hand, adding systems doesn't seem like something which should be happening often enough for this to be an annoyance.
I recently solved this problem with what I call a "doubly-opaque pointer" (is there a named pattern or idiom for this?). The idea is based on a service provider object, which uses (abuses) forward declarations, template functions, and the opaque pointer idiom to provide a strongly typed pointer to its users. Only the object that constructs the ServiceManager will need to construct (and/or setup) all of its services. When setup correctly, only the ServiceManager.cpp and the object that sets up the ServiceManager will need to be recompiled if a service is added to the ServiceManager.

Here's a sample code sample:

// ServiceManagerImpl.h
class ResourceManager;
class SceneManager;
class RenderManager;

struct ServiceManagerImpl {
ResourceManager* resman;
SceneManager* sceneman;
RenderManager* renderman;
};


// ServiceManager.h
struct ServiceManagerImpl;

class ServiceManager {
public:
ServiceManager(ServiceManagerImpl* impl);

public:
template<class ServiceType>
ServiceType* get();

private:
ServiceManagerImpl* impl;
};


// ServiceManager.cpp
#include "ServiceManager.h"
#include "ServiceManagerImpl.h"

ServiceManager::ServiceManager(ServiceManagerImpl* impl) : impl(impl) {
}

template<> ResourceManager* ServiceManager::get() { return impl->resman; }
template<> SceneManager* ServiceManager::get() { return impl->sceneman; }
template<> RenderManager* ServiceManager::get() { return impl->renderman; }


And a sample demonstratation:

// Game.cpp
void Game::Setup() {
ServiceManagerImpl* impl = new ServiceManagerImpl;
impl->resman = new ResourceManager;
impl->renderman = new RenderManager;
impl->sceneman = new SceneManager;

theServiceManager = new ServiceManager(impl);
}

void Game::Dothings() {
for ( int idx = 0; idx < entities.size(); ++idx )
entities[idx]->update(theServiceManager);
}


// MonsterEntity.cpp
#include "MonsterEntity.h" // "ServiceManager.h" (implied)
#include "RenderManager.h"

void MonsterEntity::Update(ServiceManager& services){
services.get<RenderManager>()->renderThing(iDunno);
}


// PlayerEntity.cpp
#include "PlayerEntity.h" // "ServiceManager.h" (implied)
#include "SceneManager.h"

void PlayerEntity::Update(ServiceManager& services) {
services.get<SceneManager>()->currentScene()->setCameraPosition(getPosition());
}


As you can see, a new service can be added to ServiceManagerImpl.h with an accompanying template specialization for ServiceManager::get in ServiceManager.cpp without affecting ServiceManager.h and none of the ServicesManager users need to be recompiled. Only Game.cpp and ServiceManager.cpp need to be recompiled (expensive for Game.cpp, relatively light for ServiceManager.cpp).

I'm not sure how this rates on the OOP-perversion scale, but I think this is pretty neat.

EDIT:
Here's an image illustrating such an approach as well
http://i.imgur.com/rbPhD.png
I like the doubly-opaque pointer, like service locator it relieves the long list of getter method but doesn't require service ID managing or RTTI and will also tell you what's wrong at compile time.

As for components, I think I still need to pass around a context object around for their constructor or update method(The doubly-opaque pointer could also help this) , or use factory for components(which should be shorter than exposing all those services).

I also agreed that the recomplie issue is a bit overrated. I tend to add features one by one to make sure they all work fine. As the game architecture become more stable I shall seldom need to change the context object.

Thank you all for replying.

This topic is closed to new replies.

Advertisement