Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/presentation/src/network/Server.cc @ 2415

Last change on this file since 2415 was 2415, checked in by scheusso, 15 years ago
  • adjusted some priorities of objects (movableentity, controllableentity, positionableentity, model)
  • dedicated server mode doesn't consume 100%cpu load anymore now
  • 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#include <cassert>
45
46
47#include "ConnectionManager.h"
48#include "ClientConnectionListener.h"
49#include "GamestateManager.h"
50#include "ClientInformation.h"
51#include "util/Sleep.h"
52#include "core/ConsoleCommand.h"
53#include "core/CoreIncludes.h"
54#include "core/Iterator.h"
55#include "packet/Chat.h"
56#include "packet/Packet.h"
57#include "packet/Welcome.h"
58#include "packet/DeleteObjects.h"
59#include <util/Convert.h>
60#include "ChatListener.h"
61
62namespace orxonox
63{
64  const unsigned int MAX_FAILURES = 20;
65
66  /**
67  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
68  *
69  */
70  Server::Server() {
71    timeSinceLastUpdate_=0;
72    connection = new ConnectionManager();
73    gamestates_ = new GamestateManager();
74  }
75
76  Server::Server(int port){
77    timeSinceLastUpdate_=0;
78    connection = new ConnectionManager(port);
79    gamestates_ = new GamestateManager();
80  }
81
82  /**
83  * Constructor
84  * @param port Port to listen on
85  * @param bindAddress Address to listen on
86  */
87  Server::Server(int port, const std::string& bindAddress) {
88    timeSinceLastUpdate_=0;
89    connection = new ConnectionManager(port, bindAddress);
90    gamestates_ = new GamestateManager();
91  }
92
93  /**
94  * Constructor
95  * @param port Port to listen on
96  * @param bindAddress Address to listen on
97  */
98  Server::Server(int port, const char *bindAddress) {
99    timeSinceLastUpdate_=0;
100    connection = new ConnectionManager(port, bindAddress);
101    gamestates_ = new GamestateManager();
102  }
103
104  /**
105  * @brief Destructor
106  */
107  Server::~Server(){
108    if(connection)
109      delete connection;
110    if(gamestates_)
111      delete gamestates_;
112  }
113
114  /**
115  * This function opens the server by creating the listener thread
116  */
117  void Server::open() {
118    connection->createListener();
119    return;
120  }
121
122  /**
123  * This function closes the server
124  */
125  void Server::close() {
126    connection->quitListener();
127    return;
128  }
129
130  bool Server::processChat(const std::string& message, unsigned int playerID){
131    ClientInformation *temp = ClientInformation::getBegin();
132    packet::Chat *chat;
133    while(temp){
134      chat = new packet::Chat(message, playerID);
135      chat->setClientID(temp->getID());
136      if(!chat->send())
137        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
138      temp = temp->next();
139    }
140//    COUT(1) << "Player " << playerID << ": " << message << std::endl;
141    return true;
142  }
143
144
145  /**
146  * Run this function once every tick
147  * calls processQueue and updateGamestate
148  * @param time time since last tick
149  */
150  void Server::tick(float time) {
151    processQueue();
152    //this steers our network frequency
153    timeSinceLastUpdate_+=time;
154    if(timeSinceLastUpdate_>=NETWORK_PERIOD){
155      timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
156      gamestates_->processGamestates();
157      updateGamestate();
158    }
159  }
160
161  bool Server::queuePacket(ENetPacket *packet, int clientID){
162    return connection->addPacket(packet, clientID);
163  }
164 
165  /**
166   * @brief: returns ping time to client in milliseconds
167   */
168  unsigned int Server::getPing(unsigned int clientID){
169    assert(ClientInformation::findClient(clientID));
170    return ClientInformation::findClient(clientID)->getRTT();
171  }
172
173  /**
174   * @brief: return packet loss ratio to client (scales from 0 to 1)
175   */
176  double Server::getPacketLoss(unsigned int clientID){
177    assert(ClientInformation::findClient(clientID));
178    return ClientInformation::findClient(clientID)->getPacketLoss();
179  }
180 
181  /**
182  * processes all the packets waiting in the queue
183  */
184  void Server::processQueue() {
185    ENetEvent *event;
186    while(!connection->queueEmpty()){
187      //std::cout << "Client " << clientID << " sent: " << std::endl;
188      //clientID here is a reference to grab clientID from ClientInformation
189      event = connection->getEvent();
190      if(!event)
191        continue;
192      assert(event->type != ENET_EVENT_TYPE_NONE);
193      switch( event->type ) {
194      case ENET_EVENT_TYPE_CONNECT:
195        COUT(3) << "processing event_Type_connect" << std::endl;
196        addClient(event);
197        break;
198      case ENET_EVENT_TYPE_DISCONNECT:
199        if(ClientInformation::findClient(&event->peer->address))
200          disconnectClient(event);
201        break;
202      case ENET_EVENT_TYPE_RECEIVE:
203        if(!processPacket(event->packet, event->peer))
204          COUT(3) << "processing incoming packet failed" << std::endl;
205        break;
206      default:
207        break;
208      }
209      delete event;
210      //if statement to catch case that packetbuffer is empty
211    }
212  }
213
214  /**
215  * takes a new snapshot of the gamestate and sends it to the clients
216  */
217  void Server::updateGamestate() {
218    gamestates_->update();
219    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
220    //std::cout << "updated gamestate, sending it" << std::endl;
221    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
222    sendGameState();
223    sendObjectDeletes();
224    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
225    //std::cout << "sent gamestate" << std::endl;
226  }
227
228  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
229    packet::Packet *p = packet::Packet::createPacket(packet, peer);
230    return p->process();
231  }
232
233  /**
234  * sends the gamestate
235  */
236  bool Server::sendGameState() {
237    COUT(5) << "Server: starting function sendGameState" << std::endl;
238    ClientInformation *temp = ClientInformation::getBegin();
239    bool added=false;
240    while(temp != NULL){
241      if( !(temp->getSynched()) ){
242        COUT(5) << "Server: not sending gamestate" << std::endl;
243        temp=temp->next();
244        if(!temp)
245          break;
246        //think this works without continue
247        continue;
248      }
249      COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
250      COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl;
251      int gid = temp->getGamestateID(); //get gamestate id
252      int cid = temp->getID(); //get client id
253      COUT(5) << "Server: got acked (gamestate) ID from clientlist: " << gid << std::endl;
254      packet::Gamestate *gs = gamestates_->popGameState(cid);
255      if(gs==NULL){
256        COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
257        temp = temp->next();
258        continue;
259      }
260      //std::cout << "adding gamestate" << std::endl;
261      gs->setClientID(cid);
262      if ( !gs->send() ){
263        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
264        temp->addFailure();
265      }else
266        temp->resetFailures();
267      added=true;
268      temp=temp->next();
269      // gs gets automatically deleted by enet callback
270    }
271    return true;
272  }
273
274  bool Server::sendObjectDeletes(){
275    ClientInformation *temp = ClientInformation::getBegin();
276    packet::DeleteObjects *del = new packet::DeleteObjects();
277    if(!del->fetchIDs())
278      return true;  //everything ok (no deletes this tick)
279//     COUT(3) << "sending DeleteObjects" << std::endl;
280    while(temp != NULL){
281      if( !(temp->getSynched()) ){
282        COUT(5) << "Server: not sending gamestate" << std::endl;
283        temp=temp->next();
284        continue;
285      }
286      int cid = temp->getID(); //get client id
287      packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
288      assert(cd);
289      cd->setClientID(cid);
290      if ( !cd->send() )
291        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
292      temp=temp->next();
293      // gs gets automatically deleted by enet callback
294    }
295    return true;
296  }
297
298
299  bool Server::addClient(ENetEvent *event){
300    static unsigned int newid=1;
301
302    COUT(2) << "Server: adding client" << std::endl;
303    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
304    if(!temp){
305      COUT(2) << "Server: could not add client" << std::endl;
306      return false;
307    }
308    /*if(temp==ClientInformation::getBegin()) { //not good if you use anything else than insertBack
309      newid=1;
310    }
311    else
312      newid=temp->prev()->getID()+1;*/
313    temp->setID(newid);
314    temp->setPeer(event->peer);
315
316    // inform all the listeners
317    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
318    while(listener){
319      listener->clientConnected(newid);
320      listener++;
321    }
322
323    newid++;
324
325    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
326    return createClient(temp->getID());
327}
328
329  bool Server::createClient(int clientID){
330    ClientInformation *temp = ClientInformation::findClient(clientID);
331    if(!temp){
332      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
333      return false;
334    }
335    COUT(4) << "Con.Man: creating client id: " << temp->getID() << std::endl;
336    connection->syncClassid(temp->getID());
337    temp->setSynched(true);
338    COUT(3) << "sending welcome" << std::endl;
339    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
340    w->setClientID(temp->getID());
341    bool b = w->send();
342    assert(b);
343    packet::Gamestate *g = new packet::Gamestate();
344    g->setClientID(temp->getID());
345    b = g->collectData(0);
346    if(!b)
347      return false; //no data for the client
348    b = g->compressData();
349    assert(b);
350    b = g->send();
351    assert(b);
352    return true;
353  }
354
355  bool Server::disconnectClient(ENetEvent *event){
356    COUT(4) << "removing client from list" << std::endl;
357    //return removeClient(head_->findClient(&(peer->address))->getID());
358
359    //boost::recursive_mutex::scoped_lock lock(head_->mutex_);
360    ClientInformation *client = ClientInformation::findClient(&event->peer->address);
361    if(!client)
362      return false;
363    gamestates_->removeClient(client);
364
365// inform all the listeners
366    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
367    while(listener){
368      listener->clientDisconnected(client->getID());
369      listener++;
370    }
371
372    return ClientInformation::removeClient(event->peer);
373  }
374
375  void Server::disconnectClient(int clientID){
376    ClientInformation *client = ClientInformation::findClient(clientID);
377    if(client)
378      disconnectClient(client);
379  }
380  void Server::disconnectClient( ClientInformation *client){
381    connection->disconnectClient(client);
382    gamestates_->removeClient(client);
383  }
384
385  bool Server::chat(const std::string& message){
386      return this->sendChat(message, Host::getPlayerID());
387  }
388
389  bool Server::broadcast(const std::string& message){
390      return this->sendChat(message, CLIENTID_UNKNOWN);
391  }
392
393  bool Server::sendChat(const std::string& message, unsigned int clientID){
394    ClientInformation *temp = ClientInformation::getBegin();
395    packet::Chat *chat;
396    while(temp){
397      chat = new packet::Chat(message, clientID);
398      chat->setClientID(temp->getID());
399      if(!chat->send())
400        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
401      temp = temp->next();
402    }
403//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
404    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
405      it->incomingChat(message, clientID);
406
407    return true;
408  }
409
410}
Note: See TracBrowser for help on using the repository browser.