Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

corrected some problems with objectID's on client and asserts

  • Property svn:eol-style set to native
File size: 21.4 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::registerVar(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  /**
289   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID and classID to the given memory
290   * takes a pointer to already allocated memory (must have at least getSize bytes length)
291   * structure of the bitstream:
292   * |totalsize,objectID,classID,var1,var2,string1_length,string1,var3,...|
293   * length of varx: size saved int syncvarlist
294   * @param mem pointer to allocated memory with enough size
295   * @param id gamestateid of the gamestate to be saved (important for priorities)
296   * @param mode defines the direction in which the data will be send/received
297   *             0x1: server->client
298   *             0x2: client->server (not recommended)
299   *             0x3: bidirectional
300   * @return true: if !doSync or if everything was successfully saved
301   */
302  bool Synchronisable::getData(uint8_t*& mem, unsigned int id, uint8_t mode){
303    if(mode==0x0)
304      mode=state_;
305    //if this tick is we dont synchronise, then abort now
306    if(!doSync(id, mode))
307      return true;
308    //std::cout << "inside getData" << std::endl;
309    unsigned int tempsize = 0;
310    if(classID==0)
311      COUT(3) << "classid 0 " << this->getIdentifier()->getName() << std::endl;
312
313    if (this->classID == (unsigned int)-1)
314        this->classID = this->getIdentifier()->getNetworkID();
315
316    assert(this->classID==this->getIdentifier()->getNetworkID());
317//     this->classID=this->getIdentifier()->getNetworkID(); // TODO: correct this
318    std::list<synchronisableVariable *>::iterator i;
319    unsigned int size;
320    size=getSize(id, mode);
321
322    // start copy header
323    synchronisableHeader *header = (synchronisableHeader *)mem;
324    header->size = size;
325    header->objectID = this->objectID;
326    header->creatorID = this->creatorID;
327    header->classID = this->classID;
328    header->dataAvailable = true;
329    tempsize += sizeof(synchronisableHeader);
330    mem += sizeof(synchronisableHeader);
331    // end copy header
332
333
334    COUT(5) << "Synchronisable getting data from objectID: " << objectID << " classID: " << classID << " length: " << size << std::endl;
335    // copy to location
336    for(i=syncList->begin(); i!=syncList->end(); ++i){
337      if( ((*i)->mode & mode) == 0 ){
338        COUT(5) << "not getting data: " << std::endl;
339        continue;  // this variable should only be received
340      }
341     
342      // =========== start bidirectional stuff =============
343      // if the variable gets synchronised bidirectional, then add the reference to the bytestream
344      if( ( (*i)->mode & direction::bidirectional ) == direction::bidirectional )
345      {
346        if( ( ((*i)->mode == direction::serverMaster) && (mode == 0x1) ) || \
347            ( ((*i)->mode == direction::clientMaster) && (mode == 0x2) ) )
348        {
349          // MASTER
350          if((*i)->type==DATA){
351            if( memcmp((*i)->var,(*i)->varBuffer,(*i)->size) != 0 ) //check whether the variable changed during the last tick
352            {
353              ((*i)->varReference)++;   //the variable changed so increase the refnr
354              memcpy((*i)->varBuffer, (*i)->var, (*i)->size); //set the buffer to the new value
355            }
356          }
357          else //STRING
358          {
359            if( *static_cast<std::string*>((*i)->var) != *static_cast<std::string*>((*i)->varBuffer) ) //the string changed
360            {
361              ((*i)->varReference)++;   //the variable changed
362              *static_cast<std::string*>((*i)->varBuffer) = *static_cast<std::string*>((*i)->var);  //now set the buffer to the new value
363            }
364          }
365        }
366        // copy the reference number to the stream
367        *(uint8_t*)mem = (*i)->varReference;
368        mem += sizeof( (*i)->varReference );
369        tempsize += sizeof( (*i)->varReference );
370      }
371      // ================== end bidirectional stuff
372       
373      switch((*i)->type){
374        case DATA:
375          memcpy( (void *)(mem), (void*)((*i)->var), (*i)->size);
376          mem += (*i)->size;
377          tempsize += (*i)->size;
378          break;
379        case STRING:
380          memcpy( (void *)(mem), (void *)&((*i)->size), sizeof(size_t) );
381          mem += sizeof(size_t);
382          const char *data = ( ( *(std::string *) (*i)->var).c_str());
383          memcpy( mem, (void*)data, (*i)->size);
384          COUT(5) << "synchronisable: char: " << (const char *)(mem) << " data: " << data << " string: " << *(std::string *)((*i)->var) << std::endl;
385          mem += (*i)->size;
386          tempsize += (*i)->size + sizeof(size_t);
387          break;
388      }
389    }
390    assert(tempsize==size);
391    return true;
392  }
393
394
395  /**
396   * This function takes a bytestream and loads the data into the registered variables
397   * @param mem pointer to the bytestream
398   * @param mode same as in getData
399   * @return true/false
400   */
401  bool Synchronisable::updateData(uint8_t*& mem, uint8_t mode, bool forceCallback){
402    if(mode==0x0)
403      mode=state_;
404    std::list<synchronisableVariable *>::iterator i;
405    //assert(objectMode_!=0x0);
406    //assert( (mode ^ objectMode_) != 0);
407    if(syncList->empty()){
408      COUT(4) << "Synchronisable::updateData syncList is empty" << std::endl;
409      return false;
410    }
411
412    uint8_t *data=mem;
413    // start extract header
414    synchronisableHeader *syncHeader = (synchronisableHeader *)mem;
415    assert(syncHeader->objectID==this->objectID);
416    assert(syncHeader->creatorID==this->creatorID);
417    assert(this->classID==syncHeader->classID); //TODO: fix this!!! maybe a problem with the identifier ?
418    if(syncHeader->dataAvailable==false){
419      mem += syncHeader->size;
420      return true;
421    }
422
423    mem += sizeof(synchronisableHeader);
424    // stop extract header
425
426    COUT(5) << "Synchronisable: objectID " << syncHeader->objectID << ", classID " << syncHeader->classID << " size: " << syncHeader->size << " synchronising data" << std::endl;
427    for(i=syncList->begin(); i!=syncList->end() && mem <= data+syncHeader->size; i++){
428      if( ((*i)->mode ^ mode) == 0 ){
429        COUT(5) << "synchronisable: not updating variable " << std::endl;
430        // if we have a forcecallback then do the callback
431        continue;  // this variable should only be set
432      }
433      COUT(5) << "Synchronisable: element size: " << (*i)->size << " type: " << (*i)->type << std::endl;
434      bool callback=false;
435      bool master=false;
436     
437      if( ( (*i)->mode & direction::bidirectional ) == direction::bidirectional )
438      {
439        uint8_t refNr = *(uint8_t *)mem;
440        if( ( ((*i)->mode == direction::serverMaster) && (mode == 0x1) ) || \
441            ( ((*i)->mode == direction::clientMaster) && (mode == 0x2) ) )
442        { // MASTER
443          master=true;
444          if( refNr != (*i)->varReference || ( memcmp((*i)->var, (*i)->varBuffer, (*i)->size) != 0 ) )
445          { // DISCARD data
446            if( (*i)->type == DATA )
447            {
448              mem += sizeof((*i)->varReference) + (*i)->size;
449            }
450            else //STRING
451            {
452              mem += sizeof(size_t) + *(size_t *)mem;
453            }
454            if( forceCallback && (*i)->callback)
455              (*i)->callback->call();
456            continue;
457          }//otherwise everything is ok and we update the value
458        }
459        else // SLAVE
460        {
461          if( (*i)->varReference == refNr ){
462            //discard data because it's outdated or not different to what we've got
463            if( (*i)->type == DATA )
464            {
465              mem += sizeof((*i)->varReference) + (*i)->size;
466            }
467            else //STRING
468            {
469              mem += sizeof(size_t) + *(size_t *)mem;
470            }
471            if( forceCallback && (*i)->callback)
472              (*i)->callback->call();
473            continue;
474          }
475          else
476            (*i)->varReference = refNr; //copy the reference value for this variable
477        }
478        mem += sizeof((*i)->varReference);
479      }
480     
481      switch((*i)->type){
482        case DATA:
483          if((*i)->callback) // check whether this variable changed (but only if callback was set)
484          {
485            if(memcmp((*i)->var, mem, (*i)->size) != 0)
486              callback=true;
487          }
488          if( master )
489          {
490            if( callback || memcmp((*i)->var, mem, (*i)->size) != 0 )
491              //value changed, so set the buffer to the new value
492              memcpy((*i)->varBuffer, mem, (*i)->size);
493          }
494          memcpy((*i)->var, mem, (*i)->size);
495          mem += (*i)->size;
496          break;
497        case STRING:
498          (*i)->size = *(size_t *)mem;
499          mem += sizeof(size_t);
500         
501          if( (*i)->callback) // check whether this string changed
502            if( *static_cast<std::string*>((*i)->var) != std::string((char *)mem) )
503              callback=true;
504          if( master )
505          {
506            if( callback || *static_cast<std::string*>((*i)->var) != std::string((char *)mem) )
507              //string changed. set the buffer to the new one
508              *static_cast<std::string*>((*i)->varBuffer)=*static_cast<std::string*>( (void*)(mem+sizeof(size_t)) );
509          }
510         
511          *((std::string *)((*i)->var)) = std::string((const char*)mem);
512          COUT(5) << "synchronisable: char: " << (const char*)mem << " string: " << std::string((const char*)mem) << std::endl;
513          mem += (*i)->size;
514          break;
515      }
516      // call the callback function, if defined
517      if((callback || forceCallback) && (*i)->callback)
518        (*i)->callback->call();
519    }
520    assert(mem == data+syncHeader->size);
521    return true;
522  }
523
524  /**
525  * This function returns the total amount of bytes needed by getData to save the whole content of the variables
526  * @param id id of the gamestate
527  * @param mode same as getData
528  * @return amount of bytes
529  */
530  uint32_t Synchronisable::getSize(unsigned int id, uint8_t mode){
531    int tsize=sizeof(synchronisableHeader);
532    if(mode==0x0)
533      mode=state_;
534    if(!doSync(id, mode))
535      return 0;
536    std::list<synchronisableVariable *>::iterator i;
537    for(i=syncList->begin(); i!=syncList->end(); i++){
538      if( ((*i)->mode & mode) == 0 )
539        continue;  // this variable should only be received, so dont add its size to the send-size
540      switch((*i)->type){
541      case DATA:
542        tsize+=(*i)->size;
543        break;
544      case STRING:
545        tsize+=sizeof(int);
546        (*i)->size=((std::string *)(*i)->var)->length()+1;
547        COUT(5) << "String size: " << (*i)->size << std::endl;
548        tsize+=(*i)->size;
549        break;
550      }
551      if( ( (*i)->mode & direction::bidirectional ) == direction::bidirectional )
552      {
553        tsize+=sizeof( (*i)->varReference );
554      }
555    }
556    return tsize;
557  }
558
559  /**
560   * This function determines, wheter the object should be saved to the bytestream (according to its syncmode/direction)
561   * @param id gamestate id
562   * @return true/false
563   */
564  bool Synchronisable::doSync(unsigned int id, uint8_t mode){
565    if(mode==0x0)
566      mode=state_;
567    return ( (objectMode_&mode)!=0 && (!syncList->empty() ) );
568  }
569
570  bool Synchronisable::doSelection(unsigned int id){
571    return true; //TODO: change this
572    //return ( id==0 || id%objectFrequency_==objectID%objectFrequency_ ) && ((objectMode_&state_)!=0);
573  }
574
575  /**
576   * This function looks at the header located in the bytestream and checks wheter objectID and classID match with the Synchronisables ones
577   * @param mem pointer to the bytestream
578   */
579  bool Synchronisable::isMyData(uint8_t* mem)
580  {
581    synchronisableHeader *header = (synchronisableHeader *)mem;
582    assert(header->objectID==this->objectID);
583    return header->dataAvailable;
584  }
585
586  /**
587   * This function sets the synchronisation mode of the object
588   * If set to 0x0 variables will not be synchronised at all
589   * If set to 0x1 variables will only be synchronised to the client
590   * If set to 0x2 variables will only be synchronised to the server
591   * If set to 0x3 variables will be synchronised bidirectionally (only if set so in registerVar)
592   * @param mode same as in registerVar
593   */
594  void Synchronisable::setObjectMode(uint8_t mode){
595    assert(mode==0x0 || mode==0x1 || mode==0x2 || mode==0x3);
596    objectMode_=mode;
597  }
598
599
600}
Note: See TracBrowser for help on using the repository browser.