Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/network/synchronizeable.cc @ 8231

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

trunk: merged the network branche back to trunk with command: svn merge branches/network trunk -r8150:HEAD

File size: 15.0 KB
RevLine 
[5523]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
[5547]11
[5523]12### File Specific:
13   main-programmer: Silvan Nellen
[5997]14   co-programmer: Benjamin Wuest
[5547]15*/
[5523]16
[6139]17#define DEBUG_MODULE_NETWORK
18
[6695]19#include "shared_network_data.h"
20#include "network_stream.h"
[5547]21#include "netdefs.h"
[7954]22#include "network_log.h"
[8068]23#include "network_game_manager.h"
[5529]24
[6695]25#include "state.h"
[5996]26
[6753]27#include <cassert>
[6695]28
29#include "synchronizeable.h"
30
31
32
[5547]33/**
[5807]34 *  default constructor
[5547]35 */
[5996]36Synchronizeable::Synchronizeable()
[5997]37{
[6341]38  this->setClassID(CL_SYNCHRONIZEABLE, "Synchronizeable");
[8068]39  this->owner = 0;
[6695]40  this->hostID = SharedNetworkData::getInstance()->getHostID();
[6341]41  this->setIsServer(this->hostID == 0);
[6695]42  this->uniqueID = NET_UID_UNASSIGNED;
[6145]43  this->networkStream = NULL;
[6695]44  this->bSynchronize = false;
[7954]45 
[6695]46  if( State::isOnline())
47  {
48    NetworkStream* nd = SharedNetworkData::getInstance()->getDefaultSyncStream();
49    assert(nd != NULL);
50    nd->connectSynchronizeable(*this);
51    this->setUniqueID(SharedNetworkData::getInstance()->getNewUniqueID());
52  }
[7954]53
54  /* make sure loadClassId is first synced var because this is read by networkStream */
55  assert( syncVarList.size() == 0 );
56  mLeafClassId = this->registerVarId( new SynchronizeableInt( (int*)&this->getLeafClassID(), (int*)&this->getLeafClassID(), "leafClassId" ) );
57   
58  this->registerVar( new SynchronizeableInt( &this->owner, &this->owner, "owner" ) );
59  this->registerVar( new SynchronizeableString( &this->objectName, &this->objectName, "objectName" ) );
[5997]60}
61
[5523]62
[5996]63
[5547]64/**
[5807]65 *  default destructor deletes all unneded stuff
[5547]66 */
67Synchronizeable::~Synchronizeable()
[6139]68{
69  if ( this->networkStream )
70    this->networkStream->disconnectSynchronizeable(*this);
[8068]71 
72  if ( this->isServer() && this->beSynchronized() && this->getUniqueID() > 0 )
73    NetworkGameManager::getInstance()->removeSynchronizeable( this->getUniqueID() );
[6139]74}
[5523]75
[5547]76/**
[7954]77 * Sets the server flag to a given value
78 * @param isServer: the boolean value which the server flag is to set to
[5547]79 */
[7954]80void Synchronizeable::setIsServer(bool isServer)
[6139]81{
[7954]82  if( isServer )
83    this->state = this->state | STATE_SERVER;
84  else
85    this->state = this->state & (~STATE_SERVER);
[6139]86}
[5523]87
[6695]88
[5547]89/**
[7954]90 * Determines if the server flag is set
91 * @return true, if the server flag is true, false else
[5547]92 */
[7954]93bool Synchronizeable::isServer()
[6139]94{
[7954]95  return (this->state & STATE_SERVER) >0;
[6139]96}
[5547]97
98
99
[7954]100int Synchronizeable::getStateDiff( int userId, byte* data, int maxLength, int stateId, int fromStateId, int priorityTH )
101{
102  //make sure this user has his history
103  if ( sentStates.size() <= userId )
104    sentStates.resize( userId+1 );
[5547]105
[7954]106  //calculate needed memory
107  int neededSize = 0;
[5997]108
[7954]109  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
[8147]110  {
111    //PRINTF(0)("SIZE = %d %s\n", (*it)->getSize(), (*it)->getName().c_str());
[7954]112    neededSize += (*it)->getSize();
[8147]113  }
[5997]114
[7954]115  if ( !( neededSize <= maxLength ) )
116  {
117    PRINTF(0)( "%d > %d\n", neededSize, maxLength );
118    assert(false);
119  }
120
121  //remove older states from history than fromStateId
122  StateHistory::iterator it = sentStates[userId].begin();
123
124  while ( it != sentStates[userId].end() && (*it)->stateId < fromStateId )
125    it++;
126
127  if ( it != sentStates[userId].begin() )
128  {
129    for ( StateHistory::iterator it2 = sentStates[userId].begin(); it2 != it; it2++ )
130    {
131      if ( (*it2)->data != NULL )
132      {
133        delete [] (*it2)->data;
134        (*it2)->data = NULL;
135      }
136    }
137    sentStates[userId].erase( sentStates[userId].begin(), it );
138  }
139
140  //find state to create diff from
141  StateHistoryEntry * stateFrom = NULL;
142
143  it = sentStates[userId].begin();
144  while ( it != sentStates[userId].end() && (*it)->stateId != fromStateId )
145    it++;
146 
147//  if ( getLeafClassID() == CL_SPACE_SHIP )
148//  {
149//    PRINTF(0)("getStateDiff:SpaceShip from: %d stateId: %d\n", (it == sentStates[userId].end())?-1:fromStateId, stateId);
150//  }
151
152  if ( it == sentStates[userId].end() )
153  {
154    StateHistoryEntry * initialEntry = new StateHistoryEntry();
155
156    initialEntry->stateId = fromStateId;
157    initialEntry->dataLength = 0;
158    initialEntry->data = NULL;
159
160    stateFrom = initialEntry;
161  }
162  else
163    stateFrom = (*it);
164
165  StateHistoryEntry * stateTo = new StateHistoryEntry();
166
167  stateTo->stateId = stateId;
168  stateTo->dataLength = neededSize;
169  stateTo->data = new byte[ neededSize ];
170
171  std::list<int>::iterator sizeIter = stateFrom->sizeList.begin();
172
173  int i = 0;
174  int n;
175 
176  bool hasPermission;
177
178  // now do the actual synchronization: kick all variables to write into a common buffer
179  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
180  {
181    hasPermission = (
182            this->isServer() && (*it)->checkPermission( PERMISSION_SERVER ) ||
183            this->owner == this->hostID && (*it)->checkPermission( PERMISSION_OWNER ) ||
[8068]184            this->isServer() && this->owner != userId && (*it)->checkPermission( PERMISSION_OWNER ) ||
[7954]185            (*it)->checkPermission( PERMISSION_ALL ) 
186                    );
187   
[8147]188    if ( ( sizeIter != stateFrom->sizeList.end() && *sizeIter != (*it)->getSize() ) || ( hasPermission && (*it)->getPriority() >= priorityTH ) || sizeIter == stateFrom->sizeList.end() )
[7954]189    {
190      n = (*it)->writeToBuf( stateTo->data+i, stateTo->dataLength - i );
191      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), n);
192      stateTo->sizeList.push_back( n );
193      //(*it)->debug();
194      i += n;
195    }
196    else
197    {
198      for ( int j = 0; j<(*sizeIter); j++ )
199      {
200        assert( i < stateFrom->dataLength );
201        stateTo->data[i] = stateFrom->data[i];
202        i++;
203      }
204      //NETPRINTF(0)("getvar %s %d\n", (*it)->getName().c_str(), *sizeIter);
205      stateTo->sizeList.push_back( (*sizeIter) );
206    }
207
208    if ( sizeIter != stateFrom->sizeList.end() )
209      sizeIter++;
210  }
211
212  sentStates[userId].push_back( stateTo );
213 
[8147]214  if ( i != neededSize )
215  {
216    PRINTF(0)("strange error: (%s) %d != %d\n", this->getClassName(), i, neededSize);
217    assert(false);
218  }
[7954]219
220  //write diff to data
221  for ( i = 0; i<neededSize; i++ )
222  {
223    if ( i < stateFrom->dataLength )
224      data[i] = stateTo->data[i] - stateFrom->data[i];
225    else
226      data[i] = stateTo->data[i];
227  }
228
229  return neededSize;
230}
231
[5997]232/**
[7954]233 * sets a new state out of a diff created on another host
234 * @param userId hostId of user who send me that diff
235 * @param data pointer to diff
236 * @param length length of diff
237 * @param stateId id of current state
238 * @param fromStateId id of the base state id
239 * @return number bytes read
240 * @todo check for permissions
[5997]241 */
[7954]242int Synchronizeable::setStateDiff( int userId, byte* data, int length, int stateId, int fromStateId )
[5997]243{
[7954]244  //make sure this user has his history
245  if ( recvStates.size() <= userId )
246    recvStates.resize( userId+1 );
247
248  //create new state
249  StateHistoryEntry * stateTo = new StateHistoryEntry();
250  stateTo->stateId = stateId;
251  stateTo->dataLength = length;
252  stateTo->data = new byte[ length ];
253
254
255  //find state to apply diff to
256  StateHistoryEntry * stateFrom = NULL;
257
258  StateHistory::iterator it = recvStates[userId].begin();
259  while ( it != recvStates[userId].end() && (*it)->stateId != fromStateId )
260    it++;
261
262 
263//  if ( getLeafClassID() == CL_SPACE_SHIP )
264//  {
265//    PRINTF(0)("setStateDiff:SpaceShip from: %d stateId: %d\n", (it == recvStates[userId].end())?-1:fromStateId, stateId);
266//  }
267
268  if ( it == recvStates[userId].end() )
269  {
270    StateHistoryEntry * initialEntry = new StateHistoryEntry();
271
272    initialEntry->stateId = fromStateId;
273    initialEntry->dataLength = 0;
274    initialEntry->data = NULL;
275
276    stateFrom = initialEntry;
277  }
[5997]278  else
[7954]279    stateFrom = (*it);
280 
281  //apply diff
282  for ( int i = 0; i<length; i++ )
283  {
284    if ( i < stateFrom->dataLength )
285      stateTo->data[i] = stateFrom->data[i] + data[i];
286    else
287      stateTo->data[i] = data[i];
288   
289  }
290 
291  //add state to state history
292  recvStates[userId].push_back( stateTo );
293 
294  int i = 0;
295  int n = 0;
296  std::list<int> changes;
297 
298  for ( SyncVarList::iterator it = syncVarList.begin(); it != syncVarList.end(); it++ )
299  {
300    if (
301        (*it)->checkPermission( PERMISSION_SERVER ) && networkStream->isUserServer( userId ) ||
302        (*it)->checkPermission( PERMISSION_OWNER ) && this->owner == userId ||
[8068]303        networkStream->isUserServer( userId ) && this->owner != getHostID() && (*it)->checkPermission( PERMISSION_OWNER ) ||
[7954]304        (*it)->checkPermission( PERMISSION_ALL ) 
305       )
306    {
307      n = (*it)->readFromBuf( stateTo->data + i, stateTo->dataLength - i );
308      i += n;
309      //NETPRINTF(0)("%s::setvar %s %d\n", getClassName(), (*it)->getName().c_str(), n);
310      //(*it)->debug();
311      if ( (*it)->getHasChanged() )
312      {
313        changes.push_back( (*it)->getVarId() );
314      }
315    }
316    else
317    {
318//      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 );
319      n = (*it)->getSizeFromBuf( stateTo->data + i, stateTo->dataLength - i );
320      //NETPRINTF(0)("%s::setvar %s %d\n", getClassName(), (*it)->getName().c_str(), n);
321      //(*it)->debug();
322      i += n;
323    }
324  }
325
326  this->varChangeHandler( changes );
327 
328  return i;
[5997]329}
330
[7954]331 /**
332 * override this function to be notified on change
333 * of your registred variables.
334 * @param id id's which have changed
335 */
336void Synchronizeable::varChangeHandler( std::list<int> & id )
337{
338}
[6695]339
[5997]340/**
[7954]341 * registers a varable to be synchronized over network
342 * @param var see src/lib/network/synchronizeable_var/ for available classes
[5997]343 */
[7954]344void Synchronizeable::registerVar( SynchronizeableVar * var )
[5997]345{
[8068]346  //PRINTF(0)("ADDING VAR: %s\n", var->getName().c_str());
[7954]347  syncVarList.push_back( var );
[5997]348}
349
350/**
[7954]351 * registers a varable to be synchronized over network
352 * return value is passed to varChangeHandler on change
353 * @param var see src/lib/network/synchronizeable_var/ for available classes
354 * @return handle passed to varChangeHandler on changes
[5997]355 */
[7954]356int Synchronizeable::registerVarId( SynchronizeableVar * var )
[5997]357{
[8068]358  //PRINTF(0)("ADDING VAR: %s\n", var->getName().c_str());
[7954]359  syncVarList.push_back( var );
360  var->setWatched( true );
361  var->setVarId( syncVarList.size()-1 );
362  return syncVarList.size()-1;
[5997]363}
364
365/**
[7954]366 * removed user's states from memory
367 * @param userId user to clean
[5997]368 */
[7954]369void Synchronizeable::cleanUpUser( int userId )
[5997]370{
[8228]371  if ( recvStates.size() > userId )
[7954]372  {
[8228]373    for ( std::list<StateHistoryEntry*>::iterator it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
[7954]374    {
[8228]375      if ( (*it)->data )
376        delete [] (*it)->data;
377      (*it)->data = NULL;
378   
379      delete *it;
[7954]380    }
[8228]381    recvStates[userId].clear();
[7954]382  }
[8228]383 
384  if ( sentStates.size() > userId )
[7954]385  {
[8228]386   
387    for ( std::list<StateHistoryEntry*>::iterator it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
[7954]388    {
[8228]389      if ( (*it)->data )
390        delete [] (*it)->data;
391      (*it)->data = NULL;
392   
393      delete *it;
[7954]394    }
[8228]395    sentStates[userId].clear();
[7954]396  }
[5997]397}
[6139]398
[6341]399/**
[7954]400 * this function is called after recieving a state.
401 * @param userId
402 * @param stateId
403 * @param fromStateId
[6341]404 */
[7954]405void Synchronizeable::handleRecvState( int userId, int stateId, int fromStateId )
[6341]406{
[7954]407   //make sure this user has his history
408  if ( recvStates.size() <= userId )
409    recvStates.resize( userId+1 );
410 
411  //remove old states
412  StateHistory::iterator it = recvStates[userId].begin();
413
414#if 0
415  while ( it != recvStates[userId].end() && (*it)->stateId < fromStateId )
416    it++;
417
418  if ( it != recvStates[userId].begin() )
419  {
420    for ( StateHistory::iterator it2 = recvStates[userId].begin(); it2 != it; it2++ )
421    {
422      if ( (*it2)->data != NULL )
423      {
424        delete [] (*it2)->data;
425        (*it2)->data = NULL;
426      }
427    }
428    recvStates[userId].erase( recvStates[userId].begin(), it );
429  }
430#endif
431
432  for ( it = recvStates[userId].begin(); it != recvStates[userId].end();  )
433  {
434    if ( (*it)->stateId < fromStateId )
435    {
436      StateHistory::iterator delIt = it;
437      it ++;
438     
439      if ( (*delIt)->data )
440        delete [] (*delIt)->data;
441      recvStates[userId].erase( delIt );
442     
443      continue;
444    }
445    it++;
446  }
447 
448  StateHistory::iterator fromState = recvStates[userId].end();
449  StateHistory::iterator toState = recvStates[userId].end();
450 
451  for ( it = recvStates[userId].begin(); it != recvStates[userId].end(); it++ )
452  {
453    if ( (*it)->stateId == stateId )
454      toState = it;
455    if ( (*it)->stateId == fromStateId )
456      fromState = it;
457   
458    if ( fromState != recvStates[userId].end() && toState != recvStates[userId].end() )
459      break;
460  }
461 
462  // setStateDiff was not called and i know fromStateId
463  if ( fromState != recvStates[userId].end() && toState == recvStates[userId].end() )
464  {
465    StateHistoryEntry * entry = new StateHistoryEntry;
466   
467    entry->dataLength = (*fromState)->dataLength;
468    if ( entry->dataLength > 0 )
469    {
470      entry->data = new byte[entry->dataLength];
471         
472      assert( (*fromState)->data );
473      memcpy( entry->data, (*fromState)->data, entry->dataLength );
474    }
475    else
476      entry->data = NULL;
477   
478    entry->sizeList = (*fromState)->sizeList;
479    entry->stateId = stateId;
480   
481    recvStates[userId].push_back(entry);
482  }
[6341]483}
[6139]484
[6341]485/**
[7954]486 * this function is called after sending a state
487 * @param userId
488 * @param stateId
489 * @param fromStateId
[6341]490 */
[7954]491void Synchronizeable::handleSentState( int userId, int stateId, int fromStateId )
[6341]492{
[7954]493   //make sure this user has his history
494  if ( sentStates.size() <= userId )
495    sentStates.resize( userId+1 );
496
497   //remove old states
498  StateHistory::iterator it = sentStates[userId].begin();
499
500  for ( it = sentStates[userId].begin(); it != sentStates[userId].end();  )
501  {
502    if ( (*it)->stateId < fromStateId )
503    {
504      StateHistory::iterator delIt = it;
505      it ++;
506     
507      if ( (*delIt)->data )
508        delete [] (*delIt)->data;
509      sentStates[userId].erase( delIt );
510     
511      continue;
512    }
513    it++;
514  }
515
516 
517  StateHistory::iterator fromState = sentStates[userId].end();
518  StateHistory::iterator toState = sentStates[userId].end();
519 
520  for ( it = sentStates[userId].begin(); it != sentStates[userId].end(); it++ )
521  {
522    if ( (*it)->stateId == stateId )
523      toState = it;
524    if ( (*it)->stateId == fromStateId )
525      fromState = it;
526   
527    if ( fromState != sentStates[userId].end() && toState != sentStates[userId].end() )
528      break;
529  }
530
531 
532  // getStateDiff was not called and i know fromStateId
533  if ( fromState != sentStates[userId].end() && toState == sentStates[userId].end() )
534  {
535    StateHistoryEntry * entry = new StateHistoryEntry;
536   
537    entry->dataLength = (*fromState)->dataLength;
538    if ( entry->dataLength > 0 )
539    {
540      entry->data = new byte[entry->dataLength];
541     
542      assert( (*fromState)->data );
543      memcpy( entry->data, (*fromState)->data, entry->dataLength );
544    }
545    else
546      entry->data = NULL;
547   
548    entry->sizeList = (*fromState)->sizeList;
549    entry->stateId = stateId;
550   
551    sentStates[userId].push_back(entry);
552  }
553 
[6341]554}
[6139]555
[6341]556
557
Note: See TracBrowser for help on using the repository browser.