Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/netp5/src/network/Server.cc @ 3211

Last change on this file since 3211 was 3209, checked in by rgrieder, 15 years ago

Cleanup in network plus a few dependency reductions (no enet-function inlines, using enum PacketFlag instead of the enet version)

  • Property svn:eol-style set to native
File size: 11.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
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 <enet/enet.h>
44#include <cassert>
45#include <string>
46
47#include "util/Debug.h"
48#include "core/Clock.h"
49#include "core/ObjectList.h"
50#include "packet/Chat.h"
51#include "packet/ClassID.h"
52#include "packet/DeleteObjects.h"
53#include "packet/FunctionIDs.h"
54#include "packet/Gamestate.h"
55#include "packet/Welcome.h"
56#include "ChatListener.h"
57#include "ClientInformation.h"
58#include "FunctionCallManager.h"
59#include "GamestateManager.h"
60
61namespace orxonox
62{
63  const unsigned int MAX_FAILURES = 20;
64
65  /**
66  * Constructor for default values (bindaddress is set to ENET_HOST_ANY
67  *
68  */
69  Server::Server() {
70    timeSinceLastUpdate_=0;
71    gamestates_ = new GamestateManager();
72  }
73
74  Server::Server(int port){
75    this->setPort( port );
76    timeSinceLastUpdate_=0;
77    gamestates_ = new GamestateManager();
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, const std::string& bindAddress) {
86    this->setPort( port );
87    this->setBindAddress( bindAddress );
88    timeSinceLastUpdate_=0;
89    gamestates_ = new GamestateManager();
90  }
91
92  /**
93  * @brief Destructor
94  */
95  Server::~Server(){
96    if(gamestates_)
97      delete gamestates_;
98  }
99
100  /**
101  * This function opens the server by creating the listener thread
102  */
103  void Server::open() {
104    COUT(4) << "opening server" << endl;
105    this->openListener();
106    return;
107  }
108
109  /**
110  * This function closes the server
111  */
112  void Server::close() {
113    COUT(4) << "closing server" << endl;
114    this->disconnectClients();
115    this->closeListener();
116    return;
117  }
118
119  bool Server::processChat(const std::string& message, unsigned int playerID){
120    ClientInformation *temp = ClientInformation::getBegin();
121    packet::Chat *chat;
122    while(temp){
123      chat = new packet::Chat(message, playerID);
124      chat->setClientID(temp->getID());
125      if(!chat->send())
126        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
127      temp = temp->next();
128    }
129//    COUT(1) << "Player " << playerID << ": " << message << std::endl;
130    return true;
131  }
132
133
134  /**
135  * Run this function once every tick
136  * calls processQueue and updateGamestate
137  * @param time time since last tick
138  */
139  void Server::update(const Clock& time) {
140    Connection::processQueue();
141    gamestates_->processGamestates();
142    //this steers our network frequency
143    timeSinceLastUpdate_+=time.getDeltaTime();
144    if(timeSinceLastUpdate_>=NETWORK_PERIOD)
145    {
146      timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
147      updateGamestate();
148      FunctionCallManager::sendCalls();
149    }
150    sendPackets(); // flush the enet queue
151  }
152
153  bool Server::queuePacket(ENetPacket *packet, int clientID){
154    return ServerConnection::addPacket(packet, clientID);
155  }
156 
157  /**
158   * @brief: returns ping time to client in milliseconds
159   */
160  unsigned int Server::getPing(unsigned int clientID){
161    assert(ClientInformation::findClient(clientID));
162    return ClientInformation::findClient(clientID)->getRTT();
163  }
164
165  /**
166   * @brief: return packet loss ratio to client (scales from 0 to 1)
167   */
168  double Server::getPacketLoss(unsigned int clientID){
169    assert(ClientInformation::findClient(clientID));
170    return ClientInformation::findClient(clientID)->getPacketLoss();
171  }
172
173  /**
174  * takes a new snapshot of the gamestate and sends it to the clients
175  */
176  void Server::updateGamestate() {
177//     if( ClientInformation::getBegin()==NULL )
178      //no client connected
179//       return;
180    gamestates_->update();
181    COUT(5) << "Server: one gamestate update complete, goig to sendGameState" << std::endl;
182    //std::cout << "updated gamestate, sending it" << std::endl;
183    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
184    sendGameState();
185    sendObjectDeletes();
186    COUT(5) << "Server: one sendGameState turn complete, repeat in next tick" << std::endl;
187    //std::cout << "sent gamestate" << std::endl;
188  }
189
190  bool Server::processPacket( ENetPacket *packet, ENetPeer *peer ){
191    packet::Packet *p = packet::Packet::createPacket(packet, peer);
192    return p->process();
193  }
194
195  /**
196  * sends the gamestate
197  */
198  bool Server::sendGameState() {
199    COUT(5) << "Server: starting function sendGameState" << std::endl;
200    ClientInformation *temp = ClientInformation::getBegin();
201    bool added=false;
202    while(temp != NULL){
203      if( !(temp->getSynched()) ){
204        COUT(5) << "Server: not sending gamestate" << std::endl;
205        temp=temp->next();
206        if(!temp)
207          break;
208        //think this works without continue
209        continue;
210      }
211      COUT(4) << "client id: " << temp->getID() << " RTT: " << temp->getRTT() << " loss: " << temp->getPacketLoss() << std::endl;
212      COUT(5) << "Server: doing gamestate gamestate preparation" << std::endl;
213      int gid = temp->getGamestateID(); //get gamestate id
214      int cid = temp->getID(); //get client id
215      COUT(5) << "Server: got acked (gamestate) ID from clientlist: " << gid << std::endl;
216      packet::Gamestate *gs = gamestates_->popGameState(cid);
217      if(gs==NULL){
218        COUT(2) << "Server: could not generate gamestate (NULL from compress)" << std::endl;
219        temp = temp->next();
220        continue;
221      }
222      //std::cout << "adding gamestate" << std::endl;
223      gs->setClientID(cid);
224      if ( !gs->send() ){
225        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
226        temp->addFailure();
227      }else
228        temp->resetFailures();
229      added=true;
230      temp=temp->next();
231      // gs gets automatically deleted by enet callback
232    }
233    return true;
234  }
235
236  bool Server::sendObjectDeletes(){
237    ClientInformation *temp = ClientInformation::getBegin();
238    if( temp == NULL )
239      //no client connected
240      return true;
241    packet::DeleteObjects *del = new packet::DeleteObjects();
242    if(!del->fetchIDs())
243      return true;  //everything ok (no deletes this tick)
244//     COUT(3) << "sending DeleteObjects" << std::endl;
245    while(temp != NULL){
246      if( !(temp->getSynched()) ){
247        COUT(5) << "Server: not sending gamestate" << std::endl;
248        temp=temp->next();
249        continue;
250      }
251      int cid = temp->getID(); //get client id
252      packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
253      assert(cd);
254      cd->setClientID(cid);
255      if ( !cd->send() )
256        COUT(3) << "Server: packet with client id (cid): " << cid << " not sended: " << temp->getFailures() << std::endl;
257      temp=temp->next();
258      // gs gets automatically deleted by enet callback
259    }
260    delete del;
261    return true;
262  }
263
264
265  void Server::addClient(ENetEvent *event){
266    static unsigned int newid=1;
267
268    COUT(2) << "Server: adding client" << std::endl;
269    ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
270    if(!temp){
271      COUT(2) << "Server: could not add client" << std::endl;
272    }
273    temp->setID(newid);
274    temp->setPeer(event->peer);
275
276    // inform all the listeners
277    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
278    while(listener){
279      listener->clientConnected(newid);
280      listener++;
281    }
282
283    ++newid;
284
285    COUT(3) << "Server: added client id: " << temp->getID() << std::endl;
286    createClient(temp->getID());
287}
288
289  bool Server::createClient(int clientID){
290    ClientInformation *temp = ClientInformation::findClient(clientID);
291    if(!temp){
292      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
293      return false;
294    }
295    COUT(5) << "Con.Man: creating client id: " << temp->getID() << std::endl;
296   
297    // synchronise class ids
298    syncClassid(temp->getID());
299   
300    // now synchronise functionIDs
301    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
302    fIDs->setClientID(clientID);
303    bool b = fIDs->send();
304    assert(b);
305   
306    temp->setSynched(true);
307    COUT(4) << "sending welcome" << std::endl;
308    packet::Welcome *w = new packet::Welcome(temp->getID(), temp->getShipID());
309    w->setClientID(temp->getID());
310    b = w->send();
311    assert(b);
312    packet::Gamestate *g = new packet::Gamestate();
313    g->setClientID(temp->getID());
314    b = g->collectData(0,0x1);
315    if(!b)
316      return false; //no data for the client
317    b = g->compressData();
318    assert(b);
319    b = g->send();
320    assert(b);
321    return true;
322  }
323 
324  void Server::disconnectClient( ClientInformation *client ){
325    ServerConnection::disconnectClient( client );
326    gamestates_->removeClient(client);
327// inform all the listeners
328    ObjectList<ClientConnectionListener>::iterator listener = ObjectList<ClientConnectionListener>::begin();
329    while(listener){
330      listener->clientDisconnected(client->getID());
331      ++listener;
332    }
333    delete client; //remove client from list
334  }
335
336  bool Server::chat(const std::string& message){
337      return this->sendChat(message, Host::getPlayerID());
338  }
339
340  bool Server::broadcast(const std::string& message){
341      return this->sendChat(message, CLIENTID_UNKNOWN);
342  }
343
344  bool Server::sendChat(const std::string& message, unsigned int clientID){
345    ClientInformation *temp = ClientInformation::getBegin();
346    packet::Chat *chat;
347    while(temp){
348      chat = new packet::Chat(message, clientID);
349      chat->setClientID(temp->getID());
350      if(!chat->send())
351        COUT(3) << "could not send Chat message to client ID: " << temp->getID() << std::endl;
352      temp = temp->next();
353    }
354//    COUT(1) << "Player " << Host::getPlayerID() << ": " << message << std::endl;
355    for (ObjectList<ChatListener>::iterator it = ObjectList<ChatListener>::begin(); it != ObjectList<ChatListener>::end(); ++it)
356      it->incomingChat(message, clientID);
357
358    return true;
359  }
360
361  void Server::syncClassid(unsigned int clientID) {
362    int failures=0;
363    packet::ClassID *classid = new packet::ClassID();
364    classid->setClientID(clientID);
365    while(!classid->send() && failures < 10){
366      failures++;
367    }
368    assert(failures<10);
369    COUT(4) << "syncClassid:\tall synchClassID packets have been sent" << std::endl;
370  }
371
372}
Note: See TracBrowser for help on using the repository browser.