Skip to content

Instantly share code, notes, and snippets.

@Elletra
Last active November 1, 2021 06:19
Show Gist options
  • Save Elletra/01c1d0d0dfddb3beb4f3c98fa99ae275 to your computer and use it in GitHub Desktop.
Save Elletra/01c1d0d0dfddb3beb4f3c98fa99ae275 to your computer and use it in GitHub Desktop.
The main.cs file that is baked into Blockland's executable
//-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
//echo("1");
$defaultGame = "Add-Ons;config;saves";
$displayHelp = false;
//-----------------------------------------------------------------------------
// Support functions used to manage the mod string
function pushFront(%list, %token, %delim)
{
if (%list !$= "")
return %token @ %delim @ %list;
return %token;
}
function pushBack(%list, %token, %delim)
{
if (%list !$= "")
return %list @ %delim @ %token;
return %token;
}
function popFront(%list, %delim)
{
return nextToken(%list, unused, %delim);
}
//------------------------------------------------------------------------------
// Process command line arguments
$modcount = 0;
$userMods = $defaultGame;
//-----------------------------------------------------------------------------
// The displayHelp, onStart, onExit and parseArgs function are overriden
// by mod packages to get hooked into initialization and cleanup.
function onStart()
{
echo("\n--------- Initializing Base ---------");
// Load the scripts that start it all...
exec("base/client/init.cs");
exec("base/server/init.cs");
initCommon();
// Server gets loaded for all sessions, since clients
// can host in-game servers.
initServer();
serverPart2();
}
function onExit()
{
if (isObject(ServerConnection))
ServerConnection.sendDisconnectPacket();
if(isFunction("shutDown"))
shutDown();
echo("Exporting server prefs");
export("$Pref::Server::*", "config/server/prefs.cs", False);
export("$Pref::Net::PacketRateToClient", "config/server/prefs.cs", True); //true = append
export("$Pref::Net::PacketRateToServer", "config/server/prefs.cs", True);
export("$Pref::Net::PacketSize", "config/server/prefs.cs", True);
export("$Pref::Net::LagThreshold", "config/server/prefs.cs", True);
//remove server variables so they dont pollute the client prefs
deleteVariables("$Pref::Server::*");
echo("Exporting client prefs");
export("$pref::*", "config/client/prefs.cs", False);
echo("Exporting client config");
if (isObject(moveMap))
moveMap.save("config/client/config.cs", false);
}
function parseProtocol(%proto)
{
//parse protocol string
%protoLen = strLen("\"blockland:");
%protoCheck = getSubStr(%proto, 0, %protoLen);
if(%protoCheck $= "\"blockland:" ||
%protoCheck $= "blockland:/" )
{
%query = getSubStr(%proto, %protoLen, strLen(%proto) - %protoLen);
echo("Parsing protocol query: " @ %query );
%query = strReplace(%query, "\"", ""); //remove trailing quote
%query = strReplace(%query, "/", "\t"); //break with tabs for easy tokenizing
%fieldCount = getFieldCount(%query);
for(%j = 0; %j < %fieldCount; %j++)
{
%field = getField(%query, %j);
if(%field $= "")
continue;
%pos = stripos(%field, "-");
%fieldType = getSubStr(%field, 0, %pos);
%fieldData = getSubStr(%field, %pos+1, 9999);
//url decode
%fieldData = strReplace(%fieldData, "%20", " ");
switch$ (%fieldType)
{
case "gamemode":
//start a game on the given map
$GameModeArg = %fieldData;
case "place":
//load the this place id from the master server
%fieldData = mFloor(%fieldData);
$placeArg = %fieldData;
case "join":
//connect to the given IP and port
$connectArg = strReplace(%fieldData, "_", ":"); //link has _ because chrome doesn't like extra :'s
case "password":
//join with the given password
$passwordArg = %fieldData;
case "dedicated":
$Server::Dedicated = true;
enableWinConsole(true);
case "dedicatedLAN":
$Server::LAN = true;
$Server::Dedicated = true;
enableWinConsole(true);
case "port":
$portArg = %fieldData;
}
}
}
}
function parseArgs()
{
//get mac protocol argument
if(isMacintosh())
{
if(gotProtoURL())
{
%protoURL = getProtoURL();
echo("Got Macintosh protocol url: " @ %protoURL);
$Game::argv[$Game::argc] = %protoURL;
$Game::argc++;
}
}
//combine all args, resplit
// we start at 2 because 1 is the secret arg that the launcher gives us
if(getBuildString() $= "Ship")
%start = 2;
else
%start = 1;
echo("argc = " @ $Game::argc);
for ($i = %start; $i < $Game::argc ; $i++)
{
echo("argv[" @ $i @ "] = " @ $Game::argv[$i]);
%allArgs = %allArgs SPC $Game::argv[$i];
}
%allArgs = trim(%allArgs);
%wordCount = getWordCount(%allArgs);
$Game::argc = %wordCount + 1;
for(%i = 0; %i < %wordCount; %i++)
{
$Game::argv[%i + 1] = getWord(%allArgs, %i);
}
echo("Parsing command line arguments: " @ %allArgs);
for ($i = 1; $i < $Game::argc ; $i++)
{
$arg = $Game::argv[$i];
$nextArg = $Game::argv[$i+1];
$hasNextArg = $Game::argc - $i > 1;
$logModeSpecified = false;
parseProtocol($arg);
switch$ ($arg)
{
case "-dbgPort":
// we must have a next arg
$argUsed[$i]++;
if ($hasNextArg)
{
$GameDebugPort = $nextArg;
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -dbgPort <port>");
case "-dbgPassword":
// we must have a next arg
$argUsed[$i]++;
if ($hasNextArg)
{
$GameDebugPassword = $nextArg;
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -dbgPassword <password>");
case "-dbgEnable":
$GameDebugEnable = true;
$argUsed[$i]++;
case "-connect":
$argUsed[$i]++;
if ($hasNextArg)
{
// mark which server we will automatically connect to
$connectArg = $nextArg;
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -connect <x.x.x.x:port>");
case "-log":
$argUsed[$i]++;
if ($hasNextArg)
{
// Turn on console logging
if ($nextArg != 0)
{
// Dump existing console to logfile first.
$nextArg += 4;
}
setLogMode($nextArg);
$logModeSpecified = true;
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -log <Mode: 0,1,2>");
case "-console":
enableWinConsole(true);
$argUsed[$i]++;
case "-noConsole":
$NoConsole = true;
$argUsed[$i]++;
case "-jSave":
$argUsed[$i]++;
if ($hasNextArg)
{
$SavingJournal = true;
echo("Saving event log to journal: " @ $nextArg);
saveJournal($nextArg);
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -jSave <journal_name>");
case "-noJournal":
//disables auto.jrn in debug mode
$argUsed[$i]++;
$noJournal = true;
case "-jPlay":
$argUsed[$i]++;
if ($hasNextArg)
{
%playingJournal = true;
playJournal($nextArg,false);
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -jPlay <journal_name>");
case "-jDebug":
$argUsed[$i]++;
if ($hasNextArg)
{
playJournal($nextArg,true);
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -jDebug <journal_name>");
case "-help":
$displayHelp = true;
$argUsed[$i]++;
case "-dedicated":
$Server::Dedicated = true;
enableWinConsole(true);
$argUsed[$i]++;
case "-dedicatedLAN":
$Server::LAN = true;
$Server::Dedicated = true;
enableWinConsole(true);
$argUsed[$i]++;
case "-port":
$argUsed[$i]++;
if ($hasNextArg)
{
$portArg = $nextArg;
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -port <number>");
case "-gamemode":
$argUsed[$i]++;
if ($hasNextArg)
{
$GameModeArg = $nextArg;
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -gamemode <name>");
case "-quit":
$argUsed[$i]++;
$QuitAfterMissionLoad = true;
case "-dumpCRCs":
$argUsed[$i]++;
$DumpCRCValues = true;
case "-loadBLS":
$argUsed[$i]++;
if ($hasNextArg)
{
$loadBlsArg = $nextArg;
if(!isFile($loadBlsArg))
$loadBlsArg = strReplace($loadBlsArg, "_", " ");
if(!isFile($loadBlsArg))
$loadBlsArg = "";
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -loadBLS <filename>");
case "-serverName":
$argUsed[$i]++;
if ($hasNextArg)
{
$serverNameArg = $nextArg;
$serverNameArg = strReplace($serverNameArg, "_", " ");
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -serverName <name>");
case "-maxPlayers":
$argUsed[$i]++;
if ($hasNextArg)
{
$maxPlayersArg = mFloor($nextArg);
if($maxPlayersArg <= 0)
{
error("Error: -maxPlayers should be > 0");
}
$argUsed[$i+1]++;
$i++;
}
else
error("Error: Missing Command Line argument. Usage: -maxPlayers <number>");
case "-trace":
$argUsed[$i]++;
trace(1);
case "+connect_lobby":
$argUsed[$i]++;
if ($hasNextArg)
{
$steamLobbyArg = $nextArg;
echo("Got steam lobby argument: " @ $steamLobbyArg );
}
else
{
error("Error: Missing Command Line argument. Usage: +connect_lobby <64-bit lobby id>");
}
case "-steam":
$launchedFromSteam = true;
$argUsed[$i]++;
case "-nosteam":
$noSteam = true;
$argUsed[$i]++;
case "-blid":
$argUsed[$i]++;
if ($hasNextArg)
{
setMyBLID($nextArg);
$argUsed[$i+1]++;
$i++;
}
else
{
error("Error: Missing Command Line argument. Usage: -blid <number>");
}
case "-loginToken":
$argUsed[$i]++;
if ($hasNextArg)
{
setLoginToken($nextArg);
$argUsed[$i+1]++;
$i++;
}
else
{
error("Error: Missing Command Line argument. Usage: -loginToken <string>");
}
case "-noupnp":
$argUsed[$i]++;
$noUpnpArg = true;
case "-dtoken":
$argUsed[$i]++;
if ($hasNextArg)
{
setDedicatedToken($nextArg);
$argUsed[$i+1]++;
$i++;
}
else
{
error("Error: Missing Command Line argument. Usage: -dToken <string>");
}
default:
$argUsed[$i]++;
if($userMods $= "")
$userMods = $arg;
}
}
if($modcount == 0 && ($defaultGame !$= ""))
{
$userMods = $defaultGame;
$modcount = 1;
}
if(!$NoConsole)
EnableWinConsole(true);
//automatically record journal for debug
if(!%playingJournal && !$SavingJournal)
if(getBuildString() $= "Debug")
if(!$noJournal) //double negative!
saveJournal("auto.jrn");
}
// Parse the command line arguments
echo("Blockland v" @ $Version @ " build " @ getBuildNumber());
echo("Module Directory: " @ getModuleDirectory());
echo("Profile Path: " @ getProfilePath());
echo("Total Ram: " @ getTotalRam() @ " MB");
echo("OS: " @ getOSLong());
echo("");
echo("--------- Parsing Arguments ---------");
parseArgs();
package Help
{
function onExit()
{
// Override onExit when displaying help
}
};
function displayHelp()
{
activatePackage(Help);
// Notes on logmode: console logging is written to console.log.
// -log 0 disables console logging.
// -log 1 appends to existing logfile; it also closes the file
// (flushing the write buffer) after every write.
// -log 2 overwrites any existing logfile; it also only closes
// the logfile when the application shuts down. (default)
error(
"Torque Demo command line options:\n"@
" -log <logmode> Logging behavior; see main.cs comments for details\n"@
" -console Open a separate console\n"@
" -jSave <file_name> Record a journal\n"@
" -jPlay <file_name> Play back a journal\n"@
" -jDebug <file_name> Play back a journal and issue an int3 at the end\n"@
" -noJournal Disable automatic journal recording in debug mode\n"@
" -quit Automatically quit after game successfully starts\n"@
" -trace Start console trace immediately\n"@
// TorqueDebugPatcher begin
" -dbgPort <port> Set debug port (default = 28040)\n"@
" -dbgPassword <pass> Set debug password (default = password)\n"@
" -dbgEnable Start game in debug mode\n"@
// TorqueDebugPatcher end
" -dedicated Start as dedicated server\n"@
" -dedicatedLAN Start as dedicated LAN server\n"@
" -port Port for dedicated server\n"@
" -gamemode Specify a game mode to start\n"@
" -loadBLS Specify a save file to load\n"@
" -serverName \n"@
" -maxPlayers \n"@
" -connect <address> For non-dedicated: Connect to a game at <address>\n"@
" -steam Indicates that game was launched from steam\n"@
" -nosteam Don't use steam\n"@
" -help Display this help message\n"
);
}
//--------------------------------------------------------------------------
// Default to a new logfile each session.
if (!$logModeSpecified)
{
setLogMode(6);
}
// Set the mod path which dictates which directories will be visible
// to the scripts and the resource engine.
setModPaths($userMods);
// Get the first mod on the list, which will be the last to be applied... this
// does not modify the list.
nextToken($userMods, currentMod, ";");
// Execute startup scripts for each mod, starting at base and working up
function loadDir(%dir)
{
setModPaths(pushback($userMods, %dir, ";"));
exec(%dir @ "/main.cs");
}
echo("--------- Loading Common ---------");
//Added to create a single base
// Load up common script base
loadDir("base");
//setModPaths("common");
//-----------------------------------------------------------------------------
// Load up defaults console values.
// Defaults console values
exec("base/client/defaults.cs");
exec("base/server/defaults.cs");
// Preferences (overide defaults)
if(isFile("config/client/prefs.cs"))
exec("config/client/prefs.cs");
if(isFile("config/server/prefs.cs"))
exec("config/server/prefs.cs");
//christ, we need to load the add-on and music enabled/disabled settings at least once, in case player starts in game mode (without ever going to custom gui) and later wants to change to custom game mode via admin menu
if(isFile("config/server/ADD_ON_LIST.cs"))
exec("config/server/ADD_ON_LIST.cs");
else
exec("base/server/defaultAddOnList.cs");
if(isFile("config/server/musicList.cs"))
exec("config/server/musicList.cs");
else
exec("base/server/defaultMusicList.cs");
//overide servername with command line argument
if($serverNameArg !$= "")
$Server::Name = $serverNameArg;
if(mFloor($maxPlayersArg) > 0)
$Pref::Server::MaxPlayers = mFloor($maxPlayersArg);
echo("--------- Loading MODS ---------");
function loadMods(%modPath)
{
%modPath = nextToken(%modPath, token, ";");
if (%modPath !$= "")
loadMods(%modPath);
//echo(%token @ "/main.cs");
if(isFile(%token @ "/main.cs")) //badspot: we specify some "mod paths" just to have access to the directory
{
if(exec(%token @ "/main.cs") != true){
error("Error: Unable to find specified mod: " @ %token );
$modcount--;
}
}
else
{
//echo("Skipping mod: ", %token);
$modcount--;
}
}
if($modcount != 0)
{
loadMods($userMods);
echo("");
}
// Either display the help message or startup the app.
if ($displayHelp)
{
enableWinConsole(true);
displayHelp();
quit();
}
else
{
onStart();
echo("Engine initialized...");
}
// Display an error message for unused arguments
for ($i = 1; $i < $Game::argc; $i++)
{
if (!$argUsed[$i])
error("Error: Unknown command line argument: " @ $Game::argv[$i]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment