diff --git a/Engine/source/app/auth.h b/Engine/source/app/auth.h index 2eb76c1924..708478eece 100644 --- a/Engine/source/app/auth.h +++ b/Engine/source/app/auth.h @@ -32,7 +32,8 @@ class Auth2Certificate /// Formerly contained data indicating whether a user is valid. struct AuthInfo { - enum { + enum + { MaxNameLen = 31, }; diff --git a/Engine/source/app/badWordFilter.cpp b/Engine/source/app/badWordFilter.cpp index 2983a8bb5d..9905cfadd0 100644 --- a/Engine/source/app/badWordFilter.cpp +++ b/Engine/source/app/badWordFilter.cpp @@ -30,15 +30,15 @@ MODULE_BEGIN( BadWordFilter ) - MODULE_INIT - { - BadWordFilter::create(); - } - - MODULE_SHUTDOWN - { - BadWordFilter::destroy(); - } +MODULE_INIT +{ + BadWordFilter::create(); +} + +MODULE_SHUTDOWN +{ + BadWordFilter::destroy(); +} MODULE_END; @@ -63,9 +63,9 @@ BadWordFilter::~BadWordFilter() void BadWordFilter::create() { - Con::addVariable("pref::enableBadWordFilter", TypeBool, &filteringEnabled, - "@brief If true, the bad word filter will be enabled.\n\n" - "@ingroup Game"); + Con::addVariable("pref::enableBadWordFilter", TypeBool, &filteringEnabled, + "@brief If true, the bad word filter will be enabled.\n\n" + "@ingroup Game"); gBadWordFilter = new BadWordFilter; gBadWordFilter->addBadWord("shit"); gBadWordFilter->addBadWord("fuck"); @@ -229,55 +229,55 @@ bool BadWordFilter::containsBadWords(const char *cstring) } DefineEngineFunction(addBadWord, bool, (const char* badWord),, - "@brief Add a string to the bad word filter\n\n" + "@brief Add a string to the bad word filter\n\n" - "The bad word filter is a table containing words which will not be " - "displayed in chat windows. Instead, a designated replacement string will be displayed. " - "There are already a number of bad words automatically defined.\n\n" + "The bad word filter is a table containing words which will not be " + "displayed in chat windows. Instead, a designated replacement string will be displayed. " + "There are already a number of bad words automatically defined.\n\n" - "@param badWord Exact text of the word to restrict.\n" - "@return True if word was successfully added, false if the word or a subset of it already exists in the table\n" + "@param badWord Exact text of the word to restrict.\n" + "@return True if word was successfully added, false if the word or a subset of it already exists in the table\n" - "@see filterString()\n\n" + "@see filterString()\n\n" - "@tsexample\n" - "// In this game, \"Foobar\" is banned\n" - "%badWord = \"Foobar\";\n\n" - "// Returns true, word was successfully added\n" - "addBadWord(%badWord);\n\n" - "// Returns false, word has already been added\n" - "addBadWord(\"Foobar\");" - "@endtsexample\n" + "@tsexample\n" + "// In this game, \"Foobar\" is banned\n" + "%badWord = \"Foobar\";\n\n" + "// Returns true, word was successfully added\n" + "addBadWord(%badWord);\n\n" + "// Returns false, word has already been added\n" + "addBadWord(\"Foobar\");" + "@endtsexample\n" - "@ingroup Game") + "@ingroup Game") { return gBadWordFilter->addBadWord(badWord); } DefineEngineFunction(filterString, const char *, (const char* baseString, const char* replacementChars), (nullAsType(), nullAsType()), - "@brief Replaces the characters in a string with designated text\n\n" + "@brief Replaces the characters in a string with designated text\n\n" - "Uses the bad word filter to determine which characters within the string will be replaced.\n\n" + "Uses the bad word filter to determine which characters within the string will be replaced.\n\n" - "@param baseString The original string to filter.\n" - "@param replacementChars A string containing letters you wish to swap in the baseString.\n" - "@return The new scrambled string \n" + "@param baseString The original string to filter.\n" + "@param replacementChars A string containing letters you wish to swap in the baseString.\n" + "@return The new scrambled string \n" - "@see addBadWord()\n" - "@see containsBadWords()\n" + "@see addBadWord()\n" + "@see containsBadWords()\n" - "@tsexample\n" - "// Create the base string, can come from anywhere\n" - "%baseString = \"Foobar\";\n\n" - "// Create a string of random letters\n" - "%replacementChars = \"knqwrtlzs\";\n\n" - "// Filter the string\n" - "%newString = filterString(%baseString, %replacementChars);\n\n" - "// Print the new string to console\n" - "echo(%newString);" - "@endtsexample\n" + "@tsexample\n" + "// Create the base string, can come from anywhere\n" + "%baseString = \"Foobar\";\n\n" + "// Create a string of random letters\n" + "%replacementChars = \"knqwrtlzs\";\n\n" + "// Filter the string\n" + "%newString = filterString(%baseString, %replacementChars);\n\n" + "// Print the new string to console\n" + "echo(%newString);" + "@endtsexample\n" - "@ingroup Game") + "@ingroup Game") { const char *replaceStr = NULL; @@ -294,39 +294,39 @@ DefineEngineFunction(filterString, const char *, (const char* baseString, const } DefineEngineFunction(containsBadWords, bool, (const char* text),, - "@brief Checks to see if text is a bad word\n\n" - - "The text is considered to be a bad word if it has been added to the bad word filter.\n\n" - - "@param text Text to scan for bad words\n" - "@return True if the text has bad word(s), false if it is clean\n" - - "@see addBadWord()\n" - "@see filterString()\n" - - "@tsexample\n" - "// In this game, \"Foobar\" is banned\n" - "%badWord = \"Foobar\";\n\n" - "// Add a banned word to the bad word filter\n" - "addBadWord(%badWord);\n\n" - "// Create the base string, can come from anywhere like user chat\n" - "%userText = \"Foobar\";\n\n" - "// Create a string of random letters\n" - "%replacementChars = \"knqwrtlzs\";\n\n" - "// If the text contains a bad word, filter it before printing\n" - "// Otherwise print the original text\n" - "if(containsBadWords(%userText))\n" - "{\n" - " // Filter the string\n" - " %filteredText = filterString(%userText, %replacementChars);\n\n" - " // Print filtered text\n" - " echo(%filteredText);\n" - "}\n" - "else\n" - " echo(%userText);\n\n" - "@endtsexample\n" - - "@ingroup Game") + "@brief Checks to see if text is a bad word\n\n" + + "The text is considered to be a bad word if it has been added to the bad word filter.\n\n" + + "@param text Text to scan for bad words\n" + "@return True if the text has bad word(s), false if it is clean\n" + + "@see addBadWord()\n" + "@see filterString()\n" + + "@tsexample\n" + "// In this game, \"Foobar\" is banned\n" + "%badWord = \"Foobar\";\n\n" + "// Add a banned word to the bad word filter\n" + "addBadWord(%badWord);\n\n" + "// Create the base string, can come from anywhere like user chat\n" + "%userText = \"Foobar\";\n\n" + "// Create a string of random letters\n" + "%replacementChars = \"knqwrtlzs\";\n\n" + "// If the text contains a bad word, filter it before printing\n" + "// Otherwise print the original text\n" + "if(containsBadWords(%userText))\n" + "{\n" + " // Filter the string\n" + " %filteredText = filterString(%userText, %replacementChars);\n\n" + " // Print filtered text\n" + " echo(%filteredText);\n" + "}\n" + "else\n" + " echo(%userText);\n\n" + "@endtsexample\n" + + "@ingroup Game") { return gBadWordFilter->containsBadWords(text); } diff --git a/Engine/source/app/badWordFilter.h b/Engine/source/app/badWordFilter.h index 439cd9a3eb..bd17b17553 100644 --- a/Engine/source/app/badWordFilter.h +++ b/Engine/source/app/badWordFilter.h @@ -35,7 +35,8 @@ class BadWordFilter friend struct FilterTable; Vector filterTables; - enum { + enum + { TerminateNotFound = 0xFFFE, TerminateFound = 0xFFFF, MaxBadwordLength = 32, @@ -52,12 +53,21 @@ class BadWordFilter public: bool addBadWord(const char *word); bool setDefaultReplaceStr(const char *str); - const char* getDefaultReplaceStr(){ return defaultReplaceStr; } + const char* getDefaultReplaceStr() + { + return defaultReplaceStr; + } void filterString(char *string, const char *replaceStr = NULL); bool containsBadWords(const char *string); - static bool isEnabled() { return filteringEnabled; } - static void setEnabled(bool enable) { filteringEnabled = enable; } + static bool isEnabled() + { + return filteringEnabled; + } + static void setEnabled(bool enable) + { + filteringEnabled = enable; + } static void create(); static void destroy(); }; diff --git a/Engine/source/app/banList.cpp b/Engine/source/app/banList.cpp index 4e7de54a24..44ac30c6fd 100644 --- a/Engine/source/app/banList.cpp +++ b/Engine/source/app/banList.cpp @@ -44,14 +44,14 @@ ConsoleDoc( BanList* BanList::smInstance; MODULE_BEGIN( BanList ) - MODULE_INIT - { - new BanList; - } - MODULE_SHUTDOWN - { - delete BanList::instance(); - } +MODULE_INIT +{ + new BanList; +} +MODULE_SHUTDOWN +{ + delete BanList::instance(); +} MODULE_END; @@ -61,7 +61,7 @@ BanList::BanList() { AssertFatal( !smInstance, "BanList::BanList - already instantiated" ); VECTOR_SET_ASSOCIATION( list ); - + smInstance = this; } @@ -76,7 +76,7 @@ void BanList::addBan(S32 uniqueId, const char *TA, S32 banTime) // make sure this bastard isn't already banned on this server Vector::iterator i; - for(i = list.begin();i != list.end();i++) + for(i = list.begin(); i != list.end(); i++) { if(uniqueId == i->uniqueId) { @@ -120,7 +120,7 @@ void BanList::addBanRelative(S32 uniqueId, const char *TA, S32 numSeconds) void BanList::removeBan(S32 uniqueId, const char *) { Vector::iterator i; - for(i = list.begin();i != list.end();i++) + for(i = list.begin(); i != list.end(); i++) { if(uniqueId == i->uniqueId) { @@ -137,7 +137,7 @@ bool BanList::isBanned(S32 uniqueId, const char *) S32 curTime = Platform::getTime(); Vector::iterator i; - for(i = list.begin();i != list.end();) + for(i = list.begin(); i != list.end();) { if(i->bannedUntil != 0 && i->bannedUntil < curTime) { @@ -199,24 +199,24 @@ void BanList::exportToFile(const char *name) //----------------------------------------------------------------------------- DefineEngineStaticMethod( BanList, addAbsolute, void, ( S32 uniqueId, const char* transportAddress, S32 banTime ),, - "Ban a user until a given time.\n\n" - "@param uniqueId Unique ID of the player.\n" - "@param transportAddress Address from which the player connected.\n" - "@param banTime Time at which they will be allowed back in." - "@tsexample\n" - "// Kick someone off the server\n" - "// %client - This is the connection to the person we are kicking\n" - "function kick(%client)\n" - "{\n" - " // Let the server know what happened\n" - " messageAll( 'MsgAdminForce', '\\c2The Admin has kicked %1.', %client.playerName);\n\n" - " // If it is not an AI Player, execute the ban.\n" - " if (!%client.isAIControlled())\n" - " BanList::addAbsolute(%client.guid, %client.getAddress(), $pref::Server::KickBanTime);\n\n" - " // Let the player know they messed up\n" - " %client.delete(\"You have been kicked from this server\");\n" - "}\n" - "@endtsexample\n\n") + "Ban a user until a given time.\n\n" + "@param uniqueId Unique ID of the player.\n" + "@param transportAddress Address from which the player connected.\n" + "@param banTime Time at which they will be allowed back in." + "@tsexample\n" + "// Kick someone off the server\n" + "// %client - This is the connection to the person we are kicking\n" + "function kick(%client)\n" + "{\n" + " // Let the server know what happened\n" + " messageAll( 'MsgAdminForce', '\\c2The Admin has kicked %1.', %client.playerName);\n\n" + " // If it is not an AI Player, execute the ban.\n" + " if (!%client.isAIControlled())\n" + " BanList::addAbsolute(%client.guid, %client.getAddress(), $pref::Server::KickBanTime);\n\n" + " // Let the player know they messed up\n" + " %client.delete(\"You have been kicked from this server\");\n" + "}\n" + "@endtsexample\n\n") { BanList::instance()->addBan( uniqueId, transportAddress, banTime ); } @@ -224,24 +224,24 @@ DefineEngineStaticMethod( BanList, addAbsolute, void, ( S32 uniqueId, const char //----------------------------------------------------------------------------- DefineEngineStaticMethod( BanList, add, void, ( S32 uniqueId, const char* transportAddress, S32 banLength ),, - "Ban a user for banLength seconds.\n\n" - "@param uniqueId Unique ID of the player.\n" - "@param transportAddress Address from which the player connected.\n" - "@param banLength Time period over which to ban the player." - "@tsexample\n" - "// Kick someone off the server\n" - "// %client - This is the connection to the person we are kicking\n" - "function kick(%client)\n" - "{\n" - " // Let the server know what happened\n" - " messageAll( 'MsgAdminForce', '\\c2The Admin has kicked %1.', %client.playerName);\n\n" - " // If it is not an AI Player, execute the ban.\n" - " if (!%client.isAIControlled())\n" - " BanList::add(%client.guid, %client.getAddress(), $pref::Server::KickBanTime);\n\n" - " // Let the player know they messed up\n" - " %client.delete(\"You have been kicked from this server\");\n" - "}\n" - "@endtsexample\n\n") + "Ban a user for banLength seconds.\n\n" + "@param uniqueId Unique ID of the player.\n" + "@param transportAddress Address from which the player connected.\n" + "@param banLength Time period over which to ban the player." + "@tsexample\n" + "// Kick someone off the server\n" + "// %client - This is the connection to the person we are kicking\n" + "function kick(%client)\n" + "{\n" + " // Let the server know what happened\n" + " messageAll( 'MsgAdminForce', '\\c2The Admin has kicked %1.', %client.playerName);\n\n" + " // If it is not an AI Player, execute the ban.\n" + " if (!%client.isAIControlled())\n" + " BanList::add(%client.guid, %client.getAddress(), $pref::Server::KickBanTime);\n\n" + " // Let the player know they messed up\n" + " %client.delete(\"You have been kicked from this server\");\n" + "}\n" + "@endtsexample\n\n") { BanList::instance()->addBanRelative( uniqueId, transportAddress, banLength ); } @@ -249,12 +249,12 @@ DefineEngineStaticMethod( BanList, add, void, ( S32 uniqueId, const char* transp //----------------------------------------------------------------------------- DefineEngineStaticMethod( BanList, removeBan, void, ( S32 uniqueId, const char* transportAddress ),, - "Unban someone.\n\n" - "@param uniqueId Unique ID of the player.\n" - "@param transportAddress Address from which the player connected.\n" - "@tsexample\n" - "BanList::removeBan(%userID, %ipAddress);\n" - "@endtsexample\n\n") + "Unban someone.\n\n" + "@param uniqueId Unique ID of the player.\n" + "@param transportAddress Address from which the player connected.\n" + "@tsexample\n" + "BanList::removeBan(%userID, %ipAddress);\n" + "@endtsexample\n\n") { BanList::instance()->removeBan( uniqueId, transportAddress ); } @@ -262,28 +262,28 @@ DefineEngineStaticMethod( BanList, removeBan, void, ( S32 uniqueId, const char* //----------------------------------------------------------------------------- DefineEngineStaticMethod( BanList, isBanned, bool, ( S32 uniqueId, const char* transportAddress ),, - "Is someone banned?\n\n" - "@param uniqueId Unique ID of the player.\n" - "@param transportAddress Address from which the player connected.\n\n" - "@tsexample\n" - "//-----------------------------------------------------------------------------\n" - "// This script function is called before a client connection\n" - "// is accepted. Returning "" will accept the connection,\n" - "// anything else will be sent back as an error to the client.\n" - "// All the connect args are passed also to onConnectRequest\n" - "function GameConnection::onConnectRequest( %client, %netAddress, %name )\n" - "{\n" - " // Find out who is trying to connect\n" - " echo(\"Connect request from: \" @ %netAddress);\n\n" - " // Are they allowed in?\n" - " if(BanList::isBanned(%client.guid, %netAddress))\n" - " return \"CR_YOUAREBANNED\";\n\n" - " // Is there room for an unbanned player?\n" - " if($Server::PlayerCount >= $pref::Server::MaxPlayers)\n" - " return \"CR_SERVERFULL\";\n" - " return "";\n" - "}\n" - "@endtsexample\n\n") + "Is someone banned?\n\n" + "@param uniqueId Unique ID of the player.\n" + "@param transportAddress Address from which the player connected.\n\n" + "@tsexample\n" + "//-----------------------------------------------------------------------------\n" + "// This script function is called before a client connection\n" + "// is accepted. Returning "" will accept the connection,\n" + "// anything else will be sent back as an error to the client.\n" + "// All the connect args are passed also to onConnectRequest\n" + "function GameConnection::onConnectRequest( %client, %netAddress, %name )\n" + "{\n" + " // Find out who is trying to connect\n" + " echo(\"Connect request from: \" @ %netAddress);\n\n" + " // Are they allowed in?\n" + " if(BanList::isBanned(%client.guid, %netAddress))\n" + " return \"CR_YOUAREBANNED\";\n\n" + " // Is there room for an unbanned player?\n" + " if($Server::PlayerCount >= $pref::Server::MaxPlayers)\n" + " return \"CR_SERVERFULL\";\n" + " return "";\n" + "}\n" + "@endtsexample\n\n") { return BanList::instance()->isBanned( uniqueId, transportAddress ); } @@ -291,11 +291,11 @@ DefineEngineStaticMethod( BanList, isBanned, bool, ( S32 uniqueId, const char* t //----------------------------------------------------------------------------- DefineEngineStaticMethod( BanList, export, void, ( const char* filename ),, - "Dump the banlist to a file.\n\n" - "@param filename Path of the file to write the list to.\n\n" - "@tsexample\n" - "BanList::Export(\"./server/banlist.cs\");\n" - "@endtsexample\n\n") + "Dump the banlist to a file.\n\n" + "@param filename Path of the file to write the list to.\n\n" + "@tsexample\n" + "BanList::Export(\"./server/banlist.cs\");\n" + "@endtsexample\n\n") { BanList::instance()->exportToFile( filename ); } diff --git a/Engine/source/app/banList.h b/Engine/source/app/banList.h index 35d8881148..196c15cd58 100644 --- a/Engine/source/app/banList.h +++ b/Engine/source/app/banList.h @@ -24,44 +24,47 @@ #define _BANLIST_H_ #ifndef _ENGINEAPI_H_ - #include "console/engineAPI.h" +#include "console/engineAPI.h" #endif #ifndef _TVECTOR_H_ - #include "core/util/tVector.h" +#include "core/util/tVector.h" #endif /// Helper class to keep track of bans. class BanList { - public: - - DECLARE_STATIC_CLASS( BanList ); - - struct BanInfo - { - S32 uniqueId; - char transportAddress[128]; - S32 bannedUntil; - }; - - protected: +public: - Vector< BanInfo > list; - - static BanList* smInstance; + DECLARE_STATIC_CLASS( BanList ); - public: + struct BanInfo + { + S32 uniqueId; + char transportAddress[128]; + S32 bannedUntil; + }; - BanList(); - - static BanList* instance() { return smInstance; } +protected: - void addBan(S32 uniqueId, const char *TA, S32 banTime); - void addBanRelative(S32 uniqueId, const char *TA, S32 numSeconds); - void removeBan(S32 uniqueId, const char *TA); - bool isBanned(S32 uniqueId, const char *TA); - bool isTAEq(const char *bannedTA, const char *TA); - void exportToFile(const char *fileName); + Vector< BanInfo > list; + + static BanList* smInstance; + +public: + + BanList(); + + static BanList* instance() + { + return smInstance; + } + + void addBan(S32 uniqueId, const char *TA, S32 banTime); + void addBanRelative(S32 uniqueId, const char *TA, S32 numSeconds); + void removeBan(S32 uniqueId, const char *TA); + bool isBanned(S32 uniqueId, const char *TA); + bool isTAEq(const char *bannedTA, const char *TA); + void exportToFile(const char *fileName); }; #endif diff --git a/Engine/source/app/game.cpp b/Engine/source/app/game.cpp index 5878accd65..fdf022d8d8 100644 --- a/Engine/source/app/game.cpp +++ b/Engine/source/app/game.cpp @@ -67,21 +67,21 @@ bool gEditingMission = false; ConsoleFunctionGroupBegin( InputManagement, "Functions that let you deal with input from scripts" ); -DefineEngineFunction( deactivateDirectInput, void, (), , - "()" - "@brief Disables DirectInput.\n\n" - "Also deactivates any connected joysticks.\n\n" - "@ingroup Input" ) +DefineEngineFunction( deactivateDirectInput, void, (),, + "()" + "@brief Disables DirectInput.\n\n" + "Also deactivates any connected joysticks.\n\n" + "@ingroup Input" ) { if ( Input::isActive() ) Input::deactivate(); } -DefineEngineFunction( activateDirectInput, void, (), , - "()" - "@brief Activates DirectInput.\n\n" - "Also activates any connected joysticks." - "@ingroup Input") +DefineEngineFunction( activateDirectInput, void, (),, + "()" + "@brief Activates DirectInput.\n\n" + "Also activates any connected joysticks." + "@ingroup Input") { if ( !Input::isActive() ) Input::activate(); @@ -91,10 +91,10 @@ ConsoleFunctionGroupEnd( InputManagement ); //-------------------------------------------------------------------------- static const U32 MaxPlayerNameLength = 16; -DefineEngineFunction( strToPlayerName, const char*, (const char* ptr ), , "strToPlayerName(string);" ) +DefineEngineFunction( strToPlayerName, const char*, (const char* ptr ),, "strToPlayerName(string);" ) { - // Strip leading spaces and underscores: + // Strip leading spaces and underscores: while ( *ptr == ' ' || *ptr == '_' ) ptr++; @@ -138,90 +138,90 @@ DefineEngineFunction( strToPlayerName, const char*, (const char* ptr ), , "strTo } *rptr = '\0'; - //finally, strip out the ML text control chars... - return GuiMLTextCtrl::stripControlChars(ret); + //finally, strip out the ML text control chars... + return GuiMLTextCtrl::stripControlChars(ret); } - return( "" ); + return( "" ); } -ConsoleFunctionGroupBegin( Platform , "General platform functions."); +ConsoleFunctionGroupBegin( Platform, "General platform functions."); -DefineEngineFunction( lockMouse, void, (bool isLocked ), , "(bool isLocked)" - "@brief Lock or unlock the mouse to the window.\n\n" - "When true, prevents the mouse from leaving the bounds of the game window.\n\n" - "@ingroup Input") +DefineEngineFunction( lockMouse, void, (bool isLocked ),, "(bool isLocked)" + "@brief Lock or unlock the mouse to the window.\n\n" + "When true, prevents the mouse from leaving the bounds of the game window.\n\n" + "@ingroup Input") { Platform::setWindowLocked(isLocked); } DefineEngineFunction( setNetPort, bool, (int port, bool bind), (true), "(int port, bool bind=true)" - "@brief Set the network port for the game to use.\n\n" + "@brief Set the network port for the game to use.\n\n" - "@param port The port to use.\n" - "@param bind True if bind() should be called on the port.\n" + "@param port The port to use.\n" + "@param bind True if bind() should be called on the port.\n" - "@returns True if the port was successfully opened.\n" + "@returns True if the port was successfully opened.\n" - "This will trigger a windows firewall prompt. " - "If you don't have firewall tunneling tech you can set this to false to avoid the prompt.\n\n" - "@ingroup Networking") + "This will trigger a windows firewall prompt. " + "If you don't have firewall tunneling tech you can set this to false to avoid the prompt.\n\n" + "@ingroup Networking") { return Net::openPort((S32)port, bind); } -DefineEngineFunction(isAddressTypeAvailable, bool, (int addressType), , "(protocol id)" - "@brief Determines if a specified address type can be reached.\n\n" - "@ingroup Networking") +DefineEngineFunction(isAddressTypeAvailable, bool, (int addressType),, "(protocol id)" + "@brief Determines if a specified address type can be reached.\n\n" + "@ingroup Networking") { - return Net::isAddressTypeAvailable((NetAddress::Type)addressType); + return Net::isAddressTypeAvailable((NetAddress::Type)addressType); } -DefineEngineFunction( closeNetPort, void, (), , "()" - "@brief Closes the current network port\n\n" - "@ingroup Networking") +DefineEngineFunction( closeNetPort, void, (),, "()" + "@brief Closes the current network port\n\n" + "@ingroup Networking") { Net::closePort(); } -DefineEngineFunction( saveJournal, void, (const char * filename), , "(string filename)" - "Save the journal to the specified file.\n\n" - "@ingroup Platform") +DefineEngineFunction( saveJournal, void, (const char * filename),, "(string filename)" + "Save the journal to the specified file.\n\n" + "@ingroup Platform") { Journal::Record(filename); } -DefineEngineFunction( playJournal, void, (const char * filename), , "(string filename)" - "@brief Begin playback of a journal from a specified field.\n\n" - "@param filename Name and path of file journal file\n" - "@ingroup Platform") +DefineEngineFunction( playJournal, void, (const char * filename),, "(string filename)" + "@brief Begin playback of a journal from a specified field.\n\n" + "@param filename Name and path of file journal file\n" + "@ingroup Platform") { // CodeReview - BJG 4/24/2007 - The break flag needs to be wired back in. // bool jBreak = (argc > 2)? dAtob(argv[2]): false; Journal::Play(filename); } -DefineEngineFunction( getSimTime, S32, (), , "()" - "Return the current sim time in milliseconds.\n\n" - "@brief Sim time is time since the game started.\n\n" - "@ingroup Platform") +DefineEngineFunction( getSimTime, S32, (),, "()" + "Return the current sim time in milliseconds.\n\n" + "@brief Sim time is time since the game started.\n\n" + "@ingroup Platform") { return Sim::getCurrentTime(); } -DefineEngineFunction( getRealTime, S32, (), , "()" - "@brief Return the current real time in milliseconds.\n\n" - "Real time is platform defined; typically time since the computer booted.\n\n" - "@ingroup Platform") +DefineEngineFunction( getRealTime, S32, (),, "()" + "@brief Return the current real time in milliseconds.\n\n" + "Real time is platform defined; typically time since the computer booted.\n\n" + "@ingroup Platform") { return Platform::getRealMilliseconds(); } DefineEngineFunction(getLocalTime, const char*, (),, - "@brief Return the current local time as: weekday month day year hour min sec.\n\n" - "Local time is platform defined." - "@ingroup Platform") + "@brief Return the current local time as: weekday month day year hour min sec.\n\n" + "Local time is platform defined." + "@ingroup Platform") { Platform::LocalTime lt; Platform::getLocalTime(lt); @@ -229,13 +229,13 @@ DefineEngineFunction(getLocalTime, const char*, (),, static const U32 bufSize = 128; char *retBuffer = Con::getReturnBuffer(bufSize); dSprintf(retBuffer, bufSize, "%d %d %d %d %02d %02d %02d", - lt.weekday, - lt.month + 1, - lt.monthday, - lt.year + 1900, - lt.hour, - lt.min, - lt.sec); + lt.weekday, + lt.month + 1, + lt.monthday, + lt.year + 1900, + lt.hour, + lt.min, + lt.sec); return retBuffer; } @@ -256,7 +256,7 @@ bool clientProcess(U32 timeDelta) #ifndef TORQUE_TGB_ONLY ret = ClientProcessList::get()->advanceTime(timeDelta); #else - ret = gt2dNetworkClientProcess.advanceTime( timeDelta ); + ret = gt2dNetworkClientProcess.advanceTime( timeDelta ); #endif ITickable::advanceTime(timeDelta); @@ -265,16 +265,16 @@ bool clientProcess(U32 timeDelta) // Determine if we're lagging GameConnection* connection = GameConnection::getConnectionToServer(); if(connection) - { + { connection->detectLag(); - } + } #else // Determine if we're lagging t2dGameConnection* connection = t2dGameConnection::getConnectionToServer(); if(connection) - { + { connection->detectLag(); - } + } #endif // Let SFX process. diff --git a/Engine/source/app/mainLoop.cpp b/Engine/source/app/mainLoop.cpp index ea2322d81e..4c1f0de74a 100644 --- a/Engine/source/app/mainLoop.cpp +++ b/Engine/source/app/mainLoop.cpp @@ -105,12 +105,12 @@ StringTableEntry gMiniDumpExecDir; namespace engineAPI { - // This is the magic switch for deciding which interop the engine - // should use. It will go away when we drop the console system - // entirely but for now it is necessary for several behaviors that - // differ between the interops to decide what to do. +// This is the magic switch for deciding which interop the engine +// should use. It will go away when we drop the console system +// entirely but for now it is necessary for several behaviors that +// differ between the interops to decide what to do. bool gUseConsoleInterop = true; - + bool gIsInitialized = false; } @@ -121,20 +121,20 @@ namespace engineAPI #if defined( TORQUE_DEBUG ) && !defined( TORQUE_DISABLE_MEMORY_MANAGER ) - #ifdef TORQUE_COMPILER_VISUALC - # pragma data_seg( ".CRT$XTU" ) - - static void* sCheckMemBeforeTermination = &Memory::ensureAllFreed; - - # pragma data_seg() - #elif defined( TORQUE_COMPILER_GCC ) - - __attribute__ ( ( destructor ) ) static void _ensureAllFreed() - { - Memory::ensureAllFreed(); - } - - #endif +#ifdef TORQUE_COMPILER_VISUALC +# pragma data_seg( ".CRT$XTU" ) + +static void* sCheckMemBeforeTermination = &Memory::ensureAllFreed; + +# pragma data_seg() +#elif defined( TORQUE_COMPILER_GCC ) + +__attribute__ ( ( destructor ) ) static void _ensureAllFreed() +{ + Memory::ensureAllFreed(); +} + +#endif #endif @@ -145,21 +145,21 @@ void processTimeEvent(S32 elapsedTime) // If recording a video and not playinb back a journal, override the elapsedTime if (VIDCAP->isRecording() && !Journal::IsPlaying()) - elapsedTime = VIDCAP->getMsPerFrame(); - + elapsedTime = VIDCAP->getMsPerFrame(); + // cap the elapsed time to one second // if it's more than that we're probably in a bad catch-up situation if(elapsedTime > 1024) elapsedTime = 1024; - + U32 timeDelta; if(ATTS(gTimeAdvance)) timeDelta = ATTS(gTimeAdvance); else timeDelta = (U32) (elapsedTime * ATTS(gTimeScale)); - + Platform::advanceTime(elapsedTime); - + // Don't build up more time than a single tick... this makes the sim // frame rate dependent but is a useful hack for singleplayer. if ( ATTS(gFrameSkip) ) @@ -167,11 +167,11 @@ void processTimeEvent(S32 elapsedTime) timeDelta = TickMs; bool tickPass; - + PROFILE_START(ServerProcess); tickPass = serverProcess(timeDelta); PROFILE_END(); - + PROFILE_START(ServerNetProcess); // only send packets if a tick happened if(tickPass) @@ -180,24 +180,24 @@ void processTimeEvent(S32 elapsedTime) Con::setBoolVariable( "$pref::hasServerTicked", tickPass ); PROFILE_END(); - + PROFILE_START(SimAdvanceTime); Sim::advanceTime(timeDelta); PROFILE_END(); - + PROFILE_START(ClientProcess); tickPass = clientProcess(timeDelta); // Used to indicate if client was just ticked. Con::setBoolVariable( "$pref::hasClientTicked", tickPass ); PROFILE_END_NAMED(ClientProcess); - + PROFILE_START(ClientNetProcess); if(tickPass) GNet->processClient(); PROFILE_END(); - + GNet->checkTimeouts(); - + gFPS.update(); // Give the texture manager a chance to cleanup any @@ -206,26 +206,26 @@ void processTimeEvent(S32 elapsedTime) TEXMGR->cleanupCache( 5 ); PROFILE_END(); - + // Update the console time Con::setFloatVariable("Sim::Time",F32(Platform::getVirtualMilliseconds()) / 1000); } void StandardMainLoop::init() { - #ifdef TORQUE_DEBUG +#ifdef TORQUE_DEBUG gStartupTimer = PlatformTimer::create(); - #endif - - #ifdef TORQUE_DEBUG_GUARD - Memory::flagCurrentAllocs( Memory::FLAG_Global ); - #endif +#endif + +#ifdef TORQUE_DEBUG_GUARD + Memory::flagCurrentAllocs( Memory::FLAG_Global ); +#endif Platform::setMathControlStateKnown(); - + // Asserts should be created FIRST PlatformAssert::create(); - + ManagedSingleton< ThreadManager >::createSingleton(); FrameAllocator::init(TORQUE_FRAME_SIZE); // See comments in torqueConfig.h @@ -265,16 +265,16 @@ void StandardMainLoop::init() Platform::init(); // platform specific initialization RedBook::init(); Platform::initConsole(); - + ThreadPool::GlobalThreadPool::createSingleton(); // Set engineAPI initialized to true engineAPI::gIsInitialized = true; // Initialize modules. - + EngineModuleManager::initializeSystem(); - + // Initialise ITickable. #ifdef TORQUE_TGB_ONLY ITickable::init( 4 ); @@ -287,22 +287,22 @@ void StandardMainLoop::init() #endif Con::addVariable("timeScale", TypeF32, &ATTS(gTimeScale), "Animation time scale.\n" - "@ingroup platform"); + "@ingroup platform"); Con::addVariable("timeAdvance", TypeS32, &ATTS(gTimeAdvance), "The speed at which system processing time advances.\n" - "@ingroup platform"); + "@ingroup platform"); Con::addVariable("frameSkip", TypeS32, &ATTS(gFrameSkip), "Sets the number of frames to skip while rendering the scene.\n" - "@ingroup platform"); + "@ingroup platform"); Con::setVariable( "defaultGame", StringTable->insert("scripts") ); Con::addVariable( "_forceAllMainThread", TypeBool, &ThreadPool::getForceAllMainThread(), "Force all work items to execute on main thread. turns this into a single-threaded system. Primarily useful to find whether malfunctions are caused by parallel execution or not.\n" - "@ingroup platform" ); + "@ingroup platform" ); #if defined( TORQUE_MINIDUMP ) && defined( TORQUE_RELEASE ) - Con::addVariable("MiniDump::Dir", TypeString, &gMiniDumpDir); - Con::addVariable("MiniDump::Exec", TypeString, &gMiniDumpExec); - Con::addVariable("MiniDump::Params", TypeString, &gMiniDumpParams); - Con::addVariable("MiniDump::ExecDir", TypeString, &gMiniDumpExecDir); + Con::addVariable("MiniDump::Dir", TypeString, &gMiniDumpDir); + Con::addVariable("MiniDump::Exec", TypeString, &gMiniDumpExec); + Con::addVariable("MiniDump::Params", TypeString, &gMiniDumpParams); + Con::addVariable("MiniDump::ExecDir", TypeString, &gMiniDumpExecDir); #endif // Register the module manager. @@ -313,15 +313,15 @@ void StandardMainLoop::init() // Register the asset database as a module listener. ModuleDatabase.addListener(&AssetDatabase); - + ActionMap* globalMap = new ActionMap; globalMap->registerObject("GlobalActionMap"); Sim::getActiveActionMapSet()->pushObject(globalMap); - + // Do this before we init the process so that process notifiees can get the time manager tm = new TimeManager; tm->timeEvent.notify(&::processTimeEvent); - + // Start up the Input Event Manager INPUTMGR->start(); @@ -330,9 +330,9 @@ void StandardMainLoop::init() // Hook in for UDP notification Net::getPacketReceiveEvent().notify(GNet, &NetInterface::processPacketReceiveEvent); - #ifdef TORQUE_DEBUG_GUARD - Memory::flagCurrentAllocs( Memory::FLAG_Static ); - #endif +#ifdef TORQUE_DEBUG_GUARD + Memory::flagCurrentAllocs( Memory::FLAG_Static ); +#endif } void StandardMainLoop::shutdown() @@ -348,11 +348,11 @@ void StandardMainLoop::shutdown() // Unregister the asset database. AssetDatabase.unregisterObject(); - + // Shut down modules. - + EngineModuleManager::shutdownSystem(); - + ThreadPool::GlobalThreadPool::deleteSingleton(); #ifdef TORQUE_ENABLE_VFS @@ -362,7 +362,7 @@ void StandardMainLoop::shutdown() RedBook::destroy(); Platform::shutdown(); - + #if defined( _XBOX ) || defined( TORQUE_OS_MAC ) DebugOutputConsumer::destroy(); #endif @@ -374,7 +374,7 @@ void StandardMainLoop::shutdown() FrameAllocator::destroy(); Net::shutdown(); Sampler::destroy(); - + ManagedSingleton< ThreadManager >::deleteSingleton(); // asserts should be destroyed LAST @@ -457,7 +457,7 @@ bool StandardMainLoop::handleCommandLine( S32 argc, const char **argv ) Stream *mainCsStream = NULL; // The working filestream. - FileStream str; + FileStream str; const char *defaultScriptName = "main.cs"; bool useDefaultScript = true; @@ -570,7 +570,7 @@ bool StandardMainLoop::handleCommandLine( S32 argc, const char **argv ) Platform::setMainDotCsDir(buffer); Platform::setCurrentDirectory(buffer); - Con::evaluate(script, false, useDefaultScript ? defaultScriptName : argv[1]); + Con::evaluate(script, false, useDefaultScript ? defaultScriptName : argv[1]); delete[] script; #ifdef TORQUE_ENABLE_VFS @@ -582,15 +582,15 @@ bool StandardMainLoop::handleCommandLine( S32 argc, const char **argv ) bool StandardMainLoop::doMainLoop() { - #ifdef TORQUE_DEBUG +#ifdef TORQUE_DEBUG if( gStartupTimer ) { Con::printf( "Started up in %.2f seconds...", - F32( gStartupTimer->getElapsedMs() ) / 1000.f ); + F32( gStartupTimer->getElapsedMs() ) / 1000.f ); SAFE_DELETE( gStartupTimer ); } - #endif - +#endif + bool keepRunning = true; // while(keepRunning) { @@ -612,11 +612,11 @@ bool StandardMainLoop::doMainLoop() #ifdef TORQUE_OS_MAC if (newFocus) WindowManager->getFirstWindow()->show(); - + #endif lastFocus = newFocus; } - + // under the web plugin do not sleep the process when the child window loses focus as this will cripple the browser perfomance if (!Platform::getWebDeployment()) tm->setBackground(!newFocus); @@ -627,7 +627,7 @@ bool StandardMainLoop::doMainLoop() { tm->setBackground(false); } - + PROFILE_START(MainLoop); Sampler::beginFrame(); @@ -638,7 +638,7 @@ bool StandardMainLoop::doMainLoop() Sampler::endFrame(); PROFILE_END_NAMED(MainLoop); } - + return keepRunning; } diff --git a/Engine/source/app/net/httpObject.cpp b/Engine/source/app/net/httpObject.cpp index b3d26b6f44..2d8f81a510 100644 --- a/Engine/source/app/net/httpObject.cpp +++ b/Engine/source/app/net/httpObject.cpp @@ -31,85 +31,85 @@ IMPLEMENT_CONOBJECT(HTTPObject); ConsoleDocClass( HTTPObject, - "@brief Allows communications between the game and a server using HTTP.\n\n" - - "HTTPObject is derrived from TCPObject and makes use of the same callbacks for dealing with " - "connections and received data. However, the way in which you use HTTPObject to connect " - "with a server is different than TCPObject. Rather than opening a connection, sending data, " - "waiting to receive data, and then closing the connection, you issue a get() or post() and " - "handle the response. The connection is automatically created and destroyed for you.\n\n" - - "@tsexample\n" - "// In this example we'll retrieve the weather in Las Vegas using\n" - "// Google's API. The response is in XML which could be processed\n" - "// and used by the game using SimXMLDocument, but we'll just output\n" - "// the results to the console in this example.\n\n" - - "// Define callbacks for our specific HTTPObject using our instance's\n" - "// name (WeatherFeed) as the namespace.\n\n" - - "// Handle an issue with resolving the server's name\n" - "function WeatherFeed::onDNSFailed(%this)\n" - "{\n" - " // Store this state\n" - " %this.lastState = \"DNSFailed\";\n\n" - - " // Handle DNS failure\n" - "}\n\n" - - "function WeatherFeed::onConnectFailed(%this)\n" - "{\n" - " // Store this state\n" - " %this.lastState = \"ConnectFailed\";\n\n" - " // Handle connection failure\n" - "}\n\n" - - "function WeatherFeed::onDNSResolved(%this)\n" - "{\n" - " // Store this state\n" - " %this.lastState = \"DNSResolved\";\n\n" - "}\n\n" - - "function WeatherFeed::onConnected(%this)\n" - "{\n" - " // Store this state\n" - " %this.lastState = \"Connected\";\n\n" - - " // Clear our buffer\n" - " %this.buffer = \"\";\n" - "}\n\n" - - "function WeatherFeed::onDisconnect(%this)\n" - "{\n" - " // Store this state\n" - " %this.lastState = \"Disconnected\";\n\n" - - " // Output the buffer to the console\n" - " echo(\"Google Weather Results:\");\n" - " echo(%this.buffer);\n" - "}\n\n" - - "// Handle a line from the server\n" - "function WeatherFeed::onLine(%this, %line)\n" - "{\n" - " // Store this line in out buffer\n" - " %this.buffer = %this.buffer @ %line;\n" - "}\n\n" - - "// Create the HTTPObject\n" - "%feed = new HTTPObject(WeatherFeed);\n\n" - - "// Define a dynamic field to store the last connection state\n" - "%feed.lastState = \"None\";\n\n" - - "// Send the GET command\n" - "%feed.get(\"www.google.com:80\", \"/ig/api\", \"weather=Las-Vegas,US\");\n" - "@endtsexample\n\n" - - "@see TCPObject\n" - - "@ingroup Networking\n" -); + "@brief Allows communications between the game and a server using HTTP.\n\n" + + "HTTPObject is derrived from TCPObject and makes use of the same callbacks for dealing with " + "connections and received data. However, the way in which you use HTTPObject to connect " + "with a server is different than TCPObject. Rather than opening a connection, sending data, " + "waiting to receive data, and then closing the connection, you issue a get() or post() and " + "handle the response. The connection is automatically created and destroyed for you.\n\n" + + "@tsexample\n" + "// In this example we'll retrieve the weather in Las Vegas using\n" + "// Google's API. The response is in XML which could be processed\n" + "// and used by the game using SimXMLDocument, but we'll just output\n" + "// the results to the console in this example.\n\n" + + "// Define callbacks for our specific HTTPObject using our instance's\n" + "// name (WeatherFeed) as the namespace.\n\n" + + "// Handle an issue with resolving the server's name\n" + "function WeatherFeed::onDNSFailed(%this)\n" + "{\n" + " // Store this state\n" + " %this.lastState = \"DNSFailed\";\n\n" + + " // Handle DNS failure\n" + "}\n\n" + + "function WeatherFeed::onConnectFailed(%this)\n" + "{\n" + " // Store this state\n" + " %this.lastState = \"ConnectFailed\";\n\n" + " // Handle connection failure\n" + "}\n\n" + + "function WeatherFeed::onDNSResolved(%this)\n" + "{\n" + " // Store this state\n" + " %this.lastState = \"DNSResolved\";\n\n" + "}\n\n" + + "function WeatherFeed::onConnected(%this)\n" + "{\n" + " // Store this state\n" + " %this.lastState = \"Connected\";\n\n" + + " // Clear our buffer\n" + " %this.buffer = \"\";\n" + "}\n\n" + + "function WeatherFeed::onDisconnect(%this)\n" + "{\n" + " // Store this state\n" + " %this.lastState = \"Disconnected\";\n\n" + + " // Output the buffer to the console\n" + " echo(\"Google Weather Results:\");\n" + " echo(%this.buffer);\n" + "}\n\n" + + "// Handle a line from the server\n" + "function WeatherFeed::onLine(%this, %line)\n" + "{\n" + " // Store this line in out buffer\n" + " %this.buffer = %this.buffer @ %line;\n" + "}\n\n" + + "// Create the HTTPObject\n" + "%feed = new HTTPObject(WeatherFeed);\n\n" + + "// Define a dynamic field to store the last connection state\n" + "%feed.lastState = \"None\";\n\n" + + "// Send the GET command\n" + "%feed.get(\"www.google.com:80\", \"/ig/api\", \"weather=Las-Vegas,US\");\n" + "@endtsexample\n\n" + + "@see TCPObject\n" + + "@ingroup Networking\n" + ); //-------------------------------------- @@ -225,9 +225,9 @@ void HTTPObject::expandPath(char *dest, const char *path, U32 destSize) U32 i; for(i = 0; i <= ' '; i++) asciiEscapeTable[i] = true; - for(;i <= 0x7F; i++) + for(; i <= 0x7F; i++) asciiEscapeTable[i] = false; - for(;i <= 0xFF; i++) + for(; i <= 0xFF; i++) asciiEscapeTable[i] = true; asciiEscapeTable[static_cast('\"')] = true; asciiEscapeTable[static_cast('_')] = true; @@ -286,7 +286,7 @@ void HTTPObject::onConnected() else { dSprintf(buffer, sizeof(buffer), "POST %s HTTP/1.1\r\nHost: %s\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: %i\r\n\r\n%s\r\n\r\n", - expPath, mHostName, dStrlen(mPost), mPost); + expPath, mHostName, dStrlen(mPost), mPost); } if(pt) @@ -419,56 +419,56 @@ U32 HTTPObject::onReceive(U8 *buffer, U32 bufferLen) //-------------------------------------- DefineEngineMethod( HTTPObject, get, void, ( const char* Address, const char* requirstURI, const char* query ), ( "" ), - "@brief Send a GET command to a server to send or retrieve data.\n\n" - - "@param Address HTTP web address to send this get call to. Be sure to include the port at the end (IE: \"www.garagegames.com:80\").\n" - "@param requirstURI Specific location on the server to access (IE: \"index.php\".)\n" - "@param query Optional. Actual data to transmit to the server. Can be anything required providing it sticks with limitations of the HTTP protocol. " - "If you were building the URL manually, this is the text that follows the question mark. For example: http://www.google.com/ig/api?weather=Las-Vegas,US\n" - - "@tsexample\n" - "// Create an HTTP object for communications\n" - "%httpObj = new HTTPObject();\n\n" - "// Specify a URL to transmit to\n" - "%url = \"www.garagegames.com:80\";\n\n" - "// Specify a URI to communicate with\n" - "%URI = \"/index.php\";\n\n" - "// Specify a query to send.\n" - "%query = \"\";\n\n" - "// Send the GET command to the server\n" - "%httpObj.get(%url,%URI,%query);\n" - "@endtsexample\n\n" - ) + "@brief Send a GET command to a server to send or retrieve data.\n\n" + + "@param Address HTTP web address to send this get call to. Be sure to include the port at the end (IE: \"www.garagegames.com:80\").\n" + "@param requirstURI Specific location on the server to access (IE: \"index.php\".)\n" + "@param query Optional. Actual data to transmit to the server. Can be anything required providing it sticks with limitations of the HTTP protocol. " + "If you were building the URL manually, this is the text that follows the question mark. For example: http://www.google.com/ig/api?weather=Las-Vegas,US\n" + + "@tsexample\n" + "// Create an HTTP object for communications\n" + "%httpObj = new HTTPObject();\n\n" + "// Specify a URL to transmit to\n" + "%url = \"www.garagegames.com:80\";\n\n" + "// Specify a URI to communicate with\n" + "%URI = \"/index.php\";\n\n" + "// Specify a query to send.\n" + "%query = \"\";\n\n" + "// Send the GET command to the server\n" + "%httpObj.get(%url,%URI,%query);\n" + "@endtsexample\n\n" + ) { if( !query || !query[ 0 ] ) - object->get(Address, requirstURI, NULL); + object->get(Address, requirstURI, NULL); else - object->get(Address, requirstURI, query); + object->get(Address, requirstURI, query); } DefineEngineMethod( HTTPObject, post, void, ( const char* Address, const char* requirstURI, const char* query, const char* post ),, - "@brief Send POST command to a server to send or retrieve data.\n\n" - - "@param Address HTTP web address to send this get call to. Be sure to include the port at the end (IE: \"www.garagegames.com:80\").\n" - "@param requirstURI Specific location on the server to access (IE: \"index.php\".)\n" - "@param query Actual data to transmit to the server. Can be anything required providing it sticks with limitations of the HTTP protocol. \n" - "@param post Submission data to be processed.\n" - - "@tsexample\n" - "// Create an HTTP object for communications\n" - "%httpObj = new HTTPObject();\n\n" - "// Specify a URL to transmit to\n" - "%url = \"www.garagegames.com:80\";\n\n" - "// Specify a URI to communicate with\n" - "%URI = \"/index.php\";\n\n" - "// Specify a query to send.\n" - "%query = \"\";\n\n" - "// Specify the submission data.\n" - "%post = \"\";\n\n" - "// Send the POST command to the server\n" - "%httpObj.POST(%url,%URI,%query,%post);\n" - "@endtsexample\n\n" - ) + "@brief Send POST command to a server to send or retrieve data.\n\n" + + "@param Address HTTP web address to send this get call to. Be sure to include the port at the end (IE: \"www.garagegames.com:80\").\n" + "@param requirstURI Specific location on the server to access (IE: \"index.php\".)\n" + "@param query Actual data to transmit to the server. Can be anything required providing it sticks with limitations of the HTTP protocol. \n" + "@param post Submission data to be processed.\n" + + "@tsexample\n" + "// Create an HTTP object for communications\n" + "%httpObj = new HTTPObject();\n\n" + "// Specify a URL to transmit to\n" + "%url = \"www.garagegames.com:80\";\n\n" + "// Specify a URI to communicate with\n" + "%URI = \"/index.php\";\n\n" + "// Specify a query to send.\n" + "%query = \"\";\n\n" + "// Specify the submission data.\n" + "%post = \"\";\n\n" + "// Send the POST command to the server\n" + "%httpObj.POST(%url,%URI,%query,%post);\n" + "@endtsexample\n\n" + ) { object->post(Address, requirstURI, query, post); } diff --git a/Engine/source/app/net/httpObject.h b/Engine/source/app/net/httpObject.h index ac12690aae..f5ded60ed6 100644 --- a/Engine/source/app/net/httpObject.h +++ b/Engine/source/app/net/httpObject.h @@ -35,7 +35,8 @@ class HTTPObject : public TCPObject private: typedef TCPObject Parent; protected: - enum ParseState { + enum ParseState + { ParsingStatusLine, ParsingHeader, ParsingChunkHeader, @@ -45,7 +46,7 @@ class HTTPObject : public TCPObject ParseState mParseState; U32 mTotalBytes; U32 mBytesRemaining; - public: +public: U32 mStatus; F32 mVersion; U32 mContentLength; diff --git a/Engine/source/app/net/net.cpp b/Engine/source/app/net/net.cpp index abec3ccc1e..b35488d7a6 100644 --- a/Engine/source/app/net/net.cpp +++ b/Engine/source/app/net/net.cpp @@ -38,75 +38,101 @@ //---------------------------------------------------------------- - RemoteCommandEvent::RemoteCommandEvent(S32 argc, const char **argv, NetConnection *conn) +RemoteCommandEvent::RemoteCommandEvent(S32 argc, const char **argv, NetConnection *conn) +{ + mArgc = argc; + for(S32 i = 0; i < argc; i++) { - mArgc = argc; - for(S32 i = 0; i < argc; i++) + if(argv[i][0] == StringTagPrefixByte) { - if(argv[i][0] == StringTagPrefixByte) + char buffer[256]; + mTagv[i+1] = NetStringHandle(dAtoi(argv[i]+1)); + if(conn) { - char buffer[256]; - mTagv[i+1] = NetStringHandle(dAtoi(argv[i]+1)); - if(conn) - { - dSprintf(buffer + 1, sizeof(buffer) - 1, "%d", conn->getNetSendId(mTagv[i+1])); - buffer[0] = StringTagPrefixByte; - mArgv[i+1] = dStrdup(buffer); - } + dSprintf(buffer + 1, sizeof(buffer) - 1, "%d", conn->getNetSendId(mTagv[i+1])); + buffer[0] = StringTagPrefixByte; + mArgv[i+1] = dStrdup(buffer); } - else - mArgv[i+1] = dStrdup(argv[i]); } + else + mArgv[i+1] = dStrdup(argv[i]); } +} #ifdef TORQUE_DEBUG_NET - const char *RemoteCommandEvent::getDebugName() - { - static char buffer[256]; - dSprintf(buffer, sizeof(buffer), "%s [%s]", getClassName(), mTagv[1].isValidString() ? mTagv[1].getString() : "--unknown--" ); - return buffer; - } +const char *RemoteCommandEvent::getDebugName() +{ + static char buffer[256]; + dSprintf(buffer, sizeof(buffer), "%s [%s]", getClassName(), mTagv[1].isValidString() ? mTagv[1].getString() : "--unknown--" ); + return buffer; +} #endif - RemoteCommandEvent::~RemoteCommandEvent() - { - for(S32 i = 0; i < mArgc; i++) - dFree(mArgv[i+1]); - } +RemoteCommandEvent::~RemoteCommandEvent() +{ + for(S32 i = 0; i < mArgc; i++) + dFree(mArgv[i+1]); +} - void RemoteCommandEvent::pack(NetConnection* conn, BitStream *bstream) - { - bstream->writeInt(mArgc, CommandArgsBits); - // write it out reversed... why? - // automatic string substitution with later arguments - - // handled automatically by the system. +void RemoteCommandEvent::pack(NetConnection* conn, BitStream *bstream) +{ + bstream->writeInt(mArgc, CommandArgsBits); + // write it out reversed... why? + // automatic string substitution with later arguments - + // handled automatically by the system. - for(S32 i = 0; i < mArgc; i++) - conn->packString(bstream, mArgv[i+1]); - } + for(S32 i = 0; i < mArgc; i++) + conn->packString(bstream, mArgv[i+1]); +} + +void RemoteCommandEvent::write(NetConnection* conn, BitStream *bstream) +{ + pack(conn, bstream); +} - void RemoteCommandEvent::write(NetConnection* conn, BitStream *bstream) +void RemoteCommandEvent::unpack(NetConnection* conn, BitStream *bstream) +{ + + mArgc = bstream->readInt(CommandArgsBits); + // read it out backwards + for(S32 i = 0; i < mArgc; i++) { - pack(conn, bstream); + conn->unpackString(bstream, mBuf); + mArgv[i+1] = dStrdup(mBuf); } +} - void RemoteCommandEvent::unpack(NetConnection* conn, BitStream *bstream) - { +void RemoteCommandEvent::process(NetConnection *conn) +{ + static char idBuf[10]; + + // de-tag the command name - mArgc = bstream->readInt(CommandArgsBits); - // read it out backwards - for(S32 i = 0; i < mArgc; i++) + for(S32 i = mArgc - 1; i >= 0; i--) + { + char *arg = mArgv[i+1]; + if(*arg == StringTagPrefixByte) { - conn->unpackString(bstream, mBuf); + // it's a tag: + U32 localTag = dAtoi(arg + 1); + NetStringHandle tag = conn->translateRemoteStringId(localTag); + NetStringTable::expandString( tag, + mBuf, + sizeof(mBuf), + (mArgc - 1) - i, + (const char**)(mArgv + i + 2) ); + dFree(mArgv[i+1]); mArgv[i+1] = dStrdup(mBuf); } } - - void RemoteCommandEvent::process(NetConnection *conn) + const char *rmtCommandName = dStrchr(mArgv[1], ' ') + 1; + if(conn->isConnectionToServer()) { - static char idBuf[10]; + dStrcpy(mBuf, "clientCmd"); + dStrcat(mBuf, rmtCommandName); - // de-tag the command name + char *temp = mArgv[1]; + mArgv[1] = mBuf; for(S32 i = mArgc - 1; i >= 0; i--) { @@ -131,8 +157,9 @@ dStrcpy(mBuf, "clientCmd", 1024); dStrcat(mBuf, rmtCommandName, 1024); - char *temp = mArgv[1]; - mArgv[1] = mBuf; + dSprintf(idBuf, sizeof(idBuf), "%d", conn->getId()); + mArgv[0] = mBuf; + mArgv[1] = idBuf; Con::execute(mArgc, (const char **) mArgv+1); mArgv[1] = temp; @@ -143,59 +170,50 @@ dStrcat(mBuf, rmtCommandName, 1024); char *temp = mArgv[1]; - dSprintf(idBuf, sizeof(idBuf), "%d", conn->getId()); - mArgv[0] = mBuf; - mArgv[1] = idBuf; - - Con::execute(mArgc+1, (const char **) mArgv); - mArgv[1] = temp; - } +void RemoteCommandEvent::sendRemoteCommand(NetConnection *conn, S32 argc, const char **argv) +{ + if(U8(argv[0][0]) != StringTagPrefixByte) + { + Con::errorf(ConsoleLogEntry::Script, "Remote Command Error - command must be a tag."); + return; + } + S32 i; + for(i = argc - 1; i >= 0; i--) + { + if(argv[i][0] != 0) + break; + argc = i; } + for(i = 0; i < argc; i++) + conn->validateSendString(argv[i]); + RemoteCommandEvent *cevt = new RemoteCommandEvent(argc, argv, conn); + conn->postNetEvent(cevt); +} - void RemoteCommandEvent::sendRemoteCommand(NetConnection *conn, S32 argc, const char **argv) - { - if(U8(argv[0][0]) != StringTagPrefixByte) - { - Con::errorf(ConsoleLogEntry::Script, "Remote Command Error - command must be a tag."); - return; - } - S32 i; - for(i = argc - 1; i >= 0; i--) - { - if(argv[i][0] != 0) - break; - argc = i; - } - for(i = 0; i < argc; i++) - conn->validateSendString(argv[i]); - RemoteCommandEvent *cevt = new RemoteCommandEvent(argc, argv, conn); - conn->postNetEvent(cevt); - } - - const char* RemoteCommandEvent::getTaggedString(const char* tag) - { - const char *indexPtr = tag; - if (*indexPtr == StringTagPrefixByte) - indexPtr++; - return gNetStringTable->lookupString(dAtoi(indexPtr)); - } - - void RemoteCommandEvent::removeTaggedString(S32 tag) - { - if (tag) - gNetStringTable->removeString(tag, true); - } - - const char* RemoteCommandEvent::addTaggedString(const char* str) - { - NetStringHandle s(str); - gNetStringTable->incStringRefScript(s.getIndex()); - - char *ret = Con::getReturnBuffer(10); - ret[0] = StringTagPrefixByte; - dSprintf(ret + 1, 9, "%d", s.getIndex()); - return ret; - } +const char* RemoteCommandEvent::getTaggedString(const char* tag) +{ + const char *indexPtr = tag; + if (*indexPtr == StringTagPrefixByte) + indexPtr++; + return gNetStringTable->lookupString(dAtoi(indexPtr)); +} + +void RemoteCommandEvent::removeTaggedString(S32 tag) +{ + if (tag) + gNetStringTable->removeString(tag, true); +} + +const char* RemoteCommandEvent::addTaggedString(const char* str) +{ + NetStringHandle s(str); + gNetStringTable->incStringRefScript(s.getIndex()); + + char *ret = Con::getReturnBuffer(10); + ret[0] = StringTagPrefixByte; + dSprintf(ret + 1, 9, "%d", s.getIndex()); + return ret; +} char RemoteCommandEvent::mBuf[1024]; @@ -203,9 +221,9 @@ char RemoteCommandEvent::mBuf[1024]; IMPLEMENT_CO_NETEVENT_V1(RemoteCommandEvent); ConsoleDocClass( RemoteCommandEvent, - "@brief Object used for remote procedure calls.\n\n" - "Not intended for game development, for exposing ConsoleFunctions (such as commandToClient) only.\n\n" - "@internal"); + "@brief Object used for remote procedure calls.\n\n" + "Not intended for game development, for exposing ConsoleFunctions (such as commandToClient) only.\n\n" + "@internal"); @@ -213,40 +231,40 @@ ConsoleFunctionGroupBegin( Net, "Functions for use with the network; tagged stri DefineEngineStringlyVariadicFunction( commandToServer, void, 2, RemoteCommandEvent::MaxRemoteCommandArgs + 1, "(string func, ...)" - "@brief Send a command to the server.\n\n" - - "@param func Name of the server command being called\n" - "@param ... Various parameters being passed to server command\n\n" - - "@tsexample\n" - "// Create a standard function. Needs to be executed on the client, such \n" - "// as within scripts/client/default.bind.cs\n" - "function toggleCamera(%val)\n" - "{\n" - " // If key was down, call a server command named 'ToggleCamera'\n" - " if (%val)\n" - " commandToServer('ToggleCamera');\n" - "}\n\n" - "// Server command being called from above. Needs to be executed on the \n" - "// server, such as within scripts/server/commands.cs\n" - "function serverCmdToggleCamera(%client)\n" - "{\n" - " if (%client.getControlObject() == %client.player)\n" - " {\n" - " %client.camera.setVelocity(\"0 0 0\");\n" - " %control = %client.camera;\n" - " }\n" - " else\n" - " {\n" - " %client.player.setVelocity(\"0 0 0\");\n" - " %control = %client.player;\n" - " }\n" - " %client.setControlObject(%control);\n" - " clientCmdSyncEditorGui();\n" - "}\n" - "@endtsexample\n\n" - - "@ingroup Networking") + "@brief Send a command to the server.\n\n" + + "@param func Name of the server command being called\n" + "@param ... Various parameters being passed to server command\n\n" + + "@tsexample\n" + "// Create a standard function. Needs to be executed on the client, such \n" + "// as within scripts/client/default.bind.cs\n" + "function toggleCamera(%val)\n" + "{\n" + " // If key was down, call a server command named 'ToggleCamera'\n" + " if (%val)\n" + " commandToServer('ToggleCamera');\n" + "}\n\n" + "// Server command being called from above. Needs to be executed on the \n" + "// server, such as within scripts/server/commands.cs\n" + "function serverCmdToggleCamera(%client)\n" + "{\n" + " if (%client.getControlObject() == %client.player)\n" + " {\n" + " %client.camera.setVelocity(\"0 0 0\");\n" + " %control = %client.camera;\n" + " }\n" + " else\n" + " {\n" + " %client.player.setVelocity(\"0 0 0\");\n" + " %control = %client.player;\n" + " }\n" + " %client.setControlObject(%control);\n" + " clientCmdSyncEditorGui();\n" + "}\n" + "@endtsexample\n\n" + + "@ingroup Networking") { NetConnection *conn = NetConnection::getConnectionToServer(); if(!conn) @@ -256,35 +274,35 @@ DefineEngineStringlyVariadicFunction( commandToServer, void, 2, RemoteCommandEve } DefineEngineStringlyVariadicFunction( commandToClient, void, 3, RemoteCommandEvent::MaxRemoteCommandArgs + 2, "(NetConnection client, string func, ...)" - "@brief Send a command from the server to the client\n\n" - - "@param client The numeric ID of a client GameConnection\n" - "@param func Name of the client function being called\n" - "@param ... Various parameters being passed to client command\n\n" - - "@tsexample\n" - "// Set up the client command. Needs to be executed on the client, such as\n" - "// within scripts/client/client.cs\n" - "// Update the Ammo Counter with current ammo, if not any then hide the counter.\n" - "function clientCmdSetAmmoAmountHud(%amount)\n" - "{\n" - " if (!%amount)\n" - " AmmoAmount.setVisible(false);\n" - " else\n" - " {\n" - " AmmoAmount.setVisible(true);\n" - " AmmoAmount.setText(\"Ammo: \"@%amount);\n" - " }\n" - "}\n\n" - "// Call it from a server function. Needs to be executed on the server, \n" - "//such as within scripts/server/game.cs\n" - "function GameConnection::setAmmoAmountHud(%client, %amount)\n" - "{\n" - " commandToClient(%client, 'SetAmmoAmountHud', %amount);\n" - "}\n" - "@endtsexample\n\n" - - "@ingroup Networking\n") + "@brief Send a command from the server to the client\n\n" + + "@param client The numeric ID of a client GameConnection\n" + "@param func Name of the client function being called\n" + "@param ... Various parameters being passed to client command\n\n" + + "@tsexample\n" + "// Set up the client command. Needs to be executed on the client, such as\n" + "// within scripts/client/client.cs\n" + "// Update the Ammo Counter with current ammo, if not any then hide the counter.\n" + "function clientCmdSetAmmoAmountHud(%amount)\n" + "{\n" + " if (!%amount)\n" + " AmmoAmount.setVisible(false);\n" + " else\n" + " {\n" + " AmmoAmount.setVisible(true);\n" + " AmmoAmount.setText(\"Ammo: \"@%amount);\n" + " }\n" + "}\n\n" + "// Call it from a server function. Needs to be executed on the server, \n" + "//such as within scripts/server/game.cs\n" + "function GameConnection::setAmmoAmountHud(%client, %amount)\n" + "{\n" + " commandToClient(%client, 'SetAmmoAmountHud', %amount);\n" + "}\n" + "@endtsexample\n\n" + + "@ingroup Networking\n") { NetConnection *conn; if(!Sim::findObject(argv[1], conn)) @@ -298,87 +316,87 @@ DefineEngineStringlyVariadicFunction( commandToClient, void, 3, RemoteCommandEve DefineEngineFunction(removeTaggedString, void, (S32 tag), (-1), - "@brief Remove a tagged string from the Net String Table\n\n" + "@brief Remove a tagged string from the Net String Table\n\n" - "@param tag The tag associated with the string\n\n" + "@param tag The tag associated with the string\n\n" - "@see \\ref syntaxDataTypes under Tagged %Strings\n" - "@see addTaggedString()\n" - "@see getTaggedString()\n" - "@ingroup Networking\n") - { + "@see \\ref syntaxDataTypes under Tagged %Strings\n" + "@see addTaggedString()\n" + "@see getTaggedString()\n" + "@ingroup Networking\n") +{ RemoteCommandEvent::removeTaggedString(tag); - } +} -DefineEngineFunction(addTaggedString, const char* , (const char* str), (""), - "@brief Use the addTaggedString function to tag a new string and add it to the NetStringTable\n\n" +DefineEngineFunction(addTaggedString, const char*, (const char* str), (""), + "@brief Use the addTaggedString function to tag a new string and add it to the NetStringTable\n\n" - "@param str The string to be tagged and placed in the NetStringTable. Tagging ignores case, " - "so tagging the same string (excluding case differences) will be ignored as a duplicated tag.\n\n" + "@param str The string to be tagged and placed in the NetStringTable. Tagging ignores case, " + "so tagging the same string (excluding case differences) will be ignored as a duplicated tag.\n\n" - "@return Returns a string( containing a numeric value) equivalent to the string ID for the newly tagged string" + "@return Returns a string( containing a numeric value) equivalent to the string ID for the newly tagged string" - "@see \\ref syntaxDataTypes under Tagged %Strings\n" - "@see removeTaggedString()\n" - "@see getTaggedString()\n" - "@ingroup Networking\n") - { + "@see \\ref syntaxDataTypes under Tagged %Strings\n" + "@see removeTaggedString()\n" + "@see getTaggedString()\n" + "@ingroup Networking\n") +{ return RemoteCommandEvent::addTaggedString(str); - } +} -DefineEngineFunction(getTaggedString, const char* , (const char *tag), (""), - "@brief Use the getTaggedString function to convert a tag to a string.\n\n" +DefineEngineFunction(getTaggedString, const char*, (const char *tag), (""), + "@brief Use the getTaggedString function to convert a tag to a string.\n\n" - "This is not the same as detag() which can only be used within the context " - "of a function that receives a tag. This function can be used any time and " - "anywhere to convert a tag to a string.\n\n" + "This is not the same as detag() which can only be used within the context " + "of a function that receives a tag. This function can be used any time and " + "anywhere to convert a tag to a string.\n\n" - "@param tag A numeric tag ID.\n" + "@param tag A numeric tag ID.\n" - "@returns The string as found in the Net String table.\n" + "@returns The string as found in the Net String table.\n" - "@see \\ref syntaxDataTypes under Tagged %Strings\n" - "@see addTaggedString()\n" - "@see removeTaggedString()\n" - "@ingroup Networking\n") - { - return RemoteCommandEvent::getTaggedString(tag); - } + "@see \\ref syntaxDataTypes under Tagged %Strings\n" + "@see addTaggedString()\n" + "@see removeTaggedString()\n" + "@ingroup Networking\n") +{ + return RemoteCommandEvent::getTaggedString(tag); +} DefineEngineStringlyVariadicFunction( buildTaggedString, const char*, 2, 11, "(string format, ...)" - "@brief Build a string using the specified tagged string format.\n\n" - - "This function takes an already tagged string (passed in as a tagged string ID) and one " - "or more additional strings. If the tagged string contains argument tags that range from " - "%%1 through %%9, then each additional string will be substituted into the tagged string. " - "The final (non-tagged) combined string will be returned. The maximum length of the tagged " - "string plus any inserted additional strings is 511 characters.\n\n" - - "@param format A tagged string ID that contains zero or more argument tags, in the form of " - "%%1 through %%9.\n" - "@param ... A variable number of arguments that are insterted into the tagged string " - "based on the argument tags within the format string.\n" - - "@returns An ordinary string that is a combination of the original tagged string with any additional " - "strings passed in inserted in place of each argument tag.\n" - - "@tsexample\n" - "// Create a tagged string with argument tags\n" - "%taggedStringID = addTaggedString(\"Welcome %1 to the game!\");\n\n" - - "// Some point later, combine the tagged string with some other string\n" - "%string = buildTaggedString(%taggedStringID, %playerName);\n" - "echo(%string);\n" - "@endtsexample\n\n" - - "@see \\ref syntaxDataTypes under Tagged %Strings\n" - "@see addTaggedString()\n" - "@see getTaggedString()\n" - "@ingroup Networking\n") + "@brief Build a string using the specified tagged string format.\n\n" + + "This function takes an already tagged string (passed in as a tagged string ID) and one " + "or more additional strings. If the tagged string contains argument tags that range from " + "%%1 through %%9, then each additional string will be substituted into the tagged string. " + "The final (non-tagged) combined string will be returned. The maximum length of the tagged " + "string plus any inserted additional strings is 511 characters.\n\n" + + "@param format A tagged string ID that contains zero or more argument tags, in the form of " + "%%1 through %%9.\n" + "@param ... A variable number of arguments that are insterted into the tagged string " + "based on the argument tags within the format string.\n" + + "@returns An ordinary string that is a combination of the original tagged string with any additional " + "strings passed in inserted in place of each argument tag.\n" + + "@tsexample\n" + "// Create a tagged string with argument tags\n" + "%taggedStringID = addTaggedString(\"Welcome %1 to the game!\");\n\n" + + "// Some point later, combine the tagged string with some other string\n" + "%string = buildTaggedString(%taggedStringID, %playerName);\n" + "echo(%string);\n" + "@endtsexample\n\n" + + "@see \\ref syntaxDataTypes under Tagged %Strings\n" + "@see addTaggedString()\n" + "@see getTaggedString()\n" + "@ingroup Networking\n") { const char *indexPtr = argv[1]; if (*indexPtr == StringTagPrefixByte) diff --git a/Engine/source/app/net/net.h b/Engine/source/app/net/net.h index c0aee93353..93490d64c3 100644 --- a/Engine/source/app/net/net.h +++ b/Engine/source/app/net/net.h @@ -17,7 +17,8 @@ class RemoteCommandEvent : public NetEvent { public: typedef NetEvent Parent; - enum { + enum + { MaxRemoteCommandArgs = 20, CommandArgsBits = 5 }; @@ -46,7 +47,7 @@ class RemoteCommandEvent : public NetEvent virtual void process(NetConnection *conn); static void sendRemoteCommand(NetConnection *conn, S32 argc, const char **argv); - + static void removeTaggedString(S32); static const char* addTaggedString(const char* str); diff --git a/Engine/source/app/net/netExamples.cpp b/Engine/source/app/net/netExamples.cpp index 1f53c6d215..e78dc49123 100644 --- a/Engine/source/app/net/netExamples.cpp +++ b/Engine/source/app/net/netExamples.cpp @@ -29,69 +29,81 @@ class SimpleMessageEvent : public NetEvent { - char *msg; -public: - typedef NetEvent Parent; - SimpleMessageEvent(const char *message = NULL) + char *msg; + public: + typedef NetEvent Parent; + SimpleMessageEvent(const char *message = NULL) { if(message) msg = dStrdup(message); else msg = NULL; } - ~SimpleMessageEvent() - { dFree(msg); } - - virtual void pack(NetConnection* /*ps*/, BitStream *bstream) - { bstream->writeString(msg); } - virtual void write(NetConnection*, BitStream *bstream) - { bstream->writeString(msg); } - virtual void unpack(NetConnection* /*ps*/, BitStream *bstream) - { char buf[256]; bstream->readString(buf); msg = dStrdup(buf); } - virtual void process(NetConnection *) - { Con::printf("RMSG %d %s", mSourceId, msg); } - - DECLARE_CONOBJECT(SimpleMessageEvent); + ~SimpleMessageEvent() + { + dFree(msg); + } + + virtual void pack(NetConnection* /*ps*/, BitStream *bstream) + { + bstream->writeString(msg); + } + virtual void write(NetConnection*, BitStream *bstream) + { + bstream->writeString(msg); + } + virtual void unpack(NetConnection* /*ps*/, BitStream *bstream) + { + char buf[256]; + bstream->readString(buf); + msg = dStrdup(buf); + } + virtual void process(NetConnection *) + { + Con::printf("RMSG %d %s", mSourceId, msg); + } + + DECLARE_CONOBJECT(SimpleMessageEvent); }; IMPLEMENT_CO_NETEVENT_V1(SimpleMessageEvent); ConsoleDocClass( SimpleMessageEvent, - "@brief A very simple example of a network event.\n\n" + "@brief A very simple example of a network event.\n\n" - "This object exists purely for instructional purposes. It is primarily " - "geared toward developers that wish to understand the inner-working of " - "Torque 3D's networking system. This is not intended for actual game " - "development.\n\n " + "This object exists purely for instructional purposes. It is primarily " + "geared toward developers that wish to understand the inner-working of " + "Torque 3D's networking system. This is not intended for actual game " + "development.\n\n " - "@see NetEvent for the inner workings of network events\n\n" + "@see NetEvent for the inner workings of network events\n\n" - "@ingroup Networking\n"); + "@ingroup Networking\n"); DefineEngineStaticMethod( SimpleMessageEvent, msg, void, (NetConnection* con, const char* message),, - "@brief Send a SimpleMessageEvent message to the specified connection.\n\n" - - "The far end that receives the message will print the message out to the console.\n" - - "@param con The unique ID of the connection to transmit to\n" - "@param message The string containing the message to transmit\n\n" - - "@tsexample\n" - "// Send a message to the other end of the given NetConnection\n" - "SimpleMessageEvent::msg( %conn, \"A message from me!\");\n\n" - - "// The far end will see the following in the console\n" - "// (Note: The number may be something other than 1796 as it is the SimObjectID\n" - "// of the received event)\n" - "// \n" - "// RMSG 1796 A message from me!\n" - "@endtsexample\n\n" - ) + "@brief Send a SimpleMessageEvent message to the specified connection.\n\n" + + "The far end that receives the message will print the message out to the console.\n" + + "@param con The unique ID of the connection to transmit to\n" + "@param message The string containing the message to transmit\n\n" + + "@tsexample\n" + "// Send a message to the other end of the given NetConnection\n" + "SimpleMessageEvent::msg( %conn, \"A message from me!\");\n\n" + + "// The far end will see the following in the console\n" + "// (Note: The number may be something other than 1796 as it is the SimObjectID\n" + "// of the received event)\n" + "// \n" + "// RMSG 1796 A message from me!\n" + "@endtsexample\n\n" + ) { - //NetConnection *con = (NetConnection *) Sim::findObject(argv[1]); + //NetConnection *con = (NetConnection *) Sim::findObject(argv[1]); - if(con) - con->postNetEvent(new SimpleMessageEvent(message)); + if(con) + con->postNetEvent(new SimpleMessageEvent(message)); } //ConsoleFunction( msg, void, 3, 3, "(NetConnection id, string message)" @@ -128,61 +140,61 @@ class SimpleNetObject : public NetObject dStrcpy(message, msg, 256); } - DECLARE_CONOBJECT(SimpleNetObject); + DECLARE_CONOBJECT(SimpleNetObject); }; IMPLEMENT_CO_NETOBJECT_V1(SimpleNetObject); ConsoleDocClass( SimpleNetObject, - "@brief A very simple example of a class derived from NetObject.\n\n" + "@brief A very simple example of a class derived from NetObject.\n\n" + + "This object exists purely for instructional purposes. It is primarily " + "geared toward developers that wish to understand the inner-working of " + "Torque 3D's networking system. This is not intended for actual game " + "development.\n\n " - "This object exists purely for instructional purposes. It is primarily " - "geared toward developers that wish to understand the inner-working of " - "Torque 3D's networking system. This is not intended for actual game " - "development.\n\n " - - "@tsexample\n" - "// On the server, create a new SimpleNetObject. This is a ghost always\n" - "// object so it will be immediately ghosted to all connected clients.\n" - "$s = new SimpleNetObject();\n\n" + "@tsexample\n" + "// On the server, create a new SimpleNetObject. This is a ghost always\n" + "// object so it will be immediately ghosted to all connected clients.\n" + "$s = new SimpleNetObject();\n\n" - "// All connected clients will see the following in their console:\n" - "// \n" - "// Got message: Hello World!\n" - "@endtsexample\n\n" + "// All connected clients will see the following in their console:\n" + "// \n" + "// Got message: Hello World!\n" + "@endtsexample\n\n" - "@see NetObject for a full breakdown of this example object\n" + "@see NetObject for a full breakdown of this example object\n" - "@ingroup Networking\n"); + "@ingroup Networking\n"); DefineEngineMethod( SimpleNetObject, setMessage, void, (const char* msg),, - "@brief Sets the internal message variable.\n\n" - - "SimpleNetObject is set up to automatically transmit this new message to " - "all connected clients. It will appear in the clients' console.\n" - - "@param msg The new message to send\n\n" - - "@tsexample\n" - "// On the server, create a new SimpleNetObject. This is a ghost always\n" - "// object so it will be immediately ghosted to all connected clients.\n" - "$s = new SimpleNetObject();\n\n" - - "// All connected clients will see the following in their console:\n" - "// \n" - "// Got message: Hello World!\n\n" - - "// Now again on the server, change the message. This will cause it to\n" - "// be sent to all connected clients.\n" - "$s.setMessage(\"A new message from me!\");\n\n" - - "// All connected clients will now see in their console:\n" - "// \n" - "// Go message: A new message from me!\n" - "@endtsexample\n\n" - ) + "@brief Sets the internal message variable.\n\n" + + "SimpleNetObject is set up to automatically transmit this new message to " + "all connected clients. It will appear in the clients' console.\n" + + "@param msg The new message to send\n\n" + + "@tsexample\n" + "// On the server, create a new SimpleNetObject. This is a ghost always\n" + "// object so it will be immediately ghosted to all connected clients.\n" + "$s = new SimpleNetObject();\n\n" + + "// All connected clients will see the following in their console:\n" + "// \n" + "// Got message: Hello World!\n\n" + + "// Now again on the server, change the message. This will cause it to\n" + "// be sent to all connected clients.\n" + "$s.setMessage(\"A new message from me!\");\n\n" + + "// All connected clients will now see in their console:\n" + "// \n" + "// Go message: A new message from me!\n" + "@endtsexample\n\n" + ) { - object->setMessage(msg); + object->setMessage(msg); } //ConsoleMethod( SimpleNetObject, setMessage, void, 3, 3, "(string msg)") diff --git a/Engine/source/app/net/serverQuery.cpp b/Engine/source/app/net/serverQuery.cpp index 03defe700f..5d8cad9f6a 100644 --- a/Engine/source/app/net/serverQuery.cpp +++ b/Engine/source/app/net/serverQuery.cpp @@ -149,8 +149,8 @@ static U32 gHeartbeatSeq = 0; class DemoNetInterface : public NetInterface { -public: - void handleInfoPacket(const NetAddress *address, U8 packetType, BitStream *stream); + public: + void handleInfoPacket(const NetAddress *address, U8 packetType, BitStream *stream); }; DemoNetInterface gNetInterface; @@ -192,8 +192,14 @@ struct PacketStatus tryCount = gPacketRetryCount; } - inline U8 getOldIndex() { return (U8)index; } - inline U16 getIndex() { return index; } + inline U8 getOldIndex() + { + return (U8)index; + } + inline U16 getIndex() + { + return index; + } }; static Vector gPacketStatusList(__FILE__, __LINE__); @@ -233,7 +239,7 @@ struct ServerFilter RegionAddressMask = RegionIsIPV4Address | RegionIsIPV6Address }; - + //Rearranging the fields according to their sizes char* gameType; char* missionType; @@ -316,7 +322,7 @@ void clearServerList(); //---------------------------------------------------------------- class ProcessMasterQueryEvent : public SimEvent { - U32 session; + U32 session; public: ProcessMasterQueryEvent( U32 _session ) { @@ -331,7 +337,7 @@ class ProcessMasterQueryEvent : public SimEvent //---------------------------------------------------------------- class ProcessPingEvent : public SimEvent { - U32 session; + U32 session; public: ProcessPingEvent( U32 _session ) { @@ -346,7 +352,7 @@ class ProcessPingEvent : public SimEvent //---------------------------------------------------------------- class ProcessPacketEvent : public SimEvent { - U32 session; + U32 session; public: ProcessPacketEvent( U32 _session ) { @@ -362,7 +368,7 @@ class ProcessPacketEvent : public SimEvent //---------------------------------------------------------------- class HeartbeatEvent : public SimEvent { - U32 mSeq; + U32 mSeq; public: HeartbeatEvent(U32 seq) { @@ -382,26 +388,26 @@ class HeartbeatEvent : public SimEvent //----------------------------------------------------------------------------- void queryLanServers(U32 port, U8 flags, const char* gameType, const char* missionType, - U8 minPlayers, U8 maxPlayers, U8 maxBots, U32 regionMask, U32 maxPing, U16 minCPU, - U8 filterFlags) + U8 minPlayers, U8 maxPlayers, U8 maxBots, U32 regionMask, U32 maxPing, U16 minCPU, + U8 filterFlags) { sgServerQueryActive = true; pushServerFavorites(); - sActiveFilter.type = ServerFilter::Offline; + sActiveFilter.type = ServerFilter::Offline; - // Clear the filter: - if ( !sActiveFilter.gameType || dStricmp( sActiveFilter.gameType, "Any" ) != 0 ) - { - sActiveFilter.gameType = (char*) dRealloc( sActiveFilter.gameType, 4 ); - dStrcpy( sActiveFilter.gameType, "Any", 4 ); - } - if ( !sActiveFilter.missionType || dStricmp( sActiveFilter.missionType, "Any" ) != 0 ) - { - sActiveFilter.missionType = (char*) dRealloc( sActiveFilter.missionType, 4 ); - dStrcpy( sActiveFilter.missionType, "Any", 4 ); - } - sActiveFilter.queryFlags = 0; + // Clear the filter: + if ( !sActiveFilter.gameType || dStricmp( sActiveFilter.gameType, "Any" ) != 0 ) + { + sActiveFilter.gameType = (char*) dRealloc( sActiveFilter.gameType, 4 ); + dStrcpy( sActiveFilter.gameType, "Any", 4 ); + } + if ( !sActiveFilter.missionType || dStricmp( sActiveFilter.missionType, "Any" ) != 0 ) + { + sActiveFilter.missionType = (char*) dRealloc( sActiveFilter.missionType, 4 ); + dStrcpy( sActiveFilter.missionType, "Any", 4 ); + } + sActiveFilter.queryFlags = 0; sActiveFilter.minPlayers = minPlayers; sActiveFilter.maxPlayers = maxPlayers; sActiveFilter.maxBots = maxBots; @@ -430,50 +436,50 @@ void queryLanServers(U32 port, U8 flags, const char* gameType, const char* missi //----------------------------------------------------------------------------- DefineEngineFunction( queryAllServers - , void, ( U32 lanPort - , U32 flags - , const char * gameType - , const char * missionType - , U32 minPlayers - , U32 maxPlayers - , U32 maxBots - , U32 regionMask - , U32 maxPing - , U32 minCPU - , U32 filterFlags ) - , , "queryAllServers(...);" ) + , void, ( U32 lanPort + , U32 flags + , const char * gameType + , const char * missionType + , U32 minPlayers + , U32 maxPlayers + , U32 maxBots + , U32 regionMask + , U32 maxPing + , U32 minCPU + , U32 filterFlags ) + ,, "queryAllServers(...);" ) { U32 buddyList = 0; clearServerList(); queryMasterServer(flags,gameType,missionType,minPlayers,maxPlayers, - maxBots,regionMask,maxPing,minCPU,filterFlags,0,&buddyList); + maxBots,regionMask,maxPing,minCPU,filterFlags,0,&buddyList); queryLanServers(lanPort, flags, gameType, missionType, minPlayers, maxPlayers, maxBots, - regionMask, maxPing, minCPU, filterFlags); + regionMask, maxPing, minCPU, filterFlags); } DefineEngineFunction( queryLanServers - , void, ( U32 lanPort - , U32 flags - , const char * gameType - , const char * missionType - , U32 minPlayers - , U32 maxPlayers - , U32 maxBots - , U32 regionMask - , U32 maxPing - , U32 minCPU - , U32 filterFlags ) - , , "queryLanServers(...);" ) + , void, ( U32 lanPort + , U32 flags + , const char * gameType + , const char * missionType + , U32 minPlayers + , U32 maxPlayers + , U32 maxBots + , U32 regionMask + , U32 maxPing + , U32 minCPU + , U32 filterFlags ) + ,, "queryLanServers(...);" ) { clearServerList(); queryLanServers(lanPort, flags, gameType, missionType, minPlayers, maxPlayers, maxBots, - regionMask, maxPing, minCPU, filterFlags); + regionMask, maxPing, minCPU, filterFlags); } @@ -494,8 +500,8 @@ void queryMasterGameTypes() //----------------------------------------------------------------------------- void queryMasterServer(U8 flags, const char* gameType, const char* missionType, - U8 minPlayers, U8 maxPlayers, U8 maxBots, U32 regionMask, U32 maxPing, - U16 minCPU, U8 filterFlags, U8 buddyCount, U32* buddyList ) + U8 minPlayers, U8 maxPlayers, U8 maxBots, U32 regionMask, U32 maxPing, + U16 minCPU, U8 filterFlags, U8 buddyCount, U32* buddyList ) { // Reset the list packet flag: gGotFirstListPacket = false; @@ -561,30 +567,30 @@ void queryMasterServer(U8 flags, const char* gameType, const char* missionType, } DefineEngineFunction( queryMasterServer - , void, ( U32 flags - , const char * gameType - , const char * missionType - , U32 minPlayers - , U32 maxPlayers - , U32 maxBots - , U32 regionMask - , U32 maxPing - , U32 minCPU - , U32 filterFlags ) - , , "queryMasterServer(...);" ) + , void, ( U32 flags + , const char * gameType + , const char * missionType + , U32 minPlayers + , U32 maxPlayers + , U32 maxBots + , U32 regionMask + , U32 maxPing + , U32 minCPU + , U32 filterFlags ) + ,, "queryMasterServer(...);" ) { U32 buddyList = 0; clearServerList(); queryMasterServer(flags,gameType,missionType,minPlayers,maxPlayers, - maxBots,regionMask,maxPing,minCPU,filterFlags,0,&buddyList); + maxBots,regionMask,maxPing,minCPU,filterFlags,0,&buddyList); } //----------------------------------------------------------------------------- DefineEngineFunction( querySingleServer - , void, ( const char* addrText, U8 flags ) - , (0), "querySingleServer(address, flags);" ) + , void, ( const char* addrText, U8 flags ) + , (0), "querySingleServer(address, flags);" ) { NetAddress addr; Net::stringToAddress( addrText, &addr ); @@ -668,7 +674,7 @@ void cancelServerQuery() } } -DefineEngineFunction( cancelServerQuery, void, (), , "cancelServerQuery();" ) +DefineEngineFunction( cancelServerQuery, void, (),, "cancelServerQuery();" ) { cancelServerQuery(); } @@ -696,36 +702,38 @@ void stopServerQuery() } } -DefineEngineFunction( stopServerQuery, void, (), , "stopServerQuery();" ) +DefineEngineFunction( stopServerQuery, void, (),, "stopServerQuery();" ) { stopServerQuery(); } //----------------------------------------------------------------------------- -DefineEngineFunction( startHeartbeat, void, (), , "startHeartbeat();" ) +DefineEngineFunction( startHeartbeat, void, (),, "startHeartbeat();" ) { - if (validateAuthenticatedServer()) { + if (validateAuthenticatedServer()) + { gHeartbeatSeq++; processHeartbeat(gHeartbeatSeq); // thump-thump... } } -DefineEngineFunction( stopHeartbeat, void, (), , "stopHeartbeat();" ) +DefineEngineFunction( stopHeartbeat, void, (),, "stopHeartbeat();" ) { gHeartbeatSeq++; } //----------------------------------------------------------------------------- -DefineEngineFunction( getServerCount, int, (), , "getServerCount();" ) +DefineEngineFunction( getServerCount, int, (),, "getServerCount();" ) { return gServerList.size(); } -DefineEngineFunction( setServerInfo, bool, (U32 index), , "setServerInfo(index);" ) +DefineEngineFunction( setServerInfo, bool, (U32 index),, "setServerInfo(index);" ) { - if (index < gServerList.size()) { + if (index < gServerList.size()) + { ServerInfo& info = gServerList[index]; char addrString[256]; @@ -785,18 +793,21 @@ Vector* getMasterServerList() static Vector masterList; masterList.clear(); - for (U32 i = 0; i < 10; i++) { + for (U32 i = 0; i < 10; i++) + { char buffer[50]; dSprintf(buffer,sizeof(buffer),"pref::Master%d",i); const char* master = Con::getVariable(buffer); - if (master && *master) { + if (master && *master) + { NetAddress address; // Format for master server variable: // regionMask:netAddress U32 region = 1; // needs to default to something > 0 dSscanf(master,"%d:",®ion); const char* madd = dStrchr(master,':') + 1; - if (region && Net::stringToAddress(madd,&address) == Net::NoError) { + if (region && Net::stringToAddress(madd,&address) == Net::NoError) + { masterList.increment(); MasterInfo& info = masterList.last(); info.address = address; @@ -1196,7 +1207,7 @@ static void processMasterServerQuery( U32 session ) out->clearStringBuffer(); out->write( U8( NetInterface::MasterServerListRequest ) ); - + out->write( U8( sActiveFilter.queryFlags) ); out->write( ( gMasterServerPing.session << 16 ) | ( gMasterServerPing.key & 0xFFFF ) ); out->write( U8( 255 ) ); @@ -1408,7 +1419,7 @@ static void processServerListPackets( U32 session ) out->write( U8( sActiveFilter.queryFlags ) ); // flags out->write( ( session << 16) | ( p.key & 0xFFFF ) ); - + if ( extendedPacket ) out->write( p.getOldIndex() ); // packet index else @@ -1459,10 +1470,10 @@ static void updatePingProgress() char msg[64]; U32 pingsLeft = countPingRequests(); dSprintf( msg, sizeof(msg), - (!pingsLeft && gPingList.size())? - "Waiting for lan servers...": - "Pinging servers: %d left...", - pingsLeft ); + (!pingsLeft && gPingList.size())? + "Waiting for lan servers...": + "Pinging servers: %d left...", + pingsLeft ); // Ping progress is 0 -> 0.5 F32 progress = 0.0f; @@ -1928,8 +1939,8 @@ static void handleGamePingResponse( const NetAddress* address, BitStream* stream // Get the server build version: stream->read( &temp32 ); if ( applyFilter - && ( sActiveFilter.filterFlags & ServerFilter::CurrentVersion ) - && ( temp32 != getVersionNumber() ) ) + && ( sActiveFilter.filterFlags & ServerFilter::CurrentVersion ) + && ( temp32 != getVersionNumber() ) ) { Con::printf( "Server %s filtered out by version number.", addrString ); gFinishedList.push_back( *address ); @@ -1990,12 +2001,14 @@ static void handleGameInfoRequest( const NetAddress* address, U32 key, U8 flags out->write( flags ); out->write( key ); - if ( compressStrings ) { + if ( compressStrings ) + { out->writeString( Con::getVariable( "Server::GameType" ) ); out->writeString( Con::getVariable( "Server::MissionType" ) ); out->writeString( Con::getVariable( "Server::MissionName" ) ); } - else { + else + { writeCString( out, Con::getVariable( "Server::GameType" ) ); writeCString( out, Con::getVariable( "Server::MissionType" ) ); writeCString( out, Con::getVariable( "Server::MissionName" ) ); @@ -2060,7 +2073,7 @@ static void handleGameInfoResponse( const NetAddress* address, BitStream* stream // Test against the active filter: if ( applyFilter && dStricmp( sActiveFilter.gameType, "any" ) != 0 - && dStricmp( si->gameType, sActiveFilter.gameType ) != 0 ) + && dStricmp( si->gameType, sActiveFilter.gameType ) != 0 ) { Con::printf( "Server %s filtered out by rules set. (%s:%s)", addrString, sActiveFilter.gameType, si->gameType ); removeServerInfo( address ); @@ -2078,7 +2091,7 @@ static void handleGameInfoResponse( const NetAddress* address, BitStream* stream // Test against the active filter: if ( applyFilter && dStricmp( sActiveFilter.missionType, "any" ) != 0 - && dStricmp( si->missionType, sActiveFilter.missionType ) != 0 ) + && dStricmp( si->missionType, sActiveFilter.missionType ) != 0 ) { Con::printf( "Server %s filtered out by mission type. (%s:%s)", addrString, sActiveFilter.missionType, si->missionType ); removeServerInfo( address ); diff --git a/Engine/source/app/net/serverQuery.h b/Engine/source/app/net/serverQuery.h index fcdcaa6c1b..7e2f285471 100644 --- a/Engine/source/app/net/serverQuery.h +++ b/Engine/source/app/net/serverQuery.h @@ -88,15 +88,39 @@ struct ServerInfo } ~ServerInfo(); - bool isNew() { return( status == Status_New ); } - bool isQuerying() { return( status.test( Status_Querying ) ); } - bool isUpdating() { return( status.test( Status_Updating ) ); } - bool hasResponded() { return( status.test( Status_Responded ) ); } - bool isTimedOut() { return( status.test( Status_TimedOut ) ); } + bool isNew() + { + return( status == Status_New ); + } + bool isQuerying() + { + return( status.test( Status_Querying ) ); + } + bool isUpdating() + { + return( status.test( Status_Updating ) ); + } + bool hasResponded() + { + return( status.test( Status_Responded ) ); + } + bool isTimedOut() + { + return( status.test( Status_TimedOut ) ); + } - bool isDedicated() { return( status.test( Status_Dedicated ) ); } - bool isPassworded() { return( status.test( Status_Passworded ) ); } - bool isLinux() { return( status.test( Status_Linux ) ); } + bool isDedicated() + { + return( status.test( Status_Dedicated ) ); + } + bool isPassworded() + { + return( status.test( Status_Passworded ) ); + } + bool isLinux() + { + return( status.test( Status_Linux ) ); + } }; @@ -107,12 +131,12 @@ extern Vector gServerList; extern bool gServerBrowserDirty; extern void clearServerList(); extern void queryLanServers(U32 port, U8 flags, const char* gameType, const char* missionType, - U8 minPlayers, U8 maxPlayers, U8 maxBots, U32 regionMask, U32 maxPing, U16 minCPU, - U8 filterFlags); + U8 minPlayers, U8 maxPlayers, U8 maxBots, U32 regionMask, U32 maxPing, U16 minCPU, + U8 filterFlags); extern void queryMasterGameTypes(); extern void queryMasterServer(U8 flags, const char* gameType, const char* missionType, - U8 minPlayers, U8 maxPlayers, U8 maxBots, U32 regionMask, U32 maxPing, U16 minCPU, - U8 filterFlags, U8 buddyCount, U32* buddyList ); + U8 minPlayers, U8 maxPlayers, U8 maxBots, U32 regionMask, U32 maxPing, U16 minCPU, + U8 filterFlags, U8 buddyCount, U32* buddyList ); extern void queryFavoriteServers( U8 flags ); extern void querySingleServer(const NetAddress* addr, U8 flags); extern void startHeartbeat(); diff --git a/Engine/source/app/net/tcpObject.cpp b/Engine/source/app/net/tcpObject.cpp index 07c8908ebb..ca762a3259 100644 --- a/Engine/source/app/net/tcpObject.cpp +++ b/Engine/source/app/net/tcpObject.cpp @@ -34,139 +34,139 @@ TCPObject *TCPObject::table[TCPObject::TableSize] = {0, }; IMPLEMENT_CONOBJECT(TCPObject); ConsoleDocClass( TCPObject, - "@brief Allows communications between the game and a server using TCP/IP protocols.\n\n" - - "To use TCPObject you set up a connection to a server, send data to the server, and handle " - "each line of the server's response using a callback. Once you are done communicating with " - "the server, you disconnect.\n\n" - - "TCPObject is intended to be used with text based protocols which means you'll need to " - "delineate the server's response with an end-of-line character. i.e. the newline " - "character @\\n. You may optionally include the carriage return character @\\r prior to the newline " - "and TCPObject will strip it out before sending the line to the callback. If a newline " - "character is not included in the server's output, the received data will not be " - "processed until you disconnect from the server (which flushes the internal buffer).\n\n" - - "TCPObject may also be set up to listen to a specific port, making Torque into a TCP server. " - "When used in this manner, a callback is received when a client connection is made. Following " - "the outside connection, text may be sent and lines are processed in the usual manner.\n\n" - - "If you want to work with HTTP you may wish to use HTTPObject instead as it handles all of the " - "HTTP header setup and parsing.\n\n" - - "@tsexample\n" - "// In this example we'll retrieve the new forum threads RSS\n" - "// feed from garagegames.com. As we're using TCPObject, the\n" - "// raw text response will be received from the server, including\n" - "// the HTTP header.\n\n" - - "// Define callbacks for our specific TCPObject using our instance's\n" - "// name (RSSFeed) as the namespace.\n\n" - - "// Handle an issue with resolving the server's name\n" - "function RSSFeed::onDNSFailed(%this)\n" - "{\n" - " // Store this state\n" - " %this.lastState = \"DNSFailed\";\n\n" - - " // Handle DNS failure\n" - "}\n\n" - - "function RSSFeed::onConnectFailed(%this)\n" - "{\n" - " // Store this state\n" - " %this.lastState = \"ConnectFailed\";\n\n" - " // Handle connection failure\n" - "}\n\n" - - "function RSSFeed::onDNSResolved(%this)\n" - "{\n" - " // Store this state\n" - " %this.lastState = \"DNSResolved\";\n\n" - "}\n\n" - - "function RSSFeed::onConnected(%this)\n" - "{\n" - " // Store this state\n" - " %this.lastState = \"Connected\";\n\n" - "}\n\n" - - "function RSSFeed::onDisconnect(%this)\n" - "{\n" - " // Store this state\n" - " %this.lastState = \"Disconnected\";\n\n" - "}\n\n" - - "// Handle a line from the server\n" - "function RSSFeed::onLine(%this, %line)\n" - "{\n" - " // Print the line to the console\n" - " echo( %line );\n" - "}\n\n" - - "// Create the TCPObject\n" - "%rss = new TCPObject(RSSFeed);\n\n" - - "// Define a dynamic field to store the last connection state\n" - "%rss.lastState = \"None\";\n\n" - - "// Connect to the server\n" - "%rss.connect(\"www.garagegames.com:80\");\n\n" - - "// Send the RSS feed request to the server. Response will be\n" - "// handled in onLine() callback above\n" - "%rss.send(\"GET /feeds/rss/threads HTTP/1.1\\r\\nHost: www.garagegames.com\\r\\n\\r\\n\");\n" - "@endtsexample\n\n" - - "@see HTTPObject\n" - - "@ingroup Networking\n" -); + "@brief Allows communications between the game and a server using TCP/IP protocols.\n\n" + + "To use TCPObject you set up a connection to a server, send data to the server, and handle " + "each line of the server's response using a callback. Once you are done communicating with " + "the server, you disconnect.\n\n" + + "TCPObject is intended to be used with text based protocols which means you'll need to " + "delineate the server's response with an end-of-line character. i.e. the newline " + "character @\\n. You may optionally include the carriage return character @\\r prior to the newline " + "and TCPObject will strip it out before sending the line to the callback. If a newline " + "character is not included in the server's output, the received data will not be " + "processed until you disconnect from the server (which flushes the internal buffer).\n\n" + + "TCPObject may also be set up to listen to a specific port, making Torque into a TCP server. " + "When used in this manner, a callback is received when a client connection is made. Following " + "the outside connection, text may be sent and lines are processed in the usual manner.\n\n" + + "If you want to work with HTTP you may wish to use HTTPObject instead as it handles all of the " + "HTTP header setup and parsing.\n\n" + + "@tsexample\n" + "// In this example we'll retrieve the new forum threads RSS\n" + "// feed from garagegames.com. As we're using TCPObject, the\n" + "// raw text response will be received from the server, including\n" + "// the HTTP header.\n\n" + + "// Define callbacks for our specific TCPObject using our instance's\n" + "// name (RSSFeed) as the namespace.\n\n" + + "// Handle an issue with resolving the server's name\n" + "function RSSFeed::onDNSFailed(%this)\n" + "{\n" + " // Store this state\n" + " %this.lastState = \"DNSFailed\";\n\n" + + " // Handle DNS failure\n" + "}\n\n" + + "function RSSFeed::onConnectFailed(%this)\n" + "{\n" + " // Store this state\n" + " %this.lastState = \"ConnectFailed\";\n\n" + " // Handle connection failure\n" + "}\n\n" + + "function RSSFeed::onDNSResolved(%this)\n" + "{\n" + " // Store this state\n" + " %this.lastState = \"DNSResolved\";\n\n" + "}\n\n" + + "function RSSFeed::onConnected(%this)\n" + "{\n" + " // Store this state\n" + " %this.lastState = \"Connected\";\n\n" + "}\n\n" + + "function RSSFeed::onDisconnect(%this)\n" + "{\n" + " // Store this state\n" + " %this.lastState = \"Disconnected\";\n\n" + "}\n\n" + + "// Handle a line from the server\n" + "function RSSFeed::onLine(%this, %line)\n" + "{\n" + " // Print the line to the console\n" + " echo( %line );\n" + "}\n\n" + + "// Create the TCPObject\n" + "%rss = new TCPObject(RSSFeed);\n\n" + + "// Define a dynamic field to store the last connection state\n" + "%rss.lastState = \"None\";\n\n" + + "// Connect to the server\n" + "%rss.connect(\"www.garagegames.com:80\");\n\n" + + "// Send the RSS feed request to the server. Response will be\n" + "// handled in onLine() callback above\n" + "%rss.send(\"GET /feeds/rss/threads HTTP/1.1\\r\\nHost: www.garagegames.com\\r\\n\\r\\n\");\n" + "@endtsexample\n\n" + + "@see HTTPObject\n" + + "@ingroup Networking\n" + ); IMPLEMENT_CALLBACK(TCPObject, onConnectionRequest, void, (const char* address, const char* ID), (address, ID), - "@brief Called whenever a connection request is made.\n\n" - "This callback is used when the TCPObject is listening to a port and a client is attempting to connect.\n" - "@param address Server address connecting from.\n" - "@param ID Connection ID\n" - "@see listen()\n" - ); + "@brief Called whenever a connection request is made.\n\n" + "This callback is used when the TCPObject is listening to a port and a client is attempting to connect.\n" + "@param address Server address connecting from.\n" + "@param ID Connection ID\n" + "@see listen()\n" + ); IMPLEMENT_CALLBACK(TCPObject, onLine, void, (const char* line), (line), - "@brief Called whenever a line of data is sent to this TCPObject.\n\n" - "This callback is called when the received data contains a newline @\\n character, or " - "the connection has been disconnected and the TCPObject's buffer is flushed.\n" - "@param line Data sent from the server.\n" - ); + "@brief Called whenever a line of data is sent to this TCPObject.\n\n" + "This callback is called when the received data contains a newline @\\n character, or " + "the connection has been disconnected and the TCPObject's buffer is flushed.\n" + "@param line Data sent from the server.\n" + ); IMPLEMENT_CALLBACK(TCPObject, onPacket, bool, (const char* data), (data), - "@brief Called when we get a packet with no newlines or nulls (probably websocket).\n\n" - "@param data Data sent from the server.\n" - "@return true if script handled the packet.\n" - ); + "@brief Called when we get a packet with no newlines or nulls (probably websocket).\n\n" + "@param data Data sent from the server.\n" + "@return true if script handled the packet.\n" + ); IMPLEMENT_CALLBACK(TCPObject, onEndReceive, void, (), (), - "@brief Called when we are done reading all lines.\n\n" - ); + "@brief Called when we are done reading all lines.\n\n" + ); IMPLEMENT_CALLBACK(TCPObject, onDNSResolved, void, (),(), - "Called whenever the DNS has been resolved.\n" - ); + "Called whenever the DNS has been resolved.\n" + ); IMPLEMENT_CALLBACK(TCPObject, onDNSFailed, void, (),(), - "Called whenever the DNS has failed to resolve.\n" - ); + "Called whenever the DNS has failed to resolve.\n" + ); IMPLEMENT_CALLBACK(TCPObject, onConnected, void, (),(), - "Called whenever a connection is established with a server.\n" - ); + "Called whenever a connection is established with a server.\n" + ); IMPLEMENT_CALLBACK(TCPObject, onConnectFailed, void, (),(), - "Called whenever a connection has failed to be established with a server.\n" - ); + "Called whenever a connection has failed to be established with a server.\n" + ); IMPLEMENT_CALLBACK(TCPObject, onDisconnect, void, (),(), - "Called whenever the TCPObject disconnects from whatever it is currently connected to.\n" - ); + "Called whenever the TCPObject disconnects from whatever it is currently connected to.\n" + ); TCPObject *TCPObject::find(NetSocket tag) { @@ -418,7 +418,8 @@ void TCPObject::connect(const char *address) void TCPObject::disconnect() { - if( mTag != NetSocket::INVALID ) { + if( mTag != NetSocket::INVALID ) + { Net::closeConnectTo(mTag); } removeFromTable(); @@ -445,99 +446,99 @@ bool TCPObject::sendFile(const char* fileName) //Send the buffer send(buffer.address(), buffer.size()); - return true; + return true; } -DefineEngineMethod(TCPObject, send, void, (const char *data),, - "@brief Transmits the data string to the connected computer.\n\n" +DefineEngineMethod(TCPObject, send, void, (const char *data),, + "@brief Transmits the data string to the connected computer.\n\n" - "This method is used to send text data to the connected computer regardless if we initiated the " - "connection using connect(), or listening to a port using listen().\n" + "This method is used to send text data to the connected computer regardless if we initiated the " + "connection using connect(), or listening to a port using listen().\n" - "@param data The data string to send.\n" + "@param data The data string to send.\n" - "@tsexample\n" - "// Set the command data\n" - "%data = \"GET \" @ $RSSFeed::serverURL @ \" HTTP/1.0\\r\\n\";\n" - "%data = %data @ \"Host: \" @ $RSSFeed::serverName @ \"\\r\\n\";\n" - "%data = %data @ \"User-Agent: \" @ $RSSFeed::userAgent @ \"\\r\\n\\r\\n\"\n\n" + "@tsexample\n" + "// Set the command data\n" + "%data = \"GET \" @ $RSSFeed::serverURL @ \" HTTP/1.0\\r\\n\";\n" + "%data = %data @ \"Host: \" @ $RSSFeed::serverName @ \"\\r\\n\";\n" + "%data = %data @ \"User-Agent: \" @ $RSSFeed::userAgent @ \"\\r\\n\\r\\n\"\n\n" - "// Send the command to the connected server.\n" - "%thisTCPObj.send(%data);\n" - "@endtsexample\n") + "// Send the command to the connected server.\n" + "%thisTCPObj.send(%data);\n" + "@endtsexample\n") { object->send( (const U8*)data, dStrlen(data) ); } -DefineEngineMethod(TCPObject, sendFile, bool, (const char *fileName),, - "@brief Transmits the file in binary to the connected computer.\n\n" +DefineEngineMethod(TCPObject, sendFile, bool, (const char *fileName),, + "@brief Transmits the file in binary to the connected computer.\n\n" - "@param fileName The filename of the file to transfer.\n") + "@param fileName The filename of the file to transfer.\n") { return object->sendFile(fileName); } -DefineEngineMethod(TCPObject, finishLastLine, void, (),, - "@brief Eat the rest of the lines.\n") +DefineEngineMethod(TCPObject, finishLastLine, void, (),, + "@brief Eat the rest of the lines.\n") { object->finishLastLine(); } -DefineEngineMethod(TCPObject, listen, void, (U32 port),, - "@brief Start listening on the specified port for connections.\n\n" +DefineEngineMethod(TCPObject, listen, void, (U32 port),, + "@brief Start listening on the specified port for connections.\n\n" - "This method starts a listener which looks for incoming TCP connections to a port. " - "You must overload the onConnectionRequest callback to create a new TCPObject to " - "read, write, or reject the new connection.\n\n" + "This method starts a listener which looks for incoming TCP connections to a port. " + "You must overload the onConnectionRequest callback to create a new TCPObject to " + "read, write, or reject the new connection.\n\n" - "@param port Port for this TCPObject to start listening for connections on.\n" + "@param port Port for this TCPObject to start listening for connections on.\n" - "@tsexample\n" + "@tsexample\n" - "// Create a listener on port 8080.\n" - "new TCPObject( TCPListener );\n" - "TCPListener.listen( 8080 );\n\n" + "// Create a listener on port 8080.\n" + "new TCPObject( TCPListener );\n" + "TCPListener.listen( 8080 );\n\n" - "function TCPListener::onConnectionRequest( %this, %address, %id )\n" - "{\n" - " // Create a new object to manage the connection.\n" - " new TCPObject( TCPClient, %id );\n" - "}\n\n" + "function TCPListener::onConnectionRequest( %this, %address, %id )\n" + "{\n" + " // Create a new object to manage the connection.\n" + " new TCPObject( TCPClient, %id );\n" + "}\n\n" - "function TCPClient::onLine( %this, %line )\n" - "{\n" - " // Print the line of text from client.\n" - " echo( %line );\n" - "}\n" + "function TCPClient::onLine( %this, %line )\n" + "{\n" + " // Print the line of text from client.\n" + " echo( %line );\n" + "}\n" - "@endtsexample\n") + "@endtsexample\n") { object->listen(U32(port)); } -DefineEngineMethod(TCPObject, connect, void, (const char* address),, - "@brief Connect to the given address.\n\n" +DefineEngineMethod(TCPObject, connect, void, (const char* address),, + "@brief Connect to the given address.\n\n" - "@param address Server address (including port) to connect to.\n" + "@param address Server address (including port) to connect to.\n" - "@tsexample\n" - "// Set the address.\n" - "%address = \"www.garagegames.com:80\";\n\n" + "@tsexample\n" + "// Set the address.\n" + "%address = \"www.garagegames.com:80\";\n\n" - "// Inform this TCPObject to connect to the specified address.\n" - "%thisTCPObj.connect(%address);\n" - "@endtsexample\n") + "// Inform this TCPObject to connect to the specified address.\n" + "%thisTCPObj.connect(%address);\n" + "@endtsexample\n") { object->connect(address); } -DefineEngineMethod(TCPObject, disconnect, void, (),, - "@brief Disconnect from whatever this TCPObject is currently connected to, if anything.\n\n" +DefineEngineMethod(TCPObject, disconnect, void, (),, + "@brief Disconnect from whatever this TCPObject is currently connected to, if anything.\n\n" - "@tsexample\n" - "// Inform this TCPObject to disconnect from anything it is currently connected to.\n" - "%thisTCPObj.disconnect();\n" - "@endtsexample\n") + "@tsexample\n" + "// Inform this TCPObject to disconnect from anything it is currently connected to.\n" + "%thisTCPObj.disconnect();\n" + "@endtsexample\n") { object->disconnect(); } diff --git a/Engine/source/app/net/tcpObject.h b/Engine/source/app/net/tcpObject.h index 9a8b5e40da..0d4cc6d10c 100644 --- a/Engine/source/app/net/tcpObject.h +++ b/Engine/source/app/net/tcpObject.h @@ -34,15 +34,15 @@ class TCPObject : public SimObject public: enum State {Disconnected, DNSResolved, Connected, Listening }; - DECLARE_CALLBACK(void, onConnectionRequest, (const char* address, const char* ID)); - DECLARE_CALLBACK(void, onLine, (const char* line)); - DECLARE_CALLBACK(bool, onPacket, (const char* data)); - DECLARE_CALLBACK(void, onEndReceive, ()); - DECLARE_CALLBACK(void, onDNSResolved,()); - DECLARE_CALLBACK(void, onDNSFailed, ()); - DECLARE_CALLBACK(void, onConnected, ()); - DECLARE_CALLBACK(void, onConnectFailed, ()); - DECLARE_CALLBACK(void, onDisconnect, ()); + DECLARE_CALLBACK(void, onConnectionRequest, (const char* address, const char* ID)); + DECLARE_CALLBACK(void, onLine, (const char* line)); + DECLARE_CALLBACK(bool, onPacket, (const char* data)); + DECLARE_CALLBACK(void, onEndReceive, ()); + DECLARE_CALLBACK(void, onDNSResolved,()); + DECLARE_CALLBACK(void, onDNSFailed, ()); + DECLARE_CALLBACK(void, onConnected, ()); + DECLARE_CALLBACK(void, onConnectFailed, ()); + DECLARE_CALLBACK(void, onDisconnect, ()); private: NetSocket mTag; @@ -81,7 +81,10 @@ class TCPObject : public SimObject void connect(const char *address); void listen(U16 port); void disconnect(); - State getState() { return mState; } + State getState() + { + return mState; + } bool processArguments(S32 argc, ConsoleValueRef *argv); void send(const U8 *buffer, U32 bufferLen); @@ -94,7 +97,10 @@ class TCPObject : public SimObject void addToTable(NetSocket newTag); void removeFromTable(); - void setPort(U16 port) { mPort = port; } + void setPort(U16 port) + { + mPort = port; + } bool onAdd(); diff --git a/Engine/source/app/version.cpp b/Engine/source/app/version.cpp index 7a26adb3d3..fb6c73659c 100644 --- a/Engine/source/app/version.cpp +++ b/Engine/source/app/version.cpp @@ -76,8 +76,8 @@ const char* getEngineProductString() case 0006: return "Torque 3D"; case 0007: - return "Torque 3D MIT"; - + return "Torque 3D MIT"; + default: return "Torque Engine"; }; @@ -92,45 +92,45 @@ const char* getCompileTimeString() ConsoleFunctionGroupBegin( CompileInformation, "Functions to get version information about the current executable." ); -DefineEngineFunction( getVersionNumber, S32, (), , "Get the version of the engine build, as a string.\n\n" - "@ingroup Debugging") +DefineEngineFunction( getVersionNumber, S32, (),, "Get the version of the engine build, as a string.\n\n" + "@ingroup Debugging") { return getVersionNumber(); } -DefineEngineFunction( getAppVersionNumber, S32, (), , "Get the version of the application build, as a string.\n\n" - "@ingroup Debugging") +DefineEngineFunction( getAppVersionNumber, S32, (),, "Get the version of the application build, as a string.\n\n" + "@ingroup Debugging") { return getAppVersionNumber(); } -DefineEngineFunction( getVersionString, const char*, (), , "Get the version of the engine build, as a human readable string.\n\n" - "@ingroup Debugging") +DefineEngineFunction( getVersionString, const char*, (),, "Get the version of the engine build, as a human readable string.\n\n" + "@ingroup Debugging") { return getVersionString(); } -DefineEngineFunction( getAppVersionString, const char*, (), , "Get the version of the aplication build, as a human readable string.\n\n" - "@ingroup Debugging") +DefineEngineFunction( getAppVersionString, const char*, (),, "Get the version of the aplication build, as a human readable string.\n\n" + "@ingroup Debugging") { return getAppVersionString(); } -DefineEngineFunction( getEngineName, const char*, (), , "Get the name of the engine product that this is running from, as a string.\n\n" - "@ingroup Debugging") +DefineEngineFunction( getEngineName, const char*, (),, "Get the name of the engine product that this is running from, as a string.\n\n" + "@ingroup Debugging") { return getEngineProductString(); } -DefineEngineFunction( getCompileTimeString, const char*, (), , "Get the time of compilation.\n\n" - "@ingroup Debugging") +DefineEngineFunction( getCompileTimeString, const char*, (),, "Get the time of compilation.\n\n" + "@ingroup Debugging") { return getCompileTimeString(); } -DefineEngineFunction( getBuildString, const char*, (), , "Get the type of build, \"Debug\" or \"Release\".\n\n" - "@ingroup Debugging") +DefineEngineFunction( getBuildString, const char*, (),, "Get the type of build, \"Debug\" or \"Release\".\n\n" + "@ingroup Debugging") { #ifdef TORQUE_DEBUG return "Debug";