3 * Daniel Nelson - 8/30/0
5 * Copyright (C) 2000 Daniel Nelson
6 * Copyright (C) 2004 Andrew Sayman
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
26 * Handles all that socket stuff. We should be more worried about the size of
27 * integers on various systems.
30 #include "Communicator.h"
34 #include <sys/types.h>
38 # include <sys/socket.h>
39 # include <sys/poll.h>
40 # include <netinet/in.h>
42 # include <arpa/inet.h>
45 # include <winsock2.h>
46 # define sleep(x) Sleep(x)
50 #include "Displayer.h"
51 #include "GarbageGenerator.h"
52 #include "GarbageFlavorImage.h"
53 #include "LevelLights.h"
54 #include "MetaState.h"
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
)
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
] )
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();
98 GLubyte
*texture
= GarbageFlavorImage::loadPersonalGarbageFlavorImage();
99 commSendRel(texture
, 4 * DC_GARBAGE_TEX_LENGTH
* DC_GARBAGE_TEX_LENGTH
104 if (texture
!= null
) {
111 // check to see if they have a personal garbage flavor image
116 GLubyte texture
[4 * DC_GARBAGE_TEX_LENGTH
* DC_GARBAGE_TEX_LENGTH
];
117 commGetRel(texture
, 4 * DC_GARBAGE_TEX_LENGTH
* DC_GARBAGE_TEX_LENGTH
119 GarbageFlavorImage::handleNetworkGarbageFlavorImage(texture
);
123 void Communicator::initialize ( int mode
, int port
, char host_name
[256],
124 char player_name
[GC_PLAYER_NAME_LENGTH
] )
129 comm_link_active
= false;
131 if (enet_initialize () != 0)
133 cerr
<< "An error occurred while initializing ENet." << endl
;
138 cout
<< "ENet properly initialized." << endl
;
140 atexit (enet_deinitialize
);
143 address
.port
= CO_DEFAULT_PORT
;
147 switch (mode
& (CM_SERVER
| CM_CLIENT
)) {
149 address
.host
= ENET_HOST_ANY
;
151 host
= enet_host_create(&address
, 1, 0, 0);
153 cerr
<< "An error occured while trying to create the server" << endl
;
157 cout
<< "Waiting for connection at port " << address
.port
<< "..." << endl
;
160 if (enet_host_service(host
, &event
, CO_SERVER_TIME_OUT
* 1000) > 0)
162 switch (event
.type
) {
163 case ENET_EVENT_TYPE_CONNECT
: {
165 cout
<< "Accepting connection from ";
166 print_ip_address(peer
->address
.host
);
168 comm_link_active
= true;
171 case ENET_EVENT_TYPE_RECEIVE
: {
172 enet_packet_destroy(event
.packet
);
175 case ENET_EVENT_TYPE_DISCONNECT
: {
178 case ENET_EVENT_TYPE_NONE
: {
183 } while((mode
& CM_NO_TIME_OUT
) && !comm_link_active
);
185 if (!comm_link_active
)
187 cerr
<< "Time out." << endl
;
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
203 cout
<< "Connection made by ";
204 print_ip_address(peer
->address
.host
);
210 host
= enet_host_create(NULL
, 1, 57600, 14400);
212 cerr
<< "Could not create ENet host." << endl
;
215 comm_link_active
= true;
218 cout
<< "Hostname: " << host_name
<< endl
;
220 if (enet_address_set_host(&address
, host_name
)!=0) {
221 cerr
<< "Host '" << host_name
<< "' not found." << endl
;
226 peer
= enet_host_connect(host
, &address
, NUM_CHANNELS
);
228 cerr
<< "No available peers for initiating an ENet connection." << endl
;
231 /* Wait up to 5 seconds for the connection attempt to succeed. */
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
;
241 enet_peer_reset (peer
);
242 cerr
<< "Connection to " << host_name
<< " failed." << endl
;
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
;
254 // server sends extremeness 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
262 cout
<< "Connection made to " << peer
->address
.host
<< ':'
263 << peer
->address
.port
<< '.' << endl
;
267 startupExchange(player_name
);
270 no_communication
= false;
271 have_communicated
= false;
274 void Communicator::cleanUp ( )
276 if (comm_link_active
) {
278 comm_link_active
= false;
282 void Communicator::exchangeRandomSeed ( )
286 // server sends the the random seed
287 MESSAGE("Sending seed");
288 if (MetaState::mode
& CM_SERVER
) {
289 seed
= Random::generateSeed();
297 void Communicator::gameStart ( )
300 no_communication
= false;
301 have_communicated
= false;
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 ( )
316 no_communication
= false;
317 have_communicated
= false;
320 void Communicator::handlePlayRecv ( )
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
);
334 case CO_CHANNEL_STATUS
:
335 MESSAGE("Receiving status");
336 handlePlayRecvStatus (event
);
338 case CO_CHANNEL_BOARD
:
339 MESSAGE("Receiving board data (unimplemented)");
340 handlePlayRecvBoard (event
);
342 MESSAGE("Channel reliable used! Should not be during play!");
343 MESSAGE("Testing: Ignore leftovers?");
346 cerr
<< "Networking message handled incorrectly:" << endl
;
347 cerr
<< "Invalid channel id " << (int)event
.channelID
<< endl
;
350 enet_packet_destroy(event
.packet
);
352 case ENET_EVENT_TYPE_DISCONNECT
:
353 cerr
<< "Disconnected from host." << endl
;
356 case ENET_EVENT_TYPE_CONNECT
:
357 cerr
<< "Received an additional connection..." << endl
;
360 case ENET_EVENT_TYPE_NONE
:
361 MESSAGE("Nothing to see here... move along.");
365 cerr
<< "Unknown networking failure." << endl
;
370 void Communicator::handlePlayRecvBoard ( ENetEvent event
)
372 cerr
<< "Currently not handling board events." << endl
;
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");
422 if (recv_buffer
.loss_time_stamp
< send_buffer
.loss_time_stamp
423 || (recv_buffer
.loss_time_stamp
== send_buffer
.loss_time_stamp
425 MESSAGE("Chose myself as the winner");
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;
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
;
452 void Communicator::timeStepPlay_inline_split_ ( )
455 if(have_communicated
) {
458 have_communicated
= true;
459 if(no_communication
) return;
465 void Communicator::handlePlaySend ( )
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
);
495 if(send_garb_buffer
.count
> 0)
500 send_garb_buffer
.count
= 0;
501 send_buffer
.level_lights
= 0;
502 send_buffer
.game_state
= 0;
505 void Communicator::timeStepMeta_inline_split_ ( )
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();
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
);
530 void Communicator::barrier ( )
532 uint32 c
= CO_TEST_INT
;
537 assert(c
== CO_TEST_INT
);