Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

chat works again now. some doxygen. small change according to playerid in Host

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