Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 2012 was 2011, checked in by scheusso, 17 years ago

use the new media path now

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