Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/hud3/src/network/GameStateManager.cc @ 1299

Last change on this file since 1299 was 1265, checked in by rgrieder, 17 years ago
  • filled initialiser list of SpaceShip
  • adapted VS files in order to link network statically (circular depend.)
File size: 17.1 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, (C) 2007
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29//
30// C++ Implementation: GameStateManager
31//
32// Description:
33//
34//
35// Author:  Oliver Scheuss, (C) 2007
36//
37// Copyright: See COPYING file that comes with this distribution
38//
39//
40
41#include "GameStateManager.h"
42
43#include <utility>
44#include <iostream>
45#include <zlib.h>
46
47#include "core/CoreIncludes.h"
48#include "core/BaseObject.h"
49#include "ClientInformation.h"
50#include "Synchronisable.h"
51
52namespace network
53{
54  GameStateManager::GameStateManager(ClientInformation *head) {
55    id_=0;
56    head_=head;
57  }
58
59  GameStateManager::~GameStateManager() {
60  }
61
62  void GameStateManager::update(){
63    cleanup();
64    reference = getSnapshot();
65    COUT(4) << "inserting gamestate: " << reference << std::endl;
66    gameStateMap.insert(std::pair<int, GameState*>(id_, reference));
67    gameStateUsed[id_]=0;
68    printGameStates();
69    return;
70  }
71 
72 
73  /**
74   * this function is used to keep the memory usage low
75   * it tries to delete all the unused gamestates
76   *
77   *
78   */
79  void GameStateManager::cleanup(){
80    std::map<int,int>::iterator it = gameStateUsed.begin();
81    while(it!=gameStateUsed.end()){
82      if((id_-(*it).first)<KEEP_GAMESTATES)
83        break;
84      if( (*it).second <= 0 ){
85        COUT(4) << "GameStateManager: deleting gamestate with id: " << (*it).first << ", uses: " << (*it).second << std::endl;
86        delete[] gameStateMap[(*it).first]->data;
87        delete gameStateMap[(*it).first];
88        gameStateMap.erase((*it).first);
89        gameStateUsed.erase(it++);
90        continue;
91      }/*else if(id_-it->first<=KEEP_GAMESTATES){  //as soon as we got a used gamestate break here because we could use newer gamestates in future but only if we do not exceed KEEP_GAMESTATES # of gamestates in cache
92        COUT(4) << "breaking " << std::endl;
93        break;
94      }*/
95      it++;
96    }
97  }
98
99  GameStateCompressed *GameStateManager::popGameState(int clientID) {
100    //why are we searching the same client's gamestate id as we searched in
101    //Server::sendGameState?
102    int gID = head_->findClient(clientID)->getGamestateID();
103    COUT(4) << "G.St.Man: popgamestate: sending gstate_id: " << id_ << " diffed from: " << gID << std::endl;
104//     COUT(3) << "gamestatemap: " << &gameStateMap << std::endl;
105    //chose wheather the next gamestate is the first or not
106    if(gID != GAMESTATEID_INITIAL){
107      // TODO something with the gamestatemap is wrong
108      GameState *client=NULL;
109      std::map<int, GameState*>::iterator it = gameStateMap.find(gID);
110      if(it!=gameStateMap.end())
111        client = it->second;
112      GameState *server = reference;
113      //head_->findClient(clientID)->setGamestateID(id);
114      COUT(3) << "client: " << client << " server: " << server << " gamestatemap: " << &gameStateMap << std::endl;
115      if(client)
116        return encode(client, server);
117      else
118        return encode(server);
119    } else {
120      COUT(4) << "we got a GAMESTATEID_INITIAL for clientID: " << clientID << std::endl;
121      GameState *server = reference;
122//       ackGameState(clientID, reference->id);
123      //head_->findClient(clientID)->setGamestateID(id);
124      return encode(server);
125      // return an undiffed gamestate and set appropriate flags
126    }
127  }
128 
129  bool GameStateManager::pushGameState( GameStateCompressed *gs, int clientID ){
130    GameState *ugs = decompress(gs);
131    delete[] gs->data;
132    delete gs;
133    bool result = loadPartialSnapshot(ugs, clientID);
134    delete[] ugs->data;
135    delete ugs;
136    return result;
137  }
138
139  /**
140  * This function goes through the whole list of synchronisables and
141  * saves all the synchronisables to a flat "list".
142  * @return struct of type gamestate containing the size of the whole gamestate and a pointer linking to the flat list
143  */
144  GameState *GameStateManager::getSnapshot()
145  {
146    //std::cout << "begin getSnapshot" << std::endl;
147    //the size of the gamestate
148    int totalsize=0;
149    int memsize=0;
150    //the size of one specific synchronisable
151    int tempsize=0;
152    // get the start of the Synchronisable list
153    orxonox::Iterator<Synchronisable> it;
154    // struct for return value of Synchronisable::getData()
155    syncData sync;
156
157    GameState *retval=new GameState; //return value
158    retval->id=++id_;
159    COUT(4) << "G.ST.Man: producing gamestate with id: " << retval->id << std::endl;
160    // offset of memory functions
161    int offset=0, size=0;
162    // get total size of gamestate
163    for(it = orxonox::ObjectList<Synchronisable>::start(); it; ++it){
164      size+=it->getSize(); // size of the actual data of the synchronisable
165      size+=3*sizeof(int); // size of datasize, classID and objectID
166    }
167    //retval->data = (unsigned char*)malloc(size);
168    retval->data = new unsigned char[size];
169    if(!retval->data){
170      COUT(2) << "GameStateManager: could not allocate memory" << std::endl;
171      return NULL;
172    }
173    memsize=size;
174    // go through all Synchronisables
175    for(it = orxonox::ObjectList<Synchronisable>::start(); it; ++it){
176      //get size of the synchronisable
177      tempsize=it->getSize();
178      // add place for data and 3 ints (length,classid,objectid)
179      totalsize+=tempsize+3*sizeof(int);
180      // allocate+tempsize additional space
181      if(totalsize > size){
182        COUT(3) << "G.St.Man: need additional memory" << std::endl;
183//         if(tempsize < 1000){
184//           retval->data = (unsigned char *)realloc((void *)retval->data, totalsize+1000);
185//           memsize+=1000;
186//         } else {
187//           retval->data = (unsigned char *)realloc((void *)retval->data, totalsize+1000);
188//           memsize+=tempsize+1000;
189//         }
190//         COUT(5) << "G.St.Man: additional space allocation finished" << std::endl;
191      }
192
193      // run Synchronisable::getData with offset and additional place for 3 ints in between (for ids and length)
194      sync=it->getData((retval->data)+offset+3*sizeof(int));
195      memcpy(retval->data+offset, (void *)&(sync.length), sizeof(int));
196      memcpy(retval->data+offset+sizeof(int), (void *)&(sync.objectID), sizeof(int));
197      memcpy(retval->data+offset+2*sizeof(int), (void *)&(sync.classID), sizeof(int));
198      // increase data pointer
199      offset+=tempsize+3*sizeof(int);
200    }
201    retval->size=totalsize;
202    //#### bugfix
203    retval->diffed = false;
204    retval->complete = true;
205    //std::cout << "end snapShot" << std::endl;
206    COUT(5) << "G.ST.Man: Gamestate size: " << totalsize << std::endl;
207    COUT(5) << "G.ST.Man: 'estimated' Gamestate size: " << size << std::endl;
208    return retval;
209  }
210
211  bool GameStateManager::loadPartialSnapshot(GameState *state, int clientID){
212    if(!state)
213      return false;
214    unsigned char *data=state->data;
215    COUT(4) << "loadSnapshot: loading gs: " << state->id << std::endl;
216    // get the start of the Synchronisable list
217    orxonox::Iterator<Synchronisable> it=orxonox::ObjectList<Synchronisable>::start();
218    syncData sync;
219    // loop as long as we have some data ;)
220    while(data < state->data+state->size){
221      // prepare the syncData struct
222      sync.length = *(int *)data;
223      data+=sizeof(int);
224      sync.objectID = *(int*)data;
225      data+=sizeof(int);
226      sync.classID = *(int*)data;
227      data+=sizeof(int);
228      sync.data = data;
229      data+=sync.length;
230      COUT(4) << "objectID: " << sync.objectID << " classID: " << sync.classID << std::endl;
231      while(it && it->objectID!=sync.objectID)
232        ++it;
233
234
235      if(!it){
236        // the object does not exist yet
237        COUT(4) << "loadsnapshot: creating new object " << std::endl;
238        //COUT(4) << "loadSnapshot:\tclassid: " << sync.classID << ", name: " << ID((unsigned int) sync.classID)->getName() << std::endl;
239        orxonox::Identifier* id = ID((unsigned int)sync.classID);
240        if(!id){
241          COUT(4) << "We could not identify a new object; classid: " << sync.classID << std::endl;
242          continue;
243        }
244        Synchronisable *no = dynamic_cast<Synchronisable *>(id->fabricate());
245        COUT(4) << "loadpartialsnapshot (generating new object): classid: " << sync.classID << " objectID: " << sync.objectID << " length: " << sync.length << std::endl;
246        no->objectID=sync.objectID;
247        no->classID=sync.classID;
248        it=orxonox::ObjectList<Synchronisable>::end();
249        // update data and create object/entity...
250        if( !no->updateData(sync) )
251          COUT(1) << "We couldn't update the object: " << sync.objectID << std::endl;
252        if( !no->create() )
253          COUT(1) << "We couldn't manifest (create() ) the object: " << sync.objectID << std::endl;
254      }else{
255        // we have our object
256        COUT(4) << "loadpartialsnapshot: we found the appropriate object" << std::endl;
257        if(checkAccess(clientID, sync.objectID)){
258          if(! it->updateData(sync))
259            COUT(1) << "We couldn't update objectID: " \
260              << sync.objectID << "; classID: " << sync.classID << std::endl;
261        }else
262          COUT(4) << "loadPartialSnapshot: no access to change objectID: " << sync.objectID << std::endl;
263      }
264      ++it;
265    }
266   
267    return true;
268  }
269 
270 
271  //##### ADDED FOR TESTING PURPOSE #####
272  GameStateCompressed* GameStateManager::testCompress( GameState* g ) {
273    return compress_( g );
274  }
275
276  GameState* GameStateManager::testDiff( GameState* a, GameState* b ) {
277    return diff( a, b );
278  }
279  //##### END TESTING PURPOSE #####
280
281  GameStateCompressed *GameStateManager::encode(GameState *a, GameState *b) {
282    COUT(4) << "G.St.Man: this will be a DIFFED gamestate" << std::endl;
283    GameState *r = diff(a,b);
284    GameStateCompressed *c = compress_(r);
285    delete[] r->data;
286    delete r;
287    return c;
288  }
289
290  GameStateCompressed *GameStateManager::encode(GameState *a) {
291    COUT(5) << "G.St.Man: encoding gamestate (compress)" << std::endl;
292    a->base_id=GAMESTATEID_INITIAL;
293    return compress_(a);
294    /*GameStateCompressed *g = new GameStateCompressed;
295    g->base_id = a->base_id;
296    g->id = a->id;
297    g->diffed = a->diffed;
298    g->data = a->data;
299    g->normsize = a->size;
300    g->compsize = a->size;
301    return g;*/
302  }
303
304  GameState *GameStateManager::diff(GameState *a, GameState *b) {
305    unsigned char *ap = a->data, *bp = b->data;
306    int of=0; // pointers offset
307    int dest_length=0;
308    if(a->size>=b->size)
309      dest_length=a->size;
310    else
311      dest_length=b->size;
312    //unsigned char *dp = (unsigned char *)malloc(dest_length*sizeof(unsigned char));
313    unsigned char *dp = new unsigned char[dest_length*sizeof(unsigned char)];
314    while(of<a->size && of<b->size){
315      *(dp+of)=*(ap+of)^*(bp+of); // do the xor
316      ++of;
317    }
318    if(a->size!=b->size){ // do we have to fill up ?
319      unsigned char n=0;
320      if(a->size<b->size){
321        while(of<dest_length){
322          *(dp+of)=n^*(bp+of);
323          of++;
324        }
325      } else{
326        while(of<dest_length){
327          *(dp+of)=*(ap+of)^n;
328          of++;
329        }
330      }
331    }
332
333    GameState *r = new GameState;
334    r->id = b->id;
335    r->size = dest_length;
336    r->diffed = true;
337    r->base_id = a->id;
338    r->data = dp;
339    r->complete = true;
340    return r;
341  }
342
343  GameStateCompressed *GameStateManager::compress_(GameState *a) {
344    //COUT(4) << "G.St.Man: compressing gamestate" << std::endl;
345
346    //COUT(4) << "G.St.Man: a: id: " << a->id << " base_id: " << a->base_id << " size: " << a->size << " diffed: " << a->diffed << std::endl;
347    int size = a->size;
348
349    uLongf buffer = (uLongf)((a->size + 12)*1.01)+1;
350    //COUT(4) << "size: " << size << ", buffer: " << buffer << std::endl;
351    //unsigned char* dest = (unsigned char*)malloc( buffer );
352    unsigned char *dest = new unsigned char[buffer];
353    //COUT(4) << "dest: " << dest << std::endl;
354    int retval;
355    //std::cout << "before ziped " << buffer << std::endl;
356    retval = compress( dest, &buffer, a->data, (uLong)size );
357    //COUT(4) << "bloablabla aft3er compress" << std::endl;
358    //std::cout << "after ziped " << buffer << std::endl;
359
360    switch ( retval ) {
361      case Z_OK: COUT(5) << "G.St.Man: compress: successfully compressed" << std::endl; break;
362      case Z_MEM_ERROR: COUT(1) << "G.St.Man: compress: not enough memory available in gamestate.compress" << std::endl; 
363      return NULL;
364      case Z_BUF_ERROR: COUT(2) << "G.St.Man: compress: not enough memory available in the buffer in gamestate.compress" << std::endl;
365      return NULL;
366      case Z_DATA_ERROR: COUT(2) << "G.St.Man: compress: data corrupted in gamestate.compress" << std::endl;
367      return NULL;
368    }
369
370    GameStateCompressed *compressedGamestate = new GameStateCompressed;
371    compressedGamestate->compsize = buffer;
372//     std::cout << "compressedGamestate.compsize = buffer; " << buffer << std::endl;
373    compressedGamestate->normsize = size;
374//     std::cout << "compressedGamestate.normsize = size; " << size << std::endl;
375    compressedGamestate->id = a->id;
376    compressedGamestate->data = dest;
377    compressedGamestate->diffed = a->diffed;
378    compressedGamestate->complete = a->complete;
379    compressedGamestate->base_id = a->base_id;
380    //COUT(5) << "G.St.Man: saved compressed data in GameStateCompressed:" << std::endl;
381    return compressedGamestate;
382  }
383 
384  GameState *GameStateManager::decompress(GameStateCompressed *a) {
385    //COUT(4) << "GameStateClient: uncompressing gamestate. id: " << a->id << ", baseid: " << a->base_id << ", normsize: " << a->normsize << ", compsize: " << a->compsize << std::endl;
386    int normsize = a->normsize;
387    int compsize = a->compsize;
388    int bufsize;
389    if(normsize < compsize)
390      bufsize = compsize;
391    else
392      bufsize = normsize;
393//     unsigned char* dest = (unsigned char*)malloc( bufsize );
394    unsigned char *dest = new unsigned char[bufsize];
395    int retval;
396    uLongf length=normsize;
397    //std::cout << "gamestateclient" << std::endl;
398    //std::cout << "normsize " << a.normsize << " compsize " << a.compsize << " " << bufsize << std::endl;
399    retval = uncompress( dest, &length, a->data, (uLong)compsize );
400    //std::cout << "length " << length << std::endl;
401    switch ( retval ) {
402      case Z_OK: COUT(5) << "successfully decompressed" << std::endl; break;
403      case Z_MEM_ERROR: COUT(1) << "not enough memory available" << std::endl; return NULL;
404      case Z_BUF_ERROR: COUT(2) << "not enough memory available in the buffer" << std::endl; return NULL;
405      case Z_DATA_ERROR: COUT(2) << "data corrupted (zlib)" << std::endl; return NULL;
406    }
407
408    GameState *gamestate = new GameState;
409    gamestate->id = a->id;
410    gamestate->size = normsize;
411    gamestate->data = dest;
412    gamestate->base_id = a->base_id;
413    gamestate->diffed = a->diffed;
414    gamestate->complete = a->complete;
415
416
417    return gamestate;
418  }
419 
420
421  void GameStateManager::ackGameState(int clientID, int gamestateID) {
422    ClientInformation *temp = head_->findClient(clientID);
423    int curid = temp->getGamestateID();
424    COUT(4) << "acking gamestate " << gamestateID << " for clientid: " << clientID << " curid: " << curid << std::endl;
425    // decrease usage of gamestate and save it
426//     deleteUnusedGameState(curid);
427    //increase gamestateused
428    --(gameStateUsed.find(curid)->second);
429    ++(gameStateUsed.find(gamestateID)->second);
430    temp->setGamestateID(gamestateID);
431    /*
432    GameState *old = clientGameState[clientID];
433    deleteUnusedGameState(old);
434    clientGameState[clientID]=idGameState[gamestateID];*/
435  }
436
437  bool GameStateManager::printGameStates() {
438    std::map<int, GameState*>::iterator it;
439    COUT(4) << "gamestates: ";
440    for(it = gameStateMap.begin(); it!=gameStateMap.end(); it++){
441      COUT(4) << (*it).first << ":" << (*it).second << " | ";
442    }
443    COUT(4) << std::endl;
444    return true;
445  }
446 
447  bool GameStateManager::checkAccess(int clientID, int objectID){
448    // currently we only check, wheter the object is the clients spaceship
449//     return head_->findClient(objectID)->getShipID()==objectID;
450    return true; // TODO: change this
451  }
452 
453  void GameStateManager::removeClient(ClientInformation* client){
454    gameStateUsed[client->getGamestateID()]--;
455    head_->removeClient(client->getID());
456  }
457
458}
Note: See TracBrowser for help on using the repository browser.