1 // ============================================================================
2 // Rocks'n'Diamonds - McDuffin Strikes Back!
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
7 // http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
10 // ============================================================================
15 #include "libgame/libgame.h"
26 struct NetworkClientPlayerInfo
29 char name[MAX_PLAYER_NAME_LEN + 1];
30 struct NetworkClientPlayerInfo *next;
33 static struct NetworkClientPlayerInfo first_player =
42 static TCPsocket sfd; /* TCP server socket */
43 static UDPsocket udp; /* UDP server socket */
44 static SDLNet_SocketSet rfds; /* socket set */
46 static byte realbuffer[512];
47 static byte readbuffer[MAX_BUFFER_SIZE], writbuffer[MAX_BUFFER_SIZE];
48 static byte *buffer = realbuffer + 4;
49 static int nread = 0, nwrite = 0;
50 static boolean stop_network_game = FALSE;
52 static void DrawNetworkTextExt(char *message, int font_nr, boolean initialize)
54 static int xpos = 0, ypos = 0;
55 static int max_line_width = 0;
56 int font_width = getFontWidth(font_nr);
57 int font_height = getFontHeight(font_nr);
63 if (game_status == GAME_MODE_LOADING)
65 max_line_width = WIN_XSIZE;
67 xpos = (max_line_width - getTextWidth(message, font_nr)) / 2;
70 DrawText(xpos, ypos, message, font_nr);
77 max_line_width = SXSIZE;
79 DrawTextSCentered(ypos_1, font_nr, message);
81 /* calculate offset to x position caused by rounding */
82 int max_chars_per_line = max_line_width / font_width;
83 int xoffset = (max_line_width - max_chars_per_line * font_width) / 2;
89 Error(ERR_DEBUG, "========== %s ==========", message);
93 int max_chars_per_line = max_line_width / font_width;
94 int max_lines_per_text = 10;
95 int num_lines_spacing = (font_nr == FC_YELLOW ? 1 : 3);
96 int num_lines_printed = DrawTextBuffer(xpos, ypos, message, font_nr,
97 max_chars_per_line, -1,
98 max_lines_per_text, 0, -1,
101 ypos += (num_lines_printed + num_lines_spacing) * font_height;
103 Error(ERR_DEBUG, "%s", message);
109 static void DrawNetworkText(char *message)
111 DrawNetworkTextExt(message, FC_YELLOW, FALSE);
114 static void DrawNetworkText_Success(char *message)
116 DrawNetworkTextExt(message, FC_GREEN, FALSE);
119 static void DrawNetworkText_Failed(char *message)
121 DrawNetworkTextExt(message, FC_RED, FALSE);
124 static void DrawNetworkText_Title(char *message)
126 DrawNetworkTextExt(message, FC_GREEN, TRUE);
129 static void SendBufferToServer(int size)
131 if (!network.enabled)
134 realbuffer[0] = realbuffer[1] = realbuffer[2] = 0;
135 realbuffer[3] = (byte)size;
138 if (nwrite + 4 + size >= MAX_BUFFER_SIZE)
139 Error(ERR_EXIT, "internal error: network send buffer overflow");
141 memcpy(writbuffer + nwrite, realbuffer, 4 + size);
144 /* directly send the buffer to the network server */
145 SDLNet_TCP_Send(sfd, writbuffer, nwrite);
149 struct NetworkClientPlayerInfo *getNetworkPlayer(int player_nr)
151 struct NetworkClientPlayerInfo *player = NULL;
153 for (player = &first_player; player; player = player->next)
154 if (player->nr == player_nr)
157 if (player == NULL) /* should not happen */
158 Error(ERR_EXIT, "protocol error: reference to non-existing player %d",
164 char *getNetworkPlayerName(int player_nr)
166 struct NetworkClientPlayerInfo *player;
169 return("the network game server");
170 else if (player_nr == first_player.nr)
173 for (player = &first_player; player; player = player->next)
174 if (player->nr == player_nr && strlen(player->name) > 0)
175 return(player->name);
177 return(EMPTY_PLAYER_NAME);
180 static void StartNetworkServer(int port)
185 #if defined(TARGET_SDL2)
186 server_thread = SDL_CreateThread(NetworkServerThread,
187 "NetworkServerThread", &p);
189 server_thread = SDL_CreateThread(NetworkServerThread, &p);
191 network_server = TRUE;
194 boolean ConnectToServer(char *hostname, int port)
200 DrawNetworkText_Title("Initializing Network");
203 port = DEFAULT_SERVER_PORT;
205 if (hostname == NULL)
207 // if no hostname given, try to auto-detect network server in local network
208 // by doing a UDP broadcast on the network server port and wait for answer
210 SDLNet_SocketSet udp_socket_set = SDLNet_AllocSocketSet(1);
212 Error(ERR_EXIT, "SDLNet_AllocSocketSet() failed: %s"), SDLNet_GetError();
214 udp = SDLNet_UDP_Open(0);
216 Error(ERR_EXIT, "SDLNet_UDP_Open() failed: %s", SDLNet_GetError());
218 if (SDLNet_UDP_AddSocket(udp_socket_set, udp) == -1)
219 Error(ERR_EXIT_NETWORK_SERVER, "SDLNet_TCP_AddSocket() failed: %s"),
222 char *data_ptr = "network server UDB broadcast";
223 int data_len = strlen(data_ptr) + 1;
224 IPaddress ip_address;
226 SDLNet_Write32(0xffffffff, &ip_address.host); /* 255.255.255.255 */
227 SDLNet_Write16(port, &ip_address.port);
239 SDLNet_UDP_Send(udp, -1, &packet);
241 DrawNetworkText("Looking for local network server ...");
243 /* wait for any local network server to answer UDP broadcast */
244 for (i = 0; i < 5; i++)
246 if (SDLNet_CheckSockets(udp_socket_set, 0) == 1)
248 int num_packets = SDLNet_UDP_Recv(udp, &packet);
250 if (num_packets == 1)
252 DrawNetworkText_Success("Network server found!");
254 server_host = SDLNet_Read32(&packet.address.host);
258 DrawNetworkText_Failed("No answer from network server!");
265 Delay_WithScreenUpdates(100);
269 if (server_host == 0)
270 DrawNetworkText_Failed("No network server found!");
273 rfds = SDLNet_AllocSocketSet(1);
277 SDLNet_ResolveHost(&ip, hostname, port);
279 if (ip.host == INADDR_NONE)
280 Error(ERR_EXIT, "cannot locate host '%s'", hostname);
282 server_host = SDLNet_Read32(&ip.host);
284 DrawNetworkText("Connecting to remote host ...");
288 // if no hostname was given and no network server was auto-detected in the
289 // local network, try to connect to a network server at the local host
290 if (server_host == 0)
291 server_host = 0x7f000001; /* 127.0.0.1 */
293 SDLNet_Write32(server_host, &ip.host);
294 SDLNet_Write16(port, &ip.port);
296 DrawNetworkText("Connecting to local host ...");
299 Error(ERR_DEBUG, "trying to connect to network server at %d.%d.%d.%d ...",
300 (server_host >> 24) & 0xff,
301 (server_host >> 16) & 0xff,
302 (server_host >> 8) & 0xff,
303 (server_host >> 0) & 0xff);
305 sfd = SDLNet_TCP_Open(&ip);
309 SDLNet_TCP_AddSocket(rfds, sfd);
311 DrawNetworkText_Success("Successfully connected!");
317 DrawNetworkText_Failed("Failed to connect to network server!");
319 printf("SDLNet_TCP_Open(): %s\n", SDLNet_GetError());
322 if (hostname) /* connect to specified server failed */
325 DrawNetworkText("Starting new local network server ...");
327 StartNetworkServer(port);
329 /* wait for server to start up and try connecting several times */
330 for (i = 0; i < 30; i++)
332 if ((sfd = SDLNet_TCP_Open(&ip))) /* connected */
334 DrawNetworkText_Success("Successfully connected!");
336 SDLNet_TCP_AddSocket(rfds, sfd);
340 Delay_WithScreenUpdates(100);
343 DrawNetworkText_Failed("Failed to connect to network server!");
345 /* when reaching this point, connect to newly started server has failed */
349 void SendToServer_PlayerName(char *player_name)
351 int len_player_name = strlen(player_name);
353 buffer[1] = OP_PLAYER_NAME;
354 memcpy(&buffer[2], player_name, len_player_name);
355 SendBufferToServer(2 + len_player_name);
356 Error(ERR_NETWORK_CLIENT, "you set your player name to \"%s\"", player_name);
359 void SendToServer_ProtocolVersion()
361 buffer[1] = OP_PROTOCOL_VERSION;
362 buffer[2] = PROTOCOL_VERSION_1;
363 buffer[3] = PROTOCOL_VERSION_2;
364 buffer[4] = PROTOCOL_VERSION_3;
366 SendBufferToServer(5);
369 void SendToServer_NrWanted(int nr_wanted)
371 buffer[1] = OP_NUMBER_WANTED;
372 buffer[2] = nr_wanted;
374 SendBufferToServer(3);
377 void SendToServer_StartPlaying()
379 unsigned int new_random_seed = InitRND(level.random_seed);
381 int dummy = 0; /* !!! HAS NO MEANING ANYMORE !!! */
382 /* the name of the level must be enough */
384 buffer[1] = OP_START_PLAYING;
385 buffer[2] = (byte)(level_nr >> 8);
386 buffer[3] = (byte)(level_nr & 0xff);
387 buffer[4] = (byte)(dummy >> 8);
388 buffer[5] = (byte)(dummy & 0xff);
390 buffer[6] = (unsigned char)((new_random_seed >> 24) & 0xff);
391 buffer[7] = (unsigned char)((new_random_seed >> 16) & 0xff);
392 buffer[8] = (unsigned char)((new_random_seed >> 8) & 0xff);
393 buffer[9] = (unsigned char)((new_random_seed >> 0) & 0xff);
395 strcpy((char *)&buffer[10], leveldir_current->identifier);
397 SendBufferToServer(10 + strlen(leveldir_current->identifier) + 1);
400 void SendToServer_PausePlaying()
402 buffer[1] = OP_PAUSE_PLAYING;
404 SendBufferToServer(2);
407 void SendToServer_ContinuePlaying()
409 buffer[1] = OP_CONTINUE_PLAYING;
411 SendBufferToServer(2);
414 void SendToServer_StopPlaying(int cause_for_stopping)
416 buffer[1] = OP_STOP_PLAYING;
417 buffer[2] = cause_for_stopping;
419 SendBufferToServer(3);
422 void SendToServer_MovePlayer(byte player_action)
424 buffer[1] = OP_MOVE_PLAYER;
425 buffer[2] = player_action;
427 SendBufferToServer(3);
430 static void Handle_OP_BAD_PROTOCOL_VERSION()
432 Error(ERR_WARN, "protocol version mismatch");
433 Error(ERR_EXIT, "server expects %d.%d.x instead of %d.%d.%d",
434 buffer[2], buffer[3],
435 PROTOCOL_VERSION_1, PROTOCOL_VERSION_2, PROTOCOL_VERSION_3);
438 static void Handle_OP_YOUR_NUMBER()
440 int new_client_nr = buffer[2];
441 int new_index_nr = new_client_nr - 1;
442 struct PlayerInfo *old_local_player = local_player;
443 struct PlayerInfo *new_local_player = &stored_player[new_index_nr];
445 printf("OP_YOUR_NUMBER: %d\n", buffer[0]);
446 first_player.nr = new_client_nr;
448 if (old_local_player != new_local_player)
450 /* set relevant player settings and change to new player */
452 local_player = new_local_player;
454 old_local_player->connected_locally = FALSE;
455 new_local_player->connected_locally = TRUE;
457 old_local_player->connected_network = FALSE;
458 new_local_player->connected_network = TRUE;
461 if (first_player.nr > MAX_PLAYERS)
462 Error(ERR_EXIT, "sorry, more than %d players not allowed", MAX_PLAYERS);
464 Error(ERR_NETWORK_CLIENT, "you get client # %d", new_client_nr);
466 stored_player[new_index_nr].connected_network = TRUE;
469 static void Handle_OP_NUMBER_WANTED()
471 int client_nr_wanted = buffer[2];
472 int old_client_nr = buffer[0];
473 int new_client_nr = buffer[3];
474 int old_index_nr = old_client_nr - 1;
475 int new_index_nr = new_client_nr - 1;
476 int index_nr_wanted = client_nr_wanted - 1;
477 struct PlayerInfo *old_player = &stored_player[old_index_nr];
478 struct PlayerInfo *new_player = &stored_player[new_index_nr];
480 printf("OP_NUMBER_WANTED: %d\n", buffer[0]);
482 if (new_client_nr == client_nr_wanted) /* switching succeeded */
484 struct NetworkClientPlayerInfo *player;
486 if (old_client_nr != client_nr_wanted) /* client's nr has changed */
487 Error(ERR_NETWORK_CLIENT, "client %d switches to # %d",
488 old_client_nr, new_client_nr);
489 else if (old_client_nr == first_player.nr) /* local player keeps his nr */
490 Error(ERR_NETWORK_CLIENT, "keeping client # %d", new_client_nr);
492 if (old_client_nr != new_client_nr)
494 /* set relevant player settings and change to new player */
496 old_player->connected_network = FALSE;
497 new_player->connected_network = TRUE;
500 player = getNetworkPlayer(old_client_nr);
501 player->nr = new_client_nr;
503 if (old_player == local_player) /* local player switched */
505 local_player = new_player;
507 old_player->connected_locally = FALSE;
508 new_player->connected_locally = TRUE;
511 else if (old_client_nr == first_player.nr) /* failed -- local player? */
515 sprintf(request, "Sorry! Player %d already exists! You are player %d!",
516 index_nr_wanted + 1, new_index_nr + 1);
518 Request(request, REQ_CONFIRM);
520 Error(ERR_NETWORK_CLIENT, "cannot switch -- you keep client # %d",
524 if (game_status == GAME_MODE_MAIN)
525 DrawNetworkPlayers();
528 static void Handle_OP_PLAYER_NAME(unsigned int len)
530 struct NetworkClientPlayerInfo *player;
531 int player_nr = (int)buffer[0];
533 printf("OP_PLAYER_NAME: %d\n", player_nr);
534 player = getNetworkPlayer(player_nr);
536 Error(ERR_NETWORK_CLIENT, "client %d calls itself \"%s\"",
537 buffer[0], &buffer[2]);
538 strncpy(player->name, (char *)&buffer[2], MAX_PLAYER_NAME_LEN);
541 static void Handle_OP_PLAYER_CONNECTED()
543 struct NetworkClientPlayerInfo *player, *last_player = NULL;
544 int new_client_nr = (int)buffer[0];
545 int new_index_nr = new_client_nr - 1;
547 printf("OP_PLAYER_CONNECTED: %d\n", new_client_nr);
548 Error(ERR_NETWORK_CLIENT, "new client %d connected", new_client_nr);
550 for (player = &first_player; player; player = player->next)
552 if (player->nr == new_client_nr)
553 Error(ERR_EXIT, "multiplayer server sent duplicate player id");
555 last_player = player;
558 last_player->next = player =
559 checked_malloc(sizeof(struct NetworkClientPlayerInfo));
560 player->nr = new_client_nr;
561 player->name[0] = '\0';
564 stored_player[new_index_nr].connected_network = TRUE;
567 static void Handle_OP_PLAYER_DISCONNECTED()
569 struct NetworkClientPlayerInfo *player, *player_disconnected;
570 int player_nr = (int)buffer[0];
571 int index_nr = player_nr - 1;
573 printf("OP_PLAYER_DISCONNECTED: %d\n", player_nr);
574 player_disconnected = getNetworkPlayer(player_nr);
575 Error(ERR_NETWORK_CLIENT, "client %d (%s) disconnected",
576 player_nr, getNetworkPlayerName(buffer[0]));
578 for (player = &first_player; player; player = player->next)
579 if (player->next == player_disconnected)
580 player->next = player_disconnected->next;
581 free(player_disconnected);
583 stored_player[index_nr].connected_locally = FALSE;
584 stored_player[index_nr].connected_network = FALSE;
586 if (game_status == GAME_MODE_PLAYING)
590 sprintf(message, "Player %d left network server! Network game stopped!",
593 Request(message, REQ_CONFIRM | REQ_STAY_CLOSED);
595 SetGameStatus(GAME_MODE_MAIN);
599 else if (game_status == GAME_MODE_MAIN)
601 DrawNetworkPlayers();
605 static void Handle_OP_START_PLAYING()
607 LevelDirTree *new_leveldir;
609 unsigned int new_random_seed;
610 char *new_leveldir_identifier;
612 new_level_nr = (buffer[2] << 8) + buffer[3];
614 (buffer[6] << 24) | (buffer[7] << 16) | (buffer[8] << 8) | (buffer[9]);
615 new_leveldir_identifier = (char *)&buffer[10];
617 new_leveldir = getTreeInfoFromIdentifier(leveldir_first,
618 new_leveldir_identifier);
619 if (new_leveldir == NULL)
621 Error(ERR_WARN, "no such level identifier: '%s'", new_leveldir_identifier);
623 stop_network_game = TRUE;
628 printf("OP_START_PLAYING: %d\n", buffer[0]);
629 Error(ERR_NETWORK_CLIENT,
630 "client %d starts game [level %d from level identifier '%s']\n",
631 buffer[0], new_level_nr, new_leveldir->identifier);
633 leveldir_current = new_leveldir;
634 level_nr = new_level_nr;
640 StartGameActions(FALSE, setup.autorecord, new_random_seed);
643 static void Handle_OP_PAUSE_PLAYING()
645 printf("OP_PAUSE_PLAYING: %d\n", buffer[0]);
646 Error(ERR_NETWORK_CLIENT, "client %d pauses game", buffer[0]);
648 if (game_status == GAME_MODE_PLAYING)
651 DrawVideoDisplay(VIDEO_STATE_PAUSE_ON,0);
655 static void Handle_OP_CONTINUE_PLAYING()
657 printf("OP_CONTINUE_PLAYING: %d\n", buffer[0]);
658 Error(ERR_NETWORK_CLIENT, "client %d continues game", buffer[0]);
660 if (game_status == GAME_MODE_PLAYING)
662 tape.pausing = FALSE;
663 DrawVideoDisplay(VIDEO_STATE_PAUSE_OFF,0);
667 static void Handle_OP_STOP_PLAYING()
669 printf("OP_STOP_PLAYING: %d [%d]\n", buffer[0], buffer[2]);
670 Error(ERR_NETWORK_CLIENT, "client %d stops game [%d]", buffer[0], buffer[2]);
672 if (game_status == GAME_MODE_PLAYING)
674 int client_nr = buffer[0];
675 int index_nr = client_nr - 1;
676 struct PlayerInfo *client_player = &stored_player[index_nr];
677 boolean stopped_by_remote_player = (!client_player->connected_locally);
680 sprintf(message, (buffer[2] == NETWORK_STOP_BY_PLAYER ?
681 "Network game stopped by player %d!" :
682 buffer[2] == NETWORK_STOP_BY_ERROR ?
683 "Network game stopped due to internal error!" :
684 "Network game stopped!"), client_nr);
686 if (buffer[2] != NETWORK_STOP_BY_PLAYER || stopped_by_remote_player)
687 Request(message, REQ_CONFIRM | REQ_STAY_CLOSED);
689 SetGameStatus(GAME_MODE_MAIN);
695 static void Handle_OP_MOVE_PLAYER(unsigned int len)
697 int server_frame_counter;
700 if (!network_playing)
703 server_frame_counter =
704 (buffer[2] << 24) | (buffer[3] << 16) | (buffer[4] << 8) | (buffer[5]);
706 if (server_frame_counter != FrameCounter)
708 Error(ERR_INFO, "client and servers frame counters out of sync");
709 Error(ERR_INFO, "frame counter of client is %d", FrameCounter);
710 Error(ERR_INFO, "frame counter of server is %d", server_frame_counter);
711 Error(ERR_INFO, "this should not happen -- please debug");
713 stop_network_game = TRUE;
718 /* copy valid player actions */
719 for (i = 0; i < MAX_PLAYERS; i++)
720 stored_player[i].effective_action =
721 (i < len - 6 ? buffer[6 + i] : 0);
723 network_player_action_received = TRUE;
726 static void HandleNetworkingMessages()
728 unsigned int message_length;
730 stop_network_game = FALSE;
732 while (nread >= 4 && nread >= 4 + readbuffer[3])
734 message_length = readbuffer[3];
735 if (readbuffer[0] || readbuffer[1] || readbuffer[2])
736 Error(ERR_EXIT, "wrong network server line length");
738 memcpy(buffer, &readbuffer[4], message_length);
739 nread -= 4 + message_length;
740 memmove(readbuffer, readbuffer + 4 + message_length, nread);
744 case OP_BAD_PROTOCOL_VERSION:
745 Handle_OP_BAD_PROTOCOL_VERSION();
749 Handle_OP_YOUR_NUMBER();
752 case OP_NUMBER_WANTED:
753 Handle_OP_NUMBER_WANTED();
757 Handle_OP_PLAYER_NAME(message_length);
760 case OP_PLAYER_CONNECTED:
761 Handle_OP_PLAYER_CONNECTED();
764 case OP_PLAYER_DISCONNECTED:
765 Handle_OP_PLAYER_DISCONNECTED();
768 case OP_START_PLAYING:
769 Handle_OP_START_PLAYING();
772 case OP_PAUSE_PLAYING:
773 Handle_OP_PAUSE_PLAYING();
776 case OP_CONTINUE_PLAYING:
777 Handle_OP_CONTINUE_PLAYING();
780 case OP_STOP_PLAYING:
781 Handle_OP_STOP_PLAYING();
785 Handle_OP_MOVE_PLAYER(message_length);
788 case OP_BROADCAST_MESSAGE:
789 printf("OP_BROADCAST_MESSAGE: %d\n", buffer[0]);
790 Error(ERR_NETWORK_CLIENT, "client %d sends message", buffer[0]);
797 /* in case of internal error, stop network game */
798 if (stop_network_game)
799 SendToServer_StopPlaying(NETWORK_STOP_BY_ERROR);
802 static char *HandleNetworkingPackets()
806 /* ---------- check network server for activity ---------- */
808 int num_active_sockets = SDLNet_CheckSockets(rfds, 1);
810 if (num_active_sockets < 0)
811 return "Error checking network sockets!";
813 if (num_active_sockets == 0)
814 break; // no active sockets, stop here
816 /* ---------- read packets from network server ---------- */
818 int num_bytes = SDLNet_TCP_Recv(sfd, readbuffer + nread, 1);
821 return "Error reading from network server!";
824 return "Connection to network server lost!";
828 HandleNetworkingMessages();
834 static void FreeNetworkClientPlayerInfo(struct NetworkClientPlayerInfo *player)
840 FreeNetworkClientPlayerInfo(player->next);
842 checked_free(player);
845 static void HandleNetworkingDisconnect()
849 SDLNet_TCP_DelSocket(rfds, sfd);
850 SDLNet_TCP_Close(sfd);
852 network_playing = FALSE;
854 network.enabled = FALSE;
855 network.connected = FALSE;
857 setup.network_mode = FALSE;
859 for (i = 0; i < MAX_PLAYERS; i++)
860 stored_player[i].connected_network = FALSE;
862 FreeNetworkClientPlayerInfo(first_player.next);
865 first_player.next = NULL;
868 void HandleNetworking()
870 char *error_message = HandleNetworkingPackets();
872 if (error_message != NULL)
874 HandleNetworkingDisconnect();
876 if (game_status == GAME_MODE_PLAYING)
878 Request(error_message, REQ_CONFIRM | REQ_STAY_CLOSED);
880 SetGameStatus(GAME_MODE_MAIN);
886 Request(error_message, REQ_CONFIRM);
888 if (game_status == GAME_MODE_MAIN)
889 ClearNetworkPlayers();
894 void DisconnectFromNetworkServer()
896 DrawNetworkText_Title("Terminating Network");
897 DrawNetworkText("Disconnecting from network server ...");
899 HandleNetworkingDisconnect();
901 DrawNetworkText_Success("Successfully disconnected!");
903 /* short time to recognize result of network initialization */
904 Delay_WithScreenUpdates(1000);