Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/network/src/network/Server.cc @ 1739

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

further fixes (diff/undiff not working yet)

  • Property svn:eol-style set to native
File size: 12.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, (C) 2007
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29//
30// C++ Implementation: Server
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 "Server.h"
42
43#include <iostream>
44
45
46#include "ConnectionManager.h"
47#include "GamestateManager.h"
48#include "ClientInformation.h"
49#include "util/Sleep.h"
50#include "objects/SpaceShip.h"
51#include "core/ConsoleCommand.h"
52#include "packet/Chat.h"
53#include "packet/Packet.h"
54#include "packet/Welcome.h"
55#include <util/Convert.h>
56
57namespace network
58{
59  #define MAX_FAILURES 20;
60  #define NETWORK_FREQUENCY 30
61 
62  /**
63  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
64  *
65  */
66  Server::Server() {
67    timeSinceLastUpdate_=0;
68    connection = new ConnectionManager();
69    gamestates_ = new GamestateManager();
70    isServer_ = true;
71  }
72 
73  Server::Server(int port){
74    timeSinceLastUpdate_=0;
75    connection = new ConnectionManager(port);
76    gamestates_ = new GamestateManager();
77    isServer_ = true;
78  }
79
80  /**
81  * Constructor
82  * @param port Port to listen on
83  * @param bindAddress Address to listen on
84  */
85  Server::Server(int port, std::string bindAddress) {
86    timeSinceLastUpdate_=0;
87    connection = new ConnectionManager(port, bindAddress);
88    gamestates_ = new GamestateManager();
89    isServer_ = true;
90  }
91
92  /**
93  * Constructor
94  * @param port Port to listen on
95  * @param bindAddress Address to listen on
96  */
97  Server::Server(int port, const char *bindAddress) {
98    timeSinceLastUpdate_=0;
99    connection = new ConnectionManager(port, bindAddress);
100    gamestates_ = new GamestateManager();
101    isServer_ = true;
102  }
103
104  /**
105  * This function opens the server by creating the listener thread
106  */
107  void Server::open() {
108    connection->createListener();
109    return;
110  }
111
112  /**
113  * This function closes the server
114  */
115  void Server::close() {
116    connection->quitListener();
117    return;
118  }
119
120  bool Server::processChat(packet::Chat *message, unsigned int clientID){
121    ClientInformation *temp = ClientInformation::getBegin();
122    while(temp){
123      message->setClientID(temp->getID());
124      if(!message->send())
125        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
126      temp = temp->next();
127    }
128    return message->process();
129  }
130 
131  /**
132  * This function sends out a message to all clients
133  * @param msg message
134  * @return true/false
135  */
136  bool Server::sendChat(packet::Chat *chat) {
137    //TODO: change this (no informations about who wrote a message)
138    assert(0);
139    ClientInformation *temp = ClientInformation::getBegin();
140    while(temp){
141      chat->setClientID(temp->getID());
142      if(!chat->send())
143        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
144    }
145    return chat->process();;
146  }
147
148  /**
149  * This function sends out a message to all clients
150  * @param msg message
151  * @return true/false
152  */
153//   bool Server::sendChat(const char *msg) {
154//     char *message = new char [strlen(msg)+10+1];
155//     sprintf(message, "Player %d: %s", CLIENTID_SERVER, msg);
156//     COUT(1) << message << std::endl;
157//     ENetPacket *packet = packet_gen.chatMessage(message);
158//     COUT(5) <<"Server: adding Packets" << std::endl;
159//     return connection->addPacketAll(packet);
160//   }
161
162  /**
163  * Run this function once every tick
164  * calls processQueue and updateGamestate
165  * @param time time since last tick
166  */
167  void Server::tick(float time) {
168    processQueue();
169    //this steers our network frequency
170    timeSinceLastUpdate_+=time;
171    if(timeSinceLastUpdate_>=(1./NETWORK_FREQUENCY)){
172      timeSinceLastUpdate_=(float)((int)(timeSinceLastUpdate_*NETWORK_FREQUENCY))/timeSinceLastUpdate_;
173//      timeSinceLastUpdate_-=1./NETWORK_FREQUENCY;
174      gamestates_->processGamestates();
175      updateGamestate();
176    }
177    /*while(timeSinceLastUpdate_>1./NETWORK_FREQUENCY)
178      timeSinceLastUpdate_-=1./NETWORK_FREQUENCY;*/
179//     usleep(5000); // TODO remove
180    return;
181  }
182 
183  bool Server::queuePacket(ENetPacket *packet, int clientID){
184    return connection->addPacket(packet, clientID);
185  }
186
187  /**
188  * processes all the packets waiting in the queue
189  */
190  void Server::processQueue() {
191    ENetEvent *event;
192    while(!connection->queueEmpty()){
193      //std::cout << "Client " << clientID << " sent: " << std::endl;
194      //clientID here is a reference to grab clientID from ClientInformation
195      event = connection->getEvent();
196      if(!event)
197        continue;
198      assert(event->type != ENET_EVENT_TYPE_NONE);
199      switch( event->type ) {
200      case ENET_EVENT_TYPE_CONNECT:
201        COUT(3) << "processing event_Type_connect" << std::endl;
202        addClient(event);
203        break;
204      case ENET_EVENT_TYPE_DISCONNECT:
205        if(ClientInformation::findClient(&event->peer->address))
206          disconnectClient(event);
207        break;
208      case ENET_EVENT_TYPE_RECEIVE:
209        if(!processPacket(event->packet, event->peer))
210          COUT(3) << "processing incoming packet failed" << std::endl;
211        break;
212      default:
213        break;
214      }
215      delete event;
216      //if statement to catch case that packetbuffer is empty
217    }
218  }
219
220  /**
221  * takes a new snapshot of the gamestate and sends it to the clients
222  */
223  void Server::updateGamestate() {
224    gamestates_->update();
225    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
226    //std::cout << "updated gamestate, sending it" << std::endl;
227    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
228    sendGameState();
229    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
230    //std::cout << "sent gamestate" << std::endl;
231  }
232
233  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
234    packet::Packet *p = packet::Packet::createPacket(packet, peer);
235    return p->process();
236  }
237 
238  /**
239  * sends the gamestate
240  */
241  bool Server::sendGameState() {
242    COUT(5) << "Server: starting function sendGameState" << std::endl;
243    ClientInformation *temp = ClientInformation::getBegin();
244    bool added=false;
245    while(temp != NULL){
246      if( !(temp->getSynched()) ){
247        COUT(5) << "Server: not sending gamestate" << std::endl;
248        temp=temp->next();
249        if(!temp)
250          break;
251        //think this works without continue
252        continue;
253      }
254      COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
255      COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl;
256      int gid = temp->getGamestateID(); //get gamestate id
257      int cid = temp->getID(); //get client id
258      COUT(5) << "Server: got acked (gamestate) ID from clientlist: " << gid << std::endl;
259      packet::Gamestate *gs = gamestates_->popGameState(cid);
260      if(gs==NULL){
261        COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
262        continue;
263      }
264      //std::cout << "adding gamestate" << std::endl;
265      gs->setClientID(cid);
266      assert(gs->compressData());
267      if ( !gs->send() ){
268        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl; 
269        temp->addFailure();
270      }else
271        temp->resetFailures();
272      added=true;
273      temp=temp->next();
274      // gs gets automatically deleted by enet callback
275    }
276    /*if(added) {
277      //std::cout << "send gamestates from server.cc in sendGameState" << std::endl;
278      return connection->sendPackets();
279    }*/
280    //COUT(5) << "Server: had no gamestates to send" << std::endl;
281    return true;
282  }
283 
284//   void Server::processChat( chat *data, int clientId){
285//     char *message = new char [strlen(data->message)+10+1];
286//     sprintf(message, "Player %d: %s", clientId, data->message);
287//     COUT(1) << message << std::endl;
288//     ENetPacket *pck = packet_gen.chatMessage(message);
289//     connection->addPacketAll(pck);
290//     delete[] data->message;
291//     delete data;
292//   }
293 
294  bool Server::addClient(ENetEvent *event){
295    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
296    if(!temp){
297      COUT(2) << "Server: could not add client" << std::endl;
298      return false;
299    }
300    if(temp->prev()->getBegin()) { //not good if you use anything else than insertBack
301      temp->prev()->setID(0); //bugfix: not necessary but usefull
302      temp->setID(1);
303    }
304    else
305      temp->setID(temp->prev()->getID()+1);
306    temp->setPeer(event->peer);
307    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
308    return createClient(temp->getID());
309  }
310 
311  bool Server::createClient(int clientID){
312    ClientInformation *temp = ClientInformation::findClient(clientID);
313    if(!temp){
314      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
315      return false;
316    }
317    COUT(4) << "Con.Man: creating client id: " << temp->getID() << std::endl;
318    connection->syncClassid(temp->getID());
319    COUT(5) << "creating spaceship for clientid: " << temp->getID() << std::endl;
320    // TODO: this is only a hack, untill we have a possibility to define default player-join actions
321    if(!createShip(temp))
322      COUT(2) << "Con.Man. could not create ship for clientid: " << clientID << std::endl;
323    else
324      COUT(3) << "created spaceship" << std::endl;
325    temp->setSynched(true);
326    COUT(3) << "sending welcome" << std::endl;
327    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
328    w->setClientID(temp->getID());
329    assert(w->send());
330    return true;
331  }
332 
333  bool Server::createShip(ClientInformation *client){
334    if(!client)
335      return false;
336    orxonox::Identifier* id = ID("SpaceShip");
337    if(!id){
338      COUT(4) << "We could not create the SpaceShip for client: " << client->getID() << std::endl;
339      return false;
340    }
341    orxonox::SpaceShip *no = dynamic_cast<orxonox::SpaceShip *>(id->fabricate());
342    no->classID = id->getNetworkID();
343    client->setShipID(no->objectID);
344    no->setPosition(orxonox::Vector3(0,0,80));
345    no->setScale(10);
346    //no->setYawPitchRoll(orxonox::Degree(-90),orxonox::Degree(-90),orxonox::Degree(0));
347    no->setMesh("assff.mesh");
348    no->setMaxSpeed(500);
349    no->setMaxSideAndBackSpeed(50);
350    no->setMaxRotation(1.0);
351    no->setTransAcc(200);
352    no->setRotAcc(3.0);
353    no->setTransDamp(75);
354    no->setRotDamp(1.0);
355    no->setCamera(std::string("cam_") + convertToString(client->getID()));
356    no->create();
357    no->setBacksync(true);
358   
359    return true;
360  }
361 
362  bool Server::disconnectClient(ENetEvent *event){
363    COUT(4) << "removing client from list" << std::endl;
364    //return removeClient(head_->findClient(&(peer->address))->getID());
365   
366    //boost::recursive_mutex::scoped_lock lock(head_->mutex_);
367    orxonox::Iterator<orxonox::SpaceShip> it = orxonox::ObjectList<orxonox::SpaceShip>::start();
368    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
369    if(!client)
370      return false;
371    gamestates_->removeClient(client);
372    while(it){
373      if(it->objectID!=client->getShipID()){
374        ++it;
375        continue;
376      }
377      orxonox::Iterator<orxonox::SpaceShip> temp=it;
378      ++it;
379      delete  *temp;
380      return ClientInformation::removeClient(event->peer);
381    }
382    return false;
383  }
384
385  void Server::disconnectClient(int clientID){
386    ClientInformation *client = ClientInformation::findClient(clientID);
387    if(client)
388      disconnectClient(client);
389  }
390  void Server::disconnectClient( ClientInformation *client){
391    connection->disconnectClient(client);
392    gamestates_->removeClient(client);
393  }
394 
395}
Note: See TracBrowser for help on using the repository browser.