r_data.c 35.2 KB
Newer Older
Alam Ed Arias committed
1 2 3 4
// SONIC ROBO BLAST 2
//-----------------------------------------------------------------------------
// Copyright (C) 1993-1996 by id Software, Inc.
// Copyright (C) 1998-2000 by DooM Legacy Team.
James R. committed
5
// Copyright (C) 1999-2020 by Sonic Team Junior.
Alam Ed Arias committed
6 7 8 9 10 11
//
// 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  r_data.c
Jaime Ita Passos committed
12
/// \brief Preparation of data for rendering, generation of lookups, caching, retrieval by name
Alam Ed Arias committed
13 14 15 16 17 18 19 20 21

#include "doomdef.h"
#include "g_game.h"
#include "i_video.h"
#include "r_local.h"
#include "r_sky.h"
#include "p_local.h"
#include "m_misc.h"
#include "r_data.h"
22
#include "r_textures.h"
Jaime Ita Passos committed
23
#include "r_patch.h"
Jaime Ita Passos committed
24
#include "r_picformats.h"
Alam Ed Arias committed
25 26 27
#include "w_wad.h"
#include "z_zone.h"
#include "p_setup.h" // levelflats
toaster committed
28
#include "v_video.h" // pMasterPalette
Jaime Ita Passos committed
29
#include "f_finale.h" // wipes
Jaime Ita Passos committed
30
#include "byteptr.h"
Alam Ed Arias committed
31 32
#include "dehacked.h"

Monster Iestyn committed
33
#ifdef _WIN32
Alam Ed Arias committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include <malloc.h> // alloca(sizeof)
#endif

//
// Graphics.
// SRB2 graphics for walls and sprites
// is stored in vertical runs of opaque pixels (posts).
// A column is composed of zero or more posts,
// a patch or sprite is composed of zero or more columns.
//

size_t numspritelumps, max_spritelumps;

// needed for pre rendering
sprcache_t *spritecachedinfo;

lighttable_t *colormaps;
Jaime Ita Passos committed
51
lighttable_t *fadecolormap;
Alam Ed Arias committed
52 53

// for debugging/info purposes
I  
Jaime Ita Passos committed
54
size_t flatmemory, spritememory, texturememory;
Alam Ed Arias committed
55 56 57 58 59

// highcolor stuff
INT16 color8to16[256]; // remap color index to highcolor rgb value
INT16 *hicolormaps; // test a 32k colormap remaps high -> high

60 61
// Blends two pixels together, using the equation
// that matches the specified alpha style.
Jaime Ita Passos committed
62
UINT32 ASTBlendPixel(RGBA_t background, RGBA_t foreground, int style, UINT8 alpha)
63 64
{
	RGBA_t output;
Jaime Ita Passos committed
65
	INT16 fullalpha = (alpha - (0xFF - foreground.s.alpha));
66 67
	if (style == AST_TRANSLUCENT)
	{
Jaime Ita Passos committed
68
		if (fullalpha <= 0)
69
			output.rgba = background.rgba;
Jaime Ita Passos committed
70
		else
71
		{
Jaime Ita Passos committed
72 73 74 75 76
			// don't go too high
			if (fullalpha >= 0xFF)
				fullalpha = 0xFF;
			alpha = (UINT8)fullalpha;

Jaime Ita Passos committed
77 78
			// if the background pixel is empty,
			// match software and don't blend anything
Jaime Ita Passos committed
79
			if (!background.s.alpha)
80 81 82 83 84 85 86
			{
				// ...unless the foreground pixel ISN'T actually translucent.
				if (alpha == 0xFF)
					output.rgba = foreground.rgba;
				else
					output.rgba = 0;
			}
Jaime Ita Passos committed
87 88 89 90 91 92 93 94
			else
			{
				UINT8 beta = (0xFF - alpha);
				output.s.red = ((background.s.red * beta) + (foreground.s.red * alpha)) / 0xFF;
				output.s.green = ((background.s.green * beta) + (foreground.s.green * alpha)) / 0xFF;
				output.s.blue = ((background.s.blue * beta) + (foreground.s.blue * alpha)) / 0xFF;
				output.s.alpha = 0xFF;
			}
95
		}
Jaime Ita Passos committed
96
		return output.rgba;
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
	}
#define clamp(c) max(min(c, 0xFF), 0x00);
	else
	{
		float falpha = ((float)alpha / 256.0f);
		float fr = ((float)foreground.s.red * falpha);
		float fg = ((float)foreground.s.green * falpha);
		float fb = ((float)foreground.s.blue * falpha);
		if (style == AST_ADD)
		{
			output.s.red = clamp((int)(background.s.red + fr));
			output.s.green = clamp((int)(background.s.green + fg));
			output.s.blue = clamp((int)(background.s.blue + fb));
		}
		else if (style == AST_SUBTRACT)
		{
			output.s.red = clamp((int)(background.s.red - fr));
			output.s.green = clamp((int)(background.s.green - fg));
			output.s.blue = clamp((int)(background.s.blue - fb));
		}
		else if (style == AST_REVERSESUBTRACT)
		{
			output.s.red = clamp((int)((-background.s.red) + fr));
			output.s.green = clamp((int)((-background.s.green) + fg));
			output.s.blue = clamp((int)((-background.s.blue) + fb));
		}
		else if (style == AST_MODULATE)
		{
			fr = ((float)foreground.s.red / 256.0f);
			fg = ((float)foreground.s.green / 256.0f);
			fb = ((float)foreground.s.blue / 256.0f);
			output.s.red = clamp((int)(background.s.red * fr));
			output.s.green = clamp((int)(background.s.green * fg));
			output.s.blue = clamp((int)(background.s.blue * fb));
		}
		// just copy the pixel
		else if (style == AST_COPY)
Jaime Ita Passos committed
134 135 136 137
			output.rgba = foreground.rgba;

		output.s.alpha = 0xFF;
		return output.rgba;
138 139
	}
#undef clamp
Jaime Ita Passos committed
140
	return 0;
141 142
}

143 144 145 146
INT32 ASTTextureBlendingThreshold[2] = {255/11, (10*255/11)};

// Blends a pixel for a texture patch.
UINT32 ASTBlendTexturePixel(RGBA_t background, RGBA_t foreground, int style, UINT8 alpha)
147
{
Jaime Ita Passos committed
148 149
	// Alpha style set to translucent?
	if (style == AST_TRANSLUCENT)
150
	{
Jaime Ita Passos committed
151
		// Is the alpha small enough for translucency?
152 153 154 155
		if (alpha <= ASTTextureBlendingThreshold[1])
		{
			// Is the patch way too translucent? Don't blend then.
			if (alpha < ASTTextureBlendingThreshold[0])
Jaime Ita Passos committed
156
				return background.rgba;
157

Jaime Ita Passos committed
158
			return ASTBlendPixel(background, foreground, style, alpha);
159 160
		}
		else // just copy the pixel
Jaime Ita Passos committed
161
			return foreground.rgba;
162 163 164 165 166 167 168 169
	}
	else
		return ASTBlendPixel(background, foreground, style, alpha);
}

// Blends two palette indexes for a texture patch, then
// finds the nearest palette index from the blended output.
UINT8 ASTBlendPaletteIndexes(UINT8 background, UINT8 foreground, int style, UINT8 alpha)
170
{
Jaime Ita Passos committed
171 172
	// Alpha style set to translucent?
	if (style == AST_TRANSLUCENT)
173
	{
Jaime Ita Passos committed
174
		// Is the alpha small enough for translucency?
175
		if (alpha <= ASTTextureBlendingThreshold[1])
Jaime Ita Passos committed
176 177
		{
			UINT8 *mytransmap;
Jaime Ita Passos committed
178
			INT32 trans;
179

Jaime Ita Passos committed
180
			// Is the patch way too translucent? Don't blend then.
181
			if (alpha < ASTTextureBlendingThreshold[0])
Jaime Ita Passos committed
182
				return background;
183

Jaime Ita Passos committed
184
			// The equation's not exact but it works as intended. I'll call it a day for now.
Jaime Ita Passos committed
185 186
			trans = (8*(alpha) + 255/8)/(255 - 255/11);
			mytransmap = R_GetTranslucencyTable(trans + 1);
Jaime Ita Passos committed
187 188 189 190 191
			if (background != 0xFF)
				return *(mytransmap + (background<<8) + foreground);
		}
		else // just copy the pixel
			return foreground;
192 193 194
	}
	// just copy the pixel
	else if (style == AST_COPY)
Jaime Ita Passos committed
195
		return foreground;
196 197 198 199 200
	// use ASTBlendPixel for all other blend modes
	// and find the nearest colour in the palette
	else if (style != AST_TRANSLUCENT)
	{
		RGBA_t texel;
201 202
		RGBA_t bg = V_GetMasterColor(background);
		RGBA_t fg = V_GetMasterColor(foreground);
Jaime Ita Passos committed
203
		texel.rgba = ASTBlendPixel(bg, fg, style, alpha);
204 205 206 207 208 209 210
		return NearestColor(texel.s.red, texel.s.green, texel.s.blue);
	}
	// fallback if all above fails, somehow
	// return the background pixel
	return background;
}

211 212 213 214
#ifdef EXTRACOLORMAPLUMPS
static lumplist_t *colormaplumps = NULL; ///\todo free leak
static size_t numcolormaplumps = 0;

Alam Ed Arias committed
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
static inline lumpnum_t R_CheckNumForNameList(const char *name, lumplist_t *list, size_t listsize)
{
	size_t i;
	UINT16 lump;

	for (i = listsize - 1; i < INT16_MAX; i--)
	{
		lump = W_CheckNumForNamePwad(name, list[i].wadfile, list[i].firstlump);
		if (lump == INT16_MAX || lump > (list[i].firstlump + list[i].numlumps))
			continue;
		else
			return (list[i].wadfile<<16)+lump;
	}
	return LUMPERROR;
}

static void R_InitExtraColormaps(void)
{
	lumpnum_t startnum, endnum;
	UINT16 cfile, clump;
	static size_t maxcolormaplumps = 16;

	for (cfile = clump = 0; cfile < numwadfiles; cfile++, clump = 0)
	{
		startnum = W_CheckNumForNamePwad("C_START", cfile, clump);
240
		if (startnum == INT16_MAX)
Alam Ed Arias committed
241 242 243 244
			continue;

		endnum = W_CheckNumForNamePwad("C_END", cfile, clump);

245
		if (endnum == INT16_MAX)
Alam Ed Arias committed
246 247
			I_Error("R_InitExtraColormaps: C_START without C_END\n");

248 249 250
		// This shouldn't be possible when you use the Pwad function, silly
		//if (WADFILENUM(startnum) != WADFILENUM(endnum))
			//I_Error("R_InitExtraColormaps: C_START and C_END in different wad files!\n");
Alam Ed Arias committed
251 252 253 254 255

		if (numcolormaplumps >= maxcolormaplumps)
			maxcolormaplumps *= 2;
		colormaplumps = Z_Realloc(colormaplumps,
			sizeof (*colormaplumps) * maxcolormaplumps, PU_STATIC, NULL);
256 257
		colormaplumps[numcolormaplumps].wadfile = cfile;
		colormaplumps[numcolormaplumps].firstlump = startnum+1;
Alam Ed Arias committed
258 259 260 261 262
		colormaplumps[numcolormaplumps].numlumps = endnum - (startnum + 1);
		numcolormaplumps++;
	}
	CONS_Printf(M_GetText("Number of Extra Colormaps: %s\n"), sizeu1(numcolormaplumps));
}
263
#endif
Alam Ed Arias committed
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

//
// R_InitSpriteLumps
// Finds the width and hoffset of all sprites in the wad, so the sprite does not need to be
// cached completely, just for having the header info ready during rendering.
//

//
// allocate sprite lookup tables
//
static void R_InitSpriteLumps(void)
{
	numspritelumps = 0;
	max_spritelumps = 8192;

	Z_Malloc(max_spritelumps*sizeof(*spritecachedinfo), PU_STATIC, &spritecachedinfo);
}

Jaime Ita Passos committed
282 283 284
//
// R_CreateFadeColormaps
//
Jaime Ita Passos committed
285

286
static void R_CreateFadeColormaps(void)
Jaime Ita Passos committed
287 288 289 290
{
	UINT8 px, fade;
	RGBA_t rgba;
	INT32 r, g, b;
Jaime Ita Passos committed
291
	size_t len, i;
Jaime Ita Passos committed
292

Jaime Ita Passos committed
293
	len = (256 * FADECOLORMAPROWS);
Jaime Ita Passos committed
294
	fadecolormap = Z_MallocAlign(len*2, PU_STATIC, NULL, 8);
Jaime Ita Passos committed
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
	for (i = 0; i < len*2; i++)
		fadecolormap[i] = (i%256);

	// Load in the light tables, now 64k aligned for smokie...
	{
		lumpnum_t lump = W_CheckNumForName("FADECMAP");
		lumpnum_t wlump = W_CheckNumForName("FADEWMAP");

		// to black
		if (lump != LUMPERROR)
			W_ReadLumpHeader(lump, fadecolormap, len, 0U);
		// to white
		if (wlump != LUMPERROR)
			W_ReadLumpHeader(wlump, fadecolormap+len, len, 0U);

		// missing "to white" colormap lump
		if (lump != LUMPERROR && wlump == LUMPERROR)
			goto makewhite;
		// missing "to black" colormap lump
		else if (lump == LUMPERROR && wlump != LUMPERROR)
			goto makeblack;
		// both lumps found
		else if (lump != LUMPERROR && wlump != LUMPERROR)
			return;
	}
Jaime Ita Passos committed
320 321 322

#define GETCOLOR \
	px = colormaps[i%256]; \
Jaime Ita Passos committed
323
	fade = (i/256) * (256 / FADECOLORMAPROWS); \
324
	rgba = V_GetMasterColor(px);
Jaime Ita Passos committed
325 326

	// to black
Jaime Ita Passos committed
327
	makeblack:
Jaime Ita Passos committed
328 329 330 331 332 333
	for (i = 0; i < len; i++)
	{
		// find pixel and fade amount
		GETCOLOR;

		// subtractive color blending
Jaime Ita Passos committed
334 335 336
		r = rgba.s.red - FADEREDFACTOR*fade/10;
		g = rgba.s.green - FADEGREENFACTOR*fade/10;
		b = rgba.s.blue - FADEBLUEFACTOR*fade/10;
Jaime Ita Passos committed
337 338 339 340 341 342 343 344 345 346 347

		// clamp values
		if (r < 0) r = 0;
		if (g < 0) g = 0;
		if (b < 0) b = 0;

		// find nearest color in palette
		fadecolormap[i] = NearestColor(r,g,b);
	}

	// to white
Jaime Ita Passos committed
348
	makewhite:
Jaime Ita Passos committed
349 350 351 352 353 354
	for (i = len; i < len*2; i++)
	{
		// find pixel and fade amount
		GETCOLOR;

		// additive color blending
Jaime Ita Passos committed
355 356 357
		r = rgba.s.red + FADEREDFACTOR*fade/10;
		g = rgba.s.green + FADEGREENFACTOR*fade/10;
		b = rgba.s.blue + FADEBLUEFACTOR*fade/10;
Jaime Ita Passos committed
358 359 360 361 362 363 364 365 366 367 368 369

		// clamp values
		if (r > 255) r = 255;
		if (g > 255) g = 255;
		if (b > 255) b = 255;

		// find nearest color in palette
		fadecolormap[i] = NearestColor(r,g,b);
	}
#undef GETCOLOR
}

Alam Ed Arias committed
370 371 372 373 374
//
// R_InitColormaps
//
static void R_InitColormaps(void)
{
Jaime Ita Passos committed
375
	size_t len;
Alam Ed Arias committed
376 377 378 379
	lumpnum_t lump;

	// Load in the light tables
	lump = W_GetNumForName("COLORMAP");
Jaime Ita Passos committed
380 381
	len = W_LumpLength(lump);
	colormaps = Z_MallocAlign(len, PU_STATIC, NULL, 8);
Alam Ed Arias committed
382 383
	W_ReadLump(lump, colormaps);

Jaime Ita Passos committed
384
	// Make colormap for fades
Jaime Ita Passos committed
385
	R_CreateFadeColormaps();
Jaime Ita Passos committed
386

Alam Ed Arias committed
387 388
	// Init Boom colormaps.
	R_ClearColormaps();
389
#ifdef EXTRACOLORMAPLUMPS
Alam Ed Arias committed
390
	R_InitExtraColormaps();
391
#endif
Alam Ed Arias committed
392 393 394 395 396 397
}

void R_ReInitColormaps(UINT16 num)
{
	char colormap[9] = "COLORMAP";
	lumpnum_t lump;
398
	const lumpnum_t basecolormaplump = W_GetNumForName(colormap);
Alam Ed Arias committed
399
	if (num > 0 && num <= 10000)
Alam Ed Arias committed
400 401 402 403 404
		snprintf(colormap, 8, "CLM%04u", num-1);

	// Load in the light tables, now 64k aligned for smokie...
	lump = W_GetNumForName(colormap);
	if (lump == LUMPERROR)
405
		lump = basecolormaplump;
406 407
	else
	{
408
		if (W_LumpLength(lump) != W_LumpLength(basecolormaplump))
409
		{
410
			CONS_Alert(CONS_WARNING, "%s lump size does not match COLORMAP, results may be unexpected.\n", colormap);
411 412 413
		}
	}

414
	W_ReadLumpHeader(lump, colormaps, W_LumpLength(basecolormaplump), 0U);
Jaime Ita Passos committed
415 416
	if (fadecolormap)
		Z_Free(fadecolormap);
Jaime Ita Passos committed
417
	R_CreateFadeColormaps();
Alam Ed Arias committed
418 419 420 421 422 423 424 425 426 427 428 429

	// Init Boom colormaps.
	R_ClearColormaps();
}

//
// R_ClearColormaps
//
// Clears out extra colormaps between levels.
//
void R_ClearColormaps(void)
{
430 431 432
	// Purged by PU_LEVEL, just overwrite the pointer
	extra_colormaps = R_CreateDefaultColormap(true);
}
Alam Ed Arias committed
433

434 435
//
// R_CreateDefaultColormap()
436
// NOTE: The result colormap is not added to the extra_colormaps chain. You must do that yourself!
437 438 439 440
//
extracolormap_t *R_CreateDefaultColormap(boolean lighttable)
{
	extracolormap_t *exc = Z_Calloc(sizeof (*exc), PU_LEVEL, NULL);
441 442
	exc->fadestart = 0;
	exc->fadeend = 31;
443
	exc->flags = 0;
444 445
	exc->rgba = 0;
	exc->fadergba = 0x19000000;
446
	exc->colormap = lighttable ? R_CreateLightTable(exc) : NULL;
447 448 449 450 451
#ifdef EXTRACOLORMAPLUMPS
	exc->lump = LUMPERROR;
	exc->lumpname[0] = 0;
#endif
	exc->next = exc->prev = NULL;
452
	return exc;
Marco Z committed
453
}
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
//
// R_GetDefaultColormap()
//
extracolormap_t *R_GetDefaultColormap(void)
{
#ifdef COLORMAPREVERSELIST
	extracolormap_t *exc;
#endif

	if (!extra_colormaps)
		return (extra_colormaps = R_CreateDefaultColormap(true));

#ifdef COLORMAPREVERSELIST
	for (exc = extra_colormaps; exc->next; exc = exc->next);
	return exc;
#else
	return extra_colormaps;
#endif
}

//
Marco Z committed
476
// R_CopyColormap()
477
// NOTE: The result colormap is not added to the extra_colormaps chain. You must do that yourself!
478
//
Marco Z committed
479
extracolormap_t *R_CopyColormap(extracolormap_t *extra_colormap, boolean lighttable)
480
{
Marco Z committed
481 482
	extracolormap_t *exc = Z_Calloc(sizeof (*exc), PU_LEVEL, NULL);

483
	if (!extra_colormap)
Marco Z committed
484 485 486 487 488
		extra_colormap = R_GetDefaultColormap();

	*exc = *extra_colormap;
	exc->next = exc->prev = NULL;

489
#ifdef EXTRACOLORMAPLUMPS
Marco Z committed
490 491 492 493 494 495 496 497 498
	strncpy(exc->lumpname, extra_colormap->lumpname, 9);

	if (exc->lump != LUMPERROR && lighttable)
	{
		// aligned on 8 bit for asm code
		exc->colormap = Z_MallocAlign(W_LumpLength(lump), PU_LEVEL, NULL, 16);
		W_ReadLump(lump, exc->colormap);
	}
	else
499
#endif
Marco Z committed
500 501 502 503 504 505
	if (lighttable)
		exc->colormap = R_CreateLightTable(exc);
	else
		exc->colormap = NULL;

	return exc;
506 507
}

Marco Z committed
508 509 510 511 512 513 514 515
//
// R_AddColormapToList
//
// Sets prev/next chain for extra_colormaps var
// Copypasta from P_AddFFloorToList
//
void R_AddColormapToList(extracolormap_t *extra_colormap)
{
516
#ifndef COLORMAPREVERSELIST
Marco Z committed
517
	extracolormap_t *exc;
518
#endif
Alam Ed Arias committed
519

Marco Z committed
520 521 522 523 524 525 526 527
	if (!extra_colormaps)
	{
		extra_colormaps = extra_colormap;
		extra_colormap->next = 0;
		extra_colormap->prev = 0;
		return;
	}

528 529 530 531 532 533
#ifdef COLORMAPREVERSELIST
	extra_colormaps->prev = extra_colormap;
	extra_colormap->next = extra_colormaps;
	extra_colormaps = extra_colormap;
	extra_colormap->prev = 0;
#else
Marco Z committed
534 535 536 537 538
	for (exc = extra_colormaps; exc->next; exc = exc->next);

	exc->next = extra_colormap;
	extra_colormap->prev = exc;
	extra_colormap->next = 0;
539
#endif
Alam Ed Arias committed
540 541
}

Marco Z committed
542
//
543
// R_CheckDefaultColormapByValues()
Marco Z committed
544
//
545 546
#ifdef EXTRACOLORMAPLUMPS
boolean R_CheckDefaultColormapByValues(boolean checkrgba, boolean checkfadergba, boolean checkparams,
547
	INT32 rgba, INT32 fadergba, UINT8 fadestart, UINT8 fadeend, UINT8 flags, lumpnum_t lump)
548 549
#else
boolean R_CheckDefaultColormapByValues(boolean checkrgba, boolean checkfadergba, boolean checkparams,
550
	INT32 rgba, INT32 fadergba, UINT8 fadestart, UINT8 fadeend, UINT8 flags)
551 552 553 554 555 556
#endif
{
	return (
		(!checkparams ? true :
			(fadestart == 0
				&& fadeend == 31
557
				&& !flags)
558 559 560 561 562 563 564 565 566 567 568
			)
		&& (!checkrgba ? true : rgba == 0)
		&& (!checkfadergba ? true : fadergba == 0x19000000)
#ifdef EXTRACOLORMAPLUMPS
		&& lump == LUMPERROR
		&& extra_colormap->lumpname[0] == 0
#endif
		);
}

boolean R_CheckDefaultColormap(extracolormap_t *extra_colormap, boolean checkrgba, boolean checkfadergba, boolean checkparams)
Marco Z committed
569 570 571
{
	if (!extra_colormap)
		return true;
572

Marco Z committed
573
#ifdef EXTRACOLORMAPLUMPS
574
	return R_CheckDefaultColormapByValues(checkrgba, checkfadergba, checkparams, extra_colormap->rgba, extra_colormap->fadergba, extra_colormap->fadestart, extra_colormap->fadeend, extra_colormap->flags, extra_colormap->lump);
575
#else
576
	return R_CheckDefaultColormapByValues(checkrgba, checkfadergba, checkparams, extra_colormap->rgba, extra_colormap->fadergba, extra_colormap->fadestart, extra_colormap->fadeend, extra_colormap->flags);
Marco Z committed
577 578 579
#endif
}

580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
boolean R_CheckEqualColormaps(extracolormap_t *exc_a, extracolormap_t *exc_b, boolean checkrgba, boolean checkfadergba, boolean checkparams)
{
	// Treat NULL as default colormap
	// We need this because what if one exc is a default colormap, and the other is NULL? They're really both equal.
	if (!exc_a)
		exc_a = R_GetDefaultColormap();
	if (!exc_b)
		exc_b = R_GetDefaultColormap();

	if (exc_a == exc_b)
		return true;

	return (
		(!checkparams ? true :
			(exc_a->fadestart == exc_b->fadestart
				&& exc_a->fadeend == exc_b->fadeend
596
				&& exc_a->flags == exc_b->flags)
597 598 599 600 601 602 603 604 605 606
			)
		&& (!checkrgba ? true : exc_a->rgba == exc_b->rgba)
		&& (!checkfadergba ? true : exc_a->fadergba == exc_b->fadergba)
#ifdef EXTRACOLORMAPLUMPS
		&& exc_a->lump == exc_b->lump
		&& !strncmp(exc_a->lumpname, exc_b->lumpname, 9)
#endif
		);
}

607 608 609 610 611
//
// R_GetColormapFromListByValues()
// NOTE: Returns NULL if no match is found
//
#ifdef EXTRACOLORMAPLUMPS
612
extracolormap_t *R_GetColormapFromListByValues(INT32 rgba, INT32 fadergba, UINT8 fadestart, UINT8 fadeend, UINT8 flags, lumpnum_t lump)
613
#else
614
extracolormap_t *R_GetColormapFromListByValues(INT32 rgba, INT32 fadergba, UINT8 fadestart, UINT8 fadeend, UINT8 flags)
615 616 617
#endif
{
	extracolormap_t *exc;
618
	UINT32 dbg_i = 0;
619 620 621 622 623 624 625

	for (exc = extra_colormaps; exc; exc = exc->next)
	{
		if (rgba == exc->rgba
			&& fadergba == exc->fadergba
			&& fadestart == exc->fadestart
			&& fadeend == exc->fadeend
626
			&& flags == exc->flags
627 628 629 630 631 632
#ifdef EXTRACOLORMAPLUMPS
			&& (lump != LUMPERROR && lump == exc->lump)
#endif
		)
		{
			CONS_Debug(DBG_RENDER, "Found Colormap %d: rgba(%d,%d,%d,%d) fadergba(%d,%d,%d,%d)\n",
633 634
				dbg_i, R_GetRgbaR(rgba), R_GetRgbaG(rgba), R_GetRgbaB(rgba), R_GetRgbaA(rgba),
				R_GetRgbaR(fadergba), R_GetRgbaG(fadergba), R_GetRgbaB(fadergba), R_GetRgbaA(fadergba));
635 636 637 638 639 640 641 642 643 644
			return exc;
		}
		dbg_i++;
	}
	return NULL;
}

extracolormap_t *R_GetColormapFromList(extracolormap_t *extra_colormap)
{
#ifdef EXTRACOLORMAPLUMPS
645
	return R_GetColormapFromListByValues(extra_colormap->rgba, extra_colormap->fadergba, extra_colormap->fadestart, extra_colormap->fadeend, extra_colormap->flags, extra_colormap->lump);
Marco Z committed
646
#else
647
	return R_GetColormapFromListByValues(extra_colormap->rgba, extra_colormap->fadergba, extra_colormap->fadestart, extra_colormap->fadeend, extra_colormap->flags);
648 649 650
#endif
}

651
#ifdef EXTRACOLORMAPLUMPS
Marco Z committed
652
extracolormap_t *R_ColormapForName(char *name)
Alam Ed Arias committed
653
{
Marco Z committed
654 655
	lumpnum_t lump;
	extracolormap_t *exc;
Alam Ed Arias committed
656 657 658

	lump = R_CheckNumForNameList(name, colormaplumps, numcolormaplumps);
	if (lump == LUMPERROR)
Marco Z committed
659
		I_Error("R_ColormapForName: Cannot find colormap lump %.8s\n", name);
Alam Ed Arias committed
660

661 662 663
	exc = R_GetColormapFromListByValues(0, 0x19000000, 0, 31, 0, lump);
	if (exc)
		return exc;
Marco Z committed
664 665

	exc = Z_Calloc(sizeof (*exc), PU_LEVEL, NULL);
Alam Ed Arias committed
666

Marco Z committed
667
	exc->lump = lump;
668 669
	strncpy(exc->lumpname, name, 9);
	exc->lumpname[8] = 0;
Alam Ed Arias committed
670 671

	// aligned on 8 bit for asm code
Marco Z committed
672 673
	exc->colormap = Z_MallocAlign(W_LumpLength(lump), PU_LEVEL, NULL, 16);
	W_ReadLump(lump, exc->colormap);
Alam Ed Arias committed
674 675 676

	// We set all params of the colormap to normal because there
	// is no real way to tell how GL should handle a colormap lump anyway..
Marco Z committed
677 678
	exc->fadestart = 0;
	exc->fadeend = 31;
679
	exc->flags = 0;
680 681 682 683
	exc->rgba = 0;
	exc->fadergba = 0x19000000;

	R_AddColormapToList(exc);
Marco Z committed
684 685

	return exc;
Alam Ed Arias committed
686
}
687
#endif
Alam Ed Arias committed
688 689

//
MascaraSnake committed
690
// R_CreateColormapFromLinedef
Alam Ed Arias committed
691 692 693 694 695 696 697 698 699 700
//
// This is a more GL friendly way of doing colormaps: Specify colormap
// data in a special linedef's texture areas and use that to generate
// custom colormaps at runtime. NOTE: For GL mode, we only need to color
// data and not the colormap data.
//
static double deltas[256][3], map[256][3];

static int RoundUp(double number);

Marco Z committed
701
lighttable_t *R_CreateLightTable(extracolormap_t *extra_colormap)
Alam Ed Arias committed
702
{
703 704 705
	double cmaskr, cmaskg, cmaskb, cdestr, cdestg, cdestb;
	double maskamt = 0, othermask = 0;

706 707 708 709 710 711 712 713
	UINT8 cr = R_GetRgbaR(extra_colormap->rgba),
		cg = R_GetRgbaG(extra_colormap->rgba),
		cb = R_GetRgbaB(extra_colormap->rgba),
		ca = R_GetRgbaA(extra_colormap->rgba),
		cfr = R_GetRgbaR(extra_colormap->fadergba),
		cfg = R_GetRgbaG(extra_colormap->fadergba),
		cfb = R_GetRgbaB(extra_colormap->fadergba);
//		cfa = R_GetRgbaA(extra_colormap->fadergba); // unused in software
714

715 716
	UINT8 fadestart = extra_colormap->fadestart,
		fadedist = extra_colormap->fadeend - extra_colormap->fadestart;
Alam Ed Arias committed
717

Marco Z committed
718 719
	lighttable_t *lighttable = NULL;
	size_t i;
Alam Ed Arias committed
720

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
	/////////////////////
	// Calc the RGBA mask
	/////////////////////
	cmaskr = cr;
	cmaskg = cg;
	cmaskb = cb;

	maskamt = (double)(ca/24.0l);
	othermask = 1 - maskamt;
	maskamt /= 0xff;

	cmaskr *= maskamt;
	cmaskg *= maskamt;
	cmaskb *= maskamt;

	/////////////////////
	// Calc the RGBA fade mask
	/////////////////////
	cdestr = cfr;
	cdestg = cfg;
	cdestb = cfb;

	// fade alpha unused in software
	// maskamt = (double)(cfa/24.0l);
	// othermask = 1 - maskamt;
	// maskamt /= 0xff;

	// cdestr *= maskamt;
	// cdestg *= maskamt;
	// cdestb *= maskamt;

	/////////////////////
753
	// This code creates the colormap array used by software renderer
754
	/////////////////////
Alam Ed Arias committed
755
	{
756 757 758 759 760 761 762 763 764
		double r, g, b, cbrightness;
		int p;
		char *colormap_p;

		// Initialise the map and delta arrays
		// map[i] stores an RGB color (as double) for index i,
		//  which is then converted to SRB2's palette later
		// deltas[i] stores a corresponding fade delta between the RGB color and the final fade color;
		//  map[i]'s values are decremented by after each use
Alam Ed Arias committed
765 766
		for (i = 0; i < 256; i++)
		{
toaster committed
767 768 769
			r = pMasterPalette[i].s.red;
			g = pMasterPalette[i].s.green;
			b = pMasterPalette[i].s.blue;
Alam Ed Arias committed
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
			cbrightness = sqrt((r*r) + (g*g) + (b*b));

			map[i][0] = (cbrightness * cmaskr) + (r * othermask);
			if (map[i][0] > 255.0l)
				map[i][0] = 255.0l;
			deltas[i][0] = (map[i][0] - cdestr) / (double)fadedist;

			map[i][1] = (cbrightness * cmaskg) + (g * othermask);
			if (map[i][1] > 255.0l)
				map[i][1] = 255.0l;
			deltas[i][1] = (map[i][1] - cdestg) / (double)fadedist;

			map[i][2] = (cbrightness * cmaskb) + (b * othermask);
			if (map[i][2] > 255.0l)
				map[i][2] = 255.0l;
			deltas[i][2] = (map[i][2] - cdestb) / (double)fadedist;
		}

788
		// Now allocate memory for the actual colormap array itself!
Marco Z committed
789
		// aligned on 8 bit for asm code
Alam Ed Arias committed
790
		colormap_p = Z_MallocAlign((256 * 34) + 10, PU_LEVEL, NULL, 8);
Marco Z committed
791
		lighttable = (UINT8 *)colormap_p;
Alam Ed Arias committed
792

793 794
		// Calculate the palette index for each palette index, for each light level
		// (as well as the two unused colormap lines we inherited from Doom)
Alam Ed Arias committed
795 796 797 798 799 800 801 802 803 804 805
		for (p = 0; p < 34; p++)
		{
			for (i = 0; i < 256; i++)
			{
				*colormap_p = NearestColor((UINT8)RoundUp(map[i][0]),
					(UINT8)RoundUp(map[i][1]),
					(UINT8)RoundUp(map[i][2]));
				colormap_p++;

				if ((UINT32)p < fadestart)
					continue;
806
#define ABS2(x) ((x) < 0 ? -(x) : (x))
Alam Ed Arias committed
807 808 809 810 811 812 813 814 815 816 817 818 819 820
				if (ABS2(map[i][0] - cdestr) > ABS2(deltas[i][0]))
					map[i][0] -= deltas[i][0];
				else
					map[i][0] = cdestr;

				if (ABS2(map[i][1] - cdestg) > ABS2(deltas[i][1]))
					map[i][1] -= deltas[i][1];
				else
					map[i][1] = cdestg;

				if (ABS2(map[i][2] - cdestb) > ABS2(deltas[i][1]))
					map[i][2] -= deltas[i][2];
				else
					map[i][2] = cdestb;
821
#undef ABS2
Alam Ed Arias committed
822 823 824 825
			}
		}
	}

Marco Z committed
826 827 828
	return lighttable;
}

MascaraSnake committed
829
extracolormap_t *R_CreateColormapFromLinedef(char *p1, char *p2, char *p3)
Marco Z committed
830
{
831 832
	// default values
	UINT8 cr = 0, cg = 0, cb = 0, ca = 0, cfr = 0, cfg = 0, cfb = 0, cfa = 25;
833
	UINT32 fadestart = 0, fadeend = 31;
834
	UINT8 flags = 0;
835
	INT32 rgba = 0, fadergba = 0x19000000;
Marco Z committed
836 837

#define HEX2INT(x) (UINT32)(x >= '0' && x <= '9' ? x - '0' : x >= 'a' && x <= 'f' ? x - 'a' + 10 : x >= 'A' && x <= 'F' ? x - 'A' + 10 : 0)
Marco Z committed
838
#define ALPHA2INT(x) (x >= 'a' && x <= 'z' ? x - 'a' : x >= 'A' && x <= 'Z' ? x - 'A' : x >= '0' && x <= '9' ? 25 : 0)
839 840 841 842 843 844 845 846 847 848 849 850

	// Get base colormap value
	// First alpha-only, then full value
	if (p1[0] >= 'a' && p1[0] <= 'z' && !p1[1])
		ca = (p1[0] - 'a');
	else if (p1[0] == '#' && p1[1] >= 'a' && p1[1] <= 'z' && !p1[2])
		ca = (p1[1] - 'a');
	else if (p1[0] >= 'A' && p1[0] <= 'Z' && !p1[1])
		ca = (p1[0] - 'A');
	else if (p1[0] == '#' && p1[1] >= 'A' && p1[1] <= 'Z' && !p1[2])
		ca = (p1[1] - 'A');
	else if (p1[0] == '#')
Marco Z committed
851
	{
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
		// For each subsequent value, the value before it must exist
		// If we don't get every value, then set alpha to max
		if (p1[1] && p1[2])
		{
			cr = ((HEX2INT(p1[1]) * 16) + HEX2INT(p1[2]));
			if (p1[3] && p1[4])
			{
				cg = ((HEX2INT(p1[3]) * 16) + HEX2INT(p1[4]));
				if (p1[5] && p1[6])
				{
					cb = ((HEX2INT(p1[5]) * 16) + HEX2INT(p1[6]));

					if (p1[7] >= 'a' && p1[7] <= 'z')
						ca = (p1[7] - 'a');
					else if (p1[7] >= 'A' && p1[7] <= 'Z')
						ca = (p1[7] - 'A');
					else
						ca = 25;
				}
				else
					ca = 25;
			}
			else
				ca = 25;
		}
Marco Z committed
877
		else
878
			ca = 25;
Marco Z committed
879 880 881
	}

#define NUMFROMCHAR(c) (c >= '0' && c <= '9' ? c - '0' : 0)
882

883
	// Get parameters like fadestart, fadeend, and flags
Marco Z committed
884 885
	if (p2[0] == '#')
	{
886 887
		if (p2[1])
		{
888
			flags = NUMFROMCHAR(p2[1]);
889 890 891 892 893 894 895 896
			if (p2[2] && p2[3])
			{
				fadestart = NUMFROMCHAR(p2[3]) + (NUMFROMCHAR(p2[2]) * 10);
				if (p2[4] && p2[5])
					fadeend = NUMFROMCHAR(p2[5]) + (NUMFROMCHAR(p2[4]) * 10);
			}
		}

Marco Z committed
897 898 899 900 901
		if (fadestart > 30)
			fadestart = 0;
		if (fadeend > 31 || fadeend < 1)
			fadeend = 31;
	}
902

Marco Z committed
903 904
#undef NUMFROMCHAR

905 906 907 908 909 910 911 912 913 914 915
	// Get fade (dark) colormap value
	// First alpha-only, then full value
	if (p3[0] >= 'a' && p3[0] <= 'z' && !p3[1])
		cfa = (p3[0] - 'a');
	else if (p3[0] == '#' && p3[1] >= 'a' && p3[1] <= 'z' && !p3[2])
		cfa = (p3[1] - 'a');
	else if (p3[0] >= 'A' && p3[0] <= 'Z' && !p3[1])
		cfa = (p3[0] - 'A');
	else if (p3[0] == '#' && p3[1] >= 'A' && p3[1] <= 'Z' && !p3[2])
		cfa = (p3[1] - 'A');
	else if (p3[0] == '#')
Marco Z committed
916
	{
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
		// For each subsequent value, the value before it must exist
		// If we don't get every value, then set alpha to max
		if (p3[1] && p3[2])
		{
			cfr = ((HEX2INT(p3[1]) * 16) + HEX2INT(p3[2]));
			if (p3[3] && p3[4])
			{
				cfg = ((HEX2INT(p3[3]) * 16) + HEX2INT(p3[4]));
				if (p3[5] && p3[6])
				{
					cfb = ((HEX2INT(p3[5]) * 16) + HEX2INT(p3[6]));

					if (p3[7] >= 'a' && p3[7] <= 'z')
						cfa = (p3[7] - 'a');
					else if (p3[7] >= 'A' && p3[7] <= 'Z')
						cfa = (p3[7] - 'A');
					else
						cfa = 25;
				}
				else
					cfa = 25;
			}
			else
				cfa = 25;
		}
942
		else
943
			cfa = 25;
Marco Z committed
944
	}
Marco Z committed
945
#undef ALPHA2INT
Marco Z committed
946 947
#undef HEX2INT

948 949
	// Pack rgba values into combined var
	// OpenGL also uses this instead of lighttables for rendering
950 951
	rgba = R_PutRgbaRGBA(cr, cg, cb, ca);
	fadergba = R_PutRgbaRGBA(cfr, cfg, cfb, cfa);
952

MascaraSnake committed
953 954 955 956 957 958 959
	return R_CreateColormap(rgba, fadergba, fadestart, fadeend, flags);
}

extracolormap_t *R_CreateColormap(INT32 rgba, INT32 fadergba, UINT8 fadestart, UINT8 fadeend, UINT8 flags)
{
	extracolormap_t *extra_colormap;

960 961
	// Did we just make a default colormap?
#ifdef EXTRACOLORMAPLUMPS
962
	if (R_CheckDefaultColormapByValues(true, true, true, rgba, fadergba, fadestart, fadeend, flags, LUMPERROR))
963 964
		return NULL;
#else
965
	if (R_CheckDefaultColormapByValues(true, true, true, rgba, fadergba, fadestart, fadeend, flags))
966 967 968
		return NULL;
#endif

969
	// Look for existing colormaps
970
#ifdef EXTRACOLORMAPLUMPS
MascaraSnake committed
971
	extra_colormap = R_GetColormapFromListByValues(rgba, fadergba, fadestart, fadeend, flags, LUMPERROR);
972
#else
MascaraSnake committed
973
	extra_colormap = R_GetColormapFromListByValues(rgba, fadergba, fadestart, fadeend, flags);
974
#endif
MascaraSnake committed
975 976
	if (extra_colormap)
		return extra_colormap;
Marco Z committed
977

MascaraSnake committed
978
	CONS_Debug(DBG_RENDER, "Creating Colormap: rgba(%x) fadergba(%x)\n", rgba, fadergba);
979

MascaraSnake committed
980
	extra_colormap = Z_Calloc(sizeof(*extra_colormap), PU_LEVEL, NULL);
Marco Z committed
981 982 983

	extra_colormap->fadestart = (UINT16)fadestart;
	extra_colormap->fadeend = (UINT16)fadeend;
984
	extra_colormap->flags = flags;
Marco Z committed
985 986 987 988

	extra_colormap->rgba = rgba;
	extra_colormap->fadergba = fadergba;

989
#ifdef EXTRACOLORMAPLUMPS
Marco Z committed
990
	extra_colormap->lump = LUMPERROR;
991 992
	extra_colormap->lumpname[0] = 0;
#endif
Marco Z committed
993

994 995 996
	// Having lighttables for alpha-only entries is kind of pointless,
	// but if there happens to be a matching rgba entry that is NOT alpha-only (but has same rgb values),
	// then it needs this lighttable because we share matching entries.
Marco Z committed
997 998 999 1000 1001
	extra_colormap->colormap = R_CreateLightTable(extra_colormap);

	R_AddColormapToList(extra_colormap);

	return extra_colormap;
Alam Ed Arias committed
1002 1003
}

Marco Z committed
1004 1005
//
// R_AddColormaps()
1006
// NOTE: The result colormap is not added to the extra_colormaps chain. You must do that yourself!
Marco Z committed
1007 1008 1009 1010
//
extracolormap_t *R_AddColormaps(extracolormap_t *exc_augend, extracolormap_t *exc_addend,
	boolean subR, boolean subG, boolean subB, boolean subA,
	boolean subFadeR, boolean subFadeG, boolean subFadeB, boolean subFadeA,
1011
	boolean subFadeStart, boolean subFadeEnd, boolean ignoreFlags,
Marco Z committed
1012 1013
	boolean lighttable)
{
1014 1015
	INT16 red, green, blue, alpha;

Marco Z committed
1016 1017 1018 1019 1020 1021 1022 1023 1024
	// exc_augend is added (or subtracted) onto by exc_addend
	// In Rennaisance times, the first number was considered the augend, the second number the addend
	// But since the commutative property was discovered, today they're both called addends!
	// So let's be Olde English for a hot second.

	exc_augend = R_CopyColormap(exc_augend, false);
	if(!exc_addend)
		exc_addend = R_GetDefaultColormap();

1025
	///////////////////
Marco Z committed
1026
	// base rgba
1027 1028
	///////////////////

Marco Z committed
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
	red = max(min(
		R_GetRgbaR(exc_augend->rgba)
			+ (subR ? -1 : 1) // subtract R
			* R_GetRgbaR(exc_addend->rgba)
		, 255), 0);

	green = max(min(
		R_GetRgbaG(exc_augend->rgba)
			+ (subG ? -1 : 1) // subtract G
			* R_GetRgbaG(exc_addend->rgba)
		, 255), 0);

	blue = max(min(
		R_GetRgbaB(exc_augend->rgba)
			+ (subB ? -1 : 1) // subtract B
			* R_GetRgbaB(exc_addend->rgba)
		, 255), 0);

1047
	alpha = R_GetRgbaA(exc_addend->rgba);
Marco Z committed
1048 1049 1050 1051
	alpha = max(min(R_GetRgbaA(exc_augend->rgba) + (subA ? -1 : 1) * alpha, 25), 0);

	exc_augend->rgba = R_PutRgbaRGBA(red, green, blue, alpha);

1052 1053 1054 1055
	///////////////////
	// fade/dark rgba
	///////////////////

Marco Z committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
	red = max(min(
		R_GetRgbaR(exc_augend->fadergba)
			+ (subFadeR ? -1 : 1) // subtract R
			* R_GetRgbaR(exc_addend->fadergba)
		, 255), 0);

	green = max(min(
		R_GetRgbaG(exc_augend->fadergba)
			+ (subFadeG ? -1 : 1) // subtract G
			* R_GetRgbaG(exc_addend->fadergba)
		, 255), 0);

	blue = max(min(
		R_GetRgbaB(exc_augend->fadergba)
			+ (subFadeB ? -1 : 1) // subtract B
			* R_GetRgbaB(exc_addend->fadergba)
		, 255), 0);

1074 1075
	alpha = R_GetRgbaA(exc_addend->fadergba);
	if (alpha == 25 && !R_GetRgbaRGB(exc_addend->fadergba))
Marco Z committed
1076 1077 1078 1079 1080
		alpha = 0; // HACK: fadergba A defaults at 25, so don't add anything in this case
	alpha = max(min(R_GetRgbaA(exc_augend->fadergba) + (subFadeA ? -1 : 1) * alpha, 25), 0);

	exc_augend->fadergba = R_PutRgbaRGBA(red, green, blue, alpha);

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
	///////////////////
	// parameters
	///////////////////

	exc_augend->fadestart = max(min(
		exc_augend->fadestart
			+ (subFadeStart ? -1 : 1) // subtract fadestart
			* exc_addend->fadestart
		, 31), 0);

	exc_augend->fadeend = max(min(
		exc_augend->fadeend
			+ (subFadeEnd ? -1 : 1) // subtract fadeend
1094 1095
			* (exc_addend->fadeend == 31 && !exc_addend->fadestart ? 0 : exc_addend->fadeend)
				// HACK: fadeend defaults to 31, so don't add anything in this case
1096 1097
		, 31), 0);

1098 1099
	if (!ignoreFlags) // overwrite flags with new value
		exc_augend->flags = exc_addend->flags;
1100 1101 1102 1103 1104

	///////////////////
	// put it together
	///////////////////

1105 1106 1107
	exc_augend->colormap = lighttable ? R_CreateLightTable(exc_augend) : NULL;
	exc_augend->next = exc_augend->prev = NULL;
	return exc_augend;
Marco Z committed
1108 1109
}

Alam Ed Arias committed
1110 1111
// Thanks to quake2 source!
// utils3/qdata/images.c
1112
UINT8 NearestPaletteColor(UINT8 r, UINT8 g, UINT8 b, RGBA_t *palette)
Alam Ed Arias committed
1113 1114 1115 1116
{
	int dr, dg, db;
	int distortion, bestdistortion = 256 * 256 * 4, bestcolor = 0, i;

1117 1118 1119 1120
	// Use master palette if none specified
	if (palette == NULL)
		palette = pMasterPalette;

Alam Ed Arias committed
1121 1122
	for (i = 0; i < 256; i++)
	{
1123 1124 1125
		dr = r - palette[i].s.red;
		dg = g - palette[i].s.green;
		db = b - palette[i].s.blue;
Alam Ed Arias committed
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
		distortion = dr*dr + dg*dg + db*db;
		if (distortion < bestdistortion)
		{
			if (!distortion)
				return (UINT8)i;

			bestdistortion = distortion;
			bestcolor = i;
		}
	}

	return (UINT8)bestcolor;
}

// Rounds off floating numbers and checks for 0 - 255 bounds
static int RoundUp(double number)
{
	if (number > 255.0l)
		return 255;
	if (number < 0.0l)
		return 0;

	if ((int)number <= (int)(number - 0.5f))
		return (int)number + 1;

	return (int)number;
}

1154 1155
#ifdef EXTRACOLORMAPLUMPS
const char *R_NameForColormap(extracolormap_t *extra_colormap)
Alam Ed Arias committed
1156
{
Marco Z committed
1157
	if (!extra_colormap)
Alam Ed Arias committed
1158 1159
		return "NONE";

Marco Z committed
1160
	if (extra_colormap->lump == LUMPERROR)
Alam Ed Arias committed
1161 1162
		return "INLEVEL";

1163
	return extra_colormap->lumpname;
Alam Ed Arias committed
1164
}
1165
#endif
Alam Ed Arias committed
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217

//
// build a table for quick conversion from 8bpp to 15bpp
//

//
// added "static inline" keywords, linking with the debug version
// of allegro, it have a makecol15 function of it's own, now
// with "static inline" keywords,it sloves this problem ;)
//
FUNCMATH static inline int makecol15(int r, int g, int b)
{
	return (((r >> 3) << 10) | ((g >> 3) << 5) | ((b >> 3)));
}

static void R_Init8to16(void)
{
	UINT8 *palette;
	int i;

	palette = W_CacheLumpName("PLAYPAL",PU_CACHE);

	for (i = 0; i < 256; i++)
	{
		// PLAYPAL uses 8 bit values
		color8to16[i] = (INT16)makecol15(palette[0], palette[1], palette[2]);
		palette += 3;
	}

	// test a big colormap
	hicolormaps = Z_Malloc(16384*sizeof(*hicolormaps), PU_STATIC, NULL);
	for (i = 0; i < 16384; i++)
		hicolormaps[i] = (INT16)(i<<1);
}

//
// R_InitData
//
// Locates all the lumps that will be used by all views
// Must be called after W_Init.
//
void R_InitData(void)
{
	if (highcolor)
	{
		CONS_Printf("InitHighColor...\n");
		R_Init8to16();
	}

	CONS_Printf("R_LoadTextures()...\n");
	R_LoadTextures();

1218 1219 1220
	CONS_Printf("P_InitPicAnims()...\n");
	P_InitPicAnims();

Alam Ed Arias committed
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
	CONS_Printf("R_InitSprites()...\n");
	R_InitSpriteLumps();
	R_InitSprites();

	CONS_Printf("R_InitColormaps()...\n");
	R_InitColormaps();
}

//
// R_PrecacheLevel
//
// Preloads all relevant graphics for the level.
//
void R_PrecacheLevel(void)
{
	char *texturepresent, *spritepresent;
	size_t i, j, k;
	lumpnum_t lump;

	thinker_t *th;
	spriteframe_t *sf;

	if (demoplayback)
		return;

	// do not flush the memory, Z_Malloc twice with same user will cause error in Z_CheckHeap()
	if (rendermode != render_soft)
		return;

	// Precache flats.
	flatmemory = P_PrecacheLevelFlats();

	//
	// Precache textures.
	//
	// no need to precache all software textures in 3D mode
	// (note they are still used with the reference software view)
1258
	texturepresent = calloc(numtextures, sizeof (*texturepresent));
Alam Ed Arias committed
1259 1260 1261 1262 1263
	if (texturepresent == NULL) I_Error("%s: Out of memory looking up textures", "R_PrecacheLevel");

	for (j = 0; j < numsides; j++)
	{
		// huh, a potential bug here????
1264
		if (sides[j].toptexture >= 0 && sides[j].toptexture < numtextures)
Alam Ed Arias committed
1265
			texturepresent[sides[j].toptexture] = 1;
1266
		if (sides[j].midtexture >= 0 && sides[j].midtexture < numtextures)
Alam Ed Arias committed
1267
			texturepresent[sides[j].midtexture] = 1;
1268
		if (sides[j].bottomtexture >= 0 && sides[j].bottomtexture < numtextures)
Alam Ed Arias committed
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
			texturepresent[sides[j].bottomtexture] = 1;
	}

	// Sky texture is always present.
	// Note that F_SKY1 is the name used to indicate a sky floor/ceiling as a flat,
	// while the sky texture is stored like a wall texture, with a skynum dependent name.
	texturepresent[skytexture] = 1;

	texturememory = 0;
	for (j = 0; j < (unsigned)numtextures; j++)
	{
		if (!texturepresent[j])
			continue;

		if (!texturecache[j])
			R_GenerateTexture(j);
		// pre-caching individual patches that compose textures became obsolete,
		// since we cache entire composite textures
	}
	free(texturepresent);

	//
	// Precache sprites.
	//
	spritepresent = calloc(numsprites, sizeof (*spritepresent));
	if (spritepresent == NULL) I_Error("%s: Out of memory looking up sprites", "R_PrecacheLevel");

1296
	for (th = thlist[THINK_MOBJ].next; th != &thlist[THINK_MOBJ]; th = th->next)
1297 1298
		if (th->function.acp1 != (actionf_p1)P_RemoveThinkerDelayed)
			spritepresent[((mobj_t *)th)->sprite] = 1;
Alam Ed Arias committed
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308

	spritememory = 0;
	for (i = 0; i < numsprites; i++)
	{
		if (!spritepresent[i])
			continue;

		for (j = 0; j < sprites[i].numframes; j++)
		{
			sf = &sprites[i].spriteframes[j];
1309 1310 1311 1312
#define cacheang(a) {\
		lump = sf->lumppat[a];\
		if (devparm)\
			spritememory += W_LumpLength(lump);\
1313
		W_CachePatchNum(lump, PU_SPRITE);\
1314 1315 1316
	}
			// see R_InitSprites for more about lumppat,lumpid
			switch (sf->rotate)
Alam Ed Arias committed
1317
			{
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
				case SRF_SINGLE:
					cacheang(0);
					break;
				case SRF_2D:
					cacheang(2);
					cacheang(6);
					break;
				default:
					k = (sf->rotate & SRF_3DGE ? 16 : 8);
					while (k--)
						cacheang(k);
					break;
Alam Ed Arias committed
1330
			}
1331
#undef cacheang
Alam Ed Arias committed
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
		}
	}
	free(spritepresent);

	// FIXME: this is no longer correct with OpenGL render mode
	CONS_Debug(DBG_SETUP, "Precache level done:\n"
			"flatmemory:    %s k\n"
			"texturememory: %s k\n"
			"spritememory:  %s k\n", sizeu1(flatmemory>>10), sizeu2(texturememory>>10), sizeu3(spritememory>>10));
}