Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/objecthierarchy/src/network/Synchronisable.cc @ 2033

Last change on this file since 2033 was 2033, checked in by scheusso, 16 years ago

some minor bugs fixed

  • Property svn:eol-style set to native
File size: 17.8 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Dumeni Manatschal, (C) 2007
24 *      Oliver Scheuss, (C) 2007
25 *   Co-authors:
26 *      ...
27 *
28 */
29
30//
31// C++ Implementation: synchronisable
32//
33// Description:
34//
35//
36// Author:  Dumeni, Oliver Scheuss, (C) 2007
37//
38// Copyright: See COPYING file that comes with this distribution
39//
40
41#include "Synchronisable.h"
42
43#include <cstring>
44#include <string>
45#include <iostream>
46#include <assert.h>
47
48#include "core/CoreIncludes.h"
49#include "core/BaseObject.h"
50// #include "core/Identifier.h"
51
52namespace network
53{
54
55
56  std::map<unsigned int, Synchronisable *> Synchronisable::objectMap_;
57  std::queue<unsigned int> Synchronisable::deletedObjects_;
58
59  int Synchronisable::state_=0x1; // detemines wheter we are server (default) or client
60
61  /**
62  * Constructor:
63  * Initializes all Variables and sets the right objectID
64  */
65  Synchronisable::Synchronisable(){
66    RegisterRootObject(Synchronisable);
67    static uint32_t idCounter=0;
68    objectFrequency_=1;
69    objectMode_=0x1; // by default do not send data to server
70    objectID=idCounter++;
71    classID = (unsigned int)-1;
72    syncList = new std::list<synchronisableVariable *>;
73  }
74
75  /**
76   * Destructor:
77   * Delete all callback objects and remove objectID from the objectMap_
78   */
79  Synchronisable::~Synchronisable(){
80    // delete callback function objects
81    if(!orxonox::Identifier::isCreatingHierarchy()){
82      for(std::list<synchronisableVariable *>::iterator it = syncList->begin(); it!=syncList->end(); it++)
83        delete (*it)->callback;
84      if (this->objectMode_ != 0x0)
85        deletedObjects_.push(objectID);
86//       COUT(3) << "destruct synchronisable +++" << objectID << " | " << classID << std::endl;
87//       COUT(3) << " bump ---" << objectID << " | " << &objectMap_ << std::endl;
88//       assert(objectMap_[objectID]->objectID==objectID);
89//       objectMap_.erase(objectID);
90    }
91  }
92
93  /**
94   * This function gets called after all neccessary data has been passed to the object
95   * Overload this function and recall the create function of the parent class
96   * @return true/false
97   */
98  bool Synchronisable::create(){
99    this->classID = this->getIdentifier()->getNetworkID();
100//     COUT(4) << "creating synchronisable: setting classid from " << this->getIdentifier()->getName() << " to: " << classID << std::endl;
101
102//     COUT(3) << "construct synchronisable +++" << objectID << " | " << classID << std::endl;
103//     objectMap_[objectID]=this;
104//     assert(objectMap_[objectID]==this);
105//     assert(objectMap_[objectID]->objectID==objectID);
106    return true;
107  }
108
109
110  /**
111   * This function sets the internal mode for synchronisation
112   * @param b true if this object is located on a client or on a server
113   */
114  void Synchronisable::setClient(bool b){
115    if(b) // client
116      state_=0x2;
117    else  // server
118      state_=0x1;
119  }
120
121  /**
122   * This function fabricated a new synchrnisable (and children of it), sets calls updateData and create
123   * After calling this function the mem pointer will be increased by the size of the needed data
124   * @param mem pointer to where the appropriate data is located
125   * @param mode defines the mode, how the data should be loaded
126   * @return pointer to the newly created synchronisable
127   */
128  Synchronisable *Synchronisable::fabricate(uint8_t*& mem, int mode)
129  {
130    synchronisableHeader *header = (synchronisableHeader *)mem;
131
132    COUT(3) << "fabricating object with id: " << header->objectID << std::endl;
133
134    orxonox::Identifier* id = ClassByID(header->classID);
135    assert(id);
136    orxonox::BaseObject *bo = id->fabricate(0); //TODO: get BaseObject* from header->creatorID here
137    Synchronisable *no = dynamic_cast<Synchronisable *>(bo);
138    assert(no);
139    no->objectID=header->objectID;
140    no->creatorID=header->creatorID; //TODO: remove this
141    no->classID=header->classID;
142    COUT(3) << "fabricate objectID: " << no->objectID << " classID: " << no->classID << std::endl;
143          // update data and create object/entity...
144    bool b = no->updateData(mem, mode, true);
145//    assert(b);
146    if (b)
147    {
148        b = no->create();
149        assert(b);
150    }
151    return no;
152  }
153
154
155  /**
156   * Finds and deletes the Synchronisable with the appropriate objectID
157   * @param objectID objectID of the Synchronisable
158   * @return true/false
159   */
160  bool Synchronisable::deleteObject(unsigned int objectID){
161//     assert(getSynchronisable(objectID));
162    if(!getSynchronisable(objectID))
163      return false;
164    assert(getSynchronisable(objectID)->objectID==objectID);
165//     delete objectMap_[objectID];
166    Synchronisable *s = getSynchronisable(objectID);
167    if(s)
168      delete s;
169    else
170      return false;
171    return true;
172  }
173
174  /**
175   * This function looks up the objectID in the objectMap_ and returns a pointer to the right Synchronisable
176   * @param objectID objectID of the Synchronisable
177   * @return pointer to the Synchronisable with the objectID
178   */
179  Synchronisable* Synchronisable::getSynchronisable(unsigned int objectID){
180    orxonox::ObjectList<Synchronisable>::iterator it;
181    for(it = orxonox::ObjectList<Synchronisable>::begin(); it; ++it){
182      if( it->getObjectID()==objectID )
183           return *it;
184    }
185    return NULL;
186
187//     std::map<unsigned int, Synchronisable *>::iterator i = objectMap_.find(objectID);
188//     if(i==objectMap_.end())
189//       return NULL;
190//     assert(i->second->objectID==objectID);
191//     return (*i).second;
192  }
193
194
195  /**
196  * This function is used to register a variable to be synchronized
197  * also counts the total datasize needed to save the variables
198  * @param var pointer to the variable
199  * @param size size of the datatype the variable consists of
200  * @param t the type of the variable (network::DATA or network::STRING
201  * @param mode same as in getData
202  * @param cb callback object that should get called, if the value of the variable changes
203  */
204  void Synchronisable::registerVar(void *var, int size, variableType t, int mode, NetworkCallbackBase *cb){
205    assert( mode==direction::toclient || mode==direction::toserver || mode==direction::serverMaster || mode==direction::clientMaster);
206    // create temporary synch.Var struct
207    synchronisableVariable *temp = new synchronisableVariable;
208    temp->size = size;
209    temp->var = var;
210    temp->mode = mode;
211    temp->type = t;
212    temp->callback = cb;
213    if( ( mode & direction::bidirectional ) )
214    {
215      temp->varBuffer = new uint8_t[size];
216      memcpy(temp->varBuffer, temp->var, size); //now fill the buffer for the first time
217      temp->varReference = 0;
218    }
219    COUT(5) << "Syncronisable::registering var with size: " << temp->size << " and type: " << temp->type << std::endl;
220    //std::cout << "push temp to syncList (at the bottom) " << datasize << std::endl;
221    COUT(5) << "Syncronisable::objectID: " << objectID << " this: " << this << " name: " << this->getIdentifier()->getName() << " networkID: " << this->getIdentifier()->getNetworkID() << std::endl;
222    syncList->push_back(temp);
223#ifndef NDEBUG
224    std::list<synchronisableVariable *>::iterator it = syncList->begin();
225    while(it!=syncList->end()){
226      assert(*it!=var);
227      it++;
228    }
229#endif
230  }
231
232  /**
233   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID and classID to the given memory
234   * takes a pointer to already allocated memory (must have at least getSize bytes length)
235   * structure of the bitstream:
236   * |totalsize,objectID,classID,var1,var2,string1_length,string1,var3,...|
237   * length of varx: size saved int syncvarlist
238   * @param mem pointer to allocated memory with enough size
239   * @param id gamestateid of the gamestate to be saved (important for priorities)
240   * @param mode defines the direction in which the data will be send/received
241   *             0x1: server->client
242   *             0x2: client->server (not recommended)
243   *             0x3: bidirectional
244   * @return true: if !doSync or if everything was successfully saved
245   */
246  bool Synchronisable::getData(uint8_t*& mem, unsigned int id, int mode){
247    //if this tick is we dont synchronise, then abort now
248    if(!doSync(id))
249      return true;
250    //std::cout << "inside getData" << std::endl;
251    unsigned int tempsize = 0;
252    if(mode==0x0)
253      mode=state_;
254    if(classID==0)
255      COUT(3) << "classid 0 " << this->getIdentifier()->getName() << std::endl;
256
257    if (this->classID == (unsigned int)-1)
258        this->classID = this->getIdentifier()->getNetworkID();
259
260    assert(this->classID==this->getIdentifier()->getNetworkID());
261//     this->classID=this->getIdentifier()->getNetworkID(); // TODO: correct this
262    std::list<synchronisableVariable *>::iterator i;
263    unsigned int size;
264    size=getSize(id, mode);
265
266    // start copy header
267    synchronisableHeader *header = (synchronisableHeader *)mem;
268    header->size = size;
269    header->objectID = this->objectID;
270    header->creatorID = this->creatorID;
271    header->classID = this->classID;
272    header->dataAvailable = true;
273    tempsize+=sizeof(synchronisableHeader);
274    mem+=sizeof(synchronisableHeader);
275    // end copy header
276
277
278    COUT(5) << "Synchronisable getting data from objectID: " << objectID << " classID: " << classID << " length: " << size << std::endl;
279    // copy to location
280    for(i=syncList->begin(); i!=syncList->end(); ++i){
281      if( ((*i)->mode & mode) == 0 ){
282        COUT(5) << "not getting data: " << std::endl;
283        continue;  // this variable should only be received
284      }
285      // if the variable gets synchronised bidirectional, then add the reference to the bytestream
286      if( ( (*i)->mode & direction::bidirectional ) )
287      {
288        *(uint8_t*)mem = (*i)->varReference;
289        mem += sizeof( (*i)->varReference );
290      }
291      switch((*i)->type){
292        case DATA:
293          memcpy( (void *)(mem), (void*)((*i)->var), (*i)->size);
294          mem+=(*i)->size;
295          tempsize+=(*i)->size + sizeof( (*i)->varReference );
296          break;
297        case STRING:
298          memcpy( (void *)(mem), (void *)&((*i)->size), sizeof(size_t) );
299          mem+=sizeof(size_t);
300          const char *data = ( ( *(std::string *) (*i)->var).c_str());
301          memcpy( mem, (void*)data, (*i)->size);
302          COUT(5) << "synchronisable: char: " << (const char *)(mem) << " data: " << data << " string: " << *(std::string *)((*i)->var) << std::endl;
303          mem+=(*i)->size;
304          tempsize+=(*i)->size + sizeof( (*i)->varReference ) + sizeof(size_t);
305          break;
306      }
307    }
308    assert(tempsize==size);
309    return true;
310  }
311
312
313  /**
314   * This function takes a bytestream and loads the data into the registered variables
315   * @param mem pointer to the bytestream
316   * @param mode same as in getData
317   * @return true/false
318   */
319  bool Synchronisable::updateData(uint8_t*& mem, int mode, bool forceCallback){
320    if(mode==0x0)
321      mode=state_;
322    std::list<synchronisableVariable *>::iterator i;
323    if(syncList->empty()){
324      COUT(4) << "Synchronisable::updateData syncList is empty" << std::endl;
325      return false;
326    }
327
328    uint8_t *data=mem;
329    // start extract header
330    synchronisableHeader *syncHeader = (synchronisableHeader *)mem;
331    assert(syncHeader->objectID==this->objectID);
332//    assert(syncHeader->creatorID==this->creatorID);
333    if(syncHeader->dataAvailable==false){
334      mem+=syncHeader->size;
335      return true;
336    }
337
338    mem+=sizeof(synchronisableHeader);
339    // stop extract header
340    assert(this->objectID==syncHeader->objectID);
341//    assert(this->classID==syncHeader->classID); //TODO: fix this!!! maybe a problem with the identifier ?
342
343    COUT(5) << "Synchronisable: objectID " << syncHeader->objectID << ", classID " << syncHeader->classID << " size: " << syncHeader->size << " synchronising data" << std::endl;
344    for(i=syncList->begin(); i!=syncList->end() && mem <= data+syncHeader->size; i++){
345      if( ((*i)->mode ^ mode) == 0 ){
346        COUT(5) << "synchronisable: not updating variable " << std::endl;
347        continue;  // this variable should only be set
348      }
349      COUT(5) << "Synchronisable: element size: " << (*i)->size << " type: " << (*i)->type << std::endl;
350      bool callback=false;
351      switch((*i)->type){
352        case DATA:
353          if( ( (*i)->mode & direction::bidirectional ) )
354          {
355            if( ( mode == 0x1 && (*i)->mode == direction::serverMaster ) || \
356                  ( mode == 0x2 && (*i)->mode == direction::clientMaster ) )    // if true we are master on this variable
357            {
358              uint8_t refNr = *(uint8_t *)mem;
359              if( refNr != (*i)->varReference )
360              {
361                mem += sizeof((*i)->varReference) + (*i)->size; // the reference for this variable is not recent, discard data
362                break;
363              }
364            }
365            else //we are slave for this variable
366            {
367              (*i)->varReference = *(uint8_t *)mem; //copy the reference value for this variable
368            }
369            mem += sizeof((*i)->varReference);
370          }
371          if((*i)->callback) // check whether this variable changed (but only if callback was set)
372            if(strncmp((char *)(*i)->var, (char *)mem, (*i)->size)!=0)
373              callback=true;
374          memcpy((void*)(*i)->var, mem, (*i)->size);
375          mem+=(*i)->size;
376          break;
377        case STRING:
378          if( ( (*i)->mode & direction::bidirectional ) )
379          {
380            if( ( mode == 0x1 && (*i)->mode == direction::serverMaster ) || \
381                  ( mode == 0x2 && (*i)->mode == direction::clientMaster ) )    // if true we are master for this variable
382            {
383              uint8_t refNr = *(uint8_t *)mem;
384              mem += sizeof( (*i)->varReference );
385              if( refNr != (*i)->varReference ){
386                mem += sizeof(size_t) + *(size_t *)mem; // the reference for this variable is not recent, discard data
387                break;
388              }
389            }
390            else //we are slave for this variable
391            {
392              (*i)->varReference = *(uint8_t *)mem; //copy the reference value for this variable
393            }
394            mem += sizeof( (*i)->varReference );
395          }
396          (*i)->size = *(size_t *)mem;
397          COUT(5) << "string size: " << (*i)->size << std::endl;
398          mem += sizeof(size_t);
399          if((*i)->callback) // check whether this string changed
400            if( *(std::string *)((*i)->var) != std::string((char *)mem) )
401              callback=true;
402          *((std::string *)((*i)->var)) = std::string((const char*)mem);
403          COUT(5) << "synchronisable: char: " << (const char*)mem << " string: " << std::string((const char*)mem) << std::endl;
404          mem += (*i)->size;
405          break;
406      }
407      // call the callback function, if defined
408      if((callback || forceCallback) && (*i)->callback)
409        (*i)->callback->call();
410    }
411    return true;
412  }
413
414  /**
415  * This function returns the total amount of bytes needed by getData to save the whole content of the variables
416  * @param id id of the gamestate
417  * @param mode same as getData
418  * @return amount of bytes
419  */
420  uint32_t Synchronisable::getSize(unsigned int id, int mode){
421    if(!doSync(id))
422      return 0;
423    int tsize=sizeof(synchronisableHeader);
424    if(mode==0x0)
425      mode=state_;
426    std::list<synchronisableVariable *>::iterator i;
427    for(i=syncList->begin(); i!=syncList->end(); i++){
428      if( ((*i)->mode & mode) == 0 )
429        continue;  // this variable should only be received, so dont add its size to the send-size
430      switch((*i)->type){
431      case DATA:
432        tsize+=(*i)->size;
433        break;
434      case STRING:
435        tsize+=sizeof(int);
436        (*i)->size=((std::string *)(*i)->var)->length()+1;
437        COUT(5) << "String size: " << (*i)->size << std::endl;
438        tsize+=(*i)->size;
439        break;
440      }
441      if( ( (*i)->mode & direction::bidirectional ) != 0)
442      {
443        tsize+=sizeof( (*i)->varReference );
444      }
445    }
446    return tsize;
447  }
448
449  /**
450   * This function determines, wheter the object should be saved to the bytestream (according to its syncmode/direction)
451   * @param id gamestate id
452   * @return true/false
453   */
454  bool Synchronisable::doSync(unsigned int id){
455    return ( (objectMode_&state_)!=0 && (!syncList->empty() ) );
456  }
457
458  bool Synchronisable::doSelection(unsigned int id){
459    return ( id==0 || id%objectFrequency_==objectID%objectFrequency_ ) && ((objectMode_&state_)!=0);
460  }
461
462  /**
463   * This function looks at the header located in the bytestream and checks wheter objectID and classID match with the Synchronisables ones
464   * @param mem pointer to the bytestream
465   */
466  bool Synchronisable::isMyData(uint8_t* mem)
467  {
468    synchronisableHeader *header = (synchronisableHeader *)mem;
469    assert(header->objectID==this->objectID);
470    return header->dataAvailable;
471  }
472
473  /**
474   * This function sets the synchronisation mode of the object
475   * If set to 0x1 variables will only be synchronised to the client
476   * If set to 0x2 variables will only be synchronised to the server
477   * If set to 0x3 variables will be synchronised bidirectionally (only if set so in registerVar)
478   * @param mode same as in registerVar
479   */
480  void Synchronisable::setObjectMode(int mode){
481    assert(mode==0x0 || mode==0x1 || mode==0x2 || mode==0x3);
482    objectMode_=mode;
483  }
484
485
486}
Note: See TracBrowser for help on using the repository browser.