Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

added a function unregisterVariable to unregister variable that has been registered inside a synchronisable before
use it like this:
unregisterVariable(&this→myVar_) if you registered the variable with REGISTERDATA(this→myVar_)

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