d_clisrv.c 139 KB
Newer Older
Alam Ed Arias committed
1 2 3
// SONIC ROBO BLAST 2
//-----------------------------------------------------------------------------
// Copyright (C) 1998-2000 by DooM Legacy Team.
James R. committed
4
// Copyright (C) 1999-2020 by Sonic Team Junior.
Alam Ed Arias committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
//
// This program is free software distributed under the
// terms of the GNU General Public License, version 2.
// See the 'LICENSE' file for more details.
//-----------------------------------------------------------------------------
/// \file  d_clisrv.c
/// \brief SRB2 Network game communication and protocol, all OS independent parts.

#include <time.h>
#ifdef __GNUC__
#include <unistd.h> //for unlink
#endif

#include "i_net.h"
#include "i_system.h"
#include "i_video.h"
#include "d_net.h"
#include "d_main.h"
#include "g_game.h"
24
#include "st_stuff.h"
Alam Ed Arias committed
25 26
#include "hu_stuff.h"
#include "keys.h"
Marco Z committed
27
#include "g_input.h" // JOY1
Alam Ed Arias committed
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#include "m_menu.h"
#include "console.h"
#include "d_netfil.h"
#include "byteptr.h"
#include "p_saveg.h"
#include "z_zone.h"
#include "p_local.h"
#include "m_misc.h"
#include "am_map.h"
#include "m_random.h"
#include "mserv.h"
#include "y_inter.h"
#include "r_local.h"
#include "m_argv.h"
#include "p_setup.h"
#include "lzf.h"
#include "lua_script.h"
#include "lua_hook.h"
46
#include "md5.h"
Alam Ed Arias committed
47 48 49 50 51 52 53 54 55 56 57

#ifdef CLIENT_LOADINGSCREEN
// cl loading screen
#include "v_video.h"
#include "f_finale.h"
#endif

//
// NETWORKING
//
// gametic is the tic about to (or currently being) run
58 59
// Server:
//   maketic is the tic that hasn't had control made for it yet
Alam Ed Arias committed
60 61
//   nettics is the tic for each node
//   firstticstosend is the lowest value of nettics
62 63
// Client:
//   neededtic is the tic needed by the client to run the game
Alam Ed Arias committed
64
//   firstticstosend is used to optimize a condition
65
// Normally maketic >= gametic > 0
Alam Ed Arias committed
66 67 68 69 70 71

#define PREDICTIONQUEUE BACKUPTICS
#define PREDICTIONMASK (PREDICTIONQUEUE-1)
#define MAX_REASONLENGTH 30

boolean server = true; // true or false but !server == client
72
#define client (!server)
Alam Ed Arias committed
73
boolean nodownload = false;
74
boolean serverrunning = false;
Alam Ed Arias committed
75 76 77
INT32 serverplayer = 0;
char motd[254], server_context[8]; // Message of the Day, Unique Context (even without Mumble support)

78
// Server specific vars
Alam Ed Arias committed
79
UINT8 playernode[MAXPLAYERS];
LJ Sonic committed
80
char playeraddress[MAXPLAYERS][64];
Alam Ed Arias committed
81

82 83 84 85 86 87
// Minimum timeout for sending the savegame
// The actual timeout will be longer depending on the savegame length
tic_t jointimeout = (10*TICRATE);
static boolean sendingsavegame[MAXNETNODES]; // Are we sending the savegame?
static tic_t freezetimeout[MAXNETNODES]; // Until when can this node freeze the server before getting a timeout?

88 89 90 91
// Incremented by cv_joindelay when a client joins, decremented each tic.
// If higher than cv_joindelay * 2 (3 joins in a short timespan), joins are temporarily disabled.
static tic_t joindelay = 0;

Alam Ed Arias committed
92 93 94 95 96 97 98
UINT16 pingmeasurecount = 1;
UINT32 realpingtable[MAXPLAYERS]; //the base table of ping where an average will be sent to everyone.
UINT32 playerpingtable[MAXPLAYERS]; //table of player latency values.
SINT8 nodetoplayer[MAXNETNODES];
SINT8 nodetoplayer2[MAXNETNODES]; // say the numplayer for this node if any (splitscreen)
UINT8 playerpernode[MAXNETNODES]; // used specialy for scplitscreen
boolean nodeingame[MAXNETNODES]; // set false as nodes leave game
SteelT committed
99
tic_t servermaxping = 800; // server's max ping. Defaults to 800
Alam Ed Arias committed
100 101 102 103 104 105 106
static tic_t nettics[MAXNETNODES]; // what tic the client have received
static tic_t supposedtics[MAXNETNODES]; // nettics prevision for smaller packet
static UINT8 nodewaiting[MAXNETNODES];
static tic_t firstticstosend; // min of the nettics
static tic_t tictoclear = 0; // optimize d_clearticcmd
static tic_t maketic;

Alam Ed Arias committed
107 108 109 110 111 112
static INT16 consistancy[BACKUPTICS];

// Resynching shit!
static UINT32 resynch_score[MAXNETNODES]; // "score" for kicking -- if this gets too high then cfail kick
static UINT16 resynch_delay[MAXNETNODES]; // delay time before the player can be considered to have desynched
static UINT32 resynch_status[MAXNETNODES]; // 0 bit means synched for that player, 1 means possibly desynched
113
static UINT8 resynch_sent[MAXNETNODES][MAXPLAYERS]; // what synch packets have we attempted to send to the player
Alam Ed Arias committed
114 115 116 117 118
static UINT8 resynch_inprogress[MAXNETNODES];
static UINT8 resynch_local_inprogress = false; // WE are desynched and getting packets to fix it.
static UINT8 player_joining = false;
UINT8 hu_resynching = 0;

James R. committed
119
UINT8 adminpassmd5[16];
120 121
boolean adminpasswordset = false;

122
// Client specific
Alam Ed Arias committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
static ticcmd_t localcmds;
static ticcmd_t localcmds2;
static boolean cl_packetmissed;
// here it is for the secondary local player (splitscreen)
static UINT8 mynode; // my address pointofview server

static UINT8 localtextcmd[MAXTEXTCMD];
static UINT8 localtextcmd2[MAXTEXTCMD]; // splitscreen
static tic_t neededtic;
SINT8 servernode = 0; // the number of the server node
/// \brief do we accept new players?
/// \todo WORK!
boolean acceptnewnode = true;

// engine

// Must be a power of two
#define TEXTCMD_HASH_SIZE 4

typedef struct textcmdplayer_s
{
	INT32 playernum;
	UINT8 cmd[MAXTEXTCMD];
	struct textcmdplayer_s *next;
} textcmdplayer_t;

typedef struct textcmdtic_s
{
	tic_t tic;
	textcmdplayer_t *playercmds[TEXTCMD_HASH_SIZE];
	struct textcmdtic_s *next;
} textcmdtic_t;

ticcmd_t netcmds[BACKUPTICS][MAXPLAYERS];
static textcmdtic_t *textcmds[TEXTCMD_HASH_SIZE] = {NULL};


160
consvar_t cv_showjoinaddress = {"showjoinaddress", "On", CV_SAVE, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};
Alam Ed Arias committed
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

static CV_PossibleValue_t playbackspeed_cons_t[] = {{1, "MIN"}, {10, "MAX"}, {0, NULL}};
consvar_t cv_playbackspeed = {"playbackspeed", "1", 0, playbackspeed_cons_t, NULL, 0, NULL, NULL, 0, 0, NULL};

static inline void *G_DcpyTiccmd(void* dest, const ticcmd_t* src, const size_t n)
{
	const size_t d = n / sizeof(ticcmd_t);
	const size_t r = n % sizeof(ticcmd_t);
	UINT8 *ret = dest;

	if (r)
		M_Memcpy(dest, src, n);
	else if (d)
		G_MoveTiccmd(dest, src, d);
	return ret+n;
}

static inline void *G_ScpyTiccmd(ticcmd_t* dest, void* src, const size_t n)
{
	const size_t d = n / sizeof(ticcmd_t);
	const size_t r = n % sizeof(ticcmd_t);
	UINT8 *ret = src;

	if (r)
		M_Memcpy(dest, src, n);
	else if (d)
		G_MoveTiccmd(dest, src, d);
	return ret+n;
}



193 194 195
// Some software don't support largest packet
// (original sersetup, not exactely, but the probability of sending a packet
// of 512 bytes is like 0.1)
Alam Ed Arias committed
196 197
UINT16 software_MAXPACKETLENGTH;

198 199 200 201 202 203
/** Guesses the value of a tic from its lowest byte and from maketic
  *
  * \param low The lowest byte of the tic value
  * \return The full tic value
  *
  */
Alam Ed Arias committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
tic_t ExpandTics(INT32 low)
{
	INT32 delta;

	delta = low - (maketic & UINT8_MAX);

	if (delta >= -64 && delta <= 64)
		return (maketic & ~UINT8_MAX) + low;
	else if (delta > 64)
		return (maketic & ~UINT8_MAX) - 256 + low;
	else //if (delta < -64)
		return (maketic & ~UINT8_MAX) + 256 + low;
}

// -----------------------------------------------------------------
// Some extra data function for handle textcmd buffer
// -----------------------------------------------------------------

static void (*listnetxcmd[MAXNETXCMD])(UINT8 **p, INT32 playernum);

void RegisterNetXCmd(netxcmd_t id, void (*cmd_f)(UINT8 **p, INT32 playernum))
{
#ifdef PARANOIA
	if (id >= MAXNETXCMD)
228
		I_Error("Command id %d too big", id);
Alam Ed Arias committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
	if (listnetxcmd[id] != 0)
		I_Error("Command id %d already used", id);
#endif
	listnetxcmd[id] = cmd_f;
}

void SendNetXCmd(netxcmd_t id, const void *param, size_t nparam)
{
	if (localtextcmd[0]+2+nparam > MAXTEXTCMD)
	{
		// for future reference: if (cv_debug) != debug disabled.
		CONS_Alert(CONS_ERROR, M_GetText("NetXCmd buffer full, cannot add netcmd %d! (size: %d, needed: %s)\n"), id, localtextcmd[0], sizeu1(nparam));
		return;
	}
	localtextcmd[0]++;
	localtextcmd[localtextcmd[0]] = (UINT8)id;
	if (param && nparam)
	{
		M_Memcpy(&localtextcmd[localtextcmd[0]+1], param, nparam);
		localtextcmd[0] = (UINT8)(localtextcmd[0] + (UINT8)nparam);
	}
}

// splitscreen player
void SendNetXCmd2(netxcmd_t id, const void *param, size_t nparam)
{
	if (localtextcmd2[0]+2+nparam > MAXTEXTCMD)
	{
		I_Error("No more place in the buffer for netcmd %d\n",id);
		return;
	}
	localtextcmd2[0]++;
	localtextcmd2[localtextcmd2[0]] = (UINT8)id;
	if (param && nparam)
	{
		M_Memcpy(&localtextcmd2[localtextcmd2[0]+1], param, nparam);
		localtextcmd2[0] = (UINT8)(localtextcmd2[0] + (UINT8)nparam);
	}
}

UINT8 GetFreeXCmdSize(void)
{
	// -1 for the size and another -1 for the ID.
	return (UINT8)(localtextcmd[0] - 2);
}

// Frees all textcmd memory for the specified tic
static void D_FreeTextcmd(tic_t tic)
{
	textcmdtic_t **tctprev = &textcmds[tic & (TEXTCMD_HASH_SIZE - 1)];
	textcmdtic_t *textcmdtic = *tctprev;

	while (textcmdtic && textcmdtic->tic != tic)
	{
		tctprev = &textcmdtic->next;
		textcmdtic = textcmdtic->next;
	}

	if (textcmdtic)
	{
		INT32 i;

		// Remove this tic from the list.
		*tctprev = textcmdtic->next;

		// Free all players.
		for (i = 0; i < TEXTCMD_HASH_SIZE; i++)
		{
			textcmdplayer_t *textcmdplayer = textcmdtic->playercmds[i];

			while (textcmdplayer)
			{
				textcmdplayer_t *tcpnext = textcmdplayer->next;
				Z_Free(textcmdplayer);
				textcmdplayer = tcpnext;
			}
		}

		// Free this tic's own memory.
		Z_Free(textcmdtic);
	}
}

// Gets the buffer for the specified ticcmd, or NULL if there isn't one
static UINT8* D_GetExistingTextcmd(tic_t tic, INT32 playernum)
{
	textcmdtic_t *textcmdtic = textcmds[tic & (TEXTCMD_HASH_SIZE - 1)];
	while (textcmdtic && textcmdtic->tic != tic) textcmdtic = textcmdtic->next;

	// Do we have an entry for the tic? If so, look for player.
	if (textcmdtic)
	{
		textcmdplayer_t *textcmdplayer = textcmdtic->playercmds[playernum & (TEXTCMD_HASH_SIZE - 1)];
		while (textcmdplayer && textcmdplayer->playernum != playernum) textcmdplayer = textcmdplayer->next;

		if (textcmdplayer) return textcmdplayer->cmd;
	}

	return NULL;
}

// Gets the buffer for the specified ticcmd, creating one if necessary
static UINT8* D_GetTextcmd(tic_t tic, INT32 playernum)
{
	textcmdtic_t *textcmdtic = textcmds[tic & (TEXTCMD_HASH_SIZE - 1)];
	textcmdtic_t **tctprev = &textcmds[tic & (TEXTCMD_HASH_SIZE - 1)];
	textcmdplayer_t *textcmdplayer, **tcpprev;

	// Look for the tic.
	while (textcmdtic && textcmdtic->tic != tic)
	{
		tctprev = &textcmdtic->next;
		textcmdtic = textcmdtic->next;
	}

	// If we don't have an entry for the tic, make it.
	if (!textcmdtic)
	{
		textcmdtic = *tctprev = Z_Calloc(sizeof (textcmdtic_t), PU_STATIC, NULL);
		textcmdtic->tic = tic;
	}

	tcpprev = &textcmdtic->playercmds[playernum & (TEXTCMD_HASH_SIZE - 1)];
	textcmdplayer = *tcpprev;

	// Look for the player.
	while (textcmdplayer && textcmdplayer->playernum != playernum)
	{
		tcpprev = &textcmdplayer->next;
		textcmdplayer = textcmdplayer->next;
	}

	// If we don't have an entry for the player, make it.
	if (!textcmdplayer)
	{
		textcmdplayer = *tcpprev = Z_Calloc(sizeof (textcmdplayer_t), PU_STATIC, NULL);
		textcmdplayer->playernum = playernum;
	}

	return textcmdplayer->cmd;
}

static void ExtraDataTicker(void)
{
	INT32 i;

	for (i = 0; i < MAXPLAYERS; i++)
		if (playeringame[i] || i == 0)
		{
			UINT8 *bufferstart = D_GetExistingTextcmd(gametic, i);

			if (bufferstart)
			{
				UINT8 *curpos = bufferstart;
				UINT8 *bufferend = &curpos[curpos[0]+1];

				curpos++;
				while (curpos < bufferend)
				{
					if (*curpos < MAXNETXCMD && listnetxcmd[*curpos])
					{
						const UINT8 id = *curpos;
						curpos++;
392
						DEBFILE(va("executing x_cmd %s ply %u ", netxcmdnames[id - 1], i));
Alam Ed Arias committed
393 394 395 396 397 398 399
						(listnetxcmd[id])(&curpos, i);
						DEBFILE("done\n");
					}
					else
					{
						if (server)
						{
400
							SendKick(i, KICK_MSG_CON_FAIL | KICK_MSG_KEEP_BODY);
Alam Ed Arias committed
401 402 403
							DEBFILE(va("player %d kicked [gametic=%u] reason as follows:\n", i, gametic));
						}
						CONS_Alert(CONS_WARNING, M_GetText("Got unknown net command [%s]=%d (max %d)\n"), sizeu1(curpos - bufferstart), *curpos, bufferstart[0]);
404
						break;
Alam Ed Arias committed
405 406 407 408 409
					}
				}
			}
		}

410
	// If you are a client, you can safely forget the net commands for this tic
411 412
	// If you are the server, you need to remember them until every client has been acknowledged,
	// because if you need to resend a PT_SERVERTICS packet, you will need to put the commands in it
413
	if (client)
414
		D_FreeTextcmd(gametic);
Alam Ed Arias committed
415 416 417 418 419 420 421 422 423 424 425 426 427 428
}

static void D_Clearticcmd(tic_t tic)
{
	INT32 i;

	D_FreeTextcmd(tic);

	for (i = 0; i < MAXPLAYERS; i++)
		netcmds[tic%BACKUPTICS][i].angleturn = 0;

	DEBFILE(va("clear tic %5u (%2u)\n", tic, tic%BACKUPTICS));
}

429 430 431 432 433 434 435 436 437 438 439 440 441
void D_ResetTiccmds(void)
{
	INT32 i;

	memset(&localcmds, 0, sizeof(ticcmd_t));
	memset(&localcmds2, 0, sizeof(ticcmd_t));

	// Reset the net command list
	for (i = 0; i < TEXTCMD_HASH_SIZE; i++)
		while (textcmds[i])
			D_Clearticcmd(textcmds[i]->tic);
}

442 443 444 445
void SendKick(UINT8 playernum, UINT8 msg)
{
	UINT8 buf[2];

446 447 448
	if (!(server && cv_rejointimeout.value))
		msg &= ~KICK_MSG_KEEP_BODY;

449 450 451 452 453
	buf[0] = playernum;
	buf[1] = msg;
	SendNetXCmd(XD_KICK, &buf, 2);
}

Alam Ed Arias committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
// -----------------------------------------------------------------
// end of extra data function
// -----------------------------------------------------------------

// -----------------------------------------------------------------
// extra data function for lmps
// -----------------------------------------------------------------

// if extradatabit is set, after the ziped tic you find this:
//
//   type   |  description
// ---------+--------------
//   byte   | size of the extradata
//   byte   | the extradata (xd) bits: see XD_...
//            with this byte you know what parameter folow
// if (xd & XDNAMEANDCOLOR)
//   byte   | color
//   char[MAXPLAYERNAME] | name of the player
// endif
// if (xd & XD_WEAPON_PREF)
//   byte   | original weapon switch: boolean, true if use the old
//          | weapon switch methode
//   char[NUMWEAPONS] | the weapon switch priority
//   byte   | autoaim: true if use the old autoaim system
// endif
/*boolean AddLmpExtradata(UINT8 **demo_point, INT32 playernum)
{
	UINT8 *textcmd = D_GetExistingTextcmd(gametic, playernum);

	if (!textcmd)
		return false;

	M_Memcpy(*demo_point, textcmd, textcmd[0]+1);
	*demo_point += textcmd[0]+1;
	return true;
}

void ReadLmpExtraData(UINT8 **demo_pointer, INT32 playernum)
{
	UINT8 nextra;
	UINT8 *textcmd;

	if (!demo_pointer)
		return;

	textcmd = D_GetTextcmd(gametic, playernum);
	nextra = **demo_pointer;
	M_Memcpy(textcmd, *demo_pointer, nextra + 1);
	// increment demo pointer
	*demo_pointer += nextra + 1;
}*/

// -----------------------------------------------------------------
// end extra data function for lmps
// -----------------------------------------------------------------

Alam Ed Arias committed
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
// -----------------------------------------------------------------
// resynch player data
// -----------------------------------------------------------------
static inline void resynch_write_player(resynch_pak *rsp, const size_t i)
{
	size_t j;

	rsp->playernum = (UINT8)i;

	// Do not send anything visual related.
	// Only send data that we need to know for physics.
	rsp->playerstate = (UINT8)players[i].playerstate; //playerstate_t
	rsp->pflags = (UINT32)LONG(players[i].pflags); //pflags_t
	rsp->panim  = (UINT8)players[i].panim; //panim_t

	rsp->aiming = (angle_t)LONG(players[i].aiming);
	rsp->currentweapon = LONG(players[i].currentweapon);
	rsp->ringweapons = LONG(players[i].ringweapons);

529 530 531 532
	rsp->ammoremoval = (UINT16)SHORT(players[i].ammoremoval);
	rsp->ammoremovaltimer = (tic_t)LONG(players[i].ammoremovaltimer);
	rsp->ammoremovalweapon = LONG(players[i].ammoremovalweapon);

Alam Ed Arias committed
533 534 535 536
	for (j = 0; j < NUMPOWERS; ++j)
		rsp->powers[j] = (UINT16)SHORT(players[i].powers[j]);

	// Score is resynched in the rspfirm resync packet
toaster committed
537 538
	rsp->rings = SHORT(players[i].rings);
	rsp->spheres = SHORT(players[i].spheres);
Alam Ed Arias committed
539 540 541 542 543 544 545 546
	rsp->lives = players[i].lives;
	rsp->continues = players[i].continues;
	rsp->scoreadd = players[i].scoreadd;
	rsp->xtralife = players[i].xtralife;
	rsp->pity = players[i].pity;

	rsp->skincolor = players[i].skincolor;
	rsp->skin = LONG(players[i].skin);
547
	rsp->availabilities = LONG(players[i].availabilities);
Alam Ed Arias committed
548 549
	// Just in case Lua does something like
	// modify these at runtime
550 551
	rsp->camerascale = (fixed_t)LONG(players[i].camerascale);
	rsp->shieldscale = (fixed_t)LONG(players[i].shieldscale);
Alam Ed Arias committed
552 553 554 555 556 557 558 559 560 561 562
	rsp->normalspeed = (fixed_t)LONG(players[i].normalspeed);
	rsp->runspeed = (fixed_t)LONG(players[i].runspeed);
	rsp->thrustfactor = players[i].thrustfactor;
	rsp->accelstart = players[i].accelstart;
	rsp->acceleration = players[i].acceleration;
	rsp->charability = players[i].charability;
	rsp->charability2 = players[i].charability2;
	rsp->charflags = (UINT32)LONG(players[i].charflags);
	rsp->thokitem = (UINT32)LONG(players[i].thokitem); //mobjtype_t
	rsp->spinitem = (UINT32)LONG(players[i].spinitem); //mobjtype_t
	rsp->revitem = (UINT32)LONG(players[i].revitem); //mobjtype_t
563
	rsp->followitem = (UINT32)LONG(players[i].followitem); //mobjtype_t
Monster Iestyn committed
564 565 566
	rsp->actionspd = (fixed_t)LONG(players[i].actionspd);
	rsp->mindash = (fixed_t)LONG(players[i].mindash);
	rsp->maxdash = (fixed_t)LONG(players[i].maxdash);
Alam Ed Arias committed
567
	rsp->jumpfactor = (fixed_t)LONG(players[i].jumpfactor);
568 569
	rsp->playerheight = (fixed_t)LONG(players[i].height);
	rsp->playerspinheight = (fixed_t)LONG(players[i].spinheight);
Alam Ed Arias committed
570 571 572 573 574 575 576 577 578

	rsp->speed = (fixed_t)LONG(players[i].speed);
	rsp->secondjump = players[i].secondjump;
	rsp->fly1 = players[i].fly1;
	rsp->glidetime = (tic_t)LONG(players[i].glidetime);
	rsp->climbing = players[i].climbing;
	rsp->deadtimer = players[i].deadtimer;
	rsp->exiting = (tic_t)LONG(players[i].exiting);
	rsp->homing = players[i].homing;
579
	rsp->dashmode = (tic_t)LONG(players[i].dashmode);
Monster Iestyn committed
580
	rsp->skidtime = (tic_t)LONG(players[i].skidtime);
Alam Ed Arias committed
581 582 583 584 585 586 587 588 589 590 591 592 593 594
	rsp->cmomx = (fixed_t)LONG(players[i].cmomx);
	rsp->cmomy = (fixed_t)LONG(players[i].cmomy);
	rsp->rmomx = (fixed_t)LONG(players[i].rmomx);
	rsp->rmomy = (fixed_t)LONG(players[i].rmomy);

	rsp->weapondelay = LONG(players[i].weapondelay);
	rsp->tossdelay = LONG(players[i].tossdelay);

	rsp->starpostx = SHORT(players[i].starpostx);
	rsp->starposty = SHORT(players[i].starposty);
	rsp->starpostz = SHORT(players[i].starpostz);
	rsp->starpostnum = LONG(players[i].starpostnum);
	rsp->starposttime = (tic_t)LONG(players[i].starposttime);
	rsp->starpostangle = (angle_t)LONG(players[i].starpostangle);
595
	rsp->starpostscale = (fixed_t)LONG(players[i].starpostscale);
Alam Ed Arias committed
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627

	rsp->maxlink = LONG(players[i].maxlink);
	rsp->dashspeed = (fixed_t)LONG(players[i].dashspeed);
	rsp->angle_pos = (angle_t)LONG(players[i].angle_pos);
	rsp->old_angle_pos = (angle_t)LONG(players[i].old_angle_pos);
	rsp->bumpertime = (tic_t)LONG(players[i].bumpertime);
	rsp->flyangle = LONG(players[i].flyangle);
	rsp->drilltimer = (tic_t)LONG(players[i].drilltimer);
	rsp->linkcount = LONG(players[i].linkcount);
	rsp->linktimer = (tic_t)LONG(players[i].linktimer);
	rsp->anotherflyangle = LONG(players[i].anotherflyangle);
	rsp->nightstime = (tic_t)LONG(players[i].nightstime);
	rsp->drillmeter = LONG(players[i].drillmeter);
	rsp->drilldelay = players[i].drilldelay;
	rsp->bonustime = players[i].bonustime;
	rsp->mare = players[i].mare;
	rsp->lastsidehit = SHORT(players[i].lastsidehit);
	rsp->lastlinehit = SHORT(players[i].lastlinehit);

	rsp->losstime = (tic_t)LONG(players[i].losstime);
	rsp->timeshit = players[i].timeshit;
	rsp->onconveyor = LONG(players[i].onconveyor);

	rsp->hasmo = false;
	//Transfer important mo information if the player has a body.
	//This lets us resync players even if they are dead.
	if (!players[i].mo)
		return;
	rsp->hasmo = true;

	rsp->health = LONG(players[i].mo->health);
	rsp->angle = (angle_t)LONG(players[i].mo->angle);
Jaime Ita Passos committed
628
	rsp->rollangle = (angle_t)LONG(players[i].mo->rollangle);
Alam Ed Arias committed
629 630 631 632 633 634 635 636 637
	rsp->x = LONG(players[i].mo->x);
	rsp->y = LONG(players[i].mo->y);
	rsp->z = LONG(players[i].mo->z);
	rsp->momx = LONG(players[i].mo->momx);
	rsp->momy = LONG(players[i].mo->momy);
	rsp->momz = LONG(players[i].mo->momz);
	rsp->friction = LONG(players[i].mo->friction);
	rsp->movefactor = LONG(players[i].mo->movefactor);

638 639 640 641
	rsp->sprite = (spritenum_t)LONG(players[i].mo->sprite);
	rsp->frame = LONG(players[i].mo->frame);
	rsp->sprite2 = players[i].mo->sprite2;
	rsp->anim_duration = SHORT(players[i].mo->anim_duration);
Alam Ed Arias committed
642 643
	rsp->tics = LONG(players[i].mo->tics);
	rsp->statenum = (statenum_t)LONG(players[i].mo->state-states); // :(
Monster Iestyn committed
644
	rsp->eflags = (UINT16)SHORT(players[i].mo->eflags);
Alam Ed Arias committed
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
	rsp->flags = LONG(players[i].mo->flags);
	rsp->flags2 = LONG(players[i].mo->flags2);

	rsp->radius = LONG(players[i].mo->radius);
	rsp->height = LONG(players[i].mo->height);
	rsp->scale = LONG(players[i].mo->scale);
	rsp->destscale = LONG(players[i].mo->destscale);
	rsp->scalespeed = LONG(players[i].mo->scalespeed);
}

static void resynch_read_player(resynch_pak *rsp)
{
	INT32 i = rsp->playernum, j;
	mobj_t *savedmo = players[i].mo;

	// Do not send anything visual related.
	// Only send data that we need to know for physics.
	players[i].playerstate = (UINT8)rsp->playerstate; //playerstate_t
	players[i].pflags = (UINT32)LONG(rsp->pflags); //pflags_t
	players[i].panim  = (UINT8)rsp->panim; //panim_t

	players[i].aiming = (angle_t)LONG(rsp->aiming);
	players[i].currentweapon = LONG(rsp->currentweapon);
	players[i].ringweapons = LONG(rsp->ringweapons);

670 671 672 673
	players[i].ammoremoval = (UINT16)SHORT(rsp->ammoremoval);
	players[i].ammoremovaltimer = (tic_t)LONG(rsp->ammoremovaltimer);
	players[i].ammoremovalweapon = LONG(rsp->ammoremovalweapon);

Alam Ed Arias committed
674 675 676 677
	for (j = 0; j < NUMPOWERS; ++j)
		players[i].powers[j] = (UINT16)SHORT(rsp->powers[j]);

	// Score is resynched in the rspfirm resync packet
toaster committed
678 679
	players[i].rings = SHORT(rsp->rings);
	players[i].spheres = SHORT(rsp->spheres);
Alam Ed Arias committed
680 681 682 683 684 685 686 687
	players[i].lives = rsp->lives;
	players[i].continues = rsp->continues;
	players[i].scoreadd = rsp->scoreadd;
	players[i].xtralife = rsp->xtralife;
	players[i].pity = rsp->pity;

	players[i].skincolor = rsp->skincolor;
	players[i].skin = LONG(rsp->skin);
688
	players[i].availabilities = LONG(rsp->availabilities);
Alam Ed Arias committed
689 690
	// Just in case Lua does something like
	// modify these at runtime
691 692
	players[i].camerascale = (fixed_t)LONG(rsp->camerascale);
	players[i].shieldscale = (fixed_t)LONG(rsp->shieldscale);
Alam Ed Arias committed
693 694 695 696 697 698 699 700 701 702 703
	players[i].normalspeed = (fixed_t)LONG(rsp->normalspeed);
	players[i].runspeed = (fixed_t)LONG(rsp->runspeed);
	players[i].thrustfactor = rsp->thrustfactor;
	players[i].accelstart = rsp->accelstart;
	players[i].acceleration = rsp->acceleration;
	players[i].charability = rsp->charability;
	players[i].charability2 = rsp->charability2;
	players[i].charflags = (UINT32)LONG(rsp->charflags);
	players[i].thokitem = (UINT32)LONG(rsp->thokitem); //mobjtype_t
	players[i].spinitem = (UINT32)LONG(rsp->spinitem); //mobjtype_t
	players[i].revitem = (UINT32)LONG(rsp->revitem); //mobjtype_t
704
	players[i].followitem = (UINT32)LONG(rsp->followitem); //mobjtype_t
Monster Iestyn committed
705 706 707
	players[i].actionspd = (fixed_t)LONG(rsp->actionspd);
	players[i].mindash = (fixed_t)LONG(rsp->mindash);
	players[i].maxdash = (fixed_t)LONG(rsp->maxdash);
Alam Ed Arias committed
708
	players[i].jumpfactor = (fixed_t)LONG(rsp->jumpfactor);
709 710
	players[i].height = (fixed_t)LONG(rsp->playerheight);
	players[i].spinheight = (fixed_t)LONG(rsp->playerspinheight);
Alam Ed Arias committed
711 712 713 714 715 716 717 718 719

	players[i].speed = (fixed_t)LONG(rsp->speed);
	players[i].secondjump = rsp->secondjump;
	players[i].fly1 = rsp->fly1;
	players[i].glidetime = (tic_t)LONG(rsp->glidetime);
	players[i].climbing = rsp->climbing;
	players[i].deadtimer = rsp->deadtimer;
	players[i].exiting = (tic_t)LONG(rsp->exiting);
	players[i].homing = rsp->homing;
720
	players[i].dashmode = (tic_t)LONG(rsp->dashmode);
Monster Iestyn committed
721
	players[i].skidtime = (tic_t)LONG(rsp->skidtime);
Alam Ed Arias committed
722 723 724 725 726 727 728 729 730 731 732 733 734 735
	players[i].cmomx = (fixed_t)LONG(rsp->cmomx);
	players[i].cmomy = (fixed_t)LONG(rsp->cmomy);
	players[i].rmomx = (fixed_t)LONG(rsp->rmomx);
	players[i].rmomy = (fixed_t)LONG(rsp->rmomy);

	players[i].weapondelay = LONG(rsp->weapondelay);
	players[i].tossdelay = LONG(rsp->tossdelay);

	players[i].starpostx = SHORT(rsp->starpostx);
	players[i].starposty = SHORT(rsp->starposty);
	players[i].starpostz = SHORT(rsp->starpostz);
	players[i].starpostnum = LONG(rsp->starpostnum);
	players[i].starposttime = (tic_t)LONG(rsp->starposttime);
	players[i].starpostangle = (angle_t)LONG(rsp->starpostangle);
736
	players[i].starpostscale = (fixed_t)LONG(rsp->starpostscale);
Alam Ed Arias committed
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778

	players[i].maxlink = LONG(rsp->maxlink);
	players[i].dashspeed = (fixed_t)LONG(rsp->dashspeed);
	players[i].angle_pos = (angle_t)LONG(rsp->angle_pos);
	players[i].old_angle_pos = (angle_t)LONG(rsp->old_angle_pos);
	players[i].bumpertime = (tic_t)LONG(rsp->bumpertime);
	players[i].flyangle = LONG(rsp->flyangle);
	players[i].drilltimer = (tic_t)LONG(rsp->drilltimer);
	players[i].linkcount = LONG(rsp->linkcount);
	players[i].linktimer = (tic_t)LONG(rsp->linktimer);
	players[i].anotherflyangle = LONG(rsp->anotherflyangle);
	players[i].nightstime = (tic_t)LONG(rsp->nightstime);
	players[i].drillmeter = LONG(rsp->drillmeter);
	players[i].drilldelay = rsp->drilldelay;
	players[i].bonustime = rsp->bonustime;
	players[i].mare = rsp->mare;
	players[i].lastsidehit = SHORT(rsp->lastsidehit);
	players[i].lastlinehit = SHORT(rsp->lastlinehit);

	players[i].losstime = (tic_t)LONG(rsp->losstime);
	players[i].timeshit = rsp->timeshit;
	players[i].onconveyor = LONG(rsp->onconveyor);

	//We get a packet for each player in game.
	if (!playeringame[i])
		return;

	//...but keep old mo even if it is corrupt or null!
	players[i].mo = savedmo;

	//Transfer important mo information if they have a valid mo.
	if (!rsp->hasmo)
		return;

	//server thinks player has a body.
	//Give them a new body that can be then manipulated by the server's info.
	if (!players[i].mo) //client thinks it has no body.
		P_SpawnPlayer(i);

	//At this point, the player should have a body, whether they were respawned or not.
	P_UnsetThingPosition(players[i].mo);
	players[i].mo->angle = (angle_t)LONG(rsp->angle);
Jaime Ita Passos committed
779
	players[i].mo->rollangle = (angle_t)LONG(rsp->rollangle);
Monster Iestyn committed
780
	players[i].mo->eflags = (UINT16)SHORT(rsp->eflags);
Alam Ed Arias committed
781 782 783 784 785 786 787 788
	players[i].mo->flags = LONG(rsp->flags);
	players[i].mo->flags2 = LONG(rsp->flags2);
	players[i].mo->friction = LONG(rsp->friction);
	players[i].mo->health = LONG(rsp->health);
	players[i].mo->momx = LONG(rsp->momx);
	players[i].mo->momy = LONG(rsp->momy);
	players[i].mo->momz = LONG(rsp->momz);
	players[i].mo->movefactor = LONG(rsp->movefactor);
789 790 791 792 793 794 795 796

	// Don't use P_SetMobjStateNF to restore state, write/read all the values manually!
	// This should stop those stupid console errors, hopefully.
	// -- Monster Iestyn
	players[i].mo->sprite = (spritenum_t)LONG(rsp->sprite);
	players[i].mo->frame = LONG(rsp->frame);
	players[i].mo->sprite2 = rsp->sprite2;
	players[i].mo->anim_duration = SHORT(rsp->anim_duration);
Alam Ed Arias committed
797
	players[i].mo->tics = LONG(rsp->tics);
798
	players[i].mo->state = &states[LONG(rsp->statenum)];
799

Alam Ed Arias committed
800 801 802 803 804 805 806 807 808 809 810
	players[i].mo->x = LONG(rsp->x);
	players[i].mo->y = LONG(rsp->y);
	players[i].mo->z = LONG(rsp->z);
	players[i].mo->radius = LONG(rsp->radius);
	players[i].mo->height = LONG(rsp->height);
	// P_SetScale is redundant for this, as all related variables are already restored properly.
	players[i].mo->scale = LONG(rsp->scale);
	players[i].mo->destscale = LONG(rsp->destscale);
	players[i].mo->scalespeed = LONG(rsp->scalespeed);

	// And finally, SET THE MOBJ SKIN damn it.
811
	if ((players[i].powers[pw_carry] == CR_NIGHTSMODE) && (skins[players[i].skin].sprites[SPR2_NFLY].numframes == 0))
812 813 814 815 816 817 818 819 820
	{
		players[i].mo->skin = &skins[DEFAULTNIGHTSSKIN];
		players[i].mo->color = skins[DEFAULTNIGHTSSKIN].prefcolor; // this will be corrected by thinker to super flash
	}
	else
	{
		players[i].mo->skin = &skins[players[i].skin];
		players[i].mo->color = players[i].skincolor; // this will be corrected by thinker to super flash/mario star
	}
Alam Ed Arias committed
821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840

	P_SetThingPosition(players[i].mo);
}

static inline void resynch_write_ctf(resynchend_pak *rst)
{
	mobj_t *mflag;
	UINT8 i, j;

	for (i = 0, mflag = redflag; i < 2; ++i, mflag = blueflag)
	{
		rst->flagx[i] = rst->flagy[i] = rst->flagz[i] = 0;
		rst->flagloose[i] = rst->flagflags[i] = 0;
		rst->flagplayer[i] = -1;

		if (!mflag)
		{
			// Should be held by a player
			for (j = 0; j < MAXPLAYERS; ++j)
			{
Alam Ed Arias committed
841 842 843 844
				// GF_REDFLAG is 1, GF_BLUEFLAG is 2
				// redflag handling is i=0, blueflag is i=1
				// so check for gotflag == (i+1)
				if (!playeringame[j] || players[j].gotflag != (i+1))
Alam Ed Arias committed
845 846 847 848
					continue;
				rst->flagplayer[i] = (SINT8)j;
				break;
			}
Alam Ed Arias committed
849 850
			if (j == MAXPLAYERS) // fine, no I_Error
			{
Alam Ed Arias committed
851
				CONS_Alert(CONS_ERROR, "One of the flags has gone completely missing...\n");
Alam Ed Arias committed
852 853
				rst->flagplayer[i] = -2;
			}
Alam Ed Arias committed
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
			continue;
		}

		rst->flagx[i] = (fixed_t)LONG(mflag->x);
		rst->flagy[i] = (fixed_t)LONG(mflag->y);
		rst->flagz[i] = (fixed_t)LONG(mflag->z);
		rst->flagflags[i] = LONG(mflag->flags2);
		rst->flagloose[i] = LONG(mflag->fuse); // Dropped or not?
	}
}

static inline void resynch_read_ctf(resynchend_pak *p)
{
	UINT8 i;

	for (i = 0; i < MAXPLAYERS; ++i)
		players[i].gotflag = 0;

	// Red flag
Alam Ed Arias committed
873 874 875
	if (p->flagplayer[0] == -2)
		; // The server doesn't even know what happened to it...
	else if (p->flagplayer[0] != -1) // Held by a player
Alam Ed Arias committed
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
	{
		if (!playeringame[p->flagplayer[0]])
			 I_Error("Invalid red flag player %d who isn't in the game!", (INT32)p->flagplayer[0]);
		players[p->flagplayer[0]].gotflag = GF_REDFLAG;
		if (redflag)
		{
			P_RemoveMobj(redflag);
			redflag = NULL;
		}
	}
	else
	{
		if (!redflag)
			redflag = P_SpawnMobj(0,0,0,MT_REDFLAG);

		P_UnsetThingPosition(redflag);
		redflag->x = (fixed_t)LONG(p->flagx[0]);
		redflag->y = (fixed_t)LONG(p->flagy[0]);
		redflag->z = (fixed_t)LONG(p->flagz[0]);
		redflag->flags2 = LONG(p->flagflags[0]);
		redflag->fuse = LONG(p->flagloose[0]);
		P_SetThingPosition(redflag);
	}

	// Blue flag
Alam Ed Arias committed
901 902 903
	if (p->flagplayer[1] == -2)
		; // The server doesn't even know what happened to it...
	else if (p->flagplayer[1] != -1) // Held by a player
Alam Ed Arias committed
904 905 906
	{
		if (!playeringame[p->flagplayer[1]])
			 I_Error("Invalid blue flag player %d who isn't in the game!", (INT32)p->flagplayer[1]);
Alam Ed Arias committed
907
		players[p->flagplayer[1]].gotflag = GF_BLUEFLAG;
Alam Ed Arias committed
908 909 910 911 912 913 914 915 916 917 918 919
		if (blueflag)
		{
			P_RemoveMobj(blueflag);
			blueflag = NULL;
		}
	}
	else
	{
		if (!blueflag)
			blueflag = P_SpawnMobj(0,0,0,MT_BLUEFLAG);

		P_UnsetThingPosition(blueflag);
Alam Ed Arias committed
920 921 922 923 924
		blueflag->x = (fixed_t)LONG(p->flagx[1]);
		blueflag->y = (fixed_t)LONG(p->flagy[1]);
		blueflag->z = (fixed_t)LONG(p->flagz[1]);
		blueflag->flags2 = LONG(p->flagflags[1]);
		blueflag->fuse = LONG(p->flagloose[1]);
Alam Ed Arias committed
925 926 927 928 929 930 931 932
		P_SetThingPosition(blueflag);
	}
}

static inline void resynch_write_others(resynchend_pak *rst)
{
	UINT8 i;

933
	rst->ingame = 0;
934
	rst->outofcoop = 0;
Alam Ed Arias committed
935 936 937 938 939

	for (i = 0; i < MAXPLAYERS; ++i)
	{
		if (!playeringame[i])
		{
940
			rst->ctfteam[i] = 0;
Alam Ed Arias committed
941 942 943 944 945 946 947 948 949 950
			rst->score[i] = 0;
			rst->numboxes[i] = 0;
			rst->totalring[i] = 0;
			rst->realtime[i] = 0;
			rst->laps[i] = 0;
			continue;
		}

		if (!players[i].spectator)
			rst->ingame |= (1<<i);
951 952
		if (players[i].outofcoop)
			rst->outofcoop |= (1<<i);
953
		rst->ctfteam[i] = (INT32)LONG(players[i].ctfteam);
Alam Ed Arias committed
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
		rst->score[i] = (UINT32)LONG(players[i].score);
		rst->numboxes[i] = SHORT(players[i].numboxes);
		rst->totalring[i] = SHORT(players[i].totalring);
		rst->realtime[i] = (tic_t)LONG(players[i].realtime);
		rst->laps[i] = players[i].laps;
	}

	// endian safeness
	rst->ingame = (UINT32)LONG(rst->ingame);
}

static inline void resynch_read_others(resynchend_pak *p)
{
	UINT8 i;
	UINT32 loc_ingame = (UINT32)LONG(p->ingame);
969
	UINT32 loc_outofcoop = (UINT32)LONG(p->outofcoop);
Alam Ed Arias committed
970 971 972 973

	for (i = 0; i < MAXPLAYERS; ++i)
	{
		// We don't care if they're in the game or not, just write all the data.
974
		players[i].spectator = !(loc_ingame & (1<<i));
975
		players[i].outofcoop = (loc_outofcoop & (1<<i));
976
		players[i].ctfteam = (INT32)LONG(p->ctfteam[i]); // no, 0 does not mean spectator, at least not in Match
Alam Ed Arias committed
977 978 979 980 981 982 983 984 985 986 987 988 989 990
		players[i].score = (UINT32)LONG(p->score[i]);
		players[i].numboxes = SHORT(p->numboxes[i]);
		players[i].totalring = SHORT(p->totalring[i]);
		players[i].realtime = (tic_t)LONG(p->realtime[i]);
		players[i].laps = p->laps[i];
	}
}

static void SV_InitResynchVars(INT32 node)
{
	resynch_delay[node] = TICRATE; // initial one second delay
	resynch_score[node] = 0; // clean slate
	resynch_status[node] = 0x00;
	resynch_inprogress[node] = false;
991
	memset(resynch_sent[node], 0, MAXPLAYERS);
Alam Ed Arias committed
992 993 994 995 996 997 998 999
}

static void SV_RequireResynch(INT32 node)
{
	INT32 i;

	resynch_delay[node] = 10; // Delay before you can fail sync again
	resynch_score[node] += 200; // Add score for initial desynch
1000
	resynch_status[node] = 0xFFFFFFFF; // No players assumed synched
Alam Ed Arias committed
1001 1002 1003
	resynch_inprogress[node] = true; // so we know to send a PT_RESYNCHEND after sync

	// Initial setup
1004
	memset(resynch_sent[node], 0, MAXPLAYERS);
Alam Ed Arias committed
1005 1006 1007 1008
	for (i = 0; i < MAXPLAYERS; ++i)
	{
		if (!playeringame[i]) // Player not in game so just drop it from required synch
			resynch_status[node] &= ~(1<<i);
1009
		else if (playernode[i] == node); // instantly update THEIR position
Alam Ed Arias committed
1010 1011 1012 1013 1014 1015 1016 1017 1018
		else // Send at random times based on num players
			resynch_sent[node][i] = M_RandomKey(D_NumPlayers()>>1)+1;
	}
}

static void SV_SendResynch(INT32 node)
{
	INT32 i, j;

Alam Ed Arias committed
1019 1020 1021 1022 1023 1024 1025 1026
	if (!nodeingame[node])
	{
		// player left during resynch
		// so obviously we don't need to do any of this anymore
		resynch_inprogress[node] = false;
		return;
	}

Alam Ed Arias committed
1027 1028 1029 1030 1031 1032 1033 1034 1035
	// resynched?
	if (!resynch_status[node])
	{
		// you are now synched
		resynch_inprogress[node] = false;

		netbuffer->packettype = PT_RESYNCHEND;

		netbuffer->u.resynchend.randomseed = P_GetRandSeed();
Jaime Ita Passos committed
1036
		if (gametyperules & GTR_TEAMFLAGS)
Alam Ed Arias committed
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
			resynch_write_ctf(&netbuffer->u.resynchend);
		resynch_write_others(&netbuffer->u.resynchend);

		HSendPacket(node, true, 0, (sizeof(resynchend_pak)));
		return;
	}

	netbuffer->packettype = PT_RESYNCHING;
	for (i = 0, j = 0; i < MAXPLAYERS; ++i)
	{
		// if already synched don't bother
		if (!(resynch_status[node] & 1<<i))
			continue;

		// waiting for a reply or just waiting in general
		if (resynch_sent[node][i])
		{
			--resynch_sent[node][i];
			continue;
		}

		resynch_write_player(&netbuffer->u.resynchpak, i);
		HSendPacket(node, false, 0, (sizeof(resynch_pak)));

		resynch_sent[node][i] = TICRATE;
		resynch_score[node] += 2; // penalty for send

		if (++j > 3)
			break;
	}

	if (resynch_score[node] > (unsigned)cv_resynchattempts.value*250)
	{
1070
		SendKick(nodetoplayer[node], KICK_MSG_CON_FAIL | KICK_MSG_KEEP_BODY);
Alam Ed Arias committed
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
		resynch_score[node] = 0;
	}
}

static void CL_AcknowledgeResynch(resynch_pak *rsp)
{
	resynch_read_player(rsp);

	netbuffer->packettype = PT_RESYNCHGET;
	netbuffer->u.resynchgot = rsp->playernum;
	HSendPacket(servernode, true, 0, sizeof(UINT8));
}

static void SV_AcknowledgeResynchAck(INT32 node, UINT8 rsg)
{
	if (rsg >= MAXPLAYERS)
		resynch_score[node] += 16384; // lol.
	else
	{
		resynch_status[node] &= ~(1<<rsg);
		--resynch_score[node]; // unpenalize
	}
1093 1094 1095

	// Don't let resynch cause a timeout
	freezetimeout[node] = I_GetTime() + connectiontimeout;
Alam Ed Arias committed
1096 1097 1098 1099 1100
}
// -----------------------------------------------------------------
// end resynch
// -----------------------------------------------------------------

Alam Ed Arias committed
1101 1102 1103 1104 1105 1106 1107 1108
static INT16 Consistancy(void);

#ifndef NONET
#define JOININGAME
#endif

typedef enum
{
1109 1110 1111 1112
	CL_SEARCHING,
	CL_DOWNLOADFILES,
	CL_ASKJOIN,
	CL_WAITJOINRESPONSE,
Alam Ed Arias committed
1113
#ifdef JOININGAME
1114
	CL_DOWNLOADSAVEGAME,
Alam Ed Arias committed
1115
#endif
1116 1117
	CL_CONNECTED,
	CL_ABORTED
Alam Ed Arias committed
1118 1119 1120 1121
} cl_mode_t;

static void GetPackets(void);

1122
static cl_mode_t cl_mode = CL_SEARCHING;
Alam Ed Arias committed
1123

Alam Ed Arias committed
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
// Player name send/load

static void CV_SavePlayerNames(UINT8 **p)
{
	INT32 i = 0;
	// Players in game only.
	for (; i < MAXPLAYERS; ++i)
	{
		if (!playeringame[i])
		{
			WRITEUINT8(*p, 0);
			continue;
		}
		WRITESTRING(*p, player_names[i]);
	}
}

static void CV_LoadPlayerNames(UINT8 **p)
{
	INT32 i = 0;
	char tmp_name[MAXPLAYERNAME+1];
	tmp_name[MAXPLAYERNAME] = 0;

	for (; i < MAXPLAYERS; ++i)
	{
		READSTRING(*p, tmp_name);
		if (tmp_name[0] == 0)
			continue;
		if (tmp_name[MAXPLAYERNAME]) // overflow detected
			I_Error("Received bad server config packet when trying to join");
		memcpy(player_names[i], tmp_name, MAXPLAYERNAME+1);
	}
}

Alam Ed Arias committed
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
#ifdef CLIENT_LOADINGSCREEN
//
// CL_DrawConnectionStatus
//
// Keep the local client informed of our status.
//
static inline void CL_DrawConnectionStatus(void)
{
	INT32 ccstime = I_GetTime();

	// Draw background fade
Marco Z committed
1169
	if (!menuactive) // menu already draws its own fade
1170
		V_DrawFadeScreen(0xFF00, 16); // force default
Alam Ed Arias committed
1171 1172 1173 1174 1175

	// Draw the bottom box.
	M_DrawTextBox(BASEVIDWIDTH/2-128-8, BASEVIDHEIGHT-24-8, 32, 1);
	V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-24, V_YELLOWMAP, "Press ESC to abort");

1176
	if (cl_mode != CL_DOWNLOADFILES)
Alam Ed Arias committed
1177 1178
	{
		INT32 i, animtime = ((ccstime / 4) & 15) + 16;
1179
		UINT8 palstart = (cl_mode == CL_SEARCHING) ? 32 : 96;
Alam Ed Arias committed
1180 1181 1182 1183 1184 1185 1186 1187
		// 15 pal entries total.
		const char *cltext;

		for (i = 0; i < 16; ++i)
			V_DrawFill((BASEVIDWIDTH/2-128) + (i * 16), BASEVIDHEIGHT-24, 16, 8, palstart + ((animtime - i) & 15));

		switch (cl_mode)
		{
Alam Ed Arias committed
1188
#ifdef JOININGAME
1189
			case CL_DOWNLOADSAVEGAME:
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
				if (lastfilenum != -1)
				{
					cltext = M_GetText("Downloading game state...");
					Net_GetNetStat();
					V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE,
						va(" %4uK",fileneeded[lastfilenum].currentsize>>10));
					V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE,
						va("%3.1fK/s ", ((double)getbps)/1024));
				}
				else
					cltext = M_GetText("Waiting to download game state...");
Alam Ed Arias committed
1201
				break;
Alam Ed Arias committed
1202
#endif
1203 1204
			case CL_ASKJOIN:
			case CL_WAITJOINRESPONSE:
Alam Ed Arias committed
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
				cltext = M_GetText("Requesting to join...");
				break;
			default:
				cltext = M_GetText("Connecting to server...");
				break;
		}
		V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP, cltext);
	}
	else
	{
1215 1216 1217
		if (lastfilenum != -1)
		{
			INT32 dldlength;
1218
			static char tempname[28];
1219 1220
			fileneeded_t *file = &fileneeded[lastfilenum];
			char *filename = file->filename;
1221 1222

			Net_GetNetStat();
1223
			dldlength = (INT32)((file->currentsize/(double)file->totalsize) * 256);
1224 1225
			if (dldlength > 256)
				dldlength = 256;
1226 1227
			V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, 256, 8, 111);
			V_DrawFill(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, dldlength, 8, 96);
1228 1229

			memset(tempname, 0, sizeof(tempname));
1230 1231 1232
			// offset filename to just the name only part
			filename += strlen(filename) - nameonlylength(filename);

1233
			if (strlen(filename) > sizeof(tempname)-1) // too long to display fully
1234
			{
1235 1236 1237 1238
				size_t endhalfpos = strlen(filename)-10;
				// display as first 14 chars + ... + last 10 chars
				// which should add up to 27 if our math(s) is correct
				snprintf(tempname, sizeof(tempname), "%.14s...%.10s", filename, filename+endhalfpos);
1239 1240 1241
			}
			else // we can copy the whole thing in safely
			{
1242
				strncpy(tempname, filename, sizeof(tempname)-1);
1243
			}
1244 1245 1246 1247

			V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP,
				va(M_GetText("Downloading \"%s\""), tempname));
			V_DrawString(BASEVIDWIDTH/2-128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE,
1248
				va(" %4uK/%4uK",fileneeded[lastfilenum].currentsize>>10,file->totalsize>>10));
1249 1250 1251 1252 1253 1254
			V_DrawRightAlignedString(BASEVIDWIDTH/2+128, BASEVIDHEIGHT-24, V_20TRANS|V_MONOSPACE,
				va("%3.1fK/s ", ((double)getbps)/1024));
		}
		else
			V_DrawCenteredString(BASEVIDWIDTH/2, BASEVIDHEIGHT-24-32, V_YELLOWMAP,
				M_GetText("Waiting to download files..."));
Alam Ed Arias committed
1255 1256 1257 1258
	}
}
#endif

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
/** Sends a special packet to declare how many players in local
  * Used only in arbitratrenetstart()
  * Sends a PT_CLIENTJOIN packet to the server
  *
  * \return True if the packet was successfully sent
  * \todo Improve the description...
  *       Because to be honest, I have no idea what arbitratrenetstart is...
  *       Is it even used...?
  *
  */
Alam Ed Arias committed
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
static boolean CL_SendJoin(void)
{
	UINT8 localplayers = 1;
	if (netgame)
		CONS_Printf(M_GetText("Sending join request...\n"));
	netbuffer->packettype = PT_CLIENTJOIN;

	if (splitscreen || botingame)
		localplayers++;
	netbuffer->u.clientcfg.localplayers = localplayers;
James R. committed
1279 1280
	netbuffer->u.clientcfg._255 = 255;
	netbuffer->u.clientcfg.packetversion = PACKETVERSION;
Alam Ed Arias committed
1281 1282
	netbuffer->u.clientcfg.version = VERSION;
	netbuffer->u.clientcfg.subversion = SUBVERSION;
James R. committed
1283 1284
	strncpy(netbuffer->u.clientcfg.application, SRB2APPLICATION,
			sizeof netbuffer->u.clientcfg.application);
1285 1286 1287 1288 1289

	CleanupPlayerName(consoleplayer, cv_playername.zstring);
	if (splitscreen)
		CleanupPlayerName(1, cv_playername2.zstring);/* 1 is a HACK? oh no */

1290 1291
	strncpy(netbuffer->u.clientcfg.names[0], cv_playername.zstring, MAXPLAYERNAME);
	strncpy(netbuffer->u.clientcfg.names[1], cv_playername2.zstring, MAXPLAYERNAME);
1292

Alam Ed Arias committed
1293 1294 1295
	return HSendPacket(servernode, true, 0, sizeof (clientconfig_pak));
}

LJ Sonic committed
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
static INT32 FindRejoinerNum(SINT8 node)
{
	char strippednodeaddress[64];
	const char *nodeaddress;
	char *port;
	INT32 i;

	// Make sure there is no dead dress before proceeding to the stripping
	if (!I_GetNodeAddress)
		return -1;
	nodeaddress = I_GetNodeAddress(node);
	if (!nodeaddress)
		return -1;

	// Strip the address of its port
	strcpy(strippednodeaddress, nodeaddress);
	port = strchr(strippednodeaddress, ':');
	if (port)
		*port = '\0';

	// Check if any player matches the stripped address
	for (i = 0; i < MAXPLAYERS; i++)
	{
		if (playeringame[i] && playeraddress[i][0] && playernode[i] == UINT8_MAX
		&& !strcmp(playeraddress[i], strippednodeaddress))
			return i;
	}

	return -1;
}

Alam Ed Arias committed
1327 1328 1329 1330 1331
static void SV_SendServerInfo(INT32 node, tic_t servertime)
{
	UINT8 *p;

	netbuffer->packettype = PT_SERVERINFO;
James R. committed
1332 1333
	netbuffer->u.serverinfo._255 = 255;
	netbuffer->u.serverinfo.packetversion = PACKETVERSION;
Alam Ed Arias committed
1334 1335
	netbuffer->u.serverinfo.version = VERSION;
	netbuffer->u.serverinfo.subversion = SUBVERSION;
James R. committed
1336 1337
	strncpy(netbuffer->u.serverinfo.application, SRB2APPLICATION,
			sizeof netbuffer->u.serverinfo.application);
Alam Ed Arias committed
1338 1339 1340 1341 1342 1343
	// return back the time value so client can compute their ping
	netbuffer->u.serverinfo.time = (tic_t)LONG(servertime);
	netbuffer->u.serverinfo.leveltime = (tic_t)LONG(leveltime);

	netbuffer->u.serverinfo.numberofplayer = (UINT8)D_NumPlayers();
	netbuffer->u.serverinfo.maxplayer = (UINT8)cv_maxplayers.value;
LJ Sonic committed
1344

1345
	if (!node || FindRejoinerNum(node) != -1)
LJ Sonic committed
1346 1347 1348 1349 1350 1351 1352 1353
		netbuffer->u.serverinfo.refusereason = 0;
	else if (!cv_allownewplayer.value)
		netbuffer->u.serverinfo.refusereason = 1;
	else if (D_NumPlayers() >= cv_maxplayers.value)
		netbuffer->u.serverinfo.refusereason = 2;
	else
		netbuffer->u.serverinfo.refusereason = 0;

1354 1355
	strncpy(netbuffer->u.serverinfo.gametypename, Gametype_Names[gametype],
			sizeof netbuffer->u.serverinfo.gametypename);
Alam Ed Arias committed
1356 1357 1358 1359 1360 1361 1362 1363 1364
	netbuffer->u.serverinfo.modifiedgame = (UINT8)modifiedgame;
	netbuffer->u.serverinfo.cheatsenabled = CV_CheatsEnabled();
	netbuffer->u.serverinfo.isdedicated = (UINT8)dedicated;
	strncpy(netbuffer->u.serverinfo.servername, cv_servername.string,
		MAXSERVERNAME);
	strncpy(netbuffer->u.serverinfo.mapname, G_BuildMapName(gamemap), 7);

	M_Memcpy(netbuffer->u.serverinfo.mapmd5, mapmd5, 16);

1365 1366
	memset(netbuffer->u.serverinfo.maptitle, 0, sizeof netbuffer->u.serverinfo.maptitle);

1367
	if (mapheaderinfo[gamemap-1] && *mapheaderinfo[gamemap-1]->lvlttl)
toaster committed
1368 1369
	{
		char *read = mapheaderinfo[gamemap-1]->lvlttl, *writ = netbuffer->u.serverinfo.maptitle;
toaster committed
1370
		while (writ < (netbuffer->u.serverinfo.maptitle+32) && *read != '\0')
toaster committed
1371 1372 1373 1374 1375 1376 1377 1378
		{
			if (!(*read & 0x80))
			{
				*writ = toupper(*read);
				writ++;
			}
			read++;
		}
1379
		*writ = '\0';
toaster committed
1380 1381
		//strncpy(netbuffer->u.serverinfo.maptitle, (char *)mapheaderinfo[gamemap-1]->lvlttl, 33);
	}
Alam Ed Arias committed
1382
	else
toaster committed
1383
		strncpy(netbuffer->u.serverinfo.maptitle, "UNKNOWN", 32);
Alam Ed Arias committed
1384

1385
	if (mapheaderinfo[gamemap-1] && !(mapheaderinfo[gamemap-1]->levelflags & LF_NOZONE))
Alam Ed Arias committed
1386 1387 1388 1389
		netbuffer->u.serverinfo.iszone = 1;
	else
		netbuffer->u.serverinfo.iszone = 0;

1390 1391
	if (mapheaderinfo[gamemap-1])
		netbuffer->u.serverinfo.actnum = mapheaderinfo[gamemap-1]->actnum;
Alam Ed Arias committed
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406

	p = PutFileNeeded();

	HSendPacket(node, false, 0, p - ((UINT8 *)&netbuffer->u));
}

static void SV_SendPlayerInfo(INT32 node)
{
	UINT8 i;
	netbuffer->packettype = PT_PLAYERINFO;

	for (i = 0; i < MAXPLAYERS; i++)
	{
		if (!playeringame[i])
		{
1407
			netbuffer->u.playerinfo[i].num = 255; // This slot is empty.
Alam Ed Arias committed
1408 1409 1410
			continue;
		}

1411
		netbuffer->u.playerinfo[i].num = i;
Alam Ed Arias committed
1412 1413 1414 1415
		strncpy(netbuffer->u.playerinfo[i].name, (const char *)&player_names[i], MAXPLAYERNAME+1);
		netbuffer->u.playerinfo[i].name[MAXPLAYERNAME] = '\0';

		//fetch IP address
1416 1417
		//No, don't do that, you fuckface.
		memset(netbuffer->u.playerinfo[i].address, 0, 4);
Alam Ed Arias committed
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435

		if (G_GametypeHasTeams())
		{
			if (!players[i].ctfteam)
				netbuffer->u.playerinfo[i].team = 255;
			else
				netbuffer->u.playerinfo[i].team = (UINT8)players[i].ctfteam;
		}
		else
		{
			if (players[i].spectator)
				netbuffer->u.playerinfo[i].team = 255;
			else
				netbuffer->u.playerinfo[i].team = 0;
		}

		netbuffer->u.playerinfo[i].score = LONG(players[i].score);
		netbuffer->u.playerinfo[i].timeinserver = SHORT((UINT16)(players[i].jointime / TICRATE));
toaster committed
1436 1437 1438 1439 1440
		netbuffer->u.playerinfo[i].skin = (UINT8)(players[i].skin
#ifdef DEVELOP // it's safe to do this only because PLAYERINFO isn't read by the game itself
		% 3
#endif
		);
Alam Ed Arias committed
1441 1442

		// Extra data
1443
		netbuffer->u.playerinfo[i].data = 0; //players[i].skincolor;
Alam Ed Arias committed
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457

		if (players[i].pflags & PF_TAGIT)
			netbuffer->u.playerinfo[i].data |= 0x20;

		if (players[i].gotflag)
			netbuffer->u.playerinfo[i].data |= 0x40;

		if (players[i].powers[pw_super])
			netbuffer->u.playerinfo[i].data |= 0x80;
	}

	HSendPacket(node, false, 0, sizeof(plrinfo) * MAXPLAYERS);
}

1458 1459 1460 1461 1462 1463
/** Sends a PT_SERVERCFG packet
  *
  * \param node The destination
  * \return True if the packet was successfully sent
  *
  */
Alam Ed Arias committed
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
static boolean SV_SendServerConfig(INT32 node)
{
	INT32 i;
	UINT8 *p, *op;
	boolean waspacketsent;

	netbuffer->packettype = PT_SERVERCFG;

	netbuffer->u.servercfg.version = VERSION;
	netbuffer->u.servercfg.subversion = SUBVERSION;

	netbuffer->u.servercfg.serverplayer = (UINT8)serverplayer;
	netbuffer->u.servercfg.totalslotnum = (UINT8)(doomcom->numslots);
	netbuffer->u.servercfg.gametic = (tic_t)LONG(gametic);
	netbuffer->u.servercfg.clientnode = (UINT8)node;
	netbuffer->u.servercfg.gamestate = (UINT8)gamestate;
	netbuffer->u.servercfg.gametype = (UINT8)gametype;
	netbuffer->u.servercfg.modifiedgame = (UINT8)modifiedgame;
Alam Ed Arias committed
1482 1483 1484 1485 1486

	// we fill these structs with FFs so that any players not in game get sent as 0xFFFF
	// which is nice and easy for us to detect
	memset(netbuffer->u.servercfg.playerskins, 0xFF, sizeof(netbuffer->u.servercfg.playerskins));
	memset(netbuffer->u.servercfg.playercolor, 0xFF, sizeof(netbuffer->u.servercfg.playercolor));
1487
	memset(netbuffer->u.servercfg.playeravailabilities, 0xFF, sizeof(netbuffer->u.servercfg.playeravailabilities));
Alam Ed Arias committed
1488

wolfs committed
1489 1490
	memset(netbuffer->u.servercfg.adminplayers, -1, sizeof(netbuffer->u.servercfg.adminplayers));

Alam Ed Arias committed
1491 1492
	for (i = 0; i < MAXPLAYERS; i++)
	{
wolfs committed
1493
		netbuffer->u.servercfg.adminplayers[i] = (SINT8)adminplayers[i];
wolfs committed
1494

Alam Ed Arias committed
1495 1496 1497 1498
		if (!playeringame[i])
			continue;
		netbuffer->u.servercfg.playerskins[i] = (UINT8)players[i].skin;
		netbuffer->u.servercfg.playercolor[i] = (UINT8)players[i].skincolor;
1499
		netbuffer->u.servercfg.playeravailabilities[i] = (UINT32)LONG(players[i].availabilities);
Alam Ed Arias committed
1500 1501
	}

Alam Ed Arias committed
1502
	memcpy(netbuffer->u.servercfg.server_context, server_context, 8);
Alam Ed Arias committed
1503 1504 1505
	op = p = netbuffer->u.servercfg.varlengthinputs;

	CV_SavePlayerNames(&p);
Alam Ed Arias committed
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
	CV_SaveNetVars(&p);
	{
		const size_t len = sizeof (serverconfig_pak) + (size_t)(p - op);

#ifdef DEBUGFILE
		if (debugfile)
		{
			fprintf(debugfile, "ServerConfig Packet about to be sent, size of packet:%s to node:%d\n",
				sizeu1(len), node);
		}
#endif

		waspacketsent = HSendPacket(node, true, 0, len);
	}

#ifdef DEBUGFILE
	if (debugfile)
	{
		if (waspacketsent)
		{
			fprintf(debugfile, "ServerConfig Packet was sent\n");
		}
		else
		{
			fprintf(debugfile, "ServerConfig Packet could not be sent right now\n");
		}
	}
#endif

	return waspacketsent;
}

#ifdef JOININGAME
#define SAVEGAMESIZE (768*1024)

static void SV_SendSaveGame(INT32 node)
{
	size_t length, compressedlen;
	UINT8 *savebuffer;
	UINT8 *compressedsave;
	UINT8 *buffertosend;

	// first save it in a malloced buffer
	savebuffer = (UINT8 *)malloc(SAVEGAMESIZE);
	if (!savebuffer)
	{
		CONS_Alert(CONS_ERROR, M_GetText("No more free memory for savegame\n"));
		return;
	}

	// Leave room for the uncompressed length.
1557
	save_p = savebuffer + sizeof(UINT32);
Alam Ed Arias committed
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578

	P_SaveNetGame();

	length = save_p - savebuffer;
	if (length > SAVEGAMESIZE)
	{
		free(savebuffer);
		save_p = NULL;
		I_Error("Savegame buffer overrun");
	}

	// Allocate space for compressed save: one byte fewer than for the
	// uncompressed data to ensure that the compression is worthwhile.
	compressedsave = malloc(length - 1);
	if (!compressedsave)
	{
		CONS_Alert(CONS_ERROR, M_GetText("No more free memory for savegame\n"));
		return;
	}

	// Attempt to compress it.
1579
	if((compressedlen = lzf_compress(savebuffer + sizeof(UINT32), length - sizeof(UINT32), compressedsave + sizeof(UINT32), length - sizeof(UINT32) - 1)))
Alam Ed Arias committed
1580 1581 1582 1583 1584 1585 1586
	{
		// Compressing succeeded; send compressed data

		free(savebuffer);

		// State that we're compressed.
		buffertosend = compressedsave;
1587 1588
		WRITEUINT32(compressedsave, length - sizeof(UINT32));
		length = compressedlen + sizeof(UINT32);
Alam Ed Arias committed
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
	}
	else
	{
		// Compression failed to make it smaller; send original

		free(compressedsave);

		// State that we're not compressed
		buffertosend = savebuffer;
		WRITEUINT32(savebuffer, 0);
	}

1601
	SV_SendRam(node, buffertosend, length, SF_RAM, 0);
Alam Ed Arias committed
1602
	save_p = NULL;
1603 1604 1605 1606

	// Remember when we started sending the savegame so we can handle timeouts
	sendingsavegame[node] = true;
	freezetimeout[node] = I_GetTime() + jointimeout + length / 1024; // 1 extra tic for each kilobyte
Alam Ed Arias committed
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
}

#ifdef DUMPCONSISTENCY
#define TMPSAVENAME "badmath.sav"
static consvar_t cv_dumpconsistency = {"dumpconsistency", "Off", CV_NETVAR, CV_OnOff, NULL, 0, NULL, NULL, 0, 0, NULL};

static void SV_SavedGame(void)
{
	size_t length;
	UINT8 *savebuffer;
1617
	char tmpsave[256];
Alam Ed Arias committed
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658

	if (!cv_dumpconsistency.value)
		return;

	sprintf(tmpsave, "%s" PATHSEP TMPSAVENAME, srb2home);

	// first save it in a malloced buffer
	save_p = savebuffer = (UINT8 *)malloc(SAVEGAMESIZE);
	if (!save_p)
	{
		CONS_Alert(CONS_ERROR, M_GetText("No more free memory for savegame\n"));
		return;
	}

	P_SaveNetGame();

	length = save_p - savebuffer;
	if (length > SAVEGAMESIZE)
	{
		free(savebuffer);
		save_p = NULL;
		I_Error("Savegame buffer overrun");
	}

	// then save it!
	if (!FIL_WriteFile(tmpsave, savebuffer, length))
		CONS_Printf(M_GetText("Didn't save %s for netgame"), tmpsave);

	free(savebuffer);
	save_p = NULL;
}

#undef  TMPSAVENAME
#endif
#define TMPSAVENAME "$$$.sav"


static void CL_LoadReceivedSavegame(void)
{
	UINT8 *savebuffer = NULL;
	size_t length, decompressedlen;
1659
	char tmpsave[256];
Alam Ed Arias committed
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678

	sprintf(tmpsave, "%s" PATHSEP TMPSAVENAME, srb2home);

	length = FIL_ReadFile(tmpsave, &savebuffer);

	CONS_Printf(M_GetText("Loading savegame length %s\n"), sizeu1(length));
	if (!length)
	{
		I_Error("Can't read savegame sent");
		return;
	}

	save_p = savebuffer;

	// Decompress saved game if necessary.
	decompressedlen = READUINT32(save_p);
	if(decompressedlen > 0)
	{
		UINT8 *decompressedbuffer = Z_Malloc(decompressedlen, PU_STATIC, NULL);
1679
		lzf_decompress(save_p, length - sizeof(UINT32), decompressedbuffer, decompressedlen);
Alam Ed Arias committed
1680 1681 1682 1683 1684 1685
		Z_Free(savebuffer);
		save_p = savebuffer = decompressedbuffer;
	}

	paused = false;
	demoplayback = false;
1686
	titlemapinaction = TITLEMAP_OFF;
Alam Ed Arias committed
1687 1688 1689 1690 1691 1692
	titledemo = false;
	automapactive = false;

	// load a base level
	if (P_LoadNetGame())
	{
1693
		const UINT8 actnum = mapheaderinfo[gamemap-1]->actnum;
Alam Ed Arias committed
1694 1695 1696 1697 1698
		CONS_Printf(M_GetText("Map is now \"%s"), G_BuildMapName(gamemap));
		if (strcmp(mapheaderinfo[gamemap-1]->lvlttl, ""))
		{
			CONS_Printf(": %s", mapheaderinfo[gamemap-1]->lvlttl);
			if (!(mapheaderinfo[gamemap-1]->levelflags & LF_NOZONE))
1699
				CONS_Printf(M_GetText(" Zone"));
Alam Ed Arias committed
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
			if (actnum > 0)
				CONS_Printf(" %2d", actnum);
		}
		CONS_Printf("\"\n");
	}
	else
	{
		CONS_Alert(CONS_ERROR, M_GetText("Can't load the level!\n"));
		Z_Free(savebuffer);
		save_p = NULL;
		if (unlink(tmpsave) == -1)
Alam Ed Arias committed
1711
			CONS_Alert(CONS_ERROR, M_GetText("Can't delete %s\n"), tmpsave);
Alam Ed Arias committed
1712 1713 1714 1715 1716 1717 1718
		return;
	}

	// done
	Z_Free(savebuffer);
	save_p = NULL;
	if (unlink(tmpsave) == -1)
Alam Ed Arias committed
1719
		CONS_Alert(CONS_ERROR, M_GetText("Can't delete %s\n"), tmpsave);
Alam Ed Arias committed
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
	consistancy[gametic%BACKUPTICS] = Consistancy();
	CON_ToggleOff();
}
#endif

#ifndef NONET
static void SendAskInfo(INT32 node, boolean viams)
{
	const tic_t asktime = I_GetTime();
	netbuffer->packettype = PT_ASKINFO;
	netbuffer->u.askinfo.version = VERSION;
	netbuffer->u.askinfo.time = (tic_t)LONG(asktime);

	// Even if this never arrives due to the host being firewalled, we've
	// now allowed traffic from the host to us in, so once the MS relays
	// our address to the host, it'll be able to speak to us.
	HSendPacket(node, false, 0, sizeof (askinfo_pak));

	// Also speak to the MS.
	if (viams && node != 0 && node != BROADCASTADDR)
		SendAskInfoViaMS(node, asktime);
}

serverelem_t serverlist[MAXSERVERLIST];
UINT32 serverlistcount = 0;

1746 1747
#define FORCECLOSE 0x8000

Alam Ed Arias committed
1748 1749 1750 1751 1752 1753 1754
static void SL_ClearServerList(INT32 connectedserver)
{
	UINT32 i;

	for (i = 0; i < serverlistcount; i++)
		if (connectedserver != serverlist[i].node)
		{
1755
			Net_CloseConnection(serverlist[i].node|FORCECLOSE);
Alam Ed Arias committed
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
			serverlist[i].node = 0;
		}
	serverlistcount = 0;
}

static UINT32 SL_SearchServer(INT32 node)
{
	UINT32 i;
	for (i = 0; i < serverlistcount; i++)
		if (serverlist[i].node == node)
			return i;

	return UINT32_MAX;
}

static void SL_InsertServer(serverinfo_pak* info, SINT8 node)
{
	UINT32 i;

	// search if not already on it
	i = SL_SearchServer(node);
	if (i == UINT32_MAX)
	{
		// not found add it
		if (serverlistcount >= MAXSERVERLIST)
			return; // list full

James R. committed
1783 1784 1785 1786 1787 1788
		if (info->_255 != 255)
			return;/* old packet format */

		if (info->packetversion != PACKETVERSION)
			return;/* old new packet format */

Alam Ed Arias committed
1789 1790 1791 1792 1793 1794
		if (info->version != VERSION)
			return; // Not same version.

		if (info->subversion != SUBVERSION)
			return; // Close, but no cigar.

James R. committed
1795 1796 1797
		if (strcmp(info->application, SRB2APPLICATION))
			return;/* that's a different mod */

Alam Ed Arias committed
1798 1799 1800 1801 1802 1803
		i = serverlistcount++;
	}

	serverlist[i].info = *info;
	serverlist[i].node = node;

Alam Ed Arias committed
1804 1805
	// resort server list
	M_SortServerList();
Alam Ed Arias committed
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
}

void CL_UpdateServerList(boolean internetsearch, INT32 room)
{
	SL_ClearServerList(0);

	if (!netgame && I_NetOpenSocket)
	{
		MSCloseUDPSocket();		// Tidy up before wiping the slate.
		if (I_NetOpenSocket())
		{
			netgame = true;
			multiplayer = true;
		}
	}

	// search for local servers
	if (netgame)
		SendAskInfo(BROADCASTADDR, false);

	if (internetsearch)
	{
		const msg_server_t *server_list;
		INT32 i = -1;
		server_list = GetShortServersList(room);
		if (server_list)
		{
			char version[8] = "";
#if VERSION > 0 || SUBVERSION > 0
			snprintf(version, sizeof (version), "%d.%d.%d", VERSION/100, VERSION%100, SUBVERSION);
#else
			strcpy(version, GetRevisionString());
#endif
			version[sizeof (version) - 1] = '\0';

			for (i = 0; server_list[i].header.buffer[0]; i++)
			{
				// Make sure MS version matches our own, to
				// thwart nefarious servers who lie to the MS.

1846
				if (strcmp(version, server_list[i].version) == 0)
Alam Ed Arias committed
1847 1848 1849 1850 1851
				{
					INT32 node = I_NetMakeNodewPort(server_list[i].ip, server_list[i].port);
					if (node == -1)
						break; // no more node free
					SendAskInfo(node, true);
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
					// Force close the connection so that servers can't eat
					// up nodes forever if we never get a reply back from them
					// (usually when they've not forwarded their ports).
					//
					// Don't worry, we'll get in contact with the working
					// servers again when they send SERVERINFO to us later!
					//
					// (Note: as a side effect this probably means every
					// server in the list will probably be using the same node (e.g. node 1),
					// not that it matters which nodes they use when
					// the connections are closed afterwards anyway)
					// -- Monster Iestyn 12/11/18
					Net_CloseConnection(node|FORCECLOSE);
Alam Ed Arias committed
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
				}
			}
		}

		//no server list?(-1) or no servers?(0)
		if (!i)
		{
			; /// TODO: display error or warning?
		}
	}
}

#endif // ifndef NONET

1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
/** Called by CL_ServerConnectionTicker
  *
  * \param viams ???
  * \param asksent ???
  * \return False if the connection was aborted
  * \sa CL_ServerConnectionTicker
  * \sa CL_ConnectToServer
  *
  */
static boolean CL_ServerConnectionSearchTicker(boolean viams, tic_t *asksent)
{
LJ Sonic committed
1890
#ifndef NONET
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
	INT32 i;

	// serverlist is updated by GetPacket function
	if (serverlistcount > 0)
	{
		// this can be a responce to our broadcast request
		if (servernode == -1 || servernode >= MAXNETNODES)
		{
			i = 0;
			servernode = serverlist[i].node;
			CONS_Printf(M_GetText("Found, "));
		}
		else
		{
			i = SL_SearchServer(servernode);
			if (i < 0)
				return true;
		}

		// Quit here rather than downloading files and being refused later.
LJ Sonic committed
1911
		if (serverlist[i].info.refusereason)
1912 1913 1914 1915
		{
			D_QuitNetGame();
			CL_Reset();
			D_StartTitle();
LJ Sonic committed
1916 1917 1918 1919 1920 1921
			if (serverlist[i].info.refusereason == 1)
				M_StartMessage(M_GetText("The server is not accepting\njoins for the moment.\n\nPress ESC\n"), NULL, MM_NOTHING);
			else if (serverlist[i].info.refusereason == 2)
				M_StartMessage(va(M_GetText("Maximum players reached: %d\n\nPress ESC\n"), serverlist[i].info.maxplayer), NULL, MM_NOTHING);
			else
				M_StartMessage(M_GetText("You can't join.\nI don't know why,\nbut you can't join.\n\nPress ESC\n"), NULL, MM_NOTHING);
1922 1923 1924
			return false;
		}