Event/Action Management

Started by
7 comments, last by Irlan Robson 9 years, 7 months ago

I'm currently considering how i might approach a parameter based event management system.

My aim is to build it such that the actions that are executed on a particular event are able to be dynamic. This would essentially extend the event system that is used for input control, however my aim is to use a lot less case statements.

My initial thought was to build up a couple of string based maps so that parameters may be allocated against events, for example:

map<string,string> actionMap;

map<string,function> FunctionMap;

actionMap["onCollision"] = "doDestroy"

FunctionMap["doDestroy"] = <pointer reference to function to execute for destroying an object>

allowing for other parts of the code to call,

FunctionMap[ActionMap["onCollision"]](<object reference>);

I've already encountered some pitfalls with this approach, particularly the catches with using function pointers, and void* variables, and was curious to see what other people were doing in this kind of case?

Is there any real advantage in doing this compared to say, case statements against variables? Noting I'm hoping to have a few thousand objects at a time.

Advertisement

In my projects I usually write event subclass for every different case with base properties in base class and event specific properties in subclasses. This is the typical OOP that can save you from hours of debugging looking for error in your dynamic events, however you have to spend more time implementing different classes. You can easily go with only one dynamic class with maps etc.. but that in future can create a messy code with lots of constants for parameter names and huge potential for bugs. I guess this is a personal choice, both options are valid.

www.corsairgames.com


I've already encountered some pitfalls with this approach, particularly the catches with using function pointers, and void* variables, and was curious to see what other people were doing in this kind of case?

You can surpass most of these pitfalls by using an additional layer of indirection. That would be:

- instead of passing void*-pointers, you can use a "Variable"-wrapper class. This "Variable"-class would have to be no more than a variant, that allows you to store any type and cast it back on will. Thats easy to make, if you know how to use templates. The function will already know which types to expect, so all you need is some sort of type-id to make sure that the passed in value is correct (hint: this is optional in case you really trust yourself never to mess the input up ;)). Using the CRTP however, this is quite easy to accomplish:


static int typeId = 0;

template<typename Type>
int typeId(void)
{
    static const int id= typeId++;
    return typeId;
}

class Variable
{
public:
	template<typename Type>
	Variable(const Type& value) : m_type(typeId<Type>())
	{
		m_pData = new Type(value);
	}

	template<typename Type>
	const Type& GetValue(void) const
 	{
		assert(m_type == typeId<Type>());
		return *(const Type*)m_pData;
	}

private:

	void* m_pData;
	int m_type;
}


// usage in code:

void onDestroy(const std::vector<Variable>& vVariables)
{
	assert(vVariables.size() == 1);
	const MyObjectType& object = vVariables.front().GetValue<MyObjectType>();
}

// ....

MyObjectType enemy;

std::vector<Variable> vVariables;
vVariables.emplace_back(enemy);

onDestroy(vVariables);

Using typeId<Type>() will return a runtime-static ID for the specific type. You can then store a function-pointer defined as


typedef void (*Function)(const std::vector<Variable>&);

in your map. You can use helper functions, especially templated once (variadic templates ftw!) to make the usage as easy as possible, also note that the code I show you isn't fully implemented out and probaby doesn't even run as is.


I've already encountered some pitfalls with this approach, particularly the catches with using function pointers, and void* variables, and was curious to see what other people were doing in this kind of case?

I see from the fact you're using std::map that you're already partially using C++. You could go a step further and use std::function instead of the C way of raw pointers and void* and avoid most of those catches you've encountered.

Stephen M. Webb
Professional Free Software Developer

Thanks for the responses so far... attempting to digest them.

I'm liking the look of std::function and was surprised that I've not seen that before... is this new with c++11?

So I thought I'd come back in here after having a tinker and give my outcomes.


#include <functional>
#include <vector>
#include <string>
#include <map>

template 
int idType(void)
{
	static const int id = typeid(varType).hash_code();
	return id;
}

class Variable{
public:
	template
	Variable(const varType& _in) : type(idType()){
		data = new varType(_in);
	}

	template
	const varType& GetValue(void) const{
		assert(type == idType());
		return *(const varType*)data;
	}
	
	int GetType(void) const{
		return type;
	}

private:
	void* data;
	int type;
};


int destroyObject(Variable targetID){
	if (targetID.GetType() == typeid(std::string).hash_code())
		fprintf(stdout, "%s to be destroyed\n", targetID.GetValue().c_str());
	else if (targetID.GetType() == typeid(int).hash_code())
		fprintf(stdout, "%i to be destroyed\n", targetID.GetValue());
	else
		fprintf(stdout, "ERROR: EVENTMGT - destroyObject passed invalid variable\n");

	return 0;
}

int createObject(Variable targetID){
	//will be passed 2 values, both will be strings...
	if (targetID.GetType() == typeid(std::string).hash_code())
		fprintf(stdout, "%s to be created\n", targetID.GetValue().c_str());
	else
		fprintf(stdout, "ERROR: EVENTMGT - destroyObject passed invalid variable\n");

	return 0;
}

int testUpdate(Variable value){
	int newValue = 5;

	return newValue;
}

class EVENTMANAGER{

	std::map funcMap;
	std::map actionMap;
	//onCollide callAction doDestroy;
	//function* funcArray[1];

	
public:
	EVENTMANAGER(){
		funcMap["doDestroy"] = destroyObject;
		funcMap["doCreate"] = createObject;
		funcMap["testUpdate"] = testUpdate;
		actionMap["onCollision"] = "doDestroy";
	}

	void functionRun(std::string s){
		std::string strings[2];
		int targetId = 2;
		Variable returnVal = funcMap.at("testUpdate")(targetId);
		targetId = returnVal.GetValue();

		std::string string = "this is a string";
		Variable arg = string;
		(funcMap.at(actionMap.at(s)))(arg); //could simply pass the string variable, rather than casgint a Variable type to a string.

		//example of passing string to function, needs to be explicitly defined and passed as string.
		//[Variable arg = "this is a string"] will assume that the variable type is char* and char* is not a valid type.

		//std::string string = "this is a string";
		//fprintf(stdout, "%s is set to arg\n", arg.GetValue().c_str());
		//(funcMap.at(actionMap.at(s)))(string);
		
		//example of passing float to function
		//Variable argf = "1.0f";
		//(funcMap.at(actionMap.at(s)))(argf)
		
		
	}

};

As you outlined Juliean, the code you put up was somewhat non-functional, particularly had issues with the type identification in the first block.

Opted to try the typeid inbuilt function to use the hash code to track the variable type, though i've read there are some issues with this, particularly cross platform however its more of an issue using the name member from what i understand.

I've taken on the point of using <functional>, and toyed with the idea of using a Variable return type, for a Variable input.

I had thought about using STD::Vector though thought that this might be redundant, and when i played with it, there was a little bit more effort to pull the variable arguments out, but it completely worked, though its probably better using the vector vs passing a vector.

Its surprising how powerful this kind of templated class and function is, and from the research i've been doing, a lot of people simply say its not possible... which is really surprising that this is as simple as it is.

[edit] Borked formatting [/edit]

I'm not exactly a veteran coder, so take what I say with a grain of salt, but it sounds like you might be interested in the Command pattern: http://en.wikipedia.org/wiki/Command_pattern

Essentially, instead of passing around function pointers that take in void* parameters, you encapsulate the function calls in an object with a common interface. For example, in an RTS-like game:

Disclaimer: didn't test this code


class Command
{
public:
    virtual ~Command()
    {}

    virtual void execute() = 0;
}

class MoveCommand : public Command
{
public:
    MoveCommand( GameActor& actor, double goalX, double goalY )
    :   _actor( actor ),
        _goalX( goalX ),
        _goalY( goalY )
    {}

    ~MoveCommand()
    {}

    void execute()
    {
        // do whatever sophisticated move logic you need here
        // probably something better than this.
        _actor.moveBy( _goalX - _actor.getX(), _goalY - _actor.getY() );
    }

private:

    // store whatever data you need for this type of command
    GameActor& _actor;
    double _goalX;
    double _goalY;
}

Then, you can create commands somewhere and pass them into a CommandHandler class that executes them whenever you need.


class CommandHandler
{
    ...
public:
    void addCommand( Command* command )
    {
        _commands.push_back( command );
    }
    void executeCommands()
    {
        for( auto command : _commands )
        {
            command->execute();
        }
    }

private:
    std::vector<Command*> _commands;
}

// somewhere in your code
Command* command = new MoveCommand( someActor, someX, someY );
commandHandler.addCommand( command );

// later
commandHandler.executeCommands();


Also, it would probably be better if instead of using strings in your actionMap and functionMap, you used enums instead. That way the compiler will detect invalid keys so you don't get burned by typing "onDestory" somewhere in your code, which could end up being a difficult bug to track down.

The use of String at the moment is more of a 'first cut' than anything else. I've done some 'safety testing' and it appears the way this has been implemented is that simply putting in a line that says "onDestroy" without parenthesis will simply do nothing (will be undefined variable, or invalid call of function) and to call it from the funcmap you have to actively call the funcmap to do the call, there's no magic pointer at a global level. I take the point about the invalid key though, there is no error checking at the moment to ensure that the key being used actually exists in the maps, other than the map security itself, and if a non-mapped key is used it does error out. That is my next step (people say i work backwards), the aim at this point was to create the ability to reference a function from a map and pass dynamic variables.

Little off-topic but is very rare the use of events in a well structured game. They are just IDs that you pass to objects instead of calling the object function. My recommendation is that you try to solve your problem without the use of events. If you're thinking that input are events they aren't. Search on the forums and you will see. Using strings to declare an event is the worst approach I think. Since all objects can know about the event, why give it a name instead of a constant ID? Games aren't that Java Application that use events for everything, they're real time simulations.

This topic is closed to new replies.

Advertisement