summaryrefslogtreecommitdiff
path: root/src/gfxinit.cpp
blob: f76e90968e948bba2ea03d7ad179866b82d609b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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
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
160
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
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
/* $Id$ */

/** @file gfxinit.cpp Initializing of the (GRF) graphics. */

#include "stdafx.h"
#include "openttd.h"
#include "debug.h"
#include "gfxinit.h"
#include "spritecache.h"
#include "fileio_func.h"
#include "fios.h"
#include "newgrf.h"
#include "md5.h"
#include "variables.h"
#include "fontcache.h"
#include "gfx_func.h"
#include "core/alloc_func.hpp"
#include "core/bitmath_func.hpp"
#include "core/smallvec_type.hpp"
#include <string.h>
#include "settings_type.h"
#include "string_func.h"
#include "ini_type.h"

#include "table/sprites.h"

/** The currently used palette */
PaletteType _use_palette = PAL_AUTODETECT;
char _ini_graphics_set[32];

/** Structure holding filename and MD5 information about a single file */
struct MD5File {
	const char *filename;        ///< filename
	uint8 hash[16];              ///< md5 sum of the file
	const char *missing_warning; ///< warning when this file is missing
};

/** Types of graphics in the base graphics set */
enum GraphicsFileType {
	GFT_BASE,     ///< Base sprites for all climates
	GFT_LOGOS,    ///< Logos, landscape icons and original terrain generator sprites
	GFT_ARCTIC,   ///< Landscape replacement sprites for arctic
	GFT_TROPICAL, ///< Landscape replacement sprites for tropical
	GFT_TOYLAND,  ///< Landscape replacement sprites for toyland
	GFT_EXTRA,    ///< Extra sprites that were not part of the original sprites
	MAX_GFT       ///< We are looking for this amount of GRFs
};

/** Information about a single graphics set. */
struct GraphicsSet {
	const char *name;          ///< The name of the graphics set
	const char *description;   ///< Description of the graphics set
	uint32 shortname;          ///< Four letter short variant of the name
	uint32 version;            ///< The version of this graphics set
	PaletteType palette;       ///< Palette of this graphics set

	MD5File files[MAX_GFT];    ///< All GRF files part of this set
	uint found_grfs;           ///< Number of the GRFs that could be found

	GraphicsSet *next;         ///< The next graphics set in this list

	/** Free everything we allocated */
	~GraphicsSet()
	{
		free((void*)this->name);
		free((void*)this->description);
		for (uint i = 0; i < MAX_GFT; i++) {
			free((void*)this->files[i].filename);
			free((void*)this->files[i].missing_warning);
		}

		delete this->next;
	}
};

/** All graphics sets currently available */
static GraphicsSet *_available_graphics_sets = NULL;
/** The one and only graphics set that is currently being used. */
static const GraphicsSet *_used_graphics_set = NULL;

#include "table/files.h"
#include "table/landscape_sprite.h"

static const SpriteID * const _landscape_spriteindexes[] = {
	_landscape_spriteindexes_1,
	_landscape_spriteindexes_2,
	_landscape_spriteindexes_3,
};

static uint LoadGrfFile(const char *filename, uint load_index, int file_index)
{
	uint load_index_org = load_index;
	uint sprite_id = 0;

	FioOpenFile(file_index, filename);

	DEBUG(sprite, 2, "Reading grf-file '%s'", filename);

	while (LoadNextSprite(load_index, file_index, sprite_id)) {
		load_index++;
		sprite_id++;
		if (load_index >= MAX_SPRITES) {
			usererror("Too many sprites. Recompile with higher MAX_SPRITES value or remove some custom GRF files.");
		}
	}
	DEBUG(sprite, 2, "Currently %i sprites are loaded", load_index);

	return load_index - load_index_org;
}


void LoadSpritesIndexed(int file_index, uint *sprite_id, const SpriteID *index_tbl)
{
	uint start;
	while ((start = *index_tbl++) != END) {
		uint end = *index_tbl++;

		do {
			bool b = LoadNextSprite(start, file_index, *sprite_id);
			assert(b);
			(*sprite_id)++;
		} while (++start <= end);
	}
}

static void LoadGrfIndexed(const char* filename, const SpriteID* index_tbl, int file_index)
{
	uint sprite_id = 0;

	FioOpenFile(file_index, filename);

	DEBUG(sprite, 2, "Reading indexed grf-file '%s'", filename);

	LoadSpritesIndexed(file_index, &sprite_id, index_tbl);
}


/**
 * Calculate and check the MD5 hash of the supplied filename.
 * @param file filename and expected MD5 hash for the given filename.
 * @return true if the checksum is correct.
 */
static bool FileMD5(const MD5File file)
{
	size_t size;
	FILE *f = FioFOpenFile(file.filename, "rb", DATA_DIR, &size);

	if (f != NULL) {
		Md5 checksum;
		uint8 buffer[1024];
		uint8 digest[16];
		size_t len;

		while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
			size -= len;
			checksum.Append(buffer, len);
		}

		FioFCloseFile(f);

		checksum.Finish(digest);
		return memcmp(file.hash, digest, sizeof(file.hash)) == 0;
	} else { // file not found
		return false;
	}
}

/**
 * Determine the graphics pack that has to be used.
 * The one with the most correct files wins.
 */
static void DetermineGraphicsPack()
{
	if (_used_graphics_set != NULL) return;

	const GraphicsSet *best = _available_graphics_sets;
	for (const GraphicsSet *c = _available_graphics_sets; c != NULL; c = c->next) {
		if (best->found_grfs < c->found_grfs ||
				(best->found_grfs == c->found_grfs && best->shortname == c->shortname && best->version < c->version)) {
			best = c;
		}
	}

	_used_graphics_set = best;
}

/**
 * Determine the palette that has to be used.
 *  - forced palette via command line -> leave it that way
 *  - otherwise -> palette based on the graphics pack
 */
static void DeterminePalette()
{
	if (_use_palette < MAX_PAL) return;

	_use_palette = _used_graphics_set->palette;
}

/**
 * Checks whether the MD5 checksums of the files are correct.
 *
 * @note Also checks sample.cat and other required non-NewGRF GRFs for corruption.
 */
void CheckExternalFiles()
{
	DetermineGraphicsPack();
	DeterminePalette();

	static const size_t ERROR_MESSAGE_LENGTH = 128;
	char error_msg[ERROR_MESSAGE_LENGTH * (MAX_GFT + 1)];
	error_msg[0] = '\0';
	char *add_pos = error_msg;

	for (uint i = 0; i < lengthof(_used_graphics_set->files); i++) {
		if (!FileMD5(_used_graphics_set->files[i])) {
			add_pos += snprintf(add_pos, ERROR_MESSAGE_LENGTH, "Your '%s' file is corrupted or missing! %s\n", _used_graphics_set->files[i].filename, _used_graphics_set->files[i].missing_warning);
		}
	}

	bool sound = false;
	for (uint i = 0; !sound && i < lengthof(_sound_sets); i++) {
		sound = FileMD5(_sound_sets[i]);
	}

	if (!sound) {
		add_pos += snprintf(add_pos, ERROR_MESSAGE_LENGTH, "Your 'sample.cat' file is corrupted or missing! You can find 'sample.cat' on your Transport Tycoon Deluxe CD-ROM.\n");
	}

	if (add_pos != error_msg) ShowInfoF(error_msg);
}


static void LoadSpriteTables()
{
	uint i = FIRST_GRF_SLOT;

	LoadGrfFile(_used_graphics_set->files[GFT_BASE].filename, 0, i++);

	/*
	 * The second basic file always starts at the given location and does
	 * contain a different amount of sprites depending on the "type"; DOS
	 * has a few sprites less. However, we do not care about those missing
	 * sprites as they are not shown anyway (logos in intro game).
	 */
	LoadGrfFile(_used_graphics_set->files[GFT_LOGOS].filename, 4793, i++);

	/*
	 * Load additional sprites for climates other than temperate.
	 * This overwrites some of the temperate sprites, such as foundations
	 * and the ground sprites.
	 */
	if (_settings_game.game_creation.landscape != LT_TEMPERATE) {
		LoadGrfIndexed(
			_used_graphics_set->files[GFT_ARCTIC + _settings_game.game_creation.landscape - 1].filename,
			_landscape_spriteindexes[_settings_game.game_creation.landscape - 1],
			i++
		);
	}

	/* Initialize the unicode to sprite mapping table */
	InitializeUnicodeGlyphMap();

	/*
	 * Load the base NewGRF with OTTD required graphics as first NewGRF.
	 * However, we do not want it to show up in the list of used NewGRFs,
	 * so we have to manually add it, and then remove it later.
	 */
	GRFConfig *top = _grfconfig;
	GRFConfig *master = CallocT<GRFConfig>(1);
	master->filename = strdup(_used_graphics_set->files[GFT_EXTRA].filename);
	FillGRFDetails(master, false);
	ClrBit(master->flags, GCF_INIT_ONLY);
	master->next = top;
	_grfconfig = master;

	LoadNewGRF(SPR_NEWGRFS_BASE, i);

	/* Free and remove the top element. */
	ClearGRFConfig(&master);
	_grfconfig = top;
}


void GfxLoadSprites()
{
	DEBUG(sprite, 2, "Loading sprite set %d", _settings_game.game_creation.landscape);

	GfxInitSpriteMem();
	LoadSpriteTables();
	GfxInitPalettes();
}

/**
 * Try to read a single piece of metadata and return false if it doesn't exist.
 * @param name the name of the item to fetch.
 */
#define fetch_metadata(name) \
	item = metadata->GetItem(name, false); \
	if (item == NULL || strlen(item->value) == 0) { \
		DEBUG(grf, 0, "Base graphics set detail loading: %s field missing", name); \
		return false; \
	}

/** Names corresponding to the GraphicsFileType */
static const char *_gft_names[MAX_GFT] = { "base", "logos", "arctic", "tropical", "toyland", "extra" };

/**
 * Read the graphics set information from a loaded ini.
 * @param graphics the graphics set to write to
 * @param ini      the ini to read from
 * @param path     the path to this ini file (for filenames)
 * @return true if loading was successful.
 */
static bool FillGraphicsSetDetails(GraphicsSet *graphics, IniFile *ini, const char *path)
{
	memset(graphics, 0, sizeof(*graphics));

	IniGroup *metadata = ini->GetGroup("metadata");
	IniItem *item;

	fetch_metadata("name");
	graphics->name = strdup(item->value);

	fetch_metadata("description");
	graphics->description = strdup(item->value);

	fetch_metadata("shortname");
	for (uint i = 0; item->value[i] != '\0' && i < 4; i++) {
		graphics->shortname |= ((uint8)item->value[i]) << (32 - i * 8);
	}

	fetch_metadata("version");
	graphics->version = atoi(item->value);

	fetch_metadata("palette");
	graphics->palette = (*item->value == 'D' || *item->value == 'd') ? PAL_DOS : PAL_WINDOWS;

	/* For each of the graphics file types we want to find the file, MD5 checksums and warning messages. */
	IniGroup *files  = ini->GetGroup("files");
	IniGroup *md5s   = ini->GetGroup("md5s");
	IniGroup *origin = ini->GetGroup("origin");
	for (uint i = 0; i < MAX_GFT; i++) {
		MD5File *file = &graphics->files[i];
		/* Find the filename first. */
		item = files->GetItem(_gft_names[i], false);
		if (item == NULL) {
			DEBUG(grf, 0, "No graphics file for: %s", _gft_names[i]);
			return false;
		}

		const char *filename = item->value;
		file->filename = MallocT<char>(strlen(filename) + strlen(path) + 1);
		sprintf((char*)file->filename, "%s%s", path, filename);

		/* Then find the MD5 checksum */
		item = md5s->GetItem(filename, false);
		if (item == NULL) {
			DEBUG(grf, 0, "No MD5 checksum specified for: %s", filename);
			return false;
		}
		char *c = item->value;
		for (uint i = 0; i < sizeof(file->hash) * 2; i++, c++) {
			uint j;
			if ('0' <= *c && *c <= '9') {
				j = *c - '0';
			} else if ('a' <= *c && *c <= 'f') {
				j = *c - 'a' + 10;
			} else if ('A' <= *c && *c <= 'F') {
				j = *c - 'A' + 10;
			} else {
				DEBUG(grf, 0, "Malformed MD5 checksum specified for: %s", filename);
				return false;
			}
			if (i % 2 == 0) {
				file->hash[i / 2] = j << 4;
			} else {
				file->hash[i / 2] |= j;
			}
		}

		/* Then find the warning message when the file's missing */
		item = origin->GetItem(filename, false);
		if (item == NULL) item = origin->GetItem("default", false);
		if (item == NULL) {
			DEBUG(grf, 1, "No origin warning message specified for: %s", filename);
			file->missing_warning = strdup("");
		} else {
			file->missing_warning = strdup(item->value);
		}

		if (FileMD5(*file)) graphics->found_grfs++;
	}

	return true;
}

/** Helper for scanning for files with GRF as extension */
class OBGFileScanner : FileScanner {
public:
	/* virtual */ bool AddFile(const char *filename, size_t basepath_length);

	/** Do the scan for OBGs. */
	static uint DoScan()
	{
		OBGFileScanner fs;
		return fs.Scan(".obg", DATA_DIR);
	}
};

/**
 * Try to add a graphics set with the given filename.
 * @param filename        the full path to the file to read
 * @param basepath_length amount of characters to chop of before to get a relative DATA_DIR filename
 * @return true if the file is added.
 */
bool OBGFileScanner::AddFile(const char *filename, size_t basepath_length)
{
	bool ret = false;
	DEBUG(grf, 1, "Found %s as base graphics set", filename);

	GraphicsSet *graphics = new GraphicsSet();;
	IniFile *ini = new IniFile();
	ini->LoadFromDisk(filename);

	char *path = strdup(filename + basepath_length);
	char *psep = strrchr(path, PATHSEPCHAR);
	if (psep != NULL) {
		psep[1] = '\0';
	} else {
		*path = '\0';
	}

	if (FillGraphicsSetDetails(graphics, ini, path)) {
		bool duplicate = false;
		for (const GraphicsSet *c = _available_graphics_sets; !duplicate && c != NULL; c = c->next) {
			duplicate = (strcmp(c->name, graphics->name) == 0) || (c->shortname == graphics->shortname && c->version == graphics->version);
		}
		if (duplicate) {
			delete graphics;
		} else {
			graphics->next = _available_graphics_sets;
			_available_graphics_sets = graphics;
			ret = true;
		}
	} else {
		delete graphics;
	}
	free(path);

	delete ini;
	return ret;
}



/** Scan for all Grahpics sets */
void FindGraphicsSets()
{
	DEBUG(grf, 1, "Scanning for Graphics sets");
	OBGFileScanner::DoScan();
}

/**
 * Set the graphics set to be used.
 * @param name of the graphics set to use
 * @return true if it could be loaded
 */
bool SetGraphicsSet(const char *name)
{
	if (StrEmpty(name)) {
		DetermineGraphicsPack();
		CheckExternalFiles();
		return true;
	}

	for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) {
		if (strcmp(name, g->name) == 0) {
			_used_graphics_set = g;
			CheckExternalFiles();
			return true;
		}
	}
	return false;
}

/**
 * Returns a list with the graphics sets.
 * @param p    where to print to
 * @param last the last character to print to
 * @return the last printed character
 */
char *GetGraphicsSetsList(char *p, const char *last)
{
	p += snprintf(p, last - p, "List of graphics sets:\n");
	for (const GraphicsSet *g = _available_graphics_sets; g != NULL; g = g->next) {
		if (g->found_grfs <= 1) continue;

		p += snprintf(p, last - p, "%18s: %s", g->name, g->description);
		int difference = MAX_GFT - g->found_grfs;
		if (difference != 0) {
			p += snprintf(p, last - p, " (missing %i file%s)\n", difference, difference == 1 ? "" : "s");
		} else {
			p += snprintf(p, last - p, "\n");
		}
	}
	p += snprintf(p, last - p, "\n");

	return p;
}