Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/presentationFS15merge/src/libraries/network/Server.cc @ 10612

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

merged branch multiplayerFS15

  • Property svn:eol-style set to native
File size: 13.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
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!=0; 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    std::vector<packet::Gamestate*>::iterator it;
235    for( it = gamestates.begin(); it != gamestates.end(); ++it )
236    {
237      (*it)->send(static_cast<Host*>(this));
238    }
239    return true;
240  }
241
242
243  bool Server::sendObjectDeletes()
244  {
245//     ClientInformation *temp = ClientInformation::getBegin();
246//     if( temp == NULL )
247      //no client connected
248    if( this->clientIDs_.size()==0 )
249      return true;
250    packet::DeleteObjects *del = new packet::DeleteObjects();
251    if(!del->fetchIDs())
252    {
253      delete del;
254      return true;  //everything ok (no deletes this tick)
255    }
256//     orxout(verbose, context::network) << "sending DeleteObjects" << endl;
257//     while(temp != NULL){
258//       if( !(temp->getSynched()) )
259//       {
260//         orxout(verbose_more, context::network) << "Server: not sending gamestate" << endl;
261//         temp=temp->next();
262//         continue;
263//       }
264//       int cid = temp->getID(); //get client id
265//       packet::DeleteObjects *cd = new packet::DeleteObjects(*del);
266//       assert(cd);
267    del->setPeerID(NETWORK_PEER_ID_BROADCAST);
268    if ( !del->send( static_cast<Host*>(this) ) )
269      orxout(internal_warning, context::network) << "Server: could not broadcast deleteObjects packet" << endl;
270//       temp=temp->next();
271      // gs gets automatically deleted by enet callback
272//     }
273//     delete del;
274    return true;
275  }
276
277
278  void Server::addPeer(uint32_t peerID)
279  {
280//     static unsigned int newid=1;
281//
282//     orxout(internal_info, context::network) << "Server: adding client" << endl;
283//     ClientInformation *temp = ClientInformation::insertBack(new ClientInformation);
284//     if(!temp)
285//     {
286//       orxout(internal_warning, context::network) << "Server: could not add client" << endl;
287//     }
288//     temp->setID(newid);
289//     temp->setPeer(event->peer);
290
291    // inform all the listeners
292    this->clientIDs_.push_back(peerID);
293    WANDiscoverable::updateClientNumber(this->clientIDs_.size());
294    LANDiscoverable::updateClientNumber(this->clientIDs_.size());
295
296    ClientConnectionListener::broadcastClientConnected(peerID);
297    GamestateManager::addPeer(peerID);
298
299//     ++newid;
300
301    orxout(internal_info, context::network) << "Server: added client id: " << peerID << endl;
302
303    createClient(peerID);
304}
305
306  void Server::removePeer(uint32_t peerID)
307  {
308    orxout(verbose, context::network) << "removing client from list" << endl;
309//     ClientInformation *client = ClientInformation::findClient(&event->peer->address);
310//     if(!client)
311//       return;
312//     else
313//     {
314  std::vector<uint32_t>::iterator it;
315  for( it=this->clientIDs_.begin(); it!=this->clientIDs_.end(); ++it )
316  {
317    if( *it == peerID )
318    {
319      this->clientIDs_.erase(it);
320      break;
321    }
322  }
323  WANDiscoverable::updateClientNumber(this->clientIDs_.size());
324  LANDiscoverable::updateClientNumber(this->clientIDs_.size());
325
326  ClientConnectionListener::broadcastClientDisconnected(peerID);
327  GamestateManager::removePeer(peerID);
328      //ServerConnection::disconnectClient( client );
329      //ClientConnectionListener::broadcastClientDisconnected( client->getID() ); //this is done in ClientInformation now
330//       delete client;
331//     }
332  }
333
334  void Server::processPacket(packet::Packet* packet)
335  {
336    if( packet->isReliable() )
337    {
338      if( this->getLastReceivedGamestateID(packet->getPeerID()) >= packet->getRequiredGamestateID() )
339        packet->process(static_cast<Host*>(this));
340      else
341        this->packetQueue_.push_back(packet);
342    }
343    else
344      packet->process(static_cast<Host*>(this));
345  }
346
347
348  bool Server::createClient(int clientID)
349  {
350//     ClientInformation *temp = ClientInformation::findClient(clientID);
351//     if(!temp)
352//     {
353//       orxout(internal_error, context::network) << "Server. could not create client with id: " << clientID << endl;
354//       return false;
355//     }
356//     orxout(verbose, context::network) << "Con.Man: creating client id: " << temp->getID() << endl;
357
358    // synchronise class ids
359    syncClassid(clientID);
360
361    // now synchronise functionIDs
362    packet::FunctionIDs *fIDs = new packet::FunctionIDs();
363    fIDs->setPeerID(clientID);
364    bool b = fIDs->send( static_cast<Host*>(this) );
365    assert(b);
366
367//     temp->setSynched(true);
368    GamestateManager::setSynched(clientID);
369
370    orxout(verbose, context::network) << "sending welcome" << endl;
371    packet::Welcome *w = new packet::Welcome(clientID);
372    w->setPeerID(clientID);
373    b = w->send( static_cast<Host*>(this) );
374    assert(b);
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    std::vector<uint32_t>::iterator it;
437    for( it=this->clientIDs_.begin(); it!=this->clientIDs_.end(); ++it )
438      if( *it == targetID )
439        return true;
440
441    return false;
442  }
443
444  void Server::syncClassid(unsigned int clientID)
445  {
446    int failures=0;
447    packet::ClassID *classid = new packet::ClassID();
448    classid->setPeerID(clientID);
449    while(!classid->send( static_cast<Host*>(this) ) && failures < 10){
450      failures++;
451    }
452    assert(failures<10);
453    orxout(verbose, context::network) << "syncClassid:\tall synchClassID packets have been sent" << endl;
454  }
455
456}
Note: See TracBrowser for help on using the repository browser.