Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/merge/src/network/ConnectionManager.cc @ 1361

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

reverted some changes from previous version

File size: 14.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, (C) 2007
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29//
30// C++ Interface: ConnectionManager
31//
32// Description: The Class ConnectionManager manages the servers conenctions to the clients.
33// each connection is provided by a new process. communication between master process and
34// connection processes is provided by ...
35//
36//
37// Author:  Oliver Scheuss
38//
39
40#include <iostream>
41// boost.thread library for multithreading support
42#include <boost/bind.hpp>
43
44#include "core/CoreIncludes.h"
45#include "core/BaseObject.h"
46#include "util/Math.h"
47#include "objects/SpaceShip.h"
48#include "ClientInformation.h"
49#include "ConnectionManager.h"
50#include "Synchronisable.h"
51
52namespace std
53{
54  bool operator< (ENetAddress a, ENetAddress b) {
55    if(a.host <= b.host)
56      return true;
57    else
58      return false;
59  }
60}
61
62namespace network
63{
64  //boost::thread_group network_threads;
65 
66  ConnectionManager::ConnectionManager():receiverThread_(0){}
67 
68  ConnectionManager::ConnectionManager(ClientInformation *head) : receiverThread_(0) {
69    quit=false;
70    bindAddress.host = ENET_HOST_ANY;
71    bindAddress.port = NETWORK_PORT;
72    head_ = head;
73  }
74
75  ConnectionManager::ConnectionManager(int port, std::string address, ClientInformation *head) :receiverThread_(0) {
76    quit=false;
77    enet_address_set_host (& bindAddress, address.c_str());
78    bindAddress.port = NETWORK_PORT;
79    head_ = head;
80  }
81
82  ConnectionManager::ConnectionManager(int port, const char *address, ClientInformation *head) : receiverThread_(0) {
83    quit=false;
84    enet_address_set_host (& bindAddress, address);
85    bindAddress.port = NETWORK_PORT;
86    head_ = head;
87  }
88
89  ENetPacket *ConnectionManager::getPacket(ENetAddress &address) {
90    if(!buffer.isEmpty())
91      return buffer.pop(address);
92    else
93      return NULL;
94  }
95/**
96This function only pops the first element in PacketBuffer (first in first out)
97used by processQueue in Server.cc
98*/
99  ENetPacket *ConnectionManager::getPacket(int &clientID) {
100    ENetAddress address;
101    ENetPacket *packet=getPacket(address);
102    ClientInformation *temp =head_->findClient(&address);
103    if(!temp)
104      return NULL;
105    clientID=temp->getID();
106    return packet;
107  }
108
109  bool ConnectionManager::queueEmpty() {
110    return buffer.isEmpty();
111  }
112
113  void ConnectionManager::createListener() {
114    receiverThread_ = new boost::thread(boost::bind(&ConnectionManager::receiverThread, this));
115    //network_threads.create_thread(boost::bind(boost::mem_fn(&ConnectionManager::receiverThread), this));
116         //boost::thread thr(boost::bind(boost::mem_fn(&ConnectionManager::receiverThread), this));
117    return;
118  }
119
120  bool ConnectionManager::quitListener() {
121    quit=true;
122    //network_threads.join_all();
123    receiverThread_->join();
124    return true;
125  }
126
127  bool ConnectionManager::addPacket(ENetPacket *packet, ENetPeer *peer) {
128    ClientInformation *temp = head_->findClient(&(peer->address));
129    if(!temp)
130      return false;
131    if(enet_peer_send(peer, (enet_uint8)temp->getID() , packet)!=0)
132      return false;
133    return true;
134  }
135
136  bool ConnectionManager::addPacket(ENetPacket *packet, int clientID) {
137    ClientInformation *temp = head_->findClient(clientID);
138    if(!temp)
139      return false;
140    if(enet_peer_send(temp->getPeer(), (enet_uint8)clientID, packet)!=0)
141      return false;
142    return true;
143  }
144
145  bool ConnectionManager::addPacketAll(ENetPacket *packet) {
146    for(ClientInformation *i=head_->next(); i!=0; i=i->next()){
147      if(enet_peer_send(i->getPeer(), (enet_uint8)i->getID(), packet)!=0)
148        return false;
149    }
150    return true;
151  }
152
153  bool ConnectionManager::sendPackets(ENetEvent *event) {
154    if(server==NULL)
155      return false;
156    if(enet_host_service(server, event, NETWORK_SEND_WAIT)>=0)
157      return true;
158    else
159      return false;
160  }
161
162  bool ConnectionManager::sendPackets() {
163    ENetEvent event;
164    if(server==NULL)
165      return false;
166    if(enet_host_service(server, &event, NETWORK_SEND_WAIT)>=0)
167      return true;
168    else
169      return false;
170  }
171
172  void ConnectionManager::receiverThread() {
173    // what about some error-handling here ?
174    enet_initialize();
175    atexit(enet_deinitialize);
176    ENetEvent *event = new ENetEvent;
177    server = enet_host_create(&bindAddress, NETWORK_MAX_CONNECTIONS, 0, 0);
178    if(server==NULL){
179      // add some error handling here ==========================
180      quit=true;
181      return;
182    }
183
184    while(!quit){
185      if(enet_host_service(server, event, NETWORK_WAIT_TIMEOUT)<0){
186        // we should never reach this point
187        quit=true;
188        // add some error handling here ========================
189      }
190      switch(event->type){
191        // log handling ================
192        case ENET_EVENT_TYPE_CONNECT:
193          addClient(event);
194          //this is a workaround to ensure thread safety
195          /*if(!addFakeConnectRequest(&event))
196            COUT(3) << "Problem pushing fakeconnectRequest to queue" << std::endl;*/
197          COUT(5) << "Con.Man: connection event has occured" << std::endl;
198          break;
199        case ENET_EVENT_TYPE_RECEIVE:
200          //std::cout << "received data" << std::endl;
201          COUT(5) << "Con.Man: receive event has occured" << std::endl;
202          // only add, if client has connected yet and not been disconnected
203          if(head_->findClient(&event->peer->address))
204            processData(event);
205          else
206            COUT(3) << "received a packet from a client we don't know" << std::endl;
207          break;
208        case ENET_EVENT_TYPE_DISCONNECT:
209          clientDisconnect(event->peer);
210          break;
211        case ENET_EVENT_TYPE_NONE:
212          break;
213      }
214//       usleep(100);
215      receiverThread_->yield(); //TODO: find apropriate
216    }
217    disconnectClients();
218    // if we're finishied, destroy server
219    enet_host_destroy(server);
220  }
221 
222  //### added some bugfixes here, but we cannot test them because
223  //### the server crashes everytime because of some gamestates
224  //### (trying to resolve that now)
225  void ConnectionManager::disconnectClients() {
226    ENetEvent event;
227    ClientInformation *temp = head_->next();
228    while(temp!=0){
229      enet_peer_disconnect(temp->getPeer(), 0);
230      temp = temp->next();
231    }
232    //bugfix: might be the reason why server crashes when clients disconnects
233    //temp = temp->next();
234    temp = head_->next();
235    while( temp!=0 && enet_host_service(server, &event, NETWORK_WAIT_TIMEOUT) > 0){
236      switch (event.type)
237      {
238      case ENET_EVENT_TYPE_NONE: break;
239      case ENET_EVENT_TYPE_CONNECT: break;
240      case ENET_EVENT_TYPE_RECEIVE:
241        enet_packet_destroy(event.packet);
242        break;
243      case ENET_EVENT_TYPE_DISCONNECT:
244        COUT(4) << "disconnecting all clients" << std::endl;
245        if(head_->findClient(&(event.peer->address)))
246          delete head_->findClient(&(event.peer->address));
247        //maybe needs bugfix: might also be a reason for the server to crash
248        temp = temp->next();
249        break;
250      }
251    }
252    return;
253  }
254
255  bool ConnectionManager::processData(ENetEvent *event) {
256    // just add packet to the buffer
257    // this can be extended with some preprocessing
258    return buffer.push(event);
259  }
260
261  bool ConnectionManager::clientDisconnect(ENetPeer *peer) {
262    COUT(4) << "removing client from list" << std::endl;
263    return removeClient(head_->findClient(&(peer->address))->getID());
264  }
265/**
266This function adds a client that connects to the clientlist of the server
267NOTE: if you change this, don't forget to change the test function
268addClientTest in diffTest.cc since addClient is not good for testing because of syncClassid
269*/
270  bool ConnectionManager::addClient(ENetEvent *event) {
271    ClientInformation *temp = head_->insertBack(new ClientInformation);
272    if(!temp){
273      COUT(2) << "Conn.Man. could not add client" << std::endl;
274      return false;
275    }
276    if(temp->prev()->getHead()) { //not good if you use anything else than insertBack
277      temp->prev()->setID(0); //bugfix: not necessary but usefull
278      temp->setID(1);
279    }
280    else
281      temp->setID(temp->prev()->getID()+1);
282    temp->setPeer(event->peer);
283    COUT(3) << "Con.Man: added client id: " << temp->getID() << std::endl;
284    return true;
285  }
286
287  int ConnectionManager::getClientID(ENetPeer peer) {
288    return getClientID(peer.address);
289  }
290
291  int ConnectionManager::getClientID(ENetAddress address) {
292    return head_->findClient(&address)->getID();
293  }
294
295  ENetPeer *ConnectionManager::getClientPeer(int clientID) {
296    return head_->findClient(clientID)->getPeer();
297  }
298
299  void ConnectionManager::syncClassid(int clientID) {
300    unsigned int network_id=0, failures=0;
301    std::string classname;
302    orxonox::Identifier *id;
303    std::map<std::string, orxonox::Identifier*>::const_iterator it = orxonox::Factory::getFactoryBegin();
304    while(it != orxonox::Factory::getFactoryEnd()){
305      id = (*it).second;
306      if(id == NULL)
307        continue;
308      classname = id->getName();
309      network_id = id->getNetworkID();
310      if(network_id==0)
311        COUT(3) << "we got a null class id: " << id->getName() << std::endl;
312      COUT(4) << "Con.Man:syncClassid:\tnetwork_id: " << network_id << ", classname: " << classname << std::endl;
313
314      while(!addPacket(packet_gen.clid( (int)network_id, classname ), clientID) && failures < 10){
315        failures++;
316      }
317      ++it;
318    }
319    sendPackets();
320    COUT(4) << "syncClassid:\tall synchClassID packets have been sent" << std::endl;
321  }
322
323  bool ConnectionManager::createClient(int clientID){
324    ClientInformation *temp = head_->findClient(clientID);
325    if(!temp){
326      COUT(2) << "Conn.Man. could not create client with id: " << clientID << std::endl;
327      return false;
328    }
329    COUT(4) << "Con.Man: creating client id: " << temp->getID() << std::endl;
330    syncClassid(temp->getID());
331    COUT(4) << "creating spaceship for clientid: " << temp->getID() << std::endl;
332    // TODO: this is only a hack, untill we have a possibility to define default player-join actions
333    if(!createShip(temp))
334      COUT(2) << "Con.Man. could not create ship for clientid: " << clientID << std::endl;
335    else
336      COUT(3) << "created spaceship" << std::endl;
337    temp->setSynched(true);
338    COUT(3) << "sending welcome" << std::endl;
339    sendWelcome(temp->getID(), temp->getShipID(), true);
340    return true;
341  }
342 
343  bool ConnectionManager::removeClient(int clientID){
344    orxonox::Iterator<orxonox::SpaceShip> it = orxonox::ObjectList<orxonox::SpaceShip>::start();
345    ClientInformation *client = head_->findClient(clientID);
346    if(!client)
347      return false;
348    while(it){
349      if(it->objectID!=client->getShipID()){
350        ++it;
351        continue;
352      }
353      orxonox::Iterator<orxonox::SpaceShip> temp=it;
354      ++it;
355      delete  *temp;
356      return head_->removeClient(clientID);
357    }
358    return false;
359  }
360 
361  bool ConnectionManager::createShip(ClientInformation *client){
362    if(!client)
363      return false;
364    orxonox::Identifier* id = ID("SpaceShip");
365    if(!id){
366      COUT(4) << "We could not create the SpaceShip for client: " << client->getID() << std::endl;
367      return false;
368    }
369    orxonox::SpaceShip *no = dynamic_cast<orxonox::SpaceShip *>(id->fabricate());
370    no->setPosition(orxonox::Vector3(0,80,0));
371    no->setScale(10);
372    no->setYawPitchRoll(orxonox::Degree(-90),orxonox::Degree(-90),orxonox::Degree(0));
373    no->setMesh("assff.mesh");
374    no->setMaxSpeed(500);
375    no->setMaxSideAndBackSpeed(50);
376    no->setMaxRotation(1.0);
377    no->setTransAcc(200);
378    no->setRotAcc(3.0);
379    no->setTransDamp(75);
380    no->setRotDamp(1.0);
381    no->setCamera("cam_"+client->getID());
382    no->classID = id->getNetworkID();
383    no->create();
384   
385    client->setShipID(no->objectID);
386    return true;
387  }
388 
389  bool ConnectionManager::removeShip(ClientInformation *client){
390    int id=client->getShipID();
391    orxonox::Iterator<orxonox::SpaceShip> it;
392    for(it = orxonox::ObjectList<orxonox::SpaceShip>::start(); it; ++it){
393      if(it->objectID!=id)
394        continue;
395      delete *it;
396    }
397    return true;
398  }
399 
400  bool ConnectionManager::sendWelcome(int clientID, int shipID, bool allowed){
401    if(addPacket(packet_gen.generateWelcome(clientID, shipID, allowed),clientID)){
402      sendPackets();
403      return true;
404    }else
405      return false;
406  }
407 
408  void ConnectionManager::disconnectClient(ClientInformation *client){
409    enet_peer_disconnect(client->getPeer(), 0);
410    removeShip(client);
411  }
412 
413  bool ConnectionManager::addFakeConnectRequest(ENetEvent *ev){
414    ENetEvent event;
415    event.peer=ev->peer;
416    event.packet = packet_gen.generateConnectRequest();
417    return buffer.push(&event);
418  }
419 
420 
421//   int ConnectionManager::getNumberOfClients() {
422//     
423//     return clientsShip.size();
424//   }
425 
426  /*void ConnectionManager::addClientsObjectID( int clientID, int objectID ) {
427  COUT(4) << "ship of client: " << clientID << ": " << objectID << " mapped" << std::endl;
428  clientsShip.insert( std::make_pair( clientID, objectID ) );
429}
430
431  int ConnectionManager::getClientsShipID( int clientID ) {
432  return clientsShip[clientID];
433}
434
435  int ConnectionManager::getObjectsClientID( int objectID ) {
436  std::map<int, int>::iterator iter;
437  for( iter = clientsShip.begin(); iter != clientsShip.end(); iter++ ) {
438  if( iter->second == objectID ) return iter->first;
439}
440  return -99;
441}
442
443  void ConnectionManager::deleteClientIDReg( int clientID ) {
444  clientsShip.erase( clientID );
445}
446
447  void ConnectionManager::deleteObjectIDReg( int objectID ) {
448  std::map<int, int>::iterator iter = clientsShip.begin();
449  for( iter = clientsShip.begin(); iter != clientsShip.end(); iter++ ) {
450  if( iter->second == objectID ) break;
451}
452  clientsShip.erase( iter->first );
453}*/
454}
Note: See TracBrowser for help on using the repository browser.