Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/network/src/lib/network/synchronizeable.cc @ 8301

Last change on this file since 8301 was 8301, checked in by rennerc, 19 years ago

fixed master memory leak :D

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