Merged Multi Player Project into main branch

git-svn-id: https://ja2svn.mooo.com/source/ja2/trunk/GameSource/ja2_v1.13/Build@2144 3b4a5df2-a311-0410-b5c6-a8a6f20db521
This commit is contained in:
lalien
2008-05-12 08:20:47 +00:00
parent c448713412
commit 3e22dce318
132 changed files with 14527 additions and 4859 deletions
File diff suppressed because it is too large Load Diff
+95
View File
@@ -0,0 +1,95 @@
#pragma once
#include "Soldier Init List.h"
#include "Merc Hiring.h"
#include "event pump.h"
extern bool is_connected;
extern bool is_connecting;
extern bool is_client;
extern bool is_server;
extern bool is_networked;
extern int PLAYER_TEAM_TIMER_SEC_PER_TICKS;
//extern char CLIENT_NUM[30];
extern int CLIENT_NUM;
extern int ENEMY_ENABLED;
extern int CREATURE_ENABLED;
extern int MILITIA_ENABLED;
extern int CIV_ENABLED;
extern int MAX_CLIENTS;
extern int SAME_MERC;
extern bool allowlaptop;
extern UINT8 netbTeam;
extern UINT8 ubID_prefix;
extern FLOAT DAMAGE_MULTIPLIER;
extern UINT16 crate_usMapPos;
//extern int INTERRUPTS;
extern int ALLOW_EQUIP;
extern INT32 MAX_MERCS;
void lockui (bool unlock);
void start_battle ( void );
void DropOffItemsInSector( UINT8 ubOrderNum );
void test_func2 ( void );
void mp_help (void);
void mp_help2 (void);
void grid_display ( void);
void send_loaded (void);
void send_donegui ( UINT8 ubResult );
UINT8 numenemyLAN( UINT8 ubSectorX, UINT8 ubSectorY );
void connect_client ( void );
void start_server (void);
void client_packet ( void );
void server_packet ( void );
void server_disconnect (void);
void client_disconnect (void);
void DialogRemoved( UINT8 ubResult );
void manual_overide(void);
void send_path ( SOLDIERTYPE *pSoldier, UINT16 sDestGridNo, UINT16 usMovementAnim, BOOLEAN fFromUI, BOOLEAN fForceRestartAnim );
void send_stance ( SOLDIERTYPE *pSoldier, UINT8 ubDesiredStance );
void send_dir ( SOLDIERTYPE *pSoldier, UINT16 usDesiredDirection );
void send_fire( SOLDIERTYPE *pSoldier, INT16 sTargetGridNo );
void send_hit( EV_S_WEAPONHIT *SWeaponHit );
void send_hire( UINT8 iNewIndex, UINT8 ubCurrentSoldier, INT16 iTotalContractLength, BOOLEAN fCopyProfileItemsOver);
void send_gui_pos(SOLDIERTYPE *pSoldier, FLOAT dNewXPos, FLOAT dNewYPos);
void send_gui_dir(SOLDIERTYPE *pSoldier, UINT16 usNewDirection);
void send_EndTurn( UINT8 ubNextTeam );
void send_AI( SOLDIERCREATE_STRUCT *pCreateStruct, UINT8 *pubID );
void send_stop (EV_S_STOP_MERC *SStopMerc);
void send_interrupt(SOLDIERTYPE *pSoldier);
BOOLEAN CheckConditionsForBattle( GROUP *pGroup ); // this comes from strategic movement.cpp
extern char client_names[4][30];
void send_settings();
void StartInterrupt( void );
+57
View File
@@ -0,0 +1,57 @@
#pragma once
//time for a new header :)
extern int readyteamreg[10];
typedef struct
{
UINT16 soldier_id;
UINT16 attacker_id;
}death_struct;
typedef struct
{
UINT16 ubID;
INT16 sGridNo;
BOOLEAN fNoAnimations;
}doors;
void send_door ( SOLDIERTYPE *pSoldier, INT16 sGridNo, BOOLEAN fNoAnimations );
void send_changestate (EV_S_CHANGESTATE * SChangeState);
void send_death( SOLDIERTYPE *pSoldier);
void send_hitstruct(EV_S_STRUCTUREHIT * SStructureHit);
void send_hitwindow(EV_S_WINDOWHIT * SWindowHit);
void send_miss(EV_S_MISS * SMiss);
void cheat_func(void);
//void start_tt(void);
void unlock (void);
void UpdateSoldierToNetwork ( SOLDIERTYPE *pSoldier );
extern BOOLEAN gfUIInterfaceSetBusy;
void kick_player (void);
void overide_turn (void);
extern bool DISABLE_MORALE;
void send_fireweapon ( EV_S_FIREWEAPON * SFireWeapon);
void end_interrupt ( BOOLEAN fMarkInterruptOccurred );
void EndInterrupt( BOOLEAN fMarkInterruptOccurred );
void sendRT (void);
extern int numreadyteams;//for realtime
extern bool requested;
extern bool getReal;
extern UINT8 gubCheatLevel;
void startCombat(UINT8 ubStartingTeam);
extern int WEAPON_READIED_BONUS;
+83
View File
@@ -0,0 +1,83 @@
#pragma once
//this one just for structs, variables and functions used between the client and server scripts...
extern char CLIENT_NAME[30];
typedef struct
{
UINT8 client_num;
char client_name[30];
int team;
int cl_edge;
}client_info;
typedef struct
{
int max_clients;
int same_merc;
float damage_multiplier;
INT16 gsMercArriveSectorX;
INT16 gsMercArriveSectorY;
int ENEMY_ENABLED;
int CREATURE_ENABLED;
int MILITIA_ENABLED;
int CIV_ENABLED;
int gsPLAYER_BSIDE;
INT32 secs_per_tick;
INT32 starting_balance;
bool soDis_Bobby;
bool soDis_Equip;
BOOLEAN sofGunNut;
UINT8 soubGameStyle;
UINT8 soubDifficultyLevel;
BOOLEAN sofTurnTimeLimit;
BOOLEAN sofIronManMode;
UINT8 soubBobbyRay;
BOOLEAN sofNewInv; // WANNE - MP: New inventory
INT32 gsMAX_MERCS;
UINT8 client_num;
char client_name[30];
char client_names[4][30];
//int cl_ops[4];
int team;
int TESTING;
char kitbag[100];
bool emorale;
int gsREPORT_NAME;
int cl_edge;
float TIME;
int WEAPON_READIED_BONUS;
} settings_struct;
//typedef struct
//{
// int clnum;
// UINT8 ubid;
//}ovh_struct;
//
//typedef struct
//{
// UINT8 ubid;
//}adv;
typedef struct
{
BOOLEAN fMarkInterruptOccurred;
INT8 bteam;
UINT8 ubid;
}endINT;
typedef struct
{
INT8 bteam;
}real_struct;
typedef struct
{
UINT8 ubStartingTeam;
}sc_struct;
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
// Fuck it, GCC won't compile with exports. Someone else can fix this if they want
#if defined(_WIN32) && !(defined(__GNUC__) || defined(__GCCXML__)) && !defined(_RAKNET_LIB) && defined(_RAKNET_DLL)
#define RAK_DLL_EXPORT __declspec(dllexport)
#else
#define RAK_DLL_EXPORT
#endif
+212
View File
@@ -0,0 +1,212 @@
/// \file
/// \brief All the message identifiers used by RakNet. Message identifiers comprise the first byte of any message.
///
/// This file is part of RakNet Copyright 2003 Kevin Jenkins.
///
/// Usage of RakNet is subject to the appropriate license agreement.
/// Creative Commons Licensees are subject to the
/// license found at
/// http://creativecommons.org/licenses/by-nc/2.5/
/// Single application licensees are subject to the license found at
/// http://www.rakkarsoft.com/SingleApplicationLicense.html
/// Custom license users are subject to the terms therein.
/// GPL license users are subject to the GNU General Public
/// License as published by the Free
/// Software Foundation; either version 2 of the License, or (at your
/// option) any later version.
#ifndef __MESSAGE_IDENTIFIERS_H
#define __MESSAGE_IDENTIFIERS_H
/// You should not edit the file MessageIdentifiers.h as it is a part of RakNet static library
/// To define your own message id, define an enum following the code example that follows.
///
/// \code
/// enum {
/// ID_MYPROJECT_MSG_1 = ID_USER_PACKET_ENUM,
/// ID_MYPROJECT_MSG_2,
/// ...
/// };
/// \endcode
///
/// \note All these enumerations should be casted to (unsigned char) before writing them to RakNet::BitStream
enum
{
//
// RESERVED TYPES - DO NOT CHANGE THESE
// All types from RakPeer
//
/// These types are never returned to the user.
/// Ping from a connected system. Update timestamps (internal use only)
ID_INTERNAL_PING,
/// Ping from an unconnected system. Reply but do not update timestamps. (internal use only)
ID_PING,
/// Ping from an unconnected system. Only reply if we have open connections. Do not update timestamps. (internal use only)
ID_PING_OPEN_CONNECTIONS,
/// Pong from a connected system. Update timestamps (internal use only)
ID_CONNECTED_PONG,
/// Asking for a new connection (internal use only)
ID_CONNECTION_REQUEST,
/// Connecting to a secured server/peer (internal use only)
ID_SECURED_CONNECTION_RESPONSE,
/// Connecting to a secured server/peer (internal use only)
ID_SECURED_CONNECTION_CONFIRMATION,
/// Packet that tells us the packet contains an integer ID to name mapping for the remote system (internal use only)
ID_RPC_MAPPING,
/// A reliable packet to detect lost connections (internal use only)
ID_DETECT_LOST_CONNECTIONS,
/// Offline message so we know when to reset and start a new connection (internal use only)
ID_OPEN_CONNECTION_REQUEST,
/// Offline message response so we know when to reset and start a new connection (internal use only)
ID_OPEN_CONNECTION_REPLY,
/// Remote procedure call (internal use only)
ID_RPC,
/// Remote procedure call reply, for RPCs that return data (internal use only)
ID_RPC_REPLY,
//
// USER TYPES - DO NOT CHANGE THESE
//
/// RakPeer - In a client/server environment, our connection request to the server has been accepted.
ID_CONNECTION_REQUEST_ACCEPTED,
/// RakPeer - Sent to the player when a connection request cannot be completed due to inability to connect.
ID_CONNECTION_ATTEMPT_FAILED,
/// RakPeer - Sent a connect request to a system we are currently connected to.
ID_ALREADY_CONNECTED,
/// RakPeer - A remote system has successfully connected.
ID_NEW_INCOMING_CONNECTION,
/// RakPeer - The system we attempted to connect to is not accepting new connections.
ID_NO_FREE_INCOMING_CONNECTIONS,
/// RakPeer - The system specified in Packet::systemAddress has disconnected from us. For the client, this would mean the server has shutdown.
ID_DISCONNECTION_NOTIFICATION,
/// RakPeer - Reliable packets cannot be delivered to the system specified in Packet::systemAddress. The connection to that system has been closed.
ID_CONNECTION_LOST,
/// RakPeer - We preset an RSA public key which does not match what the system we connected to is using.
ID_RSA_PUBLIC_KEY_MISMATCH,
/// RakPeer - We are banned from the system we attempted to connect to.
ID_CONNECTION_BANNED,
/// RakPeer - The remote system is using a password and has refused our connection because we did not set the correct password.
ID_INVALID_PASSWORD,
/// RakPeer - A packet has been tampered with in transit. The sender is contained in Packet::systemAddress.
ID_MODIFIED_PACKET,
/// RakPeer - The four bytes following this byte represent an unsigned int which is automatically modified by the difference in system times between the sender and the recipient. Requires that you call SetOccasionalPing.
ID_TIMESTAMP,
/// RakPeer - Pong from an unconnected system. First byte is ID_PONG, second sizeof(RakNetTime) bytes is the ping, following bytes is system specific enumeration data.
ID_PONG,
/// RakPeer - Inform a remote system of our IP/Port, plus some offline data
ID_ADVERTISE_SYSTEM,
/// ConnectionGraph plugin - In a client/server environment, a client other than ourselves has disconnected gracefully. Packet::systemAddress is modified to reflect the systemAddress of this client.
ID_REMOTE_DISCONNECTION_NOTIFICATION,
/// ConnectionGraph plugin - In a client/server environment, a client other than ourselves has been forcefully dropped. Packet::systemAddress is modified to reflect the systemAddress of this client.
ID_REMOTE_CONNECTION_LOST,
/// ConnectionGraph plugin - In a client/server environment, a client other than ourselves has connected. Packet::systemAddress is modified to reflect the systemAddress of this client.
ID_REMOTE_NEW_INCOMING_CONNECTION,
// RakPeer - Downloading a large message. Format is ID_DOWNLOAD_PROGRESS (MessageID), partCount (unsigned int), partTotal (unsigned int), partLength (unsigned int), first part data (length <= MAX_MTU_SIZE)
ID_DOWNLOAD_PROGRESS,
/// FileListTransfer plugin - Setup data
ID_FILE_LIST_TRANSFER_HEADER,
/// FileListTransfer plugin - A file
ID_FILE_LIST_TRANSFER_FILE,
/// DirectoryDeltaTransfer plugin - Request from a remote system for a download of a directory
ID_DDT_DOWNLOAD_REQUEST,
/// RakNetTransport plugin - Transport provider message, used for remote console
ID_TRANSPORT_STRING,
/// ReplicaManager plugin - Create an object
ID_REPLICA_MANAGER_CONSTRUCTION,
/// ReplicaManager plugin - Destroy an object
ID_REPLICA_MANAGER_DESTRUCTION,
/// ReplicaManager plugin - Changed scope of an object
ID_REPLICA_MANAGER_SCOPE_CHANGE,
/// ReplicaManager plugin - Serialized data of an object
ID_REPLICA_MANAGER_SERIALIZE,
/// ReplicaManager plugin - Finished downloading all serialized objects
ID_REPLICA_MANAGER_DOWNLOAD_COMPLETE,
/// ConnectionGraph plugin - Request the connection graph from another system
ID_CONNECTION_GRAPH_REQUEST,
/// ConnectionGraph plugin - Reply to a connection graph download request
ID_CONNECTION_GRAPH_REPLY,
/// ConnectionGraph plugin - Update edges / nodes for a system with a connection graph
ID_CONNECTION_GRAPH_UPDATE,
/// ConnectionGraph plugin - Add a new connection to a connection graph
ID_CONNECTION_GRAPH_NEW_CONNECTION,
/// ConnectionGraph plugin - Remove a connection from a connection graph - connection was abruptly lost
ID_CONNECTION_GRAPH_CONNECTION_LOST,
/// ConnectionGraph plugin - Remove a connection from a connection graph - connection was gracefully lost
ID_CONNECTION_GRAPH_DISCONNECTION_NOTIFICATION,
/// Router plugin - route a message through another system
ID_ROUTE_AND_MULTICAST,
/// RakVoice plugin - Open a communication channel
ID_RAKVOICE_OPEN_CHANNEL_REQUEST,
/// RakVoice plugin - Communication channel accepted
ID_RAKVOICE_OPEN_CHANNEL_REPLY,
/// RakVoice plugin - Close a communication channel
ID_RAKVOICE_CLOSE_CHANNEL,
/// RakVoice plugin - Voice data
ID_RAKVOICE_DATA,
/// Autopatcher plugin - Get a list of files that have changed since a certain date
ID_AUTOPATCHER_GET_CHANGELIST_SINCE_DATE,
/// Autopatcher plugin - A list of files to create
ID_AUTOPATCHER_CREATION_LIST,
/// Autopatcher plugin - A list of files to delete
ID_AUTOPATCHER_DELETION_LIST,
/// Autopatcher plugin - A list of files to get patches for
ID_AUTOPATCHER_GET_PATCH,
/// Autopatcher plugin - A list of patches for a list of files
ID_AUTOPATCHER_PATCH_LIST,
/// Autopatcher plugin - Returned to the user: An error from the database repository for the autopatcher.
ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR,
/// Autopatcher plugin - Finished getting all files from the autopatcher
ID_AUTOPATCHER_FINISHED_INTERNAL,
ID_AUTOPATCHER_FINISHED,
/// Autopatcher plugin - Returned to the user: You must restart the application to finish patching.
ID_AUTOPATCHER_RESTART_APPLICATION,
/// NATPunchthrough plugin - Intermediary got a request to help punch through a nat
ID_NAT_PUNCHTHROUGH_REQUEST,
/// NATPunchthrough plugin - Intermediary cannot complete the request because the target system is not connected
ID_NAT_TARGET_NOT_CONNECTED,
/// NATPunchthrough plugin - While attempting to connect, we lost the connection to the target system
ID_NAT_TARGET_CONNECTION_LOST,
/// NATPunchthrough plugin - Internal message to connect at a certain time
ID_NAT_CONNECT_AT_TIME,
/// NATPunchthrough plugin - Internal message to send a message (to punch through the nat) at a certain time
ID_NAT_SEND_OFFLINE_MESSAGE_AT_TIME,
/// LightweightDatabase plugin - Query
ID_DATABASE_QUERY_REQUEST,
/// LightweightDatabase plugin - Update
ID_DATABASE_UPDATE_ROW,
/// LightweightDatabase plugin - Remove
ID_DATABASE_REMOVE_ROW,
/// LightweightDatabase plugin - A serialized table. Bytes 1+ contain the table. Pass to TableSerializer::DeserializeTable
ID_DATABASE_QUERY_REPLY,
/// LightweightDatabase plugin - Specified table not found
ID_DATABASE_UNKNOWN_TABLE,
/// LightweightDatabase plugin - Incorrect password
ID_DATABASE_INCORRECT_PASSWORD,
/// ReadyEvent plugin - Set the ready state for a particular system
ID_READY_EVENT_SET,
/// ReadyEvent plugin - Unset the ready state for a particular system
ID_READY_EVENT_UNSET,
/// All systems are in state ID_READY_EVENT_SET
ID_READY_EVENT_ALL_SET,
/// ReadyEvent plugin - Request of ready event state - used for pulling data when newly connecting
ID_READY_EVENT_QUERY,
// For the user to use. Start your first enumeration at this value.
ID_USER_PACKET_ENUM,
//-------------------------------------------------------------------------------------------------------------
};
#endif
+42
View File
@@ -0,0 +1,42 @@
/// \file
/// \brief This file contains enumerations for packet priority and reliability enumerations.
///
/// This file is part of RakNet Copyright 2003 Kevin Jenkins.
///
/// Usage of RakNet is subject to the appropriate license agreement.
/// Creative Commons Licensees are subject to the
/// license found at
/// http://creativecommons.org/licenses/by-nc/2.5/
/// Single application licensees are subject to the license found at
/// http://www.rakkarsoft.com/SingleApplicationLicense.html
/// Custom license users are subject to the terms therein.
/// GPL license users are subject to the GNU General Public
/// License as published by the Free
/// Software Foundation; either version 2 of the License, or (at your
/// option) any later version.
#ifndef __PACKET_PRIORITY_H
#define __PACKET_PRIORITY_H
/// These enumerations are used to describe when packets are delivered.
enum PacketPriority
{
SYSTEM_PRIORITY, /// \internal Used by RakNet to send above-high priority messages.
HIGH_PRIORITY, /// High priority messages are send before medium priority messages.
MEDIUM_PRIORITY, /// Medium priority messages are send before low priority messages.
LOW_PRIORITY, /// Low priority messages are only sent when no other messages are waiting.
NUMBER_OF_PRIORITIES
};
/// These enumerations are used to describe how packets are delivered.
/// \note Note to self: I write this with 3 bits in the stream. If I add more remember to change that
enum PacketReliability
{
UNRELIABLE, /// Same as regular UDP, except that it will also discard duplicate datagrams. RakNet adds (6 to 17) + 21 bits of overhead, 16 of which is used to detect duplicate packets and 6 to 17 of which is used for message length.
UNRELIABLE_SEQUENCED, /// Regular UDP with a sequence counter. Out of order messages will be discarded. This adds an additional 13 bits on top what is used for UNRELIABLE.
RELIABLE, /// The message is sent reliably, but not necessarily in any order. Same overhead as UNRELIABLE.
RELIABLE_ORDERED, /// This message is reliable and will arrive in the order you sent it. Messages will be delayed while waiting for out of order messages. Same overhead as UNRELIABLE_SEQUENCED.
RELIABLE_SEQUENCED /// This message is reliable and will arrive in the sequence you sent it. Out or order messages will be dropped. Same overhead as UNRELIABLE_SEQUENCED.
};
#endif
+30
View File
@@ -0,0 +1,30 @@
/// Define __GET_TIME_64BIT to have RakNetTime use a 64, rather than 32 bit value. A 32 bit value will overflow after about 5 weeks.
/// However, this doubles the bandwidth use for sending times, so don't do it unless you have a reason to.
/// Disabled by default.
// #define __GET_TIME_64BIT
/// Makes RakNet threadsafe
/// Define this if you use the same instance of RakPeer from multiple threads
/// Otherwise leave it undefined, since it makes things an order of magnitude slower.
/// Disabled by default
// #define _RAKNET_THREADSAFE
/// Define __BITSTREAM_NATIVE_END to NOT support endian swapping in the BitStream class. This is faster and is what you should use
/// unless you actually plan to have different endianness systems connect to each other
/// Enabled by default.
#define __BITSTREAM_NATIVE_END
#if defined(_CONSOLE_2)
#undef __BITSTREAM_NATIVE_END
#endif
/// Maximum (stack) size to use with _alloca before using new and delete instead.
#define MAX_ALLOCA_STACK_ALLOCATION 1048576
// Use WaitForSingleObject instead of sleep.
// Defining it plays nicer with other systems, and uses less CPU, but gives worse RakNet performance
// Undefining it uses more CPU time, but is more responsive and faster.
#define USE_WAIT_FOR_MULTIPLE_EVENTS
// If you need it
#define RAKNET_VERSION "3.0 09/07/07"
Binary file not shown.
Binary file not shown.
Binary file not shown.
+172
View File
@@ -0,0 +1,172 @@
/// \file
/// \brief A structure that holds all statistical data returned by RakNet.
///
/// This file is part of RakNet Copyright 2003 Kevin Jenkins.
///
/// Usage of RakNet is subject to the appropriate license agreement.
/// Creative Commons Licensees are subject to the
/// license found at
/// http://creativecommons.org/licenses/by-nc/2.5/
/// Single application licensees are subject to the license found at
/// http://www.rakkarsoft.com/SingleApplicationLicense.html
/// Custom license users are subject to the terms therein.
/// GPL license users are subject to the GNU General Public
/// License as published by the Free
/// Software Foundation; either version 2 of the License, or (at your
/// option) any later version.
#ifndef __RAK_NET_STATISTICS_H
#define __RAK_NET_STATISTICS_H
#include "PacketPriority.h"
#include "Export.h"
#include "RakNetTypes.h"
/// \brief Network Statisics Usage
///
/// Store Statistics information related to network usage
struct RAK_DLL_EXPORT RakNetStatistics
{
/// Number of Messages in the send Buffer (high, medium, low priority)
unsigned messageSendBuffer[ NUMBER_OF_PRIORITIES ];
/// Number of messages sent (high, medium, low priority)
unsigned messagesSent[ NUMBER_OF_PRIORITIES ];
/// Number of data bits used for user messages
unsigned messageDataBitsSent[ NUMBER_OF_PRIORITIES ];
/// Number of total bits used for user messages, including headers
unsigned messageTotalBitsSent[ NUMBER_OF_PRIORITIES ];
/// Number of packets sent containing only acknowledgements
unsigned packetsContainingOnlyAcknowlegements;
/// Number of acknowledgements sent
unsigned acknowlegementsSent;
/// Number of acknowledgements waiting to be sent
unsigned acknowlegementsPending;
/// Number of acknowledgements bits sent
unsigned acknowlegementBitsSent;
/// Number of packets containing only acknowledgements and resends
unsigned packetsContainingOnlyAcknowlegementsAndResends;
/// Number of messages resent
unsigned messageResends;
/// Number of bits resent of actual data
unsigned messageDataBitsResent;
/// Total number of bits resent, including headers
unsigned messagesTotalBitsResent;
/// Number of messages waiting for ack (// TODO - rename this)
unsigned messagesOnResendQueue;
/// Number of messages not split for sending
unsigned numberOfUnsplitMessages;
/// Number of messages split for sending
unsigned numberOfSplitMessages;
/// Total number of splits done for sending
unsigned totalSplits;
/// Total packets sent
unsigned packetsSent;
/// Number of bits added by encryption
unsigned encryptionBitsSent;
/// total bits sent
unsigned totalBitsSent;
/// Number of sequenced messages arrived out of order
unsigned sequencedMessagesOutOfOrder;
/// Number of sequenced messages arrived in order
unsigned sequencedMessagesInOrder;
/// Number of ordered messages arrived out of order
unsigned orderedMessagesOutOfOrder;
/// Number of ordered messages arrived in order
unsigned orderedMessagesInOrder;
/// Packets with a good CRC received
unsigned packetsReceived;
/// Packets with a bad CRC received
unsigned packetsWithBadCRCReceived;
/// Bits with a good CRC received
unsigned bitsReceived;
/// Bits with a bad CRC received
unsigned bitsWithBadCRCReceived;
/// Number of acknowledgement messages received for packets we are resending
unsigned acknowlegementsReceived;
/// Number of acknowledgement messages received for packets we are not resending
unsigned duplicateAcknowlegementsReceived;
/// Number of data messages (anything other than an ack) received that are valid and not duplicate
unsigned messagesReceived;
/// Number of data messages (anything other than an ack) received that are invalid
unsigned invalidMessagesReceived;
/// Number of data messages (anything other than an ack) received that are duplicate
unsigned duplicateMessagesReceived;
/// Number of messages waiting for reassembly
unsigned messagesWaitingForReassembly;
/// Number of messages in reliability output queue
unsigned internalOutputQueueSize;
/// Current bits per second
double bitsPerSecond;
/// connection start time
RakNetTime connectionStartTime;
// If true, not all the data can go out in one frame, and RakNet is sending continuously
// RakNet will try to increase the bandwidth, so this condition may be temporary and only last a second. However, it if
// stays on most of the time, you are at the maximum bandwidth and should slow down your sends, because other data is now waiting.
bool bandwidthExceeded;
RakNetStatistics operator +=(const RakNetStatistics& other)
{
unsigned i;
for (i=0; i < NUMBER_OF_PRIORITIES; i++)
{
messageSendBuffer[i]+=other.messageSendBuffer[i];
messagesSent[i]+=other.messagesSent[i];
messageDataBitsSent[i]+=other.messageDataBitsSent[i];
messageTotalBitsSent[i]+=other.messageTotalBitsSent[i];
}
packetsContainingOnlyAcknowlegements+=other.packetsContainingOnlyAcknowlegements;
acknowlegementsSent+=other.packetsContainingOnlyAcknowlegements;
acknowlegementsPending+=other.acknowlegementsPending;
acknowlegementBitsSent+=other.acknowlegementBitsSent;
packetsContainingOnlyAcknowlegementsAndResends+=other.packetsContainingOnlyAcknowlegementsAndResends;
messageResends+=other.messageResends;
messageDataBitsResent+=other.messageDataBitsResent;
messagesTotalBitsResent+=other.messagesTotalBitsResent;
messagesOnResendQueue+=other.messagesOnResendQueue;
numberOfUnsplitMessages+=other.numberOfUnsplitMessages;
numberOfSplitMessages+=other.numberOfSplitMessages;
totalSplits+=other.totalSplits;
packetsSent+=other.packetsSent;
encryptionBitsSent+=other.encryptionBitsSent;
totalBitsSent+=other.totalBitsSent;
sequencedMessagesOutOfOrder+=other.sequencedMessagesOutOfOrder;
sequencedMessagesInOrder+=other.sequencedMessagesInOrder;
orderedMessagesOutOfOrder+=other.orderedMessagesOutOfOrder;
orderedMessagesInOrder+=other.orderedMessagesInOrder;
packetsReceived+=other.packetsReceived;
packetsWithBadCRCReceived+=other.packetsWithBadCRCReceived;
bitsReceived+=other.bitsReceived;
bitsWithBadCRCReceived+=other.bitsWithBadCRCReceived;
acknowlegementsReceived+=other.acknowlegementsReceived;
duplicateAcknowlegementsReceived+=other.duplicateAcknowlegementsReceived;
messagesReceived+=other.messagesReceived;
invalidMessagesReceived+=other.invalidMessagesReceived;
duplicateMessagesReceived+=other.duplicateMessagesReceived;
messagesWaitingForReassembly+=other.messagesWaitingForReassembly;
internalOutputQueueSize+=other.internalOutputQueueSize;
return *this;
}
};
/// Verbosity level currently supports 0 (low), 1 (medium), 2 (high)
/// \param[in] s The Statistical information to format out
/// \param[in] buffer The buffer containing a formated report
/// \param[in] verbosityLevel
/// 0 low
/// 1 medium
/// 2 high
void RAK_DLL_EXPORT StatisticsToString( RakNetStatistics *s, char *buffer, int verbosityLevel );
#endif
+273
View File
@@ -0,0 +1,273 @@
/// \file
/// \brief Types used by RakNet, most of which involve user code.
///
/// This file is part of RakNet Copyright 2003 Kevin Jenkins.
///
/// Usage of RakNet is subject to the appropriate license agreement.
/// Creative Commons Licensees are subject to the
/// license found at
/// http://creativecommons.org/licenses/by-nc/2.5/
/// Single application licensees are subject to the license found at
/// http://www.rakkarsoft.com/SingleApplicationLicense.html
/// Custom license users are subject to the terms therein.
/// GPL license users are subject to the GNU General Public
/// License as published by the Free
/// Software Foundation; either version 2 of the License, or (at your
/// option) any later version.
#ifndef __NETWORK_TYPES_H
#define __NETWORK_TYPES_H
#include "RakNetDefines.h"
#include "Export.h"
/// Forward declaration
namespace RakNet
{
class BitStream;
};
/// Given a number of bits, return how many bytes are needed to represent that.
#define BITS_TO_BYTES(x) (((x)+7)>>3)
#define BYTES_TO_BITS(x) ((x)<<3)
/// \sa NetworkIDObject.h
typedef unsigned char UniqueIDType;
typedef unsigned short SystemIndex;
typedef unsigned char RPCIndex;
const int MAX_RPC_MAP_SIZE=((RPCIndex)-1)-1;
const int UNDEFINED_RPC_INDEX=((RPCIndex)-1);
/// First byte of a network message
typedef unsigned char MessageID;
// Define __GET_TIME_64BIT if you want to use large types for GetTime (takes more bandwidth when you transmit time though!)
// You would want to do this if your system is going to run long enough to overflow the millisecond counter (over a month)
#ifdef __GET_TIME_64BIT
typedef long long RakNetTime;
typedef long long RakNetTimeNS;
#else
typedef unsigned int RakNetTime;
typedef long long RakNetTimeNS;
#endif
/// Describes the local socket to use for RakPeer::Startup
struct RAK_DLL_EXPORT SocketDescriptor
{
SocketDescriptor();
SocketDescriptor(unsigned short _port, const char *_hostAddress);
/// The local port to bind to. Pass 0 to have the OS autoassign a port.
unsigned short port;
/// The local network card address to bind to, such as "127.0.0.1". Pass an empty string to use INADDR_ANY.
char hostAddress[32];
};
/// \brief Unique identifier for a system.
/// Corresponds to a network address
struct RAK_DLL_EXPORT SystemAddress
{
///The peer address from inet_addr.
unsigned int binaryAddress;
///The port number
unsigned short port;
// Return the systemAddress as a string in the format <IP>:<Port>
// Note - returns a static string. Not thread-safe or safe for multiple calls per line.
char *ToString(bool writePort=true) const;
// Sets the binary address part from a string. Doesn't set the port
void SetBinaryAddress(const char *str);
SystemAddress& operator = ( const SystemAddress& input )
{
binaryAddress = input.binaryAddress;
port = input.port;
return *this;
}
bool operator==( const SystemAddress& right ) const;
bool operator!=( const SystemAddress& right ) const;
bool operator > ( const SystemAddress& right ) const;
bool operator < ( const SystemAddress& right ) const;
};
struct RAK_DLL_EXPORT NetworkID
{
// Set this to true to use peer to peer mode for NetworkIDs.
// Obviously the value of this must match on all systems.
// True, and this will write the systemAddress portion with network sends. Takes more bandwidth, but NetworkIDs can be locally generated
// False, and only localSystemAddress is used.
static bool peerToPeerMode;
// In peer to peer, we use both systemAddress and localSystemAddress
// In client / server, we only use localSystemAddress
SystemAddress systemAddress;
unsigned short localSystemAddress;
NetworkID& operator = ( const NetworkID& input );
static bool IsPeerToPeerMode(void);
static void SetPeerToPeerMode(bool isPeerToPeer);
bool operator==( const NetworkID& right ) const;
bool operator!=( const NetworkID& right ) const;
bool operator > ( const NetworkID& right ) const;
bool operator < ( const NetworkID& right ) const;
};
/// Size of SystemAddress data
#define SystemAddress_Size 6
/// This represents a user message from another system.
struct Packet
{
/// Server only - this is the index into the player array that this systemAddress maps to
SystemIndex systemIndex;
/// The system that send this packet.
SystemAddress systemAddress;
/// The length of the data in bytes
/// \deprecated You should use bitSize.
unsigned int length;
/// The length of the data in bits
unsigned int bitSize;
/// The data from the sender
unsigned char* data;
/// @internal
/// Indicates whether to delete the data, or to simply delete the packet.
bool deleteData;
};
class RakPeerInterface;
/// All RPC functions have the same parameter list - this structure.
struct RPCParameters
{
/// The data from the remote system
unsigned char *input;
/// How many bits long \a input is
unsigned int numberOfBitsOfData;
/// Which system called this RPC
SystemAddress sender;
/// Which instance of RakPeer (or a derived RakPeer or RakPeer) got this call
RakPeerInterface *recipient;
RakNetTime remoteTimestamp;
/// The name of the function that was called.
char *functionName;
/// You can return values from RPC calls by writing them to this BitStream.
/// This is only sent back if the RPC call originally passed a BitStream to receive the reply.
/// If you do so and your send is reliable, it will block until you get a reply or you get disconnected from the system you are sending to, whichever is first.
/// If your send is not reliable, it will block for triple the ping time, or until you are disconnected, or you get a reply, whichever is first.
RakNet::BitStream *replyToSender;
};
/// Index of an unassigned player
const SystemIndex UNASSIGNED_PLAYER_INDEX = 65535;
/// Index of an invalid SystemAddress
const SystemAddress UNASSIGNED_SYSTEM_ADDRESS =
{
0xFFFFFFFF, 0xFFFF
};
/// Unassigned object ID
const NetworkID UNASSIGNED_NETWORK_ID =
{
{0xFFFFFFFF, 0xFFFF}, 65535
};
const int PING_TIMES_ARRAY_SIZE = 5;
/// \brief RPC Function Implementation
///
/// The Remote Procedure Call Subsystem provide the RPC paradigm to
/// RakNet user. It consists in providing remote function call over the
/// network. A call to a remote function require you to prepare the
/// data for each parameter (using BitStream) for example.
///
/// Use the following C function prototype for your callbacks
/// @code
/// void functionName(RPCParameters *rpcParms);
/// @endcode
/// If you pass input data, you can parse the input data in two ways.
/// 1.
/// Cast input to a struct (such as if you sent a struct)
/// i.e. MyStruct *s = (MyStruct*) input;
/// Make sure that the sizeof(MyStruct) is equal to the number of bytes passed!
/// 2.
/// Create a BitStream instance with input as data and the number of bytes
/// i.e. BitStream myBitStream(input, (numberOfBitsOfData-1)/8+1)
/// (numberOfBitsOfData-1)/8+1 is how convert from bits to bytes
/// Full example:
/// @code
/// void MyFunc(RPCParameters *rpcParms) {}
/// RakPeer *rakClient;
/// REGISTER_AS_REMOTE_PROCEDURE_CALL(rakClient, MyFunc);
/// This would allow MyFunc to be called from the server using (for example)
/// rakServer->RPC("MyFunc", 0, clientID, false);
/// @endcode
/// \def REGISTER_STATIC_RPC
/// \ingroup RAKNET_RPC
/// Register a C function as a Remote procedure.
/// \param[in] networkObject Your instance of RakPeer, RakPeer, or RakPeer
/// \param[in] functionName The name of the C function to call
/// \attention 12/01/05 REGISTER_AS_REMOTE_PROCEDURE_CALL renamed to REGISTER_STATIC_RPC. Delete the old name sometime in the future
//#pragma deprecated(REGISTER_AS_REMOTE_PROCEDURE_CALL)
//#define REGISTER_AS_REMOTE_PROCEDURE_CALL(networkObject, functionName) REGISTER_STATIC_RPC(networkObject, functionName)
#define REGISTER_STATIC_RPC(networkObject, functionName) (networkObject)->RegisterAsRemoteProcedureCall((#functionName),(functionName))
/// \def CLASS_MEMBER_ID
/// \ingroup RAKNET_RPC
/// \brief Concatenate two strings
/// \def REGISTER_CLASS_MEMBER_RPC
/// \ingroup RAKNET_RPC
/// \brief Register a member function of an instantiated object as a Remote procedure call.
/// RPC member Functions MUST be marked __cdecl!
/// \sa ObjectMemberRPC.cpp
/// \b CLASS_MEMBER_ID is a utility macro to generate a unique signature for a class and function pair and can be used for the Raknet functions RegisterClassMemberRPC(...) and RPC(...)
/// \b REGISTER_CLASS_MEMBER_RPC is a utility macro to more easily call RegisterClassMemberRPC
/// \param[in] networkObject Your instance of RakPeer, RakPeer, or RakPeer
/// \param[in] className The class containing the function
/// \param[in] functionName The name of the function (not in quotes, just the name)
#define CLASS_MEMBER_ID(className, functionName) #className "_" #functionName
#define REGISTER_CLASS_MEMBER_RPC(networkObject, className, functionName) {union {void (__cdecl className::*cFunc)( RPCParameters *rpcParms ); void* voidFunc;}; cFunc=&className::functionName; networkObject->RegisterClassMemberRPC(CLASS_MEMBER_ID(className, functionName),voidFunc);}
/// \def UNREGISTER_AS_REMOTE_PROCEDURE_CALL
/// \depreciated
/// \brief Only calls UNREGISTER_STATIC_RPC
/// \def UNREGISTER_STATIC_RPC
/// \ingroup RAKNET_RPC
/// Unregisters a remote procedure call
/// RPC member Functions MUST be marked __cdecl! See the ObjectMemberRPC example.
/// \param[in] networkObject The object that manages the function
/// \param[in] functionName The function name
// 12/01/05 UNREGISTER_AS_REMOTE_PROCEDURE_CALL Renamed to UNREGISTER_STATIC_RPC. Delete the old name sometime in the future
//#pragma deprecated(UNREGISTER_AS_REMOTE_PROCEDURE_CALL)
//#define UNREGISTER_AS_REMOTE_PROCEDURE_CALL(networkObject,functionName) UNREGISTER_STATIC_RPC(networkObject,functionName)
#define UNREGISTER_STATIC_RPC(networkObject,functionName) (networkObject)->UnregisterAsRemoteProcedureCall((#functionName))
/// \def UNREGISTER_CLASS_INST_RPC
/// \ingroup RAKNET_RPC
/// \brief Unregisters a member function of an instantiated object as a Remote procedure call.
/// \param[in] networkObject The object that manages the function
/// \param[in] className The className that was originally passed to REGISTER_AS_REMOTE_PROCEDURE_CALL
/// \param[in] functionName The function name
#define UNREGISTER_CLASS_MEMBER_RPC(networkObject, className, functionName) (networkObject)->UnregisterAsRemoteProcedureCall((#className "_" #functionName))
#endif
+71
View File
@@ -0,0 +1,71 @@
/// \file
/// \brief Factory class for RakNet objects
///
/// This file is part of RakNet Copyright 2003 Kevin Jenkins.
///
/// Usage of RakNet is subject to the appropriate license agreement.
/// Creative Commons Licensees are subject to the
/// license found at
/// http://creativecommons.org/licenses/by-nc/2.5/
/// Single application licensees are subject to the license found at
/// http://www.rakkarsoft.com/SingleApplicationLicense.html
/// Custom license users are subject to the terms therein.
/// GPL license users are subject to the GNU General Public
/// License as published by the Free
/// Software Foundation; either version 2 of the License, or (at your
/// option) any later version.
#ifndef __RAK_NETWORK_FACTORY_H
#define __RAK_NETWORK_FACTORY_H
#include "Export.h"
class RakPeerInterface;
class ConsoleServer;
class ReplicaManager;
class LogCommandParser;
class PacketLogger;
class RakNetCommandParser;
class RakNetTransport;
class TelnetTransport;
class PacketConsoleLogger;
class PacketFileLogger;
class Router;
class ConnectionGraph;
class RAK_DLL_EXPORT RakNetworkFactory
{
public:
// For DLL's, these are user classes that you might want to new and delete.
// You can't instantiate exported classes directly in your program. The instantiation
// has to take place inside the DLL. So these functions will do the news and deletes for you.
// if you're using the source or static library you don't need these functions, but can use them if you want.
static RakPeerInterface* GetRakPeerInterface( void );
static ConsoleServer* GetConsoleServer( void );
static ReplicaManager* GetReplicaManager( void );
static LogCommandParser* GetLogCommandParser( void );
static PacketLogger* GetPacketLogger( void );
static RakNetCommandParser* GetRakNetCommandParser( void );
static RakNetTransport* GetRakNetTransport( void );
static TelnetTransport* GetTelnetTransport( void );
static PacketConsoleLogger* GetPacketConsoleLogger( void );
static PacketFileLogger* GetPacketFileLogger( void );
static Router* GetRouter( void );
static ConnectionGraph* GetConnectionGraph( void );
// To delete the object returned by the Get functions above.
static void DestroyRakPeerInterface( RakPeerInterface* i );
static void DestroyConsoleServer( ConsoleServer* i);
static void DestroyReplicaManager( ReplicaManager* i);
static void DestroyLogCommandParser( LogCommandParser* i);
static void DestroyPacketLogger( PacketLogger* i);
static void DestroyRakNetCommandParser( RakNetCommandParser* i );
static void DestroyRakNetTransport( RakNetTransport* i );
static void DestroyTelnetTransport( TelnetTransport* i );
static void DestroyPacketConsoleLogger( PacketConsoleLogger* i );
static void DestroyPacketFileLogger( PacketFileLogger* i );
static void DestroyRouter( Router* i );
static void DestroyConnectionGraph( ConnectionGraph* i );
};
#endif
+488
View File
@@ -0,0 +1,488 @@
/// \file
/// \brief An interface for RakPeer. Simply contains all user functions as pure virtuals.
///
/// This file is part of RakNet Copyright 2003 Kevin Jenkins.
///
/// Usage of RakNet is subject to the appropriate license agreement.
/// Creative Commons Licensees are subject to the
/// license found at
/// http://creativecommons.org/licenses/by-nc/2.5/
/// Single application licensees are subject to the license found at
/// http://www.rakkarsoft.com/SingleApplicationLicense.html
/// Custom license users are subject to the terms therein.
/// GPL license users are subject to the GNU General Public
/// License as published by the Free
/// Software Foundation; either version 2 of the License, or (at your
/// option) any later version.
#ifndef __RAK_PEER_INTERFACE_H
#define __RAK_PEER_INTERFACE_H
#include "PacketPriority.h"
#include "RakNetTypes.h"
#include "Export.h"
// Forward declarations
namespace RakNet
{
class BitStream;
}
class PluginInterface;
struct RPCMap;
struct RakNetStatistics;
class RouterInterface;
class NetworkIDManager;
/// The primary interface for RakNet, RakPeer contains all major functions for the library.
/// See the individual functions for what the class can do.
/// \brief The main interface for network communications
class RAK_DLL_EXPORT RakPeerInterface
{
public:
///Destructor
virtual ~RakPeerInterface() {}
// --------------------------------------------------------------------------------------------Major Low Level Functions - Functions needed by most users--------------------------------------------------------------------------------------------
/// \brief Starts the network threads, opens the listen port.
/// You must call this before calling Connect().
/// Multiple calls while already active are ignored. To call this function again with different settings, you must first call Shutdown().
/// \note Call SetMaximumIncomingConnections if you want to accept incoming connections
/// \param[in] maxConnections The maximum number of connections between this instance of RakPeer and another instance of RakPeer. Required so the network can preallocate and for thread safety. A pure client would set this to 1. A pure server would set it to the number of allowed clients.- A hybrid would set it to the sum of both types of connections
/// \param[in] localPort The port to listen for connections on.
/// \param[in] _threadSleepTimer How many ms to Sleep each internal update cycle (30 to give the game priority, 0 for regular (recommended)
/// \param[in] socketDescriptors An array of SocketDescriptor structures to force RakNet to listen on a particular IP address or port (or both). Each SocketDescriptor will represent one unique socket. Do not pass redundant structures. To listen on a specific port, you can pass SocketDescriptor(myPort,0); such as for a server. For a client, it is usually OK to just pass SocketDescriptor();
/// \param[in] socketDescriptorCount The size of the \a socketDescriptors array. Pass 1 if you are not sure what to pass.
/// \return False on failure (can't create socket or thread), true on success.
virtual bool Startup( unsigned short maxConnections, int _threadSleepTimer, SocketDescriptor *socketDescriptors, unsigned socketDescriptorCount )=0;
/// Secures connections though a combination of SHA1, AES128, SYN Cookies, and RSA to prevent connection spoofing, replay attacks, data eavesdropping, packet tampering, and MitM attacks.
/// There is a significant amount of processing and a slight amount of bandwidth overhead for this feature.
/// If you accept connections, you must call this or else secure connections will not be enabled for incoming connections.
/// If you are connecting to another system, you can call this with values for the (e and p,q) public keys before connecting to prevent MitM
/// \pre Must be called while offline
/// \param[in] pubKeyE A pointer to the public keys from the RSACrypt class.
/// \param[in] pubKeyN A pointer to the public keys from the RSACrypt class.
/// \param[in] privKeyP Public key generated from the RSACrypt class.
/// \param[in] privKeyQ Public key generated from the RSACrypt class. If the private keys are 0, then a new key will be generated when this function is called@see the Encryption sample
virtual void InitializeSecurity(const char *pubKeyE, const char *pubKeyN, const char *privKeyP, const char *privKeyQ )=0;
/// Disables all security.
/// \note Must be called while offline
virtual void DisableSecurity( void )=0;
/// Sets how many incoming connections are allowed. If this is less than the number of players currently connected,
/// no more players will be allowed to connect. If this is greater than the maximum number of peers allowed,
/// it will be reduced to the maximum number of peers allowed. Defaults to 0.
/// \param[in] numberAllowed Maximum number of incoming connections allowed.
virtual void SetMaximumIncomingConnections( unsigned short numberAllowed )=0;
/// Returns the value passed to SetMaximumIncomingConnections()
/// \return the maximum number of incoming connections, which is always <= maxConnections
virtual unsigned short GetMaximumIncomingConnections( void ) const=0;
/// Returns how many open connections there are at this time
/// \return the number of open connections
virtual unsigned short NumberOfConnections(void) const=0;
/// Sets the password incoming connections must match in the call to Connect (defaults to none). Pass 0 to passwordData to specify no password
/// This is a way to set a low level password for all incoming connections. To selectively reject connections, implement your own scheme using CloseConnection() to remove unwanted connections
/// \param[in] passwordData A data block that incoming connections must match. This can be just a password, or can be a stream of data. Specify 0 for no password data
/// \param[in] passwordDataLength The length in bytes of passwordData
virtual void SetIncomingPassword( const char* passwordData, int passwordDataLength )=0;
/// Gets the password passed to SetIncomingPassword
/// \param[out] passwordData Should point to a block large enough to hold the password data you passed to SetIncomingPassword()
/// \param[in,out] passwordDataLength Maximum size of the array passwordData. Modified to hold the number of bytes actually written
virtual void GetIncomingPassword( char* passwordData, int *passwordDataLength )=0;
/// \brief Connect to the specified host (ip or domain name) and server port.
/// Calling Connect and not calling SetMaximumIncomingConnections acts as a dedicated client.
/// Calling both acts as a true peer. This is a non-blocking connection.
/// You know the connection is successful when IsConnected() returns true or Receive() gets a message with the type identifier ID_CONNECTION_ACCEPTED.
/// If the connection is not successful, such as a rejected connection or no response then neither of these things will happen.
/// \pre Requires that you first call Initialize
/// \param[in] host Either a dotted IP address or a domain name
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password.
/// \param[in] passwordDataLength The length in bytes of passwordData
/// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on.
/// \return True on successful initiation. False on incorrect parameters, internal error, or too many existing peers. Returning true does not mean you connected!
virtual bool Connect( const char* host, unsigned short remotePort, const char *passwordData, int passwordDataLength, unsigned connectionSocketIndex=0 )=0;
/// \brief Connect to the specified network ID (Platform specific console function)
/// Does built-in NAt traversal
/// \param[in] passwordData A data block that must match the data block on the server passed to SetIncomingPassword. This can be a string or can be a stream of data. Use 0 for no password.
/// \param[in] passwordDataLength The length in bytes of passwordData
virtual bool Console2Connect( void *networkServiceId, const char *passwordData, int passwordDataLength )=0;
/// \brief Stops the network threads and closes all connections.
/// \param[in] blockDuration How long, in milliseconds, you should wait for all remaining messages to go out, including ID_DISCONNECTION_NOTIFICATION. If 0, it doesn't wait at all.
/// \param[in] orderingChannel If blockDuration > 0, ID_DISCONNECTION_NOTIFICATION will be sent on this channel
/// If you set it to 0 then the disconnection notification won't be sent
virtual void Shutdown( unsigned int blockDuration, unsigned char orderingChannel=0 )=0;
/// Returns if the network thread is running
/// \return true if the network thread is running, false otherwise
virtual bool IsActive( void ) const=0;
/// Fills the array remoteSystems with the SystemAddress of all the systems we are connected to
/// \param[out] remoteSystems An array of SystemAddress structures to be filled with the SystemAddresss of the systems we are connected to. Pass 0 to remoteSystems to only get the number of systems we are connected to
/// \param[in, out] numberOfSystems As input, the size of remoteSystems array. As output, the number of elements put into the array
virtual bool GetConnectionList( SystemAddress *remoteSystems, unsigned short *numberOfSystems ) const=0;
/// Sends a block of data to the specified system that you are connected to.
/// This function only works while the connected
/// \param[in] data The block of data to send
/// \param[in] length The size in bytes of the data to send
/// \param[in] priority What priority level to send on. See PacketPriority.h
/// \param[in] reliability How reliability to send this data. See PacketPriority.h
/// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream
/// \param[in] systemAddress Who to send this packet to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to.
/// \return False if we are not connected to the specified recipient. True otherwise
virtual bool Send( const char *data, const int length, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast )=0;
/// Sends a block of data to the specified system that you are connected to. Same as the above version, but takes a BitStream as input.
/// \param[in] bitStream The bitstream to send
/// \param[in] priority What priority level to send on. See PacketPriority.h
/// \param[in] reliability How reliability to send this data. See PacketPriority.h
/// \param[in] orderingChannel When using ordered or sequenced messages, what channel to order these on. Messages are only ordered relative to other messages on the same stream
/// \param[in] systemAddress Who to send this packet to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to.
/// \return False if we are not connected to the specified recipient. True otherwise
virtual bool Send( const RakNet::BitStream * bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast )=0;
/// Gets a message from the incoming message queue.
/// Use DeallocatePacket() to deallocate the message after you are done with it.
/// User-thread functions, such as RPC calls and the plugin function PluginInterface::Update occur here.
/// \return 0 if no packets are waiting to be handled, otherwise a pointer to a packet.
/// sa RakNetTypes.h contains struct Packet
virtual Packet* Receive( void )=0;
/// Call this to deallocate a message returned by Receive() when you are done handling it.
/// \param[in] packet The message to deallocate.
virtual void DeallocatePacket( Packet *packet )=0;
/// Return the total number of connections we are allowed
// TODO - rename for RakNet 3.0
virtual unsigned short GetMaximumNumberOfPeers( void ) const=0;
// --------------------------------------------------------------------------------------------Remote Procedure Call Functions - Functions to initialize and perform RPC--------------------------------------------------------------------------------------------
/// \ingroup RAKNET_RPC
/// Register a C or static member function as available for calling as a remote procedure call
/// \param[in] uniqueID A null-terminated unique string to identify this procedure. See RegisterClassMemberRPC() for class member functions.
/// \param[in] functionPointer(...) The name of the function to be used as a function pointer. This can be called whether active or not, and registered functions stay registered unless unregistered
virtual void RegisterAsRemoteProcedureCall( const char* uniqueID, void ( *functionPointer ) ( RPCParameters *rpcParms ) )=0;
/// \ingroup RAKNET_RPC
/// Register a C++ member function as available for calling as a remote procedure call.
/// \param[in] uniqueID A null terminated string to identify this procedure. Recommended you use the macro REGISTER_CLASS_MEMBER_RPC to create the string. Use RegisterAsRemoteProcedureCall() for static functions.
/// \param[in] functionPointer The name of the function to be used as a function pointer. This can be called whether active or not, and registered functions stay registered unless unregistered with UnregisterAsRemoteProcedureCall
/// \sa The sample ObjectMemberRPC.cpp
virtual void RegisterClassMemberRPC( const char* uniqueID, void *functionPointer )=0;
/// \ingroup RAKNET_RPC
/// Unregisters a C function as available for calling as a remote procedure call that was formerly registered with RegisterAsRemoteProcedureCall. Only call offline.
/// \param[in] uniqueID A string of only letters to identify this procedure. Recommended you use the macro CLASS_MEMBER_ID for class member functions.
virtual void UnregisterAsRemoteProcedureCall( const char* uniqueID )=0;
/// \ingroup RAKNET_RPC
/// Used by Object member RPC to lookup objects given that object's ID
/// Also used by the ReplicaManager plugin
/// \param[in] An instance of NetworkIDManager to use for the lookup.
virtual void SetNetworkIDManager( NetworkIDManager *manager )=0;
/// \return Returns the value passed to SetNetworkIDManager or 0 if never called.
virtual NetworkIDManager *GetNetworkIDManager(void) const=0;
/// \ingroup RAKNET_RPC
/// Calls a C function on the remote system that was already registered using RegisterAsRemoteProcedureCall().
/// \param[in] uniqueID A NULL terminated string identifying the function to call. Recommended you use the macro CLASS_MEMBER_ID for class member functions.
/// \param[in] data The data to send
/// \param[in] bitLength The number of bits of \a data
/// \param[in] priority What priority level to send on. See PacketPriority.h.
/// \param[in] reliability How reliability to send this data. See PacketPriority.h.
/// \param[in] orderingChannel When using ordered or sequenced message, what channel to order these on.
/// \param[in] systemAddress Who to send this message to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to.
/// \param[in] includedTimestamp Pass a timestamp if you wish, to be adjusted in the usual fashion as per ID_TIMESTAMP. Pass 0 to not include a timestamp.
/// \param[in] networkID For static functions, pass UNASSIGNED_NETWORK_ID. For member functions, you must derive from NetworkIDObject and pass the value returned by NetworkIDObject::GetNetworkID for that object.
/// \param[in] replyFromTarget If 0, this function is non-blocking. Otherwise it will block while waiting for a reply from the target procedure, which should be remotely written to RPCParameters::replyToSender and copied to replyFromTarget. The block will return early on disconnect or if the sent packet is unreliable and more than 3X the ping has elapsed.
/// \return True on a successful packet send (this does not indicate the recipient performed the call), false on failure
virtual bool RPC( const char* uniqueID, const char *data, unsigned int bitLength, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, RakNetTime *includedTimestamp, NetworkID networkID, RakNet::BitStream *replyFromTarget )=0;
/// \ingroup RAKNET_RPC
/// Calls a C function on the remote system that was already registered using RegisterAsRemoteProcedureCall.
/// If you want that function to return data you should call RPC from that system in the same wayReturns true on a successful packet
/// send (this does not indicate the recipient performed the call), false on failure
/// \param[in] uniqueID A NULL terminated string identifying the function to call. Recommended you use the macro CLASS_MEMBER_ID for class member functions.
/// \param[in] data The data to send
/// \param[in] bitLength The number of bits of \a data
/// \param[in] priority What priority level to send on. See PacketPriority.h.
/// \param[in] reliability How reliability to send this data. See PacketPriority.h.
/// \param[in] orderingChannel When using ordered or sequenced message, what channel to order these on.
/// \param[in] systemAddress Who to send this message to, or in the case of broadcasting who not to send it to. Use UNASSIGNED_SYSTEM_ADDRESS to specify none
/// \param[in] broadcast True to send this packet to all connected systems. If true, then systemAddress specifies who not to send the packet to.
/// \param[in] includedTimestamp Pass a timestamp if you wish, to be adjusted in the usual fashion as per ID_TIMESTAMP. Pass 0 to not include a timestamp.
/// \param[in] networkID For static functions, pass UNASSIGNED_NETWORK_ID. For member functions, you must derive from NetworkIDObject and pass the value returned by NetworkIDObject::GetNetworkID for that object.
/// \param[in] replyFromTarget If 0, this function is non-blocking. Otherwise it will block while waiting for a reply from the target procedure, which should be remotely written to RPCParameters::replyToSender and copied to replyFromTarget. The block will return early on disconnect or if the sent packet is unreliable and more than 3X the ping has elapsed.
/// \return True on a successful packet send (this does not indicate the recipient performed the call), false on failure
virtual bool RPC( const char* uniqueID, const RakNet::BitStream *bitStream, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, RakNetTime *includedTimestamp, NetworkID networkID, RakNet::BitStream *replyFromTarget )=0;
// -------------------------------------------------------------------------------------------- Connection Management Functions--------------------------------------------------------------------------------------------
/// Close the connection to another host (if we initiated the connection it will disconnect, if they did it will kick them out).
/// \param[in] target Which system to close the connection to.
/// \param[in] sendDisconnectionNotification True to send ID_DISCONNECTION_NOTIFICATION to the recipient. False to close it silently.
/// \param[in] channel Which ordering channel to send the disconnection notification on, if any
virtual void CloseConnection( const SystemAddress target, bool sendDisconnectionNotification, unsigned char orderingChannel=0 )=0;
/// Returns if a particular systemAddress is connected to us
/// \param[in] systemAddress The SystemAddress we are referring to
/// \return True if this system is connected and active, false otherwise.
virtual bool IsConnected(const SystemAddress systemAddress)=0;
/// Given a systemAddress, returns an index from 0 to the maximum number of players allowed - 1.
/// \param[in] systemAddress The SystemAddress we are referring to
/// \return The index of this SystemAddress or -1 on system not found.
virtual int GetIndexFromSystemAddress( const SystemAddress systemAddress )=0;
/// This function is only useful for looping through all systems
/// Given an index, will return a SystemAddress.
/// \param[in] index Index should range between 0 and the maximum number of players allowed - 1.
/// \return The SystemAddress
virtual SystemAddress GetSystemAddressFromIndex( int index )=0;
/// Bans an IP from connecting. Banned IPs persist between connections but are not saved on shutdown nor loaded on startup.
/// param[in] IP Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will ban all IP addresses starting with 128.0.0
/// \param[in] milliseconds how many ms for a temporary ban. Use 0 for a permanent ban
virtual void AddToBanList( const char *IP, RakNetTime milliseconds=0 )=0;
/// Allows a previously banned IP to connect.
/// param[in] Dotted IP address. Can use * as a wildcard, such as 128.0.0.* will banAll IP addresses starting with 128.0.0
virtual void RemoveFromBanList( const char *IP )=0;
/// Allows all previously banned IPs to connect.
virtual void ClearBanList( void )=0;
/// Returns true or false indicating if a particular IP is banned.
/// \param[in] IP - Dotted IP address.
/// \return true if IP matches any IPs in the ban list, accounting for any wildcards. False otherwise.
virtual bool IsBanned( const char *IP )=0;
// --------------------------------------------------------------------------------------------Pinging Functions - Functions dealing with the automatic ping mechanism--------------------------------------------------------------------------------------------
/// Send a ping to the specified connected system.
/// \pre The sender and recipient must already be started via a successful call to Startup()
/// \param[in] target Which system to ping
virtual void Ping( const SystemAddress target )=0;
/// Send a ping to the specified unconnected system. The remote system, if it is Initialized, will respond with ID_PONG followed by sizeof(RakNetTime) containing the system time the ping was sent.(Default is 4 bytes - See __GET_TIME_64BIT in RakNetTypes.h
/// \param[in] host Either a dotted IP address or a domain name. Can be 255.255.255.255 for LAN broadcast.
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[in] onlyReplyOnAcceptingConnections Only request a reply if the remote system is accepting connections
/// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on.
virtual void Ping( const char* host, unsigned short remotePort, bool onlyReplyOnAcceptingConnections, unsigned connectionSocketIndex=0 )=0;
/// Returns the average of all ping times read for the specific system or -1 if none read yet
/// \param[in] systemAddress Which system we are referring to
/// \return The ping time for this system, or -1
virtual int GetAveragePing( const SystemAddress systemAddress )=0;
/// Returns the last ping time read for the specific system or -1 if none read yet
/// \param[in] systemAddress Which system we are referring to
/// \return The last ping time for this system, or -1
virtual int GetLastPing( const SystemAddress systemAddress ) const=0;
/// Returns the lowest ping time read or -1 if none read yet
/// \param[in] systemAddress Which system we are referring to
/// \return The lowest ping time for this system, or -1
virtual int GetLowestPing( const SystemAddress systemAddress ) const=0;
/// Ping the remote systems every so often, or not. This is off by default. Can be called anytime.
/// \param[in] doPing True to start occasional pings. False to stop them.
virtual void SetOccasionalPing( bool doPing )=0;
// --------------------------------------------------------------------------------------------Static Data Functions - Functions dealing with API defined synchronized memory--------------------------------------------------------------------------------------------
/// Sets the data to send along with a LAN server discovery or offline ping reply.
/// \a length should be under 400 bytes, as a security measure against flood attacks
/// \param[in] data a block of data to store, or 0 for none
/// \param[in] length The length of data in bytes, or 0 for none
/// \sa Ping.cpp
virtual void SetOfflinePingResponse( const char *data, const unsigned int length )=0;
//--------------------------------------------------------------------------------------------Network Functions - Functions dealing with the network in general--------------------------------------------------------------------------------------------
/// Return the unique address identifier that represents you on the the network and is based on your local IP / port.
/// \return the identifier of your system internally, which may not be how other systems see if you if you are behind a NAT or proxy
virtual SystemAddress GetInternalID( const SystemAddress systemAddress=UNASSIGNED_SYSTEM_ADDRESS ) const=0;
/// Return the unique address identifier that represents you on the the network and is based on your externalIP / port
/// (the IP / port the specified player uses to communicate with you)
/// \param[in] target Which remote system you are referring to for your external ID. Usually the same for all systems, unless you have two or more network cards.
virtual SystemAddress GetExternalID( const SystemAddress target ) const=0;
/// Set the time, in MS, to use before considering ourselves disconnected after not being able to deliver a reliable message.
/// Default time is 10,000 or 10 seconds in release and 30,000 or 30 seconds in debug.
/// \param[in] timeMS Time, in MS
/// \param[in] target Which system to do this for
virtual void SetTimeoutTime( RakNetTime timeMS, const SystemAddress target )=0;
/// Set the MTU per datagram. It's important to set this correctly - otherwise packets will be needlessly split, decreasing performance and throughput.
/// Maximum allowed size is MAXIMUM_MTU_SIZE.
/// Too high of a value will cause packets not to arrive at worst and be fragmented at best.
/// Too low of a value will split packets unnecessarily.
/// Recommended size is 1500
/// sa MTUSize.h
/// \param[in] size The MTU size
/// \pre Can only be called when not connected.
/// \return false on failure (we are connected), else true
virtual bool SetMTUSize( int size )=0;
/// Returns the current MTU size
/// \param[in] target Which system to get this for. UNASSIGNED_SYSTEM_ADDRESS to get the default
/// \return The current MTU size
virtual int GetMTUSize( const SystemAddress target ) const=0;
/// Returns the number of IP addresses this system has internally. Get the actual addresses from GetLocalIP()
virtual unsigned GetNumberOfAddresses( void )=0;
/// Returns an IP address at index 0 to GetNumberOfAddresses-1
virtual const char* GetLocalIP( unsigned int index )=0;
/// Allow or disallow connection responses from any IP. Normally this should be false, but may be necessary
/// when connecting to servers with multiple IP addresses.
/// \param[in] allow - True to allow this behavior, false to not allow. Defaults to false. Value persists between connections
virtual void AllowConnectionResponseIPMigration( bool allow )=0;
/// Sends a one byte message ID_ADVERTISE_SYSTEM to the remote unconnected system.
/// This will tell the remote system our external IP outside the LAN along with some user data.
/// \pre The sender and recipient must already be started via a successful call to Initialize
/// \param[in] host Either a dotted IP address or a domain name
/// \param[in] remotePort Which port to connect to on the remote machine.
/// \param[in] data Optional data to append to the packet.
/// \param[in] dataLength length of data in bytes. Use 0 if no data.
/// \param[in] connectionSocketIndex Index into the array of socket descriptors passed to socketDescriptors in RakPeer::Startup() to send on.
virtual void AdvertiseSystem( const char *host, unsigned short remotePort, const char *data, int dataLength, unsigned connectionSocketIndex=0 )=0;
/// Controls how often to return ID_DOWNLOAD_PROGRESS for large message downloads.
/// ID_DOWNLOAD_PROGRESS is returned to indicate a new partial message chunk, roughly the MTU size, has arrived
/// As it can be slow or cumbersome to get this notification for every chunk, you can set the interval at which it is returned.
/// Defaults to 0 (never return this notification)
/// \param[in] interval How many messages to use as an interval
virtual void SetSplitMessageProgressInterval(int interval)=0;
/// Set how long to wait before giving up on sending an unreliable message
/// Useful if the network is clogged up.
/// Set to 0 or less to never timeout. Defaults to 0.
/// \param[in] timeoutMS How many ms to wait before simply not sending an unreliable message.
virtual void SetUnreliableTimeout(RakNetTime timeoutMS)=0;
/// Send a message to host, with the IP socket option TTL set to 1
/// This message will not reach the host, but will open the router.
/// Used for NAT-Punchthrough
virtual void SendTTL1( const char* host, unsigned short remotePort, unsigned connectionSocketIndex=0 )=0;
// --------------------------------------------------------------------------------------------Compression Functions - Functions related to the compression layer--------------------------------------------------------------------------------------------
/// Enables or disables frequency table tracking. This is required to get a frequency table, which is used in GenerateCompressionLayer()
/// This value persists between connect calls and defaults to false (no frequency tracking)
/// \pre You can call this at any time - however you SHOULD only call it when disconnected. Otherwise you will only trackpart of the values sent over the network.
/// \param[in] doCompile True to enable tracking
virtual void SetCompileFrequencyTable( bool doCompile )=0;
/// Returns the frequency of outgoing bytes into output frequency table
/// The purpose is to save to file as either a master frequency table from a sample game session for passing to
/// GenerateCompressionLayer()
/// \pre You should only call this when disconnected. Requires that you first enable data frequency tracking by calling SetCompileFrequencyTable(true)
/// \param[out] outputFrequencyTable The frequency of each corresponding byte
/// \return False (failure) if connected or if frequency table tracking is not enabled. Otherwise true (success)
virtual bool GetOutgoingFrequencyTable( unsigned int outputFrequencyTable[ 256 ] )=0;
/// This is an optional function to generate the compression layer based on the input frequency table.
/// If you want to use it you should call this twice - once with inputLayer as true and once as false.
/// The frequency table passed here with inputLayer=true should match the frequency table on the recipient with inputLayer=false.
/// Likewise, the frequency table passed here with inputLayer=false should match the frequency table on the recipient with inputLayer=true.
/// Calling this function when there is an existing layer will overwrite the old layer.
/// \pre You should only call this when disconnected
/// \param[in] inputFrequencyTable A frequency table for your data
/// \param[in] inputLayer Is this the input layer?
/// \return false (failure) if connected. Otherwise true (success)
/// \sa Compression.cpp
virtual bool GenerateCompressionLayer( unsigned int inputFrequencyTable[ 256 ], bool inputLayer )=0;
/// Delete the output or input layer as specified. This is not necessary to call and is only valuable for freeing memory.
/// \pre You should only call this when disconnected
/// \param[in] inputLayer True to mean the inputLayer, false to mean the output layer
/// \return false (failure) if connected. Otherwise true (success)
virtual bool DeleteCompressionLayer( bool inputLayer )=0;
/// Returns the compression ratio. A low compression ratio is good. Compression is for outgoing data
/// \return The compression ratio
virtual float GetCompressionRatio( void ) const=0;
///Returns the decompression ratio. A high decompression ratio is good. Decompression is for incoming data
/// \return The decompression ratio
virtual float GetDecompressionRatio( void ) const=0;
// -------------------------------------------------------------------------------------------- Plugin Functions--------------------------------------------------------------------------------------------
/// Attatches a Plugin interface to run code automatically on message receipt in the Receive call
/// \note If plugins have dependencies on each other then the order does matter - for example the router plugin should go first because it might route messages for other plugins
/// \param[in] messageHandler Pointer to a plugin to attach
virtual void AttachPlugin( PluginInterface *plugin )=0;
/// Detaches a Plugin interface to run code automatically on message receipt
/// \param[in] messageHandler Pointer to a plugin to detach
virtual void DetachPlugin( PluginInterface *messageHandler )=0;
// --------------------------------------------------------------------------------------------Miscellaneous Functions--------------------------------------------------------------------------------------------
/// Put a message back at the end of the receive queue in case you don't want to deal with it immediately
/// \param[in] packet The packet you want to push back.
/// \param[in] pushAtHead True to push the packet so that the next receive call returns it. False to push it at the end of the queue (obviously pushing it at the end makes the packets out of order)
virtual void PushBackPacket( Packet *packet, bool pushAtHead )=0;
/// \Internal
// \param[in] routerInterface The router to use to route messages to systems not directly connected to this system.
virtual void SetRouterInterface( RouterInterface *routerInterface )=0;
/// \Internal
// \param[in] routerInterface The router to use to route messages to systems not directly connected to this system.
virtual void RemoveRouterInterface( RouterInterface *routerInterface )=0;
/// \Returns a packet for you to write to if you want to create a Packet for some reason.
/// You can add it to the receive buffer with PushBackPacket
/// \param[in] dataSize How many bytes to allocate for the buffer
/// \return A packet you can write to
virtual Packet* AllocatePacket(unsigned dataSize)=0;
// --------------------------------------------------------------------------------------------Network Simulator Functions--------------------------------------------------------------------------------------------
/// Adds simulated ping and packet loss to the outgoing data flow.
/// To simulate bi-directional ping and packet loss, you should call this on both the sender and the recipient, with half the total ping and maxSendBPS value on each.
/// You can exclude network simulator code with the _RELEASE #define to decrease code size
/// \param[in] maxSendBPS Maximum bits per second to send. Packetloss grows linearly. 0 to disable. (CURRENTLY BROKEN - ALWAYS DISABLED)
/// \param[in] minExtraPing The minimum time to delay sends.
virtual void ApplyNetworkSimulator( double maxSendBPS, unsigned short minExtraPing, unsigned short extraPingVariance)=0;
/// Limits how much outgoing bandwidth can be sent per-connection.
/// This limit does not apply to the sum of all connections!
/// Exceeding the limit queues up outgoing traffic
/// \param[in] maxBitsPerSecond Maximum bits per second to send. Use 0 for unlimited (default). Once set, it takes effect immedately and persists until called again.
virtual void SetPerConnectionOutgoingBandwidthLimit( unsigned maxBitsPerSecond )=0;
/// Returns if you previously called ApplyNetworkSimulator
/// \return If you previously called ApplyNetworkSimulator
virtual bool IsNetworkSimulatorActive( void )=0;
// --------------------------------------------------------------------------------------------Statistical Functions - Functions dealing with API performance--------------------------------------------------------------------------------------------
/// Returns a structure containing a large set of network statistics for the specified system.
/// You can map this data to a string using the C style StatisticsToString() function
/// \param[in] systemAddress: Which connected system to get statistics for
/// \return 0 on can't find the specified system. A pointer to a set of data otherwise.
/// \sa RakNetStatistics.h
virtual RakNetStatistics * const GetStatistics( const SystemAddress systemAddress )=0;
// --------------------------------------------------------------------------------------------EVERYTHING AFTER THIS COMMENT IS FOR INTERNAL USE ONLY--------------------------------------------------------------------------------------------
/// \internal
virtual char *GetRPCString( const char *data, const unsigned int bitSize, const SystemAddress systemAddress)=0;
};
#endif
+6
View File
@@ -0,0 +1,6 @@
#ifndef __RAK_SLEEP_H
#define __RAK_SLEEP_H
void RakSleep(unsigned int ms);
#endif
Binary file not shown.
Binary file not shown.
Binary file not shown.
+677
View File
@@ -0,0 +1,677 @@
#include "MessageIdentifiers.h"
#include "RakNetworkFactory.h"
#include "RakPeerInterface.h"
#include "RakNetStatistics.h"
#include "RakNetTypes.h"
#include "BitStream.h"
#include "RakSleep.h"
#include <assert.h>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "types.h"
#include "gamesettings.h"
char kbag[100];
char net_div[30];
INT32 gsMAX_MERCS;
bool gsMORALE;
int gsREPORT_NAME;
#include "text.h"
#include "connect.h"
#include "message.h"
#include "network.h"
#include "overhead.h"
UINT16 nc; //number of open connection
UINT16 ncr; //number of ready confirmed connections
//something keep record of ready connections ..
int mercs_ready[255];
bool gsDis_Bobby;
bool gsDis_Equip;
int gsSAME_MERC;
float gsDAMAGE_MULTIPLIER;
int gsINTERRUPTS ;
int gsMAX_CLIENTS ;
int gsPLAYER_BSIDE;
int gsTESTING;
INT32 gssecs_per_tick;
INT32 gsstarting_balance;
float TIME;
int sWEAPON_READIED_BONUS;
unsigned char SGetPacketIdentifier(Packet *p);
unsigned char SpacketIdentifier;
RakPeerInterface *server;
int numreadyteams;
int readyteamreg[10];
SystemAddress blank;
typedef struct
{
SystemAddress address;
int cl_number;
}client_data;
client_data client_d[4];
// use UNASSIGNED_SYSTEM_ADDRESS instead of rpcParameters->sender to send it back to yourself (the sender)
// there is very little in here dependant on the game engine and originally started out as an independant dedicated server .exe, and could if go ther again ... hayden.
//********* RPC SECTION ************
void sendPATH(RPCParameters *rpcParameters)
{
server->RPC("recievePATH",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendSTANCE(RPCParameters *rpcParameters)
{
server->RPC("recieveSTANCE",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendDIR(RPCParameters *rpcParameters)
{
server->RPC("recieveDIR",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendFIRE(RPCParameters *rpcParameters)
{
server->RPC("recieveFIRE",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendHIT(RPCParameters *rpcParameters)
{
server->RPC("recieveHIT",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendHIRE(RPCParameters *rpcParameters)
{
server->RPC("recieveHIRE",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendguiPOS(RPCParameters *rpcParameters)
{
server->RPC("recieveguiPOS",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendguiDIR(RPCParameters *rpcParameters)
{
server->RPC("recieveguiDIR",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendEndTurn(RPCParameters *rpcParameters)
{
server->RPC("recieveEndTurn",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendAI(RPCParameters *rpcParameters)
{
server->RPC("recieveAI",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendSTOP(RPCParameters *rpcParameters)
{
server->RPC("recieveSTOP",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendINTERRUPT(RPCParameters *rpcParameters)
{
server->RPC("recieveINTERRUPT",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendREADY(RPCParameters *rpcParameters)
{
server->RPC("recieveREADY",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendGUI(RPCParameters *rpcParameters)
{
server->RPC("recieveGUI",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendBULLET(RPCParameters *rpcParameters)
{
server->RPC("recieveBULLET",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendSTATE(RPCParameters *rpcParameters)
{
server->RPC("recieveSTATE",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendDEATH(RPCParameters *rpcParameters)
{
server->RPC("recieveDEATH",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendhitSTRUCT(RPCParameters *rpcParameters)
{
server->RPC("recievehitSTRUCT",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendhitWINDOW(RPCParameters *rpcParameters)
{
server->RPC("recievehitWINDOW",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendMISS(RPCParameters *rpcParameters)
{
server->RPC("recieveMISS",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void updatenetworksoldier(RPCParameters *rpcParameters)
{
server->RPC("UpdateSoldierFromNetwork",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void Snull_team(RPCParameters *rpcParameters)
{
server->RPC("null_team",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendFIREW(RPCParameters *rpcParameters)
{
server->RPC("recieve_fireweapon",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void sendDOOR(RPCParameters *rpcParameters)
{
server->RPC("recieve_door",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void endINTERRUPT(RPCParameters *rpcParameters)
{
server->RPC("resume_turn",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, rpcParameters->sender, true, 0, UNASSIGNED_NETWORK_ID,0);
}
void startCOMBAT(RPCParameters *rpcParameters)
{
if(!( gTacticalStatus.uiFlags & INCOMBAT ))
{
gTacticalStatus.uiFlags |= INCOMBAT;
sc_struct* data = (sc_struct*)rpcParameters->input;
EndTurn( data->ubStartingTeam );
}
}
void sendREAL(RPCParameters *rpcParameters)
{
real_struct* rData = (real_struct*)rpcParameters->input;
//ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"netbTeam %d is ready for realtime",rData->bteam );//diabled unless testing as cheats
if(readyteamreg[rData->bteam]==0)
{
readyteamreg[rData->bteam]=1;//register vote, to prevent double voting ;p~ //hayden
numreadyteams++;
int numactiveteams=0;
int b;
for(int i=6;i<=LAST_TEAM;i++)
{
if(i==6)b=0;
else b=i;
if(gTacticalStatus.Team[ b ].bTeamActive)numactiveteams++;
}//same
//ScreenMsg( FONT_LTBLUE, MSG_CHAT, MPServerMessage[5], numreadyteams, numactiveteams );
//check # clients ready for realtime
if (numreadyteams >= numactiveteams)
{
//if all send notification for realtime changeover
//ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"Switching to realtime..." );
numreadyteams=0;
memset( &readyteamreg , 0 , sizeof (int) * 10);
server->RPC("gotoRT",(const char*)rpcParameters->input, (*rpcParameters).numberOfBitsOfData, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true, 0, UNASSIGNED_NETWORK_ID,0);
}
}
}
int f_rec_num(int mode, SystemAddress sender)//from client data
{
int x;
client_data cl_record;
for ( x=0; x<4;x++)
{
cl_record = client_d[x];
if(mode==0)//find empty slot for new record
{
if(cl_record.address.binaryAddress==0)
return(x);
}
if(mode==1)//wipe clean all
{
client_d[x].address.binaryAddress=0;
client_d[x].address.port=0;
client_d[x].cl_number=0;
}
if(mode==2)//clear one record
{
if(cl_record.address.binaryAddress==sender.binaryAddress && cl_record.address.port==sender.port)
{
client_d[x].address.port=0;
client_d[x].cl_number=0;
client_d[x].address.binaryAddress=0;
return(254);
}
}
}
if(mode == 0)//'no free slots'
{
ScreenMsg( FONT_RED, MSG_CHAT, L"Client Record Error, Restart Server, and Report Error." );
return (255);
}
return(254);
}
//************************* //UNASSIGNED_SYSTEM_ADDRESS
//START INTERNAL SERVER
//*************************
//void send_settings (void)//send server settings to client
void requestSETTINGS(RPCParameters *rpcParameters )
{
client_info* clinf = (client_info*)rpcParameters->input;
//server assigned client numbers - hayden.
SystemAddress sender = rpcParameters->sender;//get senders address
int bslot = f_rec_num(0,blank);//get empty record slot
client_d[bslot].address=sender; //record clients address
int new_cl_num = bslot+1;//client number to assign
client_d[bslot].cl_number=new_cl_num; //record clients number
settings_struct lan;
//lan.client_num = clinf->client_num;//old client assigned number
lan.client_num = new_cl_num; //new server assigned number
strcpy(lan.client_name , clinf->client_name);
lan.max_clients = gsMAX_CLIENTS;
memcpy(lan.kitbag , kbag,sizeof (char)*100);
lan.damage_multiplier = gsDAMAGE_MULTIPLIER;
lan.same_merc = gsSAME_MERC;
lan.gsMercArriveSectorX=gsMercArriveSectorX;
lan.gsMercArriveSectorY=gsMercArriveSectorY;
lan.ENEMY_ENABLED=ENEMY_ENABLED;
lan.CREATURE_ENABLED=CREATURE_ENABLED;
lan.MILITIA_ENABLED=MILITIA_ENABLED;
lan.CIV_ENABLED=CIV_ENABLED;
lan.gsPLAYER_BSIDE=gsPLAYER_BSIDE;
lan.emorale=gsMORALE;
lan.gsREPORT_NAME=gsREPORT_NAME;
//something new
lan.secs_per_tick=gssecs_per_tick;
lan.soubBobbyRay=gGameOptions.ubBobbyRay;
lan.sofGunNut=gGameOptions.fGunNut;
lan.soubGameStyle=gGameOptions.ubGameStyle;
lan.soubDifficultyLevel=gGameOptions.ubDifficultyLevel;
lan.sofTurnTimeLimit=gGameOptions.fTurnTimeLimit;
lan.sofIronManMode=gGameOptions.fIronManMode;
lan.starting_balance=gsstarting_balance;
lan.sofNewInv=gGameOptions.ubInventorySystem;
lan.soDis_Bobby=gsDis_Bobby;
lan.soDis_Equip=gsDis_Equip;
lan.gsMAX_MERCS=gsMAX_MERCS;
memcpy( lan.client_names , client_names, sizeof( char ) * 4 * 30 );
lan.team=clinf->team;
//lan.cl_ops[0]=clinf->cl_ops[0];
//lan.cl_ops[1]=clinf->cl_ops[1];
//lan.cl_ops[2]=clinf->cl_ops[2];
//lan.cl_ops[3]=clinf->cl_ops[3];
//memcpy(lan.cl_ops,clinf->cl_ops,sizeof(int)*4);
////
lan.TESTING=gsTESTING;
lan.cl_edge=clinf->cl_edge;
lan.TIME=TIME;
lan.WEAPON_READIED_BONUS=sWEAPON_READIED_BONUS;
server->RPC("recieveSETTINGS",(const char*)&lan, (int)sizeof(settings_struct)*8, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true, 0, UNASSIGNED_NETWORK_ID,0);
}
//void rOVH (RPCParameters *rpcParameters)
//{
// ovh_struct* rovhs = (ovh_struct*)rpcParameters->input;
//
//
//
// ++mercs_ready[rovhs->ubid];
// //ncr++;
// nc = server->NumberOfConnections();
//
// if(mercs_ready[rovhs->ubid] >= nc)
// {
// mercs_ready[rovhs->ubid]=0;
// ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"advance %d",rovhs->ubid );
//
// adv aoh;
// aoh.ubid=rovhs->ubid;
//
// server->RPC("advance_ovh_frame",(const char*)&aoh, (int)sizeof(adv)*8, HIGH_PRIORITY, RELIABLE, 0, UNASSIGNED_SYSTEM_ADDRESS, true, 0, UNASSIGNED_NETWORK_ID,0);
//
// }
//
//}
void start_server (void)
{
if(!is_server)
{
//retrieve settings from .ini
f_rec_num(1,blank);//wipe clean
//char maxclients[30];
char port[30];
char SERVER_PORT[30];
//char MAX_CLIENTS[30] ;
// GetPrivateProfileString( "Ja2_mp Settings","MAX_CLIENTS", "", maxclients, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","SERVER_PORT", "", port, MAX_PATH, "..\\Ja2_mp.ini" );
// strcpy( MAX_CLIENTS , maxclients );
strcpy( SERVER_PORT, port );
char ints[30];
char maxclients[30];
char hire_same_merc[30];
char bteam1_enabled[30];
char bteam2_enabled[30];
char bteam3_enabled[30];
char bteam4_enabled[30];
char player_bside[30];
char sBalance[30];
char time_div[30];
char mor[30];
GetPrivateProfileString( "Ja2_mp Settings","SAME_MERC", "", hire_same_merc, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","DISABLE_MORALE", "", mor, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","MAX_CLIENTS", "", maxclients, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","DAMAGE_MULTIPLIER", "", net_div, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","ENEMY_ENABLED", "", bteam1_enabled, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","CREATURE_ENABLED", "", bteam2_enabled, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","MILITIA_ENABLED", "", bteam3_enabled, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","CIV_ENABLED", "", bteam4_enabled, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","GAME_MODE", "", player_bside, MAX_PATH, "..\\Ja2_mp.ini" );
//something new
gsMORALE=0;
if(atoi(mor)==1)gsMORALE=1;
GetPrivateProfileString( "Ja2_mp Settings","KIT_BAG", "", kbag, MAX_PATH, "..\\Ja2_mp.ini" );
char rpn[30];
GetPrivateProfileString( "Ja2_mp Settings","REPORT_NAME", "", rpn, MAX_PATH, "..\\Ja2_mp.ini" );
gsREPORT_NAME=atoi(rpn);
GetPrivateProfileString( "Ja2_mp Settings","STARTING_BALANCE", "", sBalance, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","TIMED_TURN_SECS_PER_TICK", "", time_div, MAX_PATH, "..\\Ja2_mp.ini" );
char dis_bob[30];
char dis_equip[30];
char max_merc[30];
char test[30];
GetPrivateProfileString( "Ja2_mp Settings","DISABLE_BOBBY_RAYS", "", dis_bob, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","DISABLE_AIM_AND_MERC_EQUIP", "", dis_equip, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","MAX_MERCS", "", max_merc, MAX_PATH, "..\\Ja2_mp.ini" );
GetPrivateProfileString( "Ja2_mp Settings","TESTING", "", test, MAX_PATH, "..\\Ja2_mp.ini" );
gsDis_Bobby=false;
gsDis_Equip=false;
if(atoi(dis_bob)==1)gsDis_Bobby=true;
if(atoi(dis_equip)==1)gsDis_Equip=true;
gsMAX_MERCS=atoi(max_merc);
gsTESTING = atoi(test);
////
ENEMY_ENABLED =atoi(bteam1_enabled);
CREATURE_ENABLED =atoi(bteam2_enabled);
MILITIA_ENABLED =atoi(bteam3_enabled);
CIV_ENABLED =atoi(bteam4_enabled);
gsPLAYER_BSIDE = atoi(player_bside);
gsSAME_MERC = atoi(hire_same_merc);
gsDAMAGE_MULTIPLIER =(FLOAT)atof(net_div);
gsINTERRUPTS = atoi(ints);
gsMAX_CLIENTS = atoi(maxclients);
gssecs_per_tick=atoi(time_div) ;
gsstarting_balance=atoi(sBalance);
char time[30];
GetPrivateProfileString( "Ja2_mp Settings","TIME", "", time, MAX_PATH, "..\\Ja2_mp.ini" );
TIME=(FLOAT)atof(time);
char wpr[30];
GetPrivateProfileString( "Ja2_mp Settings","WEAPON_READIED_BONUS", "", wpr, MAX_PATH, "..\\Ja2_mp.ini" );
sWEAPON_READIED_BONUS=atoi(wpr);
//**********************
ScreenMsg( FONT_LTBLUE, MSG_CHAT, MPServerMessage[0] );
server=RakNetworkFactory::GetRakPeerInterface();
bool b = server->Startup(gsMAX_CLIENTS, 30, &SocketDescriptor(atoi(SERVER_PORT),0), 1);
server->SetMaximumIncomingConnections((gsMAX_CLIENTS));
//RPC's
REGISTER_STATIC_RPC(server, sendPATH);
REGISTER_STATIC_RPC(server, sendSTANCE);
REGISTER_STATIC_RPC(server, sendDIR);
REGISTER_STATIC_RPC(server, sendFIRE);
REGISTER_STATIC_RPC(server, sendHIT);
REGISTER_STATIC_RPC(server, sendHIRE);
REGISTER_STATIC_RPC(server, sendguiPOS);
REGISTER_STATIC_RPC(server, sendguiDIR);
REGISTER_STATIC_RPC(server, sendEndTurn);
REGISTER_STATIC_RPC(server, sendAI);
REGISTER_STATIC_RPC(server, sendSTOP);
REGISTER_STATIC_RPC(server, sendINTERRUPT);
REGISTER_STATIC_RPC(server, sendREADY);
REGISTER_STATIC_RPC(server, sendGUI);
REGISTER_STATIC_RPC(server, sendBULLET);
REGISTER_STATIC_RPC(server, requestSETTINGS);
REGISTER_STATIC_RPC(server, sendSTATE);
REGISTER_STATIC_RPC(server, sendDEATH);
REGISTER_STATIC_RPC(server, sendhitSTRUCT);
REGISTER_STATIC_RPC(server, sendhitWINDOW);
REGISTER_STATIC_RPC(server, sendMISS);
//REGISTER_STATIC_RPC(server, rOVH);
REGISTER_STATIC_RPC(server, updatenetworksoldier);
REGISTER_STATIC_RPC(server, Snull_team);
REGISTER_STATIC_RPC(server, sendFIREW);
REGISTER_STATIC_RPC(server, sendDOOR);
REGISTER_STATIC_RPC(server, endINTERRUPT);
REGISTER_STATIC_RPC(server, sendREAL);
REGISTER_STATIC_RPC(server, startCOMBAT);
//
if (b)
{
ScreenMsg( FONT_LTBLUE, MSG_CHAT, MPServerMessage[1]);
ScreenMsg( FONT_LTBLUE, MSG_CHAT, MPServerMessage[2]);
is_server = true;
connect_client();//connect client to server
}
else
{
ScreenMsg( FONT_LTBLUE, MSG_CHAT, MPServerMessage[4]);
}
}
else
{
ScreenMsg( FONT_LTBLUE, MSG_CHAT, MPServerMessage[3]);
}
}
// recieve and process server info packets
void server_packet ( void )
{
Packet* p;
if (is_server)
{
p = server->Receive();
while(p)
{
//continue; // Didn't get any packets
// We got a packet, get the identifier with our handy function
SpacketIdentifier = SGetPacketIdentifier(p);
//ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, L"packet recieved");
// Check if this is a network message packet
switch (SpacketIdentifier)
{
case ID_DISCONNECTION_NOTIFICATION://client disconnected purposefullly
// Connection lost normally
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_DISCONNECTION_NOTIFICATION");
f_rec_num(2, p->systemAddress);//clear record
break;
case ID_ALREADY_CONNECTED:
// Connection lost normally
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_ALREADY_CONNECTED");
break;
case ID_REMOTE_DISCONNECTION_NOTIFICATION: // Server telling the clients of another client disconnecting gracefully. You can manually broadcast this in a peer to peer enviroment if you want.
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_REMOTE_DISCONNECTION_NOTIFICATION");
break;
case ID_REMOTE_CONNECTION_LOST: // Server telling the clients of another client disconnecting forcefully. You can manually broadcast this in a peer to peer enviroment if you want.
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_REMOTE_CONNECTION_LOST");
break;
case ID_REMOTE_NEW_INCOMING_CONNECTION: // Server telling the clients of another client connecting. You can manually broadcast this in a peer to peer enviroment if you want.
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_REMOT/MING_CONNECTION");
break;
case ID_CONNECTION_ATTEMPT_FAILED:
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_CONNECTION_ATTEMPT_FAILED");
break;
case ID_NO_FREE_INCOMING_CONNECTIONS:
// Sorry, the server is full. I don't do anything here but
// A real app should tell the user
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_NO_FREE_INCOMING_CONNECTIONS");
break;
case ID_CONNECTION_LOST:
// Couldn't deliver a reliable packet - i.e. the other system was abnormally
// terminated
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_CONNECTION_LOST");//client dropped
f_rec_num(2, p->systemAddress);//clear record
break;
case ID_CONNECTION_REQUEST_ACCEPTED:
// This tells the client they have connected
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_CONNECTION_REQUEST_ACCEPTED");
break;
case ID_NEW_INCOMING_CONNECTION:
//tells server client has connected
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_NEW_INCOMING_CONNECTION");
//send_settings();//send off server set settings
break;
case ID_MODIFIED_PACKET:
// Cheater!
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"ID_MODIFIED_PACKET");
break;
default:
ScreenMsg( FONT_LTBLUE, MSG_CHAT, L"** a packet has been recieved for which i dont know what to do... **");
break;
}
// We're done with the packet, get more :)
server->DeallocatePacket(p);
p = server->Receive();
}
}
}
// Copied from Multiplayer.cpp
// If the first byte is ID_TIMESTAMP, then we want the 5th byte
// Otherwise we want the 1st byte
unsigned char SGetPacketIdentifier(Packet *p)
{
if (p==0)
return 255;
if ((unsigned char)p->data[0] == ID_TIMESTAMP)
{
assert(p->length > sizeof(unsigned char) + sizeof(unsigned long));
return (unsigned char) p->data[sizeof(unsigned char) + sizeof(unsigned long)];
}
else
return (unsigned char) p->data[0];
}
void server_disconnect (void)
{
if(is_server)
{
server->Shutdown(300);
is_server = false;
// We're done with the network
RakNetworkFactory::DestroyRakPeerInterface(server);
ScreenMsg( FONT_LTBLUE, MSG_CHAT, MPServerMessage[6]);
}
else
{
ScreenMsg( FONT_LTBLUE, MSG_CHAT, MPServerMessage[7]);
}
}
+399
View File
@@ -0,0 +1,399 @@
#ifdef PRECOMPILEDHEADERS
#include "Tactical All.h"
#include "strategic.h"
#else
#include "builddefines.h"
#include "Bullets.h"
#include <stdio.h>
#include <string.h>
#include "wcheck.h"
#include "stdlib.h"
#include "debug.h"
#include "math.h"
#include "worlddef.h"
#include "worldman.h"
#include "renderworld.h"
#include "Assignments.h"
#include "Soldier Control.h"
#include "Animation Control.h"
#include "Animation Data.h"
#include "Isometric Utils.h"
#include "Event Pump.h"
#include "Timer Control.h"
#include "Render Fun.h"
#include "Render Dirty.h"
#include "mousesystem.h"
#include "interface.h"
#include "sysutil.h"
#include "FileMan.h"
#include "points.h"
#include "Random.h"
#include "ai.h"
#include "Interactive Tiles.h"
#include "soldier ani.h"
#include "english.h"
#include "overhead.h"
#include "Soldier Profile.h"
#include "Game Clock.h"
#include "soldier create.h"
#include "Merc Hiring.h"
#include "Game Event Hook.h"
#include "message.h"
#include "strategicmap.h"
#include "strategic.h"
#include "items.h"
#include "Soldier Add.h"
#include "History.h"
#include "Squads.h"
#include "Strategic Merc Handler.h"
#include "Dialogue Control.h"
#include "Map Screen Interface.h"
#include "Map Screen Interface Map.h"
#include "screenids.h"
#include "jascreens.h"
#include "text.h"
#include "Merc Contract.h"
#include "LaptopSave.h"
#include "personnel.h"
#include "Auto Resolve.h"
#include "Map Screen Interface Bottom.h"
#include "Quests.h"
#include "GameSettings.h"
#endif
#include "MessageIdentifiers.h"
#include "RakNetworkFactory.h"
#include "RakPeerInterface.h"
#include "RakNetStatistics.h"
#include "RakNetTypes.h"
#include "BitStream.h"
#include <assert.h>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
#include "tactical placement gui.h"
#include "connect.h"
#include "network.h"
#pragma pack(1)
#include "text.h"
#include "Types.h"
#include "connect.h"
#include "message.h"
#include "Event pump.h"
#include "Soldier Init List.h"
#include "Overhead.h"
#include "weapons.h"
#include "Merc Hiring.h"
#include "soldier profile.h"
#include"laptop.h"
#include "florist Order Form.h"
#include "prebattle interface.h"
#include "teamturns.h"
extern INT8 SquadMovementGroups[ ];
#include "test_space.h"
#include "soldier control.h"
bool ovh_advance;
bool ovh_ready;
#include "opplist.h"
//int cnt = 40;
void test_func2 (void)//now bound to "0" //currently displays coordinates of the mouse
{
ScreenMsg( FONT_LTGREEN, MSG_CHAT, L"test_func2 - function testing ground:" );
SOLDIERTYPE * pSoldier=MercPtrs[ 0 ];
//SOLDIERTYPE * pSoldier2=MercPtrs[ 127 ];
//
////pSoldier->AdjustNoAPToFinishMove( TRUE );
//
////pSoldier2->bVisible = 1;
//ManSeesMan(pSoldier,pSoldier2,pSoldier2->sGridNo,pSoldier2->pathing.bLevel,0,1);
/*
INT16 sCellX, sCellY;
sCellX = CenterX( 22163 );
sCellY = CenterY( 22163 );
pSoldier->EVENT_InternalSetSoldierPosition( sCellX, sCellY ,FALSE, FALSE, FALSE );*/
//SOLDIERTYPE * pSoldier=MercPtrs[ 0 ];
//pSoldier->bLife=0;
//SoldierCollapse( pSoldier );
//SoldierTakeDamage( pFirer, ANIM_CROUCH, 1, 100, TAKE_DAMAGE_BLOODLOSS, NOBODY, NOWHERE, 0, TRUE );
//TurnSoldierIntoCorpse( pFirer, FALSE, FALSE );
//SOLDIERTYPE * pSoldier=MercPtrs[ 0 ];
////
//pSoldier->fNoAPToFinishMove = TRUE;
//
//
//fInterfacePanelDirty = DIRTYLEVEL2;
////EVENT_InitNewSoldierAnim(pSoldier,3,0,0);
//pSoldier->ubDesiredHeight = ANIM_CROUCH;
//SOLDIERTYPE * pSoldier=MercPtrs[ 0 ];
//pSoldier->usAnimState=50;
//TurnSoldierIntoCorpse( pSoldier, TRUE, TRUE );
//gTacticalStatus.uiFlags |= SHOW_ALL_MERCS;
//BeginTeamTurn (0);
;
//gTacticalStatus.ubCurrentTeam = OUR_TEAM;
//guiPendingOverrideEvent = LA_ENDUIOUTURNLOCK;
//ExitCombatMode();
//fInterfacePanelDirty = DIRTYLEVEL2;
//InitPlayerUIBar( FALSE );
//UIHandleLUIEndLock( NULL );
//if( (gTacticalStatus.uiFlags & TURNBASED) && (gTacticalStatus.uiFlags & INCOMBAT) )
// ScreenMsg( FONT_LTGREEN, MSG_CHAT, L"combat turn based" );
//else
// ScreenMsg( FONT_LTGREEN, MSG_CHAT, L"not" );
//SOLDIERTYPE * pSoldier=MercPtrs[ 0 ];
//
// if ( ( gAnimControl[ pSoldier->usAnimState ].uiFlags &( ANIM_FIREREADY | ANIM_FIRE ) ) )
// {
// ScreenMsg( FONT_LTGREEN, MSG_CHAT, L"Ready" );
// }
// else
// ScreenMsg( FONT_LTGREEN, MSG_CHAT, L"Not" );
////fInterfacePanelDirty = DIRTYLEVEL2;
////guiPendingOverrideEvent = LU_ENDUILOCK;
////guiPendingOverrideEvent = LA_ENDUIOUTURNLOCK;
//
//
//
// ClearIntList();
// //guiPendingOverrideEvent = LU_ENDUILOCK;
// guiPendingOverrideEvent = LA_ENDUIOUTURNLOCK;
// fInterfacePanelDirty = DIRTYLEVEL2;
//
// if ( gusSelectedSoldier != NOBODY )
// {
// SlideTo( NOWHERE, gusSelectedSoldier, NOBODY ,SETLOCATOR);
// MercPtrs[ gusSelectedSoldier ]->DoMercBattleSound( BATTLE_SOUND_ATTN1 );
// }
// InitPlayerUIBar( 0 );
//HandleTacticalUI( );
//guiPendingOverrideEvent = LA_BEGINUIOURTURNLOCK;
//int n = 0;
//for(cnt=40+n ; cnt < 40+5+n ; cnt++)
//{
//
//QuickCreateProfileMerc( CIV_TEAM, cnt );jk
//
//RecruitRPC( cnt );
//Sleep(3000);
//}
//QuickCreateProfileMerc( CIV_TEAM, cnt );
//RecruitRPC( cnt );
//cnt++;
//HandleDoorChangeFromGridNo( pSoldier, 18451, FALSE );
//OBJECTTYPE Object;
//for (cnt=0; cnt<20;cnt++)
//{
//CreateItem( 201, 100, &Object );
//
//AutoPlaceObject( pSoldier, &Object, TRUE );
//
//
//INT16 sCellX, sCellY;
////ConvertGridNoToCellXY( 13576, &sCellX, &sCellY );
//
// sCellX = CenterX( 13576 );
// sCellY = CenterY( 13576 );
//
// //pSoldier->dXPos = sCellX;
// //pSoldier->dYPos = sCellY;
//
// //pSoldier->sX = (INT16)sCellX;
// //pSoldier->sY = (INT16)sCellY;
// EVENT_InitNewSoldierAnim( pSoldier, 6, 0, FALSE );
//EVENT_SetSoldierPositionForceDelete( pSoldier, (FLOAT)sCellX, (FLOAT)sCellY );
//HaultSoldierFromSighting( pSoldier, 1 );
//pSoldier->sScheduledStop=7961;
////
////EVENT_SetSoldierPosition( pSoldier, 1140, 1170 );
//AdjustNoAPToFinishMove( pSoldier, TRUE );
//pSoldier->fTurningFromPronePosition = FALSE;
//
////HaultSoldierFromSighting( pSoldier, 1 );
//UINT16 usPathData[30];
//usPathData[0]=3;
//usPathData[1]=5;
//usPathData[2]=7;
//
//pSoldier->sFinalDestination = 8446;
//
//pSoldier->usPathDataSize=3;
//pSoldier->usPathIndex=0;
//
//memcpy(pSoldier->usPathingData,usPathData,sizeof(UINT16)*30);
//INT16 sNewGridNo;
//sNewGridNo = NewGridNo( (UINT16)pSoldier->sGridNo, DirectionInc( (UINT8)pSoldier->usPathingData[ pSoldier->usPathDataSize ] ) );
//pSoldier->sFinalDestination = sNewGridNo;
//EVENT_InitNewSoldierAnim( pSoldier, 0, 0, FALSE );
//ovh_advance=true;
//
//
// CHAR16 string[255];
// memcpy(string,TeamTurnString[ 7 ], sizeof( CHAR16) * 255 );
//
// CHAR16 name[255];
// mbstowcs( name, CLIENT_NAME, sizeof (char)*30 );
//
// CHAR16 full[255];
// swprintf(full, L"%s - '%s'",string,name);
////
////
// memcpy( TeamTurnString[ 7 ] , full, sizeof( CHAR16) * 255 );
}
//BOOLEAN fMadeCorpse;
// SOLDIERTYPE * pSoldier=MercPtrs[ 0 ];
//pSoldier->bLife = 0;
// HandleSoldierDeath( pSoldier, &fMadeCorpse );
//guiPendingOverrideEvent = LA_BEGINUIOURTURNLOCK;
//
//guiPendingOverrideEvent = CA_MERC_SHOOT;
//
//guiPendingOverrideEvent = G_GETTINGITEM;
//
//guiPendingOverrideEvent = LU_ON_TERRAIN;
//
//guiPendingOverrideEvent = ET_ON_TERRAIN;
//
//guiPendingOverrideEvent = A_CHANGE_TO_MOVE;
//HandleTacticalUI( );
//CHAR8 string[60];
// wcscpy( string, "GetVideoObject" );
//sprintf( string, "hello");
/* char szDefault[255];
sprintf(szDefault, "%s","hello");
ScreenMsg( FONT_LTGREEN, MSG_CHAT, L"%S has connected.",szDefault );*/
//manual overide
//manual_overide();
//allow_bullet=1;
//
//if(1)
//{
// stage=0;
// ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, L"1" );
// //FireBulletGivenTarget( MercPtrs[0], 875, 995, 1, 11, -74, 0, 0 );
//
//
// INT32 iBullet;
// BULLET * pBullet;
// iBullet = CreateBullet( 0, 0, 0,11 );
// if (iBullet == -1)
// {
// ScreenMsg( FONT_YELLOW, MSG_CHAT, L"Failed to create bullet");
// }
// pBullet = GetBulletPtr( iBullet );
// //ScreenMsg( FONT_YELLOW, MSG_CHAT, L"Created Bullet");
// pBullet->fCheckForRoof=0;
// pBullet->qIncrX=-917769;
// pBullet->qIncrY=-507159;
// pBullet->qIncrZ=-537679;
// pBullet->sHitBy=-30;
// pBullet->ddHorizAngle=-2.5959375990628013;
// pBullet->fAimed=1;
// pBullet->ubItemStatus=0;
// pBullet->qCurrX=1231159031;
// pBullet->qCurrY=1221083881;
// pBullet->qCurrZ=182963121;
// pBullet->iImpact=28;
// pBullet->iRange=200;
// pBullet->sTargetGridNo=15929;
// pBullet->bStartCubesAboveLevelZ=2;
// pBullet->bEndCubesAboveLevelZ=0;
// pBullet->iDistanceLimit=328;
// SOLDIERTYPE * pFirer=MercPtrs[ 0 ];
// //FireBullet( pFirer, pBullet, FALSE );
// if(is_client)send_bullet( pBullet, 11 );//hayden
//}
//else
//{
// stage=1;
// ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, L"0" );
// FireBulletGivenTarget( MercPtrs[0], 875, 995, 1, 11, -74, 0, 0 );
//}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#define ENABLE_COLLISION (is_server && pBullet->pFirer->ubID<120) || (!is_server && is_client && pBullet->pFirer->ubID<20) || (!is_server && !is_client)
void send_bullet( BULLET * pBullet, UINT16 usHandItem);
INT8 FireBullet( SOLDIERTYPE * pFirer, BULLET * pBullet, BOOLEAN fFake );
#define NOCDCHECK
extern bool ovh_advance;
extern bool ovh_ready;
void request_ovh(UINT8 ubID);