Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/netp4/src/network/packet/Gamestate.cc @ 3137

Last change on this file since 3137 was 3137, checked in by scheusso, 15 years ago

various performance and memory issues fixed

  • Property svn:eol-style set to native
File size: 19.3 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 *      Oliver Scheuss
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29#include "Gamestate.h"
30#include <enet/enet.h>
31#include <zlib.h>
32#include <cassert>
33#include "../GamestateHandler.h"
34#include "../synchronisable/Synchronisable.h"
35#include "../TrafficControl.h"
36#include "core/GameMode.h"
37#include "core/CoreIncludes.h"
38#include "core/Iterator.h"
39
40
41
42
43namespace orxonox {
44
45namespace packet {
46
47#define GAMESTATE_START(data) (data + GamestateHeader::getSize())
48
49#define PACKET_FLAG_GAMESTATE  ENET_PACKET_FLAG_RELIABLE
50
51
52Gamestate::Gamestate()
53{
54  flags_ = flags_ | PACKET_FLAG_GAMESTATE;
55  header_ = 0;
56}
57
58Gamestate::Gamestate(uint8_t *data, unsigned int clientID):
59    Packet(data, clientID)
60{
61  flags_ = flags_ | PACKET_FLAG_GAMESTATE;
62  header_ = new GamestateHeader(data_);
63}
64
65Gamestate::Gamestate(uint8_t *data)
66{
67  flags_ = flags_ | PACKET_FLAG_GAMESTATE;
68  data_=data;
69  header_ = new GamestateHeader(data_);
70}
71
72Gamestate::Gamestate(const Gamestate& g) :
73    Packet( *(Packet*)&g )
74{
75  flags_ = flags_ | PACKET_FLAG_GAMESTATE;
76  header_ = new GamestateHeader(data_);
77}
78
79
80Gamestate::~Gamestate()
81{
82  if( header_ )
83    delete header_;
84}
85
86bool Gamestate::collectData(int id, uint8_t mode)
87{
88  assert(this->header_==0); // make sure the header didn't exist before
89  uint32_t tempsize=0, currentsize=0;
90  assert(data_==0);
91  uint32_t size = calcGamestateSize(id, mode);
92
93  COUT(4) << "G.ST.Man: producing gamestate with id: " << id << std::endl;
94  if(size==0)
95    return false;
96  data_ = new uint8_t[size + GamestateHeader::getSize()];
97  if(!data_){
98    COUT(2) << "GameStateManager: could not allocate memory" << std::endl;
99    return false;
100  }
101 
102  // create the header object
103  assert( header_ == 0 );
104  header_ = new GamestateHeader(data_);
105
106  //start collect data synchronisable by synchronisable
107  uint8_t *mem=data_;
108  mem += GamestateHeader::getSize();
109  ObjectList<Synchronisable>::iterator it;
110  for(it = ObjectList<Synchronisable>::begin(); it; ++it){
111   
112//     tempsize=it->getSize(id, mode);
113
114    tempsize = it->getData(mem, id, mode);
115    if ( tempsize != 0 )
116      dataVector_.push_back( obj(it->getObjectID(), it->getCreatorID(), tempsize, mem-data_) );
117   
118#ifndef NDEBUG
119    if(currentsize+tempsize > size){
120      assert(0); // if we don't use multithreading this part shouldn't be neccessary
121      // start allocate additional memory
122      COUT(3) << "G.St.Man: need additional memory" << std::endl;
123      ObjectList<Synchronisable>::iterator temp = it;
124      uint32_t addsize=tempsize;
125      while(++temp)
126        addsize+=temp->getSize(id, mode);
127      data_ = (uint8_t *)realloc(data_, GamestateHeader::getSize() + currentsize + addsize);
128      if(!data_)
129        return false;
130      size = currentsize+addsize;
131    }// stop allocate additional memory
132#endif
133//     if(!it->getData(mem, id, mode))
134//       return false; // mem pointer gets automatically increased because of call by reference
135    // increase size counter by size of current synchronisable
136    currentsize+=tempsize;
137  }
138
139
140  //start write gamestate header
141  header_->setDataSize( currentsize );
142  header_->setID( id );
143  header_->setBaseID( GAMESTATEID_INITIAL );
144  header_->setDiffed( false );
145  header_->setComplete( true );
146  header_->setCompressed( false );
147  //stop write gamestate header
148
149  COUT(5) << "G.ST.Man: Gamestate size: " << currentsize << std::endl;
150  COUT(5) << "G.ST.Man: 'estimated' (and corrected) Gamestate size: " << size << std::endl;
151  return true;
152}
153
154bool Gamestate::spreadData(uint8_t mode)
155{
156  COUT(4) << "processing gamestate with id " << header_->getID() << endl;
157  assert(data_);
158  assert(!header_->isCompressed());
159  assert(!header_->isDiffed());
160  uint8_t *mem=data_+GamestateHeader::getSize();
161  Synchronisable *s;
162
163  // update the data of the objects we received
164  while(mem < data_+GamestateHeader::getSize()+header_->getDataSize()){
165    SynchronisableHeader objectheader(mem);
166
167    s = Synchronisable::getSynchronisable( objectheader.getObjectID() );
168    if(!s)
169    {
170      if (!GameMode::isMaster())
171      {
172        Synchronisable::fabricate(mem, mode);
173      }
174      else
175      {
176        mem += objectheader.getDataSize();
177      }
178    }
179    else
180    {
181      bool b = s->updateData(mem, mode);
182      assert(b);
183    }
184  }
185   // In debug mode, check first, whether there are no duplicate objectIDs
186#ifndef NDEBUG
187  if(this->getID()%1000==0){
188    std::list<uint32_t> v1;
189    ObjectList<Synchronisable>::iterator it;
190    for (it = ObjectList<Synchronisable>::begin(); it != ObjectList<Synchronisable>::end(); ++it) {
191      if (it->getObjectID() == OBJECTID_UNKNOWN) {
192        if (it->objectMode_ != 0x0) {
193          COUT(0) << "Found object with OBJECTID_UNKNOWN on the client with objectMode != 0x0!" << std::endl;
194          COUT(0) << "Possible reason for this error: Client created a synchronized object without the Server's approval." << std::endl;
195          COUT(0) << "Objects class: " << it->getIdentifier()->getName() << std::endl;
196          assert(false);
197        }
198      }
199      else {
200        std::list<uint32_t>::iterator it2;
201        for (it2 = v1.begin(); it2 != v1.end(); ++it2) {
202          if (it->getObjectID() == *it2) {
203            COUT(0) << "Found duplicate objectIDs on the client!" << std::endl
204                    << "Are you sure you don't create a Sychnronisable objcect with 'new' \
205                        that doesn't have objectMode = 0x0?" << std::endl;
206            assert(false);
207          }
208        }
209        v1.push_back(it->getObjectID());
210      }
211    }
212  }
213#endif
214  return true;
215}
216
217uint32_t Gamestate::getSize() const
218{
219  assert(data_);
220  if(header_->isCompressed())
221    return header_->getCompSize()+GamestateHeader::getSize();
222  else
223  {
224    return header_->getDataSize()+GamestateHeader::getSize();
225  }
226}
227
228bool Gamestate::operator==(packet::Gamestate gs){
229  uint8_t *d1 = data_+GamestateHeader::getSize();
230  uint8_t *d2 = gs.data_+GamestateHeader::getSize();
231  GamestateHeader* h1 = new GamestateHeader(data_);
232  GamestateHeader* h2 = new GamestateHeader(gs.data_);
233  assert(h1->getDataSize() == h2->getDataSize());
234  assert(!isCompressed());
235  assert(!gs.isCompressed());
236  return memcmp(d1, d2, h1->getDataSize())==0;
237}
238
239bool Gamestate::process()
240{
241  return GamestateHandler::addGamestate(this, getClientID());
242}
243
244
245
246bool Gamestate::compressData()
247{
248  assert(data_);
249  assert(!header_->isCompressed());
250  uLongf buffer = (uLongf)(((header_->getDataSize() + 12)*1.01)+1);
251  if(buffer==0)
252    return false;
253
254  uint8_t *ndata = new uint8_t[buffer+GamestateHeader::getSize()];
255  uint8_t *dest = ndata + GamestateHeader::getSize();
256  uint8_t *source = data_ + GamestateHeader::getSize();
257  int retval;
258  retval = compress( dest, &buffer, source, (uLong)(header_->getDataSize()) );
259  switch ( retval ) {
260    case Z_OK: COUT(5) << "G.St.Man: compress: successfully compressed" << std::endl; break;
261    case Z_MEM_ERROR: COUT(1) << "G.St.Man: compress: not enough memory available in gamestate.compress" << std::endl; return false;
262    case Z_BUF_ERROR: COUT(2) << "G.St.Man: compress: not enough memory available in the buffer in gamestate.compress" << std::endl; return false;
263    case Z_DATA_ERROR: COUT(2) << "G.St.Man: compress: data corrupted in gamestate.compress" << std::endl; return false;
264  }
265
266  //copy and modify header
267  GamestateHeader *temp = header_;
268  header_ = new GamestateHeader(ndata, temp);
269  delete temp;
270  //delete old data
271  delete[] data_;
272  //save new data
273  data_ = ndata;
274  header_->setCompSize( buffer );
275  header_->setCompressed( true );
276  COUT(5) << "gamestate compress datasize: " << header_->getDataSize() << " compsize: " << header_->getCompSize() << std::endl;
277  return true;
278}
279bool Gamestate::decompressData()
280{
281  assert(data_);
282  assert(header_->isCompressed());
283  COUT(4) << "GameStateClient: uncompressing gamestate. id: " << header_->getID() << ", baseid: " << header_->getBaseID() << ", datasize: " << header_->getDataSize() << ", compsize: " << header_->getCompSize() << std::endl;
284  uint32_t datasize = header_->getDataSize();
285  uint32_t compsize = header_->getCompSize();
286  uint32_t bufsize;
287  bufsize = datasize;
288  assert(bufsize!=0);
289  uint8_t *ndata = new uint8_t[bufsize + GamestateHeader::getSize()];
290  uint8_t *dest = ndata + GamestateHeader::getSize();
291  uint8_t *source = data_ + GamestateHeader::getSize();
292  int retval;
293  uLongf length=bufsize;
294  retval = uncompress( dest, &length, source, (uLong)compsize );
295  switch ( retval ) {
296    case Z_OK: COUT(5) << "successfully decompressed" << std::endl; break;
297    case Z_MEM_ERROR: COUT(1) << "not enough memory available" << std::endl; return false;
298    case Z_BUF_ERROR: COUT(2) << "not enough memory available in the buffer" << std::endl; return false;
299    case Z_DATA_ERROR: COUT(2) << "data corrupted (zlib)" << std::endl; return false;
300  }
301
302  //copy over the header
303  GamestateHeader *temp = header_;
304  header_ = new GamestateHeader( data_, header_ );
305  delete temp;
306
307  if (this->bDataENetAllocated_){
308    // Memory was allocated by ENet. --> We let it be since enet_packet_destroy will
309    // deallocated it anyway. So data and packet stay together.
310    this->bDataENetAllocated_ = false;
311  }
312  else{
313    // We allocated the memory in the first place (unlikely). So we destroy the old data
314    // and overwrite it with the new decompressed data.
315    delete[] this->data_;
316  }
317
318  //set new pointers
319  data_ = ndata;
320  header_->setCompressed( false );
321  assert(header_->getDataSize()==datasize);
322  assert(header_->getCompSize()==compsize);
323  return true;
324}
325
326/*Gamestate *Gamestate::diff(Gamestate *base)
327{
328  assert(data_);
329  assert(!header_->isCompressed());
330  assert(!header_->isDiffed());
331  GamestateHeader diffHeader(base->data_);
332  uint8_t *basep = GAMESTATE_START(base->data_), *gs = GAMESTATE_START(this->data_);
333  uint32_t of=0; // pointers offset
334  uint32_t dest_length=0;
335  dest_length=header_->getDataSize();
336  if(dest_length==0)
337    return NULL;
338  uint8_t *ndata = new uint8_t[dest_length*sizeof(uint8_t)+GamestateHeader::getSize()];
339  uint8_t *dest = ndata + GamestateHeader::getSize();
340  while(of < diffHeader.getDataSize() && of < header_->getDataSize()){
341    *(dest+of)=*(basep+of)^*(gs+of); // do the xor
342    ++of;
343  }
344  if(diffHeader.getDataSize()!=header_->getDataSize()){
345    uint8_t n=0;
346    if(diffHeader.getDataSize() < header_->getDataSize()){
347      while(of<dest_length){
348        *(dest+of)=n^*(gs+of);
349        of++;
350      }
351    }
352  }
353
354  Gamestate *g = new Gamestate(ndata, getClientID());
355  *(g->header_) = *header_;
356  g->header_->setDiffed( true );
357  g->header_->setBaseID( base->getID() );
358  g->flags_=flags_;
359  g->packetDirection_ = packetDirection_;
360  return g;
361}*/
362
363Gamestate *Gamestate::diff(Gamestate *base)
364{
365  assert(this && base); assert(data_ && base->data_);
366  assert(!header_->isCompressed() && !base->header_->isCompressed());
367  assert(!header_->isDiffed());
368 
369  uint8_t *basep = GAMESTATE_START(base->data_);
370  uint8_t *gs = GAMESTATE_START(this->data_);
371  uint32_t dest_length = header_->getDataSize();
372 
373  if(dest_length==0)
374    return NULL;
375 
376  uint8_t *ndata = new uint8_t[dest_length*sizeof(uint8_t)+GamestateHeader::getSize()];
377  uint8_t *dest = GAMESTATE_START(ndata);
378 
379  rawDiff( dest, gs, basep, header_->getDataSize(), base->header_->getDataSize() );
380#ifndef NDEBUG
381  uint8_t *dest2 = new uint8_t[dest_length];
382  rawDiff( dest2, dest, basep, header_->getDataSize(), base->header_->getDataSize() );
383  assert( memcmp( dest2, gs, dest_length) == 0 );
384#endif
385
386  Gamestate *g = new Gamestate(ndata, getClientID());
387  assert(g->header_);
388  *(g->header_) = *header_;
389  g->header_->setDiffed( true );
390  g->header_->setBaseID( base->getID() );
391  g->flags_=flags_;
392  g->packetDirection_ = packetDirection_;
393  assert(g->isDiffed());
394  assert(!g->isCompressed());
395  return g;
396}
397
398Gamestate *Gamestate::undiff(Gamestate *base)
399{
400  assert(this && base); assert(data_ && base->data_);
401  assert(!header_->isCompressed() && !base->header_->isCompressed());
402  assert(header_->isDiffed());
403 
404  uint8_t *basep = GAMESTATE_START(base->data_);
405  uint8_t *gs = GAMESTATE_START(this->data_);
406  uint32_t dest_length = header_->getDataSize();
407 
408  if(dest_length==0)
409    return NULL;
410 
411  uint8_t *ndata = new uint8_t[dest_length*sizeof(uint8_t)+GamestateHeader::getSize()];
412  uint8_t *dest = ndata + GamestateHeader::getSize();
413 
414  rawDiff( dest, gs, basep, header_->getDataSize(), base->header_->getDataSize() );
415 
416  Gamestate *g = new Gamestate(ndata, getClientID());
417  assert(g->header_);
418  *(g->header_) = *header_;
419  g->header_->setDiffed( false );
420  g->flags_=flags_;
421  g->packetDirection_ = packetDirection_;
422  assert(!g->isDiffed());
423  assert(!g->isCompressed());
424  return g;
425}
426
427
428// Gamestate *Gamestate::diff(Gamestate *base)
429// {
430//   assert(data_);
431//   assert(!header_->isCompressed());
432//   assert(!header_->isDiffed());
433//   GamestateHeader diffHeader(base->data_);
434//   uint8_t *basep = GAMESTATE_START(base->data_), *gs = GAMESTATE_START(this->data_);
435//   uint32_t of=0; // pointers offset
436//   uint32_t dest_length=0;
437//   dest_length=header_->getDataSize();
438//   if(dest_length==0)
439//     return NULL;
440//   uint8_t *ndata = new uint8_t[dest_length*sizeof(uint8_t)+GamestateHeader::getSize()];
441//   uint8_t *dest = ndata + GamestateHeader::getSize();
442//   
443//   
444//   // LOOP-UNROLLED DIFFING
445//   uint32_t *dest32 = (uint32_t*)dest, *base32 = (uint32_t*)basep, *gs32 = (uint32_t*)gs;
446//   // diff in 4-byte steps
447//   while( of < (uint32_t)(header_->getDataSize())/4 ){
448//     if( of < (uint32_t)(diffHeader.getDataSize())/4 )
449//     {
450//       *(dest32+of)=*(base32+of) ^ *(gs32+of); // do the xor
451//       ++of;
452//     }
453//     else
454//     {
455//       *(dest32+of)=*(gs32+of); // same as 0 ^ *(gs32+of)
456//       ++of;
457//     }
458//   }
459//   for( unsigned int of2 = 0; of2 < header_->getDataSize()%4; ++of2 )
460//   {
461//     if( of*4+of2 < diffHeader.getDataSize() )
462//     {
463//       *(dest+4*of+of2)=*(basep+4*of+of2) ^ *(gs+4*of+of2); // do the xor
464//     }
465//     else
466//     {
467//       *(dest+4*of+of2)=*(gs+4*of+of2); // same as 0 ^ *(gs32+of)
468//     }
469//   }
470//
471//   Gamestate *g = new Gamestate(ndata, getClientID());
472//   *(g->header_) = *header_;
473//   g->header_->setDiffed( true );
474//   g->header_->setBaseID( base->getID() );
475//   g->flags_=flags_;
476//   g->packetDirection_ = packetDirection_;
477//   return g;
478// }
479
480
481void Gamestate::rawDiff( uint8_t* newdata, uint8_t* data, uint8_t* basedata, uint32_t datalength, uint32_t baselength)
482{
483  uint64_t* gd = (uint64_t*)data;
484  uint64_t* bd = (uint64_t*)basedata;
485  uint64_t* nd = (uint64_t*)newdata;
486 
487  unsigned int i;
488  for( i=0; i<datalength/8; i++ )
489  {
490    if( i<baselength/8 )
491      *(nd+i) = *(gd+i) ^ *(bd+i);  // xor the data
492    else
493      *(nd+i) = *(gd+i); // just copy over the data
494  }
495  unsigned int j;
496  // now process the rest (when datalength isn't a multiple of 4)
497  for( j = 8*(datalength/8); j<datalength; j++ )
498  {
499    if( j<baselength )
500      *(newdata+j) = *(data+j) ^ *(basedata+j); // xor
501    else
502      *(newdata+j) = *(data+j); // just copy
503  }
504  assert(j==datalength);
505}
506
507Gamestate* Gamestate::doSelection(unsigned int clientID, unsigned int targetSize){
508  assert(data_);
509  std::list<obj>::iterator it;
510
511  // allocate memory for new data
512  uint8_t *gdata = new uint8_t[header_->getDataSize()+GamestateHeader::getSize()];
513  // create a gamestate out of it
514  Gamestate *gs = new Gamestate(gdata);
515  uint8_t *newdata = gdata + GamestateHeader::getSize();
516  uint8_t *origdata = GAMESTATE_START(data_);
517
518  //copy the GamestateHeader
519  assert(gs->header_);
520  *(gs->header_) = *header_;
521
522  uint32_t objectOffset;
523  unsigned int objectsize, destsize=0;
524  // TODO: Why is this variable not used?
525  //Synchronisable *object;
526
527  //call TrafficControl
528  TrafficControl::getInstance()->processObjectList( clientID, header_->getID(), dataVector_ );
529
530  //copy in the zeros
531//   std::list<obj>::iterator itt;
532//   COUT(0) << "myvector contains:";
533//   for ( itt=dataVector_.begin() ; itt!=dataVector_.end(); itt++ )
534//     COUT(0) << " " << (*itt).objID;
535//   COUT(0) << endl;
536  for(it=dataVector_.begin(); it!=dataVector_.end();){
537    SynchronisableHeader oldobjectheader(origdata);
538    SynchronisableHeader newobjectheader(newdata);
539    if ( (*it).objSize == 0 )
540    {
541      ++it;
542      continue;
543    }
544    objectsize = oldobjectheader.getDataSize();
545    objectOffset=SynchronisableHeader::getSize(); //skip the size and the availableData variables in the objectheader
546    if ( (*it).objID == oldobjectheader.getObjectID() ){
547      memcpy(newdata, origdata, objectsize);
548      assert(newobjectheader.isDataAvailable()==true);
549      ++it;
550    }else{
551      newobjectheader = oldobjectheader;
552      newobjectheader.setDataAvailable(false);
553      memset(newdata+objectOffset, 0, objectsize-objectOffset);
554    }
555    newdata += objectsize;
556    origdata += objectsize;
557    destsize += objectsize;
558  }
559#ifndef NDEBUG
560  uint32_t origsize = destsize;
561  while ( origsize < header_->getDataSize() )
562  {
563    SynchronisableHeader oldobjectheader(origdata);
564    objectsize = oldobjectheader.getDataSize();
565    origdata += objectsize;
566    origsize += objectsize;
567  }
568  assert(origsize==header_->getDataSize());
569  assert(destsize!=0);
570#endif
571  gs->header_->setDataSize( destsize );
572  return gs;
573}
574
575
576/*Gamestate *Gamestate::undiff(Gamestate *base)
577{
578  assert(this && base);assert(data_);
579  assert(header_->isDiffed());
580  assert(!header_->isCompressed() && !base->header_->isCompressed());
581  uint8_t *basep = GAMESTATE_START(base->data_);
582  uint8_t *gs = GAMESTATE_START(this->data_);
583  uint32_t of=0; // pointers offset
584  uint32_t dest_length=0;
585  dest_length=header_->getDataSize();
586  if(dest_length==0)
587    return NULL;
588  uint8_t *ndata = new uint8_t[dest_length*sizeof(uint8_t)+GamestateHeader::getSize()];
589  uint8_t *dest = ndata + GamestateHeader::getSize();
590  while(of < base->header_->getDataSize() && of < header_->getDataSize()){
591    *(dest+of)=*(basep+of)^*(gs+of); // do the xor
592    ++of;
593  }
594  if(base->header_->getDataSize()!=header_->getDataSize()){
595    uint8_t n=0;
596    if(base->header_->getDataSize() < header_->getDataSize()){
597      while(of < dest_length){
598        *(dest+of)=n^*(gs+of);
599        of++;
600      }
601    }
602  }
603  Gamestate *g = new Gamestate(ndata, getClientID());
604  assert(g->header_);
605  *(g->header_) = *header_;
606  g->header_->setDiffed( false );
607  g->flags_=flags_;
608  g->packetDirection_ = packetDirection_;
609  assert(!g->isDiffed());
610  assert(!g->isCompressed());
611  return g;
612}*/
613
614uint32_t Gamestate::calcGamestateSize(int32_t id, uint8_t mode)
615{
616  uint32_t size=0;
617    // get the start of the Synchronisable list
618  ObjectList<Synchronisable>::iterator it;
619    // get total size of gamestate
620  for(it = ObjectList<Synchronisable>::begin(); it; ++it)
621    size+=it->getSize(id, mode); // size of the actual data of the synchronisable
622  return size;
623}
624
625} //namespace packet
626} //namespace orxonox
Note: See TracBrowser for help on using the repository browser.