torque Torque Game Engine Documentation
CVS Revision Label 1.3.x

NetConnection Class Reference

#include <netConnection.h>

Inheritance diagram for NetConnection:

ConnectionProtocol SimGroup SimSet SimObject ConsoleObject GameConnection AIConnection AIClient

Detailed Description

Torque network connection.

Introduction

NetConnection is the glue that binds a networked Torque game together. It combines the low-level notify protocol implemented in ConnectionProtocol with a SimGroup to provide a powerful basis for implementing a multiplayer game protocol.

On top of this basis it implements several distinct subsystems:

  • Event manager, which is responsible for transmitting NetEvents over the wire. It deals with ensuring that the various types of NetEvents are delivered appropriately, and with notifying the event of its delivery status.
  • Move manager, which is responsible for transferring a Move to the server 32 times a second (on the client) and applying it to the control object (on the server).
  • Ghost manager, which is responsible for doing scoping calculations (on the server side) and transmitting most-recent ghost information to the client.
  • File transfer; it is often the case that clients will lack important files when connecting to a server which is running a mod or new map. This subsystem allows the server to transfer such files to the client.
  • Networked String Table; string data can easily soak up network bandwidth, so for efficiency, we implement a networked string table. We can then notify the connection of strings we will reference often, such as player names, and transmit only a tag, instead of the whole string.
  • Demo Recording is also implemented in NetConnection. A demo in Torque is a log of the network traffic between client and server; when a NetConnection records a demo, it simply logs this data to a file. When it plays a demo back, it replays the logged data.
  • The Connection Database is used to keep track of all the NetConnections; it can be iterated over (for instance, to send an event to all active connections), or queried by address.

On Events

The Event Manager is exposed to the outside world via postNetEvent(), which accepts NetEvents.

See also:
NetEvent for a more thorough explanation of how to use events.

On Ghosting and Scoping

Ghosting is the most complex, and most powerful, part of Torque's networking capabilities. It allows the information sent to clients to be very precisely matched to what they need, so that no excess bandwidth is wasted. The control object's onCameraScopeQuery() is called, to determine scoping information for the client; then objects which are in scope are then transmitted to the client, prioritized by the results of their getPriority() method.

There is a cap on the maximum number of ghosts; ghost IDs are currently sent via a 10-bit field, ergo, there is a cap of 1024 objects ghosted per client. This can be easily raised; see the GhostConstants enum.

Each object ghosted is assigned a ghost ID; the client is _only_ aware of the ghost ID. This acts to enhance game security, as it becomes difficult to map objects from one connection to another, or to reliably identify objects from ID alone. IDs are also reassigned based on need, making it hard to track objects that have fallen out of scope (as any object which the player shouldn't see would).

resolveGhost() is used on the client side, and resolveObjectFromGhostIndex() on the server side, to turn ghost IDs into object references.

The NetConnection is a SimGroup. On the client side, it contains all the objects which have been ghosted to that client. On the server side, it is empty; it can be used (typically in script) to hold objects related to the connection. For instance, you might place an observation camera in the NetConnnection. In both cases, when the connection is destroyed, so are the contained objects.

See also:
NetObject, which is the superclass for ghostable objects, and ShapeBase, which is the base for player and vehicle classes.


Ghost manager

enum  GhostConstants {
  GhostIdBitSize = 12,
  MaxGhostCount = 1 << GhostIdBitSize,
  GhostLookupTableSize = 1 << GhostIdBitSize,
  GhostIndexBitSize = 4
}
 Some configuration values. More...
U32 getGhostsActive ()
bool isGhostingTo ()
 Are we ghosting to someone?
bool isGhostingFrom ()
 Are we ghosting from someone?
void ghostOnRemove ()
 Called by onRemove, to shut down the ghost subsystem.
virtual void doneScopingScene ()
 Called when we're done with normal scoping.
void setScopeObject (NetObject *object)
 Set the object around which we are currently scoping network traffic.
NetObjectgetScopeObject ()
 Get the object aorund which we are currently scoping network traffic.
void objectInScope (NetObject *object)
 Add an object to scope.
void objectLocalScopeAlways (NetObject *object)
 Add an object to scope, marking that it should always be scoped to this connection.
void objectLocalClearAlways (NetObject *object)
 Mark an object that is being ghosted as not always needing to be scoped.
NetObjectresolveGhost (S32 id)
 Get a NetObject* from a ghost ID (on client side).
NetObjectresolveObjectFromGhostIndex (S32 id)
 Get a NetObject* from a ghost index (on the server side).
S32 getGhostIndex (NetObject *object)
 Get the ghost index corresponding to a given NetObject.
void ghostPushNonZero (GhostInfo *gi)
 Move a GhostInfo into the nonzero portion of the list (so that we know to update it).
void ghostPushToZero (GhostInfo *gi)
 Move a GhostInfo into the zero portion of the list (so that we know not to update it).
void ghostPushZeroToFree (GhostInfo *gi)
 Move a GhostInfo from the zero portion of the list to the free portion.
void ghostPushFreeToZero (GhostInfo *info)
 Move a GhostInfo from the free portion of the list to the zero portion.
void resetGhosting ()
 Stop all ghosting activity and inform the other side about this.
void activateGhosting ()
 Activate ghosting, once it's enabled.
bool isGhosting ()
 Are we ghosting?
void detachObject (GhostInfo *info)
 Begin to stop ghosting an object.
void setGhostAlwaysObject (NetObject *object, U32 index)
 Mark an object to be always ghosted. Index is the ghost index of the object.
void sendConnectionMessage (U32 message, U32 sequence=0, U32 ghostCount=0)
 Send ghost connection handshake message.
virtual void handleConnectionMessage (U32 message, U32 sequence, U32 ghostCount)
 Handle message from sendConnectionMessage().
enum  GhostStates {
  GhostAlwaysDone,
  ReadyForNormalGhosts,
  EndGhosting,
  GhostAlwaysStarting,
  SendNextDownloadRequest,
  FileDownloadSizeMessage,
  NumConnectionMessages
}
void clearGhostInfo ()
bool validateGhostArray ()
void ghostPacketDropped (PacketNotify *notify)
void ghostPacketReceived (PacketNotify *notify)
void ghostWritePacket (BitStream *bstream, PacketNotify *notify)
void ghostReadPacket (BitStream *bstream)
void freeGhostInfo (GhostInfo *)
void ghostWriteStartBlock (ResizeBitStream *stream)
void ghostReadStartBlock (BitStream *stream)
GhostInfo ** mGhostArray
 Linked list of ghostInfos ghosted by this side of the connection.
U32 mGhostZeroUpdateIndex
 Index in mGhostArray of first ghost with 0 update mask.
U32 mGhostFreeIndex
 Index in mGhostArray of first free ghost.
U32 mGhostsActive
bool mGhosting
 
  • Track actve ghosts on client side Am I currently ghosting objects?

bool mScoping
 am I currently scoping objects?
U32 mGhostingSequence
 Sequence number describing this ghosting session.
NetObject ** mLocalGhosts
 Local ghost for remote object.
GhostInfomGhostRefs
 Allocated array of ghostInfos. Null if ghostFrom is false.
GhostInfo ** mGhostLookupTable
 Table indexed by object id to GhostInfo. Null if ghostFrom is false.
SimObjectPtr< NetObjectmScopeObject
 The object around which we are scoping this connection.

Demo Recording

enum  DemoBlockTypes {
  BlockTypePacket,
  BlockTypeSendPacket,
  NetConnectionBlockTypeCount
}
enum  DemoConstants {
  MaxNumBlockTypes = 16,
  MaxBlockSize = 0x1000
}
bool isRecording ()
bool isPlayingBack ()
U32 getNextBlockType ()
void recordBlock (U32 type, U32 size, void *data)
virtual void handleRecordedBlock (U32 type, U32 size, void *data)
bool processNextBlock ()
bool startDemoRecord (const char *fileName)
bool replayDemoRecord (const char *fileName)
void startDemoRead ()
void stopRecording ()
void stopDemoPlayback ()
virtual void writeDemoStartBlock (ResizeBitStream *stream)
virtual bool readDemoStartBlock (BitStream *stream)
virtual void demoPlaybackComplete ()
StreammDemoWriteStream
StreammDemoReadStream
U32 mDemoNextBlockType
U32 mDemoNextBlockSize
U32 mDemoWriteStartTime
U32 mDemoReadStartTime
U32 mDemoLastWriteTime
U32 mDemoRealStartTime

Global Connection List

NetConnectiongetNext ()
static NetConnectiongetConnectionList ()
NetConnectionmNextConnection
 Next item in list.
NetConnectionmPrevConnection
 Previous item in list.
static NetConnectionmConnectionList
 Head of list.

Event Manager

bool postNetEvent (NetEvent *event)
 Post an event to this connection.
enum  NetEventConstants {
  InvalidSendEventSeq = -1,
  FirstValidSendEventSeq = 0
}
void eventOnRemove ()
void eventPacketDropped (PacketNotify *notify)
void eventPacketReceived (PacketNotify *notify)
void eventWritePacket (BitStream *bstream, PacketNotify *notify)
void eventReadPacket (BitStream *bstream)
void eventWriteStartBlock (ResizeBitStream *stream)
void eventReadStartBlock (BitStream *stream)
NetEventNotemSendEventQueueHead
NetEventNotemSendEventQueueTail
NetEventNotemUnorderedSendEventQueueHead
NetEventNotemUnorderedSendEventQueueTail
NetEventNotemWaitSeqEvents
NetEventNotemNotifyEventList
bool mSendingEvents
S32 mNextSendEventSeq
S32 mNextRecvEventSeq
S32 mLastAckedEventSeq
static FreeListChunker< NetEventNotemEventNoteChunker

Networked string table

void mapString (U32 netId, StringHandle &string)
U32 checkString (StringHandle &string, bool *isOnOtherSide=NULL)
U32 getNetSendId (StringHandle &string)
void confirmStringReceived (StringHandle &string, U32 index)
StringHandle translateRemoteStringId (U32 id)
void validateSendString (const char *str)
void packString (BitStream *stream, const char *str)
void unpackString (BitStream *stream, char readBuffer[1024])
void packStringHandleU (BitStream *stream, StringHandle &h)
StringHandle unpackStringHandleU (BitStream *stream)
bool mTranslateStrings
ConnectionStringTablemStringTable

File transfer

bool startSendingFile (const char *fileName)
 Start sending the specified file over the link.
void chunkReceived (U8 *chunkData, U32 chunkLen)
 Called when we receive a FileChunkEvent.
void sendNextFileDownloadRequest ()
 Get the next file...
void sendFileChunk ()
 Post the next FileChunkEvent.
virtual void fileDownloadSegmentComplete ()
 Called when we finish downloading file data.
void loadNextGhostAlwaysObject (bool hadNewFiles)
 This is part of the file transfer logic; basically, we call this every time we finish downloading new files.
Vector< char * > mMissingFileList
 List of files missing for this connection.
StreammCurrentDownloadingFile
 Stream for currently uploading file (if any).
voidmCurrentFileBuffer
 Storage for currently downloading file.
U32 mCurrentFileBufferSize
 Size of currently downloading file in bytes.
U32 mCurrentFileBufferOffset
 Our position in the currently downloading file in bytes.
U32 mNumDownloadedFiles
 Number of files we have downloaded.
char mLastFileErrorBuffer [256]
 Error storage for file transfers.
Vector< GhostSavemGhostAlwaysSaveList
 List of objects to ghost-always.

Statistics

U32 mLastUpdateTime
F32 mRoundTripTime
F32 mPacketLoss
U32 mSimulatedPing
F32 mSimulatedPacketLoss

State

U32 mProtocolVersion
U32 mSendDelayCredit
U32 mConnectSequence
U32 mAddressDigest [4]
bool mEstablished
bool mMissionPathsSent
NetRate mCurRate
NetRate mMaxRate
SimObjectPtr< NetConnectionmRemoteConnection
 If we're doing a "short circuited" connection, this stores a pointer to the other side.
NetAddress mNetAddress

Timeout Management

U32 mPingSendCount
U32 mPingRetryCount
U32 mLastPingSendTime

Connection Table

We store our connections on a hash table so we can quickly find them.

NetConnectionmNextTableHash
static NetConnectionmHashTable [HashTableSize]

Public Types

enum  Constants { HashTableSize = 127 }
enum  NetConnectionFlags {
  ConnectionToServer = BIT(0),
  ConnectionToClient = BIT(1),
  LocalClientConnection = BIT(2),
  NetworkConnection = BIT(3)
}
enum  NetConnectionState {
  NotConnected,
  AwaitingChallengeResponse,
  AwaitingConnectRequest,
  AwaitingConnectResponse,
  Connected
}

Public Member Functions

void sendDisconnectPacket (const char *reason)
virtual bool canRemoteCreate ()
virtual void onTimedOut ()
virtual void onConnectTimedOut ()
virtual void onDisconnect (const char *reason)
virtual void onConnectionRejected (const char *reason)
virtual void onConnectionEstablished (bool isInitiator)
virtual void handleStartupError (const char *errorString)
virtual void writeConnectRequest (BitStream *stream)
virtual bool readConnectRequest (BitStream *stream, const char **errorString)
virtual void writeConnectAccept (BitStream *stream)
virtual bool readConnectAccept (BitStream *stream, const char **errorString)
void connect (const NetAddress *address)
U32 getNetClassGroup ()
void setSimulatedNetParams (F32 packetLoss, U32 ping)
bool isServerConnection ()
bool isLocalConnection ()
bool isNetworkConnection ()
void setIsServerConnection ()
void setIsLocalClientConnection ()
void setNetworkConnection (bool net)
virtual void setEstablished ()
void setRemoteConnectionObject (NetConnection *connection)
 Call this if the "connection" is local to this app. This short-circuits the protocol layer.
void setSequence (U32 connectSequence)
void setAddressDigest (U32 digest[4])
void getAddressDigest (U32 digest[4])
U32 getSequence ()
void setProtocolVersion (U32 protocolVersion)
U32 getProtocolVersion ()
F32 getRoundTripTime ()
F32 getPacketLoss ()
void checkMaxRate ()
void handlePacket (BitStream *stream)
void processRawPacket (BitStream *stream)
void handleNotify (bool recvd)
void handleConnectionEstablished ()
void keepAlive ()
const NetAddressgetNetAddress ()
void setNetAddress (const NetAddress *address)
Net::Error sendPacket (BitStream *stream)
bool checkTimeout (U32 time)
 returns true if the connection timed out
void checkPacketSend (bool force)
bool missionPathsSent () const
void setMissionPathsSent (const bool s)
void onRemove ()
 Called when the object is removed from the sim.
 NetConnection ()
 ~NetConnection ()
void setConnectionState (U32 state)
U32 getConnectionState ()
void setGhostFrom (bool ghostFrom)
 Sets whether ghosts transmit from this side of the connection.
void setGhostTo (bool ghostTo)
 Sets whether ghosts are allowed from the other side of the connection.
void setSendingEvents (bool sending)
 Sets whether this side actually sends the events that are posted to it.
void setTranslatesStrings (bool xl)
 Sets whether this connection is capable of translating strings.
void setNetClassGroup (U32 group)
 Sets the group of NetClasses this connection traffics in.
bool isEstablished ()
 Is the connection established?
 DECLARE_CONOBJECT (NetConnection)
virtual PacketNotifyallocNotify ()
 Get a free Notify structure.

Static Public Member Functions

static NetConnectiongetServerConnection ()
static NetConnectiongetLocalClientConnection ()
static void setLocalClientConnection (NetConnection *conn)
static bool filesWereDownloaded ()
static char * getErrorBuffer ()
static void setLastError (const char *fmt,...)
static NetConnectionlookup (const NetAddress *remoteAddress)
 Find a NetConnection, if any, with the specified address.
static void consoleInit ()
 Register global constant variables and do other one-time initialization tasks in a subclass of ConsoleObject.

Data Fields

U32 mConnectionSendCount
 number of connection messages we've sent.
U32 mConnectionState
 State of the connection, from NetConnectionState.
PacketNotifymNotifyQueueHead
 Head of packet notify list.
PacketNotifymNotifyQueueTail
 Tail of packet notify list.

Static Public Attributes

static char mErrorBuffer [256]

Protected Member Functions

virtual void readPacket (BitStream *bstream)
virtual void writePacket (BitStream *bstream, PacketNotify *note)
virtual void packetReceived (PacketNotify *note)
virtual void packetDropped (PacketNotify *note)
virtual void connectionError (const char *errorString)

Protected Attributes

U32 mConnectSendCount
U32 mConnectLastSendTime

Static Protected Attributes

static SimObjectPtr< NetConnectionmServerConnection
static SimObjectPtr< NetConnectionmLocalClientConnection
static bool mFilesWereDownloaded

Private Types

typedef SimGroup Parent

Private Member Functions

void netAddressTableInsert ()
void netAddressTableRemove ()

Private Attributes

BitSet32 mTypeFlags
U32 mNetClassGroup
 The NetClassGroup of this connection.

Friends

class NetInterface

Data Structures

struct  GhostRef
 Structure to track ghost references in packets. More...
struct  GhostSave
 Structure to track ghost-always objects and their ghost indices. More...
struct  NetRate
struct  PacketNotify
 Structure to track packets and what we sent over them. More...


Member Typedef Documentation

typedef SimGroup NetConnection::Parent [private]
 

Reimplemented from SimGroup.

Reimplemented in AIClient, AIConnection, and GameConnection.


Member Enumeration Documentation

enum NetConnection::Constants
 

Enumeration values:
HashTableSize 

Reimplemented in GameConnection.

enum NetConnection::NetConnectionFlags
 

Enumeration values:
ConnectionToServer 
ConnectionToClient 
LocalClientConnection 
NetworkConnection 

enum NetConnection::NetConnectionState
 

Enumeration values:
NotConnected 
AwaitingChallengeResponse  We've sent a challenge request, awaiting the response.
AwaitingConnectRequest  We've received a challenge request and sent a challenge response.
AwaitingConnectResponse  We've received a challenge response and sent a connect request.
Connected  We've accepted a connect request, or we've received a connect response accept.

enum NetConnection::NetEventConstants [private]
 

Enumeration values:
InvalidSendEventSeq 
FirstValidSendEventSeq 

enum NetConnection::GhostStates [protected]
 

Enumeration values:
GhostAlwaysDone 
ReadyForNormalGhosts 
EndGhosting 
GhostAlwaysStarting 
SendNextDownloadRequest 
FileDownloadSizeMessage 
NumConnectionMessages 

enum NetConnection::GhostConstants
 

Some configuration values.

Enumeration values:
GhostIdBitSize 
MaxGhostCount 
GhostLookupTableSize 
GhostIndexBitSize 

enum NetConnection::DemoBlockTypes
 

Enumeration values:
BlockTypePacket 
BlockTypeSendPacket 
NetConnectionBlockTypeCount 

enum NetConnection::DemoConstants
 

Enumeration values:
MaxNumBlockTypes 
MaxBlockSize 


Constructor & Destructor Documentation

NetConnection::NetConnection  ) 
 

NetConnection::~NetConnection  ) 
 


Member Function Documentation

void NetConnection::sendDisconnectPacket const char *  reason  ) 
 

virtual bool NetConnection::canRemoteCreate  )  [virtual]
 

Reimplemented in GameConnection.

virtual void NetConnection::onTimedOut  )  [virtual]
 

Reimplemented in GameConnection.

virtual void NetConnection::onConnectTimedOut  )  [virtual]
 

Reimplemented in GameConnection.

virtual void NetConnection::onDisconnect const char *  reason  )  [virtual]
 

Reimplemented in GameConnection.

virtual void NetConnection::onConnectionRejected const char *  reason  )  [virtual]
 

Reimplemented in GameConnection.

virtual void NetConnection::onConnectionEstablished bool  isInitiator  )  [virtual]
 

Reimplemented in GameConnection.

virtual void NetConnection::handleStartupError const char *  errorString  )  [virtual]
 

Reimplemented in GameConnection.

virtual void NetConnection::writeConnectRequest BitStream stream  )  [virtual]
 

Reimplemented in GameConnection.

virtual bool NetConnection::readConnectRequest BitStream stream,
const char **  errorString
[virtual]
 

Reimplemented in GameConnection.

virtual void NetConnection::writeConnectAccept BitStream stream  )  [virtual]
 

Reimplemented in GameConnection.

virtual bool NetConnection::readConnectAccept BitStream stream,
const char **  errorString
[virtual]
 

Reimplemented in GameConnection.

void NetConnection::connect const NetAddress address  ) 
 

static NetConnection* NetConnection::getConnectionList  )  [inline, static]
 

NetConnection* NetConnection::getNext  )  [inline]
 

static NetConnection* NetConnection::getServerConnection  )  [inline, static]
 

Reimplemented in GameConnection.

static NetConnection* NetConnection::getLocalClientConnection  )  [inline, static]
 

Reimplemented in GameConnection.

static void NetConnection::setLocalClientConnection NetConnection conn  )  [inline, static]
 

U32 NetConnection::getNetClassGroup  )  [inline]
 

static bool NetConnection::filesWereDownloaded  )  [inline, static]
 

static char* NetConnection::getErrorBuffer  )  [inline, static]
 

void NetConnection::setSimulatedNetParams F32  packetLoss,
U32  ping
[inline]
 

bool NetConnection::isServerConnection  )  [inline]
 

bool NetConnection::isLocalConnection  )  [inline]
 

bool NetConnection::isNetworkConnection  )  [inline]
 

void NetConnection::setIsServerConnection  )  [inline]
 

void NetConnection::setIsLocalClientConnection  )  [inline]
 

void NetConnection::setNetworkConnection bool  net  )  [inline]
 

virtual void NetConnection::setEstablished  )  [virtual]
 

void NetConnection::setRemoteConnectionObject NetConnection connection  )  [inline]
 

Call this if the "connection" is local to this app. This short-circuits the protocol layer.

void NetConnection::setSequence U32  connectSequence  ) 
 

void NetConnection::setAddressDigest U32  digest[4]  ) 
 

void NetConnection::getAddressDigest U32  digest[4]  ) 
 

U32 NetConnection::getSequence  ) 
 

void NetConnection::setProtocolVersion U32  protocolVersion  )  [inline]
 

U32 NetConnection::getProtocolVersion