Each module now includes its own header first. Removed sstream.h and the definition...
[crack-attack.git] / src / Communicator.cxx
blob0854a6b1c21ab2459bd4e7e75241e7b62f928789
1 /*
2 * Communicator.cxx
3 * Daniel Nelson - 8/30/0
5 * Copyright (C) 2000 Daniel Nelson
6 * Copyright (C) 2004 Andrew Sayman
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.
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.
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 * Daniel Nelson - aluminumangel.org
23 * 174 W. 18th Ave.
24 * Columbus, OH 43210
26 * Handles all that socket stuff. We should be more worried about the size of
27 * integers on various systems.
30 #include "Communicator.h"
32 #include <cassert>
33 #include <iostream>
34 #include <sys/types.h>
35 #include <cstring>
37 #ifndef _WIN32
38 # include <sys/socket.h>
39 # include <sys/poll.h>
40 # include <netinet/in.h>
41 # include <netdb.h>
42 # include <arpa/inet.h>
43 #else
44 # include <stdlib.h>
45 # include <winsock2.h>
46 # define sleep(x) Sleep(x)
47 #endif
49 #include "Game.h"
50 #include "Displayer.h"
51 #include "GarbageGenerator.h"
52 #include "GarbageFlavorImage.h"
53 #include "LevelLights.h"
54 #include "MetaState.h"
55 #include "Random.h"
57 using namespace std;
59 ENetHost *Communicator::host;
60 ENetPeer *Communicator::peer;
61 int Communicator::time_step;
62 bool Communicator::comm_link_active;
63 bool Communicator::no_communication;
64 bool Communicator::have_communicated;
65 int Communicator::last_recv_sync;
66 int Communicator::last_own_sync;
67 CommunicationBuffer Communicator::send_buffer;
68 CommunicationBuffer Communicator::recv_buffer;
69 GarbageBuffer Communicator::send_garb_buffer;
70 GarbageBuffer Communicator::recv_garb_buffer;
71 CommunicationBuffer Communicator::work_buffer;
72 bool Communicator::win_ties;
73 char Communicator::opponent_name[GC_PLAYER_NAME_LENGTH];
75 static void print_ip_address( int ip )
77 ip = ntohl(ip);
78 cout << ((ip & 0xFF000000) >> 24) << ".";
79 cout << ((ip & 0x00FF0000) >> 16) << ".";
80 cout << ((ip & 0x0000FF00) >> 8) << ".";
81 cout << (ip & 0x000000FF);
84 void Communicator::startupExchange ( char player_name[GC_PLAYER_NAME_LENGTH] )
86 // exchange names
87 MESSAGE("Exchanging names");
88 commSendRel(player_name, GC_PLAYER_NAME_LENGTH);
89 commGetRel(opponent_name, GC_PLAYER_NAME_LENGTH);
91 // notify if we have a personal garbage flavor image
92 MESSAGE("Exchanging garbage");
93 uint32 flag = GarbageFlavorImage::personalGarbageFlavorImageExists();
94 commSendRel(flag);
96 // and send it out
97 if (flag) {
98 GLubyte *texture = GarbageFlavorImage::loadPersonalGarbageFlavorImage();
99 commSendRel(texture, 4 * DC_GARBAGE_TEX_LENGTH * DC_GARBAGE_TEX_LENGTH
100 * sizeof(GLubyte));
101 #ifndef _WIN32
102 delete [] texture;
103 #else
104 if (texture != null) {
105 delete [] texture;
106 texture = null;
108 #endif
111 // check to see if they have a personal garbage flavor image
112 commGetRel(flag);
114 // and recv it
115 if (flag) {
116 GLubyte texture[4 * DC_GARBAGE_TEX_LENGTH * DC_GARBAGE_TEX_LENGTH];
117 commGetRel(texture, 4 * DC_GARBAGE_TEX_LENGTH * DC_GARBAGE_TEX_LENGTH
118 * sizeof(GLubyte));
119 GarbageFlavorImage::handleNetworkGarbageFlavorImage(texture);
123 void Communicator::initialize ( int mode, int port, char host_name[256],
124 char player_name[GC_PLAYER_NAME_LENGTH] )
126 ENetAddress address;
127 host = NULL;
128 peer = NULL;
129 comm_link_active = false;
131 if (enet_initialize () != 0)
133 cerr << "An error occurred while initializing ENet." << endl;
134 exit(1);
136 else
138 cout << "ENet properly initialized." << endl;
140 atexit (enet_deinitialize);
142 if (port == 0)
143 address.port = CO_DEFAULT_PORT;
144 else
145 address.port = port;
147 switch (mode & (CM_SERVER | CM_CLIENT)) {
148 case CM_SERVER: {
149 address.host = ENET_HOST_ANY;
151 host = enet_host_create(&address, 1, 0, 0);
152 if (NULL == host) {
153 cerr << "An error occured while trying to create the server" << endl;
154 exit(1);
157 cout << "Waiting for connection at port " << address.port << "..." << endl;
158 ENetEvent event;
159 do {
160 if (enet_host_service(host, &event, CO_SERVER_TIME_OUT * 1000) > 0)
162 switch (event.type) {
163 case ENET_EVENT_TYPE_CONNECT: {
164 peer = event.peer;
165 cout << "Accepting connection from ";
166 print_ip_address(peer->address.host);
167 cout << endl;
168 comm_link_active = true;
169 break;
171 case ENET_EVENT_TYPE_RECEIVE: {
172 enet_packet_destroy(event.packet);
173 break;
175 case ENET_EVENT_TYPE_DISCONNECT: {
176 break;
178 case ENET_EVENT_TYPE_NONE: {
179 break;
183 } while((mode & CM_NO_TIME_OUT) && !comm_link_active);
185 if (!comm_link_active)
187 cerr << "Time out." << endl;
188 exit(1);
191 // check version id
193 commSendRel(CO_VERSION, strlen(CO_VERSION) + 1);
195 // server sends extremeness level
196 enet_uint8 X_level = ((mode & CM_X) ? 1 : 0);
197 commSendRel(&X_level, sizeof(X_level));
199 // for simplicity, server wins ties - but don't tell anyone; it's the only
200 // available symmetry breaking term
201 win_ties = true;
203 cout << "Connection made by ";
204 print_ip_address(peer->address.host);
205 cout << endl;
206 break;
209 case CM_CLIENT: {
210 host = enet_host_create(NULL, 1, 57600, 14400);
211 if(NULL == host) {
212 cerr << "Could not create ENet host." << endl;
213 exit(1);
215 comm_link_active = true;
217 #ifdef DEVELOPMENT
218 cout << "Hostname: " << host_name << endl;
219 #endif
220 if (enet_address_set_host(&address, host_name)!=0) {
221 cerr << "Host '" << host_name << "' not found." << endl;
222 exit(1);
226 peer = enet_host_connect(host, &address, NUM_CHANNELS);
227 if(NULL == peer) {
228 cerr << "No available peers for initiating an ENet connection." << endl;
229 exit(1);
231 /* Wait up to 5 seconds for the connection attempt to succeed. */
232 ENetEvent event;
233 MESSAGE("Waiting five seconds for connection attempt to succeed");
234 if (enet_host_service (host, & event, 5000) > 0 &&
235 event.type == ENET_EVENT_TYPE_CONNECT)
237 cout << "Connection to " << host_name << " succeeded." << endl;
239 else
241 enet_peer_reset (peer);
242 cerr << "Connection to " << host_name << " failed." << endl;
243 exit(1);
246 // check version id
247 char sversion[CO_VERSION_MAX_LENGTH];
248 commGetRel(sversion, CO_VERSION_MAX_LENGTH);
249 if(strncmp(sversion, CO_VERSION, CO_VERSION_MAX_LENGTH)!=0) {
250 cerr << "Connected to incompatible version: " << sversion << endl;
251 exit(1);
254 // server sends extremeness level
255 enet_uint8 X_level;
256 commGetRel(&X_level, sizeof(X_level));
257 if (X_level == 1) MetaState::mode |= CM_X;
259 // for simplicity, client loses ties - but don't tell anyone
260 win_ties = false;
262 cout << "Connection made to " << peer->address.host << ':'
263 << peer->address.port << '.' << endl;
264 break;
267 startupExchange(player_name);
269 time_step = 1;
270 no_communication = false;
271 have_communicated = false;
274 void Communicator::cleanUp ( )
276 if (comm_link_active) {
277 enet_deinitialize();
278 comm_link_active = false;
282 void Communicator::exchangeRandomSeed ( )
284 uint32 seed;
286 // server sends the the random seed
287 MESSAGE("Sending seed");
288 if (MetaState::mode & CM_SERVER) {
289 seed = Random::generateSeed();
290 commSendRel(seed);
291 } else
292 commGetRel(seed);
294 Random::seed(seed);
297 void Communicator::gameStart ( )
299 time_step = 1;
300 no_communication = false;
301 have_communicated = false;
302 last_recv_sync = 0;
303 last_own_sync = 0;
304 send_garb_buffer.count = 0;
305 recv_garb_buffer.count = 0;
306 send_buffer.level_lights = 0;
307 recv_buffer.level_lights = 0;
308 send_buffer.game_state = 0;
310 exchangeRandomSeed();
313 void Communicator::gameFinish ( )
315 time_step = 1;
316 no_communication = false;
317 have_communicated = false;
320 void Communicator::handlePlayRecv ( )
322 ENetEvent event;
323 int code;
325 while((code = enet_host_service(host, &event, 0)) > 0) switch(event.type)
327 case ENET_EVENT_TYPE_RECEIVE:
328 MESSAGE("Receiving message for channel " << (int)event.channelID << "|"
329 << " len " << event.packet->dataLength << "|");
330 switch(event.channelID) {
331 case CO_CHANNEL_GARBAGE:
332 handlePlayRecvGarbage(event);
333 break;
334 case CO_CHANNEL_STATUS:
335 MESSAGE("Receiving status");
336 handlePlayRecvStatus (event);
337 break;
338 case CO_CHANNEL_BOARD:
339 MESSAGE("Receiving board data (unimplemented)");
340 handlePlayRecvBoard (event);
341 case CO_CHANNEL_REL:
342 MESSAGE("Channel reliable used! Should not be during play!");
343 MESSAGE("Testing: Ignore leftovers?");
344 break;
345 default:
346 cerr << "Networking message handled incorrectly:" << endl;
347 cerr << "Invalid channel id " << (int)event.channelID << endl;
348 exit(1);
350 enet_packet_destroy(event.packet);
351 break;
352 case ENET_EVENT_TYPE_DISCONNECT:
353 cerr << "Disconnected from host." << endl;
354 exit(1);
355 break;
356 case ENET_EVENT_TYPE_CONNECT:
357 cerr << "Received an additional connection..." << endl;
358 exit(1);
359 break;
360 case ENET_EVENT_TYPE_NONE:
361 MESSAGE("Nothing to see here... move along.");
362 break;
364 if (code < 0) {
365 cerr << "Unknown networking failure." << endl;
366 exit(1);
370 void Communicator::handlePlayRecvBoard ( ENetEvent event )
372 cerr << "Currently not handling board events." << endl;
373 exit(1);
376 void Communicator::handlePlayRecvGarbage ( ENetEvent event )
378 fillGarbageBuffer(event.packet);
380 // add new garbage to the queue
381 GarbageGenerator::addToQueue(recv_garb_buffer);
384 void Communicator::handlePlayRecvStatus ( ENetEvent event )
386 fillCommunicationBuffer(event.packet);
388 MESSAGE("Receiving other player status");
390 // handle the recved level light data
391 LevelLights::handleRecvBuffer();
393 // if we have been remotely paused
394 if (recv_buffer.game_state & GS_PAUSED)
395 Game::netSignalPause();
397 // if we have been remotely unpaused
398 else if (recv_buffer.game_state & GS_UNPAUSED)
399 Game::netSignalUnpause();
401 // store the current sync state
402 last_recv_sync = recv_buffer.sync;
403 last_own_sync = time_step - Game::time_step;
405 // if we're out of sync with our opponent, enter a sync pause
406 if (last_recv_sync > last_own_sync && (Game::state & GS_NORMAL))
407 Game::syncPause(last_recv_sync - last_own_sync);
409 // if our opponent thinks he may have lost
410 if (recv_buffer.game_state & GS_MAY_HAVE_LOST) {
411 MESSAGE("Opponent may have lost");
412 // if it's a concession
413 if (recv_buffer.game_state & GS_CONCESSION) {
414 MetaState::state |= MS_CONCESSION;
415 MESSAGE("by concession");
418 // if we also think we may have lost
419 if (Game::state & GS_MAY_HAVE_LOST) {
420 MESSAGE("We also think we may have lost");
421 // pick a winner
422 if (recv_buffer.loss_time_stamp < send_buffer.loss_time_stamp
423 || (recv_buffer.loss_time_stamp == send_buffer.loss_time_stamp
424 && win_ties)) {
425 MESSAGE("Chose myself as the winner");
426 Game::won();
429 // otherwise, we win
430 } else {
431 MESSAGE("I win");
432 Game::won();
435 // if the opponent has confirmed our loss
436 } else if (recv_buffer.game_state & GS_MUST_CONFIRM_LOSS) {
437 MESSAGE("Opponent has confirmed my loss");
438 Game::lossConfirmation();
439 no_communication = true;
440 return;
443 // if we were waiting a cycle for our opponent to recv his loss confirmation
444 if (Game::state & GS_CONFIRMATION_HOLD) {
445 Game::state &= ~GS_CONFIRMATION_HOLD;
446 no_communication = true;
447 Game::state |= GS_END_PLAY;
448 return;
452 void Communicator::timeStepPlay_inline_split_ ( )
454 // recv
455 if(have_communicated) {
456 handlePlayRecv();
457 } else
458 have_communicated = true;
459 if(no_communication) return;
461 // send
462 handlePlaySend();
465 void Communicator::handlePlaySend ( )
467 // send
468 // ready the level light data for sending
469 LevelLights::readySendBuffer();
471 // ready the game state information for sending - pause and unpause
472 // information have already been set
473 if (Game::state & GS_MAY_HAVE_LOST) {
474 MESSAGE("May have lost");
475 send_buffer.game_state |= GS_MAY_HAVE_LOST;
476 if (MetaState::state & MS_CONCESSION) {
477 MESSAGE("Conceeding");
478 send_buffer.game_state |= GS_CONCESSION;
480 } else if (Game::state & GS_MUST_CONFIRM_LOSS) {
481 MESSAGE("Must confirm loss");
482 send_buffer.game_state |= GS_MUST_CONFIRM_LOSS;
483 Game::state &= ~GS_MUST_CONFIRM_LOSS;
484 Game::state |= GS_CONFIRMATION_HOLD;
487 // ready the sync for sending
488 if (!(Game::state & GS_PAUSED))
489 send_buffer.sync = (uint32) (time_step - Game::time_step);
491 #ifdef DEVELOPMENT
492 send_buffer.print();
493 #endif
495 if(send_garb_buffer.count > 0)
496 commSendGarbage();
497 commSendStatus();
499 // reset send buffer
500 send_garb_buffer.count = 0;
501 send_buffer.level_lights = 0;
502 send_buffer.game_state = 0;
505 void Communicator::timeStepMeta_inline_split_ ( )
507 uint32 state;
508 bool state_available;
510 if(have_communicated) {
511 state_available = commGetRelNoBlock(state);
512 if (state_available) {
513 // handle recved state data
514 if (state & MS_REMOTE_KEY_WAIT)
515 MetaState::remoteKeyPressed();
516 else if (state & MS_READY_GAME_START)
517 MetaState::remoteReady();
519 } else
520 have_communicated = true;
522 if (MetaState::state & MS_GAME_PLAY) return;
524 // ready state data for sending
525 state = MetaState::state & (MS_REMOTE_KEY_WAIT | MS_READY_GAME_START);
527 commSendRel(state);
530 void Communicator::barrier ( )
532 uint32 c = CO_TEST_INT;
534 commSendRel(c);
535 commGetRel(c);
537 assert(c == CO_TEST_INT);