Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/libraries/network/Server.cc @ 11822

Last change on this file since 11822 was 11103, checked in by landauf, 9 years ago

fixed warnings (release build).
fixed error in GravityBombField

  • Property svn:eol-style set to native
File size: 13.2 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#define WIN32_LEAN_AND_MEAN
44#include <enet/enet.h>
45#include <cassert>
46#include <string>
47
48#include "util/Clock.h"
49#include "util/Output.h"
50#include "core/command/Executor.h"
51#include "packet/Chat.h"
52#include "packet/ClassID.h"
53#include "packet/DeleteObjects.h"
54#include "packet/FunctionIDs.h"
55#include "packet/Gamestate.h"
56#include "packet/Welcome.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  {
71    this->timeSinceLastUpdate_=0;
72  }
73
74  Server::Server(int port)
75  {
76    this->setPort( port );
77    this->timeSinceLastUpdate_=0;
78  }
79/*
80  Server::Server(int port, const std::string name)
81  {
82    this->setPort( port );
83    this->timeSinceLastUpdate_=0;
84    this->serverName_=name;
85  }*/
86  /**
87  * Constructor
88  * @param port Port to listen on
89  * @param bindAddress Address to listen on
90  */
91  Server::Server(int port, const std::string& bindAddress)
92  {
93    this->setPort( port );
94    this->setBindAddress( bindAddress );
95    this->timeSinceLastUpdate_=0;
96  }
97
98  /**
99  * @brief Destructor
100  */
101  Server::~Server()
102  {
103  }
104
105  /**
106  * This function opens the server by creating the listener thread
107  */
108  void Server::open()
109  {
110    Host::setActive(true);
111    orxout(verbose, context::network) << "opening server" << endl;
112    this->openListener();
113
114    /* make discoverable on LAN */
115    LANDiscoverable::setActivity(true);
116    LANDiscoverable::updateClientNumber(0);
117
118    /* make discoverable on WAN */
119    WANDiscoverable::setActivity(true);
120    WANDiscoverable::updateClientNumber(0);
121
122    /* done */
123    return;
124  }
125
126  /**
127  * This function closes the server
128  */
129  void Server::close()
130  {
131    Host::setActive(false);
132    orxout(verbose, context::network) << "closing server" << endl;
133    this->disconnectClients();
134    this->closeListener();
135
136    /* tell master server we're closing */
137    orxout(internal_info, context::network) << "disconnecting." << endl;
138    WANDiscoverable::setActivity(false);
139    orxout(internal_info, context::network) << "disconnecting done" << endl;
140
141    LANDiscoverable::setActivity(false);
142    return;
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::update(const Clock& time)
151  {
152    // receive incoming packets
153    Connection::processQueue();
154
155    // receive and process incoming discovery packets
156    LANDiscoverable::update();
157
158    if ( GamestateManager::hasPeers() )
159    {
160      // process incoming gamestates
161      GamestateManager::processGamestates();
162      FunctionCallManager::processBufferedFunctionCalls();
163
164      // send function calls to clients
165      FunctionCallManager::sendCalls( static_cast<Host*>(this) );
166
167      //this steers our network frequency
168      timeSinceLastUpdate_+=time.getDeltaTime();
169      if(timeSinceLastUpdate_>=NETWORK_PERIOD)
170      {
171        timeSinceLastUpdate_ -= static_cast<unsigned int>( timeSinceLastUpdate_ / NETWORK_PERIOD ) * NETWORK_PERIOD;
172        updateGamestate();
173      }
174//       sendPackets(); // flush the enet queue
175    }
176  }
177
178  void Server::queuePacket(ENetPacket *packet, int clientID, uint8_t channelID)
179  {
180    ServerConnection::addPacket(packet, clientID, channelID);
181  }
182
183  /**
184   * @brief: returns ping time to client in milliseconds
185   */
186  unsigned int Server::getRTT(unsigned int clientID)
187  {
188//     assert(ClientInformation::findClient(clientID));
189//     return ClientInformation::findClient(clientID)->getRTT();
190    // TODO: reimplement
191    return 0;
192  }
193
194  void Server::printRTT()
195  {
196//     for( ClientInformation* temp=ClientInformation::getBegin(); temp!=nullptr; temp=temp->next() )
197//       orxout(message) << "Round trip time to client with ID: " << temp->getID() << " is " << temp->getRTT() << " ms" << endl;
198  }
199
200  /**
201   * @brief: return packet loss ratio to client (scales from 0 to 1)
202   */
203  float Server::getPacketLoss(unsigned int clientID)
204  {
205//     assert(ClientInformation::findClient(clientID));
206//     return ClientInformation::findClient(clientID)->getPacketLoss();
207    return 0.;
208  }
209
210  /**
211  * takes a new snapshot of the gamestate and sends it to the clients
212  */
213  void Server::updateGamestate()
214  {
215    if( this->clientIDs_.size()==0 )
216      //no client connected
217      return;
218    GamestateManager::update();
219//     orxout(verbose_more, context::network) << "Server: one gamestate update complete, goig to sendGameState" << endl;
220    //orxout(verbose_more, context::network) << "updated gamestate, sending it" << endl;
221    //if(clients->getGamestateID()!=GAMESTATEID_INITIAL)
222    sendGameStates();
223    sendObjectDeletes();
224//     orxout(verbose_more, context::network) << "Server: one sendGameState turn complete, repeat in next tick" << endl;
225    //orxout(verbose_more, context::network) << "sent gamestate" << endl;
226  }
227
228  /**
229  * sends the current gamestate to all peers
230  */
231  bool Server::sendGameStates()
232  {
233    std::vector<packet::Gamestate*> gamestates = GamestateManager::getGamestates();
234    for( packet::Gamestate* gamestate : gamestates )
235    {
236      gamestate->send(static_cast<Host*>(this));
237    }
238    return true;
239  }
240
241
242  bool Server::sendObjectDeletes()
243  {
244//     ClientInformation *temp = ClientInformation::getBegin();
245//     if( temp == nullptr )
246      //no client connected
247    if( this->clientIDs_.size()==0 )
248      return true;
249    packet::DeleteObjects *del = new packet::DeleteObjects();
250    if(!del->fetchIDs())
251    {
252      delete del;
253      return true;  //everything ok (no deletes this tick)
254    }
255//     orxout(verbose, context::network) << "sending DeleteObjects" << endl;
256//     while(temp != nullptr){
257//       if( !(temp->getSynched()) )
258//       {
259//         orxout(verbose_more, context::network) << "Server: not sending gamestate" << endl;
260//         temp=temp->next();
261//         continue;
262//       }
263//       int cid = temp->getID(); //get client id
264//       packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
265//       assert(cd);
266    del->setPeerID(NETWORK_PEER_ID_BROADCAST);
267    if ( !del->send( static_cast<Host*>(this) ) )
268      orxout(internal_warning, context::network) << "Server: could not broadcast deleteObjects packet" << endl;
269//       temp=temp->next();
270      // gs gets automatically deleted by enet callback
271//     }
272//     delete del;
273    return true;
274  }
275
276
277  void Server::addPeer(uint32_t peerID)
278  {
279//     static unsigned int newid=1;
280//
281//     orxout(internal_info, context::network) << "Server: adding client" << endl;
282//     ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
283//     if(!temp)
284//     {
285//       orxout(internal_warning, context::network) << "Server: could not add client" << endl;
286//     }
287//     temp->setID(newid);
288//     temp->setPeer(event->peer);
289
290    // inform all the listeners
291    this->clientIDs_.push_back(peerID);
292    WANDiscoverable::updateClientNumber(this->clientIDs_.size());
293    LANDiscoverable::updateClientNumber(this->clientIDs_.size());
294
295    ClientConnectionListener::broadcastClientConnected(peerID);
296    GamestateManager::addPeer(peerID);
297
298//     ++newid;
299
300    orxout(internal_info, context::network) << "Server: added client id: " << peerID << endl;
301
302    createClient(peerID);
303}
304
305  void Server::removePeer(uint32_t peerID)
306  {
307    orxout(verbose, context::network) << "removing client from list" << endl;
308//     ClientInformation *client = ClientInformation::findClient(&event->peer->address);
309//     if(!client)
310//       return;
311//     else
312//     {
313  std::vector<uint32_t>::iterator it;
314  for( it=this->clientIDs_.begin(); it!=this->clientIDs_.end(); ++it )
315  {
316    if( *it == peerID )
317    {
318      this->clientIDs_.erase(it);
319      break;
320    }
321  }
322  WANDiscoverable::updateClientNumber(this->clientIDs_.size());
323  LANDiscoverable::updateClientNumber(this->clientIDs_.size());
324
325  ClientConnectionListener::broadcastClientDisconnected(peerID);
326  GamestateManager::removePeer(peerID);
327      //ServerConnection::disconnectClient( client );
328      //ClientConnectionListener::broadcastClientDisconnected( client->getID() ); //this is done in ClientInformation now
329//       delete client;
330//     }
331  }
332
333  void Server::processPacket(packet::Packet* packet)
334  {
335    if( packet->isReliable() )
336    {
337      if( this->getLastReceivedGamestateID(packet->getPeerID()) >= packet->getRequiredGamestateID() )
338        packet->process(static_cast<Host*>(this));
339      else
340        this->packetQueue_.push_back(packet);
341    }
342    else
343      packet->process(static_cast<Host*>(this));
344  }
345
346
347  bool Server::createClient(int clientID)
348  {
349//     ClientInformation *temp = ClientInformation::findClient(clientID);
350//     if(!temp)
351//     {
352//       orxout(internal_error, context::network) << "Server. could not create client with id: " << clientID << endl;
353//       return false;
354//     }
355//     orxout(verbose, context::network) << "Con.Man: creating client id: " << temp->getID() << endl;
356
357    // synchronise class ids
358    syncClassid(clientID);
359
360    // now synchronise functionIDs
361    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
362    fIDs->setPeerID(clientID);
363    bool b = fIDs->send( static_cast<Host*>(this) );
364    assert(b);
365
366//     temp->setSynched(true);
367    GamestateManager::setSynched(clientID);
368
369    orxout(verbose, context::network) << "sending welcome" << endl;
370    packet::Welcome *w = new packet::Welcome(clientID);
371    w->setPeerID(clientID);
372    b = w->send( static_cast<Host*>(this) );
373    assert(b);
374    (void)b; // avoid compiler warning
375//     packet::Gamestate *g = new packet::Gamestate();
376//     g->setPeerID(clientID);
377//     b = g->collectData(0,packet::GAMESTATE_MODE_SERVER);
378//     assert(b);
379//     if(!b)
380//       return false; //no data for the client
381// //     b = g->compressData();
382// //     assert(b);
383//     b = g->send( static_cast<Host*>(this) );
384//     assert(b);
385    return true;
386  }
387
388  void Server::disconnectClient( uint32_t clientID )
389  {
390    ServerConnection::disconnectClient( clientID );
391    GamestateManager::removePeer( clientID );
392    // inform all the listeners
393    // ClientConnectionListener::broadcastClientDisconnected(client->getID()); // this is done in ClientInformation now
394  }
395
396  /**
397   * @brief Sends a chat message to the given target ID.
398   * @param message message to be sent
399   * @param sourceID the ID of the sender
400   * @param targetID the ID of the receiver
401   */
402  void Server::doSendChat(const std::string& message, unsigned int sourceID, unsigned int targetID)
403  {
404    // check if the target exists. just ignore the message otherwise
405    if (!this->isValidTarget(targetID)) // TODO: remove this if an invalid clientIDs don't trigger assertions anymore
406      return;
407
408    // send the message to the target
409    packet::Chat* packet = new packet::Chat(message, sourceID, targetID);
410    packet->setPeerID(targetID);
411    packet->send( static_cast<Host*>(this) );
412
413    // if the target is (or includes) this host as well, call the parent function which passes the message to the listeners
414    if (targetID == NETWORK_PEER_ID_BROADCAST || targetID == Host::getPlayerID())
415      Host::doReceiveChat(message, sourceID, targetID);
416  }
417
418  /**
419   * @brief Gets called if a packet::Chat packet is received. Forwards the packet to the target
420   * and calls the parent function if necessary.
421   */
422  void Server::doReceiveChat(const std::string& message, unsigned int sourceID, unsigned int targetID)
423  {
424      this->doSendChat(message, sourceID, targetID);
425  }
426
427  /**
428   * @brief Returns true if the target ID is in the list of clients (or if it
429   * corresponds to the broadcast or the server ID).
430   */
431  bool Server::isValidTarget(unsigned int targetID)
432  {
433    if (targetID == NETWORK_PEER_ID_BROADCAST || targetID == NETWORK_PEER_ID_SERVER)
434      return true;
435
436    for( uint32_t id : this->clientIDs_ )
437      if( id == targetID )
438        return true;
439
440    return false;
441  }
442
443  void Server::syncClassid(unsigned int clientID)
444  {
445    int failures=0;
446    packet::ClassID *classid = new packet::ClassID();
447    classid->setPeerID(clientID);
448    while(!classid->send( static_cast<Host*>(this) ) && failures < 10){
449      failures++;
450    }
451    assert(failures<10);
452    orxout(verbose, context::network) << "syncClassid:\tall synchClassID packets have been sent" << endl;
453  }
454
455}
Note: See TracBrowser for help on using the repository browser.