Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network/src/network/Synchronisable.cc @ 1794

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

some security assert in synchronisable

  • Property svn:eol-style set to native
File size: 14.2 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 <string>
44#include <iostream>
45#include <assert.h>
46
47#include "core/CoreIncludes.h"
48#include "core/BaseObject.h"
49// #include "core/Identifier.h"
50
51namespace network
52{
53 
54
55  std::map<unsigned int, Synchronisable *> Synchronisable::objectMap_;
56  std::queue<unsigned int> Synchronisable::deletedObjects_;
57
58  int Synchronisable::state_=0x1; // detemines wheter we are server (default) or client
59
60  /**
61  * Constructor:
62  * Initializes all Variables and sets the right objectID
63  */
64  Synchronisable::Synchronisable(){
65    RegisterRootObject(Synchronisable);
66    static unsigned int idCounter=0;
67    datasize=0;
68    objectFrequency_=1;
69    objectMode_=0x1; // by default do not send data to servere
70    objectID=idCounter++;
71    syncList = new std::list<synchronisableVariable *>;
72  }
73
74  /**
75   * Destructor:
76   * Delete all callback objects and remove objectID from the objectMap_
77   */
78  Synchronisable::~Synchronisable(){
79    // delete callback function objects
80    if(!orxonox::Identifier::isCreatingHierarchy()){
81      for(std::list<synchronisableVariable *>::iterator it = syncList->begin(); it!=syncList->end(); it++)
82        delete (*it)->callback;
83      assert(objectMap_[objectID]->objectID==objectID);
84      objectMap_.erase(objectID);
85    }
86  }
87
88  /**
89   * This function gets called after all neccessary data has been passed to the object
90   * Overload this function and recall the create function of the parent class
91   * @return true/false
92   */
93  bool Synchronisable::create(){
94    objectMap_[objectID]=this;
95    assert(objectMap_[objectID]==this);
96    this->classID = this->getIdentifier()->getNetworkID();
97    COUT(4) << "creating synchronisable: setting classid from " << this->getIdentifier()->getName() << " to: " << classID << std::endl;
98    return true;
99  }
100
101 
102  /**
103   * This function sets the internal mode for synchronisation
104   * @param b true if this object is located on a client or on a server
105   */
106  void Synchronisable::setClient(bool b){
107    if(b) // client
108      state_=0x2;
109    else  // server
110      state_=0x1;
111  }
112 
113  /**
114   * This function fabricated a new synchrnisable (and children of it), sets calls updateData and create
115   * After calling this function the mem pointer will be increased by the size of the needed data
116   * @param mem pointer to where the appropriate data is located
117   * @param mode defines the mode, how the data should be loaded
118   * @return pointer to the newly created synchronisable
119   */
120  Synchronisable *Synchronisable::fabricate(unsigned char*& mem, int mode)
121  {
122    unsigned int size, objectID, classID;
123    size = *(unsigned int *)mem;
124    objectID = *(unsigned int*)(mem+sizeof(unsigned int));
125    classID = *(unsigned int*)(mem+2*sizeof(unsigned int));
126   
127    orxonox::Identifier* id = GetIdentifier(classID);
128    assert(id);
129    orxonox::BaseObject *bo = id->fabricate();
130    Synchronisable *no = dynamic_cast<Synchronisable *>(bo);
131    assert(no);
132    no->objectID=objectID;
133    no->classID=classID;
134    COUT(3) << "fabricate objectID: " << no->objectID << " classID: " << no->classID << std::endl;
135          // update data and create object/entity...
136    assert(no->updateData(mem, mode));
137    assert( no->create() );
138    return no;
139  }
140
141 
142  /**
143   * Finds and deletes the Synchronisable with the appropriate objectID
144   * @param objectID objectID of the Synchronisable
145   * @return true/false
146   */
147  bool Synchronisable::deleteObject(unsigned int objectID){
148    assert(getSynchronisable(objectID));
149    assert(getSynchronisable(objectID)->objectID==objectID);
150    delete objectMap_[objectID];
151    return true;
152  }
153 
154  /**
155   * This function looks up the objectID in the objectMap_ and returns a pointer to the right Synchronisable
156   * @param objectID objectID of the Synchronisable
157   * @return pointer to the Synchronisable with the objectID
158   */
159  Synchronisable* Synchronisable::getSynchronisable(unsigned int objectID){
160    std::map<unsigned int, Synchronisable *>::iterator i = objectMap_.find(objectID);
161    if(i==objectMap_.end())
162      return NULL;
163    assert(i->second->objectID==objectID);
164    return (*i).second;
165  }
166
167 
168  /**
169  * This function is used to register a variable to be synchronized
170  * also counts the total datasize needed to save the variables
171  * @param var pointer to the variable
172  * @param size size of the datatype the variable consists of
173  * @param t the type of the variable (network::DATA or network::STRING
174  * @param mode same as in getData
175  * @param cb callback object that should get called, if the value of the variable changes
176  */
177  void Synchronisable::registerVar(void *var, int size, variableType t, int mode, NetworkCallbackBase *cb){
178    // create temporary synch.Var struct
179    synchronisableVariable *temp = new synchronisableVariable;
180    temp->size = size;
181    temp->var = var;
182    temp->mode = mode;
183    temp->type = t;
184    temp->callback = cb;
185    COUT(5) << "Syncronisable::registering var with size: " << temp->size << " and type: " << temp->type << std::endl;
186    // increase datasize
187    datasize+=sizeof(int)+size;
188    //std::cout << "push temp to syncList (at the bottom) " << datasize << std::endl;
189    COUT(5) << "Syncronisable::objectID: " << objectID << " this: " << this << " name: " << this->getIdentifier()->getName() << " networkID: " << this->getIdentifier()->getNetworkID() << std::endl;
190    syncList->push_back(temp);
191#ifndef NDEBUG
192    std::list<synchronisableVariable *>::iterator it = syncList->begin();
193    while(it!=syncList->end()){
194      assert(*it!=var);
195      it++;
196    }
197#endif
198  }
199 
200  /**
201   * This function takes all SynchronisableVariables out of the Synchronisable and saves them together with the size, objectID and classID to the given memory
202   * takes a pointer to already allocated memory (must have at least getSize bytes length)
203   * structure of the bitstream:
204   * |totalsize,objectID,classID,var1,var2,string1_length,string1,var3,...|
205   * length of varx: size saved int syncvarlist
206   * @param mem pointer to allocated memory with enough size
207   * @param id gamestateid of the gamestate to be saved (important for priorities)
208   * @param mode defines the direction in which the data will be send/received
209   *             0x1: server->client
210   *             0x2: client->server (not recommended)
211   *             0x3: bidirectional
212   * @return true: if !isMyTick or if everything was successfully saved
213   */
214  bool Synchronisable::getData(unsigned char*& mem, unsigned int id, int mode){
215    //if this tick is we dont synchronise, then abort now
216    if(!isMyTick(id))
217      return true;
218    //std::cout << "inside getData" << std::endl;
219    unsigned int tempsize = 0;
220    if(mode==0x0)
221      mode=state_;
222    if(classID==0)
223      COUT(3) << "classid 0 " << this->getIdentifier()->getName() << std::endl;
224    this->classID=this->getIdentifier()->getNetworkID(); // TODO: correct this
225    std::list<synchronisableVariable *>::iterator i;
226    unsigned int size;
227    size=getSize(id, mode);
228   
229    // start copy header
230    memcpy(mem, &size, sizeof(unsigned int));
231    mem+=sizeof(unsigned int);
232    memcpy(mem, &(this->objectID), sizeof(unsigned int));
233    mem+=sizeof(unsigned int);
234    memcpy(mem, &(this->classID), sizeof(unsigned int));
235    mem+=sizeof(unsigned int);
236    tempsize+=12;
237    // end copy header
238   
239   
240    COUT(5) << "Synchronisable getting data from objectID: " << objectID << " classID: " << classID << " length: " << size << std::endl;
241    // copy to location
242    for(i=syncList->begin(); i!=syncList->end(); ++i){
243      //(std::memcpy(retVal.data+n, (const void*)(&(i->size)), sizeof(int));
244      if( ((*i)->mode & mode) == 0 ){
245        COUT(5) << "not getting data: " << std::endl;
246        continue;  // this variable should only be received
247      }
248      switch((*i)->type){
249        case DATA:
250          memcpy( (void *)(mem), (void*)((*i)->var), (*i)->size);
251          mem+=(*i)->size;
252          tempsize+=(*i)->size;
253          break;
254        case STRING:
255          memcpy( (void *)(mem), (void *)&((*i)->size), sizeof(int) );
256          mem+=sizeof(int);
257          const char *data = ( ( *(std::string *) (*i)->var).c_str());
258          memcpy( mem, (void*)data, (*i)->size);
259          COUT(5) << "synchronisable: char: " << (const char *)(mem) << " data: " << data << " string: " << *(std::string *)((*i)->var) << std::endl;
260          mem+=(*i)->size;
261          tempsize+=(*i)->size + 4;
262          break;
263      }
264    }
265    assert(tempsize==size);
266    return true;
267  }
268
269 
270  /**
271   * This function takes a bytestream and loads the data into the registered variables
272   * @param mem pointer to the bytestream
273   * @param mode same as in getData
274   * @return true/false
275   */
276  bool Synchronisable::updateData(unsigned char*& mem, int mode){
277    if(mode==0x0)
278      mode=state_;
279    std::list<synchronisableVariable *>::iterator i;
280    if(syncList->empty()){
281      COUT(4) << "Synchronisable::updateData syncList is empty" << std::endl;
282      return false;
283    }
284    unsigned char *data=mem;
285    // start extract header
286    if(!isMyData(mem))
287      return true;
288    unsigned int objectID, classID, size;
289    size = *(int *)mem;
290    mem+=sizeof(size);
291    objectID = *(int *)mem;
292    mem+=sizeof(objectID);
293    classID = *(int *)mem;
294    mem+=sizeof(classID);
295    // stop extract header
296    assert(this->objectID==objectID);
297    assert(this->classID==classID);
298   
299    COUT(5) << "Synchronisable: objectID " << objectID << ", classID " << classID << " size: " << size << " synchronising data" << std::endl;
300    for(i=syncList->begin(); i!=syncList->end() && mem <= data+size; i++){
301      if( ((*i)->mode ^ mode) == 0 ){
302        COUT(5) << "synchronisable: not updating variable " << std::endl;
303        continue;  // this variable should only be set
304      }
305      COUT(5) << "Synchronisable: element size: " << (*i)->size << " type: " << (*i)->type << std::endl;
306      bool callback=false;
307      switch((*i)->type){
308        case DATA:
309          if((*i)->callback) // check whether this variable changed (but only if callback was set)
310            if(strncmp((char *)(*i)->var, (char *)mem, (*i)->size)!=0)
311              callback=true;
312          memcpy((void*)(*i)->var, mem, (*i)->size);
313          mem+=(*i)->size;
314          break;
315        case STRING:
316          (*i)->size = *(int *)mem;
317          COUT(5) << "string size: " << (*i)->size << std::endl;
318          mem+=sizeof(int);
319          if((*i)->callback) // check whether this string changed
320            if( *(std::string *)((*i)->var) != std::string((char *)mem) )
321              callback=true;
322          *((std::string *)((*i)->var)) = std::string((const char*)mem);
323          COUT(5) << "synchronisable: char: " << (const char*)mem << " string: " << std::string((const char*)mem) << std::endl;
324          mem += (*i)->size;
325          break;
326      }
327      // call the callback function, if defined
328      if(callback && (*i)->callback)
329        (*i)->callback->call();
330    }
331    return true;
332  }
333
334  /**
335  * This function returns the total amount of bytes needed by getData to save the whole content of the variables
336  * @param id id of the gamestate
337  * @param mode same as getData
338  * @return amount of bytes
339  */
340  int Synchronisable::getSize(unsigned int id, int mode){
341    if(!isMyTick(id))
342      return 0;
343    int tsize=sizeof(synchronisableHeader);
344    if(mode==0x0)
345      mode=state_;
346    std::list<synchronisableVariable *>::iterator i;
347    for(i=syncList->begin(); i!=syncList->end(); i++){
348      if( ((*i)->mode & mode) == 0 )
349        continue;  // this variable should only be received, so dont add its size to the send-size
350      switch((*i)->type){
351      case DATA:
352        tsize+=(*i)->size;
353        break;
354      case STRING:
355        tsize+=sizeof(int);
356        (*i)->size=((std::string *)(*i)->var)->length()+1;
357        COUT(5) << "String size: " << (*i)->size << std::endl;
358        tsize+=(*i)->size;
359        break;
360      }
361    }
362    return tsize;
363  }
364
365  /**
366   * This function determines, wheter the object should be saved to the bytestream (according to its syncfrequency)
367   * @param id gamestate id
368   * @return true/false
369   */
370  bool Synchronisable::isMyTick(unsigned int id){
371//     return true;
372    return ( id==0 || id%objectFrequency_==objectID%objectFrequency_ ) && ((objectMode_&state_)!=0);
373  }
374 
375  /**
376   * This function looks at the header located in the bytestream and checks wheter objectID and classID match with the Synchronisables ones
377   * @param mem pointer to the bytestream
378   */
379  bool Synchronisable::isMyData(unsigned char* mem)
380  {
381    unsigned int objectID, classID, size;
382    size = *(int *)mem;
383    mem+=sizeof(size);
384    objectID = *(int *)mem;
385    mem+=sizeof(objectID);
386    classID = *(int *)mem;
387    mem+=sizeof(classID);
388   
389    assert(classID == this->classID);
390    return (objectID == this->objectID);
391  }
392 
393  /**
394   * This function sets the synchronisation mode of the object
395   * If set to 0x1 variables will only be synchronised to the client
396   * If set to 0x2 variables will only be synchronised to the server
397   * If set to 0x3 variables will be synchronised bidirectionally (only if set so in registerVar)
398   * @param mode same as in registerVar
399   */
400  void Synchronisable::setObjectMode(int mode){
401    assert(mode==0x1 || mode==0x2 || mode==0x3);
402    objectMode_=mode;
403  }
404
405
406}
Note: See TracBrowser for help on using the repository browser.