Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 2034 was 2034, checked in by landauf, 16 years ago

Synchronisable translates creator ↔ creatorID

  • Property svn:eol-style set to native
File size: 18.6 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(orxonox::BaseObject* creator){
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    this->creatorID = OBJECTID_UNKNOWN;
75
76    searchcreatorID:
77    if (creator)
78    {
79        if (creator->isA(Class(Synchronisable)))
80        {
81            Synchronisable* synchronisable_creator = dynamic_cast<Synchronisable*>(creator);
82            this->creatorID = synchronisable_creator->getObjectID();
83        }
84        else if (creator != creator->getCreator())
85        {
86            creator = creator->getCreator();
87            goto searchcreatorID;
88        }
89    }
90  }
91
92  /**
93   * Destructor:
94   * Delete all callback objects and remove objectID from the objectMap_
95   */
96  Synchronisable::~Synchronisable(){
97    // delete callback function objects
98    if(!orxonox::Identifier::isCreatingHierarchy()){
99      for(std::list<synchronisableVariable *>::iterator it = syncList->begin(); it!=syncList->end(); it++)
100        delete (*it)->callback;
101      if (this->objectMode_ != 0x0)
102        deletedObjects_.push(objectID);
103//       COUT(3) << "destruct synchronisable +++" << objectID << " | " << classID << std::endl;
104//       COUT(3) << " bump ---" << objectID << " | " << &objectMap_ << std::endl;
105//       assert(objectMap_[objectID]->objectID==objectID);
106//       objectMap_.erase(objectID);
107    }
108  }
109
110  /**
111   * This function gets called after all neccessary data has been passed to the object
112   * Overload this function and recall the create function of the parent class
113   * @return true/false
114   */
115  bool Synchronisable::create(){
116    this->classID = this->getIdentifier()->getNetworkID();
117//     COUT(4) << "creating synchronisable: setting classid from " << this->getIdentifier()->getName() << " to: " << classID << std::endl;
118
119//     COUT(3) << "construct synchronisable +++" << objectID << " | " << classID << std::endl;
120//     objectMap_[objectID]=this;
121//     assert(objectMap_[objectID]==this);
122//     assert(objectMap_[objectID]->objectID==objectID);
123    return true;
124  }
125
126
127  /**
128   * This function sets the internal mode for synchronisation
129   * @param b true if this object is located on a client or on a server
130   */
131  void Synchronisable::setClient(bool b){
132    if(b) // client
133      state_=0x2;
134    else  // server
135      state_=0x1;
136  }
137
138  /**
139   * This function fabricated a new synchrnisable (and children of it), sets calls updateData and create
140   * After calling this function the mem pointer will be increased by the size of the needed data
141   * @param mem pointer to where the appropriate data is located
142   * @param mode defines the mode, how the data should be loaded
143   * @return pointer to the newly created synchronisable
144   */
145  Synchronisable *Synchronisable::fabricate(uint8_t*& mem, int mode)
146  {
147    synchronisableHeader *header = (synchronisableHeader *)mem;
148
149    COUT(3) << "fabricating object with id: " << header->objectID << std::endl;
150
151    orxonox::Identifier* id = ClassByID(header->classID);
152    assert(id);
153    orxonox::BaseObject* creator = 0;
154    if (header->creatorID != OBJECTID_UNKNOWN)
155    {
156        Synchronisable* synchronisable_creator = Synchronisable::getSynchronisable(header->creatorID);
157        if (!synchronisable_creator)
158            return 0;
159        else
160            creator = dynamic_cast<orxonox::BaseObject*>(synchronisable_creator);
161    }
162    orxonox::BaseObject *bo = id->fabricate(creator);
163    assert(bo);
164    Synchronisable *no = dynamic_cast<Synchronisable *>(bo);
165    assert(no);
166    no->objectID=header->objectID;
167    no->creatorID=header->creatorID; //TODO: remove this
168    no->classID=header->classID;
169    COUT(3) << "fabricate objectID: " << no->objectID << " classID: " << no->classID << std::endl;
170          // update data and create object/entity...
171    bool b = no->updateData(mem, mode, true);
172//    assert(b);
173    if (b)
174    {
175        b = no->create();
176        assert(b);
177    }
178    return no;
179  }
180
181
182  /**
183   * Finds and deletes the Synchronisable with the appropriate objectID
184   * @param objectID objectID of the Synchronisable
185   * @return true/false
186   */
187  bool Synchronisable::deleteObject(unsigned int objectID){
188//     assert(getSynchronisable(objectID));
189    if(!getSynchronisable(objectID))
190      return false;
191    assert(getSynchronisable(objectID)->objectID==objectID);
192//     delete objectMap_[objectID];
193    Synchronisable *s = getSynchronisable(objectID);
194    if(s)
195      delete s;
196    else
197      return false;
198    return true;
199  }
200
201  /**
202   * This function looks up the objectID in the objectMap_ and returns a pointer to the right Synchronisable
203   * @param objectID objectID of the Synchronisable
204   * @return pointer to the Synchronisable with the objectID
205   */
206  Synchronisable* Synchronisable::getSynchronisable(unsigned int objectID){
207    orxonox::ObjectList<Synchronisable>::iterator it;
208    for(it = orxonox::ObjectList<Synchronisable>::begin(); it; ++it){
209      if( it->getObjectID()==objectID )
210           return *it;
211    }
212    return NULL;
213
214//     std::map<unsigned int, Synchronisable *>::iterator i = objectMap_.find(objectID);
215//     if(i==objectMap_.end())
216//       return NULL;
217//     assert(i->second->objectID==objectID);
218//     return (*i).second;
219  }
220
221
222  /**
223  * This function is used to register a variable to be synchronized
224  * also counts the total datasize needed to save the variables
225  * @param var pointer to the variable
226  * @param size size of the datatype the variable consists of
227  * @param t the type of the variable (network::DATA or network::STRING
228  * @param mode same as in getData
229  * @param cb callback object that should get called, if the value of the variable changes
230  */
231  void Synchronisable::registerVar(void *var, int size, variableType t, int mode, NetworkCallbackBase *cb){
232    assert( mode==direction::toclient || mode==direction::toserver || mode==direction::serverMaster || mode==direction::clientMaster);
233    // create temporary synch.Var struct
234    synchronisableVariable *temp = new synchronisableVariable;
235    temp->size = size;
236    temp->var = var;
237    temp->mode = mode;
238    temp->type = t;
239    temp->callback = cb;
240    if( ( mode & direction::bidirectional ) )
241    {
242      temp->varBuffer = new uint8_t[size];
243      memcpy(temp->varBuffer, temp->var, size); //now fill the buffer for the first time
244      temp->varReference = 0;
245    }
246    COUT(5) << "Syncronisable::registering var with size: " << temp->size << " and type: " << temp->type << std::endl;
247    //std::cout << "push temp to syncList (at the bottom) " << datasize << std::endl;
248    COUT(5) << "Syncronisable::objectID: " << objectID << " this: " << this << " name: " << this->getIdentifier()->getName() << " networkID: " << this->getIdentifier()->getNetworkID() << std::endl;
249    syncList->push_back(temp);
250#ifndef NDEBUG
251    std::list<synchronisableVariable *>::iterator it = syncList->begin();
252    while(it!=syncList->end()){
253      assert(*it!=var);
254      it++;
255    }
256#endif
257  }
258
259  /**
260   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID and classID to the given memory
261   * takes a pointer to already allocated memory (must have at least getSize bytes length)
262   * structure of the bitstream:
263   * |totalsize,objectID,classID,var1,var2,string1_length,string1,var3,...|
264   * length of varx: size saved int syncvarlist
265   * @param mem pointer to allocated memory with enough size
266   * @param id gamestateid of the gamestate to be saved (important for priorities)
267   * @param mode defines the direction in which the data will be send/received
268   *             0x1: server->client
269   *             0x2: client->server (not recommended)
270   *             0x3: bidirectional
271   * @return true: if !doSync or if everything was successfully saved
272   */
273  bool Synchronisable::getData(uint8_t*& mem, unsigned int id, int mode){
274    //if this tick is we dont synchronise, then abort now
275    if(!doSync(id))
276      return true;
277    //std::cout << "inside getData" << std::endl;
278    unsigned int tempsize = 0;
279    if(mode==0x0)
280      mode=state_;
281    if(classID==0)
282      COUT(3) << "classid 0 " << this->getIdentifier()->getName() << std::endl;
283
284    if (this->classID == (unsigned int)-1)
285        this->classID = this->getIdentifier()->getNetworkID();
286
287    assert(this->classID==this->getIdentifier()->getNetworkID());
288//     this->classID=this->getIdentifier()->getNetworkID(); // TODO: correct this
289    std::list<synchronisableVariable *>::iterator i;
290    unsigned int size;
291    size=getSize(id, mode);
292
293    // start copy header
294    synchronisableHeader *header = (synchronisableHeader *)mem;
295    header->size = size;
296    header->objectID = this->objectID;
297    header->creatorID = this->creatorID;
298    header->classID = this->classID;
299    header->dataAvailable = true;
300    tempsize+=sizeof(synchronisableHeader);
301    mem+=sizeof(synchronisableHeader);
302    // end copy header
303
304
305    COUT(5) << "Synchronisable getting data from objectID: " << objectID << " classID: " << classID << " length: " << size << std::endl;
306    // copy to location
307    for(i=syncList->begin(); i!=syncList->end(); ++i){
308      if( ((*i)->mode & mode) == 0 ){
309        COUT(5) << "not getting data: " << std::endl;
310        continue;  // this variable should only be received
311      }
312      // if the variable gets synchronised bidirectional, then add the reference to the bytestream
313      if( ( (*i)->mode & direction::bidirectional ) )
314      {
315        *(uint8_t*)mem = (*i)->varReference;
316        mem += sizeof( (*i)->varReference );
317      }
318      switch((*i)->type){
319        case DATA:
320          memcpy( (void *)(mem), (void*)((*i)->var), (*i)->size);
321          mem+=(*i)->size;
322          tempsize+=(*i)->size + sizeof( (*i)->varReference );
323          break;
324        case STRING:
325          memcpy( (void *)(mem), (void *)&((*i)->size), sizeof(size_t) );
326          mem+=sizeof(size_t);
327          const char *data = ( ( *(std::string *) (*i)->var).c_str());
328          memcpy( mem, (void*)data, (*i)->size);
329          COUT(5) << "synchronisable: char: " << (const char *)(mem) << " data: " << data << " string: " << *(std::string *)((*i)->var) << std::endl;
330          mem+=(*i)->size;
331          tempsize+=(*i)->size + sizeof( (*i)->varReference ) + sizeof(size_t);
332          break;
333      }
334    }
335    assert(tempsize==size);
336    return true;
337  }
338
339
340  /**
341   * This function takes a bytestream and loads the data into the registered variables
342   * @param mem pointer to the bytestream
343   * @param mode same as in getData
344   * @return true/false
345   */
346  bool Synchronisable::updateData(uint8_t*& mem, int mode, bool forceCallback){
347    if(mode==0x0)
348      mode=state_;
349    std::list<synchronisableVariable *>::iterator i;
350    if(syncList->empty()){
351      COUT(4) << "Synchronisable::updateData syncList is empty" << std::endl;
352      return false;
353    }
354
355    uint8_t *data=mem;
356    // start extract header
357    synchronisableHeader *syncHeader = (synchronisableHeader *)mem;
358    assert(syncHeader->objectID==this->objectID);
359//    assert(syncHeader->creatorID==this->creatorID);
360    if(syncHeader->dataAvailable==false){
361      mem+=syncHeader->size;
362      return true;
363    }
364
365    mem+=sizeof(synchronisableHeader);
366    // stop extract header
367    assert(this->objectID==syncHeader->objectID);
368//    assert(this->classID==syncHeader->classID); //TODO: fix this!!! maybe a problem with the identifier ?
369
370    COUT(5) << "Synchronisable: objectID " << syncHeader->objectID << ", classID " << syncHeader->classID << " size: " << syncHeader->size << " synchronising data" << std::endl;
371    for(i=syncList->begin(); i!=syncList->end() && mem <= data+syncHeader->size; i++){
372      if( ((*i)->mode ^ mode) == 0 ){
373        COUT(5) << "synchronisable: not updating variable " << std::endl;
374        continue;  // this variable should only be set
375      }
376      COUT(5) << "Synchronisable: element size: " << (*i)->size << " type: " << (*i)->type << std::endl;
377      bool callback=false;
378      switch((*i)->type){
379        case DATA:
380          if( ( (*i)->mode & direction::bidirectional ) )
381          {
382            if( ( mode == 0x1 && (*i)->mode == direction::serverMaster ) || \
383                  ( mode == 0x2 && (*i)->mode == direction::clientMaster ) )    // if true we are master on this variable
384            {
385              uint8_t refNr = *(uint8_t *)mem;
386              if( refNr != (*i)->varReference )
387              {
388                mem += sizeof((*i)->varReference) + (*i)->size; // the reference for this variable is not recent, discard data
389                break;
390              }
391            }
392            else //we are slave for this variable
393            {
394              (*i)->varReference = *(uint8_t *)mem; //copy the reference value for this variable
395            }
396            mem += sizeof((*i)->varReference);
397          }
398          if((*i)->callback) // check whether this variable changed (but only if callback was set)
399            if(strncmp((char *)(*i)->var, (char *)mem, (*i)->size)!=0)
400              callback=true;
401          memcpy((void*)(*i)->var, mem, (*i)->size);
402          mem+=(*i)->size;
403          break;
404        case STRING:
405          if( ( (*i)->mode & direction::bidirectional ) )
406          {
407            if( ( mode == 0x1 && (*i)->mode == direction::serverMaster ) || \
408                  ( mode == 0x2 && (*i)->mode == direction::clientMaster ) )    // if true we are master for this variable
409            {
410              uint8_t refNr = *(uint8_t *)mem;
411              mem += sizeof( (*i)->varReference );
412              if( refNr != (*i)->varReference ){
413                mem += sizeof(size_t) + *(size_t *)mem; // the reference for this variable is not recent, discard data
414                break;
415              }
416            }
417            else //we are slave for this variable
418            {
419              (*i)->varReference = *(uint8_t *)mem; //copy the reference value for this variable
420            }
421            mem += sizeof( (*i)->varReference );
422          }
423          (*i)->size = *(size_t *)mem;
424          COUT(5) << "string size: " << (*i)->size << std::endl;
425          mem += sizeof(size_t);
426          if((*i)->callback) // check whether this string changed
427            if( *(std::string *)((*i)->var) != std::string((char *)mem) )
428              callback=true;
429          *((std::string *)((*i)->var)) = std::string((const char*)mem);
430          COUT(5) << "synchronisable: char: " << (const char*)mem << " string: " << std::string((const char*)mem) << std::endl;
431          mem += (*i)->size;
432          break;
433      }
434      // call the callback function, if defined
435      if((callback || forceCallback) && (*i)->callback)
436        (*i)->callback->call();
437    }
438    return true;
439  }
440
441  /**
442  * This function returns the total amount of bytes needed by getData to save the whole content of the variables
443  * @param id id of the gamestate
444  * @param mode same as getData
445  * @return amount of bytes
446  */
447  uint32_t Synchronisable::getSize(unsigned int id, int mode){
448    if(!doSync(id))
449      return 0;
450    int tsize=sizeof(synchronisableHeader);
451    if(mode==0x0)
452      mode=state_;
453    std::list<synchronisableVariable *>::iterator i;
454    for(i=syncList->begin(); i!=syncList->end(); i++){
455      if( ((*i)->mode & mode) == 0 )
456        continue;  // this variable should only be received, so dont add its size to the send-size
457      switch((*i)->type){
458      case DATA:
459        tsize+=(*i)->size;
460        break;
461      case STRING:
462        tsize+=sizeof(int);
463        (*i)->size=((std::string *)(*i)->var)->length()+1;
464        COUT(5) << "String size: " << (*i)->size << std::endl;
465        tsize+=(*i)->size;
466        break;
467      }
468      if( ( (*i)->mode & direction::bidirectional ) != 0)
469      {
470        tsize+=sizeof( (*i)->varReference );
471      }
472    }
473    return tsize;
474  }
475
476  /**
477   * This function determines, wheter the object should be saved to the bytestream (according to its syncmode/direction)
478   * @param id gamestate id
479   * @return true/false
480   */
481  bool Synchronisable::doSync(unsigned int id){
482    return ( (objectMode_&state_)!=0 && (!syncList->empty() ) );
483  }
484
485  bool Synchronisable::doSelection(unsigned int id){
486    return ( id==0 || id%objectFrequency_==objectID%objectFrequency_ ) && ((objectMode_&state_)!=0);
487  }
488
489  /**
490   * This function looks at the header located in the bytestream and checks wheter objectID and classID match with the Synchronisables ones
491   * @param mem pointer to the bytestream
492   */
493  bool Synchronisable::isMyData(uint8_t* mem)
494  {
495    synchronisableHeader *header = (synchronisableHeader *)mem;
496    assert(header->objectID==this->objectID);
497    return header->dataAvailable;
498  }
499
500  /**
501   * This function sets the synchronisation mode of the object
502   * If set to 0x1 variables will only be synchronised to the client
503   * If set to 0x2 variables will only be synchronised to the server
504   * If set to 0x3 variables will be synchronised bidirectionally (only if set so in registerVar)
505   * @param mode same as in registerVar
506   */
507  void Synchronisable::setObjectMode(int mode){
508    assert(mode==0x0 || mode==0x1 || mode==0x2 || mode==0x3);
509    objectMode_=mode;
510  }
511
512
513}
Note: See TracBrowser for help on using the repository browser.