init.c 40.8 KB
Newer Older
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
/* 
 *
 *   Copyright (c) 2004-2010 Arthur Huillet
 *   Copyright (c) 1994, 2002, 2003 Johannes Prix
 *   Copyright (c) 1994, 2002 Reinhard Prix
 *
 *
 *  This file is part of Freedroid
 *
 *  Freedroid is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  Freedroid is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Freedroid; see the file COPYING. If not, write to the 
 *  Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
 *  MA  02111-1307  USA
 *
 */

/**
 * (Not all of the) Initialization routines for FreedroidRPG.
 */

#define _init_c

#include "system.h"

#include "defs.h"
#include "struct.h"
#include "global.h"
#include "proto.h"
#include "widgets/widgets.h"

#include "getopt.h"

#ifdef __WIN32__
44 45 46 47 48
// For _mkdir()
#include <direct.h>
// For SHGetSpecialFolderPath()
#ifndef _WIN32_IE
// From MSDN: The Microsoft Internet Explorer 4.0 Desktop Update must be installed for this function to be available.
49
#define _WIN32_IE 0x0400
50
#endif
51 52 53
#include <shlobj.h>
#endif

54 55 56 57
#ifdef ENABLE_NLS
#include <iconv.h>
#endif

58 59
void Init_Game_Data(void);
void UpdateCountersForThisFrame();
60 61 62
void DoAllMovementAndAnimations(void);

struct dynarray difficulties;
63

64 65
int term_has_color_cap = FALSE;
int run_from_term = FALSE;
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

/**
 *
 *
 */
void clear_out_arrays_for_fresh_game(void)
{
	int i;

	for (i = 0; i < MAX_MELEE_SHOTS; i++)
		delete_melee_shot(&AllMeleeShots[i]);

	for (i = 0; i < MAXBULLETS; i++) {
		DeleteBullet(i, FALSE);
	}
	for (i = 0; i < MAXBLASTS; i++) {
		DeleteBlast(i);
	}
	clear_active_spells();

	clear_enemies();
87
	clear_volatile_obstacles();
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
	ClearAutomapData();

	clear_npcs();

	init_tux();
}

/** 
 * This function displays a startup status bar that shows a certain
 * percentage of loading done.
 */
void next_startup_percentage(int done)
{
	static int startup_percent = 0;
	SDL_Rect Bar_Rect;

	/* Define STARTUP_PERCENTAGE_COMPUTE to get an estimate
	   of the real percentage associated to each step during the
	   game startup.
	   */
#ifdef STARTUP_PERCENTAGE_COMPUTE
	static long load_start_time;

	struct load_step {
		long elapsed;
		int percent;
	};

	static struct dynarray *step_times = NULL;
	if (!step_times)
		step_times = dynarray_alloc(10, sizeof(struct load_step));

	if (!startup_percent)
		load_start_time = SDL_GetTicks();
#endif

	startup_percent += done;
	if (startup_percent > 100)
		startup_percent = 100;

#ifdef STARTUP_PERCENTAGE_COMPUTE
	long elapsed = SDL_GetTicks() - load_start_time;

	printf("Step %d: %ld ms have elapsed (%d%%), now at %d%%\n", step_times->size, elapsed, done, startup_percent);

	struct load_step step = { elapsed, done };
	dynarray_add(step_times, &step, sizeof(struct load_step));

	if (startup_percent >= 100) {
		float ms_to_percent = 100.0 / elapsed;
		printf("Loading took %ld ms, 1 ms = %f%%\n", elapsed, ms_to_percent);

		int i;
		for (i = 1; i < step_times->size; i++) {
#define STEP(X) ((struct load_step *)step_times->arr)[X]
			int step_time = STEP(i).elapsed - STEP(i-1).elapsed;
			int step_percent = step_time * ms_to_percent;
			printf("Step %d: %d ms -> %d%%\n", i, step_time, step_percent);
		}
	}
#endif

	if (use_open_gl)
		blit_background("startup1.jpg");

	Bar_Rect.x = 160 * GameConfig.screen_width / 640;
	Bar_Rect.y = 288 * GameConfig.screen_height / 480;
	Bar_Rect.w = 3 * startup_percent * GameConfig.screen_width / 640;
	Bar_Rect.h = 30 * GameConfig.screen_height / 480;
	draw_rectangle(&Bar_Rect, 150, 200, 225, 255);

	Bar_Rect.x = (160 + 3 * startup_percent) * GameConfig.screen_width / 640;
	Bar_Rect.y = 288 * GameConfig.screen_height / 480;
	Bar_Rect.w = (300 - 3 * startup_percent) * GameConfig.screen_width / 640;
	Bar_Rect.h = 30 * GameConfig.screen_height / 480;
	draw_rectangle(&Bar_Rect, 0, 0, 0, 255);

	SDL_SetClipRect(Screen, NULL);

167
	set_current_font(Blue_Font);
168 169
	char percent[10];
	sprintf(percent, "%d%%", startup_percent);
170
	display_text(percent, UNIVERSAL_COORD_W(310) - 9, UNIVERSAL_COORD_H(301) - 7, NULL, 1.0);
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

	our_SDL_update_rect_wrapper(Screen, 0, 0, Screen->w, Screen->h);

}

/**
 * This function can be used to play a generic title file, containing 
 * 
 *  1. a background picture name
 *  2. a background music to play
 *  3. some text to display in a scrolling fashion
 *
 */
void PlayATitleFile(char *Filename)
{
186 187
	struct title_screen screen = { NULL, NULL, NULL };
	char fpath[PATH_MAX];
188

189
	while (SpacePressed() || MouseLeftPressed()) ;
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
	if (find_localized_file(Filename, TITLES_DIR, fpath, PLEASE_INFORM)) {
		set_lua_ctor_upvalue(LUA_CONFIG, "title_screen", &screen);
		run_lua_file(LUA_CONFIG, fpath);

#ifdef ENABLE_NLS
		// Convert the title_screen(s text to selected charset encoding
		struct auto_string *tocode = alloc_autostr(64);
		autostr_printf(tocode, "%s//TRANSLIT", lang_get_encoding());
		iconv_t converter = iconv_open(tocode->value, "UTF-8");
		free_autostr(tocode);
		if (converter == (iconv_t)-1) {
			error_once_message(ONCE_PER_GAME, __FUNCTION__,
			                   "Error on iconv_open() (encoding: %s): %s",
			                   NO_REPORT, lang_get_encoding(), strerror(errno));
		} else {
#if __FreeBSD__
			// FreeBSD changed to its own iconv starting with 10-CURRENT
			// Future ref: check for OS version < 10-CURRENT would allow non-const
			const char *in_ptr = screen.text;
#else
			char *in_ptr = screen.text;
#endif	//__FreeBSD__
			size_t in_len = strlen(screen.text);
			// We currently only have 8 bits encodings, so we should not need
			// an output buffer larger than the input one.
			char *converted_text = MyMalloc(in_len+1);
			char *out_ptr = converted_text;
			size_t out_len = in_len;

			size_t nb = iconv(converter, &in_ptr, &in_len, &out_ptr, &out_len);

			// In case of error, use the un-converted text
			if (nb == (size_t)-1) {
				if (errno == EILSEQ || errno == EINVAL) {
					error_once_message(ONCE_PER_GAME, __FUNCTION__,
				                       "Error during Title text conversion (title: %s - encoding: %s): %s\n"
					                   "Invalid sequence:\n--->%.20s...<---",
									   PLEASE_INFORM, Filename, lang_get_encoding(), strerror(errno), in_ptr);
				} else {
					error_once_message(ONCE_PER_GAME, __FUNCTION__,
				                       "Error during Title text conversion (title: %s - encoding: %s): %s",
									   NO_REPORT, Filename, lang_get_encoding(), strerror(errno));
				}
				free(converted_text);
			} else {
				// Replace the title's text by the converted one
				free(screen.text);
				screen.text = converted_text;
			}
240
		}
241 242
		iconv_close(converter);
#endif
243

244 245 246
		// Remove trailing whitespaces and carriage returns.
		char *ptr = screen.text + strlen(screen.text) - 1;
		while (*ptr != '\0' && (*ptr == ' ' || *ptr == '\t' || *ptr == '\n')) *(ptr--) = '\0';
247

248
		switch_background_music(screen.song);
249

250 251
		SDL_SetClipRect(Screen, NULL);
		set_current_font(Para_Font);
252

253
		ScrollText(screen.text,screen.background);
254

255 256
		clear_screen();
		our_SDL_flip_wrapper();
257

258 259 260
		free(screen.background);
		free(screen.song);
		free(screen.text);
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
	}
}

/**
 * This function loads all the constant concerning robot archetypes
 * from a section in memory to the actual archetype structures.
 */
static void Get_Robot_Data(void *DataPointer)
{
	int RobotIndex = 0;
	char *RobotPointer;
	char *EndOfDataPointer;
	int i;

#define ROBOT_SECTION_BEGIN_STRING "*** Start of Robot Data Section: ***"
#define ROBOT_SECTION_END_STRING "*** End of Robot Data Section: ***"
#define NEW_ROBOT_BEGIN_STRING "** Start of new Robot: **"
#define DROIDNAME_BEGIN_STRING "Droidname: "
#define PORTRAIT_FILENAME_WITHOUT_EXT "Droid portrait file name (without extension) to use=\""

#define DROID_PORTRAIT_ROTATION_SERIES_NAME_PREFIX "Droid uses portrait rotation series with prefix=\""

#define MAXSPEED_BEGIN_STRING "Maximum speed of this droid: "
#define CLASS_BEGIN_STRING "Class of this droid: "
#define MAXENERGY_BEGIN_STRING "Maximum energy of this droid: "
#define BASE_HEALING_BEGIN_STRING "Rate of healing: "
287
#define SENSOR_ID_BEGIN_STRING "Sensor ID=\""
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
#define EXPERIENCE_REWARD_BEGIN_STRING "Experience_Reward gained for destroying one of this type: "
#define WEAPON_ITEM_BEGIN_STRING "Weapon item=\""
#define GREETING_SOUND_STRING "Greeting Sound number="
#define DROID_DEATH_SOUND_FILE_NAME "Death sound file name=\""
#define DROID_ATTACK_ANIMATION_SOUND_FILE_NAME "Attack animation sound file name=\""
#define TO_HIT_STRING "Chance of this robot scoring a hit="
#define GETTING_HIT_MODIFIER_STRING "Chance modifier, that this robot gets hit="
#define IS_HUMAN_SPECIFICATION_STRING "Is this 'droid' a human : "
#define INDIVIDUAL_SHAPE_SPECIFICATION_STRING "Individual shape of this droid or just -1 for classic ball shaped : "
#define NOTES_BEGIN_STRING "Notes concerning this droid=_\""

	RobotPointer = LocateStringInData(DataPointer, ROBOT_SECTION_BEGIN_STRING);
	EndOfDataPointer = LocateStringInData(DataPointer, ROBOT_SECTION_END_STRING);

	DebugPrintf(1, "\n\nStarting to read Robot data...\n\n");
	// At first, we must allocate memory for the droid specifications.
	// How much?  That depends on the number of droids defined in freedroid.ruleset.
	// So we have to count those first.  ok.  lets do it.

	Number_Of_Droid_Types = CountStringOccurences(DataPointer, NEW_ROBOT_BEGIN_STRING);
	if (NB_DROID_TYPES < Number_Of_Droid_Types + 2) {
309
		error_message(__FUNCTION__, "\
310 311
The value of %d for \"NB_DROID_TYPES\" defined in struct.h is less than %d\n\
which is \"Number_of_Droid_Types\" + 2. Please increase the value of \"NB_DROID_TYPES\"!",
312
			PLEASE_INFORM | IS_FATAL, NB_DROID_TYPES, Number_Of_Droid_Types + 2);
313 314 315 316
	}

	// Not that we know how many robots are defined in freedroid.ruleset, we can allocate
	// a fitting amount of memory.
317 318 319
	i = sizeof(droidspec);
	Droidmap = MyMalloc(i * (Number_Of_Droid_Types + 1) + 1);
	DebugPrintf(1, "\nWe have counted %d different droid types in the game data file.", Number_Of_Droid_Types);
320 321 322 323 324 325 326 327 328 329 330 331 332
	DebugPrintf(2, "\nMEMORY HAS BEEN ALLOCATED.\nTHE READING CAN BEGIN.\n");

	//Now we start to read the values for each robot:
	//Of which parts is it composed, which stats does it have?
	while ((RobotPointer = strstr(RobotPointer, NEW_ROBOT_BEGIN_STRING)) != NULL) {
		DebugPrintf(2, "\n\nFound another Robot specification entry!  Lets add that to the others!");
		RobotPointer++;	// to avoid doubly taking this entry
		char *EndOfThisRobot = strstr(RobotPointer, NEW_ROBOT_BEGIN_STRING);
		if (EndOfThisRobot)
			EndOfThisRobot[0] = 0;

		// Now we read in the Name of this droid.  We consider as a name the rest of the
		// line with the DROIDNAME_BEGIN_STRING until the "\n" is found.
333
		Droidmap[RobotIndex].droidname = ReadAndMallocStringFromData(RobotPointer, DROIDNAME_BEGIN_STRING, "\n");
334 335

		// Now we read in the default short_description_text for this droid.
336 337 338
		Droidmap[RobotIndex].default_short_description = ReadAndMallocStringFromDataOptional(RobotPointer, "Default description:_\"", "\"");
		if (!Droidmap[RobotIndex].default_short_description)
			Droidmap[RobotIndex].default_short_description = strdup("");
339 340 341

		// Now we read in the prefix of the file names in the rotation series
		// to use for the console droid rotation
342
		Droidmap[RobotIndex].droid_portrait_rotation_series_prefix =
343 344 345 346 347
		    ReadAndMallocStringFromData(RobotPointer, DROID_PORTRAIT_ROTATION_SERIES_NAME_PREFIX, "\"");

		// Now we read in the file name of the death sound for this droid.  
		// Is should be enclosed in double-quotes.
		//
348
		Droidmap[RobotIndex].droid_death_sound_file_name =
349 350 351 352 353
		    ReadAndMallocStringFromData(RobotPointer, DROID_DEATH_SOUND_FILE_NAME, "\"");

		// Now we read in the file name of the attack animation sound for this droid.  
		// Is should be enclosed in double-quotes.
		//
354
		Droidmap[RobotIndex].droid_attack_animation_sound_file_name =
355 356 357
		    ReadAndMallocStringFromData(RobotPointer, DROID_ATTACK_ANIMATION_SOUND_FILE_NAME, "\"");

		// Now we read in the maximal speed this droid can go. 
358
		ReadValueFromString(RobotPointer, MAXSPEED_BEGIN_STRING, "%f", &Droidmap[RobotIndex].maxspeed, EndOfDataPointer);
359 360

		// Now we read in the class of this droid.
361
		ReadValueFromString(RobotPointer, CLASS_BEGIN_STRING, "%d", &Droidmap[RobotIndex].class, EndOfDataPointer);
362 363

		// Now we read in the maximal energy this droid can store. 
364
		ReadValueFromString(RobotPointer, MAXENERGY_BEGIN_STRING, "%f", &Droidmap[RobotIndex].maxenergy, EndOfDataPointer);
365 366

		// Now we read in the lose_health rate.
367 368 369 370 371 372 373 374 375
		ReadValueFromString(RobotPointer, BASE_HEALING_BEGIN_STRING, "%f", &Droidmap[RobotIndex].healing_friendly, EndOfDataPointer);
		Droidmap[RobotIndex].healing_hostile = Droidmap[RobotIndex].healing_friendly;

		// Now we read what sensor this robot use.
		char *tmp_sensor_ID = ReadAndMallocStringFromDataOptional(RobotPointer, SENSOR_ID_BEGIN_STRING, "\"");
		if (!tmp_sensor_ID)
			tmp_sensor_ID = strdup("spectral"); // Default value if no sensor defined.
		Droidmap[RobotIndex].sensor_id = get_sensor_id_by_name(tmp_sensor_ID);
		free(tmp_sensor_ID);
376 377 378

		// Now we read in range of vision of this droid
		ReadValueFromString(RobotPointer, "Aggression distance of this droid=", "%f",
379
				    &Droidmap[RobotIndex].aggression_distance, EndOfDataPointer);
380 381 382

		// Now we read in range of vision of this droid
		ReadValueFromString(RobotPointer, "Time spent eyeing Tux=", "%f",
383
				    &Droidmap[RobotIndex].time_spent_eyeing_tux, EndOfDataPointer);
384 385 386

		// Now we experience_reward to be had for destroying one droid of this type
		ReadValueFromString(RobotPointer, EXPERIENCE_REWARD_BEGIN_STRING, "%hd",
387
				    &Droidmap[RobotIndex].experience_reward, EndOfDataPointer);
388 389

		// Now we read in the monster level = maximum treasure chest to pick from
390 391
		ReadValueFromStringWithDefault(RobotPointer, "Drops item class=", "%hd", "-1", 
					       &Droidmap[RobotIndex].drop_class, EndOfDataPointer);
392

393 394 395 396
		char *tmp_item_id = ReadAndMallocStringFromData(RobotPointer, WEAPON_ITEM_BEGIN_STRING, "\"");
		Droidmap[RobotIndex].weapon_item.type = get_item_type_by_id(tmp_item_id);
		free(tmp_item_id);
		ReadValueFromStringWithDefault(RobotPointer, "Gun muzzle height=", "%d", "30", &Droidmap[RobotIndex].gun_muzzle_height, EndOfDataPointer);
397 398 399

		// Now we read in the % chance for droid to drop botpart
		ReadValueFromStringWithDefault(RobotPointer, "Percent to drop Entropy Inverter=", "%hd", "0",
400
					       &Droidmap[RobotIndex].amount_of_entropy_inverters, EndOfDataPointer);
401
		ReadValueFromStringWithDefault(RobotPointer, "Percent to drop Plasma Transistor=", "%hd", "0",
402
					       &Droidmap[RobotIndex].amount_of_plasma_transistors, EndOfDataPointer);
403
		ReadValueFromStringWithDefault(RobotPointer, "Percent to drop Superconducting Relay Unit=", "%hd", "0",
404
					       &Droidmap[RobotIndex].amount_of_superconductors, EndOfDataPointer);
405
		ReadValueFromStringWithDefault(RobotPointer, "Percent to drop Antimatter-Matter Converter=", "%hd", "0",
406
					       &Droidmap[RobotIndex].amount_of_antimatter_converters, EndOfDataPointer);
407
		ReadValueFromStringWithDefault(RobotPointer, "Percent to drop Tachyon Condensator=", "%hd", "0",
408
					       &Droidmap[RobotIndex].amount_of_tachyon_condensators, EndOfDataPointer);
409 410 411

		// Now we read in the greeting sound type of this droid type
		ReadValueFromString(RobotPointer, GREETING_SOUND_STRING, "%hd",
412
				    &Droidmap[RobotIndex].greeting_sound_type, EndOfDataPointer);
413 414

		// Now we read in the to-hit chance this robot has in combat against an unarmored target
415
		ReadValueFromString(RobotPointer, TO_HIT_STRING, "%hd", &Droidmap[RobotIndex].to_hit, EndOfDataPointer);
416 417 418

		// Now we read in the modifier, that increases/decreases the chance of this robot getting hit
		ReadValueFromString(RobotPointer, "Time to recover after getting hit=", "%f",
419
				    &Droidmap[RobotIndex].recover_time_after_getting_hit, EndOfDataPointer);
420 421

		// Now we read in the is_human flag of this droid type
422
		ReadValueFromString(RobotPointer, IS_HUMAN_SPECIFICATION_STRING, "%hd", &Droidmap[RobotIndex].is_human, EndOfDataPointer);
423 424 425

		// Now we read in the Graphics to associate with this droid type
		char *enemy_surface = ReadAndMallocStringFromData(RobotPointer, "Filename prefix for graphics=\"", "\"");
426
		Droidmap[RobotIndex].individual_shape_nr = 0;
427 428
		for (i=0; i < ENEMY_ROTATION_MODELS_AVAILABLE; i++) {
			if (PrefixToFilename[i] && !strcmp(enemy_surface, PrefixToFilename[i])){
429
				Droidmap[RobotIndex].individual_shape_nr = i;
430 431 432 433 434 435
				break;
			}
		}
		free(enemy_surface);

		// Now we read in the notes about this droid type
436
		Droidmap[RobotIndex].notes = ReadAndMallocStringFromData(RobotPointer, NOTES_BEGIN_STRING, "\"");
437 438 439 440 441 442 443 444

		// Now we're potentially ready to process the next droid.  Therefore we proceed to
		// the next number in the Droidmap array.
		RobotIndex++;
		if (EndOfThisRobot)
			EndOfThisRobot[0] = '*';	// We put back the star at its place
	}

445 446
	struct difficulty *diff = dynarray_member(&difficulties, GameConfig.difficulty_level, sizeof(struct difficulty));

447
	for (i = 0; i < Number_Of_Droid_Types; i++) {
448 449 450 451 452 453
		Droidmap[i].maxspeed *= diff->droid_max_speed;
		Droidmap[i].maxenergy *= diff->droid_hpmax;
		Droidmap[i].experience_reward *= diff->droid_experience_reward;
		Droidmap[i].aggression_distance *= diff->droid_aggression_distance;
		Droidmap[i].healing_friendly *= diff->droid_friendly_healing;
		Droidmap[i].healing_hostile *= diff->droid_hostile_healing;
454 455 456 457
	}
};				// int Get_Robot_Data ( void )

/**
458
 * Load the configuration of the fdrpg "engine", that is the game independent data
459
 */
460
static void load_fdrpg_config()
461
{
462
	char fpath[PATH_MAX];
463

464 465 466 467 468
	// Load the languages specs
	dynarray_free(&lang_specs);
	dynarray_free(&lang_codesets);
	if (find_file("languages.lua", MAP_DIR, fpath, PLEASE_INFORM)) {
		run_lua_file(LUA_CONFIG, fpath);
469 470 471 472 473 474 475 476 477
	}
}

/**
 * This function loads all the constant variables of the game from
 * a data file, using mainly subroutines which do the main work.
 */
void Init_Game_Data()
{
478
	char fpath[PATH_MAX];
479 480
	char *Data;

481 482 483
	// Load difficulties.
	find_file("difficulties.lua", MAP_DIR, fpath, PLEASE_INFORM | IS_FATAL);
	run_lua_file(LUA_CONFIG, fpath);
484

485 486 487
	// Load skills and programs (spells) information
	find_file("skill_specs.lua", MAP_DIR, fpath, PLEASE_INFORM | IS_FATAL);
	run_lua_file(LUA_CONFIG, fpath);
488 489

	// Load the blast data (required for the bullets to load)
490
	find_file("blast_specs.lua", MAP_DIR, fpath, PLEASE_INFORM | IS_FATAL);
491 492
	run_lua_file(LUA_CONFIG, fpath);

493
	// Load the bullet data (required for the item archetypes to load)
494
	//
495 496 497
	dynarray_free(&bullet_specs);
	find_file("bullet_specs.lua", MAP_DIR, fpath, PLEASE_INFORM | IS_FATAL);
	run_lua_file(LUA_CONFIG, fpath);
498 499 500 501 502 503 504 505 506

	// Load Tux animation and rendering specifications.
	tux_rendering_load_specs("tuxrender_specs.lua");

	// Load Bot animation definitions and animations
	// must be before Get_Robot_Data()
	Load_Enemy_Surfaces();

	// Item archetypes must be loaded too
507 508
	find_file("item_specs.lua", MAP_DIR, fpath, PLEASE_INFORM | IS_FATAL);
	run_lua_file(LUA_CONFIG, fpath);
509 510

	// Load add-on specifications.
511
	find_file("addon_specs.lua", MAP_DIR, fpath, PLEASE_INFORM | IS_FATAL);
512 513 514
	run_lua_file(LUA_CONFIG, fpath);

	// Time to eat some droid archetypes...
515
	find_file("droid_archetypes.dat", MAP_DIR, fpath, PLEASE_INFORM | IS_FATAL);
516 517 518 519 520 521
	Data = ReadAndMallocAndTerminateFile(fpath, "*** End of this Freedroid data File ***");
	Get_Robot_Data(Data);
	free(Data);

	// Load obstacle specifications.
	dynarray_init(&obstacle_map, 512, sizeof(struct obstacle_spec));
522
	find_file("obstacle_specs.lua", MAP_DIR, fpath, PLEASE_INFORM | IS_FATAL);
523 524 525
	run_lua_file(LUA_CONFIG, fpath);

	// Load floor tile specifications.
526
	find_file("floor_tiles.lua", MAP_DIR, fpath, PLEASE_INFORM | IS_FATAL);
527
	run_lua_file(LUA_CONFIG, fpath);
528
	dirty_animated_floor_tile_list();
529 530 531 532 533 534 535 536 537

	next_startup_percentage(1);
}

char copyright[] = "\nFreedroidRPG comes with NO WARRANTY to the extent permitted by law.\n\
You may redistribute copies of FreedroidRPG\n\
under the terms of the GNU General Public License.\n\
For more information about these matters, see the file named COPYING.\n";

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
char usage_string[] = ""
"Usage: freedroidRPG [-h | --help]\n"
"                    [-v | --version]\n"
"                    [-e | --editor]\n"
"                    [-s | --sound]        [-q | --nosound]\n"
"                    [-o | --open_gl]      [-n | --no_open_gl]\n"
"                    [-f | --fullscreen]   [-w | --window]\n"
"                    [-t | --system_lang]\n"
"                    [-l character-name | --load=character-name]\n"
"                    [-r Y | --resolution=Y]  Y = 99 lists hardcoded resolutions.\n"
"                                             Y may also be of the form 'WxH' e.g. '800x600'\n"
"                    [-d X | --debug=X]       X = 0-5; default 1\n"
"\n"
"Please report bugs either by entering them into the bug tracker on our website at:\n\n"
"http://bugs.freedroid.org\n\n"
"or by sending an e-mail to:\n\n"
"freedroid-discussion AT lists.sourceforge.net\n\n"
"For more information and known issues please see README.\n"
"Thanks a lot in advance.\n"
"                          / The FreedroidRPG dev team.\n\n";
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580

#define MAX_RESOLUTIONS 32
screen_resolution screen_resolutions[MAX_RESOLUTIONS];
screen_resolution hard_resolutions[] = {
	{640, 480, "640 x 480", TRUE},
	{800, 600, "800 x 600", TRUE},
	{1024, 768, "1024 x 768", TRUE},
	{1152, 864, "1152 x 864", TRUE},
	{1280, 960, "1280 x 960", TRUE},
	{1400, 1050, "1400 x 1050", TRUE},
	{1600, 1200, "1600 x 1200", TRUE}
};

/* -----------------------------------------------------------------
 *  parse command line arguments and set global switches 
 *  exit on error, so we don't need to return success status
 * -----------------------------------------------------------------*/
void ParseCommandLine(int argc, char *const argv[])
{
	int c;
	int resolution_code = 1;

	static struct option long_options[] = {
581 582 583 584 585 586 587 588 589 590 591 592 593 594
		{"version",     0, 0, 'v'},
		{"help",        0, 0, 'h'},
		{"editor",      0, 0, 'e'},
		{"load",        1, 0, 'l'},
		{"open_gl",     0, 0, 'o'},
		{"no_open_gl",  0, 0, 'n'},
		{"nosound",     0, 0, 'q'},
		{"sound",       0, 0, 's'},
		{"debug",       1, 0, 'd'},
		{"window",      0, 0, 'w'},
		{"fullscreen",  0, 0, 'f'},
		{"resolution",  1, 0, 'r'},
		{"system_lang", 0, 0, 't'},
		{"benchmark",   1, 0, 'b'},
595 596 597 598
		{0, 0, 0, 0}
	};

	while (1) {
599
		c = getopt_long(argc, argv, "vel:onqsb:h?d::r:wft", long_options, NULL);
600 601 602 603 604 605 606
		if (c == -1)
			break;

		switch (c) {
			/* version statement -v or --version
			 * following gnu-coding standards for command line interfaces */
		case 'v':
607
			printf("\n%s %s  \n", PACKAGE, freedroid_version);
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 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 670 671 672 673 674 675 676
			printf("%s",copyright);
			exit(0);
			break;

		case 'h':
		case '?':
			printf("%s",usage_string);
			exit(0);
			break;

		case 'e':
			start_editor = TRUE;
			break;

		case 'l':
			if (!optarg) {
				fprintf(stderr, "Please provide saved game name.\n");
				exit(1);
			}

			load_saved = TRUE;
			saved_game_name = optarg;
			break;

		case 'o':
			use_open_gl = TRUE;
			break;

		case 'n':
			use_open_gl = FALSE;
			break;

		case 'q':
			sound_on = FALSE;
			break;

		case 's':
			sound_on = TRUE;
			break;

		case 'd':
			if (!optarg)
				debug_level = 1;
			else
				debug_level = atoi(optarg);
			break;

		case 'r':
			if (!optarg) {
				GameConfig.screen_width = DEFAULT_SCREEN_WIDTH;
				GameConfig.screen_height = DEFAULT_SCREEN_HEIGHT;
			} else {
				int nb_res = sizeof(hard_resolutions) / sizeof(hard_resolutions[0]);
				char *x = strtok(optarg, "x");
				char *y = strtok(NULL, "x");

				// User input a resolution
				if (y != NULL) {
					GameConfig.screen_width = atoi(x);
					GameConfig.screen_height = atoi(y);
				} else {

					resolution_code = atoi(optarg);

					if (resolution_code >= 0 && resolution_code < nb_res) {
						GameConfig.screen_width = hard_resolutions[resolution_code].xres;
						GameConfig.screen_height = hard_resolutions[resolution_code].yres;
					} else {
						fprintf(stderr, "\nresolution code received: %d\n", resolution_code);
677
						char *txt = (char *)malloc(nb_res * 128 + 1);
678 679 680 681 682 683 684
						txt[0] = '\0';
						int i;
						for (i = 0; i < nb_res; i++) {
							char tmp[129];
							snprintf(tmp, 129, "\t\t%d = %s\n", i, hard_resolutions[i].comment);
							strncat(txt, tmp, 128);
						}
685
						error_message(__FUNCTION__, "  %s%s  %s", IS_FATAL,
686 687 688 689
								 "\tThe resolution identifier given is not a valid resolution code.\n"
								 "\tThese codes correspond to the following hardcoded resolutions available:\n",
								 txt,
								 "\tAdditional resolutions may be specified by the form 'WxH' e.g. '800x600'\n"
690
								 "\tThe in-game menu automatically detects fullscreen modes supported by your hardware.");
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
						free(txt);
					}
				}
			}
			// By default, after starting up, the current resolution should be
			// the resolution used at the next game startup too, so we preselect
			// that for now.  The user can still change that later inside the
			// game from within the options menu.
			//
			GameConfig.next_time_width_of_screen = GameConfig.screen_width;
			GameConfig.next_time_height_of_screen = GameConfig.screen_height;
			break;
		case 'b':
			if (!optarg) {
				fprintf(stderr, "Please specify what to benchmark.\n");
				exit(1);
			}

			do_benchmark = strdup(optarg);
			break;
		case 'f':
			GameConfig.fullscreen_on = TRUE;
			break;

		case 'w':
			GameConfig.fullscreen_on = FALSE;
			break;

719 720 721 722
		case 't':
			lang_set("", NULL);
			break;

723 724 725 726 727 728 729 730 731 732 733 734
		default:
			printf("\nOption %c not implemented yet! Ignored.", c);
			break;
		}		/* switch(c) */
	}			/* while(1) */
}

/* -----------------------------------------------------------------
 * This function initializes a completely new game within FreedroidRPG.
 * In contrast to InitFreedroid, this function should be called 
 * whenever or better before any new game is started.
 * -----------------------------------------------------------------*/
735
void PrepareStartOfNewCharacter(char *start_label)
736
{
737
	gps start_pos;
738 739 740 741 742 743 744 745 746 747 748 749 750

	Activate_Conservative_Frame_Computation();

	// We make sure we don't have garbage in our arrays from a 
	// previous game or failed load-game attempt...
	//
	clear_out_arrays_for_fresh_game();
	// We do the same as above for lua state
	reset_lua_state();

	GetEventTriggers("events.dat");

	if (!skip_initial_menus)
751
		PlayATitleFile("StartOfGame.lua");
752 753 754 755 756 757

	init_npcs();
	init_factions();

	GetCrew("ReturnOfTux.droids");

758 759
	start_pos = get_map_label_center(start_label);
	
760 761 762 763
	reset_visible_levels();
	if (game_root_mode == ROOT_IS_LVLEDIT && level_exists(GameConfig.last_edited_level))
		teleport_to_level_center(GameConfig.last_edited_level);
	else
764
		Teleport(start_pos.z, start_pos.x, start_pos.y, FALSE, TRUE);
765 766 767 768 769 770 771 772 773 774 775
	clear_active_bullets();

	// At this point the position history can be initialized
	//
	InitInfluPositionHistory();

	// Now we read in the mission targets for this mission
	// Several different targets may be specified simultaneously
	//
	GetQuestList("quests.dat");

776
	switch_background_music(curShip.AllLevels[Me.pos.z]->Background_Song_Name);
777 778 779 780 781 782 783 784 785

	// Now we know that right after starting a new game, the Tux might have
	// to 'change clothes' i.e. a lot of tux images need to be updated which can
	// take a little time.  Therefore we print some message so the user will not
	// panic and push the reset button :)
	//
	our_SDL_flip_wrapper();

	widget_text_init(message_log, _("--- Message Log ---"));
786
	if (strcmp(start_label, "TutorialTuxStart") == 0)
787 788 789 790 791 792 793 794
		append_new_game_message(_("Starting tutorial."));
	else
		append_new_game_message(_("Starting new game."));
}

void prepare_level_editor()
{
	game_root_mode = ROOT_IS_LVLEDIT;
795
	game_status = INSIDE_LVLEDITOR;
796
	skip_initial_menus = 1;
797 798
	char fp[PATH_MAX];
	find_file("levels.dat", MAP_DIR, fp, PLEASE_INFORM | IS_FATAL);
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
	LoadShip(fp, 0);
	PrepareStartOfNewCharacter("NewTuxStartGameSquare");
	skip_initial_menus = 0;
	free(Me.character_name);
	Me.character_name = strdup("MapEd");
}

/**
 * This function sets the GameConfig back to the default values, NOT THE
 * VALUES STORED IN THE USERS CONFIG FILE.  This function is useful if 
 * no config file if found or if the config file turns out to originate
 * from a different version of FreedroidRPG, which could be dangerous as
 * well.
 */
void ResetGameConfigToDefaultValues(void)
{
	// At first we set audio volume to maximum value.
	// This might be replaced later with values from a 
	// private user FreedroidRPG config file.  But for now
	// this code is good enough...
	//
	GameConfig.Current_BG_Music_Volume = 0.5;
	GameConfig.Current_Sound_FX_Volume = 0.5;
822
	GameConfig.Current_Sound_Output_Fmt = SOUND_OUTPUT_FMT_STEREO;
823 824 825 826 827 828 829 830 831
	GameConfig.current_gamma_correction = 1.00;
	GameConfig.WantedTextVisibleTime = 3;
	GameConfig.Draw_Framerate = TRUE;
	GameConfig.Draw_Position = TRUE;
	GameConfig.All_Texts_Switch = FALSE;
	GameConfig.enemy_energy_bars_visible = TRUE;
	GameConfig.limit_framerate = TRUE;
	GameConfig.skip_light_radius = FALSE;
	GameConfig.omit_obstacles_in_level_editor = FALSE;
832
	GameConfig.omit_map_labels_in_level_editor = TRUE;
833 834 835 836 837 838 839
	GameConfig.omit_enemies_in_level_editor = TRUE;
	GameConfig.zoom_is_on = FALSE;
	GameConfig.show_blood = TRUE;
	GameConfig.show_lvledit_tooltips = TRUE;
	GameConfig.show_grid = TRUE;
	GameConfig.show_wp_connections = FALSE;
	GameConfig.number_of_big_screen_messages = 4;
840
	GameConfig.delay_for_big_screen_messages = 3;
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
	GameConfig.enable_cheatkeys = FALSE;
	GameConfig.skip_shadow_blitting = FALSE;
	GameConfig.do_fadings = TRUE;
	GameConfig.xray_vision_for_tux = FALSE;
	GameConfig.cheat_running_stamina = FALSE;
	GameConfig.lazyload = 1;
	GameConfig.show_item_labels = 0;
	GameConfig.last_edited_level = -1;
	GameConfig.show_all_floor_layers = 1;
	GameConfig.screen_width = DEFAULT_SCREEN_WIDTH;
	GameConfig.screen_height = DEFAULT_SCREEN_HEIGHT;
	GameConfig.next_time_width_of_screen = GameConfig.screen_width;
	GameConfig.next_time_height_of_screen = GameConfig.screen_height;
	GameConfig.fullscreen_on = FALSE;
	GameConfig.difficulty_level = DIFFICULTY_NORMAL;
856 857 858 859
	if (GameConfig.locale) {
		free(GameConfig.locale);
	}
	GameConfig.locale = my_strdup("");
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
}

/** 
 * Set signal handlers for SIGSEGV and SIGFPE.
 */
static void set_signal_handlers(void)
{
#ifndef __WIN32__
#ifndef __APPLE_CC__

	struct sigaction action;

	// We set up the structure for the new signal handling
	// to give to the operating system
	//
	action.sa_handler = print_trace;
	sigemptyset(&action.sa_mask);
	action.sa_flags = 0;

	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGFPE, &action, NULL);

#endif
#endif
}

/**
 * Enumerates resolutions supported by SDL
 */
static void detect_available_resolutions(void)
{
	SDL_Rect **modes;
892
	int size = 0;
893 894 895 896

	// Get available fullscreen/hardware modes (reported by SDL)
	modes = SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_HWSURFACE);
	if (modes == (SDL_Rect**) -1) {
897
		error_message(__FUNCTION__,
898 899
			"SDL reports all resolutions are supported in fullscreen mode.\n"
			"Please use -r WIDTHxHEIGHT to specify any one you like.\n"
900
			"Defaulting to a sane one for now", NO_REPORT);
901 902
	} else {
		// Add resolutions to the screen_resolutions array
903 904
		for (size = 0; size < MAX_RESOLUTIONS && modes[size]; ++size)
			screen_resolutions[size] = (screen_resolution) {modes[size]->w, modes[size]->h, "", TRUE};
905 906
	}

907 908 909 910
	if (size == 0) {
		screen_resolutions[0] =	(screen_resolution) {DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, "", TRUE};
		screen_resolutions[1] = (screen_resolution) {-1, -1, "", FALSE};
		return;
911 912
	}

913 914 915 916 917 918
	// Sort
	int i, j;
	screen_resolution resolution_holder;

	for (i = 0; i < size; i++) {
		for (j = 0; j < size - 1; j++) {
919 920 921 922 923 924 925
			// Sort in descending order of xres, then yres
			if (screen_resolutions[j].xres < screen_resolutions[j + 1].xres ||
					(screen_resolutions[j].xres == screen_resolutions[j + 1].xres &&
					screen_resolutions[j].yres < screen_resolutions[j +1].yres)) {
				resolution_holder = screen_resolutions[j + 1];
				screen_resolutions[j + 1] = screen_resolutions[j];
				screen_resolutions[j] = resolution_holder;
926
			}
927 928 929 930
		}
	}

	// Add our terminator on the end, just in case
931 932
	screen_resolutions[size] = (screen_resolution) {-1, -1, "", FALSE};
}
933

934
void prepare_execution(int argc, char *argv[])
935
{
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
#if defined HAVE_UNISTD_H && defined HAVE_DIRNAME
	// change working directory to the executable's directory
	if (chdir(dirname(argv[0])))
		fprintf(stderr, "Couldn't change working directory to %s.\n", dirname(argv[0]));
#endif

	// Get color capability of current output stream.
	// Real code to get such a capability has to use setupterm() and
	// tigetnum() from the ncurses lib.
	// In order to avoid a dependency to ncurses, we use here a simple trick.
	run_from_term = FALSE;
	term_has_color_cap = FALSE;
#ifndef __WIN32__
	run_from_term = isatty(STDOUT_FILENO);
	if (run_from_term && !strncmp(getenv("TERM"), "xterm", 5))
		term_has_color_cap = TRUE;
#endif
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978

	// Get the homedir, and define the directory where the config file and
	// the savegames will be stored
#if __WIN32__

	our_homedir = ".";
	// There is no real homedir on Windows.
	// So we use the user's "My Documents" as a home directory.
	char mydocuments_path[MAX_PATH];
	if (SHGetSpecialFolderPath(0, mydocuments_path, CSIDL_PERSONAL, FALSE)) {
		our_homedir = strdup(mydocuments_path);
	}
	our_config_dir = MyMalloc(strlen(our_homedir) + 20);
	sprintf(our_config_dir, "%s/FreedroidRPG", our_homedir);

#else

	// first we need the user's homedir for loading/saving stuff
	if ((our_homedir = getenv("HOME")) == NULL) {
		our_homedir = ".";
	}
	our_config_dir = MyMalloc(strlen(our_homedir) + 20);
	sprintf(our_config_dir, "%s/.freedroid_rpg", our_homedir);

#endif

979 980
	struct stat statbuf;

981 982 983 984 985 986 987 988 989 990 991 992 993
#if __WIN32__
	if (stat(our_config_dir, &statbuf) == -1) {
		_mkdir(our_config_dir);
	}
#else
	if (stat(our_config_dir, &statbuf) == -1) {
		if (mkdir(our_config_dir, S_IREAD | S_IWRITE | S_IEXEC) == -1) {
			free(our_config_dir);
			our_config_dir = NULL;
		}
	}
#endif

994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
	// If not run from a terminal, stdout and stderr are redirect to a text file
	// written in the config dir (fdrpg_out.txt).
	// Note: On Windows, in SDL_WinMain(), stdout and stderr are redirected to
	// files, before to call our main(). Those files are automatically created
	// in the directory of the current process. They will be removed when the process
	// ends, because they are empty.
	if (!run_from_term) {
		char *filename = MyMalloc(strlen(our_config_dir) + 15);
		sprintf(filename, "%s/fdrpg_out.txt", our_config_dir);
		if (!freopen(filename, "w", stdout)) {
			DebugPrintf(-4, "Was not able to redirect stdout to %s/fdrpg_out.txt", our_config_dir);
		}
		free(filename);
		if (dup2(fileno(stdout), fileno(stderr)) == -1) {
			DebugPrintf(-4, "Was not able to redirect stderr to stdout. Errno: %d", errno);
		}

		fprintf(stderr, "Hello!  This window contains the DEBUG OUTPUT of FreedroidRPG.\n"
		                "\n"
		                "Normally you would not see this message or this window, but apparently\n"
		                "FreedroidRPG has terminated because of an error of some sort.\n"
		                "\n"
		                "You might wish to inspect the debug output below.  Maybe sending the\n"
		                "debug output (or at least the lower end of the debug output) to the\n"
		                "FreedroidRPG developers could help them to track down the problem.\n"
		                "\n"
		                "Well, it's no guarantee that we can solve any bug, but it's certainly\n"
		                "better than nothing.  Thanks anyway for your interest in FreedroidRPG.\n"
		                "\n\n"
		                "--start of real debug log--\n\n");
	}

1026 1027 1028
	// We mention the version of FreedroidRPG, so that debug reports
	// are easier to assign to the different versions of the game.

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
	DebugPrintf(-4, "\nHello, this is FreedroidRPG, version %s.\n", freedroid_version);
}

/* -----------------------------------------------------------------
 * This function initializes the whole FreedroidRPG game.
 *
 * THIS MUST NOT BE CONFUSED WITH INITNEWGAME, WHICH
 * ONLY INITIALIZES A NEW MISSION FOR THE GAME.
 *
 * ----------------------------------------------------------------- */
void InitFreedroid(int argc, char **argv)
{
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
	set_signal_handlers();

	clear_out_arrays_for_fresh_game();

	timeout_from_item_drop = 0;

	Overall_Average = 0.041;
	SkipAFewFrames = 0;

	ResetGameConfigToDefaultValues();

	input_keyboard_init();
	init_lua();
1054 1055 1056
	init_luaconfig();

	load_fdrpg_config();
1057 1058 1059 1060

	LoadGameConfig();

	if (SDL_Init(SDL_INIT_VIDEO) == -1)
1061 1062
		error_message(__FUNCTION__, "Couldn't initialize SDL: %s", PLEASE_INFORM | IS_FATAL, SDL_GetError());

1063 1064 1065 1066
	// So the video library could be initialized.  So it should also be
	// cleaned up and closed once we're done and quit FreedroidRPG.
	atexit(SDL_Quit);

1067 1068 1069 1070
	// Enable to compute the unicode value of a pressed key.
	// Needed to use the numkeys which are on top of the alphakeys on keyboards.
	SDL_EnableUNICODE(1);

1071 1072 1073 1074 1075 1076
	detect_available_resolutions();

	ParseCommandLine(argc, argv);

	LightRadiusInit();

1077 1078 1079 1080 1081 1082 1083
	init_timer();

	InitVideo();

	// Adapt button positions for the current screen resolution. Note: At this
	// point the video mode was already initialized, therefore we know if OpenGL
	// is used or not and also which screen resolution is used.
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
	//
	adapt_button_positions_to_screen_resolution();

	Copy_Rect(Full_User_Rect, User_Rect);

	next_startup_percentage(0);

	init_keyboard_input_array();
	init_message_log();

1094
	init_audio();
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

	Init_Game_Data();

	/* 
	 * Initialize random-number generator in order to make 
	 * level-start etc really different at each program start
	 */
	srand(time(NULL));

	InitPictures(); //requires game data loaded in Init_Game_Data()

	next_startup_percentage(100);
1107 1108 1109 1110 1111 1112 1113 1114
	if (strstr(VERSION, "rc") && !do_benchmark) {
		blit_background("startup1.jpg");
		alert_window(_("You are playing a Release Candidate.\n"
		               "Strange bugs may still be present in the game.\n"
		               "Please report any issues you find to our bugtracker at http://bugs.freedroid.org/\n"
		               "Thank you for helping us test the game.\n\nGood luck!\n"));
	}
}
1115 1116 1117 1118 1119 1120 1121 1122 1123 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 1158
/**
 * This function displayes the last seconds of the game when the influencer
 * has actually been killed.  It generates some explosions and waits for
 * some seconds, where the user can reload his latest game, or after that
 * returns to finally quit the inner game loop and the program will 
 * (outside this function) ask for a completely new game or loading a different
 * saved game or quit as in the very beginning of the game.
 */
void ThouArtDefeated(void)
{
	int now;

	DebugPrintf(1, "\n%s(): Real function call confirmed.", __FUNCTION__);
	append_new_game_message(_("Game over.\n"));
	SetNewBigScreenMessage(_("Game over.\n"));
	GameConfig.Inventory_Visible = FALSE;
	GameConfig.CharacterScreen_Visible = FALSE;
	ThouArtDefeatedSound();
	start_tux_death_explosions();
	now = SDL_GetTicks();

	GameConfig.SkillScreen_Visible = FALSE;
	GameConfig.CharacterScreen_Visible = FALSE;
	GameConfig.Inventory_Visible = FALSE;

	// Now that the influencer is dead, all this precious items
	// spring off of him...
	//
	if (Me.weapon_item.type > 0) {
		DropItemAt(Me.weapon_item.type, Me.pos.z, Me.pos.x - 0.5, Me.pos.y - 0.5, 1);
	}
	if (Me.drive_item.type > 0) {
		DropItemAt(Me.drive_item.type, Me.pos.z, Me.pos.x + 0.5, Me.pos.y - 0.5, 1);
	}
	if (Me.shield_item.type > 0) {
		DropItemAt(Me.shield_item.type, Me.pos.z, Me.pos.x + 0.5, Me.pos.y + 0.5, 1);
	}
	if (Me.armour_item.type > 0) {
		DropItemAt(Me.armour_item.type, Me.pos.z, Me.pos.x - 0.5, Me.pos.y + 0.5, 1);
	}
	if (Me.special_item.type > 0) {
		DropItemAt(Me.special_item.type, Me.pos.z, Me.pos.x - 0.5, Me.pos.y, 1);
	}
	if (Me.Gold > 0) {
1159
		DropItemAt(get_item_type_by_id("Valuable Circuits"), Me.pos.z, Me.pos.x, Me.pos.y, 1);
1160 1161 1162 1163 1164
	}

	GameOver = TRUE;

	while ((SDL_GetTicks() - now < 1000 * WAIT_AFTER_KILLED)) {
1165
		StartTakingTimeForFPSCalculation();
1166 1167

		AssembleCombatPicture(DO_SCREEN_UPDATE | SHOW_ITEMS);
1168

1169 1170
		UpdateCountersForThisFrame();
		
1171 1172
		DoAllMovementAndAnimations();
		move_enemies();
1173

1174
		ComputeFPSForThisFrame();
1175
	}
1176 1177 1178
	input_handle();
	if (!skip_initial_menus && (game_root_mode == ROOT_IS_GAME))
		PlayATitleFile("GameLost.lua");
1179

1180
	do_death_menu();
1181 1182 1183 1184 1185

};				// void ThouArtDefeated(void)

/**
 * This function displays the last seconds of the game when the influencer
1186 1187 1188
 * has actually won the game.  It anims the game while it's waits for
 * some seconds, after printed a winning message. After that, Credits.title
 * can be displayed, or the game reboots to main.
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
 */
void ThouHastWon(void)
{
	int now;

	DebugPrintf(1, "\n%s(): Real function call confirmed.", __FUNCTION__);
	append_new_game_message(_("Game won.\n"));
	SetNewBigScreenMessage(_("Game won.\n"));
	GameConfig.Inventory_Visible = FALSE;
	GameConfig.CharacterScreen_Visible = FALSE;
	now = SDL_GetTicks();

	GameOver = TRUE;

	while ((SDL_GetTicks() - now < 1000 * WAIT_AFTER_GAME_WON)) {
1204
		StartTakingTimeForFPSCalculation();
1205

1206
		AssembleCombatPicture(DO_SCREEN_UPDATE | SHOW_ITEMS);
1207

1208 1209 1210 1211
		UpdateCountersForThisFrame();
		
		DoAllMovementAndAnimations();
		move_enemies();
1212

1213
		ComputeFPSForThisFrame();
1214 1215 1216 1217 1218
	}

	// Now it's time for the end game title file...
	//
	//PlayATitleFile("EndOfGame.title");
1219 1220
	if (!skip_initial_menus)
		PlayATitleFile("Credits.lua");
1221 1222 1223 1224 1225 1226

	input_handle();

};				// void ThouHastWon(void)

#undef _init_c