Game Development Community

Return a C++ Class through ConsoleMethod?

by Dante Falcone · in Torque Game Engine · 11/27/2008 (7:49 am) · 4 replies

Hello, I'm having a bit of a problem in this current situation.

I have entity data being saved in binary data files, and a script driven in game editor for these. I would like to be able to load these files and display their data via script. The problem I am having is that I would like to be able to pass the data class to the console through ConsoleMethod:

ConsoleMethod( NpcData, load, [b]NpcData[/b], 3, 3, "( char* NpcName )"
				  "Loads binary NpcData into a temporary class and returns the class")
{
	char loadFileName[30];
	std::strcat(loadFileName, argv[2]);
	std::strcat(loadFileName, ".npcData");

	std::ifstream inFile(loadFileName, std::ios_base::binary);

	if (inFile)
	{
		inFile.read( (char*)[b]object[/b], sizeof([b]NpcData[/b]) );
		inFile.close();
	}

	[b]return object;[/b]
}

This is not allowed by the engine, since my custom class is not a standard torque data type. Is there another way to do this problerly? The only work around I can think of at this time is to return each member of that class as a string, or array or strings. But that would take forever to implement (over 50 members), and a pain if I ever add or remove members from this class.

Any help would be HUGELY appreciated!

Thanks all,
-Dante

About the author

I am a Producer in the Video Game industry and specialize in MMO development, Character Art->Game pipelines, and general support programming.


#1
11/29/2008 (11:17 am)
AND I figured this out on my own.

When dealing with ConsoleMethod in the engine, 'object' is the same thing as a 'this' pointer to the object calling the function. So there is no reason to return object, the pointer can directly manipulate the instanced class object. Now to just stop using the STL and figure Torque's built in file functions...

Also in case anyone is curious by chance, I did not have any luck saving a whole class in binary and loading. But I am able to do this with Structs just fine, and it is better anyway b/c it only saves relevant data.

Correct code:

ConsoleMethod( NpcData, load, void, 3, 3, "( char* NpcName )"
				  "Loads binary NpcData into a temporary class and returns the class")
{
	char loadFileName[30];
	std::strcat(loadFileName, argv[2]);
	std::strcat(loadFileName, ".npcData");

	std::ifstream inFile(loadFileName, std::ios_base::binary);

	if (inFile)
	{
		inFile.read( (char*)[b]object->theStruct[/b], sizeof([b]NpcData::MyStructDefinition[/b]) );
		inFile.close();
	}
}
#2
11/29/2008 (12:57 pm)
Kudos on solving the problem. Very informative question and answer.
#3
11/29/2008 (1:24 pm)
Thanks Michael. Would you guys mind adding that info about the 'object' pointer to the documentation? Would be a good add in my opinion.

Take care,
Dante
#4
11/29/2008 (1:26 pm)
@Dante Falcone - Sure thing. I'll include it in the System Overview section of the Console section.