Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/network/Server.cc @ 1747

Last change on this file since 1747 was 1747, checked in by landauf, 17 years ago

merged core3 back to trunk

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