Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/proxy/src/lib/network/network_stream.cc @ 9291

Last change on this file since 9291 was 9291, checked in by patrick, 18 years ago

network socket and addresses passins

File size: 25.6 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
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*/
18
19
20#define DEBUG_MODULE_NETWORK
21
22
23#include "base_object.h"
24#include "network_protocol.h"
25#include "udp_socket.h"
26#include "udp_server_socket.h"
27#include "monitor/connection_monitor.h"
28#include "monitor/network_monitor.h"
29#include "synchronizeable.h"
30#include "network_game_manager.h"
31#include "shared_network_data.h"
32#include "message_manager.h"
33#include "preferences.h"
34#include "zip.h"
35
36#include "src/lib/util/loading/resource_manager.h"
37
38#include "network_log.h"
39
40#include "player_stats.h"
41
42#include "lib/util/loading/factory.h"
43
44#include "debug.h"
45#include "class_list.h"
46#include <algorithm>
47
48
49#include "network_stream.h"
50
51
52using namespace std;
53
54
55#define PACKAGE_SIZE  256
56
57
58/**
59 * empty constructor
60 */
61NetworkStream::NetworkStream()
62    : DataStream()
63{
64  this->init();
65  /* initialize the references */
66  this->pInfo->nodeType = NET_CLIENT;
67}
68
69
70/**
71 * start as a client, connect to a server
72 *  @param host: host name (address)
73 *  @param port: port number
74 */
75NetworkStream::NetworkStream( std::string host, int port )
76{
77  this->init();
78  // init the peers[0] the server to ceonnect to
79  this->peers[0].socket = new UdpSocket( host, port );
80  this->peers[0].userId = 0;
81  this->peers[0].nodeType = NET_MASTER_SERVER;
82  this->peers[0].connectionMonitor = new ConnectionMonitor( 0 );
83  // and set also the localhost
84  this->pInfo->nodeType = NET_CLIENT;
85}
86
87
88/**
89 * start as a server
90 *  @param port: at this port
91 */
92NetworkStream::NetworkStream( int port )
93{
94  this->init();
95  this->serverSocket = new UdpServerSocket(port);
96  this->pInfo->nodeType = NET_MASTER_SERVER;
97}
98
99
100/**
101 * generic init functions
102 */
103void NetworkStream::init()
104{
105  /* set the class id for the base object */
106  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
107  this->serverSocket = NULL;
108  this->networkGameManager = NULL;
109  this->networkMonitor = NULL;
110
111  this->pInfo = new PeerInfo();
112  this->pInfo->userId = 0;
113  this->pInfo->lastAckedState = 0;
114  this->pInfo->lastRecvedState = 0;
115
116
117  this->currentState = 0;
118
119  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
120
121  assert( Zip::getInstance()->loadDictionary( "testdict" ) >= 0 );
122  this->dictClient = Zip::getInstance()->loadDictionary( "dict2pl_client" );
123  assert( this->dictClient >= 0 );
124  this->dictServer = Zip::getInstance()->loadDictionary( "dict2p_server" );
125  assert( this->dictServer >= 0 );
126}
127
128
129/**
130 * deconstructor
131 */
132NetworkStream::~NetworkStream()
133{
134  if ( this->serverSocket )
135  {
136    serverSocket->close();
137    delete serverSocket;
138    serverSocket = NULL;
139  }
140  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
141  {
142    if ( i->second.socket )
143    {
144      i->second.socket->disconnectServer();
145      delete i->second.socket;
146      i->second.socket = NULL;
147    }
148
149    if ( i->second.handshake )
150    {
151      delete i->second.handshake;
152      i->second.handshake = NULL;
153    }
154
155    if ( i->second.connectionMonitor )
156    {
157      delete i->second.connectionMonitor;
158      i->second.connectionMonitor = NULL;
159    }
160  }
161  for ( SynchronizeableList::const_iterator it = getSyncBegin(); it != getSyncEnd(); it ++ )
162    (*it)->setNetworkStream( NULL );
163
164  if( this->pInfo)
165    delete this->pInfo;
166}
167
168
169/**
170 * creates a new instance of the network game manager
171 */
172void NetworkStream::createNetworkGameManager()
173{
174  this->networkGameManager = NetworkGameManager::getInstance();
175  // setUniqueID( maxCon+2 ) because we need one id for every handshake
176  // and one for handshake to reject client maxCon+1
177  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
178  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
179}
180
181
182/**
183 * starts the network handshake
184 */
185void NetworkStream::startHandshake()
186{
187  Handshake* hs = new Handshake(this->pInfo->nodeType);
188  hs->setUniqueID( 0 );
189  assert( peers[0].handshake == NULL );
190  peers[0].handshake = hs;
191
192  hs->setPreferedNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Player" ) );
193
194//   peers[0].handshake->setSynchronized( true );
195  //this->connectSynchronizeable(*hs);
196  //this->connectSynchronizeable(*hs);
197  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getName());
198}
199
200
201/**
202 * this functions connects a synchronizeable to the networkstream, therefore synchronizeing
203 * it all over the network and creating it on the other platforms (if and only if it is a
204 * server
205 */
206void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
207{
208  this->synchronizeables.push_back(&sync);
209  sync.setNetworkStream( this );
210
211//   this->bActive = true;
212}
213
214
215/**
216 * removes the synchronizeable from the list of synchronized entities
217 */
218void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
219{
220  // removing the Synchronizeable from the List.
221  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
222  if (disconnectSynchro != this->synchronizeables.end())
223    this->synchronizeables.erase(disconnectSynchro);
224
225  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
226}
227
228
229/**
230 * this is called to process data from the network socket to the synchronizeable and vice versa
231 */
232void NetworkStream::processData()
233{
234  // create the network monitor after all the init work and before there is any connection handlings
235  if( this->networkMonitor == NULL)
236    this->networkMonitor = new NetworkMonitor(this);
237
238
239  int tick = SDL_GetTicks();
240
241  this->currentState++;
242  // there was a wrap around
243  if( this->currentState < 0)
244  {
245    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");
246  }
247
248  if ( this->pInfo->nodeType == NET_MASTER_SERVER )
249  {
250    // execute everytthing the master server shoudl do
251    if ( serverSocket )
252      serverSocket->update();
253
254    this->updateConnectionList();
255  }
256  else if( this->pInfo->nodeType == NET_PROXY_SERVER)
257  {
258    // execute everything the proxy server should do
259  }
260  else
261  {
262    // check if the connection is ok else terminate and remove
263    if ( peers[0].socket && ( !peers[0].socket->isOk() || peers[0].connectionMonitor->hasTimedOut() ) )
264    {
265      PRINTF(1)("lost connection to server\n");
266
267      peers[0].socket->disconnectServer();
268      delete peers[0].socket;
269      peers[0].socket = NULL;
270
271      if ( peers[0].handshake )
272        delete peers[0].handshake;
273      peers[0].handshake = NULL;
274
275      if ( peers[0].connectionMonitor )
276        delete peers[0].connectionMonitor;
277      peers[0].connectionMonitor = NULL;
278    }
279  }
280
281  cleanUpOldSyncList();
282  handleHandshakes();
283
284  // update the network monitor
285  this->networkMonitor->process();
286
287  // order of up/downstream is important!!!!
288  // don't change it
289  handleDownstream( tick );
290  handleUpstream( tick );
291}
292
293
294/**
295 * if we are a server update the connection list to accept new connections (clients)
296 * also start the handsake for the new clients
297 */
298void NetworkStream::updateConnectionList( )
299{
300  //check for new connections
301
302  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
303
304  // we got new network node
305  if ( tempNetworkSocket )
306  {
307    int clientId;
308    // if there is a list of free client id slots, take these
309    if ( freeSocketSlots.size() > 0 )
310    {
311      clientId = freeSocketSlots.back();
312      freeSocketSlots.pop_back();
313      peers[clientId].socket = tempNetworkSocket;
314      peers[clientId].handshake = new Handshake(this->pInfo->nodeType, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID() );
315      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
316      peers[clientId].handshake->setUniqueID(clientId);
317      peers[clientId].userId = clientId;
318      peers[clientId].nodeType = NET_CLIENT;
319    }
320    else
321    {
322      clientId = 1;
323
324      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
325        if ( it->first >= clientId )
326          clientId = it->first + 1;
327
328      peers[clientId].socket = tempNetworkSocket;
329      peers[clientId].handshake = new Handshake(this->pInfo->nodeType, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
330      peers[clientId].handshake->setUniqueID(clientId);
331      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
332      peers[clientId].userId = clientId;
333      peers[clientId].nodeType = NET_CLIENT;
334
335      PRINTF(0)("num sync: %d\n", synchronizeables.size());
336    }
337
338    // check if there are too many clients connected
339    if ( clientId > NET_MAX_CONNECTIONS )
340    {
341      peers[clientId].handshake->doReject( "too many connections" );
342      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
343    }
344    else
345    {
346      PRINTF(0)("New Client: %d\n", clientId);
347    }
348
349    //this->connectSynchronizeable(*handshakes[clientId]);
350  }
351
352
353
354  //check if connections are ok else remove them
355  for ( PeerList::iterator it = peers.begin(); it != peers.end(); )
356  {
357    if (
358          it->second.socket &&
359          (
360            !it->second.socket->isOk()  ||
361            it->second.connectionMonitor->hasTimedOut()
362          )
363       )
364    {
365      std::string reason = "disconnected";
366      if ( it->second.connectionMonitor->hasTimedOut() )
367        reason = "timeout";
368      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
369
370
371      // clean up the network data
372      it->second.socket->disconnectServer();
373      delete it->second.socket;
374      it->second.socket = NULL;
375
376      if ( it->second.connectionMonitor )
377        delete it->second.connectionMonitor;
378      it->second.connectionMonitor = NULL;
379
380      if ( it->second.handshake )
381        delete it->second.handshake;
382      it->second.handshake = NULL;
383
384      for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )
385      {
386        (*it2)->cleanUpUser( it->second.userId );
387      }
388
389      NetworkGameManager::getInstance()->signalLeftPlayer(it->second.userId);
390
391      freeSocketSlots.push_back( it->second.userId );
392
393      PeerList::iterator delit = it;
394      it++;
395
396      peers.erase( delit );
397
398      continue;
399    }
400
401    it++;
402  }
403
404
405}
406
407
408void NetworkStream::debug()
409{
410  if( this->isMasterServer())
411    PRINT(0)(" Host ist Server with ID: %i\n", this->pInfo->userId);
412  else
413    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
414
415  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
416  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
417  {
418    if( (*it)->beSynchronized() == true)
419      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
420               (*it)->getUniqueID(), (*it)->beSynchronized());
421  }
422  PRINT(0)(" Maximal Connections: %i\n", NET_MAX_CONNECTIONS );
423
424}
425
426
427/**
428 * @returns the number of synchronizeables registered to this stream
429 */
430int NetworkStream::getSyncCount()
431{
432  int n = 0;
433  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
434    if( (*it)->beSynchronized() == true)
435      ++n;
436
437  //return synchronizeables.size();
438  return n;
439}
440
441
442/**
443 * check if handshakes completed. if so create the network game manager else remove it again
444 */
445void NetworkStream::handleHandshakes( )
446{
447  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
448  {
449    if ( it->second.handshake )
450    {
451      // handshake finished
452      if ( it->second.handshake->completed() )
453      {
454        //handshake is correct
455        if ( it->second.handshake->ok() )
456        {
457          if ( !it->second.handshake->allowDel() )
458          {
459            if ( this->pInfo->nodeType == NET_CLIENT )
460            {
461              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
462              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
463
464              it->second.nodeType = it->second.handshake->getRemoteNodeType();
465              it->second.ip = it->second.socket->getDestAddress();
466              this->networkMonitor->addNode(&it->second);
467
468              this->networkGameManager = NetworkGameManager::getInstance();
469              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
470              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
471            }
472
473
474            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
475
476            it->second.handshake->del();
477          }
478          else
479          {
480            // handsheke finished registring new player
481            if ( it->second.handshake->canDel() )
482            {
483              if ( this->pInfo->nodeType == NET_MASTER_SERVER )
484              {
485                it->second.nodeType = it->second.handshake->getRemoteNodeType();
486                this->networkMonitor->addNode(&it->second);
487
488                handleNewClient( it->second.userId );
489
490                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
491                {
492                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
493                }
494              }
495
496              PRINT(0)("handshake finished delete it\n");
497              delete it->second.handshake;
498              it->second.handshake = NULL;
499            }
500          }
501
502        }
503        else
504        {
505          PRINT(1)("handshake failed!\n");
506          it->second.socket->disconnectServer();
507        }
508      }
509    }
510  }
511}
512
513
514/**
515 * handle upstream network traffic
516 */
517void NetworkStream::handleUpstream( int tick )
518{
519  int offset;
520  int n;
521
522  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
523  {
524    offset = INTSIZE; // reserve enough space for the packet length
525
526    // continue with the next peer if this peer has no socket assigned (therefore no network)
527    if ( !peer->second.socket )
528      continue;
529
530    // header informations: current state
531    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
532    assert( n == INTSIZE );
533    offset += n;
534
535    // header informations: last acked state
536    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
537    assert( n == INTSIZE );
538    offset += n;
539
540    // header informations: last recved state
541    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
542    assert( n == INTSIZE );
543    offset += n;
544
545    // now write all synchronizeables in the packet
546    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
547    {
548      int oldOffset = offset;
549      Synchronizeable & sync = **it;
550
551      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
552      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
553        continue;
554
555      // if handshake not finished only sync handshake
556      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
557        continue;
558
559      // if we are a server and this is not our handshake
560      if ( isMasterServer() && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
561        continue;
562
563      /* list of synchronizeables that will never be synchronized over the network: */
564      // do not sync null parent
565      if ( sync.getLeafClassID() == CL_NULL_PARENT )
566        continue;
567
568      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
569
570      // server fakes uniqueid == 0 for handshake
571      if ( this->isMasterServer() && sync.getUniqueID() < NET_MAX_CONNECTIONS - 1 )
572        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
573      else
574        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
575
576      assert( n == INTSIZE );
577      offset += n;
578
579      // make space for size
580      offset += INTSIZE;
581
582      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
583      offset += n;
584
585      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
586
587      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
588      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
589      bool allZero = true;
590      for ( int i = 0; i < n; i++ )
591      {
592         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
593           allZero = false;
594      }
595      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
596      // data that hast not changed
597      if ( allZero )
598      {
599        offset = oldOffset;
600      }
601    } // all synchronizeables written
602
603
604
605    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
606    {
607      Synchronizeable & sync = **it;
608
609      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
610        continue;
611
612      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
613    }
614
615
616    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
617
618    // now compress the data with the zip library
619    int compLength = 0;
620    if ( this->isMasterServer() )
621      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
622    else
623      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
624
625    if ( compLength <= 0 )
626    {
627      PRINTF(1)("compression failed!\n");
628      continue;
629    }
630
631    assert( peer->second.socket->writePacket( compBuf, compLength ) );
632
633    if ( this->remainingBytesToWriteToDict > 0 )
634      writeToNewDict( buf, offset, true );
635
636    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
637    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
638
639  }
640}
641
642/**
643 * handle downstream network traffic
644 */
645void NetworkStream::handleDownstream( int tick )
646{
647  int offset = 0;
648
649  int length = 0;
650  int packetLength = 0;
651  int compLength = 0;
652  int uniqueId = 0;
653  int state = 0;
654  int ackedState = 0;
655  int fromState = 0;
656  int syncDataLength = 0;
657
658  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
659  {
660
661    if ( !peer->second.socket )
662      continue;
663
664    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
665    {
666      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
667
668      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
669
670      if ( packetLength < 4*INTSIZE )
671      {
672        if ( packetLength != 0 )
673          PRINTF(1)("got too small packet: %d\n", packetLength);
674        continue;
675      }
676
677      if ( this->remainingBytesToWriteToDict > 0 )
678        writeToNewDict( buf, packetLength, false );
679
680      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
681      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
682      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
683      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
684      offset = 4*INTSIZE;
685
686      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
687
688
689      //if this is an old state drop it
690      if ( state <= peer->second.lastRecvedState )
691        continue;
692
693      if ( packetLength != length )
694      {
695        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
696        peer->second.socket->disconnectServer();
697        continue;
698      }
699
700      while ( offset + 2*INTSIZE < length )
701      {
702        assert( offset > 0 );
703        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
704        offset += INTSIZE;
705
706        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
707        offset += INTSIZE;
708
709        assert( syncDataLength > 0 );
710        assert( syncDataLength < 10000 );
711
712        Synchronizeable * sync = NULL;
713
714        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
715        {
716        //                                        client thinks his handshake has id 0!!!!!
717          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
718          {
719            sync = *it;
720            break;
721          }
722        }
723
724        if ( sync == NULL )
725        {
726          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
727          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
728          {
729            offset += syncDataLength;
730            continue;
731          }
732
733          if ( !peers[peer->second.userId].isMasterServer() )
734          {
735            offset += syncDataLength;
736            continue;
737          }
738
739          int leafClassId;
740          if ( INTSIZE > length - offset )
741          {
742            offset += syncDataLength;
743            continue;
744          }
745
746          Converter::byteArrayToInt( buf + offset, &leafClassId );
747
748          assert( leafClassId != 0 );
749
750          BaseObject * b = NULL;
751          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
752          /* Exception 1: NullParent */
753          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
754          {
755            PRINTF(1)("Can not create Class with ID %x!\n", (int)leafClassId);
756            offset += syncDataLength;
757            continue;
758          }
759          else
760            b = Factory::fabricate( (ClassID)leafClassId );
761
762          if ( !b )
763          {
764            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
765            offset += syncDataLength;
766            continue;
767          }
768
769          if ( b->isA(CL_SYNCHRONIZEABLE) )
770          {
771            sync = dynamic_cast<Synchronizeable*>(b);
772            sync->setUniqueID( uniqueId );
773            sync->setSynchronized(true);
774
775            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
776          }
777          else
778          {
779            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
780            delete b;
781            offset += syncDataLength;
782            continue;
783          }
784        }
785
786
787        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
788        offset += n;
789        //NETPRINTF(0)("SSSSSEEEEETTTTT: %s %d\n",sync->getClassName(), n);
790
791      }
792
793      if ( offset != length )
794      {
795        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
796        peer->second.socket->disconnectServer();
797      }
798
799
800      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
801      {
802        Synchronizeable & sync = **it;
803
804        if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
805          continue;
806
807        sync.handleRecvState( peer->second.userId, state, fromState );
808      }
809
810      assert( peer->second.lastAckedState <= ackedState );
811      peer->second.lastAckedState = ackedState;
812
813      assert( peer->second.lastRecvedState < state );
814      peer->second.lastRecvedState = state;
815
816    }
817
818  }
819
820}
821
822/**
823 * is executed when a handshake has finished
824 */
825void NetworkStream::handleNewClient( int userId )
826{
827  // init and assign the message manager
828  MessageManager::getInstance()->initUser( userId );
829  // do all game relevant stuff here
830  networkGameManager->signalNewPlayer( userId );
831
832  // register the new client at the network monitor
833//   this->networkMonitor->addClient();
834}
835
836
837/**
838 * removes old items from oldSynchronizeables
839 */
840void NetworkStream::cleanUpOldSyncList( )
841{
842  int now = SDL_GetTicks();
843
844  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
845  {
846    if ( it->second < now - 10*1000 )
847    {
848      std::map<int,int>::iterator delIt = it;
849      it++;
850      oldSynchronizeables.erase( delIt );
851      continue;
852    }
853    it++;
854  }
855}
856
857/**
858 * writes data to DATA/dicts/newdict
859 * @param data pointer to data
860 * @param length length
861 */
862void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
863{
864  if ( remainingBytesToWriteToDict <= 0 )
865    return;
866
867  if ( length > remainingBytesToWriteToDict )
868    length = remainingBytesToWriteToDict;
869
870  std::string fileName = ResourceManager::getInstance()->getDataDir();
871  fileName += "/dicts/newdict";
872
873  if ( upstream )
874    fileName += "_upstream";
875  else
876    fileName += "_downstream";
877
878  FILE * f = fopen( fileName.c_str(), "a" );
879
880  if ( !f )
881  {
882    PRINTF(2)("could not open %s\n", fileName.c_str());
883    remainingBytesToWriteToDict = 0;
884    return;
885  }
886
887  if ( fwrite( data, 1, length, f ) != length )
888  {
889    PRINTF(2)("could not write to file\n");
890    fclose( f );
891    return;
892  }
893
894  fclose( f );
895
896  remainingBytesToWriteToDict -= length;
897}
898
899
900
901
902
903
Note: See TracBrowser for help on using the repository browser.