Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

Changeset 9406 in orxonox.OLD for trunk/src/lib/network


Ignore:
Timestamp:
Jul 24, 2006, 11:09:47 AM (18 years ago)
Author:
bensch
Message:

orxonox/trunk: merged the proxy back

merged with commandsvn merge -r9346:HEAD https://svn.orxonox.net/orxonox/branches/proxy .

no conflicts

Location:
trunk/src/lib/network
Files:
3 deleted
41 edited
19 copied

Legend:

Unmodified
Added
Removed
  • trunk/src/lib/network/Makefile.am

    r8623 r9406  
    88                      shared_network_data.cc \
    99                      network_socket.cc \
    10                       connection_monitor.cc \
    1110                      network_stream.cc \
    1211                      data_stream.cc \
     
    2019                      network_game_manager.cc \
    2120                      converter.cc \
     21                      peer_info.cc \
    2222                      message_manager.cc \
    2323                      network_log.cc \
     
    2525                      player_stats.cc \
    2626                      udp_broadcast.cc \
     27                      \
     28                      proxy/network_settings.cc \
     29                      \
     30                                  monitor/connection_monitor.cc \
     31                      monitor/network_monitor.cc \
     32                      monitor/network_node.cc \
    2733                      \
    2834                      synchronizeable_var/synchronizeable_var.cc \
     
    3339                      synchronizeable_var/synchronizeable_float.cc \
    3440                      synchronizeable_var/synchronizeable_bool.cc \
    35                       synchronizeable_var/synchronizeable_uint.cc
     41                      synchronizeable_var/synchronizeable_uint.cc \
     42                      synchronizeable_var/synchronizeable_ip.cc \
     43                      \
     44                      ip.cc
    3645
    3746
    3847
    3948
    40 noinst_HEADERS = synchronizeable.h \
    41                  network_manager.h \
    42                  shared_network_data.h \
    43                  network_socket.h \
    44                  connection_monitor.h \
    45                  network_stream.h \
    46                  data_stream.h \
    47                  network_protocol.h \
    48                  server_socket.h \
    49                  tcp_server_socket.h \
    50                  tcp_socket.h \
    51                  udp_server_socket.h \
    52                  udp_socket.h \
    53                  handshake.h \
    54                  network_game_manager.h \
    55                  converter.h \
    56                  netdefs.h \
    57                  message_manager.h \
    58                  network_log.h \
    59                  zip.h \
    60                  player_stats.h \
    61                  udp_broadcast.h \
    62                  \
    63                  synchronizeable_var/synchronizeable_var.h \
    64                  synchronizeable_var/synchronizeable_vector.h \
    65                  synchronizeable_var/synchronizeable_int.h \
    66                  synchronizeable_var/synchronizeable_quaternion.h \
    67                  synchronizeable_var/synchronizeable_string.h \
    68                  synchronizeable_var/synchronizeable_float.h \
    69                  synchronizeable_var/synchronizeable_bool.h \
    70                  synchronizeable_var/synchronizeable_uint.h
    71 
    72 
     49noinst_HEADERS = \
     50                netdefs.h \
     51                nettypes.h \
     52                netincl.h \
     53                \
     54                synchronizeable.h \
     55                network_manager.h \
     56                shared_network_data.h \
     57                network_socket.h \
     58                network_stream.h \
     59                data_stream.h \
     60                network_protocol.h \
     61                server_socket.h \
     62                tcp_server_socket.h \
     63                tcp_socket.h \
     64                udp_server_socket.h \
     65                udp_socket.h \
     66                handshake.h \
     67                network_game_manager.h \
     68                converter.h \
     69                peer_info.h \
     70                netdefs.h \
     71                message_manager.h \
     72                network_log.h \
     73                zip.h \
     74                player_stats.h \
     75                udp_broadcast.h \
     76                \
     77                proxy/network_settings.cc \
     78                \
     79                monitor/connection_monitor.h \
     80                monitor/network_monitor.h \
     81                monitor/network_node.h \
     82                \
     83                synchronizeable_var/synchronizeable_var.h \
     84                synchronizeable_var/synchronizeable_vector.h \
     85                synchronizeable_var/synchronizeable_int.h \
     86                synchronizeable_var/synchronizeable_quaternion.h \
     87                synchronizeable_var/synchronizeable_string.h \
     88                synchronizeable_var/synchronizeable_float.h \
     89                synchronizeable_var/synchronizeable_bool.h \
     90                synchronizeable_var/synchronizeable_uint.h \
     91                synchronizeable_var/synchronizeable_ip.h \
     92                \
     93                ip.h
  • trunk/src/lib/network/converter.cc

    r8362 r9406  
    1010
    1111### File Specific:
    12    main-programmer: Benjamin Wuest
    13    co-programmer: ...
     12   main-programmer: Benjamin Wuest (bwuest@ee.ethz.ch)
     13   co-programmer: Christoph Renner (rennerc@ee.ethz.ch)
    1414*/
    1515
     
    3030
    3131/* using namespace std is default, this needs to be here */
    32 using namespace std;
     32
    3333
    3434/*!
     
    3838{
    3939  /* set the class id for the base object */
    40   //this->setClassID(CL_ENTITY_MANAGER, "EntityManager");
    4140}
    4241
  • trunk/src/lib/network/data_stream.cc

    r8623 r9406  
    1919
    2020/* using namespace std is default, this needs to be here */
    21 using namespace std;
     21
    2222
    2323
  • trunk/src/lib/network/handshake.cc

    r9235 r9406  
    1010
    1111### File Specific:
    12    main-programmer: christoph
    13    co-programmer:
     12   main-programmer: Christoph Renner (rennerc@ee.ethz.ch)
     13   co-programmer: Patirck Boenzli (boenzlip@orxonox.ethz.ch)
    1414*/
    1515
    1616
    17 /* this is for debug output. It just says, that all calls to PRINT() belong to the DEBUG_MODULE_NETWORK module
    18    For more information refere to https://www.orxonox.net/cgi-bin/trac.cgi/wiki/DebugOutput
    19 */
    2017#define DEBUG_MODULE_NETWORK
    2118
     
    2522#include "debug.h"
    2623
    27 Handshake::Handshake( bool server, int clientId, int networkGameManagerId, int messageManagerId )
     24
     25
     26
     27
     28 Handshake::Handshake( int nodeType, int clientId, int networkGameManagerId, int messageManagerId )
    2829  : Synchronizeable()
    2930{
     
    3132  this->setClassID(CL_HANDSHAKE, "Handshake");
    3233
    33   this->setIsServer(server);
    3434
     35  // register all variable handlers
    3536  orxId_handler = registerVarId( new SynchronizeableInt( &localState.orxId, &remoteState.orxId, "orxonoxId", PERMISSION_ALL ) );
    3637  version_handler = registerVarId( new SynchronizeableInt( &localState.version, &remoteState.version, "version", PERMISSION_ALL ) );
     
    4243  errorString_handler = registerVarId( new SynchronizeableString( &localState.errorString, &remoteState.errorString, "errorString", PERMISSION_ALL ) );
    4344
     45  this->nodeTypeHandler = registerVarId( new SynchronizeableInt( &localState.nodeType, &remoteState.nodeType, "nodeType", PERMISSION_ALL ) );
     46
    4447  candel_id = registerVarId( new SynchronizeableInt( &localState.canDel, &remoteState.canDel, "canDel", PERMISSION_ALL ) );
    45  
     48
    4649  registerVar( new SynchronizeableString( &localState.preferedNickName, &remoteState.preferedNickName, "preferedNickName", PERMISSION_ALL ) );
     50  // now synchronize only two of the available proxy server addresses
     51  registerVar( new SynchronizeableIP( &this->proxy1, &this->proxy1, "proxy server 1", PERMISSION_MASTER_SERVER ) );
     52  registerVar( new SynchronizeableIP( &this->proxy2, &this->proxy2, "proxy server 2", PERMISSION_MASTER_SERVER ) );
     53  registerVar( new SynchronizeableInt( &this->redirectProxy, &this->redirectProxy, "proxy server redirection flag", PERMISSION_MASTER_SERVER ) );
    4754
     55
     56  // init the local state
    4857  localState.completed = 0;
    4958  localState.error = 0;
     
    5463  localState.orxId = _ORXONOX_ID;
    5564  localState.version = _ORXONOX_VERSION;
     65  localState.nodeType = nodeType;
    5666  localState.canDel = 0;
    5767
     68
     69  // init the remote state
    5870  remoteState.completed = 0;
    5971  remoteState.error = 0;
     
    6476  remoteState.orxId = 0;
    6577  remoteState.version = 0;
     78  remoteState.nodeType = NET_CLIENT;
    6679  remoteState.canDel = 0;
    6780
     81
     82  this->proxy1 = IP(0, 0);
     83  this->proxy2 = IP(0, 0);
     84  this->redirectProxy = 0;
     85
     86
     87  // activate the synchronization process
    6888  this->setSynchronized(true);
    6989  PRINTF(0)("Handshake created clientId = %d\n", clientId);
    7090}
     91
    7192
    7293/**
     
    7899  for ( std::list<int>::iterator it = id.begin(); it != id.end(); it++ )
    79100  {
    80     if ( *it == orxId_handler )
     101    // orxonox id handler
     102    if ( *it == this->orxId_handler )
    81103    {
    82104      if ( remoteState.orxId != _ORXONOX_ID )
     
    87109        continue;
    88110      }
    89 
    90111    }
    91112
    92     if ( *it == version_handler )
     113    // orxonox version handler
     114    if ( *it == this->version_handler )
    93115    {
    94116      if ( remoteState.version != _ORXONOX_VERSION )
     
    99121        continue;
    100122      }
    101 
    102123    }
    103124
     125    // node type handler: for each node type there is a specific action to be taken
     126    if ( *it == this->nodeTypeHandler)
     127    {
     128      if ( remoteState.nodeType == NET_MASTER_SERVER )
     129      {
     130        continue;
     131      }
     132      else if( remoteState.nodeType == NET_PROXY_SERVER_ACTIVE)
     133      {
     134        continue;
     135      }
     136      else if( remoteState.nodeType == NET_CLIENT)
     137      {
     138        continue;
     139      }
     140    }
     141
     142    // cancel
    104143    if ( *it == candel_id )
    105144    {
    106145      PRINTF(0)("handshake finished candel changed\n");
    107146    }
    108 
    109147  }
    110148
    111   if (
    112       remoteState.orxId == _ORXONOX_ID &&
    113       remoteState.version == _ORXONOX_VERSION
    114      )
     149  // handshake completed
     150  if ( remoteState.orxId == _ORXONOX_ID &&
     151       remoteState.version == _ORXONOX_VERSION )
     152  {
    115153    localState.completed = 1;
     154  }
    116155}
    117156
  • trunk/src/lib/network/handshake.h

    r9235 r9406  
    11/*!
    22 * @file network_stream.h
    3  *  implementation of a network pipe
     3 *  implementation of a network pipe. This node handles the handshake of two network nodes and exchanges informationas
     4 * vial to the connection setup.
     5 *
     6 * the local node only writes in the localState variable. the remoteState variable will be written from the remote network node
     7 * so don't write into it!
    48 */
    59
     
    812
    913#include "base_object.h"
     14#include "ip.h"
    1015#include "synchronizeable.h"
     16#include "shared_network_data.h"
    1117
    12 #define _ORXONOX_ID 0xF91337A0
     18//!< a struct to save the handshakes to
     19struct HandshakeState
     20{
     21  int           orxId;                         //!< orxonox id
     22  int           version;                       //!< network protocol version
    1323
    14 #define _ORXONOX_VERSION 1
     24  int           networkManagerId;              //!< unique id of the network manager
     25  int           messageManagerId;              //!< unique id of the message manager
     26  int           hostId;                        //!< host id
     27  int           nodeType;                      //!< type of the network node
    1528
    16 struct HandshakeState {
    17   int orxId;
    18   int version;
    19  
    20   int networkManagerId;
    21   int messageManagerId;
    22   int hostId;
    23  
    24   int completed;
    25   int canDel;
    26  
    27   int error;
    28  
    29   std::string errorString;
    30  
     29  int           completed;                     //!< true if completed
     30  int           canDel;                        //!< true if marked for deletion
     31
     32  int           error;                         //!< error number
     33
     34  std::string   errorString;                   //!< error string
     35
    3136  //additional data
    32   std::string preferedNickName;
     37  std::string   preferedNickName;              //!< prefered nick name
    3338};
    3439
     40
     41//!< the handshake itself with some interface functions
    3542class Handshake : public Synchronizeable
    3643{
     44
    3745  public:
    38     Handshake( bool server, int clientId = 0, int networkGameManagerId = 0, int messageManagerId = 0 );
    39     inline bool       completed(){ return localState.completed != 0 && remoteState.completed != 0; }
    40     inline bool       ok(){ return localState.error == 0 && remoteState.error == 0; }
    41     inline int        getHostId(){ return remoteState.hostId; }
    42     inline int        getNetworkGameManagerId(){ return remoteState.networkManagerId; }
    43     inline int        getMessageManagerId(){ return remoteState.messageManagerId; }
    44     inline void       doReject( std::string reason ){ localState.error = 1; localState.errorString = "the server rejected your connection ["+ reason +"]"; }
    45     inline bool       canDel(){ return localState.canDel == 1 && remoteState.canDel == 1; }
    46     inline bool       allowDel(){ return localState.canDel == 1; }
    47     inline void       del(){ localState.canDel = 1; }
    48    
    49     inline void       setPreferedNickName( const std::string & nick ){ localState.preferedNickName = nick; }
     46    Handshake( int nodeType, int clientId = 0, int networkGameManagerId = 0, int messageManagerId = 0 );
     47
     48
     49    /* functions indicating states of the handshake */
     50    /** @returns true if the handshake is completed */
     51    inline bool completed(){ return localState.completed != 0 && remoteState.completed != 0; }
     52    /** @returns true if no error has occured until now */
     53    inline bool ok(){ return localState.error == 0 && remoteState.error == 0; }
     54    /** stops the handshake and reject the other side with @param reason: string describing the reason */
     55    inline void doReject( std::string reason ){ localState.error = 1; localState.errorString = "the server rejected your connection ["+ reason +"]"; }
     56    /** @returns true if the handshake is finished and the instances can be deleted */
     57    inline bool canDel(){ return localState.canDel == 1 && remoteState.canDel == 1; }
     58    /** @returns true if the local state can be removed*/
     59    inline bool allowDel(){ return localState.canDel == 1; }
     60    /** marks the handshake to be deleted */
     61    inline void del(){ localState.canDel = 1; }
     62
     63
     64    /* the actual informations exchanged in the handshake */
     65    /** @returns the host id of the remote host */
     66    inline int  getHostId(){ return remoteState.hostId; }
     67    /** @returns the unique id of the network game manager*/
     68    inline int  getNetworkGameManagerId(){ return remoteState.networkManagerId; }
     69    /** @returns the unique id of the message manager */
     70    inline int  getMessageManagerId(){ return remoteState.messageManagerId; }
     71    /** @returns the node type of the remote host */
     72    inline int getRemoteNodeType() { return this->remoteState.nodeType; }
     73
     74    /** sets @param nick the prefereded nick name */
     75    inline void setPreferedNickName( const std::string & nick ){ localState.preferedNickName = nick; }
     76    /** @returns the prefered nick name */
    5077    inline std::string getPreferedNickName(){ return remoteState.preferedNickName; }
    51    
     78
     79    /** @returns if true the local client should reconnect to a proxy server from the proxy server list */
     80    inline bool redirect() { return this->redirectProxy;}
     81    /** @param flag: indicating if the client should be redirected */
     82    inline void setRedirect(bool flag) { if( SharedNetworkData::getInstance()->isClient()) return; this->redirectProxy = (int)flag; }
     83
     84    /** @param address: the address of the proxy server 1 if any */
     85    inline void setProxy1Address(IP address) { if( SharedNetworkData::getInstance()->isClient()) return; this->proxy1 = address; }
     86    /** @returns the address of the proxy server 1 if any */
     87    inline IP getProxy1Address() { return this->proxy1; }
     88    /** @param address: the address of the proxy server 2 if any */
     89    inline void setProxy2Address(IP address) { if( SharedNetworkData::getInstance()->isClient()) return; this->proxy2 = address; }
     90    /** @returns the address of the proxy server 2 if any */
     91    inline IP getProxy2Address() { return this->proxy2; }
     92
     93
     94    /* variable handler function */
    5295    virtual void varChangeHandler( std::list<int> & id );
    5396
     97
    5498  private:
    55     HandshakeState localState;
    56     HandshakeState remoteState;
    57    
    58     int netManId_handler;
    59     int msgManId_handler;
    60     int hostId_handler;
    61     int completed_handler;
    62     int error_handler;
    63     int errorString_handler;
    64     int orxId_handler;
    65     int version_handler;
    66     int candel_id;
     99    HandshakeState     localState;                            //!< the local handshake state
     100    HandshakeState     remoteState;                           //!< the remote handshake state
    67101
     102    int                orxId_handler;                         //!< orxonox id handler
     103    int                version_handler;                       //!< orxonox version id handler
     104    int                netManId_handler;                      //!< network manager handler
     105    int                msgManId_handler;                      //!< message manager handler
     106    int                hostId_handler;                        //!< host id handler
     107    int                nodeTypeHandler;                       //!< node type handler
     108    int                proxy1Handler;                         //!< handler for the proxy
     109    int                proxy2Handler;                         //!< handler for the proxy
     110
     111    int                completed_handler;                     //!< handshake completion handler
     112    int                error_handler;                         //!< handshake error handler
     113    int                errorString_handler;                   //!< handshake error string handler
     114    int                candel_id;                             //!< handshake deletion handler
     115    int                nodeType;                              //!, the type of the network node
     116
     117    int                redirectProxy;                         //!< true if the client should reconnect to a proxy server
     118    IP                 proxy1;                               //!< ip address of the first proxy (0.0.0.0 of not available)
     119    IP                 proxy2;                               //!< ip address of the second proxy (0.0.0.0 of not available)
    68120};
    69121
  • trunk/src/lib/network/message_manager.cc

    r9059 r9406  
    2020#include "network_stream.h"
    2121#include "shared_network_data.h"
    22 
    23 using namespace std;
     22#include "converter.h"
     23#include <cassert>
     24
     25
    2426
    2527MessageManager* MessageManager::singletonRef = NULL;
     
    5254      }
    5355    }
    54    
     56
    5557    it->second.messages.clear();
    5658    it->second.toAck.clear();
    5759  }
    58  
     60
    5961  messageQueue.clear();
    60  
     62
    6163  this->messageHandlerMap.clear();
    62  
     64
    6365  MessageManager::singletonRef = NULL;
    6466}
     
    8284  int i = 0;
    8385  int n;
    84  
     86
    8587  n = Converter::intToByteArray( messageQueue[userId].toAck.size(), data + i, maxLength );
    8688  i += n;
    8789  assert( n == INTSIZE );
    88  
     90
    8991  for ( std::list<int>::iterator it = messageQueue[userId].toAck.begin(); it != messageQueue[userId].toAck.end(); it++)
    9092  {
     
    9395    assert( n == INTSIZE );
    9496  }
    95  
     97
    9698  messageQueue[userId].toAck.clear();
    97  
     99
    98100  n = Converter::intToByteArray( messageQueue[userId].messages.size(), data + i, maxLength );
    99101  i += n;
    100102  assert( n == INTSIZE );
    101  
     103
    102104  for ( std::list<NetworkMessage>::iterator it = messageQueue[userId].messages.begin(); it != messageQueue[userId].messages.end(); it++ )
    103105  {
     
    105107    i += n;
    106108    assert( n == INTSIZE );
    107    
     109
    108110    n = Converter::intToByteArray( it->number, data + i, maxLength );
    109111    i += n;
    110112    assert( n == INTSIZE );
    111    
     113
    112114    n = Converter::intToByteArray( it->messageId, data + i, maxLength );
    113115    i += n;
    114116    assert( n == INTSIZE );
    115    
     117
    116118    assert( i + it->length <= maxLength );
    117119    memcpy( data + i, it->data, it->length );
    118120    i += it->length;
    119121  }
    120  
     122
    121123  return i;
    122124}
     
    136138  int i = 0;
    137139  int n;
    138  
     140
    139141  int nAcks;
    140  
     142
    141143  assert( i + INTSIZE <= length );
    142144  n = Converter::byteArrayToInt( data + i, &nAcks );
    143145  assert( n == INTSIZE );
    144146  i += n;
    145  
     147
    146148  std::list<int> acks;
    147  
     149
    148150  int number;
    149  
     151
    150152  for ( int j = 0; j < nAcks; j++ )
    151153  {
     
    154156    assert( n == INTSIZE );
    155157    i += n;
    156    
     158
    157159    acks.push_back( number );
    158160  }
    159  
     161
    160162  int nMessages;
    161  
     163
    162164  assert( i + INTSIZE <= length );
    163165  n = Converter::byteArrayToInt( data + i, &nMessages );
     
    166168
    167169  int messageLength, messageId;
    168  
     170
    169171  for ( int j = 0; j < nMessages; j++ )
    170172  {
     
    173175    assert( n == INTSIZE );
    174176    i += n;
    175    
     177
    176178    assert( i + INTSIZE <= length );
    177179    n = Converter::byteArrayToInt( data + i, &number );
    178180    assert( n == INTSIZE );
    179181    i += n;
    180  
     182
    181183    assert( i + INTSIZE <= length );
    182184    n = Converter::byteArrayToInt( data + i, &messageId );
    183185    assert( n == INTSIZE );
    184186    i += n;
    185    
     187
    186188    if ( number > 0 )
    187189      messageQueue[userId].toAck.push_back( number );
    188    
     190
    189191    assert( i + messageLength <= length );
    190192    assert( messageHandlerMap.find( (MessageId)messageId ) != messageHandlerMap.end() );
     
    194196      {
    195197        NetworkMessage msg;
    196        
     198
    197199        msg.data = new byte[messageLength];
    198200        memcpy( msg.data, data + i, messageLength );
     
    200202        msg.messageId = (MessageId)messageId;
    201203        msg.number = userId;
    202        
     204
    203205        incomingMessageBuffer.push_back( msg );
    204206      }
     
    207209    i += messageLength;
    208210  }
    209  
    210  
     211
     212
    211213  //TODO maybe handle incomingMessage in tick function. else local messages will not be handled if no clients are connected
    212214  for ( std::list<NetworkMessage>::iterator it = incomingMessageBuffer.begin(); it != incomingMessageBuffer.end();  )
     
    223225    it++;
    224226  }
    225  
     227
    226228  //walk throu message queue and remove acked messages
    227229  for ( std::list<NetworkMessage>::iterator it = messageQueue[userId].messages.begin(); it != messageQueue[userId].messages.end();  )
     
    236238    it++;
    237239  }
    238  
     240
    239241  //TODO find bether way. maybe with timestamp
    240242  if ( messageQueue[userId].recievedMessages.size() > 1000 )
     
    255257  if ( messageQueue.find( userId ) == messageQueue.end() )
    256258    return;
    257    
     259
    258260  for ( std::list<NetworkMessage>::iterator it = messageQueue[userId].messages.begin(); it != messageQueue[userId].messages.end(); it++ )
    259261  {
     
    262264    it->data = NULL;
    263265  }
    264  
     266
    265267  messageQueue[userId].toAck.clear();
    266  
     268
    267269  messageQueue.erase( userId );
    268270}
     
    270272/**
    271273 * registers function to handle messages with id messageId. someData is passed to callbackfuntion
    272  * @param messageId message id to handle 
     274 * @param messageId message id to handle
    273275 * @param cb function pointer to callback function
    274276 * @param someData this pointer is passed to callback function without modification
     
    278280{
    279281  MessageHandler messageHandler;
    280  
     282
    281283  messageHandler.cb = cb;
    282284  messageHandler.messageId = messageId;
    283285  messageHandler.someData = someData;
    284  
     286
    285287  messageHandlerMap[messageId] = messageHandler;
    286  
     288
    287289  return true;
    288290}
     
    309311 * @param data pointer to data
    310312 * @param dataLength length of data
    311  * @param recieverType 
    312  * @param reciever 
     313 * @param recieverType
     314 * @param reciever
    313315 */
    314316void MessageManager::sendMessage( MessageId messageId, byte * data, int dataLength, RecieverType recieverType, int reciever, MessagePriority messagePriority )
     
    316318  for ( MessageQueue::iterator it = messageQueue.begin(); it != messageQueue.end(); it++ )
    317319  {
    318     if ( 
     320    if (
    319321         recieverType == RT_ALL_ME ||
    320322         recieverType == RT_ALL_NOT_ME ||
    321323         recieverType == RT_USER && it->first == reciever ||
    322324         recieverType == RT_NOT_USER && it->first != reciever ||
    323          recieverType == RT_SERVER && getNetworkStream()->isUserServer( it->first )
     325         recieverType == RT_SERVER && getNetworkStream()->isUserMasterServer( it->first )
    324326       )
    325327    {
     
    336338    }
    337339  }
    338  
     340
    339341  if ( recieverType == RT_ALL_ME )
    340342  {
  • trunk/src/lib/network/netdefs.h

    r9246 r9406  
     1/*
     2   orxonox - the future of 3D-vertical-scrollers
    13
     4   Copyright (C) 2004 orx
     5
     6   This program is free software; you can redistribute it and/or modify
     7   it under the terms of the GNU General Public License as published by
     8   the Free Software Foundation; either version 2, or (at your option)
     9   any later version.
     10
     11### File Specific:
     12   main-programmer: Christoph Renner rennerc@ee.ethz.ch
     13   co-programmer:   Patrick Boenzli  boenzlip@orxonox.ethz.ch
     14
     15     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
     16     July 2006: some code rearangement and integration of the proxy server mechanism (boenzlip@ee.ethz.ch)
     17*/
    218
    319/*!
    420 * @file network_manager.h
    521 *  Main interface for the network module. Manages all the modules
    6 
    722 */
    823
    9 #ifndef _NETDEFS
    10 #define _NETDEFS
     24#ifndef _NETDEFS_H
     25#define _NETDEFS_H
    1126
    12 #ifdef HAVE_SDL_NET_H
    13   #include <SDL_net.h>
    14 #else
    15   #include <SDL/SDL_net.h>
    16 #endif
     27#include "nettypes.h"
     28#include "netincl.h"
    1729
    1830
    19 #define MAX_CONNECTIONS 1000
    2031
     32//!< the amount of slots used before a proxy server is activated
     33#define NET_CONNECTION_SATURATION 0.75
     34
     35//!< network polling frequency
    2136#define NETWORK_FREQUENCY 66
    2237
    2338
    24 typedef unsigned char byte;
     39//!< orxonox protocol id
     40#define _ORXONOX_ID        0xF91337A0
     41//!< orxonox network version identifier
     42#define _ORXONOX_VERSION   1
    2543
    2644
    2745//!< enum indicating the type of the node
    2846typedef enum {
    29   NET_SERVER,
    30   NET_CLIENT
     47  NET_MASTER_SERVER,
     48  NET_PROXY_SERVER_ACTIVE,
     49  NET_PROXY_SERVER_PASSIVE,
     50  NET_CLIENT,
     51
     52  NET_NR_TYPES
     53
    3154} NodeType;
    3255
     
    4467} UidType;
    4568
    46 #endif /* _NETWORK_MANAGER */
     69#endif /* _NETDEFS_H */
  • trunk/src/lib/network/network_game_manager.cc

    r9235 r9406  
    1010
    1111### File Specific:
    12    main-programmer: Benjamin Wuest
    13    co-programmer: ...
     12   main-programmer: Christoph Renner rennerc@ee.ethz.ch
     13   co-programmer:   Patrick Boenzli  boenzlip@orxonox.ethz.ch
     14
     15     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
     16     July 2006: some code rearangement and integration of the proxy server mechanism (boenzlip@ee.ethz.ch)
    1417*/
    1518
    1619
    17 /* this is for debug output. It just says, that all calls to PRINT() belong to the DEBUG_MODULE_NETWORK module
    18    For more information refere to https://www.orxonox.net/cgi-bin/trac.cgi/wiki/DebugOutput
    19 */
     20
    2021#define DEBUG_MODULE_NETWORK
    2122
     
    4546
    4647
    47 /* using namespace std is default, this needs to be here */
    48 using namespace std;
     48
    4949
    5050NetworkGameManager* NetworkGameManager::singletonRef = NULL;
     
    6262
    6363  this->setSynchronized(true);
    64  
     64
    6565  MessageManager::getInstance()->registerMessageHandler( MSGID_DELETESYNCHRONIZEABLE, delSynchronizeableHandler, NULL );
    6666  MessageManager::getInstance()->registerMessageHandler( MSGID_PREFEREDTEAM, preferedTeamHandler, NULL );
    6767  MessageManager::getInstance()->registerMessageHandler( MSGID_CHATMESSAGE, chatMessageHandler, NULL );
    68  
     68
    6969  this->gameState = 0;
    7070  registerVar( new SynchronizeableInt( &gameState, &gameState, "gameState" ) );
     
    7777{
    7878  delete MessageManager::getInstance();
    79  
     79
    8080  PlayerStats::deleteAllPlayerStats();
    81  
     81
    8282  NetworkGameManager::singletonRef = NULL;
    8383}
     
    8686/**
    8787 * insert new player into game
    88  * @param userId 
    89  * @return 
     88 * @param userId
     89 * @return
    9090 */
    9191bool NetworkGameManager::signalNewPlayer( int userId )
    9292{
    93   assert( SharedNetworkData::getInstance()->isGameServer() );
     93  assert( SharedNetworkData::getInstance()->isMasterServer() ||  SharedNetworkData::getInstance()->isProxyServer());
    9494  assert( State::getGameRules() );
    9595  assert( State::getGameRules()->isA( CL_NETWORK_GAME_RULES ) );
    96  
     96
    9797  NetworkGameRules & rules = *(dynamic_cast<NetworkGameRules*>(State::getGameRules()));
    98  
     98
    9999  int team = rules.getTeamForNewUser();
    100100  ClassID playableClassId = rules.getPlayableClassId( userId, team );
     
    102102  std::string playableTexture = rules.getPlayableModelFileName( userId, team, playableClassId );
    103103  float       playableScale = rules.getPlayableScale( userId, team, playableClassId );
    104  
     104
    105105  BaseObject * bo = Factory::fabricate( playableClassId );
    106  
     106
    107107  assert( bo != NULL );
    108108  assert( bo->isA( CL_PLAYABLE ) );
    109  
     109
    110110  Playable & playable = *(dynamic_cast<Playable*>(bo));
    111  
     111
    112112  playable.loadMD2Texture( playableTexture );
    113  
     113
    114114  playable.loadModel( playableModel, 100.0f );
    115115  playable.setOwner( userId );
    116116  playable.setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
    117117  playable.setSynchronized( true );
    118  
     118
    119119  PlayerStats * stats = rules.getNewPlayerStats( userId );
    120  
     120
    121121  stats->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
    122122  stats->setSynchronized( true );
    123123  stats->setOwner( SharedNetworkData::getInstance()->getHostID() );
    124  
     124
    125125  stats->setTeamId( team );
    126126  stats->setPlayableClassId( playableClassId );
    127127  stats->setPlayableUniqueId( playable.getUniqueID() );
    128128  stats->setModelFileName( playableModel );
    129  
     129
    130130  if ( userId == 0 )
    131131    stats->setNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Server" ) );
    132  
     132
    133133  if ( rules.isA( CL_MULTIPLAYER_TEAM_DEATHMATCH ) )
    134134    dynamic_cast<MultiplayerTeamDeathmatch*>(&rules)->respawnPlayable( &playable, team, 0.0f );
    135  
     135
    136136  return true;
    137137}
     
    140140/**
    141141 * remove player from game
    142  * @param userID 
    143  * @return 
     142 * @param userID
     143 * @return
    144144 */
    145145bool NetworkGameManager::signalLeftPlayer(int userID)
     
    151151    delete PlayerStats::getStats( userID );
    152152  }
    153  
     153
    154154  return true;
    155155}
     
    159159/**
    160160 * handler for remove synchronizeable messages
    161  * @param messageId 
    162  * @param data 
    163  * @param dataLength 
    164  * @param someData 
    165  * @param userId 
     161 * @param messageId
     162 * @param data
     163 * @param dataLength
     164 * @param someData
     165 * @param userId
    166166 * @return true on successfull handling else handler will be called again
    167167 */
    168168bool NetworkGameManager::delSynchronizeableHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId )
    169169{
    170   if ( getInstance()->isServer() )
     170  if ( SharedNetworkData::getInstance()->isMasterServer() ||  SharedNetworkData::getInstance()->isProxyServer())
    171171  {
    172172    PRINTF(2)("Recieved DeleteSynchronizeable message from client %d!\n", userId);
    173173    return true;
    174174  }
    175  
     175
    176176  int uniqueId = 0;
    177177  int len = Converter::byteArrayToInt( data, &uniqueId );
    178  
     178
    179179  if ( len != dataLength )
    180180  {
     
    182182    return true;
    183183  }
    184  
     184
    185185  const std::list<BaseObject*> * list = ClassList::getList( CL_SYNCHRONIZEABLE );
    186  
     186
    187187  for ( std::list<BaseObject*>::const_iterator it = list->begin(); it != list->end(); it++ )
    188188  {
     
    194194        return true;
    195195      }
    196      
     196
    197197      delete dynamic_cast<Synchronizeable*>(*it);
    198198      return true;
    199199    }
    200200  }
    201  
     201
    202202  return true;
    203203}
     
    210210{
    211211  byte buf[INTSIZE];
    212  
     212
    213213  assert( Converter::intToByteArray( uniqueId, buf, INTSIZE ) == INTSIZE );
    214214
     
    220220/**
    221221 * handler for MSGID_PREFEREDTEAM message
    222  * @param messageId 
    223  * @param data 
    224  * @param dataLength 
    225  * @param someData 
    226  * @param userId 
    227  * @return 
     222 * @param messageId
     223 * @param data
     224 * @param dataLength
     225 * @param someData
     226 * @param userId
     227 * @return
    228228 */
    229229bool NetworkGameManager::preferedTeamHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId )
    230230{
    231   assert( NetworkGameManager::getInstance()->isServer() );
    232  
     231  assert( SharedNetworkData::getInstance()->isMasterServer() ||  SharedNetworkData::getInstance()->isProxyServer());
     232
    233233  int teamId = 0;
    234234  int len = Converter::byteArrayToInt( data, &teamId );
    235  
     235
    236236  if ( len != dataLength )
    237237  {
     
    239239    return true;
    240240  }
    241  
     241
    242242  NetworkGameManager::getInstance()->setPreferedTeam( userId, teamId );
    243  
     243
    244244  return true;
    245245}
     
    249249  if ( !PlayerStats::getStats( userId ) )
    250250    return;
    251  
     251
    252252  PlayerStats & stats = *(PlayerStats::getStats( userId ));
    253  
     253
    254254  stats.setPreferedTeamId( teamId );
    255255}
     
    257257/**
    258258 * set prefered team for this host
    259  * @param teamId 
     259 * @param teamId
    260260 */
    261261void NetworkGameManager::prefereTeam( int teamId )
    262262{
    263   if ( isServer() )
     263  if ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer())
    264264    setPreferedTeam( SharedNetworkData::getInstance()->getHostID(), teamId );
    265265  else
    266266  {
    267267    byte buf[INTSIZE];
    268    
     268
    269269    assert( Converter::intToByteArray( teamId, buf, INTSIZE) == INTSIZE );
    270    
     270
    271271    MessageManager::getInstance()->sendMessage( MSGID_PREFEREDTEAM, buf, INTSIZE, RT_USER, 0, MP_HIGHBANDWIDTH );
    272272  }
     
    285285    {
    286286      const std::list<BaseObject*> * list = ClassList::getList( CL_PLAYABLE );
    287        
     287
    288288      if ( list && std::find( list->begin(), list->end(), *it ) != list->end() )
    289       {     
    290         PRINTF(0)("Delete unused playable: %s owner: %d\n", (*it)->getClassName(), (*it)->getOwner() );
     289      {
     290        PRINTF(0)("Delete unused playable: %s owner: %d\n", (*it)->getClassCName(), (*it)->getOwner() );
    291291        std::list<Playable*>::iterator delit = it;
    292292        it++;
     
    305305{
    306306  PRINTF(0)("NetworkGameManager::chatMessageHandler %d %d\n", userId, SharedNetworkData::getInstance()->getHostID() );
    307   if ( NetworkGameManager::getInstance()->isServer() && userId !=  SharedNetworkData::getInstance()->getHostID() )
     307  if ( (SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer()) && userId !=  SharedNetworkData::getInstance()->getHostID() )
    308308  {
    309309    MessageManager::getInstance()->sendMessage( messageId, data, dataLength, RT_ALL_NOT_ME, 0, MP_HIGHBANDWIDTH );
    310310  }
    311  
     311
    312312  assert( State::getGameRules() );
    313313  assert( State::getGameRules()->isA( CL_NETWORK_GAME_RULES ) );
    314  
     314
    315315  NetworkGameRules & rules = *(dynamic_cast<NetworkGameRules*>(State::getGameRules()));
    316  
     316
    317317  if ( dataLength < 3*INTSIZE )
    318318  {
    319319    PRINTF(2)("got too small chatmessage from client %d\n", userId);
    320    
     320
    321321    return true;
    322322  }
    323  
     323
    324324  int messageType = 0;
    325325  Converter::byteArrayToInt( data, &messageType );
     
    328328  std::string message;
    329329  Converter::byteArrayToString( data+2*INTSIZE, message, dataLength-2*INTSIZE );
    330  
     330
    331331  rules.handleChatMessage( senderUserId, message, messageType );
    332332
     
    346346  assert( Converter::intToByteArray( SharedNetworkData::getInstance()->getHostID(), buf+INTSIZE, INTSIZE ) == INTSIZE );
    347347  assert( Converter::stringToByteArray(message, buf+2*INTSIZE, message.length()+INTSIZE) == message.length()+INTSIZE );
    348  
    349   if ( this->isServer() )
     348
     349  if ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer())
    350350    MessageManager::getInstance()->sendMessage( MSGID_CHATMESSAGE, buf, message.length()+3*INTSIZE, RT_ALL_ME, 0, MP_HIGHBANDWIDTH );
    351351  else
    352352    MessageManager::getInstance()->sendMessage( MSGID_CHATMESSAGE, buf, message.length()+3*INTSIZE, RT_ALL_NOT_ME, 0, MP_HIGHBANDWIDTH );
    353353
    354  
     354
    355355  delete [] buf;
    356356}
  • trunk/src/lib/network/network_game_manager.h

    r8708 r9406  
    2828  NET_YOU_ARE_ENTITY,
    2929  NET_REQUEST_ENTITY_LIST,
    30   NET_REQUEST_PNODE_PATH,
    31   NET_SEND_PNODE_PATH,
    3230
    3331  NET_NUMBER
     
    4240
    4341/*!
    44  * a class that can create and remove entities
     42 * a class that can create and remove entities over the network
    4543 */
    4644class NetworkGameManager: public Synchronizeable
    4745{
     46
    4847  public:
    4948    virtual ~NetworkGameManager();
    50    
     49
    5150    static NetworkGameManager* NetworkGameManager::getInstance()
    5251    { if (!NetworkGameManager::singletonRef) NetworkGameManager::singletonRef = new NetworkGameManager(); return NetworkGameManager::singletonRef; }
     
    5554    bool signalNewPlayer( int userId );
    5655    bool signalLeftPlayer( int userID );
    57    
    58     void removeSynchronizeable( int uniqueId );
    59    
     56
    6057    void prefereTeam( int teamId );
     58
    6159
    6260    inline void setGameState( int gameState ){ this->gameState = gameState; }
    6361    inline int getGameState(){ return this->gameState; }
    64    
     62
    6563    void tick( float ds );
    66    
     64
     65    void removeSynchronizeable( int uniqueId );
    6766    void sendChatMessage( const std::string & message, int messageType );
     67
    6868
    6969  private:
    7070    NetworkGameManager();
    71    
     71
    7272    static bool delSynchronizeableHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId );
    7373    static bool preferedTeamHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId );
    7474    static bool chatMessageHandler( MessageId messageId, byte * data, int dataLength, void * someData, int userId );
    75    
     75
    7676    void setPreferedTeam( int userId, int teamId );
    7777
     78
     79  private:
    7880    static NetworkGameManager*    singletonRef;
    79    
     81
    8082    int                           gameState;
    81    
     83
    8284    std::list<Playable*>          playablesToDelete;
    8385};
  • trunk/src/lib/network/network_manager.cc

    r9059 r9406  
    1010
    1111   ### File Specific:
    12    main-programmer: Patrick Boenzli
    13    co-programmer: ...
     12   main-programmer: Patrick Boenzli (patrick@orxonox.ethz.ch)
     13   co-programmer: Christoph Renner (rennerc@ee.ethz.ch)
    1414*/
    1515
     
    3434
    3535/* using namespace std is default, this needs to be here */
    36 using namespace std;
     36
    3737
    3838SHELL_COMMAND(debug, NetworkManager, debug);
     
    5353  this->networkStream = NULL;
    5454  this->elapsedTime = 0.0f;
    55  
    56    
     55
     56
    5757  int port = Preferences::getInstance()->getInt( "network", "telnetport", 0 );
    58  
     58
    5959  if ( port > 0 )
    6060    NetworkLog::getInstance()->listen( port );
     
    7575    this->networkStream = NULL;
    7676  }
    77  
     77
    7878  NetworkManager::singletonRef = NULL;
    7979}
     
    9595{
    9696
     97}
     98
     99
     100
     101/**
     102 *  creates a new NetworkStream of server type
     103 * @param port: number of the TCP port
     104 */
     105int NetworkManager::createMasterServer(unsigned int port)
     106{
     107  // load the network settings
     108  NetworkSettings::getInstance()->loadData();
     109
     110  // create the network stream
     111  this->networkStream = new NetworkStream(NET_MASTER_SERVER);
     112  this->networkStream->createServer( port);
     113
     114  // start the network game manager
     115  this->networkStream->createNetworkGameManager();
     116
     117  PRINTF(0)("Created Network Master Server\n");
     118  SDL_Delay(20);
     119  return 1;
     120}
     121
     122/**
     123 *  creates a new network stream of proxy server type
     124 * @param port: number of the TCP port
     125 */
     126int NetworkManager::createProxyServer(unsigned int port)
     127{
     128  // load the network settings
     129  NetworkSettings::getInstance()->loadData();
     130
     131  // create the network stream
     132  this->networkStream = new NetworkStream(NET_PROXY_SERVER_ACTIVE);
     133  this->networkStream->createServer( port);
     134  // and connect to the master server for synchronization
     135//   this->networkStream->connectToMasterServer(NetworkSettings::getInstance()->getMasterAddr());
     136  // and to the other proxy servers
     137
     138
     139
     140  // start the network game manager
     141  this->networkStream->createNetworkGameManager();
     142
     143
     144  PRINTF(0)("Created Network Proxy Server\n");
     145  SDL_Delay(20);
     146  return 1;
    97147}
    98148
     
    102152 * @param hostName: the name of the destination host
    103153 */
    104 int NetworkManager::establishConnection(const std::string & name, unsigned int port)
    105 {
    106   this->networkStream = new NetworkStream( name, port );
    107   SharedNetworkData::getInstance()->setDefaultSyncStream(this->networkStream);
     154int NetworkManager::createClient(const std::string & name, unsigned int port)
     155{
     156  // load the network settings
     157  NetworkSettings::getInstance()->loadData();
     158
     159  // create the network stream
     160  this->networkStream = new NetworkStream(NET_CLIENT);
     161  // connect to the master server, if a redirection should occure, this is handled in the NetworkStream itself
     162  this->networkStream->connectToMasterServer( name, port);
     163
     164  // and start the handshake
    108165  this->networkStream->startHandshake();
     166
     167  PRINTF(0)("Created Network Client");
    109168  return 1;
    110169}
     
    112171
    113172/**
    114  *  creates a new NetworkStream of server type
    115  * @param port: number of the TCP port
    116  */
    117 int NetworkManager::createServer(unsigned int port)
    118 {
    119   SharedNetworkData::getInstance()->setHostID(0);
    120   SharedNetworkData::getInstance()->setGameServer(true);
    121   this->networkStream = new NetworkStream(port);
    122   SharedNetworkData::getInstance()->setDefaultSyncStream(this->networkStream);
    123   this->networkStream->createNetworkGameManager();
    124   PRINTF(0)("CREATE SERVER\n");
    125   SDL_Delay(20);
    126   return 1;
    127 }
    128 
    129 
     173 * connects a synchronizeable to the network stream
     174 * @param sync: synchronizeable to connect
     175 */
    130176void NetworkManager::connectSynchronizeable(Synchronizeable& sync)
    131177{
     
    144190  if( likely(this->elapsedTime < 1.0f / NETWORK_FREQUENCY))
    145191    return;
     192
    146193  this->elapsedTime = 0.0f;
    147194
    148   if ( networkStream )
     195  if ( this->networkStream )
    149196    networkStream->processData();
    150  
     197
    151198  NetworkGameManager::getInstance()->tick( this->elapsedTime );
    152199}
  • trunk/src/lib/network/network_manager.h

    r9059 r9406  
    3636    void shutdown();
    3737
    38     int establishConnection( const std::string & name, unsigned int port);
    39     int createServer(unsigned int port);
    40 
    41     /** Returns the hostID @return The hostID of the object */
    42     inline int getHostID() { return SharedNetworkData::getInstance()->getHostID(); }
    43     inline bool isGameServer() { return SharedNetworkData::getInstance()->isGameServer(); }
    44 
     38    int createClient( const std::string & name, unsigned int port);
     39    int createMasterServer( unsigned int port);
     40    int createProxyServer( unsigned int port);
    4541
    4642    void connectSynchronizeable(Synchronizeable& sync);
     
    5652  private:
    5753    static NetworkManager*           singletonRef;            //!< Pointer to the only instance of this Class
    58     NetworkStream*                   networkStream;       //!< pointer to network stream
     54    NetworkStream*                   networkStream;           //!< pointer to network stream
    5955
    6056    float                            elapsedTime;             //!< elapsed time since the last network update
  • trunk/src/lib/network/network_protocol.cc

    r6341 r9406  
    3333
    3434/* using namespace std is default, this needs to be here */
    35 using namespace std;
     35
    3636
    3737
  • trunk/src/lib/network/network_socket.cc

    r7954 r9406  
    3333{
    3434  bOk = true;
     35  this->ip.host = 0;
     36  this->ip.port = 0;
    3537}
    3638
  • trunk/src/lib/network/network_socket.h

    r7954 r9406  
    2727     */
    2828    virtual void connectToServer( std::string host, int port ) = 0;
    29    
     29
    3030    /**
    3131     * disconnect from server
    3232     */
    3333    virtual void disconnectServer() = 0;
     34
     35    /**
     36     * reconnecting to another server by terminating old connection and init a new connection
     37     */
     38    virtual void reconnectToServer( std::string host, int port) = 0;
     39
     40    /**
     41     * reconnecting to anoter server softly
     42     */
     43    virtual void reconnectToServerSoft( std::string host, int port) = 0;
    3444
    3545    /**
     
    4050     */
    4151    virtual bool writePacket(byte * data, int length) = 0;
    42    
     52
    4353    /**
    4454     * read a packet sent by another NetworkSocket
     
    5464     */
    5565    inline bool isOk() { return this->bOk; }
    56  
     66
     67    /** @returns the ip adderess of the destination socket */
     68    IPaddress getRemoteAddress() { return ip; }
     69
     70
    5771  protected:
    58     bool bOk;            //!< check for socket status
     72    bool              bOk;            //!< check for socket status
    5973
     74    IPaddress         ip;             //!< host,port
    6075};
    6176
  • trunk/src/lib/network/network_stream.cc

    r9246 r9406  
    1212   main-programmer: Christoph Renner rennerc@ee.ethz.ch
    1313   co-programmer:   Patrick Boenzli  boenzlip@orxonox.ethz.ch
     14
     15     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
     16     July 2006: some code rearangement and integration of the proxy server mechanism (boenzlip@ee.ethz.ch)
    1417*/
    1518
     
    2225#include "udp_socket.h"
    2326#include "udp_server_socket.h"
    24 #include "connection_monitor.h"
     27#include "monitor/connection_monitor.h"
     28#include "monitor/network_monitor.h"
    2529#include "synchronizeable.h"
     30#include "ip.h"
    2631#include "network_game_manager.h"
    2732#include "shared_network_data.h"
     
    4247#include <algorithm>
    4348
    44 /* include your own header */
     49
    4550#include "network_stream.h"
    4651
    47 /* probably unnecessary */
    48 using namespace std;
     52
     53#include "converter.h"
    4954
    5055
     
    5257
    5358
     59/**
     60 * empty constructor
     61 */
    5462NetworkStream::NetworkStream()
    5563    : DataStream()
     
    5765  this->init();
    5866  /* initialize the references */
    59   this->type = NET_CLIENT;
    60 }
    61 
    62 
    63 /**
    64  * connect to a server as a client
    65  *  @param host: host name (address)
    66  *  @param port: port number
    67  */
    68 NetworkStream::NetworkStream( std::string host, int port )
    69 {
    70   this->type = NET_CLIENT;
     67  this->pInfo->nodeType = NET_CLIENT;
     68}
     69
     70
     71NetworkStream::NetworkStream( int nodeType)
     72{
    7173  this->init();
    72   this->peers[0].socket = new UdpSocket( host, port );
    73   this->peers[0].userId = 0;
    74   this->peers[0].isServer = true;
    75   this->peers[0].connectionMonitor = new ConnectionMonitor( 0 );
    76 }
    77 
    78 
    79 /**
    80  * start as a server
    81  *  @param port: at this port
    82  */
    83 NetworkStream::NetworkStream( int port )
    84 {
    85   this->type = NET_SERVER;
    86   this->init();
    87   this->serverSocket = new UdpServerSocket(port);
    88   this->bActive = true;
    89 }
     74
     75  this->pInfo->nodeType = nodeType;
     76
     77  switch( nodeType)
     78  {
     79    case NET_MASTER_SERVER:
     80      // init the shared network data
     81      SharedNetworkData::getInstance()->setHostID(0);
     82//       SharedNetworkData::getInstance()->setNodeType(NET_MASTER_SERVER);
     83      break;
     84
     85    case NET_PROXY_SERVER_ACTIVE:
     86      // init the shared network data
     87      SharedNetworkData::getInstance()->setHostID(0);
     88//       SharedNetworkData::getInstance()->setNodeType(NET_PROXY_SERVER_ACTIVE);
     89      break;
     90    case NET_PROXY_SERVER_PASSIVE:
     91            // init the shared network data
     92      SharedNetworkData::getInstance()->setHostID(0);
     93//       SharedNetworkData::getInstance()->setNodeType(NET_PROXY_SERVER_PASSIVE);
     94      break;
     95    case NET_CLIENT:
     96//       SharedNetworkData::getInstance()->setNodeType(NET_CLIENT);
     97      break;
     98  }
     99
     100  SharedNetworkData::getInstance()->setDefaultSyncStream(this);
     101
     102  // get the local ip address
     103  IPaddress ip;
     104  SDLNet_ResolveHost( &ip, NULL, 0);
     105  this->pInfo->ip = ip;
     106}
     107
    90108
    91109
     
    97115  /* set the class id for the base object */
    98116  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
    99   this->bActive = false;
    100117  this->serverSocket = NULL;
    101118  this->networkGameManager = NULL;
    102   myHostId = 0;
    103   currentState = 0;
     119  this->networkMonitor = NULL;
     120
     121  this->pInfo = new PeerInfo();
     122  this->pInfo->userId = 0;
     123  this->pInfo->lastAckedState = 0;
     124  this->pInfo->lastRecvedState = 0;
     125
     126
     127  this->currentState = 0;
    104128
    105129  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
     
    147171  for ( SynchronizeableList::const_iterator it = getSyncBegin(); it != getSyncEnd(); it ++ )
    148172    (*it)->setNetworkStream( NULL );
     173
     174  if( this->pInfo)
     175    delete this->pInfo;
     176
     177  if( this->networkMonitor)
     178    delete this->networkMonitor;
     179}
     180
     181
     182/**
     183 * establish a connection to a remote master server
     184 * @param host: host name
     185 * @param port: the port number
     186 */
     187void NetworkStream::connectToMasterServer(std::string host, int port)
     188{
     189  int node = this->peers.size();
     190  this->peers[node].socket = new UdpSocket( host, port );
     191  this->peers[node].userId = 0;
     192
     193  this->peers[node].nodeType = NET_MASTER_SERVER;
     194  this->peers[node].connectionMonitor = new ConnectionMonitor( 0 );
     195  this->peers[node].ip = this->peers[node].socket->getRemoteAddress();
     196}
     197
     198
     199/**
     200 * establish a connection to a remote proxy server
     201 * @param host: host name
     202 * @param port: the port number
     203 */
     204void NetworkStream::connectToProxyServer(std::string host, int port)
     205{
     206  int node = this->peers.size();
     207  this->peers[node].socket = new UdpSocket( host, port );
     208  this->peers[node].userId = 0;
     209
     210  this->peers[node].nodeType = NET_PROXY_SERVER_ACTIVE;
     211  this->peers[node].connectionMonitor = new ConnectionMonitor( 0 );
     212  this->peers[node].ip = this->peers[node].socket->getRemoteAddress();
     213}
     214
     215
     216/**
     217 * create a server
     218 * @param port: interface port for all clients
     219 */
     220void NetworkStream::createServer(int port)
     221{
     222  this->serverSocket = new UdpServerSocket(port);
    149223}
    150224
     
    156230{
    157231  this->networkGameManager = NetworkGameManager::getInstance();
    158   // setUniqueID( maxCon+2 ) because we need one id for every handshake
    159   // and one for handshake to reject client maxCon+1
     232
    160233  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
    161234  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
     
    165238/**
    166239 * starts the network handshake
     240 * handsakes are always initialized from the client side first. this starts the handshake and therefore is only
     241 * executed as client
    167242 */
    168243void NetworkStream::startHandshake()
    169244{
    170   Handshake* hs = new Handshake(false);
     245  Handshake* hs = new Handshake(this->pInfo->nodeType);
    171246  hs->setUniqueID( 0 );
    172247  assert( peers[0].handshake == NULL );
    173248  peers[0].handshake = hs;
    174249
     250  // set the preferred nick name
    175251  hs->setPreferedNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Player" ) );
    176252
    177 //   peers[0].handshake->setSynchronized( true );
    178   //this->connectSynchronizeable(*hs);
    179   //this->connectSynchronizeable(*hs);
    180   PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getName());
     253  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getCName());
    181254}
    182255
     
    192265  sync.setNetworkStream( this );
    193266
    194   this->bActive = true;
     267//   this->bActive = true;
    195268}
    196269
     
    215288void NetworkStream::processData()
    216289{
     290  // create the network monitor after all the init work and before there is any connection handlings
     291  if( this->networkMonitor == NULL)
     292    this->networkMonitor = new NetworkMonitor(this);
     293
     294
    217295  int tick = SDL_GetTicks();
    218296
    219   currentState++;
    220 
    221   if ( this->type == NET_SERVER )
    222   {
     297  this->currentState++;
     298  // there was a wrap around
     299  if( this->currentState < 0)
     300  {
     301    PRINTF(1)("A wrap around in the state variable as occured. The server was running so long? Pls restart server or write a mail to the supporters!\n");
     302  }
     303
     304  if ( this->pInfo->isMasterServer())
     305  {
     306    // execute everytthing the master server shoudl do
     307    if ( serverSocket )
     308      serverSocket->update();
     309
     310    this->updateConnectionList();
     311  }
     312  else if( this->pInfo->isProxyServer())
     313  {
     314    // execute everything the proxy server should do
    223315    if ( serverSocket )
    224316      serverSocket->update();
     
    249341  cleanUpOldSyncList();
    250342  handleHandshakes();
     343
     344  // update the network monitor
     345  this->networkMonitor->process();
    251346
    252347  // order of up/downstream is important!!!!
     
    258353
    259354/**
    260  * if we are a server update the connection list to accept new connections (clients)
    261  * also start the handsake for the new clients
     355 * if we are a NET_MASTER_SERVER or NET_PROXY_SERVER_ACTIVE update the connection list to accept new
     356 * connections (clients) also start the handsake for the new clients
    262357 */
    263358void NetworkStream::updateConnectionList( )
     
    276371      clientId = freeSocketSlots.back();
    277372      freeSocketSlots.pop_back();
    278       peers[clientId].socket = tempNetworkSocket;
    279       peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID() );
    280       peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
    281       peers[clientId].handshake->setUniqueID(clientId);
    282       peers[clientId].userId = clientId;
    283       peers[clientId].isServer = false;
    284373    }
    285374    else
     
    290379        if ( it->first >= clientId )
    291380          clientId = it->first + 1;
    292 
    293       peers[clientId].socket = tempNetworkSocket;
    294       peers[clientId].handshake = new Handshake(true, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
    295       peers[clientId].handshake->setUniqueID(clientId);
    296       peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
    297       peers[clientId].userId = clientId;
    298       peers[clientId].isServer = false;
    299 
    300       PRINTF(0)("num sync: %d\n", synchronizeables.size());
    301     }
    302 
    303     // check if there are too many clients connected
    304     if ( clientId > MAX_CONNECTIONS )
    305     {
    306       peers[clientId].handshake->doReject( "too many connections" );
    307       PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
    308     }
    309     else
    310     {
    311       PRINTF(0)("New Client: %d\n", clientId);
    312     }
    313 
    314     //this->connectSynchronizeable(*handshakes[clientId]);
     381    }
     382    peers[clientId].socket = tempNetworkSocket;
     383
     384
     385    // create new handshake and init its variables
     386    peers[clientId].handshake = new Handshake(this->pInfo->nodeType, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
     387    peers[clientId].handshake->setUniqueID(clientId);
     388
     389    peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
     390    peers[clientId].userId = clientId;
     391
     392    PRINTF(0)("num sync: %d\n", synchronizeables.size());
     393
     394    // get the proxy server informations and write them to the handshake, if any (proxy)
     395    assert( this->networkMonitor != NULL);
     396    PeerInfo* pi = this->networkMonitor->getFirstChoiceProxy();
     397    if( pi != NULL)
     398    {
     399      peers[clientId].handshake->setProxy1Address( pi->ip);
     400    }
     401    pi = this->networkMonitor->getSecondChoiceProxy();
     402    if( pi != NULL)
     403      peers[clientId].handshake->setProxy2Address( pi->ip);
     404
     405    // check if the connecting client should reconnect to a proxy server
     406    peers[clientId].handshake->setRedirect(/*this->networkMonitor->isReconnectNextClient()*/false);
     407
     408    // the connecting node of course is a client
     409    peers[clientId].nodeType = NET_CLIENT;
     410    peers[clientId].ip = peers[clientId].socket->getRemoteAddress();
     411
     412
     413    // check if there are too many clients connected (DEPRECATED: new: the masterserver sends a list of proxy servers)
     414//     if ( clientId > SharedNetworkData::getInstance()->getMaxPlayer() )
     415//     {
     416// //       peers[clientId].handshake->setRedirect(true);
     417// //
     418// //       peers[clientId].handshake->doReject( "too many connections" );
     419//       PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
     420//     }
     421//     else
     422//     {
     423//       PRINTF(0)("New Client: %d\n", clientId);
     424//     }
     425    PRINTF(0)("New Client: %d\n", clientId);
     426
     427
    315428  }
    316429
     
    339452      it->second.socket = NULL;
    340453
     454      // remove the old connectin monitor
    341455      if ( it->second.connectionMonitor )
    342456        delete it->second.connectionMonitor;
    343457      it->second.connectionMonitor = NULL;
    344458
     459      // remove the handshake
    345460      if ( it->second.handshake )
    346461        delete it->second.handshake;
    347462      it->second.handshake = NULL;
    348463
     464      // and cleanup the user infos
    349465      for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )
    350466      {
     
    373489void NetworkStream::debug()
    374490{
    375   if( this->isServer())
    376     PRINT(0)(" Host ist Server with ID: %i\n", this->myHostId);
    377   else
    378     PRINT(0)(" Host ist Client with ID: %i\n", this->myHostId);
     491  if( SharedNetworkData::getInstance()->isMasterServer()) {
     492    PRINT(0)(" Host ist Master Server with ID: %i\n", this->pInfo->userId);
     493  }
     494  else if( SharedNetworkData::getInstance()->isProxyServer()) {
     495    PRINT(0)(" Host ist Proxy Server with ID: %i\n", this->pInfo->userId);
     496  }
     497  else {
     498    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
     499  }
    379500
    380501  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
     
    382503  {
    383504    if( (*it)->beSynchronized() == true)
    384       PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
     505      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassCName(), (*it)->getCName(),
    385506               (*it)->getUniqueID(), (*it)->beSynchronized());
    386507  }
    387   PRINT(0)(" Maximal Connections: %i\n", MAX_CONNECTIONS );
     508  PRINT(0)(" Maximal Connections: %i\n", SharedNetworkData::getInstance()->getMaxPlayer() );
    388509
    389510}
     
    414535    if ( it->second.handshake )
    415536    {
     537      // handshake finished
    416538      if ( it->second.handshake->completed() )
    417539      {
     540        //handshake is correct
    418541        if ( it->second.handshake->ok() )
    419542        {
     543          // the server gave it free for deletion
    420544          if ( !it->second.handshake->allowDel() )
    421545          {
    422             if ( type != NET_SERVER )
     546
     547            if ( this->pInfo->isClient() )
    423548            {
    424549              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
    425               myHostId = SharedNetworkData::getInstance()->getHostID();
    426 
     550              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
     551
     552              it->second.nodeType = it->second.handshake->getRemoteNodeType();
     553              it->second.ip = it->second.socket->getRemoteAddress();
     554              // add the new server to the nodes list (it can be a NET_MASTER_SERVER or NET_PROXY_SERVER)
     555              this->networkMonitor->addNode(&it->second);
     556              // get proxy 1 address and add it
     557              this->networkMonitor->addNode(it->second.handshake->getProxy1Address(), NET_PROXY_SERVER_ACTIVE);
     558              // get proxy 2 address and add it
     559              this->networkMonitor->addNode(it->second.handshake->getProxy2Address(), NET_PROXY_SERVER_ACTIVE);
     560
     561              // now check if the server accepted the connection
     562              if( it->second.handshake->redirect())
     563                this->handleReconnect( it->second.userId);
     564
     565              // create the new network game manager and init it
    427566              this->networkGameManager = NetworkGameManager::getInstance();
    428567              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
     568              // init the new message manager
    429569              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
    430570            }
     
    432572
    433573            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
    434 
    435574            it->second.handshake->del();
    436575          }
    437576          else
    438577          {
     578            // handshake finished registring new player
    439579            if ( it->second.handshake->canDel() )
    440580            {
    441               if ( type == NET_SERVER )
     581
     582              if ( this->pInfo->isMasterServer() )
    442583              {
    443                 handleNewClient( it->second.userId );
     584                it->second.nodeType = it->second.handshake->getRemoteNodeType();
     585                it->second.ip = it->second.socket->getRemoteAddress();
     586
     587                this->networkMonitor->addNode(&it->second);
     588
     589                this->handleNewClient( it->second.userId );
     590
     591                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
     592                {
     593                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
     594                }
     595              }
     596              else if ( this->pInfo->isProxyServer() )
     597              {
     598                it->second.nodeType = it->second.handshake->getRemoteNodeType();
     599                it->second.ip = it->second.socket->getRemoteAddress();
     600
     601                this->networkMonitor->addNode(&it->second);
     602
     603                this->handleNewClient( it->second.userId );
    444604
    445605                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
     
    468628
    469629/**
     630 * this functions handles a reconnect event received from the a NET_MASTER_SERVER or NET_PROXY_SERVER
     631 */
     632void NetworkStream::handleReconnect(int userId)
     633{
     634  PRINTF(0)("===============================================\n");
     635  PRINTF(0)("Client is redirected to the other proxy servers\n");
     636  PRINTF(0)("===============================================\n");
     637
     638  return;
     639
     640  PeerInfo* pInfo = &this->peers[userId];
     641
     642  // reject the server
     643  pInfo->handshake->doReject( "redirected to different server");
     644
     645  // flush the old synchronization states, since the numbering could be completely different
     646  pInfo->lastAckedState = 0;
     647  pInfo->lastRecvedState = 0;
     648  // not sure if this works as expected
     649  if( pInfo->handshake)
     650    delete pInfo->handshake;
     651
     652  // disconnect from the current server and reconnect to proxy server
     653  pInfo->socket->reconnectToServer( pInfo->handshake->getProxy1Address().ipString(), pInfo->handshake->getProxy1Address().port());
     654
     655  // and restart the handshake
     656  this->startHandshake();
     657}
     658
     659
     660/**
    470661 * handle upstream network traffic
    471662 */
     
    501692    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
    502693    {
     694
    503695      int oldOffset = offset;
    504696      Synchronizeable & sync = **it;
     697
    505698
    506699      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
     
    512705        continue;
    513706
    514       // if we are a server and this is not our handshake
    515       if ( isServer() && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
     707      // if we are a server (both master and proxy servers) and this is not our handshake
     708      if ( ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer() ) && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
    516709        continue;
    517710
     
    521714        continue;
    522715
     716
     717      assert( sync.getLeafClassID() != 0);
     718
    523719      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
    524720
    525721      // server fakes uniqueid == 0 for handshake
    526       if ( this->isServer() && sync.getUniqueID() < MAX_CONNECTIONS - 1 )
     722      if ( ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer() ) &&
     723             sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1) // plus one to handle one client more than the max to redirect it
    527724        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
    528725      else
    529726        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
    530727
     728
    531729      assert( n == INTSIZE );
    532730      offset += n;
    533731
    534       // make space for size
     732      // make space for packet size
    535733      offset += INTSIZE;
    536734
     
    573771    // now compress the data with the zip library
    574772    int compLength = 0;
    575     if ( this->isServer() )
     773    if ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer())
    576774      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
    577775    else
     
    637835      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
    638836      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
    639       //NETPRINTF(n)("ackedstate: %d\n", ackedState);
    640837      offset = 4*INTSIZE;
    641838
    642839      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
    643840
    644       //NETPRINTF(n)("got packet: %d, %d\n", length, packetLength);
    645 
    646     //if this is an old state drop it
     841
     842      //if this is an old state drop it
    647843      if ( state <= peer->second.lastRecvedState )
    648844        continue;
     
    655851      }
    656852
    657       while ( offset + 2*INTSIZE < length )
     853      while ( offset + 2 * INTSIZE < length )
    658854      {
    659855        assert( offset > 0 );
     
    669865        Synchronizeable * sync = NULL;
    670866
     867        // look for the synchronizeable in question
    671868        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
    672869        {
    673         //                                        client thinks his handshake has id 0!!!!!
     870          // client thinks his handshake has id 0!!!!!
    674871          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
    675872          {
     
    679876        }
    680877
     878        // this synchronizeable does not yet exist! create it
    681879        if ( sync == NULL )
    682880        {
    683881          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
     882
     883          // if it is an old synchronizeable already removed, ignore it
    684884          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
    685885          {
     
    688888          }
    689889
    690           if ( !peers[peer->second.userId].isServer )
     890          // if the node we got this unknown sync from is a client we ignore it (since it has no rights to create a new sync)
     891          if ( peers[peer->second.userId].isClient() )
    691892          {
    692893            offset += syncDataLength;
     
    705906          assert( leafClassId != 0 );
    706907
     908
    707909          BaseObject * b = NULL;
    708910          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
     
    710912          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
    711913          {
    712             PRINTF(1)("Can not create Class with ID %x!\n", (int)leafClassId);
     914            PRINTF(1)("Don't create Object with ID %x, ignored!\n", (int)leafClassId);
    713915            offset += syncDataLength;
    714916            continue;
     
    730932            sync->setSynchronized(true);
    731933
    732             PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
     934            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassCName(), sync->getUniqueID());
    733935          }
    734936          else
     
    744946        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
    745947        offset += n;
    746         //NETPRINTF(0)("SSSSSEEEEETTTTT: %s %d\n",sync->getClassName(), n);
    747948
    748949      }
     
    779980/**
    780981 * is executed when a handshake has finished
    781  * @todo create playable for new user
    782982 */
    783983void NetworkStream::handleNewClient( int userId )
    784984{
     985  // init and assign the message manager
    785986  MessageManager::getInstance()->initUser( userId );
    786 
     987  // do all game relevant stuff here
    787988  networkGameManager->signalNewPlayer( userId );
    788989}
     990
    789991
    790992/**
  • trunk/src/lib/network/network_stream.h

    r9246 r9406  
    1414#include "server_socket.h"
    1515#include "handshake.h"
    16 #include "connection_monitor.h"
     16#include "monitor/connection_monitor.h"
    1717#include "udp_server_socket.h"
     18#include "peer_info.h"
     19
     20#include "shared_network_data.h"
    1821
    1922class Synchronizeable;
     
    2124class ServerSocket;
    2225class NetworkGameManager;
     26class NetworkMonitor;
    2327
    24 //!< this structure contains informations about the network node
    25 class PeerInfo
    26 {
    27   public:
    28     PeerInfo() { clear(); }
    29     void clear() { userId = 0; isServer = false; socket = NULL; handshake = NULL; lastAckedState = 0; lastRecvedState = 0; connectionMonitor = NULL; }
    30 
    31 
    32   public:
    33     int                 userId;
    34     bool                isServer;
    35     NetworkSocket *     socket;
    36     Handshake *         handshake;
    37     ConnectionMonitor * connectionMonitor;
    38     int                 lastAckedState;
    39     int                 lastRecvedState;
    40 };
    4128
    4229typedef std::list<Synchronizeable*>  SynchronizeableList;
     
    4936  public:
    5037    NetworkStream();
    51     NetworkStream( std::string host, int port);
    52     NetworkStream( int port );
     38    NetworkStream(int nodeType);
     39    virtual ~NetworkStream();
    5340
    54     virtual ~NetworkStream();
    5541    void init();
     42
     43    void connectToMasterServer(std::string host, int port);
     44    void connectToProxyServer(std::string host, int port);
     45    void createServer(int port);
    5646
    5747    void createNetworkGameManager();
    5848    void startHandshake();
    5949
     50    /* synchronizeable interface */
    6051    void connectSynchronizeable(Synchronizeable& sync);
    6152    void disconnectSynchronizeable(Synchronizeable& sync);
    6253
    63     inline bool isServer() const { return (this->type == NET_SERVER)? true:false; }
    64     inline bool isActive() const { return this->bActive; }
     54    inline int getMaxConnections(){ return SharedNetworkData::getInstance()->getMaxPlayer(); }
    6555
    66     inline int getMaxConnections(){ return MAX_CONNECTIONS; }
     56    /* functions for the peerInfo information retreival */
     57    inline bool isUserIdActive( int userID ) { return (peers.find(userID) != peers.end()); }
     58    inline bool isUserMasterServer( int userID ){ if ( !isUserIdActive(userID) ) return false; return peers[userID].isMasterServer(); }
     59    inline bool isUserProxyServer( int userID ){ if ( !isUserIdActive(userID) ) return false; return peers[userID].isProxyServer(); }
     60    inline bool isUserClient( int userID ){ if ( !isUserIdActive(userID) ) return false; return peers[userID].isClient(); }
    6761
     62    /* peering interface */
     63    inline PeerInfo & getPeerInfo( int userId ) { return peers[userId]; }
     64    inline PeerInfo* getPeerInfo() { return this->pInfo; }
     65    inline PeerList getPeerInfoList() { return this->peers; }
     66
     67    /* data processing*/
    6868    virtual void processData();
     69
     70    /* debugging */
     71    void debug();
     72
     73
     74  private:
    6975
    7076    inline SynchronizeableList::const_iterator getSyncBegin(){ return synchronizeables.begin(); }
    7177    inline SynchronizeableList::const_iterator getSyncEnd(){ return synchronizeables.end(); }
     78    void cleanUpOldSyncList();
    7279    int getSyncCount();
    7380
    74     inline bool isUserIdActive( int userID ) { return (peers.find(userID) != peers.end()); }
    75     inline bool isUserServer( int userID ){ if ( !isUserIdActive(userID) ) return false; return peers[userID].isServer; }
    76 
    77     void debug();
    78 
    79     inline PeerInfo & getPeerInfo( int userId ) { return peers[userId]; }
    80 
    81 
    82   private:
    8381    void updateConnectionList();
     82    /* handle processes */
    8483    void handleHandshakes();
    8584    void handleUpstream( int tick );
    8685    void handleDownstream(int tick );
     86
     87    /* handle events*/
    8788    void handleNewClient( int userId );
    88     void cleanUpOldSyncList();
     89    void handleReconnect( int userId );
    8990
    9091    void writeToNewDict( byte * data, int length, bool upstream );
     
    9293
    9394  private:
    94     SynchronizeableList        synchronizeables;
    95     PeerList                   peers;
    96     ServerSocket*              serverSocket;
    97     int                        type;
    98     bool                       bActive;
    99     std::list<int>             freeSocketSlots;
     95    PeerList                   peers;                       //!< list of the network node informations
    10096
    101     int                        myHostId;
     97    PeerInfo*                  pInfo;                       //!< the info about the local peer node (not in the PeerList)
    10298
     99    std::list<int>             freeSocketSlots;             //!< list of free sockets (to ensure not to resycle sockets)
    103100    int                        currentState;                //!< current state id
    104101
    105     NetworkGameManager*        networkGameManager;
     102    NetworkMonitor*            networkMonitor;              //!< the network monitor
     103    NetworkGameManager*        networkGameManager;          //!< reference to the network game manager
     104    ServerSocket*              serverSocket;                //!< the listening socket of the server
    106105
    107106    std::map<int,int>          oldSynchronizeables;         //!< used to save recently deleted sync ids to not recreate them
     107    SynchronizeableList        synchronizeables;            //!< list of the synchronizeables
    108108
    109109    byte                       buf[UDP_PACKET_SIZE];        //!< used by handleUp/Downstream
    110110    byte                       compBuf[UDP_PACKET_SIZE];    //!< used by handleUp/Downstream
    111 
    112111    int                        remainingBytesToWriteToDict; //!< if > 0 NetworkStream will write packets to DATA/dicts/newdict
    113112
    114     int dictServer;
    115     int dictClient;
     113    int                        dictServer;                  //!< the zip dict for the server
     114    int                        dictClient;                  //!< the zip dict for the client
    116115};
    117116#endif /* _NETWORK_STREAM */
  • trunk/src/lib/network/player_stats.cc

    r9235 r9406  
    2323#include "shared_network_data.h"
    2424
     25#include "converter.h"
     26
    2527#include "preferences.h"
    2628
     
    3840{
    3941  init();
    40  
     42
    4143  this->userId = userId;
    4244}
     
    6264  this->nickName = "Player";
    6365  this->oldNickName = "Player";
    64  
     66
    6567  userId_handle = registerVarId( new SynchronizeableInt( &userId, &userId, "userId" ) );
    6668  teamId_handle = registerVarId( new SynchronizeableInt( &teamId, &teamId, "teamId" ) );
     
    7173  modelFileName_handle = registerVarId( new SynchronizeableString( &modelFileName, &modelFileName, "modelFileName" ) );
    7274  nickName_handler = registerVarId( new SynchronizeableString( &nickName, &nickName, "nickName" ) );
    73  
     75
    7476  MessageManager::getInstance()->registerMessageHandler( MSGID_CHANGENICKNAME, changeNickHandler, NULL );
    75  
     77
    7678  PRINTF(0)("PlayerStats created\n");
    7779}
     
    9698  {
    9799    this->setPlayableUniqueId( this->playableUniqueId );
    98    
     100
    99101    PRINTF(0)("uniqueID changed %d %d %d\n", userId, SharedNetworkData::getInstance()->getHostID(), getUniqueID());
    100102  }
    101  
     103
    102104  if ( std::find( id.begin(), id.end(), nickName_handler ) != id.end() )
    103105  {
     
    115117{
    116118  const std::list<BaseObject*> * list = ClassList::getList( CL_PLAYER_STATS );
    117  
     119
    118120  if ( !list )
    119121  {
    120122    return NULL;
    121123  }
    122  
     124
    123125  for ( std::list<BaseObject*>::const_iterator it = list->begin(); it != list->end(); it++ )
    124126  {
     
    128130    }
    129131  }
    130  
     132
    131133  return NULL;
    132134}
     
    138140{
    139141  const std::list<BaseObject*> * list = ClassList::getList( CL_PLAYABLE );
    140  
     142
    141143  if ( !list )
    142144  {
     
    144146    return;
    145147  }
    146  
     148
    147149  this->playable = NULL;
    148150  for ( std::list<BaseObject*>::const_iterator it = list->begin(); it != list->end(); it++ )
     
    156158    }
    157159  }
    158  
     160
    159161  if ( this->playable && userId == SharedNetworkData::getInstance()->getHostID() )
    160162  {
    161163    State::getPlayer()->setPlayable( this->playable );
    162164  }
    163  
     165
    164166  this->playableUniqueId = uniqueId;
    165167}
     
    173175  if ( playable )
    174176    return playable;
    175  
     177
    176178  assert( playableUniqueId > 0 );
    177  
     179
    178180  setPlayableUniqueId( playableUniqueId );
    179  
     181
    180182  assert( playable );
    181  
     183
    182184  return playable;
    183185}
     
    189191void PlayerStats::setNickName( std::string nick )
    190192{
    191   if ( SharedNetworkData::getInstance()->isGameServer() )
     193  if ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer() )
    192194  {
    193195    this->nickName = nick;
     
    199201  {
    200202    byte * data = new byte[nick.length()+INTSIZE];
    201    
     203
    202204    assert( Converter::stringToByteArray( nick, data, nick.length()+INTSIZE) == nick.length()+INTSIZE );
    203    
     205
    204206    MessageManager::getInstance()->sendMessage( MSGID_CHANGENICKNAME, data, nick.length()+INTSIZE, RT_SERVER, 0, MP_HIGHBANDWIDTH );
    205207    return;
     
    211213  std::string newNick;
    212214  int res = Converter::byteArrayToString( data, newNick, dataLength );
    213  
     215
    214216  if ( res != dataLength )
    215217  {
     
    217219    newNick = "invalid";
    218220  }
    219  
     221
    220222  if ( PlayerStats::getStats( userId ) )
    221223    PlayerStats::getStats( userId )->setNickName( newNick );
    222  
     224
    223225  return true;
    224226}
     
    228230  if ( getStats( SharedNetworkData::getInstance()->getHostID() ) )
    229231    getStats( SharedNetworkData::getInstance()->getHostID() )->setNickName( newNick );
    230    
     232
    231233  Preferences::getInstance()->setString( "multiplayer", "nickname", newNick );
    232234}
     
    237239{
    238240  const std::list<BaseObject*> * list;
    239  
     241
    240242  while ( (list  = ClassList::getList( CL_PLAYER_STATS )) != NULL && list->begin() != list->end() )
    241243    delete *list->begin();
     
    247249{
    248250  ScoreList result;
    249  
     251
    250252  const std::list<BaseObject*> * list = ClassList::getList( CL_PLAYER_STATS );
    251  
     253
    252254  if ( !list )
    253255  {
    254256    return result;
    255257  }
    256  
     258
    257259  for ( std::list<BaseObject*>::const_iterator it = list->begin(); it != list->end(); it++ )
    258260  {
    259261    PlayerStats & stats = *dynamic_cast<PlayerStats*>(*it);
    260    
     262
    261263    TeamScoreList::iterator it = result[stats.getTeamId()].begin();
    262    
     264
    263265    while (  it != result[stats.getTeamId()].end() && stats.score > it->score )
    264266    {
    265267      it++;
    266268    }
    267    
     269
    268270    PlayerScore score;
    269271    score.name = stats.getNickName();
    270272    score.score = stats.getScore();
    271    
     273
    272274    result[stats.getTeamId()].insert(it, score);
    273275  }
    274  
     276
    275277  return result;
    276278}
  • trunk/src/lib/network/shared_network_data.cc

    r9110 r9406  
    1818#include "shared_network_data.h"
    1919#include "netdefs.h"
     20#include "state.h"
    2021
     22#include "debug.h"
    2123
    22 using namespace std;
    2324
    2425
     
    3334  this->setClassID(CL_SHARED_NETWORK_DATA, "SharedNetworkData");
    3435
     36  this->nodeType = NET_CLIENT;
    3537  this->hostID = -1;
    3638  this->defaultSyncStream = NULL;
    37   this->newUniqueID = MAX_CONNECTIONS + 2;
    38   this->bGameServer = false;
     39
     40  // setUniqueID( maxCon+2 ) because we need one id for every handshake
     41  // and one for handshake to reject client maxCon+1
     42  this->newUniqueID = 2;
    3943}
    4044
  • trunk/src/lib/network/shared_network_data.h

    r6695 r9406  
    88
    99#include "base_object.h"
     10#include "netdefs.h"
     11#include "proxy/network_settings.h"
    1012
     13//!< maximal connectinons for the server
     14#define NET_MAX_CONNECTIONS 2
    1115
    1216class NetworkStream;
    1317class Synchronizeable;
    14 template<typename>
    15     class tList;
     18
    1619
    1720/* and here is the class itsself*/
     
    2528
    2629    /** @returns the next uniqueID free for an object */
    27     inline int getNewUniqueID() { return ( this->bGameServer)?this->newUniqueID++:-1; }
     30    inline int getNewUniqueID() { return ( this->nodeType != NET_CLIENT)?this->newUniqueID++:-1; }
     31    /** sets the @param newUniqueID: the new offset for the next unique id */
     32    inline void setNewUniqueID(int newUniqueID) { this->newUniqueID = newUniqueID; }
    2833
    29     /** @returns true is this node is a game server */
    30     inline bool isGameServer() { return this->bGameServer; }
     34    /** @returns true is this node is a master server */
     35    inline bool isMasterServer() { return this->nodeType == NET_MASTER_SERVER; }
     36    /** @returns true is this node is a proxy server */
     37    inline bool isProxyServer() { return this->nodeType == NET_PROXY_SERVER_ACTIVE; }
     38    /** @returns true is this node is a client*/
     39    inline bool isClient() { return this->nodeType == NET_CLIENT; }
    3140    /** sets the game server flag @param bGameServer true if it is a game server */
    32     inline void setGameServer(bool bGameServer) { this->bGameServer = bGameServer; }
     41    inline void setNodeType(int nodeType) { this->nodeType = nodeType; }
     42
     43    /** @returns the maximum number of players for this server */
     44    inline int getMaxPlayer() { return NetworkSettings::getInstance()->getMaxPlayer(); }
    3345
    3446    /** @returns the hostID of the node */
     
    4961  private:
    5062    int                             newUniqueID;             //!< next uniqueID
    51     bool                            bGameServer;             //!< true if it is a server
     63    int                             nodeType;                //!< saves the node type here
     64
    5265    int                             hostID;                  //!< The Host-ID of the Manager
    5366    NetworkStream*                  defaultSyncStream;       //!< default synchronize NetworkStream
  • trunk/src/lib/network/synchronizeable.cc

    r9110 r9406  
    1111
    1212### File Specific:
    13    main-programmer: Silvan Nellen
    14    co-programmer: Benjamin Wuest
     13   main-programmer: Christoph Renner (rennerc@ee.ethz.ch)
     14   co-programmer: Patrick Boenzli (patrick@orxonox.ethz.ch)
    1515*/
    1616
     
    2929#include "synchronizeable.h"
    3030
     31#include "converter.h"
     32
    3133
    3234
     
    3840  this->setClassID(CL_SYNCHRONIZEABLE, "Synchronizeable");
    3941  this->owner = 0;
    40   this->setIsServer(SharedNetworkData::getInstance()->getHostID() == 0);
     42//   this->setIsServer(SharedNetworkData::getInstance()->getHostID() == 0);
    4143  this->uniqueID = NET_UID_UNASSIGNED;
    4244  this->networkStream = NULL;
    4345  this->bSynchronize = false;
    44  
     46
    4547  if( State::isOnline())
    4648  {
     
    5456  assert( syncVarList.size() == 0 );
    5557  mLeafClassId = this->registerVarId( new SynchronizeableInt( (int*)&this->getLeafClassID(), (int*)&this->getLeafClassID(), "leafClassId" ) );
    56    
     58
    5759  this->registerVar( new SynchronizeableInt( &this->owner, &this->owner, "owner" ) );
    5860  this->registerVar( new SynchronizeableString( &this->objectName, &this->objectName, "objectName" ) );
     
    6971  {
    7072    this->networkStream->disconnectSynchronizeable(*this);
    71  
    72     if ( this->isServer() && this->beSynchronized() && this->getUniqueID() > 0 && !this->isA( CL_MESSAGE_MANAGER ) )
     73
     74    if ( (SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer() )
     75           && this->beSynchronized() && this->getUniqueID() > 0 && !this->isA( CL_MESSAGE_MANAGER ) )
    7376      NetworkGameManager::getInstance()->removeSynchronizeable( this->getUniqueID() );
    7477  }
    75    
     78
    7679  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
    7780  {
     
    7982  }
    8083  syncVarList.clear();
    81  
     84
    8285  for ( UserStateHistory::iterator it = recvStates.begin(); it != recvStates.end(); it++ )
    8386  {
     
    9396
    9497  }
    95  
     98
    9699  for ( UserStateHistory::iterator it = sentStates.begin(); it != sentStates.end(); it++ )
    97100  {
     
    105108      delete *it2;
    106109    }
    107 
    108   }
    109 }
    110 
    111 /**
    112  * Sets the server flag to a given value
    113  * @param isServer: the boolean value which the server flag is to set to
    114  */
    115 void Synchronizeable::setIsServer(bool isServer)
    116 {
    117   if( isServer )
    118     this->state = this->state | STATE_SERVER;
    119   else
    120     this->state = this->state & (~STATE_SERVER);
    121 }
    122 
    123 
    124 /**
    125  * Determines if the server flag is set
    126  * @return true, if the server flag is true, false else
    127  */
    128 bool Synchronizeable::isServer()
    129 {
    130   return (this->state & STATE_SERVER) >0;
    131 }
    132 
    133 
    134 
     110  }
     111}
     112
     113
     114
     115/**
     116 * creates a diff image from two states
     117 * @param userId: the userid of the user where the image will be sent to
     118 * @param data: the binary data array to write to
     119 * @param maxLength: maximal length of the data written (length of available space in the array)
     120 * @param stateId: the state id that this diff will represent
     121 * @param priorityTH: the priority threshold: all syncs below this threshold won't be synchronized
     122 *
     123 * @todo check for permissions
     124 */
    135125int Synchronizeable::getStateDiff( int userId, byte* data, int maxLength, int stateId, int fromStateId, int priorityTH )
    136126{
     
    169159        (*it2)->data = NULL;
    170160      }
    171      
     161
    172162      delete *it2;
    173163    }
     
    181171  while ( it != sentStates[userId].end() && (*it)->stateId != fromStateId )
    182172    it++;
    183  
    184 //  if ( getLeafClassID() == CL_SPACE_SHIP )
    185 //  {
    186 //    PRINTF(0)("getStateDiff:SpaceShip from: %d stateId: %d\n", (it == sentStates[userId].end())?-1:fromStateId, stateId);
    187 //  }
    188173
    189174  if ( it == sentStates[userId].end() )
     
    196181
    197182    stateFrom = initialEntry;
    198    
     183
    199184    sentStates[userId].push_back( stateFrom );
    200185  }
     
    205190
    206191  sentStates[userId].push_back( stateTo );
    207  
     192
    208193  stateTo->stateId = stateId;
    209194  stateTo->dataLength = neededSize;
     
    214199  int i = 0;
    215200  int n;
    216  
    217   bool hasPermission;
     201
     202  bool hasPermission = false;
    218203  bool sizeChanged = false;
    219204
     
    221206  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
    222207  {
    223     hasPermission = (
    224             this->isServer() && (*it)->checkPermission( PERMISSION_SERVER ) ||
    225         this->owner == SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ) ||
    226             this->isServer() && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ) ||
    227             (*it)->checkPermission( PERMISSION_ALL )
    228                     );
    229    
    230     if ( sizeIter == stateFrom->sizeList.end() || *sizeIter != (*it)->getSize() )
     208    // DATA PERMISSIONS
     209    // check if this synchronizeable has the permissions to write the data
     210
     211    // first check MASTER_SERVER permissions
     212    if( SharedNetworkData::getInstance()->isMasterServer() && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
     213      hasPermission = true;
     214    // now check PROXY_SERVER permissions
     215    else if( SharedNetworkData::getInstance()->isProxyServer() && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
     216      hasPermission = true;
     217    // now check OWNER permissions
     218    else if( this->owner == SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
     219      hasPermission = true;
     220    // now check ALL permissions
     221    else if( (*it)->checkPermission( PERMISSION_ALL ))
     222      hasPermission = true;
     223    // SPECIAL: get write permissions if i am master server and i am able to overwrite the client stuff
     224    else if( SharedNetworkData::getInstance()->isMasterServer() && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ))
     225      hasPermission = true;
     226    // SPECIAL: get write permissions if i am proxy server and i am able to overwrite the client stuff
     227    else if( SharedNetworkData::getInstance()->isProxyServer()  && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ))
     228      hasPermission = true;
     229    else
     230      hasPermission = false;
     231
     232
     233    if ( sizeIter == stateFrom->sizeList.end() || *sizeIter != (*it)->getSize() )
    231234      sizeChanged = true;
    232    
     235
    233236    if ( ( hasPermission && (*it)->getPriority() >= priorityTH ) || sizeChanged )
    234237    {
    235238      n = (*it)->writeToBuf( stateTo->data+i, stateTo->dataLength - i );
    236239      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
     240      //PRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
    237241      stateTo->sizeList.push_back( n );
    238       //(*it)->debug();
     242      // this is only for very hardcore debug sessions
     243      // (*it)->debug();
    239244      i += n;
    240245    }
     
    257262  if ( i != neededSize )
    258263  {
    259     PRINTF(0)("strange error: (%s) %d != %d\n", this->getClassName(), i, neededSize);
     264    PRINTF(0)("strange error: (%s) %d != %d\n", this->getClassCName(), i, neededSize);
    260265    assert(false);
    261266  }
     
    281286 * @param fromStateId id of the base state id
    282287 * @return number bytes read
     288 *
    283289 * @todo check for permissions
    284290 */
     
    299305  StateHistoryEntry * stateFrom = NULL;
    300306
     307  // search the state from wich the diff is made of
    301308  StateHistory::iterator it = recvStates[userId].begin();
    302309  while ( it != recvStates[userId].end() && (*it)->stateId != fromStateId )
    303310    it++;
    304311
    305  
    306 //  if ( getLeafClassID() == CL_SPACE_SHIP )
    307 //  {
    308 //    PRINTF(0)("setStateDiff:SpaceShip from: %d stateId: %d\n", (it == recvStates[userId].end())?-1:fromStateId, stateId);
    309 //  }
    310 
     312  // if this is the first state to receive
    311313  if ( it == recvStates[userId].end() )
    312314  {
     
    318320
    319321    stateFrom = initialEntry;
    320    
     322
    321323    recvStates[userId].push_back( stateFrom );
    322324  }
    323325  else
    324326    stateFrom = (*it);
    325  
    326   //apply diff
     327
     328
     329  // apply diff
    327330  for ( int i = 0; i<length; i++ )
    328331  {
     
    331334    else
    332335      stateTo->data[i] = data[i];
    333    
    334   }
    335  
     336  }
     337
    336338  //add state to state history
    337339  recvStates[userId].push_back( stateTo );
    338  
     340
    339341  int i = 0;
    340342  int n = 0;
    341343  std::list<int> changes;
    342  
     344  bool hasPermission = false;
     345
     346  // extract the new state for every client
    343347  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
    344348  {
    345     if (
    346         (*it)->checkPermission( PERMISSION_SERVER ) && networkStream->isUserServer( userId ) ||
    347         (*it)->checkPermission( PERMISSION_OWNER ) && this->owner == userId ||
    348         networkStream->isUserServer( userId ) && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ) ||
    349         (*it)->checkPermission( PERMISSION_ALL )
    350        )
     349    // DATA PERMISSIONS
     350    // check if this synchronizeable has the permissions to write the data
     351
     352    // first check MASTER_SERVER permissions
     353    if(  this->networkStream->isUserMasterServer( userId ) && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
     354      hasPermission = true;
     355    // now check PROXY_SERVER permissions
     356    else if( this->networkStream->isUserProxyServer( userId )  && (*it)->checkPermission( PERMISSION_MASTER_SERVER ))
     357      hasPermission = true;
     358    // now check OWNER permissions
     359    else if( this->owner == userId && (*it)->checkPermission( PERMISSION_OWNER ))
     360      hasPermission = true;
     361    // now check ALL permissions
     362    else if( (*it)->checkPermission( PERMISSION_ALL ))
     363      hasPermission = true;
     364    // SPECIAL: get write permissions if im sending to a master server that does not own this sync
     365    else if( this->networkStream->isUserMasterServer( userId ) && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
     366      hasPermission = true;
     367    // SPECIAL: get write permissions if im sending to a proxy server that does not own this sync
     368    else if( this->networkStream->isUserProxyServer( userId )  && this->owner != SharedNetworkData::getInstance()->getHostID() && (*it)->checkPermission( PERMISSION_OWNER ))
     369      hasPermission = true;
     370    else
     371      hasPermission = false;
     372
     373
     374
     375    // if it has the permission to write do it
     376    if( hasPermission)
    351377    {
    352378      n = (*it)->readFromBuf( stateTo->data + i, stateTo->dataLength - i );
    353379      i += n;
    354       //NETPRINTF(0)("%s::setvar %s %d\n", getClassName(), (*it)->getName().c_str(), n);
     380      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
     381      //PRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
    355382      //(*it)->debug();
    356383      if ( (*it)->getHasChanged() )
     
    361388    else
    362389    {
    363 //      PRINTF(0)("DONT SET VAR BECAUSE OF PERMISSION: %s %d %d %d %d %d %d\n", (*it)->getName().c_str(), (*it)->checkPermission( PERMISSION_SERVER ), (*it)->checkPermission( PERMISSION_OWNER ), (*it)->checkPermission( PERMISSION_ALL ), networkStream->isUserServer( userId ), this->owner, userId );
     390//      PRINTF(0)("DONT SET VAR BECAUSE OF PERMISSION: %s %d %d %d %d %d %d\n", (*it)->getName().c_str(), (*it)->checkPermission( PERMISSION_MASTER_SERVER ), (*it)->checkPermission( PERMISSION_OWNER ), (*it)->checkPermission( PERMISSION_ALL ), networkStream->isUserServer( userId ), this->owner, userId );
    364391      n = (*it)->getSizeFromBuf( stateTo->data + i, stateTo->dataLength - i );
    365       //NETPRINTF(0)("%s::setvar %s %d\n", getClassName(), (*it)->getName().c_str(), n);
     392      //NETPRINTF(0)("%s::setvar %s %d\n", getClassCName(), (*it)->getName().c_str(), n);
    366393      //(*it)->debug();
    367394      i += n;
     
    370397
    371398  this->varChangeHandler( changes );
    372  
     399
    373400  return i;
    374401}
     
    423450        (*it)->data = NULL;
    424451      }
    425    
     452
    426453      delete *it;
    427454    }
    428455    recvStates[userId].clear();
    429456  }
    430  
     457
    431458  if ( sentStates.size() > userId )
    432459  {
    433    
     460
    434461    for ( std::list<StateHistoryEntry*>::iterator it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
    435462    {
     
    439466        (*it)->data = NULL;
    440467      }
    441    
     468
    442469      delete *it;
    443470    }
     
    448475/**
    449476 * this function is called after recieving a state.
    450  * @param userId 
    451  * @param stateId 
    452  * @param fromStateId 
     477 * @param userId
     478 * @param stateId
     479 * @param fromStateId
    453480 */
    454481void Synchronizeable::handleRecvState( int userId, int stateId, int fromStateId )
     
    457484  if ( recvStates.size() <= userId )
    458485    recvStates.resize( userId+1 );
    459  
     486
    460487  //remove old states
    461488  StateHistory::iterator it = recvStates[userId].begin();
     
    485512      StateHistory::iterator delIt = it;
    486513      it ++;
    487      
     514
    488515      if ( (*delIt)->data )
    489516      {
     
    493520      delete *delIt;
    494521      recvStates[userId].erase( delIt );
    495      
     522
    496523      continue;
    497524    }
    498525    it++;
    499526  }
    500  
     527
    501528  StateHistory::iterator fromState = recvStates[userId].end();
    502529  StateHistory::iterator toState = recvStates[userId].end();
    503  
     530
    504531  for ( it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
    505532  {
     
    508535    if ( (*it)->stateId == fromStateId )
    509536      fromState = it;
    510    
     537
    511538    if ( fromState != recvStates[userId].end() && toState != recvStates[userId].end() )
    512539      break;
    513540  }
    514  
     541
    515542  // setStateDiff was not called and i know fromStateId
    516543  if ( fromState != recvStates[userId].end() && toState == recvStates[userId].end() )
    517544  {
    518545    StateHistoryEntry * entry = new StateHistoryEntry;
    519    
     546
    520547    entry->dataLength = (*fromState)->dataLength;
    521548    if ( entry->dataLength > 0 )
    522549    {
    523550      entry->data = new byte[entry->dataLength];
    524          
     551
    525552      assert( (*fromState)->data );
    526553      memcpy( entry->data, (*fromState)->data, entry->dataLength );
     
    528555    else
    529556      entry->data = NULL;
    530    
     557
    531558    entry->sizeList = (*fromState)->sizeList;
    532559    entry->stateId = stateId;
    533    
     560
    534561    recvStates[userId].push_back(entry);
    535562  }
     
    538565/**
    539566 * this function is called after sending a state
    540  * @param userId 
    541  * @param stateId 
    542  * @param fromStateId 
     567 * @param userId
     568 * @param stateId
     569 * @param fromStateId
    543570 */
    544571void Synchronizeable::handleSentState( int userId, int stateId, int fromStateId )
     
    557584      StateHistory::iterator delIt = it;
    558585      it ++;
    559      
     586
    560587      if ( (*delIt)->data )
    561588      {
     
    565592      delete *delIt;
    566593      sentStates[userId].erase( delIt );
    567      
     594
    568595      continue;
    569596    }
     
    571598  }
    572599
    573  
     600
    574601  StateHistory::iterator fromState = sentStates[userId].end();
    575602  StateHistory::iterator toState = sentStates[userId].end();
    576  
     603
    577604  for ( it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
    578605  {
     
    581608    if ( (*it)->stateId == fromStateId )
    582609      fromState = it;
    583    
     610
    584611    if ( fromState != sentStates[userId].end() && toState != sentStates[userId].end() )
    585612      break;
    586613  }
    587614
    588  
     615
    589616  // getStateDiff was not called and i know fromStateId
    590617  if ( fromState != sentStates[userId].end() && toState == sentStates[userId].end() )
    591618  {
    592619    StateHistoryEntry * entry = new StateHistoryEntry;
    593    
     620
    594621    entry->dataLength = (*fromState)->dataLength;
    595622    if ( entry->dataLength > 0 )
    596623    {
    597624      entry->data = new byte[entry->dataLength];
    598      
     625
    599626      assert( (*fromState)->data );
    600627      memcpy( entry->data, (*fromState)->data, entry->dataLength );
     
    602629    else
    603630      entry->data = NULL;
    604    
     631
    605632    entry->sizeList = (*fromState)->sizeList;
    606633    entry->stateId = stateId;
    607    
     634
    608635    sentStates[userId].push_back(entry);
    609636  }
    610  
    611 }
    612 
    613 
    614 
     637
     638}
     639
     640
     641
  • trunk/src/lib/network/synchronizeable.h

    r8708 r9406  
    11/*!
    22 * @file synchronizeable.h
    3     \brief interface for all classes that have to be synchronized
     3 * @brief interface for all classes that have to be synchronized
    44 */
    55
     
    88
    99#include "base_object.h"
    10 #include "netdefs.h"
    11 #include "converter.h"
    12 #include "vector.h"
    13 #include "quaternion.h"
     10
    1411#include "synchronizeable_var/synchronizeable_var.h"
    1512#include "synchronizeable_var/synchronizeable_vector.h"
     
    2017#include "synchronizeable_var/synchronizeable_bool.h"
    2118#include "synchronizeable_var/synchronizeable_uint.h"
    22 
     19#include "synchronizeable_var/synchronizeable_ip.h"
    2320
    2421#include <vector>
    2522#include <list>
    2623
    27 //State constants: They have to be of the form 2^n
    28 #define STATE_SERVER 1
    2924
    3025struct StateHistoryEntry
     
    5146    virtual ~Synchronizeable();
    5247
    53     void setIsServer( bool isServer );
    54     bool isServer();
    55 
    5648    virtual void varChangeHandler( std::list<int> & id );
    5749
     
    6153    virtual void handleSentState( int userId, int stateId, int fromStateId );
    6254    virtual void handleRecvState( int userId, int stateId, int fromStateId );
    63    
     55
    6456    void registerVar( SynchronizeableVar * var );
    6557    int registerVarId( SynchronizeableVar * var );
     
    8274  protected:
    8375    NetworkStream*    networkStream;  //!< reference network stream we are connected to
    84     int               state;
     76
    8577
    8678  private:
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_bool.cc

    r7954 r9406  
    1616
    1717#include "synchronizeable_bool.h"
     18#include <cassert>
    1819
    1920
     
    4445{
    4546  assert( maxLength >= 1 );
    46  
     47
    4748  buf[0] = ( *vPtrIn ) ? 1 : 0;
    48  
     49
    4950  return 1;
    5051}
     
    5960{
    6061  assert( maxLength >= 1 );
    61  
     62
    6263  bool oldVal = *vPtrOut;
    63  
     64
    6465  *vPtrOut = buf[0] != 0;
    65  
     66
    6667  setHasChanged( oldVal != *vPtrOut );
    67  
     68
    6869  return 1;
    6970}
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_bool.h

    r7954 r9406  
    22 * @file synchronizeable_int.h
    33 * @brief Definition of SynchronizeableInt
    4 */
    5 
    6 #include "synchronizeable_var/synchronizeable_var.h"
     4 */
    75
    86#ifndef _SYNCHRONIZEABLE_BOOL_H
    97#define _SYNCHRONIZEABLE_BOOL_H
    108
     9#include "synchronizeable_var.h"
     10
    1111class SynchronizeableBool : public SynchronizeableVar {
    1212
    1313  public:
    14     SynchronizeableBool( bool * ptrIn, bool * ptrOut, std::string name, int permission = PERMISSION_SERVER, int priority = 0 );
     14    SynchronizeableBool( bool * ptrIn, bool * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
    1515    virtual ~SynchronizeableBool();
    16    
     16
    1717    virtual int writeToBuf( byte * buf, int maxLength );
    1818    virtual int readFromBuf( byte * buf, int maxLength );
    19    
     19
    2020    /**
    2121     * check if writeToBuf will return the same size every time
     
    2323     */
    2424    virtual bool hasStaticSize(){ return true; };
    25    
     25
    2626    virtual void debug();
    27    
     27
    2828  private:
    2929    bool * vPtrIn;       //!< pointer to data (read)
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_float.cc

    r7954 r9406  
    1717#include "synchronizeable_float.h"
    1818#include "converter.h"
     19#include <cassert>
    1920
    2021
     
    4647{
    4748  int res = Converter::floatToByteArray( *vPtrIn, buf, maxLength );
    48  
     49
    4950  assert( res == FLOATSIZE );
    50  
     51
    5152  return res;
    5253}
     
    6162{
    6263  assert( maxLength >= FLOATSIZE );
    63  
     64
    6465  float oldVal = *vPtrOut;
    65  
     66
    6667  int res = Converter::byteArrayToFloat( buf, vPtrOut );
    67  
     68
    6869  setHasChanged( oldVal != *vPtrOut );
    69  
     70
    7071  assert( res == FLOATSIZE );
    71  
     72
    7273  return res;
    7374}
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_float.h

    r7954 r9406  
    22 * @file synchronizeable_float.h
    33 * @brief Definition of SynchronizeableFloat
    4 */
     4 */
    55
    6 #include "synchronizeable_var/synchronizeable_var.h"
    76
    87#ifndef _SYNCHRONIZEABLE_FLOAT_H
    98#define _SYNCHRONIZEABLE_FLOAT_H
    109
     10#include "synchronizeable_var.h"
     11
    1112class SynchronizeableFloat : public SynchronizeableVar {
    1213
    1314  public:
    14     SynchronizeableFloat( float * ptrIn, float * ptrOut, std::string name, int permission = PERMISSION_SERVER, int priority = 0 );
     15    SynchronizeableFloat( float * ptrIn, float * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
    1516    virtual ~SynchronizeableFloat();
    16    
     17
    1718    virtual int writeToBuf( byte * buf, int maxLength );
    1819    virtual int readFromBuf( byte * buf, int maxLength );
    19        
     20
    2021    /**
    2122     * check if writeToBuf will return the same size every time
     
    2324     */
    2425    virtual bool hasStaticSize(){ return true; };
    25    
     26
    2627    virtual void debug();
    27    
     28
    2829  private:
    2930    float * vPtrIn;       //!< pointer to data (read)
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_int.cc

    r7954 r9406  
    1818#include "converter.h"
    1919
     20#include <cassert>
    2021
    2122/**
     
    4647{
    4748  int res = Converter::intToByteArray( *vPtrIn, buf, maxLength );
    48  
     49
    4950  assert( res == INTSIZE );
    50  
     51
    5152  return res;
    5253}
     
    6162{
    6263  assert( maxLength >= INTSIZE );
    63  
     64
    6465  int oldVal = *vPtrOut;
    65  
     66
    6667  int res = Converter::byteArrayToInt( buf, vPtrOut );
    67  
     68
    6869  setHasChanged( oldVal != *vPtrOut );
    69  
     70
    7071  assert( res == INTSIZE );
    71  
     72
    7273  return res;
    7374}
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_int.h

    r7954 r9406  
    44*/
    55
    6 #include "synchronizeable_var/synchronizeable_var.h"
    76
    87#ifndef _SYNCHRONIZEABLE_INT_H
    98#define _SYNCHRONIZEABLE_INT_H
    109
     10#include "synchronizeable_var.h"
     11
    1112class SynchronizeableInt : public SynchronizeableVar {
    1213
    1314  public:
    14     SynchronizeableInt( int * ptrIn, int * ptrOut, std::string name, int permission = PERMISSION_SERVER, int priority = 0 );
     15    SynchronizeableInt( int * ptrIn, int * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
    1516    virtual ~SynchronizeableInt();
    16    
     17
    1718    virtual int writeToBuf( byte * buf, int maxLength );
    1819    virtual int readFromBuf( byte * buf, int maxLength );
    19    
     20
    2021    /**
    2122     * check if writeToBuf will return the same size every time
     
    2324     */
    2425    virtual bool hasStaticSize(){ return true; };
    25    
     26
    2627    virtual void debug();
    27    
     28
    2829  protected:
    2930    int * vPtrIn;       //!< pointer to data (read)
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_quaternion.cc

    r7954 r9406  
    1717#include "synchronizeable_quaternion.h"
    1818#include "converter.h"
     19#include <cassert>
    1920
    2021
     
    9899  assert( res > 0 );
    99100  n += res;
    100  
     101
    101102  Quaternion oldVal = *vPtrOut;
    102103
    103104  *vPtrOut = Quaternion( Vector(x, y, z), w );
    104  
     105
    105106  setHasChanged( ! ( oldVal == *vPtrOut ) );
    106107
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_quaternion.h

    r7954 r9406  
    44*/
    55
    6 #include "synchronizeable_var/synchronizeable_var.h"
    7 
    86#ifndef _SYNCHRONIZEABLE_QUATERNION_H
    97#define _SYNCHRONIZEABLE_QUATERNION_H
     8
     9#include "synchronizeable_var.h"
    1010
    1111#include "quaternion.h"
     
    1414
    1515  public:
    16     SynchronizeableQuaternion( Quaternion * ptrIn, Quaternion * ptrOut, std::string name, int permission = PERMISSION_SERVER, int priority = 0 );
     16    SynchronizeableQuaternion( Quaternion * ptrIn, Quaternion * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
    1717    virtual ~SynchronizeableQuaternion();
    18    
     18
    1919    virtual int writeToBuf( byte * buf, int maxLength );
    2020    virtual int readFromBuf( byte * buf, int maxLength );
    21        
     21
    2222    /**
    2323     * check if writeToBuf will return the same size every time
     
    2525     */
    2626    virtual bool hasStaticSize(){ return true; };
    27    
     27
    2828    virtual void debug();
    29    
     29
    3030  private:
    3131    Quaternion * vPtrIn;       //!< pointer to data (read)
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_string.cc

    r8147 r9406  
    1717#include "synchronizeable_string.h"
    1818#include "converter.h"
     19#include <cassert>
    1920
    2021
     
    4647{
    4748  int res = Converter::stringToByteArray( *vPtrIn, buf, maxLength );
    48  
     49
    4950  assert( res > 0 );
    5051  assert( res == vPtrIn->length()+INTSIZE );
    51  
     52
    5253  return res;
     54}
     55
     56int SynchronizeableString::getSize()
     57{
     58   return vPtrIn->length()+INTSIZE;
    5359}
    5460
     
    6268{
    6369  std::string oldVal = *vPtrOut;
    64      
     70
    6571  int res = Converter::byteArrayToString( buf, *vPtrOut, maxLength );
    66  
     72
    6773  setHasChanged( oldVal != *vPtrOut );
    68  
     74
    6975  if ( res < 0 )
    7076  {
     
    7278  }
    7379  assert( res > 0 );
    74  
     80
    7581  return res;
    7682}
     
    94100{
    95101  std::string t;
    96  
     102
    97103  int res = Converter::byteArrayToString( buf, t, maxLength );
    98  
     104
    99105  assert( res > 0 );
    100  
     106
    101107  return res;
    102108}
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_string.h

    r7954 r9406  
    44*/
    55
    6 #include "synchronizeable_var/synchronizeable_var.h"
    7 #include "converter.h"
    8 
    96#ifndef _SYNCHRONIZEABLE_STRING_H
    107#define _SYNCHRONIZEABLE_STRING_H
     8
     9#include "synchronizeable_var.h"
    1110
    1211#include <string>
     
    1514
    1615  public:
    17     SynchronizeableString( std::string * ptrIn, std::string * ptrOut, std::string name, int permission = PERMISSION_SERVER, int priority = 0 );
     16    SynchronizeableString( std::string * ptrIn, std::string * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
    1817    virtual ~SynchronizeableString();
    19    
     18
    2019    virtual int writeToBuf( byte * buf, int maxLength );
    2120    virtual int readFromBuf( byte * buf, int maxLength );
    22    
    23        
     21
     22
    2423    /**
    2524     * check if writeToBuf will return the same size every time
     
    2726     */
    2827    virtual bool hasStaticSize(){ return false; };
    29    
    30     virtual int getSize(){ return vPtrIn->length()+INTSIZE; }
    31    
     28
     29    virtual int getSize();
     30
    3231    virtual int getSizeFromBuf( byte * buf, int maxLength );
    33    
     32
    3433    virtual void debug();
    35    
     34
    3635  private:
    3736    std::string * vPtrIn;       //!< pointer to data (read)
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_uint.h

    r7954 r9406  
    44*/
    55
    6 #include "synchronizeable_var/synchronizeable_int.h"
    76
    87#ifndef _SYNCHRONIZEABLE_UINT_H
    98#define _SYNCHRONIZEABLE_UINT_H
    109
     10#include "synchronizeable_int.h"
     11
    1112class SynchronizeableUInt : public SynchronizeableInt {
    1213
    1314  public:
    14     SynchronizeableUInt( unsigned int * ptrIn, unsigned int * ptrOut, std::string name, int permission = PERMISSION_SERVER, int priority = 0 );
     15    SynchronizeableUInt( unsigned int * ptrIn, unsigned int * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
    1516    virtual ~SynchronizeableUInt();
    16    
     17
    1718    virtual void debug();
    1819
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_var.cc

    r7954 r9406  
    1616
    1717#include "synchronizeable_var.h"
    18 
     18#include "netdefs.h"
     19#include <cassert>
    1920
    2021
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_var.h

    r7954 r9406  
    77#define _SYNCHRONIZEABLE_VAR_H
    88
     9#include "nettypes.h"
    910#include <string>
    10 #include "netdefs.h"
    11 #include <assert.h>
    1211
    1312enum {
    14   PERMISSION_SERVER = 1,
    15   PERMISSION_OWNER  = 2,
    16   PERMISSION_ALL    = 4
     13  PERMISSION_MASTER_SERVER = 1,
     14  PERMISSION_PROXY_SERVER  = 2,
     15  PERMISSION_OWNER         = 4,
     16  PERMISSION_ALL           = 8
    1717};
    1818
     
    2020
    2121  public:
    22     SynchronizeableVar( void * ptrIn, void * ptrOut, std::string name, int length, int permission = PERMISSION_SERVER, int priority = 0 );
     22    SynchronizeableVar( void * ptrIn, void * ptrOut, std::string name, int length, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
    2323    virtual ~SynchronizeableVar();
    2424
     
    2828     */
    2929    inline bool beWatched(){ return this->bWatched; }
    30    
    31     /** 
     30
     31    /**
    3232     * set flag if synchronizeable wants to be informed on changes
    3333     */
     
    9696     */
    9797    inline void resetPriority() { this->priority = this->realPriority; }
    98    
     98
    9999    /**
    100100     * reads actual size from buffer. this is used when size is not constant
     
    104104     */
    105105    virtual inline int getSizeFromBuf( byte * buf, int maxLength ){ return this->getSize(); }
    106    
     106
    107107    /**
    108108     * set variable id
     
    110110     */
    111111    inline void setVarId( int id ){ this->varId = id; }
    112    
    113     /** 
     112
     113    /**
    114114     * get variable id
    115115     * @return variable id
    116116     */
    117117    inline int getVarId(){ return varId; }
    118    
     118
    119119    /**
    120120     * set hasChanged
     
    122122     */
    123123    inline void setHasChanged( bool changed ){ this->changed = changed; }
    124    
    125     /** 
     124
     125    /**
    126126     * get hasChanged
    127127     * @return variable id
    128128     */
    129129    inline bool getHasChanged(){ return changed; }
    130    
     130
    131131    /**
    132132     * print out variable value
     
    137137  private:
    138138    bool bWatched;      //!< true if synchronizeable wants to be informed on changes
    139    
     139
    140140    int permission;     //!< who is allowed to change this var
    141141    int priority;       //!< priority assigned to var
    142142    int realPriority;   //!< priority assigned to var, increased every time not sent
    143143    int varId;          //!< id to identify varables
    144    
     144
    145145    bool changed;       //!< true if last readFromBuf changed anything
    146146
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_vector.cc

    r7954 r9406  
    1717#include "synchronizeable_vector.h"
    1818#include "converter.h"
     19#include <cassert>
    1920
    2021
     
    7980  int res;
    8081  int n = 0;
    81  
     82
    8283  Vector oldVec = *vPtrOut;
    8384
     
    9596
    9697  *vPtrOut = Vector( x, y, z );
    97  
     98
    9899  setHasChanged( !(*vPtrOut == oldVec) );
    99100
  • trunk/src/lib/network/synchronizeable_var/synchronizeable_vector.h

    r7954 r9406  
    44*/
    55
    6 #include "synchronizeable_var/synchronizeable_var.h"
    7 
    86#ifndef _SYNCHRONIZEABLE_VECTOR_H
    97#define _SYNCHRONIZEABLE_VECTOR_H
     8
     9#include "synchronizeable_var.h"
    1010
    1111#include "vector.h"
     
    1414
    1515  public:
    16     SynchronizeableVector( Vector * ptrIn, Vector * ptrOut, std::string name, int permission = PERMISSION_SERVER, int priority = 0 );
     16    SynchronizeableVector( Vector * ptrIn, Vector * ptrOut, std::string name, int permission = PERMISSION_MASTER_SERVER, int priority = 0 );
    1717    virtual ~SynchronizeableVector();
    18    
     18
    1919    virtual int writeToBuf( byte * buf, int maxLength );
    2020    virtual int readFromBuf( byte * buf, int maxLength );
    21    
     21
    2222    /**
    2323     * check if writeToBuf will return the same size every time
     
    2525     */
    2626    virtual bool hasStaticSize(){ return true; }
    27    
     27
    2828    virtual void debug();
    29    
     29
    3030  private:
    3131    Vector * vPtrIn;       //!< pointer to data (read)
  • trunk/src/lib/network/tcp_server_socket.cc

    r7954 r9406  
    136136  _isListening = false;
    137137}
     138
  • trunk/src/lib/network/tcp_server_socket.h

    r7954 r9406  
    2828    virtual void close();
    2929    virtual void update() {};
    30    
     30
    3131  private:
    3232    TCPsocket listenSocket;
     
    3636
    3737    void init();
    38  
     38
    3939};
    4040
  • trunk/src/lib/network/tcp_socket.h

    r7954 r9406  
    11/*!
    2  * @file network_socket.h
    3   *  Main interface for the network module. Manages all the modules
     2 * @file tcp_socket.h
     3  *  tcp socket network interface
    44
    55*/
     
    1616#define _INCOMING_BUFFER_SIZE 2024000
    1717#define _OUTGOING_BUFFER_SIZE 2024000
    18 #define _LOCAL_BUFFER_SIZE 1024
     18#define _LOCAL_BUFFER_SIZE 2048
    1919//sleep if incoming buffer is full
    2020#define _MSECONDS_SLEEP_FULL_BUFFER 10
     
    4747
    4848    virtual void connectToServer( std::string host, int port );
    49    
     49
    5050    virtual void disconnectServer();
     51    virtual void reconnectToServer( std::string host, int port);
     52    virtual void reconnectToServerSoft( std::string host, int port);
    5153
    5254    virtual bool writePacket(byte * data, int length);
  • trunk/src/lib/network/udp_socket.cc

    r8802 r9406  
    7474{
    7575  this->init();
     76  this->ip = ip;
    7677  this->serverSocket = serverSocket;
    7778  this->userId = userId;
     
    105106  assert( serverSocket == NULL );
    106107
    107   IPaddress ip;
    108  
    109108  this->randomByte = generateNewRandomByte();
    110109
    111110  PRINTF(0)("connect to server %s on port %d\n", host.c_str(), port);
    112111
    113   if ( SDLNet_ResolveHost( &ip, host.c_str(), port ) != 0 )
     112  if ( SDLNet_ResolveHost( &this->ip, host.c_str(), port ) != 0 )
    114113  {
    115114    PRINTF(1)("SDLNet_ResolveHost: %s\n", SDLNet_GetError() );
     
    126125  }
    127126
    128   int channel = SDLNet_UDP_Bind(socket, 1, &ip);
     127  int channel = SDLNet_UDP_Bind(socket, 1, &this->ip);
    129128  if ( channel == -1 )
    130129  {
     
    147146  bOk = false;
    148147  socket = NULL;
    149 }
     148
     149  this->ip.host = 0;
     150  this->ip.port = 0;
     151}
     152
     153
     154/**
     155 * reconnects to
     156 * @param host new server address
     157 * @param port new port number
     158 *
     159 * this terminates the current connection and starts a new connection to the new server
     160 */
     161void UdpSocket::reconnectToServer( std::string host, int port)
     162{
     163  // first disconnect the old server
     164  this->disconnectServer();
     165
     166  // now connect to the new
     167  this->connectToServer( host, port);
     168}
     169
     170
     171/**
     172 * reconnects to
     173 * @param host new server address
     174 * @param port new port number
     175 *
     176 * this terminates the current connection and starts a new connection to the new server
     177 */
     178void UdpSocket::reconnectToServerSoft( std::string host, int port)
     179{}
     180
    150181
    151182/**
     
    179210
    180211    byte udpCmd = 0;
    181    
     212
    182213    if ( networkPacket.length > 0 )
    183214    {
     
    189220    else
    190221      return 0;
    191      
     222
    192223    if ( !checkRandomByte( networkPacket.data[0] ) )
    193224      return 0;
     
    198229      networkPacket.data = NULL;
    199230    }
    200    
     231
    201232    if ( !checkUdpCmd( udpCmd ) )
    202233      return 0;
     
    207238  {
    208239    int numrecv = SDLNet_UDP_Recv( socket, packet);
    209    
     240
    210241    byte udpCmd = 0;
    211242
     
    218249      else
    219250        return 0;
    220            
     251
    221252      if ( !checkRandomByte( packet->data[0] ) )
    222253        return 0;
    223              
     254
    224255      if ( !checkUdpCmd( udpCmd ) )
    225256        return 0;
     
    283314    return false;
    284315  }
    285  
     316
    286317  if ( !this->serverSocket && ( udpCmd & UDPCMD_INVALIDRNDBYTE ) )
    287318  {
     
    292323    return false;
    293324  }
    294  
     325
    295326  return true;
    296327}
     
    300331  srand( SDL_GetTicks() );
    301332  byte res = ( rand() & 0xFC );
    302  
     333
    303334  PRINTF(0)("generated random byte: %x\n", res);
    304  
     335
    305336  return res;
    306337}
  • trunk/src/lib/network/udp_socket.h

    r8802 r9406  
    3131
    3232    virtual void connectToServer( std::string host, int port );
    33    
    3433    virtual void disconnectServer();
    3534
     35    virtual void reconnectToServer( std::string host, int port);
     36    virtual void reconnectToServerSoft( std::string host, int port);
     37
    3638    virtual bool writePacket(byte * data, int length );
     39    virtual int readPacket(byte * data, int maxLength);
    3740
    38     virtual int readPacket(byte * data, int maxLength);
    39    
     41
    4042  private:
    4143    UdpServerSocket * serverSocket;   //!< will get packets here
    4244    int               userId;         //!< user id used by serverSocket
    43     IPaddress         ip;             //!< host,port
    4445    UDPsocket         socket;         //!< socket used to send/recieve
    4546    UDPpacket *       packet;
    46    
     47
    4748    byte              randomByte;     //!< contains random bytes & 0xFC
    48    
     49
    4950    bool writeRawPacket( byte * data, int length );
    5051    bool checkUdpCmd( byte udpCmd );
    5152    bool checkRandomByte( byte rndByte );
    5253    byte generateNewRandomByte();
    53    
     54
    5455    void init();
    5556
Note: See TracChangeset for help on using the changeset viewer.